Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Emacs how to operate (i.e. search) only in code regions?

Tags:

emacs

elisp

I'd like to isearch/search-replace/occur only in code (that is not in comments or strings).

This must be a common problem, so what packages do this already?

If no existing packages do this, I'm thinking a minor-mode where strings and comments are hidden based on fontification would do the trick. Is there one?

like image 531
event_jr Avatar asked Sep 26 '11 12:09

event_jr


People also ask

How do I search for a word in Emacs?

Emacs also offers a simple, or nonincremental, search. To use a more straightforward search, type C-s RETURN or select Search from the Search menu. Type the search string, press RETURN, and Emacs begins the search. Simply press C-s again to repeat the search.

What is the command to search forward in Emacs?

The Emacs search command is different from the search commands of most editors, in that it is "incremental". This means that the search happens while you type in the string to search for. The command to initiate a search is C-s for forward search, and C-r for reverse search.

How do I search and replace in Emacs?

Simple Search and Replace Operations When you want to replace every instance of a given string, you can use a simple command that tells Emacs to do just that. Type ESC x replace-string RETURN, then type the search string and press RETURN. Now type the replacement string and press RETURN again.

How do I select multiple lines in Emacs?

With Emacs 25, simply press Ctrl + Space and then move your cursor wherever you want to highlight/select the region of text which interests you.


1 Answers

Icicles search gives you several ways to do this. Here are two:

  • Search "things" (e.g. defuns, sexps, xml elements, etc.), ignoring comments (option icicle-ignore-comments-flag). That is, use selected code segments as search contexts, but ignore any comments within code or code inside comments.

  • Search the complement of the comments. E.g., define the search contexts as the complement of the zones of text that are font-locked with either face font-lock-comment-face or face font-lock-comment-delimiter-face (which means search all code outside of comments).

After defining the search contexts, just type text to incrementally filter the contexts. And you can replace any matches on demand.

like image 191
Drew Avatar answered Nov 15 '22 08:11

Drew