vim search pattern for a piece of text line yanked in visual mode - vim

I am trying search a part of some line which is yanked under visual mode.
What's the quickest way to do it in VIM? For exmaple,
Hello, #{1} world.
I press v enter visual mode and select llo, #{1} wor at the line 1. Then I yanked the selected text by pressing y, and then, I am trying to search for the selected text by pressing /. That leads to the following questions:
A: How to past a yanked text when I am in search mode?
B: How to avoid the work of escaping characters for a search pattern?

A:
Ctrl-r 0.
B:
In addition to the Ctrl-r 0 trick, there's also Ctrl-r =, which lets you type in an expression to be evaluated and expands to the result.
/ (now the prompt looks like /)
Ctrl-R = (now the prompt looks like =)
escape(#0, '\^$*.~[') Enter (now the prompt looks like /llo, #{1} wor)
Enter
Note that #reg means "the contents of register reg", and register 0 is the the last yank or delete. I think that escapes all the characters which are special in vi regexps… in any case, you would probably prefer to make a mapping than to type that all in.

When you yank some text (and specify no register to yank it into), it goes to register 0. So, if you want to search for that yanked text, press ESC to get into normal mode and then
/CTRL-r0
(i.e. press /, then CTRL+r, then 0) to pull the content of register 0 into the search pattern.
Some notes:
To search for other patterns stored in other registers, you could type :reg and watch the register contents before deciding which register content to use for your search.
To yank into a different register than 0 (e.g. 2), you could type "2y (:he v_y).
To search for the selected text directly, you could use the mapping described here which enables you to simply press X (uppercase character X) while in visual mode to search for that text.
For searching in general, this vimcast gives you an introduction to the very powerful command line window with the history of searches (discovered it two weeks ago and absolutely love it!).

I've overriden the star command for the visual mode (NB: it requires one file from lh-vim-lib). It answers your need:
select in visual mode
press */#
continue searching with n/N

Related

Using Ack.vim on visual selection

Currently I have this mapping in my ~/.vimrc
noremap <Leader>a :Ack <cword><cr>
which enables me to search for a word under the cursor.
I would like to search for a current visual selection instead, because sometimes words are not enough.
Is there a way I can send visual selection to ack.vim?
You can write a visual-mode map that yanks the highlighted text and then pastes it verbatim (properly escaped) onto the vim command-line:
vnoremap <Leader>a y:Ack <C-r>=fnameescape(#")<CR><CR>
This solution uses the <C-r>= trick that allows you to enter a kind of second-level command-line, which allows you to enter any vimscript expression, which is then evaluated, and the result is stringified and pasted onto the (original, first-level) command-line where the cursor is.
A slight disadvantage of this approach is that it commandeers the unnamed register, which you may not want.
While bgoldst's answer should work just fine, you could also consider my fork of ack.vim: https://github.com/AndrewRadev/ack.vim
It comes with a working :Ack command in visual mode, and a few other extras that I've summarized at the top of the README.
At the time of this writing this is the default behaviour of Ack.
Just do the following:
move your cursor on any word in normal mode (for instance, hit Esc button to enter in normal mode, you know...)
type :Ack with no argument
it will search for the word under the cursor
Usually I select text during a search in a file (for instance put cursor inside word and type * repeateadly) the type :Ack to look for that word in other files of the project.

How do I repeatedly search & replace a long string of text in vim?

I'm aware of the vim replace command, which is of the form, eg:
:%s/old/new/gc
But what if either of these strings is long? How can I use something like visual selection mode, the clipboard or vim registers instead of having to type the old/new text in?
You can use q: to bring up a command-line window. This lets you use all the vim editing commands to edit the vim command line, including p to paste. So, you could copy the text into a register, paste it into the command line window, and execute it that way.
I recently discovered this feature via vimcasts.
According to the manual, you can use Ctrl+R to insert the contents of a register into the current position in the command line. The manual also claims that Ctrl+Y inserts the text highlighted with the mouse into the command line. Remember that in X11 and some other systems, you can also paste text into a program from the system clipboard using the middle mouse button or a menu command in your terminal emulator.
I think to avoid have your command line be huge you can use this to solve your issue
:%s/foo/\=#a/g
That replaces "foo" with whatever is in register a.
If you're trying to do a substitute with a long complicated search pattern, here's a good way of going about it:
Try out the search pattern using some test cases and refine it until you have the pattern you want. I find incsearch really helps, especially with complicated regular expressions.
You can then use :%s//new to replace all instances of the last searched for pattern.
If you've entered a pattern and want to copy it out of the search history, you can use q/ to bring up a command line window containing recent search patterns very similar to the q: one that contains recent command history.
On the other hand, if you're asking about how to copy and paste text into the substitute command:
I'd write the pattern out in insert mode and yank the search and replacement into two distinct registers using, say, "ay and "by and then use :%s/<C-R>a/<C-R>b/gc to do the substitute. There are lots of variations of the yank command, but this one should also work automatically when using a visual selection.
If you're copying in text from the clipboard, you can use <C-R>* to paste it's contents in insert mode.
I have the following mapping in my .vimrc
vnoremap <leader>r "ry:%s/^Rr/
So I visually select the thing I want to replace, and hit ,r, type the replacement and hit return. If I want to paste the replacement, I yank it before selecting the text to replace, and then use <C-r>" to paste it as the replacement before hitting return.
Note: to insert ^R in your .vimrc, you actually type <C-v><C-r>.

How to paste yanked text into the Vim command line

I'd like to paste yanked text into Vim's command line. Is it possible?
Yes. Hit Ctrl-R then ". If you have literal control characters in what you have yanked, use Ctrl-R, Ctrl-O, ".
Here is an explanation of what you can do with registers. What you can do with registers is extraordinary, and once you know how to use them you cannot live without them.
Registers are basically storage locations for strings. Vim has many registers that work in different ways:
0 (yank register: when you use y in normal mode, without specifying a register, yanked text goes there and also to the default register),
1 to 9 (shifting delete registers, when you use commands such as c or d, what has been deleted goes to register 1, what was in register 1 goes to register 2, etc.),
" (default register, also known as unnamed register. This is where the " comes in Ctrl-R, "),
a to z for your own use (capitalized A to Z are for appending to corresponding registers).
_ (acts like /dev/null (Unix) or NUL (Windows), you can write to it but it's discarded and when you read from it, it is always empty),
- (small delete register),
/ (search pattern register, updated when you look for text with /, ?, * or # for instance; you can also write to it to dynamically change the search pattern),
: (stores last VimL typed command via Q or :, readonly),
+ and * (system clipboard registers, you can write to them to set the clipboard and read the clipboard contents from them)
See :help registers for the full reference.
You can, at any moment, use :registers to display the contents of all registers. Synonyms and shorthands for this command are :display, :reg and :di.
In Insert or Command-line mode, Ctrl-R plus a register name, inserts the contents of this register. If you want to insert them literally (no auto-indenting, no conversion of control characters like 0x08 to backspace, etc), you can use Ctrl-R, Ctrl-O, register name.
See :help i_CTRL-R and following paragraphs for more reference.
But you can also do the following (and I probably forgot many uses for registers).
In normal mode, hit ":p. The last command you used in vim is pasted into your buffer.
Let's decompose: " is a Normal mode command that lets you select what register is to be used during the next yank, delete or paste operation. So ": selects the colon register (storing last command). Then p is a command you already know, it pastes the contents of the register.
cf. :help ", :help quote_:
You're editing a VimL file (for instance your .vimrc) and would like to execute a couple of consecutive lines right now: yj:#"Enter.
Here, yj yanks current and next line (this is because j is a linewise motion but this is out of scope of this answer) into the default register (also known as the unnamed register). Then the :# Ex command plays Ex commands stored in the register given as argument, and " is how you refer to the unnamed register. Also see the top of this answer, which is related.
Do not confuse " used here (which is a register name) with the " from the previous example, which was a Normal-mode command.
cf. :help :# and :help quote_quote
Insert the last search pattern into your file in Insert mode, or into the command line, with Ctrl-R, /.
cf. :help quote_/, help i_CTRL-R
Corollary: Keep your search pattern but add an alternative: / Ctrl-R, / \|alternative.
You've selected two words in the middle of a line in visual mode, yanked them with y, they are in the unnamed register. Now you want to open a new line just below where you are, with those two words: :pu. This is shorthand for :put ". The :put command, like many Ex commands, works only linewise.
cf. :help :put
You could also have done: :call setreg('"', #", 'V') then p. The setreg function sets the register of which the name is given as first argument (as a string), initializes it with the contents of the second argument (and you can use registers as variables with the name #x where x is the register name in VimL), and turns it into the mode specified in the third argument, V for linewise, nothing for characterwise and literal ^V for blockwise.
cf. :help setreg(). The reverse functions are getreg() and getregtype().
If you have recorded a macro with qa...q, then :echo #a will tell you what you have typed, and #a will replay the macro (probably you knew that one, very useful in order to avoid repetitive tasks)
cf. :help q, help #
Corollary from the previous example: If you have 8go in the clipboard, then #+ will play the clipboard contents as a macro, and thus go to the 8th byte of your file. Actually this will work with almost every register. If your last inserted string was dd in Insert mode, then #. will (because the . register contains the last inserted string) delete a line. (Vim documentation is wrong in this regard, since it states that the registers #, %, : and . will only work with p, P, :put and Ctrl-R).
cf. :help #
Don't confuse :# (command that plays Vim commands from a register) and # (normal-mode command that plays normal-mode commands from a register).
Notable exception is #:. The command register does not contain the initial colon neither does it contain the final carriage return. However in Normal mode, #: will do what you expect, interpreting the register as an Ex command, not trying to play it in Normal mode. So if your last command was :e, the register contains e but #: will reload the file, not go to end of word.
cf. :help #:
Show what you will be doing in Normal mode before running it: #='dd' Enter. As soon as you hit the = key, Vim switches to expression evaluation: as you enter an expression and hit Enter, Vim computes it, and the result acts as a register content. Of course the register = is read-only, and one-shot. Each time you start using it, you will have to enter a new expression.
cf. :help quote_=
Corollary: If you are editing a command, and you realize that you should need to insert into your command line some line from your current buffer: don't press Esc! Use Ctrl-R =getline(58) Enter. After that you will be back to command line editing, but it has inserted the contents of the 58th line.
Define a search pattern manually: :let #/ = 'foo'
cf. :help :let
Note that doing that, you needn't to escape / in the pattern. However you need to double all single quotes of course.
Copy all lines beginning with foo, and afterwards all lines containing bar to clipboard, chain these commands: qaq (resets the a register storing an empty macro inside it), :g/^foo/y A, :g/bar/y A, :let #+ = #a.
Using a capital register name makes the register work in append mode
Better, if Q has not been remapped by mswin.vim, start Ex mode with Q, chain those “colon commands” which are actually better called “Ex commands”, and go back to Normal mode by typing visual.
cf. :help :g, :help :y, :help Q
Double-space your file: :g/^/put _. This puts the contents of the black hole register (empty when reading, but writable, behaving like /dev/null) linewise, after each line (because every line has a beginning!).
Add a line containing foo before each line: :g/^/-put ='foo'. This is a clever use of the expression register. Here, - is a synonym for .-1 (cf. :help :range). Since :put puts the text after the line, you have to explicitly tell it to act on the previous one.
Copy the entire buffer to the system clipboard: :%y+.
cf. :help :range (for the % part) and :help :y.
If you have misrecorded a macro, you can type :let #a=' Ctrl-R =replace(#a,"'","''",'g') Enter ' and edit it. This will modify the contents of the macro stored in register a, and it's shown here how you can use the expression register to do that. Another, simpler, way of modifying a macro is to paste it in a buffer ("ap), edit it, and put it again into the register, by selecting it and "ay.
If you did dddd, you might do uu in order to undo. With p you could get the last deleted line. But actually you can also recover up to 9 deletes with the registers #1 through #9.
Even better, if you do "1P, then . in Normal mode will play "2P, and so on.
cf. :help . and :help quote_number
If you want to insert the current date in Insert mode: Ctrl-R=strftime('%y%m%d')Enter.
cf. :help strftime()
Once again, what can be confusing:
:# is a command-line command that interprets the contents of a register as vimscript and sources it
# in normal mode command that interprets the contents of a register as normal-mode keystrokes (except when you use : register, that contains last played command without the initial colon: in this case it replays the command as if you also re-typed the colon and the final return key).
" in normal mode command that helps you select a register for yank, paste, delete, correct, etc.
" is also a valid register name (the default, or unnamed, register) and therefore can be passed as an arguments for commands that expect register names
For pasting something that is the system clipboard you can just use SHIFT - INS.
It works in Windows, but I am guessing it works well in Linux too.
"I'd like to paste yanked text into Vim command line."
While the top voted answer is very complete, I prefer editing the command history.
In normal mode, type: q:. This will give you a list of recent commands, editable and searchable with normal vim commands. You'll start on a blank command line at the bottom.
For the exact thing that the article asks, pasting a yanked line (or yanked anything) into a command line, yank your text and then: q:p (get into command history edit mode, and then (p)ut your yanked text into a new command line. Edit at will, enter to execute.
To get out of command history mode, it's the opposite. In normal mode in command history, type: :q + enter
For pasting something from the system clipboard into the Vim command line ("command mode"), use Ctrl+R followed by +. For me, at least on Ubuntu, Shift+Ins is not working.
PS: I am not sure why Ctrl+R followed by *, which is theoretically the same as Ctrl+R followed by + doesn't seem to work always. I searched and discovered the + version and it seems to work always, at least on my box.
It's worth noting also that the yank registers are the same as the macro buffers. In other words, you can simply write out your whole command in your document (including your pasted snippet), then "by to yank it to the b register, and then run it with #b.
For context, this information comes from out-of-the-box, no plugins, no .vimrc Vim 7.4 behavior in Linux Mint with the default options.
You can always select text with the mouse (or using V or v and placing the selection in the "* register), and paste it into the command line with Shift + Ctrl + v.
Typing Ctrl + r in the command line will cause a prompt for a register name. so typing :CTRL-r* will place the content register * into the command line. It will paste any register, not just "*. See :help c_CTRL-R.
Furthermore, the middle mouse button will paste into the command line.
See :help->quote-plus for a description of the how X Window deals with selection. Even in a plain, out-of-the-box Vim (again, in Vim 7.4 in Linux Mint, anyway), any selection made with the left mouse button can be pasted in the command line with the middle mouse button.
In addition, the middle mouse button will also paste text selected in Vim into many other X Window applications, even GUI ones (for example, Firefox and Thunderbird) and pasting text into the command line is also possible where the text was selected from other apps.
See :help->x11-selection for addl information.
tl;dr
Try the :CTRL-r approach first, and then use Shift + Ctrl + v or the middle mouse button if you need something else.
It is conceded that it can be confusing.
I was having a similar problem. I wanted the selected text to end up in a command, but not rely on pasting it in. Here's the command I was trying to write a mapping for:
:call VimuxRunCommand("python")
The docs for this plugin only show using string literals. The following will break if you try to select text that contains doublequotes:
vnoremap y:call VimuxRunCommand("<c-r>"")<cr>
To get around this, you just reference the contents of the macro using # :
vnoremap y:call VimuxRunCommand(#")<cr>
Passes the contents of the unnamed register in and works with my double quote and multiline edgecases.
OS X
If you are using Vim in Mac OS X, unfortunately it comes with older version, and not complied with clipboard options. Luckily, Homebrew can easily solve this problem.
Install Vim:
brew install vim --with-lua --with-override-system-vi
Install the GUI version of Vim:
brew install macvim --with-lua --with-override-system-vi
Restart the terminal for it to take effect.
Append the following line to ~/.vimrc
set clipboard=unnamed
Now you can copy the line in Vim with yy and paste it system-wide.
"[a-z]y: Copy text to the [a-z] register
Use :! to go to the edit command
Ctrl + R: Follow the register identity to paste what you copy.
It used to CentOS 7.
If you have two values yanked into two different registers (for example register a and register b) then you can simply set a variable c and do the operation on it.
For example, :set c = str2float(#a) + str2float(#b) and then you can paste the content of c anywhere.
For example whilst in INSERT mode, CTRL + R then type = to enter into the expression register and just type c after equal sign and hit ENTER. Done you should now have the total of a and b registers.
All these can be recorded in a macro and repeated over!
The str2float function is used if you are working with floats, if you don't, you will get integers instead.
I am not sure if this is idiomatic but it worked for my case where I needed to add 2 numbers in a row and repeat it for 500 more lines.
I like to use Control-v to paste from the system clipboard, so I use:
cnoremap <C-v> <C-r>+

Replace word with contents of paste buffer?

I need to do a bunch of word replacements in a file and want to do it with a vi command, not an EX command such as :%s///g.
I know that this is the typical way one replaces the word at the current cursor position: cw<text><esc> but is there a way to do this with the contents of the unnamed register as the replacement text and without overwriting the register?
I'm thinking by "paste" you mean the unnamed (yank/put/change/delete/substitute) register, right? (Since that's the one that'd get overwritten by the change command.)
Registers are generally specified by typing " then the name (single character) of the register, like "ay then "ap to yank into register a, then put the contents of register a. Same goes for a change command. In this case, if you don't want the text you remove with the change command to go anywhere, you can use the black hole register "_: "_cw. Then once in insert mode, you can hit ctrl-R followed by the register you want (probably ") to put in the contents of that register.
"* - selection register (middle-button paste)
"+ - clipboard register (probably also accessible with ctrl-shift-v via the terminal)
"" - vim's default (unnamed) yank/put/change/delete/substitute register.
Short answer: "_cw^R"
Edit: as others are suggesting, you can of course use a different register for the yank (or whatever) that got your text into the default register. You don't always think of that first, though, so it's nice to do a single change command without blowing it away. Though it's not totally blown away. There are the numbered registers "0 through "9:
Vim fills these registers with text from yank and delete commands.
Numbered register 0 contains the text from the most recent yank command, unless the command specified another register with ["x].
Numbered register 1 contains the text deleted by the most recent delete or change command, unless the command specified another register or the text is less than one line (the small delete register is used then). An exception is made for the delete operator with these movement commands: %, (, ), `, /, ?, n, N, { and }. Register "1 is always used then (this is Vi compatible). The "- register is used as well if the delete is within a line.
With each successive deletion or change, Vim shifts the previous contents of register 1 into register 2, 2 into 3, and so forth, losing the previous
contents of register 9.
Using the information in this post, I have formed this useful mapping. I chose 'cp' because it signifies "change paste"
nmap <silent> cp "_cw<C-R>"<Esc>
EDIT:
Also I took this a step further and supported any motion.
To get the equivalent of command above it would be cpw for "change paste word"
"This allows for change paste motion cp{motion}
nmap <silent> cp :set opfunc=ChangePaste<CR>g#
function! ChangePaste(type, ...)
silent exe "normal! `[v`]\"_c"
silent exe "normal! p"
endfunction
You can use the visual mode of vim for this. e.g. copy a word: ye and then overwrite another one with the copied word: vep
If your cursor is on the word you want to replace with the contents of the unnamed register, you can use viwp. v switches to visual mode, iw selects the inner word, and p puts the contents of the register in its place.
In practice, when I need to replace one word (function name, etc.) with another, I'll move to the one to use as a replacement, yiw to yank the inner word to the unnamed register, then move to the word I'm replacing, and viwp to replace it. Pretty quick way of substituting one word for another. If you searched (/) for the word you're replacing to get to it, you can then just hit n to get to the next occurrence you need to replace. Obviously no substitute for using :%s/find/replace/g, but for a couple of quick substitutions it can be handy, especially if you already have the new word in a register.
If you make use of a named register (ie. use "ay or "ad, etc., to fill your paste register), you can do something like
cw<CTRL-R>a<esc>
Which will replace the word with the contents of register a. As far as I can tell, you can't use the default register because when you cw it'll be filled with the word that was cut by that command.
Do you mean the system paste buffer or the vi register?
If you want to use the system paste buffer then you are fine and could do dw"+P - " chooses a register, and "+ is the system paste buffer.
Otherwise copy into the non-default register with say "ay to copy into register a and then to replace something do dw"aP
You can use yw to yank the word, then you can change the word with yanked word by vipw to yank word and paste previously yanked word.
You can use registers for that:
first place replacement text in register
<mark some text>"ay
where a is register name
then you can use that register in replacement
ve"ap
Or you could do Shift+v-p (select the whole line and paste in its' place)

When is Visual mode used in Vim?

I'm relatively new to the world of Vim. I've been learning my way around it but have yet to find a practical purpose to enter visual mode.
What are some scenarios when visual mode is especially useful?
Are there actions that can only be performed from within visual mode?
I use visual mode when I want to highlight a section of text. I start by typing v in standard mode, which then enables the visual mode. Then I use the arrow keys to move the cursor. This causes the text between my starting point and the current cursor location to be highlighted. Once you select a section of text like this, entering a command (e.g. search/replace) in command mode (by typing :) will only affect the selected area.
Another useful visual command is shift+v (visual line). This does the same as above, but it selects entire lines at a time instead of individual characters.
When you want to comment a block of text.
In command mode :
Shift + v
,ctrl +v,
j or k,
I , #(comment
character) and then Esc
Vim inserts the comment character to
the start of the block..
is when I am using Gvim, I find it much easier to copy data
to the clipboard through visual mode.
In command mode :
Shift + v
, j or k ,
" , +
,y
Here + is the clipboard
register
This to me is much more legible that using markers
is for manual indenting
Shift + v,
Shift + > for
moving to the right.
Shift + < for
moving to the left. .
repeats
this is fun :-)
One of the nice things about visual mode is that, because of Vim's focus on modality, you can perform most of the commands that you are used to (such as search/replace with :s, d to delete text, or r to replace text) while also seeing exactly what will be affected -- this allows you to determine the exact scope of whatever you are doing.
Furthermore, as someone else mentioned, you can easily insert a prefix (like a comment character or, say, & for alignment or \item in LaTeX) by selecting the first character of each line in visual block mode (ctrl+v), pressing I to insert before the first character, typing in whatever you want to insert, and then Escing back to normal mode.
The last kind of visual mode is visual line (Shift+v), which allows you to quickly select a number of lines. From there, you can change their indentation using > or < (prefix this with a number to indent by that many tabs), use d or y to delete or copy those lines, use zf to create a new fold from those lines, or use any other selection-based command.
Finally, there are a lot of other cool things you can do with visual mode, including gv to reselect your last visual[line/block] mode selection, gU to convert a visual selection to uppercase or gu for lowercase, and many more.
In addition to the other (great) answers, it's an easy way to define scope for an action. For example, to limit a search & replace to a specific method...
Say you have this code:
function foo() {
abc();
while (1) {
def();
abc();
}
}
You can place the cursor on any of the braces or parentheses and press v, %, :, s/abc/xyz/g and your search & replace will have a defined scope in which the action will occur.
Visual mode is useful if you want to apply a command to a section of text that isn't easily described as a primitive movement command. You can select some text in visual mode with a complex sequence of movements and then apply a command to that selection.
I often find myself using visual-block mode (Ctrl + v) more than any of the other visual modes.
You can easily remove indentation, comments, etc. once you are aware of this mode. In my experience, this is often faster than figuring out how to form an equivalent search-and-delete statement.
You can also add indentation (or comments as Cherian stated) by selecting a block of text and pressing I, typing whatever you want to add, and pressing Esc (note: you may need to redraw the screen (e.g. by moving the cursor) to see the effects of this).
I haven't seen the following mentioned, probably because they're subtle.
1 - Less hassle with the unnamed register
Whenever you copy (yank) some text, and then want to d to change some other text, e.g., diw to "delete inner word," Vim will place the deleted text into the unnamed register. Then if you try to paste, it will just paste the deleted text right back unless you do "0p to paste from the 0 register.
But with visual mode, you can just do something like viwp and don't have to mess with registers.
So, for comparison, to copy and replace inside some parens:
yiw -> move somewhere -> vi(p
vs
yiw -> move -> ci(<C-r>0p
yiw -> move -> "_di(p
yiw -> move -> di("0P
Note: this also works for deleting text and pasting it back over a text object. See here.
2 - Jumping to parts of a text object
If you want to jump to the beginning or end of a text object, you can select it in visual mode and press o. For example, va" to select anywhere inside quotes, and then press o to jump to the matching quotes, kind of like % for matching brackets.

Resources