SO Vault: What are your favorite Vim tricks?

0

Full article

StackOverflow sees quite a few threads deleted, usually for good reasons. Among the stinkers, though, lies the occasionally useful or otherwise interesting one, deleted by some pedantic nitpicker - so I resurrect them. πŸ‘»

Note: Because these threads are older, info may be outdated and links may be dead. Feel free to contact me, but I may not update them... this is an archive after all.


What are your favorite Vim tricks?

Question asked by Joe Van Dyk

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

Comments

Logically equivalent questions to: stackoverflow.com/questions/87299/… – Kent Fredric Sep 18 '08 at 18:08

Every time I come back to read the answers I learn something! – Luc M Aug 16 '11 at 14:21

Not constructive? Really? – ergosys Oct 21 '11 at 20:20

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 Jan 6 '12 at 20:21

I'd thought this was exactly the right sort of question for a SE/SO community wiki… – me_and Jan 27 '12 at 13:03


Answer by 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=%

Comments

You, Sir, are my hero! – Joachim Sauer Dec 16 '08 at 10:24

much better than !w /tmp/whatever, and then remembering to sudo cp it... +1! – Mikeage Feb 22 '09 at 9:23

Inspired. Elegant. – Peter Rowell May 5 '09 at 17:23

I'm in love with this and will use this within the week =) – chauncey Jun 17 '09 at 21:29

Why not just ":w !sudo tee %"? – hhh Aug 29 '09 at 11:20

It doesn't work very cleanly - prompts to reload file and then loses where it was, at least for me. – Artem Russakovskii Sep 28 '09 at 9:35

Using gvim, I get the response sudo: sorry you must have a tty to run sudo. – Scottie T Jan 5 '10 at 13:30

Scottie: Use gksudo or another graphical equivalent in that case. – Roger Pate Jan 12 '10 at 20:14

Could someone explain how this works in detail? – Doppelganger Apr 8 '10 at 14:23

Nevermind my question, if someone is interested just look here: stackoverflow.com/questions/2600783/… – Doppelganger Apr 8 '10 at 15:22

Shouldn't you use /usr/bin/tee? – idbrii Feb 23 '11 at 19:02

You shouldn't use sudo vim. Better define EDITOR as vim (export EDITOR=vim in your .bashrc) and run sudoedit. – Gerardo Marset Apr 11 '11 at 18:09

Here's an improved version of that: github.com/blueyed/dotfiles/blob/… – blueyed Apr 13 '11 at 15:51

blueyed, I tried your version and managed to trash my /etc/hosts with it. Better not to use this, guys. – loevborg Jun 27 '11 at 9:14


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

Comments

Awesome, thanks. – Liran Orevi Aug 9 '09 at 8:43

didn't know about the 'a' and 'i' motions. Very useful. – deft_code Jan 8 '10 at 16:59

I can't believe I've been through over a decade of vim'ming without knowing a/i. Nice tip! – Nik Reiman Nov 23 '10 at 10:37

Oh my god, amazing! This is going to change my life. – terrace Jun 27 '11 at 4:58

These are called text objects by the way. And there's a few more than the number you specified. – ldog Oct 9 '11 at 20:58


Answer by Aristotle Pagaltzis

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.

Comments

That is a most excellent tip. – dowski Nov 14 '08 at 20:42

In addition to <> and "", this also works with [], {}, and (). – Robert Gowland Aug 18 '09 at 13:08

It's really cool. How to remember this : a = all i = inner try these ones : a[ i[ a< i< a{ i{ – nXqd Mar 24 '10 at 12:55

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 Apr 29 '12 at 4:20


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

Comments

Neat, didn't know that one. Btw, try Ctr-r + = (5+4)*3 [Enter] while in insert mode. – Claes Mogren Dec 11 '08 at 9:48

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 Nov 14 '09 at 16:12

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 Jan 9 '10 at 21:16

I use ctrl-[ to esc. – Michael Ekoka Feb 7 '10 at 15:51

Hey I bet RAlt+numpad-keysequence 0,2,7 would work too, right? :-) – Warren P Jul 15 '10 at 15:54

How did you achieve this "button" effects in your answer? – Sarwar Erfan Feb 8 '11 at 10:23

Sarwar, it's <kbd> tag, you can see it when you try to edit the main post – number5 Feb 24 '11 at 0:32

I have giant hands so I just reach up to esc with my left pinky! – z8000 Jun 27 '11 at 2:30

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 Jun 28 '11 at 1:34

It is really awesome!!!! – SΕ‚awosz Aug 25 '11 at 19:27


Answer by Adam Neal

*

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

Comments

One of the simplest yet greatest features – Ed Guiness Jan 20 '09 at 9:13

How do you clear the search so it stops highlighting? – Albert Feb 13 '09 at 15:58

:nohlsearch will temporarily turn off search highlighting. Happy Vimming! vimdoc.sourceforge.net/cgi-bin/vimfaq2html3.pl#11.1 – Adam Neal Feb 13 '09 at 21:41

Cool! Really useful. Was this documented somewhere? – Luis May 9 '09 at 17:25

Can't believe I have used vim this long and didn't know this one – Robert Swisher Aug 6 '09 at 23:17

Also '#' does the same, but backwards. – dalloliogm Aug 14 '09 at 10:42

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 Jan 30 '10 at 9:59

It does really help :) – nXqd Mar 24 '10 at 12:56

Holy crap I had no idea. Awesome! – rossipedia May 17 '10 at 23:21

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> – idbrii Feb 23 '11 at 19:04

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 Jan 18 '12 at 21:43


Answer by Dominic Dos Santos (Sep 18, 2008)

[I

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

Comments

quite cool tip! Would be interesting to know the vim help topic for this. – amit Jan 6 '11 at 7:30

@Amit: :help [ and scroll down a bit. – Fred Nurk Jan 11 '11 at 18:31


Answer by Rich Adams (Sep 19, 2008)

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.

Comments

Great if it's ugly and you don't want to check it back into source control later.. – Adam Hawes Feb 19 '09 at 4:40

gg=G`` will format the file and take you back to where you were. – NotDan Dec 3 '10 at 19:20

This is a feature i really need – lucapette Jan 7 '11 at 22:26

So beautiful! :) – rturrado Jan 19 '11 at 15:36


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

Comments

Lucas, can you explain how to do this. c-n/c-p doesn't seem to do for me what you said. thanks. – user15071 Oct 26 '08 at 3:38

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 Nov 7 '08 at 14:21

I usually map this to <C-SPace> as a quick auto-complete. – Ayman Aug 19 '09 at 5:48

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 Sep 15 '11 at 4:26


Answer by Ludvig A. Norin

. (period)

Repeats the previous change

Comments

This one is really useful :) – nXqd Apr 22 '10 at 23:58

I'm appreciating the power of this a lot more lately. – justinxreese Jun 27 '11 at 3:02


Answer by jW.

:%s/search/replace/g 

Global Search and replace

Comments

:%s/search/replace/gc The 'c' makes it prompt you at each replace instance – Mark Biek Sep 18 '08 at 18:32

its not 'global' its just inside the current buffer. for global look for Greplace plugin for vim – Vitaly Kushner Jun 27 '11 at 18:45

@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 Aug 17 '11 at 12:59

Use this with args and argdo to apply the search and replace to more than one file! – chandsie Aug 18 '11 at 15:49


Answer by Scottie T

:e!

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

Comments

I always just use 'u'ndo to fix bad search/replaces :) – hark Nov 6 '08 at 3:20

Reloading the file will destroy your undo history for the buffer. I try to avoid that at all cost. – Aristotle Pagaltzis Nov 23 '08 at 0:52

For me :e is very useful when watching an active logfile. – Marcin Dec 18 '08 at 19:19

@Marcin, why not just use tail -f | less? – Christian Mann May 25 '12 at 21:12

@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 Jun 4 '12 at 15:16


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

Comments

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 Jan 30 '10 at 10:05

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 Apr 1 '10 at 2:27

@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 May 7 '11 at 8:36


Answer by jug

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)

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)

0fxqal2xbpfxq2u0qbfx4@axbpq3u0qc6@b
q9@c

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.

Comments

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 Sep 28 '08 at 16:12

I got some problems editing. My original Edit summary was "added example of a complex macro". – j.p. Jan 7 '12 at 19:27


Answer by Ludvig A. Norin (Sep 18, 2008)

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

Comments

for file in *.cpp – Fred Nurk Jan 11 '11 at 18:35

Why not just :set ff=unix, then later :w? – blueyed Apr 13 '11 at 16:29


Answer by Lucas S. (Sep 18, 2008)

=%

Indents the block between two braces/#ifdefs

Comments

This doesn't work for me... But =G does... – Aaron H. Nov 14 '08 at 20:07

or gqq for the current line. – vitule Dec 16 '08 at 10:14

== for current line (just 2 keystrokes) – Cyber Oliveira Dec 18 '08 at 18:07

It does not seem to work well for Python. – Reinstate Monica Oct 21 '09 at 12:36

or {=} for current paragraph, etc. – A B Apr 19 '10 at 1:41

@Aaron, you have to have the cursor positioned on one of the curly braces before hitting =%. – Robert Gowland Jun 17 '10 at 13:50

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 Apr 21 '11 at 15:42


Answer by mghaoui (Nov 10, 2008)

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.

Comments

Duplicate of stackoverflow.com/questions/95072/… – Fred Nurk Jan 11 '11 at 18:37

It was edited on Oct 5 '10 at 9:49. It was posted on Sep '08. – Gerardo Marset Jun 21 '11 at 23:46

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 Feb 24 '12 at 10:50


Answer by Brad Parks

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


Answer by Krzysiek Goj (Sep 28, 2008)

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


Answer by rgcb (Sep 18, 2008)

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

Comments

An easier way to delete lines matching a pattern is with :global. :g/foo/d – graywh Feb 10 '09 at 22:39

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 Jun 27 '11 at 2:30


Answer by ryan_s (Oct 09, 2008)

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.

Comments

+1 Awesome, I always found those temporary files annoying... – Lin Oct 8 '09 at 14:49

Ah, and this way I dont have problems running into other's .swp file – Jeffrey Jose Apr 1 '10 at 2:31

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 Jan 2 '11 at 5:20


Answer by poisonedbit

Copy to system clipboard:

"+y

Paste from system clipboard:

"+p

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

gj
gk

And for my favourite:

:Sex

Split and explore!

Comments

+1 for moving between the wrapped lines! – j.p. Jan 7 '12 at 20:03


Answer by Joe Van Dyk (Sep 18, 2008)

 :mak

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

Comments

:make is the command. Unambiguous shorter terms are allowed, so :mak works. – Paul Biggar Aug 2 '09 at 9:54

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 Apr 1 '10 at 2:29


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

Comments

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 Mar 14 '12 at 19:21


Answer by Lucas Oman (Sep 18, 2008)

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

Comments

I used something similar for a while but found it doesn't like complex window splits. :( – matpie Jan 25 '09 at 10:06

Good to know. I rarely use splits; I prefer tabs. – Lucas Oman Feb 14 '09 at 15:46


Answer by Ronny Brendel (Sep 19, 2008)

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

Comments

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 Oct 20 '08 at 19:15

Enter blockwise visual mode through <C-v>, select the rectangle of lines-by-columns you want do delete, and hit `d'. – ngn Oct 26 '08 at 19:35


Answer by WolfgangP (Oct 31, 2010)

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.

Comments

Use Ctrl-E to insert the character below. – blueyed Apr 13 '11 at 16:33


Answer by A Lee

Ctrl+]

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

Ctrl+T

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.


Answer by Kreich

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


Answer by Scottie T

:g/search/p

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

Comments

Did not knew that one. Very usefull. Thank you. – Oli Feb 26 '09 at 11:27

Did not knew that one. Very usefull. Thank you. (dido) – Luis May 9 '09 at 17:32

Along with its cousin :v which applies to non matching lines. – ojblass Jun 20 '09 at 18:24

works also without p, as :g/search/ and with # you get the line number as :g/search/# – user2427 Nov 30 '11 at 12:51

Wow. wow and re-wow! – Luc M Dec 1 '11 at 15:57


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

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

: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 for more examples.


Answer by aaronstacy (Nov 06, 2008)

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>

Comments

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 Jan 27 '09 at 14:32

This doesn't seem much different from visual blocking over a lines, then hitting I and then inserting whatever character you want. – Nikron Feb 23 '09 at 7:19

Unless I'm missing something, blocking over lines and hitting I doesn't work (vim 7.1, 7.2, Darwin, Linux) – aaronstacy Mar 15 '09 at 21:53

Note that visual-block mode is different from visual mode. ctrl-v is the default key to enter visual-block mode. – jkerian Nov 12 '10 at 17:43

I recommend using tcomment instead. – blueyed Apr 13 '11 at 16:32


Answer by Mapad

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

Comments

@Madpad: Amazing! – j.p. Jan 7 '12 at 20:34


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


Answer by Adam Neal

%

Brace/parentheses match.

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

Comments

MatchIt plugin can make it even better (eg. jump between matching opening and closing XML/HTML tags). – Adam Byrtek Dec 5 '08 at 22:27


Answer by Jon DellOro (Nov 24, 2008)

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

!}fmt

to format the current paragraph.


Answer by DustinB (Sep 18, 2008)

Read contents of an external command into the doc:

:r !ls


Answer by Kreich (Sep 18, 2008)

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)

Comments

It's just ~ not shift-~ It's just that ~ is shift-# on a UK keyboard (and probably shifted on a US one too) – Draemon Nov 21 '08 at 18:49

ALT-GR ~ on swedish – some Feb 1 '09 at 7:34

You can use visual mode ('v') to select large blocks to change, too. – Bernard Jul 22 '09 at 11:03


Answer by PEELY (Sep 19, 2008)

Delete all blank lines in a file:

:g/^$/d

Comments

Delete all blank lines in a file (even with only spaces). :v/./d – graywh Feb 10 '09 at 22:44


Answer by Christopher Cashell (Sep 18, 2008)

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

Comments

:help modeline for info. – sykora Jan 27 '09 at 14:29


Answer by nayfnu (Nov 13, 2008)

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:

"+

Answer by arcanex (Nov 13, 2008)

Jumps.

m[a-z]

Mark location under [a-z]

`[a-z]

Jump to marked location

``

Jump to last location

g;

Jump to last edit

Comments

Don't forget '. which jumps to the last change in the file. – MattG Sep 22 '09 at 15:01


Answer by Cyber Oliveira

: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 ctrlv+ESC on Unix or ctrlq+ESC on Windows)

Comments

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 Aug 17 '11 at 13:46


Answer by smt (Nov 10, 2008)

set backup
set backupdir=~/backup/vim

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

Comments

very nice, thanks :) – dalloliogm Aug 14 '09 at 10:45


Answer by Swaroop C H (Jan 20, 2009)

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.

Comments

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 Jan 2 '11 at 5:39


Answer by f3lix (Jan 30, 2009)

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


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


Answer by Pramod (Sep 28, 2008)

  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.

Comments

Regarding #4: ci( does the same as c%, but the cursor can be anywhere inside the parens. – graywh Feb 10 '09 at 22:42


Answer by 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)
  %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.


Answer by u0b34a0f6ae (Sep 29, 2009)

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!


Answer by Liran Orevi

:%j 

To join all lines into a single line.

Comments

when did you ever need this? – vitule Dec 16 '08 at 10:19

you missed a leading ":", otherwise it becomes a completely different command :) – Cyber Oliveira Dec 18 '08 at 19:04

@LΓ©o thanks, fixed it now. – Liran Orevi Dec 1 '09 at 0:24


Answer by Ludvig A. Norin (Sep 18, 2008)

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

Comments

d7d works too, and it should be faster as you don't have to press d twice in a row. – Gerardo Marset Mar 31 '11 at 13:34


Answer by Chuck (Sep 18, 2008)

v

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


Answer by camflan (Sep 28, 2008)

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.

Comments

C-[ has the same effect as Esc. Having CapsLock remapped with Ctrl, it feels very comfortable for me. – binOr Oct 9 '09 at 9:54


Answer by shyam (Oct 18, 2008)

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.

Comments

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 Feb 10 '09 at 22:46


Answer by Jack Senechal (Oct 21, 2008)

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


Answer by phi (Dec 17, 2008)

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.


Answer by Jed Daniels (Mar 19, 2010)

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


Answer by igrigorik (Jun 27, 2011)

VimGolf @ http://vimgolf.com

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.


Answer by Ludvig A. Norin (Sep 18, 2008)

u <-- undo :-)

Comments

And ctrl-r redo.. for those times you undo a little too much – MattG Sep 22 '09 at 15:03

And -> :earlier 15m – Aaron H. Oct 22 '10 at 16:28


Answer by jpeacock (Sep 19, 2008)

vim -o file1 file2 ...

To open multiple files at once in separate panes.

Comments

also, -O to open in vertical panes and -p to open in tabs. (I like this one a lot ;) – David Winslow Mar 19 '10 at 22:49


Answer by Aaron H. (Nov 14, 2008)

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


Answer by Otto (May 06, 2010)

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.


Answer by amit (Jan 06, 2011)

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

Comments

Check a.vim plugin. – Luc Hermitte Jan 6 '11 at 9:14


Answer by 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"'
    checktime
endfunction

A program named HSTART 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.)


Answer by CMS (Sep 18, 2008)

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.


Answer by hafbaked (Sep 18, 2008)

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


Answer by skiphoppy (Sep 18, 2008)

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.


Answer by ernie (Sep 19, 2008)

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


Answer by Bauna (Sep 19, 2008)

cw

"change word" while editing config files!


Answer by ryan_s (Sep 19, 2008)

#

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

Comments

And * forwards `) – Liran Orevi Dec 1 '09 at 0:27


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

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


Answer by Sridhar Iyer (Sep 23, 2008)

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


Answer by David.Chu.ca (Nov 06, 2008)

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!


Answer by AndrΓ© (Nov 13, 2008)

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


Answer by Nathan Fellman (Jan 20, 2009)

[d to show the definition of a macro

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


Answer by Dan Goldstein (Jan 27, 2009)

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.


Answer by adam (Feb 13, 2009)

vmap // y/"

Search for the visually selected text.


Answer by raimue (Feb 19, 2009)

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

Answer by Jeff (Feb 25, 2009)

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.


Answer by Johan (Feb 22, 2009)

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

Comments

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 Feb 22 '09 at 10:24


Answer by Joshua (Apr 18, 2010)

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.


Answer by Damien Wilson (May 17, 2010)

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.


Answer by amit (Jan 08, 2011)

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

 A Lazy Brown Fox

to

 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.

Using

   set incsearch 
   set hlsearch 

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


Answer by EmmEff (Sep 18, 2008)

gqip

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

Comments

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 Oct 26 '08 at 19:51


Answer by rgcb (Sep 18, 2008)

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


Answer by leeand00 (Sep 18, 2008)

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


Answer by Jason Moore (Sep 18, 2008)

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


Answer by unexist (Sep 18, 2008)

Vimrc to highlight tabs:

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


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

Comments

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 Oct 26 '08 at 20:02


Answer by Cliff (Sep 19, 2008)

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


Answer by Kreich (Oct 02, 2008)

:vsplit [filename]

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

opens an additional page, horizontally splitting the current page.

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


Answer by mempko (Oct 27, 2008)

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

Answer by ididak (Nov 07, 2008)

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.


Answer by Benedikt Waldvogel (Nov 13, 2008)

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

Answer by Scottie T (Dec 05, 2008)

ZZ = :wq
ZQ = :q!


Answer by vitule (Dec 16, 2008)

Ctrl+w Ctrl+]

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


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

Answer by cmcginty (Feb 09, 2009)

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

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

Answer by smcameron (Feb 10, 2009)

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


Answer by George V. Reilly (Feb 22, 2009)

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.


Answer by Ton van den Heuvel (Oct 07, 2009)

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.


Answer by juque (Oct 27, 2009)

The very best!

:set vb t_vb= 

no more beep!


Answer by chardin

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

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


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

Comments

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 Feb 28 '09 at 2:58


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


Answer by ground5hark (May 17, 2010)

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/^#//

Answer by sica07 (Sep 23, 2010)

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.


Answer by OneOfOne (Jan 19, 2011)

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


Answer by omab (Jun 27, 2011)

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>

Answer by Ludvig A. Norin (Sep 18, 2008)

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


Answer by Joe Van Dyk (Sep 18, 2008)

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.


Answer by Ludvig A. Norin (Sep 18, 2008)

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


Answer by Paul Brinkley (Sep 18, 2008)

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>

Answer by Max Cantor (Sep 19, 2008)

http://dotfiles.org/.vimrc

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


Answer by Artur Siara (Sep 19, 2008)

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 % user@example.com:~/some_folder/

Answer by Mapad

Go through last edits after you scrolled:

gi

insertion where the cursor last used to be before when quit insertion mode.

g;

go to the previous position of cursor in change list

g,

go to the next position of cursor in change list

Undo/Redo what you did:

:undol

list all branches of the changes you made

10 g- or 10 u

undo 10 previous change

10 g+ or 10 Ctrl+R

redo 10 previous changes

:later 1h

go 1 hour later

:earlier 1h

go 1 hour back


Answer by Robert Swisher (Nov 12, 2008)

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


Answer by user35978 (Nov 13, 2008)

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.


Shared with attribution, where reasonably possible, per the SO attribution policy and cc-by-something. If you were the author of something I posted here, and want that portion removed, just let me know.

Author

Grant Winney

Is there anything more satisfying than sharing knowledge? Of teaching someone and witnessing their "ah ha" moment? I usually write about tech, but no promises. I hope you find something interesting!



Comments