Property Lists In Emacs

Xah Lee has a nice post up with a function that fixes what he sees as some problems with the default Emacs case-changing commands. Apparently, our use cases are different because I’m not bothered by the default behavior. Still, the function is a nice one and you may find that it meets your needs.

One of the techniques that Lee uses is to maintain a bit of state in a property list. Property lists are a feature of many Lisps and although they aren’t used a lot, they are often just what you need. One way of thinking about property lists is that they are very much like association lists (alists) that are attached to a symbol. (You can have more general, free-standing property lists too but we won’t consider them here). They are a list of property-value pairs that can be set with the put command or read with the get command.

So what are property lists used for? One common use is to control disabled commands. For example, in my post on Using The Emacs save-restriction Special Form, I mentioned that narrow-to-region is disabled by default and that you should add

(put 'narrow-to-region 'disabled nil)

in your .emacs or init.el file to enable it. The narrow-to-region symbol has a set of properties, one of which is disabled. The result of the put is to set that property to nil. By default, the property is t. Before narrow-to-region is executed, Emacs checks its property list to see if the disabled property is t. If it is, Emacs tells you that the command is disabled and gives you some choices in how to proceed.

Another example, which I use a lot, is to control indentation. For example, I have a Scheme implementation of the Common Lisp dolist macro that we’ve discussed before. The problem is that Emacs doesn’t know how to indent the macro correctly because it’s not part of standard Scheme. Fortunately, I can tell Emacs what to do by adding the scheme-indent-function property and setting it to 1. I do that by adding

(put 'dotimes 'scheme-indent-function 1)

to my init.el file.

You might think that properties are restricted by Elisp to just those used by Emacs itself but that is not the case. You can attach any property you like to any symbol. That brings us to Lee’s function. Because he wants to be able to step through 3 possibilities (all lower, initial cap, all upper) he needs to remember what the last state was. He does that by adding a state property to his function, toggle-letter-case. Take a look at his post to see the details—the code is pretty easy to follow.

Summary

Command Action
(put 'symbol 'prop val) Set the prop property of symbol to val
(get 'symbol 'prop) Get the value of symbol‘s property prop
(symbol-plist 'symbol) Return the property list of symbol
This entry was posted in Programming and tagged . Bookmark the permalink.