This is about how to use vim. Shortcuts and configurations.
Shortcuts
Cut/Delete
dd
: Delete current line#dd
: Delete # linesdw
: Delete current wordd$
: Delete to end of lineD
: 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 clipboarddf<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 + contentdit
: Delte in Tag block - useful to remove content between html tags.
Copy/Yank
yy
: Yank current lineY
: Yank current line#yy
: Yank # linesy#k
: Yank the current and N preceeding lines.yw
: Yank current wordy$
: Yank to end of liney^
: 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 clipboarda,by g
: Yank line a to b into register g."g3y
: Yank 3 lines into register g.
Paste/Put
p
: Put current register at cursorP
: 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 indent7pu a
: Paste register a under line 7"pa
: Paste register a under the current line.
Modify
gUw
: Switch case of word to CAPSguw
: Switch case of word to lower~
: Switch case of character under cursorg~w
: Invert case on wordr#
: Replace character under cursor with #ce
: Replace from cursor to end of wordc$
: Replace from cursor to end of lineC
: Replace from cursor to end of linec#w
: Replace # wordsci"
: Replace between double quote pairci'
: Replace between single quote pairci)
: Replace between () pairci]
: Replace between [] pairci}
: Replace between {} pairci>
: Replace between <> paircit
: Replace beetween XML/HTML tag pair<ctrl> A
: Increment number under cursor<ctrl> X
: Decrement number under cursorx
: Delete character under cursorX
: Delete character before cursor>>
: Indent entire line<<
: Unindent entire line==
: Autoindent entire line:reg
: View contents of registers:set ro
: Set file to readonly. Will still allow editing the buffer.:set nomodifiable
: Make file unmodifiable, (set noma
).
Code folding
zo
: Open foldzc
: Close foldzr
: Reduce fold levelzm
: Increase fold levelzR
: Reduce all foldszM
: Increase all foldszj
: Move to next fold downwardszk
: Move to next fold upwardzd
: Delete foldzE
: Delete all foldszf#j
: Create fold of # lines below cursor:#,& fold
: Create fold beetween line # and &zfap
: Create fold of paragpraphzfa}
: Create fold in {} bracketszfa)
: Create fold in () bracketszfa]
: Create fold in [] bracketszfa>
: Create fold in <> brackets
Search and Replace
/#
: Find # searching forward?#
: Find # searching backwardn
: Continue search downwardsN
: Continue search upwards/foo/e
: Set cursor to the end of match3/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
: Substitude old for new on line with no prompt:#,&s/old/new/g
: Substitude old for new on lines # to & with no prompt:%s/old/new/g
: Globally substitude old for new with no prompt:%s/old/new/gc
: Globally substitude old for new with promptgUw
: Convert whole word to uppcase:%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 bufferold
: Search patternnew
: Replacement textg
: Change all occurences in each line (global)e
: No error if the pattern is found.|
: Separator between commandsupdate
: 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 theautowriteall
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
the current buffer
: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 config file
:so $MYVIMRC
: Reload the currently active config file
External Calls
:! <command>
Execute an external command in the shell:r <file>
Insert the contents of file at cursor position:r !<command>
Insert ouptut 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].1,5w !bash
Execute line 1 to 5 in the bash shell.
Tabs
: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
: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, S
: (upper case) 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 + -
: Descrease current pane height<ctrl> W + >
: Increase current pane width<ctrl> W + <
: Descrease current pane width<ctrl>+w, q
: close the current window/pane.
File
: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, close current buffer and open as current buffer. :x
: Save and quit:q
: Quit:q!
: Force quit:bd
: Delete/close buffer:hardcopy
: Print file
Location
<crtl> G
: Show current position in file:f
: Show line numbersm[a-zA-Z]
: Place mark [a-zA-Z] at cursor`[a-zA-Z]
: Goto mark [a-zA-Z]:marks
: Show all marks
Text Insertion
i
: Insert text before cursorI
: Insert text at beginning of lineR
: Start overtype modea
: Insert text after cursorA
: Insert text af end of lineo
: Open new line following current lineO
: Open new line before current linev
: Switch to visual selection modeV
: 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 cursos by one.CTRL+x
CTRL+f
: Expand the current path from the filesystem.
Movement
h
: Move cursor leftl
: Move cursor rightj
: Move cursor downk
: Move cursor upgj
: Move cursor down one display linegk
: Move cursor up one display lineH
: Move cursor to top of displayM
: Move cursor to middle of displayL
: Move cursor to bottom of displayw
: Move cursor forward to start of next worde
: Move cursor to end of next wordb
: Move cursor backward one word)
: Move cursor forward one sentence(
: Move cursor backward one sentence0
: 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 screenful<ctrl>+B
: Move cursor backward one screenfulx<ctrl>+y
: Move the cursor up x lines (default: 1 )<ctrl>+U
: Move cursor up half a screenfulx<ctrl>+E
: Move the screen down x lines (default: 1)<ctrl>+D
: Move cursor down half a screenfulgg
: Move cursor to top of filegd
: Move the cursor to the defition 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 lineF#
: Move cursor backwards character # on linet#
: Move cursor forward to character before the next character # on lineT#
: Move cursor backward to character after the next character # on line
Movement (lines)
Spaces are inserted for clarity, but not required.
5,7m 21
: Move lines 5 to 7 to after line 215m.
: 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 12m 'a
: Move current line to after line with mark a.m 'a-1
: Move current line to before line with mark a.
Sorting
10,12!sort -k2
: Sort lines 10 to 12 by the second word/column:sort u
: Sort all lines and remove dublicates
Macros
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
{Visual}gq
: format the visually selected areagqq
: format the current lineg~iw
: Change the current word to uppcase lettersgUiw
: Change the current word to uppcase letters (as above)
Misc
u
: UndoU
: Restore line<ctrl> r
: RedoJ
: Join line below to current line.
: Repeat last command{Visual}gq
: format the visually selected area (linebreaks at 80 chars)gqq
: format the current line (linebreaks at 80 chars):set ro
: Sets a file readonly, but still changeable:set nomodifiable
: Sets a file to readonly without being able to edit it. Short ::set noma
:set modifiable
: Sets a file to being modifable again. Short::set ma
Spellchecking
Some of the key commands when using spellchecking:
]s
— move to the next mispelled word[s
— move to the previous mispelled wordzg
— add a word to the dictionaryzug
— undo the addition of a word to the dictionaryz=
— view spelling suggestions for a mispelled word
To enable spell checking temporarily:
:setlocal spell
.vimrc
settings
Linebreak
Set automatic linebreak to 80 characters. This will break the line at the defined character. This might get annoyting in certain file types (like markdown), so it could be moved in ~/.vim/after/ftplugin/<filetype>.vim
instead.
set tc=80
Current date insertion
Insert the current date or a current timestamp at the position of the cursor, followed by a whitespace.
" 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
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
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
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
- ctrl-vim
- loremipsum
- nerdtree
- syntastic
- tabular
- tocdown
- vim-easy-align
- vim-markdownfootnotes
- vim-fugitive
- vimoutliner
- vim-puppet
- vim-repeat
- vim-snipmate
- vim-snippets
- vim-surround
- vim-unimpaired
vim-easy-align
Align YAML
- Mark fields
ga->:
NERDTree
Config
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
Shortcuts
<SHIFT>+A
: Toggle fullscreen for PanelB
: Open bookmarks:Bookmark <name>
: Create bookmark at the current selected node./<string>
: Search for string in the currently listed nodes
vim-surround
Surrounding Words, sentences what-ever with braches, tags, xml, etc, etc.
Take a look at vim-repeat to enable the repeat key .
.
Shortcuts
ysiw[
: Add surrounding,Hello
->[Hello]
ds'
: Remove surrounding,'Hello'
->Hello
ysiw<em>
: Emphasize,Hello
-><em>Hello</em>
vim-repeat
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"
Trailing whitespaces
The following lines in ~/.vimrc
will mark all trailing whitespaces red.
highlight ExtraWhitespace ctermbg=red guibg=red
match ExtraWhitespace /\s\+$/
Unicode
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
/