Vim

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

Shortcuts

Cut/Delete

  • 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: Delte 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

  • yy: Yank current line
  • Y: Yank current line
  • #yy: Yank # lines
  • y#k: Yank the current and N preceeding 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.

Paste/Put

  • 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

  • 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 beetween 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
  • ==: 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 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 beetween line # and &
  • zfap: Create fold of paragpraph
  • zfa}: Create fold in {} brackets
  • zfa): Create fold in () brackets
  • zfa]: Create fold in [] brackets
  • zfa>: Create fold in <> brackets

Search and Replace

  • /#: 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: 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 prompt
  • gUw: 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 buffer
  • old: Search pattern
  • new: Replacement text
  • g: Change all occurences 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

  • :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 numbers
  • m[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 cursor
  • I: Insert text at beginning of line
  • R: Start overtype mode
  • a: Insert text after cursor
  • A: Insert text af 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 cursos by one.
  • CTRL+x CTRL+f: Expand the current path from the filesystem.

Movement

  • 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 screenful
  • <ctrl>+B: Move cursor backward one screenful
  • x<ctrl>+y: Move the cursor up x lines (default: 1 )
  • <ctrl>+U: Move cursor up half a screenful
  • x<ctrl>+E: Move the screen down x lines (default: 1)
  • <ctrl>+D: Move cursor down half a screenful
  • gg: Move cursor to top of file
  • gd: 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 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

Movement (lines)

Spaces are inserted for clarity, but not required.

  • 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

  • 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 area
  • gqq: format the current line
  • g~iw: Change the current word to uppcase letters
  • gUiw: Change the current word to uppcase letters (as above)

Misc

  • 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 (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 word
  • zg — add a word to the dictionary
  • zug — undo the addition of a word to the dictionary
  • z= — 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

Source

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

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

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 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 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

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 whitespaces

Source Source

The following lines in ~/.vimrc will mark all trailing whitespaces 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