Category Archives: emacs

On this page:

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!

Read Lisp, Tweak Emacs [Beginner 1/4]: How to try Emacs Lisp

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

Okay! People have given lots of great feedback on the e-mail course. It’s time to post the course content on my blog so that you can read it here too (or search for it in case you want). =) I’ll post these one section at a time, but you can read the current draft at http://emacslife.com/how-to-read-emacs-lisp.html if you want to. Any updates will probably be over there too!

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 section, you should be able to

  • find Emacs Lisp code to study and use
  • try Emacs Lisp code before saving it to your configuration (that way, you don’t have to keep restarting Emacs)
  • add code to your configuration so that it runs whenever Emacs starts

Finding Emacs Lisp code

It’s easier to learn how to read Emacs Lisp when you start with simple examples that will help you use Emacs more effectively. Here are some useful sources:

Emacs documentation

Manuals and FAQs for Emacs-related tools often include code snippets. For example, the Emacs FAQ has an entry like this:

5.47 How can I tell Emacs to fill paragraphs with a single space after each period?
===================================================================================

Add the following line to your `.emacs' file:

     (setq sentence-end-double-space nil)

You can read the Emacs manual by typing C-h i (info) and choosing the Emacs item. If you’re on a terminal that doesn’t understand the C-h key, use F1 or M-x help whenever you see a reference to C-h, or use M-x to call the command by name (ex: F1 i, or M-x info). To jump directly to the Emacs manual, you can use C-h r (info-emacs-manual). You can also find the Emacs Manual at http://www.gnu.org/software/emacs/manual/emacs.html .

Packages

Emacs has lots of packages in different repositories, many of which require a little extra code in order to be used to full effect. You can use M-x package-list-packages to list the packages that Emacs knows about by default. You will need an Internet connection for that.

If you’re new to Emacs, try getting used to Emacs without packages first. There’s plenty of functionality already built in. When you come across a gap, chances are that someone has written a package to make Emacs behave the way you want it to. Since there are lots of packages that do similar things, you might want to look for recommendations or ask people which ones you should start with.

In addition to the default package repository, there are other community-supported repositories. See Installing packages if you would like to install a package from a different repository.

If you install a package, check out the README, description, documentation, or source code comments for interesting packages to find suggested code to add to your Emacs configuration.

Here are some packages that might be interesting:

  • company: adds text completion
  • yasnippet: snippets and templates
  • undo-tree: visualize your undo/redo history

You will need to be connected to the Internet in order to view and install packages. You can use M-x package-list-packages to show the available packages and read the descriptions for the packages above.

Webpages, blog posts, and the Emacs Wiki

While searching for information related to Emacs, you’ll probably come across lots of Emacs Lisp snippets. The EmacsWiki has lots of code, too. Since this is a community-maintained wiki, you may come across code that is out of date or that refers to packages that you don’t have. I’ve included common errors in this guide to help you figure things out – see “Oh no! I have an error!”

Here are some sites you may want to check out:

Mailing lists, newsgroups, and Q&A sites

There are many places where you can ask for help with Emacs. gnu.emacs.help is available as a mailing list or as a newsgroup – check your favourite Usenet server or use Gmane. StackOverflow and Quora are popular as well. If you ask questions there, you might get answers in the form of Emacs Lisp code. You’ll also come across Emacs Lisp code while searching for answers.

Find a snippet of Emacs Lisp code you want to understand more deeply, or look at the examples in the sections below.

Trying out code

It’s easier to understand code if you can experiment with it. Emacs Lisp code is made up of symbolic expressions (known as S-expressions, expressions, or sexp for short). Expressions are usually enclosed in pairs of parentheses. There are several ways you can try Emacs Lisp expressions before saving them in your configuration.

Note: As you experiment with Emacs Lisp, you might run into errors. Check out “Oh no! I have an error!” for some common errors and what to do about them.

Here are some ways you can run Emacs Lisp code. I’ll explain them in more detail below.

  • M-x ielm (Inferior Emacs Lisp Mode) – evaluates expressions after you press RET, which is handy for pasting in code
  • The *scratch* buffer and Emacs Lisp files – makes it easy to edit and re-evaluate expressions
  • M-: (eval-expression) – good for quickly evaluating Emacs Lisp code while you’re doing something else
  • C-x C-e (eval-last-sexp) – handy when reading expressions in manuals or other text

M-x ielm (Inferior Emacs Lisp Mode)

The Inferior Emacs Lisp Mode gives you a prompt where you can type or paste in Emacs Lisp code. Start it with M-x ielm. Press RET after you enter code, and the results will be displayed. “Inferior” is a technical term referring to how it’s run, not a comment on the simplicity of the tool or the code you want to try. You can go to previously-executed code, change things, and press RET to run (or “evaluate”) it again.

If you’re copying or typing code, make sure your parentheses are all matched – every “(” should have a “)“. IELM won’t run the code unless it sees the closing parenthesis. So the following code is incomplete:

(message "Hello

but this will work:

(message "Hello world")

You can use M-p (comint-previous-input) to go through the previously-typed expressions. M-n (comint-next-input) goes forward.

Tip: When you’re trying out an unfamiliar mode, use C-h m (describe-mode) to learn more about the commands that are available in that mode.

The *scratch* buffer and Emacs Lisp .el files

When Emacs starts, it creates a buffer called *scratch* with the following contents:

;; This buffer is for notes you don't want to save, and for Lisp evaluation.
;; If you want to create a file, visit that file with C-x C-f,
;; then enter the text in that file's own buffer.

You can add code to the end.

;; This buffer is for notes you don't want to save, and for Lisp evaluation.
;; If you want to create a file, visit that file with C-x C-f,
;; then enter the text in that file's own buffer.

(message "Hello world")

Note: ; is the comment character. Anything after the comment character is considered part of the comment. Make sure you add your code on a new line, not in the comment. ;; above is how we usually start comments that take up the entire line.

To run code (“evaluate” it, in Emacs terms), you can use the following commands based on what you want to run:

  • M-x eval-buffer runs all the code in the current file or buffer.
  • M-x eval-region runs the code in the selected region. You can select a region of text by using the mouse. Alternatively, you can type C-SPC to mark the start of the region, then move your cursor to the end of the region. If you want to learn more about selecting regions, check out the Emacs tutorial (C-h t, C-h t, or M-x help-with-tutorial).
  • C-x C-e (eval-last-sexp) runs the expression (S-expression, or sexp) before the cursor. NOTE: Your cursor should be after the closing parenthesis, not on it.

In the *scratch* buffer, you can also press C-j (eval-print-last-sexp) after an expression in order to evaluate it and display the results in the buffer.

The *scratch* buffer is not automatically saved. If you would like to save your code for future use, you can create a file with an .el ending. el stands for Emacs Lisp, and Emacs will open these files in Emacs Lisp mode. The commands listed above work in Emacs Lisp files.

M-: (eval-expression)

If you want to quickly try a single expression, you can use M-: (eval-expression). It will display the results in the echo area near the bottom of your screen. If you want to insert the results into your buffer, call it with C-u M-: instead. For example, you can use C-u M-: (* 18 2) to multiply 18 and 2 quickly. To review previous results, you can switch to the *Messages* buffer.

C-x C-e (eval-last-sexp)

C-x C-e (eval-last-sexp) runs the expression (S-expression, or sexp) before the cursor. NOTE: Your cursor should be after the closing parenthesis, not on it. C-x C-e (eval-last-sexp) works in lots of buffers, not just in Emacs Lisp ones. You can use it to quickly try expressions while reading manual pages or other documentation.

You can get the text file for this lesson from http://emacslife.com/read-lisp-tweak-emacs/beginner-1-try-emacs-lisp.txt . If you’re reading this lesson in Emacs, try putting your cursor after the closing ) and calling C-x C-e (eval-last-sexp) on the following line:

(menu-bar-mode -1)

This turns off the menu bar along the top of your Emacs window. If you like the menu bar, you can turn it on again by evaluating:

(menu-bar-mode 1)

As with M-: (eval-expression), you can use the C-u prefix to insert the results instead of displaying them. For example, try using C-u C-x C-e (eval-last-sexp) to evaluate the following expression:

(* 6 7)

If you want that code to run every time you start Emacs…

then add it to your ~/.emacs.d/init.el file. You can generally add new code at the end. If the code has something to do with add-to-list and load-path, it might be good to add it to the beginning instead.

Note: The Emacs configuration file used to be ~/.emacs, and most webpages refer to that. ~/.emacs still works – in fact, if you have that, it may stop Emacs from loading ~/.emacs.d/init.el. On the other hand, if you use ~/.emacs.d/init.el (and move your ~/.emacs code to that file instead), then you have one less hidden file in your home directory (~). If you’re adding code to your config and it’s not getting loaded, make sure you have either ~/.emacs or ~/.emacs.d/init.el, but not both.

When you’re starting out, it’s a good idea to keep your configuration in one file. Later on, you can split it up into multiple files if you want.

Practice

Try this out:

Next module: “How can I understand what Emacs Lisp code does?”

  1. Browse through http://www.emacswiki.org/emacs/CategoryDotEmacs for some code that looks like it will make Emacs work more like the way you want it to. If you need help figuring it out, send me a copy of the code ([email protected]).
  2. Use M-x ielm to evaluate this expression interactively:
    system-type
    

    This shows you the value of the system-type variable. Note: Variables can be evaluated without the parentheses, but functions can’t. Use You can use ielm to call functions like this, though:

    (max 2 6 10 5)
    
  3. Use M-: (eval-expression) buffer to evaluate the following expression:
    (* 21 2)
    

    M-: is handy for quick calculations. Remember, you can use it with
    C-u (that is, C-u M-:) to insert the result into the buffer.
    Try it now: C-u M-: (* 21 2)

  4. Use C-x C-e (eval-last-sexp) to evaluate the expression below. If you are reading this in Emacs, you can evaluate it by putting your cursor after the last ) and calling C-x C-e (eval-last-sexp). If you are reading this outside Emacs, you can copy that text into any buffer and then use C-x C-e (eval-last-sexp) to evaluate it.
    (* (+ 1 2) 3)
    
  5. Add (message "Hello, world!") to the end of your ~/.emacs.d/init.el (or ~/.emacs, if you’re using that file instead). Use M-x eval-buffer to load your config. It should display the message near the bottom of your screen. If you restart Emacs, you should also see that message briefly.
  6. Call M-x visual-line-mode to tell Emacs to visually wrap lines without actually changing the text. If you like this, add (visual-line-mode) to your ~/.emacs.d/init.el.
Series NavigationRead Lisp Tweak Emacs [Beginner 2/4]: How to understand what Emacs Lisp code does »

Emacs: beginner, intermediate, advanced

In a recent Emacs Chat, Bozhidar Batsov mentioned the need for more intermediate to advanced resources, not just tutorials covering the same introductory ground. It got me thinking about different levels of Emacs use, and what kinds of things would help people move upwards.

I think of Emacs beginners as people who are getting the hang of using Emacs. They might even use Emacs regularly. They might have installed and configured a number of packages with lots of help from StackOverflow, coworkers, IRC, and so on. They are not yet comfortable with customization, so they find workflow descriptions and code snippets helpful.

Intermediate users are those who have figured out workflows that fit them well. They may have installed and configured a number of packages. They’re comfortable reading the documentation to figure out how to customize variables, and may even have written a few custom functions and keybindings. They’ve dived into the Emacs Lisp Reference Manual a few times, and know where to go to find examples and common idioms. Some have written tutorials to help beginners get started with useful packages or tips.

Advanced users are those who can imagine a new use for Emacs and make it happen. Here’s where you’ll find people with complex workflows built around combinations of packages, people who write custom modes and other tools, and people for whom hacking Emacs has become a recreational activity. They’re comfortable digging through the source and creating their own versions. They might even package the new code in order to share those features with others. Their code feels like Emacs code, following conventions and idioms.

What have I learned from Emacs Chats about how people move from one stage to the other?

Beginner to intermediate: “Oh, neat, Emacs can do that! I wonder how I can…”

Many people find it inspiring to see how other people have tweaked Emacs. Demos, examples, IRC conversations, and peeking over people’s shoulders are all great ways to find out that Emacs can do more than you think it does, which is an important motivator for moving from the beginner stage to the intermediate stage.

Useful resources could include:

  • Demos of interesting features that require some configuration, with notes on other things you might tweak along the way (exercises for the reader?)
  • Walkthroughs of advanced users’ workflows, since people pick up little tips that advanced users may forget to mention
  • Tips on how to read and modify code

Intermediate to advanced: “I’m in Emacs all the time anyway, so I might as well…”

Going from intermediate to advanced tends to involve a lot of practice in creating little tools, much rereading of the Emacs Lisp Reference and well-written package source code, and participation in the community (through mailing lists, IRC, StackOverflow, Github, etc). It can involve a commitment to use Emacs for way more than you might expect, possibly pushing it to be equivalent or superior to other tools.

People who maintain packages with active communities or who answer questions on mailing lists/newsgroups StackOverflow/Quora/IRC tend to grow a lot, too, since they actively learn from other people’s questions.

Useful resources could include:

  • Practical applications of concepts from the Emacs Lisp Reference
  • Tweaks using internal or obscure code
  • Posts that new features or “What if…” and walk through the code (and possibly the thought process as well)

Emacs is so big, so people probably have different levels of competence for different things. For example, one can be a beginner at Smartparens (memorized the keybindings for some common operations), while being an intermediate/advanced user of completions (have defined a custom completion backend).

What kinds of resources have helped you move from stage to stage? What would you like to see more of?

Emacs Chat: Oh no, my chat with Bodil Stokke didn’t get recorded!

Camtasia said it was recording the whole thing, and then when I went to edit it, I found that I only had the first 9 minutes. Extracting the .camrec didn’t get me any additional data. Nooooooooooooooooooooooooo! That’s what I get for doing an interview without two recording systems. Normally I use Google Hangout On Air’s built-in recording and Camtasia Studio as a backup, but since I was using appear.in, I only had Camtasia Studio running.

And it was a cool demo/discussion of Flycheck with Haskell (including better ways to do things), Tern, js2-mode, smartparens, tagedit, the XWidgets branch and running Reveal.js presentations inside Emacs, styling tips (Powerline, Nyancat, font-locking), the Emacs Lisp Reference…

We might be able to reschedule after I crawl out from under a rock and also hammer a solid backup screen recording strategy in place, although Bodil mentioned she’s open to using Google Hangout on Air even though it uses some proprietary plugins.

In the meantime:

http://twitter.com/bodil

https://gitlab.com/bodil/emacs-d/tree/master

Argh. Bodil, I’m so sorry!

Emacs Chat: Christopher Wellons

Christopher Wellons (nullprogram.com, github.com/skeeto/) started using Emacs nine years ago and has built all sorts of nifty customizations since, including something that plays Tetris for you. He demonstrates the benefits of having an HTTP server running inside Emacs by using Skewer to interact with a web browser and Impatient-mode to share his syntax-highlighted buffer through the Web. In addition, he covers foreign function interfaces, packages, and other good things. Check it out!

Links: 

Download the MP3