Category Archives: emacs

On this page:

Upgrading from Rails 3 to Rails 4; thank goodness for Emacs and rspec

I spent some time working on upgrading Quantified Awesome from Rails 3 to Rails 4. I was so glad that I had invested the time into writing enough RSpec and Cucumber tests to cover all the code, since that flushed out a lot of the differences between versions: deprecated methods, strong parameters, and so on.

rspec-mode was really helpful while testing upgrade-related changes. I quickly got into the habit of using C-c , m (rspec-verify-matching) to run the spec file related to the current file. If I needed to test specific things, I headed over to the spec file and used C-c , s (rspec-verify-single). Because RSpec had also changed a little bit, I needed to change the way rspec-verify-single worked.

(defun sacha/rspec-verify-single ()
  "Runs the specified example at the point of the current buffer."
  (interactive)
  (rspec-run-single-file
   (concat
     (rspec-spec-file-for (buffer-file-name))
     ":"
     (save-restriction
               (widen)
               (number-to-string (line-number-at-pos))))
   (rspec-core-options)))

(sacha/package-install 'rspec-mode)
(use-package rspec-mode
  :config
  (progn
    (setq rspec-command-options "--fail-fast --color")
    (fset 'rspec-verify-single 'sacha/rspec-verify-single)))

C-c , c (rspec-verify-continue) was also a handy function, especially with an .rspec containing the --color --fail-fast options. rspec-verify-continue starts from the current test and runs other tests following it, so you don’t have to re-run the tests that worked until you’re ready for everything.

I should probably get back to setting up Guard so that the tests are automatically re-run whenever I save files, but this is a good start. Also, yay, I’m back to all the tests working!

Test coverage didn’t mean I could avoid all the problems, though. I hadn’t properly frozen the versions in my Gemfile or checked the asset pipeline. When I deployed to my webserver, I ran into problems with incompatible changes between Rails 4.0 and 4.1, and Bootstrap 2 and Bootstrap 3. Whoops! Now I’m trying to figure out how to get formtastic-bootstrap to play nicely with Bootstrap 3 and Rails 4 and the latest Formtastic… There are some git repositories that claim to do this correctly, but they don’t seem to work.

Grr.

Fine, I’ll switch to simple_form, since that seems to be sort of okay with Bootstrap 3. I ended up using this simple_form_bootstrap3 initializer along with

# You can wrap a collection of radio/check boxes in a pre-defined tag, defaulting to none.
config.collection_wrapper_tag = :div

# You can define the class to use on all collection wrappers. Defaulting to none.
config.collection_wrapper_class = 'collection'

and this in my style.css.sass:

.form-horizontal
  .control-group
    @extend .form-group
  .control-label
    @extend .col-sm-2
  .control-group > .form-control, .form-group > .form-control, .form-group > .collection
    @extend .col-sm-10
  .help-block
    @extend .col-sm-offset-2
  .control-label.boolean
    text-align: left
    font-weight: normal
    @extend .col-sm-offset-2
  label.radio
    font-weight: normal

which is totally a hack, but it sort-of-semi-works for now.

More changes to come, since I’ve got to get it sorted out for Rails 4.1 too! Mrph.

Read Lisp, Tweak Emacs (Beginner 4/4): “How can I add more features? How do I deal with errors?”

This entry is part 4 of 4 in the series Read Lisp, Tweak Emacs

Previous module: “How can I make things more convenient?”

Some conventions we’ll use:

  • Inline code will be boxed and monospace in the HTML version and generally surrounded by equal signs in plain text.
  • Code samples will be monospace and in boxes in the HTML version, and enclosed in #+begin_src#+end_src in plain text. Example:
    (message "Hello world")
    

After this module, you’ll be able to:

  • load libraries so that you can add new features or set configuration variables
  • install and configure packages in order to add more features to your Emacs
  • understand and fix common errors
  • learn more! =)

Adding more features to Emacs

Most Emacs libraries are not loaded automatically. This saves memory and keeps things simpler. Some of the customizations you may want to make require that other parts of Emacs are loaded first. For example, if you want to define a key for the c-mode-map (used for editing C code) or add a function to org-mode-hook (called when a buffer is set up with Org Mode), those libraries need to be loaded first. You can load libraries by using require, like this:

(require 'org)

This loads the org library. require looks for a file named after the name provided to it, loads it, and double-checks that the library includes (provide 'feature-name-goes-here). It signals a Cannot open load file error if the library is not found. If the library exists but does not provide that symbol, you’ll get a Required feature FEATURE was not provided error instead.

Note that the symbol you give to require might not be the same as the function you call. For example, c-mode is actually defined in the cc-mode library, while org-mode is defined in org. To find out what file a function is defined in, use C-h f (describe-function) followed by the name of the function. The first line will tell you what file the function is defined in, if any. For example, c-mode‘s definition starts with:

c-mode is an interactive autoloaded compiled Lisp function in
`cc-mode.el'.

The first part of the filename (before the .el or .elc) is usually what you would use with require. If you have the source installed (the .el file), you can look for the (provide ...) expression to find the actual symbol to use.

Installing packages

Emacs comes with a lot of code, but there are even more packages out there. When you read other people’s Emacs configurations, you might come across other interesting packages to try out.

Sometimes people don’t indicate which packages they use, so you have to guess the package name based on the function. For example, (global-auto-complete-mode) turns on a completion mode called auto-complete-mode in all buffers. Before you can use this, you will need to install the auto-complete package. In general, you can find package names by looking at functions that include mode in their name, removing global, turn-on, and other prefixes as needed.

The default package repository in Emacs 24 has a limited number of packages. For more choices, you may want to add another repository such as MELPA or Marmalade Here’s the code that you would run in order to add these repositories to your Emacs:

(require 'package)
(add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/"))
(add-to-list 'package-archives '("marmalade" . "http://marmalade-repo.org/packages/"))

Note that MELPA includes many packages under active development. If you prefer to install only the packages marked as stable, replace the MELPA line with this:

(add-to-list 'package-archives '("melpa-stable" . "http://hiddencameras.milkbox.net/packages/"))

If you’re connected to the Internet, use M-x package-refresh-contents to update the list of packages. Use M-x package-list-packages to list the available packages. RET displays the package’s description. i marks the current package for installation, and x actually performs the operations. If you know the name of the package you want to install, you can skip the list and use M-x package-install instead.

A lightweight list of the key functions defined by packages is loaded after your init.el is run. You can start that initialization earlier by adding (package-initialize), which is useful if you want to call functions that are defined in packages.

Sometimes people want to install some packages on one computer but not on another. Here’s some code that runs some configuration if the miniedit package can be loaded, but silently continues if the package has not been installed.

(when (require 'miniedit nil t)
   (miniedit-install)
   (define-key minibuffer-local-map (kbd "C-c e") 'miniedit))

If you use C-h f (describe-function) on require, you’ll see that it has one required argument (feature) and two optional arguments (filename, noerror). require returns non-nil (or true) if the library was loaded, so if the library exists, then the rest of the code inside the when expression gets called.

Along those lines, you may come across code that looks like this:

(eval-after-load "dash" 
  '(dash-enable-font-lock))

This runs (dash-enable-font-lock) only after dash is loaded. It does not automatically load dash. You’ll see this when people have configuration that they want to run only if something is loaded, which can make sense for performance reasons. When you’re starting out, you may want to use require instead of eval-after-load, since the argument to eval-after-load has to be quoted.

Other Emacs Lisp files

Some files are not yet available as packages. If you search for the function, you’ll probably find a webpage with an .el file. You can save those to your computer and load them with:

(load "/path/to/file")

You can also use this technique to split up your Emacs configuration file into smaller files. For example, you might have an org-config.el file, a programming-config.el file, and so forth. If you would like to load a host-specific file only if it exists, you can take advantage of the optional NOERROR argument for load like this:

(load (concat "~/.emacs.d/" (system-name) ".el") t)

Want to find out what that filename is? Position your cursor after the ​".el") and use C-x C-e (eval-last-sexp) to see the value in the buffer.

Use C-h f (describe-function) to learn more about the load function, including other arguments you can pass to it.

If you would like to use the require syntax to load files only if they haven’t already been loaded, you can do that as long as they include the (provide ...) expression somewhere. First, you’ll need to add your downloaded Emacs Lisp file to the load-path with something like this.

(add-to-list 'load-path "/path/to/dir/with/el/files")

Then you can use require to load the Emacs Lisp code if it exists.

(require 'feature-name)

“Oh no! I have an error!”

Part of learning Emacs is having the confidence to experiment, which you can develop by learning how to recognize and deal with different errors.

If you’ve already added the code to your ~/.emacs.d/init.el, you can start Emacs with emacs --debug-init to display debugging messages, or you can start Emacs with emacs -q to skip your personal configuration. Before reporting a bug with Emacs or with a package, use emacs -q (or emacs -Q, which skips site-wide configuration as well) to see if it works as intended without your personal configuration.

To make it easier to find errors while Emacs is running, use M-x toggle-debug-on-error, then do whatever you did to trigger the error. You will probably see a detailed list of functions called in the *Messages* buffer. If you find this useful, you can enable this by default in your ~/.emacs.d/init.el. Add:

(setq debug-on-error t)

If you have code that takes a while, you might find the debug-on-quit variable or the M-x toggle-debug-on-quit function useful as well. You can quit a long-running operation by using C-g (keyboard-quit).

You can narrow down the source of the problem by progressively commenting out more and more of the code. Make sure you comment out balanced sets of parentheses. To comment a region, select it and use M-x comment-region. You can use M-x uncomment-region to uncomment it. M-x comment-dwim (do what I mean) guesses whether you want to comment or uncomment something, and has the handy keyboard shortcut M-;.

Here are some common error messages and how you can try fixing them. If you don’t see the error you’re struggling with here, ask the relevant mailing list, help-gnu-emacs, the #emacs channel on irc.freenode.net, or StackOverflow for help. Good luck!

Scan error: “Unbalanced parentheses” or “Containing expression ends prematurely”

You may have pasted in something that has a “(” but no matching “)“, which results in unbalanced parentheses. Alternatively, you may have pasted in something that has “)” but no “(“, which results in a premature end. You can use M-x check-parens to quickly check for mismatched parentheses, or try reading the code carefully in order to find the mismatched pair. You can also use C-M-f (forward-sexp) and C-M-b (backward-sexp) to navigate by complete expressions until you find the specific one that causes the error.

Cannot open load file: …

The code is trying to require or load a file that Emacs can’t find.

  • Have you installed the appropriate package? Use M-x list-packages to see if it has been packaged into a form that’s easy to install. You may need to add other sources to your package-archives to see a wider range of packages.
  • Have you downloaded it manually and added it to your load-path? See the notes on load-path for more details.
  • If you’re using load, does the file exist?

Lisp error: (void-function …)

The code calls a function that has not been defined.

  • Have you installed the appropriate package? Look at the function name and try to guess the name of the package. People usually start the function name with the package name in order to make the function names unique. Use M-x list-packages to see the available packages. You may need to add other sources to your package-archives to see a wider range of packages.
  • If you downloaded the library manually, load or require it.
  • If you’re copying some code that isn’t packaged in a library, check if there are any defun (define function) expressions that you forgot to copy. Make sure to include and evaluate those.

Symbol’s value as variable is void: _

The code is trying to get the value of a variable that has not yet been set. See if there’s other code that you need to evaluate first in order to set up those variables. If the expression involves add-to-list or add-hook, you may need to use require to load the library that defines that list or hook first.

You might also get this if you’re using C-x C-e (eval-last-sexp) to evaluate an expression that’s inside let or other things that create variables. When you’re starting out, make sure you use C-x C-e (eval-last-sexp) after the outermost set of parentheses.

I’m using C-x C-e (eval-last-sexp) and I don’t get the results I expected

Make sure you call C-x C-e after the outermost ) for the expression you want to evaluate.

(ido-mode 1)
            ^
            |
            +---- Your cursor should be here

If the code you’re looking at has multiple expressions, you’ll need to call C-x C-e after each of them. It might be easier to select the region and use M-x eval-region, or evaluate the entire buffer with M-x eval-buffer. Alternatively, use M-x ielm to evaluate the code instead.

Again, if you don’t see the error you’re struggling with here, ask the relevant mailing list, help-gnu-emacs, the #emacs channel on irc.freenode.net, or StackOverflow for help. Good luck!

Wrapping up the beginner course

I hope that this course has helped you become more comfortable with reading and tweaking Emacs Lisp configuration code from blog posts, wiki pages, and other resources. There’s much more to learn, of course. With describe-function, describe-variable, and the ability to quickly experiment with Emacs Lisp code without restarting Emacs all the time, I’m sure you’ll get the hang of it! If you’d like to review or refer to this course, you can get it as one page at http://emacslife.com/how-to-read-emacs-lisp.html .

Check out An Introduction to Programming in Emacs Lisp, and delve into the Emacs Lisp Reference Manual for more details. Both are available within Emacs as Info manuals, which you can read with C-h i (info). Look for the Emacs Lisp Intro and Elisp entries, and browse through those manuals for more details. To search the current info manuals, type s (Info-search). To search all info manuals, use M-x info-apropos.

If you liked this or you have other questions, please get in touch – [email protected]. I’d love to hear from you, and I’m happy to help with other Emacs questions you may have. Good luck and have fun!

More links:

Series Navigation« Read Lisp Tweak Emacs (Beginner 3/4): How can I make things more convenient?

Read Lisp Tweak Emacs (Beginner 3/4): How can I make things more convenient?

This entry is part 3 of 4 in the series Read Lisp, Tweak Emacs

“How can I customize Emacs to make things more convenient?”

After this module, you’ll be able to:

  • define your own keyboard shortcuts so that you can call functions more easily
  • work with custom functions that other people have defined in their configurations
  • copy and use anonymous functions

Keyboard shortcuts

The default keyboard shortcuts (or “keybindings”) can be difficult to remember, and many useful functions don’t have any keyboard shortcuts at all. People often set up their own keyboard shortcuts to make other commands easier to use. There are different ways to assign keys depending on where you want the keybinding to be available.

Setting keybindings in all buffers

You can assign a key to a function globally, which means that it will be available in buffers of any type if there are no mode maps or local keybindings that override it. (Mode maps are set by major modes like emacs-lisp-mode or minor modes like auto-fill-mode.) Setting a global keybinding is usually done with global-set-key, although sometimes you’ll see it done with define-key and global-map.

You can use global-set-key interactively by calling it with M-x global-set-key. Type the keyboard shortcut you would like to set, then specify the name of the function you would like Emacs to call. Note that the function must be interactive – that is, it must be something you can call with M-x and it should include (interactive ...) in its definition. For example, try M-x global-set-key, then press <f10>, and assign it to save-buffer. After you do that, you should be able to press <f10> to save the current buffer.

If you like a keybinding that you’ve interactively set, use C-x ESC ESC (repeat-complex-command) to see the Emacs Lisp code for it. You can copy and paste that into your configuration. For example, setting the keybinding above will result in:

(global-set-key [f10] (quote save-buffer))

You can also write keybindings from scratch. For example, the code below redefines the Return key (or the Enter key) so that it calls the newline-and-indent function by default.

(global-set-key (kbd "RET") 'newline-and-indent)

Remember, ​'newline-and-indent and (quote newline-and-indent) are the same thing – they both refer to the name of a thing (a function, in this case) instead of its value.

(global-set-key (kbd "C-+") 'text-scale-increase)
(global-set-key (kbd "C--") 'text-scale-decrease)

These set C-+ (Ctrl and <plus>) and C-- (Ctrl and <minus>) to increase and decrease the font size when you’re running Emacs in a graphical environment.

If you want to set a keyboard shortcut only in particular modes or types of files, jump ahead to Setting keybindings in a particular mode.

What does kbd do? How can I figure out which key it sets?

If you’ve gone through the Emacs Tutorial (Help – Emacs Tutorial or C-h t), you’ll be familiar with many of the conventions used for writing keyboard shortcuts. C- stands for the Ctrl key, M- stands for the Meta key (which is probably Alt or Option on your keyboard). There are other prefixes as well. S- is for Shift, H- is for Hyper, and s- is for Super. Some people use operating system tools (such as setxkbmap for Linux) to change keys on their keyboard to Super or Hyper in order to enable even more keyboard shortcuts.

Uppercase or lowercase depends on the character in the shortcut. C-x means Control + x, while C-X is actually Control + Shift + X. You can also specify shift by adding S-, so C-X and C-S-x are the same.

In addition, there are some special characters: RET, SPC, TAB, and ESC must be written in uppercase to mean the special keys they refer to. (There’s also LFD and NUL, but you’re probably not going to encounter those as often.) You can use angle brackets to refer to some other keys, like <return>, <up>, <down>, <left>, <right>. Function keys are written like this: <f1>.

There are different ways to specify the key. Many people use (kbd ...) because it makes bindings easy to read.

(global-set-key (kbd "M-/") 'hippie-expand)

This is the same as

(global-set-key "\M-/" 'hippie-expand)

or

(global-set-key [?\M-/] 'hippie-expand)

You can use ^ to mean Control, so

(global-set-key (kbd "C-s") 'isearch-forward-regexp)

is the same as either of these lines:

(global-set-key "\C-s" 'isearch-forward-regexp)
(global-set-key (kbd "^s") 'isearch-forward-regexp)

but C- is probably easier to read.

When you use kbd, whitespace doesn’t usually matter, but it’s easier to read if you use space to separate the keys to type. For more information about the syntax used by kbd, see C-h f (describe-function) for kbd, then follow the link to the documentation for edmacro-mode.

In general, you can use C-h k (describe-key) followed by a keyboard shortcut to see if it’s already bound, and if so, what function it calls. If you type C-h k and the key you’re interested in, and Emacs is still waiting for another key, then you’re probably looking at a prefix key. For example, C-x is a prefix key that’s used in keyboard shortcuts like C-x C-e (eval-last-sexp).

Multi-key shortcuts

You can set up keybindings that use more than one key combination. This is a popular technique since you can only have so many short keybindings. For example, the following code changes C-x C-b to call ibuffer, which lists your buffers and makes it easy to jump to another buffer.

(global-set-key (kbd "C-x C-b") 'ibuffer)

You don’t have to start with C-c or C-x. Consider using one of your function keys like <f9> as the start of your keyboard shortcuts. Then you can create shortcuts that don’t involve using Ctrl, Alt, or other modifier keys. For example:

(global-set-key (kbd "<f9> b") 'ibuffer)

Read other people’s configurations to get a sense of useful commands and handy keyboard shortcuts. By convention, shortcuts like C-c followed by a lowercase or uppercase letter are reserved for your use, as are the function keys <f5> to <f9>. Other keyboard shortcuts are likely to already be defined by modes. You can override them if you want.

Some people like using a function key followed by letters in order to minimize the need to press Control or Meta. For example, you might use:

(global-set-key (kbd "C-c r") 'query-replace)

or

(global-set-key (kbd "<f9> r") 'query-replace)

to make it easier to replace strings. You can even bind it to both shortcuts.

Binding keys to other keys

In addition to setting keyboard shortcuts for functions, you can also define keys to expand to a longer sequence of keystrokes. You can use this for inserting strings or calling keyboard macros. For example:

(global-set-key (kbd "<f7> e") "[email protected]")
(global-set-key (kbd "<f7> w") "http://example.com")
(global-set-key (kbd "<f7> u") (kbd "C-x C-s"))

These might be handy for quickly inserting your e-mail address or website.

Dealing with errors: “Key sequence __ starts with non-prefix key _

If you want to create a multi-key shortcut, the preceding keys must not already be assigned to functions. For example, if you want M-t l to call transpose-lines, you’ll need to get rid of M-t‘s default binding to transpose-words first. To unset a key, bind it to nil or use global-unset-key. Here’s a group of shortcuts you can try.

(global-set-key (kbd "M-t") nil) ;; Remove the old keybinding
(global-set-key (kbd "M-t c") 'transpose-chars)
(global-set-key (kbd "M-t w") 'transpose-words)
(global-set-key (kbd "M-t t") 'transpose-words)
(global-set-key (kbd "M-t M-t") 'transpose-words)
(global-set-key (kbd "M-t l") 'transpose-lines)
(global-set-key (kbd "M-t e") 'transpose-sexps)
(global-set-key (kbd "M-t s") 'transpose-sentences)
(global-set-key (kbd "M-t p") 'transpose-paragraphs)

The example above has three bindings for transpose-words. M-t w uses the mnemonic of t-ranspose w-ords. M-t t is similar to the original binding for transpose-words, which was M-t. M-t M-t may seem like overkill, but sometimes you’ll find it easier to hold the Meta key down and hit t twice quickly instead of typing M-t, releasing Meta, and then typing t. As you read other people’s keybindings, you’ll get a sense of how people have configured their keyboard shortcuts to speed up typing and minimize thinking.

Setting keybindings in a particular mode

Sometimes you want keys to do different things in different types of files. Modes are how Emacs changes behaviour based on context. For example, Java files use java-mode, Org files use org-mode, and so forth. In addition to the major mode for a buffer, you may have several minor modes that modify the behaviour. Each mode has a keybinding map (or a “keymap”). You can assign a key in a mode map, which means it will override global keybindings in buffers with that mode. You can do this with define-key if you know the name of the keymap you want to change, which is generally the name of the mode + -map. For example:

(define-key emacs-lisp-mode-map (kbd "C-c f") 'find-function)

changes the C-c f keyboard shortcut to find-function (which jumps to the definition of a function), but only in Emacs Lisp buffers.

Note that if you use define-key with a mode map, the mode must already be loaded by the time this code is run. That’s why you’ll often see this after a require (which loads the code) or inside an eval-after-load (which postpones the code until after the mode is loaded). See Adding more features to Emacs for information on loading packages and adding new functions to Emacs.

Other ways people bind keys

The bind-key package provides a function that makes it easier to see your personal keybindings, but bind-key is not part of Emacs by default. I use bind-key a lot in my configuration. The syntax is similar to global-set-key, except it automatically wraps the keyboard shortcut string in kbd. It also keeps track of which keyboard shortcuts you’ve overridden so that you can use M-x describe-personal-keybindings to review them.

(bind-key "C-+" 'text-scale-increase)
(bind-key "C--" 'text-scale-decrease)

You’ll need to install and use the bind-key package before you can use that code.

Because keybinding is something that lots of people do to customize their Emacs, you may find other ways that people have simplified writing keybindings for themselves. When in doubt, use C-h f (describe-function) to explore how something works. If the function can’t be found, see if it’s in a package somewhere, or search the Web for more information.

For more about keybindings, see the Emacs manual and this Mastering Emacs post on keybindings.

Defuns – function definitions

In addition to the functions built into Emacs or available in packages, many people define their own with the defun function.

People often distinguish custom functions by starting them with my/ or their initials. This makes it easier to tell which functions they’ve customized and which ones are part of a package. It also minimizes the risk of accidentally overriding a function defined elsewhere. You can change the name of a function as long as you make sure you change the name wherever it’s called, such as in keyboard shortcuts, hooks, or other functions.

For example, here’s a custom function from Jorgan Schaefer’s config:

(defun fc/kill-to-beginning-of-line ()
  "Kill from the beginning of the line to point."
  (interactive)
  (kill-region (point-at-bol) (point)))

This creates a function called fc/kill-to-beginning-of-line. () is the argument list. Since it doesn’t contain anything, that means this function does not take arguments. ​"Kill from the beginning of the line to point."​ is a documentation string (or docstring) that describes what the function does. Docstrings are optional, but highly recommended. (interactive) means that this can be called with M-x (execute-extended-command) or bound to a keyboard shortcut.

If a function does not have the (interactive) keyword, you won’t be able to call it with M-x or assign it to a keyboard shortcut, but you will still be able to write Emacs Lisp code that calls the function. This means M-x (execute-extended-command) lists only the commands that people will probably find useful while working directly with Emacs, skipping internal functions used by code.

Once you’ve defined a custom function, you can bind it to a keyboard shortcut if you want. The code below binds the fc/kill-to-beginning-of-line function to C-c C-u:

(global-set-key (kbd "C-c C-u") 'fc/kill-to-beginning-of-line)

You will often see custom functions added to hooks. A hook is a list of functions that’s called by some other code. Modes usually define a hook that’s called after the mode is initialized so that you can further customize its behaviours. For example, emacs-lisp-mode has an associated emacs-lisp-mode-hook which is run when a buffer is set up in Emacs Lisp Mode. You can add built-in functions or custom functions to hooks, and they’ll be run when that hook is called.

People sometimes use hook functions to set up keybindings instead of using define-key. For example, this code:

(add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)
(define-key emacs-lisp-mode-map (kbd "C-c f") 'find-function)

can also be written as:

(defun my/set-up-emacs-lisp-shortcuts ()
  "Set up some conveniences for Emacs Lisp."
  (turn-on-eldoc-mode)
  (local-set-key (kbd "C-c f") 'find-function))
(add-hook 'emacs-lisp-mode-hook 'my/set-up-emacs-lisp-shortcuts)

Lambdas – anonymous functions

Sometimes people just want to create a keyboard binding or process some data without defining a new function. lambda creates an anonymous function, which is a function that doesn’t have a name. Here’s an example:

(global-set-key (kbd "C-c e") (lambda () (interactive) (find-file "~/.emacs.d/init.el")))

This binds C-c e to an anonymous function. The () means it doesn’t take any arguments. (interactive) means it can be called through a keyboard shortcut, although since it’s anonymous, it can’t be called with M-x. The function opens the ~/.emacs.d/init.el file, which is a handy way to edit your configuration.

  1. Look for an Emacs configuration file that defines keybindings that you’re curious about. Install any packages or copy any custom functions needed. Experiment with using those keybindings. Do you like them? Do you want to tweak them further?
  2. Think about how you use Emacs. What kinds of keyboard shortcuts would make your work easier? How can you adapt some of the functions you’ve read into things that would make them even more convenient for you?
You can find the draft of the complete course at emacslife.com/how-to-read-emacs-lisp.html. Enjoy!
Series Navigation« Read Lisp Tweak Emacs [Beginner 2/4]: How to understand what Emacs Lisp code doesRead Lisp, Tweak Emacs (Beginner 4/4): “How can I add more features? How do I deal with errors?” »

Summarizing the last meeting dates in Org Contacts

Steffan Heilmann wanted to be able to quickly see the last time he interacted with someone if he tracked interactions in org-contacts. That is, given something like this:

* John Smith
** DONE Conversation
[2014-01-20]
** DONE E-mail
[2014-01-15]
* Jane Smith
** DONE Conversation
[2014-01-07]

… we want to see the latest timestamps for each contact entry.

Here’s the code that I came up with. It scans backward for timestamps or headings. Whenever it finds a timestamp, it compares the timestamp with the one that it has previously stored and keeps the later timestamp. Whenever it encounters a level-1 heading, it sets the property and clears the stored timestamp.

(defun sacha/org-update-with-last-meeting ()
  "Update each level 1 heading with the LASTMEETING property."
  (interactive)
  (goto-char (point-max))
  (let (last-meeting)
    (while (re-search-backward
            (concat "\\(" org-outline-regexp "\\)\\|\\("
                    org-maybe-keyword-time-regexp "\\)") nil t)
      (cond
       ((and (match-string 1)
             (= (nth 1 (save-match-data (org-heading-components))) 1)
             last-meeting)
        ;; heading
        (save-excursion (org-set-property "LASTMEETING" last-meeting))
        (setq last-meeting nil))
       ((and (match-string 2))
        (if (or (null last-meeting) (string< last-meeting (match-string 2)))
            (setq last-meeting (match-string 2))))))))

Scanning backwards works well here because that makes it easy to add information to the top-level heading we’re interested in. If we scanned it the other way around (say, with org-map-entries), we might need to backtrack in order to set the property on the top-level heading.

The result is something like this:

* John Smith
  :PROPERTIES:
  :LASTMEETING: [2014-01-20]
  :END:
** DONE E-mail
[2014-01-15]
** DONE Conversation
[2014-01-20]
* Someone without a meeting
* Jane Smith
  :PROPERTIES:
  :LASTMEETING: [2014-01-07]
  :END:
** DONE Conversation
[2014-01-07]

You can then use something like:

#+COLUMNS: %25ITEM %LASTMEETING %TAGS %PRIORITY %TODO
#+BEGIN: columnview :maxlevel 1
| ITEM                        | LASTMEETING  | TAGS | PRIORITY | TODO |
|-----------------------------+--------------+------+----------+------|
| * John Smith                | [2014-01-20] |      |          |      |
| * Someone without a meeting |              |      |          |      |
| * Jane Smith                | <2014-01-07> |      |          |      |
#+END:

… or even use M-x org-sort to sort the entries by the LASTMEETING property (R will reverse-sort by property).

Read Lisp Tweak Emacs [Beginner 2/4]: How to understand what Emacs Lisp code does

This entry is part 2 of 4 in the series Read Lisp, Tweak Emacs

Some conventions we’ll use:

  • Inline code will be boxed and monospace in the HTML version and generally surrounded by equal signs in plain text.
  • Code samples will be monospace and in boxes in the HTML version, and enclosed in #+begin_src#+end_src in plain text. Example:
    (message "Hello world")
    

After this module, you should be able to

  • learn more about the functions and variables that you find in Emacs Lisp code
  • pay attention to important details when copying code, such as ‘ (quote) and . (dot notation)
  • add to and remove items from lists

Learn more about functions

The symbol after ( is usually a function name, unless it’s part of a list of literals (numbers, strings, etc.). You’ll learn how to recognize literal lists later.

In math, operators like + and * go between the numbers they will work on. In Emacs Lisp, the operator (or the “function”) is at the start of the expression, followed by the things it’s going to operate on (“arguments”).

Here’s how to calculate (1 + 2) * 3 in Emacs Lisp. Note that the multiplication is surrounded by parentheses, even if we usually leave out the parentheses in math. That’s because in Emacs Lisp, all function calls have their own set of parentheses.

(* (+ 1 2) 3)

Let’s take a closer look:

( ( 1 + 2 ) * 3 )    Math expression
( * ( + 1 2 ) 3 )    Emacs Lisp expression

math-to-emacs-lisp.png

See how the operators are at the beginning of whatever they’re working on, and the parentheses enclose everything that’s related to that operator?

Understanding this will let you read code like:

(global-hl-line-mode)

This calls the global-hl-line-mode function, which highlights the current line.

(show-paren-mode)

This calls the show-paren-mode function, which shows matching parentheses when your cursor is after them.

(blink-cursor-mode -1)

This calls the blink-cursor-mode function with -1 as the argument, which turns blinking cursors off.

(find-file "~/todo.org")

This calls the find-file function with the todo.org file in your home directory. It opens the file, creating it if it doesn’t exist yet.

(turn-on-eldoc-mode)

This turns on eldoc-mode, which displays the argument list for the current function. You can move your cursor around to see argument lists for other functions.

(add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)

This turns on eldoc-mode when a buffer is switched to Emacs Lisp mode. You’ll learn more about why some things have ​'​ and some don’t in the section “Some things are taken literally” in this module.

To find out if something is a function, what it does, what arguments it takes, and if it has any keyboard shortcuts, use the C-h f (describe-function) command. Give it the function name. For example, C-h f add-hook will show you the documentation for add-hook, and C-h f show-paren-mode will show you the documentation for that.

The documentation for show-paren-mode starts with “show-paren-mode is an interactive autoloaded Lisp function”. Interactive functions are functions that can be called with M-x or with keyboard shortcuts, and they’re usually functions that you’ll find useful while interacting with Emacs. Non-interactive functions tend to be for internal use, such as code that other Emacs Lisp code will call. Read the description of the function to learn more about arguments that you can pass to change its behavior. If it mentions a prefix argument, that means that you can change its behaviour by typing C-u before you call the function.

Emacs is extensively documented. Whenever you come across a strange function, check it out with C-h f (describe-function). If you have the Emacs Lisp sources installed, you can learn more about how the functions work. Just follow the link from the documentation, or use M-x find-function to learn more.

In fact, you can learn more about functions even if you don’t know what they’re called. For example, if you know the keyboard shortcut or you can see the item on one of the menus, use C-h k (describe-key) to learn more about that command. Emacs will show you the function that’s associated with that keyboard shortcut or menu item. You can also look up functions by keyword if you use M-x apropos.

  1. Use C-h f (describe-function) to learn more about the following functions:
  2. describe-function: Yes, this is also a function! The documentation will give you alternative keyboard shortcuts such as F1 f.
  3. find-file: You can use this to open specific files. See the function description to learn how to use this with remote files.
  4. message: This is an example of a function that has a variable number of arguments. The first argument says how the message will be displayed, and the rest of the arguments contain the values.
  5. just-one-space: Handy way to clean up space. What keyboard shortcut is it bound to?
  6. Look for Emacs configuration code that you would like to understand further. Use C-h f (describe-function) to learn more about the functions in the code. For example, here are some snippets from my configuration. What do the functions do?
    (savehist-mode 1)
    (tooltip-mode -1)
    (tool-bar-mode -1)
    (menu-bar-mode -1)
    (scroll-bar-mode -1)
    (prefer-coding-system 'utf-8)
    

Learn more about variables

Variables are containers that can hold different values. In Emacs Lisp, you can change the value of a variable as many times as you want, and you can change it to different types of data as needed.

Like the way you can use C-h f (describe-function) to learn more about a function, you can use C-h v (describe-variable) to learn more about a variable by name. For example, use C-h v to look up the documentation for visible-bell. It says:

Non-nil means try to flash the frame to represent a bell.

A non-nil value is anything that isn’t nil, such as t or 1. If you would like to configure your Emacs to flash instead of ringing the bell,
you could add the following code to your ~/.emacs.d/init.el:

(setq visible-bell t)

Here’s another useful snippet:

(setq column-number-mode t)

This turns on the display of the column number in the modeline.

Many variables have the same value no matter what you’re looking at. Some variables change depending on the buffer you’re in, and are called “buffer-local” variables. Use C-h v to find out if a variable is buffer-local. For example, the documentation for tab-width includes:

Automatically becomes buffer-local when set.

This means you can’t globally set it with setq, because any changes you make will only be applied to the current buffer. However, you can set the default value with setq-default like this:

(setq-default tab-width 2)

To make it easier for you to customize Emacs without writing Emacs Lisp code, many variables give you an interface for setting the variable. If you use describe-variable to look up the definition, you’ll often see a line like “You can customize this variable.” Click on the customize link in the documentation or move your point to it and press RET. You can change the value there and try it temporarily, or you can save it to your configuration. The Customize interface is good for exploring, but because the code that it generates can difficult to read or share, many people skip it and use Emacs Lisp code instead.

  1. Use C-h v (describe-variable) to learn more about the variables in the following code snippet:
    (setq-default indicate-empty-lines t)
    (setq-default show-trailing-whitespace t)
    
  2. Look for Emacs configuration code that has variables you would like to learn more about. Use C-h v (describe-variable) to look up their definition and the values they can be set to.

Understand symbols

Let’s take a closer look at this example.

(add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)

add-hook is a function. ‘emacs-lisp-mode-hook and ‘turn-on-eldoc-mode have single quotes, which tells Emacs to skip evaluating them. They refer to the name of the thing instead of its value. emacs-lisp-mode-hook is a variable that contains a list of functions to run, and turn-on-eldoc-mode is a function that we’re adding to that list.

The single quote means take it literally – treat it as the name of something. If you remove the quote from emacs-lisp-mode-hook, Emacs will look up the value in that variable and use that as the name of the variable to actually set, and you’ll probably get an error.

Use M-: (eval-expression) or another way to evaluate expressions to tell the difference between:

emacs-lisp-mode-hook

and

'emacs-lisp-mode-hook

The first one does not have a quotation mark, and Emacs replaces it with the value that the variable emacs-lisp-mode-hook contains. The second one is quoted, so Emacs treats it as the name of a thing.

Here’s another example:

(fset 'yes-or-no-p 'y-or-n-p)

This calls the fset function, which sets the function definition of yes-or-no-p to the function y-or-n-p. In short, it changes the “yes” or “no” prompts to “y” or “n”, which can be convenient.

Not everything is quoted. You’ll often see lines like this in Emacs configuration files:

(setq delete-old-versions -1)

setq stands for “set quoted”. This is actually the same code as (set 'delete-old-versions -1) or (set (quote delete-old-versions) -1), but
setq is shorter, so it’s more common.

This can be confusing. When you’re starting out, copy code carefully. If there’s a single quote, make sure there’s a single quote in your copy. If there isn’t, skip it.

Work with lists

You can set the value of a variable to multiple things. In Emacs configuration files, you’ll often see ‘ used for lists. For example,

(setq diff-switches '("-b" "-u"))

sets the options for the diff command to a list containing two items, -b and -u. Quoting the list creates a list and quotes all the content in it as needed. You can create lists with the list function instead. The code above is the same as:

(setq diff-switches (list "-b" "-u"))

The code above sets the value of the variable to a list, ignoring any previous values it had.

Add to a list

Most of the time, though, you want to add to a list instead of completely replacing it. You’ll often see something like this in people’s configuration files:

(add-to-list 'load-path "~/elisp")

This adds the ~/elisp directory to the beginning of the list of directories that Emacs checks when loading libraries. If the directory is already in the list, add-to-list does nothing.

Hooks

Hooks are lists of functions that are called from Emacs Lisp in order to modify the behaviour of something. For example, different modes have their own hooks so that you can add functions that will run when that mode is initialized. You saw this example earlier in the module:

(add-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)

This is equivalent to:

(add-to-list 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)

It adds the turn-on-eldoc-mode function to the list of functions
when a buffer is initialized with emacs-lisp-mode.

Deleting from a list

If you need to delete something from a list, you can use the delete function like this:

(setq load-path (delete "~/elisp" load-path))

This deletes the specified member from the list. Note that the second argument for delete is not quoted, so Emacs Lisp uses the value instead of treating it as the name of a list.

Hooks are lists of functions, so you can delete items using delete. Alternatively, a cleaner way to remove a hook is to use remove-hook like this:

(remove-hook 'emacs-lisp-mode-hook 'turn-on-eldoc-mode)

Dot notation

Some things look like lists, but there’s a dot between the first element and the last element. Whether something should have a dot or not depends on what’s expected by the function that uses the data. For example:

(add-to-list 'package-archives '("melpa" . "http://melpa.milkbox.net/packages/"))

This calls the add-to-list function with two arguments. The first argument (‘package-archives) specifies the list to add an item to, and the second argument (‘("melpa" . "http://melpa.milkbox.net/packages/")) is the data to add.

The dot (x . y) shows that this is a cons cell, which is something that has two parts. These parts are called the car and the cdr, and can contain symbols, values, lists, and so on. A cons cell like ("abc" . "def") looks like this:

       car              cdr
+----------------+----------------+
|     "abc"      |     "def"      |
+----------------+----------------+

A list like ‘("abc" "def") is made up of several cons cells.

       car              cdr                         car             cdr
+----------------+----------------+         +----------------+----------------+
|     "abc"      |       ------------------>|      "def"     |      nil       |
+----------------+----------------+         +----------------+----------------+

In Emacs Lisp, ‘("abc" "def") is equivalent to (cons "abc" (cons "def" nil)), and it’s not the same as (cons "abc" "def"). Here’s something that shows the differences:

(cdr '("abc" . "def"))  ;; Returns "def", which is a string
(cdr '("abc" "def"))    ;; Returns ("def"), which is a list

If the function you’re calling expects a string instead of a list, or the other way around, you’ll run into errors. That’s why you have to be careful about whether something uses dots or not. A good way to find out is by reading other people’s configuration and seeing how they use that variable.

Because lists are made up of cons cells, you’ll sometimes see people add to lists like this:

(setq load-path (cons "~/elisp" load-path))

This adds ~/elisp to the beginning of the load-path list. It does this by using cons to create a new cons cell that has ~/elisp at the beginning and a pointer to the rest of the values in load-path, and then storing that in load-path. It’s the same as (add-to-list 'load-path "~/elisp"), assuming load-path does not already have that directory. If it does, cons adds it anyway, but add-to-list does not.

Lists can also contain lists. For example, here’s some code that saves backup files (the ones that end in ~) to ~/.emacs.d/backups.

(setq backup-directory-alist '(("." . "~/.emacs.d/backups")))

This is how the second argument breaks down:

( ;; a list with one item
 ("." . "~/.emacs.d/backups") ;; a cons cell with a car of "." and a cdr of "~/.emacs.d/backups"
)

If you want to learn more about cons cells, see the Emacs Lisp Reference.

Advanced: Backquotes or backticks (`) are special. They quote the expression that follows them, but they also allow you to substitute values or evaluate expressions. Backquotes are useful for more complex structures or when you’re working with macros. They do basically the same thing as ‘ for lists, but anything preceded by a comma (,) is evaluated. They’re less common, but if you do come across them, note that ` is not the same as ‘. See the Emacs Lisp Reference for more information. Here’s a quick example:

(setq backup-directory-alist `((".*" . ,temporary-file-directory)))

This stores backup files in the directory specified by temporary-file-directory.

Review

Look for Emacs configuration code that you would like to understand further. Use C-h f (describe-function) to learn more about functions and C-h v (describe-variable) to learn more about variables in the code. Can you figure out what the code does and how you might modify it slightly to fit your needs even better?

Series Navigation« Read Lisp, Tweak Emacs [Beginner 1/4]: How to try Emacs LispRead Lisp Tweak Emacs (Beginner 3/4): How can I make things more convenient? »

What could Emacs coaching look like?

I asked people on Twitter how much they might pay for 30-60 minutes of Emacs coaching. Based on replies and e-mails, the general consensus seems to be about $25-35 for 30 minutes and $35-50 for an hour, depending on the level of tweaking.

This is how I imagine it might work and why it might be worth it:

Troubleshooting
You could spend days (or weeks!) posting and replying to mailing lists or StackOverflow, or you could spend an interactive session quickly digging into what’s wrong and how to work around or fix it. In addition, you’ll probably pick up lots of tips by watching someone’s problem-solving or debugging process. This probably works as a quick e-mail describing the problem, a 30-60 minute troubleshooting session over screen sharing or SSH/tmux, and possibly a free or paid-for follow-up if more investigation is needed. Probably a good idea to have a satisfaction guarantee, since some problems are harder to solve than others.
Guidance, pair programming, or coding
You’ve got an idea for an Emacs customization or major mode, but it requires more Emacs Lisp geekery than you’re comfortable with or you don’t know how to go about implementing it. A few high-level pointers might get you going: check out these examples, use this function to do that, etc. Or you might want to write most of the code yourself while having someone around so that you can ask questions if you get stuck – maybe a lower rate for the virtual equivalent of hanging out in a cafe together while working on separate things? Alternatively, a code review can point out how you can debug or improve things. Lastly, there’s also the option of handing off most of the coding, with some interactive sessions as you nail down exactly how you want it to behave.
Coaching
I think this is where incredible is, actually – getting help when you don’t even know what you don’t know. Emacs is really big. It can be difficult to get a sense of what’s possible or what’s surprisingly easy, so you might be plodding along with an inefficient workflow that could be tweaked with a little configuration or a few changed practices. A good coach can discuss your goals, watch how you do things, demonstrate better ways to work, and help you implement those changes.
Gradual learning
On a related note, it’s also easy to get intimidated by how much there is. It can help to have a gradual learning path. I’ve talked to quite a few people who found Org Mode task management overwhelming and had hundreds of tasks piled up in their text files. Ditto for Emacs Lisp learning! Imagine having the Emacs equivalent of a personal trainer who can help you come up with an individualized program of learning so that you’re focused on one small chunk at a time. =)

Plot twist! This is actually for Bastien Guerry (Org Mode maintainer, also http://emacs-doctor.com/), not for me. I’ve been doing Emacs-related Helpouts for a token fee and I’m happy to chat with people about Emacs gratis as well, but I think it would be even awesomer to see if someone as wonderful as Bastien can build a nice little business out of it.

How wonderful is Bastien? Well, if you’ve seen my Emacs Chat with him or read his posts on the Org Mode mailing list, you know that he’s smart, experienced, and friendly. In fact, the more I think about what Emacs consulting might be like, the more I want to sign up too. I use Org a lot and I’m generally comfortable tinkering with the source code, but there are a few things that I haven’t quite wrapped by mind around yet: more export tweaks, more Babel/tangling, a better capture workflow… And I have yet to get around to setting up proper autocomplete and other development tools, too!

Bastien’s travelling at the moment, but wouldn’t it be lovely if he got back to a bunch of e-mails to [email protected] with requests or suggestions? =) E-mail him if you’re interested, and help him figure out what’s a good way to help you. He mentioned being open to pay-what-you-want pricing. If money is tight, reach out to him anyway – and if you want to donate more as a way of thanking him for all the other stuff he does, that’s also a great excuse to ask him to help improve how you use Emacs.

Hey, if there are Eclipse consultants… Surely we can get even more value out of Emacs consulting!