Buffer Menu Sorting in Emacs 24

Upgrading to Emacs 24 a few months ago was mostly seamless. I only encountered one issue that was difficult to fix and has been lingering until today, when I finally got annoyed enough to devote some time to researching and fixing it.

I like having the Buffer Menu configured to always be sorted by filename. In Emacs 23, you could simply set the Buffer-menu-sort-column variable and you were done. That variable isn’t recognized in Emacs 24, despite claims to the contrary on various web sources.

If you look at the code in buff-menu.el, it was rewritten in 24 to use tabulated-list for its display mechanics. There is a Buffer-menu-sort function which is an alias to tabulated-list-sort. Once you are in the *Buffer List* buffer, you can call Buffer-menu-sort interactively using a prefix argument to specify the column: type ‘M-5 M-x Buffer-menu-sort’ to sort by filename. This works very nicely. Doing it a second time reverses the sort order.

So the challenge is to automate this, calling Buffer-menu-sort only once, automatically at the time a *Buffer List* buffer is first created. The mode will keep its entries sorted going forward.

I tried doing this by advising the list-buffer function, and having a buffer local variable keep track of whether I had already called Buffer-menu-sort once before. This didn’t work: something seemed to be resetting my buffer local variable, but I couldn’t figure out what.

The solution I ended up with is below. The advice function checks a variable called jc-buffer-menu which stores the current Buffer Menu buffer, and calls Buffer-menu-sort as needed. Put the code in your .emacs file, and you’re done.