### defsetf examples and gv-define-simple-setter equivalents Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Obsolete-Setf-Customization.html Examples of defsetf with car and buffer-name, and their direct translations to gv-define-simple-setter. ```emacs-lisp (defsetf car setcar) (defsetf buffer-name rename-buffer t) ``` ```emacs-lisp (gv-define-simple-setter car setcar) (gv-define-simple-setter buffer-name rename-buffer t) ``` -------------------------------- ### defsetf nth example and gv-define-setter equivalent Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Obsolete-Setf-Customization.html Standard example of defsetf for nth and its equivalent using gv-define-setter. ```emacs-lisp (defsetf nth (n x) (store) `(setcar (nthcdr ,n ,x) ,store)) ``` ```emacs-lisp (gv-define-setter nth (store n x) `(setcar (nthcdr ,n ,x) ,store)) ``` -------------------------------- ### Alternative cl-do* iteration Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Iteration.html Demonstrates an alternative implementation of the previous cl-do example using cl-do*. ```emacs-lisp (cl-do* ((xp foo (cdr xp)) (yp bar (cdr yp)) (x (car xp) (car xp)) (y (car yp) (car yp)) z) ((or (null xp) (null yp)) (nreverse z)) (push (f x y) z)) ``` -------------------------------- ### cl-case example Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Conditionals.html An example of using cl-case to handle different character inputs from read-char. ```emacs-lisp (cl-case (read-char) (?a (do-a-thing)) (?b (do-b-thing)) ((?\r ?\n) (do-ret-thing)) (t (do-other-thing))) ``` -------------------------------- ### cl-eval-when usage examples Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Time-of-Evaluation.html Demonstrates various combinations of compile, load, and eval situations for top-level forms in a file named foo.el. ```elisp ;; Top-level forms in foo.el: (cl-eval-when (compile) (setq foo1 'bar)) (cl-eval-when (load) (setq foo2 'bar)) (cl-eval-when (compile load) (setq foo3 'bar)) (cl-eval-when (eval) (setq foo4 'bar)) (cl-eval-when (eval compile) (setq foo5 'bar)) (cl-eval-when (eval load) (setq foo6 'bar)) (cl-eval-when (eval compile load) (setq foo7 'bar)) ``` -------------------------------- ### Equivalent cl-block and while loop Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Iteration.html Shows the underlying structure of the previous cl-loop example using cl-block and while. ```emacs-lisp (cl-block nil (while t (foo) (if (no-more) (return 72)) (bar))) ``` -------------------------------- ### Equivalence of get and cl-getf Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Property-Lists.html Shows that (get sym prop) is equivalent to (cl-getf (symbol-plist sym) prop). ```lisp (get sym prop) ≡ (cl-getf (symbol-plist sym) prop) ``` -------------------------------- ### cl-defun Keyword Argument Example Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Argument-Lists.html An example of a function definition using required, optional, and keyword arguments. ```emacs-lisp (cl-defun foo (a &optional b &key c d (e 17))) ``` -------------------------------- ### cl-find with :key Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Sequence-Basics.html Example showing how to use the :key argument with cl-find to search for an element based on a key function. ```APIDOC ## cl-find with :key ### Description This example demonstrates the use of the :key argument in the cl-find function. It searches for an element of the list whose CAR equals x, rather than an element that equals x itself. ### Example (cl-find x y :key 'car) ### Notes - The :key argument should be nil or a function of one argument. - The key function is used as a filter through which the elements of the sequence are seen. - If :key is omitted or nil, the filter is effectively the identity function. ``` -------------------------------- ### Infinite cl-loop example Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Iteration.html Demonstrates an infinite loop using cl-loop that terminates via a return statement. ```emacs-lisp (cl-loop (foo) (if (no-more) (return 72)) (bar)) ``` -------------------------------- ### cl-typecase example Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Conditionals.html An example of using cl-typecase to execute different logic based on the type of the variable x. ```emacs-lisp (cl-typecase x (integer (munch-integer x)) (float (munch-float x)) (string (munch-integer (string-to-number x))) (t (munch-anything x))) ``` -------------------------------- ### define-modify-macro example definitions Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Obsolete-Setf-Customization.html Example definitions of incf and concatf using define-modify-macro. Note that &key is not allowed in arglist, but &rest is sufficient to pass keywords. ```emacs-lisp (define-modify-macro incf (&optional (n 1)) +) (define-modify-macro concatf (&rest args) concat) ``` -------------------------------- ### Advice substitute for flet: add-advice example Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Obsolete-Macros.html Shows using advice as a better substitute for flet when dynamic scoping is desired. Defines a variable to enable the advice and uses add-advice with :around to conditionally run do-something. Note that redefining primitives like + with flet, cl-letf, or advice will fail when byte-compiled. ```emacs-lisp (defvar my-fun-advice-enable nil) (add-advice 'fun :around (lambda (orig &rest args) (if my-fun-advice-enable (do-something) (apply orig args)))) ``` -------------------------------- ### cl-letf example Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Modify-Macros.html Moves point to the beginning of the buffer and binds a to 17. After the body exits, a is restored and point is moved back to its original position. The cleanup happens even on throw or error. ```lisp (cl-letf (((point) (point-min)) (a 17)) ...) ``` -------------------------------- ### cl-shiftf equivalence example Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Modify-Macros.html Shows the equivalent cl-psetf form for (cl-shiftf a b c d). The subforms of a, b, and c are evaluated only once each and in apparent order. ```lisp (prog1 a (cl-psetf a b b c c d)) ``` -------------------------------- ### Example: collect and append in cl-loop Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Accumulation-Clauses.html Shows a cl-loop that collects names and appends lists of kids, returning a combined list. Demonstrates multiple accumulation clauses of different types in one loop. ```emacs-lisp (cl-loop for name in '(fred sue alice joe june) for kids in '((bob ken) () () (kris sunshine) ()) collect name append kids) ⇒ (fred bob ken sue alice joe kris sunshine june) ``` -------------------------------- ### cl-remove with :test and -if variant Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Sequence-Basics.html Example showing the equivalence between using :test with cl-remove and using the -if variant with a predicate. ```APIDOC ## cl-remove with :test and -if variant ### Description This example shows how to remove all zeros from a sequence using the :test argument and the equivalent -if variant. ### Example (cl-remove 0 seq :test '=) ≡ (cl-remove-if 'zerop seq) ### Notes - The :test argument should be nil or a function of two arguments. - The test function is used to compare two sequence elements or a search value with sequence elements. - The -if and -if-not varieties take a predicate function instead of an item. ``` -------------------------------- ### cl-rotatef equivalence example Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Modify-Macros.html Shows the equivalent cl-psetf form for (cl-rotatef a b c d). cl-rotatef always returns nil and (cl-rotatef a b) exchanges a and b. ```lisp (cl-psetf a b b c c d d a) ``` -------------------------------- ### Using cl-prettyexpand to expand a cl-loop macro Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Efficiency-Concerns.html Type this form in the *scratch* buffer and press C-x C-e to insert a nicely formatted expansion of the cl-loop macro. The expansion is shown in the following example. ```emacs-lisp (cl-prettyexpand '(cl-loop for x below 10 collect x)) ``` ```emacs-lisp (cl-block nil (let* ((x 0) (g1004 nil)) (while (< x 10) (setq g1004 (cons x g1004)) (setq x (+ x 1))) (nreverse g1004))) ``` -------------------------------- ### define-modify-macro expansion example Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Obsolete-Setf-Customization.html Shows the expansion of a define-modify-macro call: (name place args...) expands to (cl-callf func place args...) which is roughly equivalent to (setf place (func place args...)). ```emacs-lisp (name place args...) ``` ```emacs-lisp (cl-callf func place args...) ``` ```emacs-lisp (setf place (func place args...)) ``` -------------------------------- ### cl-do* Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Iteration.html Similar to cl-do but uses let* binding for initial values and setq for step assignments, allowing later variables to reference earlier ones. ```APIDOC ## Macro: cl-do* (spec...) (end-test [result...]) forms... ### Description This is to cl-do what let* is to let. Initial values are bound sequentially (as if by let*), and steps are assigned as if by setq rather than cl-psetq. ### Syntax (cl-do* (spec...) (end-test [result...]) forms...) ### Parameters - **spec** - Each spec is of the form (var [init [step]]). - **var** (symbol) - Variable to bind. - **init** (optional) - Initial value; defaults to nil. - **step** (optional) - Expression to update the variable each iteration. - **end-test** (form) - Evaluated each iteration; if true, the loop ends. - **result** (optional forms) - Evaluated after the loop ends, with variables still bound, to produce the return value. - **forms** (body) - Evaluated each iteration before updating variables. ### Behavior - Variables are bound sequentially, so later variables can use earlier ones in their init. - Steps are assigned sequentially using setq semantics. - The loop is enclosed in an implicit nil block. ### Example (cl-do* ((xp foo (cdr xp)) (yp bar (cdr yp)) (x (car xp) (car xp)) (y (car yp) (car yp)) z) ((or (null xp) (null yp)) (nreverse z)) (push (f x y) z)) ``` -------------------------------- ### cl-letf* Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Modify-Macros.html Like cl-letf but does bindings in sequential order, analogous to let*. ```APIDOC ## Macro: cl-letf* (bindings...) forms... ### Description This macro is to cl-letf what let* is to let: It does the bindings in sequential rather than parallel order. ### Syntax (cl-letf* (bindings...) forms...) ### Parameters - bindings (list) - Each binding is (place value) or (place) for one-element list. - forms (any Lisp forms) - The body to execute. ### Behavior Sequential binding, like let*. ``` -------------------------------- ### Variable binding with with Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Other-Clauses.html Demonstrates the equivalence of 'with' to 'let' and 'for' initialization, and shows how 'with' can be used to accumulate values. ```elisp (cl-loop with x = 17 do ...) (let ((x 17)) (cl-loop do ...)) (cl-loop for x = 17 then x do ...) ``` ```elisp (cl-loop for x in my-list with res = nil do (push x res) finally return res) ``` -------------------------------- ### cl-callf examples Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Modify-Macros.html Three examples of the generic modify macro cl-callf: using abs, concat, and cl-union. The function is called with place and args, and the result is assigned back to place. ```lisp (cl-callf abs my-number) (cl-callf concat (buffer-name) "<" (number-to-string n) ">") (cl-callf cl-union happy-people (list joe bob) :test 'same-person) ``` -------------------------------- ### cl-list-length Source: https://www.gnu.org/software/emacs/manual/html_node/cl/List-Functions.html Returns the length of a list, but returns nil for circular lists instead of getting stuck. ```APIDOC ## Function: cl-list-length x ### Description Returns the length of list x, exactly like (length x), except that if x is a circular list (where the CDR-chain forms a loop rather than terminating with nil), this function returns nil. ### Parameters - **x** (list) - Required - The list whose length is to be computed. ### Returns - The length of the list as an integer, or nil if the list is circular. ``` -------------------------------- ### Compare setq and cl-psetq behavior Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Assignment.html Demonstrates the difference between sequential assignment with setq and parallel assignment with cl-psetq. ```lisp (setq x 2 y 3) (setq x (+ x y) y (* x y)) x ⇒ 5 y ; y was computed after x was set. ⇒ 15 (setq x 2 y 3) (cl-psetq x (+ x y) y (* x y)) x ⇒ 5 y ; y was computed before x was set. ⇒ 6 ``` -------------------------------- ### for var being the frames Source: https://www.gnu.org/software/emacs/manual/html_node/cl/For-Clauses.html Iterates over all Emacs frames, binding var to each frame in next-frame order starting from selected-frame. ```APIDOC ## for var being the frames ### Description Iterates over all Emacs frames. The clause 'screens' is a synonym for 'frames'. The frames are visited in 'next-frame' order starting from 'selected-frame'. ### Syntax `for var being the frames` ### Parameters - **var** (symbol) - Required - Variable bound to each frame. ### Example ```lisp (cl-loop for f being the frames do (message "frame: %S" f)) ``` ``` -------------------------------- ### incf using gv-letplace Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Obsolete-Setf-Customization.html Replacement for the incf define-modify-macro using gv-letplace. This example shows how to write a read-modify-write macro with gv-letplace. ```emacs-lisp (defmacro incf (place &optional n) (gv-letplace (getter setter) place (cl-once-only ((v (or n 1))) (funcall setter `(+ ,v ,getter))))) ``` -------------------------------- ### Compare cl-with-gensyms usage Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Macro_002dWriting-Macros.html Comparison between manual gensym creation and using the cl-with-gensyms macro to bind fresh uninterned symbols. ```Common Lisp (defmacro my-macro (foo) (let ((bar (gensym "bar")) (baz (gensym "baz")) (quux (gensym "quux"))) `(let ((,bar (+ ...))) ...))) (defmacro my-macro (foo) (cl-with-gensyms (bar baz quux) `(let ((,bar (+ ...))) ...))) ``` -------------------------------- ### Defining Derived Types with cl-deftype Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Derived-Types.html Examples of defining derived types including null, list, and a custom unsigned-byte type. ```lisp (cl-deftype null () '(satisfies null)) ; predefined (cl-deftype list () '(or null cons)) ; predefined (cl-deftype unsigned-byte (&optional bits) (list 'integer 0 (if (eq bits '*) bits (1- (ash 1 bits))))) (unsigned-byte 8) ≡ (integer 0 255) (unsigned-byte) ≡ (integer 0 *) unsigned-byte ≡ (integer 0 *) ``` -------------------------------- ### Process lines at least once with cl-loop do until Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Loop-Examples.html Similar to the previous example, but munch-line is always called at least once because the until condition is checked after the do clause. ```Emacs Lisp (cl-loop do (munch-line) until (eobp) do (forward-line 1)) ``` -------------------------------- ### Copy and test structure instances Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Structures.html Demonstrates copying a structure instance and using the generated predicate function to verify the structure type. ```elisp (setq dave (make-person :first-name "Dave" :sex 'male)) ⇒ [cl-struct-person "Dave" nil male] (setq other (copy-person dave)) ⇒ [cl-struct-person "Dave" nil male] (eq dave other) ⇒ nil (eq (person-first-name dave) (person-first-name other)) ⇒ t (person-p dave) ⇒ t (person-p [1 2 3 4]) ⇒ nil (person-p "Bogus") ⇒ nil (person-p '[cl-struct-person counterfeit person object]) ⇒ t ``` -------------------------------- ### Defining Derived Types with Parents Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Derived-Types.html Example of defining a derived type that explicitly declares its parent type to assist with method ordering. ```lisp (cl-deftype unsigned-byte (&optional bits) (list 'integer 0 (if (eq bits '*) bits (1- (ash 1 bits))))) (cl-deftype unsigned-8bits () "Unsigned 8-bits integer." (declare (parents unsigned-byte)) '(unsigned-byte 8)) ``` -------------------------------- ### cl-defstruct with multiple :constructor options Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Structures.html Shows a structure with no default constructor and two full-format constructors: new-person and new-hound. The new-hound constructor uses &key and &aux to compute age from dog-years. Demonstrates that &optional and &key arguments without defaults take defaults from slot descriptors. ```emacs-lisp (cl-defstruct (person (:constructor nil) ; no default constructor (:constructor new-person (first-name sex &optional (age 0))) (:constructor new-hound (&key (first-name "Rover") (dog-years 0) &aux (age (* 7 dog-years)) (sex 'canine)))) first-name age sex) ``` -------------------------------- ### Manual implementation of my-list macro Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Macro_002dWriting-Macros.html An example of a macro that manually handles form evaluation using gensyms to ensure forms are evaluated only once. ```Common Lisp (defmacro my-list (x y &rest forms) (let ((x-result (gensym)) (y-result (gensym))) `(let ((,x-result ,x) (,y-result ,y)) (list ,x-result ,y-result ,x-result ,y-result (progn ,@forms))))) ``` -------------------------------- ### Creating a closure with lexical-let Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Obsolete-Lexical-Binding.html Shows how lexical-let captures a variable to create a function object that remembers its environment. ```elisp (defun make-adder (n) (lexical-let ((n n)) (lambda (m) (+ n m)))) (setq add17 (make-adder 17)) (funcall add17 4) ⇒ 21 ``` -------------------------------- ### lexical-let vs let behavior Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Obsolete-Lexical-Binding.html Demonstrates how lexical-let creates a distinct local variable compared to the dynamic scoping of let. ```elisp (setq a 5) (defun foo (b) (+ a b)) (let ((a 2)) (foo a)) ⇒ 4 (lexical-let ((a 2)) (foo a)) ⇒ 7 ``` -------------------------------- ### Use always clause for condition checking Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Iteration-Clauses.html Example of using the always clause to verify that all elements in a list satisfy a condition, returning t if all are non-nil. ```Lisp (if (cl-loop for size in size-list always (> size 10)) (only-big-sizes) (some-small-sizes)) ``` -------------------------------- ### for var being the intervals [of object] Source: https://www.gnu.org/software/emacs/manual/html_node/cl/For-Clauses.html Iterates over all intervals of a buffer or string with constant text properties, binding var to conses of start and end positions. ```APIDOC ## for var being the intervals [of object] ### Description Iterates over all intervals of a buffer or string with constant text properties. The variable var will be bound to conses of start and end positions, where one start position is always equal to the previous end position. The clause allows 'of', 'from', 'to', and 'property' terms, where the latter term restricts the search to just the specified property. The 'of' term may specify either a buffer or a string. ### Syntax `for var being the intervals [of object] [from pos] [to pos] [property prop]` ### Parameters - **var** (symbol) - Required - Variable bound to conses of start and end positions. - **object** (buffer or string) - Optional - The object to iterate over. - **pos** (integer) - Optional - Position limits for the region. - **prop** (symbol) - Optional - Restricts the search to the specified text property. ### Example ```lisp (cl-loop for int being the intervals of (current-buffer) do (message "interval: %S" int)) ``` ``` -------------------------------- ### Swap variables using cl-psetq Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Assignment.html Shows the simplest use of cl-psetq to exchange the values of two variables. ```lisp (cl-psetq x y y x) ``` -------------------------------- ### cl-struct-slot-offset Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Structures.html Returns the zero-based offset of a slot within a structure type. The offset is relative to the start of the structure data type and is adjusted for any structure name and :initial-offset slots. ```APIDOC ## Function: cl-struct-slot-offset ### Description Return the offset of slot slot-name in struct-type. The returned zero-based slot index is relative to the start of the structure data type and is adjusted for any structure name and :initial-offset slots. Signal error if struct struct-type does not contain slot-name. ### Parameters - struct-type (symbol) - Required - The structure type symbol. - slot-name (symbol) - Required - The name of the slot. ### Returns - (integer) - The zero-based offset of the slot. ### Errors - Signals an error if struct-type does not contain slot-name. ``` -------------------------------- ### cl-do Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Iteration.html Creates a general iterative loop with variable bindings, an end test, and optional result forms. Each variable is bound to an init value and updated with a step expression each iteration. ```APIDOC ## Macro: cl-do (spec...) (end-test [result...]) forms... ### Description Creates a general iterative loop. Each spec binds a variable to an init value and optionally provides a step expression. The loop evaluates the end-test each iteration; if true, the loop finishes and evaluates the result forms. The loop is enclosed in an implicit nil block. ### Syntax (cl-do (spec...) (end-test [result...]) forms...) ### Parameters - **spec** - Each spec is of the form (var [init [step]]). - **var** (symbol) - Variable to bind. - **init** (optional) - Initial value; defaults to nil. - **step** (optional) - Expression to update the variable each iteration. - **end-test** (form) - Evaluated each iteration; if true, the loop ends. - **result** (optional forms) - Evaluated after the loop ends, with variables still bound, to produce the return value. - **forms** (body) - Evaluated each iteration before updating variables. ### Behavior - Variables are bound as if by let. - Each iteration: evaluate end-test; if true, evaluate result forms and return. Otherwise, evaluate body forms, then update variables using cl-psetq semantics. - The loop is enclosed in an implicit nil block, so (cl-return) can exit. - If no result forms, returns nil. - If a variable has no step form, it is not modified by the loop. ### Example (cl-do ((x foo (cdr x)) (y bar (cdr y)) (z nil (cons (f (car x) (car y)) z))) ((or (null x) (null y)) (nreverse z))) ``` -------------------------------- ### cl-list* Source: https://www.gnu.org/software/emacs/manual/html_node/cl/List-Functions.html Constructs a list from arguments, with the final argument becoming the CDR of the last cell. ```APIDOC ## Function: cl-list* arg &rest others ### Description Constructs a list of its arguments. The final argument becomes the CDR of the last cell constructed. For example, (cl-list* a b c) is equivalent to (cons a (cons b c)), and (cl-list* a b nil) is equivalent to (list a b). ### Parameters - **arg** (any) - Required - The first element of the list. - **others** (any) - Optional - Additional arguments; the last one becomes the CDR. ### Returns - A list constructed from the arguments. ``` -------------------------------- ### cl-defstruct with :constructor and :type options Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Structures.html Defines a person structure with a custom constructor name 'create-person', using a list representation, and the :named option. This demonstrates the structure option syntax where options are keyword symbols or lists starting with a keyword. ```emacs-lisp (cl-defstruct (person (:constructor create-person) (:type list) :named) first-name age sex) ``` -------------------------------- ### Compare while and cl-loop while Source: https://www.gnu.org/software/emacs/manual/html_node/cl/Iteration-Clauses.html Shows the equivalence between the standard while loop and the cl-loop while clause, noting the implicit nil block in the latter. ```Lisp (while cond forms...) (cl-loop while cond do forms...) ```