Categories: geek » emacs » elisp

View topic page - RSS - Atom - Subscribe via email

Org Mode: Inserting a function definition

| elisp, emacs, org, elisp

While nudging jcs to add a definition of jcs-insert-url to the blog post about Making Things Easier, I realized it might be handy to have a quick function for inserting a function definition without thinking about where it's defined. This tries to use the definition from the source, and it can fall back to using the stored function definition if necessary. There's probably a better way to do this, but this was small and fun to write. =)

Naturally, I used it to insert itself:

(defun my/org-insert-defun (function)
  "Inserts an Org source block with the definition for FUNCTION."
  (interactive (find-function-read))
  (let* ((buffer-point (condition-case nil (find-definition-noselect function nil) (error nil)))
         (new-buf (car buffer-point))
         (new-point (cdr buffer-point))
         definition)
    (if buffer-point        
      (with-current-buffer new-buf ;; Try to get original definition
        (save-excursion
          (goto-char new-point)
          (setq definition (buffer-substring-no-properties (point) (save-excursion (end-of-defun) (point))))))
      ;; Fallback: Print function definition
      (setq definition (concat (prin1-to-string (symbol-function function)) "\n")))
    (insert "#+begin_src emacs-lisp\n" definition "#+end_src\n")))

Using your own Emacs Lisp functions in Org Mode table calculations: easier dosage totals

Posted: - Modified: | emacs, org, elisp

UPDATE 2015-06-17: In the comments below, Will points out that if you use proper dates ([yyyy-mm-dd] instead of yyyy-mm-dd), Org will do the date arithmetic for you. Neato! Here’s what Will said:

Hi Sacha. Did you know you can do date arithmetic directly on org’s inactive or active timestamps? It can even give you an answer in fractional days if the time of day is different in the two timestamps:

| Start                  | End                    | Interval |
|------------------------+------------------------+----------|
| [2015-06-16 Tue]       | [2015-06-23 Tue]       |        7 |
| <2015-06-13 Sat>       | <2015-06-15 Mon>       |        2 |
| [2015-06-10 Wed 20:00] | [2015-06-17 Wed 08:00] |      6.5 |
#+TBLFM: $3=$2 - $1 

Here’s my previous convoluted way of doing things… =)
—-

I recently wrote about calculating how many doses you need to buy using an Org Mode table. On reflection, it’s easier and more flexible to do that calculation using an Emacs Lisp function instead of writing a function that processes and outputs entire tables.

First, we define a function that calculates the number of days between two dates, including the dates given. I put this in my Emacs config.

(defun my/org-days-between (start end)
  "Number of days between START and END.
This includes START and END."
  (1+ (- (calendar-absolute-from-gregorian (org-date-to-gregorian end))
         (calendar-absolute-from-gregorian (org-date-to-gregorian start)))))

Here’s the revised table. I moved the “Needed” column to the left of the medication type because this makes it much easier to read and confirm.

| Needed | Type         | Per day |      Start |        End | Stock |
|--------+--------------+---------+------------+------------+-------|
|     30 | Medication A |       2 | 2015-06-16 | 2015-06-30 |     0 |
|      2 | Medication B |     0.1 | 2015-06-16 | 2015-06-30 |   0.2 |
#+TBLFM: @2$1..@>$1='(ceiling (- (* (my/org-days-between $4 $5) (string-to-number $3)) (string-to-number $6)))

C-c C-c on the #+TBLFM: line updates the values in column 1.

@2$1..@>$1 means the cells from the second row (@2) to the last row (@>) in the first column ($1).  '  tells Org to evaluate the following expression as Emacs Lisp, substituting the values as specified ($4 is the fourth column’s value, etc.).

The table formula calculates the value of the first column (Needed) based on how many you need per day, the dates given (inclusive), and how much you already have in stock. It rounds numbers up by using the ceiling function.

Because this equation uses the values from each row, the start and end date must be filled in for all rows. To quickly duplicate values downwards, set org-table-copy-increment to nil, then use S-return (shift-return) in the table cell you want to copy. Keep typing S-return to copy more.

This treats the calculation inputs as strings, so I used string-to-number to convert some of them to numbers for multiplication and subtraction. If you were only dealing with numbers, you can convert them automatically by using the ;N flag, like this:

| Needed | Type         | Per day | Days | Stock |
|--------+--------------+---------+------+-------|
|      6 | Medication A |       2 |    3 |     0 |
|      1 | Medication B |     0.1 |    3 |   0.2 |
#+TBLFM: @2$1..@>$1='(ceiling (- (* $3 $4) $5)));N

Continuous integration and code coverage for Emacs packages with Travis and Coveralls

Posted: - Modified: | emacs, elisp

Do you maintain an Emacs package hosted on Github? Would you like to get those confidence-building, bragging-rights-granting, other-developers-inspiring build: passing and coverage: 100% badges into your README file?

It turns out that this is pretty easy with ERT, Cask, Travis CI, undercover.el, and Coveralls.io.

  1. Log on to Travis and enable continuous integration for your repository.
  2. Log on to Coveralls.io and enable coverage testing for your repository.
  3. Set up a git branch, since you'll probably be making lots of small commits while you smooth out the testing workflow.
  4. Define your tests with ERT. See https://github.com/abo-abo/tiny/blob/master/tiny-test.el for an example. For undercover support, you'll want to include something like:
    (when (require 'undercover nil t)
      (undercover "tiny.el"))
    
  5. Define your dependencies with Cask. Include undercover. For example, here's a simple Cask file:
    (source gnu)
    (source melpa)
    
    (development
      (depends-on "undercover"))
    
  6. Add a .travis.yml that specifies how to test your package on Travis. For example, see this .travis.yml and Makefile.
  7. Commit and push.
  8. Check your repository status in Travis to see if it ran properly.
  9. Check your coverage status in Coveralls.io to see if it displayed properly.
  10. Get the badge code from Travis and Coveralls, and add them to your README (probably using Markdown). You can get the badge code from Travis by clicking on your build status badge next to your repository name. Coveralls has prominent instructions for getting your badge. Yay!

Incidentally, if you want to see your test coverage locally, you can (require 'testcover) and then use testcover-this-defun or testcover-start to instrument the macros and functions for coverage. Run your tests, then use testcover-mark-all to look at the results. See the documentation in testcover.el to find out what the coloured overlays mean. Edebug has a test coverage tool too, so you can explore that one if you prefer it.

Additional notes on testing:

Resources:

View or add comments (Disqus), or e-mail me at sacha@sachachua.com

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

Posted: - Modified: | elisp, emacs, elisp

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 – sacha@sachachua.com. 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:

View or add comments (Disqus), or e-mail me at sacha@sachachua.com

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

Posted: - Modified: | elisp, emacs, elisp

“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") "you@example.com")
(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!
View or add comments (Disqus), or e-mail me at sacha@sachachua.com

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

| elisp, emacs, elisp

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?

View or add comments (Disqus), or e-mail me at sacha@sachachua.com

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

Posted: - Modified: | elisp, emacs, elisp

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 (sacha@sachachua.com).
  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.
View or add comments (Disqus), or e-mail me at sacha@sachachua.com