Monday, March 11, 2013

Automatic bookmarking of locations in Emacs

One of the things I find myself doing over and again in Emacs is returning to the last place I was editing a file. Sometimes that's because I've killed a buffer before I should have done (thinking I was finished), sometimes it's because I've exited Emacs and sometimes it's because I simply return to something a day or two later.

Since it was incredibly annoying to have to search for the last place I was working I created a simple system in Emacs that automatically remembers where I was and then lets me jump there by hitting C-l (obviously you can choose whatever key binding you like, I choose that because I never use C-l for its real purpose).

The automatic bookmarking works by using three Emacs hooks: when kill-buffer-hook or after-save-hook are called it records the current line number of the buffer in an internal hash table; when kill-emacs-hook is called it makes sure that the line number in each current buffer is saved and serializes the hash table to ~/.emacs.d/last-location.

There are probably lots of improvements wizard elisp hackers can make, but here's what works for me (you need my-emacs-d to be the path to your .emacs.d directory):

PS As a commenter points out there's already saveplace.el that I had failed to find before writing my own.


Unknown said...

What does this give you that saveplace.el doesn't?

Mike Kazantsev said...

I find myself editing mostly some narrow parts of a file within a specific commit - like adding a method here and import there, or changing stuff in that function - provided code doesn't force me to go over whole file and tweak all references of something.

So basically if emacs would track where previous changes in file occurred, and be able to jump up/down between these, that's all I really need in most cases.


Not only it allows one to jump between these "hot spots", but also neatly highlights these.