Endless Parentheses

Ramblings on productivity and technical subjects.

profile for Malabarba on Stack Exchange

Leave the cursor at start of match after isearch

Have you ever stopped to think about why isearch leaves point at the end of the match? It does make some intuitive sense to leave you after the characters you have just typed, but that doesn’t make it the most practical behaviour.

This is something I’d never even given half a thought in the past, but it’s one of the first things a friend questioned me as he was diving into Emacs (yes, the same one as last week). Why not leave the cursor at the start of the match, instead of the end?

It’s great when someone’s fresh perspective shakes new ideas into my gradually-calcifying init file, so I immediately started looking for a way to do this. Fortunately, Google was quick to find me an answer, in the dotfiles of one Sylvain Rousseau. I should go through the entire file later to look for more snippets, but for the current purpose, the following is all we need.

(add-hook 'isearch-mode-end-hook
(defun endless/goto-match-beginning ()
  "Go to the start of current isearch match.
Use in `isearch-mode-end-hook'."
  (when (and isearch-forward
             (number-or-marker-p isearch-other-end)
             (not mark-active)
             (not isearch-mode-end-hook-quit))
    (goto-char isearch-other-end)))

After using this for a few days, I’ve already ran into a couple of cases where I would have preferred the original behaviour. Still, the net balance has been positive so far so it’s probably going to stay.

Update 23 Mar 2016

One alternative to the approach above is cutejumper's suggestion below, straight from the Emacs wiki. This will only leave point at the start of search if you exit the search with C-↵ instead of .

(define-key isearch-mode-map [(control return)]
(defun isearch-exit-other-end ()
  "Exit isearch, at the opposite end of the string."
  (goto-char isearch-other-end))

Tags: search, init.el, emacs,

comments powered by Disqus