829

There are a plethora of questions where people talk about common tricks, notably "Vim+ctags tips and tricks".

However, I don't refer to commonly used shortcuts that someone new to Vim would find cool. I am talking about a seasoned Unix user (be they a developer, administrator, both, etc.), who thinks they know something 99% of us never heard or dreamed about. Something that not only makes their work easier, but also is COOL and hackish. After all, Vim resides in the most dark-corner-rich OS in the world, thus it should have intricacies that only a few privileged know about and want to share with us.

9
  • 12
    :Sex Split window and open integrated file explorer (horizontal split) Jun 16, 2014 at 9:51
  • 3
    This question seems to be pretty constructive - by looking at the number of upvotes... , voted to reopen - maybe some even cooler answer arrives - which can be upvoted if useful - hence giving more value to SOF. Ordering the answers by votes I have learned a lot of cool stuff in just 5 minutes... really valuable stuff here, why close something this valuable ? How is this not constructive ?
    – jhegedus
    Oct 17, 2015 at 7:11
  • 7
    Ridiculous that this question is closed. Talk about legalism. Apr 21, 2016 at 16:10
  • 3
    I think this question is very constructive but, more appropriate at Quora.
    – Diogo Melo
    May 20, 2016 at 20:12
  • 3
    Why are there 2(as of now) votes to delete this question? What good would it possibly do?
    – Akavall
    Jan 9, 2017 at 5:52

70 Answers 70

803

Might not be one that 99% of Vim users don't know about, but it's something I use daily and that any Linux+Vim poweruser must know.

Basic command, yet extremely useful.

:w !sudo tee %

I often forget to sudo before editing a file I don't have write permissions on. When I come to save that file and get a permission error, I just issue that vim command in order to save the file without the need to save it to a temp file and then copy it back again.

You obviously have to be on a system with sudo installed and have sudo rights.

19
  • 122
    Arguably, that's even better than running vim as root! Upvoted!
    – Arafangion
    Sep 14, 2009 at 0:06
  • 28
    For a noob, what exactly does tee do? Would someone mind parseing out this command for me?
    – AndyL
    Mar 1, 2010 at 14:38
  • 42
    cmap w!! w !sudo tee %
    – clt60
    May 12, 2011 at 6:09
  • 65
    You should never run sudo vim. Instead you should export EDITOR as vim and run sudoedit. Jul 5, 2011 at 0:49
  • 9
    @maximus: vim replaces % by the name of the current buffer/file.
    – migu
    Sep 2, 2013 at 20:42
634

Something I just discovered recently that I thought was very cool:

:earlier 15m

Reverts the document back to how it was 15 minutes ago. Can take various arguments for the amount of time you want to roll back, and is dependent on undolevels. Can be reversed with the opposite command :later

8
  • 6
    @skinp: If you undo and then make further changes from the undone state, you lose that redo history. This lets you go back to a state which is no longer in the undo stack.
    – ephemient
    Apr 8, 2009 at 16:15
  • 39
    Also very usefull is g+ and g- to go backward and forward in time. This is so much more powerfull than an undo/redo stack since you don't loose the history when you do something after an undo. Jul 21, 2009 at 13:53
  • 9
    You don't lose the redo history if you make a change after an undo. It's just not easily accessed. There are plugins to help you visualize this, like Gundo.vim Nov 29, 2011 at 12:09
  • 589
    Wow, so now I can just do :later 8h and I'm done for today? :P
    – Igor Popov
    Dec 29, 2011 at 6:59
  • 8
    Your command assumes one will spend at least 15 minutes in vim!
    – Déjà vu
    Jul 11, 2014 at 5:14
423

:! [command] executes an external command while you're in Vim.

But add a dot after the colon, :.! [command], and it'll dump the output of the command into your current window. That's : . !

For example:

:.! ls

I use this a lot for things like adding the current date into a document I'm typing:

:.! date
9
  • 75
    This is quite similar to :r! The only difference as far as I can tell is that :r! opens a new line, :.! overwrites the current line.
    – saffsd
    May 6, 2009 at 14:41
  • 7
    An alternative to :.!date is to write "date" on a line and then run !$sh (alternatively having the command followed by a blank line and run !jsh). This will pipe the line to the "sh" shell and substitute with the output from the command.
    – hlovdal
    Jan 25, 2010 at 21:11
  • 45
    :.! is actually a special case of :{range}!, which filters a range of lines (the current line when the range is .) through a command and replaces those lines with the output. I find :%! useful for filtering whole buffers.
    – Nefrubyr
    Mar 25, 2010 at 16:24
  • 3
    @sundar: Why pass a line to sed, when you can use the similar built-in ed/ex commands? Try running :.s/old/new/g ;-)
    – jabirali
    Jul 13, 2010 at 4:30
  • 5
    And also note that '!' is like 'y', 'd', 'c' etc. i.e. you can do: !!, number!!, !motion (e.g. !Gshell_command<cr> replace from current line to end of file ('G') with output of shell_command).
    – aqn
    Apr 26, 2013 at 20:52
320

Not exactly obscure, but there are several "delete in" commands which are extremely useful, like..

  • diw to delete the current word
  • di( to delete within the current parens
  • di" to delete the text between the quotes

Others can be found on :help text-objects

9
  • 8
    dab "delete arounb brackets", daB for around curly brackets, t for xml type tags, combinations with normal commands are as expected cib/yaB/dit/vat etc
    – sjh
    Apr 8, 2009 at 15:33
  • 15
    @Masi: yi(va(p deletes only the brackets
    – Don Reba
    Apr 13, 2009 at 21:41
  • 44
    This is possibly the biggest reason for me staying with Vim. That and its equivalent "change" commands: ciw , ci( , ci" , as well as dt<space> and ct<space> Apr 26, 2009 at 11:11
  • 4
    @thomasrutter: Why not dW/cW instead of dt<space>?
    – Roger Pate
    Oct 12, 2010 at 16:40
  • 9
    @Masi: With the surround plugin: ds(.
    – Roger Pate
    Oct 12, 2010 at 16:43
244

de Delete everything till the end of the word by pressing . at your heart's desire.

ci(xyz[Esc] -- This is a weird one. Here, the 'i' does not mean insert mode. Instead it means inside the parenthesis. So this sequence cuts the text inside parenthesis you're standing in and replaces it with "xyz". It also works inside square and figure brackets -- just do ci[ or ci{ correspondingly. Naturally, you can do di (if you just want to delete all text without typing anything. You can also do a instead of i if you want to delete the parentheses as well and not just text inside them.

ci" - cuts the text in current quotes

ciw - cuts the current word. This works just like the previous one except that ( is replaced with w.

C - cut the rest of the line and switch to insert mode.

ZZ -- save and close current file (WAY faster than Ctrl-F4 to close the current tab!)

ddp - move current line one row down

xp -- move current character one position to the right

U - uppercase, so viwU upercases the word

~ - switches case, so viw~ will reverse casing of entire word

Ctrl+u / Ctrl+d scroll the page half-a-screen up or down. This seems to be more useful than the usual full-screen paging as it makes it easier to see how the two screens relate. For those who still want to scroll entire screen at a time there's Ctrl+f for Forward and Ctrl+b for Backward. Ctrl+Y and Ctrl+E scroll down or up one line at a time.

Crazy but very useful command is zz -- it scrolls the screen to make this line appear in the middle. This is excellent for putting the piece of code you're working on in the center of your attention. Sibling commands -- zt and zb -- make this line the top or the bottom one on the sreen which is not quite as useful.

% finds and jumps to the matching parenthesis.

de -- delete from cursor to the end of the word (you can also do dE to delete until the next space)

bde -- delete the current word, from left to right delimiter

df[space] -- delete up until and including the next space

dt. -- delete until next dot

dd -- delete this entire line

ye (or yE) -- yanks text from here to the end of the word

ce - cuts through the end of the word

bye -- copies current word (makes me wonder what "hi" does!)

yy -- copies the current line

cc -- cuts the current line, you can also do S instead. There's also lower cap s which cuts current character and switches to insert mode.

viwy or viwc. Yank or change current word. Hit w multiple times to keep selecting each subsequent word, use b to move backwards

vi{ - select all text in figure brackets. va{ - select all text including {}s

vi(p - highlight everything inside the ()s and replace with the pasted text

b and e move the cursor word-by-word, similarly to how Ctrl+Arrows normally do. The definition of word is a little different though, as several consecutive delmiters are treated as one word. If you start at the middle of a word, pressing b will always get you to the beginning of the current word, and each consecutive b will jump to the beginning of the next word. Similarly, and easy to remember, e gets the cursor to the end of the current, and each subsequent, word.

similar to b/e, capital B and E move the cursor word-by-word using only whitespaces as delimiters.

capital D (take a deep breath) Deletes the rest of the line to the right of the cursor, same as Shift+End/Del in normal editors (notice 2 keypresses -- Shift+D -- instead of 3)

17
  • 16
    zt is quite useful if you use it at the start of a function or class definition.
    – Nick Lewis
    Jul 17, 2009 at 16:41
  • 9
    vity and vitc can be shortened to yit and cit respectively. Sep 7, 2009 at 8:27
  • 33
    All the things you're calling "cut" is "change". eg: C is change until the end of the line. Vim's equivalent of "cut" is "delete", done with d/D. The main difference between change and delete is that delete leaves you in normal mode but change puts you into a sort of insert mode (though you're still in the change command which is handy as the whole change can be repeated with .). Feb 19, 2011 at 23:49
  • 11
    I thought this was for a list of things that not many people know. yy is very common, I would have thought.
    – Almo
    May 29, 2012 at 20:09
  • 19
    bye does not work when you are in the first character of the word. yiw always does. Jul 3, 2012 at 20:50
213

One that I rarely find in most Vim tutorials, but it's INCREDIBLY useful (at least to me), is the

g; and g,

to move (forward, backward) through the changelist.

Let me show how I use it. Sometimes I need to copy and paste a piece of code or string, say a hex color code in a CSS file, so I search, jump (not caring where the match is), copy it and then jump back (g;) to where I was editing the code to finally paste it. No need to create marks. Simpler.

Just my 2cents.

4
  • 32
    similarly, '. will go to the last edited line, And `. will go to the last edited position
    – aehlke
    Feb 12, 2010 at 1:19
  • 8
    Ctrl-O and Ctrl-I (tab) will work similarly, but not the same. They move backward and forward in the "jump list", which you can view by doing :jumps or :ju For more information do a :help jumplist Apr 16, 2010 at 0:29
  • 20
    You can list the change list by doing :changes Apr 16, 2010 at 0:30
  • Hot dang that's useful. I use <C-o>/<C-i> for this all the time - or marking my place. Jan 30, 2013 at 14:49
189
:%!xxd

Make vim into a hex editor.

:%!xxd -r

Revert.

Warning: If you don't edit with binary (-b), you might damage the file. – Josh Lee in the comments.

7
  • 9
    And how do you revert it back?
    – Christian
    Jul 7, 2009 at 19:11
  • 40
    :!xxd -r //To revert back from HEX
    – Naga Kiran
    Jul 8, 2009 at 13:46
  • 21
    I actually think it's :%!xxd -r to revert it back Nov 14, 2009 at 10:37
  • @JoshLee: If one is careful not to traverse newlines, is it safe to not use the -b option? I ask because sometimes I want to make a hex change, but I don't want to close and reopen the file to do so.
    – dotancohen
    Jun 7, 2013 at 5:50
  • 4
    @dotancohen: If you don't want to close/reopen the file you can do :set binary
    – Bambu
    Nov 23, 2014 at 23:58
138
gv

Reselects last visual selection.

0
123

Sometimes a setting in your .vimrc will get overridden by a plugin or autocommand. To debug this a useful trick is to use the :verbose command in conjunction with :set. For example, to figure out where cindent got set/unset:

:verbose set cindent?

This will output something like:

cindent
    Last set from /usr/share/vim/vim71/indent/c.vim

This also works with maps and highlights. (Thanks joeytwiddle for pointing this out.) For example:

:verbose nmap U
n  U             <C-R>
        Last set from ~/.vimrc

:verbose highlight Normal
Normal         xxx guifg=#dddddd guibg=#111111 font=Inconsolata Medium 14
        Last set from ~/src/vim-holodark/colors/holodark.vim
5
  • 8
    Excellent tip - exactly what I was looking for today. Oct 23, 2009 at 22:09
  • Excellent tip man! How do you get to know these geeky things?
    – Rafid
    Jan 9, 2011 at 7:50
  • 1
    :verbose can also be used before nmap l or highlight Normal to find out where the l keymap or the Normal highlight were last defined. Very useful for debugging! Jul 5, 2014 at 22:08
  • @joeytwiddle Thanks! I added that info to the answer. Jul 7, 2014 at 19:10
  • When you get into creating custom mappings, this will save your ass so many times, probably one of the most useful ones here (IMO)!
    – SidOfc
    Sep 24, 2017 at 11:26
103

:%TOhtml

Creates an html rendering of the current file.

2
102

Not sure if this counts as dark-corner-ish at all, but I've only just learnt it...

:g/match/y A

will yank (copy) all lines containing "match" into the "a/@a register. (The capitalization as A makes vim append yankings instead of replacing the previous register contents.) I used it a lot recently when making Internet Explorer stylesheets.

5
  • counts, counts as i haven't seen this one :)
    – Sasha
    Apr 8, 2009 at 15:51
  • Nice one. Never heard of it... Might be useful :P
    – skinp
    Apr 8, 2009 at 16:53
  • 7
    You can use :g! to find lines that don't match a pattern e.x. :g!/set/normal dd (delete all lines that don't contain set)
    – tsukimi
    May 27, 2012 at 6:17
  • 4
    Sometimes it's better to do what tsukimi said and just filter out lines that don't match your pattern. An abbreviated version of that command though: :v/PATTERN/d Explanation: :v is an abbreviation for :g!, and the :g command applies any ex command to lines. :y[ank] works and so does :normal, but here the most natural thing to do is just :d[elete].
    – Pandu
    Oct 12, 2013 at 8:39
  • You can also do :g/match/normal "Ayy -- the normal keyword lets you tell it to run normal-mode commands (which you are probably more familiar with). Feb 5, 2016 at 17:58
97

Want to look at your :command history?

q:

Then browse, edit and finally to execute the command.

Ever make similar changes to two files and switch back and forth between them? (Say, source and header files?)

:set hidden
:map <TAB> :e#<CR>

Then tab back and forth between those files.

9
  • 137
    I hit q: by accident all the time...
    – Josh Lee
    Sep 22, 2009 at 16:58
  • 12
    Alternatively, from the ex editor (:), you can do CTRL-f to pop up the command history window.
    – Jason Down
    Oct 6, 2009 at 4:14
  • 6
    @jleedev me too. I almost hate this command, just because I use it accidentally way too much.
    – bradlis7
    Mar 23, 2010 at 17:10
  • 10
    q/ and q? can be used to do a similar thing for your search patterns.
    – bpw1621
    Feb 19, 2011 at 15:01
  • 6
    Hitting <C-f> after : or / (or any time you're in command mode) will bring up the same history menu. So you can remap q: if you hit it accidentally a lot and still access this awesome mode.
    – idbrii
    Feb 23, 2011 at 19:07
90

Vim will open a URL, for example

vim http://stackoverflow.com/

Nice when you need to pull up the source of a page for reference.

5
  • 2
    For me it didn't open the source; instead it apparently used elinks to dump rendered page into a buffer, and then opened that. Sep 21, 2010 at 8:07
  • there's error when executed this command Jun 20, 2012 at 10:04
  • 7
    Works better with a slash at the end. Neat trick!
    – Thomas
    Apr 19, 2013 at 21:00
  • @Vdt: It'd be useful if you posted your error. If it's this one: "error (netrw) neither the wget nor the fetch command is available" you obviously need to make one of those tools available from your PATH environment variable. Jun 3, 2013 at 15:23
  • I find this one particularly useful when people send links to a paste service and forgot to select a syntax highlighting, I generally just have to open the link in vim after appending "&raw".
    – Dettorer
    Oct 29, 2014 at 13:47
72

Macros can call other macros, and can also call itself.

eg:

qq0dwj@qq@q

...will delete the first word from every line until the end of the file.

This is quite a simple example but it demonstrates a very powerful feature of vim

8
  • 3
    I didn't know macros could repeat themselves. Cool. Note: qx starts recording into register x (he uses qq for register q). 0 moves to the start of the line. dw delets a word. j moves down a line. @q will run the macro again (defining a loop). But you forgot to end the recording with a final "q", then actually run the macro by typing @q. Apr 16, 2010 at 0:39
  • 2
    I think that's intentional, as a nested and recursive macro.
    – Yktula
    Apr 18, 2010 at 5:32
  • 7
    qqqqqifuu<Esc>h@qq@q Jul 5, 2011 at 1:38
  • 8
    Another way of accomplishing this is to record a macro in register a that does some transformation to a single line, then linewise highlight a bunch of lines with V and type :normal! @a to applyyour macro to every line in your selection. Aug 29, 2011 at 15:33
  • 1
    Macros being used recursively is definitely a design choice, and they will keep doing so until they hit the end of the buffer. If your macro is recursive and stuck in an infinite loop, press ctrl+c to stop it rather than killing your entire vim process.
    – Stun Brick
    Aug 29, 2018 at 10:20
58

Assuming you have Perl and/or Ruby support compiled in, :rubydo and :perldo will run a Ruby or Perl one-liner on every line in a range (defaults to entire buffer), with $_ bound to the text of the current line (minus the newline). Manipulating $_ will change the text of that line.

You can use this to do certain things that are easy to do in a scripting language but not so obvious using Vim builtins. For example to reverse the order of the words in a line:

:perldo $_ = join ' ', reverse split

To insert a random string of 8 characters (A-Z) at the end of every line:

:rubydo $_ += ' ' + (1..8).collect{('A'..'Z').to_a[rand 26]}.join

You are limited to acting on one line at a time and you can't add newlines.

8
  • what if i only want perldo to run on a specified line? or a selected few lines?
    – Sujoy
    May 6, 2009 at 18:27
  • 5
    You can give it a range like any other command. For example :1,5perldo will only operate on lines 1-5. May 6, 2009 at 18:52
  • Could you do $_ += '\nNEWLINE!!!' to get a newline after the current one?
    – Greg
    Jul 2, 2009 at 16:41
  • Sadly not, it just adds a funky control character to the end of the line. You could then use a Vim search/replace to change all those control characters to real newlines though. Jul 2, 2009 at 17:26
  • 4
    Similarly, pydo and py3do work for python if you have the required support compiled in.
    – Derecho
    Mar 14, 2014 at 8:48
58

^O and ^I

Go to older/newer position. When you are moving through the file (by searching, moving commands etc.) vim rember these "jumps", so you can repeat these jumps backward (^O - O for old) and forward (^I - just next to I on keyboard). I find it very useful when writing code and performing a lot of searches.

gi

Go to position where Insert mode was stopped last. I find myself often editing and then searching for something. To return to editing place press gi.

gf

put cursor on file name (e.g. include header file), press gf and the file is opened

gF

similar to gf but recognizes format "[file name]:[line number]". Pressing gF will open [file name] and set cursor to [line number].

^P and ^N

Auto complete text while editing (^P - previous match and ^N next match)

^X^L

While editing completes to the same line (useful for programming). You write code and then you recall that you have the same code somewhere in file. Just press ^X^L and the full line completed

^X^F

Complete file names. You write "/etc/pass" Hmm. You forgot the file name. Just press ^X^F and the filename is completed

^Z or :sh

Move temporary to the shell. If you need a quick bashing:

  • press ^Z (to put vi in background) to return to original shell and press fg to return to vim back
  • press :sh to go to sub shell and press ^D/exit to return to vi back
2
  • With ^X^F my pet peeve is that filenames include = signs, making it do rotten things in many occasions (ini files, makefiles etc). I use se isfname-== to end that nuisance
    – sehe
    Mar 4, 2012 at 21:50
  • 3
    +1 the built-in autocomplete is just sitting there waiting to be discovered. Jul 5, 2014 at 22:10
52

Typing == will correct the indentation of the current line based on the line above.

Actually, you can do one = sign followed by any movement command. ={movement}

For example, you can use the % movement which moves between matching braces. Position the cursor on the { in the following code:

if (thisA == that) {
//not indented
if (some == other) {
x = y;
}
}

And press =% to instantly get this:

if (thisA == that) {
    //not indented
    if (some == other) {
        x = y;
    }
}

Alternately, you could do =a{ within the code block, rather than positioning yourself right on the { character.

5
  • Hm, I didn't know this about the indentation. May 2, 2011 at 0:48
  • No need, usually, to be exactly on the braces. Thought frequently I'd just =} or vaBaB= because it is less dependent. Also, v}}:!astyle -bj matches my code style better, but I can get it back into your style with a simple %!astyle -aj
    – sehe
    Mar 4, 2012 at 22:03
  • 8
    gg=G is quite neat when pasting in something.
    – remmy
    Oct 19, 2013 at 12:12
  • Related: Re-indenting badly indented code at Vim SE
    – kenorb
    Feb 19, 2015 at 11:30
  • @kyrias Oh, I've been doing it like ggVG=. Feb 4, 2016 at 16:16
51
" insert range ip's
"
"          ( O O )
" =======oOO=(_)==OOo======

:for i in range(1,255) | .put='10.0.0.'.i | endfor
8
  • 2
    I don't see what this is good for (besides looking like a joke answer). Can anybody else enlighten me? Nov 16, 2011 at 0:42
  • 2
    open vim and then do ":for i in range(1,255) | .put='10.0.0.'.i | endfor"
    – codygman
    Nov 6, 2012 at 8:33
  • 2
    @RyanEdwards filling /etc/hosts maybe
    – Ruslan
    Sep 30, 2013 at 10:30
  • 28
    This is a terrific answer. Not the bit about creating the IP addresses, but the bit that implies that VIM can use for loops in commands.
    – dotancohen
    Nov 30, 2014 at 14:56
  • 4
    Without ex-mode: i10.0.0.1<Esc>Y254p$<C-v>}g<C-a>
    – BlackCap
    Aug 31, 2017 at 7:54
47

This is a nice trick to reopen the current file with a different encoding:

:e ++enc=cp1250 %:p

Useful when you have to work with legacy encodings. The supported encodings are listed in a table under encoding-values (see help encoding-values). Similar thing also works for ++ff, so that you can reopen file with Windows/Unix line ends if you get it wrong for the first time (see help ff).

6
  • Never had to use this sort of a thing, but we'll certainly add to my arsenal of tricks...
    – Sasha
    Apr 7, 2009 at 18:43
  • great tip, thanks. For bonus points, add a list of common valid encodings. Apr 7, 2009 at 18:44
  • 2
    I have used this today, but I think I didn't need to specify "%:p"; just opening the file and :e ++enc=cp1250 was enough. I Jul 8, 2009 at 19:29
  • would :set encoding=cp1250 have the same effect?
    – laz
    Jul 8, 2009 at 19:32
  • 1
    `:e +b %' is similarly useful for reopening in binary mode (no munging of newlines)
    – intuited
    Jun 4, 2010 at 2:51
40
imap jj <esc>
18
  • 8
    how will you type jj then? :P
    – hasen
    Jun 12, 2009 at 6:08
  • 7
    How often to you type jj? In English at least?
    – ojblass
    Jul 5, 2009 at 18:29
  • 55
    I remapped capslock to esc instead, as it's an otherwise useless key. My mapping was OS wide though, so it has the added benefit of never having to worry about accidentally hitting it. The only drawback IS ITS HARDER TO YELL AT PEOPLE. :)
    – Alex
    Oct 5, 2009 at 5:32
  • 8
    @Alex: definitely, capslock is death. "wait, wtf? oh, that was ZZ?....crap."
    – intuited
    Jun 4, 2010 at 4:18
  • 8
    @ojblass: Not sure how many people ever right matlab code in Vim, but ii and jj are commonly used for counter variables, because i and j are reserved for complex numbers. Oct 3, 2012 at 12:45
37

Let's see some pretty little IDE editor do column transposition.

:%s/\(.*\)^I\(.*\)/\2^I\1/

Explanation

\( and \) is how to remember stuff in regex-land. And \1, \2 etc is how to retrieve the remembered stuff.

>>> \(.*\)^I\(.*\)

Remember everything followed by ^I (tab) followed by everything.

>>> \2^I\1

Replace the above stuff with "2nd stuff you remembered" followed by "1st stuff you remembered" - essentially doing a transpose.

9
  • 4
    Switches a pair of tab-separated columns (separator arbitrary, it's all regex) with each other.
    – chaos
    Apr 7, 2009 at 18:33
  • 42
    This is just a regex; plenty of IDEs have regex search-and-replace.
    – rlbond
    Apr 26, 2009 at 4:11
  • 7
    @rlbond - It comes down to how good is the regex engine in the IDE. Vim's regexes are pretty powerful; others.. not so much sometimes.
    – romandas
    Jun 19, 2009 at 16:58
  • 3
    The * will be greedy, so this regex assumes you have just two columns. If you want it to be nongreedy use {-} instead of * (see :help non-greedy for more information on the {} multiplier) Apr 16, 2010 at 0:32
  • 5
    This is actually a pretty simple regex, it's only escaping the group parentheses that makes it look complicated.
    – mk12
    Jun 22, 2012 at 17:31
31

Not exactly a dark secret, but I like to put the following mapping into my .vimrc file, so I can hit "-" (minus) anytime to open the file explorer to show files adjacent to the one I just edit. In the file explorer, I can hit another "-" to move up one directory, providing seamless browsing of a complex directory structures (like the ones used by the MVC frameworks nowadays):

map - :Explore<cr>

These may be also useful for somebody. I like to scroll the screen and advance the cursor at the same time:

map <c-j> j<c-e>
map <c-k> k<c-y>

Tab navigation - I love tabs and I need to move easily between them:

map <c-l> :tabnext<enter>
map <c-h> :tabprevious<enter>

Only on Mac OS X: Safari-like tab navigation:

map <S-D-Right> :tabnext<cr>
map <S-D-Left> :tabprevious<cr>
2
  • You can also browse files within Vim itself, using :Explore Oct 1, 2009 at 21:33
  • Hi Roman, this is exactly what this mapping does, but assigns it to a "hot key". :)
    – KKovacs
    Oct 15, 2009 at 15:20
29

Often, I like changing current directories while editing - so I have to specify paths less.

cd %:h
3
  • What does this do? And does it work with autchdir?
    – Leonard
    May 8, 2009 at 1:54
  • 2
    I suppose it would override autochdir temporarily (until you switched buffers again). Basically, it changes directory to the root directory of the current file. It gives me a bit more manual control than autochdir does.
    – rampion
    May 8, 2009 at 2:55
  • 1
    :set autochdir //this also serves the same functionality and it changes the current directory to that of file in buffer
    – Naga Kiran
    Jul 8, 2009 at 13:44
28

I like to use 'sudo bash', and my sysadmin hates this. He locked down 'sudo' so it could only be used with a handful of commands (ls, chmod, chown, vi, etc), but I was able to use vim to get a root shell anyway:

bash$ sudo vi +'silent !bash' +q
Password: ******
root#
3
  • 9
    FWIW, sudoedit (or sudo -e) edits privileged files but runs your editor as your normal user.
    – RJHunter
    Jul 21, 2009 at 0:53
  • 12
    yeah... I'd hate you too ;) you should only need a root shell VERY RARELY, unless you're already in the habit of running too many commands as root which means your permissions are all screwed up. Feb 22, 2011 at 15:58
  • 5
    Why does your sysadmin even give you root? :D
    – d33tah
    Mar 30, 2014 at 17:50
26

I often use many windows when I work on a project and sometimes I need to resize them. Here's what I use:

map + <C-W>+
map - <C-W>-

These mappings allow to increase and decrease the size of the current window. It's quite simple but it's fast.

2
  • 19
    There's also Ctrl-W =, which makes the windows equal width.
    – Bill Lynch
    Apr 8, 2009 at 2:49
  • 2
    Don't forget you can prepend numbers to perform an action multiple times in Vim. So to expand the current window height by 8 lines: 8<C-W>+ Jan 29, 2012 at 18:12
25
:r! <command>

pastes the output of an external command into the buffer.

Do some math and get the result directly in the text:

:r! echo $((3 + 5 + 8))

Get the list of files to compile when writing a Makefile:

:r! ls *.c

Don't look up that fact you read on wikipedia, have it directly pasted into the document you are writing:

:r! lynx -dump http://en.wikipedia.org/wiki/Whatever
3
  • 14
    ^R=3+5+8 in insert mode will let you insert the value of the expression (3+5+8) in text with fewer keystrokes.
    – Sudhanshu
    Jun 7, 2010 at 8:40
  • How can I get the result/output to a different buffer than the current?
    – dcn
    Mar 27, 2011 at 10:13
  • Related: How to dump output from external command into editor? at Vim SE
    – kenorb
    Feb 19, 2015 at 11:31
25

Not an obscure feature, but very useful and time saving.

If you want to save a session of your open buffers, tabs, markers and other settings, you can issue the following:

mksession session.vim

You can open your session using:

vim -S session.vim
1
  • 6
    You can also :so session.vim inside vim. Nov 3, 2012 at 13:45
23

Map F5 to quickly ROT13 your buffer:

map <F5> ggg?G``

You can use it as a boss key :).

3
  • 16
    I don't know what you are writing... But surely, my boss would be more curious when he saw me write ROT13 jumble :)
    – sehe
    Mar 4, 2012 at 21:57
  • or to spoof your friends: nmap i ggg?G`` . Or the diabolical: nmap i ggg?G``i!
    – romeovs
    Jun 19, 2014 at 19:22
  • 1
    @romeovs 2nd one is infinite loop, use nnoremap
    – Amit Gold
    Aug 7, 2016 at 10:14
20

I use vim for just about any text editing I do, so I often times use copy and paste. The problem is that vim by default will often times distort imported text via paste. The way to stop this is to use

:set paste

before pasting in your data. This will keep it from messing up.

Note that you will have to issue :set nopaste to recover auto-indentation. Alternative ways of pasting pre-formatted text are the clipboard registers (* and +), and :r!cat (you will have to end the pasted fragment with ^D).

It is also sometimes helpful to turn on a high contrast color scheme. This can be done with

:color blue

I've noticed that it does not work on all the versions of vim I use but it does on most.

3
  • 11
    The "distortion" is happening because you have some form of automatic indentation enabled. Using set paste or specifying a key for the pastetoggle option is a common way to work around this, but the same effect can be achieved with set mouse=a as then Vim knows that the flood of text it sees is a paste triggered by the mouse.
    – jamessan
    Dec 28, 2009 at 8:27
  • 1
    If you have gvim installed you can often (though it depends on what your options your distro compiles vim with) use the X clipboard directly from vim through the * register. For example "*p to paste from the X xlipboard. (It works from terminal vim, too, it's just that you might need the gvim package if they're separate)
    – remmy
    Oct 19, 2013 at 12:15
  • 2
    @kyrias for the record, * is the PRIMARY ("middle-click") register. The clipboard is + Feb 4, 2016 at 16:26
19

I just found this one today via NSFAQ:

Comment blocks of code.

Enter Blockwise Visual mode by hitting CTRL-V.

Mark the block you wish to comment.

Hit I (capital I) and enter your comment string at the beginning of the line. (// for C++)

Hit ESC and all lines selected will have // prepended to the front of the line.

10
  • I added # to comment out a block of code in ruby. How do I undo it. Jun 17, 2009 at 16:56
  • 3
    You can just hit ctrl+v again, mark the //'s and hit x to "uncomment"
    – nos
    Jul 28, 2009 at 20:00
  • 6
    I use NERDCommenter for this.
    – ZyX
    Mar 7, 2010 at 14:18
  • 1
    Commented out code is probably one of the worst types of comment you could possibly put in your code. There are better uses for the awesome block insert. Feb 4, 2016 at 16:23
  • 1
    @Pie because commented out code is dead code. Dead code serves no useful purpose and creates clutter. You think you're preserving code you might want to bring back later, but there's always a better way. You can use your undo history, you can dupe the file, or you can use git, which has this functionality built in (git checkout). As for better uses for block insert, there aren't any set-in-stone. You just use it whenever you have multiple lines where you want to insert the same sequence of characters at the same place. Jul 29, 2019 at 0:31