I am dealing with a block of comments like:
//this is comment 1
//this is comment 2
//this is comment 3
//this is comment 4
I would like to make it look like:
//this is comment 1
//this is comment 2
//this is comment 3
//this is comment 4
Is there a Vim shortcut to make this transformation on selected lines while staying in command mode?
You can use the :substitute command. With the cursor anywhere on the
first of the lines:
:,+3s/$/\r
This inserts an additional newline at the end of each line.
You can also use the :global command. With the cursor anywhere on
the first of the lines, run:
:,+3g//norm o
For each of the next four lines, this executes the o Normal-mode
command, adding a new blank line.
In both of the commands, the ,+3 prefix is a range for the
command, see :help range. Briefly, the comma separates the addresses
of the starting and ending lines of the range, where the current line
is used if we omit the former of the two addresses. The +3 address
refers to the line that is three lines below from the current line.
Rather than specifying a range, e.g., ,+3, for either of these
commands, you can use the V Normal-mode command to make a Visual
block across all the lines that you want. Then typing : to begin the
command will auto-fill the range specifying the visual block, and you
can then enter either of the two commands starting with s or g:
:'<,'>s/$/\r
You can use a macro:
qao<esc>jq
then use 3#a to apply the macro 3 times over the last lines.
where:
qa "Start recording a macro named a
o "Insert new line under current line
<esc> "Exit insert mode
j " Move down next line
q " end macro
Select your visual selection with V
Then run a regex replace to replace one line break with two
:s/\n/\r\r/g
One can use the command
:g/^/pu_
on the whole buffer (by default) or on a selected range of lines.
Select the lines you want with V
Then type : and s/\ze/\r
Related
I have a file in which first 10 lines are the columns of a table and the rest 10 lines are the values of each column.
How can I use norm in VIM to append the values after each column names like this:
column1
...
column10
value1
...value10
-->
column1: value1
...
column10: value10
It is a little similar with this(Vim - Copy Nth word of each line, from line 10-100, to end of line), but I don't know how to go to line 1:10 and append the copied lines.
Any idea will be appreciated!
Fairly naive and crude way to do this, but:
:1,10norm! 10j0d$10kA: ^[p
Explanation:
1,10norm!: for lines 1 to 10, do the following (the ! means any custom mapping you have will be ignored, thanks to D. Ben Knoble for reminding of this):
10j: move down 10 lines
0d$: delete the whole line (not including newline)
10k: move back up 10 lines
A:: append (at the end of the line) ': ' (note the trailing space)
^[: input escape character, going back to normal mode. This (^[) is a single character and is inputted by typing Ctrl-v then escape, not by typing ^[.
p: paste the line deleted in step 3
Another (copy-pastable) way, (ab)using the substitute command:
:1,10s/\v(.*)\ze(.*\n){10}(.*)/\1: \3/ | 11,20d
which does:
1,10s/: for lines 1 to 10, execute the following substitution:
\v: use very-magic regex mode (see :help \v)
(.*): capture the entire current line (eg column1)
\ze: signal the end of the match. This way everything read (and captured) afterwards will not be affected (but can still be read)
(.*\n){10}: skip 10 (including current) lines, ie skip selector to 10 lines below
(.*): capture the line (eg value1)
/: end the 'select' part of the substitute command
\1: \3: replace with captured groups (eg column1: value1)
|: command separator
11,20d: delete lines 11 to 20
Use blockwise-visual mode to perform the operations.
You can enter visual block mode with Ctrl-V and it allows you to select and operate on columns. It also allows you to perform the same action on a block, which you can use to add the : to the lines with the column names.
I'll use normal Vim syntax for keystrokes in my examples, <C-v> means Ctrl-V.
Start by deleting the values into the default register, using a visual block:
11G<C-v>9j$d
Then Add the : to the column lines, also using a visual block:
1G<C-v>9j$A: <Esc>
Then add some more spaces to the first line, to ensure there's room for all the column names to fit:
A <Esc>
Finally, put the visual block at the end of the first line:
$p
It will actually put it on all lines all the way to the end.
This is slightly different from what you specified, since the values are all aligned on the same column. If you want different spacing, you can perhaps use a :s operation to fix spacing.
10:s/: */: /<cr>
Depending on where you pasted (if some column names had more trailing spaces than the first one), you might have some trailing spaces after the pasted values to fix as well, but that should be easy to do using a similar procedure.
Visual block operations are really powerful, it's a great feature to learn and keep in your "toolbox" in Vim. They're really handy with this kind of problem where thinking in "columns" makes the most sense.
I've tried this in Vim 8.1 and Neovim (nvr 2.1.10) with and without my ~/.vimrc (the latter to check if vimrc entries were causative -- no effect).
Given this example
apple
banana
carrot
dates
I can record a macro (#a)
yy
p
to yank and paste (i.e. duplicate) a line. When I apply (#a) that macro to individual lines, and repeat that macro (##) on individual lines it duplicates that line.
However, when I visually select those lines and try to apply the macro, trying any of these
:'<,>'norm #a ## :'<,>'norm #a on single line works
:'<,>'normal #a
:'<,>'norm! #a
:'<,>':norm #a
:'<,>':normal #a
:'<,>':norm! #a
:1,4norm! #a ## https://stackoverflow.com/a/390194/1904943
etc. the macro duplicates (once per selected line) the first line in the selected text:
apple
apple
apple
apple
apple
banana
carrot
dates
What's the problem, here?
The reason you're seeing this issue is because of the way ranges work on ex commands.
When you specify a range, that range is evaluated to line numbers before any operations occur. In this case, '< is evaluated as 1, and '> is evaluated as 4, because these are linewise operations. When you run the macro the first time on line 1, a new line is created with "apple". When the macro runs on line 2, that line contains "apple", so that word is duplicated, and so on. Whatever contents are on that line at the time the command is executed are used. You can see the same behavior if you use % (for all lines) or 2,4 to select "banana" and below.
However, POSIX specifies different behavior for the :g command:
The global and v commands are logically two-pass operations. First, mark the lines within the specified lines for which the line excluding the terminating matches (global) or does not match (v or global!) the specified pattern. Second, execute the ex commands given by commands, with the current line ( '.' ) set to each marked line.
That's why :g/^/norm yyp works here: because the lines to modify are marked before execution, and only the marked lines have the command executed. Lines that are inserted after the fact aren't considered. :g does accept ranges, as you noted, so you can limit your operation to a set of lines you'd like to handle.
file.txt
abc123
456efg
hi789j
command
:set hlsearch
/\d\+
I want to copy highlighted text bellow to clipboard (or register):
123
456
789
Just like
egrep -o '[0-9]+' file.txt
Thanks.
One can follow the below procedure.
Empty a register (for instance, "a).
qaq
or
:let #a = ''
Run the command1
:g/\d\+/norm!//e^Mv??^M"Ay
If it is necessary to append a new line character after each of the
matches, run this command instead:2
:g/\d\+/norm!//e^Ma^M^[??^Mv$"Ayu
Type ^M as Ctrl+V then Enter (or
Ctrl+M), type ^[ as
Ctrl+V then Esc (or
Ctrl+[). In order not to retype the pattern
that just have been used in search, one can press
Ctrl+R, / to automatically insert
last search pattern.
Also one can record the command to execute on matched lines (the part
following norm!) as a macro. This allows to see the actions
immediately on a sample line and to make sure they are correct. Then,
the macro can be applied using :global:
:g/\d\+/norm!#z
1 At the top level, the command is a :global executing the Ex
command norm!//e^Mv??^M"Ay on each of the lines that match the pattern
\d\+. The Ex command begins with the norm! command to execute the Normal
mode commands //e^Mv??^M"Ay. These are three commands separated by the
carriage return symbol ^M. The first one, //e, looks for the search
pattern (which is set to the pattern used in the global command) and put the
cursor to the last symbol of the match (because of the flag e, see :help
search-offset). Then v command starts Visual mode. The command ?? looks
for the last search pattern backwards (and put the cursor to the first
character of the match), thus selecting the text that match the last search
pattern. The last command, "Ay, yanks the selected text appending it to the
a register.
2 The second global command resembles the first one in outline.
At each of the matched lines, it moves cursor to the last symbol of the match
and inserts newline after that symbol. Then it puts the cursor to the start
of the match and selects (in Visual mode) everything up to the end of line
(including just inserted newline). Finally, the command appends the selected
text to the register, and undoes newline inserting.
3 One can always see the actions recorded in particular macro by
examining the contents of the corresponding register using :di z or "zp,
for example.
If your text obeys the pattern you posted you can start visual mode blockwise with Ctrl+V and select from 1 in the first line to 9 in the last line. Then you just copy to the + register, which is the system clipboard, by typing "+y.
Edit:
I have tested this new solution for the text:
abc123
456efg
hi789j
Replace all non-digit by nothing with :%s/\D//g and the result will be:
123
456
789
Copy it to the clipboard typing "+y%, then revert the changes with u and you are done.
Use this command to extract all URLs, and append to the end of file:
:let urls = [] | %s/http:[^"]*/\=add(urls, submatch(0))[-1]/g | call setline(line('$')+1, urls)
Often times it seems I have a list of items, and I need to add numbers in front of them. For example:
Item one
Item two
Item three
Which should be:
1. Item one
2. Item two
3. Item three
In vim, I can press I in edit mode, insert "1.", hit escape. Then I go to the next line, press ., and then ^A to increment the number. This seems hugely inefficient... how would I make a macro so that I can go to the next line, and insert a number at the beginning which is one greater than the line before?
You can easily record a macro to do it.
First insert 1. at the start of the first line (there are a couple of spaces after the 1. but you can't see them).
Go to the start of the second line and go into record mode with qa.
Press the following key sequence:
i # insert mode
<ctrl-Y><ctrl-Y><ctrl-Y> # copy the first few characters from the line above
<ESC> # back to normal mode
| # go back to the start of the line
<ctrl-A> # increment the number
j # down to the next line
q # stop recording
Now you can play back the recording with #a (the first time; for subsequent times, you can do ## to repeat the last-executed macro) and it will add a new incremented number to the start of each line.
Select your lines in visual mode with: V, then type:
:'<,'>s/^\s*\zs/\=(line('.') - line("'<")+1).'. '
Which is easy to put in a command:
command! -nargs=0 -range=% Number <line1>,<line2>s/^\s*\zs/\=(line('.') - <line1>+1).'. '
Here's an easy way, without recording a macro:
Make a blockwise, visual selection on the first character of each list item:
^<C-V>2j
Insert a 0. at the beginning of these lines:
I0. <Esc>
Re-select the visual selection (which is now all of the 0s) with gv and increment them as a sequence g<C-A>:
gvg<C-A>
The entire sequence: ^<C-V>2jI0. <Esc>gvg<C-A>.
A recording of the process in action.
There are also some plugins for doing this type of work if you have to do it on occasion:
http://vim.sourceforge.net/scripts/script.php?script_id=670
You can use the 'record' feature.
It is an easy way to record macros in Vim.
See :help record
In normal mode 'qa' to start recording what you type in the 'a' register
Type the necessary command to insert a number at the beginning of line, copy it to next line and use CTRL-A to increase its value.
'q' to end the recording
then '#a' to replay the macro stored in register 'a'
('##' repeat the last macro).
And you can do things like '20#a' to do it twenty times in a row.
It is pretty handy to repeat text modification.
Depending of the cases, it is easier or harder to use than a regexp.
Maybe it's not a macro solution, but at least it's easy.
add numbers to all lines
It's possible to use :%!nl -ba or :%!cat -n commands which will add line numbers to all the lines.
On Windows, you've to have Cygwin/MSYS/SUA installed.
add numbers to selected lines
To add numbers only for selected lines, please select them in visual mode (v and cursors), then when finished - execute the command: :%!nl (ignore blank lines) or :%!cat -n (blank lines included).
formatting
To remove extra spaces, select them in visual block (Ctrl+v) and remove them (x).
To add some characters (., :, )) after the numbers, select them in visual block (Ctrl+v), then append the character (A, type the character, then finish with Esc).
Insert a number at the start of the block of text eg.
1. Item One
Enter the vim normal mode command as follows:
qb^yW+P^<Ctrl-A>q
This means:
qb # start recording macro 'b'
^ # move to start of text on the line
yW # 'yank' or copy a word including the ending whitespace.
+ # move one line down to the start of the next line
P # place text ahead of the cursor
^ # move to start of text
<Ctrl-A> # increment text
q # Finish recording macro
What this allows you to do is replay the macro across the last line of numbered list as many times as needed.
It is some time later and I think it is time to upgrade this answer, at least for neovim users.
Here I wrote a lua function you can bind to Enter and it will work on any imaginable type of list, such as
1. foo
1.99-> bar
and after pressing enter, this line will be added:
1.100->
all using this function
vim.api.nvim_set_keymap('i','<Enter>','v:lua.enter_or_list()', {expr = true})
function _G.enter_or_list()
local line = vim.api.nvim_buf_get_lines(0, vim.fn.line('.') - 1, -1, false)[1]:match('^%s*[^%a%s]+')
if not line then
return '\r'
else
local start, finish = line:find('[^%a%s]*%d')
local main = line:sub(start,finish)
local suffix = line:sub(finish+1)
return table.concat({
'\r',
main,
vim.api.nvim_replace_termcodes('<Esc><C-a>a', true, true, true),
suffix,
' '
})
end
end
for vim users, I have a little simpler, but a little less capable keybinding:
imap <silent> <S-Enter> <CR><Esc>kk<End>Ev<Home>yjpk<End>e<C-a><End>a<Space>
I hope this will be useful to other people as well, as it is very convenient.
Cheers
I'm aware that in Vim I can often repeat a command by simply adding a number in front of it. For example, one can delete 5 lines by:
5dd
It's also often possible to specify a range of lines to apply a command to, for example
:10,20s:hello:goodbye:gc
How can I perform a 'vertical edit'? I'd like to, for example, insert a particular symbol, say a comma, at the beggining (skipping whitespace, i.e. what you'd get if you type a comma after Shift-I in command mode) of every line in a given range. How can this be achieved (without resorting to down-period-down-period-down-period)?
Ctrl-v enters visual mode blockwise. You can then move (hjkl-wise, as normal), and if you want to insert something on multiple lines, use Shift-i.
So for the text:
abc123abc
def456def
ghi789ghi
if you hit Ctrl-v with your cursor over the 1, hit j twice to go down two columns, then Shift-i,ESC , your text would look like this:
abc,123abc
def,456def
ghi,789ghi
(the multi-line insert has a little lag, and won't render until AFTER you hit ESC).
:10,20s/^/,/
Or use a macro, record with:
q a i , ESC j h q
use with:
# a
Explanation: q a starts recording a macro to register a, q ends recording. There are registers a to z available for this.
That's what the :norm(al) command is for:
:10,20 normal I,
If you are already using the '.' to repeat your last command a lot, then I found this to be the most convenient solution so far. It allows you to repeat your last command on each line of a visual block by using
" allow the . to execute once for each line of a visual selection
vnoremap . :normal .<CR>
I believe the easiest way to do this is
1) record a macro for one line, call it 'a'; in this case one types
q a I , ESC j q
2) select the block of lines that you want to apply the macro to
3) use the 'norm' function to execute macro 'a' over this block of lines, i.e.,
:'<,'>norm#a
I think the easiest is to record a macro, and then repeat the macro as many times as you want. For example to add a comma at the start of every line, you type:
q a I , ESC j q
to repeat that 5 times, you enter
5 # a
With your edit already saved in the . operator, do the following:
Select text you want to apply the operator to using visual mode
Then run the command :norm .
Apart from the macros, as already answered, for the specific case of inserting a comma in a range of lines (say from line 10 to 20), you might do something like:
:10,20s/\(.*\)/,\1
That is, you can create a numbered group match with \( and \), and use \1 in the replacement string to say "replace with the contents of the match".
I use block visual mode. This allows you to perform inserts/edits across multiple lines (aka 'vertical edits').