vim: copy and paste text without looking into the line number - linux

For example, I want to copy the line 5~15 and paste it in another place. I find several methods:
Move your cursor to the line 5, then 11yy, and p
Command: 5,15y and p
Ctrl + V, select the block within line 5~15, then go the place you want to paste in, leave enough blank lines for pasting(or it would be overlap with the current text), and p
I'm not satisfied with any of these methods, for method 1 and 2, I would have to bother to see the line number or count how many lines I want to copy, when the text covers many lines, it becomes quite tricky. For method 3, I would have to allow enough space ahead, which also acquires me to count the lines I want to paste. So is there any method that is just like method 3, only that I don't need to leave enough space beforehand?
EDIT: Method 2, the original 5,15yy is wrong. Has been corrected.

When you want to copy entire lines, use linewise visual mode, entered via V. With this, the register contents will shift existing lines automatically when pasted, unlike the blockwise selection you've used via <C-V>.
You can also use :put to paste as whole lines (even if you've (mistakenly) make a blockwise selection). For more such tricks and handy mappings, there's my UnconditionalPaste plugin.

A method similar to your 3. would be:
Go to Line-5, then V15Gy or V10jy or Vjjj...jy (V is Visual Mode linewise. You can see your selected lines without bodhering about the line numbers)
Go to Line-40(or somewhere else) and p. That would put the yanked lines after Line-40. Or use P to put it before Line-40.
Or you can use the Ex-command :t (the same as :copy but shorter)
:5,15t 40

Related

VIM to delete a range of lines into a register

I am trying to delete a range of lines into a register a. Is this the easiest way to achieve this?
:5,10d a
The definition of "easiest" depends on what do you have, and what do you want to do
if you have a start line number and end number, e.g.
:2349,5344d a
is the easiest way.
You don't have to consider the questions like
"where is my cursor?"
"how many lines would be removed?"
...
If you are about to remove a small amount of lines, particularly they are on same screen. (You could use relative-linenumber.) for example: "a5dd but you have to move your cursor to the first line you want to delete. And this could be done by option 1 too: 5:d a<CR> (vim will automatically translate it into .,.+5d a<CR>)
If you just know the 1st line of deletion, and find the last line you want to delete by reading your text, (of course, small amount of lines) you could press V, and press j by reading, when it reaches the deletion ending border, press "ad
If the "range" in your question is the "range" concept in vim, The first option would be better. since it could be 234,540, it could be 1;/foo, /foo/,/bar/... :h range see detail
so back to the first sentence in my answer, There is no absolutely easiest way. It all depends on what do you have, and what do you want to do.
The other way to achieve this would be to highlight the range of lines in visual line mode. (Shift-V)
Then type "ad while in visual line mode. This will put the deleted lines into the a register.
" followed by a register puts the next delete, yank or put into that register.
Below is the documentation for " (quote)
*quote*
"{a-zA-Z0-9.%#:-"} Use register {a-zA-Z0-9.%#:-"} for next delete, yank
or put (use uppercase character to append with
delete and yank) ({.%#:} only work with put).
Another example of deleting multiple lines and putting it in a register. To delete 6 lines and put them in a register you can got to the line and type "a6dd. This puts the 6 deleted lines into register a.

How can I highlight multiple lines in gVim without using the mouse?

Vim noob here. I am trying to select multiple lines of code to copy and paste in other areas. Is there a way to do this without using the mouse?
A few other ways that don't use visual mode at all:
using marks
leave a mark somewhere with ma
move somewhere else
yank from here to there with y'a
using search motions
localize some unique token at the end of the part you want to yank
yank from here to there with y/foo<cr> (forward search) or y?bar<cr> (backward search)
using text-objects
determine what text-object would map to what you want to yank:
inner/outer word, iw/aw
inner/outer pair, i'"([{</a'"([{<
inner/outer html tag, it/at
sentence, s
paragraph, p
"block", ]
…
yank that text-object with, say, yip
using other motions
yank to end of function: y]}
yank to end of file: yG
all of the above solutions with visual mode
V'ay
V/foo<cr>y
V?bar<cr>y
Vipy, etc.
V]}y
VGy
:h motion.txt will hopefully blow your mind, like it did to mine.
You can place your cursor in the first line you want to copy and then type nyy where n is the number of lines you want to copy. For example, type 2yy to copy the two lines under the cursor.
Then, you can paste them using p.
You can also select multiple lines by placing your cursor somewhere and keeping Shift pressed. Move your cursor to the end of the desired selection and stop pressing Shift. Then copy using just y (and not yy) and paste with p.
Yep, in normal mode type V[direction] and you will highlight multiple lines. If you don't want whole lines, use v instead of V. To copy it, hit y and move to the area which you want to paste in and hit p. To delete it, instead of y use x.
Alternatively, you can simply use [number of lines]yy to yank some number of lines or [number of lines]dd to cut some number of lines. In this case pasting is the same.

Vim: insert the same characters across multiple lines

Sometimes I want to edit a certain visual block of text across multiple lines.
For example, I would take a text that looks like this:
name
comment
phone
email
And make it look like this
vendor_name
vendor_comment
vendor_phone
vendor_email
Currently the way I would do it now is...
Select all 4 row lines of a block by pressing V and then j four times.
Indent with >.
Go back one letter with h.
Go to block visual mode with Ctrlv.
Select down four rows by pressing j four times. At this point you have selected a 4x1 visual blocks of whitespace (four rows and one column).
Press C. Notice this pretty much indented to the left by one column.
Type out a " vendor_" without the quote. Notice the extra space we had to put back.
Press Esc. This is one of the very few times I use Esc to get out of insert mode. Ctrlc would only edit the first line.
Repeat step 1.
Indent the other way with <.
I don't need to indent if there is at least one column of whitespace before the words. I wouldn't need the whitespace if I didn't have to clear the visual block with c.
But if I have to clear, then is there a way to do what I performed above without creating the needed whitespace with indentation?
Also why does editing multiple lines at once only work by exiting out of insert mode with Esc over Ctrlc?
Here is a more complicated example:
name = models.CharField( max_length = 135 )
comment = models.TextField( blank = True )
phone = models.CharField( max_length = 135, blank = True )
email = models.EmailField( blank = True )
to
name = models.whatever.CharField( max_length = 135 )
comment = models.whatever.TextField( blank = True )
phone = models.whatever.CharField( max_length = 135, blank = True )
email = models.whatever.EmailField( blank = True )
In this example I would perform the vertical visual block over the ., and then reinsert it back during insert mode, i.e., type .whatever.. Hopefully now you can see the drawback to this method. I am limited to only selecting a column of text that are all the same in a vertical position.
Move the cursor to the n in name.
Enter visual block mode (Ctrlv).
Press j three times (or 3j) to jump down by 3 lines; G (capital g) to jump to the last line
Press I (capital i).
Type in vendor_. Note: It will only update the screen in the first line - until Esc is pressed (6.), at which point all lines will be updated.
Press Esc.
An uppercase I must be used rather than a lowercase i, because the lowercase i is interpreted as the start of a text object, which is rather useful on its own, e.g. for selecting inside a tag block (it):
Another approach is to use the . (dot) command in combination with i.
Move the cursor where you want to start
Press i
Type in the prefix you want (e.g. vendor_)
Press esc.
Press j to go down a line
Type . to repeat the last edit, automatically inserting the prefix again
Alternate quickly between j and .
I find this technique is often faster than the visual block mode for small numbers of additions and has the added benefit that if you don't need to insert the text on every single line in a range you can easily skip them by pressing extra j's.
Note that for large number of contiguous additions, the block approach or macro will likely be superior.
Select the lines you want to modify using CtrlV.
Press:
I: Insert before what's selected.
A: Append after what's selected.
c: Replace what's selected.
Type the new text.
Press Esc to apply the changes to all selected lines.
I would use a macro to record my actions and would then repeat it.
Put your cursor on the first letter in name.
Hit qq to start recording into the q buffer.
Hit i to go into insert mode, type vector_, and then hit Esc to leave insert mode.
Now hit 0 to go back to the beginning of the line.
Now hit j to go down.
Now hit q again to stop recording.
You now have a nice macro.
Type 3#q to execute your macro three times to do the rest of the lines.
:%s/^/vendor_/
or am I missing something?
Updated January 2016
Whilst the accepted answer is a great solution, this is actually slightly fewer keystrokes, and scales better - based in principle on the accepted answer.
Move the cursor to the n in name.
Enter visual block mode (ctrlv).
Press 3j
Press I.
Type in vendor_.
Press esc.
Note, this has fewer keystrokes than the accepted answer provided (compare Step 3). We just count the number of j actions to perform.
If you have line numbers enabled (as illustrated above), and know the line number you wish to move to, then step 3 can be changed to #G where # is the wanted line number.
In our example above, this would be 4G. However when dealing with just a few line numbers an explicit count works well.
An alternative that can be more flexible:
Example: To enter the text XYZ at the beginning of the line
:%norm IXYZ
What's happening here?
% == Execute on every line
norm == Execute the following keys in normal mode (short for normal)
I == Insert at beginning of line
XYZ == The text you want to enter
Then you hit Enter, and it executes.
Specific to your request:
:%norm Ivendor_
You can also choose a particular range:
:2,4norm Ivendor_
Or execute over a selected visual range:
:'<,'>norm Ivendor_
Or execute for each line that matches a 'target' regex:
:%g/target/norm Ivendor_
I wanted to comment out a lot of lines in some config file on a server that only had vi (no nano), so visual method was cumbersome as well
Here's how i did that.
Open file vi file
Display line numbers :set number! or :set number
Then use the line numbers to replace start-of-line with "#", how?
:35,77s/^/#/
Note: the numbers are inclusive, lines from 35 to 77, both included will be modified.
To uncomment/undo that, simply use :35,77s/^#//
If you want to add a text word as a comment after every line of code, you can also use:
:35,77s/$/#test/ (for languages like Python)
:35,77s/;$/;\/\/test/ (for languages like Java)
credits/references:
https://unix.stackexchange.com/questions/84929/uncommenting-multiple-lines-of-code-specified-by-line-numbers-using-vi-or-vim
https://unix.stackexchange.com/questions/120615/how-to-comment-multiple-lines-at-once
You might also have a use case where you want to delete a block of text and replace it.
Like this
Hello World
Hello World
To
Hello Cool
Hello Cool
You can just visual block select "World" in both lines.
Type c for change - now you will be in insert mode.
Insert the stuff you want and hit escape.
Both get reflected vertically. It works just like 'I', except that it replaces the block with the new text instead of inserting it.
Suppose you have this file:
something
name
comment
phone
email
something else
and more ...
You want to add "vendor_" in front of "name", "comment", "phone", and "email", regardless of where they appear in the file.
:%s/\<\(name\|comment\|phone\|email\)\>/vendor_\1/gc
The c flag will prompt you for confirmation. You can drop that if you don't want the prompt.
Use Ctrl+V to enter visual block mode
Move Up/Down to select the columns of text in the lines you want to comment.
Then hit Shift+i and type the text you want to insert.
Then hit Esc, wait 1 second and the inserted text will appear on every line
Ctrl + v to go to visual block mode
Select the lines using the up and down arrow
Enter lowercase 3i (press lowercase I three times)
I (press capital I. That will take you into insert mode.)
Write the text you want to add
Esc
Press the down arrow
I came here to paste in many lines an already copied string. When copy with y we can paste, in the INSERT MODE, pressing Ctrl+r and right after press ''. This will have the same result as being in NORMAL MODE and press p. This is called paste from registry.
Suppose the following text in the buffer:
vendor_something
text
to_receive
the_paste
pattern
Then we can put the cursor pointing to v in vendor_ and press v, move to right using l until select the underscore symbol we want to paste in the text bellow. After that, we can point the cursor at the beginning of "text" (two lines bellow vendor_something) and press Ctrl+v. Then I to go into INSERT MODE where we press 3j Ctrl+r '' Esc. The result of this sequence will be:
vendor_something
vendor_text
vendor_to_receive
vendor_the_paste
vendor_pattern
:.,+3s/^/vendor_/
Another example, I needed to just add two spaces to a block of 125 lines, so I used (with cursor positioned at the beginning of the first line of the block):
:.,+125s/^/ /
Worked great.
If the change is required in the entire file,
:1,$s/^/vendor_/
If the change is required for only a few lines,
Go to the first line where change is required, and either give the command
:.,ns/^/vendor_/
Substitute n with the line number of the last line in the block.
Or,
:.,+ns/^/vendor_/
Substitute n with number of lines minus 1 in which the change is required.

Cut and paste multiple lines in vim

I'm running vim 7.3 on a Mac 10.7.2 and I'm having some trouble cutting and pasting several lines.
On my old Linux setup (which was stolen so I don't know versions), I could type "dd" multiple times and then "p" would yank all of them back. For example: type: "dd dd" and two lines would be deleted. Now type "p" and both lines are pasted back into the buffer.
I know I can accomplish what I want by typing "2dd", and then "p" - but I would like to be able to "dd"-out lines without counting the number of lines ahead of time.
Any ideas?
Have you considered using visual mode?
You could just go:
Press V
Select everything you want to cut without counting
Press d
Go to where you want to paste
Press p
This should yield approximately half as many keystrokes as the dd method since you press one key per line rather than two. Bonus points if you use 5j (or similar) to select multiple lines at a time.
You could type:
d<n>d
where <n> is the number of lines that you want to cut, and then you could paste them with:
p
For example, to cut and paste 3 lines:
d3d
p
To cut and paste by line numbers (do :set number to see the line numbers), for lines x to y do:
:x,yd
or if your cursor is already on line x, do
:,yd
Then go to where you want to paste and press p
Not sure if this is close enough to what you're trying, but one thing you could do is use a specific register, and capitalize your register name. That tells vim to append to the register rather than replace it, so if you have the lines:
one
two
three
you can enter
"qdd
"Qdd
"Qdd
and then subsequently if you enter
"qp
it will paste back the original lines
To copy and paste 4 lines:
y4y (with the cursor on the starting line you wanna copy)
p (with cursor on the line you wanna paste after)
I agree with #Ben S. that this is the preferred way to accomplish this but if you are just looking to replicate your old behavior you can remap dd to append to a specified register, and then map p to paste from that register and clear it.
This will have the disadvantage of causing p to only work with things deleted using dd (using d} to delete to the end of the paragraph would not put the text in the correct register to be pasted later).
Add the following to your vimrc
noremap dd "Ddd "Appends the contents of the current line into register d
noremap p "dp:let #d=""<CR> "Pastes from register d and then clears it out
if you don't want pasting to clear out the contents of the register
noremap p "dp "Paste from register d
but this will cause that register to grow without ever clearing it out

How to insert a block of white spaces starting at the cursor position in vi?

Suppose I have the piece of text below with the cursor staying at the first A currently,
AAAA
BBB
CC
D
How can I add spaces in front of each line to make it like, and it would be great if the number of columns of spaces can be specified on-the-fly, e.g., two here.
AAAA
BBB
CC
D
I would imagine there is a way to do it quickly in visual mode, but any ideas?
Currently I'm copying the first column of text in visual mode twice, and replace the entire two column to spaces, which involves > 5 keystrokes, too cumbersome.
Constraint:
Sorry that I didn't state the question clearly and might create some confusions.
The target is only part of a larger file, so it would be great if the number of rows and columns starting from the first A can be specified.
Edit:
Thank both #DeepYellow and #Johnsyweb, apparently >} and >ap are all great tips that I was not aware of, and they both could be valid answers before I clarified on the specific requirement for the answer to my question, but in any case, #luser droog 's answer stands out as the only viable answer. Thank you everyone!
I'd use :%s/^/ /
You could also specify a range of lines :10,15s/^/ /
Or a relative range :.,+5s/^/ /
Or use regular expressions for the locations :/A/,/D/>.
For copying code to paste on SO, I usually use sed from the terminal sed 's/^/ /' filename
Shortcut
I just learned a new trick for this. You enter visual mode v, select the region (with regular movement commands), then hit : which gives you this:
:'<,'>
ready for you to type just the command part of the above commands, the marks '< and '> being automatically set to the bounds of the visual selection.
To select and indent the current paragraph:
vip>
or
vip:>
followed by enter.
Edit:
As requested in the comments, you can also add spaces to the middle of a line using a regex quantifier \{n} on the any meta-character ..
:%s/^.\{14}/& /
This adds a space 14 chars from the left on each line. Of course % could be replaced by any of the above options for specifying the range of an ex command.
When on the first A, I'd go in block visual mode ctrl-v, select the lines you want to modify, press I (insert mode with capital i), and apply any changes I want for the first line. Leaving visual mode esc will apply all changes on the first line to all lines.
Probably not the most efficient on number of key-strokes, but gives you all the freedom you want before leaving visual mode. I don't like it when I have to specify by hand the line and column range in a regex command.
I'd use >}.
Where...
>: Shifts right and
}: means until the end of the paragraph
Hope this helps.
Ctrl + v (to enter in visual mode)
Use the arrow keys to select the lines
Shift + i (takes you to insert mode)
Hit space keys or whatever you want to type in front of the selected lines.
Save the changes (Use :w) and now you will see the changes in all the selected lines.
I would do like Nigu. Another solution is to use :normal:
<S-v> to enter VISUAL-LINE mode
3j or jjj or /D<CR> to select the lines
:norm I<Space><Space>, the correct range ('<,'>) being inserted automatically
:normal is probably a bit overkill for this specific case but sometimes you may want to perform a bunch of complex operations on a range of lines.
You can select the lines in visual mode, and type >. This assumes that you've set your tabs up to insert spaces, e.g.:
setl expandtab
setl shiftwidth=4
setl tabstop=4
(replace 4 with your preference in indentation)
If the lines form a paragraph, >ap in normal mode will shift the whole paragraph above and below the current position.
Let's assume you want to shift a block of code:
setup the count of spaces used by each shift command, :set shiftwidth=1, default is 8.
press Ctrl+v in appropriate place and move cursor up k or down j to select some area.
press > to shift the block and . to repeat the action until desired position (if cursor is missed, turn back with h or b).
Another thing you could try is a macro. If you do not know already, you start a macro with q and select the register to save the macro... so to save your macro in register a you would type qa in normal mode.
At the bottom there should be something that says recording. Now just do your movement as you would like.
So in this case you wanted 2 spaces in front of every line, so with your cursor already at the beginning of the first line, go into insert mode, and hit space twice. Now hit escape to go to normal mode, then down to the next line, then to the beginning of that line, and press q. This ends and saves the macro
(so that it is all in one place, this is the full list of key combinations you would do, where <esc> is when you press the escape key, and <space> is where you hit the space bar: qai<space><space><esc>j0q This saves the macro in register a )
Now to play the macro back you do # followed by the register you saved it in... so in this example #a. Now the second line will also have 2 spaces in front of them.
Macros can also run multiple times, so if I did 3#a the macro would run 3 times, and you would be done with this.
I like using macros for this like this because it is more intuitive to me, because I can do exactly what I want it to do, and just replay it multiple times.
I was looking for similar solution, and use this variation
VG:norm[N]I
N = numbers of spaces to insert.
V=Crtl-V
*** Notice *** put space immediate after I.

Resources