1

I found this useful setting form this post, which highlights trailing whitespaces :

highlight ExtraWhitespace ctermbg=grey guibg=grey
noremap <F10> :match ExtraWhitespace /\s\+$/<CR>

This works when I tap F10 but I also want the highlighting to go away when I tap F10 again. Typing :match works but I was wondering if this could be done from this keymap itself. I tried putting ! after match but that is not allowed.

1 Answer 1

3

You can get a List of all matches previously defined for the current window with the getmatches() function. By using an <expr> mapping, you can dynamically set a mapping based on the size of the List returned by getmatches() with a conditional expression.


Conditional expressions in Vimscript (often called ternary expressions in other languages) take the following form:

a ? b : c

where a, b, and c are expressions. If a evaluates to true, then the conditional expression as a whole evaluates to b, otherwise, it evaluates to c.

The following expression evaluates to ':match<CR>' if the length of the List returned by getmatches() is greater than zero, otherwise it will evaluate to ':match ExtraWhitespace /\s\+$/<CR>'.

len(getmatches()) > 0 ? ':match<CR>' : ':match ExtraWhitespace /\s\+$/<CR>'

Using an <expr> mapping allows you to evaluate an expression to determine the function of the mapping, rather than a static value. The result of the expression should be a string representation of the desired Ex commands.


So, putting our conditional expression together with our <expr> mapping, we can do the following:

noremap <expr> <F10> len(getmatches()) > 0 ? ':match<CR>' : ':match ExtraWhitespace /\s\+$/<CR>'

Relevant help:

:h :map-<expr>
:h getmatches()

Your Answer

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

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