Lets say I have a block of text:
and I want to comment it all out in vi
What I usually do is go to the first line and hit "^i" and then enter "#". next I arrow down to the next line and hit "." and then repeat until all the lines are commented.
If I hit "2" then "." it will give me.
I know I can do this with numbered lines, like
but I want to be able to do this without having to enter line numbers.
Keep in mind I am using vi not vim, so "^v" will not work.
asked 06 May '10, 18:47
An alternative for plain vi, and if you have a small number of lines to change, is to do this
What you are doing here is telling it to do a search and replace on the block marked out by the current line (. - dot) to the current line plus 3 (dot plus 3). If you have four lines to comment out, it will be current line plus 3 = .,.+3. If you have 10 lines it will be current line plus 9 = .,.+9.
When you do a search and replace, before the s you can specify the region that the search and replace is to apply to. One method of specifying the region is to use line numbers, like m,n = from line m to line n. Example 45,55.
There are a number of abbreviations that fit in there. $ = last line in the file. So if you want to apply it to the whole file, you use 1,$ = from line 1 to last line. Another abbreviation is . meaning the current line. Example .,$ meaning from the current line to the last line in the file.
You can also do relative numbers, like $ - 5 meaning up to the fifth last line. Or .+4 meaning current line plus 4. Or .-2 meaning current line minus 2.
You can use macro recording to do this:
So all together the key presses would be:
Use repeat last substitute maybe. (unless that's vim specific)
will comment out 4 lines
answered 06 May '10, 21:41
map something to it:
:map ^K I#^[jI#^[
that works for me on AIX, so should work in any vi.
To get the esc working, use control-v, so the key sequence is:
colon map control-k space shift-i shift-3 control-v esc j shift-i shift-3 control-v esc
answered 06 May '10, 19:50
For plain standard vi, do this:
Basically, you go to to the first line of the block and mark it and you may as well use register a. So that's ma.
Then you move to the end of the block and you do a search and replace.
: puts you into ex mode
'a is the start of the search block and it refers to the mark you made earlier
. is the current line
so the whole block is described by 'a,. (dash a comma dot)
then you replace the start of the line with a #, but only for that specified block (s/^/#/)
This is standard vi, so it will work for you.
why dont you use Emacs..its very simple in emacs which you have asked
answered 06 May '10, 19:34
Quicker, no custom macros needed:
Shift - I will take you to the beginning of the line, then add your # character. Escape, and it's applied to the entire highlighted block.
This may be vim specific.
answered 06 May '10, 20:42