Vim Commands Tutorial
Useful resources:
-
Tutorial: https://docs.oracle.com/cd/E19683-01/806-7612/6jgfmsvq7/index.html
-
Summary of Basic
vi
Commands: https://docs.oracle.com/cd/E19683-01/806-7612/6jgfmsvqn/index.html
Vim Reference Guide
Cheatsheet: https://vim.rtorr.com, zh-cn
Modes of vi
-
Edit / Entry / Insert mode:
i
Where you type text.
-
Normal mode:
ESC
Edit more efficiently, navigate.
-
Command-line mode:
:
Where you can enter commands like
:w
to save,:q
to quit, etc.- Press
Enter
to execute the command. - Press
ESC
to ignore whatever is typed and return to normal mode.
- Press
-
Visual mode:
v
(character-wise),V
(line-wise),ctrl+v
(block-wise)For selection
ref:
Get help
:help {subject}
get help on a given subject:help x
get help on the “x” command-
:help 'number'
get help on the ‘number’ optionThe Vim editor has a number of options that enable you to configure and customize the editor. If you want help for an option, you need to enclose it in single quotation marks.
General notation you often see when reading vim documentation:
Notation | Description |
---|---|
[] |
Characters in square brackets are optional. |
[count] |
Repeat the command for count times |
Configuration file:
~/.vimrc
: main config file (options, mappings, autocommands).~/.vim/
: a folder containing scripts, plugins, colorschemes, etc. Vim scans it via theruntimepath
.
:echo &runtimepath
/Users/menghan/.vim,
/Users/menghan/.vim/plugged/editorconfig-vim,/usr/share/vim/vimfiles,
/usr/share/vim/vim91,
/usr/share/vim/vimfiles/after,/Users/menghan/.vim/after
Copy from Vim to Clipboard on Mac
You may be familiar with the yank
command: y
to copy selected text, yy
to copy the current line. It copies stuff to Vim’s internal buffer. I want to copy in Vim and paste to other apps using cmd-C.
To copy to the system clipboard, we’ll use the same command with a few extras modifier to select the correct register.
- Choosing a register
In Vim, you choose a register using
"
. - The system register
For both Mac and Windows, you can select the system register by using
+
. - Putting it all together
Enter visual mode by hitting
v
(orV
if you want to select by lines). Select the text you want to copy, if you want to select til the end of line, press$
, then type:"+y
, it means “copy the selected text into the system register+
”.
Keyboard shortcuts | Function |
---|---|
Navigation | |
h/j/k/l |
←/↓/↑/→ |
o (lowercase o) |
Open a new line below the current line and enters insert mode |
O (uppercase o) |
Open a new line above the current line and enters insert mode |
0 (zero) |
move the cursor to the start of the line, even if the position is blank |
^ |
jump to the first non-blank character of the line, i.e., ignoring any spaces or tabs. |
$ |
go to the end of the line |
n| |
Move to column n of current line. |
gg |
beginning of file |
G |
end of file |
>> |
indent |
<< |
unindent |
ctrl+u |
half page above |
ctrl+d |
half page down |
Move One Word | |
w |
(“word”) move the cursor to the next word or special character |
W |
Jump forwards to the start of a word, treating punctuation as part of words. → Next word, using space as delimiter. |
b |
(“back”) to move the cursor to the left or special character |
B |
Jump backwards to the start of the previous word, treating punctuation as part of words. → Last word, using space as delimiter. |
e |
(“end”) to move the cursor to the last character of the current word. |
E |
End of word, treating punctuation as part of words. |
Copy and Paste | |
dd |
deletes the current line |
yy |
yanks (copy) the current line |
p (Lowercase) |
paste after cursor |
P (Uppercase) |
paste before cursor |
y$ |
Copy everything from the cursor to the end of the line |
d$ |
Cut everything from the cursor to the end of the line |
y^ |
Copy everything from the start of the line to the cursor. |
Deleting Text | |
x |
Delete character under the cursor |
3x / x.. |
Delete three characters |
X |
Delete character to the left of the cursor |
daw / dw |
Delete a word |
5dw |
Delete the next five words. 5 means repeat 5 times, dw means delete a word. |
Insert Mode | |
i |
Insert before the cursor |
I |
Insert at the beginning of the line |
a |
Insert (append) after the cursor |
A |
Insert (append) at the end of the line |
Configuration
:set list
enable list mode; show whitespace chars.
Use :help 'listchars'
to show what the strings mean. To summarize it here:
tab
: displayed as^I
(ctrl-I
)eol
: end of line, default$
trail
: trailing spacesspace
: space.nbsp
: non-breakable space
:set nolist
hide whitespace chars
:set listchars=option1:char1,option2:char2,...
configures the characters used to represent invisible characters when the list
option is enabled. This allows for visual identification of elements like tabs, trailing spaces, and end-of-line markers.
-
charx
: the characters used to display the original whitespace characters.The characters ‘:’ and ‘,’ should not be used. UTF-8 characters can be used when ‘encoding’ is “utf-8”, otherwise only printable characters are allowed. All characters must be single width.
Each character can be specified as hex.
set listchars=eol:\\x24 set listchars=eol:\\u21b5 set listchars=eol:\\U000021b5
Note that a double backslash is used. The number of hex characters must be exactly 2 for
\\x
, 4 for\\u
and 8 for\\U
.Examples:
:set lcs=tab:>-,trail:- :set lcs=tab:>-,eol:<,nbsp:% :set lcs=extends:>,precedes:< :set showbreak=↪\ :set listchars=tab:→\ ,eol:↲,nbsp:␣,trail:•,extends:⟩,precedes:⟨,space:• :set listchars=eol:$,tab:>#,trail:~
you may choose the characters you like.
Parameters that I’m using in my .vimrc
:
set listchars=eol:¬,tab:>·,trail:~ " Show whitespace characters
eol:¬
End of line, the end of the line will show¬
tab:>·
Each tab will show>···
instead of a big whitespacetrail:~
Trailing spaces, it will show~
instead of the amount of spaces given
I didn’t use set list
in my .vimrc
. That means the whitespace characters will not be shown by default. You can enable it by typing :set list
in normal mode.
Make Vim show ALL white spaces as a character
Debian requires files to end with a newline character <EOL>
.
Q: How to insert tab character when expandtab option is on in Vim?
A: You can use <CTRL-V><Tab>
in “insert mode”. In insert mode, <CTRL-V>
inserts a literal copy of your next character.
先按 CTRL-V
,然后按 Tab
键。不是同时按三个键。
FAQ
Q: What is visual mode?
A: It’s like selection using keyboard, instead of a cursor. The selected part will be highlighted.
Q: How to enter visual mode?
A: Press
v
to start characterwise visual mode from your cursor,V
for single-line (linewise visual mode), andctrl+V
for multiple-line, i.e., visual block mode. Select a rectangular block of text.
Q: How to cut entire line and paste to another place?
A: Press dd
to cut, go to the place where you want to insert, press P
(uppercase). The current line will move down by one line.
Q: What is a mapleader?
A: Mapleader will allow you set a key unused by Vim as the <leader>
key. The leader key, in conjunction with another key, will allow you to create new shortcuts. The backslash key (\
) is the default leader key.
" Set the backslash as the leader key.
let mapleader = "\"
Delete to the beginning or end of file
-
Delete to the beginning of the file
:1,.d
That command can be read as “From line 1 to the current position, delete”, or if you prefer, “Delete from line 1 to the current line position.”
-
Delete to the end of the file
:.,$d
That command can be read as “From the current position to the end of file, delete.”
Q: How to Undo and Redo?
A: In command mode,
- use
u
(lowercase) or:undo
key to Undo- Hit
u
multiple times will redo recursively
- Hit
ctrl
+r
or:redo
to Redo.
Tip:
- You can undo multiple changes,
[number]u
. For example,2u
will undo the last 2 changes.
Using a Count to Repeat Commands
Many vi commands can be preceded by a repeat factor (called a count)—a number that precedes the command and tells it how many times to repeat the operation.
For example, 3dd
repeats the command to delete a line three times, therefore deleting three lines. 2dw
deletes two words, and 4x
deletes four characters or spaces.
Using a period (.
) to repeat the previous text-changing command.
For example, if you have just deleted a line with dd
, you can move the cursor to another line and delete it by simply typing a period.
Q: How to autoload the current file while detecting changes?
A: If you want to load the changes, use :e
(short for :edit
). Caveat: If you use :edit!
it will discard local changes and reload.
You can set it in your .vimrc
by default:
set autoread
Block comment
Q: How to indent a block by 2 spaces?
A: Enter Visual Line mode (⇧V) → Select your lines → Enter colon (:
), '<,'>
will auto add, which means for the selected lines → Type norm I<space><space>
(norm, space, capital I, two spaces)→ Hit Enter.
Break down the command:
:'<,'>
: for the lines I selectednorm
: Execute the following sequence of keystrokes as if I was in normal modeI
: Insert at the beginning of the line the following characters<space>
: The character(s) you would like to insert
Another option: use AlignFromCursor
plugin.
Tip:
- When in Visual Line mode (
⇧V
), select the block , hit (Tab
) will indent the block by 4 spaces.
Method 2 – Visual Block Mode (^V)
The other method you can use to comment out multiple lines is to use Visual Block Mode.
To do this, press ESC and navigate to the lines you want to comment out.
-
Press
CTRL
+V
to enable Visual Block Mode.- Using the up and down arrow key, highlight the lines you wish to comment out.
- Once you have the lines selected, press the
SHIFT
+I
keys to enter insert mode. - Enter your command symbol, for example, # sign, and press the ESC key. Vim will comment out all the highlighted lines.
How to remove first ;
of the selected lines?
;extension=php_bz2.dll
;extension=php_curl.dll
;extension=php_fileinfo.dll
;extension=php_ftp.dll
- Place cursor on first or last
;
- Press
Ctrl
+V
to enter Visual Block mode - Use arrow keys or j, k to select the
;
characters you want to delete (or the other “first few characters”) - Press
X
to delete them all at once
This approach can be used to unindent multiple lines as well.
Command-line Mode
Command-line mode is used to enter Ex commands (“:”), search patterns (“/” and “?”), and filter commands (“!”).
Ex command-lines
Quotes ("
)
- at the start of line causes the whole line to be ignored;
-
after a command causes the rest of the line to be ignored.
Ths can be used to add comments.
:set ai "set 'autoindent' option
<key>
means the special key typed. E.g.,
<Esc>
: escape key<Tab>
: tab<CR>
: carriage return, i.e., Enter key
ref:
Norm[al] Commands
:norm
is useful to execute a normal command on a range of lines.
:norm[al][!] {commands}
Execute Normal mode commands {commands}. This makes it possible to execute Normal mode commands typed on the command-line. {commands}
are executed like they are typed.
- For undo all commands are undone together.
- Execution stops when an error is encountered.
Pad line with dashes until 80 characters long
- Select the lines you want to pad.
-
Press
:
to enter the command-line mode and type.:'<,'>normal 80A-<Esc>81|dw
Command breakdown:
:'<,'>
: Selects the current visual selection.normal
: Enters normal mode for the selected lines.80A-
: Appends at the end of the line a dash (-
) 80 times<Esc>
: Exits insert mode. (literally type, do not hitEsc
)81|dw
: Moves the cursor to the column 81 (81|
) and deletes the rest of the line (dw
, delete until the beginning of next word; dashes count as one word).
Note that
:norm
is a shorthand for:normal
, which allows you to run normal mode commands on the selected lines. - Press
Enter
to execute the command.
How to insert soft line break?
<!--- add two spaces -->
My line of text<space><space>
[Name of link](url)
<!--- or add one blackslash -->
My line of text\
[Name of link](url)
Regular expression
Regex 正则表达式
Short totorial: https://www3.ntu.edu.sg/home/ehchua/programming/howto/Regexe.html
The [...]
, known as character class (or bracket list), encloses a list of characters. It matches any SINGLE character in the list. In this example, [0-9]
matches any SINGLE character between 0 and 9 (i.e., a digit), where dash (-
) denotes the range.
Symbol | Meaning | Example |
---|---|---|
* |
the preceding character can occur 0 or more times. | meo*w will match mew , meow , meooow , and meoooooooooooow . [0-9]* matches zero or more digits. It accepts all those in [0-9]+ plus the empty string. |
+ |
the preceding character can occur 1 or more times. | meo+w will match meow , meooow , and meoooooooooooow , but not match mew .[0-9]+ matches one or more digits such as 123 , 000 . |
. |
any character | .* means zero or more of any character. |
[A-Za-z] |
all letters (uppercase and lowercase) | |
{m} |
repetition indicator, meaning the preceding character can repeat exactly m times |
|
{m,} |
the preceding character can repeat m or more times |
|
{m,n} |
the preceding character can repeat m to n times, inclusive |
|
^ |
start-of-line | |
$ |
end-of-line | ^[0-9]+$ matches a numeric string. |
Plugin Manager
vim-plug
is a popular plugin manager for Vim.
Install vim-plug
by running the following command in your terminal:
curl -fLo ~/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
Usage
Add a vim-plug section to your ~/.vimrc
- Begin the section with
call plug#begin()
- List the plugins with
Plug
commands - End the section with
call plug#end()
call plug#begin()
" List your plugins here
Plug 'tpope/vim-sensible'
call plug#end()
vim-plug loads whatever you declare between plug#begin()
and plug#end()
.
Reload the file or restart Vim, then you can,
:PlugInstall
to install the plugins:PlugUpdate
to install or update the plugins:PlugDiff
to review the changes from the last update:PlugClean
to remove plugins no longer in the list
File Structure Under vim-plug
-
vim-plug script:
~/.vim/autoload/plug.vim
-
Plugins (by default):
~/.vim/plugged/REPO_NAME
editorconfig-vim
This plugin is used to configure file format and maintain consistent coding styles for shared projects across various editors and IDEs. It enables editors to read the file format and adhere to defined styles.
For instance, when you save a file in BBEdit, it will automatically convert line endings to LF
(Unix style) and remove trailing spaces, ensuring consistency across different editors.
How to install:
-
Add to your
.vimrc
in your plugin section:Plug 'editorconfig/editorconfig-vim'
-
Save the
.vimrc
file with the command:w
. -
Source your
.vimrc
by calling:source $MYVIMRC
.Replace
$MYVIMRC
with your.vimrc
path, defaults to~/.vimrc
. -
Then call
:PlugInstall
.
Configuration
When opening a file, EditorConfig plugins look for a file named .editorconfig
(all lowercase) in the directory of the opened file and in every parent directory. A search for .editorconfig
files will stop if the root filepath is reached or an EditorConfig file with root=true
is found.
Example $HOME/.vim/plugged/editorconfig-vim/.editorconfig
file:
# top-most EditorConfig file
root = true
# Default settings for all files
[*]
indent_style = space # Use spaces for indentation
indent_size = 2 # Set indentation size to 2 spaces
end_of_line = lf # Use Unix-style line endings (LF)
charset = utf-8 # Set file encoding to UTF-8
trim_trailing_whitespace = true # Remove any whitespace at the end of lines
insert_final_newline = true # Ensure file ends with a newline
# Override for Markdown files
[*.md]
indent_style = space
indent_size = 4
# Override for HTML and CSS files
[*.{html,css}]
indent_style = space # Use spaces for indentation
indent_size = 2 # Set indentation size to 2 spaces
For a project-specific .editorconfig
file, you can create a .editorconfig
file in the root directory of your project. The settings in this file will override the global settings.
-
end_of_line
property can be set to “CR”, “LF”, or “CRLF” (case insensitive) to set line-ending style.lf
: Unix style:\n
(:set ff=unix
force vim to set file format, line endings will change accordingly)crlf
: Windows dos style:\r\n
(:fileformat=dos
)cr
: old Mac style:\r
(:set ff=mac
)
What
editorconfig-vim
does when you open or save files:- When opening/switching to a file, apply built-in editor setting. In some editors, this will mark the file as dirty.
- If no built-in editor setting, apply built-in editor operation on file save.
- If no built-in editor operation, apply manual operation on file save or do nothing.
In plain language, if your editor can’t do that automatically, it will fix the line endings when you save.
ref:
nerdtree
The NERDTree is a file system explorer for the Vim editor. Using this plugin, users can visually browse complex directory hierarchies, quickly open files for reading or editing, and perform basic file system operations.
Refs:
-
Configuration guide: https://www.freecodecamp.org/news/vimrc-configuration-guide-customize-your-vim-editor/
-
Learning the vi and Vim Editors by Arnold Robbins, Elbert Hannah, and Linda Lamb.