Vim

This is about how to use vim. Shortcuts and configurations.

Shortcuts

Cut/Delete

Keys Description
dd Delete current line
#dd Delete # lines
dw Delete current word
d$ Delete to end of line
D Delete to end of line
|#,&d Delete from line # to &
"[a-zA-Z0-9]dd Delete line into register [a-zA-Z0-9].
"+dd Delete line into host clipboard
df<char> Delete forward including next character char.
dt<char> Delete forward until but not including char.
dT<char> Delete backward up to character char.
dF<char> Delete backwards through character char.
dat Delete a Tag block - useful to remove HTML tags + content
dit Delete in Tag block - useful to remove content between HTML tags.
diw Delete inner word
daw Delete outer word
das Delete a sentence.
dap Delete a paragraph.

Copy/Yank

Keys Description
yy Yank current line
Y Yank current line
#yy Yank # lines
y#k Yank the current and N preceding lines.
yw Yank current word
y$ Yank to end of line
y^ Yank to beginning of line
|#,&y Yank from line # to &
"[a-zA-Z0-9]yy Yank line into register [a-zA-Z0-9]
"+yy Yank line into host clipboard
a,by g Yank line a to b into register g.
"g3y Yank 3 lines into register g.
:7t. Yank line 7 and paste it below the current line.
:7y Yank line 7 into the buffer.
:7,7+10y Yank line 7 to 17 into the buffer.

Paste/Put

Keys Description
p Put current register at cursor.
P Put current register before cursor.
"[a-zA-Z0-9]p Put register [a-zA-Z0-9] at cursor.
"+p Put text from clipboard at cursor.
]p Put current register WRT indent.
7pu a Paste register a under line 7.
"pa Paste register a under the current line.

Modify

Keys Description
gUw Switch case of word to CAPS
guw Switch case of word to lower
~ Switch case of character under cursor
g~w Invert case on word
r# Replace character under cursor with #
ce Replace from cursor to end of word
c$ Replace from cursor to end of line
C Replace from cursor to end of line
c#w Replace # words
ci" Replace between double quote pair
ci' Replace between single quote pair
ci) Replace between () pair
ci] Replace between [] pair
ci} Replace between {} pair
ci> Replace between <> pair
cit Replace between XML/HTML tag pair
<ctrl> A Increment number under cursor
<ctrl> X Decrement number under cursor
x Delete character under cursor
X Delete character before cursor
>> Indent entire line
<< Unindent entire line
== Auto-indent entire line
|reg View contents of registers
|set ro Set file to read-only. Will still allow editing the buffer.
|set nomodifiable Make file unmodifiable, (set noma).

Code folding

Keys Description
zo Open fold
zc Close fold
zr Reduce fold level
zm Increase fold level
zR Reduce all folds
zM Increase all folds
zj Move to next fold downwards
zk Move to next fold upward
zd Delete fold
zE Delete all folds
zf#j Create fold of # lines below cursor
|#,& fold Create fold between line # and &
zfap Create fold of paragraph
zfa} Create fold in {} brackets
zfa) Create fold in () brackets
zfa] Create fold in [] brackets
zfa> Create fold in <> brackets

Search and Replace

Keys Description
/# Find # searching forward
?# Find # searching backward
n Continue search downwards
N Continue search upwards
/foo/e Set cursor to the end of match
3/foo/e+1 find 3rd foo, set cursor to the end of match + 1
/foo/s-2 Set cursor to start of match - 2
/foo/+3 find foo and move cursor three lines down
/foo\|bar Search for foo or bar
|%s/\r//g Delete DOS returns ^M
%s#\s*\r\?$## Delete trailing spaces and DOS returns.
% Move to matching bracket from under cursor
|s/old/new/g Substitute old for new on line with no prompt
|#,&s/old/new/g Substitute old for new on lines # to & with no prompt
|%s/old/new/g Globally substitute old for new with no prompt
|%s/old/new/gc Globally substitute old for new with prompt
gUw Convert whole word to uppercase
|%s/[A-Z]/\l\0/g convert all to lowercase Go to visual mode, select and press ~
|bufdo %s/old/new/ge | update Search and replace in all buffers and write it back.
bufdo Apply the following commands to all buffers
%s Search and replace all lines in the buffer
old Search pattern
new Replacement text
g Change all occurrences in each line (global)
e No error if the pattern is found.
| Separator between commands
update Save (write file only if changes were made). That is necessary because by default, Vim will not switch away from a buffer if it has been changed. One alternative is to set the autowriteall option so changed buffers are automatically saved when required.
set autowriteall
:bufdo %s/old/new/ge
  • %s/.*\n.*\n/\0New content\r/g: Add the string New content after every second line in the whole file. Common line addressing applies, of course.

Reload the current file

Source

the current buffer

Keys Description
:edit Reload the current file.
:so % Reload the current open file.
:edit! Reload the current file and ignore made changes to the current buffer.

the configuration file

  • :so $MYVIMRC: Reload the currently active configuration file

External Calls

Keys Description
:! <command> Execute an external command in the shell
:r <file> Insert the contents of file at cursor position
:r !<command> Insert output of command at cursor position
:r! sed -n '<start>,<end>p' <file> Insert the content of file in the range from start to end at the cursor position.
gx Open the URL under the cursor.
1,5w !bash Execute line 1 to 5 in the bash shell.

Tabs

Keys Description
:tabnew Open a new tab.
:tabe <file> Open file in a new tab.
<ctrl> PgUp Switch to tab on Right.
<ctrl> PgDn Switch to tab on Left.
:tabdo <command> Run command in all tabs.
:retab Convert spaces to tabs or tabs to spaces.

Panes

Keys Description
:vnew|:vsp Split window/pane vertically.
<ctrl>+w, v (lower case) for vertical splitting.
:new|:sp Split window/pane horizontally.
:vim -o file1 file2 Open mention files in horizontally.
:vim -O file1 file2 Open mention files in vertically.
<ctrl>+w, <shift>-s For horizontal splitting.
<ctrl> W + H Switch to pane to the left.
<ctrl> W + L Switch to pane to the right.
<ctrl> W + J Switch to pane to the below.
<ctrl> W + K Switch to pane to the above.
<ctrl> W + _ Give all vertical space to current pane.
<ctrl> W + | Give all horizontal space to current pane.
<ctrl> W + = Evenly distribute space for all panes.
<ctrl> W + + Increase current pane height.
<ctrl> W + - Decrease current pane height.
<ctrl> W + > Increase current pane width.
<ctrl> W + < Decrease current pane width.
<ctrl>+w, q close the current window/pane.

File

Keys Description
:e <file> Open file.
:enew New file.
:w Save current file.
:w <file> Save current file as new filename, but keep the current buffer open.
:wq Save and quit.
:sav $file Write content to $file, close current buffer and open $file as current buffer.
:x Save and quit.
:q Quit.
:q! Force quit.
:bd Delete/close buffer.
:hardcopy Print file.
CTRL+G Print the current relative file name.
1 CTRL+G Print the current file name with full path.

Location

Keys Description
<crtl> G Show current position in file.
:f Show line numbers.
m[a-zA-Z] Place mark [a-zA-Z] at cursor.
`[a-zA-Z] Go to mark [a-zA-Z].
:marks Show all marks.

Text Insertion

Keys Description
i Insert text before cursor.
I Insert text at beginning of line.
R Start over-type mode.
a Insert text after cursor.
A Insert text after end of line.
o Open new line following current line.
O Open new line before current line.
v Switch to visual selection mode.
V Switch to visual line selection mode.
<crtl> v Switch to visual block selection mode.
<ESC>xin<ESC> Insert character n x number of times at the current position.
CTRL+A Increase the integer under the cursor by one.
CTRL+X Decrease the integer under the cursor by one.
CTRL+x CTRL+f Expand the current path from the file-system.

Movement

Keys Description
h Move cursor left.
l Move cursor right.
j Move cursor down.
k Move cursor up.
gj Move cursor down one display line.
gk Move cursor up one display line.
H Move cursor to top of display.
M Move cursor to middle of display.
L Move cursor to bottom of display.
w Move cursor forward to start of next word.
e Move cursor to end of next word.
b Move cursor backward one word.
) Move cursor forward one sentence.
( Move cursor backward one sentence.
0 Move cursor to start of line.
^ Move cursor to first character of line.
$ Move cursor to end of line.
<ctrl>+F Move cursor forward one full screen.
<ctrl>+B Move cursor backward one full screen.
x<ctrl>+y Move the cursor up x lines (default: 1 ).
<ctrl>+U Move cursor up half a screen.
x<ctrl>+E Move the screen down x lines (default: 1).
<ctrl>+D Move cursor down half a screen.
gg Move cursor to top of file.
gd Move the cursor to the definition of a method under the cursor.
G Move cursor to bottom of file.
#G Move cursor to line #.
#gg Move cursor to line #.
f# Move cursor forward to next character # on line.
F# Move cursor backwards character # on line.
t# Move cursor forward to character before the next character # on line.
T# Move cursor backward to character after the next character # on line.
vim "+normal ${line}G${column}|" $file Open file with cursor at specific position.

Movement (lines)

Spaces are inserted for clarity, but not required.

Keys Description
5,7m 21 Move lines 5 to 7 to after line 21.
5m. Move line 5 to after the current line.
5m $ Move line 5 to after the last line (end of file).
.,.+4m 21 Move 5 lines start with the current line to after line 21.
,+4m21 same (Move 5 lines start with the current line to after line 21.
m 12 Move current line to after line 12.
m 'a Move current line to after line with mark a.
m 'a-1 Move current line to before line with mark a.

Sorting

Source

Keys Description
10,12!sort -k2 Sort lines 10 to 12 by the second word/column.
:sort u Sort all lines and remove duplicates.

Macros

Keys Description
q[a-zA-Z0-9] Start recording macro into register [a-zA-Z0-9].
q End recording of current macro.
@[a-zA-Z0-9] Playback macro from register [a-zA-Z0-9].
n@[a-zA-Z0-9] Playback macro from register [a-zA-Z0-9] n times.

Formatting

Keys Description
{Visual}gq format the visually selected area.
gqq format the current line.
g~iw Change the current word to uppercase letters.
gUiw Change the current word to uppercase letters (as above).

Misc

Keys Description
u Undo.
U Restore line.
<ctrl> r Redo.
J Join line below to current line.
. Repeat last command.
{Visual}gq format the visually selected area (line-breaks at 80 chars).
gqq format the current line (line-breaks at 80 chars).
:set ro Sets a file read-only, but still changeable.
:set nomodifiable Sets a file to read-only without being able to edit it. Short : :set noma.
:set modifiable Sets a file to being modifiable again. Short: :set ma.

Spellchecking

Some of the key commands when using spellchecking:

Keys Description
]s move to the next misspelled word
[s move to the previous misspelled word
zg add a word to the dictionary
zG add a word to the internal word-list. Will be forgotten when leaving VIM.
zug undo the addition of a word to the dictionary
z= view spelling suggestions for a misspelled word
:spellgood $string Add string as a good word to the word-list.
:spellgood! $string Add string as a good word to the internal word-list.

To enable spell checking temporarily:

:set spell spelllang=en_GB
:set spell

.vimrc settings

Line break

Set automatic line break to 80 characters. This will break the line at the defined character. This might get annoying in certain file types (like markdown), so it could be moved in ~/.vim/after/ftplugin/<filetype>.vim instead.

set tc=80

Current date insertion

Source

Insert the current date or a current timestamp at the position of the cursor, followed by a white-space.

" Key mappings for date insertion
:nnoremap <F9> "=strftime("%Y-%m-%d")<CR>P<SPACE>i<SPACE><ESC>l
:nnoremap <F10> "=strftime("%Y-%m-%d %H:%M:%S")<CR>P<SPACE>i<SPACE><ESC>l

Swap file location

Source

The swap file contains the changes and edits on a file between savings.

" The directory must exist
:set directory=$HOME/.vim/swapfiles//

For Unix and Win32, if a directory ends in two path separators "//" or "\", the swap file name will be built from the complete path to the file with all path separators substituted to percent '%' signs. This will ensure file name uniqueness in the preserve directory.


Read range of lines from file

Source

These are some way of reading a range of lines from a file into the current buffer.

:r! sed -n <start>,<end>p /path/to/file.txt
:put =readfile('/path/to/foo/foo.c')[<start-1>:<end-1>]

Remote editing

For editing files remotely on a server, you a combination with SCP.

:edit scp://username@host//path/to/file

Current file path

Source

You can use the current file path in VIM for Shell execution or to run the current file without leaving vim. Use the placeholder % for this.

# Stash the current file
# git add <filename>
:! git add %

# Execute the current file:
# ./<filename>
:!%:p

Plugins

vim-easy-align

Align YAML

  1. Mark fields
  2. ga->:

Nerdtree

Source

Configuration

Set Nerdtree window to toggle on F4 and the width of the panel to 60

$ cat .vimrc
...
:nnoremap <F4> :NERDTreeToggle<CR>
let g:NERDTreeWinSize=60

Nerdtree shortcuts

Keys Description
<SHIFT>+A Toggle full-screen for Panel
B Open bookmarks
:Bookmark <name> Create bookmark at the current selected node.
/<string> Search for string in the currently listed nodes

vim-surround

Source

Surrounding Words, sentences what-ever with branches, tags, XML, etc, etc. Take a look at vim-repeat to enable the repeat key ..

VIM-surround shortcuts

Keys Description
ysiw[ Add surrounding, Hello -> [Hello]
ds' Remove surrounding, 'Hello' -> Hello
ysiw<em> Emphasize, Hello -> <em>Hello</em>

vim-repeat

Source

Making the repeat key (.) work with plugin maps.

Firefox Plugin Vimperator

The Firefox plugin Vimperator brings VIM into the browser. Besides using the standard commands, it also supports external editor.

External editor

Put this line in the configuration file ~/.vimperatorrc:

" Changing the editor
set editor="rxvt -e vim"

VIM and GIT commits

Source

VIM remembers the last position when it was closed. In GIT commits this leads to the start position being not always on the first line.

This change in vimrc sets the start line to 0 for GIT commits:

autocmd FileType gitcommit call setpos('.', [0, 1, 1, 0])

Trailing white-spaces

Source Source

The following lines in ~/.vimrc will mark all trailing white-spaces red.

highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/

Vim Doku


Unicode

Source Source

Enter Unicode i Vim by pressing CTRL+VU + Code (in insert mode).

Eg.

CTRL+VU+2610: ☐
CTRL+VU+2611: ☑

Digraph

For adding all kinds of special characters

<ctlr>k + the two symbols for the character

Searching in it with

:help digraph-table
/

Sources