396

I'm learning new commands in Vim all the time, but I'm sure everyone learns something new once in a while. I just recently learned about this:

zz, zt, zb - position cursor at middle, top, or bottom of screen

What are some other useful or elegant commands you wish you'd learned ages ago?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Lin
  • 5,235
  • 8
  • 31
  • 30
  • 51
    technically, zz, zt, zb are positioning the *screen* with the cursor at the middle / top / bottom. to position the *cursor* at the middle / top / bottom use M, H, or L. Both sets of commands are useful! – Peter Aug 18 '09 at 00:37
  • 1
    Reading this post months or a year ago has since helped me every day. dap is something I use to move paragraphs multiple times an hour, thanks to this post. – dansch Nov 01 '13 at 11:49
  • 37
    I have never picked up so many tricks from a page that has been marked as non constructive :) Thanks all. – Tasos Bitsios Feb 25 '14 at 12:50

45 Answers45

332

I really wish I'd known that you can use Ctrl+C instead of Esc to switch out of insert mode. That's been a real productivity boost for me.

unrealapex
  • 578
  • 9
  • 23
yalestar
  • 9,334
  • 6
  • 39
  • 52
  • 97
    I remapped my Caps-Lock to an Esc. That's both easier than the normal Esc and Ctrl-C – Kasper Aug 16 '09 at 14:16
  • @kmm: I remap my capslock to control, that's much easier than your solution. And works outside vim. – Adriano Varoli Piazza Aug 19 '09 at 12:28
  • 31
    another popular was is to use 'jj' for ESC. I like this approach so far. :map! jj – claytron Sep 29 '09 at 21:44
  • 28
    You can also use CTRL-[ (which I like because it's both little fingers... just a little rotation of both hands). – Jason Down Oct 06 '09 at 04:33
  • 44
    use 'jk' as a variant on @claytron's. if you unknowingly are in INSERT mode already, jk leaves you where you were, so you can hit it whenever (credit: someone else...not my idea). – Kyle Cureau Nov 30 '12 at 07:24
  • I have a keyboard where i don't use two keys: right-pinkie and the one on the right of that. [Portuguese Keyboard Layout](http://upload.wikimedia.org/wikipedia/en/c/cf/KeyboardLayout-Portuguese.png) – alexpinho98 Jul 27 '13 at 12:10
  • I do "imap lkj " because sometimes I use 'jj' and 'jk' as variables or actual text--plus it has a really natural feel--just rolls off the fingers.. :) – Brian Jan 19 '14 at 21:43
  • 6
    This is a great tip, though be careful: it breaks VISUAL BLOCK functionality. You have to press ESC instead of Ctrl-C to properly insert a block new text, rather than just on a single line. – gsk Feb 11 '14 at 19:17
  • 11
    Keep in mind that using `Ctrl-c` to exit out of insert mode does not trigger the `InsertLeave` autocommand event. If you have any plugins or scripts depending on it, they won't work. See `:h i_CTRL-C`. – sharat87 Mar 26 '14 at 03:22
  • 3
    i prefer CTRL-[, it's standard vim hotkey that works everywhere – dredozubov Jun 05 '14 at 13:04
  • 6
    @Emile I like to map both `jk` and `kj` to so that I can just hit both and it doesn't matter which one I happened to press first. It's almost like a single keystroke. – tckmn Aug 04 '14 at 10:56
  • 4
    @gsk @Shrikant It looks like CTRL-[ works with both visual block and `InsertLeave`. Thanks to the comments on this answer, that's what I'm going to stick with (I'll have to un-learn ESC...). – Brian McCutchon Aug 31 '14 at 03:53
  • 2
    Just gonna be "that guy" here and slightly contradict the claims that `jk` leaves you where you were in normal mode. This is not true when you are in the first xor last line of the buffer. (Though it *is* true if they are one and the same, as you wouldn't have anywhere to go but to stay put.) – Victor Zamanian Feb 22 '16 at 21:18
  • UK keyboard layout user here. I remap 'Alt-Gr' to escape so it's under my right thumb. It makes vim much easier to drive. – Jim Johnson Jun 10 '16 at 18:15
205

The most recent "wow" trick that I learnt is a method of doing complicated search-and-replace. Quite often in the past, I've had a really complicated regexp to do substitutions on and it's not worked. There is a better way:

:set incsearch             " I have this in .vimrc
/my complicated regexp     " Highlighted as you enter characters
:%s//replace with this/    " You don't have to type it again

The "trick" here (for want of a better word) is the way that you can use the search to create the regexp (and 'incsearch' highlights it as you enter characters) and then use an empty pattern in the substitution: the empty pattern defaults to the last search pattern.

Example:

/blue\(\d\+\)
:%s//red\1/

Equivalent to:

:%s/blue\(\d\+\)/red\1/

See:

:help 'incsearch'
:help :substitute
DrAl
  • 70,428
  • 10
  • 106
  • 108
  • 1
    wow... I've been looking for something like this – figurassa Feb 24 '10 at 04:38
  • 1
    yeah, I wish that I knew abou this sooner. But then again, that's what I say about everything I learn that is new in vim. – Robert Massaioli Jun 16 '10 at 07:28
  • 26
    For anyone really loving this, try hitting `/` to insert the last search query. (See `:help i_CTRL-R`) Really useful for similar to above, but you want to capture part of the search results. (like this: `%s:/\\([fF]rank\\) and mary/marie and \1/g`) – idbrii Sep 19 '10 at 21:50
  • 4
    `:%s//...` also works with `*` (search word under cursor). A plugin called visual-star-search extends the functionality of `*` to match the whole text of a visual selection which makes it easy to search & replace the selected text, e.g. `v3e` (visually select 3 words) `*` (search) and `:%s//replacement/g` (replace all occurences with "replacement"). I use this so often that I have a mapping for the global substitution command: `:nmap s :%s///g`. – Patrick Oscity Nov 10 '13 at 21:19
  • 1
    @idbrii since people reading may be Vim noobs (me), the `%s:` should be `:%s`, and for my system, I needed `\(\)` instead of `\\(\\)` – Charlie Gorichanaz Aug 06 '17 at 18:13
166

I created this reference of my most used command for a friend of mine:

select                                   v
select row(s)                            SHIFT + v
select blocks (columns)                  CTRL  + v
indent selected text                     >
unindent selected text                   <
list buffers                             :ls
open buffer                              :bN (N = buffer number)
print                                    :hardcopy
open a file                              :e /path/to/file.txt
                                         :e C:\Path\To\File.txt
sort selected rows                       :sort
search for word under cursor             *
open file under cursor                   gf
  (absolute path or relative)
format selected code                     =
select contents of entire file           ggVG
convert selected text to uppercase       U
convert selected text to lowercase       u
invert case of selected text             ~
convert tabs to spaces                   :retab
start recording a macro                  qX (X = key to assign macro to)
stop recording a macro                   q
playback macro                           @X (X = key macro was assigned to)
replay previously played macro *         @@
auto-complete a word you are typing **   CTRL + n
bookmark current place in file           mX (X = key to assign bookmark to)
jump to bookmark                         `X (X = key bookmark was assigned to
                                             ` = back tick/tilde key)
show all bookmarks                       :marks
delete a bookmark                        :delm X (X = key bookmark to delete)
delete all bookmarks                     :delm!
split screen horizontally                :split
split screen vertically                  :vsplit
navigating split screens                 CTRL + w + j = move down a screen
                                         CTRL + w + k = move up a screen
                                         CTRL + w + h = move left a screen
                                         CTRL + w + l = move right a screen
close all other split screens            :only

*  - As with other commands in vi, you can playback a macro any number of times.
     The following command would playback the macro assigned to the key `w' 100
     times: 100@w

** - Vim uses words that exist in your current buffer and any other buffer you may have open for auto-complete suggestions.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
brian newman
  • 3,964
  • 5
  • 25
  • 24
  • You list "~X" to go to the mark with name X. That doesn't work for me - instead I use "'X" (single quote). –  Aug 20 '09 at 06:38
  • Wow. Your absolutely right. When I was typing out the guide I guess my eye only seen the tilde and glossed over the back tick. I will update accordingly. Thanks for the heads up. – brian newman Aug 20 '09 at 12:45
  • I saw you are using u and U to convert text case. You can use ~ to toggle the case instead. – rg88 Oct 01 '09 at 09:20
  • 5
    this list is nice, but I really want to know how did you draw this table? with VIM? which plugin? I'm looking for one currently. – Kent Mar 11 '10 at 14:34
  • 6
    I used VIM, but no plugin. However; using the select block feature made it relatively easy. Glad you found the list useful! ~brian – brian newman Mar 12 '10 at 13:29
  • 11
    Ctrl-Q for block-selection is a specificity of mswin.vim that allows CTRL-V to paste. Most vim users would consider this evil and disable mswin.vim. "+P or Ctrl-R + is not that hard to type to insert clipboard contents. – Benoit Sep 16 '11 at 13:54
  • thank you for shift-v, u and U! @gaoshan88, ~ is toggling the case, but sometimes I need to set case explicitely for mixed case text, so u and U are very useful. – wobmene Feb 20 '12 at 14:14
  • Omg, I've been using gu/gU for changing the case all these years, when I just needed the u/U in selection mode. I guess you can learn something new every day. – José Ramón Nov 13 '15 at 11:10
148

gi switches to insertion mode, placing the cursor at the same location it was previously.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Cyber Oliveira
  • 8,178
  • 4
  • 28
  • 18
  • 32
    I was so happy when I found out about `g;` now this moves me to tears :-) – Patrick Oscity Sep 21 '13 at 20:15
  • @longdeqidao not at all. It returns to the last insertion point. So you can scroll at your hearts content and it'll pull you back to where you were last inserting. – Cyber Oliveira Aug 02 '15 at 02:22
  • 9
    FYI, g; (which @PatrickOscity referred to above) puts the cursor at the place an edit was made. You can use it multiple times to go back in history. Noting this here because my vim help doesn't mention this for some odd reason. – PonyEars Aug 07 '15 at 14:16
  • 14
    Vim's intuitiveness never ceases to impress me. Since @PonyEars mentioned `g;` I tried if the "opposite" of it would be `g,` and lo and behold, we can go back and forward! – Cyber Oliveira Aug 07 '15 at 20:29
  • `a` is shorter. :) But `gi` is very intuitive indeed, with `g` usually being an opposite operation. – user2609980 Jul 21 '16 at 16:24
  • @ErwinRooijakkers a is completely different to gi though. –  Jun 02 '17 at 12:15
112
:q!

I wish I knew that before I started vi for the first time.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michał Piaskowski
  • 3,800
  • 2
  • 34
  • 46
  • 24
    as an emacs guy, that is the funniest comment i've read. not sure you meant it to be though. You made me happy today. – pjammer Apr 10 '12 at 18:53
  • 31
    I remember trying vim and emacs for the first time on the same day, not knowing how to exit either. I thought to myself _what the heck is wrong with these people!?_ – physicsmichael Dec 31 '13 at 18:40
  • 14
    +1. The first time you start vim, the default message should be "write :q to quit". I would have save so much time lol – José Ramón Jul 01 '14 at 10:26
  • 2
    @JoséRamón But it _does_ show it on the screen by default if you enter vim without opening a file. Was this added recently? I can clearly remember trying vim years ago and it was there already. It also tells you to use `:q!` if you try to quit without saving the buffer. – mechalynx Sep 08 '14 at 23:13
  • 5
    @ivy_lynx yes, you may be right, but only if you open vim without files. Usually, the first time you open vim is because you need to edit a config file in Unix, so you write "$ vim file" and you can't find your way out. Or am I the only one? – José Ramón Sep 09 '14 at 06:52
  • @JoséRamón I think your experience is quite rare - considering nano is available and that most that are new to unix will probably not know about either one, I think it's a bit unlikely that the first time you run vim it will be with any files open. That said, it could have some hint for how to quit or get help but, I feel the design, as it is, is quite elegant and I'd do the same. From a design perspective, how many times will you expect someone who doesn't know vim, to deliberately use vim to edit a text file? And from the command line no less. If you panic, you can always close the terminal. – mechalynx Sep 09 '14 at 10:48
  • 1
    @Lernkurve Apparantly Apple very nearly launched the :qxxqa!!phone and didn't notice the i until it was too late. –  Sep 30 '15 at 12:38
  • troll. may was well have said `:! rm -rf /` – danielpops May 02 '16 at 20:28
  • 2
    @danielpops It's not a troll, it's a running joke that people who open vim for the first time (or accidentally) often won't know how to exit it again. – jazzpi Sep 21 '16 at 11:39
  • I sense a pattern that has roots from long ago - "Let's look at a typical novice's session with the mighty ed:" https://www.gnu.org/fun/jokes/ed-msg.html – aportr Dec 15 '16 at 15:08
  • @danielpops How can you not see this is a joke? Who is being trolled? –  Jun 02 '17 at 12:29
  • @DrEval why is it completely different? – user2609980 Jun 03 '17 at 13:07
  • @ErwinRooijakkers Huh? –  Jun 06 '17 at 08:23
  • @DrEval I replied to the difference between `gi` and `a`. You said, somewhere, that they were "completely different". – user2609980 Jun 06 '17 at 22:28
  • @ErwinRooijakkers Well, they are. You're unlikely to ever be in a position where you can choose one over the other. –  Jun 07 '17 at 06:37
  • @DrEval, how are they different? – user2609980 Jun 09 '17 at 10:08
  • @ErwinRooijakkers One appends text after the current cursor location, and the other moves the cursor to the last point you edited text and puts you into insert mode. Given that you didn't add your comment in the correct position, asking underneath an entirely different answer, one can see how this distinction might be lost on you! –  Jun 09 '17 at 10:47
  • Oooh indeed. :) – user2609980 Jun 12 '17 at 12:06
  • using ZQ instead. – logbasex Jan 13 '21 at 09:25
57

^X-F completes using filenames from the current directory. No more copying/pasting from the terminal or painful double checking.

^X-P completes using words in the current file

:set scrollbind forces one buffer to scroll alongside another. e.g. split your window into two vertical panes. Load one file in each (perhaps different versions of the same file). Do :set scrollbind in each. Now when you scroll in one, both panes will scroll together. Ideal for comparing files.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
  • How to disable the scrollbind once I've enabled it? – Amjith Aug 14 '09 at 14:23
  • 2
    *jinxed_coder*: `:set noscb` to turn it off and use `:set scb` to turn it on (not `:scrollbind`). `:h scrollbind` – jmdeldin Aug 14 '09 at 16:20
  • Whoops. Corrected for ':set scrollbind'. – Brian Agnew Aug 14 '09 at 16:24
  • 7
    **^X-P** completes with preference to previous words in the file, **^X-N** with preference to the next words in the file. – u0b34a0f6ae Sep 14 '09 at 18:15
  • You can also diff files by opening file1 and running `:diffsplit file2` or just starting vim with `vim -d file1 file2`. Vim automatically scrollbinds the two files. – Brian McCutchon Aug 30 '14 at 23:14
  • just hit Ctrl-X in **insert** mode and you will be able to see all the available commands in the bottom i.e. `-- ^X mode (^]^D^E^F^I^K^L^N^O^Ps^U^V^Y)` for eg. **^X-D** for **Definition completion** – Prabhat Kumar Singh Nov 19 '14 at 14:11
  • @PrabhatKumarSingh where is a good place to read up on these? E.g. for `^X ^D` I didn't find much with google (and I've yet to learn efficiently navigating `:h`) – lucidbrot Feb 16 '18 at 21:45
57

You can use a whole set of commands to change text inside brackets / parentheses / quotation marks/ tags. It's super useful to avoid having to find the start and finish of the group. Try ci(, ci{, ci<, ci", ci', ct depending on what kind of object you want to change. And the ca(, ca{, ... variants delete the brackets / quotation marks as well.

Easy to remember: change inside a bracketed statement / change a bracketed statement.

ndvo
  • 939
  • 11
  • 16
Peter
  • 127,331
  • 53
  • 180
  • 211
  • 17
    this isn't only for `c`. You can do this with `d` to delete (e.g. di( or da(), `y` to yank, `v` to select etc. – Nathan Fellman Aug 18 '09 at 18:27
  • Hello! I would like to know there the documentation for this is using `:help`? I can't find it anywhere. >_ – Matej Oct 02 '12 at 13:14
  • @MatejNanut: absolutely. Try `:help motion`. Then, look at `:help c` and `:help d` and `:help y` etc, which all take a motion. – Peter Oct 02 '12 at 18:31
  • 1
    @Peter I've checked those out before, but couldn't find mention of the peculiar "inner + delimiter" behaviour. It turns out to be in `:help motion.txt`! Thanks! – Matej Oct 02 '12 at 19:16
  • 2
    this tip is the sole reason why i switched to vi in the first place :) – Justin L. Feb 03 '13 at 03:45
  • 1
    If you're editing HTML or XML you can use `cit` to change the contents of the current tag. For example in `Some text`, if your cursor is over the "m" you can do `dit`to get ``. – Jonathan Potter Apr 30 '14 at 19:49
  • help: `:h motion.txt` and search/goto '6. Text object selection' – Florian Jun 24 '18 at 16:17
48

The asterisk key, *, will search for the word under the cursor.

[+Tab will take you to the definition of a C function that's under your cursor. (It doesn't always work, though.)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
smcameron
  • 2,547
  • 1
  • 19
  • 12
  • 1
    Try 'man ctags' if you're using *nix to learn how to generate a "tags" file that tells vim how to find the definition of any function or variable in many languages in addition to C. Use ctrl+] to find the definition of the token under your cursor, or use :tag tokenToFind to find any token it knows about. You can even start vim with "vim -t tokenToFind" to open the appropriate file and position the cursor at the function you need to edit. – Adam Liss Aug 18 '09 at 00:22
  • 25
    the # key will search in reverse direction for the word under the cursor – dansch Apr 29 '13 at 17:50
  • https://github.com/bronson/vim-visual-star-search enables star search for visual selections. I don't want to miss it any more. – Patrick Oscity Sep 21 '13 at 20:22
  • `[ + Tab ` will work always when you extend the `path` with required folders like `set path+=path/to/files` – dlmeetei Feb 01 '16 at 07:46
  • How can I switch on search without navigation? `*` goes forward; `#` backwards; I want to highlight and stay at place. – fde-capu Aug 28 '20 at 03:13
47
  1. Don't press Esc ever. See this answer to learn why. As mentioned above, Ctrl + C is a better alternative. I strongly suggest mapping your Caps Lock key to escape.

  2. If you're editing a Ctags compatible language, using a tags file and :ta, Ctrl + ], etc. is a great way to navigate the code, even across multiple files. Also, Ctrl + N and Ctrl + P completion using the tags file is a great way to cut down on keystrokes.

  3. If you're editing a line that is wrapped because it's wider than your buffer, you can move up/down using gk and gj.

  4. Try to focus on effective use of the motion commands before you learn bad habits. Things like using 'dt' or 'd3w' instead of pressing x a bunch of times. Basically, any time that you find yourself pressing the same key repeatedly, there's probably a better/faster/more concise way of accomplishing the same thing.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
anthony
  • 40,424
  • 5
  • 55
  • 128
47

Some of my latest additions to my Vim brainstore:

  • ^wi: Jump to the tag under the cursor by splitting the window.
  • cib/ciB: Change the text inside the current set of parenthesis () or braces {}, respectively.
  • :set listchars=tab:>-,trail:_ list: Show tabs/trailing spaces visually different from other spaces. It helps a lot with Python coding.
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Walter
  • 7,809
  • 1
  • 30
  • 30
  • 4
    This needs more votes! `cib` is great. – Matt Parker Apr 30 '12 at 15:39
  • also: ciw to change the current word (or caw, the same but left hand only) ciW to change the current W=o.(r-d) Sames with v instead of c will select in visual instead of replacing – lajarre Nov 22 '12 at 16:54
  • 5
    cib is equivalent to typing "ci(". You can also do "ci[", "ci{", or (if your vimrc is set up correctly) "ci<", for other types of brackets. – Tom Lord Jul 11 '13 at 14:26
  • 2
    Also, "cit" to change the text inside a tag. Very useful when working with XML/HTML. – Walter Oct 16 '13 at 14:43
  • it's also worth mentioning that you can suffix w/ the closing brace instead, should you prefer that. also, i've just learned about `ci}` & `cit` - wow, this is going to be _very_ useful. `vi[m]` is proving a very exciting program[s]! – underscore_d Oct 17 '15 at 20:35
44

ZZ (works like :wq)

And about the cursor position: I found that a cursor which always stays in the middle of screen is cool -

set scrolloff=9999
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
maykeye
  • 1,286
  • 1
  • 12
  • 16
39

gv starts visual mode and automatically selects what you previously had selected.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
too much php
  • 88,666
  • 34
  • 128
  • 138
34

:shell to launch a shell console from Vim. Useful when for example you want to test a script without quitting Vim. Simply hit ^d when you done with the shell console, and then you come back to Vim and your edited file.

peroumal1
  • 266
  • 1
  • 3
  • 5
  • I guess `:!sh` was too hard. I prefer that because it's easier to compose command lines using registers/completions from the current buffer or e.g. use `%`/`%:h` for the current filename/dirname etc. – sehe Feb 07 '15 at 22:55
  • 1
    This one is very cool. I use it every day.. Before that it was, :wq, do cli stuff, reopen vim with same file.. Great optimization – Flashin Dec 08 '15 at 09:21
  • 9
    Ctrl-Z to switch to shell and fg to go back to vim. – Mario G. Mar 12 '17 at 19:46
  • Put `map ! :shell` in your `.vimrc`, and you can launch the shell just with Alt+!, or Alt+Shift+1. (Mnemonic: `:!{cmd}` executes `{cmd}` with the shell.) – musiphil May 05 '17 at 19:37
  • `:shell` will start a new nested shell level though. Whereas `ctrl-z` does not. – wisbucky Jun 26 '18 at 00:45
  • `:term` and `:vert term` are favorites 'cause they split open. – fde-capu Aug 28 '20 at 03:16
34

This always cheers me up:

:help 42
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dogbane
  • 266,786
  • 75
  • 396
  • 414
31

vimcryption

vim -x filename.txt

You will be asked for a passphrase, edit and save. Now whenever you open the file in vi again you will have to enter the password to view.

anteatersa
  • 1,449
  • 2
  • 12
  • 18
  • Sync this with your dropbox and you get a really nice password manager ;-) – Luis Nell Oct 18 '12 at 11:49
  • 15
    But note that unless you `set cryptmethod=blowfish` (only available in 7.3+) it will use an algorithm with laughable strength. See `help encryption` for more detail. – A B Nov 19 '12 at 20:54
  • 3
    Please do not use vim encryption, is not good encryption, and bad security is worst than none. More info: https://github.com/neovim/neovim/issues/694 – rodrigoq Dec 24 '14 at 13:31
  • 2
    https://dgl.cx/2014/10/vim-blowfish meta-tldr: "fixed in Vim 7.4.399 [https://groups.google.com/forum/#!msg/vim_dev/D8FyRd0EwlE/bkBOo-hzTzoJ], for backwards compatibility reasons it needs to be a new cryptmethod, so use `:set cm=blowfish2`" – underscore_d Oct 17 '15 at 20:47
28

Build and debug your code from within Vim!

Configuration

Not much, really. You need a Makefile in the current directory.

To Compile

While you're in Vim, type :make to invoke a shell and build your program. Don't worry when the output scrolls by; just press Enter when it's finished to return to Vim.

The Magic

Back within Vim, you have the following commands at your disposal:

  1. :cl lists the errors, warnings, and other messages.
  2. :cc displays the current error/warning message at the bottom of the screen and jumps to the offending line in your code.
  3. :cc n jumps to the nth message.
  4. :cn advances to the next message.
  5. :cp jumps to the previous message.

There are more; if you're interested, type :help :cc from within Vim.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adam Liss
  • 47,594
  • 12
  • 108
  • 150
26

Press % when the cursor is on a quote, parenthesis, bracket, or brace to find its match.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adam Liss
  • 47,594
  • 12
  • 108
  • 150
  • 21
    If the cursor is not over any of those it shifts to the right until it hits one of them. – Cyber Oliveira Sep 02 '09 at 15:09
  • I just tried it and it seems that it defaults left in you're inside. Experimenting a bit: If the cursor is at the dot, then: (<--. ) or . --(---->) or . --(--(----)--->) or nothing happens if you're to the right of all the braces ( ) . – mattb Apr 21 '21 at 11:07
25

^P and ^N

Complete previous (^P) or next (^N) text.

^O and ^I

Go to previous (^O - "O" for old) location or to the next (^I - "I" just near to "O").

When you perform searches, edit files, etc., you can navigate through these "jumps" forward and back.

Marks

Press ma (m- mark, a - name of mark). Later to return to the position, type `a.

Community
  • 1
  • 1
dimba
  • 26,717
  • 34
  • 141
  • 196
  • 1
    Wow, I didn't know about ^O and ^I: that is awesome. Might be worth including `:help jump-motions` etc in your answer in case anyone wants more information. – DrAl Aug 14 '09 at 08:15
  • check out ShowMarks http://www.vim.org/scripts/script.php?script_id=152 . It will help you remember where and what all of your marks are in a buffer. you can toggle the visualization on and off with \mt – tester Mar 09 '11 at 16:45
  • I don't get the difference between ^P and ^N... – lajarre Nov 22 '12 at 17:00
  • @lajarre they cycle through the list of available completions in opposite direction – Patrick Oscity Sep 21 '13 at 20:19
  • 3
    I often use ^O^O when opening up Vim after I noticed that I want to edit the last edited file again. Huge time saver! – Patrick Oscity Sep 21 '13 at 20:20
23

^r^w to paste the word under the cursor in command mode.

It is really useful when using grep or replace commands.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Canopus
  • 7,351
  • 11
  • 46
  • 57
  • If it's the only word you want, then * in normal mode will search for the word under the cursor. – idbrii Sep 19 '10 at 22:02
22

Until [character] (t). It is useful for any command which accepts a range. My favorite is ct; or ct) which deletes everything up to the trailing semicolon / closing parentheses and then places you in insert mode.

Also, G and gg are useful (Go to bottom and top respectively).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
MighMoS
  • 1,228
  • 8
  • 18
  • best one here, though some of the others are useful too, I just knew about em all already – dansch Apr 24 '13 at 20:42
  • 1
    Also `f` instead of `t`, which will [action] up *through* that character; for instance, having the cursor on the beginning of a function argument, `df,` will delete it (in suitable languages, of course). – fmt Oct 25 '13 at 04:33
  • t and f are great for editing part of a camelCase variable. Eg, if you just duplicated a line and need to change firstVariable to secondVariable, position your cursor at the start of firstVariable, then ctV – Greg Sep 19 '14 at 15:07
  • 1
    T and F also work, but in the opposite direction. – Fede Jul 30 '16 at 12:20
18

^y will copy the character above the cursor.

innaM
  • 47,505
  • 4
  • 67
  • 87
18

Typing a line number followed by gg will take you to that line.

xastor
  • 482
  • 5
  • 17
17

I wish I'd known basic visual block mode stuff earlier. Even if you don't use Vim for anything else, it can be a big time saver to open up a file in Vim just for some block operations. I'm quite sure I wasted a ton of time doing this kind of thing manually.

Examples I've found particularly useful, when, say, refactoring lists of symbolic constant names consistently:

Enter Visual Block mode (Ctrl + Q for me on Windows instead of Ctrl + V)

Move the cursor to highlight the desired block.

Then, I whatever text and press Esc to have the text inserted in front of the block on every line.

Use A instead of I to have the text inserted after the block on every line.

Also - simply toggling the case of a visual selection with ~ can be a big time saver.

And simply deleting columns, too, with d of course.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Anon
  • 11,870
  • 3
  • 23
  • 19
14

q<letter> - records a macro.

and

@<same-letter> - plays it back.

These are by far the most useful commands in Vim since you can have the computer do a whole lot of work for you, and you don't even have to write a program or anything.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
leeand00
  • 25,510
  • 39
  • 140
  • 297
  • The use of `q` simplifies matters, but you aren't required to use it: just save into a named buffer the buffer command `"` - for example, using buffer `a` - `"ad$` ... – Mei Oct 21 '13 at 18:12
  • @Mei `q` records a macro; macros can contain commands, not just text, so `"ad$` is different from `qa`. – Brian McCutchon Aug 31 '14 at 00:11
  • @Sortofabeginner That's irrelevant here. The command "ad$ puts text into buffer a and qa runs it. – Mei Aug 31 '14 at 00:14
  • 2
    @Mei `qa` doesn't run it; `qa` records it and `@a` runs it. It is true that you can write a macro in plain text, store it in register `a` with something like `"ad$`, and then execute it with `@a`, but this is quite a bit more work. There is a fundamental difference between cut-and-paste and record-and-run. – Brian McCutchon Aug 31 '14 at 00:32
  • Doh! I knew that. Thanks for the correction – Mei Aug 31 '14 at 00:52
14

Opening multiple files using tabs

:tabe filepath

Navigating between open files

gt and gT or :tabn and :tabp

Save the open session so that you can get back to your list of open files later

:mksession session_file_name.vim

Open a created session

vim -S session_file_name.vim

Close all files at once

:qa

Another command I learned recently

autocmd

It allows you to run a command on an event, so you could for example run the command make when you save a file using something like:

:autocmd BufWritePost *.cpp :make
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Mansuro
  • 4,558
  • 4
  • 36
  • 76
12

qx will start recording keystrokes. You can do pretty much any editing task and Vim remembers it. Hit q again when you're finished, and press @x to replay your keystrokes. This is great for repetitive edits which are too complex to write a mapping for. You can have many recordings by using a character other than x.

too much php
  • 88,666
  • 34
  • 128
  • 138
  • 5
    Also the same character 'x' is shared between the 'q' record macro command and the named clipboards ("x...). You can leave snippets of macros sitting around your file and copy them to a named clipboard (e.g. "xyy) and then play them back (@x). – Cyber Oliveira Sep 02 '09 at 15:07
  • And if you create the awesomist macro ever, you can past that clipboard into your _vimrc with a 'let @x = ""' (putting the macro in the "") and save it forever! – Kearns Apr 02 '13 at 14:59
11

I would have to say that one of my favorites is putting the help window in a new tab:

:tab help <help_topic>

This opens up help in a new tab and, as somebody that loves Vim tabs, this is ridiculously useful.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Robert Massaioli
  • 13,379
  • 7
  • 57
  • 73
  • 2
    Buffers are the tabs of vim. They are better supported by the vim workflow. I suspect tabs were only added to vim because too many people did not understand buffers. – still_dreaming_1 Jun 07 '15 at 12:42
  • 1
    Ok so very soon after saying that, I found a use for tabs in vim. It is true that if you are using one buffer per tab, you need to learn about buffers. That is not how tabs were intended to be used in vim. Most advanced vim users use buffers the way tabs are used in most programs. Many people think tabs should have been named layouts in vim. They are mostly for having different collections of windows open in different tabs. You could also have a specific buffer that you go back to a lot open in one tab, and use the other tab for viewing all other buffers. – still_dreaming_1 Jun 07 '15 at 13:15
9

Tabbed interface

Apart from split windows, you also can have tabbed windows. In the escape mode, type tabnew. You can open multiple tabs like this. To navigate between tabs, type tabn. This will move to the next tab. To move to a tabbed window, type tabn2 to move the second tab and so on.

To close a tab, type tabc, tabclose, or just close.

If you are in a terminal emulator (basically terminal in GUI) then you can try doing set mouse=a. Once that's done, you can click inside the editor with your mouse. And this will also help you navigate between tabs by clicking, and also closing by clicking on the close button at the right side.

Align your code - Full file

Just type G=gg in the escape mode.

Fold your code

Say you have a function that is completed. You want to minimise (or fold) that part of code so that you can free up some space and reduce clutter. Just select the code. Then, type fold.

This will fold the code up. If you want to expand the code, just go there, and type zo. To fold again, type zc.

Community
  • 1
  • 1
Nikhil Baliga
  • 1,339
  • 12
  • 18
9
:x #(Save and Quit a File)

Same as :wq or ZZ

jmohr
  • 4,706
  • 4
  • 29
  • 29
  • For those who like `:wq` too much, I use `:command! Wq :wq` to deal with the pesky cases when I can't get off my shift key fast enough. – fmt Oct 25 '13 at 04:36
9

:b [any portion of a buffer name] to switch buffers. So if you have two buffers, "somefile1.txt", and "someotherfile2.txt", you can switch to the second with simply ":b 2.t<enter>". It also supports tab completion, although it's not required.

Speaking of tab completion, the setting :set wildmode=full wildmenu is also very helpful. It enables complete tab completion for command-mode, as well as a very helpful ncurses-style menu of all the possible matches when using it.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael
  • 4,700
  • 9
  • 35
  • 42
9

cw

Change word - deletes the word under the cursor and puts you in insert mode to type a new one. Of course this works with other movement keys, so you can do things like c$ to change to the end of the line.

f + character

Finds the next occurrence of the character on the current line. So you can do vft to select all the text up to the next "t" on the current line. It's another movement key, so it works with other commands too.

Adam Neal
  • 2,147
  • 7
  • 24
  • 39
9

:%s,/search,/replace,

You can use other characters than / (slash) to separate patterns for substitution. This way you don’t have to escape the slashes of file paths.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
hfs
  • 2,433
  • 24
  • 37
8

Taking xcramps' suggestion one step further, I can't tell you how many times I've used:

:%!sort

to sort a list of items in a file.

Details:

:range!command

will execute a shell command on the specified range of lines. A range is usually specified as start,end

Examples:
1,3 specifies the first 3 lines
'a,'b selects the text between bookmarks a and b
.,$ selects the entire document (. = first line; $ = last line)
% is a shortcut for .,$ and also selects the entire document.

Feel free to mix and match numbers, bookmarks, ., and $.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Adam Liss
  • 47,594
  • 12
  • 108
  • 150
6

I'm surprised no-one's mentioned Vim's windowing support. Ctrl + W, S is something I use nearly every time I open Vim.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kris Jenkins
  • 4,083
  • 30
  • 40
5
ma
move cursor down
:'a,.!program

This will take all text between where you set the a mark (ma) to the current line (.), run it through program, and replace the contents of the marked region with the results. You can even use it to see the contents of a directory (for example) by making a blank line, then with cursor sitting on that line,

:.!ls

Oh, and you can set marks like this for a-z (i.e. ma), and

'a

will jump you to the position you marked as "a."

/ searches forward, and ? repeats search backwards without having to resupply search pattern.

Groovy stuff. vi is highly underrated. Once you get the hang of it, you won't ever want to use the IDE supplied editors.

xcramps
  • 1,203
  • 1
  • 9
  • 9
  • For `:.!ls` I would more logically use `:r !ls` because it doesn't take input from my buffer and creates the line. I use `:r !uuidgen` e.g. – sehe Feb 07 '15 at 23:01
5

I often make functions for editing tasks and store them in my .vimrc file, so I can find them again.

For example, reading .NET callstacks that have been converted into a single line:

function! FixCallStacks()
:%s;\[NLN\];\r;g
:%s;\[TAB\];\t;g
endfunction
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Igor Dvorkin
  • 827
  • 1
  • 8
  • 18
5

Comment out a range of lines:

  1. First set a bookmark at the beginning of range: ma

  2. Go the the last line in range

  3. The command is:

    :'a,.s/^/# /
    

    Assuming # is your comment character.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
alps123
  • 124
  • 7
5

:qall and :wqall to close all the split screens.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vijay Dev
  • 26,966
  • 21
  • 76
  • 96
4
:Te[xplore]

Tab & Explore (does a tabnew before generating the browser window)

4

I just discovered this one while browsing the Vim help:

:help index

This takes you to a single (searchable!) page with all the commands for all the modes.

So if you know that the command you're trying to remember/learn starts with or involves a certain keystroke, you can search for that and flip through all the possibilities. Or you can just browse the mode you're interested in to see/learn editing possibilities.

I can't count the number of times I've done just :help Ctrl + R or whatever and gotten just the first thing, which is of course never the one you want. This is much better than :helpgrep IMO.

And into the .vimrc it goes:

nnoremap <silent> <F1> :help normal-index<CR>
inoremap <silent> <F1> <C-O>:help insert-index<CR>

:help still gets you to the default F1 page.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
David Pope
  • 6,457
  • 2
  • 35
  • 45
3

Use Vim bindings on the command line in Bash:

    set -o vi

In other, readline-using programs, hit Ctrl + Alt + J to switch from Emacs to Vim bindings.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Michael Fox
  • 3,632
  • 1
  • 17
  • 27
2

In our software shop, variable declarations need to be sorted. In the language that we use, multiple variables can appear on the same line.

new var1,var2,var3,etc

It is a real pain to go through and visually attempt to sort each and every variable. The block highlighting, and sort command in Vim are my friends here:

  1. Move the cursor to the first variable to be sorted.
  2. Issue the v command to enter visual mode.
  3. Move the cursor to the end of the last variable to be sorted in my case I enter $ to go to the end of the line).
  4. Execute the !sort command to tell Vim to sort the highlighted text.

This will only work if their exists a 'sort' command on the underlying system.

igotmumps
  • 549
  • 2
  • 7
  • What coding standard tells you to sort variable declarations alphabetically? – Peter Mortensen Nov 18 '19 at 15:04
  • I program in a language called mumps. In a procedure, we can have 10's of variables all on one line. And there can be multiple lines. scanning through the list can be a real pain. Internally, we like to have to variable names sorted to make it easy to find. – igotmumps Nov 27 '19 at 15:59
1

I know this is not completely Vim. But I find the cscope integration really good, and it helps me a lot when hacking the Linux kernel.

  • Ctrl + \, g to reach the definition of a function

  • Ctrl + \, s to find all the usages of a function, macro, or variable.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
LB40
  • 12,041
  • 17
  • 72
  • 107
0

set confirm allows you to quit Vim gracefully with :q. You don't need to use ZZ or other heavy-handed mechanisms which blindly save or discard all changes.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
too much php
  • 88,666
  • 34
  • 128
  • 138
-3

For obsessive Vim configuration have a look at https://github.com/jmcantrell/dotfiles-vim

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
allan
  • 875
  • 6
  • 3