Man

Development & AI | Alper Akgun

Learning emacs elisp 1/4 - Basics

August, 2023

This is a guide to learn by examples. There are two ways I run the commands.

Open a new buffer and run `C-x C-e` after each expression

Using interactive expression evaluation `M-x ielm`

"Hello, world!" using print, format & message

(print "Hello World")

;;; HEADER COMMENT
;; Comment: use message to write to `*Messages*` buffer
(message "Hello World")
(message "Hello World %s, You got %d" "Alice" 9)
(format "Hello World %s, You got %d" "Jane" 9)

Buffers; Print, insert

(insert "work")
(setq buff (generate-new-buffer "*HEY*"))
(print "Hello new buffer" buff)
(switch-to-buffer buff)
(prin1 "No newline added")
(princ "Human readable")
(print "One line\nAnother line\tA column\\backslash")
(number-to-string 42)
(format "%d" 42)
(string-to-number "42")

Simple math

(+ 41 1)
(- 41 1)
(/ 84 2)
(* 7 6)
(* 7 (* (+ 2 1) 2))
(integerp 2)
(floatp 2)
(expt 2 5)
(truncate 3.14)
(floor 3.14)
(ceiling 3.14)
(round 3.14)

Variables

(set 'age 23) ; global unquoted variables
(print age)
(setq size 5) ; use this generally for global variables
(print size)

(setq x 12
y 30) ; multiple declarations
(print x)
(print y)


;; local variables with "let"

(let (a b)
  (setq a 2)
  (setq b 21)
  (* a b)
) ; 42

(let* ((x 1)
       (y x))
  (+ x y)) ; let* allows you to refer to the previous variables

;; more common form of local variables with "let"
(let ((a 3) (b 14))
  (* 3 14)
) ; 42

;; Annotate variables
(defconst pi 3.141592 "Mathematical PI constant")
(print pi)
(defvar e 2.7172 "Math e number")
(print e)

            

Expressions and blocks

;; Multiple expressions
(progn
  (message "a")
  (message "b"))


(progn 3 4) ; 4
            

Strings

(setq name "alice")
(length name)
(substring name 0 3)
(concat name ", hello!")
(split-string name "l")
(string-reverse name)
(stringp name)
(string-blank-p name)
(string-or-null-p name)
(string-equal name "alice")
            

Booleans

(if nil "yes" "no")
(if () "yes" "no")
(if '() "yes" "no")
(if (list) "yes" "no")

(and t nil) ; nil
(and t nil t t t) ; nil
(not t) ; nil
(not nil) ; t
(or t nil) ; t


(< 2 3) ; t
(> 3 4) ; nil
(>= 3 4) ; nil
(<= 3 4) ; t

(= 3 3) ; t
(= 3 3.0) ; t

(string-equal "abc" "abc")
(string-equal 'abc 'abc)

(equal 3 3.0) ; nil

(eq 'x 'x) ; t  check if the same object
            

If and when

(if (< 3 42)
  (progn 42))  ;;  (if test true_body)

(if (< 3 42)
  (progn 42)
  (progn 3))  ;;  (when test expr1 expr2 etc)

(when (< 3 42)  (print "a") (print "b")) ; (when test expr1 expr2 etc)
            

Objects and classes

(require 'cl)  ; top of file  

(defstruct person
  "A person structure."
  name
  (age 0)
  (height 0.0))

make-person)  ; new Person()
(make-person :age 39)
(make-person :name "Alice" :height 5.83 :age 42)