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
c are expressions. If
a evaluates to
true, then the conditional expression as a whole evaluates to
b, otherwise, it evaluates to
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>'
<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>'