2017-02-18 Using isearch-string on exit from isearch

Recently, I wanted my function, which asks the user for some string, use the isearch term as the default. That’s easy – the variable isearch-string holds the term searched (note that it may be a plain string or a regex!). The problem was, I wanted that to be the default only when I invoked my command from isearch (sort of what M-% does when called from within isearch). The way M-% does its magic when invoked during isearch is simple: in isearch-mode-map, that key is bound to isearch-query-replace and not the usual query-replace. I didn’t want anything like that, though: I wanted my command to be callable via M-x.

I thought about checking whether last-command was isearch-forward or isearch-backward and if yes, using isearch-string. The problem is, last-command is usually something else, like isearch-printing-char or anything else from isearch-mode-map.

I know about two ways of overcoming that. The hackery way is to apply this check: (string-match "^isearch-" (symbol-name last-command)). Slightly risky, but works due to the way Emacs functions are traditionally named.

Probably the cleaner way is to use isearch-mode-end-hook, to which I can add a function setting last-command to something like isearch:

(add-hook 'isearch-mode-end-hook (lambda () (setq last-command 'isearch)))

(Such command does not exist, but we can set last-command to whatever symbol we want!) Then we can check for that exact symbol in our command. The expression below evaluates to the input given by the user, which is equal to the last isearch term when isearch was the thing the user was doing when evaluating and s?he just pressed RET.

(let ((default (when (eq last-command 'isearch)
  (read-string (if default
		   (format "Your input [%s]: " default)
		 "Your input: ")
		   nil nil default))

I’m not sure whether this won’t break anything, but I don’t think so. Anyway, I’m starting using it; if anything breaks, I’ll update this post.

Thanks to Michael Heerdegen for his suggestion on the help-gnu-emacs list.

CategoryEnglish, CategoryBlog, CategoryEmacs