Skip to content

Instantly share code, notes, and snippets.

@soifou
Last active March 5, 2021 09:04
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soifou/be3a85788c7a898f5300 to your computer and use it in GitHub Desktop.
Save soifou/be3a85788c7a898f5300 to your computer and use it in GitHub Desktop.
Useful Vim commands

VIM Starter kit

Open file

vim file1

Ok just kidding, everyone know this but you can do also

vim
:e file1

And switch to another file

:e /foo/bar/file2

Save file and exit

:wq

Save file (and exit) only if buffer has changed

:x

Search a word in a file

/something

Then press ENTER, type n to go the next occurence.

Replace a word by another in the whole file

:%s/old/new/g

Another way is to go to your word, hit *, then do:

:%s//replacement/g

When no search pattern is used, last search pattern, taken from register @/, is used.

Cut/paste line(s)

Go to a line in normal mode, hit V to enter visual mode then d to cut selection. If you want cut several lines, update your selection with hjkl on visual mode then d.

Go to the line where you want to paste, then hit P before or p after the cursor.

Duplicate line

Go to a line in normal mode, hit yy (yank whole line) then go wherever you want to duplicate and hit p. If you want to duplicate several times hit 3p instead, it will paste 3 identical lines.

Delete lines

To delete a line, go to the line, then type dd. To delete a line and the next one, type d then ⬇️ You can delete more lines above/below if you type d, then the number and ⬆️ or ⬇️. For instance, you want to delete the current line and 3 lines above then type d3 and ⬆️

Goto

Line n°123

123G

Last line

G

First line

gg

Autocompletion

If a word already exists in the file, type CTRL+n to complete the word, example:

this is awesome awe

Then type CTRL+n to complete the word.

Increment/decrement numbers

In normal mode you can increment a number with Ctrl+a and decrement with Ctrl+x

Diff

First open your initial file in Vim. Then open the second one in split mode:

vim file1
:vsplit file2

Launch the diff in the first buffer:

:diffthis

Switch buffer with Ctrl+w and launch again the diff:

:diffthis

The two files will then be highlighted with focus on their differences. To turn the diff off, simply use:

:diffoff

The short way

You can actually do the same thing a little bit shorter

vim file1
:vsplit file2
:windo diffthis

Note the command windo means "windows do".

The shortest way

Vim can chain these commands in one like this

vim file1
:vertical diffsplit file2

Undo/redo

Revert the document before your last change

:earlier

Note that you can inverse this with the command:

:later

Revert the document one minute ago:

:earlier 1m
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment