Quick and dirty code folding

Code folding, the ability to hide code or text blocks in source or text files, is a feature present in most editors nowadays. Emacs has several modes providing this functionality with various degrees of sophistication: outline-mode, allout, hide-show or folding-mode come to mind. One can even use Emacs narrowing capabilities to cook up custom folding.

Over the years, i’ve used several of these packages (and perhaps i’ll share some tips on them in future postings). But i’ve noticed that, at the end of the day, i have usually little use for folding. I strive for short functions (whenever a function body extends a half-page, i feel a strong refactoring urge), and as a consequence i seldom need to hide their bodies, nor to mention blocks within them.

There is however one folding trick that i use all the time. I often want to hide all function bodies in a file, to get a quick summary of it contents. As it happens, you don’t need any package or extra configuration for that. Just go to any source file, type

        M-1 C-x $

and magic happens! As usual, it’s white magic: C-x $ will bring your code back.

We can use Emacs’ help system to discover what’s going on: C-h k C-x $ tells us that the above key combination is calling set-selective-display, a function that takes one numerical argument (the M-1 prefix passes 1 as the value of that argument) and, unsurprisingly, sets the variable selective-display to the value of that argument. I’ll let you read about the details in Emacs help itself, although i’m sure that by now you get the idea.

If you find yourself setting and unsetting selective-display as often as i do, next thing will be defining a handy keyboard shortcut, right?

(defun jao-toggle-selective-display ()
  (set-selective-display (if selective-display nil 1)))

(global-set-key [f1] 'jao-toggle-selective-display)

or we can also use an optional numerical prefix (with 1 as default) with a little modification:

(defun jao-toggle-selective-display (column)
  (interactive "P")
   (if selective-display nil (or column 1))))

Happy folding!


Enhancing Gmail browsing

I use pretty often emacs-w3m to read technical HTML docs within Emacs. When you’re programming, reading manuals, blogs or tutorials without leaving your operating system editor is all but convenient.

Browsing EmacsWikiActually, emacs-w3m does a very, very good job rendering even moderately complex sites, and i’ve been known to use it as my default browser. It is not limited to plain text (Emacs groks images these days), has tabs (shameless plug: take a look at my w3m-session package to add session management) and renders tables and other HTML constructs nicely. And of course, navigating sites like the Emacs wiki without leaving Emacs is just the way to go. Besides, if you don’t like how a page looks in emacs-w3m, opening it in your graphical browser is just a keystroke away (C-h w w3m-view-url-with-external-browser to discover it).

Gmail's login pageI also have usually open a tab with my Gmail account, to quickly check my email every now and then. As you can see in the screenshot on the right, emacs-w3m renders Gmail pages very decently (hint: you’ll need to activate cookies to use Gmail, by setting the variable w3m-use-cookies to a non-nil value). But of course the Gmail page i visit more frequently is the Spam tab, and the operation i want to perform more frequently in there is to mark all the mails and press ‘Delete Forever’. But alas, w3m does not support javascript, and the handy ‘Select All’ link is missing. Obviously, tabbing your way to every single spam mail to select it would be a pain, and one is tempted to follow the advice at the top of the page about a better Gmail experience.

GmailBut wait, this is not your regular browser. We’re inside Emacs, and in here, when we need something, we usually just hack it and keep on working. After all, what we need to do is quite simple: look for occurrences of ‘[ ]’ in the buffer, click them, and leave the pointer over the ‘Delete forever’ button, ready to send all our spam where it deserves. As it happens, our life is even easier thanks to the functions provided by emacs-w3m. w3m-form-goto-next-field allows easy navigation inside a form, and w3m-view-this-url will perform a click for us. So here we go: let’s write an Elisp command that looks for unmarked checkboxes and clicks them:

  (defun jao-w3m-gmail-mark-all ()
    (when (search-forward "[ ]" nil t)
      (backward-char 4)
      (while (looking-at " \\\\]")

That’s it. After evaluating this definition, we just M-x jao-w3m-gmail-mark-all to mark all our mails. Of course, a keyboard shortcut will come in handy:

  (define-key w3m-mode-map (kbd "C-ck") 'jao-w3m-gmail-mark-all)

and now we only need to press C-ck to get the job done. While we’re at it, it would be nice if typing a prefix would unmark mails instead of marking it, wouldn’t it? Well, that only needs a few tweaks in our original definition:

  (defun jao-w3m-gmail-mark-all (unmark)
    (interactive "P")
    (when (search-forward (if unmark "[*]" "[ ]") nil t)
      (backward-char 4)
      (while (looking-at (if unmark "\\\\*\\\\]" " \\\\]"))

Now, C-ck will mark, and C-uC-ck will unmark.

As you can see, the limit is just your imagination. For instance, when i’m reading non-spam, i usually mark some mails for deletion. Then i need to go to the ‘More actions…’ menu, select the ‘Delete’ operation and press ‘Go’. Hmm, a bit of a chore. Elisp to the rescue:

  (defun jao-w3m-gmail-delete ()
    (when (search-forward "[More Actions" nil t)
      (search-forward "Trash")

Admittedly, these little extensions are far from earth-shattering, but i think that they illustrate quite well what having an extensible system means. You control your environment and adapt it to your particular needs, often building upon functionality provided either by the system or by some other extension library. Another nice example of extensibility at work is my w3m-session package: i wanted persistent sessions, so i wrote an extension. And it was easy, thanks to the nice work of the emacs-w3m hackers and, let’s not forget, the dynamic nature of Elisp.

In addition, the programmer in me finds tweaks like this a continuous source of fun. You know, that fuzzy warm feeling… but i digress. Happy hacking!

Editing your file names

In my experience, dired is one of the most underused modes of Emacs. Just C-xC-f to any directory in your hard disk and you’ll be presented with a list of its files and directories. One can browse this list, and execute all kinds of commands and transformations on them. If you’ve never done that before, just give it a try, and look at the menubar for a list of nifty things you can do inside dired. There’re several ways to mark files and operate on them afterwards: for instance, just type A to find inside the selected files any regexp, or Q to search and substitute.

One of my favorites dired functionalities is wdired-change-to-wdired-mode. When you invoke this interactive function (using M-x wdired-change-to-wdired-mode), the dired buffer becomes editable. That is, you can go around and edit directly the filenames as you would edit any other emacs text buffer. And that means you have all the regular editing commands at your disposal. For instance, if i enter wdired-mode in my emacs configuration directory:


and want to change the name of all those jao-*.el files to, say, jao-config-*.el, all i have to do is to search and replace as i would do in any other text file (i.e., using M-%). Or maybe put the cursor on the first file name, mark (C-SPC), got to the end of the jao-files list, put my cursor after the last dash (as shown in the figure), and use C-xrt to replace the text in the marked rectangle. When you’re happy editing the buffer, just press C-cC-c and all your changes will be reflected in the underlying files.


Define your own keywords

These days i’m programming in and learning about Objective-C and Cocoa. Yesterday, i stumbled upon a blog entry providing The Cocoa Memory Management Regular Expression, that is, a simple regular expression that matchs (most of) the OpenStep functions allocating memory that must be explicitly de-allocated. Here’s the regexp in question:


An immediate application of this regexp is, of course, providing some sort of visual warning to remind you that memory allocation is at play. In Emacs, a way to do that is to fontify the keywords in question using an special face (font-lock-warning-face, for instance). As it happens, this is very easy to do: just call font-lock-add-keywords with the appropriate parameters:

(font-lock-add-keywords 'objc-mode
   '(("\\\\<retain\\\\>" 0 font-lock-warning-face)
     ("\\\\(\\\\<\\\\(alloc\\\\|new\\)\\\\w*\\\\)[]:]" 1 font-lock-warning-face)
     ("\\\\(\\\\w*[cC]opy\\\\w*\\\\)[]:]" 1 font-lock-warning-face)))

Each entry in the association list above consists of a regular expression, the group inside it to be hightlighted (0 means the whole match) and the face used for the highlighting. C-h f font-lock-add-keywords RET for extended help, including further examples (for instance, to highlight your to-dos).

Oh my gawd, it’s full of links!

I’ve been using emacs-muse during several years now to keep a personal knowledge base in the form a local wiki. To me, the killer feature of emacs-muse is its ability to create links to other documents, mails, URLs or any other resource accessible via Emacs (which is to say, virtually any resource). Combined with planner mode, one has a pretty good PIM system that, among many other virtues, is based on plain text files (and, therefore, is easily indexable) and is as portable as Emacs itself.

Emacs-muse is pretty neat, but not perfect. My main quibble with it is that it’s a major mode. That means that, in order to create a link to other resource, you must be in a ‘muse’ document (a sort of wiki page). But wouldn’t if be nice if you could create links in any document. Say you’re writing source code an want to reference another file in the project, or an HTML page detailing an API you’re using, or a PDF with your projects requirements. Or you’re writing an essay in LaTeX and want to link to a text file of related notes, or an email, or… you get the idea. What I’m asking for is, in emacs parlance, a minor mode providing the linking functionality.

As it often happens in the Emacs universe, my prayers have been heard. Linkd is exactly the package i wanted. In the words of its author, David O’Toole, “linkd-mode is a hypertext system for organizing and interlinking all resources available to GNU Emacs. It can be used to make a “personal web” out of all your text files—regardless of file format or major mode.” In addition, linkd trims off some of the features I rarely use in emacs-muse, namely, the publishing functionality.

Although still in alpha, linkd looks already pretty good, with such niceties as proxy icons in links, as shown in this picture:

Linkd in action

Other interesting features of linkd include its ability to mark blocks inside any file that can be link targets, and its tagging functionality. In addition, the list of planned features (searching and indexing, summarize, synthesize links a la remember-mode) makes linkd a package definitely worth exploring and keeping an eye on.

The Ghost in the Lisp Machine

A friend of mine uses to say that Emacs fills our yearning for a Lisp Machine. I tend to agree with him: Emacs is not just an editor, but a full integrated environment where you can perform virtually any imaginable task; and, most importantly, the inner workings of the system are open to you to explore and extend. Using, for extra fun, Lisp. No, i don’t think that Elisp is the nicest Lisp incarnation around, but is far better than, say, C, and i still prefer it to other scripting languages. Moreover, the awesome range of libraries at your disposal makes up for many of the deficiencies in the language.

Living in Emacs is addictive. Imagine an operating system where you can switch from writing code to browsing the web or chatting without leaving a consistent environment, with the same set of commands and shortcuts. Imagine a set of integrated applications where data is seamlessly shared, where any single functionality can be tweaked, extended and adapted to your particular needs. Where everything is easily scriptable. Imagine, in additon, that the environment provides powerful and complete interactive self-documentation facilities with which the user can find out what is available. I have yet to find an operating system providing such an integrated environment. Not even Mac OS X, where AppleScript support is often lacking and system services are underused.

Of course, the key ingredient here is Emacs’ extensibility. Far from being an afterthought or simply one of its features, extensibility is the central aspect of Emacs’ architecture. Actually, the whole point of this post is to recommend you reading Richard Stallman’s 1981 essay EMACS: The Extensible, Customizable Display Editor, which explains much better than I could the strong points of Emacs design, i.e., those traits that make Emacs more, much more, than just an editor. From the horse’s mouth:

Extensibility means that the user can add new editing commands or change old ones to fit his editing needs, while he is editing. EMACS is written in a modular fashion, composed of many separate and independent functions. The user extends EMACS by adding or replacing functions, writing their definitions in the same language that was used to write the original EMACS system. We will explain below why this is the only method of extension which is practical in use: others are theoretically equally good but discourage use, or discourage nontrivial use.
User customization helps in another, subtler way, by making the whole user community into a breeding and testing ground for new ideas. Users think of small changes, try them, and give them to other users–if an idea becomes popular, it can be incorporated into the core system. When we poll users on suggested changes, they can respond on the basis of actual experience rather than thought experiments.

The article goes on explaining the organization of the Emacs system, how it depends on its interpreter, Elisp’s main features and how built-in self-documentation is provided. Also interesting is the list of related systems at the end of the essay: Lisp machines, LOGO, MacLisp and Smalltalk. We’re definitely in good company!

The Lord of Elisp

Knuth’s Tex for the Math-kings of sigma, and pi,
Unix vim for the Server-lords with their O’Reilly tomes,
Word for Mortal Men doomed to die,
Emacs from the Bearded One on his Gnu throne,
In the land of Stallman where free software lies.
One Emacs to rule them all. One Emacs to find them,
One Emacs to take commands and to the keystrokes bind them,
In the land of Stallman, where free software lies.

(Raffael Cavallaro, gnu.emacs.help)

Posted in Fun. 3 Comments »