How can I a put a line like "==========" quickly in vim - vim

I am editing restructuredtext files. I often need to put some charactors like "=-`~" in one line, and I want the length of the line match the previous line. How should I do this in vim?
a long long title
=================
Thanks!

Another that will work:
yypv$r=

How about yyp:s/./=/g ?
You can map that to a key, e.g.
:map <F5> yyp:s/./=/g<CR>

I would use yypver= to avoid searching & shift button as much as possible. This could of course also be mapped to a key.

If your line starts without any trailing whitespace:
Hello World
Normal Mode:
YpVr=
Gives:
Hello World
===========
Explanation
Y -> Yank entire line, like yy
p -> paste the line
V -> select whole line in visual line mode
r -> replace all of select with next character
= -> the character to replace the others
If you line has leading whitespace, eg:
Hello World
Use:
Ypv$r=
Giving:
Hello World
===========
We use v$ visual selection to the end of the line, rather than using V to select everything on the line.
If you had trailing whitespace you can use the g_ movement to get to the last non whitespace character.

When the cursor is placed on a long long line you could use something like
:s/\(.*\)/\=submatch(1) . nr2char(13) . repeat('=', strlen(submatch(1)))/
In order to make it more easy to do the substitution, I'd then use a map:
nmap __ :s/\(.*\)/\=submatch(1) . nr2char(13) . repeat('=', strlen(submatch(1)))/
So, you can underline the line where the cursor is on with typing __.

Related

How to use Vim to do multiple line edit

I have text like this:
w ky,
wyz,
wyy,
wj,
w w,
and I want to change it to this:
"w ky",
"wyz",
"wyy",
"wj",
"w w",
I do it now using:
record a macro to insert double quota in one line, then go to next line qa0wi"$i"j
then just type 4#a
Yes, it works, but is there an easier way to do this?
There is an easier way. You can use the norm command. I would recommend this:
Visually select all of the lines
Type
:norm I"<C-v><esc>$i"<cr>
When you actually type this (before hitting enter), the text that should be shown in your command line is:
:'<,'>norm I"^[$i"
The norm command tells vim to simulate a set of normal mode keystrokes on certain lines. In this case, the command is:
:'<,'> " On every line in the visual selection:
norm " Do the following as if typed in normal mode:
I"<esc>$i" " Insert an '"', escape, then insert a '"' at the end (before the comma)
You can also do this without using a visual selection, by typing <n>:norm ..., and the command will apply the current n lines. (the current line and the next n-1 lines)
Doing a "very magic search \v" we can search...
\v(\w ?\w+),
\v ........... starts very magic search mode
( ........... starts group one
\w ........... any word
? ........... optional space
+ ........... one or more
) ........... ends group one
After testing the search we can pass into our command or
use the last search by placing two slashes on the search pattern
%s/\v(\w ?\w+),/"\1",/g
%s//"\1",/g
everything matched on group one can be referred by \1.
Do a basic multi-line edit at the front then do a string replace on , with ",.

Vim: delete empty lines around cursor

Suppose I'm editing the following document (* = cursor):
Lions
Tigers
Kittens
Puppies
*
Humans
What sequence can I use to delete the surrounding white space so that I'm left with:
Lions
Tigers
Kittens
Puppies
*
Humans
Note: I'm looking for an answer that handles any number of empty lines, not just this exact case.
EDIT 1: Line numbers are unknown and I only want to effect the span my cursor is in.
EDIT 2: Edited example to show I need to preserve leading whitespace on edges
Thanks
Easy. In normal mode, dipO<Esc> should do it.
Explanation:
dip on a blank line deletes it and all adjacent blank lines.
O<Esc> opens a new empty line, then goes back to normal mode.
Even more concise, cip<Esc> would roll these two steps into one, as suggested by #Lorkenpeist.
A possible solution is to use the :join command with a range:
:?.?+1,/./-1join!
Explanation:
[range]join! will join together a [range] of lines. The ! means with out inserting any extra space.
The starting point is to search backwards to the first character then down 1 line, ?.?+1
As the 1 in +1 can be assumed this can be abbreviated ?.?+
The ending point is to search forwards to the next character then up 1 line, /./-1
Same as before the 1 can be assumed so, /./-
As we are using the same pattern only searching forward the pattern can be omitted. //-
The command :join can be shorted to just :j
Final shortened command:
:?.?+,//-j!
Here are some related commands that might be handy:
1) to delete all empty lines:
:g/^$/d
:v/./d
2) Squeeze all empty lines into just 1 empty line:
:v/./,//-j
For more help see:
:h :j
:h [range]
:h :g
:h :v
Short Answer: ()V)kc<esc>
In normal mode, if you type () your cursor will move to the first blank line. ( moves the cursor to the beginning of the previous block of non-blank lines, and ) moves the cursor to the end (specifically, to the first blank line after said block). Then a simple d) will delete all text until the beginning of the next non-blank line. So the complete sequence is ()d).
EDIT: You're right, that deletes the whitespace at the beginning of the next non-blank line. Instead of d) try V)kd. V puts you in visual line mode, ) jumps to the first non-blank line (skipping the whitespace at the beginning of the line), k moves the cursor up one line. At this point you've selected all the blank lines, so d deletes the selection.
Finally, type O (capital O) followed by escape to crate a new blank line to replace the ones you deleted. Alternatively, replacing dO<Escape> with c<Escape> does the same thing with one less keystroke, so the entire sequence would be ()V)kc<Esc>.
These answers are irrelevant after the updated question:
This may not be the answer you want to hear, but I would make use of ranges. Take a look at the line number for the first empty line (let's say 55 for example) and the second to last empty line (perhaps 67). Then just do :55,67d.
Or, perhaps you only want there to ever be one empty line in your whole file. In that case you can match any occurrence of one or more empty lines and replace them with one empty line.
:%s/\(^$\n\)\+/\r/
This answer works:
If you just want to use normal mode you could search for the last line with something on it. For instance,
/.<Enter>kkVNjd
I didn't test so much, but it should work for your examples. There maybe more elegant solutions.
function! DelWrapLines()
while match(getline('.'),'^\s*$')>=0
exe 'normal kJ'
endwhile
exe 'silent +|+,/./-1d|noh'
exe 'normal k'
endfunction
source it and try :call DelWrapLines()
I know this question has already been resolved, but I just found a great solution in "sed & awk, 2nd Ed." (O'Reilly) that I thought was worth sharing. It does not use vim at all, but instead uses sed. This script will replace all instances of one or more blank lines (assuming there is no whitespace in those lines) with a single blank line. On the command line:
sed '/ˆ$/{
N
/ˆ\n$/D
}' myfile
Keep in mind that sed does not actually edit the file, but instead prints the edited lines to standard output. You can redirect this input to a file:
sed '/ˆ$/{
N
/ˆ\n$/D
}' myfile > tempfile
Be careful though, if you try to write it directly to myfile, it will just delete the entire contents of the file, which is clearly not what you want! After you write the output to tempfile, you can just mv tempfile myfile and tada! All instances of multiple blank lines are replaced by a single blank line.
Even better:
cat -s myfile > temp
mv temp myfile
cat is awesome, yes?
Bestest:
If you want to do it inside vim, you can replace all instances of multiple blank lines with a single blank line by using vim's handy feature of executing shell commands on a range of lines within vim.
:%!cat -s
That's all it takes, and your entire file is reformatted all nice!

Vim: Replacing a line with another one yanked before

At least once per day i have the following situation:
A: This line should also replace line X
...
X: This is line should be replaced
I believe that I don't perform that task efficiently.
What I do:
Go to line A: AG (replace A with the line number)
Yank line A: yy
Go to line X: XG (replace X with the line number)
Paste line A: P
Move to old line: j
Delete old line: dd
This has the additional disadvantage that line X is now in the default register, which is annoying if I find another line that should be replaced with A. Yanking to and pasting from an additional register ("ayy, "aP) makes this simple task even less efficient.
My Questions:
Did I miss a built-in Vim command to replace a line yanked before?
If not, how can I bind my own command that leaves (or restores) the yanked line in the default register?
Vp: select line, paste what was yanked
What I would do :
36G (replace 36 with the line number you want to go to)
Y
70G (replace 70 with the line number you want to go to)
Vp
You don't have to leave normal mode, but it does yank the line. You can however use V"0p which will always put the line yanked in step 2.
This has the additional disadvantage
that line X is now in the default
register, which is annoying if I find
another line that should be replaced
with A.
To delete text without affecting the normal registers, you can use the Black hole register "_:
"_dd
Building on the answers that suggest using Vp or VP to paste over a line -- to avoid changing the contents of the yank register I find the most ergonomic command is simply:
VPY
yy
j (move to the line you want to replace),and then
Vp (uppercase v and then p, will replace with the yanked content)
I would use commandline (Ex) mode and do the following two commands
:XmA
:Ad
This simply moves line X to just under A, then deleting A moves that line up
For example
:7m3
:3d
Move to the start of the first line.
y, $ – copy the line without the linebreak at the end
Move to the start of the target line.
V, p – replace just one target line
c, c, Ctrlr, 0, Esc – replace the target line with the original yank
Move to the start of the next target line.
. – repeats the command issued at 4.2.
Notes:
4.1 is y, $ because if you do y, y or Y you will copy the linebreak, and Ctrlr, 0 actually adds the linebreak below your target line.
4.2 replaces V p, which doesn’t work with repeat because technically the last action is delete, so . would just delete a line.
If anyone knows how to issue ‘replace current line with register’ from EX mode (command line), I would like to hear from you (and to know where you found the documentation). There may be a repeatable EX command which is faster than 4.2 and/or does not have the linebreak caveat.
You can also do:
Vy (in normal mode at the line you want to copy)
Vp (in normal mode at the line you want to replace)
Doesn't create spaces or line ends.
Cursor is placed at the start of the copied text.
The same keys can be used to yank/paste more than one line.
V (in normal mode at what you want to yank)
(use jk to move the selection)
y (to yank the selection)
V (in normal mode at where you want to paste)
(use jk to move the selection)
p (to replace the selection with the yanked lines)
Here's what I would do
Move beginning of line A, AG (where A is a line number obviously)
Yank line to some register, e.g. a (without new line). Type "ay$
Move to insert line, XG
Substitute line, S
Insert from register a, Ctrl-Ra
You can use this with visual mode.
Go to line A: AG
Select the line with visual mode: VESC
go to line X: XG
Enter substitute mode for the line: S
Paste the line you copied: shift+insert (or whatever other you mapping you have for pasting from the clipboard).
In light of the recent comment by cicld (thank you!), I see that I didn't grasp the original issue fully. Moving the line is not appropriate, but copying is (since the line is yanked.) So I would revise it to:
:1t20:20d_
Copy the 1st line (:t command is an alias for :copy) after line 20 (will place it on line 21)
Delete line 20, putting the deleted line into the 'blackhole' register (_) (i.e. not affecting the current yank buffer)
As mentioned in the recent comment, this will not affect the current cursor position.
You can use this commands in Normal Mode:
:AmX | Xd
the m command is for m[ove], which moves the line number A after the line number X, if you want to copy instead of move the line, use co[py]. the d command is for d[elete].
You can move(copy using co) a range of lines using
:start,end m X
:ay (where a is the line number. Example :20y). This yanks a line(pun intended).
Vp
I find it easier to use Ex command for this; ex. to move line 9 to 46:
:46|9m.|-1d
This will move the cursor to line 46, move line 9 below the current,
then delete the previous line (since moved line is the current one).
Or using mark(s), using mark 'a':
:46ma a|9m'a|'ad
I often have to Y one line and replace it in multiple places, each of which have a different value (which means that I can't do a regex).
Y to yank the desired original line
and then on every line that you'd like to replace, VpzeroY
i would simple use the "Black hole" register:
given:
nnoremap < C-d > "_dd
the solution would be:
< C-d >yy
If you only want to change part of the line you can do that this way:
Move to position of what part of text you want to copy
y,$ - Yank from cursor to EndOfLine
move to position where you want to replace
v,$,p - replace from cursor to EndOfLine with contents of register

How do I join two lines in vi?

I have two lines in a text file like below:
S<Switch_ID>_F<File type>
_ID<ID number>_T<date+time>_O<Original File name>.DAT
I want to append the two lines in vi like below:
S<Switch_ID>_F<File type>_ID<ID number>_T<date+time>_O<Original File name>.DAT
The second line got deleted and the contents of the second line was appended to the first line.
How could I do it using command mode in vi?
Shift+J removes the line change character from the current line, so by pressing "J" at any place in the line you can combine the current line and the next line in the way you want.
Vi or Vim?
Anyway, the following command works for Vim in 'nocompatible' mode. That is, I suppose, almost pure vi.
:join!
If you want to do it from normal command use
gJ
With 'gJ' you join lines as is -- without adding or removing whitespaces:
S<Switch_ID>_F<File type>
_ID<ID number>_T<date+time>_O<Original File name>.DAT
Result:
S<Switch_ID>_F<File type>_ID<ID number>_T<date+time>_O<Original File name>.DAT
With 'J' command you will have:
S<Switch_ID>_F<File type> _ID<ID number>_T<date+time>_O<Original File name>.DAT
Note space between type> and _ID.
This should do it:
J
In vi, J (that's Shift + J) or :join should do what you want, for the most part. Note that they adjust whitespace. In particular, you'll end up with a space between the two joined lines in many cases, and if the second line is indented that indentation will be removed prior to joining.
In Vim you can also use gJ (G, then Shift + J) or :join!. These will join lines without doing any whitespace adjustments.
In Vim, see :help J for more information.
Just replace the "\n" with "".
In vi/Vim for every line in the document:
%s/>\n_/>_/g
If you want to confirm every replacement:
%s/>\n_/>_/gc
If you want to join the selected lines (you are in visual mode), then just press gJ to join your lines with no spaces whatsoever.
This is described in greater detail on the vi/Vim Stack Exchange site.
Press Shift + 4 ("$") on the first line, then Shift + j ("J").
And if you want help, go into vi, and then press F1.
In Vim you can also use gJ.
ََ
Another way of joining two lines without placing cursor to that line is:
:6,6s#\n##
Here 6 is the line number to which another line will be join. To display the line number, use :set nu.
If we are on the cursor where the next line should be joined, then:
:s#\n##
In both cases we don't need g like :s#\n##g, because on one line only one \n exist.

Vim delete blank lines

What command can I run to remove blank lines in Vim?
:g/^$/d
:g will execute a command on lines which match a regex. The regex is 'blank line' and the command is :d (delete)
Found it, it's:
g/^\s*$/d
Source: Power of g at vim wikia
Brief explanation of :g
:[range]g/pattern/cmd
This acts on the specified [range] (default whole file), by executing the Ex command cmd for each line matching pattern (an Ex command is one starting with a colon such as :d for delete). Before executing cmd, "." is set to the current line.
:v/./d
or
:g/^$/d
or
:%!cat -s
The following can be used to remove only multi blank lines (reduce them to a single blank line) and leaving single blank lines intact:
:g/^\_$\n\_^$/d
how to remove all the blanks lines
:%s,\n\n,^M,g
(do this multiple times util all the empty lines went gone)
how to remove all the blanks lines leaving SINGLE empty line
:%s,\n\n\n,^M^M,g
(do this multiple times)
how to remove all the blanks lines leaving TWO empty lines AT MAXIMUM,
:%s,\n\n\n\n,^M^M^M,g
(do this multiple times)
in order to input ^M, I have to control-Q and control-M in windows
How about:
:g/^[ \t]*$/d
This works for me
:%s/^\s*$\n//gc
work with perl in vim:
:%!perl -pi -e s/^\s*$//g
I tried a few of the answers on this page, but a lot of them didn't work for me. Maybe because I'm using Vim on Windows 7 (don't mock, just have pity on me :p)?
Here's the easiest one that I found that works on Vim in Windows 7:
:v/\S/d
Here's a longer answer on the Vim Wikia: http://vim.wikia.com/wiki/Remove_unwanted_empty_lines
Press delete key in insert mode to remove blank lines.
This function only remove two or more blank lines, put the lines below in your vimrc, then use \d to call function
fun! DelBlank()
let _s=#/
let l = line(".")
let c = col(".")
:g/^\n\{2,}/d
let #/=_s
call cursor(l, c)
endfun
map <special> <leader>d :keepjumps call DelBlank()<cr>
:g/^\s*$/d
^ begin of a line
\s* at least 0 spaces and as many as possible (greedy)
$ end of a line
paste
:command -range=% DBL :<line1>,<line2>g/^\s*$/d
in your .vimrc,then restart your vim.
if you use command :5,12DBL
it will delete all blank lines between 5th row and 12th row.
I think my answer is the best answer!
If something has double linespaced your text then this command will remove the double spacing and merge pre-existing repeating blank lines into a single blank line. It uses a temporary delimiter of ^^^ at the start of a line so if this clashes with your content choose something else. Lines containing only whitespace are treated as blank.
%s/^\s*\n\n\+/^^^\r/g | g/^\s*$/d | %s/^^^^.*
This worked for me:
:%s/^[^a-zA-Z0-9]$\n//ig
It basically deletes all the lines that don't have a number or letter. Since all the items in my list had letters, it deleted all the blank lines.

Resources