Vi&Vim使用技巧

對多行添加註釋

例如,選中下面代碼片的前四行,並通過在每行的行首添加#號,將它們註釋掉:

def foo(a,b):
    for each in (a,b):
        print each
    return a+b
print "2"

最終形成這樣的效果:

#def foo(a,b):
#    for each in (a,b):
#        print each
#    return a+b
print "2"

方法:

  1. 有現成的插件nerdcommenter可以實現對不同語言添加註釋的功能。

  2. 只用現成的插件感覺不過癮的話,利用vi內置的操作同樣可以實現效果。

  3. Option 1:

** V-blocks
:1 Enter (Go to line 1)
Ctrl-V (V-Block mode)
jjj (Down 3 more lines)
Shift-I (Enter insert mode before the block)

(Insert a ‘#’)

Esc (Back to normal mode)

  1. Option #2:
Substitution
:1,4s/^/#/
Breakdown:
Ex command follows
1,4 on lines from 1 through 4
s substitute
/ separator for pieces of the substitution command.
(You can also use a different character, e.g. :)
^ beginning of the line
/ separator

the comment character for python

/ final separator

  1. Option #3:

    Repeat application of a macro (source)
    :1 Enter (Go to line 1)
    qa (Start recording on register a)
    Shift-I (Enter insert mode at the beginning of the line

(Add a ‘#’ at the beginning of the line)

Esc (Back to normal mode)
q (Stop recording)

:2,4 normal @a (re-run the macro recorded to register a on lines between 2 and 4)

OR

you can select the lines in visual mode and hit : to automatically populate the Ex line with :’<,’> (a range from the beginning to the end of the visual selection) then type normal @a and hit Enter (source).

Now, whenever you want to comment some lines just re-run the macro recorded to register a on those lines:

:9,22 normal @a (comment out lines 9-22)

發佈了45 篇原創文章 · 獲贊 6 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章