2016-02-13 Looking for keywords

Assume that you want to look through some buffer – say, a log file or something – and you are especially interested in some keyword, say foo. The simplest way is to use isearch: you press C-s foo and repeatedly press C-s and/or C-r to jump from one occurrence to another.

One problem with this approach is that isearch is kind of volatile: you exit isearch, and bam!, the keyword is no longer highlighted. This might or might not be what you want.

If not, the next thing is M-x occur. It is quite a powerful command, not known by many Emacs users I suspect. And even if you know about its existence, you might be surprised with two of its features. When in the occur buffer, you can press C-c C-f to toggle a variant of follow mode (with it, just moving the point causes the other buffer – the one showing the original buffer – to show the line corresponding to the one you’re in. Besides, you can press e in the occur buffer, and edit the lines shown in place. (This is exited with C-c C-c.) Really awesome.

But wait, there’s more! (It’s Emacs after all.) There is yet another way of spotting all occurrences of some keyword: Hi Lock mode. You can turn it on with the M-x highlight-regexp command. (It it bound to some key by default, but I never remember it.) It accepts a regex, then a face (with a reasonable default and completion, of course), and voilà! When you no longer need the highlighting, just give the same regex to M-x unhighlight-regexp (which is not as hard as it seems, since the default is the last regex you highlighted, and you have the history which can be navigated by M-p / M-n) and you’re done.

And while we’re at it, don’t forget that \b in a regex means boundary of a word, so instead of e.g. the you might want to use \bthe\b, for instance.

And if all that was not enough, there are quite a few packages outside Emacs core which do a similar thing. For instance, if isearch and occur had a baby, it would be Swiper. Try it for yourself, it’s cool. I don’t use it very often, but I have it on s-s (that is, super-s, or Windoze-s) and it’s sometimes handy. Another one, which I find occasionally very useful, is Iedit – but this one definitely deserves its own post.

As you can see, even with a thing as simple as “I want to look for this regex, and see many of its occurrences at once”, not only does Emacs have something like this, but there are quite a few ways of doing it, each appropriate in its own circumstances. As usual, Emacs has you covered.

CategoryEnglish, CategoryBlog, CategoryEmacs