views:

14543

answers:

129

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

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

+29  A: 

:%s/search/replace/g

Global Search and replace

jW
:%s/search/replace/gcThe 'c' makes it prompt you at each replace instance
Mark Biek
+7  A: 
%

Brace/parentheses match.

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

Adam Neal
MatchIt plugin can make it even better (eg. jump between matching opening and closing XML/HTML tags).
Adam Byrtek
+5  A: 

Read contents of an external command into the doc:

:r !ls

Dustin
+55  A: 

*

Search for all occurrences of word under the cursor.

Adam Neal
One of the simplest yet greatest features
Ed Guiness
How do you clear the search so it stops highlighting?
Albert
:nohlsearch will temporarily turn off search highlighting. Happy Vimming!http://vimdoc.sourceforge.net/cgi-bin/vimfaq2html3.pl#11.1
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
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 :)
nXqd
Holy crap I had no idea. Awesome!
Bryan Ross
+6  A: 

:g/search/p

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

Scottie T
Did not knew that one. Very usefull. Thank you.
Oli
Did not knew that one. Very usefull. Thank you. (dido)
Luis
Along with its cousin :v which applies to non matching lines.
ojblass
+27  A: 

:e!

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

Scottie T
I always just use 'u'ndo to fix bad search/replaces :)
hark
Reloading the file will destroy your undo history for the buffer. I try to avoid that at all cost.
Aristotle Pagaltzis
For me :e is very useful when watching an active logfile.
Marcin
+44  A: 

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 Oman
Lucas, can you explain how to do this. c-n/c-p doesn't seem to do for me what you said. thanks.
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
+22  A: 

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)
do 
  vi +':w ++ff=unix' +':q' ${file}
done
Ludvig A Norin
+30  A: 

. (period)

Repeats the previous change

Ludvig A Norin
This one is really useful :)
nXqd
+1  A: 
gqip

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

EmmEff
how is that different from this one?gqq
vitule
did not understand?, what is the meaning of gqip?
Aman Jain
`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
A: 

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

Ludvig A Norin
+4  A: 

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

Ludvig A Norin
A: 

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.

Joe Van Dyk
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
+29  A: 
=%

Indents the block between two braces/#ifdefs

Lucas S.
This doesn't work for me... But =G does...
Aaron H.
or gqq for the current line.
vitule
== for current line (just 2 keystrokes)
Leonardo Constantino
It does not seem to work well for Python.
Sridhar Ratnakumar
or {=} for current paragraph, etc.
alberge
@Aaron, you have to have the cursor positioned on one of the curly braces before hitting =%.
Robert Gowland
+4  A: 

v

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

+15  A: 
 :mak

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

Joe Van Dyk
`:make` is the command. Unambiguous shorter terms are allowed, so `:mak` works.
Paul Biggar
A nice addition to this is the vast array of compiler plugins available, which set vim up to run and parse output from lots of compilers and other syntax-error-reporting thingies. For example, editing an xml file, you can do: `:compiler xmllint` `:make %`to run xmllint on the currently edited file and jump to errors.
David Winslow
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
jeffjose
+2  A: 

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

My favorite color scheme for the moment is VibrantInk.

CMS
+8  A: 

ctrl-x->ctrl-f (while cursor on a path string)
searches for the path and auto-completes it, with multi-optional selection.

Kreich
A: 

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

Ludvig A Norin
+2  A: 

u <-- undo :-)

Ludvig A Norin
God bless undo.
ojblass
And ctrl-r redo.. for those times you undo a little too much
MattG
And -> :earlier 15m
Aaron H.
+7  A: 

Shift-~
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)

Kreich
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
You can use visual mode ('v') to select large blocks to change, too.
Bernard
+6  A: 

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
Christopher Cashell
:help modeline for info.
sykora
+1  A: 

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

+1  A: 

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.

dreeves
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
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: http://stackoverflow.com/questions/397229
dreeves
What if you want to write 'jj' ?
Liran Orevi
+1  A: 

v

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

agentj0n
+20  A: 

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

:%!<command>

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

agentj0n
An easier way to delete lines matching a pattern is with :global.:g/foo/d
graywh
+9  A: 

Ctrl+]
equivalent to Right click + "Go to Definition" in Visual Studio
(one must first create the tags file using e.g. ctags)

vitule
A: 

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

leeand00
And Ctrl-] searches for the tag under the cursor, and Ctrl-T pops back off the stack of tags.
Andy Lester
+13  A: 

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
endfunction
function SaveSession()
  if s:sessionloaded == 1
    mksession!
  end
endfunction
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".

Lucas Oman
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
+1  A: 

xp

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

Jason Moore
+2  A: 

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.

skiphoppy
+21  A: 

macros

Record:

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

Play:

@<some key>
@@ (play last macro)
100@<some key> (apply macro 100 times)
GHZ
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
+1 for camflan's comment
vitule
+1 for camflan as well, If I had the rep I would fix it...
sirlancelot
A: 

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>
Paul Brinkley
+27  A: 

[I

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

Dominic Dos Santos
+196  A: 

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)

Lee
Wow! I've needed this so many times!
kosoant
Ack! Where's that "save this for later so you can come back and vote it up when you get more votes" button?!
converter42
You, Sir, are my hero!
Joachim Sauer
This is. The best thing. Ever.
sirlancelot
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
Why not just ":w !sudo tee %"?
HH
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
Nevermind my question, if someone is interested just look here: http://stackoverflow.com/questions/2600783/how-does-the-vim-write-with-sudo-trick-work
Doppelganger
+1  A: 

Vimrc to highlight tabs:

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

unexist
+3  A: 
vim -o file1 file2 ...

To open multiple files at once in separate panes.

jpeacock
also, `-O` to open in vertical panes and `-p` to open in tabs. (I like this one a lot ;)
David Winslow
+70  A: 
da<

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

ci"

Change the content of a doublequote-delimited string.

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

Aristotle Pagaltzis
That is a most excellent tip.
dowski
In addition to <> and "", this also works with [], {}, and ().
Robert Gowland
It's really cool. How to remember this :a = alli = innertry these ones : a[ i[ a< i< a{ i{
nXqd
+3  A: 
:%j

To join all lines into a single line.

when did you ever need this?
vitule
you missed a leading ":", otherwise it becomes a completely different command :)
Leonardo Constantino
@Léo thanks, fixed it now.
Liran Orevi
+1  A: 

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  A: 
: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.

zc

To close a particular fold (under the cursor)

zo

To open a particular fold (under the cursor)

zr

To unfold all folds by one level

zm

To collapse all folds by one level

zR

Unfold ALL folds

zM

collapse ALL folds

+2  A: 

cw

"change word" while editing config files!

Bauna
Very useful, especially when combined with . to repeat the last change
SpoonMeiser
Why specifically config files?
Sergio Acosta
+2  A: 
#

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

ryan_s
And * forwards `)
Liran Orevi
A: 

http://dotfiles.org/.vimrc

This one's mine: http://dotfiles.org/~maxcantor/.vimrc

Max
+1  A: 

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

Cliff
A: 

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 % [email protected]:~/some_folder/
+6  A: 

Delete all blank lines in a file:

:g/^$/d

fiddlesticks
Delete all blank lines in a file (even with only spaces). :v/./d
graywh
+26  A: 

control-A / control-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.

Ned
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
If you use vim with GNU Screen, probably you'll need `Ctrl-A Ctrl-A` as `Ctrl-A` is meta character for GNU Screen.
jeffjose
+4  A: 

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)
  %s/\s\+$//e

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

endfunction

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.

ryan_s
+14  A: 

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

Ronny
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
Enter blockwise visual mode through <C-v>, select the rectangle of lines-by-columns you want do delete, and hit `d'.
ngn
+28  A: 

Correctly indent the entire file currently open.

gg=G

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.

Rich Adams
Great if it's ugly and you don't want to check it back into source control later..
Adam Hawes
+2  A: 

Read/write pdf files with Vi as if they were text files: http://vim.wikia.com/wiki/Open_PDF_files

Sridhar Iyer
+4  A: 

Using Esc all the time is going to cause RSI or something, I'm sure...plus 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.

camflan
That actually doesn't work so well because you'll start insert mode in a different place than you left it.
graywh
C-[ has the same effect as Esc. Having CapsLock remapped with Ctrl, it feels very comfortable for me.
binOr
+5  A: 
  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.
Pramod
Regarding #4: ci( does the same as c%, but the cursor can be anywhere inside the parens.
graywh
+15  A: 

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]

%%lce

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

%cib

Krzysiek Goj
+1  A: 
Kreich
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
+16  A: 

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.

ryan_s
+1 Awesome, I always found those temporary files annoying...
Lin
Ah, and this way I dont have problems running into other's `.swp` file
jeffjose
+4  A: 

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.

shyam
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  A: 

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: http://vimdoc.sourceforge.net/htmldoc/diff.html#:DiffOrig

Jack Senechal
+46  A: 

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

Mapad
Neat, didn't know that one. Btw, try Ctr-r + = (5+4)*3 [Enter] while in insert mode.
Claes Mogren
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
I have my (otherwise useless) Caps Lock key mapped to Esc, so I have an Esc key on the home row. Invaluable with vim.
Martinho Fernandes
I use ctrl-[ to esc.
mike
Hey I bet RAlt+numpad-keysequence 0,2,7 would work too, right? :-)
Warren P
+17  A: 

:%s//replace/g

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.

Brad Parks
+1  A: 

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

:cw
+1  A: 

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!

David.Chu.ca
+9  A: 

COMMENTING A BLOCK OF LINES IN VISUAL MODE

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>
aaronstacy
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
Unless I'm missing something, blocking over lines and hitting I doesn't work (vim 7.1, 7.2, Darwin, Linux)
aaronstacy
+1  A: 

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

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

ididak
+6  A: 

Edit command lines with vim commands under the bash shell

$ set -o vi

Now you can edit command lines using the vim syntax!

Example:

  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
Mapad
+5  A: 
set backup
set backupdir=~/backup/vim

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

smt
very nice, thanks :)
dalloliogm
+19  A: 

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.

A: 

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

Swish
+6  A: 

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:

"+
nayfnu
+2  A: 

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

André
+1  A: 

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
        endif
    endfun
    noremap <silent> gl :call MRUTab()<Cr>
endif
bene
+4  A: 

Jumps.

m[a-z]

Mark location under [a-z]

`[a-z]

Jump to marked location

``

Jump to last location

g;

Jump to last edit

Don't forget '. which jumps to the last change in the file.
MattG
+72  A: 

Using the built-in regions to change text quickly:

ci"    -> Delete 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.

too much php
Awesome, thanks.
Liran Orevi
didn't know about the 'a' and 'i' motions. Very useful.
caspin
A: 

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.

+3  A: 

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.

Quick:

: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")

Aaron H.
The buffer explorer script is also great. See http://vim.sourceforge.net/scripts/script.php?script_id=42
Hamish Downer
+6  A: 

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

!}fmt

to format the current paragraph.

Jon DellOro
+1  A: 

ZZ = :wq
ZQ = :q!

Scottie T
+1  A: 
Ctrl+w Ctrl+]

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

vitule
+3  A: 

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.

phi
+4  A: 
:normal(ize)

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 ^V+ESC on Unix or ^Q+ESC on Windows)

Leonardo Constantino
A: 

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.

Epitaph
+9  A: 

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.

Leonard
+3  A: 

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.

Swaroop C H
+1  A: 

[d to show the definition of a macro

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

Nathan Fellman
A: 

:%s/^V^M^M

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

(^V = Ctrl-V etc.)

mjy
+1  A: 
  • 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
hyperboreean
+1  A: 

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.

Dan Goldstein
+2  A: 

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.

Summary:

  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

f3lix
A: 

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

Reza Jelveh
+1  A: 

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
Casey
+1  A: 

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
Casey
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
A: 

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 "{}" \;')
endfunction
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!

sirlancelot
A: 

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.

anthony
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>kTo provide a 'smooth' version of the same idea.
Leonard
A: 

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

x
y
z

(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);,

etc.

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

x

to

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

Then, if I want to kill emacs, I head over to http://wordwarvi.sourceforge.net

smcameron
A: 

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

http://www.vim.org/scripts/script.php?script_id=1905

Steve Rowe
+1  A: 
vmap // y/"

Search for the visually selected text.

adam
+1  A: 

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
Raim
+4  A: 

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

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

jinxed_coder
+1  A: 

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.

George V. Reilly
+2  A: 

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

:.,+4!sort

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

:'<,'>!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 :-)

Johan
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
+1  A: 

Count the number of matches for the search text:

:%s/search/&/g

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

Jeff
+1  A: 

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 allows you to use an external editor for text boxes, and if you want to go further then investigate the Vimperator. Also, not at version 1.0 yet, but jV makes text areas work like vi.
  • for Thunderbird, the external editor extension allows you to use gVim to write your emails, or you could use Vimperator's sister extension - muttator.

etc.

Hamish Downer
Seems great!! I'll try it. Thanks
Luc M
A: 

Here are some Vim 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).
chardin
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
A: 

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

nightingale2k1
+5  A: 
g-

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!

kaizer.se
+1  A: 

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.

Ton van den Heuvel
A: 

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

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

:%s/\s\+$//g

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

highlight TrailingSpaces ctermbg=grey guibg=grey
match TrailingSpaces /\s\+$/
Diego Pino
A: 

The very best!

:set vb t_vb=

no more beep!

juque
A: 

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
endif 
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]
endfunction

And the bindings:

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

Make vimdiff a great merge tool

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

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.

Ubersoldat
A: 

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.

http://vim.wikia.com/wiki/Autocomplete%5Fwith%5FTAB%5Fwhen%5Ftyping%5Fwords

theIntuitionist
A: 

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

A: 

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
Vincent
+5  A: 

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

:g/TODO:/

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:

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

(p is short for :print).

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

:/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.

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

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

Also see this answer for more examples.

Dave Kirby
A: 
gg=G

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.

+3  A: 

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

--jed

Jed Daniels
+1  A: 

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.

slack3r
A: 
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.

Sridhar Iyer
+1  A: 

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.

Joshua
+2  A: 
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.

otto
+2  A: 

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 is one of the best fixed-width fonts out there.

Damien Wilson
A: 

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

:s/^/#

Removal:

:s/^#//
bobthabuilda
A: 

I can move to a pathfile in my text and press gf. That immediately moves me to that file.

a pathfile could be, /home/john/Desktop/somefile

once in it, ctrl-o takes me back.

So each file can have the most useful file actually written in it making traveling between those designated files veery fast.

Hermann Ingjaldsson
+1  A: 

Search any string you want.
Then type this.

:g//d

or

:v//d

You can also use

:g/pattern/d
:v/pattern/d

Benjamin
You should probably describe what these commands actually do.
ScottS
+8  A: 

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.

phantom-99w
A: 
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.

sica07
+5  A: 

In insert mode:

Ctrl+Y

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.

Wolfgang Plaschg