Recently I create a mapping to toggle highlight search. That’s simple but quite useful, something like nmap ,m :set hlsearch!. The only problem I’ve been facing is that sometimes I just get lost after pressing ,m.
“Did it work?”, “Is it now on or off?”… Common question from the panic of not receiving feedback 🙂
So I thought that echoing a “turned on” or “off” would make me calmer. The big question here now arrived: is it possible to include a little script inside the mapping? I know I could create a function, but that’s not my intention for this simple script:
if (&hlsearch)
echo "Search Highlight On"
else
echo "Search Highlight Off"
endif
I guess that I need to “escape” the newlines like in a preprocessor directive, maybe:
nmap ,m :set hlsearch! \
if (&hlsearch) \
echo "Search Highlight On" \
else \
echo "Search Highlight Off" \
endif
But probably that’s not the proper way, doesn’t work and I don’t even know if it is possible.
Another thing I notice is that typing things like :if (1) echo "works" doesn’t work either, even though both if and echo are “colon” commands. It gives an error with echo. So do I need to separate each command in some way? Preceding echo with another colon didn’t solve the problem.
Thanks for any help!
You can do it, but I’d recommend against it. A mapping links one or two key presses (
,m) in your case to a sequence of key presses. Therefore, to do what you want to do, you just have to type in the commands as you would if you were doing it interactively:Each
<CR>is the equivalent of pressing ENTER. The<silent>stops it from echoing the whole contents of the mapping to the screen, so you only see “Search Highlight On/Off”.The other way you can join commands (in some cases) is with
|so for example:See
:help :barfor more information on this.Do it with a function! It’ll make things much more maintainable in the long run.