someNameJustToAnswer
someNameJustToAnswer

Reputation: 155

Search selected text and show all occurrence of it in current (all other buffers) in emacs?

So in notepad++ I can select text, hit C-f, then, if I need to look for occurrence of selection in all opened files, i hit M-o and get nice clickable list with navigating to occurrence option. Or if I need list only for current file I point mouse to “Find all in current document” button do a click and get same nice clickable list only for currently active file. So is it possible to do exact thing in emac?

Upvotes: 1

Views: 1202

Answers (3)

mistige
mistige

Reputation: 667

You can do the same thing with the helm package. Emacs will search the word the cursor/"point" is on (you don't need to highlight it).

To make helm search in all open files/buffers, use:

M-x helm-multi-swoop-all

To make helm search only in file/buffer you're currently in, use:

M-x helm-swoop

Press the ENTER key to drop into the selected file at the selected line.

To bind these functions to the same key-comboes, you'd need this in your .emacs:

(global-set-key (kbd "M-o") 'helm-multi-swoop-all)
(global-set-key (kbd "C-f") 'helm-swoop)

NB Helm is hosted in the MELPA repository.

HTH, Michael

Upvotes: 0

Thomas
Thomas

Reputation: 17422

You can implement that functionality with the following lisp function:

(defun occur-selection ()
  (interactive)                   
  (when (region-active-p)         
    (let (deactivate-mark)      
      (occur (regexp-quote (buffer-substring (region-beginning) (region-end)))))))

If you put that code in your ~/.emacs file together with the follwing line:

(global-set-key [(meta o)] 'occur-selection)

you should be able to select some text, hit M-o and get a list of all occurrences of the selected text displayed in a separate buffer.

User M-g n and M-g p do cycle through the matching lines in the original buffer.

Note, however, that multiple occurrences in a single line are not distinguished.

Upvotes: 1

Thomas
Thomas

Reputation: 17422

By default, Emacs has M-x occur which work similar but slightly differently. It allows you to specify a regular expression, all matches of which in the current buffer will be displayed and hyperlinked.

If your focus is more on navigation than on highlighting all matches of a search term, there might be an external alternative that could help you.

Emacs' original philosophy is not built around user interface metaphors such as clicking with a mouse, it comes from a keyboard only background. If you're interested in this approach, you might want to have a look at the Avy package for Emacs. It lets you quickly jump to one of multiple occurrences of a word.

Check out the excellent Emacs Rocks episode "Jumping Around" to see a precursor of Avy (called ace-jump-mode) in action: http://emacsrocks.com/e10.html

Upvotes: 0

Related Questions