Reputation: 5198
I am playing around with a small Vim function that will highlight whitespace.
But the execute
command is behaving differently than when its called directly.
So the function looks like this:
function! ShowWhitespace()
execute "/\\s\\+$"
endfunction
And it is mapped as:
command! SW call ShowWhitespace()
When :SW
is executed it simply searches and gets the cursor to where whitespace exists.
However, when I do this in the command line:
:exe "/\\s\\+$"
It highlights correctly the whitespace. I am also making sure that highlightsearch
is always on, so this is not an issue of having it on or off.
As a side note, I need to have this in a function because I want to have other things that have not yet been added to it for flexibility (like toggling for example).
Why would this behave differently in a function than executing it directly? I've written a wealth of functions in Vim and never seen this work different.
EDIT & Solution:
So it seems Vim doesn't like having functions altering searches. As soon as a function exits the search patterns are cleared (as pointed out by :help function-search-undo
.
This might look ugly but does what I was looking to do in the first place:
command! -bang Ws let orig_line = line('.') | exe ((<bang>0)?":set hls!":":set hls") | exe '/\s\+$' | exe orig_line
Explained bit by bit:
Ws
command to the following actions::Ws!
or :Ws
) it sets highlightsearch
Upvotes: 1
Views: 149
Reputation: 32976
If you don't wish to move the cursor (and never do it), just set @/
to the correct search pattern, i.e.:
let @/ = '\s\+$'
NB: the function should have moved the cursor.
Upvotes: 2