Emacs Lisp Cheatsheet

help

  • C-h i for the reference

functions

defining a function

(defun function-name arg-list [docstring] body)
arg-list: (argument,[...])
  • example
        (defun square (x)
    "Return X squared."
    (interactive)
    (* x x))
    

local variables

(let ((name1 value1)
(name2 value2))
...
)

installing a function

  • just evaluate the function
  • if the function is executed when intended to evaluate the defun macro then you forgot a closing parenthesis
  • if you get a „reached end of file while parsing“ at startup then
    you maybe forgot a parenthesis

lists

initialize an empty list

(setq mylist ())

add elements

(setq mylist nil)
(push "a" mylist)
(push "b" mylist)

sort a list of numbers

(setq list '(3.0 2.0 1.0))
(setq list (sort list '<))

sort a list of strings

(setq list '("b" "c" "a"))
(setq list (sort list 'string<))

write a list to the top of the current buffer

(setq list '("alma" "bert" "christian"))
 (save-excursion
  (goto-char (point-min))
  (while list
    (insert (car list))
    (newline)
    (setq list (cdr list)))
  )

make a list unique / eliminate duplicates

(setq mylist '(3 1 2 2 1 3))
(setq mylist (seq-uniq mylist))

return the nth element (start/ w/ 0)

(nth 0 '(1 2 3))

regular expressions

go to the next word after point

(search-forward-regexp "\\w+")
  • search-forward-regexp brings point to one character after the match

use the last match

(defun findword ()
 (interactive)   
 (search-forward-regexp "\\w+")
 (message (match-string 0) )
)

generate regular expressions

(rx (or "Hello" "Hi"))

quirks

  • \( … \) means submatch (not ())
  • use \{… \} instead of {}
  • \d for „any digit“ does not exist, instead use [0-9]
  • \W means „not \w“
  • [^…] gets all tokens that are not part of the list, including new lines

comparisons

numbers

(<= 3 5)
(= 3 5)
(= 3 3)

strings

(= "abc" "bcd") ;; does not work 
(string= "abc" "bcd")