Skip to content

Instantly share code, notes, and snippets.

@jf-parent
Last active August 9, 2018 16:22
Show Gist options
  • Save jf-parent/42a95b60349bf1d7780a4ffd5b8c7baa to your computer and use it in GitHub Desktop.
Save jf-parent/42a95b60349bf1d7780a4ffd5b8c7baa to your computer and use it in GitHub Desktop.
Lisp and Emacs orgmode's Notes

To Sort

SLIME

Ansi Common LISP [chapter 4]

orgmode refiling

orgmode clock in clock out

Redmine

Asana

Kanban

Latex

line completion

python ide

Code completion

Code repl

live coding

Snippet

“SPC i s” => List all current yasnippets for inserting

pytest

superword mode

Migrate old journal into new journal

org mode

org-capture

org-archive

org-agenda

org-journal

org-wiki

org-timer => graph

Archive

For convenience a shortcut key called the major mode leader key is set by default on ​,​ which saves one precious keystroke.

Disable line too long warning

clipboard buffer => Kill ring <space> r y

Term copy and paste // character-mode vs line-mode

C-c C-v

Articles

Resources

Sacha Chua

lisp / elisp

M-x ielm

Elisp is usually compiled into a byte-code saved to .elc files, and that byte-code loads and runs faster than uncompiled Elisp.

People do not write byte-code; that job is left to the byte compiler. But we provide a disassembler to satisfy a cat-like curiosity.

The byte-code interpreter is a simple stack machine.

The stack holds arbitrary lisp objects.

The interpreter is backwards compatible but not forwards compatible (old versions can’t run new byte-code).

Each instruction is between 1 and 3 bytes.

The first byte is the opcode and the second and third bytes are either a single operand or a single intermediate value. Some operands are packed into the opcode byte.

As of this writing (Emacs 24.3) there are 142 opcodes, 6 of which have been declared obsolete. Most opcodes refer to commonly used built-in functions for fast access.

Byte-code does not offer the same safety as normal Elisp. Bad byte-code can, and will, cause Emacs to crash.

The quote, by definition, prevents evaluation, and so inhibits byte compilation of the lambda expression. It’s vital that the byte compiler does not try to guess the programmer’s intent and compile the expression anyway, since that would interfere with lists that just so happen to look like lambda expressions — i.e. any list containing the lambda symbol.

it’s a special vector object that contains byte-code, and other metadata, for evaluation by Emacs’ virtual stack machine. Elisp is one of very few languages with readable function objects, and this feature is core to its ahead-of-time byte compilation.

The #[…] is the syntax for a byte-code function object.

Byte-compiled functions are significantly faster. That’s the main purpose for byte compilation after all.

The compiler performs static checks, producing warnings and errors ahead of time. This lets you spot certain classes of problems before they occur. The static analysis is even better under lexical scope due to its tighter semantics.

Under lexical scope, byte-compiled closures may use less memory. More specifically, they won’t accidentally keep objects alive longer than necessary. I’ve never seen a name for this implementation issue, but I call it overcapturing.

While it’s common for personal configurations to skip byte compilation, Elisp should still generally be written as if it were going to be byte compiled. General rule of thumb: Ensure your lambda expressions are actually evaluated.

SLIME

alt-n / alt-p history navigation

SLIME is started with the Emacs command M-x slime. This uses the inferior-lisp package to start a Lisp process, loads and starts the Lisp-side server (known as “Swank”), and establishes a socket connection between Emacs and Lisp. Finally a REPL buffer is created where you can enter Lisp expressions for evaluation.

Funny

Emacs stands for “Escape Meta Alt Control Shift.”

Emacs is a great operating system, but it lacks a good editor; like Vi

Tips

One of the most important modifications you should make to your environment is rebinding your caps lock key to control. You’re going to use the control key a lotand to avoid the Emacs pinky I suggest you unbind your right control entirely and instead use caps lock.

C-h l

view-lossage “Woah, what key chord did I just do?”

Shows you the literal sequence of keys you’ve pressed in order.

Evil

In emacs, the word “mode” is already taken, so evil refers to vim’s modes as “states” (e.g. “normal state”).

A hook is similar to autocmd in vim.

In emacs, commands are functions that can be bound to a key (interactive) or run with M-x (<a-x>). Most commands can also be run from evil’s ex command line with :command-name<cr>.

C-g is bound to keyboard-quit (or an equivalent) by default. You use it, for example, to exit the minibuffer (e.g. if you type M-: which is bound to eval-expression and want to exit). You can replace C-g with <escape> for most cases (see Using Escape to Exit the Minibuffer), but it is still useful to know about it. If emacs freezes from a long-running command or infinite loop, you can use C-g to cancel it.

C-h is a prefix key for getting help. Since emacs has a different help system, :help will not work the same as in vim. If you want to find out about a variable, you can use C-h v (describe-variable). To find out what a key is bound to, you can use C-h k to pop open a help buffer with information about the command. For example, you can find out that C-h k is bound to describe-key by pressing C-h k C-h k. Knowing about C-h k can be useful, for example, if you want to find out what a nested key is bound to. By “nested key”, I mean that you can type d C-h k i w (d<c-h>kiw) to find out that iw here is bound to evil-inner-word.

Navigation

Go up to next paragraph (whitepace line)   {
Go down to next paragraph (whitepace line)   }
Go to previous function   [[
Go to next function   ]]
Go up to outer brace   [{
Go down to outer brace   ]}

Nomenclature

In Emacs, the keys and the terminology differ greatly: killing is cutting; yanking is pasting; and copying is awkwardly known as saving to the kill ring (or just copy, informally.) The reasons, as before, are historical. Most of the keys and terminology stem from IBM’s Common User Access6 (CUA) and Apple. But the CUA was introduced in 1987, many years after Emacs had settled on its own terminology and standards.

Font Locking is the correct term for syntax highlighting in Emacs, and in turn is made up of faces of properties (color, font, text size, and so on) that the font locking engines use to pretty-print the text.

Frame: a graphical window or terminal screen occupied by Emacs

ch shows two dashes (‘–’) if the buffer displayed in the window has the same contents as the corresponding file on the disk; i.e., if the buffer is “unmodified”. If the buffer is modified, it shows two stars (‘**’). For a read-only buffer, it shows ‘%*’ if the buffer is modified, and ‘%%’ otherwise.

modeline => status bar

M-x (pronounced mex, M x, or meta x.)

Minibuffer

The universal argument is also known by its key binding C-u.

there’s a special command called self-insert-command that, when invoked, will insert the last typed key.

s-expression (or just sexp.)

The cryptic name deserves an explanation: it’s a lisp term that covers a wide range of commands that operate on balanced expressions.

Buffer

[space][space] rename-buffer

Completion

Folding

Redmine

ESS

modes

ido-mode

To enable it, type M-x ido-mode and then try C-x b or C-x C-f again.

You can enable it permanently by customizing the option ido-mode: M-x customize-option RET ido-mode RET

You can also improve ’s fuzzy matching by enabling flex matching: M-x customize-option RET ido-enable-flex-matching RET

Spelling checking (flyspell)

Calc

Remote

Shell / Term

IDE

Commands

Word

M-x subword-mode Minor mode that treats CamelCase as distinct words M-x superword-mode Minor mode that treats snake_case as one word

Customize:

code M-x Customize M-x customize-themes /code

Rectangle

Documentation

code M-x info C-h i M-x apropos-command /code

Packages

Repo

[[http://melpa.milkbox.net/][Melpa] (Milkypostman’s Emacs Lisp Package Archive]]

code M-x package-list-packages /code

Notables

Navigations

F10 Activates the menu bar

C-x C-f Find (open) a file

C-x C-s Save the buffer

C-x b Switch buffer

C-x k Kill (close) a buffer

C-x C-b Display all open buffers

ESC ESC ESC Exits out of prompts, regions, prefix arguments and returns to just one window

C-/ Undo changes

to end the Emacs session, type C-x C-c

To quit a partially entered command, type C-g

C-v (View next screen) to move to the next screen

To move backwards one screen, type M-v

C-l Clear screen and redisplay all the text, moving the text around the cursor to the center of the screen

Previous line, C-p

Backward, C-b

Forward, C-f

Next line, C-n

M-f moves forward a word

M-b moves back a word

C-a and C-e move to the beginning or end of a line, and M-a and M-e move to the beginning or end of a sentence.

M-< (META Less-than), which moves to the beginning of the whole text, and M-> (META Greater-than), which moves to the end of the whole text

The easiest way to specify a numeric argument is to type a digit and/or a minus sign while holding down the META key. For example, M-5 C-n moves down five lines.

C-u 8 C-f moves forward eight characters

Eval Elisp

code M-x eval-buffer will evaluate the entire buffer you’re in. M-x eval-region evaluates just the region that you have marked. /code

Special commands

C-q followed by any non-graphic character (even C-g) inserts that character. For instance, C-q DEL inserts a literal ‘DEL’ character.

The command C-x z (repeat) provides another way to repeat an Emacs command many times.

Text manipulation commands

C-d Delete the character after point (delete-char).

C-k Kill to the end of the line (kill-line).

M-d Kill forward to the end of the next word (kill-word).

M-DEL Kill back to the beginning of the previous word (backward-kill-word).

C-u alone has the special meaning of “four times”: it multiplies the argument for the next command by four. C-u C-u multiplies it by sixteen. Thus, C-u C-u C-f moves forward sixteen characters. Other useful combinations are C-u C-n, C-u C-u C-n (move down a good fraction of a screen), C-u C-u C-o (make “a lot” of blank lines), and C-u C-k (kill four lines).

Inserting line

C-o Insert a blank line after the cursor (open-line).

C-x C-o Delete all but one of many consecutive blank lines (delete-blank-lines).

Undo

C-underscore

C-/

C-x u

Cutting text (killing text)

C-k #this will kill the current line

Copying text (killing text without deleting it)

Search

C-s #forward search

C-r #backward search

Find and Replace

Esc-%

Type the search text

Type the replace text

Press ‘space’ to replace it or ‘n’ to skip it and go to the next one. Press ‘!’ to replace all queries.

Blogging

External / Internal Link

Literate programming

<c-enter> add a bullet under at the same level

It’s activated with M-SPC in a org-agenda buffer , as Spacemacs conventions recommend.

Weekly entries: <space> a j s (search for **)

Code block

insert with ‘<s [tab]’

Org-Wiki

SPC a o w a | Insert asset link | SPC a o w d | Open asset directory for current page | SPC a o w h | Go to home page | SPC a o w i | Insert page link | SPC a o w j | Jump to page (if helm enabled) | SPC a o w n | Create new page |

Layout / Workspace

Plugins / Layers

Javascript

Magit

Javascript

Spacemacs

In vim you have various editing modes like insert mode and visual mode to manipulate text. In Emacs, we have states. These are equivalent to vim modes. For example, evil-insert-state is the same as insert-mode in vim.

A minor-mode in Emacs is like a feature that is activated. For example, aggressive-indent-mode is a minor-mode that automatically indents code as you type. It is important to know that there can be many minor-modes activated in a buffer. Many Emacs packages work by providing a minor-mode. A major-mode determines the editing behavior of Emacs in the current buffer. There is generally a corresponding major-mode per filetype. An example of a major-mode is python-mode, which provides python specific settings in python files. There is only one major-mode per buffer.

Spacemacs has the concept of layers. Layers are similar to vim plugins. They provide new features to use in Spacemacs. However, layers are often comprised of several packages that integrate well with each other. For example, the python layer includes support for auto-completion, documentation look-up, tests, and much more by using several different packages. This keeps you from thinking about what packages to install, and instead worry about what features you want.

Smartparens

[space] t p (to disable smartparens)

Tools

Resources

Articles

Book

Implementation

MACLISP

Interlisp

ANSI Common Lisp

Scheme

Guile Scheme

Script-Fu Scheme

CLISP

Allegro Common Lisp, a powerful commercial Lisp by Franz, Inc

LispWorks

Clozure CL

CMUCL

Interesting

Style

Concept

Generic setters

The Common Lisp language is said to support generic setters. This means that in most cases, the code for pulling a value out of a data structure (whether an array, list, string, or something else) is identical to the code for putting data into that same data structure. The setf command can be used in conjunction with functions that perform getting operations and can use the same functions to perform setting operations, instead.

When we are writing code without side-effects, there is no point in defining functions with bodies of more than one expression. The value of the last expression is returned as the value of the function, but the values of any preceding expressions are thrown away. If such expressions didn’t have side- effects, you would have no way of telling whether Lisp bothered to evaluate them at all.

nullary functions

a function without arguments is commonly called a thunk or a suspension.

Keyword symbol

:foo

Sequence functions

The sequence functions work generically across the three main ways of sequencing objects in Lisp: lists, arrays, and strings.

One particularly useful generic sequence function is reduce.

Macros

Anaphoric macros

CLOS

Common Lisp’s Common Lisp Object System (CLOS) allows you to build very sophisticated object-based systems. If you care to code with a strongly object-oriented mindset, you will probably find all the OOP language functionality you need in Common Lisp. Indeed, CLOS has many advanced object-oriented features that you won’t find in many other places. Because of this, CLOS has often been used as a research tool for studying OOP ideas.

Type dispatching

the Common Lisp command defmethod lets us define multiple versions of a function that each supports different types. When that function is called, Lisp checks the argument types at the time of the call and chooses the correct version of the function automatically.

(defmethod add ((a number) (b number))
  (+ a b))
(defmethod add ((a list) (b list))
  (append a b))
(add 3 4)
(add '(a b) '(c d))

File I/O

;; Write
(with-open-file (my-stream "data.txt" :direction :output)
      (print "my data" my-stream))
;; Read
(with-open-file (my-stream "data.txt" :direction :input)
     (read my-stream))
;; Error file already exists
(with-open-file (my-stream "data.txt" :direction :output :if-exists :error)
      (print "my data" my-stream))
;; Overwrite
(with-open-file (my-stream "data.txt" :direction :output
                                         :if-exists :supersede)
      (print "my data" my-stream))

String I/O

(defparameter foo (make-string-output-stream))
(princ "This will go into foo. " foo)
(princ "This will also go into foo. " foo)
(get-output-stream-string foo)
(with-output-to-string (*standard-output*)
      (princ "the sum of ")
       (princ 5)
       (princ " and ")
       (princ 2)
       (princ " is ")
(princ (+ 2 5)))

Error / Exception - Signaling a condition

(error "foo")
(define-condition foo () ()
(:report (lambda (condition stream)
                (princ "Stop FOOing around, numbskull!" stream))))
(error 'foo)
(handler-case (bad-function)
      (foo () "somebody signaled foo!")
       (bar () "somebody signaled bar!"))
(unwind-protect (/ 1 0)
(princ "I need to say 'flubyduby' matter what"))

Function

mapcar

mapc is a slightly more efficient variant of mapcar; the difference is that it does not return the transformed list.

Remember that mapc is just like mapcar, except that you use it in places where you care only about the side effects and don’t care about generating a final list as a result.

(mapcar #’(lambda (x) (+ x 10)) ‘(1 2 3))

(mapcar #’list ‘(a b c) ‘(1 2 3 4))

subseq

(subseq "america" 2 6)

array

;Create array
(defparameter x (make-array 3))
;Get item from array
(aref x 1)
;Set item into array
(setf (aref x 1) 'foo)
(make-array 5 :initial-contents '(1 2 3 4 5))

hash table

(defparameter x (make-hash-table))
(gethash 'yup x)
(setf (gethash 'yup x) '25)

format

;string
(format t "I am printing ˜s in the middle of this sentence." "foo")
(format t "I am printing ˜a in the middle of this sentence." "foo")
;decimal
(format t "Numbers with commas in them are ˜:d times better." 1000000)
(format t "I am printing ˜10,'xd within ten spaces of room" 1000000)
;float
(format t "PI can be estimated as ˜4f" 3.141593)
;currency
(format t "I wish I had ˜$ dollars in my bank account." 1000000.2)
;table
(defun random-animal ()
      (nth (random 5) '("dog" "tick" "tiger" "walrus" "kangaroo")))
(loop repeat 10
        do (format t "˜5t˜a ˜15t˜a ˜25t˜a˜%"
                   (random-animal)
                   (random-animal)
                   (random-animal)))
; explanation https://drive.google.com/file/d/1_CAE1ZtuYjGVBgwW7fS_gpF5LL6afvxD/view?usp=drivesdk
(loop repeat 10
        do (format t "˜30<˜a˜;˜a˜;˜a˜>˜%"
                   (random-animal)
                   (random-animal)
                   (random-animal)))
(format t "|˜{˜<|˜%|˜,33:;˜2d ˜>˜}|" (loop for x below 100 collect x))
; looping
(defparameter *animals* (loop repeat 10 collect (random-animal)))
(format t "˜{I see a ˜a! ˜}" *animals*)

terpri / freshline

terpri, simply tells Lisp to terminate the current line and start a new one for printing subsequent output.

the terpri command says “start a new line,” whereas the fresh-line command says “start a new line, if needed.

˜% causes a new line to be created in all cases (like terpri)

˜& creates new lines only as needed (like fresh-line).

(progn (princ 22)
         (terpri)
         (princ 33))
(progn (princ 22)
         (fresh-line)
         (fresh-line)
         (princ 33))
(progn (format t "this is on one line ˜%")
           (format t "˜%this is on another line"))
(progn (format t "this is on one line ˜&")
           (format t "˜&this is on another line"))
(format t "this will print ˜5%on two lines spread far apart")

maplist

(maplist #’(lambda (x) x) ‘(a b c))

setf

In fact, the first argument in setf is a special sublanguage of Common Lisp, called a generalized reference.

values

(defun foo ()
     (values 3 7))
(multiple-value-bind (a b) (foo)
(* a b))

subseq

(subseq ‘(a b c d) 1 2)

(subseq ‘(a b c d) 1)

reverse

(reverse ‘(a b c))

function

sharp-quote: #’

Predicate functions

zerop

numberp

alphanumericp

arrayp

characterp

consp

functionp

hash-table-p

listp

stringp

and symbolp

reduce

(reduce #'+ '(3 4 6 5 2))
(reduce (lambda (best item)
  (if (and (evenp item) (> item best))
    item
    best))
  '(7 4 6 5 2)
  :initial-value 0)

copy-list

takes a list and returns a copy of it

every / some

(every #’oddp ‘( 1 3 5))

(some #’evenp ‘(1 2 3))

(every #’> ‘(1 3 5) ‘(0 2 4))

append

sort

(sort ‘(0 2 138) #’>)

You have to be careful when using sort, because it’s destructive. For efficiency reasons, sort is allowed to modify the sequence given to it as an argument. So if you don’t want your original sequence modified, pass a copy.

maplist

member

(member '(a) '((a) (z)) :test #'equal)
(member 'a ((a b) (ed)) :key #'car)
(member-if #'oddp '(2 3 4))

adjoin

(adjoin 'b '(a b c))
(adjoin 'z '(a b c))

union, set-difference, intersection

(set-difference '(a b c d e) '(be))
(intersection '(a b c) '(b b c))
(union '(a b c) '(c b s))

nth, nthcdr

Common Lisp defines f i r s t through t e n t h as functions that retrieve the corresponding element of a list. These functions are not zero-indexed: (second x) is equivalent to (nth 1 x).

substitute-if

find-if

(find-if #'numberp '(a b 5 d))

count

(count #\s "mississippi")

position

(position #\4 "2kewl4skewl")

let / let*

let* command allows us to reference previously defined variables

remove-if-not

nil

Note that nil is both an atom and a list.

intersection

The intersection function tells us which items are shared between two lists.

complement

apply

(apply #’+ 1 2 ‘(3 4 5))

(funcall #’+ 1 2 3)

equality

eql returns true only if its arguments are the same object.

equal returns true if both list contains the same elements.

Lambda

The lambda in a lambda expression is not an operator. It is just a symbol.

In earlier dialects of Lisp it had a purpose: functions were represented internally as lists, and the only way to tell a function from an ordinary list was to check if the first element was the symbol lambda.

In Common Lisp, you can express functions as lists, but they are repre- sented internally as distinct function objects. So lambda is no longer really necessary. There would be no inconsistency in requiring that functions be denoted as

((x) (+ x 100)) instead of (lambda (x) (+ x 100))

but Lisp programmers were used to beginning functions with the symbol lambda, so Common Lisp retained it for the sake of tradition.

((lambda (x) (+ x 100)) 1)

(funcall #’(lambda (x) (+ x 100)) 1)

iteration

loop

(loop repeat 10
  collect 1)
(loop for n from 1 to 10
  collect n)
(loop for n from 1 to 10
  collect (+ 100 n))
(loop for i
  below 5
  sum i)
(loop for i
  in '(100 20 3)
  sum i)
(loop for i
  below 5
  do (print i))
(loop for i
  below 10
  when (oddp i)
  sum i)
(loop for i
  from 0
  do (print i)
  when (= i 5)
  return 'falafel)
(loop for i
  in '(2 3 4 5 6)
  collect (* i i))
(loop for x below 10
  for y below 10
  collect (+ x y))
(loop for x below 10
  collect (loop for y below 10
  collect (+ x y)))

do

(defun show-squares ( start end) (do ((i start (+ i 1)))
((> i end) 'done)
(format t "~A ~A ~%" i (* i i))))
(show-squares 2 5)

dolist

(setq temp-two '()) =>  NIL
 (dolist (temp-one '(1 2 3 4) temp-two) (push temp-one temp-two)) =>  (4 3 2 1)

dotime

(dotimes (i 3)
  (princ i)
  (princ ". Hatchoo!"))

(gensym) => The gensym function will create a unique variable name for you that is guaranteed never to clash with any other variable name in your code.

History

John McCarthy and his students began work on the first Lisp implementation in 1958.

After FORTRAN, Lisp is the oldest language still in use.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment