Categories: geek » emacs » elisp

View topic page - RSS - Atom - Subscribe via email

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.

Learn Emacs Lisp by reading Emacs Lisp

Posted: - Modified: | emacs, elisp

Learning Emacs Lisp can help you really tweak your Emacs environment to fit you, saving time, smoothening out frustrations, and making things easier. Reading code is an essential part of learning how to code. By reading other people’s code, you’ll not only discover interesting syntax and library features, but you’ll also start absorbing the idioms – the ways of doing things. (This is why it’s important to read good, well-formatted code.)

Where to find code

You can use C-h k (describe-key) to explore the code behind keystrokes, menu items, and mouse actions. If the source code is installed, you should see a hyperlink in the information window that appears. It’s a good idea to install the Emacs Lisp source code for Emacs.

If you know the name of the function you’re interested in, C-h f (describe-function) will link to the source code and describe the function.

You can find lots of other Emacs code snippets on http://emacswiki.org and in blog posts on http://planet.emacsen.org . gnu.emacs.sources and other Emacs-related newsgroups or mailing lists are useful, too.

How to understand code

At first glance, Emacs Lisp looks like a mess of parentheses and strange incantations. setq? defun? cdar?

This is true at second glance, too.

Read through the Emacs Lisp intro manual either online or in Emacs (C-h i m Emacs Lisp Intro). You’ll probably understand very little the first few times through. This is okay. All you need to do is get a vague idea of what things are called so that you can look them up when you need to.

Now read your code again. Slightly of it should make sense.

Skim the Emacs Lisp manual, too. This is a reference, so you’ll understand even less of it as an Emacs Lisp newbie, but it’s good for picking up terms.

You don’t need to understand all of Emacs Lisp in order to take advantage of other people’s configuration snippets. You’ll learn things along the way.

Make liberal use of C-h f to describe functions and C-h v (describe-variable) to investigate. You can jump to function definitions with find-function, which is worth binding to a keystroke. For example, to map F8 to find-function temporarily, use M-x global-set-key RET F8 find-function.

How to step through code

Edebug is an interactive debugger for Emacs so that you can step through the code instead of guessing what the code will do. (Edebug documentation) Use M-x edebug-defun to prepare the function you’re interested in, then run the function. Press SPC to step through the code, e to evaluate expressions (you can use this to find the values of numbers), h to continue until the specified point, b to set a breakpont, g to execute until a breakpoint, and q to stop debugging.

Super awesome.

How to make code your own

You can copy code to the *scratch* buffer or another file, tweak it a little, evaluate or edebug the code, and see what changed. If you like your changes, you can:

  • rename the function and add it to your configuration file,
  • use advice to modify the existing function, or
  • redefine the function (keeping the name as-is) and adding it to your configuration file. (This can lead to weird behaviour, so do this carefully!)

Enjoy!

Other reading:

EmacsWiki: Learn Emacs Lisp

Thanks to bl3u for the nudge to write about this!

Emacs Gnus: Filter Spam

Posted: - Modified: | emacs, wickedcoolemacs, elisp, gnus, mail

(draft for an upcoming book called Wicked Cool Emacs)

Ah, spam, the bane of our Internet lives. There is no completely
reliable way to automatically filter spam. Spam messages that slip
through the filters and perfectly legitimate messages that get
labelled spam are all part of the occupational hazards of using the
Internet.

The fastest way to filter spam is to use an external spam-filtering
program such as Spamassassin or Bogofilter, so your spam can be
filtered in the background and you don’t have to spend time in Emacs
filtering it yourself. In an ideal world, this would be done on the
mail server so that you don’t even need to download unwanted
messages. If your inbox isn’t full of ads for medicine or stocks, your
mail server is probably doing a decent job of filtering the mail for
you.

Server-based mail filtering

As spam filtering isn’t an exact science, you’ll want to find out how
you can check your spam folder for misclassified mail. If you download
your mail through POP, find out if there’s a webmail interface that
will allow you to check if any real mail has slipped into the junk
mail pile. If you’re on IMAP, your mail server might automatically
file spam messages in a different group. Here’s how to add the spam
group to your list of groups:

  1. Type M-x gnus to bring up the group buffer.
  2. Type ^ (gnus-group-enter-server-mode).
  3. Choose the nnimap: entry for your mail server and press RET (gnus-server-read-server).
  4. Find the spam or junk mail group if it exists.
  5. Type u (gnus-browse-unsubscribe-current-group) to toggle the subscription. Subscribed groups will appear in your M-x gnus screen if they contain at least one unread message.

Another alternative is to have all the mail (spam and non-spam)
delivered to your inbox, and then let Gnus be in charge of filing it
into your spam and non-spam groups. If other people manage your mail
server, ask them if you can have your mail processed by the spam
filter but still delivered to your inbox. If you’re administering your
own mail server, set up a spam filtering system such as SpamAssassin
or BogoFilter, then read the documentation of your spam filtering
system to find out how to process the mail.

Spam filtering systems typically add a header such as “X-Spam-Status”
or “X-Bogosity” to messages in order to indicate which messages are
spam or even how spammy they are. To check if your mail server tags
your messages as spam, open one of your messages in Gnus and type C-u
g (gnus-summary-show-article) to view the complete headers and
message. If you find a spam-related header such as X-Spam-Status, you
can use it to split your mail. Add the following to your ~/.gnus:

 (setq spam-use-regex-headers t) ;; (1)
 (setq spam-regex-headers-spam "^X-Spam-Status: Yes")   ;; (2)
 (require 'spam) ;; (3)
 (spam-initialize) ;; (4)

This configures spam.el to detect spam based on message
headers(1). Set spam-regex-headers-spam to a regular expression
matching the header your mail server uses to indicate spam.(2) This
configuration should be done before the spam.el library is loaded(3)
and initialized(4), because spam.el uses the spam-use-* variables to
determine which parts of the spam library to load.

In order to take advantage of this, you’ll also need to add a rule
that splits spam messages into a different group. If you haven’t set
up mail splitting yet, read qthe instructions on setting up fancy mail
splitting in “Project XXX: Organize mail into groups”. Add (:
spam-split) to either nnmail-split-fancy or nnimap-split-fancy,
depending on your configuration. For example, your ~/.gnus may look
like this:

(setq nnmail-split-fancy
'(
;; ... other split rules go here ...
(: spam-split)
;; ... other split rules go here ...
"mail.misc")) ; default mailbox

(draft for an upcoming book called Wicked Cool Emacs, more to come!)