GNU Emacs

Table of Contents

Emacs is a keyboard-centric text editor.

emacs_screenshot.png

Figure 1: Screenshot of Personal Emacs Setup

1. Keybindings

1.1. Basic

macro description
C-(n,p) next/previous line
(C,M)-(f,b) forward/backward, a character/word
(C,M)-v next/previous screen
C-M-v next the other window
(C,M)-(a,e) beginning/end of a line/sentence
C-l center the cursor and move screen up half a screen
M-(<,>) beginning/end of a file
C-u <number> <macro> to feed <number> to <macro>
(C,M)-(d,DEL) delete/kill a character after/before the cursor
(C,M)-k kill to the end of line/sentence
C-SPC MOTION C-w select and kill
C-y yank (paste)
M-y flip through the kill ring, <C-h> v kill-ring list them
C-j newline, evaluate lisp expression in *scratch*
C-/ undo
(C,M)-x simple/complex execute
C-g escape
C-(s,r) isearch (backward)
C-M-(s,r) regexp isearch (backward) the groups are colored different
M-s o occur, even during isearch
M-% query replace, even during isearch
C-M-% regexp query replace, that supports grouping
C-z suspends Emacs
C-x ESC ESC repeat last command
M-TAB dab completion based on the text in the open buffers
M-T transpose-word: drag a word forward
M-\ remove all spaces between words
M-SPC contract the spaces between words into one space
M-; insert a comment line

1.2. Extended

Prefix C-x (X as in eXtend)

1.2.1. Text

macro description
C-; comment out a line
C-TAB indent interactively

1.2.2. Buffer

macro description
C-s s save current buffer/selected buffers
C-w write current buffer to a file
C-f find a file
d open a directory
C-b b buffer menu/type buffer name to move to
k kill a buffer
C-c quit
<right> <left> next or previous buffer
i insert a file

1.2.3. Window

macro description
0 remove window
1 remove every other windows
2 duplicate window below
3 duplicate window to the right
4 0 kill-buffer-and-window
5 (0,1,2,o) do the same but to a frame
o move to other window
C-+ C-- zoom
^ - + enlarge, shrink if larger than buffer, balance windows
{ } shrink, enlarge horizontally

1.2.4. Frame

macro description
<f11> fullscreen
M-<f10> maximize frame

1.2.5. Register r

macro description
s R copy region into the register R
i R insert text form R
w R save workspace to R
j R load workspace form R

1.2.6. Rectangle r

macro description
o open rectangle filled with space
t string rectangle
d delete rectangle
y yank rectangle
c clear rectangle and fill with space
k kill rectangle
r copy rectangle to register

1.2.7. Bookmark r

macro description
m set bookmark at point
b jump to bookmark

1.2.8. Tab t

macro description
0 tab-close
1 tab-close-other
2 tab-new
RET tab-switch
m tab-move

1.2.9. Project p

A project is recognized if it's either tracked by a version control system, or EDE(Emacs Development Environment) has created the project.

1.2.10. Special Characters 8

  • It is the compose key equivalent.
macro description
RET (insert-char) insert unicode by its name or codepoint

Superscript letters in Unicode | Rupert Shepherd

  • e emoji
macro description
e, i emoji-insert
l emoji-list

1.2.11. Narrow n

macro description
d to function
n to region
p to page
w widen

1.3. Mode Bindings

C-c may used

1.3.1. Buffer Menu

macro description
m mark
s mark for save
d, C-k mark for delete
x execute markings
u, U unmark (all)
b bury to the end of the list
RET, e, f open buffer menu window
o open on other window
V, O view (in other window)
T toggle show files only
% toggle read-only
g revert buffer
C-o close buffer
q close window

1.3.2. dired   builtin

Directory Editing

C-x d, M-x dired Open a directory with Dired

  • Dired Guess
    • dired-x provides the dired guess functionality.
    • dired-guess-shell-alist-user contains the list of suggestions based on the filename
  • nerd-icons-dired, all-the-icons-dired, treemacs-icons-dired add icons
1.3.2.1. Local Keybindings
  • v view
    • Open with View Major mode if no other major mode for view is available.
    • q to exit
  • C do copy, D do delete, R do rename/move
  • d mark to delete
  • x execute flagged delete
  • i add subdirectory into current buffer
    • $, M-$ toggle hidden (of all)
    • C-M-u, C-M-d Tree up or down
    • C-M-n, C-M-p Next or previous subdirectory
  • m, u mark and unmark
  • T do touch, O do chown, M do chmod, G do chgrp, N do man, I do info, S do symlink, H do hardlink, Z do compress
  • X do shell command
  • C-x C-f to create a new file, make-directory to create a new directory.
  • g revert(reload) buffer
  • C-x C-q immediate edit
  • ^ > < Parent directory, Sibling directory
  • w copy filename to kill ring
  • W browse url of dired file
    • It opens a new server editing buffer for text files, which is like a externally opened file but in the same frame.
    • C-x # to mark it done and switch to next server editing buffer.
  • J goto file
  • & async shell command on the file at point, X shell command on the file
  • C-t thumbnail
    • . display thumbnail in other window
    • C-t toggle inline thumbnail
    • a append thumbnail to the thumbnail buffer
    • d display thumbnails of file at the cursor, or marked files
    • i display image in other window
    • j jump to thumbnail buffer
    • x display image externally
  • C-t tag
    • The tags are stored in ~/.emacs.d/image-dired/.image-dired_db
      • t tag files
      • r delete tag
      • f mark tagged file
  • * mark
    • m mark, u unmark, ! ? unmark all
    • * executable, / directory, @ symlink, s subdir files
    • % mark with regexp
    • * C-n, * C-p or M-{, M-} previous or next marked file
  • % regexp
    • C copy
    • R, r rename
    • S symlink
    • Y resymlink
    • H hardlink
    • d flag, g flag files containing regexp
    • & flag garbage files
    • m mark
    • l, u downcase, upcase
1.3.2.2. Configuration
  • ls-lisp-use-insert-directory-program use external ls instead of ls-lisp, the builtin ls emulation written in Lisp, if this is t
    • This does not apply to dired-sidebar for some reason.
    • insert-directory-program the external program to be used
    • dired-listing-switches controls the options passed to the program, including ls-lisp
  • ls-lisp-dirs-first
    • list directory first when using ls-lisp
  • dired-use-ls-dired append --dired option
1.3.2.3. dired-sidebar
  • dired-sidebar-toggle-sidebar
  • TAB (dired-sidebar-subtree-toggle)
  • RET (dired-sidebar-find-file) open the file in the last window
  • C-o (dired-sidebar-find-file-alt) opens the file in the window selected by ace-window
  • - (dired-sidebar-up-directory)

1.3.3. proced   builtin

list running processes, similar to top.

1.3.4. Dumb Shell

  • C-<up>, C-<down> previous or next input

1.3.5. Outline Mode

It is minor mode for markup files. It changes its behavior based on the major mode

  • Help mode: <, > beginning or end of buffer

Prefix C-c @, or sometimes C-c

macro description
C-e, C-s, C-b, C-a show entry, subtree, branches, all
C-c, C-d, C-l, C-t, C-o, C-q hide entry, subtree, leave, body, other, all
C-p, C-n previous or next visible heading
C-b, C-f backward or forward same level
C-<, C-> promote or demote
C-^, C-v move subtree up or down
RET insert heading (it copies the previous heading)

2. Commands

  • M-x execute command
    • Every keybindings are a lisp command that can be executed in here.
  • M-! run shell command and output to the minibuffer
    • It can run sudo with the help of -S option that read from standard input, or with the askpass helper which is ksshaskpass on KDE.
    • C-u prefix makes the output go to the current buffer.
    • Use M-| instead to accept a region as an argument.
  • M-: execute a Lisp expression.
  • view-register
  • compile run compile command and format the output.
  • grep run grep
    • rgrep search thoroughly
  • describe-mode describe the enabled modes
  • indent-rigidly
  • undo-only undo the region selected. It only works for the edits done natively by emacs
  • open-dribble-file record every input events into a file, recent-keys returns last 300 input events.
  • recover-file select file to recover from the auto-save file
    • recover-this-file also exists.

2.1. Text Manipulation

  • align-regexp align a region with ad hoc rules.
  • C-x RET r (revert-buffer-with-coding-system) try a new encoding.
  • recode-region, recode-file-name translate from one encoding to another.
  • fill-region break a long line into smaller ones.

2.2. Shell Functionalities

  • M-! (shell-command) run shell command in the minibuffer and echo the result.
  • eshell-command run eshell command in the minibuffer

2.3. File Manipulation

  • delete-file, rename-file
  • make-directory make-d
  • load-file: Load Lisp file, especially the .emacs.

2.4. External Functionalities

  • run-python
  • compile
    • It displays the result in a special buffer.
  • shell
    • Run the shell in dumb state

3. Modes

Major mode can be enabled on at a time, while minor modes can be used alongside any other modes.

3.1. Major Modes

Major mode is determined by

  1. Local variables mode within -*- var:VAL; ... -​*- in the first line
  2. Compare file extension against auto-mode-alist
  3. Infer from the interpreter in the #!
  4. Infer from the start of the buffer using magic-mode-alist
  5. Compare file name against auto-mode-alist
  6. Compare the start of the buffer against magic-mode-fallback-mode-alist
    • It checks for image files, markup files, PostScript files, Unix Conf files.
    • The major mode is remapped using major-mode-remap-alist

The default major mode can be accessed by M-x normal-mode

See Choosing Modes (GNU Emacs Manual)

3.1.1. Language

  • python-mode
    • ein
  • hexl-mode hexedit.
  • emacs-lisp-mode
    • C-c C-b (elisp-byte-compile-buffer)
    • C-c C-e (elisp-eval-region-or-buffer)
    • C-c C-f (elisp-byte-compile-file)
    • C-M-x (eval-defun)
    • eval-buffer

3.1.2. Special Text

  • picture-mode: draw a diagram, with cursor moving in any direction

3.1.3. View

  • View
  • DocView

3.2. Minor Modes

When a minor mode is enabled globally, it does not show on the mode line.

  • Minor mode can be set by -*- eval: (MINOR-mode) -​*- in the
  • File
    • read-only-mode
    • desktop-save-mode
      • It is not saved when emacsclient is closed
      • The frame position, search history, file history, registers, buffers are saved
    • auto-save-mode save buffers in #<file># periodically, when auto-save-default is non-nil
      • It is deleted on save, when delete-auto-save-files is non-nil
      • .#<file> -> buffer is temporarily created when the buffer is hot
      • Backup files named <file>~ are made on save when make-backup-files is non-nil
    • auto-revert-mode, global-auto-revert-mode
    • global-ede-mode
      • Emacs Development Environment
      • It is a built-in package that manages projects
    • recentf-mode remember recent files
  • GUI
    • tool-bar-mode
    • menu-bar-mode
      • the menu bar can be accessed with F10
    • scroll-bar-mode and horizontal-scroll-bar-mode
    • tab-bar-mode
    • display-line-numbers-mode
      • display-line-numbers-major-tick
      • The line numbers are not aligned correctly in variable-pitch-mode.
    • Mode Line
      • The file status <encoding><newline>@<modifiable><modified><file location>
        • Encoding: U utf-8-unix,
        • Newline: : Unix LF, <DOS> CRLF
      • line-number-mode display line number in the mode line
  • windmove-mode move and swap windows with keybindings
  • use-dialog-box let the mouse operation open a separate dialog box
  • display-time-mode display time in the minibuffer
  • Text
    • abbrev-mode simple snippet mode that triggered by RET
      • Prefix C-x a
      • C-a or + or l: add-mode-abbrev
      • g: add-global-abbrev
      • ' or e: expand-abbrev
  • auto-fill-mode automatically insert line break
    • M-q (fill-paragraph) automatically insert line breaks and fill the line at the current paragraph
    • C-x f (set-fill-column) set the column numbers for the paragraph
    • fill-region fill the paragraphs in the region, fill-region-as-paragraph consider region as one paragraph
    • center-line center a line
    • visual-line-mode wrap the long line visually
  • savehist-mode save the history of the minibuffer
  • save-place-mode save the point position
  • Unibyte Editing Mode

3.3. Keymaps

  • keymap-set and define-key can be used to modify the keymap of the mode.
  • MODE-mode-map contains the keymap of the mode.

4. Applications

4.1. Calc   builtin

GNU Emacs Calculator

There's also calculator which is a dumbed down version of the calc with single stack and infix notation.

4.1.1. Global Keybidings

  • <C-x> * c, <C-x> * *, <M-x> calc to open
    • <C-x> * o open another window
    • <C-x> * q quick calc. open in the minibuffer
  • <C-x> * e embedded calc on a block of continuous formula as a line, after evaluating it.
    • The separation of a block is detected by a two newlines.
    • <C-x> * j embed but on appropriate side of the => or :=. a : 10= becomes . .. 10
    • <C-x> * w embed on a single word if the expression is not parsable, otherwise same as just embedding.
    • The embed can be exited with any of the commands
  • <C-x> * b toggle full screen for the Calc
  • <C-x> * y y yank the top element to the most recent edit buffer
  • <C-x> * g grab, parse a line into the top element as vector
    • The number of line can be given as numeric prefix, and if only C-u is given the line is interpreted as a single entry.
  • <C-x> * r rectangle, parse a region as matrix
    • The column length can be given as numeric prefix
  • <C-x> * : sum the columns
    • <C-x> * _ sum the rows
  • <C-x> * 0 reset
  • <C-x> * x turn calc off
  • <C-x> * m read in as a macro
  • <C-x> * z user invocation
    • start Calc with user defined macro by Z I

4.1.2. Local Keybindings

The key in the heading is the common prefix.

4.1.2.1. Help
  • i manual
  • h help
    • h all keybindings
    • s summary appendix
    • i manual
  • ? rotate through the brief help
4.1.2.2. Input
  • <, > scroll to the right/left
  • {, } scroll up/down

Edit

  • U undo, D redo
  • <TAB> rotate the top two
    • rotate the top N elements downward while wrapping if positive
    • move the entire stack N step downward if negative.
    • <M-...> rotate upwards
  • <DEL> remove the top
    • remove the top N elements if positive
    • Delete the entire stack if 0
    • N th element form the top is removed if negative
    • <M-...> remove from the bottom

Input

  • <RET> duplicate the top element
  • <M-RET> push the last arguments
    • recover the deleted elements by a function
  • [2-32]#NN input number in a given radix
  • NNeNN scientific notation
  • _ negative sign
  • : enters the fraction
  • [ .. , .. ; .. ] vector and matrix, [ .. ] [ .. ) interval, representing all number between the bounds
    • [ ( pushes the incomplete object and complete it later.
    • { .. , .. } can also be used. comma is required
  • ( .. , .. ) ( .. ; .. ) complex number (in polar),
  • .. @ .. ' .. " hms time
  • " string
  • Operation can be put right after number
  • $ can be used in place of the top stack element, the output will be replace the top
    • $$, $$$ repeatedly using dollar sign access N th element from the top
  • ' algebraic input
    • Insert an expression containing symbols, equations, and various others
    • <RET> evaluate and the expression and insert
      • <M-RET> evaluate with the variables resolved, and insert
      • <C-j> or <LFD> (Line Feed) does not evaluate it, = to evaluate it later.
    • / has lower precedence than *.
    • a mod b modulo arithmetic
    • +/- to include the uncertainty
  • < , : > inline function
    • The arguments are given in a vector.
    • It cannot be used on its own. It needs to be evaluated by another function, such as, call(f, a, b), v A, apply(f, v)
4.1.2.3. Basic Operations
  • They take the elements from the stack and perform certain operations
  • Number prefix can be given
    • The binary operation is going to be reduce the top N elements if positive, or operate on each N next-to-top element by the top element if negative.
  • +, -, *, /, ^
  • \ integer division, % modulo
  • : fraction
  • ~ can be used to use the top element as the prefix number
  • K keep the arguments in the stack by prefixing this
  • Evaluation
    • = evaluate and substitute the stored variables
    • N expand the irrational values
    • a v evaluate algebra
  • Simplification
    • a s algebraic simplification
    • u s unit simplification
      • Automatically applied when in UnitSymp mode
4.1.2.4. Array Operations v
  • p, pack(a, ...) pack first few top element into another object depending on the mode specified by numeric prefix N, or the value of the top element.
    • Vector of length N if N is nonnegative
    • -1 complex number
    • -2 polar complex number
    • -3 HMS form
    • -4 error form
    • -5 modulo form
    • -6 closed interval, -7 upper half-open interval, -8 lower half-open interval, -9 open interval
    • -10 fraction
    • -11 mantissa and exponent into floating point number
  • u, unpack(a, ...) unpack the top element
    • negative number specifies the mode
    • It can unpack any formula as well, including equations
      • It unpack the structure given by the underlying lisp representation.
  • (Without the prefix) |, vconcat(a,b) concatenate top two element into a vector, I | in reverse order, H | not recursively.
  • E convert an interval into a vector of integers
  • : vector into an interval
  • i push an identity matrix
  • d diagonal matrix out of the top
  • x push the index vector
  • r, c, mrow(m, i), mcol(m, i) extract the row/column of a matrix at the index of the top element or numeric prefix. s, subvec(m, i1, i2) extract a subvector from the first index up to the second index excluding it.
    • The index is counted from 1
      • A row/column is removed if negative number
    • m_i, subscr can be used for the algebraic case.
  • f search for an element in a vector
  • a arrange a vector or a matrix into a matrix of a given number of column
  • v reverse the vector
  • h, head(v) take the head, the first element of a vector.
4.1.2.4.1. Linear Algebra
  • The regular multiplication * does the matrix multiplication.
  • t transpose
  • J conjugate transpose
  • C cross product
  • A Euclidean norm or Frobenius norm
  • n Infinity norm
  • N one-norm
  • & inverse of a square matrix
  • D determinant
  • T trace
  • L LU decomposition
  • K Kronecker product
4.1.2.4.2. Element-wise Operations
  • A Apply
    • provide each element as each argument to a function.
  • M map, R reduce, U accumulate(scan)
    • Map can take multiple vectors as the inputs
    • :, _ map or reduce each column/row of matrices
    • N specify the number of arguments.
    • The element-wise operation can be any Calc binding such as +, v M, a ].
    • x select a lisp function
    • ' specify a custom function
      • Write the expression inline, for example, sin(x) + y.
        • The arguments of the function will be selected manually after you press RET.
      • The inline expression can contain $, $$ in which case you don't need to specify the arguments.
        • $ for the top, $$ for the second to top, and so on.
      • The anonymous function can contain #1 or # (one variable) in which case the arguments does not need to be specified.
      • A lambda expression can be passed as well, for example, lambda(a, b, a+b).
  • O, I generalized outer/inner product
    • Inner product requires specifying two operator
4.1.2.4.3. Set Operations
  • + remove duplicates, # set cardinality, V union, ^ intersection, - set difference, X set XOR, ~ set complement with respect to real number
4.1.2.5. Algebra a
  • v evaluate the algebra, " expand into the definition
  • s simplify
    • x expand: divide fractions, distribute multiplication
    • f factor a polynomial
      • H a f return the list of factors with its multiplicity.
    • c, collect express the polynomial in a given variable.
    • n, nrat(a) normalize rational (symbolic fractions into a one rational expression), a partial fraction
    • \ polynomial division, % polynomial remainder, g polynomial gcd
    • I a s trigonometric function simplification
    • H a s hyperbolic function simplification
    • a e extended (unsafe) simplification
  • d derivative, i (integ(f), integ(f(x), x, a, b)) integrate
    • I (ninteg) numerical integration
  • M map equation
    • Map both side of the equation
  • P find the root of polynomial
  • S solve the equations
    • It can also take a vector of equations and a vector of variables.
  • R root finding
    • A formula or an equation is solved numerically, starting from the top element
    • It can also take a vector of equations, and a vector of initial values, a vector of variables.
    • Assigned variable can be used, _ dose not constitute a variable.
    • The formulas have to be differentiable
  • F curve fitting
    • It act on a list of list containing each variables consecutively.
    • The number specify the detail
    • 1 linear, 2 - 9 multilinear
    • e, x, E, X polynomial, l, L logarithmic
    • q quadratic
    • g Gaussian function
    • s Logistic
  • + sum over a given range
  • * product over a given range
4.1.2.6. Functions
4.1.2.7. Random
  • r random()
    • It generate a random integer between 0 and the numeric prefix, or the top element
      • a generate a number reusing the recent value
      • h shuffle
    • It shuffles the top vector, may be truncated to a desired length
4.1.2.8. Units u
  • Units are just unassigned variables that are in the unit table
  • Number with unit can be entered as a algebraic expression. Most common units and constants are predefined
    • eps0 ɛ0, mu0 μ0, c, G, h, hbar, e ech, k, …
  • s simplify for the unit expression, a autorange unit prefix the unit with appropriate one.
  • c unit convert, n convert if exact, b convert to base unit, equivalent to s base
  • d, u define/undefine unit, r remove unit, u p make it permanent in the calc.el
  • g get unit definition, v show unit table
  • s Store
  • inf, e, pi, phi, gamma, uinf, nan are preassigned variables
    • These are only evaluated by N, not =
4.1.2.9. Store s
  • If the variable name is a number N it is stored in special variable qN. The quick variables can be directly specified without s
  • If the top element is an assign statement: =, :=, it will perform it
  • r recall, push the value
  • u unstore
  • t store into, store the top element
  • x exchange with the top of the stack
  • c copy to another variable
  • +, - , … perform the operation and assign, equivalent to +=
  • = evaluate to, enter the evaluation statement of the top element
    • => The expression on the left is untact, the value on the right is recomputed by = (evaluate) whenever something changes.
  • d declare the type of a variable or a function
  • l let
4.1.2.10. Select j
  • Select within a entry and perform operation on them
  • s, u select/unselect
  • a add, b break selection, m l select more/less, 1, …, 9 select =N=th part
  • n, p select next/previous
  • d highlight selected part within the whole formula
  • c clear all selection
  • e enable/disable selection. the * marker disappears and the operation works on the entire formula anyway. It is enables by default.
  • ' replace selection through minibuffer input
  • ` edit selection through a temporary buffer
  • R, L commute right/left, C commute within a selection
  • D, M distribute/merge a level
  • J jump equals, move a term on the other side of the equation
  • +, -, *, /, … Operate on both side of a equation, or numerator and denominator of a fraction.
4.1.2.11. Convert c
  • f convert fraction to float, F float to fraction
  • p between polar and rectangular complex numbers
  • d, r, h degree, radian, hms
4.1.2.12. Display d
  • t Truncate. It cuts the stack at the cursor, and stashes the ones "above" it.
  • r change the radix
  • c, i, j, complex number format
  • Language
    • N normal, B big (pretty print), U unformatted(raw Lisp), C, L LaTeX, T TeX
    • The complex number format does not apply in B and C
4.1.2.13. Mode m
  • The current mode is displayed in the mode line
    • a partly algebraic mode, ( and [ also starts algebraic input.
    • t full algebraic mode, <ESC> to not use algebraic input.
  • S ignore cases, the prefix key becomes case insensitive.
    • d degree, r radian
      • The default unit of the output of functions that produce angles
    • p polar mode, prefer complex number
    • f fraction mode, prefer fraction
      • c f can be used to evaluate the fractions
    • i infinite mode, 1/0 produce inf
    • s symbolic mode, the irrational result will be left symbolic
      • N can be used evaluate into numeric result
    • v matrix mode, every object is assumed to be matrices unless it cannot be
    • C toggle automatic recomputation, =>
    • Simplification
      • I basic simplification
      • U unit simplification
      • A algebraic simplification (Default)
      • N number simplification, only number operations are simplified
      • E extended simplification
      • O no simplification
    • m save modes, including display/language/precision/definition/calculation
    • g get modes, push the mode numbers
    • R record mode change directly into the file
4.1.2.14. Trail t
  • d toggle trail
  • i, o focus into/outof trail
  • n, p, [, ] move the trail marker > (to the start/end), y push trail marker to the stack
  • s, r search (in reverse)
4.1.2.15. Time t
  • N push current datetime
  • D date into a number measured since Jan 1, 1 AD
  • J convert date into Julian day count
  • U convert date into unix time value
  • C convert time zone of date
4.1.2.16. Graphing g
  • It stores the values in a temporary buffer and let the Gnuplot plot it.
  • f Fast plot. graph the top two element using Gnuplot. top element is the \(y\).
    • \(x\), \(y\) can be a vector of same length
    • \(x\) can be an interval, then \(y\) needs to be an algebraic expression in one unassigned variable
    • The top element can be a formula of the form xy(x(t), y(t)).
  • p plot
  • a, d, c add/delete/clear the plot
  • g, b, k… grid, border, key
  • N select the number of datapoints
  • q quit the plot
4.1.2.17. Macro z
  • Z D bind the function to a key
  • <C-x> ( <C-x> ) the global kmacro can include the following calc specific functionalities.

    • Branch
      • COND Z [ start if, Z | else if, Z : else, Z ] end if
    • Loop

      • REPEAT Z < BODY Z > repeats a command in between, the top value times.
        • REPEAT is the top element
          • INIT FINAL Z ( BODY STEP Z ) for loop, repeat with

      counter

      • INIT, FINAL are the top two elements of the stack
      • STEP is a number
        • COND Z / break out of macro loop
      • Breaks the top element COND evaluates to true.
        • Z {, Z } loop forever
      • Scope
        • Z `
        • Z '
      • Z K set macro name for the last recorded macro, which can

    be executed by z

    • Z E edit macro
    • <C-x> e or X execute macro
      • <C-x> e create a undo history for each command, X create a single undo history
  • Z I define user invocation
    • m m saves this
  • Z F define a formula
    • The formula at the top element is stored as key, command and function.
    • The anonymous function can also be used.
    • Z G push the formula to the stack
  • Z P define a command permanently in the calc.el
  • Z U undefine
  • z is prefixed to use the user defined keys and functions
  • Lisp
    • defmath can be used
    • (interactive NUM TAG)
      • Takes NUM arguments from the stack.
    • (calc-eval "expr") is available
  • Configuration
  • p set precision
    • The floating point precision default to 12
  • x run calc command <M-x> calc-
  • q quit

4.1.3. Configurations

Configurations can be stored in:

  • .emacs: Configure manually or via Custom
  • the file set by calc-settings-file ( .emacs.d/calc.el by default).
    • This file is loaded on the first launch of Calc.

The global variables can be accessed directly, but the internal functions and variables needs to be imported via (require 'calc-*).

  • The variables that controls the initialization can be set.
  • The detail can be directly found in the repo

4.2. Org Mode   builtin

It is a mode for .org file, but it's large enough to be called an application.

4.2.1. Metadata

4.2.2. Markup

  • Heading (Topics)

    • * ** ***, …
    • Promoting without heading is not allowed due to the need for simplicity

    and compatibility with LaTeX, DocBook and traditional book/article structures.(??, ????)

    • M-<right>, M-<left> demote and promote current heading or list item
    • C-M-<right>, C-M-<left> demote and promote current subtree
    • M-<up>, M-<down> swap up and down
    • M-RET new item, M-S-RET new checklist item
  • Tags
    • C-c C-q (org-set-tags-command) add tag to a topic. C-c C-c does the same thing in a headline
    • @ and _ can be used within tag names.
    • #+TAGS: <tag>(<fast access key>) ... is used to set tags for a file
    • org-tag-alist defines the tags, with the second argument ?<fast access key>.
  • *bold*, /italic/, _underline_, +strikethrough+, ~code~, =verbatim=, : at the start of a line
  • + - *=(nested) unordered list, =1. 1) A. A) ordered list, [ ] [-] [X] checkbox, :: tag
  • Todo
    • C-c C-t or S-<right>, S-<left> org-todo, change the todo state
  • Link
    • C-c C-l org-insert-link, C-c C-o org-open-at-point
    • [[target]] or [[target][desc]]
    • type:target if no type is provided, org looks for the headings.
    • http
    • file
      • it can be nested such as file:...::#id or file:...::*heading
      • The id is set by the CUSTOM_ID property.
    • <<target>> dedicated target. Link to it with [[target]]
    • #+name: target match the exact name of an element.
    • See External Links (The Org Manual), Internal Links (The Org Manual)
    • org-link-set-parameters create custom link type
      • :follow <func> on open
      • :export <func>
      • :store <func>
      • :image-data-fun <func>
  • Footnote
    • [fn:Name], [fn:: inline], [fn:NAME: inline definition]
    • C-c C-x f footnote action. jump to the definition, or create a new footnote, and more
    • C-c C-c jump to the definition or jump back to the reference
    • C-c C-o or <mouse-1>, <mouse-2> follow the link, same as C-c C-c
  • Citation
    • The citation file can be added locally with #+bibliography: BibTeX FILE or with org-cite-global-bibliography variable.
    • It is referenced with [cite:@key]
    • Multiple key can be given separated by ;, and prefix and suffix can be given.
  • Image
    • Image is inserted as a link to the image file.
    • C-c C-x C-v to render images inline.
      • Image can only be rendered inline when there is no description in the link.
    • Instead of manually rendering inline images for every buffer, the variable org-startup-with-inline-images can be set to t globally, or the directive #+STARTUP: inlineimages can be used per file.
    • #+caption: TEXT, #+name: NAME can be preceded to the image.
    • #+attr_org, #+attr_latex, #+attr_html: :TAG VALUE are used to set the display format.
    • Images (The Org Manual)
  • #+begin_TYPE #+end_TYPE block
    • center, comment, dynamic, example, export, quote, special, verse, src
  • | table
  • # comment, @@comment: comment@@ inline comment, #+BEGIN_COMMENT #+END_COMMENT block comment, =* COMMENT section comment

4.2.3. Macro

  • #+macro: f ...$1... define macro
  • {{{f(1,...)}}} use macro

4.2.4. Commands

  • C-c C-j (org-goto) show outline in a new buffer and select from it
  • C-c C-q add tag to a topic
  • C-c C-x C-v (org-toggle-inline-images)
  • C-c C-x
    • Properties
      • p (org-set-property)
      • P (org-set-property-and-value)
    • Timer
      • ; (org-timer-set-timer) countdown timer, 0 (org-timer-start) countup timer
      • , (org-timer-pause-or-continue), _ (org-timer-stop)
      • . (org-timer) start a timer if there's none, and insert current elapsed time
    • Text
      • C-f (org-emphasize) choose bold, italic, and others.
    • ! reload all lisp files related to org.
    • LaTeX support

4.2.5. LaTeX Support

  • org-cdlatex-mode enables the cdlatex bindings
4.2.5.1. LaTeX Preview
  • org-latex-preview is now being worked on to include live preview and support in other major modes.
  • The divpng did not work sometimes with the error .dvi was not found. Changing the relative path %f to absolute path %F fixed the issue.
    • It is not supported on the Karthink's branch
  • #+startup: latexpreview renders the LaTeX expressions on startup.
    • org-startup-with-latex-preview can be also be set to t
  • <C-c> <C-x> <C-l> preview the LaTeX fragment at the cursor, if no fragment for every fragment in the current entry.

4.2.6. Source Code

  • #+begin_src #+end_src source code block
  • The source code is only executable if the language is properly installed on the system and the language is loaded by Babel
  • Babel: Code block evaluation and management.
    • The language listed by org-babel-load-languages is loaded.
    • <C-c> <C-c> evaluate
4.2.6.1. Header

#+HEADER: can be used to specify the headers

  • :var
    • VARIABLE=VALUE Give parameter to the script
  • :results
    • Collection
      • value return value, output standard output
    • Type: Result Type
      • table, vector, list, scalar, verbatim, file
    • Format: Result Format
      • raw, code, drawer
      • html Use BEGIN_EXPORT html
      • latex Use BEGIN_EXPORT latex
      • link, graphics Link to the file specified in :file header argument The code block output is not written to the disk
      • org Use BEGIN_SRC org block
      • pp Pretty-Print Source Code
    • Handling
      • replace
      • silent echo in the minibuffer
      • none compute the result without displaying them, but it can be used by other code blocks
      • discard The result is ignored. The value of the code block will be nil
      • append append to the buffer at the bottom
      • prepend Prepend to the buffer at the top

4.2.7. Org Table

  • C-c C-c align table
  • M-a, M-e beginning and end of a field.
  • M-<arrow> move a row or column
  • M-S-<right> insert column left (at point), M-S-<down> insert row above (at point)
  • M-S-<left> delete column at point, M-S-<up> delete row at point.
  • S-<arrow> move a cell
  • C-c - insert hline below
  • C-c RET insert hline below and move below the hline
  • S-RET first non-empty field above and insert copy of it below.
    • integer, time stamp, whole number prefixed/suffixed is incremented when org-table-copy-increment is set.
  • C-c TAB shrink or show specified columns.
  • Tables (The Org Manual)
4.2.7.1. Table Formula
4.2.7.1.1. Execution
  • C-c * (org-table-recalculate) apply column formulas left to right, and field/range formulas in the current row.
  • C-u C-c * or C-u C-c C-c recomputer the entire table, line by line, with the lines before the first hline is ignored.
  • C-u C-u C-c * or C-u C-u C-c C-c iteratatively recompute the entire table until no changes occur.
  • org-table-recalculate-buffer-tables
  • C-c <=> edit or create formula at the current cell.
4.2.7.1.2. Field Reference
  • Row
    • @0 Current Row
    • @1 Absolute, @+1 Relative, @< @> @>>> Relative to the top/bottom
    • @II Absolute hline, @+I @-II Relative hline, @II+2 Relative dataline relative to the absolute hline
  • Column
    • $0 Current Column
    • $1 Absolute, $-1 Relative, $> Relative to the left/right
  • Range
    • $1..$3 @-1$-2..@-1 @I..II (@I..@II)
  • Coordinate
    • @#, $# row or column number of the field for
4.2.7.1.3. Syntax
  • The calc expression is directly allowed.
    • if(COND, IF_TRUE, IF_FALSE)
    • string(STR)
    • vsum(RANGE)
    • vmean(RANGE)
  • The Emacs lisp can be used. The expression needs to be quoted.
    • ;N at the end of an expression let emacs treats the result as a numerical value.
  • remote(TBL_NAME, REF)
4.2.7.2. Features
  • The content in the first column can create a special row
    • ! name definition of columns
    • ^, _ name definition of fields in the row above (or below)
    • # make the row recalculate automatically
    • * make the row selected for global recalculation
    • / the row is not exported
  • Any one of the fields in a column can be used to specify the width and alignment of the column.
    • <N> fixed width of N,with the ability to be expanded with C-c TAB.
    • <r>, <c>, <l> to align the contents
    • <rN> is also allowed

4.2.8. Task Management

  • S-<rightarrow>, S-<leftarrow> to change the TODO status of a heading.
  • C-c , set or remove priority
  • C-c C-s schedule a heading, C-c C-d set a deadline
    • The datetime is delimited with <> or [].
    • S-<arrow> within the brackets alters the time.
  • [/] at the end of the parent heading indicate the number of completed tasks
  • Clock

4.2.9. Dot

  • The Graphviz language
  • It generates graphs
    • title:
    • type:(2d|3d|radar|grid)
      • org-plot/preset-plot-types customize
    • with:
    • min: max:
    • labels:
    • set:

Plot the table with <C-c> " g or <M-x> org-plot/gnuplot

4.2.10. Org Agenda

  • C-c [ (org-agenda-file-to-front) adds current file to org-agenda-files, C-c ] removes current file.
4.2.10.1. Todo
  • C-c C-t (org-todo), or S-<left>, S-<right> rotate the state of TODO
  • C-u C-c C-t record timestamp and a note
  • C-u N C-c C-t changes to N th state.
  • org-todo-keywords can be configured. See Tracking TODO state changes (The Org Manual)
    • Format: (<fast access key><entering log>[/<leaving log>])
    • The fast access key becomes available after C-c C-t
    • ! log timestamp, @ log note and timestamp
    • the leaving log only works when the target keywords does not have logging enabled.
    • | within the sequence indicates that the keywords after it are DONE state.
    • The logging is enabled when the destination is set by the org-log-into-drawer variable.
  • [ / ] can be added at the end of a TODO heading to count the task done.
    • C-c C-c (org-toggle-checkbox)
    • C-c , (org-priority), S-<up>, S-<down> to change priorit
  • S-M-RET (org-insert-todo-heading)
  • Schedule and Deadline
    • C-c C-s to schedule a heading. C-c C-d to set a deadline
    • <DATETIME REPEATER WARNING> date can be repeated with +N[ymwdh], and warned with -N[ymwdh]
    • .+ is for repeat after done, ++ for repeat periodically.
  • habit module has to be enabled in org-modules to use :STYLE: habit.
4.2.10.2. Agenda View
  • g D (org-agenda-view-mode-dispatch) select the view format
  • A add agendas to view
  • D toggle diary
  • g j, g k next, previous item
  • g d goto date
  • * mark all
  • U, M, unmark all
  • u undo, r redo
  • Q quit
  • a add note to an agenda
  • m toggle mark
    • x bulk action
  • S-<left>, S-<right>, H, L shift the scheduled date
    • p change date with prompt
  • S-<up>, S-<down>, J, K shift the priority

4.2.11. Org Roam

4.2.11.1. Template
  • The templates are defined in the variable org-roam-capture-templates.
    • A template looks like (KEY NAME TYPE TEMPLATE SCRIPT OPTION)
      • Template: %? within the template indicate the position of the point. It can also be (file FILEPATH) to externally load the content.
        • %^NAME can be used to prompt the user.
      • Script: :if-new and (file+head FILENAME HEADER) specify the first time header creation
        • ${slug}, ${title} can be used as a placeholder.
  • The files are hashed into SQL database, stored in ~/.emacs.d/org-roam.db.
    • org-roam-db-sync and org-roam-db-autosync-mode
4.2.11.2. Keybindings
  • C-c n d daily note for today
  • C-c n c capture node
  • C-c n i insert node

4.2.12. Org Drill

4.2.13. Org Cliplink

Automatic insertion of title of the hyperlink

It provides org-cliplink and org-cliplink-capture, which is recommended to be bound to <C-x> p i.

See GitHub - rexim/org-cliplink: Insert org-mode links from clipboard

4.2.14. org-special-block-extras

Enable the definition of custom blocks and links

org-special-block-extras

4.2.15. Export and Publish

4.2.16. Configuration

  • org-startup-folded can be set to control how much the org document is folded
  • org-indent-mode pretty indent the headings
  • number each heading
    • org-startup-numerated can be set to t

4.3. eshell   builtin

Eamcs Shell

  • There is shell and eshell. shell is the terminal called dumb that runs standard shells, and eshell is the shell and a terminal on its own.
  • eshell can run both commands and Elisp functions.
  • >>> #<buffer BUFFER> to pipe the output into a buffer.
  • C-c C-n, C-c C-p move to next or previous prompt
  • It has two different parser: one for Elisp and one for shell script.
    • $(...) for Elisp parser, and ${...} for shell script parser.
    • Some of the keywords has different syntax than the usual shell script.
    • The precedence is: alias, eshell/ function, lisp function, executable.
  • Runs the commands in eshell-visual-commands, in a special buffer.

4.3.1. Globbing Filter

*(...)

  • . file, / directory
  • ^ not
  • : modifiers: U uppercase

4.4. eww   builtin

Web Browser

It does not run javascript, and only shows the text from the HTML file.

4.5. calendar and diary   builtin

Diary is a simple way of remembering a data. Calendar integrates diary.

  • The diary is stored in ~/.emacs.d/diary file. which contains list of date-description pairs.
    • i d to create new diary entry

4.6. mpc

mpd client

The player is controlled by commands.

  • mpc-play, mpc-pause, mpc-toggle-play, mpc-stop, mpc-play-at-point
  • mpc-playlist, …

4.7. ses   builtin

Simple Emacs Spreadsheet

It is enabled in .ses files.

4.8. ispell   builtin

Spellchecking.

  • It uses ispell by default. Change it to hunspell by setting ispell-program-name
  • r replace, a accept for this session, i insert to dictionary, u uncapitalize and inser to dictionary, SPC skip
  • ispell-chage-dictionary for other language.
    • flyspell-mode highlights the misspelled words.
      • M-$ check the spelling at point
      • C-; to correct word in place
      • C-c $ to correct word interactively
    • ispell-buffer will check the buffer for spelling.

4.8.1. Configuration

  • personal dictionary is stored in ~/.hunspell_DICT.
    • noun: /10 (with final consonant), /25 (without final)

4.9. Amusements

  • dunnet text-based adventure
  • snake, tetris, pong, solitaire, gomoku, hanoi
  • decipher solve the monoalphabetic substitution cipher
  • morse-region, unmorse-region
  • nato-region, denato-region
  • zone doodles with buffer when idle.
  • dissociated-press scramble the text in the current buffer and puts them in *Dissociation*
  • butterfly from the internet joke.
  • doctor therapist Eliza

5. Configuration

  • Uses Lisp for the config file.
  • ~/.emacs, ~/.emacs.d/init.el, ~/.config/emacs/init.el

5.1. Compilation

  • The compilation options and available features for Emacs are given in
    • system-configuration-options and system-configuration-features

5.2. Custom   builtin

  • 'Easy Customization Interface' within the editor.
  • Variables and setting can be customized through this interface, and saved to the ~/.emacs
  • They are mostly accessible via M-x customize-*
  • Basic motions are possible: n, p, q

5.3. use-package

  • Init files are run before any of the package loads?, therefore add-hook is used to run commands after the packages load, with (add-hook 'HOOK_TIME #'HOOK_COMMAND).
    • after_init_hook
      • prog-mode-hook
    • image-mode-hook
  • Use package simply overrides the Customization, without modifying it.
  • use-package macro can configure the package.
    • :ensure install the package form the repository if not installed.
    • :preface run before anything else. This is for defining functions and variables.
    • :if conditional statement
    • :load-path custom load path for the package. Not usually used.
    • :after load after. :all, :any can be used alongside.
    • :defer t
    • :ensure t
    • :hook (((MODE*) . HOOK)*)
    • :bind ((KEY . FUN)*)
  • :bind-keymap the prefix for the keymap
    • :mode (REGEXP . MODE)
    • :init run now
    • :config run when the package loads
    • :custom (CUSTOM_VAR VAL "optional documentation")* customize package custom variables
    • :requires does not load the package unless the requirement is fulfilled.
    • Keywords — use-package for more
  • use-package-autoload-keymap bind a keymap

5.4. Initialization

5.4.1. Early Init

  • By default ~/.emacs.d/early-init.el is the early init file, and it runs before any of the packages load and the window is set up.
  • (setenv "VAR" "VALUE") set the environment variable
  • (setq native-comp-deferred-compilation nil) prevent native compilation

5.4.2. Init

  • ~/.emacs is used traditionally, but ~/.config/emacs/init.el and ~/.emacs.d/init.el can be used.
  • initial-scratch-message
  • inhibit-startup-screen
  • initial-buffer-choice sets the file as a startup buffer
  • emacs-startup-hook or window-setup-hook can also be hooked to any function
  • There's package called dashboard that modifies the startup screen into displaying recent files, org agendas, bookmarks and more.
  • default-frame-alist sets the properties for any frames.
    • The implicit default might not be applied to initial-buffer-choice. This option can be used in that case to set the properties explicitly.
  • See Startup Summary (GNU Emacs Lisp Reference Manual)

5.5. Theme

  • the emacs default themes are stored in /usr/share/emacs/NN.N/etc/themes/
  • The default directory for user themes is ~/.emacs.d/
  • Theme can be selected from customize-themes, or load-theme using lisp.
  • Emacs Themes Lookup

5.6. Input Method

Emacs has its own multilingual support. It translates the Latin characters into specified language.

  • default-input-method it specify the input method used when C-\ (toggle-input-method) is called.
    • korean-hangul, japanese
    • latin-prefix
    • german-postfix
      • It allows sz ß, ae ä, ue ü, oe ö.
    • compose
      • X like compose functionality!
      • C-x 8 works similarly, though much more limited

See Input Methods (GNU Emacs Manual)

  • set-input-method select a new input method
  • C-x \ (activate-transient-input-method) insert a single character
  • C-h C-\ (describe-input-method)

5.7. Keybinding

  • define-key the low level function
  • global-set-key, local-set-key legacy interactive key definition
    • It expects the KEY to be a key description (kbd "...") or [...]
  • keymap-set, keymap-global-set, keymap-local-set keymap definition
    • It expects the KEY to pass key-valid-p test
  • bind-key the external function a bind-key package

5.8. Font

  • (set-fontset-font FONTSET CHARACTERS FONT-SPEC &optional FRAME ADD)
    • It does not work on server startup. It should be hooks to a server-after-make-frame-hook
    • Manipulate a fontset, with FONTSET being t meaning the fontset-default.
    • CHARACTERS specify on which set of characters the fonts is applied.
      • script-representative-chars and char-script-table contains the symbols for known scripts.
    • FONT-SPEC specifies which font to use for the given set of characters.
    • ADD can be either nil, 'prepend or 'append in terms of the precedence list
  • set-frame-font and set-face-attribute can also be used.
  • (font-spec SPECS)
    • :name, :family, :size, and others can be specified
  • (font . FONTNAME) is also seen
  • C-x = show the character at point in the minibuffer.
  • C-u C-x = show details about the character and font being used at point.

See Font Selection (GNU Emacs Lisp Reference Manual), Fonts (GNU Emacs Manual), Modifying Fontsets (GNU Emacs Manual)

6. Packages

  • Packages are managed by the built-in package package.
    • (package-initialize) needs to run first to be able to use require. It is run automatically before .emacs since Eamcs 27.
    • But it doesn't seems like it runs package-refresh-contents also.
  • Add MELPA repository by modifying package-archives with M-x customize-option
  • package-vc-install REPO-DESC can be used to install from the source.
    • REPO-DESC can be the repository url, or a list that describe the package: '(org :url URL).
  • (package-delete PKG-DESC FORCE NOSAVE)
    • PKG-DESC is stored in the pkg-alist, which then can be extracted with cdr of assoc.

6.1. LaTeX

6.1.1. AUCTeX

  • auctex, auctex-latexmk, auctex-lua
  • Set TeX-engine to XeTeX or LuaTeX for ttf fonts.
  • <C-c> <C-c> run command
  • <C-c> <C-v> view pdf
  • <C-c> <C-p> <C-b> preview buffer
  • prettify-symbols-mode display symbols inline
  • cdlatex-mode quick input of LaTeX
  • outline-mode the contraction of sections

See LaTeX Input for Impatient Scholars | Karthinks

6.1.2. CDLaTeX

LaTeX input method

  • TAB
    • ali, ali*, equ, fg, fr, sq, beg, …
    • M-x cdlatex-command-help shows the full list
  • ` symbols
  • ' styling
  • ^, _ superscript and subscript

6.1.3. RefTeX

It is Emacs builtin, that recognizes the multi-file bibliography. It is used by CDLaTeX when inserting citation.

  • reftex-parse-all
    • It is run when a file is first opened.
    • It needs to be manually run for the changes to be recognized.
  • C-c [, (reftex-citation) insert citation from the bib database file specified in \addbibresource{} and the default bib database.
  • C-c ), (reftex-reference) add reference among the current file.

6.2. elpy

  • No longer an active project. Replace with language servers.

Emacs Python development environment

It sets up a virtual environment for each projects in the background and communicate through RPC. The virtual environment is installed in .emacs.d/elpy/rpc-venv/ by default.

It completes using company.

  • elpy-rpc-reinstall-virtualenv solved the sentinel error.

6.2.1. Features

  • Run (elpy-enable) to enable all the modules.
  • <M-TAB> elpy-company-backend provide completion suggestions at point

See Elpy — Elpy 1.35.0 documentation

6.2.2. Related

  • python: python interpreter
  • jedi: It autocompletes the python script. It also uses virtual environment and communicate through RPC via epc.
    • company-jedi and jedi are the frontends of jedi-core for company and auto-completion respectively.
    • jedi:install-server to first set the virtual environment up.
    • jedi:get-in-function-call displays the function signature at the minibuffer. jedi:show-doc is also there.
  • flymake and flycheck is available for Python.
  • Python - WikEmacs

6.3. lsp-mode

LSP Mode - Language Server Protocol support for Emacs - LSP Mode - LSP suppor…

It supports all kinds of languages and their servers. The servers are external programs that needs to be installed separately.

  • lsp-ui provides the sideline, childframe, and others.

6.3.1. Language Servers

  • ccls C/C++/Objective C
    • Faster than clangd
    • Additional ccls package required
  • clangd C++
    • Builtin
  • python-lsp-server
    • Builtin
  • pyright
    • Additional lsp-pyright required
    • The successor of Microsoft Python server
  • (lsp-register-client CLIENT) is used to register a language server for a certain mode or file extension.
    • Many are registered by default. But an obscure one has to be registered manually.
  • (make-lsp-client ...) is used to create the CLIENT object of the type lsp--client.
    • :new-connection CONNECTION run and connect to the language server.
    • :major-modes MODE set the major mode in which language server starts.
    • :server-id ID ID can be anything of the form 'id.

6.3.2. dap-mode

Debug Adapter Protocol

DAP Mode

6.4. Eglot   builtin

  • Builtin language server protocol client
  • It is more barebone compared to LSP mode.

6.5. ein

Emacs IPython Notebook

  • ein:run ein:stop to start and stop the jupyter notebook server.
  • C-c C-c Evaluate current cell.
  • C-c C-b, C-c C-a Add a cell below or above

6.5.1. Related

  • jupyter It controls the Jupyter server.

6.6. eimp

Emacs Image Manipulation Package

It enables simple image processing within Emacs.

6.7. pdf-tools

It replaces the builtin doc-view for the case of PDF files, with almost the same keybidings.

  • pdf-tools-install on startup to enable it on startup.
  • n, p next, previous page, C-n, C-p next, previous line or page, SPC scroll
  • +, -, 0 enlarge, shrink, reset scale, H, W, P fit height, width, page
  • m mark to a register, ' jump to register
  • o show outline
    • TAB toggle children, RET follow link, C-o, SPC display link
    • a show all sublevel, Q hide all sublevel
    • s, d show, hide subtree
    • f, b forward, backward same level, u up heading
    • o return to the pdf, q quit
    • Outline mode also works
  • F link action perform
  • l or B, r or N history backward, forward
  • GitHub - vedang/pdf-tools: Emacs support library for PDF files.

6.8. corfu

Newer and lighter completion system.

It utilizes the emacs completion system, compared to company's own system.

6.9. Evil

Vi emulation

  • It is customizable under Editing > Emulations > Evil
  • Viper is the default Vi emulation, but it is more primitive with less keybindings and less commands.
    • No q macro, no :register and :jumps, ci or ca.
  • It is required to (require 'evil) from the .emacs to properly set it up. Custom does not properly enable evil-mode
  • The initial evil mode for a major mode can be customized by the state mode variables or evil-set-initial-state function in the init file.

6.9.1. Keybindings

  • ? in the middle of key sequence to show helps
6.9.1.1. <N> Normal Mode
  • W, B move a WORD, which means space separated words.
  • WORD, word, line, paragraph and others are collectively known as text objects.
  • L bottom of the screen, H top of the screen
  • u undo, C-r redo
  • g f find file at point, g x open immediately
  • g q fill region (automatically add line breaks)
    • g q q fill line
  • J join the next line at the end of the current line.
  • = auto indent, >, < indent and outdent, S start a line with auto indent
  • ~ toggle case of a character
    • g ~ toggle case of a region given by the motion, g ~ ~ toggle case of a line.
  • i select in, a select around:
    • b, (, ) parenthesis
    • B, {, } brace
    • t tag
    • p paragraph
  • / regexp can be used in the query
    • \< \> match exact word
    • * search word at point
    • c g n change next match
      • This requires the evil-search-module to be evil-search.
  • m mark current position, ' goto the marked line, ` goto the marked position
    • The marks are added to the jumplist.
  • Jumplist
    • Show with :jumps
    • C-SPC creates the jump point as well
  • [ ', ]' previous and next mark line, [`, ]` previous and next mark
  • [(, ]) previous open and next close paranthesis, [{, ]} previous open and next close brace
  • [[, ]] backward section begin and forward section end, [], ][ backward section end and forward section begin
  • [s, ]s previous and next flyspell error
  • ! shell command, !! shell command again on the same region (:.!)
  • z scroll
    • b this line to the bottom, t this line to the top, z this line to the center, + bottom line to top, ^ top line to bottom
    • l scroll right, h scroll left.
  • z fold
    • c close one, m close all, o open one, r open all, O open subtree, a toggle
  • C-y scroll down a line, C-e scroll up a line.
  • g d go to definition
  • Q (Vim only) enter ex (ed extended) mode
  • Z
    • Q quit without saving
    • Z save and quit
6.9.1.2. <V> Visual Mode
  • v visual mode, V visual line mode <Vl>, C-v visual block mode <Vb>
  • Line based commands such as I, A can be entered after a region is selected.
  • g v select the previous selected region in visual mode
  • o to select in the other direction
  • '<,'> indicates a line in a selected region.
  • ! can be called on the region, using it as the standard input.
6.9.1.3. <O> command argument
  • most of the motion keys still words
  • z, Z the two character evil-sniper
6.9.1.4. <I> Insert Mode
  • C-r insert from a register
    • = put the result of simple calculator
  • C-w delete a word backward, C-h delete a character
  • C-o run a normal mode command
  • C-p, C-n complete from previous or next text
  • C-x Completion mode (only in Vim)
    • C-] tag completion from the ctags
    • C-f file completion
    • C-p, C-n context-aware local completion from previous or next text
    • C-l context-aware line completion
    • complete variable is used to determine where to look for completion
  • C-v insert special characters, such as control characters.
6.9.1.5. <M> motion mode
  • It allows the other program to temporarily override the keybindings.
  • But some are reserved
    • hjkltfwb<C-f><C-b><C-u><C-d><RET>{}()=movement, =/?nN search, 123... numbers, v visual mode
    • <C-]> visit the tag under the cursor
    • [] ?
6.9.1.6. <E> Emacs Mode
  • Every keybindings are removed except <C-z> which toggles the Emacs mode.
  • It can be escaped from the other modes by using the escape character \. \ is one-time, <C-z> is persistent.
  • Numbers are bound to simply <C-u> [123...]
    • Emacs provide <ESC> 1 and <M-1> to function the same.
6.9.1.7. " Registers
  • " the last deleted, yanked, or secondary system copied
  • . the last manual insert
  • + secondary system clipboard
  • * primary system clipboard (highlighted text)
  • - last deleted text
    • it is also stored in "
  • : the last vim command
  • % current filename
  • = simple calculator
  • 0 last yanked text
  • 19 stores the last nine (non-unique) entires that was stored in " , with the latest unique one being 1.

6.9.2. Commands

  • Address insert
    • /REGEX/ select a line containing the regex.
  • norm[al] escape to normal mode programmatically
  • m[ove]±N
  • ab[brev] create an auto-expanding abbreviation.

6.9.3. External Keybindings

  • Info Page
    • p n previous/next node
    • u up
    • d the directory node
    • s regexp search
    • m menu in current node
    • i search in the index of current node. Leave empty to show all
  • Buffer Menu
    • Entered by <M-x> buffer-menu or <C-x> <C-b>
    • <RET> f select the buffer in place
      • o open in another window, <C-o> and not focus
      • 1 select in full-frame window
      • 2 select it as one window of the two-window frame
    • d s u flag for deletion/saving, remove flags(unmark)
      • x perform the deletion and saving as flagged
      • U remove all flags from all lines
      • m mark to be displayed in another window, v opens them at once with the current
      • . the flag is for the previous buffer that opened buffer menu
    • ~ mark as unmodified
    • % toggle read-only
    • q quit
  • (add-hook 'evil-local-mode-hook 'turn-on-undo-tree-mode)

6.9.4. Plugins

6.9.4.1. evil-numbers
  • it enables the C-a C-x inline number manipulation in Vim.
  • evil-numbers/inc-at-pt, evil-numbers/dec-at-pt is provided.
6.9.4.2. evil-surround
  • cs<old delimiter><new delimiter>, ds<old delimiter>, ys<motion><new delimiter> to surround.
  • S<new delimiter> in visual mode.
  • t can represent a HTML tag as a delimiter.
  • Open delimiters for spaced delimiter, and close delimiter for tight delimiter.

evil-embrace for custom surrounding pairs.

6.9.4.3. evil-leader
  • evil-leader/set-leader, evil-leader/set-key to customize
  • The global-evil-leader-mode needs to be enabled before evil-mode.
6.9.4.4. evil-snipe
  • evil-snipe-override-mode override f, t so that it highlights
  • evil-snipe-mode add 2-character search s and x
    • It is z and x (exclusive) in the operator state, the small cursor state that waits for the motion.
6.9.4.5. evil-tex
6.9.4.6. evil-org
  • gh, gj, gk, gl navigate between elements
  • vae select and element, vaR select a subtree
  • M-RET insert heading, TAB, g TAB fold/unfold
  • M-h, << promote a heading
  • M-l, >> demote a heading
  • M-S-h, M-S-l, <aR, >aR, M-k, M-j move subtree
  • (, ), previous, next table cell, {, } beginning, end of table
  • vae select a cell, vaE select row, var select table
  • GitHub - Somelauw/evil-org-mode: Supplemental evil-mode keybindings to emacs …
6.9.4.7. evil-fringe-mode

Display the markers in the fringe.

6.10. Magit

6.11. Autotype

  • abbrev.el: Abbreviation expansion, builtin
  • expand.el: Abbreviation expansion, builtin
  • skeleton.el: Lisp syntax for templates, builtin
  • tempo.el: Lisp syntax for templates, builtin
  • skempo.el:
  • srecode.el: CEDET template manager and code generator, builtin
  • aas.el: Auto activating snippets
  • cdlatex.el: Fast LaTeX insertion
  • laas.el: Latex auto activating snippets
  • muban.el: Lightweight template expansion
  • placeholder.el: Treat buffers as templates
  • tempo-abbrev.el: Abbrev integration for Tempo
  • snippet.el: Original snippet mode, with inline expansion (from EmacsWiki?)
  • tempo-snippets.el: Interface like snippet.el for Tempo
  • yasnippet.el: Template system inspired by Textmate snippets
  • templatel.el: Jinja2 subset
  • amno1/lite:
  • tempel: Template package which uses the syntax of the Emacs Tempo library.

6.11.1. Abbrev   builtin

Eamcs builtin

6.11.2. Skeleton

Emacs builtin

6.11.3. Yasnippet

Yet Another Snippet

  • yas-snippet-dir specifies the location of the snippets, with ~/.emacs.d/snippets/ being the user snippets.
    • Snippets in a directory named with a specific mode is only activated in that mode.
    • The directories are shadowed by others.
  • C-c & C-n to define a new snippet
  • C-c & C-s to insert snippet
  • LaTeX snippets with Yasnippet & Auto Activating Snippets - YouTube useful?
6.11.3.1. Snippet Format
  • $0 the final point position.
  • $1, …, $9 the tab-stoppable fields
    • {$n:DEFAULT_VALUE} set default
    • $n mirror: Use the same number again to mirror the field.
      • {$n:$(LISP(yas-text))} mirror with transformation: the value of the field n which is represented by yas-text is transformed with Lisp expression.
    • {$n:DEFAULT_VALUE$(LISP(yas-text))} field with transformation: the inserted value is automatically transformed with given Lisp expression.
      • {$n:$$(LISP(yas-text))} is used when there's no default value.
  • `LISP` is run as soon as the snippet is expanded, and the result is inserted.
  • Yet another snippet extension
6.11.3.2. yasnippet-snippets

yasnippet-snippets and other packages contain the snippets in yasnippet-snippets-dir for yasnippet to use.

6.12. Completion

6.12.1. Frontend

They provide the completion candidates through completing-read-function

6.12.1.1. Icomplete   builtin

Suggest the completion inline within minibuffer.

6.12.1.2. Ido   builtin

Interactive do

Suggest the completion inline within minibuffer.

6.12.1.3. Ivy

It shows the completion candidates in the minibuffer vertically, similar to Vertico.

6.12.2. company

It is newer compared to auto-completion.

Top Company User Manual

  • Modular architecture
  • <C-g> to stop suggestion.
6.12.2.1. Modules
  • company-jedi, company-auctex, company-bibtex, company-lua
6.12.2.2. Configuration
  • company-minimum-prefix-length=(Option): The length of string to activate the completion. default to =3.
  • company-idle-delay=(Option): The reaction time. default to =0.3?
  • company-frontends (Option): The UI part
    • Default to (company-pseudo-tooltip-unless-just-one-frontend company-echo-metadata-frontend company-preview-if-just-one-frontend) (List of Functions)
      • Use (setq VAR '(LIST)) to set it
    • tooltip: inline popup
      • (setq company-format-margin-function #'{company-dot-icons-margin|company-text-icons-margin|company-vscode-{light|dark}-margin})
        • #' is used to quote a function.
        • company-vscode-{light|dark}-margin (Function) uses the VSCode icons in the graphical interface only, showing nothing in the terminal interface.
    • preview: The inline suggestion
    • echo: Mini buffer suggestion
  • company-backends (Option): The completion part
    • (company-bbdb company-semantic company-cmake company-capf company-clang company-files (company-dabbrev-code company-gtags company-etags company-keywords) company-oddmuse company-dabbrev)
  • company-global-modes (Option): Major modes in which company modes is enabled by global-company-mode (Command).

6.13. Interface

6.13.1. Consult

Simple navigation system, that integrates the native functionalities.

  • consult-buffer it is multi-sourced search
  • consult-outline search through the headings
    • consult-org-heading
  • consult-line narrowing lines
  • consult-imenu search through flattened imenu. It lists the identifiers in prog-mode.
  • consult-grep
    • #TEXT#FILTER TEXT the TEXT is searched if the file includes FILTER TEXT.

6.13.2. Embark

The minibuffer action within Consult

  • C-. in minibuffer
    • k kill buffer

6.13.3. Orderless

Additional completion-style

  • The default completion starts looking from the start, or from the middle if it starts with a special characters. But this style allows find in the middle

6.13.4. helm

Incremental narrowing for basically everything.

Prefix C-x c

  • M-x (helm-M-x) the fancy M-x. It is rebound to M-x
  • / (helm-find) find the entire file system with find
  • f (helm-multi-files) search files and buffers at the same time
  • a (helm-apropos) find any command, function, variable, or face
  • i (helm-imenu) menu: search outlines in org
  • l (helm-locate) use locate command to find files.
  • m (helm-man-woman) search through man pages.
  • o (helm-outline) show the outline
  • C-x C-f (helm-find-files)
  • C-x C-b (helm-buffers-list)
  • C-c f (helm-recentf) the recentf-open is remapped to helm-mode-recentf-open in helm-mode
  • C-c g (helm-google-suggest) search on Google

See Helm | Emacs incremental completion and selection narrowing framework

Navigation system

6.13.5. Counsel

Interface similar to Consult that uses Ivy

6.13.6. Swiper

The search functionality with preview similar to Consult, using Ivy completion.

6.13.7. Vertico

It displays the completion under the minibuffer vertically.

  • PGTK might not work with Vertico, where the input events drops and vertico does not update.
  • vertico-indexed-mode
    • Enable the C-u N RET to select the N th entry.

6.13.8. Marginalia

It displays description or type of the item beside the minibuffer entry.

6.13.9. Casual

It uses transient to show the menu(tmenu).

casual-calc is opened with <C-o>

6.13.10. which-key

Show the list of available keybindings

6.13.11. Treemacs

  • treemacs-mode added to aw-ignored-buffers by default.
    • Set aw-ignore-on to nil to disable this behavior.
  • P peek mode that previews the documents.
  • d delete a file, c copy a file, m move a file, R rename a file, Q kill buffer
  • o open
    • c and close treemacs, o no split, h, =v in splitted window, x external application
    • a a with ace window selection, a h, a v with ace windoe split
  • c create
    • d directory, f file
  • M-h move up or collapse, M-l same as RET
  • M-m bulk operation

Treemacs has workspaces which can contain multiple projects. Project can be a plain directory or a version controlled directory.

  • M-L, M-H change the project root directory.
  • C-c C-w Workspace Prefix
    • a create, d remove, s switch, e edit the ~/.emacs.d/.cache/treemacs-persist directly.
    • f set fallback workspace (the default)
  • C-c C-p Project Prefix
    • a add, d remove, r rename
  • Related: dired-subtree and dired-sidebar, dirtree, neotree, sidebar. Among which dired-sidebar seems promising.

6.13.12. Hydra

6.14. Project

6.14.1. project   builtin

Emacs builtin It recognizes version controlled folders and EDE projects.

6.14.2. Projectile

Project is a folder containing specific file.

  • VCS marker
  • pom.xml, Gemfile
  • It can be extended

6.15. Music

6.15.1. emms

Emacs Multimedia System

The add function and browser window is for Emacs exclusively. It tells the player through various backends within emms-player-list, one of which is emms-player-mpd.

  • emms-player-mpd-connect needs to be called first.
  • For the case of mpd the songs has to be within the mpd database, making new songs unable to play, unless the database is updated separately, either through mpc update or emms-player-mpd-update.
  • emms-player-spotify can be installed separately, which controls the local spotify app.
  • emms-all enables various features.

See The Emms Manual, mpd

6.15.1.1. Related

6.15.2. spotify

It controls the local Spotify app through D-Bus

6.15.3. smudge

Control Spotify using App API. It provides more complete functionalities.

Prefix C-c .

  • M-p play/pause
  • M-b, M-f previous and next track
  • M-s, M-r shuffle and repeat control
  • p playlist
    • f featured, m my, s search, c create
  • t track
    • r recent, s search
  • v volume
    • u, d, m up and down and mute
  • d device
  • Buffer
    • M-RET play now
    • k add to the queue
    • g reload
  • global-smudge-remote-mode enables the mode line

See GitHub - danielfm/smudge: Control the Spotify app from within Emacs.

6.16. Window

6.16.1. windmove   builtin

  • S-<arrow> change focus to different window

6.16.2. ace-window

  • M-o (ace-window)
    • m swap, M move (the buffer is rotated), x delete, j select new buffer for, n previous window
    • v vertical split, b horizontal split, o maximize
    • ? help
  • aw-dispatch-when-more-than variable prevents the ace window when less than 2 windows by default.
  • ace-window-display-mode display the window number in the mode line.

6.16.3. popper

  • Manage window by classifying them into regular, popup windows

6.16.4. transpose-frame

;; `transpose-frame'  ...  Swap x-direction and y-direction
;;
;;        +------------+------------+      +----------------+--------+     
;;        |            |     B      |      |        A       |        |     
;;        |     A      +------------+      |                |        |     
;;        |            |     C      |  =>  +--------+-------+   D    |     
;;        +------------+------------+      |   B    |   C   |        |     
;;        |            D            |      |        |       |        |     
;;        +-------------------------+      +--------+-------+--------+     
;;     
;; `flip-frame'  ...  Flip vertically     
;;     
;;        +------------+------------+      +------------+------------+     
;;        |            |     B      |      |            D            |     
;;        |     A      +------------+      +------------+------------+     
;;        |            |     C      |  =>  |            |     C      |     
;;        +------------+------------+      |     A      +------------+     
;;        |            D            |      |            |     B      |     
;;        +-------------------------+      +------------+------------+     
;;     
;; `flop-frame'  ...  Flop horizontally     
;;     
;;        +------------+------------+      +------------+------------+     
;;        |            |     B      |      |     B      |            |     
;;        |     A      +------------+      +------------+     A      |     
;;        |            |     C      |  =>  |     C      |            |     
;;        +------------+------------+      +------------+------------+     
;;        |            D            |      |            D            |     
;;        +-------------------------+      +-------------------------+     
;;     
;; `rotate-frame'  ...  Rotate 180 degrees     
;;     
;;        +------------+------------+      +-------------------------+     
;;        |            |     B      |      |            D            |     
;;        |     A      +------------+      +------------+------------+     
;;        |            |     C      |  =>  |     C      |            |     
;;        +------------+------------+      +------------+     A      |     
;;        |            D            |      |     B      |            |     
;;        +-------------------------+      +------------+------------+     
;;     
;; `rotate-frame-clockwise'  ...  Rotate 90 degrees clockwise     
;;     
;;        +------------+------------+      +-------+-----------------+     
;;        |            |     B      |      |       |        A        |     
;;        |     A      +------------+      |       |                 |     
;;        |            |     C      |  =>  |   D   +--------+--------+     
;;        +------------+------------+      |       |   B    |   C    |     
;;        |            D            |      |       |        |        |     
;;        +-------------------------+      +-------+--------+--------+     
;;     
;; `rotate-frame-anticlockwise'  ...  Rotate 90 degrees anti-clockwise     
;;     
;;        +------------+------------+      +--------+--------+-------+     
;;        |            |     B      |      |   B    |   C    |       |     
;;        |     A      +------------+      |        |        |       |     
;;        |            |     C      |  =>  +--------+--------+   D   |     
;;        +------------+------------+      |        A        |       |     
;;        |            D            |      |                 |       |     
;;        +-------------------------+      +-----------------+-------+     
;;

6.17. undo-tree

  • <C-/> <C-_>: undo
  • <C-?> <M-_>: redo
  • undo-tree-switch-branch
  • <C-x> u undo-tree-visualizer

6.18. multiple-cursors

6.19. Iedit

  • C-; during isearch enters the Iedit mode in which all the occurences are modified simultaneously.
    • M-I to restrict to current line
    • M-{ and M-} to expand the region

6.20. keycast

Provide keycast-mode-line-mode, keycast-tab-bar-mode, keycast-header-line-mode which shows the keypresses.

6.21. diminish

Hide the mode indicator for a minor mode

6.22. TRAMP   builtin

Transparent Remote Access, Multiple Protocol

Edit remote files transparently.

  • Use /ssh:SPEC:PATH in the find-file (C-x C-f).
  • These filepaths can be used within the shell as well.
  • See TRAMP 2.7.1 User Manual

6.23. gtag

Use GNU global for indexing.

Other tag system includes ctags, etags

6.24. Anki

6.24.1. anki-editor

  • anki-editor-mode the commands are available when this mode is enabled.
    • anki-editor-push-notes to sync all the notes

6.24.2. org-anki

  • org-anki it is does almost the same thing as anki-editor

6.25. Mail

6.25.2. org-mime

  • org-mime-htmlize formats the Org mail into HTML.

6.25.3. gnus

Feature rich email, Unet, and RSS client

The method to generate the feed is specified in gnus-select-method. Additional sources can be added in gnus-secondary-select-methods.

The articles (mails) are displayed in a specified format. The default is %U%R%z%I%(%[%4L: %-23,23f%]%) %s\n, where

6.25.3.1. Keybindings
  • DEL or S-SPC previous page, < beginning, > end SPC next page, N and P next/previous article, n and p next/previous unread article
  • g show article, h go to article buffer, s search within the article
  • TAB open a mail
  • d, D mark as read and move forward/backward
  • o save article, C-o save article mail
  • ! tick forward, @ mark article
  • k kill, C-k kill same subject
  • c catchup and exit
  • r reply, f followup, m mail in new buffer
  • | shell command on article buffer
  • t toggle the full mail header
  • Group Mode
    • c catchup current
    • g get new news
  • Article Mode
    • C-d next keyword, TAB next link
    • s or h go to summary buffer

6.25.4. Others

  • rmail
  • mu4e easy to use email client
  • mutt dated client
  • notmuch minimal client
    • Either offlineimap or mbsync is required to fetch emails.
  • ebdb stores and provides the contact information through autocompletion.

6.26. shr   builtin

Simple builtin HTML renderer

  • shr-render-buffer, shr-render-region

7. CLI

  • emacs
    • --debug-init run debug on init files
    • -t, --terminal use TUI
    • -f, --funcall execute Lisp function
    • -l, --load Load Lisp code file
    • --eval, --execute Evaluate Lisp expression
    • -batch, --batch run noninteractively within the terminal
  • emacsclient
    • -t terminal session
    • --alternative= use specified Eamcs server, when no server is specified and no server running new server is created.
    • --create-frame

8. Distributions

8.1. Emacs Prelude

Enhanced Emacs with ace-window, magit, avy, crux, and other packages preinstalled.

8.2. Doom Emacs

One can choose whether to use Evil or not. It uses <space> in Evil mode and C-c if not.

Various components are available as packages.

  • doom-modeline
  • doom-thems

8.3. Spacemacs

It uses <space> as the leader key, and use mnemonic keybindings.

9. Help

  • <C-h> ... for helps
    • ?, <C-h> show options
    • <C-q> quick help for basic macros
    • b current key bindings
      • k c key (briefly)
    • m current mode
    • a commands for <M-x>
    • d documentation
    • f, v, o function, variables, both
      • kill-ring is also a variable
    • r Emacs manual
      • F K for command or key sequence
      • i all installed manual, info
      • R specific manual
    • P Package description
  • C-h can be entered in the middle of prefix. It shows the available keybindings.

The default value for the help message the text at point.

10. Emacs Lisp

Elisp, .el

  • "TAB" is ^I and "<tab>" is tab key.
  • It is byte complied into .elc file

10.1. Object

10.1.1. Symbol

Symbol is an object that represent a variable or function. quote or ' wraps the variable as a symbol. It consists of four parts: name, value, function value, property list. They can be accessed with symbol-name, symbol-value, symbol-function, symbol-plist respectively.

  • fset sets the function value of the variable. It can be set to a raw function or a symbol as a indirection.
  • `(... ,a ...) backquote can be used to evaluate only certain part of expression.

Dynamically bound functions expands the scope when it is not bound locally, but lexically bound variable does not.

  • defvar makes the variable dynamically bound.
  • Lexical binding is preferred these days.
  • boundp checks if a symbol is bound to a value or void.
  • setf like setq but operates on any cell and variables.
  • (let ((var val), ...) (statement)) it binds local variable, dynamically on dynamic variable, lexically on free variable.
    • let* defines them sequencially
  • (defun name (arguments) "optional documentation" (interactive optional-argument-passing-info) (body))
    • Function that is defined interactively with (interactive OPTION) is a command which can be bound
  • (setq var val var val ...)
    • The variable is bound to the value.
    • The q is for quoted, which means the var does not need to be quoted
  • (defvar var val "optional documentation")
    • It marks the variable as special, so that it is always dynamically bound.
    • The variable is not overrode, and setq can change the value, it is seen globally
    • It allows doc string.
  • (defcustom var val "documentation" :type TYPE) it specify a variable that customize can control
  • (define-minor-mode MODE :init-value nil :lighter INDICATOR :global nil BODY)
  • (provide 'PACKAGE) specified in the end of the package file.

10.1.2. Type

  • String "abc" , Vector [a b c] are array
  • Cons Cell
    • It consists of two parts car and cdr, that can contain value or reference. CAR and CDR - Wikipedia
    • cons or . form a cons cell out of two values.
    • list is a series of cons cell that reference the next cons cell and ends in nil
  • There are various types of data, such as #<buffer>, #<marker>, #<frame>. These are only represented in the printed representation, and not to be defined in this way.
  • The value can be a closure and it can be called with funcall
    • #' can be used to explicitly tell it to use the function value.

10.1.3. Macro and Special Form

  • defmacro defines a macro that interprets expression differently, that it may not evaluate the expression.
  • Special form is similar to macro and it is often the language feature.
  • (progn EXPRESSIONS) evaluate the expressions in order

10.2. Functions

  • List
    • A list is a series of nodes (CAR CDR) -> (CAR CDR) -> ...
    • cdr can also be used to store value instead of the pointer to the next node, with (cons VAR1 VAR2) or equivalently (VAR1 . VAR2).
    • The reader reads the list and evaluate it if it is not quoted with (quote LIST) or equivalently 'LIST
  • (append LIST1 LIST2) produces the new concatenated list
  • String
    • (concat STR1 STR2) concatenate into one string
    • (format FORMAT_STR VAR)
  • Point
    • (point) return current point position
    • (goto-char NUM) move point to the position NUM
    • (forward-char &optional NUM), (backward-char &optional NUM) move point
    • (beginning-of-buffer), (end-of-buffer) move point
    • Common motion command, such as (forward-word), (forward-sentence) are also available.
    • (point-min), (point-max) return possible point position while taking narrowing into account
    • (save-excursion ...) save the point position, and allow point motions to be contained within the scope
  • Buffer
    • Get/Set Buffer
      • (current-buffer) get the current buffe
      • (get-buffer BUFFER-OR-NAME) get buffer by name
      • (get-file-buffer FILENAME) get buffer by file path
      • (get-buffer-create BUFFER-OR-NAME) get buffer while creating it when it does not exists.
      • (set-buffer BUFFER-OR-NAME) set current buffer to BUFFER
      • (with-current-buffer BUF ...) set the current buffer within the scope
      • (with-temp-buffer "CONTENT" ...) create a temporary buffer with given content
    • Buffer File
      • (buffer-file-name) the file path of the current buffer. It is nil if not applicable.
      • (find-file-noselect FILENAME) => BUF open a file into a buffer without displaying it
    • Buffer Text
      • (char-after NUM) return the character at the position
      • (thing-at-point THING &optional NO-PROPERTIES) the THING can be 'word, 'sentence, 'url and others
      • (search-forward STRING &optional BOUND NOERROR COUNT), (search-backward STRING) move the point after/before the (first) match
      • (buffer-substring START END) return string at the given range within current buffer
        • (buffer-substring-no-properties START END)
      • (insert STR) insert at point
      • (insert-file-contents-literally PATH)
      • (delete-region START END) delete the text within
  • Command
    • (this-command) return the object that represent the last executed command
  • External Command
    • (shell-command COMMAND)
      • xdg-open can be used to open a file externally.
  • Hook
    • (run-hook-with-args-until-success HOOK &rest ARGS) runs hooks sequenctially until one of them returns t.

10.3. Flow Control

10.4. Byte Compilation

  • A lisp file from a package is byte compiled on installation. It needs to be recompiled via package-recompile to load the code.

10.5. Utilities

  • (message "message" optional-format-vars) print message to the echo area
    • %s, %d can be used to format the string
  • -p is for predicate, and -q is for quoted.

10.6. History

The original Lisp came about in 1960 by John McCarthy. It diverged into several dialect in 1970s and unified with Common Lisp in 1980s. The ANSI standard was also established in 1990s.

It was a niche programming language among industry and academia and soon got outnumbered by other languages due to its low performance and lact of libraries. Java at work, Python at academia replaced them.

The Rise & Fall of LISP - Too Good For The Rest Of the World - YouTube

11. History

Editor descended from all the way to the 1970s

  • Theming mechanism was added in version 24

12. External Links

13. Reference

Created: 2025-06-21 Sat 20:45