VimScript execute search does not work anymore - vim

I don't know since when, but my visual selection search function is not working anymore. I broke the problem down to this minimal example.
Assume the following buffer:
word
word
word
When I run /word, I find all results and can jump between them.
When I run :execute '/word' this works the same as before.
When I write a short autoload function just doing the same it does not work the same:
~/.config/nvim/autoload/utils/search.vim:
function! utils#search#visual_selection() abort
execute '/word'
endfunction
Executing :call utils#search#visual_selection() makes the cursor land on the first result, but no results are highlighted. Moreover it is using the old search pattern instead of the new one. So if I search first for something non existing like foo and then execute this function, pressing n give me the error message Pattern not found: foo.
What has changed. What is the difference here?

This is actually documented behavior of Vim and NeoVim. It's not really related to the use of :execute (you can reproduce it with a direct use of /word), but with how search (and redo) work in a function.
See :help function-search-undo, which states:
The last used search pattern and the redo command "." will not be changed by the function. This also implies that the effect of :nohlsearch is undone when the function returns.
You can work around that by explicitly setting the search pattern register, which you can do with a let command.
function! utils#search#visual_selection()
let #/ = 'word'
execute "normal /\<cr>"
endfunction
The second command executes a simple / from normal mode, that is enough to search for word, since it will look for the last search pattern which is now set to what you wanted.
After the function is finished, the search pattern will keep its value, which means highlighting through 'hlsearch' will work, and so will the n command to find the next match.
A restriction from the approach above is that you can't really set search direction for repeats with n. Even though there is v:searchforward, which can be set, that variable is also reset after a function as part of the :help function-search-undo effects. There doesn't seem to be anything you can do about that one...
If the purpose of this function is for use in a key mapping, you might consider a completely different approach, using nnoremap <expr> and having the function return the normal mode command for the search as a string, that way the actual search happens outside of the function and the restrictions from function-search-undo won't apply.
For example:
function! utils#search#visual_selection(searchforward)
let pattern = 'word'
if a:searchforward
let dir = '?'
else
let dir = '/'
endif
return dir.pattern."\<cr>"
endfunction
And then:
" Mappings for next-word and previous-word
nnoremap <expr> <leader>nw utils#search#visual_selection(1)
nnoremap <expr> <leader>pw utils#search#visual_selection(0)
This avoids the issue with :help function-search-undo altogether, so consider something like this approach, if possible in your case.

Related

Using placeholders in vim

Given a vim document with multiple occurrences of a specific placeholder, say <%%>, I want to be able to jump to the next placeholder from the beginning of the document: More explicitly, if the document is given by
$\frac{<%%>}{<%%>}$
I want to press a key such that the first placeholder gets removed, i.e. we have
$\frac{}{<%%>}$
where the cursor is at the position of the placeholder and vim is in insert mode.
I'm aware of the vim-latex plugin which implements such a behaviour but only need this one feature. I tried to use the /-search of vim but didnt get the cursor position right.
Thanks in advance for any advice.
lh-brackets provides this feature -- actually vim-latex placeholder system has been inspired by lh-brackets one.
The idea to implement this feature, is:
to look for the pattern of the placeholder -- prefer search() to know whether something has been found: no selection shall be done otherwise
Actually doing it correctly may require a couple of calls to searchpair() to handle the case where the cursor is in the middle of the placeholder, see lh-brackets code as search(..., 'c') is not enough;
select this pattern -- v + movement 3<right> for instance
and finally either go into SELECT-mode (gh <c-g>) or remove the placeholder and go into insert mode (s)
If your placeholder pattern is exactly <%%>, it'll be quite simple to implement.
" I factorize common code without introducing the exact keybinding
" NB: we have to use the ancestor of map-<expr> as the later doesn't
" permit to move the cursor -> we execute the expression register: :h #=
" NB: As said earlier a correct implementation would require to call searchpair()
" twice in case the cursor is within a placeholder, see lh-brackets code
nnoremap <silent> <Plug>(jump-next) #=(search('<%%>') > 0 ? "v3l<c-g>" : '')<cr>
vmap <silent> <Plug>(jump-next) <c-\><c-n><Plug>(jump-next)
imap <silent> <Plug>(jump-next) <c-\><c-n><Plug>(jump-next)
" Tests shall be done in a real plugin before binding to the chosen shortcut: µ, <f3>, <c-j>, <tab>...
nmap <silent> µ <Plug>(jump-next)
vmap <silent> µ <Plug>(jump-next)
imap <silent> µ <Plug>(jump-next)
If sometimes it could become <%somestring%>, then I would definitively recommend using lh-brackets or any snippet engine that already takes care of this -- for instance, mu-template would permit to use your exact snippets/templates by changing locally the default placeholder characters with VimL: let s:marker_open = '<%' +
VimL: let s:marker_close = '%>' (I'm also maintaining mu-template which depends on lh-brackets).
NB: lh-brackets also provides surrounding (non intrusive), and bracket pairs insertion (can be deactivated: add :let g:cb_no_default_brackets = 1 in your .vimrc)
Using a macro might help.
In your example, use /<%%> to search for your placeholder. Then gg will take you at the beginning of the document.
Then start the macro with qa for instance. Go to the next occurrence of your placeholder with n. Then, ca< will remove the placeholder. C-o q will stop recording, while keeping you in insertion mode.
To go to and replace the next placeholder, just do #a (execute the macro stored in register a)
Does this mapping help?
:nmap %% /<%%><cr>ni
It executes a search (/<%%><cr>), repeats the search with n to skip the 1st placeholder and goes to the second. Then it switches (i) to Insert Mode.

How do I use Vim's escape() with <C-R> as its first argument?

My goal is to select several words in Vim's visual mode (well, neovim in my case), press leader+L and let fzf show search results for the selected string through :Rg. I came up with this:
vnoremap <expr> <leader>l 'y:<C-U>Rg '. shellescape(escape('<C-R>"', '()[]><')) .'<CR>'
Which does work, but when I select the text options(:modifier) and trigger a search, the escape() command doesn't escape the parentheses and Rg fails to return results.
In short, I'm expecting this command to fire:
:Rg 'options\(:modifier\)'
And I'm getting this instead:
:Rg 'options(:modifier)'
I'm guessing I can't use <C-R> in this context, but I can't seem to figure out why?
UPDATE: Thanks to a helpful reply from user D. Ben Knoble indicating I could drop and construct the mapping differently, I ended up with this, solving my problem:
vnoremap <leader>l "ky:exec 'Rg '. shellescape(escape(#k, '()[]{}?.'))<CR>
You don’t need to—all registers are available as variable’s prefixed with # (all are readable except #_, most are writable, I think).
So instead of <C-R>", use #"

vim cmap lhs only at the beginning

I have a mapping
:cnoremap ch call ShowHistoryMatching
The problem is that the ch characters expand to the right sentence in any case they are typed, no matter if at the beginning or later in the cmap input.
The problem is when I try to search for words in vim using / or ? e.g. for
/cache - it will be expanded using the mapping above.
How can I set the mapping ch to be extended only when it occurs at the beginning of the command?
cmap's are notoriously tricky because they often execute in the wrong context. Some better alternatives:
Use a normal mapping e.g. nnoremap <leader>ch :call ShowHistoryMatching()<cr>
Create a command e.g. command Ch call ShowHistoryMatching()
Use a the cmdalias.vim plugin
Use a more clever abbreviation as described in vim change :x function to delete buffer instead of save & quit post. Similar technique to cmdailias.vim.
Personally I would just create a new command.
You can use the getcmdpos() function to determine if you're at the beginning of the line or somewhere else. This technique can replace a built-in command using an abbreviation or you can adapt it for use in a mapping, possibly with an <expr> mapping.

How to use Ctrl-R_= with :execute

I'm trying to get an expression on a variable expanded on a :execute command. I've guessed this could be achieved by using Ctrl-R_=, but it is not clear how the special characters should be inserted. None of the following worked:
exec 'echo ^R=1+1^M'
exec "echo <ctrl-r>=1+1<cr>"
The purpose is set a global variable used as an option in a plugin to select how to show the results. It is used on an :execute command, and works fine for 'vsplit' or 'split'. But the choice between vertical or horizontal split sometimes depends on the window layout. In order to do this without adding extra complexity to the plugin I've thought of something like the following:
let var = '<ctrl-r>=(winwidth(0) > 160 ? "vsplit" : "split")<cr>'
Edit
Currently the plugin has something like the following:
exec 'pluginCommands' . g:splitCmd . ' morePluginCommands'
The g:splitCmd is a plugin option, which works for when set with "split", "vsplit", "tabe", etc. My intent is to change this fixed behavior, setting g:splitCmd in such a way that it represents an expression on the execute above, instead of a fixed string.
Now that I'm understanding the issue better, I think a dynamic re-evaluation inside the config var is impossible if the variable's value is inserted in an :execute g:pluginconf . 'split' statement. To achieve that, you'd need another nested :execute, or switch to command-line mode via :normal! :...; both approaches will fail on the appended . 'split', because you can't add quoting around that.
The way I would solve this is by prepending a :help :map-expr to the plugin's mapping; change
:nmap <Leader>x <Plug>Plugin
to
:nnoremap <expr> <SID>(PluginInterceptor) PluginInterceptor()
:nmap <Leader>x <SID>(PluginInterceptor)<Plug>Plugin
Now, you're get called before the mapping is executed, and can influence the plugin config there:
fun! PluginInterceptor()
let g:plugconf = winwidth(0) > 160 ? "vsplit" : "split"
return ''
endfun
If modifying the plugin mapping is for some reason difficult, you could also trigger the PluginInterceptor() function via :autocmd; for this particular case e.g. on WinEnter events.
With :execute, you already have a way to evaluate expressions; just move them out of the static strings to get them evaluated:
exec 'echo ' . 1+1
The <C-R> only works in command-line mode (and insert mode), so only within a :cnoremap ... command (or with :normal). (And even there, you can use :map <expr>, which often gives you simpler code.)
I think that what you want is simply
:let var = (winwidth(0) > 160) ? "vsplit" : "split"
It seems to me like
exec 'pluginCommands' . eval(g:splitCmd) . ' morePluginCommands'
should work just fine, and is a simple solution to this problem.

How do I turn on search highlighting from a vim script?

If I do either of the following two:
call search("searchString")
exec "/ searchString"
From a script, then vim does the search but does not highlight the results, even though hlsearch. Doing the same searches from outside a script highlights the results.
Just found out the answer myself:
call search(l:searchString)
call matchadd('Search', l:searchString)
The
feedkeys()
function is the key (pun intended):
call feedkeys("/pattern\<CR>")
or cleaner:
" highlights – or doesn’t – according to 'hlsearch' option
function SearcH(pattern)
let #/ = a:pattern
call feedkeys("/\<CR>")
endfunction
I know this is late. However when I searched for the answer to this problem this page came up. So I feel compelled to help fix it.
call search(l:searchString)
call matchadd('Search', l:searchString)
Did not work for me. (when run from inside a function) It did higlight the words I wanted to search for but n/N wouldn't cycle between them. Also when I performed a new search the "l:serachStirng" pattern still remained highlighted. This answer on this link worked much better
Vim search and highlighting control from a script
Which gave me:
let #/ = l:searchString
then run
normal n
outside the funciton (so the highlighting is done immediately without the user needing to press n)
To turn on, press ESC type :set hls
To turn off, press ESC type :set nohls
Found answer here:
http://vim.1045645.n5.nabble.com/highlighting-search-results-from-within-a-function-tt5709191.html#a5709193
```
One solution would be
function! XXXX()
execute '/this'
return #/
endfunction
and to use the following instead of ":call XXXX()".
:let #/ = XXXX()
```
I believe this works from inside a function
(to just enable highlighting and nothing more):
call feedkeys(":\<C-u>set hlsearch \<enter>")
You need to put this in your .vimrc file
" Switch syntax highlighting on, when the terminal has colors
" Also switch on highlighting the last used search pattern.
if &t_Co > 2 || has("gui_running")
syntax on
set hlsearch
endif
The .vimrc file is usually located in your home directory, or you can find it using "locate .vimrc"

Resources