You ask whether it is possible without an external package. The answer is, "of course" ;-). Are you also asking someone to give you the code for that here (which is essentially giving you an external package ;-))? Maybe someone else will provide that info.
A short answer is that you can define isearch-filter-predicate
so that Isearch and perform-replace
skip matches that are in the areas you want to skip (e.g. comments and whatever else).
If you don't mind trying a 3rd-party package, consider Isearch+. Out of the box you can interactively skip searching comments, and you should be able to do the same for math expressions (whatever they are - you will need to define a suitable predicate). Then you can use the same filtering that you set up and tested using Isearch to perform replacements (e.g. with query-replace
or whatever).
For Isearch+, you can complement/negate a search condition (predicate). For example, during Isearch:
C-z &
prompts you for a filter predicate to add. You can pick a predefined predicate using completion. One predefined predicate is[;]~[;]
, which means search only commentsoutside comments. So you You do this:C-z & TAB
, then choose candidateC-z & [;]~[;]
, or just doC-z & ~[;]
.-
The
C-z ~ 1
negates the lastin this predicate you addednickname stands for not, the[...]
stands for inside, and the;
stands for comment (;
is the comment character for Lisp, so I chose that to stand for "comment"). So now youYou are now searching everywhere except in comments.
To switch from Isearch to query-replacing, use
M-%
. Since you did this during Isearch the currentisearch-filter-predicate
carries over to replacement: You will be queried for matches only in non-comment zones.
What if you don't switch to query-replace during the same Isearch where you set up the predicate? When you finish isearching the predicate automatically goes back to what it was before you started using C-z...
. But if you use C-z s
before you exit Isearch then the predicate remains as you last defined it.
This means that after step #2#1 above, you could use C-z s
, exit Isearch, do something else, and then later use query-replace. It will pick up that "saved" filter predicate.
(You can use C-z 0
during Isearch to remove your changes to the filter predicate. You can also toggle to search the complement of what the current filter would normally choose.)
You will need to define your own predicates for filtering math zones. The code in library isearch+.el
for defining other filter predicates can help as a model.
The doc describing this on-the-fly defining and using filter predicates is at Dynamic Isearch Filtering.
(I think maybe the Emacs Wiki is down at the moment. You can also get isearch+.el
from MELPA.)