2021-06-28 Going to where you were when visiting a file

I don’t close my Emacs very often. Basically, I start it right after I turn my computer on and log in, and usually the only reason for me to close Emacs is when I update the system (given that use Arch Linux, this is actually pretty often, say once every week or two). Usually, after a few days’ worth of work, I have most of files I work on open, and I’m accustomed to just switching to a suitable buffer to continue something at the point I left it a day (or several days) ago.

Of course, I lose that information when I close Emacs. There are a few known solutions to that – the session package comes to mind, but there is also the built-in desktop.el – but I felt like cooking my own, just for a bit of fun and showing how you could implement something like this. In fact, I used desktop.el for some time, but I had mixed feelings about it. It is useful, don’t get me wrong, but I was sometimes afraid of leaving some file with passwords or other secrets open. Also, I tend to have quite a lot of open buffers and starting fresh somehow feels more “hygienic”. (Now that I think of it, all my “arguments” boil down to this one: I’m too lazy to configure desktop.el to my liking. Maybe I’m just getting old. I think I really should start using it again.)

Anyway, let’s code this nice feature that when you visit a file containing the string HERE (in capital letters), the point will automatically jump there. (In other words, you can manually mark the place you wish to return to in buffers you want this to work.) It is pretty obvious that we would like to find some hook firing when Emacs visits a file. Saying M-x apropos RET visit hook RET didn’t show anything interesting, but M-x apropos RET find hook found find-file-hook. (By the way, a nice tip is to issue such commands in a fresh emacs -Q session, since you are usually only interested in built-in features like this, and various packages tend to install a lot of things which might match your search but be of no interest for you.)

So, here’s our thing.

(defun find-next-here-mark ()
  "Find the string HERE in the current buffer."
  (let ((case-fold-search nil))
    (search-forward "HERE" nil t)))
(add-hook 'find-file-hook #'find-next-here-mark)

And that’s it for today.

CategoryEnglish, CategoryBlog, CategoryEmacs