1

Given two buffers, where

the first one has a list of keywords delimited by a new line;

the second buffer with text that contains a subset of keywords from the first buffer.

How do I search and highlight all these words from the first buffer in the second buffer?

1

Something like

:match Search /\V\<\(^R=EXPRESSION\)\>/

Where ^R is input with ^V^R and EXPRESSION is join(getbufline('#', 1, '$'), '\|') and # is your buffer holding "keyword list" one per line (for simplicity I also assume that no keyword contains "slash" or "backslash").

For something more substantial you should probably build custom syntax with syntax keyword, readfile(), execute etc.

| improve this answer | |
  • Expanding on your answer: :execute 'match Search /\V\<\('.getbufline('#', 1, '$')->map({s -> s->escape('/\')})->join('\|').'\)\>/'. Uses :execute to build the command from a string, groups the list of words with \(...\), escapes them with escape() and gets them from buffer # (last buffer.) Also, perhaps using anchors ^ and $ instead is what the OP wanted? From the description, it's one word per line apparently... Should be an easy fix. Great answer! – filbranden Jun 10 at 10:17
  • 1
    @filbranden Thank you. execute is good for scripts but if the command is expected to run interactively then the expression register is easier to write and debug, IMO. Also I'd like to avoid "method" notation, as it's not supported by Neovim, and so join(map(getbufline(...), {->escape(...)}, '...') could become too difficult to read and understand. Anyway, I believe, there's little chance that any "keyword" contains slash. – Matt Jun 10 at 12:39
  • Why not call matchadd('Search', join(getbufline('#',1,'$'),'\|')) (it can get more complicated, e.g. by adding word-boundaries, escaping special characters, etc), but that would be my basic idea. – Christian Brabandt Jun 10 at 15:15
  • @ChristianBrabandt Well, no special counter-argument, except maybe :match NONE looks to me more natural and precise than call clearmatches(). Also, I consider this as an interactive command (thinking of "keyword" buffer being opened in the current Vim session), not a standalone script. – Matt Jun 10 at 15:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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