Vim 的基本使用

内容取自 byte-of-vim, 查看原文,请参考文末链接.

Vim

Vim 是一个用于写作的计算机程序(computer program),提供一系列特性帮助你更好地进行写作。 可以用来编写购物清单,写书,或者是程序代码。

为什么选择 Vim

简单

  • 极简主义界面,帮助你集中注意力
  • 少许的核心概念

高效

There is no great writing, only great rewriting.

​ ——Louis Brandeis

与纯文本或富文本编辑器对比,Vim 可以使得复杂大量频繁的修改该变得更容易,更快,更好。Minimal effort. Maximal effect.

Vim 能干什么?

说了这么多漂亮话,Vim 到底强在哪里?

Example

编辑 Vim 中的操作
如何将光标向下移动 7 行 Press 7j
删除一个单词 Press dw
搜索文档中光标所在的单词 Press *
在 50-100 行进行查找并替换 Run :50,100s/old/new/g (s = substitute, c = confirmation )
如果光标所在的单词是一个文件,如何打开 gf (g = goto, f = file)
如果每行只有前N个字符是有用的? ctrl-v –> y (copy)
…… ……

所以,你被说服了吗?

我们为什么学习 Vim ?

Vim 图形化界面版本

Windows

Mac OS X

Linux/BSD

image-20200901204140178

​ Windos 下的 Vim

终端版本

Windows

Mac OS X

Linux/BSD

image-20200901204402296

最重要的概念 - 模式

Vim 中的模式也许是最令刚接触 Vim 的人最疑惑的部分,为什么打开不能直接输入文字?该怎么样保存并退出 Vim?据说 Stack Overflow 上关于如何退出 Vim 的问题,其点击量已有上百万次了

Vim 中不同的模式就像是电视机中的正常模式和 DVD 模式,每种模式都有其特定的功能。模式使得功能区得以划分,使得事情变得尽可能简单。Vim 的目标之一就是使用键盘就可以完成所有工作,而不需要借助鼠标。

Normal Mode (正常模式/命令行模式)

A mode for running commands

Vim 启动的默认模式

1
2
3
4
5
# Vim command :echo
:echo "Hello world"

# Vim command :help takes us to the table of contents of the reference manual
:help usr_toc

Insert Mode (插入模式/编辑模式)

A mode for writing text

打开 Vim,命令行模式下运行 :e temp.txt, 按下 i, 进入编辑模式,输入文本;

按下 <ESC>, 切换回命令行模式,运行 :w 命令保存

使用命令进行更方便的移动光标

除了 i 之外,你还可以

Command Action
i insert text just before the cursor
I insert text at the start of the line
a append text just after the cursor
A append text at the end of the line

光标移动,并切换为 Insert Mode

其他常用操作命令

Command Action
o open a new line below
O open a new line above
s substitute character
S substitutes the whole line
r replace the current character
R replace continuous characters

编辑完文本,切换回 Normal Mode, 是一个良好的习惯,完成文档的初始编写时,最好切换为 Normal Mode。

这两种模式的切换时如此的简单,按下 i 即可进入编辑模式, <ESC> 即可切换为命令行模式,图形化界面看似提供了很多菜单选项,可是如果上百个命令,以及这些命令的组合,图形化界面是难以做到的。

一旦你理解了 Vim 的模式 (哲学), 你就不会觉得好难用,好奇怪,是吧?

Visual mode

假如想要选中一连串的单词(words),并将它们完全替换为新的文本, 该如何做呢?你可不想按住删除键全部删除,再重新添加新的文本吧?Visual Mode 就将发挥它的作用。

Normal Mode 下,按下 v 或则 V 进入 Visual Mode

Command desc
v Visual Mode, character basis
V Visual Mode, line basis

image-20200901215958686

​ relation between the difference modes

Graphical cheat sheet

image-20200901221532521

总结

理解模式是如何工作的,以及如何进行模式的切换是成为一个 Vimmer 的关键,当然, Vim 也只是众多编辑器中的一种 (如 Vim 于 Emacs 之争),如何选择,取决于你的个人习惯和偏好,工欲善其事必先利其器,Vim 也只是提供了一种选择,这个看似古老的软件依然在庞大的程序员群体中占有一席之地,继续发光发热。

参考文献

[1] A Byte of Vim

[2] 7 versatile Vim commands that are easy to memorize

[3] Vim Galore

[4] Graphical vi-vim Cheat Sheet and Tutorial