15

Is it somehow possible to have different search patterns per window or buffer, ie. I want to search for term A in window/buffer A and term B in window/buffer B so that using hlsearch, highlights different things in e.g. a split in parallel.

2 Answers 2

13

You can use :autocmds to switch the current search pattern (register /) as you move along windows and buffers, but Vim will never highlight different patterns at the same time, as this still is a single global register, just being multiplexed.

Apart from searching, you can highlight different patterns (also with different colors) via the built-in :match, :2match, :3match, and :call matchadd(). These are window-local.

Finally, there are plugins like my Mark plugin that offer highlighting, searching, jumping to next match (similar to the built-in search), for multiple patterns. (The plugin page has links to alternative plugins.)

1

tldr: I've written a trivial vim plugin (https://github.com/Hoblovski/perwindow-search.vim) to illustrate how do the job in less than 100 lines of code. It's focused on your job, and is less general than Karkat's (but is well usable). Below are explanations for that code.

As mentioned by Karkat, you can use autocmd (type :h autocmd in vim) but there is only one search pattern (the vim register @/) globally.

Still you can modify @/, which opens a possibility to save it to a variable that is local to the window when you exit that window, and restoring @/ from that variable when you go back. To achieve so, use autocmd with {event} as WinEnter and WinLeave. The logic basically looks like

autocmd WinEnter *  <code restoring @/ from window-local variable>
autocmd WinLeave *  <code saving    @/ to   window-local variable>

Still, if you want different highlighting for search results in the current active window and the other windows, you cannot use the builtin global hl-Search, because search results in different windows all belong to that same highlight group.

The solution is to define two custom highlight groups, one for search results in the current window, one for those in other windows. Upon WinEnter/WinLeave, we manually set the highlight groups via clearmatches() and matchadd(<hl-group>, <pattern>, <priority>).

The above are basic ideas but a few subtle details remain

  • the highlight must be updated each time the user initiates a search (via / n N * #). We can remap these keys to include that operation.
  • since we're no longer using the builtin @/, we cannot cancel highlighting of search results with :nohls. To do so, I chose to delete those highlighting groups.
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.