Use a register value as search pattern - vim

I wish to use the content of a register as search pattern in Vim.
I would like to do this from the command line so I cannot use the <c-r> syntax since that assumes an interactive session.
It is possible to use a register as a replace pattern, like this
:%s/foo/\=#a/g
However using this syntax as a search pattern does not work
:%s/\=#a/foo/g
it outputs
E64: \= follows nothing
E476: Invalid command

In a pattern (not the replacement part), \= stands for “0 or 1 time” (it is a synonym for \? put should be preferred over \? since the latter means a literal ? when looking backwards.
See :help /\= and help pattern for more details.
Why not :
let #/=#a
%s//foo/g

I don't think it's possible directly, but you can use :exe to achieve this:
:exe '%s/' . #a . '/foo/g'

You can do this with the / register
This doesn't solve the general problem, but it appears to me that the / register is special in this regard: if you leave the search term blank, it will use whatever is in the / register; namely, whatever you searched for last.
So if you want to replace foo with the contents of #a, you could do this:
Search for foo
%s//\=#a/g (or highlight some text and start typing :s to substitute only in that range)

Related

Can not find the good syntax for a vim sustitute pattern

I have a bunch of t_ prefixed fonction names in a header file and i would like to remove this prefix from some of them.
I have ended by typing :
:s/\(\s+\)t_\([^(]+\)(/\1\2(/c
But vim complains with Pattern not found
What is wrong in my pattern ?
You forgot to put a backslash before + to give it its quantifier meaning. You can also probably simplify it using \< to match the start of a word instead of capturing spaces.
I suggest breaking the problem down, first the search:
/\v\s+\zst_\ze.*\(
Now the substitution:
:s///\c
We can reuse a search pattern simply typing an empty search on the substitution
OBS: I suppose your functions have () at the end of the line, so .*().
Another thing; \zs and \ze to match only t_, for more see: :h \zs.
If you are using neovim you can see what happens befor hitting enter, just put these lines on your init.vim:
if has("nvim")
set inccommand=nosplit
endif

Vim Custom Replace Function

Note: I'm currently using Neovim v0.2.2 (But I believe this shouldn't change anything related this post)
I'm currently attempting to create a function within vim that allows for easily replacing text.
I understand I can create a shortcuts and macros and all that, but ideally I just want to give 2 args, and not think about what specifics go where as this can interupt my thought process.
So I decided to just have a simple wrapper disguised as a function (Which I will create a command wrapper for as well, once I figure out what I did wrong here)
function! VisualReplace(query, replacement)
" Example = '<,'>s/query\%V/replacement/g
'<,'>s/a:query\%V/a:replacement/g
endfunction
As you can see, it's a very simple function that just applies the args in it's respective position, Yet, this fails even when called as a function using : call VisualReplace('some_query', 'some_replacement'
Alternatively, if you simply use the Example I have commented out directly, there's no issue, So I was hoping someoen could enlighten me on a potential fix
If need be, I could possibly look into string building & build it incrementally
Error msg:
Pattern not found: a:query\%V
General theory
Vimscript is evaluated exactly like the Ex commands typed in the : command-line. There were no variables in ex, so there's no way to specify them. When typing a command interactively, you'd probably use <C-R>= to insert variable contents:
:sleep <C-R>=timetowait<CR>m<CR>
... but in a script, :execute must be used. All the literal parts of the Ex command must be quoted (single or double quotes), and then concatenated with the variables:
execute 'sleep' timetowait . 'm'
Your function
In order to get the a:query and a:replacement arguments into :substitute, use :execute and either string concatenation or printf():
function! VisualReplace(query, replacement)
execute "'<,'>s/" . a:query . '\%V/' . a:replacement . '/g'
endfunction
Additional critique
Passing a range to a function is so common, there's special syntactic sugar for it: The range attribute to :function, and a:firstline and a:lastline implicit arguments. Read more about it at :help function-range-example. While your use case here seems to be specifically for visual mode, in general it's useful to keep the scope of functions as broad as possible.
#Ingo Karkat answered perfectly. However, I feel like there might be some workflow alternatives which might help. (Assuming you aren't trying to script this behavior)
Visual Star
It looks like you are build a search based on a visual section. You may want to consider using a visual-star plugin to simplify the process. Here is a an example of a visual star mapping:
xnoremap * :<c-u>let #/=#"<cr>gvy:let [#/,#"]=[#",#/]<cr>/\V<c-r>=substitute(escape(#/,'/\'),'\n','\\n','g')<cr><cr>
This mapping will allow you to visually select text and then execute * to make it a search pattern. Similar to how * works in normal mode on the current word.
Search refining
I get the impression that you are trying to refine your search pattern. Vim has a nice way of doing this with q/ or pressing <c-f> while searching with /. See :h q/. This will bring up the command-line window which will allow you to edit the query/command-line with all your normal Vim keys.
Search and Replace with gn motion
Sometimes doing a substitution is just overkill or doesn't quite fit the situation right. You can mimic a search and replace by using the gn motion to operate on a search pattern. By using an operator and the gn motion together you can use the dot command, ., to repeat the action easily.
Example:
/foo
cgnbar<esc>
Now you can use . to repeat the foo -> bar replacement. Use n to skip. You can use other operators as well, e.g. gU to uppercase.
See :h gn and :h operator for more help.
Related Vimcasts episodes:
Refining search patterns with the command-line window
Operating on search matches using gn
Search for the selected text

vim multiple character substitute regex issue

I am little new to Vim world. I am trying to substitute *=, ~=(actually [special char]=) in to [whatever is symbol]=(adding space both sides). Here is my substitute command:
:%s/[~,\*]=/ = /g
the problem in this case is that I am not able to add respective special symbol before the equal sign. Can you help me...
This is a classic capture and replace use case. Capture the symbol part by enclosing it in \(...\), and then reference it in the replacement part via \1. You'll find more details at :help s/\1 (or :help :substitute in general):
:%s/\([~,\*]\)=/ \1= /g
Alternatively, you can start the match only on the = with \zs. This asserts that the symbol part is there, but as it isn't included in the match, you don't need to reference it:
:%s/[~,\*]\zs=/ = /g
The same trick can be applied with \ze at the end. As you can see, this often results in shorter commands.
This is probably the simplest answer to your question:
:%s/[~,\*]=/ & /
An& in the replace segment means 'entire match'.

How to share searchText between vim search and vim substitute?

When i need to replace a string with a new string in vim.
First i would use search-mode to check that the search pattern is correct.
/search pattern
Then use the 's' command to do substitution.
:%s/search pattern/new string/
The search pattern need to type twice. If it is too complex, it would be boring.
Is there a method to avoid this?
You can simply omit the pattern in the substitution command, e.g.
:%s//new string/
This is documented in :help last-pattern (emphasis mine):
The last used pattern and offset are remembered. They can be used to
repeat the search, possibly in another direction or with another
count. Note that two patterns are remembered: One for 'normal' search
commands and one for the substitute command ":s". Each time an empty
pattern is given, the previously used pattern is used.
Also (in addition to Marco Baldelli's correct answer), the last search pattern is stored in the special register /. You can insert this in the command-line via Ctrl + R, followed by /. (This also works in insert mode, and also with other registers.) It's helpful when you want to tweak your search pattern before substituting.

How to do substitution only on highlighted text in vim?

Before doing substitution, I usually type /foo to search the pattern first.
Vim automatically highlight all strings match the pattern.
Then I figure out how to write the substitution command :%s/foo/bar/g.
When the pattern is complex, it's much harder to write the substitution command than the search command.
If I can do substitution only on highlighted strings. It becomes easy.
For example:
Question: Translate Part of a Line
I can figure out the search pattern: /\[\[\(http\)\#!.\{-}\]\]
But I cannot figure out the substitution command easily.
You can replace the previously searched pattern if you use an empty string as the search pattern in the substitute command:
After /foo type :%s//bar/g in normal mode to replace "foo" by "bar".
You could use the 'c' flag to tell Vim to confirm before replacing. It highlights and stops to ask before every match it finds to the given pattern.
:%s/foo/bar/gc
I just figured out:
:%s##\=substitute(submatch(0), '_', '/', '')#g
But is there any better ways?

Resources