5 个针对有经验用户的 Vim 实用技巧
Vim
![](/data/attachment/album/201701/26/141924vb1ma1ly86ffyfma.jpg)


这篇文章是 Vim 用户指南系列文章中的一篇：


* [Vim 初学者入门指南](/article-8143-1.html)
* [Vim 快捷键速查表](/article-8144-1.html)
* 5 个针对有经验用户的 Vim 实用技巧
* [3 个针对高级用户的 Vim 编辑器实用技巧](/article-8149-1.html)


Vim 编辑器提供了很多的特性，要想全部掌握它们很困难。然而，花费更多的时间在命令行编辑器上总是有帮助的。毫无疑问，和 Vim 用户们进行交流能够让你更快地学习新颖有创造性的东西。


**注：** 本文中用到的例子，使用的 Vim 版本是 7.4.52 。


### 1、 同时编辑多个文件


如果你是一名软件开发者或者把 Vim 作为主要的编辑器，那么可能很多时候你需要同时编辑多个文件。“<ruby> 紧跟 <rp>  （ </rp> <rt>  following </rt> <rp>  ） </rp></ruby>”是在同时编辑多个文件时可用的实用技巧。


不需要在多个 shell 界面中打开多个文件，你可以通过把多个文件的文件名作为 Vim 命令的参数从而在一个 shell 界面中打开多个文件。比如：



```
vim 文件1 文件2 文件3

```

第一个文件（例子中的文件1）将成为当前文件并被读入缓冲区。


在编辑器中，使用 `:next` 或 `:n` 命令来移动到下一个文件，使用 `:prev` 或 `:N` 命令返回上一个文件。如果想直接切换到第一个文件或最后一个文件，使用 `:bf` 和 `:bl` 命令。特别地，如果想打开另外的文件并编辑，使用 `:e` 命令并把文件名作为参数（如果该文件不在当前目录中则需要完整路径做为参数）。


任何时候如果需要列出当前打开的所有文件，使用 `:ls` 命令。看下面展示的屏幕截图。


![](/data/attachment/album/201701/26/141942p7hm7eeieh1j7p1l.png)


注意 ”%a” 表示文件在当前活动窗口，而 “#” 表示上一个活动窗口的文件。


### 2、 通过自动补全节约时间


想节约时间并提高效率吗？使用缩写吧。使用它们能够快速写出文件中多次出现、复杂冗长的词。在 Vim 中缩写命令写就是 `ab` 。


比如，当你运行下面的命令以后：



```
:ab asap as soon as possible

```

文件中出现的每一个 `asap` 都会被自动替换为 `as soon as possible` ，就像你自己输入的一样。


类似地，你可以使用缩写来更正常见的输入错误。比如，下面的命令



```
:ab recieve receive

```

将会自动更正拼写错误，就像你自己输入的一样。如果在一次特殊情况下你想阻止缩写展开或更正发生，那么你只需要在输入一个单词的最后一个字母以后按 `Ctrl + V` ，然后按空格键。


如果你想把刚才使用的缩写保存下来，从而当你下次使用 Vim 编辑器的时候可以再次使用，那么只需将完整的 `ab` 命令(没有起始的冒号)添加到　`/etc/vim/vimrc` 文件中。如果想删除某个缩写，你可以使用 `una` 命令。比如： `una asap` 。


### 3、 切分窗口便于复制/粘贴


有时，你需要从一个文件将一段代码或文本的一部分复制到另一个。当使用 GUI（图形界面）编辑器的时候，这很容易实现，但是当使用一个命令行编辑器的时候，这就变得比较困难并且很费时间。幸运的是， Vim 提供了一种高效、节约时间的方式来完成这件事。


打开两个文件中的一个然后切分 Vim 窗口来打开另一个文件。可以通过使用 `split` 命令并以文件名作为参数来完成这件事。比如：



```
:split test.c

```

上面的命令将分离窗口并打开文件 “test.c”


![](/data/attachment/album/201701/26/142000pal6qgf6b5gfffz9.png)


注意到 `split` 命令水平分离 Vim 窗口。如果你想垂直分离窗口，那么你可以使用 `vsplit` 命令。当同时打开了两个文件并从一个文件中复制好内容以后，按 `Ctrl + W` 切换到另一个文件，然后粘贴。


### 4、 保存一个没有权限的已编辑文件


有时候当你对一个文件做了大量更改以后才会意识到你对该文件仅有 `只读` 权限。


![](/data/attachment/album/201701/26/142018ytpotpoxntini2oo.png)


虽然把文件关闭，获取权限以后再重新打开是一种解决方法。但是如果你已经做了大量更改，这样做会很浪费时间，因为在这个过程中所有的更改都会丢失。 Vim 提供了一种方式来处理这种情况：你可以在编辑器中在保存文件前更改文件权限。命令是：



```
:w !sudo tee %

```

这个命令将会向你询问密码，就像在命令行中使用 `sudo` 一样，然后就能保存更改。


**一个相关的技巧**：在 Vim 中编辑一个文件的时候，如果想快速进入命令行提示符，可以在编辑器中运行 `:sh` 命令，从而你将进入一个交互的 shell 中。完成以后，运行 `exit` 命令可以快速回到 Vim 模式中。


### 5、 在复制/粘贴过程中保持缩进


大多数有经验的程序员在 Vim 上工作时都会启用自动缩进。虽然这是一个节约时间的做法，但是在粘贴一段已经缩进了的代码的时候会产生新的问题。比如，下图是我把一段已缩进代码粘贴到一个在自动缩进的 Vim 编辑器中打开的文件中时遇到的问题：


![](/data/attachment/album/201701/26/142034q67v77brs7d7ts7s.png)


这个问题的解决方法是 `pastetoggle` 选项。在 `/etc/vim/vimrc` 文件中加入下面这行内容：



```
set pastetoggle=<F2>

```

然后当你在 `插入` 模式中准备粘贴代码前先按 `F2` 键，就不会再出现上图中的问题，这样会保留原始的缩进。注意，你可以用其他的任何键来代替 `F2`，如果它已经映射到了别的功能上。


### 结论


更进一步的提高你的 Vim 编辑器技巧的唯一方法是，在你日复一日的工作中使用命令行编辑器。留意那些耗时多的操作，然后尝试去寻找是否有编辑器命令可以很快地完成这个操作。




---


via: <https://www.maketecheasier.com/vim-tips-tricks-for-experienced-users/>


作者：[Himanshu Arora](https://www.maketecheasier.com/author/himanshu/) 译者：[ucasFL](https://github.com/ucasFL) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
![A photograph of a person working in front of a computer.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-00-featured-image-1.jpg)

The Vim editor offers so many features that it’s very difficult to learn all of them. While spending more time on the command line editor always helps, there is no denying that you can learn new and productive things faster while interacting with fellow Vim users. In this article, I will go through some tips and tricks on Vim that can improve your text editing workflow today.

[1. Working with Multiple Files](#work-multiple-files)[2. Save Time with Auto Complete](#save-time-auto-complete)[3. Split Windows to Easily Copy and Paste](#split-windows-copy-paste)[4. Save a File You Edited Without Permissions](#save-edited-root-files)[5. Preserve Indentation During Copying and Pasting](#preseve-indent-copy-paste)[6. Use Text Object Commands](#use-context-commands)[7. Use Marks to Speed Up Editing](#use-marks-for-editing)[8. Automate Editing Using Macros](#automate-edits-macros)[9. Take Advantage of Third-Party Plugins](#take-advantage-plugins)

## 1. Working with Multiple Files

If you’re a software developer or someone who uses Vim as their primary editor, chances are that you have to work with multiple files simultaneously. Following are some useful tips that you can use while working with multiple files.

Instead of opening files in different terminal tabs, you can open all of them in a single tab by passing their filenames as arguments to the vim command:

`vim file1 file2 file3`

Doing this will load your three files into their own separate buffers inside Vim.

Use the `:next`

or `:n`

command to move to the next file, and the `:prev`

or `:N`

command to return to the previous one.

To directly switch to the first or the last file, use `:bf`

and `:bl`

commands, respectively.

![A terminal showing the contents of the last file in the multi-file Vim buffer.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-01-open-last-file-multi-buffer-session.png)

To open and start editing another file, use the `:e`

command with the filename as argument.

![A terminal highlighting the open command for a new file in the command buffer.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-02-highlight-edit-command-new-file.png)

**Note:** You need to provide the complete path if your file is not present in the current directory.

You can also use the `:ls`

command to list all the currently open buffers in your Vim session.

![vim-ls A terminal showing the list of currently active buffers inside Vim.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-03-show-open-buffer-list.png)

**Note**: The “%a” indicates that the file is in the current active window, while “#” tells you that it’s the last file that you switched to prior to the current one.

## 2. Save Time with Auto Complete

Want to save time and improve accuracy? Use abbreviations. They come in handy while writing long, complex words that occur frequently throughout a file. The command for abbreviations is `ab`

.

For example, running the following will automatically replace the word “asap” with “as soon as possible:”

:ab asap as soon as possible

![A terminal showing the automatic text expansion feature in Vim.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-04-show-abbreviation-expansion-sample.png)

Similarly, you can also use abbreviations to correct common typing mistakes. For example, the follow command will automatically correct the spelling mistake as you type:

:ab recieve receive

If you want to prevent the expansion/correction from happening at a particular occurrence, just press `Ctrl` + `V` after the last character of the word and then press the `Space` key.

![A terminal highlighting the user interrupt for Vim's automatic abbreviation command.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-05-highlight-abrreviation-expansion-interrupt.png)

To remove a particular abbreviation, you can use the `una`

command. For example, `:una asap`

will delete the abbreviation for “as soon as possible.”

![A terminal highlighting the command to remove an abbreviation in Vim.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-06-show-abbreviation-removal-command.png)

If you want to save the abbreviation you’ve created so that it is available to you the next time you use the Vim editor, add the complete `ab`

command without the initial colon to the “~/.vimrc” file.

**Tip:** are you currently stuck in a Vim mode? Learn some of the [different ways to exit the Vim editor](https://www.maketecheasier.com/exit-vim-editor-linux/).

## 3. Split Windows to Easily Copy and Paste

There are times when you want to copy a piece of code or a portion of text from one file to another. While the process is easy when working with GUI editors, it gets a bit tedious and time-consuming while working with a command line editor. Fortunately, Vim provides a way to minimize the time and effort required to do this.

Open one of the two files and then split the Vim window to open the other file. This can be done by using the `split`

command with the file name as argument. For example, this command will split the window and open “test.c:”

:split test.c

![vim-split A terminal showing two files in split display inside Vim.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-07-split-screen-sample-two-files.png)

Observe that the command split the Vim window horizontally. In case you want to split the window vertically, you can do so using the `vsplit`

command. Once both the files are opened, copy the stuff from one file, press `Ctrl` + `W` to switch the control to another file, and paste.

![A terminal highlighting the copied line of code from the "test.c" file to the "anotherfile.c."](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-08-highlight-pasted-code-snippet-inside-vim.png)

**On a side note: **Check out our picks for the [best cross-platform text editors for programmers](https://www.maketecheasier.com/best-cross-platform-text-editors-for-programmers/) today.

## 4. Save a File You Edited Without Permissions

There are times when you realize that a file is read-only only after making a bunch of changes to it. Although closing the file and reopening it with the required permissions is a way out, doing this will lose all the changes that you’ve already made to your file.

![vim-sudo A terminal showing the error that Vim returns when it doesn't have the permission to modify a file.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-09-sample-wrong-permissions-file-saving.png)

To fix this, you can run the `:w`

command followed by external Bash command that reloads your file with superuser priveleges:

:w !sudo tee %

Vim will ask for your password to resolve the command, then it will save your current changes.

You can also quickly access your system shell while editing a file in Vim. To do that, run the `:sh`

command from within the editor.

![A terminal showing the internal shell session inside Vim.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-10-show-internal-shell-vim.png)

Once you are done, run the `exit`

command to return to your Vim session.

## 5. Preserve Indentation During Copying and Pasting

Most of the programmers work on Vim run it with its auto-indentation feature on. Although it’s a time-saving practice, it creates a problem while pasting indented code. For example, this is what happened when I pasted indented code into a Vim editor with auto-indent on.

![vim-indentation A terminal showing a misaligned file with unnecessary indentations.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-11-show-misaligned-indentation-sample.png)

You can fix this issue by adding the `pastetoggle`

option to Vim’s config file. To do that, open the vimrc file, then paste the following line of code to the end of your config:

set pastetoggle=<F2>

Save your vimrc, then open the file that you want to paste your indented code on.

Go into Insert Mode, then press `F2` before pasting your indented code. Doing this should preserve the original indentation.

![A terminal showing a properly aligned code block using pastetoggle.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-12-show-properly-pasted-code-sample.png)

**Note:** you can replace `F2` with any other key if it’s already mapped to some other functionality.

## 6. Use Text Object Commands

Another way to easily up your Vim editing game is by using its built-in “text object commands.” These are special-case movement keys that take in the context of where the cursor currently is and operates your commands inside that context.

One of the most useful text object command that you can use is `I`

. This takes a motion key such as `W` and operates your commands inside that context. For example, you can press `C` + `I`, then `W` to run the change command on the word under your Vim cursor.

![A terminal highlighting the modified text using Text Object commands.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-13-highlight-text-object-command-sample.png)

The `I`

command also works for other forms of text delimiters. For instance, pressing `C` + `I`, then `Shift` + `9` will clear any text in-between the parenthesis under your cursor.

![A terminal highlighting the Text Object command applied to the parenthesis delimiter.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-14-highlight-vim-text-object-parenthesis-delimiter.png)

## 7. Use Marks to Speed Up Editing

Marks are a nifty feature in Vim that saves a specific spot in your file to a key on your keyboard. Similar to browser bookmarks, these enable you to jump from point to point while editing large pieces of text and code.

To create a Vim mark, navigate to the location that you want to save then press `M`, followed by the letter that you want to bind the location to. In my case, I will set my new mark to the “A” key on my keyboard.

![A terminal showing the location of a custom Vim mark.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-15-sample-marking-function.png)

Test whether your new mark is working properly by pressing `G` twice to go to the top of the document, then press ``` (Grave) + `A`.

You can also quickly go back to your previous location by double tapping the ``` (Grave) key.

To list all the available marks on your current session, press `Shift` + `;` (Semicolon), then type `marks`

on the command buffer.

![A terminal highlighting the custom mark inside Vim's registers.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-16-highlight-marked-line-in-list.png)

**Good to know:** Level up your Vim know-how by checking out our [comprehensive cheatsheet for Vim](https://www.maketecheasier.com/cheatsheet/vim-keyboard-shortcuts/).

## 8. Automate Editing Using Macros

On top of convenient commands, you can also streamline your editing workflow in Vim by automating repetitive tasks using macros. It’s a built-in feature that allows you to “record” an action inside the editor and run it across an entire file.

To create a new Vim macro, press `Q`, followed by a key where you want to assign your macro to. For me, I will assign my new macro to my “1” key.

![A terminal highlighting the prompt that Vim creates whenever it's recording a macro.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-17-highlight-sample-macro-recording-prompt.png)

Perform the edit that you want to make on the current line. In my case, I will go to the start of the line, edit the first word to “That,” add “Hello, Make Tech Easier” at the end, then go to the next line.

**Note:** Vim will perform your macros exactly as you recorded it regardless of the current cursor position.

Once you’re done with your edit, press `Q` to save your new macro.

Test whether your new macro is working properly by pressing `Shift` + `2`, followed by your macro key.

![A terminal showing the Vim macro working properly.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-18-macro-working-properly-vim-1.png)

**Tip: **you can also perform bulk editing using Vim’s visual mode. Learn more about it by checking out our quick guide to [commenting multiple lines in Vim](https://www.maketecheasier.com/comment-multiple-lines-vim/).

## 9. Take Advantage of Third-Party Plugins

Aside from its stellar built-in functions, Vim is an extensible text editor that you can [customize using third-party plugins](https://www.maketecheasier.com/8-vim-plugins-to-enhance-your-productivity/). This enables you to include features not present in default Vim and shape the editor to your workflow.

The easiest way to get started with Vim plugins is by installing Plug. This is a lightweight plugin manager that handles the installation and management of your plugins directly from Vim. To install it, run the following command:

curl -fLo ~/.vim/autoload/plug.vim --create-dirs https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim

Open your current user’s .vimrc, then paste the following block of code at the end of the file:

call plug#begin() call plug#end()

Save your .vimrc, restart Vim, then press `Shift` + `;` (Semicolon) to bring up the command buffer.

Enter `PlugStatus`

on the buffer to confirm that you’ve properly installed Plug on your Vim instance.

![A terminal highlighting the PlugStatus command for Vim Plug.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-19-plug-status-screen-display.png)

To install a plugin, go back to the `call plug#begin()`

section of your .vimrc file, then type “Plug,” followed by the Git URL of your plugin. For example, pasting the following code will install the [Goyo](https://github.com/junegunn/goyo.vim) plugin to your Vim instance:

`Plug 'https://github.com/junegunn/goyo.vim.git'`

![A terminal highlighting the Plug entry for installing a plugin in Vim.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-20-highlight-plug-git-url-sample.png)

Restart your Vim client, bring up the command buffer, then run `PlugInstall`

to start the plugin install process.

![A terminal showing the installation process for the Goyo Vim plugin.](https://www.maketecheasier.com/assets/uploads/2024/09/9-vim-tips-tricks-21-plug-install-completed.png)

With the knowledge of how to optimize Vim under your belt, you can start exploring what this brilliant text editor can do for you. Learn how to [turn Vim into a powerful word processor](https://www.maketecheasier.com/turn-vim-word-processor/) by adding some simple functions to your config file.

Image credit: [Christina @ wocintechchat.com via Unsplash](https://unsplash.com/photos/shallow-focus-photo-of-woman-using-laptop-computer-fch6vkbouCc). All alterations and screenshots by Ramces Red.

Our latest tutorials delivered straight to your inbox