I want to understand what gets stored in Vim's dot(.) register.
Consider the following text:
This is Line one
This is Line two
This is Line three
With the cursor on the first line, if I do A;<esc> I can repeat the same action for the next line by j.
However, if I do the action like removing the last character on the first line by $x and then try to repeat it for the next line by j., it is not removing the last character of the line, instead it just deletes the character under the cursor.
So why is dot command able to remember the position in the first example A;<esc> whereas not able to do the same for $x ?
From :help .:
. Repeat last change, with count replaced with [count].
Also repeat a yank command, when the 'y' flag is
included in 'cpoptions'. Does not repeat a
command-line command.
With A;, the change is to insert a ; at the end of the current line. A moves the cursor and switches to insert mode.
With $x, the $ first moves the cursor, then the x command deletes a character. They are not linked together, so the change is only the deletion of the character at the current cursor position.
(Put another way, the motion is only part of the change if the command takes a motion operator after the command, like d, or if the motion is implicit in the command, like with A.)
Related
Say, I have 10 consecutive lines followed by another 10 lines, e.g.:
1
2
⋮
10
a
b
⋮
j
I want to append the lines from the second range (a…j) to the lines in the first range (1…10), so that the above 20 lines turn into the following 10 lines, instead:
1a
2b
⋮
10j
Which Vim commands can I use to achieve this?
I would start going to line with a, then CTRL-V, 10j$d to blockwise delete everything.
Then :set virtualedit=all, goto first line, move cursor right by 10 characters for example, and press p. Now remove first sequence of spaces in your ten lines.
There is a second way, which is basically the same:
10dd
:call setreg('"', #", '^V') where ^V is typed with CTRL-V CTRL-V
(this will turn the register blockwise)
P
:,+10s/ //g
You can also do that programatically: enter Ex mode with Q, and type this
let i = 1
while i <= 10
call setline(i, getline(i) . getline(11))
11d
let i = i + 1
endwhile
vi
If you intend to reuse it put this into your vimrc :
function PasteLines(startline,numlines)
let i = 0
while i < a:numlines
call setline(a:startline+i, getline(a:startline+i) . getline(a:startline+a:numlines))
exec '' . (a:startline+a:numlines) . 'd'
let i = i + 1
endwhile
endfunction
And call it with :
:call PasteLines(1, 10)
where 1 is the first line, and 10 the number of lines. You need therefore 20 lines.
This would be my way:
qaG"aDdd9-$"apq
9#a
Explanation:
q # Begin recording typed characters...
a # to register 'a'
G # Set cursor in last line.
"aD # Delete the content from the beginning of line till the end and save it in register 'a'.
dd # Previous command deleted the content but left the line in blank, delete the complete line.
9- # Go back 9 lines.
$ # Set cursor at the end of current line (last number in your example).
"ap # Paste content of register 'a' (at end of line without newline character).
q # Stop recording.
---------------
9 # Run nine times.
#a # Commands of register 'a' (all previous commmands).
Register 'a' where I record commands is a different register of where I save content of each line, although they are named the same (letter 'a').
1. Assuming that the cursor is located on the first line of the
twenty-line block, let us consider the following short Ex command:
:,+9g/^/''+10m.|-j!
This is the :global command running on lines that belong to the
range of the next ten lines (starting from the current one). On every
of these lines, two Ex commands, ''+10m. and -j!, are sequentially
executed. The first command takes the tenth line under the line at
which the cursor has been positioned and inserts it just below the
line where the cursor is currently located, using the :move command.
The :join command, -j!, appends the just moved line to the one
just above it (without inserting or deleting whitespace in between,
due to the ! modifier).
There are two considerations that is necessary to take into account in
order to get the idea of that line movement. First, before the command
specified in a :global is executed on yet another line, the cursor
is positioned at the first column of that line. This way, the address
referenced in the aforementioned :move command as ., corresponds
to the latest line on which the command is currently being run.
Second, the number of the line that was the current one just before
a :global command was sent to execution, is added to the jump list.
Therefore, its address can be obtained in ranges through the
' pseudo-mark (see :help :range).
See also my answer to the question “Vim paste -d ' ' behaviour
out of the box?”.
2. The same effect can be achieved by means of Normal mode commands:
qqdd9+PgJ9-q9#q
This sequence of commands implements the same moving scheme, using a
macros to repeat a single-line transferring operation. The commands to
concatenate the first pair of lines, dd9+PgJ9-, are recorded in the
"q register using the q command. Similarly to the Ex command
proposed above, the macros deletes the current line (dd), moves the
cursor nine lines downward (9+), inserts the just cut line above the
new cursor position (P), joins that two lines without adding or
removing any spaces between them (gJ), and moves the cursor nine
lines upward (9-). Finally, these actions are automatically iterated
nine times using the # command to join the remaining nine pairs of
corresponding lines.
I have the following Ruby code:
if some_cond && another
foo_bar
end
and I want to change it to:
foo_bar if some_cond && another
What are the most idiomatic ways to do that in Vim?
Assuming that the cursor is located at the if-line prior to
refactoring (not necessarily at the beginning of that line),
I would use the following sequence of Normal-mode commands:
ddjVpkJ<<
or this chain of Ex commands:
:m+|-j|<|+d
Here the if-line is first moved down one line by the :move + command.
The :move command cuts a given range of lines (the current line, if
not specified) and pastes it below the line addressed by the argument.
The + address is a shorthand for .+1 referring to the next line
(see :help {address}).
Second, the line containing the body of the conditional statement is
joined with the just moved if-line. The :join command concatenates
a given range of lines into a single line. The - range is a shortened
form of the .-1 address referring to the line just above the cursor
(see :help {address}).
Third, the newly joined line is unindented by one shiftwidth using
the :< command.
Finally, the remaining end-line, which can now be addressed as +,
is removed by the :delete command.
I see few (probably non-optimal) solutions:
cursor in first character in first line:
D - remove if condition but leave cursor in same position (don't delete line)
J - join next line to current
A <Space> <ESC> - append space and exit to Normal mode
p - paste if condition
and then remove remaining end with jdd
cursor in first character in first line, as previously:
j - move to next line
dd - remove this line
k - move back to if condition
P - paste removed line before actual line, cursor should be placed to pasted line
J - join next line to current
== or << - unindent current line
and then remove remaining end with jdd
another solution:
j - move to second line
JD - join line with next, remove what was joined
dd - remove current line
k - step to previous line
PJ<< - paste, join and unshift
It's probably not optimal, but I do it without thinking, because most of this commands are in my muscle memory (you don't think how to move around you, how to yank/delete and paste most of the time, and joining line is also helpful to remember).
If you have virtualedit enabled in config, instead of A <Space> <Esc> you can $ <Space>, but I find $ harder to use than A followed by Ctrl-[ (it's simmilar to ESC).
As an advice: if you use some upper letter commands, try to chain them if it's possible, so you only need to keep Shift pressed and then execute some commands, instead of mixing upper and lower letter commands and pressing two keys at a time (upper letter is 2 key press, one is Shift). Once I found combo helpful for restarting server in console Ctrl+cpj, which sends Ctrl+c, Ctrl+p (previous command) and Ctrl+j (Enter key) with single Ctrl press. Since then I try to find simmilar time-saving combination in Vim too mostly with Shift, as Ctrl is not much used in Vim.
Yet another way:
ddpkJjdd
ddp swap the two lines
kJ move up and join the lines
== re-indent the line
jdd move down and delete the last line
There are probably 30 ways to do this.
Here is one, assuming you are starting from the end of the word end in normal mode:
dd (delete last line)
"aD (delete and copy foo_bar to buffer a)
dd (delete now-empty line 2)
"aP (paste from buffer a before caret)
aSpaceEsc (insert space and return to normal mode)
Again, "properly" rarely applies in Vim because there are so many ways to accomplish something. This is so small a change that even re-typing foo_bar could be justifiable.
In vim I filter, say the current single line, using !! through a Unix command. To achieve this I defined the following shortcut in .vimrc
:map <Enter> !!mycommand<CR>:,+1<CR>
Pressing <Enter> this takes me to the line below the current if mycommand replaces my single input line be exactly one output line. If the output has more lines (number of lines unknown before command execution) it will still take me to the line below the current.
Now, I would like to know how I can always get to the first line below the inserted output of mycommand.
The modified shortcut would then allow me to 'execute' the text file line by line using just <Enter> displaying the output each time.
If there is no way to do this without any previous knowledge of the output of mycommand, maybe there is one knowing say the first character of each output line.
Thanks a lot!
You can use the special marks '[ and '], which mark the start and end of the last changed (or yanked) text. Change your map to:
:map <Enter> !!mycommand<CR>']+
Note that I'm using + in place of your ex command. This will jump to the first non-blank character in next line. If that's not what you want, you may try simply j or, use a shorter version of your original map:
:map <Enter> !!mycommand<CR>']:+1<CR>
You don't really need the comma, to make this a range. This command is just a simplified :#, where # is a line number to jump. Here you can use . meaning "current line", and then :.+1 moves to the next line. But you can omit the dot, and that's why :+1 does the same.
I'm trying without success to put a normal command together with a search command in a function using vimscript:
This is my command:
d/\S
(delete from current cursor position to next "not space" character)
I don't know how to put this in vimscript.
I tried this but it doesn't work:
normal d
let #/ = \\S
Try this:
call search("\\S", "sW")
:normal d`'
The first line sets the ' previous context mark to the current cursor position, and then moves the cursor to the first non-whitespace char.
The second line then deletes backwards to the previous cursor position.
I'm hand-editing CNC Gcode text files and need a way to reference locations in the file and on the toolpath.
I want to modify every line in the text file so that it begins with the the upper case letter N followed by the line number, incremented in tens for each successive line, then a whitespace followed by the original text on that line. How can I do this in Vim?
I'm not sure about vi, but (since you're using the vim tag) Vim allows you to accomplish your task as follows:
Adjust the first line by hand (insert a N10 at the beginning of the line), then put the cursor at the beginning of the next line.
Press qb to start recording a macro (the b names the register used to store the macro; feel free to use a different letter -- and definitely do use a different letter if you've got something useful stashed away in b).
Move the cursor upward to the beginning of the previous line (which you have adjusted by hand). Press v to start visual selection mode, then f to move the cursor to the next space on the line (if you use a single space as your whitespace separator, that is; adjust this step if you're using a tab or multiple spaces).
Press y to yank the selected text. This will also remove the visual selection.
Move the cursor to the beginning of the next line. Press P to insert the previously yanked text before the cursor, that is, on the very beginning of the line.
Move the cursor to the numeric part of the line header. Press 10 C-a (1, 0, control + A) to increment that number by 10.
Move the cursor to the beginning of the next line. Press q to stop recording the macro.
Press 10000000 #b to execute the macro 10000000 times or until it hits the end of the file. This should be enough to take care of all the lines in your file, unless it is really huge, in which case use a bigger number.
...or use Vim to write a simple script to do the job in whichever language you like best, then run it from a terminal (or from withing Vim with something like :!./your-script-name). ;-)
The following command will prepend ‘N<line number * 10>’ to every line:
:g/^/exe 'normal! 0iN' . (line('.')*10) . ' '
You can do it easily in Vim with this:
:%s/^/\=line(".")*10 . " "/
This replaces the start of every line with the result of an expression that gives the line number times ten, followed by a space.
I have not timed it, but I suspect it might be noticeably faster than the other Vim solutions.
Cheating answer:
:%!awk '{print "N" NR "0", $0}'
There are two ways to implement that without resorting to external
tools: via a macro or by using Vimscript. In my opinion, the first way
is a little cumbersome (and probably not as effective as the solution
listed below).
The second way can be implemented like this (put the code into your
.vimrc or source it some other way):
function! NumberLines(format) range
let lfmt = (empty(a:format) ? 'N%04d' : a:format[0]) . ' %s'
for lnum in range(a:firstline, a:lastline)
call setline(lnum, printf(lfmt, lnum, getline(lnum)))
endfor
endfunction
The NumberLines function enumerates all lines of the file in a given
range and prepends to each line its number according to the provided
printf-format (N%04d, by default).
To simplify the usage of this function, it is convenient to create
a command that accepting a range of lines to process (the whole file,
by default) and a optional argument for the line number format:
command! -range=% -nargs=? NumberLines <line1>,<line2>call NumberLines([<f-args>])