Development & AI | Alper Akgun
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`
(defun greet (name)
"greet someone"
(message "Hello, %s" name))
(greet "Alice") ; function call
(defun greetHi (name last-name &optional middle-name)
"Optional params"
(interactive)
(message "%s %s %s" name middle-name last-name))
(greetHi "Alice" "Cooper" "Wayne") ;
(greetHi "Alice" "Cooper") ; will print `nil` and learn how to get rid of it
(defun greetAll (word &optional me &rest people)
"Greet all"
(message "%s! %s" word people)) ; optional and a list of params are given in that order
;; Emacs lisp does not support named parameters, default values for params, and type checking
;; Use a alist (association list) to emulate them
(defun doIt (x &optional xOpt)
"Add and print the values"
Details
X is a number
xOpt is a list of numbers like `ARG1`
See URL 'http://example.org'
See 'dired'"
(let ((arg1 (or (cdr (assoc "arg1" xOpt)) 1)))
(message "%d" (+ arg1 x))))
(doIt 2 '(("arg1" . 40)))
;; throw exit
(defun catch-throw-exit ()
"example. using catch/throw to exit function"
(interactive)
(catch 'aaa
(if (y-or-n-p "exit?")
(progn
(message "exited")
(throw 'aaa 3) ; return 3 to catch
)
(progn ; else
(message "continued")
4 ; return 4
))))
;; Apply list to args
(defun addAll (x y z)
"add X Y Z"
(+ x y z))
(apply 'addAll '(1 2 3))
((lambda (x)
(1+ x)) 41) ; apply lambda to a value
(lambda (x)
(let (a)
(setq a)
(list a '(2))))
(mapcar
(lambda (x) (aref x 1))
[[1 1] [2 4] [3 9]]
)
(fset 'inc (lambda (x) "add 1 to arg" (1+ x)))
(defun exit-with-error ()
(if (y-or-n-p "really exit?")
(user-error "Error, 'cause you exited")
(progn
(message "continue"))))
(catch 'found-three
(while (setq i (random 5))
(message "%s" i)
(when (eq 3 i) (throw 'found-three t))))
;; function types
(special-form-p 'if) ; f, cond, and, or, while, progn
(macrop 'when)
(commandp 'count-words)
(functionp 'file-name-directory)
(boundp 'buffer-filename)
(fboundp 'not-defined-func-yet) ; is it defined
;; Similar to a finally
(unwind-protect
(progn
(do-something)
(do-something-else))
(first-finally-expr)
(second-finally-expr))
;; Ignore errors
(ignore-errors
(do-something)
(do-something-else))