ErgoEmacsEmacsLispBlogEmacsLispBuy Tutorial
Web Hosting by 1&1

Emacs Incremental Search Suggestions

Xah Lee, ,

This page document a problem with emacs's incremental search feature, with suggested solution.

Emacs's “isearch” has some problems. Suppose you have this line:

the delete-current-file is quite useful to me.

and your cursor is on the second dash. You want to search the next occurrence of the word “delete-current-file”. You have to first move your cursor to the beginning of the word, then press a key for isearch, then another key to select “delete”, another to extend selection to “current”, another to “file”, then press isearch again to find the next occurrence. That's 7 operations. In GNU emacs, it's 【Alt+b Alt+b Ctrl+s Ctrl+w Ctrl+w Ctrl+w Ctrl+s】. In vim, it's just a single key press.

highlight-symbol minor mode

Today i found several solutions to this. I think one of the best is the package highlight-symbol by Nikolaj Schumacher, at: nschum.de highlight-symbol.

Note that Nikolaj Schumacher has contributed to the extend-selection command in ErgoEmacs, and has wrote several other elisp packages. His code i trust.

To install, place the package at your emacs library load path, for example:

~/.emacs.d/highlight-symbol.el

Create the 〔.emacs.d〕 dir if it doesn't exist already.

Then, put the following in your emacs init file then restart emacs.

(require 'highlight-symbol)
(global-set-key (kbd "<f10>") 'highlight-symbol-at-point)
(global-set-key (kbd "<f11>") 'highlight-symbol-prev)
(global-set-key (kbd "<f12>") 'highlight-symbol-next)

Then, F10 will highlight all occurrences of the current word. F11 again removes the highlights. F12 will move cursor to the next occurrence, and F11 for previous.

isearch-forward-at-point

Another solution is a command isearch-forward-at-point. from platypope.org blog.

When you want to start isearch on the current word, just call isearch-forward-at-point. You can give it a hotkey too.

;; I-search with initial contents.
;; original source: http://platypope.org/blog/2007/8/5/a-compendium-of-awesomeness
(defvar isearch-initial-string nil)

(defun isearch-set-initial-string ()
  (remove-hook 'isearch-mode-hook 'isearch-set-initial-string)
  (setq isearch-string isearch-initial-string)
  (isearch-search-and-update))

(defun isearch-forward-at-point (&optional regexp-p no-recursive-edit)
  "Interactive search forward for the symbol at point."
  (interactive "P\np")
  (if regexp-p (isearch-forward regexp-p no-recursive-edit)
    (let* ((end (progn (skip-syntax-forward "w_") (point)))
           (begin (progn (skip-syntax-backward "w_") (point))))
      (if (eq begin end)
          (isearch-forward regexp-p no-recursive-edit)
        (setq isearch-initial-string (buffer-substring begin end))
        (add-hook 'isearch-mode-hook 'isearch-set-initial-string)
        (isearch-forward regexp-p no-recursive-edit)))))
blog comments powered by Disqus