Complete Practical Vim 1 - Basic

2021-04-04 约 6872 字 预计阅读 14 分钟

Vim已经到了8.2版本,使用vim也有一些年头了,无论什么IDE都会配置成VIM的模式,一篇文档不足以包含vim的全部内容,这里记录的可能只有20%, 但是在编辑的80%时间都会用到,虽然近期转为NeoVim,但是核心还是Vim.本文是Vim使用技巧的基础部分

1. Why vim

One editor to write all programing language

The more you remember and the more you use, the faster you write

2. TODO

  • quickfix
  • folding

3. Help

The best document of vim is the vim help, just use :h

Vim arguments

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
VIM - Vi IMproved 8.1 (2018 May 18, compiled Apr 15 2020 06:40:31)

Usage: vim [arguments] [file ..]       edit specified file(s)
   or: vim [arguments] -               read text from stdin
   or: vim [arguments] -t tag          edit file where tag is defined
   or: vim [arguments] -q [errorfile]  edit file with first error

Arguments:
   --                   Only file names after this
   -v                   Vi mode (like "vi")
   -e                   Ex mode (like "ex")
   -E                   Improved Ex mode
   -s                   Silent (batch) mode (only for "ex")
   -d                   Diff mode (like "vimdiff")
   -y                   Easy mode (like "evim", modeless)
   -R                   Readonly mode (like "view")
   -Z                   Restricted mode (like "rvim")
   -m                   Modifications (writing files) not allowed
   -M                   Modifications in text not allowed
   -b                   Binary mode
   -l                   Lisp mode
   -C                   Compatible with Vi: 'compatible'
   -N                   Not fully Vi compatible: 'nocompatible'
   -V[N][fname]         Be verbose [level N] [log messages to fname]
   -D                   Debugging mode
   -n                   No swap file, use memory only
   -r                   List swap files and exit
   -r (with file name)  Recover crashed session
   -L                   Same as -r
   -A                   Start in Arabic mode
   -H                   Start in Hebrew mode
   -T <terminal>        Set terminal type to <terminal>
   --not-a-term         Skip warning for input/output not being a terminal
   --ttyfail            Exit if input or output is not a terminal
   -u <vimrc>           Use <vimrc> instead of any .vimrc
   --noplugin           Don't load plugin scripts
   -p[N]                Open N tab pages (default: one for each file)
   -o[N]                Open N windows (default: one for each file)
   -O[N]                Like -o but split vertically
   +                    Start at end of file
   +<lnum>              Start at line <lnum>
   --cmd <command>      Execute <command> before loading any vimrc file
   -c <command>         Execute <command> after loading the first file
   -S <session>         Source file <session> after loading the first file
   -s <scriptin>        Read Normal mode commands from file <scriptin>
   -w <scriptout>       Append all typed commands to file <scriptout>
   -W <scriptout>       Write all typed commands to file <scriptout>
   -x                   Edit encrypted files
   --startuptime <file> Write startup timing messages to <file>
   -i <viminfo>         Use <viminfo> instead of .viminfo
   --clean              'nocompatible', Vim defaults, no plugins, no viminfo
   -h  or  --help       Print Help (this message) and exit
   --version            Print version information and exit

3.1. Quick Start Help

Use<C-]>to jump into the tag,use <C-o> back.

Find the key’s document

1
:h i_CTRL-D or :h i_^d

iwith helpgrep

1
:helpgrep CTRL-N

and then switch them with quickfix window

search a tag

1
2
:tselect name
:h *(tag or keyword)*  (example:  h: *g*)

Open vim help in a vertical split windw

1
:vert[ical] h helptagname

or with position

1
:vert bo helptagname

find a tag

1
2
:h index		" all command for each mode
:h help-tags	" all tags

3.2. Use chinese help

vimcdocrelease地址去下载

Unix like系统下压缩包,然后执行

1
./vimcdoc.sh -i

windows可以下载setup的exe来安装

安装完以后切换

1
2
3
:set helplang=cn
" 切换回来
:set helplang=en

3.3. Key and Mode

  • i_ insert
  • n_ normal
  • v_ visual
  • v_b_ visual-block
  • v_g_ unknow
  • c_ command
  • t_ terminal
  • /_ search
  • Visual line
  • insert complete

4. Motion and Move

see:

motion is about how to move the cursor, motion is after operation, like dw (delete word)

What is operator, operators are generally delete or change text

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
c			change
d			delete
y			yank into register
~			swap case
g~			swap case
gu			make lowercase
gU			make uppercase
!			filter through an external program
=
gq			text formating
gw			text formating with no cursor movement
g?			ROT13 encoding
>			shift right
<			shfit left
zf			define a fold
g@			call function

4.1. Shortcuts and commands

4.1.1. General Shortcuts and commands

Shortcuts Description
e end of a word
ge previous word end
b back a word
w next word
$ or <End> end of a line
0 or <Home> start of a line
f find and goto next char
t find and goto the position befor next char
F find and goto previous char
T find and goto the position befor previous char
% jump between ( ) [ ] { z}
{n}G go to line

4.1.2. Left and Right Motions

see: :h left-right-motions

motion Description
`h
`l `
`0 `
^ first not null
`$ `
g_ last not null
g^ first not null
`{count} `
g$ g<END>
gm half of the screen width
gM half of text from the beginnig
f{char} To [count]‘th occurrence of {char} to the right.
t{char} Till before [count]‘th occurrence of {char} to the right.
F{char} To [count]‘th occurrence of {char} to the left.
T{char} Till before [count]‘th occurrence of {char} to the left.
; repeat last f,t,F,T count times
, repeat last f,t,F,T opposite direction [count] times

4.1.3. Up and Down Motions

see: :h up-down-motions

motion Description
`k
`j
- [count] lines upward, on the first non-blank character linewise
`+
[count]% go to {count} percent of file
gg | <Ctrl-HOME>
G
{count}G

4.1.4. Word Motions

see: :h word-motions

4.1.5. Object Motions

see: :h object-motions

Motion Description
( ) sentences
{ } paragraphs
]] [[ [] ][ section

4.1.6. Object Seclect

see: :h object-select

iw
aw
iW
aW
is inner sentence
as a sentence
ap a paragraph
a[ or a] a[ ] block
i[ or i] inner [ ] block
a( or a) or ab a ( ) block
i( or i) or ib inner ( ) block
a< or a> a <> block
i < or i > inner < > block
a { or a} or aB a { } block
i{ or i} or iB inner { } block
a" a’ a` a quote block
i" i’ i` inner quote block
at a tag for xml
it inner tag for xml

some example

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
"dl"	delete character (alias: "x")		
"diw"	delete inner word			
"daw"	delete a word				
"diW"	delete inner WORD (see |WORD|)		
"daW"	delete a WORD (see |WORD|)		
"dgn"   delete the next search pattern match    
"dd"	delete one line				
"dis"	delete inner sentence			
"das"	delete a sentence			
"dib"	delete inner '(' ')' block		
"dab"	delete a '(' ')' block			
"dip"	delete inner paragraph			
"dap"	delete a paragraph			
"diB"	delete inner '{' '}' block		
"daB"	delete a '{' '}' block			

4.1.7. Marks

see: : mark-motions and 1.9 Jumps -> Marks section

4.1.8. Jumps

see: :h jump-motions and 1.9 Jumps

4.1.9. changes

see: :h changelist

  • g; go to [count] older cursor position in change list
  • g, go to [count] newer cursor position in change list
  • :changes see change list

4.1.10. others

see: :h various motions

Key - Cmd Description
% Jump between items like {}[](). Find the next item in this line after or under the cursor and jump to its match.
[( go to {count} previous unmatched (
[{ go to {count} previous unmatched {
]) go to {count} next unmatched )
]} go to {count} next unmatched }
]m method
]M
[m
[M
[#
]#
[* or [/
]* or ]/

4.2. Screen Scroll

4.2.1. scroll one line

  • <C-e> scroll up
  • <C-y> scroll down

4.2.2. scroll screen

  • scroll forward by a whole screen
  • scroll back by a whole screen
  • moves the viewing window down half a screen
  • moves the viewing window up half a screen

4.2.3. scroll screen with line

  • zz scroll the screen to make the line in the middle of screen
  • zt scroll the screen to make the line on the top of screen
  • zb scroll the screen to make the line on the bottom of screen
1
2
3
4
5
6
7
8
9
        +------------------+             +------------------+
        | earlier text     |             | earlier text     |
        | earlier text     |             | earlier text     |
        | earlier text     |             | earlier text     |
        | earlier text     |   zz  -->   | line with cursor |
        | earlier text     |             | later text       |
        | earlier text     |             | later text       |
        | line with cursor |             | later text       |
        +------------------+             +------------------+

4.3. Move to the specify line

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
            |   first line of a file   ^
            |   text text text text    |
            |   text text text text    |  gg
        7G  |   text text text text    |
            |   text text text text
            |   text text text text
            V   text text text text    |
                text text text text    |  G
                text text text text    |
                last line of a file    V

4.4. Move in the screen

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
                        +---------------------------+
                H -->   | text sample text          |
                        | sample text               |
                        | text sample text          |
                        | sample text               |
                M -->   | text sample text          |
                        | sample text               |
                        | text sample text          |
                        | sample text               |
                L -->   | text sample text          |
                        +---------------------------+

4.5. Others

Shortcut or Cmd Description
Ctrl-g show your positionm

5. Windows

see h: windows

5.1. Create window

Key Desc
<C-w> s 垂直拆分
<C-w> v 水平拆分
<C-w> n 新建窗口, 默认是垂直拆分

5.2. Moving cursor to other windows

Key desc
<C-w> w goto below/right window
<C-w> W goto above/left window
<C-w> h goto left window
<C-w> j goto down window
<C-w> k goto up window
<C-w> l goto right window
<C-w> t goto top left window
<C-w> b goto bottom right window
<C-w> p goto previous(last accessed) window
<C-w> P goto preview window

5.3. Window resize

Key Desc
`[count]CTRL-W `
[count]CTRL-W _ 最大化窗口高度,或者调整高度为指定大小
[count]<C-w> + 增加(1或者count)高度
[count]<C-w> - 减少(1或者count)高度
<C-w> = 使所有窗口等高宽
[count]CTRL-W < 减少(1或者count)宽度
[count]CTRL-W > 增加(1或者count)宽度

5.4. Window close

Key Desc
CTRL-W c close window
CTRL-W o 只保留一个窗口,关闭其他所有窗口,最大化当前窗口
CTRL-W q 退出窗口,如果是最后一个vim将会退出

5.5. Window move

Key Desc
CTRL-W r 向前滚动窗口的位置,第一个变成第二个,以此类推
CTRL-W R 同上,方向相反
CTRL-W x 和下一个窗口交换位置
CTRL-W K 将当前窗口置于顶部,并宽度最大化
CTRL-W J 同上,置于底部
CTRL-W H 将当前窗口置于最左边,并高度最大化
CTRL-W L 同上,置于右边
CTRL-W T 将当前窗口在新的tabpage打开

5.6. Other window operation

1.在新窗口打开tag或者file,类似Nerdtree,查看帮助:h window-tag

2.preview window,查看帮助:h preview-window

:[count]winc[md] {arg}

Like executing CTRL-W [count] {arg}. Example:

1
2
:winc ]					" open tag
:vert winc ]			" open tag in a split window

6. Search and replace

6.1. Common command and key

:noh no highlight * search the word under the cursor, like /\<word\>

g* like * , but not put \<\>around the word

# like *, but search backwords

g# like #

n next

N previous

Ctrl-g next (not enter CR in command ), not leave command mode

Ctrl-t previous(not leave command), not leave command mode

6.2. Pattern

6.2.1. The definition of pattern

see: :h search-pattern

6.2.1.1. 1.branch

branch separate by \|, it like or

1
branch \| branch \| branch
6.2.1.2. 2.contact

contact separate by \&, it like filter

1
branch \& branch \& branch

example

1
2
	"foobeep\&..." matches "foo" in "foobeep".
	".*Peter\&.*Bob" matches in a line containing both "Peter" and "Bob"
6.2.1.3. 3.Piece

A concat is one or more pieces, concatenated

1
piece piece piece
6.2.1.4. 4.atom

A piece is an atom, possibly followed by a multi,

1
2
3
4
5
atom
or
atom multi
" example:
a* will matches "", "a", "aa", "aaa", "aaaa" ....etc
6.2.1.5. 5.an atom can be one of the long list of items
1
2
3
4
5
\(pattern\)
or
\%\(pattern\)
or
\z\(pattern\)

6.2.2. The magic

  • \m magic
  • \M nomagic
  • \v very magic (only a-z A-Z 0-9 _ have special meaning)
  • \V very nomaigc (only / ?)

this option determines how to use escape characters

the Strictness

1
\v < \m < \M < \V

for example

1

6.2.3. commands and settings about pattern

1
set shortmess-=S

clear last search pattern

1
let @/=""

6.2.4. Ignore case

use \c to ignore case , use \C to not ignore case

1
2
\cword			" word,Word,WORD,WoRd,
\CWord			" Word

or you can set option

1
2
:set ingorecase
:set noingorecase

6.2.5. offset

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
[num]	[num] lines downwards, in column 1
+[num]	[num] lines downwards, in column 1
-[num]	[num] lines upwards, in column 1
e[+num]	[num] characters to the right of the end of the match
e[-num]	[num] characters to the left of the end of the match
s[+num]	[num] characters to the right of the start of the match
s[-num]	[num] characters to the left of the start of the match
b[+num]	[num] identical to s[+num] above (mnemonic: begin)
b[-num]	[num] identical to s[-num] above (mnemonic: begin)
;{pattern}  perform another search
6.2.5.1. Line Offset

search the words and then move the cursor to the second(specify number) line

1
2
3
4
//num
" example
/word/1
/word/-2
6.2.5.2. Character Offset

e to the end of the word, b to the beginning of the word

1
2
3
4
/word/e
/word/e+1
/word/e-1
/word/b+1
1
2
3
//; //
example:
/test.*/+1;?ing?

6.2.6. repeat last pattern

1
//

6.2.7. search range

1
2
3
\%>l
example
/\%>100l

another way, like Ex, use substitute

1
:.,300s/pattern/replace/gc

6.2.8. searching backwords

use?

1
?word?e-2

6.2.9. searching commands

characters

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|/\i|	\i	\i	identifier character (see 'isident' option)
|/\I|	\I	\I	like "\i", but excluding digits
|/\k|	\k	\k	keyword character (see 'iskeyword' option)
|/\K|	\K	\K	like "\k", but excluding digits
|/\f|	\f	\f	file name character (see 'isfname' option)
|/\F|	\F	\F	like "\f", but excluding digits
|/\p|	\p	\p	printable character (see 'isprint' option)
|/\P|	\P	\P	like "\p", but excluding digits
|/\s|	\s	\s	whitespace character: <Space> and <Tab>
|/\S|	\S	\S	non-whitespace character; opposite of \s
|/\d|	\d	\d	digit:						[0-9]
|/\D|	\D	\D	non-digit:					[^0-9]
|/\x|	\x	\x	hex digit:					[0-9A-Fa-f]
|/\X|	\X	\X	non-hex digit:				[^0-9A-Fa-f]
|/\o|	\o	\o	octal digit:				[0-7]
|/\O|	\O	\O	non-octal digit:			[^0-7]
|/\w|	\w	\w	word character:				[0-9A-Za-z_]
|/\W|	\W	\W	non-word character:			[^0-9A-Za-z_]
|/\h|	\h	\h	head of word character:		[A-Za-z_]
|/\H|	\H	\H	non-head of word character:	[^A-Za-z_]
|/\a|	\a	\a	alphabetic character:		[A-Za-z]
|/\A|	\A	\A	non-alphabetic character:	[^A-Za-z]
|/\l|	\l	\l	lowercase character:		[a-z]
|/\L|	\L	\L	non-lowercase character:	[^a-z]
|/\u|	\u	\u	uppercase character:		[A-Z]
|/\U|	\U	\U	non-uppercase character		[^A-Z]
|/\_|	\_x	\_x	where x is any of the characters above: character
			class with end-of-line included

special items

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|/\e|	\e	\e	<Esc>
|/\t|	\t	\t	<Tab>
|/\r|	\r	\r	<CR>
|/\b|	\b	\b	<BS>
|/\n|	\n	\n	end-of-line
|/~|	~	\~	last given substitute string
|/\1|	\1	\1	same string as matched by first \(\)
|/\2|	\2	\2	Like "\1", but uses second \(\)
	   ...
|/\9|	\9	\9	Like "\1", but uses ninth \(\)
								*E68*
|/\z1|	\z1	\z1	only for syntax highlighting, see |:syn-ext-match|
	   ...
|/\z1|	\z9	\z9	only for syntax highlighting, see |:syn-ext-match|

	x	x	a character with no special meaning matches itself

|/[]|	[]	\[]	any character specified inside the []
|/\%[]|	\%[]	\%[]	a sequence of optionally matched atoms

|/\c|	\c	\c	ignore case, do not use the 'ignorecase' option
|/\C|	\C	\C	match case, do not use the 'ignorecase' option
|/\Z|	\Z	\Z	ignore differences in Unicode "combining characters".
			Useful when searching voweled Hebrew or Arabic text.

      magic   nomagic	matches ~
|/\m|	\m	\m	'magic' on for the following chars in the pattern
|/\M|	\M	\M	'magic' off for the following chars in the pattern
|/\v|	\v	\v	the following chars in the pattern are "very magic"
|/\V|	\V	\V	the following chars in the pattern are "very nomagic"
|/\%#=|   \%#=1   \%#=1   select regexp engine |/zero-width|

|/\%d|	\%d	\%d	match specified decimal character (eg \%d123)
|/\%x|	\%x	\%x	match specified hex character (eg \%x2a)
|/\%o|	\%o	\%o	match specified octal character (eg \%o040)
|/\%u|	\%u	\%u	match specified multibyte character (eg \%u20ac)
|/\%U|	\%U	\%U	match specified large multibyte character (eg
			\%U12345678)
|/\%C|	\%C	\%C	match any composing characters

character class expression

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
*[:alnum:]*	  [:alnum:]   isalnum	ASCII letters and digits
*[:alpha:]*	  [:alpha:]   isalpha  	ASCII letters
*[:blank:]*	  [:blank:]     	space and tab
*[:cntrl:]*	  [:cntrl:]   iscntrl 	ASCII control characters
*[:digit:]*	  [:digit:]     	decimal digits '0' to '9'
*[:graph:]*	  [:graph:]   isgraph	ASCII printable characters excluding space
*[:lower:]*	  [:lower:]   (1)	lowercase letters (all letters when 'ignorecase' is used)
*[:print:]*	  [:print:]   (2) 	printable characters including space
*[:punct:]*	  [:punct:]   ispunct	ASCII punctuation characters
*[:space:]*	  [:space:]     	whitespace characters: space, tab, CR, NL, vertical tab, form feed
*[:upper:]*	  [:upper:]   (3)	uppercase letters (all letters when 'ignorecase' is used)
*[:xdigit:]*	  [:xdigit:]    	hexadecimal digits: 0-9, a-f, A-F
*[:return:]*	  [:return:]		the <CR> character
*[:tab:]*	  [:tab:]		the <Tab> character
*[:escape:]*	  [:escape:]		the <Esc> character
*[:backspace:]*	  [:backspace:]		the <BS> character
*[:ident:]*	  [:ident:]		identifier character (same as "\i")
*[:keyword:]*	  [:keyword:]		keyword character (same as "\k")
*[:fname:]*	  [:fname:]		file name character (same as "\f")
Operation Description Example
====== ================================================= ======================================================
====== ============== ordinary-atom =============== ==================================================
contains /the
^ beginning of the line /^the
\_^ start of a line(can use anywhere)
$ end of the line /the$
\_$ end of line(use anywhere)
. The . (dot) character matches any existing character.no eof
\_. any char include EOF(end-of-line)
\< word start
\> end of a word
\zs anything, sets start of match
\ze anything, sets end of match
\%^ start of a file
\%$ end of file
\%V inside visual area
\%# cursor position
\%'m mark m position
\%<'m Matches before the position of mark m.
\%>'m Matches after the position of mark m.
\%23l in line 23
\%<23l Matches above a specific line
\%>23l Matches below a specific line
\%23c in column 23
\%<23c Matches before a specific column.
\%>23c Matches after a specific column.
\%23v in visual column 23
\%<23v Matches before a specific virtual column
\%>23v Matches after a specific virtual column
====== ============== mutli =============== ==================================================
* any times /\(ab\)\* match ab, abab, ababab
+ one or more times /ab+ match ab, abb, abbb
= 0 or 1 /words\= match word, words
? 0 or 1
{n,m} to match specific number /ab\{3,5} match abbb, abbbb, abbbbb
—— \{,4} 0,1,2,3,4
—— \{3,} 3,4,5,6……
—— \{0,1} like \=
—— \{0,} like \*
—— \{1,} like \+
—— \{3} 3 times
—— \{-1,3} match as little as possible
the text abbb will get ab
—— \{-} this match the item before it ,zero or more
times, as few as possible
the text axbxb, use the pattern /a.\{-}b will
get axb
\@> like {1} ????
\@= nothing, requires a match /foo\(bar\)\@= matches foo in foobar
/foo\(bar\)@=... matches foobar in foobar
/foo\(bar\)@=any) matches anything
\@! nothing, requires NO match /foo\(bar\)\@! matches foo not followed by bar
\@<= nothing, requires a match behind \(an\_s\+\)\@<=file matches file behind an and space
\@123<= like \@<= but only look back 123 bytes
\@<! nothing, requires No match behind
====== ============== Alternatives ============== ==================================================
| or /foo|bar /\(foo|bar\)+
/end\(if|while|for)
====== ============== Character range ============== ==================================================
[a-z]
[A-Z]
[0-9]
[^] complemented range /"[^"]*"
====== ============ Predefined Range ============ ==================================================
\d digit
\D non-digit
\x hex digit
\X non-hex digit
\s white space
\S non-white space char
\l lower case alpha
\l non-lower case alpha
\u upcase alpha
\U non-upcase alpha
====== ============ Character ============ ==================================================
\f filename char, depends on system use set isfname? to see the char range
\F like \f, excluding digits
\i identifier characters
\I like \i excluding digits
\k keywords
\K
\p printable chharacters
\P
\n line break
\_ cann’t be used alone
\_s line break or space
\_.
\<word\> only whole word
\w like [a-zA-Z0-9_]
\a alphabetic character
\h [a-zA-Z_]

about \@!, see example , my experiment

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
" the origin line
aaaaq abbbbb aaaabbbq aqqq aaq qaqaqq aqqqq abbbbqq abscq aqsbsqasd aqweqqq

" with this substitute
28s/a.\{-}q\@!/(\0)/gc

" I got this
(a)(a)(a)(aq) (a)bbbbb (a)(a)(a)(a)bbbq (aqqq) (a)(aq) q(aq)(aqq) (aqqqq) (a)bbbbqq (a)bscq (aq)sbsq(a)sd (aq)weqqq

" use this command
28s/a.\{-}q\@!/\0\r/gc

" I got this
a
a
a
aq			" why not 'a', because the pattern 'q\@!' not allow end with q, but q match the '.\{-}' 
 a			" \{-} means as few as possible
bbbbb a
a
a
a
bbbq aqqq	" the same thing, can not end with q, but before that they matches 'a.\{-}'
 a
aq
 qaq
aqq
 aqqqq
 a
bbbbqq a
bscq aq
sbsqa
sd aq
weqqq

6.2.9.1. Escape Characters
1
2
3
4
5
6
7
\c
\C
\( \)
\+
\*
\?
\|

6.3. vimgrep

1
:vim[grep][!] /{pattern}/[g][j] {file} 

6.4. Tips

6.4.1. about new line

use \r

1
:s/pattern/new\ line\r/gc

6.4.2. replace in one file

1
	:%s/four/4/g

The “%” range means to replace in all lines. The “g” flag at the end causes all words in a line to be replaced.

use the “<” item to match the start of a word, and Use “>” to match the end of a word

1
	:%s/\<four\>/4/g

add the “c” flag to have the substitute command prompt you for each replacement:

1
	:%s/\<four\>/4/gc

6.4.3. replacing in several files

the example of use macro to replace word in several files

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
	vim *.cpp		Start Vim, defining the argument list to
				contain all the C++ files.  You are now in the
				first file.
	qq			Start recording into the q register
	:%s/\<GetResp\>/GetAnswer/g
				Do the replacements in the first file.
	:wnext			Write this file and move to the next one.
	q			Stop recording.
	@q			Execute the q register.  This will replay the
				substitution and ":wnext".  You can verify
				that this doesn't produce an error message.
	999@q			Execute the q register on the remaining files.

At the last file you will get an error message, because “:wnext” cannot move to the next file. This stops the execution, and everything is done.

There is one catch: If one of the .cpp files does not contain the word “GetResp”, you will get an error and replacing will stop. To avoid this, add the “e” flag to the substitute command: >

1
	:%s/\<GetResp\>/GetAnswer/ge

The “e” flag tells “:substitute” that not finding a match is not an error.

6.4.4. switch words

1
2
3
	Doe, John 
	:%s/\([^,]*\), \(.*\)/\2 \1/
	John Doe

7. Tabpage

See: :h tabpage

Commands or Shortcut Desc
g<Tab> or <C-Tab> last use tab
:tabs list tabs
{count}<C-PageDown> / {count}gt / :tabN {count} go to the {count} next tab page
{count}<C-PageUp> / {count}gT / :tabp {count} go to the {count} previous tab page
:tabc[lose] close tab
:tabo[nly] close other tabs
:tabnew
:tabe[dit]
:tabf[ind]
:[count]tab {cmd}

8. Commands

8.1. common

Open command window, it will show command history, you can edit the command and rerun it

1
q:

8.2. command line edit

Shortcut Desc
completion the word before the cursor
erases the character before the cursor
delete to the begining
cancel
to the begin of command line
to the end of command line
one character left
one character right
or one word left
or one word right
delete a whole word
toggles between inserting characters and replacing the existing ones
list matches
like tab completion, but use the longest unambiguous string
history
Command Desc
:history the history of “:” commands.
:history / the search history
q: command line window

9. Registers

See: :h registers

9.1. Types of registers

  1. The unnamed register ""
  2. 10 numbered registers “0 to “9
  3. The small delete register “-
  4. 26 named registers “a to “z or “A to “Z
  5. Three read-only registers “:, “., “%
  6. Alternate buffer register “#
  7. The expression register “=
  8. The selection and drop registers “*, “+ and “~
  9. The black hole register “_
  10. Last search pattern register “/

9.2. Copy only register

0 is the copy only register

9.3. System register

"+ X11 clipboard

9.4. Number register

With each successive deletion or change, Vim shifts the previous contents of register 1 into register 2, 2 into 3, and so forth, losing the previous contents of register 9.

9.5. Small delete register

"- is used if the delete is within a line

9.6. Expression register(*very useful)

"= This is not really a register that stores text, but is a way to use an expression in commands which use a register. The expression register is read-write.

9.7. Black hole register

"_ When writing to this register, nothing happens. This can be used to delete text without affecting the normal registers. When reading from this register, nothing is returned.

9.8. Other registers

most of them are read only

  • "% current filename(ro)
  • "# current alternate filename(ro)
  • ". Last insert text(ro)
  • ": Last ex command(ro)
  • "/ Last search pattern(ro)

10. Jumps

10.1. Quick Start

10.1.1. Jumps

:jumps or :ls print jump list <C-i> or <Tab> Go to [count] new cursor position in jump list <C-o> go to [count] older cursor position in jump list

10.1.2. changes

:changes change list

g; go to the newest position

g,

10.1.3. buffers

:buffers then :b[number]

10.2. Marks

see: :h mark-motions

:marks list all marks

10.2.1. Add and Jump

Operation Desc
With ` (backtick) Jumping to specified location
With ' (single quote) Jumping to specified location, and the cursor is positioned on the first non-blank character
m{a-zA-Z} set mark with char
`` or '’ Jumping to the previous context mark
‘{a-z} `{a-z} Jump mark with char
m’ or m` Set the previous context mark
` or ' 0-9 previous or older position

10.2.2. special mark

  • a-z current buffer position

  • A-Z file position

  • < and > mark or jump the last visual mode select area

  • [ and ] mark or jump the last position of change by multiple command

  • ^ the last insert position

  • '( to the start of sentence , like (

  • ') to the end of sentence , like )

  • '{ to the start of paragraph , like {

  • '} to the start of paragraph , like }

  • '. to the last change position

10.2.3. Delete mark

:delmarks a	       deletes mark a
:delmarks a b 1    deletes marks a, b and 1
:delmarks Aa       deletes marks A and a
:delmarks p-z      deletes marks in the range p to z
:delmarks ^.[]     deletes marks ^ . [ ]
:delmarks \"	   deletes mark "

10.3. Jump Commands

See: :h jump-motions The following commands are jump commands:

1
2
3
4
"'", "`", "G", "/", "?", "n", "N",
"%", "(", ")", "[[", "]]", "{", "}", ":s", ":tag", "L", "M", "H" and the
commands that start editing a new file.

11. Map

11.1. About map

some keymap like this i_CTRL-D, o_CTRL-F, c_CTRL-U

prefix desc
i insert
o operation
n nomoral
v visual or highlight
c command
g

12. Edit

12.1. Basic Insert

see: :h inserting

Key-Cmd Description Example
i
I
a
A
gI
gi
o
O

12.2. Ex Insert Commands

see: :h inserting-ex

Key-Cmd Description Example
:n,m define a range :2,5
[range]p[rint] print :2,6p
[range]m[ove] move :2,5m$
[range]d[elete] delete :2,5d
[range]co{address} copy to :2,$co100
[range]y[ank] yank copy to register
[range]j[oin] join :2,6j
[range]normal {cmd} call command
[range]s/pattern/{string}/{flag} substitute
[range]g/pattern/command run command
[line]put paste :3put "+
<======================> <=========== special range ===========> <======================>
% all line :%y
. current line :.,$p
:= print total line counts
:'<,'> the highlight selected range in visual mode
:.= get current line number
+ or - line number relative range :-,+t0 :.,.+3p
'm the line which mark of m
<======================> <=========== parttern t range ===========> <======================>
:/pattern/d delete next line macth pattern
:/parttern1,/pattern2/d delete first match pattern1 to first match pattern2
:d/pattern delete to next pattern
:100;+5p current line to 100, and print 100 to 105, notice use ; not ,
<======================> <=========== Save File ===========> <======================>
[range]w file save range to a file :230,$w newfile
:w file save as a new file :w filename
[range] »newfile append lines to a exist file :100,$ >>filename
% current filename :w %.old
:r[ead] filename read a file and insert from next line :r readme.md
:128r: test.txt
<======================> <=========== other ===========> <======================>
:args
. repeat last normal command :'<,'>normal .
@: repeat last Ex command

12.3. Shortcuts and Commands

12.3.1. Special Keys

see: :h insert

Key Description
i_CTRL-D delete shiftwidth from start of line
i_CTRL-T insert shiftwidth from start of line
i_CTRL-U delete from cursor to the start of line
i_CTRL-W delete word
i_CTRL-A insert text which inserted recently
i_CTRL-I or i_<Tab> insert a tab
i_CTRL-N find next keyword
i_CTRL-P find previous keyword
i_CTRL-H or Del delete the character before the cursor
Del delete the character under the cursor
i_CTRL-J or i_<NL> start a new line
i_CTRL-M or i_<CR> start a new line
i_CTRL-@ Insert previously inserted text and stop insert.
i_CTRL-[ or ESC end insert or replace mode
i_CTRL-R {Register} insert register
i_CTRL-R_CTRL-R Insert the contents of a register. Works like using a single CTRL-R, but the text is inserted literally,not as if typed.
i_0_CTRL-D delete all indent of this line
i_^_CTRL-D Delete all indent in the current line. The indent is restored in the next line.
i_CTRL-E insert the character which is below the cursor
i_CTRL-Y insert the character which is above the cursor
i_CTRL-X Enter CTRL-X mode see: :h ins-comletion
i_CTRL-R_CTRL-E scroll window one line up
i_CTRL-R_CTRL-Y scroll window one line down
Insert Toggle between Insert and Replace mode

about CTRL-X mode

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
1. Whole lines                                     |i CTRL-X CTRL-L|
2. keywords in the current file                    |i CTRL-X CTRL-N|
3. keywords in 'dictionary'                        |i CTRL-X CTRL-K|
4. keywords in 'thesaurus', thesaurus-style        |i CTRL-X CTRL-T|
5. keywords in the current and included files      |i CTRL-X CTRL-I|
6. tags                                            |i CTRL-X CTRL-]|
7. file names                                      |i CTRL-X CTRL-F|
8. definitions or macros                           |i CTRL-X CTRL-D|
9. Vim command-line                                |i CTRL-X CTRL-V|
10. User defined completion                        |i CTRL-X CTRL-U|
11. omni completion                                |i CTRL-X CTRL-O|
12. Spelling suggestions                           |i CTRL-X s|
13. keywords in 'complete'                         |i CTRL-N|

12.3.2. Special special keys

Shortcut or Command Description
<Up> cursor one line up
<Down> cursor one line down
i_CTRL-G_k or i_CTRL-G_Up or i_CTRL-G_CTRL-K cursor one line up, insert start column
i_CTRL-G_J or i_CTRL-G_Down or i_CTRL-G_CTRL-J cursor one line down, insert start column
i_<S-Left> or i_<C-Left> cursor one word back, like “b” command
i_<S-Right> or i_<C-Right> cursor one word foward, like “w” command
i_<S-Up> or i_<PageUp> move window one page up
i_<S-Down> or i_<PageDown> move window one page down
<Home> cursor to the first char of the line
I_<C-Home> cursor to the first char of the file
<End> cursor to the last char of the line
I_<C-End> cursor to the last char of the file

12.4. Insert Mode Completion

see: :h ins-completion

check completion information, see: :h complete_info()

1
:echo complete_info()

check option, see: :h complete

1
:set complete?

default value: .,w,b,u,t,i

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
	.	scan the current buffer ('wrapscan' is ignored)
	w	scan buffers from other windows
	b	scan other loaded buffers that are in the buffer list
	u	scan the unloaded buffers that are in the buffer list
	U	scan the buffers that are not in the buffer list
	k	scan the files given with the 'dictionary' option
	kspell  use the currently active spell checking |spell|
	k{dict}	scan the file {dict}.  Several "k" flags can be given,
		patterns are valid too.  For example: >
			:set cpt=k/usr/dict/*,k~/spanish
<	s	scan the files given with the 'thesaurus' option
	s{tsr}	scan the file {tsr}.  Several "s" flags can be given, patterns
		are valid too.
	i	scan current and included files
	d	scan current and included files for defined name or macro
		|i_CTRL-X_CTRL-D|
	]	tag completion
	t	same as "]"

Notice

subsequent press the same key will continue to completion

This is a sub-mode of Insert and Replace

with out CTRL-X

Key - Cmd Desc Example
CTRL-N Search forwards for the next matching line
CTRL-P Search backwords for the next matching line
CTRL-R register insert mode
ctrl-tab LIST snippets

with prefix CTRL-X

Key-Cmd Desc Example
C-E back to insert or replace mode
C-Y accept currently selected entry
C-L Line completion
C-N like C-N
C-P like C-P
C-F file
C-R register
C-] tag
C-I Search for the first keyword in the current and include files(for c lang) that starts with the same characters
C-K dictionary
C-T thesaurus
C-D definition (or macro) name (for c lang)
C-V vim command
C -U Completion is done by a function that can be defined by the user with the
‘completefunc’ option. example set completefunc=CompleteMonths
C-O Omni completion, use omnifunc
s or C-S spelling suggestion

12.4.1. Dictionary Completion

see:

check option

:set dictionary?

download words from SCOWL

vimrc settings

1
2
3
4
5
6
7
" set dictionary
set complete+=k
if has('win32')
  set dictionary+=c:\Users\oherg\vimfiles\dictionary\words.txt
else
  set dictionary+=/usr/share/dict/words
endif

12.5. Blockwise Operators

see:

  • :h blockwise-visual
  • :h blockwise-operators
  • :h blockwise-examples

[count]CTRL-V Start Visual mode blockwise

Operations Desc
I{String}<ESC> insert {String} at the start of block on every line of the block
A{String}<ESC> insert {String} at the endof block on every line of the block
c delete all and begin to insert new text
C Like using “c”, but the selection is extended until the end of the line for all lines.
> Visual-block Shift
< Visual-block Shift
r Visual-block Replace

13. Netrw

see:

13.1. Quick Start

start

1
2
3
:E(xplore)
:Ve(xplore)
:Se(xplore)

shortcut

see: :h netrw-quickmap

shortcuts Description
i Cycle between thin, long, wide, and tree listings
mb add bookmark
qb list history and bookmark
u history back
U history forward
del remove file/directory
- go up
d mkdir
c like cd
C set the edit window
mf

filetypes

1
2
3
4
5
	directory  : /
	executable : *
	fifo       : |
	links      : @
	sockets    : =

13.2. Settings

see: :h netrw-settings

my settings

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
"*****************************************************************************
" Netrw
"*****************************************************************************

let g:netrw_banner = 0
" let g:netrw_liststyle = 3
let g:netrw_browse_split = 4
let g:netrw_altv = 1
let g:netrw_winsize = 25

" augroup ProjectDrawer
"   autocmd!
"   autocmd VimEnter * :Vexplore
" augroup END


" " Toggle Vexplore
" function! ToggleVExplorer()
"   if exists("t:expl_buf_num")
"       let expl_win_num = bufwinnr(t:expl_buf_num)
"       if expl_win_num != -1
"           let cur_win_nr = winnr()
"           exec expl_win_num . 'wincmd w'
"           close
"           exec cur_win_nr . 'wincmd w'
"           unlet t:expl_buf_num
"       else
"           unlet t:expl_buf_num
"       endif
"   else
"       exec '1wincmd w'
"       Vexplore
"       let t:expl_buf_num = bufnr("%")
"   endif
" endfunction

" map <silent> <F3> :call ToggleVExplorer()<CR>

14. Motion

see:

  • :h g@
  • :h motion

motion is about how to move the cursor, motion is after operation, like dw (delete word)

What is operator, operators are generally delete or change text

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
c			change
d			delete
y			yank into register
~			swap case
g~			swap case
gu			make lowercase
gU			make uppercase
!			filter through an external program
=
gq			text formating
gw			text formating with no cursor movement
g?			ROT13 encoding
>			shift right
<			shfit left
zf			define a fold
g@			call function

15. Spell

1
set spelllang=zh_ch,en_us,fr_ch

vim will auto download spell file

16. Folding

17. Text Object

1
:h text-objects

aw

iw

aW 一段连续的文本,直到出现空白

iw

as a sentence

is

ap a paragraph

ip

a[ or a]

i[ or i]

a( or a) or ab

i( or i) or ib

a< or a>

i< or i>

at a tag , example

text

it inner a tag

a{ or a} or aB

i{ or i} or iB

a” a’ a`

i” i' i`

TAG: vim ide
文章作者 : Cocding