Emacs Lisp Notes

A good fast track guide Elisp in 15min

Debugging

Debug a function typing M-x edebug-defun in the function block then run function.

Exit debugging a function C-M-x which is Ctrl-Alt-X

Programming

if-else and Conditions

"Print message in echo area depending on CHARACTERISTIC.  
If the CHARACTERISTIC is the string \"fierce\",  
then warn of a tiger; else say it is not fierce."  
  (if (equal characteristic "fierce")  
      (message "It is a tiger!")  
    (message "It is not fierce!")))

There are other conditions as well check below ref.

Ref - https://www.emacswiki.org/emacs/WhenToUseIf

Comparison

Check if string is empty. Similarly it can compare strings.

(equal "" user-str)

String Operations

Split String

You can split a string into seperate words with the following func.

(split-string "  two words ")  
     ⇒ ("two" "words")

Additionaly provide an argument to split with that. e.g. to split with ',' (split-string "one,two" ",")

Convert List into String

(format) will embed parentheses in the string, e.g.:

ELISP> (format "%s" '("foo" "bar"))  
"(foo bar)"

Thus if you need an analogue to Ruby/JavaScript-like join(), there is (mapconcat):

ELISP> (mapconcat 'identity '("foo" "bar") " ")  
"foo bar"

Ref - https://stackoverflow.com/questions/18979300/how-to-convert-list-to-string-in-emacs-lisp

List Operations

Add prefix to every list item

Below will add pre_ to every list item.

(mapcar (lambda (c) (concat "pre_" c)) '("abc" "123" "xy"))  
;; => ("pre_abc" "pre_123" "pre_xy")

Ref - https://stackoverflow.com/questions/22622257/how-to-add-a-common-prefix-suffix-to-a-list-of-strings

Functions

mapcar

mapcar returns list even if you pass a string or vector to it.

(mapcar #'identity "hello")  
;; => (104 101 108 108 111)

(mapcar #'identity [1 2 3])  
;; => (1 2 3)