Pablo Murad something new again, and me again

Emacs beyond the basics II: first steps in Emacs Lisp

Emacs beyond the basics II: first steps in Emacs Lisp

2026-11-09, originally published on pablomurad.com.

← all Pablo Murad texts

The first Emacs guide on this blog ended by pointing at a manual called "An Introduction to Programming in Emacs Lisp", which is how people go from using Emacs to bending it. This post is the friendly version of that step. No computer science background needed. Anyone who can copy a line into an init.el can do everything here.

The goal is small and practical. By the end, reading Lisp stops being scary, and writing commands, giving them keys, hooking them into modes and digging into any function Emacs has all become possible. That's most of what people ever do with Elisp.

Why bother #

Every key pressed in Emacs runs a function written in Emacs Lisp. The config is Lisp. The installed packages are Lisp. With a little reading ability, three things change:

Where to try things #

No file is needed to experiment. Emacs has three playgrounds.

The *scratch* buffer opens with Emacs, in a mode made for this. Type an expression, put the cursor right after it and press C-j. The result gets printed on the next line.

M-: asks for an expression in the minibuffer, runs it and shows the result at the bottom of the screen. It works from any buffer, which makes it great for quick questions like "what's the value of this variable right now?".

C-x C-e runs the expression right before the cursor, in any Lisp file. This is the one that gets the most use in init.el: change a line, put the cursor after it, C-x C-e, and the change is live without restarting.

And for a proper REPL, M-x ielm opens one, with a prompt and history.

Reading Lisp #

Lisp looks scary because of the parentheses, but the rule is simple. A list in parentheses is a call: the first thing is the function, the rest are its arguments.

(+ 1 2) ; => 3
(* 2 (+ 3 4)) ; => 14
(concat "Hello, " "Emacs") ; => "Hello, Emacs"
(upcase "hello") ; => "HELLO"

The inner parentheses run first, so (* 2 (+ 3 4)) becomes (* 2 7), which becomes 14. That's the whole grammar. Everything else is vocabulary.

A semicolon starts a comment. Strings go in double quotes. t means true, and nil means false and also "empty list". Those two show up everywhere.

Sometimes a list is data, not a call. That's what the quote is for:

'(+ 1 2) ; => (+ 1 2), just a list with three things in it
(+ 1 2) ; => 3
(car '(apples pears plums)) ; => apples, the first item
(cdr '(apples pears plums)) ; => (pears plums), the rest

The same quote is why config files are full of things like 'modus-vivendi or #'display-line-numbers-mode. The ' says "this name, as it is". The #' is the same idea for names of functions, and it helps Emacs warn about a misspelled one.

A note about indentation: Lisp doesn't care about it. The blocks of code in this post are written flat, and Emacs indents them properly. Paste the code, select it and press TAB, or use C-M-\.

Variables #

setq sets a variable. let creates variables that only exist inside its parentheses:

(setq my-name "Pablo")

(let ((x 10)
(y 32))
(+ x y)) ; => 42, and x and y vanish after this

format builds a string with placeholders, %s for anything and %d for whole numbers:

(format "Hi, %s! You have %d buffers open." my-name (length (buffer-list)))

For settings that Emacs or a package offers as options (the ones listed in M-x customize), Emacs 29 added setopt. It works like setq, but it also runs any code the option needs when it changes, and it warns when the value has the wrong type:

(setopt fill-column 80)

A simple habit: setopt for options, setq for everything else.

A first command #

A function is made with defun. Give it a name, a list of arguments, a short description and a body. Add (interactive) and it becomes a command, something to run with M-x or bind to a key.

(defun my-insert-date ()
"Insert today's date at point, like 2026-11-06."
(interactive)
(insert (format-time-string "%Y-%m-%d")))

Put the cursor after the last parenthesis and press C-x C-e. Now M-x my-insert-date works. And because it has a description, C-h f my-insert-date shows it, just like any built-in command.

Two habits worth having from day one. First, start function names with a prefix, like my-, so they never clash with something Emacs or a package already uses. Second, always write the description. Future you will read it.

Giving it a key #

Emacs 29 added a clean way to bind keys:

(keymap-global-set "C-c d" #'my-insert-date)

Now C-c d inserts the date anywhere. The choice of C-c and a letter is on purpose. Emacs keeps every C-c followed by a plain letter for the user. Neither Emacs nor well-behaved packages will ever take those keys, so they're the safe place for personal commands.

A key can also be bound inside one mode only, using that mode's keymap:

(with-eval-after-load 'org
(keymap-set org-mode-map "C-c n" #'my-new-note))

with-eval-after-load waits until Org is actually loaded before touching its keymap. Without it, Emacs would complain that org-mode-map doesn't exist yet. The my-new-note command comes in a minute.

Asking the user for something #

interactive can do more than mark a function as a command. Give it a code and Emacs will ask the user for the arguments. "s" asks for a string:

(defun my-greet (name)
"Say hello to NAME."
(interactive "sYour name: ")
(message "Hello, %s!" name))

Run M-x my-greet and Emacs prompts "Your name:" in the minibuffer. Other codes ask for a number ("n"), a file ("f"), a buffer ("b") and more. C-h f interactive lists them all.

Working with text #

Inside a buffer, the cursor position is called the point, and a few functions do most of the work:

One more is worth learning early: save-excursion. It runs some code and then puts the cursor back where it was, so the command doesn't leave the user lost in the file.

(defun my-add-todo-on-top ()
"Insert a TODO line at the top of the buffer, without moving the cursor."
(interactive)
(save-excursion
(goto-char (point-min))
(insert "TODO: review this file\n")))

Making decisions and repeating things #

if takes a condition, what to do when it's true and what to do when it isn't. when and unless are shortcuts for when only one side matters. cond is a chain of options, checked from top to bottom:

(let ((n 7))
(cond ((< n 5) "small")
((< n 10) "medium")
(t "big"))) ; => "medium"

The t at the end works as "otherwise", since t is always true.

dolist walks through a list. This one goes over every open buffer and reports which files have unsaved changes:

(defun my-list-unsaved ()
"Show which file buffers have unsaved changes."
(interactive)
(dolist (b (buffer-list))
(when (and (buffer-file-name b) (buffer-modified-p b))
(message "Unsaved: %s" (buffer-name b)))))

The messages pile up in the *Messages* buffer, which opens with C-h e.

A real command: quick notes #

Time to put it all together. This command asks for a title, turns it into a clean file name and opens a new Org note in the notes folder, already with a title and the date.

(defvar my-notes-directory "~/notes"
"Where `my-new-note' keeps its files.")

(defun my-slugify (title)
"Turn TITLE into a lowercase, dash-separated slug."
(let* ((s (downcase title))
(s (replace-regexp-in-string "[^a-z0-9]+" "-" s)))
(string-trim s "-" "-")))

(defun my-new-note (title)
"Create a new Org note called TITLE in `my-notes-directory'."
(interactive "sNote title: ")
(let* ((date (format-time-string "%Y-%m-%d"))
(file (expand-file-name
(concat date "-" (my-slugify title) ".org")
my-notes-directory)))
(make-directory my-notes-directory t)
(find-file file)
(when (= (buffer-size) 0)
(insert "#+title: " title "\n"
"#+date: " date "\n\n"))))

(keymap-global-set "C-c n" #'my-new-note)

Press C-c n, type "Ideas for the weekend", and the new file is 2026-11-06-ideas-for-the-weekend.org, with the title and the date at the top. If the file already exists, it just opens, without writing the header twice.

A few new pieces showed up here:

Read it slowly, change something, run it again. That loop is how Elisp gets learned.

Hooks: run code when something happens #

A hook is a list of functions that Emacs runs at a specific moment. Every mode has one, named after the mode with -hook at the end. This is how to say "every time I open a text file, do this":

(add-hook 'text-mode-hook #'visual-line-mode)
(add-hook 'prog-mode-hook #'display-line-numbers-mode)

The first line wraps long lines nicely in text files. The second turns on line numbers in any programming mode, since all of them build on prog-mode.

For more than one function call, use a lambda, which is a function without a name:

(add-hook 'prog-mode-hook
(lambda ()
(setq-local fill-column 100)
(electric-pair-local-mode 1)))

setq-local changes the variable only in that buffer, so Python files can have one width and notes another.

There are hooks for almost everything: before-save-hook, after-save-hook, kill-emacs-hook, emacs-startup-hook. C-h v and the word "hook" show the list.

Advice: changing someone else's command #

Sometimes a built-in command needs to do one extra thing. Advice attaches a function before, after or around it:

(defun my-announce-save (&rest _)
"Tell me which buffer was just saved."
(message "Saved %s" (buffer-name)))

(advice-add 'save-buffer :after #'my-announce-save)

Now every save shows a little message. To undo it, advice-remove with the same arguments.

Advice is powerful, and that's exactly why it deserves care. Reach for a hook first. If there isn't one, then advice is fine, but keep each piece small and give it a clear name, because advice is invisible to anyone reading the original command's code.

Reading Emacs's own code #

This is where the investment pays off. C-h f describes any function, and the description has a link to the file where it's defined. One click opens the real source. C-h k does the same for a key: press C-h k and then C-x C-s, follow the link, and there's how Emacs saves a file.

Three other help commands that pair well with Elisp:

Not everything makes sense at first. That's fine. Skim, look for familiar parts, and every week more of it becomes familiar.

When things break #

Errors in Elisp are normal, and Emacs has good tools for them.

M-x toggle-debug-on-error makes Emacs open a backtrace whenever an error happens. It looks dense, but the top lines usually point straight at the function that failed.

For personal functions, there's Edebug. Put the cursor inside a defun and press C-u C-M-x. The next time the function runs, Emacs stops at the first step and walks through it with SPC, one expression at a time, showing each value as it goes. q exits.

If the init.el breaks so badly that Emacs starts in a strange state, remember emacs -Q, which starts without any config. Open the file, fix it, restart. And emacs --debug-init starts with the config and opens the backtrace at the first error, which usually points to the exact line.

Finally, M-x checkdoc reviews the descriptions in a file and points out small style problems. It's a good teacher.

Organizing init.el #

With a few functions in place, tidiness matters. Two simple rules go a long way.

Group things by topic, with a comment on top of each group, and keep personal functions together in one section. Use ;;; for section titles. Emacs even understands them: M-x outline-minor-mode folds the file by those headings.

And let use-package do the bookkeeping for packages and built-in features alike. It's built into Emacs since version 29:

(use-package org
:hook (org-mode . visual-line-mode)
:bind ("C-c a" . org-agenda)
:config
(setq org-log-done 'time))

:hook adds hooks, :bind sets keys and :config runs code after the package loads. It's the same Lisp from above, organized into labeled boxes.

Where to go next #

Inside Emacs, C-h i opens the manuals. Look for "An Introduction to Programming in Emacs Lisp", written for people who have never programmed. It's long, gentle and full of small exercises. For the details, the "Emacs Lisp Reference Manual" sits right next to it. Both are also online at gnu.org/software/emacs/manual.

A good next exercise: pick something done by hand at least twice a week, and turn it into a command. Inserting a template, opening a set of files, cleaning up a pasted text. Small commands shaped around daily habits are where Elisp starts to feel personal.

This is part II of a series. Part I is about living inside Emacs: feeds, gopher, the fediverse, chat and mail. Part III turns Emacs into a full programming setup.

Original: https://pablomurad.com/emacs-beyond-the-basics-part-2/