Stack OverflowWhat are your favorite Vim tricks?
[+284] [141] Joe Van Dyk
[2008-09-18 18:06:17]
[ vim ]

Post your favorite Vim [1] tricks (or plug-ins or scripts). One trick per answer.

Try to come up with something other than the basics, btw. :D

(1) Logically equivalent questions to:… - Kent Fredric
(5) Every time I come back to read the answers I learn something! - Luc M
(13) Not constructive? Really? - ergosys
(4) I just found the answer here for "what can you do if you forget to use sudo with vim?". Constructive enough SO question for me. - RyanBrady
(3) I'd thought this was exactly the right sort of question for a SE/SO community wiki… - me_and
[+370] [2008-09-18 20:23:29] Lee

In my ~/.vimrc:

cmap w!! %!sudo tee > /dev/null %

Will allow you to use :w!! to write to a file using sudo if you forgot to sudo vim file (it will prompt for sudo password when writing)

Alternative that allows you to skip reloading the file:

cmap w!! w !sudo dd of=%

(3) You, Sir, are my hero! - Joachim Sauer
(1) much better than !w /tmp/whatever, and then remembering to sudo cp it... +1! - Mikeage
Inspired. Elegant. - Peter Rowell
I'm in love with this and will use this within the week =) - chauncey
(1) Why not just ":w !sudo tee %"? - hhh
(8) It doesn't work very cleanly - prompts to reload file and then loses where it was, at least for me. - Artem Russakovskii
Using gvim, I get the response sudo: sorry you must have a tty to run sudo. - Scottie T
Scottie: Use gksudo or another graphical equivalent in that case. - Roger Pate
Could someone explain how this works in detail? - Doppelganger
(2) Nevermind my question, if someone is interested just look here:… - Doppelganger
Shouldn't you use /usr/bin/tee? - pydave
(1) You shouldn't use sudo vim. Better define EDITOR as vim (export EDITOR=vim in your .bashrc) and run sudoedit. - Gerardo Marset
(3) Here's an improved version of that:… - blueyed
blueyed, I tried your version and managed to trash my /etc/hosts with it. Better not to use this, guys. - loevborg
[+170] [2008-11-13 23:49:40] too much php

Using the built-in regions to change text quickly:

ci"    -> Cut everything inside "" string and start insert mode
da[    -> Delete the [] region around your cursor
vi'    -> Visual select everything inside '' string
ya(    -> Yank all text from ( to )

The command and type of region can all be used interchangeably and don't require .vimrc editing. See :help text-objects.

Awesome, thanks. - Liran Orevi
(8) didn't know about the 'a' and 'i' motions. Very useful. - deft_code
(1) I can't believe I've been through over a decade of vim'ming without knowing a/i. Nice tip! - Nik Reiman
Oh my god, amazing! This is going to change my life. - msutherl
These are called text objects by the way. And there's a few more than the number you specified. - ldog
[+102] [2008-09-19 00:24:50] Aristotle Pagaltzis [ACCEPTED]

Delete the HTML tag the cursor is currently inside of – the whole tag, regardless of just where the cursor is.


Change the content of a doublequote-delimited string.

Etc etc, along the same lines. See :help text-objects [1].


(2) That is a most excellent tip. - dowski
(6) In addition to <> and "", this also works with [], {}, and (). - Robert Gowland
(3) It's really cool. How to remember this : a = all i = inner try these ones : a[ i[ a< i< a{ i{ - Vdt
If you combine this with visual mode, you can quickly replace the contents of one block with another: yi{ to copy the text from one block, move the to target block, and vi{p to overwrite it. - naught101
[+86] [2008-10-22 14:00:22] Mapad

Shortcuts to quit the Insert mode:

Ctrl+C                        Leave insert mode (faster than Esc)

Ctrl+O                        Leave insert mode just for the duration of one command

Ctrl+O Shift+I   Leave insert mode, go to beginning of line, and return to insert mode

Ctrl+O Shift+A   Leave insert mode, jump to end of line, and return to insert mode

(13) Neat, didn't know that one. Btw, try Ctr-r + = (5+4)*3 [Enter] while in insert mode. - Claes Mogren
(1) really neat trick the <C-o> — although you don't need to use it if you're gonna use A or I right after it. - cloudhead
(11) I have my (otherwise useless) Caps Lock key mapped to Esc, so I have an Esc key on the home row. Invaluable with vim. - R. Martinho Fernandes
(8) I use ctrl-[ to esc. - mike
Hey I bet RAlt+numpad-keysequence 0,2,7 would work too, right? :-) - Warren P
(2) How did you achieve this "button" effects in your answer? - Sarwar Erfan
(3) Sarwar, it's <kbd> tag, you can see it when you try to edit the main post - number5
I have giant hands so I just reach up to esc with my left pinky! - z8000
By default Ctrl+C cancels insert mode. 90% of the time this won't be a problem, but it breaks blockwise visual mode. For e.g. use Ctrl+V, select the beginning of some lines, shift+i, and insert a character. Press Ctrl+C and you won't see anything inserted. To fix this, I've added: imap <C-c> <ESC>. - Joe Fiorini
It is really awesome!!!! - Sławosz
[+83] [2008-09-18 18:12:22] Adam Neal


Highlight all occurrences of word under the cursor, and move the the next one. # Searches backwards.

One of the simplest yet greatest features - Ed Guiness
How do you clear the search so it stops highlighting? - Albert
(1) :nohlsearch will temporarily turn off search highlighting. Happy Vimming! - Adam Neal
Cool! Really useful. Was this documented somewhere? - Luis
Can't believe I have used vim this long and didn't know this one - Swish
(31) Also '#' does the same, but backwards. - dalloliogm
Another quick-and-dirty trick to clear the highlighting is to search for some nonsense string like 'lasdhgflas'. This has the benefit that you don't have to switch between :nohlsearch and :hlsearch like crazy, but the disadvantage is that pressing 'n' after clearing the highlight this way would repeat this nonsense search, and not your original search. - sundar
It does really help :) - Vdt
Holy crap I had no idea. Awesome! - Bryan Ross
(4) Instead of manually typing nohlsearch, try mapping it. Ctrl-L already redraws the screen, so I make it also and remove search highlighting: nnoremap <silent> <C-l> :nohl<CR><C-l> - pydave
(1) Along the same lines, gd (which stands for "goto definition") will search for all occurances of the word under the cursor, and immediately go to the first occurance of the word in the current file. - Graphics Noob
[+58] [2008-09-18 19:48:14] Dominic Dos Santos


list all lines found in current and included files that contain the word under the cursor.

(1) quite cool tip! Would be interesting to know the vim help topic for this. - phaedrus
(2) @Amit: :help [ and scroll down a bit. - Fred Nurk
[+58] [2008-09-19 17:00:12] Rich Adams

Correctly indent the entire file currently open.


Note that you may need to do :set filetype=<whatever> and then :filetype indent on before this will work. Unless they're already specified in your .vimrc file.

Great if it's ugly and you don't want to check it back into source control later.. - Adam Hawes
(15) gg=G`` will format the file and take you back to where you were. - NotDan
This is a feature i really need - lucapette
So beautiful! :) - rturrado
[+57] [2008-09-18 18:16:45] Lucas Oman

Ctrl-N / Ctrl-P

Auto-complete - searches current file for words beginning with the characters under the cursor. Great for finishing long func/var names. Will also search other files you've opened during that session.

Lucas, can you explain how to do this. c-n/c-p doesn't seem to do for me what you said. thanks. - user15071
Say you've defined the function "someFunction()" in your file. Elsewhere, you start to type "some" and then hit ctrl-p. A menu should pop up (even in command-line vim, not just gvim!) that gives you options to complete the name from names already in that file. - Lucas Oman
I usually map this to <C-SPace> as a quick auto-complete. - Ayman
I use the tab key to do this auto completion. Don't know how to show code in comment, but you can get the picture: function InsertTabWrapper() let col = col('.') - 1 if !col || getline('.')[col - 1] !~ '\k' return "\<tab>" else return "\<c-n>" endif endfunction inoremap <tab> <c-r>=InsertTabWrapper()<CR> - user176121
[+46] [2008-09-18 18:21:38] Ludvig A Norin

. (period)

Repeats the previous change

This one is really useful :) - Vdt
I'm appreciating the power of this a lot more lately. - justinxreese
[+45] [2008-09-18 18:07:21] jW.

Global Search and replace

(33) :%s/search/replace/gc The 'c' makes it prompt you at each replace instance - Mark Biek
its not 'global' its just inside the current buffer. for global look for Greplace plugin for vim - Vitaly Kushner
@Vitaly: they just mean "global" in a different sense that you do. From the Vim wiki: "The g flag means global – each occurrence in the line is changed, rather than just the first." - Nathan Long
Use this with args and argdo to apply the search and replace to more than one file! - chands
[+45] [2008-09-18 18:14:16] Scottie T

Reopen the current file, getting rid of any unsaved changes. Great for when a global search and replace goes awry.

(34) I always just use 'u'ndo to fix bad search/replaces :) - hark
(9) Reloading the file will destroy your undo history for the buffer. I try to avoid that at all cost. - Aristotle Pagaltzis
(5) For me :e is very useful when watching an active logfile. - Marcin
@Marcin, why not just use tail -f | less? - Christian Mann
@AristotlePagaltzis With 73 up, you can preserve with.. :set undodir=~/.vim/undodir// and :set undofile. Might want toset :set undolevels=1000 and :set undoreload=10000 also. - wom
[+40] [2008-09-19 12:08:44] Ned

Ctrl-A / Ctrl-X

Skip to the next number on the line and increment/decrement it. Has a C-like idea of what's decimal, hex or octal. The "skip to the next number" part is what makes this feature really useful, because it potentially saves several keystrokes getting the cursor to the right place.

I use this a lot... At first it seemed like a trivial thing to manually edit the number, but after getting used to this I realize how arduous a task it is to remember the incremented number and enter it back. All that little amount of brain cell wear and tear counts - Vim helps you stay younger! :) - sundar
(4) If you use vim with GNU Screen, probably you'll need Ctrl-A Ctrl-A as Ctrl-A is meta character for GNU Screen. - Jeffrey Jose
@Jeffey: Because of that (and because Ctrl-A goes to start of line in emacs and bash), I've always had that mapped to ctrl-z. Personally, I found I didn't really need that as much when running things inside a screen. escape ^zz in your .screenrc - Marten Veldthuis
[+37] [2008-09-18 19:44:32] GHZ



q<some key>
<edit one line and move to the next>


@<some key>
@@ (play last macro)
100@<some key> (apply macro 100 times)

EDIT: A slightly complex example might be helpful to get an insight into the power of macros.

Given an array (in C) of 32-bit integers in little endian, we want to convert it into big endian.

uint32_t littleEndian[] = {
  0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef,
  0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef,
  0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef,
  0x0f1e2d3c, 0x4b5a6978, 0x01234567, 0x89abcdef, 0x01234567, 0x89abcdef

Now goto the first data line of the array (the line after uint32_t ...) and type (with the RETURN after ..6@b)


if the array has 9+1 lines with six 4-byte integers in each line.

(Explanation, if you are not fluent in vim:

  • "0fx" takes you to the first x in the line
  • "qal2xbpfxq" defines the macro a to
    • "l" go one to the left
    • "2x" delete two letters
    • "b" go to the beginning of the word
    • "p" insert the two letters just deleted
    • "fx" go to the next x in the line
  • "2u0" undoes the changes we just did and goes to the first column
  • "qbfx4@axbpq" defines the macro b to
    • "fx" go to the next x in the line
    • "4@a" executes four times the macro a (replace 4 by 8 if you have uint64_t)
    • "xbp" deletes the letter under the cursor (happens to be the x), goes to the beginning of the word and puts the just deleted x as 2nd letter meaning that the macro b converts an uint32_t from little to big endian (rsp. vice versa)
  • "3u0" undoes the changes we just did and goes to the first column
  • "qc6@bENTERq" (where ENTER stands for pressing RETURN) defines the macro c to
    • "6@b" executes six times the macro b (replace 6 by the number of integers per line)
    • "ENTER" goes to the next line (see comment) meaning that the macro c converts all integers in a line from little to big endian (rsp. vice versa)
  • "9@c" executes the macro c nine times converting a total of ten lines as one line was already converted (of course replace 9 by whatever you need) )

Maybe this example is too complex for "real life", but it should give you an idea about how powerful macros can be.

(12) Actually 100@<key> plays the macro 100 times, not for 100 lines. It's a small but important difference. If your macro doesn't advance to the next line then you just keep applying the cahnge to the same line over and over, or if your macro is based on found words, multiple lines, etc it will vary. - camflan
I got some problems editing. My original Edit summary was "added example of a complex macro". - jug
[+33] [2008-09-18 18:20:14] Ludvig A Norin

Change the lineendings in the view:

:e ++ff=dos
:e ++ff=mac
:e ++ff=unix

This can also be used as saving operation (:w alone will not save using the lineendings you see on screen):

:w ++ff=dos
:w ++ff=mac
:w ++ff=unix

And you can use it from the command-line:

for file in $(ls *cpp)
  vi +':w ++ff=unix' +':q' ${file}

for file in *.cpp - Fred Nurk
Why not just :set ff=unix, then later :w? - blueyed
[+33] [2008-09-18 18:29:34] Lucas S.

Indents the block between two braces/#ifdefs

(4) This doesn't work for me... But =G does... - Aaron H.
or gqq for the current line. - vitule
(4) == for current line (just 2 keystrokes) - Leonardo Constantino
(2) It does not seem to work well for Python. - Sridhar Ratnakumar
or {=} for current paragraph, etc. - alberge
(1) @Aaron, you have to have the cursor positioned on one of the curly braces before hitting =%. - Robert Gowland
You don't have to be on the brace to indent the contents. Use =ib and =iB to indent inside parenthesis and curly-braces respectively. =% is still good for non-brace matches, though. - nocash
[+33] [2008-11-10 11:33:23] mghaoui

My favorite is:

CTRL-A: Increment a number under the cursor. 99 becomes 100.
CTRL-X: Decrement a number under the cursor. 100 becomes 99.

It's really cool.

(1) Duplicate of… - Fred Nurk
(2) It was edited on Oct 5 '10 at 9:49. It was posted on Sep '08. - Gerardo Marset
Ya but it gets all funky with floats, so CTRL-X on 0.0 gives you -1.0 or 0.-1 and you are very likely to hit CTRL-Z every once in a while - puk
[+30] [2008-10-23 19:24:48] Brad Parks

will replace the last term that was searched for, instead of you having to type it again.

This works well with using * to search for the word under the cursor.

[+26] [2008-09-28 17:07:01] Krzysiek Goj

Never underestimate the power of percent.

Basically, it jumps to matching brace (booooring), but when the cursor is not on a brace it goes to the right until it finds one, which is my excuse to call this post a trick.

[x] means the cursor is on x.

[s]omeObject.methodYouWouldLikeToDelete(arg1, arg2) + stuffToKeep

just type d% to get

[ ]+ stuffToKeep

Obviously, it works with (), [] and {}.

Another examples of percent-not-on-paren:

[m]y_python_list[indexToChange, oneToLeave]


fun[c]tion(wrong, wrong, wrong)


[+25] [2008-09-18 19:12:59] rgcb

running shell commands on the current file without having to exit, run the command and open it again:


for example,

:%!grep --invert-match foo

gets rid of all lines containing "foo"

:%!xmllint --format -

nicely tab-ifies the current file (if it's valid xml)

and so on...

(8) An easier way to delete lines matching a pattern is with :global. :g/foo/d - graywh
(1) You can also specify certain parts of the file. Replacing '%' with '.' (period) will only run the command on the current line. Replacing '%' with '4,8' will run the command on lines 4-8. Finally, replacing '%' with '.,$' will run the command from the current line to the end of the file. - three_cups_of_java
[+24] [2008-10-09 03:21:06] ryan_s

Useful in your vimrc,

set directory=/bla/bla/temp/

Makes vim keep its temporary files in /bla/bla/temp instead of in the directory with the file being edited.

+1 Awesome, I always found those temporary files annoying... - Lin
Ah, and this way I dont have problems running into other's .swp file - Jeffrey Jose
(2) I couldn't get the fugitive plugin to work on Windows due to "unable to rename swp file" errors and similar. It was due to crappy policy settings from our IT dept. THIS SETTING LET ME WORK AROUND IT! THANKS! - Charlie Flowers
[+20] [2010-11-23 07:26:40] poisonedbit

Copy to system clipboard:


Paste from system clipboard:


Move between wrapped lines (it's a good idea to map those):


And for my favourite:


Split and explore!

+1 for moving between the wrapped lines! - jug
[+19] [2008-09-18 18:30:54] Joe Van Dyk

Executes "make" and then will jump to the file that contain the compile errors (if any).

(16) :make is the command. Unambiguous shorter terms are allowed, so :mak works. - Paul Biggar
The other day I found myself quit vim and do make and then I thought to myself, vim would be able to do this for me. here's my answer. Thanks - Jeffrey Jose
[+17] [2009-01-10 23:58:32] Leonard

When doing a search, there are ways to position the cursor search-relative after the search. This is handy for making repeated changes:

/foo/e Finds foo and positions the cursor at the last 'o' of foo

/myfunc.\*(.\*)/e-1 Finds myfunc and places the cursor just before the closing brace, handy for adding a new argument.

/foobarblah/b+3 finds foobarbarblah and puts the cursor at the beginning of bar

This is handy if you decide to change the name of any identifier (variable or function name) - you can set it up so the cursor is on the part that needs to be changed. After you've done the first one, you can do all the rest in the file with a sequence of 'n' (to repeat the search), and '.' (to repeat the change), while taking only a second to make sure the change is applicable in this spot.

And if you're not sure of the offset, you can use \zs to place the cursor at an arbitrary position in the match eg /\(foo\)\+\zs\(bar\)\+/ will always put you at the border between the foos and bars in foofoofoobarbar foobarbarbar foofoobarbarbar, etc. - rampion
[+16] [2008-09-18 19:14:38] vitule


Equivalent to "Go to Definition" in an IDE (one must first create the tags file using e.g. ctags [1]).


Pops to the previous element in the tag stack, i.e., the location and file you were in right before you hit Ctrl+].

:help tagsrch for more details.


[+16] [2008-09-18 19:28:54] Lucas Oman

I have the following in my vimrc:

nmap <F3> <ESC>:call LoadSession()<CR>
let s:sessionloaded = 0
function LoadSession()
  source Session.vim
  let s:sessionloaded = 1
function SaveSession()
  if s:sessionloaded == 1
autocmd VimLeave * call SaveSession()

When I have all my tabs open for a project, I type :mksession. Then, whenever I return to that dir, I just open vim and hit F3 to load my "workspace".

(2) I used something similar for a while but found it doesn't like complex window splits. :( - sirlancelot
Good to know. I rarely use splits; I prefer tabs. - Lucas Oman
[+16] [2008-09-19 16:54:14] Ronny Brendel

As stated in another Thread, with the same Question:

Ctrl + v -- row visual mode Shift + i -- insert before type text Escape Escape

(Inserts the typed in text into multiple lines at the same time.)

This is great for commenting out a whole lot of lines at once. How do you use it to delete a few columns from the beginning of multiple lines? - 2cBGj7vsfp
(2) Enter blockwise visual mode through <C-v>, select the rectangle of lines-by-columns you want do delete, and hit `d'. - ngn
[+16] [2010-10-31 16:27:21] Wolfgang Plaschg

In insert mode:


Inserts the character that is above the cursor at the current cursor position and moves the cursor to the right. Great for duplicating parts of code lines.

(2) Use Ctrl-E to insert the character below. - blueyed
[+12] [2008-09-18 18:13:16] Scottie T

Grep inside this file and print matching lines. You can also replace p with d to delete matching lines.

Did not knew that one. Very usefull. Thank you. - Oli
Did not knew that one. Very usefull. Thank you. (dido) - Luis
(4) Along with its cousin :v which applies to non matching lines. - ojblass
works also without p, as :g/search/ and with # you get the line number as :g/search/# - user2427
Wow. wow and re-wow! - Luc M
[+12] [2008-09-18 18:36:13] Kreich

Ctrl-X then Ctrl-F (while cursor on a path string)
searches for the path and auto-completes it, with multi-optional selection.

[+11] [2010-01-30 12:13:19] Dave Kirby

My favourite feature is the :g[lobal] command. It goes to every line that matches (or does not match) a regex and runs a command on that line. The default command is to simple print the line to the screen, so


will list all the lines that contain the string "TODO:". If use the default command then you can leave the last slash off.

The commands can also have their own ranges which will be relative to the current line, so to display from each TODO: to the next blank line you can do this:

:g/TODO:/ .,/^$/p

(p is short for :print).

And to save all the TODO: blocks to another file:

:g/TODO:/ .,/^$/w! todo.txt  >>

(Explanation: :w means write to a file, ! means create it if it does not exist, and >> means append if it does exist.)

You can also chain commands with the | operator, e.g.

:g/TODO:/ .,/^$/w! todo.txt  >>  | .,/^$/d

will write the block to "todo.txt" then delete it from the current file.

Also see this answer [1] for more examples.

[1] http:////

[+10] [2008-11-06 03:33:53] aaronstacy


add the lines below to your .vimrc file, go into visual mode w/ "v", and hit "c" to comment the lines or "u" to uncomment them, this is insanely useful. the lines below make this possible for C, C++, Perl, Python, and shell scripts, but it's pretty easy to extend to other languages

" Perl, Python and shell scripts
autocmd BufNewFile,BufRead *.py,*.pl,*.sh vmap u :-1/^#/s///<CR>
autocmd BufNewFile,BufRead *.py,*.pl,*.sh vmap c :-1/^/s//#/<CR>
" C, C++
autocmd BufNewFile,BufRead *.h,*.c,*.cpp vmap u :-1/^\/\//s///<CR>
autocmd BufNewFile,BufRead *.h,*.c,*.cpp vmap s :-1/^/s//\/\//<CR>

(5) A dedicated commenting plugin such as EnhancedCommentify or NERD_Commenter would be better suited for this task, over various filetypes - but this does well for a quick hack. - sykora
This doesn't seem much different from visual blocking over a lines, then hitting I and then inserting whatever character you want. - Nikron
(1) Unless I'm missing something, blocking over lines and hitting I doesn't work (vim 7.1, 7.2, Darwin, Linux) - aaronstacy
Note that visual-block mode is different from visual mode. ctrl-v is the default key to enter visual-block mode. - jkerian
I recommend using tcomment instead. - blueyed
[+10] [2008-11-10 08:28:58] Mapad

Edit command lines with vim commands under the bash shell

$ set -o vi

Now you can edit command lines using the vim syntax!


  1. Press ESC to quit insert mode. You can move right/left with [h,j] keys, and forward/backward in the history with [k,l] keys.
  2. Press 'v' to edit the whole command line in vim

@Madpad: Amazing! - jug
[+10] [2010-08-27 13:01:57] phantom-99w

The other day I discovered that Vim has a "server mode". Run a command using

vim --servername <name> <file>

This will create a Vim server with the name . A regular instance of Vim then starts, but other programs can then communicate with the instance of Vim which you are then using. This probably won't help most people, but some programs can make use of this. With Jabref, for example, you can use this feature to push references directly from you bibliography manager (Jabref) into your document which you are editing with Vim.

vim --serverlist

will list all the Vim servers running at that time.

vim --remote

allows you to connect to an already existing Vim server. There are several different --remote commands to do things like commands to the server.

[+9] [2008-09-18 18:09:25] Adam Neal

Brace/parentheses match.

If you have the cursor on a parenthesis/brace/etc ((){}[]), and hit % it will jump to the corresponding one.

MatchIt plugin can make it even better (eg. jump between matching opening and closing XML/HTML tags). - Adam Byrtek
[+9] [2008-11-24 03:44:44] Jon DellOro

When I use vim for writing a tidy journal, notes, etc


to format the current paragraph.

[+8] [2008-09-18 18:11:19] Dustin

Read contents of an external command into the doc:

:r !ls

[+8] [2008-09-18 18:40:56] Kreich

switches the case of the letter under cursor (and moves right, which allows switching a whole line or combining with the "next number/word" command)

(6) It's just ~ not shift-~ It's just that ~ is shift-# on a UK keyboard (and probably shifted on a US one too) - Draemon
ALT-GR ~ on swedish - some
(1) You can use visual mode ('v') to select large blocks to change, too. - Bernard
[+8] [2008-09-19 10:42:43] fiddlesticks

Delete all blank lines in a file:


(3) Delete all blank lines in a file (even with only spaces). :v/./d - graywh
[+7] [2008-09-18 18:44:14] Christopher Cashell

Putting options in comments in a file to be edited. That way the specific options will follow the file. Example, from inside a script:

# vim: ts=3 sw=3 et sm ai smd sc bg=dark nohlsearch

(7) :help modeline for info. - sykora
[+7] [2008-11-13 22:58:27] nayfnu

Knowing that the Windows clipboard buffer can be accessed with:


has saved me lots of boring entering-insert-mode shenanigans. Also copy/pasting between vi sessions can be done with:


[+7] [2008-11-13 23:36:14] arcanex



Mark location under [a-z]


Jump to marked location


Jump to last location


Jump to last edit

(1) Don't forget '. which jumps to the last change in the file. - MattG
[+7] [2008-12-18 19:00:50] Leonardo Constantino

plays back all the commands you pass to it as if they were typed on command mode.

for example:

:1,10 normal Iabc^[Axyz

Would add 'abc' to the beginning and append 'xyz' to the end of the first 10 lines.
note: ^[ is the "escape" character (tipically ctrlv+ESC on Unix or ctrlq+ESC on Windows)

(1) You can also use this to play back a macro: :1,10 normal @a to play back the macro recorded in register a. - Nathan Long
[+6] [2008-11-10 11:29:50] smt
set backup
set backupdir=~/backup/vim

Puts all backup files (file.txt~) in the specified directory instead of cluttering up your working directories.

(1) very nice, thanks :) - dalloliogm
[+6] [2009-01-20 09:01:21] Swaroop C H

gd moves the cursor to the local definition of the variable under the cursor.

gD moves the cursor to the global definition of the variable under the cursor.

Wow! I'm using vim with javascript, and a lot of the code block stuff doesn't work well for me because js is different from c enough to throw it off (and I haven't yet bothered to try to fix it). But this works perfectly even with js! Thanks! - Charlie Flowers
[+6] [2009-01-30 15:22:26] f3lix

Appending the same text to multiple lines

If you have multiple lines and want to append the same text to all lines you can use Ctrl-V to start the visual block mode, move to select the lines, then press $ to extend the selection to the end of the line and the press A to append text (enters insert mode). When you exit insert mode (ESC) the typed text will be appended to all selected lines.

This is useful e.g to append semi-colons and other stuff you need to do when programming.


  1. Ctrl-V for visual block mode (select multiple lines)
  2. $ to extend selection to end of line
  3. A to append in insert mode
  4. ESC switch back to command mode
  5. done

PS: use I in visual block mode to insert text in multiple lines

[+6] [2009-02-22 07:33:29] Amjith

[[ - Beginning of the current function block.
]] - Beginning of the next funcion.
[{ - Beginning of the current code block.
]} - End of the current code block.

z<CR> - position the current line to the top of the screen.
zz - position the current line to the center of the screen.
z- - position the current line to the bottom of the screen.

[+5] [2008-09-19 00:25:09] ernie

To join all lines into a single line.

(3) when did you ever need this? - vitule
(1) you missed a leading ":", otherwise it becomes a completely different command :) - Leonardo Constantino
(1) @Léo thanks, fixed it now. - Liran Orevi
[+5] [2008-09-19 16:46:29] ryan_s

Remove whitespace from line endings on save.

" Remove trailing whitespace from code files on save
function StripTrailingWhitespace()

  " store current cursor location
  silent exe "normal ma<CR>"
  " store the current search value
  let saved_search = @/

  " delete the whitespace (e means don't warn if pattern not found)

  " restore old cursor location
  silent exe "normal `a<CR>"
  " restore the search value
  let @/ = saved_search


au BufWritePre *.c call StripTrailingWhitespace()

Put this in your vimrc, and add auto-commands for any file types you want to remove extra whitespace from. The last line above makes this remove trailing whitespace from C files.

[+5] [2008-09-28 16:38:27] Pramod
  1. gv repeats the last visual selection.
  2. >>Indents the curent block.
  3. set sw=n can be used to change the amount of indent.
  4. Say you want to change the parameters to a function, try c% when you're positioned on the braces.

(2) Regarding #4: ci( does the same as c%, but the cursor can be anywhere inside the parens. - graywh
[+5] [2009-09-29 19:24:47] u0b34a0f6ae

Go to previous text state. What does it mean? Browse through all undo branches with g- (previous change) and g+ (next change).

So if you undo twice in your text, then happen to change something, you suddenly have an undo/redo tree where you can't reach all branches with undo(u)/redo(Ctrl-r), but with g+/g- you can browse through all revisions!

[+4] [2008-09-18 18:26:33] Ludvig A Norin

Enter a number before any command to repeat it N times. For example:

7dd <-- will delete 7 rows

7 arrow down <-- moves down 7 times

4cw <-- removes the 4 next words and puts you in edit mode to replace them

This is in my opinion the most powerful feature of them all :-)

d7d works too, and it should be faster as you don't have to press d twice in a row. - Gerardo Marset
[+4] [2008-09-18 18:30:12] Chuck


Visual mode for selecting text to copy, delete, etc.

[+4] [2008-09-28 16:10:56] camflan

Using Esc all the time is going to cause RSI or something, I'm its not fast enough for me.

Instead, in my .vimrc I have

map! ii <Esc>

For the very few times I need to type 'ii', I just need to type i 3 times, which types one i, exits to normal mode, then another i to type a 2nd i.

That actually doesn't work so well because you'll start insert mode in a different place than you left it. - graywh
(2) C-[ has the same effect as Esc. Having CapsLock remapped with Ctrl, it feels very comfortable for me. - binOr
[+4] [2008-10-18 11:41:08] shyam

ft move to the next occurrence of t and ; and , to move to forward and backward

tt to move to the char before t ; and , work here too.

(2) Don't forget F and T for f/t in the opposite direction. Using ; after t won't move the cursor. Think of ; and , as repeat previous f/F/t/T. - graywh
[+4] [2008-10-21 17:11:23] Jack Senechal

When you have a file (or lots of files) open and the computer crashes, you end up with annoying swap files and you have to open the originals one at a time to see if there are any unsaved changes. The problem is that you've got to hit "r" for "recover", then write out the buffer to a new file, then diff with the original... what a pain!

Here's something nice which cuts down on the last few steps:

Put the following in your .vimrc file:

command DiffOrig vert new | set bt=nofile | r # | 0d_ | diffthis
        \ | wincmd p | diffthis

Then after you recover the file, type :DiffOrig to view the changes from the saved version.

From the vim docs:

[+4] [2008-12-17 21:14:44] phi

in escape mode:
xp - swaps the character under the cursor with the character in front of the cursor.
Xp - swaps the character under the cursor with the character behind the cursor.

+1 as I didn't know/think of Xp! - jug
[+4] [2010-03-19 22:28:08] Jed Daniels

Probably too simple for this crowd, but my favorite little vi trick is ZZ to save and exit. Basically it is the same as :wq, but can be done one handed.

I suppose the next thing is to colorize tabs so they can be easily distinguished from spaces when working with python code. I'm sure there are better ways to do this, but I do it by putting this in ~/.vim/syntax/python.vim:

syntax match tab "\t"
hi tab gui=underline guifg=blue ctermbg=blue


[+4] [2011-06-27 23:25:56] igrigorik

VimGolf @

Yes, shilling for own project, but it is a great way to learn Vim. Pick a challenge and try to do your best.. each time you submit, you'll unlock entries above you. Great way to pickup new tricks.

[+3] [2008-09-18 18:39:35] Ludvig A Norin

u <-- undo :-)

God bless undo. - ojblass
(3) And ctrl-r redo.. for those times you undo a little too much - MattG
(1) And -> :earlier 15m - Aaron H.
[+3] [2008-09-19 00:19:15] jpeacock
vim -o file1 file2 ...

To open multiple files at once in separate panes.

(3) also, -O to open in vertical panes and -p to open in tabs. (I like this one a lot ;) - David Winslow
[+3] [2008-11-14 20:32:03] Aaron H.

I don't see buffers mentioned, so I'll mention them.

I finally got around to trying out Emacs the other day, and discovered buffers. I thought, wow, these are awesome, I wish VIM could do this. With a search I discovered that VIM can! For them to work, you may need to do

:set hidden

first, or add "set hidden" to your vimrc file.


:ls          -- List buffers
:ls!         -- List ALL buffers
:bn          -- Open next buffer
:bp          -- Open previous buffer
:bf          -- Open first Buffer
:bl          -- Open last buffer
:b #         -- Open buffer
:bd #        -- Close buffer (# optional)
:bad <name>  -- New buffer named <name>

(# represents the buffer number listed via :ls)

and of course:

:help buffers

Windows are also extremely useful when dealing with buffers (Described in "help buffers")

The buffer explorer script is also great. See - Hamish Downer
[+3] [2010-05-06 00:23:41] Otto
imap jj <esc>

This will make it so that instead of esc you hit jj. Your hands are always on the home keys, you also are instantly moving around using hjkl(arrow keys) and until you get into some funky matrix loops you never use jj.

[+3] [2011-01-06 07:50:28] phaedrus
:e %<.cpp 

to open myfile.cpp when currently myfile.h is open. Replace :e by :sp to split the window instead of replacing the whole window.

(1) Check a.vim plugin. - Luc Hermitte
[+3] [2011-01-07 20:06:59] KidQueen9

I figured out a basic method for Vista or 7 that has the same effect as %!sudo tee > /dev/null % , hoping it would be useful for vim users using Vista/7.

The previous 2 versions(I removed them) were buggy. Here is the newest.

function ElevatedWrite()
    let tempf = tempname()
    let targetf = expand('%:p')
    let lines = getline(1, line('$'))
    call writefile(lines, tempf)
    execute '!hstart /UAC /NOCONSOLE "' . 'cmd /c copy /Y ' . shellescape(tempf) . ' ' . shellescape(targetf) . ' /B"'

A program named HSTART [1] is needed.

P.S. I used to use the silent command in conjuction with checktime, but it has the same "problem" as system() does -- it seems that vim won't wait them to end before it execute the next command, which makes checktime get called before copy is done. (or it may be because of the UAC popup.)


[+2] [2008-09-18 18:31:35] CMS

I really like the VTreeExplorer [1] script for viewing portions of the folders and files in a tree view, and snippetsEmu [2] to get TextMate-like bundles.

My favorite color scheme for the moment is VibrantInk [3].


[+2] [2008-09-18 18:44:45] hafbaked

ZZ - Save & Exit
o - add blank line below current one and go to insert mode

[+2] [2008-09-18 19:36:40] skiphoppy

I know it's basic, but my favorite vi feature is still the % key, which lets you find matching braces, brackets, or parentheses. I still remember learning it from a sentence in a Perl book by Larry Wall which said something about "at least if you do this you'll let some poor schmuck bounce on the % key in vi." I looked it up, saw what it did, and I was hooked.

It's been nearly ten years, and I still obsessively bounce on the % key while I'm sitting and thinking about what to do next, not to mention to help me match up code blocks and parentheses.

[+2] [2008-09-19 00:30:57] ernie

Knowing that Ctrl+Q in gVim on Windows inserts a control character. For example, I often want to replace ^M characters at the end of lines. It took me a while to find the correct keystroke (Ctrl+P does not work since that's the shortcut for Paste).

why not just %s/\r//g for windoze newlines? - dr Hannibal Lecter
[+2] [2008-09-19 01:15:51] tchen
:syn on

For turning on syntax highlighting

:set foldmethod=syntax

To set the code folding method to be based on the language syntax, provided that the syntax is available for your language of choice. You can put this in your .vimrc file, omit the colon if you do.


To close a particular fold (under the cursor)


To open a particular fold (under the cursor)


To unfold all folds by one level


To collapse all folds by one level


Unfold ALL folds


collapse ALL folds

[+2] [2008-09-19 01:42:54] Bauna


"change word" while editing config files!

Very useful, especially when combined with . to repeat the last change - SpoonMeiser
Why specifically config files? - Sergio Acosta
If you are not at the first character of a word.. use ciw - Jonas Wouters
[+2] [2008-09-19 02:32:56] ryan_s

Search backwards in the file for the word under the cursor. Useful for finding declarations.

(1) And * forwards `) - Liran Orevi
[+2] [2008-09-23 06:35:19] Sridhar Iyer

Read/write pdf files with Vi as if they were text files:

[+2] [2008-11-06 03:17:37]

In your ~/vimrc (or c:_vimrc for Windows), add the following lines:

" set characters shown for special cases such as:
" wrap lines, trail spaces, tab key, and end of line.
" (must be turned on whith set list)
set listchars=extends:»,trail:°,tab:>¤,eol:¶

Then you can type in the command to toggle displaying tabs, trail spaces and eol as special characters:

set list

Add these settings to enable normal move around keys back to the previous line or the next line cross eol:

" Set moving around at the end of line back to previous line by
" <backspace> key and coursor keys, and normal movememt h and l keys
set whichwrap=b,s,<,>,h,l

Enjoy VIM!

[+2] [2008-11-13 23:00:51] André

gqap reformats an entire paragraph to match the current textwidth, pretty useful for plain text of LaTeX-docs.

[+2] [2009-01-20 09:06:54] Nathan Fellman

[d to show the definition of a macro

[D to show the definition of a macro along with where it was defined.

[+2] [2009-01-27 14:17:44] Dan Goldstein

viwp - replace the word under the cursor with what's in the unnamed register.

What's nice about this is that you don't need to be at the beginning of the word to do it.

[+2] [2009-02-13 15:48:17] adam
vmap // y/"

Search for the visually selected text.

[+2] [2009-02-19 03:49:50] Raim

I am using this snippet in my .vimrc to select a block of code and adjust indentation by pressing < or > multiple times.

" keep selection on indenting in visual mode
vmap > :><cr>gv
vmap < :<<cr>gv

[+2] [2009-02-22 09:23:46] Johan

How about this one I found in The Pragmatic Programmer [1] that sorts 4 lines with the sort command (starting at the line the marker is at):


Or just mark a section with visual mode and then type !sort:


Kind of cool and useful to sort a headerfile or some includes.

Edit: This is a Unix hack, the Windows port can't call shell commands (?)

Edit: Thanks to Luc Hermitte who pointed out that this should work under Windows as well. So I found a Windows XP with a working gVim installation and tried it. I found out that both !sort and :sort did work.

Very nice :-)


(1) We can use shell commands on windows. But in this case, vim has a :sort command. No need to call an external tool. - Luc Hermitte
@Luc Hermitte, thanks. - Johan
[+2] [2009-02-25 05:12:52] Jeff

Count the number of matches for the search text:


Or, leave out the trailing g to count the number of lines the search text occurs on.

[+2] [2010-04-18 04:52:24] Joshua

As of now my favorite command is probably :retab. It lets you convert from tabs to spaces and from spaces to tabs. You can check out :help retab for more details.

[+2] [2010-05-17 23:07:44] Damien Wilson

Font selection using your system UI, straight from the docs:

For Win32, GTK, Motif, Mac OS and Photon:

:set guifont=*

will bring up a font requester, where you can pick the font you want. In MacVim :set guifont=* calls:

:macaction orderFrontFontPanel:

which is the same as choosing "Show Fonts..." from the main menu.

See :help guifont for more details. Also, Inconsolata [1] is one of the best fixed-width fonts out there.


[+2] [2011-01-08 12:45:31] phaedrus

A tip useful for beginners: I use search combined with other actions. For example to convert

 A Lazy Brown Fox


 A Brown Fox

when currently the cursor is at the end of the line, I would use ?La and enter to jump to Lazy and then dw to delete the word. Next, if I want to delete Brown, I could use dw or I could use d/Fox to delete till the first occurrence of Fox and enter. To delete till the second occurrence of Fox, use 2d/Fox.


   set incsearch 
   set hlsearch 

in vimrc is useful for highlighting searches as they are going on.

[+1] [2008-09-18 18:22:14] EmmEff

Reformat current line. Use it all the time to reformat comments in code, etc.

how is that different from this one? gqq - vitule
did not understand?, what is the meaning of gqip? - Aman Jain
(3) gqq formats only the current line, whereas gqip actually formats a whole paragraph. gqip means: format (gq) the inner content (i) of the current paragraph (p) - ngn
Doesn't work well with C language where it breaks the contents of strings inside printf. any suggestions ? - Liran Orevi
[+1] [2008-09-18 19:02:40] dreeves

Reaching up to hit ESC all the time is much too slow. I use TAB instead. Put this in your .vimrc:

    imap <tab> <esc>

CAPSLOCK is even better if you don't already have that remapped to CTRL.

I never type literal tabs in insert mode so haven't bothered with this but if someone could replace this sentence with how to swap ESC and TAB (or CAPSLOCK), that would be super handy.

Other alternatives to <Esc> are: <C-c>, <C-[>, or holding meta (alt) with the next normal mode key you type---for instance after doing an insert mode edit, I press <M-j> to go down or <M-k> to go up. - ngn
(2) Yet another alternative is to ``:imap jj <Esc>'', this trick was mentioned somewhere in this site. When you press `j' twice in insert mode, you go back to normal mode---pretty handy. - ngn
imap jj <esc> is... the... best.. vim... tip... ever!!!!! - Trumpi
Thanks for these ideas! I decided to make a separate question about this: - dreeves
What if you want to write 'jj' ? - Liran Orevi
[+1] [2008-09-18 19:03:03] rgcb


Visual mode for selecting text to copy, delete, etc.

i also find ctrl+v for visual block and shift+v for visual line quite useful

[+1] [2008-09-18 19:26:27] leeand00

:ts to search for tags in C/C++

And Ctrl-] searches for the tag under the cursor, and Ctrl-T pops back off the stack of tags. - Andy Lester
[+1] [2008-09-18 19:36:38] Jason Moore


transpose two characters.

e.g. 'teh' move cursor over the 'e' and type 'xp' (x=cut, p=paste cut buffer)

y (or yy) yank a line into the buffer

d (or dd) delete line (and put in buffer)

p put/paste the buffer

really, handy when combined with multipliers.

5yy [move cursor] p copy 5 lines

[+1] [2008-09-18 20:51:52] unexist

Vimrc to highlight tabs:

syntax match Tab /\t/
hi Tab guifg=yellow ctermbg=white

[+1] [2008-09-19 02:51:56] Cliff

dG - delete to the end of the file :vsplit file2 - show current file and file2 side by side. Could also open file1 and file2 at the same time with -o (horizontal split) or -O (vertical split) options

[+1] [2008-10-02 13:43:54] Kreich

:vsplit [filename]

opens an additional page side by side with the current page (vertically splitting the window).
:split [filename]

opens an additional page, horizontally splitting the current page.

you can move between pages with ctrl+w -> Arrow keys

Also you could use Ctrl-w-s for horizontal split and Ctrl-w-v for vertical split. Also Ctrl-w-w cycles from one window to another. - hyperboreean
Arrow keys? What is that? - Alex
[+1] [2008-10-27 19:15:08] mempko

With vim 7 I love vimgrep.

For example to search for myfunc in all my files under my project I do.

:vimgrep /myFunc/j **/*.cpp

The /j means don't jump to the first find. */.cpp means recursively search only .cpp files.

To view the results you just use the quick fix window


[+1] [2008-11-07 13:56:58] ididak

I've been using vim <branch/tag/rev>:path with git:file.vim [1] a lot lately.

Using gq} to format comments is also one my favorite vim tricks not found in the original vi.


[+1] [2008-11-13 23:08:03] bene

I wrote a function to go to the Most Recently Used tab page like Ctrl-a Ctrl-a in screen does or Alt-Tab in common window managers.

if version >= 700
    au TabLeave * let g:MRUtabPage = tabpagenr()
    fun MRUTab()
        if exists( "g:MRUtabPage" )
            exe "tabn " g:MRUtabPage
    noremap <silent> gl :call MRUTab()<Cr>

[+1] [2008-12-05 21:30:44] Scottie T

ZZ = :wq
ZQ = :q!

[+1] [2008-12-16 10:22:24] vitule
Ctrl+w Ctrl+]

splits current window to open the definition of the tag below the cursor

[+1] [2009-01-20 09:28:17] hyperboreean
  • Ctrl-w-s - split horizontal
  • Ctrl-w-v - split vertical
  • Ctr-w-w - cycle through all those windows
  • :tabnew - open a new tab inside vim
  • Ctrl-PageUp, Ctrl-PageDown - cycle through those tabs

[+1] [2009-02-09 21:01:58] Casey

Page Up/Down From Home Row

I'm always using C-f and C-b to move around, so it's better to map to the home row keys. The following .vimrc settings will set PageUp to to C-k and PageDown to C-j.

noremap <C-k> <C-u>
noremap <C-j> <C-d

[+1] [2009-02-09 21:35:23] Casey

Enhanced Tab View

Most programs have Tabs now, so why not enabled vim Tabs?

How to use it:

   Ctr-t            opens new tab
   Ctr-h            activate tab left of current
   Ctrl-l           activate tab right of current
   Alt-1 to Alt-0   jump to tab number

Add in your .gvimrc/.vimrc:

  set showtabline=2    " always show tab bar
  set tabpagemax=20    " maximum number of tabs to create

Add in your .vimrc

   " new tab
   nnoremap <C-t>     :tabnew<cr>
   vnoremap <C-t>     <C-C>:tabnew<cr>
   inoremap <C-t>     <C-C>:tabnew<cr>
   "tab left
   nnoremap <C-h>     :tabprevious<cr>
   vnoremap <C-h>     <C-C>:tabprevious<cr>
   inoremap <C-h>     <C-O>:tabprevious<cr>
   nnoremap <C-S-tab> :tabprevious<cr>
   vnoremap <C-S-tab> <C-C>:tabprevious<cr>
   inoremap <C-S-tab> <C-O>:tabprevious<cr>
   "tab right
   nnoremap <C-l>     :tabnext<cr>
   vnoremap <C-l>     <C-C>:tabnext<cr>
   inoremap <C-l>     <C-O>:tabnext<cr>
   nnoremap <C-tab>   :tabnext<cr>
   vnoremap <C-tab>   <C-C>:tabnext<cr>
   inoremap <C-tab>   <C-O>:tabnext<cr>
   "tab indexes
   noremap <A-1> 1gt
   noremap <A-2> 2gt
   noremap <A-3> 3gt
   noremap <A-4> 4gt
   noremap <A-5> 5gt
   noremap <A-6> 6gt
   noremap <A-7> 7gt
   noremap <A-8> 8gt
   noremap <A-9> 9gt
   noremap <A-0> 10gt

Just don't complain when vim starts opening files in the "wrong place". - graywh
I prefer map <A-1> to :tabn 1<CR> - Luc M
@graywh - can you be more specific? - Casey
[+1] [2009-02-10 05:26:58] anthony

Put these two lines in your .vimrc:

map <C-J> zzjzz
map <C-K> zzkzz

Use Ctrl-J/Ctrl-K to scroll up and down while keeping your cursor in the middle of the visible range.

(2) I don't actually like this because it "jumps" if you have the cursor close to the top or bottom of the window, but it did give me an idea and I have added. :map <C-J> <C-e>j :map <C-K> <C-y>k To provide a 'smooth' version of the same idea. - Leonard
[+1] [2009-02-10 06:18:12] smcameron

When updating my "blog" at work (which is just an html file) I do ":r !date" to get a timestamp.

If I find myself doing a repeated operation, I will often remap ctrl-O (which isn't used so far as I know by any vim thing) via the :map command, using ctrl-V to escape the ctrl-O.

So, for example, if I have a list of things


(and maybe 20 more things)

and I want to convert that to C code like:

printf("x = %d\n", x);
printf("y = %d\n", y);
printf("z = %d\n", z);,


I might do:

:map ^V^O yypkIprintf("^V^[A = %d\n", ^[JA);^[j

(ok, I didn't test the above, but, something like that.)

Then I just hit ctrl-o, and it converts each line from



printf("x = %d\n", x);

Then, if I want to kill emacs, I head over to

Much more intuitive to use recording: qa to start recording, perform operation, q to stop recording, @a to play recording. Optionally replace a by some other character in qa and @a. - phaedrus
[+1] [2009-02-22 08:33:29] George V. Reilly

Here's a pattern that I use a lot in keymaps. It brackets the current visual selection with a PREFIX and a SUFFIX.

vnoremap <buffer> <silent> ;s <Esc>`>aSUFFIX<Esc>`<iPREFIX<Esc>

Breaking it down, since that looks like line noise.

vnoremap        Visual-mode keymap; no further expansion of the right-hand side
<buffer>        Buffer-local. Won't apply in other buffers.
<silent>        Mapping won't be echoed on the Vim command line
;s              Mapping is bound to sequence ;s
<Esc>           Cancels selection
`>              Go to end of former visual selection
aSUFFIX<Esc>    Append SUFFIX
`<              Go to beginning of former visual selection
iPREFIX<Esc>    Insert PREFIX

For example:

vnoremap <buffer> <silent> ;s u`>a</a><Esc>`<i<a href=""><Esc>

brackets the visual selection with an HTML anchor tag.

[+1] [2009-05-05 17:07:28] Hamish Downer

I always set my keyboard to swap Caps Lock and Escape.

With the standard Ubuntu/GNOME desktop, go through the menus: System -> Preferences -> Keyboard -> Layouts tab. Then hit the "Layout Options" button, click on the triangle next to "Caps Lock key behaviour" and select "Swap ESC and CapsLock".

Not strictly part of Vim, but makes Vim so much nicer to use.

And other than that, use Vim for everything. Some useful extensions to allow more Vim usage:

  • for Firefox, It's all text [1] allows you to use an external editor for text boxes, and if you want to go further then investigate the Vimperator [2]. Also, not at version 1.0 yet, but jV [3] makes text areas work like vi.
  • for Thunderbird, the external editor [4] extension allows you to use gVim to write your emails, or you could use Vimperator's sister extension - muttator [5].



Seems great!! I'll try it. Thanks - Luc M
[+1] [2009-06-17 21:25:34] chardin

Here are some Vim [1] commands I use a lot.

  • gUU Uppercase the current line.
  • guu Lowercase the current line.
  • :%s/^I/\r/g Change all tabs to newlines. (The ^I is the tab character).

that guu also make pain in my life. Often i need to go to top and type gg (sometimes i type too much) and press u ... and suddenly my CamelCase codes becomes lowercase :( - nightingale2k1
[+1] [2009-10-07 20:42:02] Ton van den Heuvel

Remap your caps lock key to control, and then use the easier to type Ctrl-[ shortcut instead of Escape to leave insert mode. Modern Linux distributions support keyboard remapping through the keyboard settings dialog, under Windows I use SharpKeys [1].


[+1] [2009-10-27 20:01:57] juque

The very best!

:set vb t_vb=

no more beep!

[+1] [2010-04-08 19:20:46] slack3r

CTRL-O and CTRL-I goes back and forward in your jump history (also works between buffers!).

:grep foo -R * then use :cn and :cp to jump between matches.

Also in .vimrc: set autochdir was important to me -- it tells Vim to change the current directory to the current buffer's directory. This matters, for example, when I am in dir1 in the shell and start vim from there, then switch to some file in a different directory and try to do something like grep foo *.

In *nix K opens the man page for the word under cursor. Nice for syscalls (try 2K and 3K) and C standard library. (nK is manual section n)

:make in a directory containing a Makefile. Then use :cn and :cp to jump between errors.

I currently use

:nnoremap <silent> gw "_yiw:s/\(\%#\w\+\)\(\W\+\)\(\w\+\)/\3\2\1/<CR><c-o><c-l>

for swapping words (When I mess up argument order or assignment sides, etc.), but this needs improvement as it doesn't always work very well. Also, I'm not sure if there's a nice way to swap two distant words (Anybody?).

EDIT: Also I like keeping a text file in ~/.vim/doc in vim's help format which I call cheatsheet.txt where I put some things I don't use very often so I forget, but are nice tricks or important functionality. For example:

*cheatsheet.txt* Some clever tricks that I want to find quickly
1. COMMANDS *cheat-commands*
                                                                          *cheat-encoding* |++enc|
:e++enc=cp1251 Reopen file with cp1251 encoding

Then in vim i just do :help cheatsheet (:helptags ~/.vim/doc/ needs to be done to rebuild the help tags) or :help cheat-encoding (here, even tab-completion works). The benefit of this is I have only things that I know are relative to me and I don't need to dig in the VIM documentation. Also, this could be used for stuff other than VIM-specific info.

[+1] [2010-05-17 23:18:46] bobthabuilda

Insert a comment before every line selected in visual line mode.

First, select the lines which need commenting out in visual line mode (SHIFT + V).

Then type this (substitute your own comment symbol):




The first one should be :s/^/#/ - I use this one all the time. - Hamish Downer
[+1] [2010-09-23 09:04:57] sica07
A  "append at the end of the line

The A command was a productivity buster for me. It replaces $a commands. Sorry if it was mentioned before.

[+1] [2011-01-19 04:23:33] OneOfOne

If you are using KDE and want to paste from system clipboard you can use CTRL-R + in insert mode or "+p in normal mode.
You can also use CTRL-R * in insert mode / "*p in normal to paste the selection buffer (mouse's middle button).

Actually it has nothing to do with KDE, it is truth for any X11 DE/WM. Moreover, the + register even works in Ms Windows, AFAIK. - dmedvinsky
That's good to know, I don't have windows and haven't used any other DE/WM since KDE 3.0 was new (4.6 is shiny). - OneOfOne
[+1] [2011-06-27 03:21:49] omab

Leader key definition:

let mapleader = ","

Remaoing j/k to work properly with very long lines:

nnoremap j gj
nnoremap k gk

Remap something less painful to mimic ESC functionality

imap jj <ESC>

Better, map capslock to escape system-wide. It's totally useless anyway. Windows: or linux: xmodmap -e "clear lock"; xmodmap -e "keycode 0x42 = Escape" - naught101
[0] [2008-09-18 18:23:45] Ludvig A Norin

NNyl <-- copy NN characters to the right beginning with the cursor position (ie. 7yl to copy 7 characters)

p <-- paste the characters at the position after the cursor position

P <-- paste the characters at the position before the cursor position

[0] [2008-09-18 18:27:40] Joe Van Dyk

I have this in my .vimrc file -- it's helpful for doing Ruby programming.

map R :wall!:!ruby %

This lets me press 'R' and have the file saved and then execute the file in the Ruby interpreter.

Silly question I guess--but what do you do when you actually need to type an "R"? - Onorio Catenacci
Well, inputting an R wouldn't be a problem, as that would happen in an edit mode, not command mode. But that overrides the replace function, which I use a lot. - Herms
[0] [2008-09-18 18:39:13] Ludvig A Norin

At the ex prompt you have command history using up/down arrows.

[0] [2008-09-18 19:48:10] Paul Brinkley

In my vimrc file:

" Moves this window to the left, center, or right side of my monitor.
nmap ,mh   :winpos 0 0<cr>
nmap ,ml   :winpos 546 0<cr>
nmap ,m;   :winpos 1092 0<cr>
" Starts a new GVim window.
nmap ,new :!start gvim<cr>

[0] [2008-09-19 02:39:58] Max Cantor
[0] [2008-09-19 10:40:12] Artur Siara

I have some shortcuts, ie:

1.Sort a file with a few way

map ,s :%!sort<CR>
map ,su :%!sort -u<CR>
map ,si :%!sort -f<CR>
map ,siu :%!sort -uf<CR>
map ,sui :%!sort -uf<CR>
map ,sn :%!sort -n<CR>
map ,snu :%!sort -n -u<CR>

2.Open new file from current path with vertical split

map ,e :vsp .<CR>

3.Grep file with match

map ,g :%!grep

4.Change show file modes

map ,l :set list<CR>
map ,L :set nolist<CR>

5.Turn on/off highlight

map ,* :se hls<CR>
map ,8 :se nohls<CR>

6.Turn on/off numbering

map ,n :se nu<CR>
map ,N :se nonu<CR>

7.Run - perl

map ,p !perl<CR>
map ,P gg!Gperl<CR>

8.Copy file to specified server

map ,scp :!scp %

[0] [2008-11-12 23:40:28] Swish

To turn auto indent on/off for pasting with add the following to the .vimrc:

nnoremap <F2> :set invpaste paste?<CR>
imap <F2> <C-O><F2>
set pastetoggle=<F2>

That will give you a visual cue as well

[0] [2008-11-13 23:53:10] user35978

Well, I know the author said no basic.. but I didn't know this one even if I knew less-basic one. Just use o to begin insert a new-line after the present line.. I used to do something like, $a (go to the end, start writing, and create new line).. So now, only o does this :) And by the way, O insert a new line on the present line instead of inserting it after the current.

[0] [2009-01-08 23:59:30] Epitaph

Editing multiple files simultaneously is very useful.

:sp filename
opens another file name in the same window

ctrl + W (arrow key)
will take you the other window depending on its location

:windo wincmd H (or V)
tiles the windows horizontally (or vertically)

Also, I use . a lot It repeats the last executed command.

[0] [2009-01-20 09:10:20] mjy


=> remove CR (DOS/Windows => Unix text format)

(^V = Ctrl-V etc.)

[0] [2009-02-01 11:07:39] Reza Jelveh

]m [m - for next/previous method start

]M [M - for next/previous method end

They actually match the first and second level of closing/opening braces.

[0] [2009-02-10 05:20:44] sirlancelot

I keep a backup of all my files I edit in Vim using the commands below:

set backup
set backupcopy=yes
set backupskip=/tmp/*,~/.vim/backup/*
set backupdir=~/.vim/backup
au BufWritePre <buffer> let &backupext = '~' . localtime()
function! DeleteOldBackups()
    " Delete backups over 14 days old
    call system('find ~/.vim/backup -mtime +14 -exec rm "{}" \;')
au VimLeave * call DeleteOldBackups()

The code will dump all files in to ~/.vim/backup, tag them with a Unix timestamp, and delete backups over 14 days old.

It uses the Unix find command. If anyone can tell me how to use Vim built-in commands, please do so :) Otherwise, this will only work on Unix systems!

[0] [2009-02-10 06:21:21] Steve Rowe

CamelCase Motion. Let's you move through and delete/edit CamelCase words.

[0] [2009-06-26 01:39:57] nightingale2k1

gg = G (go to top of file and tidy the format) very usefull :D

[0] [2009-10-12 05:14:55] user152771

Indent source line(s) one tab to the left or right

> - Left
< - Right

Remove trailing white-space once the file is saved
Add this to your .vimrc file:

au BufWritePre * silent g/\s\+$/s///

Edit another file without saving changes made to the file currently being edited:

:set hidden

[0] [2009-10-23 13:18:10] Diego Pino

Some times I open files with vim to delete all trailing white spaces: (particularly heplful for git users aswell :)):


If you want to highlight trailing whitespaces (grey color), add the following to your .vimrc:

highlight TrailingSpaces ctermbg=grey guibg=grey
match TrailingSpaces /\s\+$/

[0] [2009-10-30 08:02:30] Federico

Switch spellcheck languages

The function:

let g:myLangList = [ "none", "it", "en_us" ]
function! MySpellLang()
"loop through languages
if !exists( "b:myLang" )
      let b:myLang=0
let b:myLang = b:myLang + 1
if b:myLang >= len(g:myLangList) | let b:myLang = 0 | endif

if b:myLang== 0 | setlocal spell nospell | endif
if b:myLang== 1 | setlocal spell spelllang=it | endif
if b:myLang== 2 | setlocal spell spelllang=en_us | endif

echo "language spell:" g:myLangList[b:myLang]

And the bindings:

map <F8> :call MySpellLang()<CR>

[0] [2009-11-20 12:26:06] Ubersoldat

Make vimdiff a great merge tool

function Vimdiff()
nmap <F7> [czz
nmap <F8> ]czz
nmap <F2> do
nmap <F3> dp

au FilterWritePre * if &diff | call Vimdiff() | endif

This will allow you to use F7 and F8 to go to the next/previous change and F2 and F3 will copy changes from left to right and vice-versa.

[0] [2009-12-17 19:07:05] theIntuitionist

Autocomplete on tab instead of oddball key combo! Really nice. Will autocomplete if there are characters to the left of the cursor, otherwise will insert a tab.

"Use TAB to complete when typing words, else inserts TABs as usual.
"Uses dictionary and source files to find matching words to complete.

"See help completion for source,
"Note: usual completion is on <C-n> but more trouble to press all the time.
"Never type the same word twice and maybe learn a new spellings!
"Use the Linux dictionary when spelling is in doubt.
"Window users can copy the file to their machine.
function! Tab_Or_Complete()
  if col('.')>1 && strpart( getline('.'), col('.')-2, 3 ) =~ '^\w'
    return "\<C-N>"
    return "\<Tab>"
:inoremap <Tab> <C-R>=Tab_Or_Complete()<CR>
:set dictionary="/usr/dict/words"

From Autocomplete with TAB when typing words [1]


[0] [2010-01-09 21:04:50] user107745

^wf ..... open file under cursor in new window

[0] [2010-01-30 09:46:11] Vincent

I have following maps, that will make navigation between windows much easier, just Ctrl + jkhl :

nmap <C-j> <C-W>j
nmap <C-k> <C-W>k
nmap <C-h> <c-w>h
nmap <C-l> <c-w>l

[0] [2010-02-22 04:38:00] secondbanana

Corrects indentation for the entire file. I was missing my trusty <C-a><C-i> in Eclipse but just found out vim handles it nicely.

it is good, but it is a duplicate in this question. Vote the other up instead.. - Johan
[0] [2010-04-08 19:28:18] Sridhar Iyer
autocmd BufReadPost *.pdf silent  %!pdftotext "%" -layout -q -eol unix -

Opens up a pdf file in vi.. Works great for programming/SDK(text centric) manuals. You can use all vi constructs on the pdf, to find info, cut-paste etc.

[0] [2010-05-29 03:24:43] Benjamin

Search any string you want.
Then type this.




You can also use


(7) You should probably describe what these commands actually do. - ScottS
[0] [2011-01-08 12:37:55] phaedrus

One nifty feature is recording. qf to start recording your actions in a buffer f and q to quit recording. @f to play recording. I use it quite often for repetitive work.

[0] [2011-06-27 02:53:30] Marc

For your .vimrc file:

nnoremap <leader>v V`] " this reselects the last inserted text.

[0] [2011-06-27 08:48:04] Kai König

This I find to be very neat since sometimes i dont find to cursor when doing search

" Press F4 to toggle highlighting on/off, and show current value.
noremap <F4> :set hlsearch! hlsearch?<CR>

[0] [2011-06-27 10:23:13] chanux

select lines in visual mode and


[0] [2011-06-27 13:34:53] user771555
:%g/{\s*$/s/$/DEBUG STMT/

For the beginning of a code block ({), add a debug statement. This is more useful in PHP as you can

echo __METHOD__ . '(' . __LINE__ . ")\n";

and get method names and line numbers. I normally insert a newline before the DEBUG STATEMENT to make it a little easier to delete afterwards with:


[0] [2011-06-27 17:53:00] cryptochaos

Run the current file you're editing. Never leave VIM when developing scripts!