命令行大全

vim\gview\gvim

舞夕之 发表于 2020-08-06 08:11浏览次数:

在类Unix操作系统上,VIM是文本编辑器,它的意思是“Vi改进”。它可以用来编辑任何类型的文本,特别适合编辑计算机程序。

查看英文版

目录:

1 vim\gview\gvim 运行系统环境

2 vim 描述

3 vim 语法

4 更多变化

5 vim 全局插件

6 vim 常用选项

7 vim 选项

8 有用的技巧

9 vim 示例

vim\gview\gvim 运行系统环境

Unix&Linux

vim 描述

vim是向上兼容Vi的文本编辑器。Vi之上有很多增强功能:多级撤消,多个窗口和缓冲区,语法突出显示,命令行编辑,文件名完成,完整的帮助系统,视觉选择等。

启动vim

最常见的是,使用以下命令开始vim编辑单个文件。

vim file

通常,启动vim的语法如下:

vim [options] [filelist]

如果缺少文件列表,则编辑器将从空缓冲区开始。否则,可以使用以下四个选项之一来选择一个或多个要编辑的文件。

主要选项
file... 一个或多个文件名的列表。第一个将是当前文件并读入缓冲区。的光标将被定位在缓冲器的第一行。您可以使用“;:next;”命令进入其他文件。要编辑以破折号开头的文件,请在文件列表前加双破折号(“;-;”)。
-- 单破折号表示要从标准输入中读取要编辑的文件。
-t{tag} 要编辑的文件和初始光标位置取决于“标签”,即一种goto标签。在标签文件中查找{;tag;},关联的文件成为当前文件,并执行关联的命令。通常,这用于C程序,在这种情况下,{;tag;}可以是函数名。结果是包含该函数的文件成为当前文件,并且光标位于该函数的开头。有关vim的更多信息,请使用命令“;:help tag-commands;”。
-q[errorfile] 以quickFix模式启动。文件错误文件被读入并显示第一个错误。如果错误文件被省略,从“获得的文件名错误文件;”选项(默认为“;errors.err在大多数系统”)。可以使用“;:cn;”命令将更多的错误跳转到。有关vim的更多信息,请使用命令“;:help quickfix;”。
调用vim

vim的行为取决于用于调用它的命令的名称。例如,如果您创建一个符号链接到VIM;执行与下列名称之一,它会表现在以下方式:

命令名称 行为
vim “正常”执行。一切都是默认的。
ex 以Ex模式启动。使用“;:vi;”命令进入普通模式。也可以用“做-e;”;参数。
view 以只读模式启动。您将受到保护,无法写入文件。也可以使用“;-R;”参数来完成。
GVIM,gview 该GUI版本(如果已安装)。启动一个新窗口。也可以使用“;-g;”参数来完成。
evim,;eview 在“简易模式”下运行GUI vim。该命令是vim操作的简化模式,非常类似于普通的文本编辑器。这与使用“;-y;”参数运行vim相同。
rvim,rview,rgvim,rgview 与上述类似,但以“受限”模式运行。从vim内部启动shell命令或挂起vim是不可能的。这与指定“;-Z;”参数相同。

vim is a text editor that is upwards compatible to Vi. There are a lot of enhancements above Vi: multi level undo, multiple windows and buffers, syntax highlighting, command line editing, file name completion, a complete help system, visual selection, and others.

Starting vim

Most often, vim is started to edit a single file using the following command.

vim file

More generally, the syntax for starting vim is as follows:

vim [options] [filelist]

If the filelist is missing, the editor will start with an empty buffer. Otherwise, one out of the following four options may be used to choose one or more files to be edited.

Main Options
file... A list of one or more file names. The first one will be the current file and read into the buffer. The cursor will be positioned on the first line of the buffer. You can get to the other files with the ":next" command. To edit a file that starts with a dash, precede the filelist with a double dash ("--").
- A single dash specifies that the file to edit is to be read from standard input.
-t {tag} The file to edit and the initial cursor position depends on a "tag", a sort of goto label. The {tag} is looked up in the tags file, the associated file becomes the current file and the associated command is executed. Mostly this is used for C programs, in which case {tag} could be a function name. The effect is that the file containing that function becomes the current file and the cursor is positioned on the start of the function. For more information within vim, use the command ":help tag-commands".
-q[errorfile] Start in quickFix mode. The file errorfile is read and the first error is displayed. If errorfile is omitted, the file name is obtained from the 'errorfile' option (defaults to "errors.err" on most systems). Further errors can be jumped to with the ":cn" command. For more information within vim, use the command ":help quickfix".
Invoking vim

vim behaves differently depending on the name of the command used to invoke it. For example, if you create a symbolic link to the vimexecutable with one of the following names, it will behave in the following fashion:

command name behavior
vim "Normal" execution. Everything is default.
ex Start in Ex mode. Go to Normal mode with the ":vi" command. Can also be done with the "-e" argument.
view Start in read-only mode. You will be protected from writing the files. Can also be done with the "-R" argument.
gvim, gview The GUI version (if installed). Starts a new window. Can also be done with the "-g" argument.
evim, eview Runs GUI vim in "easy mode". This command is a simplified mode of vimoperation, which is a lot like a normal text editor. This is the same as running vimwith the "-y" argument.
rvim, rview, rgvim, rgview Like the above, but running in "restricted" mode. It will not be possible to start shellcommands from within vim, or to suspend vim. This is the same as specifying the "-Z" argument.

查看英文版

查看中文版

vim 语法

vim [options] [file ..]
vim [options] -
vim [options] -t tag
vim [options] -q [errorfile]
附加选项

这些选项可以以任何顺序在文件名之前或之后给出。不带参数的选项可以在单个破折号后组合。

+[num] 对于第一个文件,光标将位于第num行。如果缺少num,则光标将位于最后一行。
+/{pat} 对于第一个文件,光标将位于第一个出现的{pat}上。在vim中,使用“:help search-pattern”命令获取可用的搜索模式。
+{command},-c{command} 在读取第一个文件之后,将执行{command}。{command}被解释为ex命令。如果{command}包含空格,则必须用双引号将其引起来(这取决于所使用的shell)。例如:

vim "+set si" main.c
您最多可以使用10个“+”或“-c”命令。
-S{file} {file}将在读取第一个文件后获得。这等效于-c“ source {file}”。{file}不能以'-'开头。如果省略{file},则使用“ Session.vim”(仅当-S为最后一个参数时有效)。
--cmd{command} 就像使用“-c”一样,但是该命令在处理任何vimrc文件之前就已执行。与“-c”命令无关,您最多可以使用10个命令。
-A 如果vim编译时支持阿拉伯语以编辑从右到左的文件和阿拉伯语键盘映射,则此选项以阿拉伯语模式启动vim,即设置了“arabic”。否则,将给出错误消息,并且vim中止。
-b 二进制模式。将设置一些选项,以便可以编辑二进制文件或可执行文件。
-C 兼容模式。设置“兼容”选项。即使存在.vimrc文件,这也将使vim的行为几乎像Vi。
-d 以差异模式启动。应该有两个,三个或四个文件名参数。vim将打开所有文件并显示它们之间的差异。像vimdiff一样工作。
-d{device} 打开{device}作为终端(仅在Amiga上)。
-D 调试模式。从脚本执行第一个命令时,请进入调试模式。
-e 以ex模式启动vim,就像可执行文件名为“ex”一样。
-E 以改进的ex模式启动vim,就像可执行文件被称为“exim”一样。
-F 前景模式。对于GUI版本,vim不会从启动它的外壳中分叉和分离。在Amiga上,不会重新启动vim来打开新窗口。当vim由等待编辑会话完成的程序(例如mail)执行时,应使用该选项。在Amiga上,“:sh”和“:!”命令将不起作用。
--nofork 前景模式。对于GUI版本,vim不会从其启动的shell中派生和分离。
-F 如果vim已通过FKMAP支持进行编译,以编辑从右到左的文件和Farsi键盘映射,则此选项以Farsi模式启动vim,即设置了'fkmap'和'rightleft'。否则,将给出错误消息,并且vim中止。
-G 如果vim已通过GUI支持进行编译,则此选项将启用GUI。如果未编译任何GUI支持,则会显示一条错误消息,并且vim中止。
-H 提供一些有关命令行参数和选项的帮助。此vim退出后。
-H 如果vim已被RIGHTLEFT支持编译以编辑从右到左的文件和希伯来语键盘映射,则此选项以希伯来语模式启动vim,即设置了“hkmap”和“rightleft”。否则,将给出错误消息,并且vim中止。
-i{viminfo} 启用使用viminfo文件时,此选项设置要使用的文件名,而不是默认的“〜/ .viminfo”。也可以通过使用名称“NONE”来跳过.viminfo文件的使用。
-L 与-r相同。
-l Lisp模式。将'lisp'和'showmatch'选项设置为开。
-m 修改文件已禁用。重置“写入”选项。您仍然可以修改缓冲区,但是无法写入文件。
-M 不允许修改。'modifiable'和'write'选项将被取消设置,因此不允许更改并且不能写入文件。请注意,可以设置这些选项以进行修改。
-N 不兼容模式。重置“兼容”选项。即使一个.vimrc文件不存在,这也会使vim表现得更好一些,但与Vi的兼容性较差。
-n 不会使用交换文件。崩溃后的恢复将是不可能的。如果要在非常慢的介质(例如软盘)上编辑文件,则非常方便。也可以用“:set uc = 0”完成。可以用“:set uc = 200”撤消。
-nb 成为NetBeans的编辑器服务器。
-o[N] 打开堆叠的N个窗口。如果省略N,则为每个文件打开一个窗口。
-O[N] 并排打开N个窗口。如果省略N,则为每个文件打开一个窗口。
-p[N] 打开N个标签页。如果省略N,则为每个文件打开一个标签页。
-R 只读模式。将设置“只读”选项。您仍然可以编辑缓冲区,但是可以防止意外覆盖文件。如果确实要覆盖文件,请在Ex命令中添加一个感叹号,如“:w!”所示。该-R选项还隐含了-n选项(见下文)。可以使用“:set noro”重置'readonly'选项。参见“:help'readonly'”。
-r 列出交换文件,以及有关使用它们进行恢复的信息。
-r{file} 恢复模式。交换文件用于恢复崩溃的编辑会话。交换文件是一个文件名,该文件名与带有“.swp”的文本文件相同。请参阅“:help恢复”。
-s 静音模式。仅当以“Ex”开头或在“-s”选项之前给出“-e”选项时。
-s{scriptin} 读取脚本文件{scriptin}。文件中的字符被解释为就像您键入它们一样。使用命令“:source!{scriptin}”可以完成相同的操作。如果在退出编辑器之前到达文件末尾,则会从键盘读取其他字符。
-T{terminal} 告诉vim您正在使用的终端的名称。仅在自动方式不起作用时才需要。应该是vim内置的终端(内置)或在termcap或terminfo文件中定义的终端。
-u{vimrc} 使用文件{vimrc}中的命令进行初始化。跳过所有其他初始化。使用它来编辑特殊类型的文件。通过使用名称“NONE”,它也可以用于跳过所有初始化。有关更多详细信息,请参见vim中的“:help初始化”。
-U{gvimrc} 使用文件{gvimrc}中的命令进行GUI初始化。跳过所有其他GUI初始化。通过提供名称“NONE”,它也可以用于跳过所有GUI初始化。有关更多详细信息,请参见vim中的“:help gui-init”。
-V[N] 详细。提供有关哪些文件来源以及用于读取和写入viminfo文件的消息。可选数字N是“详细”的值。默认值为10。
-v 以Vi模式启动vim,就像可执行文件被称为“vi”一样。这仅在可执行文件称为“ex”时才有效。
-w{scriptout} 您键入的所有字符都记录在文件{scriptout}中,直到退出vim为止。如果您要创建一个脚本文件以与“vim -s”或“:source!”一起使用,这将很有用。如果{scriptout}文件存在,则会附加字符。
-W{scriptout} 与-w类似,但是现有文件将被覆盖。
-X 写入文件时使用加密。将提示您输入密钥。
-X 不要连接到X服务器。缩短了终端的启动时间,但不会使用窗口标题和剪贴板。
-y 以简单模式启动vim,就像可执行文件被称为“evim”或“eview”一样。使vim的行为类似于单击并输入编辑器。
-Z 受限模式。像可执行文件以“r”开头的方式工作。
- 表示选项的结尾。此后的参数将作为文件名处理。这可用于编辑以'-'开头的文件名。
--echo-wid 仅限于GTK GUI:在标准输出上回显窗口ID。
--help 给出帮助消息并退出,就像“-h”一样。
--literal 从字面上接受文件名参数,请勿扩展通配符。这对外壳扩展通配符的Unix没有影响。
--noplugin 跳过加载插件。通过隐含-u NONE。
--remote 连接到vim服务器,并使其编辑其余参数中给出的文件。如果找不到服务器,则会发出警告,并在当前vim中编辑文件。
--remote-expr{expr} 连接到vim服务器,在其中评估{expr}并将结果打印在stdout上。
--remote-send{keys} 连接到vim服务器并向其发送{键}。
--remote-silent 为--remote,但是在未找到服务器时没有警告。
--remote-wait 作为--remote,但是vim直到文件被编辑后才退出。
--remote-wait-silent 为--remote-wait,但是在未找到服务器时没有警告。
--serverlist 列出可以找到的所有vim服务器的名称。
--servername{name} 使用{name}作为服务器名称。用于当前的vim,除非与--remote参数一起使用,否则它是要连接的服务器的名称。
--socketid{id} 仅限于GTK GUI:使用GtkPlug机制在另一个窗口中运行gvim。
--version 打印版本信息,然后退出。
从vim中访问帮助

在vim中输入“:help”以开始使用。输入“:help subject”以获取有关特定主题的帮助。例如:“:help ZZ”获取有关“ZZ”命令的帮助。使用和Ctrl-D完成主题(“:help cmdline-completion”)。存在标签可以从一个地方跳到另一个地方(各种超文本链接,请参见“:help”)。可以通过这种方式查看所有文档文件,例如“:help syntax.txt”。

与vim导师一起学习vim

vim会安装一个称为vimtutor的内置教程系统,以帮助您学习vim命令。这是一个30分钟的教程,将介绍最基本的vim功能。在Unix和Linux上,如果已正确安装vim,则可以通过运行以下命令从命令行启动它:

vimtutor

在MicrosoftWindows上,您可以在Programs / vim菜单中找到它,也可以在安装vim的目录中运行vimtutor.bat。

在vim中编辑:插入文本

该VIM编辑器是一个“模式”的主编。这意味着编辑器的行为根据您所处的模式而有所不同。这两种基本模式称为“普通模式”和“插入模式”。在普通模式下,您键入的字符是命令。在插入模式下,字符将作为文本插入。

由于您刚刚启动vim,因此它将处于正常模式。要启动插入模式,请键入“i”命令(i代表插入)。然后,您可以输入文本。它将被插入文件中。例如,您可以通过从命令行运行以下命令来启动新的vim会话:

vim

这将使您进入一个新的vim编辑窗口,该窗口将在没有文本的任何行上显示波浪号(“〜”)。该窗口将类似于以下内容:

┌────────────────────────────────────────────────────────┐
│~                                                       │
│~                                                       │
│~                                                       │
│~                                                       │
│                                                        │
└────────────────────────────────────────────────────────┘

您将以普通模式启动,因此要插入文本,您需要进入插入模式。您将输入i,然后输入要插入文档中的文本。因此,您可以键入以下内容:

iThis is a line of text.
This is line number two!
 

(在文字后按以开始新行)。最后,按键停止插入模式,然后返回到普通模式。现在,您在vim窗口中有两行文本:

┌────────────────────────────────────────────────────────┐
│This is a line of text.                                 │
│This is line number two!                                │
│~                                                       │
│~                                                       │
│                                                        │
└────────────────────────────────────────────────────────┘
摆脱困境

初次学习vim时,通常会因输入错误的命令或以错误的模式输入而感到困惑。在任何时候,要返回普通模式(无论您处于哪种模式),请按键。有时您必须按两次。如果vim对您发出蜂鸣声,则说明您已经处于“普通”模式。

到处走

返回到普通模式后,可以使用以下键移动:

H
j
k 向上
l

这些键对于移动光标来说似乎是奇怪的选择,但是这样做有一个很好的理由:移动光标是您在编辑器中最常执行的操作,并且这些键位于右手的主行上。换句话说,这些命令位于您可以最快键入它们的位置(尤其是十根手指键入时)。

您也可以使用箭头键移动光标。但是,如果这样做,则会大大降低编辑速度,因为要按下箭头键,必须将手从文本键移到箭头键。考虑到您可能每小时要进行数百次操作,因此可能会花费大量时间。另外,有些键盘没有箭头键,或者将它们放置在不寻常的地方。因此,了解hjkl键的使用在这些情况下会有所帮助。

学习这些命令的最佳方法是使用它们。使用“i”命令插入更多文本行。然后使用hjkl键移动并在某个位置插入一个单词。不要忘记按键返回到普通模式。该VIMTUTOR也是边做边学的简单方法。

删除字符

要删除一个字符,请将光标移到该字符上并输入“x”。例如,将光标移动到第一行的开头,然后键入xxxxxxx(七个x)以删除“This is”。结果应如下所示:

┌────────────────────────────────────────────────────────┐
│ a line of text.                                        │
│This is line number two!                                │
│~                                                       │
│~                                                       │
│                                                        │
└────────────────────────────────────────────────────────┘

现在,您可以插入新文本,例如通过键入以下内容:

iHere is

这将开始插入(i),插入单词“Here is”,然后退出插入模式()。结果:

┌────────────────────────────────────────────────────────┐
│Here is a line of text.                                 │
│This is line number two!                                │
│~                                                       │
│~                                                       │
│                                                        │
└────────────────────────────────────────────────────────┘
删除线

要删除整行,请将光标移至该行并键入“dd”。然后,下一行将向上移动以填补空白。例如,如果将光标移到第一行并键入“dd”,我们的示例将如下所示:

┌────────────────────────────────────────────────────────┐
│This is line number two!                                │
│~                                                       │
│~                                                       │
│~                                                       │
│                                                        │
└────────────────────────────────────────────────────────┘
删除换行符

在vim中,您可以将两行连接在一起,这意味着它们之间的换行符将被删除。“J”命令执行此操作。采取以下两行:

This is line
 number two

将光标移到第一行,然后按“J”:

This is line number two
撤消

“u”命令撤消上一次编辑。在vim中,多次按u继续撤消以前的编辑。这是vim与vi不同的一种方法;在vi中,按两次u会撤消撤消本身。

重做

按下Ctrl-R(重做)会反转前面的命令。因此,使用“u”执行撤消操作后,按Ctrl-R将撤消撤消操作。

追加中

“i”命令在光标下方的字符之前插入一个字符。那很好但是,如果您想在行尾添加内容会怎样?为此,您需要在光标之后插入文本。这是通过“a”(附加)命令完成的。例如,更改行

I am very excited about using vim.

I am very excited about using vim!!!

将光标移到行末的点(句点)。然后输入“x”删除句点。光标现在位于行尾。现在输入

a!!!

然后按键返回正常模式。

因此,任何时候要在光标所在的位置插入文本,请按“i”。但是,如果要在光标位置之后开始添加文本,请按“a”。

开辟一条新线

“o”命令在光标下方创建一个新的空行,并将vim置于插入模式。然后,您可以输入新行的文本。假设光标在这两行的第一行中:

I am very excited about using vim.
Amaze.

如果现在使用“o”命令并输入新文本:

oWow. Such useful. Many time saving.

然后键入返回正常模式。结果是:

I am very excited about using vim.
Wow. Such useful. Many time saving.
Amaze.

“O”命令(大写)类似,但是在光标上方而不是下方打开一行。

使用计数重复命令

假设您想向上移动九行。您可以输入“kkkkkkkkk”,也可以输入命令“9k”。实际上,您可以在许多命令之前加上数字。例如,之前我们通过键入“a !!!”在行的末尾添加了三个感叹号。另一种方法是使用命令“3a!”。计数3告诉后面的命令将其效果增加三倍。同样,要删除三个字符,请使用命令“3x”。计数始终在其适用的命令之前。

退出vim

要退出,请使用“ZZ”命令。此命令将写入文件并退出。

与其他编辑器不同,vim不会自动创建备份文件。如果输入“ZZ”,则所做的更改将被提交,并且不会后退。您可以配置vim以生成备份文件(请参见下面的“备份文件”),但是默认情况下不会这样做。

放弃更改

要退出而不保存更改,请使用命令

:q! 

对于那些感兴趣的细节,该命令的三个部分是冒号(:),其进入命令行模式;的q命令,它告诉退出编辑;和覆盖命令修饰符(!)。需要覆盖命令修饰符,因为vim不愿放弃更改。如果只输入“:q”,vim将显示一条错误消息并拒绝退出:

E37: No write since last change (use ! to override)

如果只想恢复文件的保存版本,则“:e!”命令将重新加载文件的原始版本。

从词到词

要使光标向前移动一个单词,请使用“w”命令。像大多数vim命令一样,您可以使用数字前缀来移动多个单词。例如,“3w”移动三个单词。本示例说明了它的工作原理:对于下面的文本行,如果在指示的位置按“w”,则光标将移至箭头指示的位置。

This is a line with example text w--->_ w->_ w>_ 

或者,使用数字前缀:

This is a line with example text
3w------->_

“b”命令向后移到上一个单词的开头:

还有一个“e”命令移至单词的下一个结尾,而“ge”命令移至一个单词的下一个结尾:

This is a line with example text
  ge  ge  e   e

如果您位于一行的最后一个单词,则使用“w”命令将您带到下一行的第一个单词。因此,您可以使用它来遍历段落,比使用“l”要快得多。“b”在另一个方向上也是如此。

在一个非单词字符的词端,如一个“”,“-”或“)”。要更改vim认为是单词的单词,请使用“:help iskeyword”命令。也可以按空格分隔的单词移动。这不是通常意义上的“单词”,这就是使用大写字母的原因。以此方式移动的命令是大写的,如下所示:

ge b w e
   _<  _<    -->_             -->_
This is-a line, with special/separated/words (and some more).
 __
gE B W E

通过混合使用小写和大写命令,您可以快速在段落中前后移动。

移至行的开头或结尾

“$”命令将光标移动到行尾。如果键盘具有键,它将执行相同的操作。

“^”命令移至该行的第一个非空白字符。“0”命令(零)移动到该行的第一个字符(键执行相同的操作):

^ _<----------
  This is a line with example text
__ 0 $

与大多数移动命令一样,“$”命令也要计数。但是多次移至行尾没有任何意义。因此,它使编辑器移至另一行的末尾。例如,“1 $”将您移至第一行(您所在的行)的末尾,“2 $”将移至下一行的末尾,依此类推。

“0”命令不带count参数,因为“0”将是count的一部分。

使用带有“^”的计数没有任何效果。

移到角色

最有用的移动命令之一是单字符搜索命令。命令“fx”在行中向前搜索单个字符“ x”。“ f”代表“查找”。

例如,您位于下一行的开头。假设您要转到“人类”中的“ h”。只需执行命令“fh”,光标将位于h上方:

To err is human. To forgive is divine.
--------->_ fh

您可以指定一个计数;因此,从该行的开头,您可以使用“3fo”转到“原谅”的“o”:

To err is human. To forgive is divine.
-------------------->_ 3fo

“F”(大写F)命令向左搜索:

To err is human. To forgive is divine.
     _<---------- Fh 

“tx”命令的工作方式类似于“fx”命令,但它会在搜索到的字符之前停止一个字符。“ t”代表“ To”。该命令的后向版本为“Tx”。

To err is human. To forgive is divine.
     __ Th tn

这四个命令可以用“;”重复。

“ ,”重复在另一个方向上。

光标永远不会移到另一行。即使句子继续,也不行。

有时您会开始搜索,只是意识到自己键入了错误的命令。例如,您键入“f”进行向后搜索,只是意识到您的意思是“F”。要中止搜索,请按。因此,“f”是一个中止的前向搜索,不会执行任何操作。取消大多数操作,而不仅仅是搜索。

匹配括号

在编写程序时,通常会使用嵌套的()构造。然后,“%”命令非常方便:它移至匹配的括号。如果光标在“(”移动到匹配的“)”。如果它是一个“),”它移动到匹配“(”。

% _<----
if (a == (b * c) / d)
  --------------->_ %

这也适用于[]和{}对。可以使用“matchpairs”选项来定义。在vim中使用“:help matchpairs”命令以获取更多信息。

当光标不在有用的字符上时,“%”将向前搜索以找到一个。因此,如果光标位于上一个示例的行的开头,则“%”将向前搜索并找到第一个“(”。然后移至其匹配项:

if (a == (b * c) / d)
--+--------------->_ %
移至特定行

要移至特定行,请使用“G”命令。

不带任何参数,“G”会将您放在文件末尾。快速进入文件开头的方法是使用“gg”。“1G”将执行相同的操作。

  |	first line of a file ^
   |	text text text text  |
   |	text text text text  | gg 7G |	text text text text  |
   |	text text text text
   |	text text text text
   V	text text text text  |
 text text text text  | G text text text text  |
 last line of a file  V

移到一行的另一种方法是使用带有计数的“%”命令,该命令将使您在文件中移动该百分比。例如,“50%”将您移至文件的一半。“90%”接近尾声。

上一个假设您想移动到文件中的一行,无论当前是否可见。如果您想移至可以看到的其中一行,该怎么办?此图显示了三个命令可以使用,^ h,中号和大号。

H将您移至可见屏幕的顶部,M移至中间,L移至末尾。例如:

    ┌───────────────────────────┐ H -->	| sample text       |
    | sample text       |
    | sample text       |
    | sample text       | M -->	| sample text	      |
    | sample text		  |
    | sample text       |
    | sample text       | L -->	| sample text       |
    └───────────────────────────┘

“ H”代表“首页”,“ M”代表“中”,“ L”代表“ Last”。

确定你在哪里

要查看文件中的位置,可以使用三种方法:

使用Ctrl-G命令。您会收到如下消息:

"usr_03.txt"的233 of 650 --35%-col 45-52

这将显示您正在编辑的文件的名称,光标所在的行号,总行数,通过文件的方式的百分比以及光标的列。

有时您会看到一个拆分的列号。例如,“col 2-9”。这表明光标位于第二个字符上,但是由于一个字符是一个制表符,占据了八个空格列,因此屏幕列为9。

设置“数字”选项。这将在每行前面显示一个行号:

:set number

要再次将其关闭:

:set number

由于'number'是一个布尔选项,因此在其名称前加上“no”可以将其关闭。布尔选项仅具有这两个值,可以打开或关闭。

vim有很多选择。除了布尔值以外,还有带有数字值的选项和字符串选项。您将在使用它们的地方看到示例。

设置“标尺”选项。这将在vim窗口的右下角显示光标位置:

:set ruler
卷动

在按Ctrl-U命令向下滚动文字的半个屏幕。可以考虑通过查看窗口查看文本,然后将该窗口向上移动一半。因此,窗口将在文本上移,该文本在文件中向后。如果您在记住哪个结束时有一点麻烦,请不要担心。大多数用户有相同的问题。

在按Ctrl-d命令移动所述观察窗下的文件在半个屏幕,从而滚动文本向上一半的屏幕。

                               ┌────────────────┐
                               | some text      |
                               | some text      |
                               | some text      |
┌───────────────┐              | some text      |
| some text     | Ctrl-U -->  |                |
|               |              | 123456         |
| 123456        |              └────────────────┘
| 7890          |
|               |              ┌────────────────┐
| example       | Ctrl-D -->  | 7890           |
└───────────────┘              |                |
                               | example        |
                               | example        |
                               | example        |
                               | example        |
                               └────────────────┘

要一次滚动一行,请使用Ctrl-E(向上滚动)和Ctrl-Y(向下滚动)。想想Ctrl-E给您额外一行。如果使用与MSWindows兼容的键映射,则Ctrl-Y将重做更改而不是滚动。

要向前滚动整个屏幕(两行除外),请使用Ctrl-F。另一种方法是向后,Ctrl-B是要使用的命令。幸运的是,Ctrl-F为前进,而Ctrl-B为后退,这很容易记住。

一个常见的问题是,在用“j”向下移动了许多行之后,光标位于屏幕的底部。您想用光标查看行的上下文。这是通过“zz”命令完成的。

┌──────────────────┐             ┌──────────────────┐
| some text        |             | some text        |
| some text        |             | some text        |
| some text        |             | some text        |
| some text        | zz -->   | line with cursor |
| some text        |             | some text        |
| some text        |             | some text        |
| line with cursor |             | some text        |
└──────────────────┘             └──────────────────┘

“zt”命令将光标线置于顶部,“zb”置于底部。要始终在光标周围保持几行上下文,请使用'scrolloff'选项(“:set scrolloff”)。

简单搜索

要搜索字符串,请使用“/string”命令。例如,要查找单词“ include”,请使用以下命令:

/include

您会注意到,当键入“/”时,光标会跳到vim窗口的最后一行,就像冒号命令一样。那是您输入单词的地方。您可以按退格键(backarrow或)进行更正。必要时使用<向左>和<向右>光标键。按执行命令。

注意:字符。* [] ^%/ \?〜$具有特殊含义。如果要在搜索中使用它们,则必须在它们前面加上一个\;见下文。

要查找下一个出现的相同字符串,请使用“n”命令。使用此命令在光标之后找到第一个“ #include”:

/#include

然后多次键入“n”。您将移动到文本中的每个“ #include”。如果知道所需的匹配项,也可以使用一个计数。因此“3n”找到第三场比赛。使用带有“/”的计数不起作用。

“?”命令的工作方式类似于“/”,但向后搜索:

?word

“N”命令以相反的方向重复最后的搜索。因此,使用“Ñ”后一个“/”命令搜索向后,使用“Ñ”之后的“?”向前搜索。

忽略大小写

通常,您必须完全键入要查找的内容。如果您不关心单词中的大写或小写,请设置'ignorecase'选项:

:set ignorecase

如果现在搜索“单词”,则它将同时匹配“单词”和“单词”。要再次匹配大小写:

:set noignorecase
历史

假设您进行了三个搜索:

/one
/two
/three

现在,让我们通过键入一个简单的“/”开始搜索,而无需按键。如果按(光标键),vim在命令行上输入“/ three”。此时按搜索三个。如果您没有按,而是按,vim会将提示更改为“/ two”。再次按键将您移至“/ one”。

您还可以使用光标键在另一个方向上浏览搜索命令的历史记录。

如果您知道以前使用的模式以什么开头,并且想再次使用它,请在按之前键入该字符。在前面的示例中,您可以键入“/ o”,并且vim将在命令行上放置“/ one”。

以“:”开头的命令也有历史记录。这样您就可以调用上一个命令并再次执行它。这两个历史是分开的。

在文本中搜索单词

假设您在文本中看到单词“ TheLongFunctionName”,并且想找到它的下一个出现位置。您可以键入“/ TheLongFunctionName”,但这很多。

有一种更简单的方法:将光标定位在单词上,然后使用“*”命令。vim会抓住光标下的单词并将其用作搜索字符串。

“#”命令在另一个方向上的作用相同。您可以在前面加上一个数字:“3 *”在光标下搜索单词的第三次出现。

搜索整个词

如果您输入“/ the”,它将也匹配“ there”。要仅找到以“ the”结尾的单词,请使用:

/ the \>

“\>”表示法是一种特殊标记,仅在单词的末尾匹配。同样,“\ <”仅匹配单词的开头。因此,仅搜索单词“ the”:

/ \ 

这与“ there”或“ soothe”不匹配。注意:“*”和“#”命令使用这些单词开头和单词结尾标记仅查找整个单词(您可以使用“g *”和“g#”来匹配部分单词)。

突出显示比赛

在编辑程序时,您会看到一个名为“ nr”的变量。您想检查它的使用位置。您可以将光标移动到“ nr”并使用“*”命令,然后按“n”进行所有匹配。

还有另一种方式。输入以下命令:

:set hlsearch

如果现在搜索“nr”,vim将突出显示所有匹配项。这是查看变量使用位置的好方法,而无需键入命令。

要将其关闭:

:set nohlsearch

然后,如果要将其用于下一个搜索命令,则需要再次将其打开。如果只想删除突出显示,请使用以下命令:

:nohlsearch

这不会重置该选项。而是禁用了突出显示。一旦执行搜索命令,突出显示将再次使用。同样,对于“n”和“N”命令。

调整搜索

有一些选项可以更改搜索的工作方式。这些是必不可少的:

:set incsearch

这使得vim在您仍在键入字符串时显示该字符串的匹配项。使用它来检查是否找到正确的匹配项。然后按键真正跳到该位置。或键入更多以更改搜索字符串。

:set nowrapscan

这将在文件末尾停止搜索。或者,当您向后搜索时,在文件的开头。默认情况下,“wrapscan”选项处于启用状态,因此可以在文件末尾进行换行搜索。

间奏曲

如果您喜欢前面提到的选项之一,并且在每次使用vim时进行设置,则可以将该命令放入vim启动文件中。

如果您需要了解启动文件的位置,请使用以下命令:

:scriptnames

编辑文件,例如使用:

:edit~/.vimrc

然后在命令中添加一行以设置选项,就像在vim中键入它一样。例:

Go:set hlsearch

“G”移到文件末尾。“o”开始新行,在其中键入“:set”命令。您可以使用结束插入模式。然后写文件:

ZZ

如果现在再次启动vim,则已经设置了'hlsearch'选项。

简单的搜索模式

该VIM编辑器使用正则表达式(“正则表达式”)来指定要搜索的内容。正则表达式是一种非常强大且紧凑的方式来指定搜索模式。

正则表达式:行的开头和结尾

该^(插入符号)字符一行的开头匹配。模式“包含”与行上任何位置的单词“包含”匹配。但是模式“^ include”仅在行的开头与单词include匹配。

在$字符行的结尾相匹配。因此,“was $”仅在行的末尾与单词“ was”匹配。

您可以尝试使用“/ ^ the $”进行搜索,它只会匹配包含单词“ the”的一行。空格很重要;因此,如果一行在单词之后包含空格,例如“ the”,则该模式将不匹配。

正则表达式:匹配任何单个字符

的。(点或句点)字符与任何现有字符匹配。例如,模式“cm”匹配第一个字符为“ c”,第二个字符为任意,第三个字符为“ m”的字符串。

正则表达式:匹配特殊字符

如果您确实想匹配一个点,则必须在其前面加上反斜杠来避免其特殊含义,例如:“\。”。对于任何特殊字符(。* [] ^%/ \?〜$)也是如此。

使用标记

当您使用“G”命令跳转到某个位置时,vim会记住该跳转之前的位置。该位置称为标记。要返回您的来源,请使用以下命令:

``

这个`是反引号或开放的单引号字符。

如果第二次使用同一命令,您将再次跳回。这是因为'命令是跳本身,从这个跳跃想起之前的位置。

通常,每次您执行的命令都可以将光标移动到同一行内,这称为跳转。这包括搜索命令“/”和“n”(匹配距离多远无关紧要)。但是,字符不会使用“fx”和“tx”或单词运动“w”和“e”来搜索。

同样,“j”和“k”不被视为跳跃。即使使用计数使它们将光标移到很远的地方。

该``命令跳来回,两个点之间。在按Ctrl-O命令则跳到一个旧的位置(“O”代表“老”)。Ctrl-I然后跳回到较新的位置。考虑以下命令序列:

33G
/~the
Ctrl-O

您首先跳到第33行,然后搜索以“ The”开头的行。然后使用Ctrl-O跳回到第33行。另一个Ctrl-O则将您带回到开始的地方。如果现在使用Ctrl-I,您将再次跳至第33行。并使用另一个Ctrl-I匹配“ The”。

注意:Ctrl-I与相同。

“:jumps”命令列出了您跳转到的位置。您上次使用的条目标有“>”。

命名商标

vim使您可以在文本中放置标记。命令“ma”将光标下方的位置标记为标记“ a”。您可以在文本中放置26个标记(从a到z)。您看不到它们,这只是vim记住的位置。

要转到标记,请使用命令`{mark},其中{mark}是标记字母。从而移动到一个标记:

`a

命令'标记(单引号或撇号)将您移至包含该标记的行的开头。这与`mark命令不同,后者将您移至带标记的列。

当处理文件中的两个相关部分时,标记可能非常有用。假设在文件开头附近有一些文本,而在文件末尾附近有一些文本。

移至开头的文本,然后在此处放置“ s”(开始)标记:

ms

然后移至您要处理的文本,并在此处添加“ e”(结束)标记:

me

现在您可以四处移动,当您要查看文件的开头时,可以使用它跳转到那里:

's

然后,您可以使用'跳回到原来的位置,或使用'e跳到最后处理的文本。

使用“ s”作为开始,使用“ e”作为结束并没有什么特别的,它们很容易记住。

您可以使用此命令来获取标记列表:

:marks

您会注意到一些特殊标记。这些包括:

'' 进行跳转之前的光标位置。
上次编辑文件时的光标位置。
[ 最后更改的开始。
] 最后更改的结束。
操作员和动作

“dw”命令删除一个单词。您可以将“w”命令识别为移动字命令。实际上,“d”命令后可以跟随任何运动命令,并且它会从当前位置删除到光标结束的位置。例如,“4w”命令可将光标移动到四个单词上。该D4W命令删除4个单词。

To err is human. To forgive is divine. To breathe is required.
        ---------------------> d4w To err is human. To breathe is required.

vim仅删除运动到光标所在的位置。这是因为vim知道您可能不想删除单词的第一个字符。如果使用“e”命令移至单词的末尾,vim会猜测您确实希望包含最后一个字符:

To err is human. To breathe is required.
        ----------> d2e To err is human. is required.

是否包括光标下的字符取决于您用来移动到该字符的命令。不包含字符时称为“排他性”,包含字符时称为“包含性”。

“$”命令移至行尾。“d $”命令从光标删除到行尾,这是一个包含性动作,因此该行的最后一个字符包含在删除操作中:

To err is human. is divine.
        --------> d$ To err is human.

这里有一个模式:操作员运动。您首先键入一个操作员命令。例如,“d”是删除运算符。然后键入一个运动命令,例如“4l”或“w”。这样,您可以对可以移动的任何文本进行操作。

更改文字

另一个运算符是“c”,请更改。它的作用类似于“d”运算符,只是它使您处于“插入”模式。例如,“cw”更改一个单词。或更具体地说,它会删除一个单词,然后将您置于插入模式。

To err is human
 -------> c2wbeTo be human

此“c2wbe”包含以下位:

C 变更运算符。
2w 移动两个词(它们将被删除并开始插入模式)。
be 插入此文本。
返回普通模式。

“Esc”之前的空格不会被删除。该Ç操作符就像d运营商,但有一个例外:“CW”。它实际上就像“ce”一样工作,改为字尾。因此,单词后的空格不包括在内,这是一个可追溯到旧Vi的例外。由于现在许多人都习惯了,不一致性一直留在VIM。

vim [options] [file ..]
vim [options] -
vim [options] -t tag
vim [options] -q [errorfile]
Additional Options

The options may be given in any order, before or after file names. Options without an argument can be combined after a single dash.

+[num] For the first file the cursor will be positioned on line num. If num is missing, the cursor will be positioned on the last line.
+/{pat} For the first file the cursor will be positioned on the first occurrence of {pat}. From withinvim, use the ":help search-pattern" command for the available search patterns.
+{command}, -c{command} {command} will be executed after the first file has been read. {command} is interpreted as an ex command. If the {command} contains spaces it must be enclosed in double quotes (this depends on the shell that is used). For example:

vim "+set si" main.c
You can use up to 10 "+" or "-c" commands.
-S {file} {file} will be sourced after the first file has been read. This is equivalent to -c "source {file}". {file} cannot start with '-'. If {file} is omitted, "Session.vim"is used (only works when -S is the last argument).
--cmd{command} Like using "-c", but the command is executed just before processing any vimrcfile. You can use up to 10 of these commands, independently from "-c" commands.
-A If vim has been compiled with Arabic support for editing right-to-left oriented files and Arabic keyboard mapping, this option starts vim in Arabic mode, i.e. 'arabic' is set. Otherwise, an error message is given and vim aborts.
-b Binary mode. A few options will be set that makes it possible to edit a binary or executable file.
-C Compatible mode. Sets the 'compatible' option. This will make vim behave mostly like Vi, even though a .vimrc file exists.
-d Start in diff mode. There should be two, three or four file name arguments. vimwill open all the files and show differences between them. Works like vimdiff.
-d {device} Open {device} for use as a terminal (only on the Amiga).
-D Debugging mode. Go to debugging mode when executing the first command from a script.
-e Start vim in ex mode, just like if the executable is called "ex".
-E Start vim in improved ex mode, just like if the executable was called "exim".
-f Foreground mode. For the GUI version, vim will not fork and detach from the shell it was started in. On the Amiga, vim is not restarted to open a new window. This option should be used when vim is executed by a program that will wait for the edit session to finish (e.g., mail). On the Amiga the ":sh" and ":!" commands will not work.
--nofork Foreground mode. For the GUI version, vim will not fork and detach from the shell it was started in.
-F If vim has been compiled with FKMAP support for editing right-to-left oriented files and Farsi keyboard mapping, this option starts vim in Farsi mode, i.e. 'fkmap' and 'rightleft' are set. Otherwise, an error message is given and vimaborts.
-g If vim has been compiled with GUI support, this option enables the GUI. If no GUI support was compiled in, an error message is given and vim aborts.
-h Give a bit of help about the command line arguments and options. After this vimexits.
-H If vim has been compiled with RIGHTLEFT support for editing right-to-left oriented files and Hebrew keyboard mapping, this option starts vim in Hebrew mode, i.e. 'hkmap' and 'rightleft' are set. Otherwise, an error message is given and vim aborts.
-i {viminfo} When using the viminfo file is enabled, this option sets the file name to use, instead of the default "~/.viminfo". This can also be used to skip the use of the .viminfo file, by giving the name "NONE".
-L Same as -r.
-l Lisp mode. Sets the 'lisp' and 'showmatch' options on.
-m Modifying files is disabled. Resets the 'write' option. You can still modify the buffer, but writing a file is not possible.
-M Modifications not allowed. The 'modifiable' and 'write' options will be unset, so that changes are not allowed and files can not be written. Note that these options can be set to enable making modifications.
-N No-compatible mode. Reset the 'compatible' option. This will make vim behave a bit better, but less Vi compatible, even though a .vimrc file does not exist.
-n No swap file will be used. Recovery after a crash will be impossible. Handy if you want to edit a file on a very slow medium (e.g., floppy). Can also be done with ":set uc=0". Can be undone with ":set uc=200".
-nb Become an editor server for NetBeans.
-o[N] Open N windows stacked. When N is omitted, open one window for each file.
-O[N] Open N windows side by side. When N is omitted, open one window for each file.
-p[N] Open N tab pages. When N is omitted, open one tab page for each file.
-R Read-only mode. The 'readonly' option will be set. You can still edit the buffer, but will be prevented from accidently overwriting a file. If you do want to overwrite a file, add an exclamation mark to the Ex command, as in ":w!". The -Roption also implies the -n option (see below). The 'readonly' option can be reset with ":set noro". See ":help 'readonly'".
-r List swap files, with information about using them for recovery.
-r {file} Recovery mode. The swap file is used to recover a crashed editing session. The swap file is a file with the same file name as the text file with ".swp" appended. See ":help recovery".
-s Silent mode. Only when started as "Ex" or when the "-e" option was given before the "-s" option.
-s {scriptin} The script file {scriptin} is read. The characters in the file are interpreted as if you had typed them. The same can be done with the command ":source! {scriptin}". If the end of the file is reached before the editor exits, further characters are read from the keyboard.
-T {terminal} Tells vim the name of the terminal you are using. Only required when the automatic way doesn't work. Should be a terminal known to vim (builtin) or defined in the termcap or terminfo file.
-u {vimrc} Use the commands in the file {vimrc} for initializations. All the other initializations are skipped. Use this to edit a special kind of files. It can also be used to skip all initializations by giving the name "NONE". See ":help initialization" within vim for more details.
-U {gvimrc} Use the commands in the file {gvimrc} for GUI initializations. All the other GUI initializations are skipped. It can also be used to skip all GUI initializations by giving the name "NONE". See ":help gui-init" within vim for more details.
-V[N] Verbose. Give messages about which files are sourced and for reading and writing a viminfo file. The optional number N is the value for 'verbose'. Default is 10.
-v Start vim in Vi mode, just like the executable was called "vi". This only has effect when the executable is called "ex".
-w{scriptout} All the characters that you type are recorded in the file {scriptout}, until you exit vim. This is useful if you want to create a script file to be used with "vim -s" or ":source!". If the {scriptout} file exists, characters are appended.
-W{scriptout} Like -w, but an existing file is overwritten.
-x Use encryption when writing files. Will prompt for a crypt key.
-X Don't connect to the X server. Shortens startup time in a terminal, but the window title and clipboard will not be used.
-y Start vim in easy mode, just like the executable was called "evim" or "eview". Makes vim behave like a click-and-type editor.
-Z Restricted mode. Works like the executable starts with "r".
-- Denotes the end of the options. Arguments after this will be handled as a file name. This can be used to edit a file name that starts with a '-'.
--echo-wid GTK GUI only: Echo the Window ID on standard output.
--help Give a help message and exit, just like "-h".
--literal Take file name arguments literally, do not expand wildcards. This has no effect on Unix where the shell expands wildcards.
--noplugin Skip loading plugins. Implied by -u NONE.
--remote Connect to a vim server and make it edit the files given in the rest of the arguments. If no server is found a warning is given and the files are edited in the current vim.
--remote-expr {expr} Connect to a vim server, evaluate {expr} in it and print the result on stdout.
--remote-send {keys} Connect to a vim server and send {keys} to it.
--remote-silent As --remote, but without the warning when no server is found.
--remote-wait As --remote, but vim does not exit until the files have been edited.
--remote-wait-silent As --remote-wait, but without the warning when no server is found.
--serverlist List the names of all vim servers that can be found.
--servername{name} Use {name} as the server name. Used for the current vim, unless used with a --remote argument, then it's the name of the server to connect to.
--socketid{id} GTK GUI only: Use the GtkPlug mechanism to run gvim in another window.
--version Print version information, and exit.
Accessing Help From Within vim

Type ":help" in vim to get started. Type ":help subject" to get help on a specific subject. For example: ":help ZZ" to get help for the "ZZ" command. Use  and Ctrl-D to complete subjects (":help cmdline-completion"). Tags are present to jump from one place to another (sort of hypertext links, see ":help"). All documentation files can be viewed in this way, for example ":help syntax.txt".

Learning vim With The vim Tutor

vim installs with a built-in tutorial system called the vimtutor to help you learn vim commands. It is a 30 minute tutorial that teaches the most basic vim functionality hands-on. On Unix and Linux, if vim has been properly installed, you can start it from the command line by running the command:

vimtutor

On Microsoft Windows you can find it in the Programs/vim menu, or you can run vimtutor.bat in the directory where vim was installed.

Editing In vim: Inserting Text

The vim editor is a "modal" editor. That means that the editor behaves differently depending on which mode you are in. The two basic modes are called Normal mode and Insert mode. In Normal mode the characters you type are commands. In Insert mode the characters are inserted as text.

Since you have just started vim it will be in Normal mode. To start Insert mode you type the "i" command (i for Insert). Then you can enter the text. It will be inserted into the file. For example, you can start a new vim session by running the following command from the command line:

vim

This will place you in a new vim editing window, which will show a tilde("~") on any line that is empty of text. The window will resemble the following:

┌────────────────────────────────────────────────────────┐
│~                                                       │
│~                                                       │
│~                                                       │
│~                                                       │
│                                                        │
└────────────────────────────────────────────────────────┘

You will start in normal mode, so to insert text you will need to enter insert mode. You will type i, and then the text you want to insert into the document. So, you can type the following:

iThis is a line of text.
This is line number two!

(Press  after the word text to start the new line). Finally you press the  key to stop Insert mode and go back to Normal mode. You now have two lines of text in your vim window:

┌────────────────────────────────────────────────────────┐
│This is a line of text.                                 │
│This is line number two!                                │
│~                                                       │
│~                                                       │
│                                                        │
└────────────────────────────────────────────────────────┘
Getting Out Of Trouble

When first learning vim, it is common to get confused by typing the wrong command, or typing it in the wrong mode. At all times, to get back to Normal mode (no matter what mode you are in), press the  key. Sometimes you have to press it twice. If vim beeps at you, you already are in Normal mode.

Moving Around

After you return to Normal mode, you can move around by using these keys:

h left
j down
k up
l right

These keys may seem like odd choices for moving the cursor, but there is a very good reason for these: Moving the cursor is the most common thing you do in an editor, and these keys are on the home row of your right hand. In other words, these commands are placed where you can type them the fastest (especially when you type with ten fingers).

You can also move the cursor by using the arrow keys. If you do, however, you greatly slow down your editing because to press the arrow keys, you must move your hand from the text keys to the arrow keys. Considering that you might be doing it hundreds of times an hour, this can take a significant amount of time. Also, there are keyboards which do not have arrow keys, or which locate them in unusual places; therefore, knowing the use of the hjkl keys helps in those situations.

The best way to learn these commands is by using them. Use the "i" command to insert some more lines of text. Then use the hjkl keys to move around and insert a word somewhere. Don't forget to press  to go back to Normal mode. The vimtutor is also an easy way to learn by doing.

Deleting Characters

To delete a character, move the cursor over it and type "x". Move the cursor to the beginning of the first line, for example, and type xxxxxxx (seven x's) to delete "This is". The result should look like this:

┌────────────────────────────────────────────────────────┐
│ a line of text.                                        │
│This is line number two!                                │
│~                                                       │
│~                                                       │
│                                                        │
└────────────────────────────────────────────────────────┘

Now you can insert new text, for example by typing:

iHere is

This begins an insert (the i), inserts the words "Here is", and then exits insert mode (). The result:

┌────────────────────────────────────────────────────────┐
│Here is a line of text.                                 │
│This is line number two!                                │
│~                                                       │
│~                                                       │
│                                                        │
└────────────────────────────────────────────────────────┘
Deleting A Line

To delete a whole line, move the cursor to that line and type "dd". The next line will then move up to fill the gap. For instance, if you move the cursor to the first line and type "dd", our example will look like:

┌────────────────────────────────────────────────────────┐
│This is line number two!                                │
│~                                                       │
│~                                                       │
│~                                                       │
│                                                        │
└────────────────────────────────────────────────────────┘
Deleting A Line Break

In vim you can join two lines together, which means that the line break between them is deleted. The "J" command does this. Take these two lines:

This is line 
   number two

Move the cursor to the first line and press "J":

This is line number two
Undo

The "u" command undoes the last edit. In vim, pressing u multiple times continues to undo previous edits. This is one of the ways vim is different than vi; in vi, pressing u twice undoes the undo itself.

Redo

Pressing Ctrl-R (redo) reverses the preceding command. So, after performing an undo with "u", pressing Ctrl-R will undo the undo.

Appending

The "i" command inserts a character before the character under the cursor. That works fine; but what happens if you want to add stuff to the end of the line? For that you need to insert text after the cursor. This is done with the "a" (append) command. For example, to change the line

I am very excited about using vim.

to

I am very excited about using vim!!!

move the cursor over to the dot (period) at the end of the line. Then type "x" to delete the period. The cursor is now positioned at the end of the line. Now type

a!!!

And then press  to return to normal mode.

So, any time you want to insert text right where the cursor is, press "i". But if you want to start adding text after the cursor position, press "a".

Opening Up A New Line

The "o" command creates a new, empty line below the cursor and puts vim in Insert mode. Then you can type the text for the new line. Suppose the cursor is somewhere in the first of these two lines:

I am very excited about using vim. 
Amaze.

If you now use the "o" command and type new text:

oWow. Such useful. Many time saving.

Then type  to return to normal mode. The result is:

I am very excited about using vim.
Wow. Such useful. Many time saving.
Amaze.

The "O" command (uppercase) is similar, but opens a line above the cursor instead of below it.

Repeating A Command Using A Count

Suppose you want to move up nine lines. You can type "kkkkkkkkk" or you can enter the command "9k". In fact, you can precede many commands with a number. For instance, earlier we added three exclamation points to the end of a line by typing "a!!!". Another way to do this is to use the command "3a!". The count of 3 tells the command that follows to triple its effect. Similarly, to delete three characters, use the command "3x". The count always comes before the command it applies to.

Quitting vim

To exit, use the "ZZ" command. This command writes the file and exits.

Unlike other editors, vim does not automatically make a backup file. If you type "ZZ", your changes are committed and there's no turning back. You can configure vim to produce backup files (see "Backup Files", below), but it will not do so by default.

Discarding Changes

To exit without saving your changes, use the command

:q!

For those of you interested in the details, the three parts of this command are the colon (:), which enters Command-line mode; the qcommand, which tells the editor to quit; and the override command modifier (!). The override command modifier is needed because vim is reluctant to throw away changes. If you were to just type ":q", vimwould display an error message and refuse to exit:

E37: No write since last change (use ! to override)

If you merely want to revert to the saved version of the file, the ":e!" command reloads the original version of the file.

Moving From Word To Word

To move the cursor forward one word, use the "w" command. Like most vim commands, you can use a numeric prefix to move past multiple words. For example, "3w" moves three words. This example shows how it works: For the following line of text, if you press "w" where indicated, the cursor moves to the place indicated by the arrow.

This is a line with example text w--->_ w->_ w>_

Or, using the numeric prefix:

This is a line with example text 3w------->_

The "b" command moves backward to the start of the previous word:

There is also the "e" command that moves to the next end of a word and "ge", which moves to the previous end of a word:

This is a line with example textge    ge     e       e

If you are at the last word of a line, the "w" command will take you to the first word in the next line. Thus you can use this to move through a paragraph, much faster than using "l". "b" does the same in the other direction.

A word ends at a non-word character, such as a ".", "-" or ")". To change what vim considers to be a word, use the ":help iskeyword" command. It is also possible to move by white space-separated words. This is not a "word" in the normal sense, that's why the uppercase is used. The commands for moving this way are in uppercase, as shown here:

 ge b w e _<     _<         -->_                          -->_
This is-a line, with special/separated/words (and some more). 
   __ gE B W E 

With this mix of lowercase and uppercase commands, you can quickly move forward and backward through a paragraph.

Moving To The Start Or End Of A Line

The "$" command moves the cursor to the end of a line. If your keyboard has an  key it will do the same thing.

The "^" command moves to the first non-blank character of the line. The "0" command (zero) moves to the very first character of the line (the  key does the same thing):

 ^ _<----------
     This is a line with example text 
__ 0 $ 

The "$" command takes a count, like most movement commands. But moving to the end of the line several times doesn't make sense. Therefore it causes the editor to move to the end of another line. For example, "1$" moves you to the end of the first line (the one you're on), "2$" to the end of the next line, and so on.

The "0" command doesn't take a count argument, because the "0" would be part of the count.

Using a count with "^" doesn't have any effect.

Moving To A Character

One of the most useful movement commands is the single-character search command. The command "fx" searches forward in the line for the single character "x". The "f" stands for "Find".

For example, you are at the beginning of the following line. Suppose you want to go to the "h" in "human". Just execute the command "fh" and the cursor will be positioned over the h:

To err is human. To forgive is divine. 
--------->_ fh 

You can specify a count; so, from the beginning of the line, you can go to the "o" of "forgive" with "3fo":

To err is human. To forgive is divine. 
-------------------->_ 3fo 

The "F" (uppercase F) command searches to the left:

To err is human. To forgive is divine.
          _<---------- Fh 

The "tx" command works like the "fx" command, except it stops one character before the searched character. The "t" stands for "To". The backward version of this command is "Tx".

To err is human. To forgive is divine. 
          __ Th tn 

These four commands can be repeated with ";".

"," repeats in the other direction.

The cursor is never moved to another line. Not even when the sentence continues.

Sometimes you will start a search, only to realize that you have typed the wrong command. You type "f" to search backward, for example, only to realize that you really meant "F". To abort a search, press . So "f" is an aborted forward search and doesn't do anything. cancels most operations, not just searches.

Matching A Parenthesis

When writing a program you often end up with nested()constructs. Then the "%" command is very handy: It moves to the matching parenthesis. If the cursor is on a "(" it moves to the matching ")". If it's on a ")" it moves to the matching "(".

 % _<----
if (a == (b * c) / d) 
    --------------->_ % 

This also works for [] and {} pairs. This can be defined with the 'matchpairs' option. Use the ":help matchpairs" command within vimfor more information.

When the cursor is not on a useful character, "%" will search forward to find one. Thus if the cursor is at the start of the line of the previous example, "%" will search forward and find the first "(". Then it moves to its match:

if (a == (b * c) / d) 
 --+--------------->_ % 
Moving To A Specific Line

To move to a specific line, use the "G" command.

With no argument, "G" positions you at the end of the file. A quick way to go to the start of a file use "gg". "1G" will do the same.

	    |	first line of a file   ^
	    |	text text text text    |
	    |	text text text text    | gg 7G |	text text text text    |
	    |	text text text text
	    |	text text text text
	    V	text text text text    |
		text text text text    | G text text text text    |
		last line of a file    V

Another way to move to a line is using the "%" command with a count, which moves you that percent through the file. For example "50%" moves you to halfway the file. "90%" goes to near the end.

The previous assumes that you want to move to a line in the file, no matter if it's currently visible or not. What if you want to move to one of the lines you can see? This figure shows the three commands you can use, H, M, and L.

H moves you to the top of the visible screen, M to the middle, and L to the end. For example:

        ┌───────────────────────────┐ H -->	| sample text               |
        | sample text               |
        | sample text               |
        | sample text               | M -->	| sample text	            |
        | sample text		    |
        | sample text               |
        | sample text               | L -->	| sample text               |
        └───────────────────────────┘

"H" stands for Home, "M" stands for Middle and "L" stands for Last.

Determining Where You Are

To see where you are in a file, there are three ways:

Use the Ctrl-G command. You get a message like this:

"usr_03.txt" line 233 of 650 --35%-- col 45-52

This shows the name of the file you are editing, the line number where the cursor is, the total number of lines, the percentage of the way through the file and the column of the cursor.

Sometimes you will see a split column number. For example, "col 2-9". This indicates that the cursor is positioned on the second character, but because character one is a tab, occupying eight spaces worth of columns, the screen column is 9.

Set the 'number' option. This displays a line number in front of every line:

:set number

To switch this off again:

:set nonumber

Since 'number' is a boolean option, prepending "no" to its name has the effect of switching it off. A boolean option has only these two values, it is either on or off.

vim has many options. Besides the boolean ones there are options with a numerical value and string options. You will see examples of this where they are used.

Set the 'ruler' option. This displays the cursor position in the lower right corner of the vim window:

:set ruler
Scrolling

The Ctrl-U command scrolls down half a screen of text. Think of looking through a viewing window at the text and moving this window up by half the height of the window. Thus the window moves up over the text, which is backward in the file. Don't worry if you have a little trouble remembering which end is up. Most users have the same problem.

The Ctrl-D command moves the viewing window down half a screen in the file, thus scrolls the text up half a screen.

                               ┌────────────────┐
                               | some text      |
                               | some text      |
                               | some text      |
┌───────────────┐              | some text      |
| some text     | Ctrl-U -->  |                |
|               |              | 123456         |
| 123456        |              └────────────────┘
| 7890          |
|               |              ┌────────────────┐
| example       | Ctrl-D -->  | 7890           |
└───────────────┘              |                |
                               | example        |
                               | example        |
                               | example        |
                               | example        |
                               └────────────────┘

To scroll one line at a time use Ctrl-E (scroll up) and Ctrl-Y (scroll down). Think of Ctrl-E to give you one line Extra. If you use MSWindows-compatible key mappings Ctrl-Y will redo a change instead of scroll.

To scroll forward by a whole screen (except for two lines) use Ctrl-F. The other way is backward, Ctrl-B is the command to use. Fortunately Ctrl-F is Forward and Ctrl-B is Backward, that's easy to remember.

A common issue is that after moving down many lines with "j" your cursor is at the bottom of the screen. You would like to see the context of the line with the cursor. That's done with the "zz" command.

┌──────────────────┐             ┌──────────────────┐
| some text        |             | some text        |
| some text        |             | some text        |
| some text        |             | some text        |
| some text        | zz -->   | line with cursor |
| some text        |             | some text        |
| some text        |             | some text        |
| line with cursor |             | some text        |
└──────────────────┘             └──────────────────┘

The "zt" command puts the cursor line at the top, "zb" at the bottom. To always keep a few lines of context around the cursor, use the 'scrolloff' option (":set scrolloff").

Simple Searches

To search for a string, use the "/string" command. To find the word "include", for example, use the command:

/include

You will notice that when you type the "/" the cursor jumps to the last line of the vim window, like with colon commands. That is where you type the word. You can press the backspace key (backarrow or ) to make corrections. Use the  and  cursor keys when necessary. Pressing  executes the command.

Note: The characters .*[]^%/\?~$ have special meanings. If you want to use them in a search you must put a \ in front of them; see below.

To find the next occurrence of the same string use the "n" command. Use this to find the first "#include" after the cursor:

/#include

And then type "n" several times. You move to each "#include" in the text. You can also use a count if you know which match you want. Thus "3n" finds the third match. Using a count with "/" doesn't work.

The "?" command works like "/" but searches backwards:

?word

The "N" command repeats the last search the opposite direction. Thus using "N" after a "/" command search backwards, using "N" after "?" searches forward.

Ignoring Case

Normally you have to type exactly what you want to find. If you don't care about upper or lowercase in a word, set the 'ignorecase' option:

:set ignorecase

If you now search for "word", it will also match "Word" and "WORD". To match case again:

:set noignorecase
History

Suppose you do three searches:

/one
/two
/three

Now let's start searching by typing a simple "/" without pressing . If you press  (the cursor key), vim puts "/three" on the command line. Pressing  at this point searches for three. If you do not press , but press  instead, vim changes the prompt to "/two". Another press of  moves you to "/one".

You can also use the  cursor key to move through the history of search commands in the other direction.

If you know what a previously used pattern starts with, and you want to use it again, type that character before pressing . With the previous example, you can type "/o" and vim will put "/one" on the command line.

The commands starting with ":" also have a history. That allows you to recall a previous command and execute it again. These two histories are separate.

Searching For A Word In The Text

Suppose you see the word "TheLongFunctionName" in the text and you want to find the next occurrence of it. You could type "/TheLongFunctionName", but that's a lot of typing.

There is an easier way: Position the cursor on the word and use the "*" command. vim will grab the word under the cursor and use it as the search string.

The "#" command does the same in the other direction. You can prepend a count: "3*" searches for the third occurrence of the word under the cursor.

Searching For Whole Words

If you type "/the" it will also match "there". To only find words that end in "the" use:

/the\>

The "\>" notation is a special marker that only matches at the end of a word. Similarly "\<" only matches at the begin of a word. Thus to search for the word "the" only:

/\

This does not match "there" or "soothe". Notice that the "*" and "#" commands use these start-of-word and end-of-word markers to only find whole words (you can use "g*" and "g#" to match partial words).

Highlighting Matches

While editing a program you see a variable called "nr". You want to check where it's used. You could move the cursor to "nr" and use the "*" command and press "n" to go along all the matches.

There is another way. Type this command:

:set hlsearch

If you now search for "nr", vim will highlight all matches. That is a very good way to see where the variable is used, without the need to type commands.

To switch this off:

:set nohlsearch

Then you need to switch it on again if you want to use it for the next search command. If you only want to remove the highlighting, use this command:

:nohlsearch

This doesn't reset the option. Instead, it disables the highlighting. As soon as you execute a search command, the highlighting will be used again. Also, for the "n" and "N" commands.

Tuning Searches

There are a few options that change how searching works. These are the essential ones:

:set incsearch

This makes vim display the match for the string while you are still typing it. Use this to check if the right match will be found. Then press  to really jump to that location. Or type more to change the search string.

:set nowrapscan

This stops the search at the end of the file. Or, when you are searching backwards, at the start of the file. The 'wrapscan' option is on by default, thus searching wraps around the end of the file.

Intermezzo

If you like one of the options mentioned before, and set it each time you use vim, you can put the command in your vim startup file.

If you need to learn where the startup file is, use this command:

:scriptnames

Edit the file, for example with:

:edit ~/.vimrc

Then add a line with the command to set the option, just like you typed it in vim. Example:

Go:set hlsearch

"G" moves to the end of the file. "o" starts a new line, where you type the ":set" command. You end insert mode with . Then write the file:

ZZ

If you now start vim again, the 'hlsearch' option will already be set.

Simple Search Patterns

The vim editor uses regular expressions ("Regex") to specify what to search for. Regular expressions are an extremely powerful and compact way to specify a search pattern.

Regex: Beginning And End Of A Line

The ^ (caret) character matches the beginning of a line. The pattern "include" matches the word include anywhere on the line. But the pattern "^include" matches the word include only if it is at the beginning of a line.

The $ character matches the end of a line. Therefore, "was$" matches the word "was" only if it is at the end of a line.

You can try searching with "/^the$", it will only match a single line consisting soley of the word "the". White space matters; therefore if a line contains a space after the word, like "the ", the pattern will not match.

Regex: Matching Any Single Character

The . (dot, or period) character matches any existing character. For example, the pattern "c.m" matches a string whose first character is a "c", whose second character is anything, and whose the third character is "m".

Regex: Matching Special Characters

If you really want to match a dot, you must avoid its special meaning by putting a backslash before it, like this: "\.". The same goes for any special character (.*[]^%/\?~$).

Using Marks

When you make a jump to a position with the "G" command, vimremembers the position from before this jump. This position is called a mark. To go back where you came from, use this command:

``

This ` is a backtick or open single-quote character.

If you use the same command a second time you will jump back again. That's because the ` command is a jump itself, and the position from before this jump is remembered.

Generally, every time you do a command that can move the cursor further than within the same line, this is called a jump. This includes the search commands "/" and "n" (it doesn't matter how far away the match is). But not the character searches with "fx" and "tx" or the word movements "w" and "e".

Also, "j" and "k" are not considered to be a jump. Even when you use a count to make them move the cursor quite a long way away.

The `` command jumps back and forth, between two points. The Ctrl-Ocommand jumps to older positions ("O" stands for "older"). Ctrl-I then jumps back to newer positions. Consider this sequence of commands:

33G
/^The
Ctrl-O

You first jump to line 33, then search for a line that starts with "The". Then with Ctrl-O you jump back to line 33. Another Ctrl-O takes you back to where you started. If you now use Ctrl-I you jump to line 33 again. And to the match for "The" with another Ctrl-I.

Note: Ctrl-I is the same as .

The ":jumps" command gives a list of positions you jumped to. The entry which you used last is marked with a ">".

Named Marks

vim enables you to place marks in the text. The command "ma" marks the place under the cursor as mark "a". You can place 26 marks (athrough z) in your text. You can't see them, it's just a position that vim remembers.

To go to a mark, use the command `{mark}, where {mark} is the mark letter. Thus to move to the a mark:

`a

The command 'mark (single quotation mark, or apostrophe) moves you to the beginning of the line containing the mark. This differs from the `mark command, which moves you to marked column.

The marks can be very useful when working on two related parts in a file. Suppose you have some text near the start of the file you need to look at, while working on some text near the end of the file.

Move to the text at the start and place the "s" (start) mark there:

ms

Then move to the text you want to work on and put the "e" (end) mark there:

me

Now you can move around, and when you want to look at the start of the file, you use this to jump there:

's

Then you can use '' to jump back to where you were, or 'e to jump to the text you were working on at the end.

There is nothing special about using "s" for start and "e" for end, they are just easy to remember.

You can use this command to get a list of marks:

:marks

You will notice a few special marks. These include:

'' The cursor position before doing a jump.
" The cursor position when last editing the file.
[ Start of the last change.
] End of the last change.
Operators And Motions

The "dw" command deletes a word. You may recognize the "w" command as the move word command. In fact, the "d" command may be followed by any motion command, and it deletes from the current location to the place where the cursor winds up. The "4w" command, for example, moves the cursor over four words. The d4w command deletes four words.

To err is human. To forgive is divine. To breathe is required. 
                 ---------------------> d4w To err is human. To breathe is required.

vim only deletes up to the position where the motion takes the cursor. That's because vim knows that you probably don't want to delete the first character of a word. If you use the "e" command to move to the end of a word, vim guesses that you do want to include that last character:

To err is human. To breathe is required. 
                ----------> d2e To err is human. is required.

Whether the character under the cursor is included depends on the command you used to move to that character. This is called "exclusive" when the character isn't included and "inclusive" when it is.

The "$" command moves to the end of a line. The "d$" command deletes from the cursor to the end of the line, which is an inclusive motion, thus the last character of the line is included in the delete operation:

To err is human. is divine. 
                 --------> d$ To err is human.

There is a pattern here: operator-motion. You first type an operator command. For example, "d" is the delete operator. Then you type a motion command like "4l" or "w". This way you can operate on any text you can move over.

Changing Text

Another operator is "c", change. It acts just like the "d" operator, except it leaves you in Insert mode. For example, "cw" changes a word. Or more specifically, it deletes a word and then puts you in Insert mode.

To err is human 
   -------> c2wbeTo be human

This "c2wbe" contains these bits:

c The change operator.
2w Move two words (they are deleted and Insert mode started).
be Insert this text.
Back to Normal mode.

The space before "human" isn't deleted. The c operator works just like the d operator, with one exception: "cw". It actually works like "ce", change to end of word. Thus the space after the word isn't included, which is an exception that dates back to the old Vi. Since many people are used to it now, the inconsistency has remained in vim.

查看英文版

查看中文版

更多变化

就像“dd”删除整行一样,“cc”更改整行。但是,它会保留现有的缩进(前导空格)。

就像“d $”删除到该行的末尾一样,“c $”更改直到该行的末尾。就像用“d $”删除文本,然后用“a”启动插入模式并追加新文本一样。

捷径

某些操作员移动命令经常使用,以致于只给它们一个字母命令:

命令: 代表: 描述:
X d1 删除光标下方的字符。
X dh 删除光标左侧的字符。
d d $ 删除到行尾。
C c $ 转到行尾。
s c1 更改一个字符。
S CC 更改整行。
在哪里计数

命令“3dw”和“d3w”删除三个单词。如果您想真正挑剔,则第一个命令“3dw”将一个单词删除三遍;命令“d3w”删除三个单词一次,这是没有区别的区别。但是,实际上您可以输入两个数字。例如,“3d2w”删除两个单词,重复3次,总共六个单词。

替换为一个字符

“r”命令不是运算符。它等待您键入一个字符,并用它替换光标下的字符。您可以使用“cl”或“s”命令执行相同的操作,但是使用“r”则不必按键。

there is somerhing grong here rT There is somerhing grong here rt There is something grong here rw There is something wrong here

使用带有“r”的计数会导致许多字符被同一字符替换。例:

There is something wrong here 5rx There is something xxxxx here

要用换行符替换字符,请使用“r”。这将删除一个字符并插入换行符。在此使用计数仅适用于删除的字符数:“4r”用一个换行符替换四个字符。

重复更改

“。”命令是vim中最简单但功能最强大的命令之一。重复上一次更改。例如,假设您正在编辑HTML文件,并且想要删除所有标记。将光标放在第一个<上,然后使用命令“df>”删除。然后你去<接下来的,并使用了“杀了它。”命令。“。”命令执行最后一个更改命令(在本例中为“df>”)。要删除其他标签,请将光标放在<”命令。

   To generate a table of contents
f< find first <  --->
df> delete to >	 -->
f< find next <	 --------->
. repeat df>			  --->
f< find next <		   ------------->
. repeat df>					  --> 

“.”命令适用于您做出的所有更改,除了“ü”(撤销),按Ctrl-R以冒号开始(重做)和命令(:)。

另一个示例:您要将单词“四个”更改为“五个”。它会在您的文本中出现几次。您可以使用以下命令序列快速完成此操作:

/ four 找到第一个字符串“ four”。
cwfive 将单词更改为“五”。
n 找到下一个“四个”。
. 重复更改为“五”。
n 找到下一个“四个”。
. 重复更改。

等等

视觉模式

要删除简单的项目,操作员的动作更改效果很好。但是,通常很难决定要在要更改的文本上移动哪个命令。然后,您可以使用可视模式。

通过按“v”启动可视模式。您将光标移到要处理的文本上。在执行此操作时,文本将突出显示。最后键入操作员命令。

例如,要从一个单词的中途删除到另一个单词的中途:

This is an examination sample of visual mode
        --------->
 velllld
This is an example of visual mode

在执行此操作时,您实际上不必计算要按“l”键到正确位置的次数。您可以立即看到按d删除的文本。

如果您在任何时候决定不想对突出显示的文本执行任何操作,只需按键,Visual模式将停止而不执行任何操作。

选择线

如果要整行工作,请使用“V”启动可视模式。您将立即看到整行被突出显示,而无需四处移动。当您左右移动时,没有任何变化。向上或向下移动时,所选内容将一次扩展整行。

例如,用“Vjj”选择三行:

                  ┌────────────────────────┐
                  | text more text         |
               >> | more text more text    | 
selected lines >> | text text text         | 
               >> | text more              | 
                  | more text more         |
                  └────────────────────────┘
选择块

如果要处理矩形字符块,请使用Ctrl-V启动可视模式。在处理表时,这非常有用。

name		Q1	Q2	Q3
pierre		123	455	234
john		0	90	39
steve		392	63	334

要删除中间的“Q2”一栏,将光标移动到“Q的”,“Q2”。按Ctrl-V启动逐块可视模式。现在将光标向下移动三行,用“3j”移动到下一个单词,用“w”。您可以看到包含最后一列的第一个字符。要排除它,请使用“h”。现在按“d”,中间的一列消失了。

去另一边

如果在可视模式下选择了一些文本,并且发现需要更改选择的另一端,请使用“o”命令。光标将移至另一端,您可以移动光标以更改选择的开始位置。再次按“o”将使您回到另一端。使用逐块选择时,您有四个角。“o”只会将您带到对角线的另一个角落。使用“O”移动到同一行的另一个角。请注意,“o”和“O”在可视模式下的工作方式与“正常”模式非常不同,在普通模式下,它们在光标下方或上方打开新行。

移动文字

当您使用“d”,“x”或其他命令删除某些内容时,将保存文本。您可以使用p命令将其粘贴回去。(此名称的vim名称为“ put”)。

看一下它是如何工作的。首先,通过将光标放在要删除的行上并键入“dd”,将删除整行。现在,将光标移动到要放置线条的位置,然后使用“p”(put)命令。该行将插入到光标下方的行上。

	a line		a line	      a line
	line 2 dd line 3 p line 3
	line 3			      line 2

因为删除了整行,所以“p”命令将文本行置于光标下方。如果删除行的一部分(例如单词),则“p”命令将其放在光标之后。

Some more boring try text to out commands. 
		 ----> dw Some more boring text to out commands. 
		 -------> welp Some more boring text to try out commands.
推杆

“P”命令将类似“p”的文本放在光标之前。当您用“dd”删除整行时,“P”会将其放回到光标上方。当您删除带有“dw”的单词时,“P”会将其放回光标之前。

您可以根据需要重复多次放置。将使用相同的文本。

您可以使用带有“p”和“P”的计数。文本将重复计数指定的次数。因此,“dd”和“3p”将放置同一删除行的三个副本。

交换角色

使用vim可以很容易地纠正此类问题,例如不小心为“ the”键入“ teh”。只需将光标放在“ teh”的e上并执行命令“ xp”。其工作方式如下:“x”删除字符e并将其放置在寄存器中。“p”将文本放在光标之后,即“ h”之后。

teh x th p the
复制文字

要将文本从一个地方复制到另一个地方,您可以删除它,使用“u”撤消删除,然后使用“p”将其放置在其他位置。有一种更简单的方法:拉动。“y”运算符将文本复制到寄存器中。然后可以使用“p”命令放置它。

Yanking只是用于复制的vim名称。“c”字母已经用于变更运算符,而“y”仍然可用。将此运算符称为“ yank”可以使您更容易记住使用“y”键。

由于“y”是运算符,因此您可以使用“yw”来修饰单词。像往常一样计数。要拉两个单词,请使用“y2w”。例:

	let sqr = LongVariable * 
		 --------------> y2w let sqr = LongVariable * p let sqr = LongVariable * LongVariable

请注意,“yw”在一个单词后包含空格。如果您不想这样做,请使用“ye”。

“yy”命令将整行删除,就像“dd”删除整行一样。出乎意料的是,当“D”从光标删除到行的末尾时,“Y”的工作方式类似于“yy”,但它会拖移整行。当心这种不一致!使用“y $”拉到行尾。

	a text line yy line 2
        last line
	a text line
	line 2 p last line
	a text line
	line 2
	a text line
	last line
使用剪贴板

如果使用的是GUI版本的vim(gvim),则可以在“编辑”菜单中找到“复制”项。首先在可视模式下选择一些文本,然后使用“编辑/复制”菜单。所选文本现在已复制到剪贴板。您可以将文本粘贴到其他程序中。在VIM本身了。

如果您已将文本复制到另一个应用程序中的剪贴板,则可以使用“编辑/粘贴”菜单将其粘贴到vim中。这适用于普通模式和插入模式。在可视模式下,所选文本将替换为粘贴的文本。

“剪切”菜单项会删除文本,然后再将其放置在剪贴板上。弹出菜单中还提供了“复制”,“剪切”和“粘贴”项(当然,仅当有弹出菜单时)。如果您的vim有工具栏,则也可以在其中找到这些项目。

如果您不使用GUI,或者不喜欢使用菜单,则必须使用其他方法。您可以使用常规的“y”(猛击)和“p”(放置)命令,但在其前面加上“ *”(双引号)。要将行复制到剪贴板:

"*yy

要将剪贴板中的文本放回文本中,请执行以下操作:

"*p

这仅在包含剪贴板支持的vim版本上有效。

文字对象

如果光标位于单词的中间,并且您要删除该单词,则需要先移回其开头,然后才能执行“ dw”。有一个更简单的方法可以做到:“daw”。

	this is some example text. daw this is some text.

“daw”的“d”是删除运算符。“aw”是文本对象。提示:“aw”代表“ A Word”。因此,“daw”是“删除单词”。确切地说,单词后的空白也将被删除(该行末尾的单词前的空白)。

使用文本对象是在vim中进行更改的第三种方法。我们已经有了操作员移动和可视模式。现在,我们添加运算符文本对象。

它与操作员移动非常相似,但不是在移动命令前后的光标位置之间的文本上进行操作,而是将文本对象作为一个整体使用。光标在对象中的什么位置都没有关系。

要更改整个句子,请使用“cis”。取这段文字:

	Hello there.  This 
	is an example.  Just 
	some text.

移至“ is an”的第二行的开头。现在使用“ cis”:

	Hello there.  This 
	is an example.  Just 
	some text.

光标在第一行的空白之间。现在,您输入新的句子“另一行”:

	Hello there.    Just 
	some text.

“cis”由“c”(更改)运算符和“ is”文本对象组成。这代表“内部句子”。还有一个“ as”(一个句子)对象。区别在于“ as”包括句子后面的空白,而“ is”则不包括。如果要删除句子,则要同时删除空格,因此请使用“das”。如果要输入新文本,则可以保留空格,因此请使用“cis”。

您还可以在可视模式下使用文本对象。它将在“视觉”选择中包括文本对象。可视模式继续,因此您可以执行多次。例如,以“v”启动可视模式并选择以“as”的句子。现在您可以重复“as”以包含更多句子。最后,您使用运算符对选定的句子进行处理。

更换模式

“R”命令使vim进入替换模式。在这种模式下,您键入的每个字符都会替换光标下的一个字符。这一直持续到您键入为止。

在此示例中,您在“text”的第一个“t”上启动替换模式:

This is text. 
Rinteresting.This is interesting.

您可能已经注意到,该命令用12个其他字符替换了该行中的5个字符。如果用完了要替换的字符,“R”命令会自动扩展该行。它不会在下一行继续。

您可以使用键在插入模式和替换模式之间切换。

使用(退格键)进行更正时,您会注意到原来的文本被放回去。因此,它像最后一个键入字符的撤消命令一样工作。

结论

操作员,移动命令和文本对象使您可以进行很多组合。现在您知道它是如何工作的,您可以将N个运算符与M个移动命令一起使用来制作N * M个命令!

例如,还有其他删除文本的方法。以下是一些常用的:

X 删除光标下的字符(“dl”的缩写)。
X 删除光标前的字符(“dh”的缩写)。
d 从光标删除到行尾(“d $”的缩写)。
dw 从光标删除到单词的下一个开头。
D b 从光标删除到上一个单词的开头。
w 删除光标下的单词(不包括空格)。
w 删除光标下的单词(包括空格)。
dG 删除直到文件末尾。
dgg 删除直到文件开始。

如果使用“c”而不是“d”,它们将成为更改命令。并使用“y”来显示文本。依此类推。

有一些常用的命令可以进行其他地方不适合的更改:

~ 更改光标下方字符的大小写,然后将光标移至下一个字符。这不是运算符(除非设置了“tildeop”),因此不能将其与运动命令一起使用。它确实在可视模式下工作,然后更改所有选定文本的大小写。
I 将光标移至该行的第一个非空白后,启动插入模式。
A 将光标移至行尾后,开始插入模式。
vimrc文件

您可能已经厌倦了键入经常使用的命令。要以所有喜欢的选项设置和映射开始vim,请将它们写在所谓的vimrc文件中。vim启动时将执行该文件中的命令。

如果您已经有一个vimrc文件(例如,当sysadmin为您设置一个设置时),则可以通过以下方式进行编辑:

:edit $MYVIMRC

如果您还没有vimrc文件,则可以创建一个。“:version”命令提到vim查找的“ user vimrc文件”的名称。

对于Unix和Macintosh,始终使用此文件,建议使用:〜/ .vimrc

对于MS-DOS和MS-Windows,可以使用以下之一:$ HOME / _vimrc,$ VIM / _vimrc

该的vimrc文件可以包含所有你一个冒号后键入的命令。最简单的是用于设置选项。例如,如果您希望vim始终以“incsearch”选项开头,则在您的vimrc文件中添加以下行:

set incsearch

为了使新行生效,您需要退出vim并重新启动。稍后,您将学习如何在不退出vim的情况下执行此操作。

简单映射

映射使您可以将一组vim命令绑定到单个键。例如,假设您需要用大括号将某些单词括起来。换句话说,您需要将诸如“金额”的单词更改为“ {金额}”。随着:地图命令,你可以告诉VIM的F5键来完成这个工作。命令如下:

:mapi{ea}

输入此命令时,必须输入四个字符来输入。类似地,键没有被按下输入键键,但通过键入五个字符。注意这种差异。

让我们分解一下:

在F5功能键。这是触发键,可导致在按下该键时执行命令。
i{ 插入{字符。所述键键端部插入模式。
e 移动到单词的末尾。
a} 将}附加到单词上。

执行“:map”命令后,要做的就是将{}放在单词周围,就是将光标放在第一个字符上并按F5。

在此示例中,触发器是单个键;它可以是任何字符串。但是,当您使用现有的vim命令时,该命令将不再可用。您最好避免这种情况。

可以与映射一起使用的一个关键是反斜杠。由于您可能想定义多个映射,因此添加另一个字符。您可以映射“\ p”在单词周围添加括号,并映射“\c”以添加花括号,例如:

:map \p i(ea)
:map \c i{ea}

您需要快速依次键入\和p,以便vim知道它们属于同一类。

“:map”命令(不带参数)列出您当前的映射。至少适用于普通模式。

Like "dd" deletes a whole line, "cc" changes a whole line. It keeps the existing indent (leading white space) though.

Just like "d$" deletes until the end of the line, "c$" changes until the end of the line. It's like doing "d$" to delete the text and then "a" to start Insert mode and append new text.

Shortcuts

Some operator-motion commands are used so often that they have been given a single letter command:

Command: Stands For: Description:
x d1 Delete character under the cursor.
X dh Delete character left of the cursor.
D d$ Delete to end of the line.
C c$ Change to end of the line.
s c1 Change one character.
S cc Change a whole line.
Where To Put The Count

The commands "3dw" and "d3w" delete three words. If you want to get really picky about things, the first command, "3dw", deletes one word three times; the command "d3w" deletes three words once, which is a difference without a distinction. You can actually put in two counts, however. For example, "3d2w" deletes two words, repeated three times, for a total of six words.

Replacing With One Character

The "r" command is not an operator. It waits for you to type a character, and will replace the character under the cursor with it. You could do the same with "cl" or with the "s" command, but with "r" you don't have to press

there is somerhing grong here rT There is somerhing grong here rt There is something grong here rw There is something wrong here

Using a count with "r" causes that many characters to be replaced with the same character. Example:

There is something wrong here 5rx There is something xxxxx here

To replace a character with a line break use "r". This deletes one character and inserts a line break. Using a count here only applies to the number of characters deleted: "4r" replaces four characters with one line break.

Repeating A Change

The "." command is one of the most simple yet powerful commands invim. It repeats the last change. For instance, suppose you are editing anHTMLfile and want to delete all thetags. You position the cursor on the first". You then go to the"). To delete another tag, position the cursor on the

   To generate a table of contents
f< find first <  --->
df> delete to >	 -->
f< find next <	 --------->
. repeat df>			  --->
f< find next <		   ------------->
. repeat df>					  --> 

The "." command works for all changes you make, except for the "u" (undo),Ctrl-R(redo) and commands that start with a colon (:).

Another example: You want to change the word "four" to "five". It appears several times in your text. You can do this quickly with this sequence of commands:

/four Find the first string "four".
cwfive Change the word to "five".
n Find the next "four".
. Repeat the change to "five".
n Find the next "four".
. Repeat the change.

etc.

Visual Mode

To delete simple items the operator-motion changes work quite well. But often it's not so easy to decide what command moves over the text you want to change. Then you can use Visual mode.

You start Visual mode by pressing "v". You move the cursor over the text you want to work on. While you do this, the text is highlighted. Finally type the operator command.

For example, to delete from halfway one word to halfway another word:

This is an examination sample of visual mode
        --------->
 velllld
This is an example of visual mode

When doing this you don't really have to count how many times you have to press "l" to end up in the right position. You can immediately see what text will be deleted when you press "d".

If at any time you decide you don't want to do anything with the highlighted text, just pressand Visual mode will stop without doing anything.

Selecting Lines

If you want to work on whole lines, use "V" to start Visual mode. You will see right away that the whole line is highlighted, without moving around. When you move left or right nothing changes. When you move up or down the selection is extended whole lines at a time.

For example, select three lines with "Vjj":

                  ┌────────────────────────┐
                  | text more text         |
               >> | more text more text    | 
selected lines >> | text text text         | 
               >> | text more              | 
                  | more text more         |
                  └────────────────────────┘
Selecting Blocks

If you want to work on a rectangular block of characters, useCtrl-Vto start Visual mode. This is very useful when working on tables.

name		Q1	Q2	Q3
pierre		123	455	234
john		0	90	39
steve		392	63	334

To delete the middle "Q2" column, move the cursor to the "Q" of "Q2". PressCtrl-Vto start blockwise Visual mode. Now move the cursor three lines down with "3j" and to the next word with "w". You can see the first character of the last column is included. To exclude it, use "h". Now press "d" and the middle column is gone.

Going To The Other Side

If you have selected some text in Visual mode, and discover that you need to change the other end of the selection, use the "o" command. The cursor will go to the other end, and you can move the cursor to change where the selection starts. Pressing "o" again brings you back to the other end. When using blockwise selection, you have four corners. "o" only takes you to one of the other corners, diagonally. Use "O" to move to the other corner in the same line. Note that "o" and "O" in Visual mode work very differently from Normal mode, where they open a new line below or above the cursor.

Moving Text

When you delete something with the "d", "x", or another command, the text is saved. You can paste it back by using thepcommand. (Thevimname for this is "put").

Take a look at how this works. First you will delete an entire line, by putting the cursor on the line you want to delete and typing "dd". Now you move the cursor to where you want to put the line and use the "p" (put) command. The line is inserted on the line below the cursor.

	a line		a line	      a line
	line 2 dd line 3 p line 3
	line 3			      line 2

Because you deleted an entire line, the "p" command placed the text line below the cursor. If you delete part of a line (a word, for instance), the "p" command puts it just after the cursor.

Some more boring try text to out commands.
 ---->
 dw
Some more boring text to out commands.
 ------->
 welp
Some more boring text to try out commands.
Putting

The "P" command puts text like "p", but before the cursor. When you deleted a whole line with "dd", "P" will put it back above the cursor. When you deleted a word with "dw", "P" will put it back just before the cursor.

You can repeat putting as many times as you like. The same text will be used.

You can use a count with "p" and "P". The text will be repeated as many times as specified with the count. Thus "dd" and then "3p" puts three copies of the same deleted line.

Swapping Characters

vimmakes it easy to correct such problems such as accidentally typing "teh" for "the". Just put the cursor on the e of "teh" and execute the command "xp". This works as follows: "x" deletes the character e and places it in a register. "p" puts the text after the cursor, which is after the "h".

teh
x
th
p
the
Copying Text

To copy text from one place to another, you could delete it, use "u" to undo the deletion and then "p" to put it somewhere else. There is an easier way: yanking. The "y" operator copies text into a register. Then a "p" command can be used to put it.

Yanking is just avimname for copying. The "c" letter was already used for the change operator, and "y" was still available. Calling this operator "yank" made it easier to remember to use the "y" key.

Since "y" is an operator, you use "yw" to yank a word. A count is possible as usual. To yank two words use "y2w". Example:

let sqr = LongVariable *
 -------------->
 y2w
 let sqr = LongVariable *
 p
 let sqr = LongVariable * LongVariable

Notice that "yw" includes the white space after a word. If you don't want this, use "ye".

The "yy" command yanks a whole line, just like "dd" deletes a whole line. Unexpectedly, while "D" deletes from the cursor to the end of the line, "Y" works like "yy", it yanks the whole line. Watch out for this inconsistency! Use "y$" to yank to the end of the line.

	a text line yy line 2
        last line
	a text line
	line 2 p last line
	a text line
	line 2
	a text line
	last line
Using The Clipboard

If you are using the GUI version ofvim(gvim), you can find the "Copy" item in the "Edit" menu. First select some text with Visual mode, then use the Edit/Copy menu. The selected text is now copied to the clipboard. You can paste the text in other programs. Invimitself too.

If you have copied text to the clipboard in another application, you can paste it invimwith the Edit/Paste menu. This works in Normal mode and Insert mode. In Visual mode the selected text is replaced with the pasted text.

The "Cut" menu item deletes the text before it's put on the clipboard. The "Copy", "Cut" and "Paste" items are also available in the popup menu (only when there is a popup menu, of course). If yourvimhas a toolbar, you can also find these items there.

If you are not using the GUI, or if you don't like using a menu, you have to use another way. You use the normal "y" (yank) and "p" (put) commands, but prepend"*(double-quote star) before it. To copy a line to the clipboard:

"*yy

To put text from the clipboard back into the text:

"*p

This only works on versions ofvimthat include clipboard support.

Text Objects

If the cursor is in the middle of a word and you want to delete that word, you need to move back to its start before you can do "dw". There is a simpler way to do this: "daw".

	this is some example text. daw this is some text.

The "d" of "daw" is the delete operator. "aw" is a text object. Hint: "aw" stands for "A Word". Thus "daw" is "Delete A Word". To be precise, the white space after the word is also deleted (the white space before the word at the end of the line).

Using text objects is the third way to make changes invim. We already had operator-motion and Visual mode. Now we add operator-text object.

It is very similar to operator-motion, but instead of operating on the text between the cursor position before and after a movement command, the text object is used as a whole. It doesn't matter where in the object the cursor was.

To change a whole sentence use "cis". Take this text:

	Hello there.  This 
	is an example.  Just 
	some text.

Move to the start of the second line, on "is an". Now use "cis":

	Hello there.    Just 
	some text.

The cursor is in between the blanks in the first line. Now you type the new sentence "Another line.":

	Hello there.  Another line.  Just 
	some text.

"cis" consists of the "c" (change) operator and the "is" text object. This stands for "Inner Sentence". There is also the "as" (a sentence) object. The difference is that "as" includes the white space after the sentence and "is" doesn't. If you would delete a sentence, you want to delete the white space at the same time, thus use "das". If you want to type new text the white space can remain, thus you use "cis".

You can also use text objects in Visual mode. It will include the text object in the Visual selection. Visual mode continues, thus you can do this several times. For example, start Visual mode with "v" and select a sentence with "as". Now you can repeat "as" to include more sentences. Finally you use an operator to do something with the selected sentences.

Replace Mode

The "R" command causesvimto enter replace mode. In this mode, each character you type replaces the one under the cursor. This continues until you type.

In this example, you start Replace mode on the first "t" of "text":

This is text. 
Rinteresting.This is interesting.

You may have noticed that this command replaced 5 characters in the line with twelve others. The "R" command automatically extends the line if it runs out of characters to replace. It will not continue on the next line.

You can switch between Insert mode and Replace mode with thekey.

When you use(backspace) to make correction, you will notice that the old text is put back. Thus it works like an undo command for the last typed character.

Conclusion

The operators, movement commands and text objects give you the possibility to make lots of combinations. Now that you know how it works, you can use N operators with M movement commands to make N * M commands!

For example, there are other ways to delete pieces of text. Here are a few often used ones:

x Delete character under the cursor (short for "dl").
X Delete character before the cursor (short for "dh").
D Delete from cursor to end of line (short for "d$").
dw Delete from cursor to next start of word.
db Delete from cursor to previous start of word.
diw Delete word under the cursor (excluding white space).
daw Delete word under the cursor (including white space).
dG Delete until the end of the file.
dgg Delete until the start of the file.

If you use "c" instead of "d" they become change commands. And with "y" you yank the text. And so forth.

There are a few often used commands to make changes that didn't fit somewhere else:

~ Change case of the character under the cursor, and move the cursor to the next character. This is not an operator (unless 'tildeop' is set), thus you can't use it with a motion command. It does work in Visual mode and changes case for all the selected text then.
I Start Insert mode after moving the cursor to the first non-blank in the line.
A Start Insert mode after moving the cursor to the end of the line.
The vimrc File

You probably got tired of typing commands that you use very often. To startvimwith all your favorite option settings and mappings, you write them in what is called thevimrcfile.vimexecutes the commands in this file when it starts up.

If you already have avimrcfile (e.g., when your sysadmin has one setup for you), you can edit it this way:

:edit $MYVIMRC

If you don't have avimrcfile yet, you can create one. The ":version" command mentions the name of the "user vimrc file"vimlooks for.

For Unix andMacintoshthis file is always used and is recommended:~/.vimrc

For MS-DOS and MS-Windows you can use one of these:$HOME/_vimrc,$VIM/_vimrc

Thevimrcfile can contain all the commands that you type after a colon. The most simple ones are for setting options. For example, if you wantvimto always start with the 'incsearch' option on, add this line you yourvimrcfile:

set incsearch

For this new line to take effect you need to exitvimand start it again. Later you will learn how to do this without exitingvim.

Simple Mappings

A mapping enables you to bind a set ofvimcommands to a single key. Suppose, for example, that you need to surround certain words with curly braces. In other words, you need to change a word such as "amount" into "{amount}". With the:mapcommand, you can tellvimthat theF5key does this job. The command is as follows:

:mapi{ea}

When entering this command, you must enterby typing four characters. Similarly,is not entered by pressing thekey, but by typing five characters. Watch out for this difference.

Let's break this down:

TheF5function key. This is the trigger key that causes the command to be executed as the key is pressed.
i{ Insert the{character. Thekey ends Insert mode.
e Move to the end of the word.
a} Append the}to the word.

After you execute the ":map" command, all you have to do to put{}around a word is to put the cursor on the first character and pressF5.

In this example, the trigger is a single key; it can be any string. But when you use an existingvimcommand, that command will no longer be available. You better avoid that.

One key that can be used with mappings is the backslash. Since you probably want to define more than one mapping, add another character. You could map "\p" to add parentheses around a word, and "\c" to add curly braces, for example:

:map \p i(ea)
:map \c i{ea}

You need to type the\and thepquickly after another, so thatvimknows they belong together.

The ":map" command (with no arguments) lists your current mappings. At least the ones for Normal mode.

查看英文版

查看中文版

vim 全局插件

获取全局插件

vim附带了一些全局插件。您可以在目录$ VIMRUNTIME / macros及其子目录中找到它们。

其他文件可以从vim官方网站下载。

使用全局插件

首先阅读插件本身中的文本以检查是否有特殊情况。然后将文件复制到您的插件目录:

系统 插件目录
Unix系统 ~/.vim/plugin/
PC and OS/2
HOME/vimfiles/plugin or $VIM/vimfiles/plugin
Amiga s:vimfiles/plugin
Macintosh $VIM:vimfiles:plugin
macOS X ~/.vim/plugin/
RISC-OS Choices:vimfiles.plugin

Unix的示例(假设您还没有插件目录):

mkdir ~/.vim
mkdir ~/.vim/plugin
cp /usr/local/share/vim/vim60/macros/justify.vim ~/.vim/plugin

就这样!现在,您可以使用此插件中定义的命令来对齐文本。

与其将插件直接放置在plugin /目录中,不如将它们放置在plugin /下的子目录中,以更好地组织它们。例如,考虑对所有Perl插件使用“ 〜/ .vim / plugin / perl / *。vim ” 。

文件类型插件

该VIM分布附带了一组插件不同的文件类型,你就可以开始用这个命令使用:

:filetype plugin on

如果缺少正在使用的文件类型的插件,或者找到了更好的插件,则可以添加它。添加文件类型插件有两个步骤:获取插件的副本,并将其放置在正确的目录中。

Getting A Global Plugin

Some global plugins come with vim. You can find them in the directory $VIMRUNTIME/macros and its sub-directories.

Others can be downloaded from the official vim website, .

Using A Global Plugin

First read the text in the plugin itself to check for any special conditions. Then copy the file to your plugin directory:

system plugin directory
Unix ~/.vim/plugin/
PC and OS/2 $HOME/vimfiles/plugin or $VIM/vimfiles/plugin
Amiga s:vimfiles/plugin
Macintosh $VIM:vimfiles:plugin
macOS X ~/.vim/plugin/
RISC-OS Choices:vimfiles.plugin

Example for Unix (assuming you didn't have a plugin directory yet):

mkdir ~/.vim
mkdir ~/.vim/plugin
cp /usr/local/share/vim/vim60/macros/justify.vim ~/.vim/plugin

That's all! Now you can use the commands defined in this plugin to justify text.

Instead of putting plugins directly into the plugin/ directory, you may better organize them by putting them into subdirectories under plugin/. As an example, consider using "~/.vim/plugin/perl/*.vim" for all your Perl plugins.

Filetype Plugins

The vim distribution comes with a set of plugins for different filetypes that you can start using with this command:

:filetype plugin on

If you are missing a plugin for a filetype you are using, or you found a better one, you can add it. There are two steps for adding a filetype plugin: get a copy of the plugin, and drop it in the right directory.

查看英文版

查看中文版

vim 常用选项

vim是一个广泛的程序,因此有很多选择!它们中的大多数您几乎都不会使用。一些更有用的将在这里提到。不要忘记,您可以使用“;:help;”命令在这些选项上找到更多帮助,在选项名称前后使用单引号引起来。例如:

:help 'wrap'

如果你搞乱了一个选项,你可以把一个把它设回默认符号选项名称后()。例:

:set iskeyword&

vim通常使用长行换行,以便您可以看到所有文本。有时最好让文本在窗口右边继续。然后,您需要左右滚动文本以查看所有长行。使用以下命令关闭包装:

:set nowrap

当您移至未显示的文本时,vim会自动滚动文本。要查看十个字符的上下文,请执行以下操作:

:set sidescroll=10

这不会更改文件中的文本,只会更改其显示方式。

大多数用于移动的命令将在行的开头和结尾处停止移动。您可以使用“;whichwrap;”选项进行更改。这将其设置为默认值:

:set whichwrap=b,s

这允许键,在一个行的第一个位置时,将光标移动到前一行的末尾。和<空间>从一行到下一个的开始的结束键移动。

要允许光标键和也进行换行,请使用以下命令:

:set whichwrap=b,s,<,>

这仍然仅适用于普通模式。要在插入模式下也让和做到这一点:

:set whichwrap=b,s,<,>,[,]

可以添加其他一些标志,请参见“;whichwrap;”。

使用语法突出显示

一切都从一个简单的命令开始:

:syntax enable

在大多数情况下,这应该可以使您的文件变色。vim命令将自动检测文件类型并加载正确的语法突出显示。注释突然变成蓝色,关键字变成棕色,字符串变成红色。这使得概述文件变得容易。一段时间后,您会发现黑白文本使您减速!

如果您始终要使用语法突出显示,请在vimrc文件中输入“;:syntax enable;”命令。

如果仅在终端支持颜色时才希望语法突出显示,可以将其放在vimrc文件中:

if &t_Co > 1
   syntax enable
endif

如果只想在GUI版本中突出显示语法,则在gvimrc文件中输入“;:syntax enable;”命令。

选择颜色

vim会猜测您正在使用的背景色。如果是黑色(或其他深色),它将使用浅色作为文本。如果是白色(或其他浅色),它将为文本使用深色。如果vim猜错了文本,将很难阅读。要解决此问题,请设置“;背景;”选项。对于深色背景:

:set background=dark

对于浅色背景:

:set background=light

确保将其放在“;:syntax enable;”命令之前,否则将已经设置了颜色。您可以在设置';background;';之后执行“;:syntax reset;”;以使vim再次设置默认颜色。

如果您不喜欢默认颜色,则可以选择其他配色方案。在GUI中,使用“编辑/配色方案”菜单。您也可以输入以下命令:

:colorscheme evening

“;傍晚;”是配色方案的名称。您可能还需要尝试其他几种方法。查看目录$ VIMRUNTIME / colors。

找到所需的配色方案后,将“;:colorscheme;”命令添加到vimrc文件中。

您也可以编写配色方案。这是您的操作方式:

(1)选择接近的配色方案。将此文件复制到您的vim目录。对于Unix,这应该有效。这些命令是在vim中完成的:

:!mkdir ~/.vim/colors
:!cp $VIMRUNTIME/colors/morning.vim ~/.vim/colors/mine.vim

(2)编辑配色方案文件。这些条目非常有用:

term 黑白终端中的属性
cterm 颜色终端中的属性
ctermfg 彩色端子中的前景色
ctermbg 彩色端子中的背景色
gui GUI中的属性
guifg GUI中的前景色
guibg GUI中的背景色

例如,使评论变为绿色:

:highlight Comment ctermfg=green guifg=green

可以用于“;cterm;”和“;gui;”的属性是“;粗体;”和“;下划线;”。如果两者都需要,请使用“;粗体,下划线;”。

(3)告诉vim始终使用您的配色方案。将此行放在您的vimrc中:

colorscheme mine

如果要查看最常用的颜色组合,请使用以下命令:

:runtime syntax/colortest.vim

您将看到各种颜色组合的文本。您可以检查哪些可读且美观。

编辑另一个文件

一旦进入vim,就可以使用以下命令开始编辑另一个文件:

:edit foo.txt

您可以使用任何文件名代替“ foo.txt”。vim将关闭当前文件并打开新文件。但是,如果当前文件中有未保存的更改,vim将显示一条错误消息,并且不会打开新文件:

E37: No write since last change (use ! to override)

vim在每个错误消息的开头都放置一个错误ID。如果您不理解该消息或引起该消息的原因,请在帮助系统中查找此ID。在这种情况下:

:help E37

在这一点上,您有许多选择。您可以使用以下命令写入文件:

:write

或者,您可以使用强制(!)字符强制vim放弃更改并编辑新文件:

:edit! foo.txt

如果要编辑另一个文件,但又不想将更改写入当前文件,则可以将其隐藏:

:hide edit foo.txt

带有更改的文本仍然存在,但是您看不到它。

编辑文件列表

您可以启动vim编辑文件序列。例如:

vim one.c two.c three.c

该命令启动vim,并告诉您您将编辑三个文件。vim仅显示第一个文件。在此文件中完成操作之后,要编辑下一个文件,请使用以下命令:

:next

如果当前文件中尚未保存更改,则会收到错误消息,并且“;:next;”将不起作用。这与上一节中提到的“;:edit;”;是相同的问题。放弃更改:

:next!

但是大多数情况下,您要保存更改并移至下一个文件。为此有一个特殊的命令:

:wnext

这与使用两个单独的命令的作用相同:

:write
:next

要查看要编辑的参数列表中的哪个文件,请查看窗口标题。它应该显示类似“;(2 of 3);”的内容。这意味着您正在编辑三个文件中的第二个文件。

如果要查看文件列表,请使用以下命令:

:args

这是“参数”的缩写。输出可能如下所示:

one.c [two.c] three.c 

这些是您在vim中启动的文件。当前正在编辑的那个“ two.c”放在方括号中。

从文件移动到文件

要返回一个文件:

:previous

就像“;:next;”命令一样,只不过它是朝另一个方向移动。同样,当您要首先写入文件时,还有一个快捷命令:

:wprevious

移至列表中的最后一个文件:

:last

并再次回到第一个:

:first

但是,没有“;:wlast;”或“;:wfirst;”命令。

您可以对“;:next;”和“;:previous;”;使用计数。向前跳过两个文件:

:2next
备份文件

通常,vim不会生成备份文件。如果要拥有一个,只需执行以下命令:

:set backup

备份文件的名称是原始文件,并在其末尾添加了波浪号(“;〜;”)。例如,如果您的文件名为data.txt,则备份文件名为data.txt〜。如果您不喜欢备份文件以〜结尾的事实,则可以更改扩展名:

:set backupext =.bak

这将使用data.txt.bak而不是data.txt〜。

在这里重要的另一个选项是“;backupdir;”。它指定备份文件的写入位置。默认情况下,将备份写在与原始文件相同的目录中将是正确的选择。

如果未设置';backup;'选项,但设置了';writebackup;',vim仍将创建一个备份文件。但是,一旦成功写入文件,它将被删除。这可以防止在某些情况下写入失败(最常见的原因是磁盘已满)而丢失原始文件。

如果要编辑源文件,则可能需要在进行任何更改之前保留文件。但是,每次写入文件时,备份文件都会被覆盖。因此,它仅包含以前的版本,而不包含第一个版本。

要使vim保留原始文件,请设置'patchmode'选项。这指定用于第一次备份已更改文件的扩展名。通常您会这样做:

:set patchmode = .orig

现在,当您第一次编辑data.txt文件时,进行更改并写入文件,vim将保留未更改文件的副本,名称为“;data.txt.orig;”。

如果您对该文件进行进一步的更改,vim会注意到“;data.txt.orig;”已经存在并将其保留。然后,其他备份文件将被称为“;data.txt〜;”(或您使用“;backupext;”;指定的任何名称)。

如果将“;patchmode;”;保留为空(这是默认设置),则将不保留原始文件。

使用寄存器

当您要将多个文本从一个文件复制到另一个文件时,必须在文件之间切换和写入目标文件会花费很多时间。为避免这种情况,请将每段文本复制到其自己的寄存器中。

寄存器是vim存储文本的地方。在这里,我们将使用名为a到z的寄存器(稍后您会发现其他寄存器)。让我们将一个句子复制到f寄存器(f表示First):

"fyas

“;yas;”命令像以前一样拉一个句子。正是“ f告诉vim,文本应该放在f寄存器中。它必须在yank命令之前。

现在,将三整行拉到l寄存器中(以l为行):

"l3Y

计数也可以在“ l”之前。要将文本块拖到b(for块)寄存器中:

Ctrl-Vjjww"by

注意:寄存器规范“ b”恰好在“ y”命令之前。这是必需的。如果将其放在“ w”命令之前,则该规范不起作用。

现在,在f,l和b寄存器中有三段文本。编辑另一个文件,四处移动并将文本放在所需的位置:

"fp

同样,寄存器规范“ f;”位于“;p;”命令之前。

您可以按任何顺序放置寄存器。文本会保留在寄存器中,直到您将其他内容插入寄存器中为止。因此,您可以随意放置它多次。

删除文本时,还可以指定一个寄存器。使用它来移动几段文字。例如,要删除一个单词并将其写入w寄存器:

"wdaw

同样,寄存器规范位于删除命令“;d;”之前。

只读查看文件

有时,您只想查看文件包含的内容,而无意将其写回。您可能会输入“;:w;”而不考虑并仍然覆盖原始文件。为避免这种情况,请将文件编辑为只读。

要以只读模式启动vim,请使用以下命令:

vim -R file

在Unix上,此命令应执行相同的操作:

view file

您现在正在以只读模式编辑“文件”。当您尝试使用“:w”时,您会收到一条错误消息,并且该文件将不会被写入。

当您尝试对文件vim进行更改时,会发出警告:

W10: Warning: Changing a readonly file

更改将完成。例如,这允许格式化文件,以便能够轻松读取它。

如果您对文件进行更改而忘记了它是只读的,则仍然可以编写它。添加!写入命令以强制写入。

如果您确实要禁止在文件中进行更改,请执行以下操作:

vim -M file

现在,每次更改文本的尝试都会失败。例如,帮助文件就是这样。如果尝试进行更改,则会收到以下错误消息:

E21: Cannot make changes, 'modifiable' is off

您可以使用-M参数设置vim以在查看器模式下工作。但是,这只是自愿的,因为这些命令将删除保护:

:set modifiable
:set write
另存为新文件名

一种开始编辑新文件的聪明方法是使用包含大部分所需内容的现有文件。例如,您开始编写一个新程序来移动文件。您知道您已经有一个复制文件的程序,因此从以下内容开始:

:edit copy.c

您可以删除不需要的内容。现在,您需要使用新名称保存文件。“;:saveas;”命令可用于此目的:

:saveas move.c

vim将以给定名称写入文件,然后编辑该文件。因此,下次您执行“;:write;”时,它将写入“;move.c;”。“;copy.c;”保持不变。

当您想更改正在编辑的文件的名称,但又不想写入文件时,可以使用以下命令:

:file move.c

vim会将文件标记为“未编辑”。这意味着vim知道这不是您开始编辑的文件。当您尝试写入文件时,您可能会收到以下消息:

E13: File exists (use ! to override)

这样可以防止您意外覆盖另一个文件。

分割视窗

打开新窗口的最简单方法是使用以下命令:

:split

此命令将屏幕分为两个窗口,并将光标留在顶部:

        ┌──────────────────────────────────┐
	|/* file one.c */		   |
	|~				   |
	|~				   |
	|one.c=============================|
	|/* file one.c */		   |
	|~				   |
	|one.c=============================|
	|				   |
        └──────────────────────────────────┘

您在此处看到的是同一文件上的两个窗口。带有“ ====”的行是该状态行。它显示有关其上方窗口的信息。实际上,状态行将显示为反向视频。

这两个窗口使您可以查看同一文件的两个部分。例如,您可以使顶部的窗口显示程序的变量声明,而底部的窗口显示使用这些变量的代码。

在按Ctrl-W W命令可以用于在窗口间跳转。如果您在顶部窗口中,则Ctrl-W w跳至其下面的窗口。如果您在底部窗口中,它将跳到第一个窗口。Ctrl-W Ctrl-W会执行相同的操作,以防您稍后松开Ctrl键。

要关闭窗口,请使用以下命令:

:close

实际上,任何退出编辑文件的命令都可以使用,例如“;:quit;”和“;ZZ;”。但是“;:close;”可以防止您在关闭最后一个窗口时意外退出vim。

如果您已经打开了一大堆窗口,但现在想专注于其中一个窗口,则此命令将非常有用:

:only

这将关闭所有窗口,但当前窗口除外。如果其他任何窗口有更改,您将收到一条错误消息,并且该窗口不会关闭。

在另一个文件上分割窗口

以下命令将打开第二个窗口,并开始编辑给定文件:

:split two.c

如果您正在编辑one.c,则结果如下所示:

        ┌──────────────────────────────────┐
	|/* file two.c */		   |
	|~				   |
	|~				   |
	|two.c=============================|
	|/* file one.c */		   |
	|~				   |
	|one.c=============================|
	|				   |
        └──────────────────────────────────┘

要在新的空文件上打开一个窗口,请使用以下命令:

:new

您可以重复使用“:split”和“:new”命令来创建任意多个窗口。

视窗大小

“;:split;”命令可以使用数字参数。如果指定,这将是新窗口的高度。例如,以下代码将打开一个三行高的新窗口,并开始编辑文件alpha.c:

:3split alpha.c

对于现有的窗口,您可以通过多种方式更改大小。当您的鼠标可以工作时,这很容易:将鼠标指针移到分隔两个窗口的状态行,然后上下拖动它。

要增加窗口的大小:Ctrl-W +

减少它:Ctrl-W-

这两个命令都需要计数,并且会使窗口大小增加或减少那么多行。因此,“;4 Ctrl-W +;”使窗口高四行。

要将窗口高度设置为指定的行数:{height} Ctrl-W _

那就是:一个数字{height},按Ctrl-W然后是一个下划线。要使窗口尽可能高,请使用Ctrl-W _命令而无需计数。

使用鼠标

在vim中,您可以通过键盘快速执行许多操作。不幸的是,窗口大小调整命令需要很多输入。在这种情况下,使用鼠标会更快。将鼠标指针放在状态线上。现在按鼠标左键并拖动。状态线移动,从而使一侧的窗口较高,而另一侧的窗口较小。

vim is an extensive program, and so it has a lot of options! Most of them you will hardly ever use. Some of the more useful ones will be mentioned here. Don't forget you can find more help on these options with the ":help" command, with single quotes before and after the option name. For example:

:help 'wrap'

In case you have messed up an option value, you can set it back to the default by putting an ampersand (&) after the option name. Example:

:set iskeyword&

vim normally wraps long lines, so that you can see all of the text. Sometimes it's better to let the text continue right of the window. Then you need to scroll the text left-right to see all of a long line. Switch wrapping off with this command:

:set nowrap

vim will automatically scroll the text when you move to text that is not displayed. To see a context of ten characters, do this:

:set sidescroll=10

This doesn't change the text in the file, only the way it is displayed.

Most commands for moving around will stop moving at the start and end of a line. You can change that with the 'whichwrap' option. This sets it to the default value:

:set whichwrap=b,s

This allows the  key, when used in the first position of a line, to move the cursor to the end of the previous line. And the  key moves from the end of a line to the start of the next one.

To allow the cursor keys  and  to also wrap, use this command:

:set whichwrap=b,s,<,>

This is still only for Normal mode. To let  and  do this in Insert mode as well:

:set whichwrap=b,s,<,>,[,]

There are a few other flags that can be added, see 'whichwrap'.

Using Syntax Highlighting

It all starts with one simple command:

:syntax enable

That should work in most situations to get color in your files. The vim command will automagically detect the type of file and load the right syntax highlighting. Suddenly comments are blue, keywords brown and strings red. This makes it easy to overview the file. After a while you will find that black&white text slows you down!

If you always want to use syntax highlighting, put the ":syntax enable" command in your vimrc file.

If you want syntax highlighting only when the terminal supports colors, you can put this in your vimrc file:

if &t_Co > 1
   syntax enable
endif

If you want syntax highlighting only in the GUI version, put the ":syntax enable" command in your gvimrc file.

Choosing Colors

vim guesses the background color that you are using. If it is black (or another dark color) it will use light colors for text. If it is white (or another light color) it will use dark colors for text. If vim guessed wrong the text will be hard to read. To solve this, set the 'background' option. For a dark background:

:set background=dark

And for a light background:

:set background=light

Make sure you put this before the ":syntax enable" command, otherwise the colors will already have been set. You could do ":syntax reset" after setting 'background' to make vim set the default colors again.

If you don't like the default colors, you can select another color scheme. In the GUI use the Edit/Color Scheme menu. You can also type the command:

:colorscheme evening

"evening" is the name of the color scheme. There are several others you might want to try out. Look in the directory $VIMRUNTIME/colors.

When you found the color scheme that you like, add the ":colorscheme" command to your vimrc file.

You could also write a color scheme. This is how you do it:

(1) Select a color scheme that comes close. Copy this file to your vimdirectory. For Unix, this should work. These commands are done from within vim:

:!mkdir ~/.vim/colors
:!cp $VIMRUNTIME/colors/morning.vim ~/.vim/colors/mine.vim

(2) Edit the color scheme file. These entries are useful:

term attributes in a B&W terminal
cterm attributes in a color terminal
ctermfg foreground color in a color terminal
ctermbg background color in a color terminal
gui attributes in the GUI
guifg foreground color in the GUI
guibg background color in the GUI

For example, to make comments green:

:highlight Comment ctermfg=green guifg=green

Attributes you can use for "cterm" and "gui" are "bold" and "underline". If you want both, use "bold,underline".

(3) Tell vim to always use your color scheme. Put this line in your vimrc:

colorscheme mine

If you want to see what the most often used color combinations look like, use this command:

:runtime syntax/colortest.vim

You will see text in various color combinations. You can check which ones are readable and look nice.

Editing Another File

Once you are in vim, you can start editing another file using this command:

:edit foo.txt

You can use any file name instead of "foo.txt". vim will close the current file and open the new one. If the current file has unsaved changes, however, vim displays an error message and does not open the new file:

E37: No write since last change (use ! to override)

vim puts an error ID at the start of each error message. If you do not understand the message or what caused it, look in the help system for this ID. In this case:

:help E37

At this point, you have a number of alternatives. You can write the file using this command:

:write

Or you can force vim to discard your changes and edit the new file, using the force (!) character:

:edit! foo.txt

If you want to edit another file, but not write the changes in the current file yet, you can make it hidden:

:hide edit foo.txt

The text with changes is still there, but you can't see it.

Editing A List Of Files

You can start vim to edit a sequence of files. For example:

vim one.c two.c three.c

This command starts vim and tells it that you will be editing three files. vim displays just the first file. After you have done your thing in this file, to edit the next file you use this command:

:next

If you have unsaved changes in the current file, you will get an error message and the ":next" will not work. This is the same problem as with ":edit" mentioned in the previous section. To abandon the changes:

:next!

But mostly you want to save the changes and move on to the next file. There is a special command for this:

:wnext

This does the same as using two separate commands:

:write
:next

To see which file in the argument list you are editing, look in the window title. It should show something like "(2 of 3)". This means you are editing the second file out of three files.

If you want to see the list of files, use this command:

:args

This is short for "arguments". The output might look like this:

one.c [two.c] three.c

These are the files you started vim with. The one you are currently editing, "two.c", is in square brackets.

Moving From File To File

To go back one file:

:previous

This is just like the ":next" command, except that it moves in the other direction. Again, there is a shortcut command for when you want to write the file first:

:wprevious

To move to the very last file in the list:

:last

And to move back to the first one again:

:first

There is no ":wlast" or ":wfirst" command however.

You can use a count for ":next" and ":previous". To skip two files forward:

:2next
Backup Files

Usually vim does not produce a backup file. If you want to have one, all you need to do is execute the following command:

:set backup

The name of the backup file is the original file with a tilde ("~") added to the end. If your file is named data.txt, for example, the backup file name is data.txt~. If you do not like the fact that the backup files end with ~, you can change the extension:

:set backupext=.bak

This will use data.txt.bak instead of data.txt~.

Another option that matters here is 'backupdir'. It specifies where the backup file is written. The default, to write the backup in the same directory as the original file, will mostly be the right thing.

When the 'backup' option isn't set but the 'writebackup' is, vim will still create a backup file. However, it is deleted as soon as writing the file was completed successfully. This functions as a safety against losing your original file when writing fails in some way (disk full is the most common cause).

If you are editing source files, you might want to keep the file before you make any changes. But the backup file will be overwritten each time you write the file. Thus it only contains the previous version, not the first one.

To make vim keep the original file, set the 'patchmode' option. This specifies the extension used for the first backup of a changed file. Usually you would do this:

:set patchmode=.orig

When you now edit the file data.txt for the first time, make changes and write the file, vim will keep a copy of the unchanged file under the name "data.txt.orig".

If you make further changes to the file, vim will notice that "data.txt.orig" already exists and leave it alone. Further backup files will then be called "data.txt~" (or whatever you specified with 'backupext').

If you leave 'patchmode' empty (that is the default), the original file will not be kept.

Using Registers

When you want to copy several pieces of text from one file to another, having to switch between the files and writing the target file takes a lot of time. To avoid this, copy each piece of text to its own register.

A register is a place where vim stores text. Here we will use the registers named a to z (later you will find out there are others). Let's copy a sentence to the f register (f for First):

"fyas

The "yas" command yanks a sentence like before. It's the "f that tells vim the text should be place in the f register. This must come just before the yank command.

Now yank three whole lines to the l register (l for line):

"l3Y

The count could be before the "l just as well. To yank a block of text to the b (for block) register:

Ctrl-Vjjww"by

Notice that the register specification "b is just before the "y" command. This is required. If you would have put it before the "w" command, it would not have worked.

Now you have three pieces of text in the f, l and b registers. Edit another file, move around and place the text where you want it:

"fp

Again, the register specification "f comes before the "p" command.

You can put the registers in any order. And the text stays in the register until you yank something else into it. Thus you can put it as many times as you like.

When you delete text, you can also specify a register. Use this to move several pieces of text around. For example, to delete-a-word and write it in the w register:

"wdaw

Again, the register specification comes before the delete command "d".

Viewing A File Read-Only

Sometimes you only want to see what a file contains, without the intention to ever write it back. There is the risk that you type ":w" without thinking and overwrite the original file anyway. To avoid this, edit the file read-only.

To start vim in readonly mode, use this command:

vim -R file

On Unix this command should do the same thing:

view file

You are now editing "file" in read-only mode. When you try using ":w" you will get an error message and the file won't be written.

When you try to make a change to the file vim gives you a warning:

W10: Warning: Changing a readonly file

The change will be done though. This allows for formatting the file, for example, to be able to read it easily.

If you make changes to a file and forgot that it was read-only, you can still write it. Add the ! to the write command to force writing.

If you really want to forbid making changes in a file, do this:

vim -M file

Now every attempt to change the text will fail. The help files are like this, for example. If you try to make a change you get this error message:

E21: Cannot make changes, 'modifiable' is off

You could use the -M argument to set up vim to work in a viewer mode. This is only voluntary though, since these commands will remove the protection:

:set modifiable
:set write
Saving As A New File Name

A clever way to start editing a new file is by using an existing file that contains most of what you need. For example, you start writing a new program to move a file. You know that you already have a program that copies a file, thus you start with:

:edit copy.c

You can delete the stuff you don't need. Now you need to save the file under a new name. The ":saveas" command can be used for this:

:saveas move.c

vim will write the file under the given name, and edit that file. Thus the next time you do ":write", it will write "move.c". "copy.c" remains unmodified.

When you want to change the name of the file you are editing, but don't want to write the file, you can use this command:

:file move.c

vim will mark the file as "not edited". This means that vim knows this is not the file you started editing. When you try to write the file, you might get this message:

E13: File exists (use ! to override)

This protects you from accidentally overwriting another file.

Splitting Windows

The easiest way to open a new window is to use the following command:

:split

This command splits the screen into two windows and leaves the cursor in the top one:

        ┌──────────────────────────────────┐
	|/* file one.c */		   |
	|~				   |
	|~				   |
	|one.c=============================|
	|/* file one.c */		   |
	|~				   |
	|one.c=============================|
	|				   |
        └──────────────────────────────────┘

What you see here is two windows on the same file. The line with "====" is that status line. It displays information about the window above it. In practice the status line will be in reverse video.

The two windows allow you to view two parts of the same file. For example, you could make the top window show the variable declarations of a program, and the bottom one the code that uses these variables.

The Ctrl-W w command can be used to jump between the windows. If you are in the top window, Ctrl-W w jumps to the window below it. If you are in the bottom window it will jump to the first window. Ctrl-W Ctrl-W does the same thing, in case you let go of the Ctrl key a bit later.

To close a window, use the command:

:close

Actually, any command that quits editing a file works, like ":quit" and "ZZ". But ":close" prevents you from accidentally exiting vim when you close the last window.

If you have opened a whole bunch of windows, but now want to concentrate on one of them, this command will be useful:

:only

This closes all windows, except for the current one. If any of the other windows has changes, you will get an error message and that window won't be closed.

Splitting A Window On Another File

The following command opens a second window and starts editing the given file:

:split two.c

If you were editing one.c, then the result looks like this:

        ┌──────────────────────────────────┐
	|/* file two.c */		   |
	|~				   |
	|~				   |
	|two.c=============================|
	|/* file one.c */		   |
	|~				   |
	|one.c=============================|
	|				   |
        └──────────────────────────────────┘

To open a window on a new, empty file, use this:

:new

You can repeat the ":split" and ":new" commands to create as many windows as you like.

Window Size

The ":split" command can take a number argument. If specified, this will be the height of the new window. For example, the following opens a new window three lines high and starts editing the file alpha.c:

:3split alpha.c

For existing windows you can change the size in several ways. When you have a working mouse, it is easy: Move the mouse pointer to the status line that separates two windows, and drag it up or down.

To increase the size of a window: Ctrl-W +

To decrease it: Ctrl-W -

Both of these commands take a count and increase or decrease the window size by that many lines. Thus "4 Ctrl-W +" make the window four lines higher.

To set the window height to a specified number of lines: {height}Ctrl-W _

That's: a number {height}, Ctrl-W and then an underscore. To make a window as high as it can be, use the Ctrl-W _ command without a count.

Using The Mouse

In vim you can do many things very quickly from the keyboard. Unfortunately, the window resizing commands require quite a bit of typing. In this case, using the mouse is faster. Position the mouse pointer on a status line. Now press the left mouse button and drag. The status line moves, thus making the window on one side higher and the other smaller.

查看英文版

查看中文版

vim 选项

可以将“;winheight;”选项设置为窗口的最小所需高度,将“;winminheight;”设置为硬的最小高度。同样,对于最小的所需宽度,有“;winwidth;”,对于硬的最小宽度,有“;winminwidth;”;。当设置了';equalalways;'选项时,vim将在关闭或打开窗口时使窗口大小相等。

垂直分割

“;:split;”命令在当前窗口上方创建一个新窗口。要使窗口显示在左侧,请使用:

:Vsplit

要么:

:vsplit two.c

结果看起来像这样:

        ┌──────────────────────────────────────┐
	|/* file two.c */  ||/* file one.c */  ||||
	|~		   ||~		       ||||
	|~		   ||~		       ||||
	|~		   ||~		       ||||
	|two.c===============one.c=============|
	|				       |
        └──────────────────────────────────────┘

实际上,||;中间的行将是反向视频。这称为垂直分隔符。它将左右两个窗口分开。

还有一个“;:vnew;”命令,用于在一个新的空文件上打开一个垂直分割的窗口。另一种方法是:

:vertical new

可以在另一个用于分割窗口的命令之前插入“;:vertical;”命令。这将导致该命令垂直而不是水平分割窗口。如果该命令未拆分窗口,则该命令将保持不变。

在Windows之间移动

由于您可以根据需要在水平和垂直方向上任意拆分窗口,因此几乎可以创建任何布局的窗口。然后,您可以使用以下命令在它们之间移动:

Ctrl-W h 移到左侧的窗口
Ctrl-W j 移到下面的窗口
Ctrl-W k 移到上方的窗口
Ctrl-W l 移到右边的窗口
Ctrl-W t 移到顶部窗口
Ctrl-W b 移至底部窗口

您会注意到与移动光标相同的字母。如果需要,还可以使用光标键。

移动窗户

您已经拆分了几个窗口,但是现在它们在错误的位置。然后,您需要一个命令将窗口移到其他位置。例如,您有三个这样的窗口:

        ┌──────────────────────────────────┐
	|/* file two.c */		   |
	|~				   |
	|~				   |
	|two.c=============================|
	|/* file three.c */		   |
	|~				   |
	|~				   |
	|three.c===========================|
	|/* file one.c */		   |
	|~				   |
	|one.c=============================|
	|				   |
        └──────────────────────────────────┘

显然,最后一个应该在顶部。转到该窗口(使用Ctrl-W w),然后键入以下命令:Ctrl-W K

这将使用大写字母ķ。发生的是窗口被移到最顶部。您会注意到,K再次用于向上移动。进行垂直分割时,Ctrl-W K将当前窗口移至顶部,并使其占据vim窗口的整个宽度。如果这是您的布局:

        ┌───────────────────────────────────────────┐
	|/* two.c */ ||/* three.c */ ||/* one.c */  |
	|~	     ||~	     ||~	    |
	|~	     ||~	     ||~	    |
	|~	     ||~	     ||~	    |
	|~	     ||~	     ||~	    |
	|~	     ||~	     ||~	    |
	|two.c=========three.c=========one.c========|
	|					    |
        └───────────────────────────────────────────┘

然后在中间窗口(three.c)中使用Ctrl-W K将导致:

	┌───────────────────────────────────────────┐
	|/* three.c */				    |
	|~					    |
	|~					    |
	|three.c====================================|
	|/* two.c */	      ||/* one.c */	    ||||
	|~		      ||~		    ||||
	|two.c==================one.c===============|
	|					    |
	└───────────────────────────────────────────┘

其他三个类似的命令(您现在可能已经猜到了):

Ctrl-W 将窗口移到最左边
Ctrl-W J 将窗口移到底部
Ctrl-W L 将窗口移到最右边
适用于所有Windows的命令

当您打开多个窗口并要退出vim时,可以分别关闭每个窗口。一种更快的方法是使用以下命令:

:qall

这代表“全部退出”。如果任何一个窗口包含更改,vim将不会退出。光标将自动定位在具有更改的窗口中。然后,您可以使用“;:write;”保存更改,或使用“;:quit!;”;放弃更改。

如果您知道有更改的窗口,并且要保存所有这些更改,请使用以下命令:

:wall

这代表“全部写入”。但是实际上,它只写有更改的文件。vim命令知道编写没有更改的文件没有任何意义。

然后是“;:qall;”和“;:wall;”的组合:“ write and quit all”命令:

:wqall

这将写入所有已修改的文件并退出vim。

最后,有一个命令退出vim并丢弃所有更改:

:qall!

请注意,无法撤消此命令!

打开所有文件的窗口

要使vim为每个文件打开一个窗口,请使用“;-o;”参数启动它:

vim -o one.txt two.txt three.txt

结果是:

	┌───────────────────────────────┐
	|file one.txt			|
	|~				|
	|one.txt========================|
	|file two.txt			|
	|~				|
	|two.txt========================|
	|file three.txt			|
	|~				|
	|three.txt======================|
	|				|
	└───────────────────────────────┘

“;-O;”参数用于获取垂直分割的窗口。

当vim已经运行时,“;:all;”命令为参数列表中的每个文件打开一个窗口。“;:vertical all;”可以垂直分割。

使用vimdiff查看差异

有一种特殊的方式来启动vim,它显示了两个文件之间的差异。让我们获取一个文件“ main.c”,并在一行中插入几个字符。将此文件设置为“ backup”选项,以便备份文件“ main.c〜”将包含该文件的先前版本。

在shell中输入以下命令(不在vim中):

vimdiff main.c〜main.c

vim将启动,并排两个窗口。您只会看到添加字符的行,以及在其上方和下方的几行。

	┌───────────────────────────────┐
	|file one.txt			|
	|~				|
	|one.txt========================|
	|file two.txt			|
	|~				|
	|two.txt========================|
	|file three.txt			|
	|~				|
	|three.txt======================|
	|				|
	└───────────────────────────────┘

该图片未显示突出显示,请使用vimdiff命令以获得更好的外观。

未修改的行已折叠为一行。称为这闭合折叠它们在图片中以“ <;-折叠;”表示。因此,顶部的单折线代表123个文本行。这些行在两个文件中都相等。

标有“;<-更改的行;”的行将突出显示,插入的文本将以另一种颜色显示。这清楚地显示了两个文件之间的区别。

被删除的行在main.c窗口中显示为“;---;”。请参见图片中的“;<-删除行;”标记。这些字符不是真的存在。它们只是填满main.c,因此它显示的行数与另一个窗口相同。

折叠栏

每个窗口的左侧都有一列,其背景略有不同。在上图中,这些用“ VV”表示。您会注意到在每个闭合折线的前面都有一个加号字符。将鼠标指针移至该加号,然后单击左按钮。折叠将打开,您可以看到其中包含的文本。

折叠栏包含开放折叠的减号。如果单击此-折叠将关闭。显然,这仅在您的鼠标正常工作时才有效。您也可以使用“ zo”打开折痕,使用“ zc”关闭折痕。

差异化

在diff模式下启动的另一种方法可以在vim内部完成。编辑“ main.c”文件,然后进行拆分并显示差异:

:edit main.c
:vertical diffsplit main.c~

“;:vertical;”命令用于使窗口垂直分割。如果省略此选项,则将获得水平分割。

如果您有补丁程序或差异文件,则可以使用第三种方式启动差异模式。首先编辑要应用补丁的文件。然后告诉vim补丁文件的名称:

:edit main.c
:vertical diffpatch main.c.diff

警告:对于正在编辑的文件,补丁文件必须仅包含一个补丁。否则,您将收到很多错误消息,并且某些文件可能会意外修补。

修补只会对vim中文件的副本进行。硬盘上的文件将保持不变(直到您决定写入文件)。

滚动装订

当文件有更多更改时,您可以按通常的方式滚动。vim将尝试使两个窗口都在同一位置启动,因此您可以轻松地并排看到差异。

如果您暂时不希望使用此命令,请使用以下命令:

:set noscrollbind
跳到变化

当您以某种方式禁用折叠功能时,可能很难找到更改。使用此命令可跳至下一个更改:

]c

要使用其他方式,请使用:

[c

预先计入一个数,即可跳得更远。

删除变更

您可以将文本从一个窗口移到另一个窗口。这将删除差异或添加新的差异。vim命令不会在所有情况下都使突出显示保持更新。要更新它,请使用以下命令:

:diffupdate

要消除差异,可以将突出显示的块中的文本从一个窗口移到另一个窗口。以上面的“ main.c”和“ main.c〜”示例为例。将光标移动到左侧窗口,在另一窗口中已删除的行上。现在键入以下命令:

dp

通过将当前窗口的文本放在另一个窗口中,可以删除更改。“ dp”代表“ diff put”。

您也可以采用其他方法。将光标移到右侧窗口,插入“已更改”的行。现在键入以下命令:

do

现在,可以通过从另一个窗口获取文本来删除更改。由于现在没有任何更改,因此vim将所有文本封闭在一起。“ do”代表“差异获取”。“ dg”本来会更好,但是已经具备不同的含义(“ dgg”从光标删除直到第一行)。

杂项选项

';laststatus;'选项可用于指定最后一个窗口何时具有状态行:

0 决不
1 仅当有分割窗口时(默认)
2 总是

许多编辑另一个文件的命令都有一个变体,可以分割窗口。对于命令行命令,这是通过在前面加上“S”来完成的。例如:“ :标签;”跳转到标签“ :雄鹿;”分割窗口并重启到标签。

对于“普通”模式命令,将使用Ctrl-W作为附件。Ctrl-;^跳至备用文件,Ctrl-W Ctrl- ^拆分窗口并编辑备用文件。

可以将';splitbelow;'选项设置为使新窗口显示在当前窗口下方。可以将';splitright;'选项设置为使垂直分割的窗口出现在当前窗口的右侧。

分割窗口时,可以添加修饰符命令以告知窗口将出现在哪里:

:左上方{cmd} 在当前窗口的左侧或上方
:左上方{cmd} 相同
:右下方{cmd} 在当前窗口的右边或下面
:右下方{cmd} 相同
:左上角{cmd} 在vim窗口的顶部或
:底部{cmd} 在vim窗口的底部或右侧
标签页

您将注意到窗口永远不会重叠。这意味着您很快就会用完屏幕空间。解决方案称为“标签页”。

假设您正在编辑“此文件”。要创建新的标签页,请使用以下命令:

:tabedit thatfile

这将在整个vim窗口的窗口中窗口编辑文件“ thatfile”。您会在顶部看到一个带有两个文件名的栏:

	┌──────────────────────────────────┐
	| thisfile | /thatfile/ __________X|    (thatfile is bold)
	|/* thatfile */			   |
	|that				   |
	|that				   |
	|~				   |
	|~				   |
	|~				   |
	|				   |
	└──────────────────────────────────┘

现在,您有两个标签页。第一个具有“此文件”的窗口,第二个具有“那个文件”的窗口。就像两个页面相互重叠,每个页面上都显示一个标签,用于显示文件名。

现在,使用鼠标指针顶行中的“ thisfile”。结果是

	┌──────────────────────────────────┐
	| /thisfile/ | thatfile __________X|    (thisfile is bold)
	|/* thisfile */			   |
	|this				   |
	|this				   |
	|~				   |
	|~				   |
	|~				   |
	|				   |
	└──────────────────────────────────┘

因此,您可以通过上下顶行上的标签在标签页之间切换。如果您没有鼠标或不想使用它,则可以使用“ gt”命令。您可以将其记住为“转到选项卡”的简称。

现在,使用命令创建另一个选项卡页:

:tab split

这将创建一个带有一个窗口的新标签页,该窗口正在编辑与我们所在窗口相同的缓冲区:

	┌─────────────────────────────────────┐
	| thisfile | /thisfile/ | thatfile __X|   (thisfile is bold)
	|/* thisfile */			      |
	|this				      |
	|this				      |
	|~				      |
	|~				      |
	|~				      |
	|				      |
	└─────────────────────────────────────┘

您可以在打开窗口的任何Ex命令之前放置“;:tab;”。该窗口将在新的标签页中打开。另一个例子:

:tab help gt

将在新标签页中显示“;gt;”;的帮助文本。

标签页还可以执行以下操作:

  • 在最后一个标签之后的空白处单击鼠标。将选择下一个标签页,如“;gt;”。
  • 用鼠标右键右上角的“ X”。当前选项卡页面将关闭。除非当前选项卡页面中有未保存的更改。
  • 用鼠标在第一行中双击。将创建一个新的标签页。
  • “;tabonly;”命令。关闭除当前页面以外的所有选项卡页面。除非其他选项卡页中有未保存的更改。

“;命令重复前面的更改”。但是,如果您想做的事情比一次更改更复杂呢?这就是命令记录的地方,称为通常宏。分三个步骤:

(1)“;q {register};”命令开始将击键记录到名为{register}的寄存器中。寄存器名称必须在a和z之间。

(2)输入您的命令。

(3)要结束录制,请按q(不带任何多余的字符)。

您现在可以通过键入命令“;@ {register;}”;来执行宏。看一下如何在实践中使用这些命令。您有一个文件名列表,如下所示:

	stdio.h 
	fcntl.h 
	unistd.h 
	stdlib.h

而您想要的是以下内容:

	#include "stdio.h" 
	#include "fcntl.h" 
	#include "unistd.h" 
	#include "stdlib.h" 

首先,移至第一行的第一个字符。接下来,执行以下命令:

一个 开始在寄存器a中记录宏。
^ 移至行首。
i#include " 在行首插入字符串#include“。
$ 移至行尾。
a" 将字符双引号(“)附加到该行的末尾。
j 转到下一行。
q 停止录制宏。

现在您已经完成了一次工作,您可以通过键入命令“;@a;”三次来重复更改。

“;@a;”命令前面可以有一个计数,这将导致宏执行该次数。在这种情况下,您将输入:

3@a
移动并执行

您可能在各个地方都有要更改的行。只需将光标移到每个位置,然后使用“;@a;”命令即可。如果您已完成一次,则可以使用“;@@;”;再次进行。键入起来有点容易。如果现在使用“;@b;”;执行寄存器b,则下一个“;@@;”将使用寄存器b。

如果将播放方法与使用“;。;”;进行比较,则存在一些差异。首先,“;。;”只能重复一次更改。如上面的示例所示,“;@a;”可以进行一些更改,也可以四处移动。其次,“;。。;”只能记住最近的更改。执行寄存器可以进行任何更改,然后仍使用“;@a;”重播记录的命令。最后,您可以使用26个不同的寄存器。因此,您可以记住要执行的26个不同的命令序列。

使用寄存器

用于记录的寄存器与用于抽出和删除命令的寄存器相同。这使您可以将记录与其他命令混合以操纵寄存器。

假设您已经在寄存器n中记录了一些命令。当您使用“;@n;”;执行此操作时,您会发现您做错了什么。您可以尝试再次录制,但是也许您会犯另一个错误。相反,请使用以下技巧:

G 转到文件末尾。
o; 创建一个空行。
"np 将文本放在ñ寄存器中。现在,您将在文件中看到以文本形式键入的命令。
{edits} 更改错误的命令。就像编辑文本一样。
0 转到该行的开头。
“ ny $ 将更正的命令加入n寄存器。
dd 删除暂存线。

现在,您可以使用“;@n;”;执行更正的命令。如果您记录的命令包含换行符,请调整示例中的最后两项以包括所有行。

追加到寄存器

到目前为止,我们已经使用小写字母表示寄存器名称。要附加到寄存器,请使用大写字母。

假设您已经记录了将单词更改为寄存器c的命令。它可以正常工作,但是您想添加一个搜索以查找下一个要更改的单词。这可以通过以下方式完成:

qC/word\q

您从“;qC;”;开始,它将记录到c寄存器并追加。因此,写入大写的寄存器名称意味着用相同的字母但小写的字母追加到寄存器。

这既适用于录制,也适用于yank和delete命令。例如,您想将多个行收集到一个寄存器中。在第一行中添加:

"aY

现在移至第二行,然后键入:

"AY

对所有行重复此命令。现在,寄存器按您拉动它们的顺序包含所有这些行。

“;:替换;”命令使您可以在整个行范围内执行串行替换。该命令的一般形式如下:

:[range]substitute/from/to/[flags]

此命令在[range]指定的行中将“;从;“字符串更改为”;到;“字符串”;。例如,您可以使用以下命令在所有行中将“教授”更改为“老师”:

:%substitute/Professor/Teacher/

注意:“ :替代;”命令几乎永远不会被完全拼出。大多数时候,人们使用缩写版本“ :s”;从这里开始将使用缩写。

命令前的“;%;”指定命令在所有行上均有效。没有范围,“;:s;”仅在当前行有效。

默认情况下,“;:替换;”命令仅更改每行中的第一个匹配项。例如,前面的命令更改了该行:

Professor Smith criticized Professor Johnson today.

至:

Teacher Smith criticized Professor Johnson today.

要更改该行中的每个匹配项,您需要添加g(变量)标志。命令:

:%s/Professor/Teacher/g

结果(从原始行开始):

Teacher Smith criticized Teacher Johnson today.

其他标志包括p(打印),它使“;:substitute;”命令打印出它更改的最后一行。该Ç(确认)标志告诉“;:替代品;”请你确认它执行每个替换之前。输入以下内容:

:%s/Professor/Teacher/c

vim查找“ Professor”的第一次出现,并显示将要更改的文本。您收到以下提示:

replace with Teacher (y/n/a/q/l/^E/^Y)?

此时,您必须输入以下答案之一:

y 是;;进行更改。
n 没有;;跳过这场比赛。
a 所有;;进行此更改以及所有其他更改,而无需进一步确认。
q 退出;;不要再做任何更改。
l 持续;;进行更改,然后退出。
Ctrl-E 向上滚动文本一行。
Ctrl-Y 向下滚动文本一行。

替代命令的“ from”部分实际上是一种模式。与用于搜索命令的类型相同。例如,此命令仅在行首出现时才用“ the”代替:

:s/^the/these/

如果要替换包含斜杠的“从”或“至”部分,则需要在其前面加上反斜杠。一种更简单的方法是使用其他字符代替斜杠。加号,例如:

:s+one/two+one or two+
命令范围

“;:substitute;”命令和其他:命令可以应用于选择行。这称为范围。

范围的简单形式是{number},{number}。例如:

:1,5s/this/that/g

在第1到5行执行替代命令。包括第5行。范围始终放在命令之前。

单个数字可用于寻址一个特定的行:

:54s/President/Fool/

当您不指定范围时,某些命令将对整个文件起作用。为了使它们在当前行上工作,使用了“;。;”地址。“;:write;”命令就是这样。没有范围,它将写入整个文件。要使其仅将当前行写入文件:

:.write otherfile

第一行始终为第一。最后一行呢?为此使用“;$;”字符。例如,要替换从光标到结尾的行:

:.,$s/yes/no/

我们之前使用的“;%;”范围实际上是从第一行到最后一行说“;1,$;”的一种简短方法。

在范围内使用图案

假设您正在编辑书中的一章,并希望将所有出现的“;灰色;”替换为“;灰色;”。但仅在本章中,而不是在下一章中。您知道第一章中只有章的边界带有单词“ Chapter”。然后,此命令将起作用:

:?^Chapter?,/^Chapter/s=grey=gray=g

您可以看到搜索模式被使用了两次。第一个“;?^章?;”找到当前位置上方与该模式匹配的行。因此,“模式”?范围用于向后搜索。同样,”;/ ^ Chapter /;”用于向前搜索下一章的开头。

为避免与斜杠纠正,此处的替代命令中使用了“”;=字符。斜线或其他字符也可以。

加减

上面的命令中有一个小错误:如果下一章的标题中包含“灰色”,则也将其替换。也许这就是您想要的,但是如果您不想要呢?然后,您可以指定一个替代量。

要搜索模式,然后使用其上方的行:

/Chapter/-1

您可以使用任何数字而不是1。要解决匹配项下面的第二行:

/Chapter/+2

可见量也可以与范围内的其他项目一起使用。看这个:

:.+3,$-5

这指定了范围,该范围从光标下方的三行开始,到文件的最后一行之前的五行结束。

使用标记

可以使用标记来代替替换某些位置的行号,记住它们并在范围内键入它们。

如第3章所述放置标记。例如,使用“;mt;”标记区域的顶部,使用“;mb;”标记区域的底部。然后,您可以使用此范围来指定标记之间的线(包括带有标记的线):

:'t,'b
视觉模式和范围

您可以使用可视模式选择文本。如果然后按“;:;”启动冒号命令,则会看到以下内容:

:'<,'>

现在,您可以键入命令,它将被应用到视觉选择的行范围。

注意:使用可视模式选择部分行或使用Ctrl-V选择文本块时,冒号命令仍将应用于整行。

的“实际上是标记,设置在可视的选择的开始和结束。标记将保持其位置,直到再次进行可视选择为止。因此,您可以使用“;'<;”命令跳转到可视区域开始的位置。您可以将标记与其他项目混合使用:

:'>,$

这解决了从可视区域的末尾到文件末尾的行。

多行

当您知道要更改多少行时,可以键入数字,然后输入“;:;”。例如,当您键入“;5:”时,将得到:

:.,.+4

现在,您可以键入要使用的命令。它将使用范围“;。;”(当前行)直到“;。+ 4;”(向下四行)。因此,它跨越五行。

全局命令

“;:global;”命令是vim的更强大的功能之一。它使您可以找到模式的匹配项并在那里执行命令。通用形式为:

:[range]global/{pattern}/{command}

这类似于“;:substitute;”命令。但是,不是将匹配的文本替换为其他文本,而是执行命令{command}。

注意:为“;:global;”;执行的命令必须以冒号开头。普通模式命令不能直接使用。在正常命令能为你做到这一点。

假设您想将“ foobar”更改为“ barfoo”,但仅在C ++样式注释中。这些注释以“;//”;开头。使用以下命令:

:g+//+s/foobar/barfoo/g

这以“;:g;”;开头。那是“;:global;”的缩写,就像“;:s;”是“;:substitute;”的缩写一样。然后是模式,用加号括起来。由于我们要查找的模式包含一个斜杠,因此使用加号分隔该模式。接着是替换命令,改为“ foobar”更改为“ barfoo”。

全局命令的默认范围是整个文件。因此,在此示例中未指定范围。这与“;:替代品;”;不同,后者只能在一行中使用,而没有范围。

该命令不是完美的,因为它还会匹配“ //”出现在一行中间的行,并且替换也将在“ //”之前进行。

就像使用“;:substitute;”一样,可以使用任何模式。以后学习更复杂的模式时,可以在这里使用它们。

视觉块模式

使用Ctrl-V,您可以开始选择文本的矩形区域。有一些命令对文本块有特殊的作用。

在可视块模式下使用“;$;”命令有一些特殊之处。当最后一个使用的运动命令是“;$;”时,“视觉”选择中的所有行将一直延伸到该行的末尾,同时光标所在的行也较短。在您使用水平移动光标的运动命令之前,此功能一直有效。因此,使用“;j;”保留它,用“;h;”停止它。

插入文字

命令“;I {string};”将文本{string}插入到可视块的左侧。首先按Ctrl-V进入可视块模式。现在,您移动光标来定义您的块。接下来,键入I进入插入模式,然后输入要插入的文本。键入时,文本仅出现在第一行。

在按键结束插入之后,文本将神奇地插入到视觉选择中包含的其余各行中。例:

	include one 
	include two 
	include three 
	include four

将光标移动到“ one”的“ o”,然后按Ctrl-V。使用“;3j;”;将其向下移动到“四个”。现在,您可以选择一个跨越四行的块选择。现在输入:

Imain.

结果:

	include main.one 
	include main.two 
	include main.three 
	include main.four

如果块跨越不延伸到块中的短行,则文本不会插入到该行中。例如,进行可视块选择,在该文本的第一行和最后一行中包括单词“ long”,从而在第二行中未选择任何文本:

 这是一条长线 短 任何其他长线 ^^^^选定的块

现在使用命令“;Ivery;”。结果是:

	This is a long line 
	short 
	Any other long line 
		  ^^^^ selected block

在短行中未插入任何文本。

如果您插入的字符串包含换行符,则“;I;”的作用就像普通的插入命令一样,并且仅影响块的第一行。

“;A;”命令以相同的方式工作,除了它附加在块右侧之后。并且确实在短行中插入了文本。因此,您可以选择是否要在短行上附加文本。

“;A;”;有一种特殊情况:选择一个可视块,然后使用“;$;”使该块延伸到每一行的末尾。现在使用“;A;”会将文本追加到每一行的末尾。

使用上面的相同示例,然后键入“ $ A XXX”,您将得到以下结果:

	This is a long line XXX 
	short XXX 
	Any other long line XXX 

这确实需要使用“;$;”命令。vim记得它曾经被使用过。通过使用其他移动命令将光标移动到最长行的末尾进行相同的选择将不会得到相同的结果。

更改文字

可视块“;c;”命令删除该块,然后将您置于“插入”模式以使您可以键入字符串。该字符串将插入到块的每一行中。

从与上述“长”字相同的选择开始,然后输入“;c_LONG_;”,您将得到:

	This is a _LONG_ line 
	short 
	Any other _LONG_ line

就像使用“;I;”一样,短线不会更改。另外,您不能在新文本中输入换行符。

“;C;”命令从块的左边缘到行尾删除文本。然后将您置于插入模式,以便您可以键入一个字符串,该字符串将添加到每行的末尾。

再次从相同的文本开始,然后输入“;Cnew text;”,您将获得:

	This is a new text 
	short 
	Any other new text

注意:即使仅选择了“长”字,其后的文本也将被删除。因此,仅视觉块左边缘的位置确实很重要。

同样,不进入该块的短线也将被排除。

更改块中字符的其他命令:

交换的情况下(一个;- >;甲和甲;- >;一)
U 使大写(一;- >;甲和甲;- >;甲)
u 化妆小写(一;- >;一个和甲;- >;一)
用字符填充

要用一个字符填充整个块,请使用“;r;”命令。同样,从上面的示例文本开始,然后输入“;rx;”:

	This is a xxxx line 
	short 
	Any other xxxx line

注意:如果要在块的行末尾包括字符,请检查';virtualedit;'功能(您可以在vim中键入“;:help virtualedit;”;以了解更多信息)。

换档

命令“;>;”将选择文本右移一个位移量,并插入间距。此变换的起点是可视块的左边缘。

再次使用相同的示例,“;>;”表示以下结果:

	This is a	  long line 
	short 
	Any other	  long line

位移量通过';shiftwidth;'选项指定。进行其更改为使用4个空格:

:set shiftwidth=4

“;<;”命令删除块左边缘的空白移位量。此命令受那里的文本量限制;因此,如果可用的空白空间移位量,则删除它所能提供的。

连接线“;Ĵ;”命令将所有选定的行连接在一起成为一行。因此,它消除了换行符。实际上,换行符,前导空白和尾随空白由一个空格代替。在行尾使用两个空格(可以通过';joinspaces;'选项更改)。

让我们使用我们现在非常熟悉的示例。使用“J”命令的结果:

	This is a long line short Any other long line 

“;J;”命令不需要逐块选择。它以完全相同的方式与“;v;”和“;V;”选择一起使用。

如果您不希望更改空白,请使用“;gJ;”命令。

读取和写入文件的一部分

在可以编写电子邮件时,您可能需要包括另一个文件。这可以通过“;:read {filename};”命令来完成。文件的文本放在光标线的下面。

从此文本开始:

	Hi John, 
	Here is the diff that fixes the bug: 
	Bye, Pierre.

将光标移到第二行并键入:

	:read patch

将插入称为“;patch;”;的文件,结果如下:

	Hi John, 
	Here is the diff that fixes the bug: 
	2c2 
	<	for (i = 0; i <= length; ++i) 
	--- 
	>	for (i = 0; i < length; ++i) 
	Bye, Pierre.

“;:读取;”命令接受一个范围。该文件将放置在该范围的最后一行编号之下。因此“;:$ r patch;”在文件末尾附加文件“ patch”。

如果要读取第一行上方的文件怎么办?这可以通过零行号来完成。该行实际上并不存在,与大多数命令一起使用时,您会收到一条错误消息。但是允许以下命令:

:0read patch

文件“补丁”将放置在文件第一行的上方。

写双层线

在范围内,仅写入指定的行:进行一系列行写入文件,可以使用“;:write;”命令。没有范围,则写入整个文件。

:.,$write tempo

这会将从游标到文件结尾的行写入文件“节奏”。如果此文件已经存在,您将收到一条错误消息。VIM可以防止意外覆盖现有文件。如果您知道自己在做什么,并且想要覆盖文件,请追加!:

:.,$write! tempo

小心:!必须立即执行“;:编写;”命令,且不留空格。否则,变为过滤器命令,稍后将在此页中进行说明。

附加到文件

在此页的第一部分中,说明了如何将许多行收集到寄存器中。可以执行相同的操作来收集文件中的行。使用此命令写第一行:

:.write collection

现在将光标移至要收集的第二行,然后键入以下内容:

:.write >>collection

“;>>;”告诉vim;“ collection”文件不能写为新文件,但是必须在末尾添加该行。您可以根据需要重复多次。

格式化文字

当您输入纯文本时,如果自动将每行的长度调整为适合窗口大小,将是很好的选择。要在插入文本时发生这种情况,请设置“;textwidth;”选项:

:set textwidth=72

To check the current value of 'textwidth':

:set textwidth

现在,行将被折断,最多只能包含72个字符。但是,当您在一行的中间插入文本或删除一些单词时,这些行将变得太长或太短。VIM不会自动重新格式化文本。

告诉vim格式化当前起点:

gqap

这是从操作员的“;gq;”命令开始。以下是“;ap;”,代表“一个主体”的文本对象。一段与下一段用空行分隔。

注意:包含空格的空白行将不会分开。这很难注意到!

可以使用任何运动或文本对象来代替“;ap;”。如果您的逐步已正确分隔,则可以使用以下命令来格式化整个文件:

gggqG

“;gg;”带您到第一行,“;gq;”是格式运算符,“;G;”跳到最后一行。如果您的指向没有明确定义,则可以仅设置手动选择的行的格式。将光标移到要格式化的第一行。从命令“;gqj;”开始。这将格式化当前行及其下一行。如果第一行很短,则会附加下一行的单词。如果太长,单词将移至下一行。光标移至第二行。现在,您可以使用“;。;”重复该命令。继续执行此操作,直到到达要设置格式的文本的末尾为止。

更改大小写

您的文本带有小写的节标题。您想将“ section”一词全部大写。使用“ gU”运算符执行此操作。从第一列中的光标开始:

			     gUw
 	section header	    ---->      SECTION header

“;gu;”运算符的作用恰恰相反:

			     guw
 	SECTION header	    ---->      section header

您也可以使用“;g〜;”来交换大小写。所有这些都是运算符,因此它们可用于任何运动命令,文本对象和可视模式。

要使操作员在线上工作,请将其加倍。删除运算符为“;d;”,因此要删除行,请使用“;dd;”。同样,“;gug;”使整行变为小写。可以简称为“;guu;”。“;GUGU;”缩短到“;GUU;”和“;G〜G〜;”;到“;克~~;”。例:

				g~~ Some GIRLS have Fun    ---->   sOME girls HAVE fUN 
使用外部程序

vim具有非常强大的命令集,它可以执行任何操作。但是,仍然有一些外部命令可以做的更好或更快速。

命令“;!{motion} {program}接受一段文本,并通过外部程序对其进行过滤。换句话说,它运行{program}表示的系统命令,并以{motion}表示的文本块作为输入。然后,此命令的输出将替换所选的块。

如果您不熟悉UNIX过滤器,那么这会很不好地概括,因此请看一个示例。sort命令对文件进行排序。如果执行以下命令,则未排序的文件input.txt将被排序并写入output.txt。这在UNIX和Microsoft Windows上均适用。

sort output.txt

现在在vim中做同样的事情。您要对文件的第1至5行进行排序。首先将光标放在第1行。接下来,执行以下命令:

!5G

“ !”告诉VIM您正在执行过滤器操作。在VIM编辑期望的动作指令跟随,指示文件到过滤器的哪一部分。“;5G;”命令告诉VIM转到第5行,因此它现在知道要过滤第1行(当前行)到5。

预期进行过滤时,光标会落在屏幕底部,并且会出现一个!提示显示。现在,您可以输入过滤器程序的名称,在本例中为sort。因此,您的完整命令如下:

!5Gsort

结果是排序程序在前5行运行。程序的输出将替换这些行。

	line 55     -->    line 11
	line 33	    -->    line 22
	line 11	    -->    line 33
	line 22	    -->    line 44
	line 44	    -->    line 55
	last line   -->    last line

“;!!;”命令通过过滤器过滤当前行。在Unix中,date命令显示当前时间和日期。“;!! date;”用date输出替换当前行。这对于将时间戳记添加到文件很有用。

当它无效时

启动一个shell,向其发送文本并捕获输出,要求vim知道shell的工作原理。如果您在过滤方面遇到问题,请检查以下选项的值:

'shell' 指定vim用于执行外部程序的程序。
'shellcmdflag' 将命令传递给外壳的参数
';shellquote;' 在命令周围使用引号
';shellxquote;' 在命令和重定向周围使用引号
';shelltype;' 一种外壳(仅适用于Amiga)
';shellslash;' 在命令中使用正斜杠(仅适用于MS-Windows等)
';shellredir;' 用于将命令输出写入文件的字符串

在Unix上,这几乎没有问题,因为有两种外壳:“;sh;”类和“;csh;”类。vim会检查';shell;'选项并自动设置相关选项,具体取决于它是否在';shell;'的某处看到“;csh;”;。

但是,在MS-Windows上,有许多不同的外壳,您可能必须调整选项才能使过滤工作。查看帮助中的选项以获取更多信息。

读取命令输出

要将当前目录的内容读入文件,请使用以下命令。

在Unix上:

:read !ls

在MS Windows上:

:read !dir

将捕获“;ls;”或“;dir;”命令的输出,并将其插入到光标下方的文本中。这类似于读取文件,除了使用“;!;”告诉vim跟随命令。

该命令可能包含参数。一个范围可以用来告诉vim应该把行放在哪里:

:0read !date -u

这会将当前时间和日期以UTC格式插入文件顶部。如果您有一个接受“;-u;”参数的日期命令。注意与使用“;!! date;”:替换一行的区别,而“;:read!date;”将插入一行。

将文字写入命令

Unix命令wc计算字数。要计算当前文件中的单词:

:write !wc

这是与以前相同的写命令,但使用的是“;!;”字符和外部命令的名称,而不是文件名。书面文本将作为标准输入传递到指定命令。输出可能如下所示:

       4      47     249 

该厕所命令不详细。此输出表示您有4行,47个单词和249个字符。

当心这个错误:

:write! wc

这将强制将文件“;wc;”;写入当前目录。(这里的空白很重要!)

重新绘制屏幕

如果外部命令产生了错误消息,则显示可能被弄乱了。vim非常高效,并且仅重绘屏幕上需要重绘的部分。但是它不知道另一个程序写了什么。要告诉vim重画屏幕,请按Ctrl-L。

The 'winheight' option can be set to a minimal desired height of a window and 'winminheight' to a hard minimum height. Likewise, there is 'winwidth' for the minimal desired width and 'winminwidth' for the hard minimum width. The 'equalalways' option, when set, makes vimequalize the windows sizes when a window is closed or opened.

Vertical splits

The ":split" command creates the new window above the current one. To make the window appear at the left side, use:

:vsplit

or:

:vsplit two.c

The result looks something like this:

        ┌──────────────────────────────────────┐
	|/* file two.c */  ||/* file one.c */  ||||
	|~		   ||~		       ||||
	|~		   ||~		       ||||
	|~		   ||~		       ||||
	|two.c===============one.c=============|
	|				       |
        └──────────────────────────────────────┘

Actually, the || lines in the middle will be in reverse video. This is called the vertical separator. It separates the two windows left and right of it.

There is also the ":vnew" command, to open a vertically split window on a new, empty file. Another way to do this:

:vertical new

The ":vertical" command can be inserted before another command that splits a window. This will cause that command to split the window vertically instead of horizontally. If the command doesn't split a window, it works unmodified.

Moving Between Windows

Since you can split windows horizontally and vertically as much as you like, you can create almost any layout of windows. Then you can use these commands to move between them:

Ctrl-W h move to the window on the left
Ctrl-W j move to the window below
Ctrl-W k move to the window above
Ctrl-W l move to the window on the right
Ctrl-W t move to the TOP window
Ctrl-W b move to the BOTTOM window

You will notice the same letters as used for moving the cursor. And the cursor keys can also be used, if you like.

Moving windows

You have split a few windows, but now they are in the wrong place. Then you need a command to move the window somewhere else. For example, you have three windows like this:

        ┌──────────────────────────────────┐
	|/* file two.c */		   |
	|~				   |
	|~				   |
	|two.c=============================|
	|/* file three.c */		   |
	|~				   |
	|~				   |
	|three.c===========================|
	|/* file one.c */		   |
	|~				   |
	|one.c=============================|
	|				   |
        └──────────────────────────────────┘

Clearly the last one should be at the top. Go to that window (using Ctrl-W w) and the type this command: Ctrl-W K

This uses the uppercase letter K. What happens is that the window is moved to the very top. You will notice that K is again used for moving upwards. When you have vertical splits, Ctrl-W K moves the current window to the top and make it occupy the full width of the vim window. If this is your layout:

        ┌───────────────────────────────────────────┐
	|/* two.c */ ||/* three.c */ ||/* one.c */  |
	|~	     ||~	     ||~	    |
	|~	     ||~	     ||~	    |
	|~	     ||~	     ||~	    |
	|~	     ||~	     ||~	    |
	|~	     ||~	     ||~	    |
	|two.c=========three.c=========one.c========|
	|					    |
        └───────────────────────────────────────────┘

Then using Ctrl-W K in the middle window (three.c) will result in:

	┌───────────────────────────────────────────┐
	|/* three.c */				    |
	|~					    |
	|~					    |
	|three.c====================================|
	|/* two.c */	      ||/* one.c */	    ||||
	|~		      ||~		    ||||
	|two.c==================one.c===============|
	|					    |
	└───────────────────────────────────────────┘

The other three similar commands (you can probably guess these now):

Ctrl-W H move window to the far left
Ctrl-W J move window to the bottom
Ctrl-W L move window to the far right
Commands For All Windows

When you have several windows open and you want to quit vim, you can close each window separately. A quicker way is using this command:

:qall

This stands for "quit all". If any of the windows contain changes, vimwill not exit. The cursor will automatically be positioned in a window with changes. You can then either use ":write" to save the changes, or ":quit!" to throw them away.

If you know there are windows with changes, and you want to save all these changes, use this command:

:wall

This stands for "write all". But actually, it only writes files with changes. The vim command knows it doesn't make sense to write files that were not changed.

And then there is the combination of ":qall" and ":wall": the "write and quit all" command:

:wqall

This writes all modified files and quits vim.

Finally, there is a command that quits vim and throws away all changes:

:qall!

Be careful, there is no way to undo this command!

Opening A Window For All Files

To make vim open a window for each file, start it with the "-o" argument:

vim -o one.txt two.txt three.txt

This results in:

	┌───────────────────────────────┐
	|file one.txt			|
	|~				|
	|one.txt========================|
	|file two.txt			|
	|~				|
	|two.txt========================|
	|file three.txt			|
	|~				|
	|three.txt======================|
	|				|
	└───────────────────────────────┘

The "-O" argument is used to get vertically split windows.

When vim is already running, the ":all" command opens a window for each file in the argument list. ":vertical all" does it with vertical splits.

Viewing Differences With vimdiff

There is a special way to start vim, which shows the differences between two files. Let's take a file "main.c" and insert a few characters in one line. Write this file with the 'backup' option set, so that the backup file "main.c~" will contain the previous version of the file.

Type this command in a shell (not in vim):

vimdiff main.c~ main.c

vim will start, with two windows side by side. You will only see the line in which you added characters, and a few lines above and below it.

	 VV		      VV
	┌─────────────────────────────────────────┐
	|+ +--123 lines: /* a|+ +--123 lines: /* a|  <- fold|||
	|  text		     |	text		  |
	|  text		     |	text		  |
	|  text		     |	text		  |
	|  text		     |	changed text	  |  <- changed line
	|  text		     |	text		  |
	|  text		     |	------------------|  <- deleted line
	|  text		     |	text		  |
	|  text		     |	text		  |
	|  text		     |	text		  |
	|+ +--432 lines: text|+ +--432 lines: text|  <- fold|||
	|  ~		     |	~		  |
	|  ~		     |	~		  |
	|main.c~==============main.c==============|
	|					  |
	└─────────────────────────────────────────┘

This picture doesn't show the highlighting, use the vimdiff command for a better look.

The lines that were not modified have been collapsed into one line. This is called a closed fold. They are indicated in the picture with "<- fold". Thus the single fold line at the top stands for 123 text lines. These lines are equal in both files.

The line marked with "<- changed line" is highlighted, and the inserted text is displayed with another color. This clearly shows what the difference is between the two files.

The line that was deleted is displayed with "---" in the main.c window. See the "<- deleted line" marker in the picture. These characters are not really there. They just fill up main.c, so that it displays the same number of lines as the other window.

The Fold Column

Each window has a column on the left with a slightly different background. In the picture above these are indicated with "VV". You notice there is a plus character there, in front of each closed fold. Move the mouse pointer to that plus and click the left button. The fold will open, and you can see the text that it contains.

The fold column contains a minus sign for an open fold. If you click on this -, the fold will close. Obviously, this only works when you have a working mouse. You can also use "zo" to open a fold and "zc" to close it.

Diffing In vim

Another way to start in diff mode can be done from inside vim. Edit the "main.c" file, then make a split and show the differences:

:edit main.c
:vertical diffsplit main.c~

The ":vertical" command is used to make the window split vertically. If you omit this, you will get a horizontal split.

If you have a patch or diff file, you can use the third way to start diff mode. First edit the file to which the patch applies. Then tell vim the name of the patch file:

:edit main.c
:vertical diffpatch main.c.diff

WARNING: The patch file must contain only one patch, for the file you are editing. Otherwise, you will get a lot of error messages, and some files might be patched unexpectedly.

The patching will only be done to the copy of the file in vim. The file on your harddisk will remain unmodified (until you decide to write the file).

Scroll Binding

When the files have more changes, you can scroll in the usual way. vimwill try to keep both the windows start at the same position, so you can easily see the differences side by side.

When you don't want this for a moment, use this command:

:set noscrollbind
Jumping To Changes

When you have disabled folding in some way, it may be difficult to find the changes. Use this command to jump forward to the next change:

]c

To go the other way use:

[c

Prepended a count to jump further away.

Removing Changes

You can move text from one window to the other. This either removes differences or adds new ones. The vim command doesn't keep the highlighting updated in all situations. To update it use this command:

:diffupdate

To remove a difference, you can move the text in a highlighted block from one window to another. Take the "main.c" and "main.c~" example above. Move the cursor to the left window, on the line that was deleted in the other window. Now type this command:

dp

The change will be removed by putting the text of the current window in the other window. "dp" stands for "diff put".

You can also do it the other way around. Move the cursor to the right window, to the line where "changed" was inserted. Now type this command:

do

The change will now be removed by getting the text from the other window. Since there are no changes left now, vim puts all text in a closed fold. "do" stands for "diff obtain". "dg" would have been better, but that already has a different meaning ("dgg" deletes from the cursor until the first line).

Miscellaneous Options

The 'laststatus' option can be used to specify when the last window has a statusline:

0 never
1 only when there are split windows (the default)
2 always

Many commands that edit another file have a variant that splits the window. For Command-line commands this is done by prepending an "s". For example: ":tag" jumps to a tag, ":stag" splits the window and jumps to a tag.

For Normal mode commands a Ctrl-W is prepended. Ctrl-^ jumps to the alternate file, Ctrl-W Ctrl-^ splits the window and edits the alternate file.

The 'splitbelow' option can be set to make a new window appear below the current window. The 'splitright' option can be set to make a vertically split window appear right of the current window.

When splitting a window you can prepend a modifier command to tell where the window is to appear:

:leftabove {cmd} left or above the current window
:aboveleft {cmd} idem
:rightbelow {cmd} right or below the current window
:belowright {cmd} idem
:topleft {cmd} at the top or left of the vim window
:botright {cmd} at the bottom or right of the vim window
Tab Pages

You will have noticed that windows never overlap. That means you quickly run out of screen space. The solution for this is called Tab pages.

Assume you are editing "thisfile". To create a new tab page use this command:

:tabedit thatfile

This will edit the file "thatfile" in a window that occupies the whole vim window. And you will notice a bar at the top with the two file names:

	┌──────────────────────────────────┐
	| thisfile | /thatfile/ __________X|    (thatfile is bold)
	|/* thatfile */			   |
	|that				   |
	|that				   |
	|~				   |
	|~				   |
	|~				   |
	|				   |
	└──────────────────────────────────┘

You now have two tab pages. The first one has a window for "thisfile" and the second one a window for "thatfile". It's like two pages that are on top of each other, with a tab sticking out of each page showing the file name.

Now use the mouse to click on "thisfile" in the top line. The result is

	┌──────────────────────────────────┐
	| /thisfile/ | thatfile __________X|    (thisfile is bold)
	|/* thisfile */			   |
	|this				   |
	|this				   |
	|~				   |
	|~				   |
	|~				   |
	|				   |
	└──────────────────────────────────┘

Thus you can switch between tab pages by clicking on the label in the top line. If you don't have a mouse or don't want to use it, you can use the "gt" command. You can remember it as an abbreviation for "Goto Tab".

Now let's create another tab page with the command:

:tab split

This makes a new tab page with one window that is editing the same buffer as the window we were in:

	┌─────────────────────────────────────┐
	| thisfile | /thisfile/ | thatfile __X|   (thisfile is bold)
	|/* thisfile */			      |
	|this				      |
	|this				      |
	|~				      |
	|~				      |
	|~				      |
	|				      |
	└─────────────────────────────────────┘

You can put ":tab" before any Ex command that opens a window. The window will be opened in a new tab page. Another example:

:tab help gt

Will show the help text for "gt" in a new tab page.

A few more things you can do with tab pages:

  • click with the mouse in the space after the last label. The next tab page will be selected, like with "gt".
  • click with the mouse on the "X" in the top right corner. The current tab page will be closed. Unless there are unsaved changes in the current tab page.
  • double click with the mouse in the top line. A new tab page will be created.
  • the "tabonly" command. Closes all tab pages except the current one. Unless there are unsaved changes in other tab pages.
Macros

The "." command repeats the preceding change. But what if you want to do something more complex than a single change? That's where command recording comes in, better known as a macro. There are three steps:

(1) The "q{register}" command starts recording keystrokes into the register named {register}. The register name must be between a and z.

(2) Type your commands.

(3) To finish recording, press q (without any extra character).

You can now execute the macro by typing the command "@{register}". Take a look at how to use these commands in practice. You have a list of file names that look like this:

	stdio.h 
	fcntl.h 
	unistd.h 
	stdlib.h

And what you want is the following:

	#include "stdio.h" 
	#include "fcntl.h" 
	#include "unistd.h" 
	#include "stdlib.h" 

You start by moving to the first character of the first line. Next you execute the following commands:

qa Start recording a macro in register a.
^ Move to the beginning of the line.
i#include " Insert the string #include " at the beginning of the line.
$ Move to the end of the line.
a" Append the character double quotation mark (") to the end of the line.
j Go to the next line.
q Stop recording the macro.

Now that you have done the work once, you can repeat the change by typing the command "@a" three times.

The "@a" command can be preceded by a count, which will cause the macro to be executed that number of times. In this case you would type:

3@a
Move And Execute

You might have the lines you want to change in various places. Just move the cursor to each location and use the "@a" command. If you have done that once, you can do it again with "@@". That's a bit easier to type. If you now execute register b with "@b", the next "@@" will use register b.

If you compare the playback method with using ".", there are several differences. First of all, "." can only repeat one change. As seen in the example above, "@a" can do several changes, and move around as well. Secondly, "." can only remember the last change. Executing a register allows you to make any changes and then still use "@a" to replay the recorded commands. Finally, you can use 26 different registers. Thus you can remember 26 different command sequences to execute.

Using Registers

The registers used for recording are the same ones you used for yank and delete commands. This allows you to mix recording with other commands to manipulate the registers.

Suppose you have recorded a few commands in register n. When you execute this with "@n" you notice you did something wrong. You could try recording again, but perhaps you will make another mistake. Instead, use this trick:

G Go to the end of the file.
o Create an empty line.
"np Put the text from the n register. You now see the commands you typed as text in the file.
{edits} Change the commands that were wrong. This is just like editing text.
0 Go to the start of the line.
"ny$ Yank the corrected commands into the n register.
dd Delete the scratch line.

Now you can execute the corrected commands with "@n". If your recorded commands include line breaks, adjust the last two items in the example to include all the lines.

Appending To A Register

So far we have used a lowercase letter for the register name. To append to a register, use an uppercase letter.

Suppose you have recorded a command to change a word to register c. It works properly, but you would like to add a search for the next word to change. This can be done with:

qC/word\q

You start with "qC", which records to the c register and appends. Thus writing to an uppercase register name means to append to the register with the same letter, but lowercase.

This works both with recording and with yank and delete commands. For example, you want to collect a sequence of lines into the a register. Yank the first line with:

"aY

Now move to the second line, and type:

"AY

Repeat this command for all lines. The a register now contains all those lines, in the order you yanked them.

Substitution

The ":substitute" command enables you to perform string replacements on a whole range of lines. The general form of this command is as follows:

:[range]substitute/from/to/[flags]

This command changes the "from" string to the "to" string in the lines specified with [range]. For example, you can change "Professor" to "Teacher" in all lines with the following command:

:%substitute/Professor/Teacher/

Note: The ":substitute" command is almost never spelled out completely. Most of the time, people use the abbreviated version ":s". From here on the abbreviation will be used.

The "%" before the command specifies the command works on all lines. Without a range, ":s" only works on the current line.

By default, the ":substitute" command changes only the first occurrence on each line. For example, the preceding command changes the line:

Professor Smith criticized Professor Johnson today.

to:

Teacher Smith criticized Professor Johnson today.

To change every occurrence on the line, you need to add the g (global) flag. The command:

:%s/Professor/Teacher/g

results in (starting with the original line):

Teacher Smith criticized Teacher Johnson today.

Other flags include p (print), which causes the ":substitute" command to print out the last line it changes. The c (confirm) flag tells ":substitute" to ask you for confirmation before it performs each substitution. Enter the following:

:%s/Professor/Teacher/c

vim finds the first occurrence of "Professor" and displays the text it is about to change. You get the following prompt:

replace with Teacher (y/n/a/q/l/^E/^Y)?

At this point, you must enter one of the following answers:

y Yes; make this change.
n No; skip this match.
a All; make this change and all remaining ones without further confirmation.
q Quit; don't make any more changes.
l Last; make this change and then quit.
Ctrl-E Scroll the text one line up.
Ctrl-Y Scroll the text one line down.

The "from" part of the substitute command is actually a pattern. The same kind as used for the search command. For example, this command only substitutes "the" when it appears at the start of a line:

:s/^the/these/

If you are substituting with a "from" or "to" part that includes a slash, you need to put a backslash before it. A simpler way is to use another character instead of the slash. A plus, for example:

:s+one/two+one or two+
Command ranges

The ":substitute" command, and other : commands, can be applied to a selection of lines. This is called a range.

The simple form of a range is {number},{number}. For example:

:1,5s/this/that/g

Executes the substitute command on the lines 1 to 5. Line 5 is included. The range is always placed before the command.

A single number can be used to address one specific line:

:54s/President/Fool/

Some commands work on the whole file when you do not specify a range. To make them work on the current line the "." address is used. The ":write" command works like that. Without a range, it writes the whole file. To make it write only the current line into a file:

:.write otherfile

The first line always has number one. How about the last line? The "$" character is used for this. For example, to substitute in the lines from the cursor to the end:

:.,$s/yes/no/

The "%" range that we used before, is actually a short way to say "1,$", from the first to the last line.

Using A Pattern In A Range

Suppose you are editing a chapter in a book, and want to replace all occurrences of "grey" with "gray". But only in this chapter, not in the next one. You know that only chapter boundaries have the word "Chapter" in the first column. This command will work then:

:?^Chapter?,/^Chapter/s=grey=gray=g

You can see a search pattern is used twice. The first "?^Chapter?" finds the line above the current position that matches this pattern. Thus the ?pattern? range is used to search backwards. Similarly, "/^Chapter/" is used to search forward for the start of the next chapter.

To avoid confusion with the slashes, the "=" character was used in the substitute command here. A slash or another character would have worked as well.

Add And Subtract

There is a slight error in the above command: If the title of the next chapter had included "grey" it would be replaced as well. Maybe that's what you wanted, but what if you didn't? Then you can specify an offset.

To search for a pattern and then use the line above it:

/Chapter/-1

You can use any number instead of the 1. To address the second line below the match:

/Chapter/+2

The offsets can also be used with the other items in a range. Look at this one:

:.+3,$-5

This specifies the range that starts three lines below the cursor and ends five lines before the last line in the file.

Using Marks

Instead of figuring out the line numbers of certain positions, remembering them and typing them in a range, you can use marks.

Place the marks as mentioned in chapter 3. For example, use "mt" to mark the top of an area and "mb" to mark the bottom. Then you can use this range to specify the lines between the marks (including the lines with the marks):

:'t,'b
Visual Mode And Ranges

You can select text with Visual mode. If you then press ":" to start a colon command, you will see this:

:'<,'>

Now you can type the command and it will be applied to the range of lines that was visually selected.

Note: When using Visual mode to select part of a line, or using Ctrl-V to select a block of text, the colon commands will still apply to whole lines.

The '< and '> are actually marks, placed at the start and end of the Visual selection. The marks remain at their position until another Visual selection is made. Thus you can use the "'<" command to jump to position where the Visual area started. And you can mix the marks with other items:

:'>,$

This addresses the lines from the end of the Visual area to the end of the file.

A Number Of Lines

When you know how many lines you want to change, you can type the number and then ":". For example, when you type "5:", you will get:

:.,.+4

Now you can type the command you want to use. It will use the range "." (current line) until ".+4" (four lines down). Thus it spans five lines.

The Global Command

The ":global" command is one of the more powerful features of vim. It allows you to find a match for a pattern and execute a command there. The general form is:

:[range]global/{pattern}/{command}

This is similar to the ":substitute" command. But, instead of replacing the matched text with other text, the command {command} is executed.

Note: The command executed for ":global" must be one that starts with a colon. Normal mode commands can not be used directly. The :normalcommand can do this for you.

Suppose you want to change "foobar" to "barfoo", but only in C++ style comments. These comments start with "//". Use this command:

:g+//+s/foobar/barfoo/g

This starts with ":g". That is short for ":global", just like ":s" is short for ":substitute". Then the pattern, enclosed in plus characters. Since the pattern we are looking for contains a slash, this uses the plus character to separate the pattern. Next comes the substitute command that changes "foobar" into "barfoo".

The default range for the global command is the whole file. Thus no range was specified in this example. This is different from ":substitute", which works on one line without a range.

The command isn't perfect, since it also matches lines where "//" appears halfway a line, and the substitution will also take place before the "//".

Just like with ":substitute", any pattern can be used. When you learn more complicated patterns later, you can use them here.

Visual Block Mode

With Ctrl-V you can start selection of a rectangular area of text. There are a few commands that do something special with the text block.

There is something special about using the "$" command in Visual block mode. When the last motion command used was "$", all lines in the Visual selection will extend until the end of the line, also when the line with the cursor is shorter. This remains effective until you use a motion command that moves the cursor horizontally. Thus using "j" keeps it, "h" stops it.

Inserting Text

The command "I{string}" inserts the text {string} in each line, just left of the visual block. You start by pressing Ctrl-V to enter visual block mode. Now you move the cursor to define your block. Next you type I to enter Insert mode, followed by the text to insert. As you type, the text appears on the first line only.

After you press  to end the insert, the text will magically be inserted in the rest of the lines contained in the visual selection. Example:

	include one 
	include two 
	include three 
	include four

Move the cursor to the "o" of "one" and press Ctrl-V. Move it down with "3j" to "four". You now have a block selection that spans four lines. Now type:

Imain.

The result:

	include main.one 
	include main.two 
	include main.three 
	include main.four

If the block spans short lines that do not extend into the block, the text is not inserted in that line. For example, make a Visual block selection that includes the word "long" in the first and last line of this text, and thus has no text selected in the second line:

	This is a long line 
	short 
	Any other long line 
		  ^^^^ selected block

Now use the command "Ivery". The result is:

	This is a very long line 
	short 
	Any other very long line

In the short line no text was inserted.

If the string you insert contains a newline, the "I" acts just like a Normal insert command and affects only the first line of the block.

The "A" command works the same way, except that it appends after the right side of the block. And it does insert text in a short line. Thus you can make a choice whether you do or don't want to append text to a short line.

There is one special case for "A": Select a Visual block and then use "$" to make the block extend to the end of each line. Using "A" now will append the text to the end of each line.

Using the same example from above, and then typing "$A XXX, you get this result:

	This is a long line XXX 
	short XXX 
	Any other long line XXX 

This really requires using the "$" command. vim remembers that it was used. Making the same selection by moving the cursor to the end of the longest line with other movement commands will not have the same result.

Changing Text

The Visual block "c" command deletes the block and then throws you into Insert mode to enable you to type in a string. The string will be inserted in each line in the block.

Starting with the same selection of the "long" words as above, then typing "c_LONG_", you get this:

	This is a _LONG_ line 
	short 
	Any other _LONG_ line

Just like with "I" the short line is not changed. Also, you can't enter a newline in the new text.

The "C" command deletes text from the left edge of the block to the end of line. It then puts you in Insert mode so that you can type in a string, which is added to the end of each line.

Starting with the same text again, and typing "Cnew text" you get:

	This is a new text 
	short 
	Any other new text

Notice that, even though only the "long" word was selected, the text after it is deleted as well. Thus only the location of the left edge of the visual block really matters.

Again, short lines that do not reach into the block are excluded.

Other commands that change the characters in the block:

~ swap case (a -> A and A -> a)
U make uppercase (a -> A and A -> A)
u make lowercase (a -> a and A -> a)
Filling With A Character

To fill the whole block with one character, use the "r" command. Again, starting with the same example text from above, and then typing "rx":

	This is a xxxx line 
	short 
	Any other xxxx line

Note: If you want to include characters beyond the end of the line in the block, check out the 'virtualedit' feature (you can type ":help virtualedit" in vim to learn more).

Shifting

The command ">" shifts the selected text to the right one shift amount, inserting whitespace. The starting point for this shift is the left edge of the visual block.

With the same example again, ">" gives this result:

	This is a	  long line 
	short 
	Any other	  long line

The shift amount is specified with the 'shiftwidth' option. To change it to use 4 spaces:

:set shiftwidth=4

The "<" command removes one shift amount of whitespace at the left edge of the block. This command is limited by the amount of text that is there; so if there is less than a shift amount of whitespace available, it removes what it can.

Joining Lines

The "J" command joins all selected lines together into one line. Thus it removes the line breaks. Actually, the line break, leading white space and trailing white space is replaced by one space. Two spaces are used after a line ending (that can be changed with the 'joinspaces' option).

Let's use the example that we got so familiar with now. The result of using the "J" command:

	This is a long line short Any other long line 

The "J" command doesn't require a blockwise selection. It works with "v" and "V" selection in exactly the same way.

If you don't want the white space to be changed, use the "gJ" command.

Reading and writing part of a file

When you are writing an e-mail message, you may want to include another file. This can be done with the ":read {filename}" command. The text of the file is put below the cursor line.

Starting with this text:

	Hi John, 
	Here is the diff that fixes the bug: 
	Bye, Pierre.

Move the cursor to the second line and type:

	:read patch

The file named "patch" will be inserted, with this result:

	Hi John, 
	Here is the diff that fixes the bug: 
	2c2 
	<	for (i = 0; i <= length; ++i) 
	--- 
	>	for (i = 0; i < length; ++i) 
	Bye, Pierre.

The ":read" command accepts a range. The file will be put below the last line number of this range. Thus ":$r patch" appends the file "patch" at the end of the file.

What if you want to read the file above the first line? This can be done with the line number zero. This line doesn't really exist, you will get an error message when using it with most commands. But this command is allowed:

:0read patch

The file "patch" will be put above the first line of the file.

Writing A Range Of Lines

To write a range of lines to a file, the ":write" command can be used. Without a range it writes the whole file. With a range only the specified lines are written:

:.,$write tempo

This writes the lines from the cursor until the end of the file into the file "tempo". If this file already exists you will get an error message. vimprotects you from accidentally overwriting an existing file. If you know what you are doing and want to overwrite the file, append !:

:.,$write! tempo

CAREFUL: The ! must follow the ":write" command immediately, without white space. Otherwise, it becomes a filter command, which is explained later on this page.

Appending To A File

In the first section of this page was explained how to collect a number of lines into a register. The same can be done to collect lines in a file. Write the first line with this command:

:.write collection

Now move the cursor to the second line you want to collect, and type this:

:.write >>collection

The ">>" tells vim the "collection" file is not to be written as a new file, but the line must be appended at the end. You can repeat this as many times as you like.

Formatting text

When you are typing plain text, it's nice if the length of each line is automatically trimmed to fit in the window. To make this happen while inserting text, set the 'textwidth' option:

:set textwidth=72

To check the current value of 'textwidth':

:set textwidth

Now lines will be broken to take only up to 72 characters. But when you insert text halfway a line, or when you delete a few words, the lines will get too long or too short. vim doesn't automatically reformat the text.

To tell vim to format the current paragraph:

gqap

This starts with the "gq" command, which is an operator. Following is "ap", the text object that stands for "a paragraph". A paragraph is separated from the next paragraph by an empty line.

Note: A blank line, which contains white space, does NOT separate paragraphs. This is hard to notice!

Instead of "ap" you could use any motion or text object. If your paragraphs are properly separated, you can use this command to format the whole file:

gggqG

"gg" takes you to the first line, "gq" is the format operator and "G" the motion that jumps to the last line. In case your paragraphs aren't clearly defined, you can format just the lines you manually select. Move the cursor to the first line you want to format. Start with the command "gqj". This formats the current line and the one below it. If the first line was short, words from the next line will be appended. If it was too long, words will be moved to the next line. The cursor moves to the second line. Now you can use "." to repeat the command. Keep doing this until you are at the end of the text you want to format.

Changing Case

You have text with section headers in lowercase. You want to make the word "section" all uppercase. Do this with the "gU" operator. Start with the cursor in the first column:

			     gUw
 	section header	    ---->      SECTION header

The "gu" operator does exactly the opposite:

			     guw
 	SECTION header	    ---->      section header

You can also use "g~" to swap case. All these are operators, thus they work with any motion command, with text objects and in Visual mode.

To make an operator work on lines you double it. The delete operator is "d", thus to delete a line you use "dd". Similarly, "gugu" makes a whole line lowercase. This can be shortened to "guu". "gUgU" is shortened to "gUU" and "g~g~" to "g~~". Example:

				g~~ Some GIRLS have Fun    ---->   sOME girls HAVE fUN 
Using An External Program

vim has a very powerful set of commands, it can do anything. But there may still be something that an external command can do better or faster.

The command "!{motion}{program}" takes a block of text and filters it through an external program. In other words, it runs the system command represented by {program}, giving it the block of text represented by {motion} as input. The output of this command then replaces the selected block.

Because this summarizes badly if you are unfamiliar with UNIX filters, take a look at an example. The sort command sorts a file. If you execute the following command, the unsorted file input.txt will be sorted and written to output.txt. This works on both UNIX and Microsoft Windows.

sort output.txt

Now do the same thing in vim. You want to sort lines 1 through 5 of a file. You start by putting the cursor on line 1. Next you execute the following command:

!5G

The "!" tells vim that you are performing a filter operation. The vimeditor expects a motion command to follow, indicating which part of the file to filter. The "5G" command tells vim to go to line 5, so it now knows that it is to filter lines 1 (the current line) through 5.

In anticipation of the filtering, the cursor drops to the bottom of the screen and a ! prompt displays. You can now type in the name of the filter program, in this case sort. Therefore, your full command is as follows:

!5Gsort

The result is that the sort program is run on the first 5 lines. The output of the program replaces these lines.

	line 55     -->    line 11
	line 33	    -->    line 22
	line 11	    -->    line 33
	line 22	    -->    line 44
	line 44	    -->    line 55
	last line   -->    last line

The "!!" command filters the current line through a filter. In Unix the date command prints the current time and date. "!!date" replaces the current line with the output of date. This is useful to add a timestamp to a file.

When It Doesn't Work

Starting a shell, sending it text and capturing the output requires that vim knows how the shell works exactly. When you have problems with filtering, check the values of these options:

'shell' specifies the program that vim uses to execute external programs.
'shellcmdflag' argument to pass a command to the shell
'shellquote' quote to be used around the command
'shellxquote' quote to be used around the command and redirection
'shelltype' kind of shell (only for the Amiga)
'shellslash' use forward slashes in the command (only for MS-Windows and alikes)
'shellredir' string used to write the command output into a file

On Unix this is hardly ever a problem, because there are two kinds of shells: "sh"-like and "csh"-like. vim checks the 'shell' option and sets related options automatically, depending on whether it sees "csh" somewhere in 'shell'.

On MS-Windows, however, there are many different shells and you might have to tune the options to make filtering work. Check the help for the options for more information.

Reading Command Output

To read the contents of the current directory into the file, use the following commands.

on Unix:

:read !ls

on MS Windows:

:read !dir

The output of the "ls" or "dir" command is captured and inserted in the text, below the cursor. This is similar to reading a file, except that the "!" is used to tell vim that a command follows.

The command may have arguments. And a range can be used to tell where vim should put the lines:

:0read !date -u

This inserts the current time and date in UTC format at the top of the file. If you have a date command that accepts the "-u" argument. Note the difference with using "!!date": that replaced a line, while ":read !date" will insert a line.

Writing Text To A Command

The Unix command wc counts words. To count the words in the current file:

:write !wc

This is the same write command as before, but instead of a file name the "!" character is used and the name of an external command. The written text will be passed to the specified command as its standard input. The output could look like this:

       4      47     249 

The wc command isn't verbose. This output means you have 4 lines, 47words and 249 characters.

Watch out for this mistake:

:write! wc

This will write the file "wc" in the current directory, with force. (White space is important here!)

Redrawing The Screen

If the external command produced an error message, the display may have been messed up. vim is very efficient and only redraws those parts of the screen that it knows need redrawing. But it can't know about what another program has written. To tell vim to redraw the screen, press Ctrl-L.

查看英文版

查看中文版

有用的技巧

replace命令可用于将所有出现的单词替换为另一个单词:

:%s/four/4/g

“%”范围表示要替换所有行。末尾的“g”标志将替换一行中的所有单词。

如果您的文件还包含“ thirtyfour”,这将无法正确处理。它将被替换为“ thirty4”。为避免这种情况,请使用“\ <”项来匹配单词的开头:

:%s/\\

显然,这在“十四”上还是错误的。使用“\>”来匹配单词的结尾:

:%s/\/4/g

如果您正在编程,则可能要在注释中而不是在代码中替换“四个”。由于这很难指定,请添加“c”标志以使替换命令提示您进行每次替换:

:%s/\/4/gc
替换成几个文件

假设您要替换多个文件中的单词。您可以编辑每个文件并手动键入命令。使用记录和播放要快得多。

假设您有一个包含C ++文件的目录,所有文件均以“ .cpp”结尾。您需要将一个名为“ GetResp”的函数重命名为“ GetAnswer”。

vim *.cpp 启动vim,定义参数列表以包含所有C ++文件。您现在在第一个文件中。
qq 开始记录到q寄存器
:%s / \ / GetAnswer / g 在第一个文件中进行替换。
:wnext 编写此文件,然后移至下一个文件。
q 停止录音。
@q 执行q寄存器。这将重播替换和“:wnext”。您可以验证这不会产生错误消息。
999@q 在其余文件上执行q寄存器。在最后一个文件中,您会收到一条错误消息,因为“:wnext”无法移动到下一个文件。这将停止执行,一切都完成了。

注意:播放录制的音序时,错误将停止执行。因此,请确保在录制时没有收到错误消息。

有一个陷阱:如果一个.cpp文件不包含单词“ GetResp”,您将得到一个错误,并且替换将停止。为了避免这种情况,请在替代命令中添加“e”标志:

:%s / \  / GetAnswer / ge

“e”标志告诉“:substitute”,找不到匹配项不是错误。

在下一个示例中,我们将文本“ Last,First”更改为“ First Last”。假设您有以下格式的名称列表:

	Doe, John 
	Smith, Peter

您要将其更改为:

	John Doe 
	Peter Smith

只需一个命令即可完成:

:%s/\([^,]*\), \(.*\)/\2 \1/

让我们将其分为几部分。显然,它以替换命令开头。“%”是行范围,代表整个文件。因此,替换在文件的每一行中完成。替代命令的参数为“/ from / to /”。斜杠将“ from”模式和“ to”字符串分开。这是“ from”模式所包含的内容:

整个搜索字符串为: \([^,]*\), \(.*\)
\(\)之间的第一部分匹配“ Last”: \( \)
通过匹配除逗号以外的任何内容: [^,]
...任何次数: *
......然后匹配“”从字面上:
\(\)之间的第二部分匹配“第一”: \(\)
通过匹配任何字符: .
...任何次数: *

在“到”部分,我们有“\ 2”和“\ 1”。这些称为反向引用。它们引用由模式中“\(\)”部分匹配的文本。“\ 2”是指与第二个“\(\)”(即“名字”)匹配的文本。“\ 1”是指第一个“\(\)”,即“姓氏”。

在替代命令的“至”部分中,最多可以使用九个反向引用。“\ 0”代表整个匹配的模式。

排序清单

在Makefile中,您通常有一个文件列表。例如:

	OBJS = \ 
		version.o \ 
		pch.o \ 
		getopt.o \ 
		util.o \ 
		getopt1.o \ 
		inp.o \ 
		patch.o \ 
		backup.o

要对该列表进行排序,请通过外部sort命令过滤文本:

/^OBJS
j
:.,/^$/-1!sort

转到第一行,其中“ OBJS”是该行的第一件事。然后它向下一行,并过滤各行,直到下一个空行。您也可以在可视模式下选择行,然后使用“!sort”。键入起来比较容易,但是在有很多行的情况下需要更多工作。

结果是这样的:

	OBJS = \ 
		backup.o 
		getopt.o \ 
		getopt1.o \ 
		inp.o \ 
		patch.o \ 
		pch.o \ 
		util.o \ 
		version.o \

注意:每行末尾的反斜杠用于指示该行继续。排序后,这是错误的!最后的“ backup.o”行没有反斜杠。现在,它可以排序到另一个位置,它必须有一个反斜杠。

最简单的解决方案是在反斜杠上添加“A \”。如果确保在其后有一个空行,则可以将反斜杠保留在最后一行。这样,您就不会再遇到这个问题了。

逆行顺序

的:全球的命令可以与结合:移动命令的第一行之前,所有的线移动,导致相反的文件。该命令是:

:global/^/m 0

缩写:

:g/^/m 0

正则表达式“^”与行的开头匹配(即使该行为空白)。的:移动命令的匹配线移动到神秘的第0行之后,这样匹配的线成为该文件的第一行。因为:global命令不会被更改的行号所困扰,所以:global继续匹配文件的所有其余行,并将每行放在第一行。

这也适用于许多行。首先移至第一行上方,并用“ mt”标记。然后将光标移到范围的最后一行并键入:

:'t+1,.g/^/m 't
数词

有时,您必须编写最多单词数的文本。vim可以为您计算单词数。

当整个文件就是您想要在其中计算字数时,请使用以下命令:

g Ctrl-G

不要在g后面输入空格,这只是在这里使命令易于阅读。

输出看起来像这样:

Col 1 of 0; Line 141 of 157; Word 748 of 774; Byte 4489 of 4976 

您可以看到您在哪个单词上(748),以及文件中的单词总数(774)。

当文本只是文件的一部分时,您可以移至文本的开头,键入“g Ctrl-G”,移至文本的末尾,再次键入“g Ctrl-G”,然后动动脑筋计算单词位置的差异。这是一个很好的练习,但是有一种更简单的方法。在可视模式下,选择要在其中进行单词计数的文本。然后键入g Ctrl-G。结果:

Selected 5 of 293 Lines; 70 of 1884 Words; 359 of 10928 Bytes 
查找手册页

在编辑Shell脚本或C程序时,您正在使用要为其查找手册页的命令或功能(这适用于Linux,不适用于MS Windows)。我们首先可以使用一个简单的方法:将光标移动到你想找到帮助,按字ķ。

vim将在单词上运行外部man程序。如果找到手册页,则会显示该手册页。这使用普通的寻呼机滚动文本(大多数是更多程序)。结束时,按将使您回到vim。

缺点是您无法同时看到手册页和正在处理的文本。有一个技巧可以使手册页出现在vim窗口中。首先,加载man文件类型插件:

:runtime! ftplugin/man.vim

如果您打算经常这样做,请将此命令放在vimrc文件中。现在,您可以使用“:Man”命令在手册页上打开一个窗口:

:Man csh

您可以滚动浏览并突出显示文本,从而可以找到所需的帮助。使用Ctrl-W w跳至包含您正在处理的文本的窗口。

要在特定章节中找到手册页,请先将章节编号放在首位。例如,在第3节中查找“echo”:

:Man 3 echo

要跳至另一手册页,该手册页的文本格式通常为“ word(1)”,请按Ctrl-]。进一步的“:Man”命令将使用相同的窗口。

要为光标下的单词显示手册页,使用命令\ķ。

(如果重新定义了,请使用它而不是反斜杠)。例如,您想在编辑此行时知道“strstr()”的返回值:

if ( strstr (input, "aap") == ) 

将光标移到“strstr”上的某个位置,然后键入“\ K”。将打开一个窗口,显示strstr()的手册页。

修剪空白

有些人在一行的末尾发现空格和制表符是无用,浪费和丑陋的。要删除每行末尾的空格,请执行以下命令:

:%s/\s\+$//

使用行范围“%”,因此这适用于整个文件。“:substitute”命令与之匹配的模式是“\ s \ + $”。这将在行尾($)之前找到空格字符(\ s),其中1个或多个(\ +)。

替换命令的“至”部分为空:“ //”。因此,它什么也不替换,有效地删除了匹配的空白。

空格的另一种浪费用途是将其放在制表符之前。通常,可以在不更改空白量的情况下将其删除。但不总是!因此,您最好手动执行此操作。使用此搜索命令:“/”。您看不到它,但是此命令中的选项卡之前有一个空格。因此它是“/”。现在使用“x”删除空格并检查空白量是否保持不变。如果确实发生更改,则可能必须插入一个选项卡。输入“n”以查找下一个匹配项。重复此操作,直到找不到更多匹配项。

查找使用单词的地方

如果您是UNIX用户,则可以结合使用vim和grep命令来编辑所有包含给定单词的文件。如果您正在使用程序并想查看或编辑所有包含特定变量的文件,这将非常有用。

例如,假设您要编辑所有包含单词“ frame_counter”的C程序文件。为此,请使用以下命令:

vim `grep -l frame_counter *.c`

让我们详细看一下该命令。grep命令在一组文件中搜索给定的单词。因为指定了-l参数,所以该命令将仅列出包含该单词的文件,而不打印匹配的行。它搜索的单词是“ frame_counter”。实际上,这可以是任何正则表达式。注意:grep用于正则表达式的内容与vim使用的内容并不完全相同。

整个命令包含在反引号(“`”)中。这告诉UNIX shell运行该命令,并假装结果是在命令行上键入的。因此,发生的情况是grep命令运行并生成文件列表,这些文件放在vim命令行上。这导致vim编辑grep输出的文件列表。然后,您可以使用“:next”和“:first”之类的命令浏览文件。

查找每一行

上面的命令仅查找在其中找到单词的文件。您仍然必须在文件中找到单词。

vim有一个内置命令,可用于在一组文件中搜索给定的字符串。例如,如果要查找所有C程序文件中所有出现的“ error_string”,请输入以下命令:

:grep error_string *.c

这使vim在所有指定的文件(* .c)中搜索字符串“ error_string”。编辑器现在将打开找到匹配项的第一个文件,并将光标定位在第一条匹配行上。要转到下一个匹配的行(无论它在什么文件中),请使用“:cnext”命令。要转到上一个匹配项,请使用“:cprev”命令。使用“:clist”查看所有匹配项以及它们的位置。

“:grep”命令使用外部命令grep(在Unix上)或findstr(在Windows上)。您可以通过设置选项'grepprg'进行更改。

命令行缩写

一些“:”命令确实很长。我们已经提到过“:substitute”可以缩写为“:s”。这是一种通用机制,所有“:”命令都可以缩写。

命令能得到多短?有26个字母,还有更多命令。例如,“:set”也以“:s”开头,但是“:s”不会以“:set”命令开头。相反,“:set”可以缩写为“:se”。

当较短的命令形式可用于两个命令时,它仅代表其中一个。没有逻辑背后的,你必须学习它们。在帮助文件中,提到了最有效的最短格式。例如:

:s[ubstitute]

这意味着“:substitute”的最短形式为“:s”。以下字符是可选的。因此“:su”和“:sub”也可以工作。

在用户手册中,我们将使用命令的全名或仍可读的简短版本。例如,“:function”可以缩写为“:fu”。但是由于大多数人不明白这意味着什么,我们将使用“:fun”。vim没有“:funny”命令,否则“:fun”也会造成混乱。

建议在vim脚本中输入完整的命令名。这样可以在以后进行更改时更易于阅读。除了一些常用的命令,例如“:w”(“:write”)和“:r”(“:read”)。

一个特别令人困惑的是“:end”,它可能代表“:endif”,“:endwhile”或“:endfunction”。因此,请始终使用全名。

简短的期权名称

在用户手册中,使用了长名称的选项名称。许多选项也有一个简短的名称。与“:”命令不同,只有一个缩写有效。例如,“ autoindent”的简称是“ ai”。因此,这两个命令执行相同的操作:

:set autoindent
:set ai
命令行完成

这是vim特性之一,其本身就是从Vi切换到vim的原因。一旦使用了此功能,就离不开它。

假设您有一个包含以下文件的目录:

	info.txt
	intro.txt
	bodyofthepaper.txt

要编辑最后一个,请使用以下命令:

:edit bodyofthepaper.txt

输入错误很容易。更快的方法是:

:edit b

这将导致相同的命令。发生了什么?所述<标签>键确实字完成光标前。在这种情况下,“b”。vim在目录中查找,仅找到一个以“b”开头的文件。那一定是您要寻找的那个,因此vim会为您完成文件名。

现在输入:

:edit i

vim会发出哔哔声,并为您提供:

:edit info.txt

发出哔声表示vim找到了多个匹配项。然后,它将使用找到的第一个匹配项(按字母顺序)。如果再次按键,将得到:

:edit intro.txt

因此,如果第一个没有提供您要查找的文件,请再次按它。如果还有更多匹配项,您将一次全部看到它们。

如果在最后一个匹配的条目上按键,将返回到第一次输入的内容:

:edit i

然后,它重新开始。因此,vim在匹配列表中循环。使用Ctrl-P可以从另一个方向浏览列表:

	      <──────────────────────────────────────────────┐
								  |──>──>
	:edit i		      :edit info.txt		   :edit intro.txt
		  <── Ctrl-P <── Ctrl-P |
	   └───────────────────────Ctrl-P─────────────────────>
命令上下文

当您输入“:set i”而不是“:edit i”并按时,您将得到:

:set icon

嘿,为什么没有收到“:set info.txt”?这是因为vim具有上下文相关的完成。vim将寻找的单词类型取决于之前的命令。vim命令知道您不能仅在“:set”命令之后使用文件名,而是可以使用选项名。

同样,如果重复输入,vim将循环显示所有匹配项。有很多,最好先输入更多字符:

:set isk

给出:

:set iskeyword

现在输入“=”并按:

:set iskeyword=@,48-57,_,192-255

这里发生的是vim插入了选项的旧值。现在您可以对其进行编辑。

用完成的就是vim在那个地方所期望的。只需尝试一下,看看它是如何工作的。在某些情况下,您将无法获得想要的东西。那是因为vim不知道您想要什么,或者是因为没有为这种情况实现补全。在这种情况下,您将插入(显示为^ I)。

查看列表匹配

当有很多匹配项时,您希望看到一个概述。通过按Ctrl-D来执行此操作。例如,在之后按Ctrl-D:

:set is

结果是:

:set is
incsearch  isfname    isident    iskeyword  isprint
:set is

vim列出匹配项,然后返回您键入的文本。现在,您可以在列表中查看所需的项目。如果不存在,可以使用来更正单词。如果有很多匹配项,请在按键完成其余操作之前,再输入几个字符。

如果仔细观察,您会发现“ incsearch”不是以“ is”开头。在这种情况下,“ is”代表“ incsearch”的简称。许多选项都有简短的名称和长的名称。vim非常聪明,知道您可能想将选项的短名称扩展为长名称。

还有更多

在按Ctrl-L命令完成这个词来最长的明确字符串。如果输入“:edit i”,并且有文件“ info.txt”和“ info_backup.txt”,则将显示“:edit info”。

'wildmode'选项可用于更改完成工作的方式。'wildmenu'选项可用于获取类似于菜单的匹配项列表。使用'后缀'选项来指定不太重要的文件,并显示在文件列表的末尾。'wildignore'选项指定根本没有列出的文件。

The substitute command can be used to replace all occurrences of a word with another word:

:%s/four/4/g

The "%" range means to replace in all lines. The "g" flag at the end causes all words in a line to be replaced.

This will not do the right thing if your file also contains "thirtyfour". It would be replaced with "thirty4". To avoid this, use the "\<" item to match the start of a word:

:%s/\\

Obviously, this still goes wrong on "fourteen". Use "\>" to match the end of a word:

:%s/\/4/g

If you are programming, you might want to replace "four" in comments, but not in the code. Since this is difficult to specify, add the "c" flag to have the substitute command prompt you for each replacement:

:%s/\/4/gc
Replacing In Several Files

Suppose you want to replace a word in more than one file. You could edit each file and type the command manually. It's a lot faster to use record and playback.

Let's assume you have a directory with C++ files, all ending in ".cpp". There is a function called "GetResp" that you want to rename to "GetAnswer".

vim *.cpp Start;vim, defining the argument list to contain all the C++ files. You are now in the first file.
qq Start recording into the;q;register
:%s/\/GetAnswer/g Do the replacements in the first file.
:wnext Write this file and move to the next one.
q Stop recording.
@q Execute the;q;register. This will replay the substitution and ":wnext". You can verify that this doesn't produce an error message.
999@q Execute the;q;register on the remaining files. At the last file you will get an error message, because ":wnext" cannot move to the next file. This stops the execution, and everything is done.

Note: When playing back a recorded sequence, an error stops the execution. Therefore, make sure you don't get an error message when recording.

There is one catch: If one of the .cpp files does not contain the word "GetResp", you will get an error and replacing will stop. To avoid this, add the "e" flag to the substitute command:

:%s/\/GetAnswer/ge

The "e" flag tells ":substitute" that not finding a match is not an error.

In this next example, let's change the text "Last, First" to "First Last". Let's say you have a list of names in this form:

	Doe, John 
	Smith, Peter

You want to change that to:

	John Doe 
	Peter Smith

This can be done with just one command:

:%s/\([^,]*\), \(.*\)/\2 \1/

Let's break this down in parts. Obviously it starts with a substitute command. The "%" is the line range, which stands for the whole file. Thus the substitution is done in every line in the file. The arguments for the substitute command are "/from/to/". The slashes separate the "from" pattern and the "to" string. This is what the "from" pattern contains:

The whole search string is: \([^,]*\), \(.*\)
The first part between;\( \);matches "Last": \( \)
by matching anything but a comma: [^,]
...any number of times: *
...then matching a ",;" literally: ,
The second part between;\( \);matches "First": \( \)
by matching any character: .
...any number of times: *

In the "to" part we have "\2" and "\1". These are called backreferences. They refer to the text matched by the "\( \)" parts in the pattern. "\2" refers to the text matched by the second "\( \)", which is the "First" name. "\1" refers to the first "\( \)", which is the "Last" name.

You can use up to nine backreferences in the "to" part of a substitute command. "\0" stands for the whole matched pattern.

Sort a list

In a;Makefile;you often have a list of files. For example:

	OBJS = \ 
		version.o \ 
		pch.o \ 
		getopt.o \ 
		util.o \ 
		getopt1.o \ 
		inp.o \ 
		patch.o \ 
		backup.o

To sort this list, filter the text through the external;sort;command:

/^OBJS
j
:.,/^$/-1!sort

This goes to the first line, where "OBJS" is the first thing in the line. Then it goes one line down and filters the lines until the next empty line. You could also select the lines in Visual mode and then use "!sort". That's easier to type, but more work when there are many lines.

The result is this:

	OBJS = \ 
		backup.o 
		getopt.o \ 
		getopt1.o \ 
		inp.o \ 
		patch.o \ 
		pch.o \ 
		util.o \ 
		version.o \

Notice that a backslash at the end of each line is used to indicate the line continues. After sorting, this is wrong! The "backup.o" line that was at the end didn't have a backslash. Now that it sorts to another place, it must have a backslash.

The simplest solution is to add the backslash with "A \". You can keep the backslash in the last line, if you make sure an empty line comes after it. That way you don't have this problem again.

Reverse line order

The;:global;command can be combined with the;:move;command to move all the lines before the first line, resulting in a reversed file. The command is:

:global/^/m 0

Abbreviated:

:g/^/m 0

The "^" regular expression matches the beginning of the line (even if the line is blank). The;:move;command moves the matching line to after the mythical zeroth line, so the current matching line becomes the first line of the file. As the;:global;command is not confused by the changing line numbering,;:global;proceeds to match all remaining lines of the file and puts each as the first.

This also works on a range of lines. First move to above the first line and mark it with "mt". Then move the cursor to the last line in the range and type:

:'t+1,.g/^/m 't
Count words

Sometimes you have to write a text with a maximum number of words.;vim;can count the words for you.

When the whole file is what you want to count the words in, use this command:

g Ctrl-G

Do not type a space after the;g, this is just used here to make the command easy to read.

The output looks like this:

Col 1 of 0; Line 141 of 157; Word 748 of 774; Byte 4489 of 4976 

You can see on which word you are (748), and the total number of words in the file (774).

When the text is only part of a file, you could move to the start of the text, type "g Ctrl-G", move to the end of the text, type "g Ctrl-G" again, and then use your brain to compute the difference in the word position. That's a good exercise, but there is an easier way. With Visual mode, select the text you want to count words in. Then type;g Ctrl-G. The result:

Selected 5 of 293 Lines; 70 of 1884 Words; 359 of 10928 Bytes 
Find A man Page

While editing a shell script or C program, you are using a command or function that you want to find the man page for (this applies to Linux, not MS Windows). Let's first use a simple way: Move the cursor to the word you want to find help on and press;K.

vim;will run the external;man;program on the word. If the man page is found, it is displayed. This uses the normal pager to scroll through the text (mostly the;more;program). When you get to the end pressing;;will get you back into;vim.

A disadvantage is that you can't see the man page and the text you are working on at the same time. There is a trick to make the man page appear in a vim window. First, load the man filetype plugin:

:runtime! ftplugin/man.vim

Put this command in your vimrc file if you intend to do this often. Now you can use the ":Man" command to open a window on a man page:

:Man csh

You can scroll around and the text is highlighted, which allows you to find the help you were looking for. Use;Ctrl-W w;to jump to the window with the text you were working on.

To find a man page in a specific section, put the section number first. For example, to look in section 3 for "echo":

:Man 3 echo

To jump to another man page, which is in the text with the typical form "word(1)", press;Ctrl-];on it. Further ":Man" commands will use the same window.

To display a man page for the word under the cursor, use the command;\K.

(If you redefined the;, use it instead of the backslash). For example, you want to know the return value of "strstr()" while editing this line:

if ( strstr (input, "aap") == ) 

Move the cursor to somewhere on "strstr" and type "\K". A window will open to display the man page for;strstr().

Trim blanks

Some people find spaces and tabs at the end of a line useless, wasteful, and ugly. To remove whitespace at the end of every line, execute the following command:

:%s/\s\+$//

The line range "%" is used, thus this works on the whole file. The pattern that the ":substitute" command matches with is "\s\+$". This finds white space characters (\s), 1 or more of them (\+), before the end-of-line ($).

The "to" part of the substitute command is empty: "//". Thus it replaces with nothing, effectively deleting the matched white space.

Another wasteful use of spaces is placing them before a tab. Often these can be deleted without changing the amount of white space. But not always! Therefore, you can best do this manually. Use this search command: "/". You cannot see it, but there is a space before a tab in this command. Thus it's "/". Now use "x" to delete the space and check that the amount of white space doesn't change. You might have to insert a tab if it does change. Type "n" to find the next match. Repeat this until no more matches can be found.

Find where a word is used

If you are a UNIX user, you can use a combination of;vim;and the grep command to edit all the files that contain a given word. This is extremely useful if you are working on a program and want to view or edit all the files that contain a specific variable.

For example, suppose you want to edit all the C program files that contain the word "frame_counter". To do this you use the command:

vim `grep -l frame_counter *.c`

Let's look at this command in detail. The grep command searches through a set of files for a given word. Because the;-l;argument is specified, the command will only list the files containing the word and not print the matching lines. The word it is searching for is "frame_counter". Actually, this can be any regular expression. Note: What grep uses for regular expressions is not exactly the same as what;vim;uses.

The entire command is enclosed in backticks ("`"). This tells the UNIX shell to run this command and pretend that the results were typed on the command line. So what happens is that the grep command is run and produces a list of files, these files are put on the;vim;command line. This results in;vim;editing the file list that is the output of;grep. You can then use commands like ":next" and ":first" to browse through the files.

Finding Each Line

The above command only finds the files in which the word is found. You still have to find the word within the files.

vim;has a built-in command that you can use to search a set of files for a given string. If you want to find all occurrences of "error_string" in all C program files, for example, enter the following command:

:grep error_string *.c

This causes;vim;to search for the string "error_string" in all the specified files (*.c). The editor will now open the first file where a match is found and position the cursor on the first matching line. To go to the next matching line (no matter in what file it is), use the ":cnext" command. To go to the previous match, use the ":cprev" command. Use ":clist" to see all the matches and where they are.

The ":grep" command uses the external commands grep (on Unix) or findstr (on Windows). You can change this by setting the option 'grepprg'.

Command Line Abbreviations

Some of the ":" commands are really long. We already mentioned that ":substitute" can be abbreviated to ":s". This is a generic mechanism, all ":" commands can be abbreviated.

How short can a command get? There are 26 letters, and many more commands. For example, ":set" also starts with ":s", but ":s" doesn't start a ":set" command. Instead ":set" can be abbreviated to ":se".

When the shorter form of a command could be used for two commands, it stands for only one of them. There is no logic behind which one, you have to learn them. In the help files the shortest form that works is mentioned. For example:

:s[ubstitute]

This means that the shortest form of ":substitute" is ":s". The following characters are optional. Thus ":su" and ":sub" also work.

In the user manual we will either use the full name of command, or a short version that is still readable. For example, ":function" can be abbreviated to ":fu". But since most people don't understand what that stands for, we will use ":fun". vim doesn't have a ":funny" command, otherwise ":fun" would be confusing too.

It is recommended that in;vim;scripts you write the full command name. That makes it easier to read back when you make later changes. Except for some often used commands like ":w" (":write") and ":r" (":read").

A particularly confusing one is ":end", which could stand for ":endif", ":endwhile" or ":endfunction". Therefore, always use the full name.

Short Option Names

In the user manual the long version of the option names is used. Many options also have a short name. Unlike ":" commands, there is only one short name that works. For example, the short name of 'autoindent' is 'ai'. Thus these two commands do the same thing:

:set autoindent
:set ai
Command Line Completion

This is one of those;vim;features that, by itself, is a reason to switch from;Vi;to;vim. Once you have used this, you can't do without.

Suppose you have a directory that contains these files:

	info.txt
	intro.txt
	bodyofthepaper.txt

To edit the last one, you use the command:

:edit bodyofthepaper.txt

It's easy to type this wrong. A much quicker way is:

:edit b

Which will result in the same command. What happened? The;key does completion of the word before the cursor. In this case "b".;vimlooks in the directory and finds only one file that starts with a "b". That must be the one you are looking for, thus;vim;completes the file name for you.

Now type:

:edit i

vim;will beep, and give you:

:edit info.txt

The beep means that;vim;has found more than one match. It then uses the first match it found (alphabetically). If you press;;again, you get:

:edit intro.txt

Thus, if the first;;doesn't give you the file you were looking for, press it again. If there are more matches, you will see them all, one at a time.

If you press;;on the last matching entry, you will go back to what you first typed:

:edit i

Then it starts all over again. Thus;vim;cycles through the list of matches. Use;Ctrl-P;to go through the list in the other direction:

	      <──────────────────────────────────────────────┐
								  |──>──>
	:edit i		      :edit info.txt		   :edit intro.txt
		  <── Ctrl-P <── Ctrl-P |
	   └───────────────────────Ctrl-P─────────────────────>
Command Context

When you type ":set i" instead of ":edit i" and press;;you get:

:set icon

Hey, why didn't you get ":set info.txt"? That's because;vim;has context sensitive completion. The kind of words vim will look for depends on the command before it. The vim command knows that you cannot use a file name just after a ":set" command, but you can use an option name.

Again, if you repeat typing the;,;vim;will cycle through all matches. There are quite a few, it's better to type more characters first:

:set isk

Gives:

:set iskeyword

Now type "=" and press;:

:set iskeyword=@,48-57,_,192-255

What happens here is that vim inserts the old value of the option. Now you can edit it.

What is completed with;;is what;vim;expects in that place. Just try it out to see how it works. In some situations, you will not get what you want. That's either because;vim;doesn't know what you want, or because completion was not implemented for that situation. In that case you will get a;;inserted (displayed as;^I).

Viewing List Matches

When there are many matches, you would like to see an overview. Do this by pressing;Ctrl-D. For example, pressing;Ctrl-D;after:

:set is

results in:

:set is
incsearch  isfname    isident    iskeyword  isprint
:set is

vim;lists the matches and then comes back with the text you typed. You can now check the list for the item you wanted. If it isn't there, you can use;;to correct the word. If there are many matches, type a few more characters before pressing;;to complete the rest.

If you have watched carefully, you will have noticed that "incsearch" doesn't start with "is". In this case "is" stands for the short name of "incsearch". Many options have a short and a long name.;vim;is clever enough to know that you might have wanted to expand the short name of the option into the long name.

There Is More

The;Ctrl-L;command completes the word to the longest unambiguous string. If you type ":edit i" and there are files "info.txt" and "info_backup.txt" you will get ":edit info".

The 'wildmode' option can be used to change the way completion works. The 'wildmenu' option can be used to get a menu-like list of matches. Use the 'suffixes' option to specify files that are less important and appear at the end of the list of files. The 'wildignore' option specifies files that are not listed at all.

查看英文版

查看中文版

vim 示例

vim

启动Vim,使您进入正常模式并显示新文档。

vim document.txt

Launchesvim;并打开filedocument.txt;,或者打开一个空白文档ifDocent.txt;。

vim

Launches vim, placing you in normal mode with a new document.

vim document.txt

Launchesvim;and opens the filedocument.txt, or a blank document ifdocument.txt;does not already exist.

查看英文版

查看中文版