0

How do you substitute every word of a line, so that it becomes a useful vimwiki tag?

Provided the following line:

Word Compund_Word

I want:

:Word: :Compund_Word:

I guess it involves some use of regex, but I haven't been able to figure out which string.

4

While on the line in question:

:s/\w\+/:&:/g

Breakdown

  • \w\+ will match 1 or more word characters ([0-9A-Za-z_]).
  • & has a special meaning in a replacement, depending on the value of 'magic' (default: on). It is replaced with the matched pattern.
  • the g flag will perform this substitution for every occurrence on the line, not just the first.

Non-ASCII use

  • To use any non-whitespace character as a word character use \S:

    :s/\S\+/:&:/g
    
  • To use any character except specific delimiters, use [^{delimiters}] (substituting {delimiters} with any number of delimiters):

    :s/[^;,|]\+/:&:/g
    

See:

:h /\w
:h /\+
:h sub-replace-special
:h 'magic'
:h :s_flags
:h :s_g
| improve this answer | |
  • 1
    Thanks to Jake Grossman's answer, I realized how it had to be done. For the sake of completion, I added instructions to non-ASCII use. – Ludenticus Sep 19 at 19:47
  • 1
    @Ludenticus You can also use \S to match any non-bank character... – filbranden Sep 19 at 19:53
1

Vimwiki also allows you to list all the tags together, with a single : separating multiple tags, such as in:

:Word:Compund_Word:Other_Tag:

To accomplish this replacement, you can use a :s command that will replace a sequence of whitespace with a single :, and additionally match the beginning and end of the line to insert an extra : on each end.

You can perform that substitution on a specific line with:

:s/^\s*\zs\|\s\+\|\ze\s*$/:/g

See :help /\zs and :help /\ze to understand how the matches for the start and end of the line work... The match for whitespace between words should be easy to grasp.

| improve this answer | |

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.