Vim equivalent of Emacs' open-rectangle - vim

Emacs has a function called open-rectangle, which allows you to select a rectangular region (i.e. Vim's visual block mode), then hit a key combination to fill that rectangle with spaces, pushing any existing content out to the right:
This is really useful when working with vertically-aligned columns of text. I feel like I should be able to do this easily in Vim too, using visual block + a search & replace. But I can't seem to figure out why my search & replace isn't bound to my rectangle when I try it.
:'<,'>s/\^/ /
This actually indents the whole line, instead of opening up this selected region. I've tried replacing:
:'<,'>s/\v(.*)/ \1/
But that has the same effect. How can I get my pattern to understand that I only want to replace each line in the selected block with spaces + the selected area? Simple replacements like just changing letters work, but using ^ or .* doesn't work the way I'd expect.
I am aware of the ability to hit "I" and insert some spaces the drop back into normal mode, but that is harder to judge when you're indenting by a large amount, over many lines.

How about:
yPgvr<Space>
This yanks the block and pastes it to duplicate it, then re-selects the original block and replaces it with spaces.

Another way:
Visual-block select only one column.
Hit nI<Space><Esc> with n being the number of blank columns you want.

As a variation on romainl's answer, I have this:
vnoremap <C-Space> I<Space><Esc>gv
It allows both insertion of n spaces at once via a prepended count, and iterative adding of columns by repeated application of the mapping.

Related

Placing characters at a specific column in vi

Is there a way to place a character at a specific line in vim, even if the line is short?
For example, I'm contributing to a project which has a comment block style which is 79 columns wide, with a comment character at either end e.g.
!--------------!
! Comment !
! More Comment !
!--------------!
but it's really annoying to space over to it, even with guessing large numbers (35i< SPACE>< ESC>)
Is there a simple command which will do this for me, or a macro or something I could write?
set ve=all
then you could move (h,j,k,l) to anywhere you want. no matter how short your line is.
there are 4 options block, all, insert, onemore for details:
check :h virtualedit
in this way, after you typed short comment, then type <ESC>080l to go to the right place to the tailing !
you can map it too, if it is often used
then it works like this:
Put this in your .vimrc file and restart vim:
inoremap <F1> <C-r>=repeat(' ', 79-virtcol('.'))<CR>!<CR>
With this just press F1 (or whatever key you map) in insert mode after entering comment text to automatically pad with spaces and insert a ! in column 79.
Another simple way is to keep an empty comment box of the correct size somewhere, yank/paste it where needed and just Replace the spaces in it with your comment each time.
If you want to reformat a box that is too short, one way is to start from the comment in your example, make a Visual Block (Ctrl+v) selecting the single column just to the left of its right-hand edge, yank it (y), then repeatedly paste it (p). This will successively move the entire right-hand side of the comment one step, extending the box rightward. Repeat until it has the desired length.
If you already entered the comment text, you can use a macro to add the right-hand ! mark at the correct place. For example, record a macro (qa) that appends more characters than are needed for any line (e.g. 80ASpaceEsc), then use the goto column (|) to go to the correct place (79|) and replace the excess characters from there (C!Esc), then move down one line (j), and stop recording (q). Repeating this macro (#a) then "fixes" each line in turn and moves to the next. In total: qa80A<space><esc>79|C!<esc>jq and then #a whenever needed. Sounds complex but is convenient once you have it.
There are certainly good answers here already, particularly the virtualedit answer. However, I don't see the method which seems most intuitive to me. I would create an empty line for the last row of the comment which is just surrounded by the exclamation points. Then I would yank and paste a new copy of the empty line, go to the old empty line and go to the point at which I want to edit and use overstrike mode (R) to add my text without affecting the placement of the ending exclamation point.
Sometimes the simplest methods, while slightly more clunky, are the easiest to use and remember.
I usually just copy and paste an existing line in the comment block (or copy one from another file) and then modify it. If the text you're replacing is about the same size as what you want to write (e.g., if you're changing the author's name), you probably only need to add or delete a few spaces to make everything line up. It's a lot less painful than spacing out to the desired width.
If you ever have a block that gets too long this way, a neat trick is to place the cursor on the 79th column and press dw. That will clear all spaces up to the ! at the end.
My AlignFromCursor plugin offers commands and mappings that align only the text to the right of the cursor, and keep the text to the left unmodified. So, with the cursor in the whitespace left of the trailing !, you can align it with <Leader>ri.

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.

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.

How to do column editing in vim?

Vim is pretty powerful when editing by line - the search/replace tools are modeled to work linewise.
But what if I want to change a particular column across all lines? For example, how can I change the 80th column in my file to a # easily?
To edit a column, follow these steps:
Stand on the beginning of the column
Press Ctrl+v, then mark across the column you want to edit.
Press Shift+i to insert text at the beginning of the column, Shift+a to append text, r to replace highlighted text, d to delete, c to change... etc.
Hit ESC when done.
I think people (me) sometimes map the column editing keys to Ctrl+Q so it won't collide with visual select line (V) or paste-text if you mapped it as such.
...I couldn't follow the steps of sa125 (facepalm) so I looked someplace else and found a simpler explanation at: https://blog.pivotal.io/labs/labs/column-edit-mode-in-vi
Ctrl+v [ and select what ever you want]
Shift+i [and write whatever...(check out ** below)]
Esc
*c without Shift can be used instead of step 2, to delete selection before insert. And also r to replace.
**!! Attention Don't be discouraged by the fact that only the first row is changed when you 'write whatever...'!!
Hope it helps!
You can use a substitution where the pattern matches a specific column (\%c):
:%s/\%80c/#/<CR>
Or you can use block-wise visual mode:
gg80|CTRL+vGr#
The 'virtualedit' option can be used to allow positioning the cursor to
positions where there is no actual character:
:set virtualedit
I may be totally off topic here, but if your idea is to avoid long lines, you could have a look at the colorcolumn option of vim 7.3.
For column-wise editing, vis.vim is really useful. You can block-select your column of interest, and manipulate it with normal commands, and even arbitrary Ex commands. From the example on that page, I have often used the pattern:
:'<,'>B s/abc/ABC/g
You can Vundle/Pathogen install vis.vim from github:
Plugin 'taku-o/vim-vis'

Replace colon with tab to make columns

I have word lists where the word or expression in Spanish is separated by its translation with a colon (":"). I want to make two columns, one for Spanish, the other for English. In vim I tried with
:%s/:/^I^I^I/g
But it does not give the desired output. The different columns are not aligned.
When deleting the colon by hand and inserting the number of tabs with the same amount of tab strokes, it always ends up aligned.
Any idea how to solve this, preferably in vim?
On a Linux/*nix system I use column(1)
:%!column -s':' -t
followed by
:%retab!
I'd probable do a
:s/:/^I/g
followed by a
:set ts=25
Where 25 is the length of the longest word expected + 2. So, if you expect the longest word of your input (on the left side of the colon) to be 12 characters, I'd choose something around 14 instead.
With Tabular.vim it's quite easy, just type :Tab /:\zs and it does the rest.
When in insert mode a setting of yours makes tab to reach a nth column. This is set with the 'softtabstop' settings if I am right.
For those tasks you could use a plugin like Align.vim or Tabularize.
Another option is to insert a huge number of spaces, and then use Visual Block with < operator as many times as necessary, if you have to do it once. Otherwise prefer reusable methods.

Resources