🖥️vim
➡️This is a command-line reference manual for commands and command combinations that you don’t use often enough to remember it. This cheatsheet explains the vim command with important options and switches using examples.
95 minute read
▁ ▂ ▃ ▄ ꧁ 🔴☠ COMMANDLINE-KUNGFU WITH CHEATSHEETS ☠🔴꧂▅ ▃ ▂ ▁
# ██╗ ██╗██╗███╗ ███╗
# ██║ ██║██║████╗ ████║
# ██║ ██║██║██╔████╔██║
# ╚██╗ ██╔╝██║██║╚██╔╝██║
# ╚████╔╝ ██║██║ ╚═╝ ██║
# ╚═══╝ ╚═╝╚═╝ ╚═╝
# File management
:e reload file
:q quit
:q! quit without saving changes
:w write file
:w {file} write new file
:x write file and exit
# Movement
k
h l basic motion
j
w next start of word
W next start of whitespace-delimited word
e next end of word
E next end of whitespace-delimited word
b previous start of word
B previous start of whitespace-delimited word
0 start of line
$ end of line
gg go to first line in file
G go to end of file
gk move down one displayed line
gj move up one displayed line
# Insertion
# To exit from insert mode use Esc or Ctrl-C
# Enter insertion mode and:
a append after the cursor
A append at the end of the line
i insert before the cursor
I insert at the beginning of the line
o create a new line under the cursor
O create a new line above the cursor
R enter insert mode but replace instead of inserting chars
:r {file} insert from file
# Editing
u undo
yy yank (copy) a line
y{motion} yank text that {motion} moves over
p paste after cursor
P paste before cursor
<Del> or x delete a character
dd delete a line
d{motion} delete text that {motion} moves over
# Search and replace with the `:substitute` (aka `:s`) command
:s/foo/bar/ replace the first match of 'foo' with 'bar' on the current line only
:s/foo/bar/g replace all matches (`g` flag) of 'foo' with 'bar' on the current line only
:%s/foo/bar/g replace all matches of 'foo' with 'bar' in the entire file (`:%s`)
:%s/foo/bar/gc ask to manually confirm (`c` flag) each replacement
# Preceding a motion or edition with a number repeats it 'n' times # Examples:
50k moves 50 lines up
2dw deletes 2 words
5yy copies 5 lines
42G go to line 42
#---------------------------------------------------------------------------------#
# VIM - Kurzanleitung von Christoph Maciejewski (c) 1999 #
#---------------------------------------------------------------------------------#
# Allgemeines
#-----------#
# Alle vim-Kommandos (beginnen mit ":") können in die Konfigurationsdatei eingetragen werden. Diese kann heissen: .gvimrc .vimrc oder unter Win32 _vimrc
# Bearbeituns-Modi
#----------------#
[ESC]: Kommandomodus
[i]: Einfügemodus (an der aktuellen Stelle)
[A]: Einfügemodus (am Ende d er aktuellen Zeile -> "append")
[:]: Execute-modus (Eingabe eines Kommandos), Kommandovervollständigung mit [TAB]
# Dateiverwaltung:
#----------------#
[:e Dateiname]: Datei laden
[:e Verzeichnis]: Dateimanager (Der Parameter ist ein Verzeichnis)
[:w]:Aktuelle Datei speichern
[:w Dateiname]: Aktuelle Datei speichern unter einem neuen Namen (Bearbeitet wird we iter das Original)
[:sav Dateiname]: Aktuelle Datei speichern unter einem neuen Namen (Neue Datei wird bearbeitet)
[:buffer Dateiname]: Zwischen den Buffers (geöffnete Dateien) umschalten
[:next]: Zum nächsten Buffer wechseln
[:prev]: Zum vorherigen Buffer wechseln
[:q]:VIM beenden (nur wenn alle Buffers gespeichert, sonst Meldung)
[:q!]:VIM beenden (nicht gespeicherte Buffers gehen verloren)
[:wq]: Speichern und Schliessen (Alternativ: [ZZ])
# Editor:
#-------#
[u]: Aktion rückgängig machen (undo)
[Ctrl+r]: Aktion wiederherstellen (redo)
[yy]: Zeile kopieren
[dd]: Zeile ausschneiden (löschen)
[dw]: Wort ausschneiden (ab der aktuellen Position nach rechts)
[db]: Wort ausschneiden (ab der aktuellen Position nach links)
[d^]: Bis Zeilenanfang löschen (ab der aktuellen Position)
[d$]: Bis Zeilenende löschen (ab der aktuellen Position)
[:'a,'bd]: Von Marke "a" bis Marke "b" löschen
[p]: Einfügen
[v]: Anfang des zu markierenden Bereichs setzen (Mit den Cursortasten Bereich markieren)
[y]: Markierten Bereich kopieren
["xy]: Markierten Bereich in das Puffer "x" kopieren (es können bis zu 26 Puffer belegt werden)
["xp]: Text aus dem Puffer "x" einfügen
[VG]: Alles markieren (ab der aktuellen Position nach unten
[mx]: Marke setzen ("x" ist ein bel. Kleinbuchstabe -> es sind 26 Marken möglich)
['x]: Zur Marke "x" springen'
[J]: CR/LF am Ende einer Zeile löschen (Zeilen zusammenfügen)
[:set list]: Nicht darstellbare Zeichen anzeigen
[:set ic]: Gross/Kleinschreibung ignorieren
[Ctrl+n]: Wort vervollständigen
[:%!xxd]: HEX-Editor-Modus (xxd muss installiert sein)
# Im Text navigieren:
#-------------------#
[gg]: An die erste Position des Textes springen
[GG]: An die letzte Position des Textes springen
[m][Cursor]: Um "m" Zeichen/Zeilen springen (mit den Cursortasten -> links, rechts, oben, unten)
[w]: Wortweise nach rechts springen (Mit [b] nach links) -> auch hier kann eine Zahl vorangestellt werden
# Suchen und Ersetzen:
#--------------------#
[/Suchwort]: Nach "Suchwort" suchen ("Suchwort" ist ein reg. Ausdruck). Mit [n] weiter suchen.
[/Suchwort/i]: Nach "Suchwort" suchen, Gross/Kleinschreibung ignorieren
[:1,$s/Unix/Linux/g]: "Unix" durch "Linux" ersetzen (Bereich: 1,$ -> vom Anfang bis Ende, g: Alle ersetzen)
[:1,.s/^/#/g]: Alle Zeilen bis zur aktuellen Cursorposition (.) auskommentieren
# Sonstiges:
#----------#
[:split]: Hauptfenster wird horizontal aufgespaltet. Wechseln mit [Ctrl+w+w].
[:r !date]: Ausgabe eines UNIX-Kommandos in den Text einfügen (hier Datum)
[:syntax on]: Syntaxeinfärbung einschalten
[:set nu!]: Zeilennummern ein-/ausblenden.
[:set ai]: Automatisches Einrücken (AutoIdent)
[:set cin]: Automatisches Einrücken im Still von C (Einrücken in Funktionsrümpfen)
[:set softtabstop=3]: Tabulator entspricht drei Leerzeichen
[:set shiftwidth=3]: Autom. Einrücken entsp richt drei Leerzeichen
[:ab w1 wort]: Autom. Ersetzen von "w1" durch "wort" während der Eingabe
#------------------------------------------------------------#
:set scrolloff=5
# Setup vim so that scrolling within a file will provide 5 lines of preceding context before the cursor.
# Twitter Vimtips
#------------------------------------------------------------#
"+p
# to paste from it.
"+y
# to copy to the X11 (or Windows) clipboard.
"2p
# Will put the second to last thing yanked
"2p
# Will put the second to last thing yanked, "3p will put the third to last, etc.
$ command | vim - (via @dlibanori)
# Edit a command output in Vim as a file
%s/<C-R>a/bar/g
# will place the contents of register 'a' in the search, and replace it with 'bar'.
%s/^ \ n/ /
# to delete all empty lines (remove spaces from command!)
'.
# jumps to last modified line'
'0
# opens the last modified file ('1 '2 '3 works too)
* # g* g#
# each searches for the word under the cursor (forwards/backwards)
/<CTRL-r><CTRL-w>
# will pull the word under the cursor into search.
/\%>80v.\+
# with search highlighting (:set hlsearch) will highlight any text after column 80.
5@a
# repeats it 5 times.
:%s//joe/igc
# substitute your last search with joe.
:%s/< !--\_.{-}-- >//
# Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
:%s/[.!?]\_s\+\a/\U&\E/g
# will uppercase the first letter of each sentence (except the very first one).
:%s/\ r//g
# to remove all those nasty ^M from a file, or
:%s/\ r$//g
# for only at the end of a line.
:%s/\v(.*\n){5}/&\r
# Will insert a blank line every 5 lines
:40,50m30
# will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
:E to see a simple file explorer.
# (:Ex will too, if that is easier to remember.)
:Sex
# Will open a file explorer in a split window. I bet you will remember that one.
:g/_pattern_/s/^/#/g
# will comment out lines containing _pattern_ (if '#' is your comment character/sequence)
:history
# lists the history of your recent commands, sans duplicates.
:ju(mps) :
# list your movements {{help|jump-motions}}
:ju(mps) :
# list your movements {{help|jump-motions}} \
:ju(mps) : list your movements {{help|jump-motions}}
:s/\(.*\):\(.*\)/\2 : \1/
# Will reverse fields separated by ':'
:tabo
# will close all open tabs except the active one.
:tabo
# Will close all open tabs except the active one.
:vimgrep /stext/ **/*.txt | :copen
# searches for stext recursively in *.txt files and show results in separate window
:vmap // y/< C-R >"< CR >
# "Will make searching for highlighted text (i.e. in visual mode) require only a highlight and //
:wa
# 'Will save all buffers.
:y<line-number>
# Will yank the passed in ln, :y<ln1, ln2> will yank the range.
< CTRL-n >< CTRL-p >
# offers word-completion while in insert mode.
< CTRL-x >< CTRL-l >
# offers line completion in insert mode.
<CTRL-i>
# trace your movements forwards in a file.
<CTRL-o> :
# trace your movements backwards in a file.
<CTRL-x><CTRL-l>
# offers line completion in insert mode.
==
# Will auto-indent the current line. Select text in visual mode, then == to auto-indent the selected lines.
@:
# to repeat the last executed command. http://is.gd/9cuP
@a
# repeats the recording.
@:
# repeats the last command-line command. So, :w then @: would write twice. Make sense? :h @: for more info!
CTRL-w K
# Will switch vertical split into horizontal, CTRL-w H will switch a horizontal into a vertical.
CTRL-w | and CTRL-W
# maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes 'em.
:%s/<word>//gn
# Count the number of occurences of a word in a file with
Ctrl-c
# to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
%s#.*\ (def\ ).*#\ 1#
# Will delete everything on all lines except for the string 'hours'. (no spaces)
?http://somestuff.com
# To search for a URL without backslashing, search backwards!
d% in #vim
# Will delete to the matching brace. Makes sense, but never used it before. /cc
[I (that is bracket-open, capital-i)
# shows lines containing the word under the cursor
`.
# jumps to exact position of last modification.`
ci " inside a " "
# Will erase everything between "" and place you in insertion mode."
ci " inside a " "
# Will" erase everything between "" and place you in insertion mode. eg. :y41 or :y45,50
g//#
# will print the results of the last search w/ line numbers
g;
# will cycle through your recent changes (or g, to go in reverse.
g<CTRL-G>
# to see technical information about the file, such as how many words are in it, or how many bytes it is.
gUU
# converts entire line to uppercase.
ga
# will display the ASCII, hex, and octal value of the character under the cursor.
ggVG=
# will auto-format the entire document
gq{movement}
# to wrap text, or just gq while in visual mode.
gqap
# will format the current paragraph.
guu
# converts entire line to lowercase.
noremap ' ` and noremap ` '
# to make marks easier to navigate. Now ` is easier to reach!
q
# stops it.
qa
# starts a recording in register 'a'.
vim -c [command]
# will launch vim and run a : command at launch, e.g. "vim -c NERDTree."
ysiw'
# 'to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin
zz
# to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
~
# nverts case of current character.
"2p
# Will put the second to last thing yanked
"3p
# Will put the third to last, etc.
/< CTRL-r >< CTRL-w >
# Will pull the word under the cursor into search.
/\%>80v.\+ with search highlighting (:set hlsearch)
# Will highlight any text after column 80.
:%s/<word>//gn
# Count the number of occurences of a word in a file with
:%s//joe/igc
# substitute your last search with joe.
:%s/[.!?]\_s\+\a/\U&\E/g
# Will uppercase the first letter of each sentence (except the very first one).
:%s/\ r$//g
# for only at the end of a line.
:%s/\ r//g
# to remove all those nasty ^M from a file, or
:%s/\\/\//g
# Replaces all backslashes with forward slashes.
:40,50m30
# Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
:E to see a simple file explorer. (:Ex
# Will too, if thats easier to remember.)
:Sex
# Will open a file explorer in a split window. I bet you'll remember that one.
:history
# lists the history of your recent commands, sans duplicates.
:ju(mps) :
# list your movements {{help|jump-motions}} \
:s/\(.*\):\(.*\)/\2 : \1/
# Will reverse fields separated by ':'
:set foldmethod=syntax
# to make editing long files of code much easier. zo to open a fold. zc to close it.
:set guifont=*
# in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
:vimgrep /stext/ **/*.txt | :copen
# searches for stext recursively in *.txt files and show results in separate window
:vimgrep pattern **/*.txt
# Will search all *.txt files in the current directory and its subdirectories for the pattern.
;
# is a motion to repeat last find with f.
f'
# would find next quote.
c;
# would change up to the next '
< CTRL-i >
# trace your movements forwards in a file.
< CTRL-o > :
# trace your movements backwards in a file.
< CTRL-x >< CTRL-l >
# offers line completion in insert mode.
'f' and 't'
# (like first and til) are very powerful. See :help t or :help f.
Replaces all backslashes with forward slashes.
"_dd
# "to delete one line without overriding the buffer. "_ is black hole register. "When writing to this register, nothing happens.""
g;
# Will cycle through your recent changes (or g, to go in reverse.
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is.
ga
# Will display the ASCII, hex, and octal value of the character under the cursor.
git config --global core.editor "gvim --nofork"
# to use gvim to edit your git messages set gits core editor as follows
gq{movement}
# to wrap text, or just
gq
# while in visual mode.
gqap
# will format the current paragraph.
"+y
# "to copy to the X11 (or Windows) clipboard. "+p to paste from it.
"2p
# Will put the second to last thing yanked,
%s/^ \ n/ / to delete all empty lines (remove spaces from command!)
* # g* g# each searches for the word under the cursor (forwards/backwards)
/.*fred&.*joe/
# Will search for fred AND joe, in any order.
/< fred >/
# Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).
/\%>80v.\+ with search highlighting (:set hlsearch)
# Will highlight any text after column 80.
/begin\_.*end
# Will search for begin AND end over multiple lines.
/fred\_s*joe/
# Will search for fred AND joe with whitespace (including newline) in between.
/fred|joe/
# Will search for either fred OR joe.
/joe.*fred.*bill/
# Will search for joe AND fred AND bill, in that order.
/joe/+3
# Will search for joe and place the cursor three lines below the match.
/joe/e
# Will search for joe and place the cursor at the end of the match.
2f/
# would find the second occurrence of '/' in a line.
40,50m30
# Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
:%s#.*(hours).*#1#
# Will delete everything on a line except for the string 'hours'.
:%s/< ! - -\_.\{-}-- >//
# Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
:%s/^ \ n \{3}//
# Will delete a block of 3 empty lines. (remove the spaces)
:%s/joe|fred/jerks/g
# Will replace both 'fred' and 'joe' with 'jerks'.
:%s/~/sue/igc
# substitute your last replacement string with sue.
:40,50m30
# Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
:E to see a simple file explorer. (:Ex
# Will too, if thats easier to remember.)
:Sex
# Will open a file explorer in a split window. I bet you'll remember that one.
:e $MYVIMRC
# to directly edit your vimrc.
:source $MYVIMRC
# to reload. Mappings may make it even easier.
:ju(mps) :
# list your movements {{help|jump-motions}} \
:match ErrorMsg '\%>80v.\+'
# uses matching to highlight lines longer than 80 columns.
:r !date
# Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).
:tab sball
# Will re-tab all files in the buffers list.
:xa
# Will save all buffers and exit Vim.
< CTRL-n >< CTRL-p >
# offers word-completion while in insert mode.
< CTRL-o > :
# trace your movements backwards in a file.
< CTRL-i >
# trace your movements forwards in a file.
==
# Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines.
@:
# to repeat the last executed command.
Ctrl-a, Ctrl-x
# Will increment and decrement, respectively, the number under the cursor.
s"
# In visual mode, use to surround the selected text with " using the surround plugin.
In your ~/.vimrc, `set clipboard=unnamed`. Now all operations work with the OS clipboard. No need for "+, "*
'\v'
# Use in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.)
[I
# (thats bracket-open, capital-i) shows lines containing the word under the cursor
ci " inside a " "
# "Will erase everything between "" and place you in insertion mode.
ggguG
# Will lower case the entire file (also known as the Jerry Yang treatment).
gq{movement} to wrap text, or just gq while in visual mode. gqap
# Will format the current paragraph.
"+y
# "to copy to the X11 (or Windows) clipboard. "+p to paste from it.
"3p
# Will put the third to last, etc. http://is.gd/do1Dt
* # g* g#
# each searches for the word under the cursor (forwards/backwards)
/< fred >/
# Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).
/begin\_.*end
# Will search for begin AND end over multiple lines.
/fred\_s*joe/
# Will search for fred AND joe with whitespace (including newline) in between.
/fred|joe/
# Will search for either fred OR joe.
/joe.*fred.*bill/
# Will search for joe AND fred AND bill, in that order.
/joe/+3
# Will search for joe and place the cursor three lines below the match.
/joe/e
# Will search for joe and place the cursor at the end of the match.
/joe/e+1
# Will search for joe and place the cursor at the end of the match, plus on character.
/joe/s-2
# Will search for joe and place the cursor at the start of the match, minus two characters.
2f/
# would find the second occurrence of '/' in a line.
:%s#<[^>]\+>##g
# Will remove HTML tags, leaving the text. (non-greedy)
:%s//joe/igc
# substitute your last search with joe.
:%s/< ! - -\_.\{-}-- >//
# Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
:%s/[.!?]\_s\+\a/\U&\E/g
# Will uppercase the first letter of each sentence (except the very first one).
:%s/^ \ n \{3}//
# Will delete a block of 3 empty lines. (remove the spaces)
:%s/^\ n\ +/\ r/
# Will compress multiple empty lines into one. (remove spaces)
:%s/joe|fred/jerks/g
# Will replace both 'fred' and 'joe' with 'jerks'.
:g/search_term/#
# display each line containing 'search_term' with line numbers.
:h slash< CTRL-d >
# to get a list of all help topics containing the word 'slash'.
:history
# lists the history of your recent commands, sans duplicates.
:lcd %:p:h
# Will change to the directory of the current file.
:match ErrorMsg '\%>80v.\+'
# uses matching to highlight lines longer than 80 columns.
:r !date
# Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).
:s/\(.*\):\(.*\)/\2 : \1/
# Will reverse fields separated by ':'
:set foldmethod=syntax
# to make editing long files of code much easier. zo to open a fold. zc to close it.
:vimgrep pattern **/*.txt
# Will search all *.txt files in the current directory and its subdirectories for the pattern.
:xa
# Will save all buffers and exit Vim.
;
# is a motion to repeat last find with f. f' would find next quote.
c;
# would change up to the next
@:
# to repeat the last executed command.
g-
g+
# After performing an undo, you can navigate through the changes using g- and g+ . Also, try :undolist to list the changes.
'f'
# first are very powerful. See :help f.
't'
# til are very powerful. See :help t
:%s/<word>//gn
# Count the number of occurences of a word in a file with
q:
# Need to edit and run a previous command? then find the command, edit it, and Enter to execute the line.
g;
# Will cycle through your recent changes (or g, to go in reverse.
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
gf
# Will open the file under the cursor. (Killer feature.)
guu
# converts entire line to lowercase.
gUU
# converts entire line to uppercase.
~
# inverts case of current character.
$ command | vim -
/.*fred&.*joe/
# Will search for fred AND joe, in any order.
/< CTRL-r >< CTRL-w >
# Will pull the word under the cursor into search.
:%s#<[^>]\+>##g
# Will remove HTML tags, leaving the text. (non-greedy)
:%s/\ r//g
# to remove all those nasty ^M from a file, or
:%s/\ r$//g
# for only at the end of a line.
:%s/^\ n\ +/\ r/
# Will compress multiple empty lines into one. (remove spaces)
:%s/~/sue/igc
# substitute your last replacement string with 'sue'.
:e $MYVIMRC
# to directly edit your vimrc.
:source $MYVIMRC
# to reload. Mappings may make it even easier.
:g/_pattern_/s/^/#/g
# Will comment out lines containing _pattern_ (if '#' is your comment character/sequence)
:g/search_term/#
# display each line containing 'search_term' with line numbers.
:lcd %:p:h
# Will change to the directory of the current file.
:set guifont=*
# in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
:tab sball
# Will re-tab all files in the buffers list.
:vimgrep /stext/ **/*.txt | :copen
:w !sudo tee %
# Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?)
:wa
# Will save all buffers.
< CTRL-x >< CTRL-l >
# offers line completion in insert mode.
CTRL-w H
# Will switch a horizontal into a vertical.
CTRL-w K
# Will switch vertical split into horizontal
CTRL-w s CTRL-w T
# Will open current buffer in new tab
CTRL-w | and CTRL-W _
# maximize your current split vertically and horizontally, respectively.
CTRL-W =
# equalizes em.
Ctrl-a, Ctrl-x
# Will increment and decrement, respectively, the number under the cursor.
vim -x filename
# Edit and encrypt a file
vim scp://username@host//path/to/file
# From a command-line, to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
K
# runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
q:
# Need to edit and run a previous command? then find the command, edit it, and Enter to execute the line.
ga
# Will display the ASCII, hex, and octal value of the character under the cursor.
gf
# Will open the file under the cursor. (Killer feature.)
ggVG=
# Will auto-format the entire document
ggguG
# Will lower case the entire file (also known as the Jerry Yang treatment).
git config --global core.editor "gvim --nofork"
# searches for stext recursively in *.txt files and show results in separate window
vim -c [command]
# to use gvim to edit your git messages set gits core editor. Will launch vim and run a : command at launch, e.g. "vim -c NERDTree."
zz
# to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
%s/<C-R>a/bar/g
# Will place the contents of register 'a' in the search, and replace it with 'bar'.
'0
# opens the last modified file ('1 '2 '3 works too)
:%s#.*(hours).*#1#
# Will delete everything on a line except for the string 'hours'.
Ctrl-c
# to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
qa
# starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
:%s/\ v(.*\ n){5}/&\ r
# Will insert a blank line every 5 lines (remove spaces)
:read [filename]
# Will insert the contents of [filename] at the current cursor position
:tabdo [some command]
# Will execute the command in all tabs. Also see windo, bufdo, argdo.
Ctrl+r=53+17<Enter>.
# In insert mode: This way you can do some calcs with vim.
'u'
# is undo.
Ctrl-R
# is redo?
ci{ ▒
# change text inside {} block. Also see di{, yi{, ci( etc.
%
# matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
%
# matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
:scriptnames
# Will list all plugins and _vimrcs loaded.
:set autochdir instead of :lcd %:p:h
# in your vimrc to change directories upon opening a file.
:vsplit filename
# Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!
# Twitter Vimtips *vimtips.txt* For Vim version 8.0. http://zzapper.co.uk/vimtips.html Jul2017
#------------------------------------------------------------#
------------------------------------------------------------------------------
# new items marked [N] , corrected items marked [C]
# *best-searching*
/joe/e : cursor set to End of match
3/joe/e+1 : find 3rd joe cursor set to End of match plus 1 [C]
/joe/s-2 : cursor set to Start of match minus 2
/joe/+3 : find joe move cursor 3 lines down
/^joe.*fred.*bill/ : find joe AND fred AND Bill (Joe at start of line)
/^[A-J]/ : search for lines beginning with one or more A-J
/begin\_.*end : search over possible multiple lines
/fred\_s*joe/ : any whitespace including newline [C]
/fred\|joe : Search for FRED OR JOE
/.*fred\&.*joe : Search for FRED AND JOE in any ORDER!
/\<fred\>/ : search for fred but not alfred or frederick [C]
/\<\d\d\d\d\> : Search for exactly 4 digit numbers
/\D\d\d\d\d\D : Search for exactly 4 digit numbers
/\<\d\{4}\> : same thing
/\([^0-9]\|^\)%.*% : Search for absence of a digit or beginning of line
# finding empty lines
/^\n\{3} : find 3 empty lines
/^str.*\nstr : find 2 successive lines starting with str
/\(^str.*\n\)\{2} : find 2 successive lines starting with str
# using rexexp memory in a search find fred.*joe.*joe.*fred *C*
/\(fred\).*\(joe\).*\2.*\1
# Repeating the Regexp (rather than what the Regexp finds)
/^\([^,]*,\)\{8}
# visual searching
:vmap // y/<C-R>"<CR> : search for visually highlighted text
:vmap <silent> // y/<C-R>=escape(@", '\\/.*$^~[]')<CR><CR> : with spec chars
# \zs and \ze regex delimiters :h /\zs
/<\zs[^>]*\ze> : search for tag contents, ignoring chevrons
# zero-width :h /\@=
/<\@<=[^>]*>\@= : search for tag contents, ignoring chevrons
/<\@<=\_[^>]*>\@= : search for tags across possible multiple lines
# searching over multiple lines \_ means including newline
/<!--\_p\{-}--> : search for multiple line comments
/fred\_s*joe/ : any whitespace including newline *C*
/bugs\(\_.\)*bunny : bugs followed by bunny anywhere in file
:h \_ : help
# search for declaration of subroutine/function under cursor
:nmap gx yiw/^\(sub\<bar>function\)\s\+<C-R>"<CR>
#" multiple file search
:bufdo /searchstr/ : use :rewind to recommence search
# multiple file search better but cheating
:bufdo %s/searchstr/&/gic : say n and then a to stop
# How to search for a URL without backslashing
?http://www.vim.org/ : (first) search BACKWARDS!!! clever huh!
# Specify what you are NOT searching for (vowels)
/\c\v([^aeiou]&\a){4} : search for 4 consecutive consonants
/\%>20l\%<30lgoat : Search for goat between lines 20 and 30 [N]
/^.\{-}home.\{-}\zshome/e : match only the 2nd occurence in a line of "home" [N]
:%s/home.\{-}\zshome/alone : Substitute only the 2nd occurrence of home in any line [U]
# find str but not on lines containing tongue
^\(.*tongue.*\)\@!.*nose.*$
\v^((tongue)@!.)*nose((tongue)@!.)*$
.*nose.*\&^\%(\%(tongue\)\@!.\)*$
:v/tongue/s/nose/&/gic
'a,'bs/extrascost//gc : trick: restrict search to between markers (answer n) [N]
/integ<C-L> : Control-L to complete search term [N]
#----------------------------------------
# *best-substitution*
:%s/fred/joe/igc : general substitute command
:%s//joe/igc : Substitute what you last searched for [N]
:%s/~/sue/igc : Substitute your last replacement string [N]
:%s/\r//g : Delete DOS returns ^M
# Is your Text File jumbled onto one line? use following
:%s/\r/\r/g : Turn DOS returns ^M into real returns
:%s= *$== : delete end of line blanks
:%s= \+$== : Same thing
:%s#\s*\r\?$## : Clean both trailing spaces AND DOS returns
:%s#\s*\r*$## : same thing
# deleting empty lines
:%s/^\n\{3}// : delete blocks of 3 empty lines
:%s/^\n\+/\r/ : compressing empty lines
:%s#<[^>]\+>##g : delete html tags, leave text (non-greedy)
:%s#<\_.\{-1,}>##g : delete html tags possibly multi-line (non-greedy)
:%s#.*\(\d\+hours\).*#\1# : Delete all but memorised string (\1) [N]
# parse xml/soap
%s#><\([^/]\)#>\r<\1#g : split jumbled up XML file into one tag per line [N]
%s/</\r&/g : simple split of html/xml/soap [N]
:%s#<[^/]#\r&#gic : simple split of html/xml/soap but not closing tag [N]
:%s#<[^/]#\r&#gi : parse on open xml tag [N]
:%s#\[\d\+\]#\r&#g : parse on numbered array elements [1] [N]
ggVGgJ : rejoin XML without extra spaces (gJ) [N]
%s=\\n#\d=\r&=g : parse PHP error stack [N]
:%s#^[^\t]\+\t## : Delete up to and including first tab [N]
# VIM Power Substitute
:'a,'bg/fred/s/dick/joe/igc : VERY USEFUL
# duplicating columns
:%s= [^ ]\+$=&&= : duplicate end column
:%s= \f\+$=&&= : Dupicate filename
:%s= \S\+$=&& : usually the same
# memory
:%s#example#& = &#gic : duplicate entire matched string [N]
:%s#.*\(tbl_\w\+\).*#\1# : extract list of all strings tbl_* from text [NC]
:s/\(.*\):\(.*\)/\2 : \1/ : reverse fields separated by :
:%s/^\(.*\)\n\1$/\1/ : delete duplicate lines
:%s/^\(.*\)\(\n\1\)\+$/\1/ : delete multiple duplicate lines [N]
# non-greedy matching \{-}
:%s/^.\{-}pdf/new.pdf/ : delete to 1st occurence of pdf only (non-greedy)
%s#^.\{-}\([0-9]\{3,4\}serial\)#\1#gic : delete up to 123serial or 1234serial [N]
# use of optional atom \?
:%s#\<[zy]\?tbl_[a-z_]\+\>#\L&#gc : lowercase with optional leading characters
# over possibly many lines
:%s/<!--\_.\{-}-->// : delete possibly multi-line comments
:help /\{-} : help non-greedy
# substitute using a register
:s/fred/<c-r>a/g : sub fred# with contents of register "a"
:s/fred/<c-r>asome_text<c-r>s/g
:s/fred/\=@a/g : better alternative as register not displayed (not *) [C]
:s/fred/\=@*/g : replace string with contents of paste register [N]
# multiple commands on one line
:%s/\f\+\.gif\>/\r&\r/g | v/\.gif$/d | %s/gif/jpg/
:%s/a/but/gie|:update|:next : then use @: to repeat
# ORing
:%s/goat\|cow/sheep/gc : ORing (must break pipe)
:'a,'bs#\[\|\]##g : remove [] from lines between markers a and b [N]
:%s/\v(.*\n){5}/&\r : insert a blank line every 5 lines [N]
# Calling a VIM function
:s/__date__/\=strftime("%c")/ : insert datestring
:inoremap \zd <C-R>=strftime("%d%b%y")<CR> : insert date eg 31Jan11 [N]
# Working with Columns sub any str1 in col3
:%s:\(\(\w\+\s\+\)\{2}\)str1:\1str2:
# Swapping first & last column (4 columns)
:%s:\(\w\+\)\(.*\s\+\)\(\w\+\)$:\3\2\1:
# format a mysql query
:%s#\<from\>\|\<where\>\|\<left join\>\|\<\inner join\>#\r&#g
# filter all form elements into paste register
:redir @*|sil exec 'g#<\(input\|select\|textarea\|/\=form\)\>#p'|redir END
:nmap ,z :redir @*<Bar>sil exec 'g@<\(input\<Bar>select\<Bar>textarea\<Bar>/\=form\)\>@p'<Bar>redir END<CR>
# substitute string in column 30 [N]
:%s/^\(.\{30\}\)xx/\1yy/
# decrement numbers by 3
:%s/\d\+/\=(submatch(0)-3)/
# increment numbers by 6 on certain lines only
:g/loc\|function/s/\d/\=submatch(0)+6/
# better
:%s#txtdev\zs\d#\=submatch(0)+1#g
:h /\zs
# increment only numbers gg\d\d by 6 (another way)
:%s/\(gg\)\@<=\d\+/\=submatch(0)+6/
:h zero-width
# rename a string with an incrementing number
:let i=10 | 'a,'bg/Abc/s/yy/\=i/ |let i=i+1 # convert yy to 10,11,12 etc
# as above but more precise
:let i=10 | 'a,'bg/Abc/s/xx\zsyy\ze/\=i/ |let i=i+1 # convert xxyy to xx11,xx12,xx13
# find replacement text, put in memory, then use \zs to simplify substitute
:%s/"\([^.]\+\).*\zsxx/\1/
# "Pull word under cursor into LHS of a substitute
:nmap <leader>z :%s#\<<c-r>=expand("<cword>")<cr>\>#
# Pull Visually Highlighted text into LHS of a substitute
:vmap <leader>z :<C-U>%s/\<<c-r>*\>/
# substitute singular or plural
:'a,'bs/bucket\(s\)*/bowl\1/gic [N]
----------------------------------------
# all following performing similar task, substitute within substitution
# Multiple single character substitution in a portion of line only
:%s,\(all/.*\)\@<=/,_,g : replace all / with _ AFTER "all/"
# Same thing
:s#all/\zs.*#\=substitute(submatch(0), '/', '_', 'g')#
# Substitute by splitting line, then re-joining
:s#all/#&^M#|s#/#_#g|-j!
# Substitute inside substitute
:%s/.*/\='cp '.submatch(0).' all/'.substitute(submatch(0),'/','_','g')/
----------------------------------------
# *best-global* command
:g/gladiolli/# : display with line numbers (YOU WANT THIS!)
:g/fred.*joe.*dick/ : display all lines fred,joe & dick
:g/\<fred\>/ : display all lines fred but not freddy
:g/^\s*$/d : delete all blank lines
:g!/^dd/d : delete lines not containing string
:v/^dd/d : delete lines not containing string
:g/joe/,/fred/d : not line based (very powerfull)
:g/fred/,/joe/j : Join Lines [N]
:g/-------/.-10,.d : Delete string & 10 previous lines
:g/{/ ,/}/- s/\n\+/\r/g : Delete empty lines but only between {...}
:v/\S/d : Delete empty lines (and blank lines ie whitespace)
:v/./,/./-j : compress empty lines
:g/^$/,/./-j : compress empty lines
:g/<input\|<form/p : ORing
:g/^/put_ : double space file (pu = put)
:g/^/m0 : Reverse file (m = move)
:g/^/m$ : No effect! [N]
:'a,'bg/^/m'b : Reverse a section a to b
:g/^/t. : duplicate every line
:g/fred/t$ : copy (transfer) lines matching fred to EOF
:g/stage/t'a : copy (transfer) lines matching stage to marker a (cannot use .) [C]
:g/^Chapter/t.|s/./-/g : Automatically underline selecting headings [N]
:g/\(^I[^^I]*\)\{80}/d : delete all lines containing at least 80 tabs
# perform a substitute on every other line
:g/^/ if line('.')%2|s/^/zz /
# match all lines containing "somestr" between markers a & b
# copy after line containing "otherstr"
:'a,'bg/somestr/co/otherstr/ : co(py) or mo(ve)
# as above but also do a substitution
:'a,'bg/str1/s/str1/&&&/|mo/str2/
:%norm jdd : delete every other line
# incrementing numbers (type <c-a> as 5 characters)
:.,$g/^\d/exe "norm! \<c-a>": increment numbers
:'a,'bg/\d\+/norm! ^A : increment numbers
# storing glob results (note must use APPEND) you need to empty reg a first with qaq.
# save results to a register/paste buffer
:g/fred/y A : append all lines fred to register a
:g/fred/y A | :let @*=@a : put into paste buffer
:g//y A | :let @*=@a : put last glob into paste buffer [N]
:let @a=''|g/Barratt/y A |:let @*=@a
# filter lines to a file (file must already exist)
:'a,'bg/^Error/ . w >> errors.txt
# duplicate every line in a file wrap a print '' around each duplicate
:g/./yank|put|-1s/'/"/g|s/.*/Print '&'/
# replace string with contents of a file, -d deletes the "mark"'
:g/^MARK$/r tmp.txt | -d
# display prettily
:g/<pattern>/z#.5 : display with context
:g/<pattern>/z#.5|echo "==========" : display beautifully
# Combining g// with normal mode commands
:g/|/norm 2f|r* : replace 2nd | with a star
"send output of previous global command to a new window
:nmap <F3> :redir @a<CR>:g//<CR>:redir END<CR>:new<CR>:put! a<CR><CR>
"----------------------------------------
# *Best-Global-combined-with-substitute* (*power-editing*)
:'a,'bg/fred/s/joe/susan/gic : can use memory to extend matching
:/fred/,/joe/s/fred/joe/gic : non-line based (ultra)
:/biz/,/any/g/article/s/wheel/bucket/gic: non-line based [N]
----------------------------------------
# Find fred before beginning search f
################################################################
# In Vim mehrere Zeilen auskommentieren
#------------------------------------------------------------#
[STRG]+[V]
um in den „block-visual mode“ zu gelangen
Gewünschte Zeilen (mit den Pfeiltasten) markieren
[SHIFT]+[i] drücken um ein Zeichen am Anfang der Zeile einzufügen
Das Kommentarzeichen einfügen (z.B. „#“ oder „//“)
Mit [ESC] den visuellen Modus beenden.
Nun sollte vor jeder Zeile die man gerade markiert hatte das Zeichen erscheinen.
# Kommentieren
Dazu Wechselt man zuerst in den “Visuellen-Block-Modus” mit STRG+V
Und markiert nun abwärts die Zeilen die man kommentieren möchte (Pfeil nach unten oder j)
Sind alle gewünschten Zeilen markiert wechselt man mit SHIFT+I in den “Insert-Modus”.
Nun schreibt man an den Anfang der obersten Zeile eine Kommentarzeichen (z.B # für Bash) und verlässt dann den “Insert-Modus”.
Nun werden an den Anfang jeder markierten Zeile eine # eingefügt.
# Ent-Kommentieren
Dazu Wechselt man zuerst in den “Visuellen-Block-Modus” mit STRG+V
Und markiert nun abwärts die Rauten die man entfernen möchte (Pfeil nach unten oder j)
Sind alle gewünschten Rauten markiert entfernt man sie mit ‘x’
########################### vim bash-support plugin ##################################
:helptags $HOME/.vim/doc/
# Make Bash-support Plug-in Help Accessible
\hh
# for built-in help
\hm
# for a command help
\ntw
# Start settings
\cfr
# insert Comments in .sh scripts
\sc
# case in … esac (n, I)
\sei
# elif then (n, I)
\sf
# for in do done (n, i, v)
\sfo
# for ((…)) do done (n, i, v)
\si
# if then fi (n, i, v)
\sie
# if then else fi (n, i, v)
\ss
# select in do done (n, i, v)
\su
# until do done (n, i, v)
\sw
# while do done (n, i, v)
\sfu
# function (n, i, v)
\se
# echo -e “…” (n, i, v)
\sp
# printf “…” (n, i, v)
\sa
# array element, ${.[.]} (n, i, v) and many more array features.
\cfu
# To create a header for the function above, type \cfu
\rr
# update file, run script (n, I)
\ra
# set script cmd line arguments (n, I)
\rc
# update file, check syntax (n, I)
\rco
# syntax check options (n, I)
\rd
# start debugger (n, I)
\re
# make script executable/not exec.(*) (in)
\nr
# to write predefined code snippets
\nw
# to read predefined code snippets
################### vim NERDTree plugin #########################
:NERDTree
# start NERDTree
# in vim you can a number under the cursor, or nearest number
# - press strg-a to increment
# - press strl-x to decrement
vim +/search-term <filename>
# will go to the first match of the specified search term
# A vi/vim 'feature'. I found this years ago, by accident: If in vi command mode you type
!!command # NOTE: no preceding colon!
# then vi will run command and put its output into the file being edited, eg:
!!ls -l
# How to add text at the end of each line - This will do it to every line in the file:
:%s/$/,/
# If you want to do a subset of lines instead of the whole file, you can specify them in place of the %.
# One way is to do a visual select and then type the :. It will fill in :'<,'> for you, then you type the rest of it (Notice you only need to add s/$/,/)
:'<,'>s/$/,/
# There is in fact a way to do this using Visual block mode. Simply pressing $A in Visual block mode appends to the end of all lines in the selection. The appended text will appear on all lines as soon as you press Esc.
# So this is a possible solution:
vip<C-V>$A,<Esc>
vi tip: pressing '.' in command mode will repeat the last change made (insert, append, delete, etc.). Can be prefixed with number.
In vim, pressing % while the cursor is over a {, ( or [ will jump your cursor to the matching ], ), or } and vice versa.
gq{movement} # to wrap text, or just gq while in visual mode. gqap will format the current paragraph.
g<CTRL-G> # to see technical information about the file, such as how many words are in it, or how many bytes it is.
:%s/[.!?]\_s\+\a/\U&\E/g # will uppercase the first letter of each sentence (except the very first one).
:g/_pattern_/s/^/#/g # will comment out lines containing _pattern_ (if '#' is your comment character/sequence)
:vimgrep /stext/ **/*.txt | :copen # searches for stext recursively in *.txt files and show results in separate window
%s/^ \ n/ / # to delete all empty lines (remove spaces from command!)
ggVG= # will auto-format the entire document
:tabo # will close all open tabs except the active one.
/\%>80v.\+ # with search highlighting (:set hlsearch) will highlight any text after column 80.
gq{movement} # to wrap text, or just gq while in visual mode. gqap will format the current paragraph.
:vimgrep /stext/ **/*.txt | :copen # searches for stext recursively in *.txt files and show results in separate window
To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
In gvim, change the cursor depending on what mode you are in (normal, insert, etc):
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
CTRL-w | and CTRL-W # maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes 'em.
/<CTRL-r><CTRL-w> # will pull the word under the cursor into search.
"+y to copy to the X11 (or Windows) clipboard. "+p to paste from it.
ga # will display the ASCII, hex, and octal value of the character under the cursor.
[I (that is bracket-open, capital-i) # shows lines containing the word under the cursor
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
:40,50m30 # will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
In your ~/.vimrc, `set clipboard=unnamed`. Now all operations work with the OS clipboard. No need for "+, "*
vim -c [command] # will launch vim and run a : command at launch, e.g. "vim -c NERDTree."
g; # will cycle through your recent changes (or g, to go in reverse.
'0 # opens the last modified file ('1 '2 '3 works too)
qa # starts a recording in register 'a'.
q # stops it.
@a # repeats the recording.
5@a # repeats it 5 times.
g//# # will print the results of the last search w/ line numbers
%s/<C-R>a/bar/g # will place the contents of register 'a' in the search, and replace it with 'bar'.
:%s/~/sue/igc substitute your last replacement string with sue.
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':'
:%s/~/sue/igc substitute your last replacement string with 'sue'.
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
Edit and encrypt a file: vim -x filename (via @dlibanori)
:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns.
K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters.
zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
/.*fred&.*joe/ # Will search for fred AND joe, in any order.
gf # Will open the file under the cursor. (Killer feature.)
/joe/e # Will search for joe and place the cursor at the end of the match.
@: to repeat the last executed command.
:read [filename] # Will insert the contents of [filename] at the current cursor position
:e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
:%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces)
/joe/+3 # Will search for joe and place the cursor three lines below the match.
Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
CTRL-w s CTRL-w T # Will open current buffer in new tab
:Sex # Will open a file explorer in a split window. I bet you will remember that one.
< CTRL-n >< CTRL-p > offers word-completion while in insert mode.
git config --global core.editor "gvim --nofork" # to use gvim to edit your git messages set gits core editor as follows:
CTRL-w K # Will switch vertical split into horizontal, CTRL-w H will switch a horizontal into a vertical.
:%s/\\/\//g # Replaces all backslashes with forward slashes.
ysiw' # to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin'
:E to see a simple file explorer. # (:Ex will too, if that is easier to remember.)
:%s/\ r//g # to remove all those nasty ^M from a file, or
:%s/\ r$//g # for only at the end of a line.
'. # jumps to last modified line'
`. # jumps to exact position of last modification.`
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment).
guu # converts entire line to lowercase.
gUU # converts entire line to uppercase.
~ # nverts case of current character.
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
noremap ' ` and noremap ` ' # to make marks easier to navigate. Now ` is easier to reach'!
:wa # Will save all buffers.
:xa # Will save all buffers and exit Vim.
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern.
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces)
:history # lists the history of your recent commands, sans duplicates.
:scriptnames # Will list all plugins and _vimrcs loaded.
:%s/<word>//gn # Count the number of occurences of a word in a file with
:vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!
<CTRL-x><CTRL-l> # offers line completion in insert mode.
"2p # Will put the second to last thing yanked
"3p # Will put the third to last, etc.
:ju(mps) : # list your movements {{help|jump-motions}}
In visual mode, use s" to surround the selected text with " using the surround plugin.
:%s//joe/igc # substitute your last search with joe.
You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
:set guifont=* # in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
:%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
== # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines.
2f/ would find the second occurrence of '/' in a line.
:lcd %:p:h # Will change to the directory of the current file.
In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
:w !sudo tee % # Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?)
<CTRL-o> : # trace your movements backwards in a file.
<CTRL-i> # trace your movements forwards in a file.
* # g* g# # each searches for the word under the cursor (forwards/backwards)
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line.
/begin\_.*end # Will search for begin AND end over multiple lines.
Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.)
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces)
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy)
/fred|joe/ # Will search for either fred OR joe.
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
Use "_dd to delete one line without overriding the buffer. "_ is black hole register. "When writing to this register, nothing happens."
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order.
:tab sball # Will re-tab all files in the buffers list.
$ command | vim - (via @dlibanori) # Edit a command output in Vim as a file
ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor.
:tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.
:%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'.
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'.
/fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between.
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character.
:r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).
:g/search_term/# display each line containing 'search_term' with line numbers.
ci " inside a " " # Will erase everything between "" and place you in insertion mode."
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).
:ju(mps) : # list your movements {{help|jump-motions}} \
:%s/\ r//g # to remove all those nasty ^M from a file, or
:%s/\ r$//g # for only at the end of a line.
< CTRL-x >< CTRL-l > offers line completion in insert mode.
/begin\_.*end # Will search for begin AND end over multiple lines.
< CTRL-n >< CTRL-p > offers word-completion while in insert mode.
Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.)
/\%>80v.\+ with search highlighting (:set hlsearch) # Will highlight any text after column 80.
To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
== # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines.
"+y to copy to the X11 (or Windows) clipboard. "+p to paste from it.
/.*fred&.*joe/ # Will search for fred AND joe, in any order.
:tab sball # Will re-tab all files in the buffers list.
:vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!
vim -c [command] # Will launch vim and run a : command at launch, e.g. "vim -c NERDTree."
ggVG= # Will auto-format the entire document
:Sex # Will open a file explorer in a split window. I bet you'll remember that one.
:%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
:scriptnames # Will list all plugins and _vimrcs loaded.
:vimgrep /stext/ **/*.txt | :copen # searches for stext recursively in *.txt files and show results in separate window
qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is.
Edit and encrypt a file: vim -x filename (via @dlibanori)
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor.
ysiw' # 'to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin
g; # Will cycle through your recent changes (or g, to go in reverse.
/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search.
:%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces)
%s/^ \ n/ / # to delete all empty lines (remove spaces from command!)
:history lists the history of your recent commands, sans duplicates.
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
"2p # Will put the second to last thing yanked, "3p will put the third to last, etc.
:r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).
:tabo # Will close all open tabs except the active one.
:set guifont=* # in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
Ctrl-c # to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
:%s/<word>//gn # Count the number of occurences of a word in a file with
< CTRL-o > : # trace your movements backwards in a file.
< CTRL-i > # trace your movements forwards in a file.
guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
:E to see a simple file explorer. (:Ex # Will too, if thats easier to remember.)
You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
:g/search_term/# display each line containing 'search_term' with line numbers.
git config --global core.editor "gvim --nofork" # to use gvim to edit your git messages set gits core editor as follows:
'0 opens the last modified file ('1 '2 '3 works too)
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces)
:tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.
:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more
ga # Will display the ASCII, hex, and octal value of the character under the cursor.
[I (that is bracket-open, capital-i) shows lines containing the word under the cursor
2f/ would find the second occurrence of '/' in a line.
:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one).
ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern.
In gvim, change the cursor depending on what mode you are in (normal, insert, etc):
; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next '
gq{movement} to wrap text, or just gq while in visual mode. gqap # Will format the current paragraph.
/joe/e # Will search for joe and place the cursor at the end of the match.
* # g* g# each searches for the word under the cursor (forwards/backwards)
:e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
:%s/~/sue/igc substitute your last replacement string with 'sue'.
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).
CTRL-w K # Will switch vertical split into horizontal
CTRL-w H # Will switch a horizontal into a vertical.
CTRL-w | and CTRL-W _ maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes em.
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.
In your ~/.vimrc, `set clipboard=unnamed`. Now all operations work with the OS clipboard. No need for "+, "*
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters.
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'.
zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':'
:%s//joe/igc substitute your last search with joe.
@: to repeat the last executed command.
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
/fred|joe/ # Will search for either fred OR joe.
:%s/~/sue/igc substitute your last replacement string with sue.
gf # Will open the file under the cursor. (Killer feature.)
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment).
Edit a command output in Vim as a file:
$ command | vim - (via @dlibanori)
CTRL-w s CTRL-w T # Will open current buffer in new tab
K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character.
:lcd %:p:h # Will change to the directory of the current file.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
:read [filename] # Will insert the contents of [filename] at the current cursor position
:wa # Will save all buffers.
:xa # Will save all buffers and exit Vim.
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line.
In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
noremap ' ` and noremap ` ' # to make marks easier to navigate. Now ` is easier to reach!
/joe/+3 # Will search for joe and place the cursor three lines below the match.
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
:%s/\\/\//g # Replaces all backslashes with forward slashes.
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order.
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy)
ci " inside a " " # "Will erase everything between "" and place you in insertion mode.
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces)
:g/_pattern_/s/^/#/g # Will comment out lines containing _pattern_ (if '#' is your comment character/sequence)
In visual mode, use s" to surround the selected text with " using the surround plugin.
:40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns.
/fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between.
:w !sudo tee % # Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?)
:%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'.
:ju(mps) : list your movements {{help|jump-motions}} \
ysiw' to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin
to use gvim to edit your git messages set gits core editor as follows:
git config --global core.editor "gvim --nofork"
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character.
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment).
vim -c [command] # Will launch vim and run a : command at launch, e.g. "vim -c NERDTree."
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'.
:set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
Edit and encrypt a file: vim -x filename (via @dlibanori)
2f/ would find the second occurrence of '/' in a line.
:lcd %:p:h # Will change to the directory of the current file.
Count the number of occurences of a word in a file with :%s/<word>//gn
g; # Will cycle through your recent changes (or g, to go in reverse.
/.*fred&.*joe/ # Will search for fred AND joe, in any order.
Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy)
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line.
@: to repeat the last executed command.
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
/fred|joe/ # Will search for either fred OR joe.
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters.
:e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
* # g* g# each searches for the word under the cursor (forwards/backwards)
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':'
In visual mode, use s" to surround the selected text with " using the surround plugin.
:tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.
/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search.
; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next '
:Sex # Will open a file explorer in a split window. I bet you'll remember that one.
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor.
:g/search_term/# display each line containing 'search_term' with line numbers.
"2p # Will put the second to last thing yanked,
"3p # Will put the third to last, etc.
:vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern.
:%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern.
:w !sudo tee % # Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?)
ci " inside a " " # Will" erase everything between "" and place you in insertion mode.
CTRL-w K # Will switch vertical split into horizontal
CTRL-w H # Will switch a horizontal into a vertical.
In gvim, change the cursor depending on what mode you are in (normal, insert, etc):
/fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between.
:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one).
[I (that is bracket-open, capital-i) shows lines containing the word under the cursor
:read [filename] # Will insert the contents of [filename] at the current cursor position
:%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces)
/\%>80v.\+ with search highlighting (:set hlsearch) # Will highlight any text after column 80.
zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
:40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
:%s//joe/igc substitute your last search with joe.
gq{movement} to wrap text, or just gq while in visual mode. gqap # Will format the current paragraph.
:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more
:%s/\\/\//g
Replaces all backslashes with forward slashes.
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order.
:%s/~/sue/igc substitute your last replacement string with 'sue'.
CTRL-w | and CTRL-W _ maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes em.
ga # Will display the ASCII, hex, and octal value of the character under the cursor.
:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns.
guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
'0 opens the last modified file ('1 '2 '3 works too)
/joe/e # Will search for joe and place the cursor at the end of the match.
:vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!
Edit a command output in Vim as a file:
$ command | vim - (via @dlibanori)
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces)
In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
:g/_pattern_/s/^/#/g # Will comment out lines containing _pattern_ (if '#' is your comment character/sequence)
:E to see a simple file explorer. (:Ex # Will too, if thats easier to remember.)
:r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).
== # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines.
%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.
"+y to copy to the X11 (or Windows) clipboard. "+p to paste from it.
:wa # Will save all buffers.
:xa # Will save all buffers and exit Vim.
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is.
To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
CTRL-w s CTRL-w T # Will open current buffer in new tab
:vimgrep /stext/ **/*.txt | :copen
searches for stext recursively in *.txt files and show results in separate window
K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
:tab sball # Will re-tab all files in the buffers list.
gf # Will open the file under the cursor. (Killer feature.)
You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
:%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'.
qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces)
< CTRL-n >< CTRL-p > offers word-completion while in insert mode.
:scriptnames # Will list all plugins and _vimrcs loaded.
In your ~/.vimrc, `set clipboard=unnamed`. Now all operations work with the OS clipboard. No need for "+, "*
/begin\_.*end # Will search for begin AND end over multiple lines.
Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.)
:history lists the history of your recent commands, sans duplicates.
:%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
< CTRL-o > : # trace your movements backwards in a file.
< CTRL-i > # trace your movements forwards in a file.
< CTRL-x >< CTRL-l > # offers line completion in insert mode.
ggVG= # Will auto-format the entire document
/joe/+3 # Will search for joe and place the cursor three lines below the match.
:%s/~/sue/igc substitute your last replacement string with sue.
Use "_dd to delete one line without overriding the buffer. "_ is black hole register. "When writing to this register, nothing happens."
%s/^ \ n/ / to delete all empty lines (remove spaces from command!)
Sorry, everyone, for the extended absence. I hope to return to tweeting on a regular schedule shortly. The site will be back, too.
:scriptnames # Will list all plugins and _vimrcs loaded.
noremap ' ` and noremap ` ' to make marks easier to navigate. Now ` is easier to reach!`
[I (that is bracket-open, capital-i) shows lines containing the word under the cursor
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces)
'0 opens the last modified file ('1 '2 '3 works too)
CTRL-w | and CTRL-W _ maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes em.
gf # Will open the file under the cursor. (Killer feature.)
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line.
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character.
vim -c [command] # Will launch vim and run a : command at launch, e.g. "vim -c NERDTree."
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.
:g/_pattern_/s/^/#/g # Will comment out lines containing _pattern_ (if '#' is your comment character/sequence)
CTRL-w K # Will switch vertical split into horizontal
CTRL-w H # Will switch a horizontal into a vertical.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
ci " inside a " " # "Will erase everything between "" and place you in insertion mode.
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern.
:lcd %:p:h # Will change to the directory of the current file.
:%s/\\/\//g
Replaces all backslashes with forward slashes.
:ju(mps) : list your movements {{help|jump-motions}} \
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy)
< CTRL-x >< CTRL-l > offers line completion in insert mode.
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters.
:vimgrep /stext/ **/*.txt | :copen
searches for stext recursively in *.txt files and show results in separate window
:g/search_term/# display each line containing 'search_term' with line numbers.
zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
:r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
/joe/e # Will search for joe and place the cursor at the end of the match.
/fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between.
CTRL-w s CTRL-w T # Will open current buffer in new tab
:read [filename] # Will insert the contents of [filename] at the current cursor position
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order.
In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
:ju(mps) : list your movements {{help|jump-motions}} \
%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.
:%s/~/sue/igc substitute your last replacement string with 'sue'.
ysiw' to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin
:wa # 'Will save all buffers.
:xa # Will save all buffers and exit Vim.
* # g* g# each searches for the word under the cursor (forwards/backwards)
:%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.)
:vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern.
:vimgrep /stext/ **/*.txt | :copen
searches for stext recursively in *.txt files and show results in separate window
zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance.
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy)
< CTRL-n >< CTRL-p > offers word-completion while in insert mode.
:%s//joe/igc substitute your last search with joe.
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces)
:set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
:tab sball # Will re-tab all files in the buffers list.
To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
:Sex # Will open a file explorer in a split window. I bet you'll remember that one.
/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search.
You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
:40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
After performing an undo, you can navigate through the changes using g- and g+. Also, try :undolist to list the changes.
:%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
/.*fred&.*joe/ # Will search for fred AND joe, in any order.
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
== # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines.
:%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces)
[I (that is bracket-open, capital-i) shows lines containing the word under the cursor
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
/joe/+3 # Will search for joe and place the cursor three lines below the match.
:%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'.
"+y # to copy to the X11 (or Windows) clipboard.
"+p # to paste from it. http://is.gd/9dkI
"2p # Will put the second to last thing yanked
"3p # Will put the third to last, etc. http://is.gd/do1Dt
/fred|joe/ # Will search for either fred OR joe.
/\%>80v.\+ with search highlighting (:set hlsearch) # Will highlight any text after column 80. http://is.gd/8ekT
g; # Will cycle through your recent changes (or g, to go in reverse.
In gvim, change the cursor depending on what mode you are in (normal, insert, etc): http://is.gd/9dq0
K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
vim -c [command] # Will launch vim and run a : command at launch, e.g. "vim -c NERDTree."
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':'
:history lists the history of your recent commands, sans duplicates.
gf # Will open the file under the cursor. (Killer feature.)
:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more http://is.gd/9clX
:lcd %:p:h # Will change to the directory of the current file.
g< CTRL-G > # to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
Edit and encrypt a file: vim -x filename (via @dlibanori)
to use gvim to edit your git messages set gits core editor as follows:
git config --global core.editor "gvim --nofork"
In visual mode, use s" to surround the selected text with " using the surround plugin. http://is.gd/fpwJQ
@: # to repeat the last executed command. http://is.gd/9cuP
/begin\_.*end # Will search for begin AND end over multiple lines.
%s/^ \ n/ / to delete all empty lines (remove spaces from command!)
Edit a command output in Vim as a file:
$ command | vim - (via @dlibanori)
; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next ' http://is.gd/qZIs
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment).
ga # Will display the ASCII, hex, and octal value of the character under the cursor.
:scriptnames # Will list all plugins and _vimrcs loaded.
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern. http://is.gd/8epA
:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns. http://is.gd/8ekT
:g/search_term/# display each line containing 'search_term' with line numbers.
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).
:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one).
CTRL-w K # Will switch vertical split into horizontal
CTRL-w H # Will switch a horizontal into a vertical.
:%s/~/sue/igc substitute your last replacement string with sue.
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces)
ggVG= # Will auto-format the entire document
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'.
gq{movement} to wrap text, or just gq while in visual mode. gqap # Will format the current paragraph.
ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor.
:tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.
:E to see a simple file explorer. (:Ex will too, if thats easier to remember.)
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters.
:w !sudo tee % # Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?)
< CTRL-x >< CTRL-l > offers line completion in insert mode.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. http://is.gd/9cuP
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character.
'0 opens the last modified file ('1 '2 '3 works too)
:g/_pattern_/s/^/#/g # Will comment out lines containing _pattern_ (if '#' is your comment character/sequence)
:vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!
:e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
2f/ would find the second occurrence of '/' in a line.
Count the number of occurences of a word in a file with :%s/<word>//gn
CTRL-w | and CTRL-W _ maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes em.
zz to center the cursor vertically on your screen. Useful when you 250Gzz, for instance. http://is.gd/XKGK1X
CTRL-w | and CTRL-W _ maximize your current split vertically and horizontally, respectively. CTRL-W = equalizes em.
/fred|joe/ # Will search for either fred OR joe.
CTRL-w K # Will switch vertical split into horizontal
CTRL-w H # Will switch a horizontal into a vertical.
/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search.
:g/_pattern_/s/^/#/g # Will comment out lines containing _pattern_ (if '#' is your comment character/sequence)
:E to see a simple file explorer. (:Ex will too, if thats easier to remember.)
To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
:w !sudo tee % # Will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?)
vim -c [command] # Will launch vim and run a : command at launch, e.g. "vim -c NERDTree."
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment).
%s/^ \ n/ / to delete all empty lines (remove spaces from command!)
Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
/joe/e # Will search for joe and place the cursor at the end of the match.
CTRL-w s CTRL-w T # Will open current buffer in new tab
:%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'.
2f/ would find the second occurrence of '/' in a line.
< CTRL-x >< CTRL-l > offers line completion in insert mode.
:set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
:vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).
:wa # Will save all buffers.
:xa # Will save all buffers and exit Vim. http://is.gd/do1qZ
In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
"2p # Will put the second to last thing yanked
"3p # Will put the third to last, etc. http://is.gd/do1Dt
Count the number of occurences of a word in a file with :%s/<word>//gn
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces)
If you have got a tip for vim users, please submit it at http://bit.ly/eQNaQ9 !
Edit a command output in Vim as a file:
$ command | vim - (via @dlibanori)
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy)
:vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern. http://is.gd/8epA
@mxey Patience is a virtue. You can see more at http://vimtweets.com. You can also suggest a tip.
You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character.
ggVG= # Will auto-format the entire document
Edit and encrypt a file: vim -x filename (via @dlibanori)
[I (thats bracket-open, capital-i) shows lines containing the word under the cursor
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
ga # Will display the ASCII, hex, and octal value of the character under the cursor.
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern. http://is.gd/8epA
< CTRL-o > : trace your movements backwards in a file. < CTRL-i > trace your movements forwards in a file.
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters.
:vimgrep /stext/ **/*.txt | :copen
searches for stext recursively in *.txt files and show results in separate window
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces)
:40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
K runs a prgrm to lookup the keyword under the cursor. If writing C, it runs man. In Ruby, it (should) run ri, Python (perhaps) pydoc.
:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more http://is.gd/9clX
'0 opens the last modified file ('1 '2 '3 works too)
:Sex # Will open a file explorer in a split window. I bet you'll remember that one.
After performing an undo, you can navigate through the changes using g- and g+. Also, try :undolist to list the changes.
ysiw' to surround current word with ', cs'{ changes 'word' to { word } using the surround plugin' http://is.gd/fpwJQ
< CTRL-n >< CTRL-p > # offers word-completion while in insert mode.
ci " inside a " " # "Will erase everything between "" and place you in insertion mode.
* # g* g# each searches for the word under the cursor (forwards/backwards)
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one).
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces)
:ju(mps) : list your movements {{help|jump-motions}} \
/.*fred&.*joe/ # Will search for fred AND joe, in any order.
:%s/~/sue/igc substitute your last replacement string with sue.
:%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces)
:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns. http://is.gd/8ekT
In gvim, change the cursor depending on what mode you are in (normal, insert, etc): http://is.gd/9dq0
@jon2512chua period repeats the last action, @: repeats the last command-line command. :h @: for more info!
@: to repeat the last executed command. http://is.gd/9cuP
:tab sball # Will re-tab all files in the buffers list.
In visual mode, use s" to surround the selected text with " using the surround plugin. http://is.gd/fpwJQ
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
/\%>80v.\+ with search highlighting (:set hlsearch) will highlight any text after column 80. http://is.gd/8ekT
g; # Will cycle through your recent changes (or g, to go in reverse.
:%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
:history lists the history of your recent commands, sans duplicates.
:read [filename] # Will insert the contents of [filename] at the current cursor position
@vimtips or just set $VISUAL in your shell.
to use gvim to edit your git messages set gits core editor as follows:
git config --global core.editor "gvim --nofork"
:tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.
/fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between.
== # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines.
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order.
%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.
; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next ' http://is.gd/qZIs
:lcd %:p:h # Will change to the directory of the current file.
:g/search_term/# display each line containing 'search_term' with line numbers.
:scriptnames # Will list all plugins and _vimrcs loaded.
:%s//joe/igc substitute your last search with joe.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
gq{movement} to wrap text, or just gq while in visual mode. gqap # Will format the current paragraph.
:%s/~/sue/igc substitute your last replacement string with 'sue'.
/joe/+3 # Will search for joe and place the cursor three lines below the match.
:e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
/begin\_.*end # Will search for begin AND end over multiple lines.
gf # Will open the file under the cursor. (Killer feature.)
"+y to copy to the X11 (or Windows) clipboard. "+p to paste from it. http://is.gd/9dkI
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor.
:%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
:r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':'
guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.) http://is.gd/tj4y
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'.
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. http://is.gd/9cuP
ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
:%s/~/sue/igc substitute your last replacement string with 'sue'.
ysiw' to surround current word with ', cs'{ changes 'word' to { word } using' the surround plugin http://is.gd/fpwJQ
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters.
< CTRL-x >< CTRL-l > offers line completion in insert mode.
:ju(mps) : list your movements {{help|jump-motions}} \
Many mentioned :Sex opens a file explorer also -- in a split window. Its a different tip! http://is.gd/hInzT Plus, :E is 2 fewer chars
Wow, figured out that d% in #vim # Will delete to the matching brace. Makes sense, but never used it before. /cc @vimtips
@: to repeat the last executed command. http://is.gd/9cuP
:E to see a simple file explorer. (:Ex # Will too, if thats easier to remember.)
< CTRL-o > : trace your movements backwards in a file. < CTRL-i > trace your movements forwards in a file.
/fred|joe/ # Will search for either fred OR joe.
:%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces)
/joe/e # Will search for joe and place the cursor at the end of the match.
gq{movement} to wrap text, or just gq while in visual mode. gqap will format the current paragraph.
:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns. http://is.gd/8ekT
:scriptnames # Will list all plugins and _vimrcs loaded.
to use gvim to edit your git messages set gits core editor as follows:
git config --global core.editor "gvim --nofork"
In visual mode, use s" to surround the selected text with " using the surround plugin. http://is.gd/fpwJQ
/.*fred&.*joe/ # Will search for fred AND joe, in any order.
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment).
* # g* g# each searches for the word under the cursor (forwards/backwards)
:vimgrep /stext/ **/*.txt | :copen
searches for stext recursively in *.txt files and show results in separate window
:%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
Count the number of occurences of a word in a file with :%s/<word>//gn
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one).
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces)
:set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces)
:%s//joe/igc substitute your last search with joe.
:%s/~/sue/igc substitute your last replacement string with sue.
"2p # Will put the second to last thing yanked,
"3p # Will put the third to last, etc. http://is.gd/do1Dt
:wa will save all buffers.
:xa # Will save all buffers and exit Vim. http://is.gd/do1qZ
:tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.
:tab sball # Will re-tab all files in the buffers list.
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor.
== # Will auto-indent the current line. Select text in visual mode, then = to auto-indent the selected lines.
:vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!
%s/<C-R>a/bar/g # Will place the contents of register 'a' in the search, and replace it with 'bar'.
After performing an undo, you can navigate through the changes using g- and g+. Also, try :undolist to list the changes.
'0 opens the last modified file ('1 '2 '3 works too)
guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more http://is.gd/9clX
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
Edit a command output in Vim as a file:
$ command | vim - (via @dlibanori)
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).
; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next ' http://is.gd/qZIs
:%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
:vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern. http://is.gd/8epA
:read [filename] # Will insert the contents of [filename] at the current cursor position
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
[I (thats bracket-open, capital-i) shows lines containing the word under the cursor
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order.
:e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy)
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern. http://is.gd/8epA
ggVG= # Will auto-format the entire document
/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search.
2f/ would find the second occurrence of '/' in a line.
Anyone interested in a #VIM skin (like http://bit.ly/aYvhSx) for #apple keyboards (w/ or w/o numpad)? Need at least 50 orders! Pls RT and DM
:g/search_term/# display each line containing 'search_term' with line numbers.
/fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between.
ga # Will display the ASCII, hex, and octal value of the character under the cursor.
In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.) http://is.gd/tj4y
/joe/+3 # Will search for joe and place the cursor three lines below the match.
:%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'.
:r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. http://is.gd/9cuP
gf # Will open the file under the cursor. (Killer feature.)
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
g; # Will cycle through your recent changes (or g, to go in reverse.
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character.
In gvim, change the cursor depending on what mode you are in (normal, insert, etc): http://is.gd/9dq0
< CTRL-n >< CTRL-p > offers word-completion while in insert mode.
Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'.
Gah! Sorry everyone. Those were meant for my personal account, of course.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
/\%>80v.\+ with search highlighting (:set hlsearch) # Will highlight any text after column 80. http://is.gd/8ekT
:lcd %:p:h # Will change to the directory of the current file.
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':'
"+y to copy to the X11 (or Windows) clipboard. "+p to paste from it. http://is.gd/9dkI
/begin\_.*end # Will search for begin AND end over multiple lines.
:40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
:history lists the history of your recent commands, sans duplicates.
ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
[I (thats bracket-open, capital-i) shows lines containing the word under the cursor
In insert mode do Ctrl+r=53+17<Enter>. This way you can do some calcs with vim.
Actually used C-a and C-x to increment and decrement numbers in some test data. Never thought I had use it!
:wa # Will save all buffers.
:xa # Will save all buffers and exit Vim. http://is.gd/do1qZ
"2p # Will put the second to last thing yanked,
"3p # Will put the third to last, etc. http://is.gd/do1Dt
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
g; # Will cycle through your recent changes (or g, to go in reverse.
You probably know that 'u' is undo. Do you know that Ctrl-R is redo?
/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search.
:g/search_term/# display each line containing 'search_term' with line numbers.
:set foldmethod=syntax to make editing long files of code much easier. zo to open a fold. zc to close it. See more http://is.gd/9clX
:%s/< ! - -\_.\{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
Use '\v' in your regex to set the mode to 'very magic', and avoid confusion. (:h \v for more info.) http://is.gd/tj4y
:tabdo [some command] # Will execute the command in all tabs. Also see windo, bufdo, argdo.
:%s/[.!?]\_s\+\a/\U&\E/g # Will uppercase the first letter of each sentence (except the very first one).
ci{ â change text inside {} block. Also see di{, yi{, ci( etc.
qa starts a recording in register 'a'. q stops it. @a repeats the recording. 5@a repeats it 5 times.
:vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern. http://is.gd/8epA
After performing an undo, you can navigate through the changes using g- and g+. Also, try :undolist to list the changes.
:s/\(.*\):\(.*\)/\2 : \1/ # Will reverse fields separated by ':'
:read [filename] # Will insert the contents of [filename] at the current cursor position
To search for a URL without backslashing, search backwards! Example: ?http://somestuff.com
:%s/\ v(.*\ n){5}/&\ r # Will insert a blank line every 5 lines (remove spaces)
:e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
:%s//joe/igc substitute your last search with joe.
:set autochdir instead of :lcd %:p:h in your vimrc to change directories upon opening a file.
:%s/~/sue/igc substitute your last replacement string with 'sue'.
:%s/joe|fred/jerks/g # Will replace both 'fred' and 'joe' with 'jerks'.
:%s/^ \ n \{3}// # Will delete a block of 3 empty lines. (remove the spaces)
< CTRL-o > : trace your movements backwards in a file. < CTRL-i > trace your movements forwards in a file.
/joe/e # Will search for joe and place the cursor at the end of the match.
Technical difficulties with my auto-tweeting. It'll return soon. It may or may not be BP's fault.
Check out these Vim tips from the Thoughtbot crew: http://robots.thoughtbot.com/post/619330025/viiiiiiiiiiiiiiiiiim
You can now search tips at http://vimtweets.com. Check it out, and tell me what you think!
:%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
:Sex # Will open a file explorer in a split window. I bet you'll remember that one.
:E to see a simple file explorer. (:Ex # Will too, if thats easier to remember.)
Smash Into Vim! It is the new screencast from PeepCode: http://peepcode.com/products/smash-into-vim-i
guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. http://is.gd/9cuP
to use gvim to edit your git messages set gits core editor as follows:
git config --global core.editor "gvim --nofork"
@panozzaj It should be a command. Sorry. I have updated the tip to read :40,50m30
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment).
:y<line-number> # Will yank the passed in ln, :y<ln1, ln2> will yank the range.
eg. :y41 or :y45,50
#vim
/begin\_.*end # Will search for begin AND end over multiple lines.
:tab sball # Will re-tab all files in the buffers list.
:set guifont=* in gvim or MacVim to get a font selection dialog. Useful while giving presentations.
40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
:lcd %:p:h # Will change to the directory of the current file.
gf # Will open the file under the cursor. (Killer feature.)
2f/ would find the second occurrence of '/' in a line.
:vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!
:%s/^\ n\ +/\ r/ # Will compress multiple empty lines into one. (remove spaces)
:r !date # Will insert the current date/time stamp (from the 'date' command -- a bit OS-specific).
/.*fred&.*joe/ # Will search for fred AND joe, in any order.
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
ga # Will display the ASCII, hex, and octal value of the character under the cursor.
:match ErrorMsg '\%>80v.\+' uses matching to highlight lines longer than 80 columns. http://is.gd/8ekT
wrote my first vim plugin! vimsizer, inspired by the great Firesizer for Firefox. http://bit.ly/9eKuOc
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'.
Bonus tweet for (USA) tax day! Please suggest tweets at vimtweets.com.
/\%>80v.\+ with search highlighting (:set hlsearch) # Will highlight any text after column 80. http://is.gd/8ekT
Ctrl-c to quickly get out of command-line mode. (Faster than hitting ESC a couple times.)
10 Vim Tutorials to Jumpstart Your Editor Skills: http://bit.ly/axRdZY
"+y to copy to the X11 (or Windows) clipboard. "+p to paste from it. http://is.gd/9dkI
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy)
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor.
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
Announcement: Do you have a vim tip you had like to share? Do you want to browse all vimtips? Check out http://vimtweets.com!
* # g* g# each searches for the word under the cursor (forwards/backwards)
@: to repeat the last executed command. http://is.gd/9cuP
< CTRL-x >< CTRL-l > offers line completion in insert mode.
gq{movement} to wrap text, or just gq while in visual mode. gqap # Will format the current paragraph.
g< CTRL-G > to see technical information about the file, such as how many words are in it, or how many bytes it is. http://is.gd/9cYj
:scriptnames # Will list all plugins and _vimrcs loaded.
And, of course, follow @vimcasts.
While you are waiting for me to begin steady tweeting again, you should check out http://vimcasts.org!
In case you were worried: tips # Will return soon. I promise.
"+y to copy to the X11 (or Windows) clipboard. "+p to paste from it. http://is.gd/9dkI
:vimgrep pattern **/*.txt # Will search all *.txt files in the current directory and its subdirectories for the pattern. http://is.gd/8epA
@kevinwatters I don't disagree! It's mostly just cute. "hey look what I can do!"
:%s/< !--\_.{-}-- >// # Will delete HTML comments, potentially spanning multiple lines. (remove the spaces)
:h slash< CTRL-d > to get a list of all help topics containing the word 'slash'.
Ctrl-a, Ctrl-x # Will increment and decrement, respectively, the number under the cursor.
guu converts entire line to lowercase. gUU converts entire line to uppercase. ~ inverts case of current character.
ga # Will display the ASCII, hex, and octal value of the character under the cursor.
ggguG # Will lower case the entire file (also known as the Jerry Yang treatment).
:%s/~/sue/igc substitute your last replacement string with 'sue'.
:g/search_term/# display each line containing 'search_term' with line numbers.
:E to see a simple file explorer. (:Ex # Will too, if thats easier to remember.)
Basic commands 'f' and 't' (like first and til) are very powerful. See :help t or :help f.
< CTRL-x >< CTRL-l > offers line completion in insert mode.
gf # Will open the file under the cursor. (Killer feature.)
@godfoca . Repeats the last edit. @: repeats the last command-line command. So, :w then @: would write twice. Make sense?
@: to repeat the last executed command. http://is.gd/9cuP
From a command-line, vim scp://username@host//path/to/file to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
:tab sball # Will re-tab all files in the buffers list.
Need to edit and run a previous command? q: then find the command, edit it, and Enter to execute the line. http://is.gd/9cuP
@pykler ha! Right, thats what I meant. ;-). Replace def with hours. Sorry.
/< fred >/ # Will search for fred, but not alfred or frederick. (spaces inserted to avoid HTML filtering).
:%s/\v(.*\n){5}/&\r # Will insert a blank line every 5 lines
:%s/\ r//g to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
:%s#<[^>]\+>##g # Will remove HTML tags, leaving the text. (non-greedy)
Tip from 2 days ago should have been %s#.*\ (def\ ).*#\ 1# # Will delete everything on all lines except for the string 'hours'. (no spaces)
:lcd %:p:h # Will change to the directory of the current file.
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'.
:e $MYVIMRC to directly edit your vimrc. :source $MYVIMRC to reload. Mappings may make it even easier.
/< CTRL-r >< CTRL-w > # Will pull the word under the cursor into search.
:vsplit filename # Will split the window vertically and open the file in the left-hand pane. Great when writing unit tests!
/.*fred&.*joe/ # Will search for fred AND joe, in any order.
; is a motion to repeat last find with f. f' would find next quote. c; would change up to the next ' http://is.gd/qZIs
/joe.*fred.*bill/ # Will search for joe AND fred AND bill, in that order.
/fred|joe/ # Will search for either fred OR joe.
Count the number of occurences of a word in a file with :%s/<word>//gn
:history lists the history of your recent commands, sans duplicates.
Added 5 new tips to the db. A sensible way for you to suggest tips is also in the works.
== # Will auto-indent the current line. Select text in visual mode, then == to auto-indent the selected lines.
:ju(mps) : list your movements {{help|jump-motions}}
Looking for tips to move text around in vim? http://smartic.us/2010/01/20/moving-text-around-in-vim/
:vmap // y/< C-R >"< CR > # "Will make searching for highlighted text (i.e. in visual mode) require only a highlight and //
% matches brackets {} [] (), and with matchit.vim, also matches def/end, < ?php/?>, < p>/< /p>, etc.
/joe/+3 # Will search for joe and place the cursor three lines below the match.
/fred\_s*joe/ # Will search for fred AND joe with whitespace (including newline) in between.
If you're a Ruby developer, check out @ReinH's rubyredgreen plugin for tests from Vim. http://is.gd/6jAut http://screenr.com/gK1
/joe/e+1 # Will search for joe and place the cursor at the end of the match, plus on character.
< CTRL-n >< CTRL-p > offers word-completion while in insert mode.
:vimgrep pattern *.txt # Will search all .txt files in the current directory for the pattern. http://is.gd/8epA
/joe/s-2 # Will search for joe and place the cursor at the start of the match, minus two characters.
I've built up ~70 tips in my db. You'll see tips you've seen previously, if you've been following a while. I know I should add more. :-)
In gvim, change the cursor depending on what mode you are in (normal, insert, etc): http://is.gd/9dq0
We're back, thanks to a reminder from HN! Tips will be tweeted daily, again. Perhaps I'll rewrite the tip-tweeting app this weekend....
% matches opening and closing chars (){}[], and with matchit.vim, def/end, HTML tags, etc. as well!
40,50m30 # Will move lines 40 through 50 to line 30. Most visual mode commands can be used w/ line numbers.
:%s#.*(hours).*#1# # Will delete everything on a line except for the string 'hours'.
* # g* g# each searches for the word under the cursor (forwards/backwards)
[Ctrl-d]
# When programming in #vim, you can use Ctrl-d to "De-tab" (Mnemonic) a line and move the cursor back one tab width. #python
vim -n rather-large-file
# If you need to edit a rather large file. vim swap files can eat up space and be slow. -n will turn them off.
:s/-/\n/gc
# Suchen und ersetzen durch Zeilenumbrüche:
# Vimrc Tips Add to your Vim configuration:
" :w!!
" write the file when you accidentally opened it without the right (root) privileges
cmap w!! w !sudo tee % > /dev/null
:set background=dark
# In vim, depending on whether your terminal background is dark or light, setting this will help with color syntax.
# Vim fu
# Filetype specific options e.g. no line numbers for markdown
au FileType markdown set nonumber
# Copy all
:%y+
# Yank all text - Spellcheck
:set spell spelllang=en_gb
]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
Visual block mode to add to start or append to end of lines
# Append to the end of all lines
vip<C-V>$A,<Esc>
# Explanation: In normal mode, Visual select a paragraph vip, switch to Visual block mode Ctrl-V, append to all lines $A a comma ,.
Using I inserts at the start of the line.
# Search and replace globally
:%s/x/y/g
# Replaces x with y
# Tabs and open files
:tabedit {file}
:tabclose
:tabonly
gt switch to next tab
gT switch to previous tab
# Move between open files with
:prev
:next
# Changing colour scheme
:colorscheme elflord
# changes the colourscheme to elflord
Search
/ is search forward
? is search back
n is find next in the same direction
N is find next in the opposite direction
* find next instance of word under cursor
# find previous instance of word under cursor
Ctrl-o takes you back
Apend etc
ea is append end of word
ciw change inner word # (i.e. delete word and go into insert mode)
Paste into a new line
# Put
:nmap <leader>p o<ESC>p
# into your vimrc and use that
Underling headings in markdown
yypVr-
# From http://vim.wikia.com/wiki/Underline_using_dashes_automatically
Typewritter scroll mode
# See https://randomdeterminism.wordpress.com/2011/08/15/typewriter-scroll-mode-in-vim/
# Unite plugin
# http://bling.github.io/blog/2013/06/02/unite-dot-vim-the-plugin-you-didnt-know-you-need/
# Removing ^M in text files
# http://its.ucsc.edu/unix-timeshare/tutorials/clean-ctrl-m.html
# Add in further line-breaks to those that already exist in markdown
:%s/ \n/\0 \r/g
# Swap two characters
xp
# Turn off highlighting after search
:noh
# Interactively replace
:%s/old/new/gc
# Removing Ctrl-M
# There are quite a few ways of doing this, but a quick way to remove ^M scattered around your file is as follows:
:%s/C-vC-m//g
# Where C-v is Ctrl-v and C-m is Ctrl-m.
# From http://dailyvim.blogspot.co.uk/2009/01/removing-ctrl-m.html
:w !sudo tee %
# Ever edit a file as a normal user that is owned by root. This vim command will allow you to overwrite it with root perms.
# Sort and remove duplicate lines in a file in one step without intermediary files
vi +'%!sort | uniq' +wq file.txt
# Explanation: We open a file with vi and run two vi commands (specified with +):
# %!sort | uniq
# % = range definition, it means all the lines in the current buffer.
# ! = run filter for the range specified. Filter is an external program, in this example sort | uniq
# wq = write buffer contents to file and exit.
# Remove offending key from known_hosts file with one swift move
vi +18d +wq ~/.ssh/known_hosts
# Explanation: When you try to ssh to a server where the host key has changed then you probably get an error message like this: Offending key in /home/jack/.ssh/known_hosts:18
# If you know for sure that it was the server his admins who changed the host key, then your next move is to remove line 18 from the file so that ssh lets you connect after accepting the new key.
# The one-liner does this in one swift move by passing simple commands to vi:
# +18d -- delete line 18
# +wq -- save the file and exit
# Sets relative line numbers so that you can easily see how many lines away a line is from the current line.
vim tip: set relativenumber
# vim trick: Open a some-file.txt in vim, highlight searchword and jump to first occurrence.
vim +/searchword some-file.txt
# Unfortunately the redirection will use UNIX style line endings. If the original files have DOS style line endings, add this command in the subshell:
vim +'set ff=dos' +wq converted
vim $( xsel -b | tr "A-Z\ " "a-z_" ).txt
# Open in vim a file name based on your X paste buffer, but lowercase and underscore spaces.
vim scp://user@server1//etc/httpd/httpd.conf
# Edit a file on a remote server using vim from your local *nix desktop
# Use vim to pretty-print code with syntax highlighting
vim +'hardcopy > output.ps' +q style.css
# Explanation: If you have syntax highlighting properly setup in vim, this command will pretty-print the specified file with syntax highlighting to output.ps. If you prefer PDF, you can convert using ps2pdf output.ps.
# vim tip:
# Use the % key while cursor over an opening/closing { ( [ or /* to jump to the matching closer or vice versa.
display -size 300x300 xc:'#D288AC'
# Display a square of the hex value color D288AC. Vim integration: http://bit.ly/1ev2WdI
# Replace a regexp pattern in many files at once
vi +'bufdo %s/pattern/replacement/g | update' +q $(grep -rl pattern /path/to/dir)
# Explanation:
# The inner grep will search recursively in specified directory and print the filenames that contain the pattern.
# All files will be opened in vi, one buffer per file.
# The arguments starting with + will be executed as vi commands:
# bufdo %s/pattern/replacement/g | update = perform the pattern substitution in all files and save the changes
# q = exit vi
# Limitations: The :bufdo command might not be there in old versions of vim.
# Remove carriage return '\r' character in many files, without looping and intermediary files
vi +'bufdo set ff=unix' +'bufdo %s/^M$//' +q file1 file2 file3
# Explanation: The arguments starting with + are commands in vi that will be executed
# set ff=unix is a shortcut for set fileformat=unix and means to use "unix" file format, i.e. without the carriage return \r character.
# %s/^M$// is a pattern substitution for all lines in the entire buffer, the pattern is "carriage return at end of the line", where ^M is not two literal characters but actually one, to enter it on the command line press Ctrl followed by Enter/Return
# bufdo means to run command in all buffers (each file is opened in a separate buffer)
# it vi
# Note: the set ff=unix is necessary, otherwise the pattern substitution will not do anything if all the lines end with \r = the file is in dos format, because in that case the line ending character will not be considered as part of the line.
# Note: if a shell-script has "accidentally" some carriage returns in it, then when you try to execute you may get an error: bad interpreter: No such file or directory. This one-liner fixes that problem. If you know that all the lines in the file have the carriage return, and there is only one file to fix, then a simplified version of the one-liner is enough:
vi +'set ff=unix' +wq file1
## Alternative one-liners:
# Remove carriage return '\r' character in many files, without looping and intermediary files
# Explanation: The recode utility installed on many systems converts between character sets. This command is shorthand for recode IBM-PC..latin1 file1 file2 file3 which converts the given files from CRLF to LF line endings.
recode pc..l1 file1 file2 file3
# Remove carriage return '\r' character in many files, without looping and intermediary files
vi +'bufdo set ff=unix' +'bufdo %s/^M$//' +q file1 file2 file3
# Explanation: The arguments starting with + are commands in vi that will be executed
# set ff=unix is a shortcut for set fileformat=unix and means to use "unix" file format, i.e. without the carriage return \r character.
# %s/^M$// is a pattern substitution for all lines in the entire buffer, the pattern is "carriage return at end of the line", where ^M is not two literal characters but actually one, to enter it on the command line press Ctrl followed by Enter/Return
# bufdo means to run command in all buffers (each file is opened in a separate buffer)
# q is to quit vi
# Note: the set ff=unix is necessary, otherwise the pattern substitution will not do anything if all the lines end with \r = the file is in dos format, because in that case the line ending character will not be considered as part of the line.
# Note: if a shell-script has "accidentally" some carriage returns in it, then when you try to execute you may get an error: bad interpreter: No such file or directory. This one-liner fixes that problem. If you know that all the lines in the file have the carriage return, and there is only one file to fix, then a simplified version of the one-liner is enough:
vi +'set ff=unix' +wq file1
:%s/[.!?]\_s\+\a/\U&\E/g
#will uppercase the first letter of each sentence (except the very first one). http://is.gd/4xZW
:g/_pattern_/s/^/#/g
# will comment out lines containing _pattern_ (if '#' is your comment character/sequence)
:vimgrep /stext/ **/*.txt | :copen
# searches for stext recursively in *.txt files and show results in separate window
%s/^ \ n/ /
#to delete all empty lines (remove spaces from command!
ggVG=
#will auto-format the entire document
/\%>80v.\+
#with search highlighting (:set hlsearch) will highlight any text after column 80.
/< CTRL-r >< CTRL-w >
#will pull the word under the cursor into search.
:s/\(.*\):\(.*\)/\2 : \1/
#will reverse fields separated by ':' http://is.gd/4xZW
/.*fred&.*joe/
#will search for fred AND joe, in any order. http://is.gd/4xZW
:e $MYVIMRC
#to directly edit your vimrc.
:source $MYVIMRC
#to reload. Mappings may make it even easier.
:%s/^ \ n \{3}//
#will delete a block of 3 empty lines. (remove the spaces) http://is.gd/4xZW
:%s/\\/\//g
#Replaces all backslashes with forward slashes.
:%s/\ r//g
#to remove all those nasty ^M from a file, or :%s/\ r$//g for only at the end of a line.
ggguG
#will lower case the entire file (also known as the Jerry Yang treatment). http://is.gd/4xZW
guu
#converts entire line to lowercase.
gUU
#converts entire line to uppercase. ~ inverts case of current character.
vim scp://username@host//path/to/file
#to edit a remote file locally. (See http://is.gd/9dwq for dependencies.)
:%s/\ v(.*\ n){5}/&\ r
# will insert a blank line every 5 lines (remove spaces) http://is.gd/6PB6n
:scriptnames
#will list all plugins and _vimrcs loaded. http://is.gd/6PB6n
:%s/<word>//gn
#Count the number of occurences of a word in a file with
:%s/< ! - -\_.\{-}-- >//
# will delete HTML comments, potentially spanning multiple lines. (remove the spaces) http://is.gd/4xZW
%s#<[^>]\+>##g
#will remove HTML tags, leaving the text. (non-greedy) http://is.gd/4xZW
:%s//joe/igc
#substitute your last search with joe. http://is.gd/4xZW
:w !sudo tee %
#will use sudo to write the open file (have you ever forgotten to `sudo vim /path/to/file`?)
:%s/^\ n\ +/\ r/
#will compress multiple empty lines into one. (remove spaces) http://is.gd/4xZW
:%s/joe|fred/jerks/g
#will replace both 'fred' and 'joe' with 'jerks'. http://is.gd/4xZW
:%s#.*(hours).*#1#
#will delete everything on a line except for the string 'hours'. http://is.gd/4xZW
:%s/\ v(.*\ n){5}/&\ r
#will insert a blank line every 5 lines (remove spaces) http://is.gd/6PB6n
:%s/[.!?]\_s\+\a/\U&\E/g
#will uppercase the first letter of each sentence (except the very first one). http://is.gd/4xZW
:s/\(.*\):\(.*\)/\2 : \1/
#will reverse fields separated by ':' http://is.gd/4xZW
# Neat @climagic trick: Open a some-file.txt in vim, highlight searchword and jump to first occurrence.
vim +/searchword some-file.txt
# Sets relative line numbers so that you can easily see how many lines away a line is from the current line.
vim tip: set relativenumber
# Do you have modelines turned on in vim? Check with
:verbose set modeline?
# Bulk rename with Vim
ls | sed 's/^/\"/g;s/$/\"/g' | vim -
:%s/./mv -i & &/g
# Inside the quotes in the second arg
vi"
:s/\%V /_/g
#" When done - If no slashes at the end of the file name
ggVG
:s/\"\ \"/\/\"\ \"/g
ggVG
:s/\"$/\/\"/g
# Save and quit
:w mvs
sh ./mvs
# Inspired by http://vim.wikia.com/wiki/Bulk_rename_files_with_Vim
# How can I add a string to the end of each line in Vim?
:%s/$/\*/g
# Repace line begining with the string ssh
%s/^/ssh /gc
# VI/VIM Anonymize email address in log file - The number 5 means to replace the leading and trailing 5 characters of an "@" in a log file with XXXX@XXXXX.
%s/.\{5\}@.\{5\}/XXXXX@XXXXXX/g
# wiederholt letzte kommando - wichtig
. in vim wiederholt letzte command
# Nummern am Rand Setzen
:set relativenumber
:set norelativenumber
# Suche vim
/ und ? for search
#==============================##==============================#
# CMD VIM #
#==============================##==============================#
Cheatsheets are an excellent complement to other information sources like Linux man-pages, Linux help, or How-To’s and tutorials, as they provide compact and easily accessible information. While man-pages and detailed tutorials often contain comprehensive explanations and extensive guides, cheatsheets summarize the most important options forthe command vim in a clear format. This allows users to quickly access the needed information for vim without having to sift through lengthy texts. Especially in stressful situations or for recurring tasks, cheatsheets for vim are a valuable resource to work efficiently and purposefully.
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
█║▌│║█║▌★ KALI ★ PARROT ★ DEBIAN 🔴 PENTESTING ★ HACKING ★ █║▌│║█║▌
██╗ ██╗ ██████╗ ██████╗ ██╗ ██╗███████╗██████╗
████████╗██╔══██╗██╔═══██╗╚██╗██╔╝██╔════╝██╔══██╗
╚██╔═██╔╝██║ ██║██║ ██║ ╚███╔╝ █████╗ ██║ ██║
████████╗██║ ██║██║ ██║ ██╔██╗ ██╔══╝ ██║ ██║
╚██╔═██╔╝██████╔╝╚██████╔╝██╔╝ ██╗███████╗██████╔╝
╚═╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═╝╚══════╝╚═════╝
█║▌│║█║▌ WITH COMMANDLINE-KUNGFU POWER █║▌│║█║▌
░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.