On this page:

A long, long weekend

How do I want to spend my leisure time? I’ve been thinking about that a bit because we have a long weekend, and I have much more discretionary time during the week than most people do.

W- and I are both homebodies. During normal weekends, we typically spend a day focused on cooking, cleaning, washing clothes, and taking care of other little things around the house. That still leaves some time for walks, gardening, reading, writing, and watching the videos that we borrow from the library. During long weekends, we usually take advantage of the extra time and energy by working on household projects or doing a deeper clean. W- tends to work long hours, so when he’s not busy with work or gym classes, I prefer to spend the time with him instead of hanging out with other friends. Life is short, after all.

I also have some time during the week, when most people are busy working. I’ve been using that time to read, learn, exercise, and explore. From time to time, I hang out with friends. Last Friday, two of my friends were hanging out at a park, so I decided to join them. It was a leisurely afternoon of sunshine, idle conversation, and ice cream. In the evening, we watched a movie which turned out to be free because of projector issues.

I’m not always keen on conversation, so I don’t particularly like scheduling things and I can be reluctant to meet up or chat. If I can guiltlessly change plans – to wander in and out as I want – I feel much better about it.

Then there’s discretionary time when I’m alone, too. I usually spend this reading, coding, writing, or drawing. I’ve been feeling a little scattered lately. It’s hard to latch onto a question and follow it. Focusing on building habits around exercise and gardening seems to be helping, and exploring recipes is fun too. Fortunately, there’s a lot to keep making slow progress on while cultivating curiosity…

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

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

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

Some conventions we’ll use:

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

After this module, you’ll be able to:

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

Adding more features to Emacs

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

(require 'org)

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

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

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

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

Installing packages

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Other Emacs Lisp files

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

(load "/path/to/file")

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

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

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

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

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

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

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

(require 'feature-name)

“Oh no! I have an error!”

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

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

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

(setq debug-on-error t)

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

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

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

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

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

Cannot open load file: …

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

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

Lisp error: (void-function …)

The code calls a function that has not been defined.

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

Symbol’s value as variable is void: _

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

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

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

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

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

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

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

Wrapping up the beginner course

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

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

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

More links:

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

This is the year I’m going to build an exercise habit

This year, I am going to become the sort of person who exercises regularly. I’m not particularly concerned about reaching a certain weight, but I’d like to improve my strength and endurance. W- is helping me ease into the learn-to-run program he did at work. I’m also starting from the first rung on the fitness ladder from The Hacker’s Diet. Small activities like these don’t take a lot of time, and the gradual progression will help me build confidence.

I’d also like to turn more exercise activities into ones that W- and I can share. Krav maga isn’t my cup of tea, but I think I’ll like jogging and walking with W-. We can stretch or do some weight-training while watching videos. Biking is fun, too.

What does making fitness part of me mean? I think it means being in tune with how things work, paying attention to the details and the changes. It’s probably like the way daily gardening has changed my experience of the backyard compared to when I dabbled in it. I’m looking forward to trying more things and learning more.

Identity is a big factor when it comes to maintaining good habits. When you make something part of who you are, it’s easier to keep doing it, and it’s harder to neglect it. Here are some of the other identity changes I’ve gone through:

  • I changed from someone who takes transit all the time to someone who bikes whenever she can.
  • I changed from someone who hated writing for school to someone who enjoys writing for this blog.
  • I changed from someone who grew up around household staff (cook, maids) to someone who cooks practically all her meals and takes care of her own chores.

I have the time, space, and support I need, and it’s good for me. I can see the results of good habits and the consequences of poor ones. And I’m going to do it without gym memberships or other things like that. We already have all the tools I need, so I just have to do it. =)

I notice I have cyclic interests

I learn about some topics in sprints, then let them go for a bit, and then come back to them. For example, my time logs for Emacs show:

  • June 2012
  • Mid-March to mid-April 2013
  • April-June 2014

2014-06-23 20_42_29-Emacs - quantified awesome

Oh. Actually, that’s an interestingly seasonal pattern. I hadn’t realized that the months lined up like that. (Although to be fair, I probably wasn’t tracking it as a category before May 2012, and it’s only very roughly lined up.) I wonder what it is…

Anyway, I feel myself shifting temporarily to other things. I know I’ll be back, but it’s just not at the forefront of my mind.

What am I thinking about instead? What am I learning more about? What am I spending more time on? Oh, the sparklines are surprisingly useful. I can just scroll down looking for patterns. Non-Emacs coding, apparently. Learning about other things. Playing video games, relaxing. Gardening. I’m spending nowhere near as much time biking as I used to, but I do spend more time walking.

Where would I like to direct my shifting interests and attention? I want to focus on building solid habits around health and fitness. That’s probably 15-30 minutes of exercise a day and preparing even better food (salads, variety). Once I’ve internalized those, I think I might circle back to Latin (I can mostly remember the declensions now, although I still make errors), and maybe either Japanese (so I can read and listen) or Cantonese (so that I can chat with W- and with the fellow gardener up the street). There’s drawing practice, too. Time to swing non-technical or non-computer-based for a bit? Hmm…

Fortunately, taking lots of notes along the way helps. I’m sure I’ll be back to this someday!

The garden is becoming part of my daily life

I’m in the garden almost every day. Almost 40 hours in total since the beginning of April. It’s my new favourite transition activity before dinner. I plant, water, pick off bugs. I’m beginning to learn what leaves feel like when they haven’t gotten enough water and when they have. The oregano, mint, cilantro, basil, and lettuce are growing much better than they did in previous years. None of the snow peas have made it indoors yet, since I’ve been eating them off the vine. The tomatoes, zucchini, winter melons, and bitter melons haven’t hit their stride yet, but maybe during the hotter months.

I like filling the salad spinner with cut-and-come-again leaves. I should let some of the plants go to seed so that I can collect them for the next batch, but it’s too tempting to snip off the flowers in order to keep the current batch going. I planted a salad mix, so I have no idea what some of these are. I know bok choy, spinach, arugula. Peppery and red-veined? Probably beet greens. I’m relying on frequency here. If there’s a lot of a type of plant, it grows in a somewhat regular formation, and I don’t already conclusively know it’s a weed, it’s probably okay to eat. So far, so good.

I have salad every other day or so. Today I had three small bowls of salad all by myself (W- had the other bowl). I shook up a quick Asian-style dressing in a small mason jar and sprinkled sesame seeds on top. We don’t normally buy those boxes of salad mix, since I feel guilty about not finishing them before they have to go. If it’s still growing, I don’t mind, although I try to harvest leaves before the slugs and leaf-miners get to them.

The salad garden is doing so much better this year compared to last year. Frequent watering and frequent harvesting, that’s probably the ticket. I should make pesto this week. Maybe Wednesday. Basil likes being harvested often, too. =) I’ve been picking flowers off every day, but there are definitely enough leaves here to make a good-sized batch of pesto.

Nom nom nom nom nom…

Weekly review: Week ending June 20, 2014

Much more sleep than average; work, too. Next week, I’ll probably focus on work and exercise. Still taking it relatively easy…

Blog posts

Sketches

Still no scans.

Link round-up

Next week. =)

Focus areas and time review

  • Business (37.2h – 22%)
    • Earn: E1: 2.5-3.5 days of consulting
    • Work on a 4clojure problem
    • Earn (23.4h – 62% of Business)
    • Build (11.0h – 29% of Business)
      • Drawing (2.0h)
      • Delegation (0.0h)
      • Packaging (0.0h)
      • Paperwork (2.8h)
    • Connect (2.8h – 7% of Business)
  • Relationships (1.5h – 0%)
    • Check progress for F2
    • Research real estate
    • Send claim correction along with note to insurance company
  • Discretionary – Productive (12.5h – 7%)
    • Emacs (2.7h – 1% of all)
      • Prep for call with Mickey Petersen
      • Take notes on people who are interested in taking course, process course steps – State “DONE” from “STARTED” [2014-06-12 Thu 20:50]
      • Summarizing the last meeting dates in Org Contacts
      • Take notes on people who are interested in taking course, process course steps
    • Add compost to back garden
    • Lasagna
    • Pizza
    • Writing (4.3h)
  • Discretionary – Play (10.1h – 6%)
  • Personal routines (26.3h – 15%)
  • Unpaid work (16.8h – 10%)
  • Sleep (63.5h – 37% – average of 9.1 per day)