Useful Vim Commands

在vim保存时获得sudo权限

  • 在维护线上服务的时候,经常要编辑一些不属于操作用户的文件,就是只有r权限的那种,
    每次保存都会提示read only。只能先记下来改了什么,然后再退出,然后 sudo vim 再做保存。

  • 下面的命令可以不退出vim进程,直接用vim命令获取sudo权限,然后直接保存文件。

1
:w !sudo tee %
  • 命令:w !{cmd},让 vim 执行一个外部命令{cmd},然后把当前缓冲区的内容从 stdin 传入。
  • tee 是一个把 stdin 保存到文件的小工具。
  • 而 %,是vim当中一个只读寄存器的名字,总保存着当前编辑文件的文件路径。
  • 所以执行这个命令,就相当于从vim外部修改了当前编辑的文件。

delete vim blank line

1
:g/^$/d
  • :g will execute a command on lines which match a regex. The regex is ‘blank line’ and the command is :d (delete)

Replace a character by a newline

1
:%s/, /\r/gc

\n matches an end of line (newline), whereas \r matches a carriage return.
On the other hand, in substitutions \n inserts a null character whereas \r inserts a newline (more precisely, it’s treated as the input )

Replace spaces more than 2 by 2 spaces(use regex)

1
%s/ \{2,}/  /gc

Replace tab with spaces

1
:%s/^I/  /gc

insert timastamp into vim

1
2
3
4
5
6
:put =strftime(\"%c\")
:put =strftime('%c')
:pu=strftime('%c')

#Or using external toolsEdit
:r !date #very useful

Abbreviation and Unabbreviation

In the following example, whenever you type US it will expand to “United States” when you’ve defined the following abbreviation.
To abbreviate a word temporarily, execute the abbr command in command mode as shown below.

1
:abbr US United States

To abbreviate a word permanently, you can place it in the .vimrc as shown above.
To remove an abbreviation definition temporarily, execute the noabbr command in command mode.

1
:noabbr US

jump using ctrl-o and ctrl-i

Vim keeps track of your navigation using a jump list.
You can go backward and forward through that list.
The jump list keeps tracks of all the places you’ve been to by tracking file name, line number and column number.
To view the jump list:

1
2
3
4
5
6
7
:jumps # show all jumps history


CTRL-O: Jump back to previous spot
CTRL-I: Jump forward to next spot
5CTRL-O: Jump to location#5 shown above location#0
5CTRL-I: Jump to location#5 shown below location#0

When you have a very long line without any newline, Vim treats it as single line. So, when you execute j on that line, it will jump to next line. However you’ll get a feeling that it has skipped lot of lines. But in reality it is just only long line.

1
2
3
4
5
gj: Scroll down a visual line
gk: Scroll up a visual line
g^: Go to the starting of current visual line
g$: Go to the end of current visual line
gm: Go to the middle of current visual line

bookmarks

1
2
3
4
5
6
7
8
m{lower case char} : local bookmark
m{upper case char} : global bookmark


`a (backtick a): Jump to the exact location of bookmark ‘a’
‘a (single quote a): Jump to the beginning of the line containing the bookmark ‘a’

marks :display all bookmarks

Insert or Append Other File to This

1
2
3
4
5
r /path/to/filename.txt
r commands # Insert commands execute result into this file

w newfilename.txt # copy this file to new created newfilename.txt
1,10 w newfilename.txt # copy only 1~10 lines to new file newfilename.txt

use powerful macro

  • Step 1: Start recording by pressing q, followed by a lower case character to name the macro.
  • Step 2: Perform any typical editing actions inside Vim editor, which will be recorded.
  • Step 3: Stop recording by pressing q.
  • Step 4: Play the recorded macro by pressing @ followed by the macro name.
  • Step 5: To repeat macros multiple times, press : NN @ macro name. NN is a number.
1
2
3
4
5
qa             # start recording name a macro
some actions # Perform any typical actions
q # Stop recording
@a # Play the record a by one time
8@a # Play the record a by 8 times

sort contents

Sort part of the file content as shown below.

  • Go to visual mode by pressing v.
  • Use arrow keys and select the lines that need to be sorted.
  • Press :, which will show :’<,’>’ at the bottom of the Vim.
  • Add !sort at the end to sort the selection
1
:'<,'>!sort

The following options are available for the :sort Vim command

1
2
3
4
5
sort :    Sort in ascending order
sort!: Sort in descending order
sort i: Ignore case while sorting
sort u: Remove duplicate lines. U stands for unique.
sort! ui: You can also combine all the sort command options.

show deleted contents

1
:reg

Increment and Decrement Number Using CTRL Keys

1
2
CTRL-A: Increment Number. Place the cursor over a number in Vim editor and press CTRL-A, which will increase the number by 1.
CTRL-X: Decrement Number. Place the cursor over a number in Vim editor and press CTRL-X, which will decrease the number by 0.

Execute One Vim Command in Insert Mode

1
ctrl-o

The following is the sequence:

  • You are in insert mode typing characters.
  • Press CTRL-O, which will temporarily take you to command mode.
  • Press any Vim command (for example, 5j to jump 5 lines)
  • You are automatically back in insert mode after the single Vim command is executed.

View Current File Details

1
2
ctrl-g
g ctrl-g

Tabs and Spaces

The following are important tabs and space related commands.
set expandtab : Convert tabs to spaces automatically. For example, When you type Tab, it will be converted it to 8 spaces. set tabstop=4 If you want Tab to be converted to 4 spaces, specify it with tabstop.

retab: Convert all the tabs in a files to spaces based on expandtab and tabstop option.

set shiftwidth=4: Specifies the number of spaces that should be used when you indent a line.

set ai: In insert mode, Vim will automatically indent new lines (when you hit return) to the same indent level of the current line.

Open the File whose Name is under the Cursor

gf: Open a file (in the same window) whose name is currently under the cursor.
CTRL-W f: Open a file (in a new window) whose name is currently under the cursor.
CTRL-W gf: Open a file (in a new tab) whose name is currently under the cursor.

Edit Multiple Files Using the Traditional

Open multiple files from command line.

1
$ vim file1 file2 file2

Open another file when you are already in a Vim session.

1
:e another_file

List all open files in the current Vim session.

1
:ls

Go to the Nth file from the above :ls output.

1
:e #N

Toggle between two files.

1
CTRL-^

Go to next file when multiple files are opened.

1
:next

Go to previous file when multiple files are opened.

1
:previous

Encrypt File in Vim

Save and encrypt the current file:
Once you’ve encrypted a file using :X, the next time you open that file, Vim will prompt for the encryption key.