《practical vim》笔记
vim
The Vim Way
1. Meet the Dot Command
2. Don't Repeat Yourself
- Reduce Extraneous Movement
Compound cmd |
Equivalent |
C |
c$ |
s |
cl |
S |
^C |
I |
^i |
A |
$a |
o |
A<CR> |
O |
ko |
3. Take One Step Back, Then Three Forward
- Make the Change Repeatable
- Make the Motion Repeatable
4. Act, Repeat, Reverse
Intent |
Act |
Repeat |
Reverse |
Make a change |
{edit} |
. |
u |
Scan line for next character |
f{char}/t{char} |
; |
, |
Scan line for previous character |
F{char}/T{uhar} |
; |
, |
Scan document for next match |
/pattern<CR> |
n |
N |
Scan document for previous match |
?pattern<CR> |
n |
N |
Perform substitution |
:s/target/replace |
& |
u |
Execute a sequence of changes |
qx{changes}q |
@x |
u |
5. Find and Replace by Hand
- Be lazy : Search without Typing (*)
- The Ideal: One Keystroke to Move, One KeyStroke to Execute
Modes
Normal Mode
7. Pause with Your Brush Off the Page
8. Chunk Your Undos
- Inset Mode :
i{edit}<ESC>
is a change
9. Compose Repeatable Changes
- Delete word by Backward
dbx
then . == x
- Delete word by Forward
bdw
then . == dw
- Delete word
daw
then . == daw
10. Use Counts to Do Simple Arithmetic
n<C-a>
and n<C-x>
perform addition and subtraction n
on numbers
11. Don't Count If You Can Repeat
12. Combine and Conquer
- Operator + Motion = Action
- when an operator command invoked in duplicate, it acts upon the current line
- Operator
Trigger |
Effect |
c |
Change |
d |
Delete |
y |
Yank into Register |
g~ |
Swap case |
gu |
make lowercase |
gU |
make uppercase |
> |
Shift right |
< |
Shift left |
= |
Autoindent |
! |
Filter {motion} lines through an external program |
motion |
mean |
l |
letter |
w |
word |
p |
paragraph |
Insert Mode
13. Make Corrections Instantly from Insert Mode
keystrokes |
Effect |
<C-h> |
Delete back one character(backspace) |
<C-w> |
Delete back one word |
<C-u> |
Delete back to start of line |
14. Get Back to Normal Mode
Keystrokes |
Effect |
<ESC> |
Switch to Normal mode |
<C-[> |
Switch to Normal mode |
<C-o> |
Switch to Insert Normal mode |
- Insert Normal mode
From Insert mode into Normal mode, run only one normal command and left off in Insert mode
15. Paste from a Register Without Leaving Insert Mode
ctrl-r {register}
paste text from {register} in Insert Mode
ctrl-r ctrl-p {register}
smarty paste text from {register} in Insert Mode
16. Do Back-of-the-Envelope Calculations in Place
ctlr-r =
expression register
17. Insert Unusual Characters by Character Code
18. Insert Unusual Characters by Digraph
Keystrokes |
Effect |
<C-v>{123} |
Insert character by decimal code (3 digit) |
<C-v>u{1234} |
Insert character by hexadecimal code |
<C-v>{nondigit} |
Insert nondigit literally |
<C-k>{char1}{char2} |
Insert character represented by {char1}{char2} digraph |
19. Overwrite Existing Text with Replace Mode
R
normal mode => replace mode
Visual Mode
20. Grok Visual Mode
- visual mode have some action with normal mode
21. Define a Visual Selection
Command |
Effect |
v |
Enable character-wise Visual mode |
V |
Enable line-wise Visual mode |
<C-v> |
Enable block-wise Visual mode |
gv |
Reselect the last visual selection |
22. Repeat Line-Wise Visual Commands
23. Prefer Operators to Visual Commands Where Possible
vit
: visually select inside the tag
24. Edit Tabular Data with Visual-Block Mode
r|
will change all select character in visual mode
25. Change Columns of Text
26. Append After a Ragged Visual Block
Command-Line Mode
27. Meet Vim's Command Line
:
Command-Line mode
- Ex commands
Command |
Effect |
:[range]delete[x] |
Delete specified lines [into register x] |
:[range]yank[x] |
Yank specified lines [into register x] |
:[line]put[x] |
Put the text from register x after the specified line |
:[range]copy{address} |
Copy the specified lines to below the line specified by {address} |
: [range]move{address} |
Move the specified lines to below the line specified by {address} |
:[range]join |
Join the specified lines |
:[range]normal{command} |
Execute Normal mode {command} on each specified line |
:[range]substitute/{pattern}/{string}/[flags] |
Replace occurrence of {pattern} with {string} on each specified line |
:[range]global/{pattern}/{cmd} |
Execute the Ex command [cmd] on all specified lines where the {pattern} matches |
Command |
Effect |
:edit/:write |
read/wirte files |
:tabnew |
create tabs |
:split |
split window |
:pre/:next |
argument list |
:bpre/:bnext |
buffer list |
:copy |
copy line |
:normal |
normal mode change |
:print |
print line |
- special keys in Vim's Command-Line Mode
same to Insert Mode
28. Execute a Command on One or More Consecutive Lines
- Use Line Number as an Address
- Specify a Range of Lines by Address
:{start}, {end}
- Specify a Range of Lines by Selection
'<,'>
- Specify a Range of Lines by Patterns
- Modify an Address Using an Offset
:{address}+n
Symbol |
Address |
1 |
First line of the file |
$ |
Last line of the file |
0 |
Virtual line above first line of the file |
. |
Line where the cursor is placed |
'm |
Line containing mark m |
'< |
Start of visual selection |
'> |
End of visual selection |
% |
The entire file (shorthand for :1,$) |
29. Duplicate or Move Lines Using :t
and :m
Commands
30. Run Normal Mode Commands Across a Range
31. Repeat the Last Ex Command
@:
repeat last Ex command, only use for first time
@@
repeat @:
<C-o>
go back to the previous record in the jump list
32. Tab-Complete Your Ex Commands
33. Insert the Current Word at the Command Prompt
<C-r><C-w>
get the word under the cursor
34. Recall Command from History
<UP>
or <DOWN>
to scrolling through past command-lines
q:
to dialing up the command-line window
Command |
Action |
q/ |
Open the command-line window with history of searches |
q: |
Open the command-line window with hsitory of Ex commands |
ctrl-f |
Switch from Command-Line mode to the command-line window |
35. Run Commands in the Shell
- Executing Programs in the Shell
!{cmd}
or shell, {cmd} and exit
- Using the Contents of a Buffer for Standard Input or Output
Command |
Effect |
:shell |
Start a shell(return to Vim by typing exit) |
:!{cmd} |
Execute {cmd} with the shell |
:read !{cmd} |
Execute {cmd} in the shell and insert its standard output below the cursor |
:[range] write !{cmd} |
Execute {cmd} in the shell with [range] lines as standard input |
:[range] !{filter} |
Filter the specified [range] through external program {filter} |
Files
Manage Multiple Files
36. Track Open Files with the Buffer List
- Understand the Distinction between Files and Buffers
File is stored on the disk, but buffer exist in memory that we are editing in Vim
- buffer usage
Do |
command |
list buffer |
:ls :args |
choose buffer |
:bpre :bnext |
locate buffer |
:bfrist :blast |
operate buffer |
:argdo |
delete buffer |
:bdelete |
37. Group Buffers into a Collection with the Argument List
- The ** wildcard also matches zero or more characters, but it can recurse downward into directories below the specified directory
38. Manage Hidden Files
Command |
Effect |
:w[rite] |
Write the contents of the buffer to disk |
:e[dit]! |
Read the file from disk back into the buffer |
:qa[ll]! |
Close all windows, discarding change without warning |
:wa[ll] |
Write all modified buffer to disk |
39. Divide Your Workspace into Split Windows
Command |
Effect |
<C-w>s |
Split the current window horizontally |
<C-w>v |
Split the current window vertically |
:sp[lit]{file} |
Split the current window horizontally |
:vsp[lit]{file} |
Split the current window vertically |
- Changing the Focus Between Windows
Command |
Effect |
<C-w>w |
Cycle between open windows |
<C-w>h |
Focus the window to the left |
<C-w>j |
Focus the window below |
<C-w>k |
Focus the window above |
<C-w>l |
Focus the window to the right |
Ex Command |
Normal Command |
Effect |
:cl[ose] |
<C-w>c |
Close the active windwow |
:on[ly] |
<C-w>o |
Keep only the active window, closing all |
- Resizing and Rearranging Windows
Keystrokes |
Buffer Contents |
<C-w>= |
Equalize width and height of all windows |
<C-w>_ |
Maximize height of the active window |
<C-w>| |
Maximize width of the active window |
[N]<C-w>_ |
Set active window height to [N] rows |
[N]<C-w>| |
Set active window width to [N] columns |
40. Organize Your Window Layouts with Tab Pages
Command |
Effect |
:tabe{dit}{filename} |
Open {filename in a new tab |
<C-w>T |
Move the current window into its own tab |
:tabc[lose] |
Close the current tab page and all of it windows |
:tabo[nly] |
Keep the active tab page, closing all others |
Ex command |
Normal command |
Effect |
:tabn[ext]{N} |
{N}gt |
Switch to tab page number {N} |
:tabn[ext] |
gt |
Switch to the next tab page |
:tabp[revious] |
gT |
Switch to the previous tab page |
Open Files and Save Them to Disk
41. Open a File by Its Filepath Using :edit
42. Open a File by Its Filename Using :find
- pls refer to
ctrl+p plugin
43. Explore the File System with netrw
44. Save Files to Nonexistent Directories
<C-g>
show the name and status of the current file
:!mkdir -p %:h
and :write
45. Save a File as the Super User
:w !sudo tee % > /dev/null
Getting Around Faster
Navigate Inside Files with Motions
46. Keep Your Fingers on the Home Row
Command |
Move cursor |
h |
one column left |
l |
one column right |
j |
one line down |
k |
one line up |
47. Distinguish Between Real Lines and Display Lines
- Lines that begin with a number correspond to the real line, which may spn one or more display lines
Command |
Move Cursor |
j |
Down one real line |
gj |
Down one display line |
k |
Up one real line |
gk |
Up one display line |
0 |
To first character of real line |
g0 |
To first character of display line |
^ |
To first nonblank character of real line |
g^ |
To first nonblank character of display line |
|Toendofrealline|g |
To end of display line |
48. Move Word-Wise
Command |
Move Cursor |
w |
Forward to start of next word |
b |
Backward to start of current/previous word |
e |
Forward to end of current/next word |
ge |
Backward to end of previous word |
- Know Your Words from Your WORDS
- A word consists of a sequence of letters, digits, and underscores, or as a sequence of other nonblank characters separated with whitespace
- a WORD consists of a sequence of nonblank characters separated with whitespace
49. Find by Character
Command |
Effect |
f{char} |
Forward to the next occurrence of {char} |
F{char} |
Backward to the previous occurrence of {char} |
t{char} |
Forward to the character before the next occurrence of {char} |
T{char} |
Backward to the character after the previous occurrence of {char} |
; |
Repeat the last character-search command |
, |
Reverse the last character-search command |
50. Search to Navigate
51. Trace Your Selection with Precision Text Objects
- Text objects allow us to interact with parenttheses, quotes, XML tag and other common patterns that appear in text
- whenever you see {motion} as part of the syntax for a command, you can also use a text object
Text object |
Selection |
a) or ab |
A pair of (parentheses) |
i) or ib |
Inside of (parentheses) |
a} or aB |
A pair of {braces} |
i} or iB |
Inside of {braces} |
a] |
A pair of [brackets] |
i] |
Inside of [brackets] |
a> |
A pair of |
i> |
Inside of |
a' |
A pair of 'single quotes' |
i' |
Inside of 'single quotes' |
at |
A pair of tags |
it |
Inside of tags |
52. Delete Around, or Change Inside
- general rule:
d{motion}
work with aX
; c{motion}
work with iX
Keystrokes |
Buffer Contents |
iw |
Current word |
aw |
Current word plus one space |
iW |
Current WORD |
aW |
Current WORD plus one space |
is |
Current sentence |
as |
Current sentence plus one space |
ip |
Current paragraph |
ap |
Current paragraph plus one blank line |
53. Mark Your Place and Snap Back to It
m{a-zA-z}
create mark, Lowercase letters are local and uppercase letters are global
'{mark}
go to mark
keystrokes |
Buffer Contents |
'' |
Position before the last jump within current file |
'. |
Location of last change |
'^ |
Location of last insertion |
'[ |
Start of last change or yank |
'] |
End of last change or yank |
'< |
Start of last visu |
54. Jump Between Matching Parentheses
- the
%
jumb between opening and closing sets of parentheses
Navigate Between Files with Jumps
55. Traverse the Jump List
<C-o>
= back; <C-i>
= forward
- jumps
Command |
Effect |
[count]G |
Jump to line number |
//pattern/?pattern/n/N |
Jump to next/previous occurence of pattern |
% |
Jump to matching parenthesis |
(/) |
Jump to start of previous/next sentence |
{/} |
Jump to start of previous/next paragraph |
H/M/L |
Jump to top/middle/bottom of screen |
gf |
Jump to file name under the cursor |
<C-]> |
Jump to definition of keyword under the cursor |
'{mark} |
Jump to a mark |
56. Traverse the Change List
g;
= back (change); g,
= forward (change)
57. Jump to the Filename Under the Cursor
58. Snap Between Files Using Global Marks
Registers
Copy and Paste
59. Delete, Yank, and Put with Vim's Unnamed Register
60. Grok Vim's Registers
- Addressing a Register
"{register}
- The Unnamed Register
""
- The Yank Register
"0
- The Named Register
"a
- "z
when we address a named register with a lowercase letter, it overwirtes the specified register, whereas when we use an uppercase letter, it appends to the specified register.
- The Black Hole Register
"_
- The System Clipboard
"+
and Selection Register "*
- The Expression Register
"=
- More Register
Registr |
Contents |
"% |
Name of the current file |
"# |
Name of the alternate file |
". |
Last inserted text |
": |
Last Ex command |
"/ |
Last search pattern |
61. Replace a Visual Selection with a Register
62. Paste from a Register
P
Insert text before the cursor
gP
Insert lines (all selects) after those lines
63. Interact with the System Clipboard
Macros
64. Record and Execute a Macro
- Capture a Sequence of Command by Recording Macro
q{register} {action} q
- Play Back a Sequence of Command by Executing Macro
@{register} or @@
65. Normalize, Strike, Abort
- when recording a macro, ensure that every command is repeatable
66. Play Back with a Count
67. Repeat a Change on Contiguous Lines
68. Append Command to a Macro
aA
record keystrokes appending them to the existing contents of register
69. Act Upon a Collection of Files
70. Evaluate an Iterator to Number Items in a List
let
create a variable and expression
echo
inspect the current value assigned to a variable
71. Edit the Contents of a Macro
- Paste the Macro into a Document
:put a
- Yank the Macro from the Document Back into a Register
"ay$
Patterns
Matching Patterns and Literals
72. Tune the Case Sensitivity of Search Patterns
- Setting Case Sensitivity Globally
ignorecase
- Setting Case Sensitivity per Search
\c
ignore and \C
take care
- Enabling Smarter Default Case Sensitivity
smartcase
Include uppercase character will case sensitive or not sensitive
73. Use the \v Pattern Switch for Reger Searches
\v
all characters assume a special meaning with the exception of "_", letter and digit
`\v#([0-9a-fA-F]{6}|[0-9a-fA-F]{3})
74. Use the \V Literal Switch for Verbatim Searches
\V
only the backslash have a special meaning
- general rule : a regular expression use the
\v
; a verbatim text use the \V
75. Use Parentheses to Capture Submathces
- reference the submatch for each pair of () by using \1, \2 and so on; \0 refer to the entire match
- _s match whitespace or a line break
76. Stake the Boundaries of a Word
- the < and > symbols match word boundaries
77. Stake the Boundaries of a Match
\zs
marks the start of a match , while the \ze
match the end of a match
/Practical \zsVim
only highlight match Vim
78. Escape Problem Characters
- Escape
/
Characters When Searching Forward \/
- Escape
?
Characters When Searching Backward \?
- Escape
\
Characters Every Time \\
Search
79. Meet the Search Command
Command |
Effect |
n |
Jump to next match, preserving direction and offset |
N |
Jump to previous match, preserving direction and offset |
/<CR> |
Jump forward to next match of same pattern |
?<CR> |
Jump backward to previous match of same pattern |
80. Highlight Search Mathes
set hlsearch
and set nohlsearch
81. Preview the First Match Before Execution
82. Count the Matches for the Current Pattern
83. Offset the Cursor to the End of a Search Match
84. Operate on a Complete Search Match
85. Create Complex Patterns by Iterating upon Search History
86. Search for the Current Visual Selection
Substitution
87. Meet the Substitute Command
- Useage
:[rang]s[ubstitute]/{pattern}/{string}/[flags]
- flags
flags |
Meaning |
g |
globally, change all matches within a line |
c |
confirm |
n |
report the number of occurences |
e |
silence errors |
& |
reuse the same flags from the previous substitute command |
- Special Characters for the Replacement String
Symbol |
Represents |
\r |
Insert a carriage return |
\t |
Insert a tab character |
\ |
Insert a single backslash |
\1 |
Insert the first submatch |
\2 |
Insert the second submatch(and so on, up to \9) |
\0 |
Insert the entire matched pattern |
& |
Insert the entire matched pattern |
~ |
Use {string} from the previous invocation of :substitute |
\={Vim script} |
Evaluate {Vim script} expression: use result as replacement {string} |
88. Find and Replace Every Match in a File
89. Eyeball Each Substitution
trigger |
Effect |
y |
Substitute this match |
n |
Skip this match |
q |
Quit substituting |
l |
"last" - Substitute this match, then quit |
a |
"all" - Substitute this and any remaining matches |
<C-e> |
Scroll the screen up |
<C-y> |
Scroll the screen down |
90. Reuse the Last Search Pattern
:%s/\v(([^']|'\w)+)'/"\1"/g
=> /\v(([^']|'\w)+)'
and :%s//"\1"/g
91. Replace with the Contents of a Register
- pass by value
<C-r>{register}
- pass by reference
\=@{register}
:let @/='Pragmatic Vim
== /Pragmatic
, but not create a record in the search history
92. Repeat the Previous Substitute Command
- Repeat a Line-Wise Substitution Across the Entire File
g&
93. Rearrange CSV Fields Using Submatches
=> /\v^([^,]),([^,]),([^,]*)$
=> :%s//\3,\2,\1
=> /\v\<\/?h\zs/d
=> :%s//\=submatch(0)-1/g
95. Swap Two or More Words
=> /\v(|)
=> :%s//\={"dog":"man","man":"dog"}[submacth(1)]/g
96. Find and Replace Across Multiple Files
=> /Pragmatic\ze Vim
=> :%s//Practical/g
=> argdo %s//Practical/ge
Global Commands
97. Meet the Global Command
- :[range] global[!] /{pattern}/ [cmd]
98. Delete Lines Containing a Pattern
- delete matching lines with
:g/re/d
- keep only matching lines with
:v/re/d
99. Collect TODO Items in a Register
:g/TODO/yank A
100. Alphabetize the Properties of Each Rule in a CSS File
:g/{/ .+1,/}/-1 sort
- Tell Vim Where to Find the Tags File
:set tags
- Generate the tags File
:!ctags -R
- Automatically Execute ctags Each Time a File is save
:autocmd BufWritePost * call system("ctags -R")
103. Navigate Keyword Definitions with Vim's Tag Navigation Command
Command |
Effect |
<C-]> |
Jump to the first tag that matches the word under the cursor |
g<C-]> |
Prompt user to select from multiple matches for the word under the cursor. |
:tag {keyword} |
Jump to the first tag that matches {keyword} |
:tjump {keyword} |
Prompt user to select from multiple matches {keyword} |
:pop or |
Reverse through tag history |
:tag |
Advance through tag history |
:tnext |
Jump to next matching tag |
:tpre |
Jump to previous matching tag |
:tfirst |
Jump to first matching tag |
:tlast |
Jump to last matching tag |
:tselect |
Prompt user to choose an item from the tag match list |
Compile Code and Navigate Errors with the Quickfix List
104. Compile code Without Leaving Vim
105. Browse the Quickfix List
Command |
Action |
:cnext |
Jump to next item |
:cprev |
Jump to previous item |
:cfirst |
Jump to first item |
:clast |
Jump to last item |
:cnfile |
Jump to first item in next file |
:cpfile |
Jump to last item in previous file |
:cc N |
Jump to nth item |
:copen |
Open the quickfix window |
:cclost |
Close the quickfix window |
106. Recall Results from a Previous Quickfix List
:colder and :cnewer
107. Customize the External Compiler
- configure
:make
to Invoke Nodelint
:setlocal makeprg=NODE_DISABLE_COLORS=1\ nodelist\ %
==>
export NODE_DISABLE_COLORS=1
nodelist %
- populate the Quickfix list using nodelint's output
:setglobal errorformat?
Search Project-Wide with grep, vimgrep, and Others
108. Call grep Without Leaving Vim
109. Customize the grep Program
110. Grep with Vim's Internal Search Engine
:vim[grep][!] /{pattern}/[g][j] {file} ...
Dial X for Autocompletion
111. Meet Vim's Keyword Autocompletion
Command |
Type of completion |
<C-n> |
Generic keywords |
<C-x><C-n> |
Current buffer keywords |
<C-x><C-i> |
Included file keywords |
<C-x><C-]> |
tags file keywords |
<C-x><C-k> |
Dictionary lookup |
<C-x><C-l> |
Whole line completion |
<C-x><C-f> |
Filename completion |
<C-x><C-o> |
Ommi-completion |
Keystrokes |
Effect |
<C-n> |
Use the next match from the word list (next match) |
<C-p> |
Use the previous match from the word list (previous match) |
<Down> |
Select the next match from the word list |
<Up> |
Select the previous match from the word list |
<C-y> |
Accept the currently selected match(yes) |
<C-e> |
Revert to the originally typed text(exit from autocompletion |
<C-h>(and<BS>) |
Delete one character from current match |
<C-l> |
Add one character from current match |
{char} |
Stop completion and insert {char} |
113. Understand the Source of Keywords
114. Autocomplete Words from the Dictionary
115. Autocomplete Entire Lines
116. Autocomplete Filenames
117. Autocomplete with Context Awareness
Find and Fix Typos with Vim's Spell Checker
118. Spell Check Your Work
:set spell
Command |
Effect |
]s |
Jump to next spelling error |
[s |
Jump to previous spelling error |
z= |
Suggest corrections for current word |
zg |
Add current word to spell file |
zw |
Remove current word from spell file |
zug |
Revert zg or zw command for current word |
119. Use Alternate Spelling Dictionaries
- Specify a Regional Variant of a Language
:set spell
:set spelllang=en_us
120. Add Words to the Spell File
121. Fix Spelling Errors from Insert Mode
<C-x>s