欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

vim 各个字符的含义 有大用 有大大用 有大大大用

Linux vi/vim常用命令

字数 875阅读 129


Linux vi/vim实用命令总结

vi有三种模式:一般模式,命令行模式,编辑模式.
一般模式下的常用命令
当输入”vi 文件名”就进入了一般模式,一般模式下可以光标移动,搜索与复制,删除字符,删除行操作.

光标移动

  1. [h/键盘向左键] [j/键盘向下键][k/键盘向上键][l/键盘向右键]分别是左下上右方向移动光标.

  2. ctrl + f / ctrl +b /ctrl+ d / ctrl +u 分别是向上移动一页, 向下移动一页, 向下移动半页,向上移动半页.

  3. n<space> n 代表第几个字符, <space>表示空格键, 例如 20+空格键 表示跳到这一行当前光标后移20的位置处.

  4. 0/功能键[home] 跳到该行第一个字符处. $/ 功能键[END]跳到该行最后一个字符.

  5. nG n第几行, 移动到这个文件的第n行. 注意 G 一定要是大写的.

  6. gg 移动到文章的第一行.

  7. N[Enter] 光标下移N行.

查找与替换

  1. /word 查找word字符串,例如/doris ,光标会跳到doris字符串的首字母处.注意是向下搜索第一个匹配的字符串. 如果要继续查找其他的,按下n 表示继续上一次的查找方向,/word时,就是继续向下查找,而按下N则与上一次查找方向相反继续查找该字符串,/word则是继续向上.

  2. ?word 向上寻找 word 字符串.其他与/word相同.

还有更强大的替换查找替换命令呢!!!!

  1. :n1,n2s/word1/word2/g
    查找n1到n2行之间的word1字符串并且替换成word2,并不需要用户确认.
    :1,$s/word1/word2/g(gc) 表示搜索第一行到最后一行中的word1并且替换成word2,如果最后一个g改成gc (c表示替换时有提示)   ( g表示全局的意思吧! ,如果没有g,则每一行都替换第一个匹配的 ),则会显示一条字符串询问是否替换,如下.
    replace with doris (y/n/a/q/l/E/Y) ?

删除

  1. x向后删除相当于[Del] X向前删除[Backspace]. nx表示向后删除n个字符.

  2. dd删除光标所在行. Ndd 删除光标所在的向下n行.

  3. d1G 删除所在行到第一行的所有数据,dG删除所在行到最后一行的所有数据.

  4. d0 数字0, 删除光标所在处到该行最前面一个字符. d$删除从光标所在处到该行的最后一个字符.

复制

yy 复制所在行 nyy向下n行
y0,y$ ,yG,y1G的含义与d0, d$, dG, d1G等触类旁通.

粘贴

  1. p 在光标下一行粘贴,P在光标上一行粘贴.

其他

1. u 撤销上一次操作 [ctrl+r] 重做上一次的操作.
2.  “.” 小数点,重复前一个操作.

PS:注意这些命令都是在一般模式下的命令哦.千万要清楚自己当前所在的模式再用相应的命令呢!!

编辑模式

在一般模式下,按下”a/A, I/i, r/R, o/O”都可以进入编辑模式。

命令行模式

在一般模式下输入”:,/,?” 进入命令行模式.

常用命令:

  1. :w 表示存储在硬盘中. :w! !表示强制写入,如果有权限的话则可以强制写入.

  2. :wq 退出并保存. : wq! 表示退出并强制保存.

  3. 设置行号 :set nu 取消行号 :set nonu.


来自 https://www.jianshu.com/p/7205ac02391a


Linux - vim 与 文件的操作

Akuaner


vim

编辑文件内容 - 三种模式的切换

图片.png

末行模式
:q 退出编辑
:w 保存文本
:wq 保存并退出
:q! 强制退出

:set nu 显示行号
:set hlserch 高亮显示
:set nohlserch 取消高亮显示

/string 全文搜索,从上到下
?string 全文搜索,从下到上
举例:/c 全文搜索c

$ 文件尾 s:搜索替换的意思

:1,$ s/oldstring/newstring 从第一行 到文件尾 ,每行第一个oldstring替换为newstring
:1,$ s/oldstring/newstring/g 从第一行到文件尾,全文oldstring替换为newstring      /g 表示全局的意思,是一行的全局,所有匹配吧
1,$ num1,num2 ?????
.,$ 从当前到文件尾
命令模式:

所有命令都不涉及当前行,操作对象只是包含,并不会改变当前行
光标快速移动:

gg 移动到文本第一行
shift + g 移动到最后一行
num shift + g 移动到指定行num
shift + 6 移动到当前行首位置
shift + 4 移动到当前行末尾

删除:

dd 删除当前行
num dd 从光标处开始,往下删除num行
d num shift+g ,删除 从num行号开始到光标处

撤销/恢复

u 撤销上一次操作
ctrl + r 恢复上一次操作

复制

yy 复制光标所在行
num yy 从光标处开始,往下复制num行
y num shift+g ,复制 从num行号开始到光标处

粘贴

p 粘贴复制的 或者 删除的内容

设置你的vim

设置TAB指定空格
在~目录下,创建.vimrc

set nu  
set autoindent  
set cindent  
set tabstop=4  
set shiftwidth=4  
set smartindent  
set showcmd  
set mouse=a  
set background=light  
set clipboard+=unnamed  
set foldenable  
set foldmethod=indent  
set foldmethod=syntax  
set foldmethod=syntax  
set nofoldenable  
syntax on

文件内容操作

查看文件内容

查看部分内容

more filename q退出,回车翻看 n%的显示

//退出后内容仍显示在屏幕上
more passwd

less filename q退出 ,上下左右翻看 (END结束)

less passwd
//退出后,屏幕干干净净
head -num filename 显示文件前num行内容
head -5 passwd //前五行内容

tail -num filename 显示文件后num行内容

tail -5 passwd
查看全部内容
cat filename
//注意,若文件过大,屏幕是显示不全的,因为有限制
cat其实不主要是用于查看文件内容
cat
1.查看文件内容
2.合并文件内容
cat namea nameb .... namen > namec
[root@localhost 2020-3-6]# touch a.cpp b.cpp
[root@localhost 2020-3-6]# ls
a.cpp  b.cpp
[root@localhost 2020-3-6]# vim a.cpp
[root@localhost 2020-3-6]# vim b.cpp
[root@localhost 2020-3-6]# more a.cpp
abcd
[root@localhost 2020-3-6]# more b.cpp 
efjh
[root@localhost 2020-3-6]# cat a.cpp b.cpp > c.cpp
[root@localhost 2020-3-6]# ls
a.cpp  b.cpp  c.cpp
[root@localhost 2020-3-6]# more c.cpp
abcd
efjh
3.重定向 : 这里指写入一些内容
cat > filename
//注意,Ctrl+c 必须另起一行
[root@localhost 2020-3-6]# cat > chong.c
hello man
hello women
^C
[root@localhost 2020-3-6]# more chong.c 
hello man
hello women
[root@localhost 2020-3-6]# cat > rechong.c
hello^C
[root@localhost 2020-3-6]# more rechong.c 
[root@localhost 2020-3-6]# 

搜索文件内容

find 目录名 -搜索方式 目标文件名

[root@localhost 2020-3-6]# find / -name bin
/sys/kernel/debug/tracing/options/bin
/bin
/usr/share/locale/bin
/usr/bin
/usr/lib/debug/bin
/usr/lib/debug/usr/bin
/usr/local/bin

文本的统计

wc -l filename //统计filename的行数
wc -w filename//统计单词数
wc -c filename//统计字节数

文件的压缩与解压

图片.png
最常见的两种:
图片.png

.tgz文件 一键打包压缩/解压解包⭐

tar zcf tarname.tar 文件1 文件2 //一键压缩
tar zxf tarname.tar //一键解压

tar选项:
z 使得tar命令同时具有压缩和解压的功能(GUN版本以后)
一键打包压缩过程
[root@localhost 2020-3-6]# ls
a.cpp  b.cpp  c.cpp  chong.c  rechong.c
[root@localhost 2020-3-6]# tar -zcf newtar.tgz *.cpp *.c
[root@localhost 2020-3-6]# ls
a.cpp  b.cpp  c.cpp  chong.c  newtar.tgz  rechong.c
一键解压解包过程
[root@localhost 2020-3-6]# ls
a.cpp  b.cpp  c.cpp  chong.c  newtar.tgz  rechong.c
[root@localhost 2020-3-6]# rm *.cpp
[root@localhost 2020-3-6]# rm *.c
[root@localhost 2020-3-6]# ls
newtar.tgz
[root@localhost 2020-3-6]# tar zxf newtar.tgz
[root@localhost 2020-3-6]# ls
a.cpp  b.cpp  c.cpp  chong.c  newtar.tgz  rechong.c

.tar.gz文件的打包压缩和解压解包⭐

压缩文件分为两个步骤:

1.打包 tar :把需要的文件塞到一个包里
2.压缩 gzip :把这个包压小

解包解压文件分为两个步骤:

1.解压 gzip -d zipname.tar.gz
2.解包 tar xf tarname.tar
文件的打包 c

tar 选项 压缩包名.tar 文件1 文件2
tar cf name.tar file1 file2
//把文件1,和文件2 打包进压缩包

tar选项:
 c 创建文件
 f 指定目标为文件(而不是设备)

 v 显示过程
 x 释放包文件
 t 显示包文件中的内容

[root@localhost 2020-3-6]# ls
a.cpp  b.cpp  c.cpp  chong.c  rechong.c
[root@localhost 2020-3-6]# tar cvf newtar.tar *.cpp *.c
a.cpp
b.cpp
c.cpp
chong.c
rechong.c
[root@localhost 2020-3-6]# ls
a.cpp  b.cpp  c.cpp  chong.c  newtar.tar  rechong.c
文件的压缩

gzip newtar.tar
对.tar文件进行压缩,变成.tar.gz压缩文件

[root@localhost 2020-3-6]# ls
a.cpp  b.cpp  c.cpp  chong.c  newtar.tar  rechong.c
[root@localhost 2020-3-6]# gzip newtar.tar 
[root@localhost 2020-3-6]# ls
a.cpp  c.cpp    newtar.tar     rechong.c
b.cpp  chong.c  newtar.tar.gz
-rw-r--r-- 1 root root 10240 Mar  7 13:14 newtar.tar
-rw-r--r-- 1 root root   221 Mar  7 12:53 newtar.tar.gz
文件的解压

gzip -d zipname.tar.gz

[root@localhost 2020-3-6]# ls
newtar.tar.gz
[root@localhost 2020-3-6]# gzip -d newtar.tar.gz 
[root@localhost 2020-3-6]# ls
newtar.tar
文件的解包 x

tar tf tarname.tar
//查看包文件

[root@localhost 2020-3-6]# tar tf newtar.tar 
a.cpp
b.cpp
c.cpp
chong.c
rechong.c

tar xf tarname.tar
//解包

[root@localhost 2020-3-6]# ls
newtar.tar
[root@localhost 2020-3-6]# tar xf newtar.tar 
[root@localhost 2020-3-6]# ls
a.cpp  b.cpp  c.cpp  chong.c  newtar.tar  rechong.c
tar选项:
 x 释放包文件
 f 指定目标为文件(而不是设备)
 t 显示包文件中的内容
 v 显示过程

 c 创建文件


来自 https://segmentfault.com/a/1190000021933031


Linux vi/vim

所有的 Unix Like 系统都会内建 vi 文书编辑器,其他的文书编辑器则不一定会存在。

但是目前我们使用比较多的是 vim 编辑器。

vim 具有程序编辑的能力,可以主动的以字体颜色辨别语法的正确性,方便程序设计。

相关文章:史上最全Vim快捷键键位图 — 入门到进阶


什么是 vim?

Vim是从 vi 发展出来的一个文本编辑器。代码补完、编译及错误跳转等方便编程的功能特别丰富,在程序员中被广泛使用。

简单的来说, vi 是老式的字处理器,不过功能已经很齐全了,但是还是有可以进步的地方。 vim 则可以说是程序开发者的一项很好用的工具。

连 vim 的官方网站 (http://www.vim.org) 自己也说 vim 是一个程序开发工具而不是文字处理软件。

vim 键盘图:


vi/vim 的使用

基本上 vi/vim 共分为三种模式,分别是命令模式(Command mode)输入模式(Insert mode)底线命令模式(Last line mode)。 这三种模式的作用分别是:

命令模式:

用户刚刚启动 vi/vim,便进入了命令模式。

此状态下敲击键盘动作会被Vim识别为命令,而非输入字符。比如我们此时按下i,并不会输入一个字符,i被当作了一个命令。

以下是常用的几个命令:

  • i 切换到输入模式,以输入字符。

  • x 删除当前光标所在处的字符。

  • : 切换到底线命令模式,以在最底一行输入命令。

若想要编辑文本:启动Vim,进入了命令模式,按下i,切换到输入模式。

命令模式只有一些最基本的命令,因此仍要依靠底线命令模式输入更多命令。

输入模式

在命令模式下按下i就进入了输入模式。

在输入模式中,可以使用以下按键:

  • 字符按键以及Shift组合,输入字符

  • ENTER,回车键,换行

  • BACK SPACE,退格键,删除光标前一个字符

  • DEL,删除键,删除光标后一个字符

  • 方向键,在文本中移动光标

  • HOME/END,移动光标到行首/行尾

  • Page Up/Page Down,上/下翻页

  • Insert,切换光标为输入/替换模式,光标将变成竖线/下划线

  • ESC,退出输入模式,切换到命令模式

底线命令模式

在命令模式下按下:(英文冒号)就进入了底线命令模式。

底线命令模式可以输入单个或多个字符的命令,可用的命令非常多。

在底线命令模式中,基本的命令有(已经省略了冒号):

  • q 退出程序

  • w 保存文件

按ESC键可随时退出底线命令模式。

简单的说,我们可以将这三个模式想成底下的图标来表示:


vi/vim 使用实例

使用 vi/vim 进入一般模式

如果你想要使用 vi 来建立一个名为 runoob.txt 的文件时,你可以这样做:

$ vim runoob.txt

直接输入 vi 文件名 就能够进入 vi 的一般模式了。请注意,记得 vi 后面一定要加文件名,不管该文件存在与否!

按下 i 进入输入模式(也称为编辑模式),开始编辑文字

在一般模式之中,只要按下 i, o, a 等字符就可以进入输入模式了!

在编辑模式当中,你可以发现在左下角状态栏中会出现 –INSERT- 的字样,那就是可以输入任意字符的提示。

这个时候,键盘上除了 Esc 这个按键之外,其他的按键都可以视作为一般的输入按钮了,所以你可以进行任何的编辑。

按下 ESC 按钮回到一般模式

好了,假设我已经按照上面的样式给他编辑完毕了,那么应该要如何退出呢?是的!没错!就是给他按下 Esc 这个按钮即可!马上你就会发现画面左下角的 – INSERT – 不见了!

在一般模式中按下 :wq 储存后离开 vi

OK,我们要存档了,存盘并离开的指令很简单,输入 :wq 即可保存离开!

OK! 这样我们就成功创建了一个 runoob.txt 的文件。


vi/vim 按键说明

除了上面简易范例的 i, Esc, :wq 之外,其实 vim 还有非常多的按键可以使用。

第一部分:一般模式可用的光标移动、复制粘贴、搜索替换等

移动光标的方法

h 或 向左箭头键(←)

光标向左移动一个字符

j 或 向下箭头键(↓)

光标向下移动一个字符

k 或 向上箭头键(↑)

光标向上移动一个字符

l 或 向右箭头键(→)

光标向右移动一个字符

如果你将右手放在键盘上的话,你会发现 hjkl 是排列在一起的,因此可以使用这四个按钮来移动光标。 如果想要进行多次移动的话,例如向下移动 30 行,可以使用 "30j" 或 "30↓" 的组合按键, 亦即加上想要进行的次数(数字)后,按下动作即可!

[Ctrl] + [f]

屏幕『向下』移动一页,相当于 [Page Down]按键 (常用)

[Ctrl] + [b]

屏幕『向上』移动一页,相当于 [Page Up] 按键 (常用)

[Ctrl] + [d]

屏幕『向下』移动半页

[Ctrl] + [u]

屏幕『向上』移动半页

+

光标移动到非空格符的下一行

-

光标移动到非空格符的上一行

n<space>

那个 n 表示『数字』,例如 20 。按下数字后再按空格键,光标会向右移动这一行的 n 个字符。例如 20<space> 则光标会向后面移动 20 个字符距离。

0 或功能键[Home]

这是数字『 0 』:移动到这一行的最前面字符处 (常用)

$ 或功能键[End]

移动到这一行的最后面字符处(常用)

H

光标移动到这个屏幕的最上方那一行的第一个字符

M

光标移动到这个屏幕的中央那一行的第一个字符

L

光标移动到这个屏幕的最下方那一行的第一个字符

G

移动到这个档案的最后一行(常用)

nG

n 为数字。移动到这个档案的第 n 行。例如 20G 则会移动到这个档案的第 20 行(可配合 :set nu)

gg

移动到这个档案的第一行,相当于 1G 啊! (常用)

n<Enter>

n 为数字。光标向下移动 n 行(常用)

搜索替换

/word

向光标之下寻找一个名称为 word 的字符串。例如要在档案内搜寻 vbird 这个字符串,就输入 /vbird 即可! (常用)

?word

向光标之上寻找一个字符串名称为 word 的字符串。

n

这个 n 是英文按键。代表重复前一个搜寻的动作。举例来说, 如果刚刚我们执行 /vbird 去向下搜寻 vbird 这个字符串,则按下 n 后,会向下继续搜寻下一个名称为 vbird 的字符串。如果是执行 ?vbird 的话,那么按下 n 则会向上继续搜寻名称为 vbird 的字符串!

N

这个 N 是英文按键。与 n 刚好相反,为『反向』进行前一个搜寻动作。 例如 /vbird 后,按下 N 则表示『向上』搜寻 vbird 。

使用 /word 配合 n 及 N 是非常有帮助的!可以让你重复的找到一些你搜寻的关键词!

:n1,n2s/word1/word2/g

n1 与 n2 为数字。在第 n1 与 n2 行之间寻找 word1 这个字符串,并将该字符串取代为 word2 !举例来说,在 100 到 200 行之间搜寻 vbird 并取代为 VBIRD 则: 『:100,200s/vbird/VBIRD/g』。(常用)

:1,$s/word1/word2/g 或 :%s/word1/word2/g

从第一行到最后一行寻找 word1 字符串,并将该字符串取代为 word2 !(常用)

:1,$s/word1/word2/gc 或 :%s/word1/word2/gc

从第一行到最后一行寻找 word1 字符串,并将该字符串取代为 word2 !且在取代前显示提示字符给用户确认 (confirm) 是否需要取代!(常用)

删除、复制与贴上

x, X

在一行字当中,x 为向后删除一个字符 (相当于 [del] 按键), X 为向前删除一个字符(相当于 [backspace] 亦即是退格键) (常用)

nx

n 为数字,连续向后删除 n 个字符。举例来说,我要连续删除 10 个字符, 『10x』。

dd

删除游标所在的那一整行(常用)

ndd

n 为数字。删除光标所在的向下 n 行,例如 20dd 则是删除 20 行 (常用)

d1G

删除光标所在到第一行的所有数据

dG

删除光标所在到最后一行的所有数据

d$

删除游标所在处,到该行的最后一个字符

d0

那个是数字的 0 ,删除游标所在处,到该行的最前面一个字符

yy

复制游标所在的那一行(常用)

nyy

n 为数字。复制光标所在的向下 n 行,例如 20yy 则是复制 20 行(常用)

y1G

复制游标所在行到第一行的所有数据

yG

复制游标所在行到最后一行的所有数据

y0

复制光标所在的那个字符到该行行首的所有数据

y$

复制光标所在的那个字符到该行行尾的所有数据

p, P

p 为将已复制的数据在光标下一行贴上,P 则为贴在游标上一行! 举例来说,我目前光标在第 20 行,且已经复制了 10 行数据。则按下 p 后, 那 10 行数据会贴在原本的 20 行之后,亦即由 21 行开始贴。但如果是按下 P 呢? 那么原本的第 20 行会被推到变成 30 行。 (常用)

J

将光标所在行与下一行的数据结合成同一行

c

重复删除多个数据,例如向下删除 10 行,[ 10cj ]

u

复原前一个动作。(常用)

[Ctrl]+r

重做上一个动作。(常用)

这个 u 与 [Ctrl]+r 是很常用的指令!一个是复原,另一个则是重做一次~ 利用这两个功能按键,你的编辑,嘿嘿!很快乐的啦!

.

不要怀疑!这就是小数点!意思是重复前一个动作的意思。 如果你想要重复删除、重复贴上等等动作,按下小数点『.』就好了! (常用)

第二部分:一般模式切换到编辑模式的可用的按钮说明

进入输入或取代的编辑模式

i, I

进入输入模式(Insert mode): i 为『从目前光标所在处输入』, I 为『在目前所在行的第一个非空格符处开始输入』。 (常用)

a, A

进入输入模式(Insert mode): a 为『从目前光标所在的下一个字符处开始输入』, A 为『从光标所在行的最后一个字符处开始输入』。(常用)

o, O

进入输入模式(Insert mode): 这是英文字母 o 的大小写。o 为『在目前光标所在的下一行处输入新的一行』; O 为在目前光标所在处的上一行输入新的一行!(常用)

r, R

进入取代模式(Replace mode): r 只会取代光标所在的那一个字符一次;R会一直取代光标所在的文字,直到按下 ESC 为止;(常用)

上面这些按键中,在 vi 画面的左下角处会出现『--INSERT--』或『--REPLACE--』的字样。 由名称就知道该动作了吧!!特别注意的是,我们上面也提过了,你想要在档案里面输入字符时, 一定要在左下角处看到 INSERT 或 REPLACE 才能输入喔!

[Esc]

退出编辑模式,回到一般模式中(常用)

第三部分:一般模式切换到指令行模式的可用的按钮说明

指令行的储存、离开等指令

:w

将编辑的数据写入硬盘档案中(常用)

:w!

若文件属性为『只读』时,强制写入该档案。不过,到底能不能写入, 还是跟你对该档案的档案权限有关啊!

:q

离开 vi (常用)

:q!

若曾修改过档案,又不想储存,使用 ! 为强制离开不储存档案。

注意一下啊,那个惊叹号 (!) 在 vi 当中,常常具有『强制』的意思~

:wq

储存后离开,若为 :wq! 则为强制储存后离开 (常用)

ZZ

这是大写的 Z 喔!如果修改过,保存当前文件,然后退出!效果等同于(保存并退出)

ZQ

不保存,强制退出。效果等同于 :q!。

:w [filename]

将编辑的数据储存成另一个档案(类似另存新档)

:r [filename]

在编辑的数据中,读入另一个档案的数据。亦即将 『filename』 这个档案内容加到游标所在行后面

:n1,n2 w [filename]

将 n1 到 n2 的内容储存成 filename 这个档案。

:! command

暂时离开 vi 到指令行模式下执行 command 的显示结果!例如 『:! ls /home』即可在 vi 当中察看 /home 底下以 ls 输出的档案信息!

vim 环境的变更

:set nu

显示行号,设定之后,会在每一行的前缀显示该行的行号

:set nonu

与 set nu 相反,为取消行号!

特别注意,在 vi/vim 中,数字是很有意义的!数字通常代表重复做几次的意思! 也有可能是代表去到第几个什么什么的意思。

举例来说,要删除 50 行,则是用 『50dd』 对吧! 数字加在动作之前,如我要向下移动 20 行呢?那就是『20j』或者是『20↓』即可。

承接Matlab、Python和C++的编程,机器学习、计算机视觉的理论实现及辅导,本科和硕士的均可,咸鱼交易,专业回答请走知乎,详谈请联系QQ号757160542,非诚勿扰。

来自 https://cloud.tencent.com/developer/article/1732676



第十章、vim 程序编辑器
最近更新日期:2009/08/20

系统管理员的重要工作就是得要修改与设定某些重要软件的配置文件,因此至少得要学会一种以上的文字接口的文书编辑器。 在所有的 Linux distributions 上头都会有的一套文书编辑器就是 vi ,而且很多软件默认也是使用 vi 做为他们编辑的接口, 因此鸟哥建议您务必要学会使用 vi 这个正规的文书编辑器。此外,vim 是进阶版的 vi , vim 不但可以用不同颜色显示文字内容,还能够进行诸如 shell script, C program 等程序编辑功能, 你可以将 vim 视为一种程序编辑器!鸟哥也是用 vim 编辑鸟站的网页文章呢! ^_^


1. vi 与 vim
  1.1 为何要学 vim
2. vi 的使用
  2.1 简易执行范例
  2.2 按键说明
  2.3 一个案例的练习
  2.4 vim 的暂存档、救援回复与开启时的警告讯息
3. vim 的额外功能
  3.1 区块选择(Visual Block)
  3.2 多档案编辑
  3.3 多窗口功能
  3.4 vim 环境设定与记录: ~/.vimrc, ~/.viminfo
  3.5 vim 常用指令示意图
4. 其他 vim 使用注意事项
  4.1 中文编码的问题
  4.2 DOS 与 Linux 的断行字符: dos2unixunix2dos
  4.3 语系编码转换: iconv
5. 重点回顾
6. 本章习题
7. 参考数据与延伸阅读
8. 针对本文的建议:http://phorum.vbird.org/viewtopic.php?t=23883


大标题的图示vi 与 vim

由前面一路走来,我们一直建议使用文本模式来处理 Linux 的系统设定问题,因为不但可以让你比较容易了解到 Linux 的运作状况,也比较容易了解整个设定的基本精神,更能『保证』你的修改可以顺利的被运作。 所以,在 Linux 的系统中使用文本编辑器来编辑你的 Linux 参数配置文件,可是一件很重要的事情呦!也因此呢,系统管理员至少应该要熟悉一种字处理器的!

Tips:
这里要再次的强调,不同的 Linux distribution 各有其不同的附加软件,例如 Red Hat Enterprise Linux 与 Fedora 的 ntsysv 与 setup 等,而 SuSE 则有 YAST 管理工具等等, 因此,如果你只会使用此种类型的软件来控制你的 Linux 系统时,当接管不同的 Linux distributions 时,呵呵!那可就苦恼了!
鸟哥的图示

在 Linux 的世界中,绝大部分的配置文件都是以 ASCII 的纯文本形态存在,因此利用简单的文字编辑软件就能够修改设定了! 与微软的 Windows 系统不同的是,如果你用惯了 Microsoft Word 或 Corel Wordperfect 的话,那么除了 X window 里面的图形接口编辑程序(如 xemacs )用起来尚可应付外,在 Linux 的文本模式下,会觉得文书编辑程序都没有窗口接口来的直观与方便。

Tips:
什么是纯文本档?其实档案记录的就是 0 与 1 ,而我们透过编码系统来将这些 0 与 1 转成我们认识的文字就是了。 在第零章里面的数据表示方式有较多说明,请自行查阅。 ASCII 就是其中一种广为使用的文字编码系统,在 ASCII 系统中的图标与代码可以参考 http://zh.wikipedia.org/wiki/ASCII呢!
鸟哥的图示

那么 Linux 在文字接口下的文书编辑器有哪些呢?其实有非常多喔!常常听到的就有: emacspiconanojoe, 与 vim 等等(注1)。 既然有这么多文字接口的文书编辑器,那么我们为什么一定要学 vi 啊?还有那个 vim 是做啥用的?底下就来谈一谈先!


小标题的图示为何要学 vim

文书编辑器那么多,我们之前在第五章也曾经介绍过那简单好用的 nano ,既然已经学会了 nano ,干嘛鸟哥还一直要你学这不是很友善的 vi 呢?其实是有原因的啦!因为:

  • 所有的 Unix Like 系统都会内建 vi 文书编辑器,其他的文书编辑器则不一定会存在;

  • 很多个别软件的编辑接口都会主动呼叫 vi (例如未来会谈到的 crontabvisudoedquota 等指令);

  • vim 具有程序编辑的能力,可以主动的以字体颜色辨别语法的正确性,方便程序设计;

  • 因为程序简单,编辑速度相当快速。

其实重点是上述的第二点,因为有太多 Linux 上面的指令都默认使用 vi 作为数据编辑的接口,所以你必须、一定要学会 vi ,否则很多指令你根本就无法操作呢!这样说,有刺激到你务必要学会 vi 的热情了吗? ^_^

那么什么是 vim 呢?其实你可以将 vim 视作 vi 的进阶版本,vim 可以用颜色或底线等方式来显示一些特殊的信息。 举例来说,当你使用 vim 去编辑一个 C 程序语言的档案,或者是我们后续会谈到的 shell script 程序时,vim 会依据档案的扩展名或者是档案内的开头信息, 判断该档案的内容而自动的呼叫该程序的语法判断式,再以颜色来显示程序代码与一般信息。也就是说, 这个 vim 是个『程序编辑器』啦!甚至一些 Linux 基础配置文件内的语法,都能够用 vim 来检查呢! 例如我们在第八章谈到的 /etc/fstab 这个档案的内容。

简单的来说, vi 是老式的字处理器,不过功能已经很齐全了,但是还是有可以进步的地方。 vim 则可以说是程序开发者的一项很好用的工具,就连 vim 的官方网站 (http://www.vim.org) 自己也说 vim 是一个『程序开发工具』而不是文字处理软件~^_^。 因为 vim 里面加入了很多额外的功能,例如支持正规表示法的搜寻架构、多档案编辑、区块复制等等。 这对于我们在 Linux 上面进行一些配置文件的修订工作时,是很棒的一项功能呢!

Tips:
什么时候会使用到 vim 呢?其实鸟哥的整个网站都是在 vim 的环境下一字一字的建立起来的喔! 早期鸟哥使用网页制作软件在编写网页,但是老是发现网页编辑软件都不怎么友善,尤其是写到 PHP 方面的程序代码时。 后来就干脆不使用所见即所得的编辑软件,直接使用 vim ,然后标签 (tag) 也都自行用键盘输入! 这样整个档案也比较干净!所以说,鸟哥我是很喜欢 vim 的啦! ^_^
鸟哥的图示

底下鸟哥会先就简单的 vi 做个介绍,然后再跟大家报告一下 vim 的额外功能与用法呢!


大标题的图示vi 的使用

基本上 vi 共分为三种模式,分别是『一般模式』、『编辑模式』与『指令列命令模式』。 这三种模式的作用分别是:

  • 一般模式
    以 vi 打开一个档案就直接进入一般模式了(这是默认的模式)。在这个模式中, 你可以使用『上下左右』按键来移动光标,你可以使用『删除字符』或『删除整行』来处理档案内容, 也可以使用『复制、贴上』来处理你的文件数据。

  • 编辑模式
    在一般模式中可以进行删除、复制、贴上等等的动作,但是却无法编辑文件内容的! 要等到你按下『i, I, o, O, a, A, r, R』等任何一个字母之后才会进入编辑模式。注意了!通常在 Linux 中,按下这些按键时,在画面的左下方会出现『 INSERT 或 REPLACE 』的字样,此时才可以进行编辑。而如果要回到一般模式时, 则必须要按下『Esc』这个按键即可退出编辑模式。

  • 指令列命令模式
    在一般模式当中,输入『 : / ? 』三个中的任何一个按钮,就可以将光标移动到最底下那一行。在这个模式当中, 可以提供你『搜寻资料』的动作,而读取、存盘、大量取代字符、离开 vi 、显示行号等等的动作则是在此模式中达成的!

简单的说,我们可以将这三个模式想成底下的图标来表示:

vi三种模式的相互关系
图 2.1、vi 三种模式的相互关系

注意到上面的图示,你会发现一般模式可与编辑模式及指令列模式切换, 但编辑模式与指令列模式之间不可互相切换喔!这非常重要啦! 闲话不多说,我们底下以一个简单的例子来进行说明吧!


小标题的图示简易执行范例

如果你想要使用 vi 来建立一个名为 test.txt 的档案时,你可以这样做:

  1. 使用 vi 进入一般模式;

    [root@www ~]# vi test.txt
    

    直接输入『 vi 档名』就能够进入 vi 的一般模式了。请注意,记得 vi 后面一定要加档名,不管该档名存在与否! 整个画面主要分为两部份,上半部与最底下一行两者可以视为独立的。如下图 2.1.1 所示,图中那个虚线是不存在的, 鸟哥用来说明而已啦!上半部显示的是档案的实际内容,最底下一行则是状态显示列(如下图的[New File]信息), 或者是命令下达列喔!

    用 vi 开启一个新档案
    图 2.1.1、用 vi 开启一个新档案


    如果你开启的档案是旧档(已经存在的档案),则可能会出现如下的信息:

    用 vi 开启一个旧档案
    图 2.1.2、用 vi 开启一个旧档案


    如上图 2.1.2 所示,箭头所指的那个『"/etc/man.config" 141L, 4617C』代表的是『档名为 /etc/man.conf, 档案内有 141 行 以及具有 4617 个字符』的意思! 那一行的内容并不是在档案内,而是 vi 显示一些信息的地方喔!此时是在一般模式的环境下啦。 接下来开始来输入吧!

  2. 按下 i 进入编辑模式,开始编辑文字

    在一般模式之中,只要按下 i, o, a 等字符就可以进入编辑模式了!在编辑模式当中,你可以发现在左下角状态栏中会出现 –INSERT- 的字样,那就是可以输入任意字符的提示啰!这个时候,键盘上除了 [Esc] 这个按键之外,其他的按键都可以视作为一般的输入按钮了,所以你可以进行任何的编辑啰!

    开始用 vi 来进行编辑
    图 2.1.3、开始用 vi 来进行编辑
    Tips:
    在 vi 里面, [tab] 这个按钮所得到的结果与空格符所得到的结果是不一样的,特别强调一下!
    鸟哥的图示
  3. 按下 [ESC] 按钮回到一般模式

    好了,假设我已经按照上面的样式给他编辑完毕了,那么应该要如何退出呢?是的!没错!就是给他按下 [Esc] 这个按钮即可!马上你就会发现画面左下角的 – INSERT – 不见了!

  4. 在一般模式中按下 :wq 储存后离开 vi

    OK,我们要存档了,存盘并离开的指令很简单,输入『:wq』即可存档离开! (注意了,按下 : 该光标就会移动到最底下一行去!) 这时你在提示字符后面输入『 ls -l 』即可看到我们刚刚建立的 test.txt 档案啦!整个图示有点像底下这样:

    储存并离开 vi 环境
    图 2.1.4、储存并离开 vi 环境

如此一来,你的档案 test.txt 就已经建立起来啰!需要注意的是,如果你的档案权限不对,例如为 -r--r--r-- 时,那么可能会无法写入,此时可以使用『强制写入』的方式吗?可以!使用『 :wq! 』 多加一个惊叹号即可!不过,需要特别注意呦!那个是在『你的权限可以改变』的情况下才能成立的! 关于权限的概念,请自行回去翻一下第六章的内容吧!


小标题的图示按键说明

除了上面简易范例的 i, [Esc], :wq 之外,其实 vim 还有非常多的按键可以使用喔!在介绍之前还是要再次强调, vim 的三种模式只有一般模式可以与编辑、指令列模式切换,编辑模式与指令列模式之间并不能切换的! 这点在图2.1里面有介绍到,注意去看看喔!底下就来谈谈 vim 软件中会用到的按键功能吧!


  • 第一部份:一般模式可用的按钮说明,光标移动、复制贴上、搜寻取代等


移动光标的方法
h 或 向左箭头键(←)光标向左移动一个字符
j 或 向下箭头键(↓)光标向下移动一个字符
k 或 向上箭头键(↑)光标向上移动一个字符
l 或 向右箭头键(→)光标向右移动一个字符
如果你将右手放在键盘上的话,你会发现 hjkl 是排列在一起的,因此可以使用这四个按钮来移动光标。 如果想要进行多次移动的话,例如向下移动 30 行,可以使用 "30j" 或 "30↓" 的组合按键, 亦即加上想要进行的次数(数字)后,按下动作即可!
[Ctrl] + [f]屏幕『向下』移动一页,相当于 [Page Down]按键 (常用)
[Ctrl] + [b]屏幕『向上』移动一页,相当于 [Page Up] 按键 (常用)
[Ctrl] + [d]屏幕『向下』移动半页
[Ctrl] + [u]屏幕『向上』移动半页
+光标移动到非空格符的下一列
-光标移动到非空格符的上一列
n<space>那个 n 表示『数字』,例如 20 。按下数字后再按空格键,光标会向右移动这一行的 n 个字符。例如 20<space> 则光标会向后面移动 20 个字符距离。
0 或功能键[Home]这是数字『 0 』:移动到这一行的最前面字符处 (常用)
$ 或功能键[End]移动到这一行的最后面字符处(常用)
H光标移动到这个屏幕的最上方那一行的第一个字符
M光标移动到这个屏幕的中央那一行的第一个字符
L光标移动到这个屏幕的最下方那一行的第一个字符
G移动到这个档案的最后一行(常用)
nGn 为数字。移动到这个档案的第 n 行。例如 20G 则会移动到这个档案的第 20 行(可配合 :set nu)
gg移动到这个档案的第一行,相当于 1G 啊! (常用)
n<Enter>n 为数字。光标向下移动 n 行(常用)
搜寻与取代
/word向光标之下寻找一个名称为 word 的字符串。例如要在档案内搜寻 vbird 这个字符串,就输入 /vbird 即可! (常用)
?word向光标之上寻找一个字符串名称为 word 的字符串。
n这个 n 是英文按键。代表『重复前一个搜寻的动作』。举例来说, 如果刚刚我们执行 /vbird 去向下搜寻 vbird 这个字符串,则按下 n 后,会向下继续搜寻下一个名称为 vbird 的字符串。如果是执行 ?vbird 的话,那么按下 n 则会向上继续搜寻名称为 vbird 的字符串!
N这个 N 是英文按键。与 n 刚好相反,为『反向』进行前一个搜寻动作。 例如 /vbird 后,按下 N 则表示『向上』搜寻 vbird 。
使用 /word 配合 n 及 N 是非常有帮助的!可以让你重复的找到一些你搜寻的关键词!
:n1,n2s/word1/word2/gn1 与 n2 为数字。在第 n1 与 n2 行之间寻找 word1 这个字符串,并将该字符串取代为 word2 !举例来说,在 100 到 200 行之间搜寻 vbird 并取代为 VBIRD 则:
『:100,200s/vbird/VBIRD/g』。(常用)
:1,$s/word1/word2/g从第一行到最后一行寻找 word1 字符串,并将该字符串取代为 word2 !(常用)
:1,$s/word1/word2/gc从第一行到最后一行寻找 word1 字符串,并将该字符串取代为 word2 !且在取代前显示提示字符给用户确认 (confirm) 是否需要取代!(常用)
删除、复制与贴上
x, X在一行字当中,x 为向后删除一个字符 (相当于 [del] 按键), X 为向前删除一个字符(相当于 [backspace] 亦即是退格键) (常用)
nxn 为数字,连续向后删除 n 个字符。举例来说,我要连续删除 10 个字符, 『10x』。
dd删除游标所在的那一整列(常用)
nddn 为数字。删除光标所在的向下 n 列,例如 20dd 则是删除 20 列 (常用)
d1G删除光标所在到第一行的所有数据
dG删除光标所在到最后一行的所有数据
d$删除游标所在处,到该行的最后一个字符
d0那个是数字的 0 ,删除游标所在处,到该行的最前面一个字符
yy复制游标所在的那一行(常用)
nyyn 为数字。复制光标所在的向下 n 列,例如 20yy 则是复制 20 列(常用)
y1G复制游标所在列到第一列的所有数据
yG复制游标所在列到最后一列的所有数据
y0复制光标所在的那个字符到该行行首的所有数据
y$复制光标所在的那个字符到该行行尾的所有数据
p, Pp 为将已复制的数据在光标下一行贴上,P 则为贴在游标上一行! 举例来说,我目前光标在第 20 行,且已经复制了 10 行数据。则按下 p 后, 那 10 行数据会贴在原本的 20 行之后,亦即由 21 行开始贴。但如果是按下 P 呢? 那么原本的第 20 行会被推到变成 30 行。 (常用)
J将光标所在列与下一列的数据结合成同一列
c重复删除多个数据,例如向下删除 10 行,[ 10cj ]
u复原前一个动作。(常用)
[Ctrl]+r重做上一个动作。(常用)
这个 u 与 [Ctrl]+r 是很常用的指令!一个是复原,另一个则是重做一次~ 利用这两个功能按键,你的编辑,嘿嘿!很快乐的啦!
.不要怀疑!这就是小数点!意思是重复前一个动作的意思。 如果你想要重复删除、重复贴上等等动作,按下小数点『.』就好了! (常用)



  • 第二部份:一般模式切换到编辑模式的可用的按钮说明


进入插入或取代的编辑模式
i, I进入插入模式(Insert mode):
i 为『从目前光标所在处插入』, I 为『在目前所在行的第一个非空格符处开始插入』。 (常用)
a, A进入插入模式(Insert mode):
a 为『从目前光标所在的下一个字符处开始插入』, A 为『从光标所在行的最后一个字符处开始插入』。(常用)
o, O进入插入模式(Insert mode):
这是英文字母 o 的大小写。o 为『在目前光标所在的下一行处插入新的一行』; O 为在目前光标所在处的上一行插入新的一行!(常用)
r, R进入取代模式(Replace mode):
r 只会取代光标所在的那一个字符一次;R会一直取代光标所在的文字,直到按下 ESC 为止;(常用)
上面这些按键中,在 vi 画面的左下角处会出现『--INSERT--』或『--REPLACE--』的字样。 由名称就知道该动作了吧!!特别注意的是,我们上面也提过了,你想要在档案里面输入字符时, 一定要在左下角处看到 INSERT 或 REPLACE 才能输入喔!
[Esc]退出编辑模式,回到一般模式中(常用)



  • 第三部份:一般模式切换到指令列模式的可用的按钮说明


指令列的储存、离开等指令
:w将编辑的数据写入硬盘档案中(常用)
:w!若文件属性为『只读』时,强制写入该档案。不过,到底能不能写入, 还是跟你对该档案的档案权限有关啊!
:q离开 vi (常用)
:q!若曾修改过档案,又不想储存,使用 ! 为强制离开不储存档案。
注意一下啊,那个惊叹号 (!) 在 vi 当中,常常具有『强制』的意思~
:wq储存后离开,若为 :wq! 则为强制储存后离开 (常用)
ZZ这是大写的 Z 喔!若档案没有更动,则不储存离开,若档案已经被更动过,则储存后离开!
:w [filename]将编辑的数据储存成另一个档案(类似另存新档)
:r [filename]在编辑的数据中,读入另一个档案的数据。亦即将 『filename』 这个档案内容加到游标所在行后面
:n1,n2 w [filename]将 n1 到 n2 的内容储存成 filename 这个档案。
:! command暂时离开 vi 到指令列模式下执行 command 的显示结果!例如
『:! ls /home』即可在 vi 当中察看 /home 底下以 ls 输出的档案信息!
vim 环境的变更
:set nu显示行号,设定之后,会在每一行的前缀显示该行的行号
:set nonu与 set nu 相反,为取消行号!


特别注意,在 vi 中,『数字』是很有意义的!数字通常代表重复做几次的意思! 也有可能是代表去到第几个什么什么的意思。举例来说,要删除 50 行,则是用 『50dd』 对吧! 数字加在动作之前~那我要向下移动 20 行呢?那就是『20j』或者是『20↓』即可。

OK!会这些指令就已经很厉害了,因为常用到的指令也只有不到一半!通常 vi 的指令除了上面鸟哥注明的常用的几个外,其他是不用背的,你可以做一张简单的指令表在你的屏幕墙上, 一有疑问可以马上的查询呦!这也是当初鸟哥使用 vim 的方法啦!


小标题的图示一个案例练习

来来来!赶紧测试一下你是否已经熟悉 vi 这个指令呢?请依照底下的需求进行指令动作。 (底下的操作为使用 CentOS 5.2 中的 man.config 来做练习的,该档案你可以在这里下载: http://cn.linux.vbird.org/linux_basic/0310vi/man.config。) 看看你的显示结果与鸟哥的结果是否相同啊?

  1. 请在 /tmp 这个目录下建立一个名为 vitest 的目录;

  2. 进入 vitest 这个目录当中;

  3. 将 /etc/man.config 复制到本目录底下(或由上述的连结下载 man.config 档案);

  4. 使用 vi 开启本目录下的 man.config 这个档案;

  5. 在 vi 中设定一下行号;

  6. 移动到第 58 行,向右移动 40 个字符,请问你看到的双引号内是什么目录?

  7. 移动到第一行,并且向下搜寻一下『 bzip2 』这个字符串,请问他在第几行?

  8. 接着下来,我要将 50 到 100 行之间的『小写 man 字符串』改为『大写 MAN 字符串』,并且一个一个挑选是否需要修改,如何下达指令?如果在挑选过程中一直按『y』, 结果会在最后一行出现改变了几个 man 呢?

  9. 修改完之后,突然反悔了,要全部复原,有哪些方法?

  10. 我要复制 65 到 73 这九行的内容(含有MANPATH_MAP),并且贴到最后一行之后;

  11. 21 到 42 行之间的开头为 # 符号的批注数据我不要了,要如何删除?

  12. 将这个档案另存成一个 man.test.config 的檔名;

  13. 去到第 27 行,并且删除 15 个字符,结果出现的第一个单字是什么?

  14. 在第一行新增一行,该行内容输入『I am a student...』;

  15. 储存后离开吧!

整个步骤可以如下显示:

  1. 『mkdir /tmp/vitest』

  2. 『cd /tmp/vitest』

  3. 『cp /etc/man.config .』

  4. 『vi man.config』

  5. 『:set nu』然后你会在画面中看到左侧出现数字即为行号。

  6. 先按下『58G』再按下『40→』会看到『/dir/bin/foo』这个字样在双引号内;

  7. 先执行『1G』或『gg』后,直接输入『/bzip2』,则会去到第 118 行才对!

  8. 直接下达『 :50,100s/man/MAN/gc 』即可!若一直按『y』最终会出现『在 23 行内置换 25 个字符串』的说明。

  9. (1)简单的方法可以一直按『 u 』回复到原始状态,(2)使用不储存离开『 :q! 』之后,再重新读取一次该档案;

  10. 『65G』 然后再『 9yy 』之后最后一行会出现『复制九行』之类的说明字样。 按下『 G 』到最后一行,再给他『 p 』贴上九行!

  11. 因为 21~42 22 行,因此『 21G 』→『 22dd 』就能删除 22 行,此时你会发现游标所在 21 行的地方变成 MANPATH 开头啰, 批注的 # 符号那几行都被删除了。

  12. 『 :w man.test.config 』,你会发现最后一行出现 "man.test.config" [New].. 的字样。

  13. 『27G』 之后,再给他『 15x 』即可删除 15 个字符,出现『 you 』的字样;

  14. 先『 1G 』去到第一行,然后按下大写的『 O 』便新增一行且在插入模式;开始输入『I am a student...』后, 按下[Esc]回到一般模式等待后续工作;

  15. 『:wq』

如果你的结果都可以查的到,那么 vi 的使用上面应该没有太大的问题啦!剩下的问题会是在…打字练习…。


小标题的图示vim 的暂存档、救援回复与开启时的警告讯息

在目前主要的编辑软件都会有『回复』的功能,亦即当你的系统因为某些原因而导致类似当机的情况时, 还可以透过某些特别的机制来让你将之前未储存的数据『救』回来!这就是鸟哥这里所谓的『回复』功能啦! 那么 vim 有没有回复功能呢?有的! vim 就是透过『暂存档』来救援的啦!

当我们在使用 vim 编辑时, vim 会在与被编辑的档案的目录下,再建立一个名为 .filename.swp 的档案。 比如说我们在上一个小节谈到的编辑 /tmp/vitest/man.config 这个档案时, vim 会主动的建立 /tmp/vitest/.man.config.swp 的暂存档,你对 man.config 做的动作就会被记录到这个 .man.config.swp 当中喔!如果你的系统因为某些原因断线了, 导致你编辑的档案还没有储存,这个时候 .man.config.swp 就能够发会救援的功能了!我们来测试一下吧! 底下的练习有些部分的指令我们尚未谈到,没关系,你先照着做,后续再回来了解啰!

[root@www ~]# cd /tmp/vitest
[root@www vitest]# vim man.config
# 此时会进入到 vim 的画面,请在 vim 的一般模式下按下『 [ctrl]-z 』的组合键

[1]+  Stopped             vim man.config  <==按下 [ctrl]-z 会告诉你这个讯息

当我们在 vim 的一般模式下按下 [ctrl]-z 的组合按键时,你的 vim 会被丢到背景去执行! 这部份的功能我们会在第十七章的程序管理当中谈到, 你这里先知道一下即可。回到命令提示字符后,接下来我们来模拟将 vim 的工作不正常的中断吧!

[root@www vitest]# ls -al
total 48
drwxr-xr-x 2 root root 4096 Jan 12 14:48 .
drwxrwxrwt 7 root root 4096 Jan 12 13:26 ..
-rw-r--r-- 1 root root 4101 Jan 12 13:55 man.config
-rw-r--r-- 1 root root 4096 Jan 12 14:48 .man.config.swp  <==就是他,暂存档
-rw-r--r-- 1 root root 4101 Jan 12 13:43 man.test.config

[root@www vitest]# kill -9 %1 <==这里仿真断线停止 vim 工作
[root@www vitest]# ls -al .man.config.swp
-rw-r--r-- 1 root root 4096 Jan 12 14:48 .man.config.swp  <==暂存档还是会存在!

那个 kill 可以仿真将系统的 vim 工作删除的情况,你可以假装当机了啦! 由于 vim 的工作被不正常的中断,导致暂存盘无法藉由正常流程来结束, 所以暂存档就不会消失,而继续保留下来。此时如果你继续编辑那个 man.config ,会出现什么情况呢? 会出现如下所示的状态喔:

[root@www vitest]# vim man.config
E325: ATTENTION  <==错误代码
Found a swap file by the name ".man.config.swp"  <==底下数行说明有暂存档的存在
          owned by: root   dated: Mon Jan 12 14:48:24 2009
         file name: /tmp/vitest/man.config  <==这个暂存盘属于哪个实际的档案?
          modified: no
         user name: root   host name: www.vbird.tsai
        process ID: 11539
While opening file "man.config"
             dated: Mon Jan 12 13:55:07 2009
底下说明可能发生这个错误的两个主要原因与解决方案!
(1) Another program may be editing the same file.
    If this is the case, be careful not to end up with two
    different instances of the same file when making changes.
    Quit, or continue with caution.

(2) An edit session for this file crashed.
    If this is the case, use ":recover" or "vim -r man.config"
    to recover the changes (see ":help recovery").
    If you did this already, delete the swap file ".man.config.swp"
    to avoid this message.

Swap file ".man.config.swp" already exists!底下说明你可进行的动作
[O]pen Read-Only, (E)dit anyway, (R)ecover, (D)elete it, (Q)uit, (A)bort:  

由于暂存盘存在的关系,因此 vim 会主动的判断你的这个档案可能有些问题,在上面的图示中 vim 提示两点主要的问题与解决方案,分别是这样的:

  • 问题一:可能有其他人或程序同时在编辑这个档案:

    由于 Linux 是多人多任务的环境,因此很可能有很多人同时在编辑同一个档案。如果在多人共同编辑的情况下, 万一大家同时储存,那么这个档案的内容将会变的乱七八糟!为了避免这个问题,因此 vim 会出现这个警告窗口! 解决的方法则是:


    • 找到另外那个程序或人员,请他将该 vim 的工作结束,然后你再继续处理。

    • 如果你只是要看该档案的内容并不会有任何修改编辑的行为,那么可以选择开启成为只读(O)档案, 亦即上述画面反白部分输入英文『 o 』即可,其实就是 [O]pen Read-Only 的选项啦!

  • 问题二:在前一个 vim 的环境中,可能因为某些不知名原因导致 vim 中断 (crashed):

    这就是常见的不正常结束 vim 产生的后果。解决方案依据不同的情况而不同喔!常见的处理方法为:


    • 如果你之前的 vim 处理动作尚未储存,此时你应该要按下『R』,亦即使用 (R)ecover 的项目, 此时 vim 会载入 .man.config.swp 的内容,让你自己来决定要不要储存!这样就能够救回来你之前未储存的工作。 不过那个 .man.config.swp 并不会在你结束 vim 后自动删除,所以你离开 vim 后还得要自行删除 .man.config.swp 才能避免每次打开这个档案都会出现这样的警告

    • 如果你确定这个暂存盘是没有用的,那么你可以直接按下『D』删除掉这个暂存盘,亦即 (D)elete it 这个项目即可。 此时 vim 会载入 man.config ,并且将旧的 .man.config.swp 删除后,建立这次会使用的新的 .man.config.swp 喔!

至于这个发现暂存盘警告讯息的画面中,有出现六个可用按钮,各按钮的说明如下:

  • [O]pen Read-Only:打开此档案成为只读档, 可以用在你只是想要查阅该档案内容并不想要进行编辑行为时。一般来说,在上课时,如果你是登入到同学的计算机去看他的配置文件, 结果发现其实同学他自己也在编辑时,可以使用这个模式;

  • (E)dit anyway:还是用正常的方式打开你要编辑的那个档案, 并不会载入暂存档的内容。不过很容易出现两个使用者互相改变对方的档案等问题!不好不好!

  • (R)ecover:就是加载暂存盘的内容,用在你要救回之前未储存的工作。 不过当你救回来并且储存离开 vim 后,还是要手动自行删除那个暂存档喔!

  • (D)elete it:你确定那个暂存档是无用的!那么开启档案前会先将这个暂存盘删除! 这个动作其实是比较常做的!因为你可能不确定这个暂存档是怎么来的,所以就删除掉他吧!哈哈!

  • (Q)uit:按下 q 就离开 vim ,不会进行任何动作回到命令提示字符。

  • (A)bort:忽略这个编辑行为,感觉上与 quit 非常类似! 也会送你回到命令提示字符就是啰!


大标题的图示vim 的额外功能

其实,目前大部分的 distributions 都以 vim 取代 vi 的功能了!如果你使用 vi 后,却看到画面的右下角有显示目前光标所在的行列号码,那么你的 vi 已经被 vim 所取代啰~ 为什么要用 vim 呢?因为 vim 具有颜色显示的功能,并且还支持许多的程序语法 (syntax), 因此,当你使用 vim 编辑程序时( 不论是 C 语言,还是 shell script ), 我们的 vim 将可帮你直接进行『程序除错 (debug)』的功能!真的很不赖吧!^_^

如果你在文本模式下,输入 alias 时,出现这样的画面:

[root@www ~]# alias
....其他省略....
alias vi='vim'  <==重点在这行啊!

这表示当你使用 vi 这个指令时,其实就是执行 vim 啦!如果你没有这一行,那么你就必须要使用 vim filename 来启动 vim 啰!基本上, vim 的一般用法与 vi 完全一模一样~没有不同啦!那么我们就来看看 vim 的画面是怎样啰!假设我想要编辑 /etc/man.config ,则输入『vim /etc/man.config

vim 的图示示意
图3.0.1、 vim 的图示示意

上面是 vim 的画面示意图,在这个画面中有几点特色要说明喔:

  1. 由于 man.config 是系统规划的配置文件,因此 vim 会进行语法检验,所以你会看到画面中内部主要为深蓝色, 且深蓝色那一行是以批注符号 (#) 为开头;

  2. 最底下一行的左边显示该档案的属性,包括 141行与 4617 字符;

  3. 最底下一行的右边出现的 1,1 表示光标所在为第一行, 第一个字符位置之意(请看一下上图中的游标所在);

所以,如果你向下移动到其他位置时,出现的非批注的数据就会有点像这样:

vim 的图示示意
图3.0.2、 vim 的图示示意

看到了喔!除了批注之外,其他的行就会有特别的颜色显示呢!可以避免你打错字啊!而且, 最右下角的 30% 代表目前这个画面占整体档案的 30% 之意!这样瞭乎?


小标题的图示区块选择(Visual Block)

刚刚我们提到的简单的 vi 操作过程中,几乎提到的都是以行为单位的操作。那么如果我想要搞定的是一个区块范围呢? 举例来说,像底下这种格式的档案:

192.168.1.1    host1.class.net
192.168.1.2    host2.class.net
192.168.1.3    host3.class.net
192.168.1.4    host4.class.net
.....中间省略......

这个档案我将他放置到 http://cn.linux.vbird.org/linux_basic/0310vi/hosts ,你可以自行下载来看一看这个档案啊!现在我们来玩一玩这个档案吧!假设我想要将 host1, host2... 等等复制起来, 并且加到每一行的后面,亦即每一行的结果要是『 192.168.1.2 host2.class.net host2 』这样的情况时, 在传统或现代的窗口型编辑器似乎不容易达到这个需求,但是咱们的 vim 是办的到的喔!那就使用区块选择 (Visual Block) 吧!当我们按下 v 或者 V 或者 [Ctrl]+v 时, 这个时候光标移动过的地方就会开始反白,这三个按键的意义分别是:

区块选择的按键意义
v字符选择,会将光标经过的地方反白选择!
V行选择,会将光标经过的行反白选择!
[Ctrl]+v区块选择,可以用长方形的方式选择资料
y将反白的地方复制起来
d将反白的地方删除掉


来实际进行我们需要的动作吧!就是将 host 再加到每一行的最后面,你可以这样做:

  1. 使用 vim hosts 来开启该档案,记得该档案请由上述的连结下载先!

  2. 将光标移动到第一行的 host 那个 h 上头,然后按下 [ctrl]-v ,左下角出现区块示意字样:

    进入区块功能的示意图
    图 3.1.1、进入区块功能的示意图


  3. 将光标移动到最底部,此时光标移动过的区域会反白!如下图所示:

    区块选择的结果示意图
    图 3.1.2、区块选择的结果示意图


  4. 此时你可以按下『 y 』来进行复制,当你按下 y 之后,反白的区块就会消失不见啰!

  5. 最后,将光标移动到第一行的最右边,并且再用编辑模式向右按两个空格键,回到一般模式后, 再按下『 p 』后,你会发现很有趣!如下图所示:

    将区块的资料贴上后的结果
    图 3.1.3、将区块的资料贴上后的结果

透过上述的功能,你可以复制一个区块,并且是贴在某个『区块的范围』内,而不是以行为单位来处理你的整份文件喔! 鸟哥个人是觉得这玩意儿非常的有帮助啦!至少在进行排列整齐的文本文件中复制/删除区块时,会是一个非常棒的功能!


小标题的图示多档案编辑

假设一个例子,你想要将刚刚我们的 hosts 内的 IP 复制到你的 /etc/hosts 这个档案去, 那么该如何编辑?我们知道在 vi 内可以使用 :r filename 来读入某个档案的内容, 不过,这样毕竟是将整个档案读入啊!如果我只是想要部分内容呢?呵呵!这个时候多档案同时编辑就很有用了。 我们可以使用 vim 后面同时接好几个档案来同时开启喔!相关的按键有:

多档案编辑的按键
:n编辑下一个档案
:N编辑上一个档案
:files列出目前这个 vim 的开启的所有档案


在过去,鸟哥想要将 A 档案内的十条消息『移动』到 B 档案去,通常要开两个 vim 窗口来复制, 偏偏每个 vim 都是独立的,因此并没有办法在 A 档案下达『 nyy 』再跑到 B 档案去『 p 』啦! 在这种情况下最常用的方法就是透过鼠标圈选, 复制后贴上。不过这样一来还是有问题,因为鸟哥超级喜欢使用 [Tab] 按键进行编排对齐动作, 透过鼠标却会将 [Tab] 转成空格键,这样内容就不一样了!此时这个多档案编辑就派上用场了!

现在你可以做一下练习看看说!假设你要将刚刚鸟哥提供的 hosts 内的前四行 IP 数据复制到你的 /etc/hosts 档案内,那可以怎么进行呢?可以这样啊:

  1. 透过『 vim hosts /etc/hosts 』指令来使用一个 vim 开启两个档案;

  2. 在 vim 中先使用『 :files 』察看一下编辑的档案数据有啥?结果如下所示。 至于下图的最后一行显示的是『按下任意键』就会回到 vim 的一般模式中!

    多档案编辑示意图
    图 3.2.1、多档案编辑示意图"


  3. 在第一行输入『 4yy 』复制四行;

  4. 在 vim 的环境下输入『 :n 』会来到第二个编辑的档案,亦即 /etc/hosts 内;

  5. 在 /etc/hosts 下按『 G 』到最后一行,再输入『 p 』贴上;

  6. 按下多次的『 u 』来还原原本的档案数据;

  7. 最终按下『 :q 』来离开 vim 的多档案编辑吧!

看到了吧?利用多档案编辑的功能,可以让你很快速的就将需要的资料复制到正确的档案内。 当然啰,这个功能也可以利用窗口接口来达到,那就是底下要提到的多窗口功能。


小标题的图示多窗口功能

在开始这个小节前,先来想象两个情况:

  • 当我有一个档案非常的大,我查阅到后面的数据时,想要『对照』前面的数据, 是否需要使用 [ctrl]+f 与 [ctrl]+b (或 pageup, pagedown 功能键) 来跑前跑后查阅?

  • 我有两个需要对照着看的档案,不想使用前一小节提到的多档案编辑功能;

在一般窗口接口下的编辑软件大多有『分割窗口』或者是『冻结窗口』的功能来将一个档案分割成多个窗口的展现, 那么 vim 能不能达到这个功能啊?可以啊!但是如何分割窗口并放入档案呢? 很简单啊!在指令列模式输入『:sp {filename}』即可!那个 filename 可有可无, 如果想要在新窗口启动另一个档案,就加入档名,否则仅输入 :sp 时, 出现的则是同一个档案在两个窗口间

让我们来测试一下,你先使用『 vim /etc/man.config 』打开这个档案,然后『 1G 』去到第一行,之后输入『 :sp 』 再次的打开这个档案一次,然后再输入『 G 』,结果会变成底下这样喔:

窗口分割的示意图
图 3.3.1、窗口分割的示意图

万一你再输入『 :sp /etc/hosts 』时,就会变成下图这样喔:

窗口分割的示意图
图 3.3.2、窗口分割的示意图

怎样?帅吧!两个档案同时在一个屏幕上面显示,你还可以利用『[ctrl]+w+↑』及『[ctrl]+w+↓』 在两个窗口之间移动呢!这样的话,复制啊、查阅啊等等的,就变的很简单啰~ 分割窗口的相关指令功能有很多,不过你只要记得这几个就好了:

多窗口情况下的按键功能
:sp [filename]开启一个新窗口,如果有加 filename, 表示在新窗口开启一个新档案,否则表示两个窗口为同一个档案内容(同步显示)。
[ctrl]+w+ j
[ctrl]+w+↓
按键的按法是:先按下 [ctrl] 不放, 再按下 w 后放开所有的按键,然后再按下 j (或向下箭头键),则光标可移动到下方的窗口。
[ctrl]+w+ k
[ctrl]+w+↑
同上,不过光标移动到上面的窗口。
[ctrl]+w+ q其实就是 :q 结束离开啦! 举例来说,如果我想要结束下方的窗口,那么利用 [ctrl]+w+↓ 移动到下方窗口后,按下 :q 即可离开, 也可以按下 [ctrl]+w+q 啊!

鸟哥第一次玩 vim 的分割窗口时,真是很高兴啊!竟然有这种功能!太棒了! ^_^


小标题的图示vim 环境设定与记录: ~/.vimrc, ~/.viminfo

有没有发现,如果我们以 vim 软件来搜寻一个档案内部的某个字符串时,这个字符串会被反白, 而下次我们再次以 vim 编辑这个档案时,该搜寻的字符串反白情况还是存在呢!甚至于在编辑其他档案时, 如果其他档案内也存在这个字符串,哇!竟然还是主动反白耶!真神奇! 另外,当我们重复编辑同一个档案时,当第二次进入该档案时, 游标竟然就在上次离开的那一行上头呢!真是好方便啊~但是,怎么会这样呢?

这是因为我们的 vim 会主动的将你曾经做过的行为登录下来,好让你下次可以轻松的作业啊! 那个记录动作的档案就是: ~/.viminfo !如果你曾经使用过 vim, 那你的家目录应该会存在这个档案才对。这个档案是自动产生的, 你不必自行建立。而你在 vim 里头所做过的动作,就可以在这个档案内部查询到啰~ ^_^

此外,每个 distributions 对 vim 的预设环境都不太相同,举例来说,某些版本在搜寻到关键词时并不会高亮度反白, 有些版本则会主动的帮你进行缩排的行为。但这些其实都可以自行设定的,那就是 vim 的环境设定啰~ vim 的环境设定参数有很多,如果你想要知道目前的设定值,可以在一般模式时输入『 :set all 』 来查阅,不过.....设定项目实在太多了~所以,鸟哥在这里仅列出一些平时比较常用的一些简单的设定值, 提供给你参考啊。

Tips:
所谓的缩排,就是当你按下 Enter 编辑新的一行时,光标不会在行首,而是在与上一行的第一个非空格符处对齐!
鸟哥的图示
vim 的环境设定参数
:set nu
:set nonu
就是设定与取消行号啊!
:set hlsearch
:set nohlsearch
hlsearch 就是 high light search(高亮度搜寻)。 这个就是设定是否将搜寻的字符串反白的设定值。默认值是 hlsearch
:set autoindent
:set noautoindent
是否自动缩排?autoindent 就是自动缩排。
:set backup是否自动储存备份档?一般是 nobackup 的, 如果设定 backup 的话,那么当你更动任何一个档案时,则源文件会被另存成一个档名为 filename~ 的档案。 举例来说,我们编辑 hosts ,设定 :set backup ,那么当更动 hosts 时,在同目录下,就会产生 hosts~ 文件名的档案,记录原始的 hosts 档案内容
:set ruler还记得我们提到的右下角的一些状态栏说明吗? 这个 ruler 就是在显示或不显示该设定值的啦!
:set showmode这个则是,是否要显示 --INSERT-- 之类的字眼在左下角的状态栏。
:set backspace=(012)一般来说, 如果我们按下 i 进入编辑模式后,可以利用退格键 (backspace) 来删除任意字符的。 但是,某些 distribution 则不许如此。此时,我们就可以透过 backspace 来设定啰~ 当 backspace 为 2 时,就是可以删除任意值;0 或 1 时,仅可删除刚刚输入的字符, 而无法删除原本就已经存在的文字了!
:set all显示目前所有的环境参数设定值。
:set显示与系统默认值不同的设定参数, 一般来说就是你有自行变动过的设定参数啦!
:syntax on
:syntax off
是否依据程序相关语法显示不同颜色? 举例来说,在编辑一个纯文本档时,如果开头是以 # 开始,那么该行就会变成蓝色。 如果你懂得写程序,那么这个 :syntax on 还会主动的帮你除错呢!但是, 如果你仅是编写纯文本档案,要避免颜色对你的屏幕产生的干扰,则可以取消这个设定 。
:set bg=dark
:set bg=light
可用以显示不同的颜色色调,预设是『 light 』。如果你常常发现批注的字体深蓝色实在很不容易看, 那么这里可以设定为 dark 喔!试看看,会有不同的样式呢!

总之,这些设定值很有用处的啦!但是......我是否每次使用 vim 都要重新设定一次各个参数值? 这不太合理吧?没错啊!所以,我们可以透过配置文件来直接规定我们习惯的 vim 操作环境呢! 整体 vim 的设定值一般是放置在 /etc/vimrc 这个档案,不过,不建议你修改他! 你可以修改 ~/.vimrc 这个档案 (预设不存在,请你自行手动建立!),将你所希望的设定值写入! 举例来说,可以是这样的一个档案:

[root@www ~]# vim ~/.vimrc
"这个档案的双引号 (") 是批注
set hlsearch            "高亮度反白
set backspace=2         "可随时用退格键删除
set autoindent          "自动缩排
set ruler               "可显示最后一行的状态
set showmode            "左下角那一行的状态
set nu                  "可以在每一行的最前面显示行号啦!
set bg=dark             "显示不同的底色色调
syntax on               "进行语法检验,颜色显示。

在这个档案中,使用『 set hlsearch 』或『 :set hlsearch 』,亦即最前面有没有冒号『 : 』效果都是一样的! 至于双引号则是批注符号!不要用错批注符号,否则每次使用 vim 时都会发生警告讯息喔! 建立好这个档案后,当你下次重新以 vim 编辑某个档案时,该档案的预设环境设定就是上头写的啰~ 这样,是否很方便你的操作啊!多多利用 vim 的环境设定功能呢!^_^


小标题的图示vim 常用指令示意图

为了方便大家查询在不同的模式下可以使用的 vim 指令,鸟哥查询了一些 vim 与 Linux 教育训练手册, 发现底下这张图非常值得大家参考!可以更快速有效的查询到需要的功能喔!看看吧!

vim 常用指令示意图
图 3.5.1 、 vim 常用指令示意图

大标题的图示其他 vim 使用注意事项

vim 其实不是那么好学,虽然他的功能确实非常强大!所以底下我们还有一些需要注意的地方要来跟大家分享喔!


小标题的图示中文编码的问题

很多朋友常常哀嚎,说他们的 vim 里面怎么无法显示正常的中文啊?其实这很有可能是因为编码的问题! 因为中文编码有 big5 与 utf8 两种,如果你的档案是使用 big5 编码制作的,但在 vim 的终端接口中你使用的是万国码(utf8), 由于编码的不同,你的中文档案内容当然就是一堆乱码了!怎么办?这时你得要考虑许多东西啦!有这些:

  1. 你的 Linux 系统默认支持的语系数据:这与 /etc/sysconfig/i18n 有关;

  2. 你的终端界面 (bash) 的语系: 这与 LANG 这个变数有关;

  3. 你的档案原本的编码;

  4. 开启终端机的软件,例如在 GNOME 底下的窗口接口。

事实上最重要的是上头的第三与第四点,只要这两点的编码一致,你就能够正确的看到与编辑你的中文档案。 否则就会看到一堆乱码啦!

一般来说,中文编码使用 big5 时,在写入某些数据库系统中,在『许、盖、功』这些字体上面会发生错误! 所以近期以来大多希望大家能够使用万国码 utf8 来进行中文编码!但是在 Windows XP 上的软件常常默认使用 big5 的编码, 包括鸟哥由于沿用以前的文件数据文件,也大多使用 big5 的编码。此时就得要注意上述的这些咚咚啰。

在 Linux 本机前的 tty1~tty6 原本默认就不支持中文编码,所以不用考虑这个问题!因为你一定会看到乱码!呵呵! 现在鸟哥假设俺的文件档案内编码为 big5 时,而且我的环境是使用 Linux 的 GNOME ,启动的终端接口为 GNOME-terminal 软件, 那鸟哥通常是这样来修正语系编码的行为:

[root@www ~]# LANG=zh_TW.big5

然后在终端接口工具栏的『终端机』-->『设定字符编码』 -->『中文 (正体) (BIG5)』项目点选一下, 如果一切都没有问题了,再用 vim 去开启那个 big5 编码的档案,就没有问题了!以上!报告完毕!


小标题的图示DOS 与 Linux 的断行字符

我们在第七章里面谈到 cat 这个指令时,曾经提到过 DOS 与 Linux 断行字符的不同。 而我们也可以利用 cat -A 来观察以 DOS (Windows 系统) 建立的档案的特殊格式, 也可以发现在 DOS 使用的断行字符为 ^M$ ,我们称为 CR 与 LF 两个符号。 而在 Linux 底下,则是仅有 LF ($) 这个断行符号。这个断行符号对于 Linux 的影响很大喔! 为什么呢?

我们说过,在 Linux 底下的指令在开始执行时,他的判断依据是 『Enter』,而 Linux 的 Enter 为 LF 符号, 不过,由于 DOS 的断行符号是 CRLF ,也就是多了一个 ^M 的符号出来, 在这样的情况下,如果是一个 shell script 的程序档案,呵呵~将可能造成『程序无法执行』的状态~ 因为他会误判程序所下达的指令内容啊!这很伤脑筋吧!

那怎么办啊?很简单啊,将格式转换成为 Linux 即可啊!『废话』,这当然大家都知道,但是, 要以 vi 进入该档案,然后一个一个删除每一行的 CR 吗?当然没有这么没人性啦! 我们可以透过简单的指令来进行格式的转换啊!

[root@www ~]# dos2unix [-kn] file [newfile]
[root@www ~]# unix2dos [-kn] file [newfile]
选项与参数:
-k  :保留该档案原本的 mtime 时间格式 (不更新档案上次内容经过修订的时间)
-n  :保留原本的旧档,将转换后的内容输出到新档案,如: dos2unix -n old new

范例一:将刚刚上述练习的 /tmp/vitest/man.config 修改成为 dos 断行
[root@www ~]# cd /tmp/vitest
[root@www vitest]# cp -a /etc/man.config .
[root@www vitest]# ll man.config
-rw-r--r-- 1 root root 4617 Jan  6  2007 man.config
[root@www vitest]# unix2dos -k man.config
unix2dos: converting file man.config to DOS format ...
# 屏幕会显示上述的讯息,说明断行转为 DOS 格式了!
[root@www vitest]# ll man.config
-rw-r--r-- 1 root root 4758 Jan  6  2007 man.config
# 断行字符多了 ^M ,所以容量增加了!

范例二:将上述的 man.config 转成 man.config.linux 的 Linux 断行字符
[root@www vitest]# dos2unix -k -n man.config man.config.linux
dos2unix: converting file man.config to file man.config.linux in UNIX format ...
[root@www vitest]# ll man.config*
-rw-r--r-- 1 root root 4758 Jan  6  2007 man.config
-rw------- 1 root root 4617 Jan  6  2007 man.config.linux

因为断行字符以及 DOS 与 Linux 操作系统底下一些字符的定义不同,因此, 不建议你在 Windows 系统当中将档案编辑好之后,才上传到 Linux 系统,会容易发生错误问题。 而且,如果你在不同的系统之间复制一些纯文本档案时,千万记得要使用 unix2dos 或 dos2unix 来转换一下断行格式啊!


小标题的图示语系编码转换

很多朋友都会有的问题,就是想要将语系编码进行转换啦!举例来说,想要将 big5 编码转成 utf8 。 这个时候怎么办?难不成要每个档案打开会转存成 utf8 吗?不需要这样做啦!使用 iconv 这个指令即可! 鸟哥将之前的 vi 章节做成 big5 编码的档案,你可以照底下的连结来下载先:

在终端机的环境下你可以使用『 wget 网址』来下载上述的档案喔!鸟哥将他下载在 /tmp/vitest 目录下。 接下来让我们来使用 iconv 这个指令来玩一玩编码转换吧!

[root@www ~]# iconv --list
[root@www ~]# iconv -f 原本编码 -t 新编码 filename [-o newfile]
选项与参数:
--list :列出 iconv 支持的语系数据
-f     :from ,亦即来源之意,后接原本的编码格式;
-t     :to ,亦即后来的新编码要是什么格式;
-o file:如果要保留原本的档案,那么使用 -o 新档名,可以建立新编码档案。

范例一:将 /tmp/vitest/vi.big5 转成 utf8 编码吧!
[root@www ~]# cd /tmp/vitest
[root@www vitest]# iconv -f big5 -t utf8 vi.big5 -o vi.utf8
[root@www vitest]# file vi*
vi.big5: ISO-8859 text, with CRLF line terminators
vi.utf8: UTF-8 Unicode text, with CRLF line terminators
# 是吧!有明显的不同吧! ^_^

这指令支持的语系非常之多,除了正体中文的 big5, utf8 编码之外,也支持简体中文的 gb2312 , 所以对岸的朋友可以简单的将鸟站的网页数据下载后,利用这个指令来转成简体,就能够轻松的读取文件数据啰! 不过,不要将转成简体的档案又上传成为您自己的网页啊!这明明是鸟哥写的不是吗? ^_^

不过如果是要将正体中文的 utf8 转成简体中文的 utf8 编码时,那就得费些功夫了! 举例来说,如果要将刚刚那个 vi.utf8 转成简体的 utf8 时,可以这样做:

[root@www vitest]# iconv -f utf8 -t big5 vi.utf8 | \
> iconv -f big5 -t gb2312 | iconv -f gb2312 -t utf8 -o vi.gb.utf8

大标题的图示重点回顾

  • Linux 底下的配置文件多为文本文件,故使用 vim 即可进行设定编辑;

  • vim 可视为程序编辑器,可用以编辑 shell script, 配置文件等,避免打错字;

  • vi 为所有 unix like 的操作系统都会存在的编辑器,且执行速度快速;

  • vi 有三种模式,一般模式可变换到编辑与指令列模式,但编辑模式与指令列模式不能互换;

  • 常用的按键有i, [Esc], :wq 等;

  • vi 的画面大略可分为两部份,(1)上半部的本文与(2)最后一行的状态+指令列模式;

  • 数字是有意义的,用来说明重复进行几次动作的意思,如 5yy 为复制 5 行之意;

  • 光标的移动中,大写的 G 经常使用,尤其是 1G, G 移动到文章的头/尾功能!

  • vi 的取代功能也很棒! :n1,n2s/old/new/g 要特别注意学习起来;

  • 小数点『 . 』为重复进行前一次动作,也是经常使用的按键功能!

  • 进入编辑模式几乎只要记住: i, o, R 三个按钮即可!尤其是新增一行的 o 与取代的 R

  • vim 会主动的建立 swap 暂存档,所以不要随意断线!

  • 如果在文章内有对齐的区块,可以使用 [ctrl]-v 进行复制/贴上/删除的行为

  • 使用 :sp 功能可以分割窗口

  • vim 的环境设定可以写入在 ~/.vimrc 档案中;

  • 可以使用 iconv 进行档案语系编码的转换

  • 使用 dos2unix 及 unix2dos 可以变更档案每一行的行尾断行字符。


大标题的图示本章练习
(要看答案请将鼠标移动到『答:』底下的空白处,按下左键圈选空白处即可察看)实作题部分:

  • 在第八章的情境模拟题二的第五点,编写 /etc/fstab 时,当时使用 nano 这个指令, 请尝试使用 vim 去编辑 /etc/fstab ,并且将第八章新增的那一行的 defatuls 改成 default ,会出现什么状态? 离开前请务必要修订成原本正确的信息。此外,如果将该行批注 (最前面加 #),你会发现字体颜色也有变化喔!

  • 尝试在你的系统中,你惯常使用的那个账号的家目录下,将本章介绍的 vimrc 内容进行一些常用设定,包括:

    • 设定搜寻高亮度反白

    • 设定语法检验启动

    • 设定默认启动行号显示

    • 设定有两行状态栏 (一行状态+一行指令列) :set laststatus=2


简答题部分:

  • 我用 vi 开启某个档案后,要在第 34 行向右移动 15 个字符,应该在一般模式中下达什么指令?(1)先按下 34G 到第 34 行;(2)再按下 [ 15 + 向右键 ],或 [ 15l ] 亦可!

  • 在 vi 开启的档案中,如何去到该档案的页首或页尾?去页首按下 1G 或 gg ;去页尾按下 G 即可

  • 在 vi 开启的档案中,如何在光标所在行中,移动到行头及行尾?移动到行头,按 0 ,移动到行尾按 $ 即可!

  • vi 的一般模式情况下,按下『 r 』有什么功能?取代光标所在的那个字符

  • 在 vi 的环境中,如何将目前正在编辑的档案另存新档名为 newfilename?:w newfilename

  • 在 linux 底下最常使用的文书编辑器为 vi ,请问如何进入编辑模式?在一般模式底下输入: i, I, a, A 为在本行当中输入新字符;(出现 –Insert- )
    在一般模式当中输入: o, O 为在一个新的一行输入新字符;
    在一般模式当中输入: r, R 为取代字符!(左下角出现 –Replace-)

  • 在 vi 软件中,如何由编辑模式跳回一般模式?可以按下[Esc]

  • 在 vi 环境中,若上下左右键无法使用时,请问如何在一般模式移动光标?[h, j, k, l]分别代表[左、下、上、右]

  • 在 vi 的一般模式中,如何删除一行、n行;如何删除一个字符?分别为 dd, ndd, x 或 X (dG 及 d1G 分别表示删除到页首及页尾)

  • 在 vi 的一般模式中,如何复制一行、n行并加以贴上?分别为 yy, nyy, p 或 P

  • 在 vi 的一般模式中如何搜寻 string 这个字符串??string (往前搜寻)
    /string (往后搜寻)

  • 在 vi 的一般模式中,如何取代 word1 成为 word2,而若需要使用者确认机制,又该如何?:1,$s/word1/word2/g 或
    :1,$s/word1/word2/gc (需要使用者确认)

  • 在 vi 目前的编辑档案中,在一般模式下,如何读取一个档案 filename 进来目前这个档案?:r filename

  • 在 vi 的一般模式中,如何存盘、离开、存档后离开、强制存档后离开?:w; :q: :wq; :wq!

  • 在 vi 底下作了很多的编辑动作之后,却想还原成原来的档案内容,应该怎么进行?直接按下 :e! 即可恢复成档案的原始状态!

  • 我在 vi 这个程序当中,不想离开 vi ,但是想执行 ls /home 这个指令,vi 有什么额外的功能可以达到这个目的:事实上,可以使用[ :! ls /home ]不过,如果你学过后面的章节之后,你会发现,执行[ ctrl + z ]亦可暂时退出 vi 让你在指令列模


来自 http://cn.linux.vbird.org/linux_basic/0310vi.php


vim 的取代置換功能「s」

vim-logo.gif在 前面我們所談的那些可以說是比較基本的東西,但是對於一份文件來說,光有前面所介紹的游標移動、刪除等等功能是不足夠的。面對一份文件我們通常會因為某些 緣故而使得我們必須去修改當中固定出現的字串樣式(pattern)成我們想要的樣子。最常遇到的就像中文文件的標點符號問題,或是 un*ix 和 DOS 文件格式之間轉換常會有個 ^M 結尾會讓人覺得很討厭,又或是我們想要把一份 HTML 格式的文件去除掉它的 HTML tag。
對於這些事情來說,拿中文標點符號置換這個很多編輯器都做得到,簡單地說如果想更動的 pattern 是一個固定的字串,那對於一般編輯器來說都不會太困難,但是對於具有固定格式,但字串內容卻不一定的該怎麼辦?就像要去掉 HTML 格式中的所有 HTML tag?這就是 vim 開始大顯身手的地方了。

今天我們不談別的其他指令,就光談在 vim 中的「 :s 」指令。小寫 :s 表示置換(substitute)的意思,不過通常你用 vim 下 :h :s 指令的時候會看到這樣的畫面:
vim help for :s substitute
其實這一串東西就是在說 :s 這個指令的格式要怎麼下。
Range:
一般對於整份文件都要作置換的話,我都會下像這樣的指令:
:%s/, /,/g
最前面的「%」就是表示全域,也就是現在編輯的這一份文件都要作後面取代的工作。那這個指令就是說要把半形的逗點「,」變成全形「,」。那後面 「g」又代表什麼意思呢?在 g 這個欄位上的東西是用來表示對目前這個指令所做的額外的選項。就拿 g 來說, g 代表在文件中每一個出現的半形逗點都要置換成全形。或許你會問剛剛不是已經用「%」表示全域了嗎,怎麼又要用 g 呢?我應該這樣說,「%」用來表示從文件的第一行到最後一行。但是在比對(match)的時候,如果不加「g」這個額外選項的話, vim 只會把每一行比對到的第一個作取代,同行其他也 match 到的就不管了。所以用「g」表示每一行中每一個比對到的都要置換。
所以同理,如果你要把那些因為 un*ix 和 DOS 之間格式不合所造成的^M消掉的話,也只需要下成這樣就可以了:
:%s/^M//g
可是有時候你想要作置換的只是文件中的某一部份的話怎麼辦?不要緊,還記得選取模式嗎?在你想置換部分的開頭按下大寫「V」然後用移動游標(我們之前講的 vim 移動游標的方法在選取模式下都可以用)到你想要的位置之後按「:」就會跳到輸入指令的狀態,如下圖最下面那行看到的一樣:
vim selection for substitute
當然你很確定行數,你也可以這樣下:
:1,300s/vim/VIM/g
或者是如果你很確定要從現在游標所在行之後的所有行都置換,可以下成:
:.,$s/vim/VIM/g
冒號一開頭的那一小點「 . 」就代表游標現在所在行,「$」則用來表示最後一行。
或許聰明的你已經想到怎麼樣可以從現在所在行之前的都要置換了,
:.,1s/vim/VIM/g
不過當你這樣打的時候, vim 會跳出來一個訊息:
Backwards range given, OK to swap (y/n)?
這就是說你給了一個起始行數比結束行數還要大的範圍。這是因為 vim 所定的範圍都是從小到大,如果你要從大到小不是不行,只是多個訊息確認你沒有打錯罷了。
Pattern:
像前面說,固定字串像把半形逗點換成全形逗點這都還容易,如果只是格式固定,但是字串內容會變動怎麼辦?就像去 HTML tag 的時候就很麻煩。
還記得我們在淺談vim那時候提過的指令嗎?
  • :%s/\n/^V/g

  • :%s/《[^<》]*>//g

  • :%s/^V/\n/g

在中間的那一些 [^<>]*看起來像外星文字的,就是 pattern 比對的主力。事實上關於這些東西,我們在談 vim 的 search 搜尋功能的時候也有提到過一些。所以我們今天就來補一些上次沒有講到的東西。
假如我現在有一筆人名、電話的資料,由於是隨手記的,上面自然就是沒有排序過。那沒排序過對於想要在上面找資料的人就很麻煩。萬一人名記不太清楚, 電話號碼也記得七七八八,雖然說有 vim 方便的 search 功能,但總是感覺不足。(當然這只是假設情況,因為實際上可能大家都已經建立某種方便搜尋的資料庫了)
我們先假設人名、電話的對應長成這樣:
趙大明  1235478982
錢小名  1223450012
王孫李  5938123812
周渚衛  1384914191
沈以情  2345934981
那我可不可以讓它變成這樣子?
1235478982   趙大明
1223450012   錢小名
5938123812   王孫李
1384914191   周渚衛
2345934981   沈以情
我可以下這樣的指令完成這個工作:
:%s/\([^0-9]\{1,}\)\([0-9]\{1,}\)/\2 \1/g
前面橘色的部分 \([^0-9]\{1,}\) 用 \( \) 括起來的,表示這是一個的單元,之後就可以依照它出現的順序而使用 \1 \2,… ,來代表它。所以我們可以看到 [^0-9] 就表示非數字的部分,後面的\{1,} 如果你還記得的話,就是代表出現至少一次。不過這個時候DK長輩會跟你說用 vim 要文明一點,要用「\+」來代表至少出現一次。看個人喜好了,如果你願意多記一些代替的符號就多記一點,你可以用 :h /multi 看到更多這些替代符號。
所以把 pattern 用 \( \) 分開之後,我們就可以用 \1,\2 來把他們交換位置。
不過你可能會說這樣還沒排序啊。我們可以用選取模式把整份文件選起來,或是你懶得用上下左右改變,你可以用 ggVG (gg 跳到第一行之後,用大寫V進入選擇模式,以大寫G跳到最後一行)把整份文件選起來之後按 :!sort,這時候在你 vim 視窗的最底下就會變成這樣:
:’《,’》!sort
下去就會變成根據每一行的最前頭作排序的結果。所以結果就會變成:
1223450012   錢小名
1235478982   趙大明
1384914191   周渚衛
2345934981   沈以情
5938123812   王孫李
很簡單吧? :p
如果你願意配合暫存器( registers )的話,有時候也能省點力氣。在講 vim search 的時候,我們曾經提了用 搭配數字鍵 0 來把暫存器 0 的東西叫出來。同樣的,我們不管用 / 或是 ? 等等輸入字串的時候,事實上都已經把要搜尋的字串寫入「/」的暫存器裡面,所以當我們只是想置換的字串就是搜尋的字串的話,我們可以這樣做:+r>
:%s/+r>/用來取代的字串/g
表示在按 之後按下「/」這個按鍵。這樣就可以把搜尋的字串叫出來並用之於置換指令上。+r>
額外指令
我們剛剛在前面談到可以作像「g」這些的額外控制。那有哪些控制可以作呢?
比方說在我們作置換的時候,由於 vim 預設是有大小寫的差別,如果你不管大小寫都要取代的話,那可以用「i」這個額外參數來控制 vim 取代的時候就不管大小寫都會作取代的工作。
不過有時候,我們可能不太能確定是不是整份文件中的每一個都要取代,那我們就可以加「c」 confirm 確認參數來控制,那使用上也很容易。 vim 會在比對到之後問
(y/n/a/q/l/^E/^Y)?
  • y 是代表執行目前的取代。

  • n 是跳過。

  • a 代表 always ,就是從目前以後的取代都會執行。

  • 則是不要作取代,並且離開詢問要不要取代的狀態,並回到指令模式或原來的模式下。

  • l 則是 last 的意思,就是目前這個取代執行後就離開詢問的取代模式,回到指令模式或原來的模式下。

  • ^E 表示往前一頁。

  • ^Y 表示往後一頁。

對於 :s 的用法到這裡我們就已經把常用的幾個方式都說完了。礙於篇幅,我也決定先寫到這裡就好,不然寫一大篇,可能連有興趣進來瞭解 vim 的人光看到就害怕了,怎麼還有辦法體會 vim 的好呢?其實關於 :s 的用法,還有 pattern 還有很多的方式在本篇中沒有提到,你可以在 vim 中用 :h :s 看到更多詳細的資料。今天就來 vim 吧!

from http://greenisland.csie.nctu.edu.tw/wp/2005/09/02/302/
-----------------------------------------------------------------------------------------------------------------------------------------
vi/vim 中可以使用 :s 命令來替換字串。該命令有很多種不同細節使用方法,可以實現複雜的功能,記錄幾種在此,方便以後查詢。
:s/vivian/sky/ 替換當前行第一個 vivian 為 sky
:s/vivian/sky/g 替換當前行所有 vivian 為 sky
:n,$s/vivian/sky/ 替換第 n 行開始到最後一行中每一行的第一個 vivian 為 sky
:n,$s/vivian/sky/g 替換第 n 行開始到最後一行中每一行所有 vivian 為 sky
n 為數字,若 n 為 .,表示從當前行開始到最後一行
:%s/vivian/sky/(等同於 :g/vivian/s//sky/) 替換每一行的第一個 vivian 為 sky
:%s/vivian/sky/g(等同於 :g/vivian/s//sky/g) 替換每一行中所有 vivian 為 sky
可以使用 # 作為分隔符號,此時中間出現的 / 不會作為分隔符號
:s#vivian/#sky/# 替換當前行第一個 vivian/ 為 sky/
:%s+/oradata/apras/+/user01/apras1+ (使用+ 來 替換 / ): /oradata/apras/替換成/user01/apras1/
1.:s/vivian/sky/ 替換當前行第一個 vivian 為 sky
:s/vivian/sky/g 替換當前行所有 vivian 為 sky
2. :n,$s/vivian/sky/ 替換第 n 行開始到最後一行中每一行的第一個 vivian 為 sky
:n,$s/vivian/sky/g 替換第 n 行開始到最後一行中每一行所有 vivian 為 sky
(n 為數字,若 n 為 .,表示從當前行開始到最後一行)
3. :%s/vivian/sky/(等同於 :g/vivian/s//sky/) 替換每一行的第一個 vivian 為 sky
:%s/vivian/sky/g(等同於 :g/vivian/s//sky/g) 替換每一行中所有 vivian 為 sky
4. 可以使用 # 作為分隔符號,此時中間出現的 / 不會作為分隔符號
:s#vivian/#sky/# 替換當前行第一個 vivian/ 為 sky/
5. 刪除文本中的^M
問題描述:對於換行,window下用回車換行(0A0D)來表示,linux下是回車(0A)來表示。這樣,將window上的檔拷到unix上用時,總會有個^M.請寫個用在unix下的過濾windows文件的分行符號(0D)的shell或c程式。
。 使用命令:cat filename1 | tr -d “^V^M” > newfile;
。 使用命令:sed -e “s/^V^M//” filename > outputfilename.需要注意的是在1、2兩種方法中,^V和^M指的是Ctrl+V和Ctrl+M.你必須要手工進行輸入,而不是粘貼。
。 在vi中處理:首先使用vi打開檔,然後按ESC鍵,接著輸入命令:%s/^V^M//.
。 :%s/^M$//g
如果上述方法無用,則正確的解決辦法是: [Page]
。 tr -d \"\\r\" < src >dest
。 tr -d \"\\015\" dest
。 strings A>B
6. 替換確認
我們有很多時候會需要某個字元(串)在文章中某些位置出現時被替換,而其它位置不被替換的有選擇的操作,這就需要使用者來進行確認,vi的查找替換同樣支持
例如
:s/vivian/sky/g 替換當前行所有 vivian 為 sky
在命令後面加上一個字母c就可以實現,即:s/vivian/sky/gc
顧名思意,c是confirm的縮寫
7. 其它
利用 :s 命令可以實現字串的替換。具體的用法包括:
:s/str1/str2/ 用字串 str2 替換行中首次出現的字串 str1
:s/str1/str2/g 用字串 str2 替換行中所有出現的字串 str1
:。,$ s/str1/str2/g 用字串 str2 替換正文當前行到末尾所有出現的字串 str1
:1,$ s/str1/str2/g 用字串 str2 替換正文中所有出現的字串 str1
:g/str1/s//str2/g 功能同上
從上述替換命令可以看到:g 放在命令末尾,表示對搜索字串的每次出現進行替換;不加 g,表示只對搜索
字串的首次出現進行替換;g 放在命令開頭,表示對正文中所有包含搜索字串的行進行替換操作

3 則留言:

  1. 超讚的 没看人家寫 vi 的 search replace 寫得這麼棒的喔 !

    回覆
  2. 實用 3Q!!學了幾招

    回覆
  3. 謝謝,介紹得很仔細,很受用,感恩

    回覆



来自  https://chunchaichang.blogspot.com/2010/08/vim-s.html


Linux vim command

Updated: 03/13/2021 by Computer Hope

vim command

On Unix-like operating systems, vim, which stands for "Vi Improved", is a text editor. It can be used for editing any kind of text and is especially suited for editing computer programs.

Description

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 vim executable with one of the following names, it will behave in the following fashion:

command namebehavior
vim"Normal" execution. Everything is default.
exStart in Ex mode. Go to Normal mode with the ":vi" command. Can also be done with the "-eargument.
viewStart in read-only mode. You will be protected from writing the files. Can also be done with the "-R" argument.
gvimgviewThe GUI version (if installed). Starts a new window. Can also be done with the "-g" argument.
evimeviewRuns GUI vim in "easy mode". This command is a simplified mode of vim operation, which is a lot like a normal text editor. This is the same as running vim with the "-y" argument.
rvimrviewrgvimrgviewLike the above, but running in "restricted" mode. It will not be possible to start shell commands from within vim, or to suspend vim. This is the same as specifying the "-Z" argument.

Syntax

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 within <v> vim, 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 vimrc file. You can use up to 10 of these commands, independently from "-c" commands.
-AIf 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.
-bBinary mode. A few options will be set that makes it possible to edit a binary or executable file.
-CCompatible mode. Sets the 'compatible' option. This will make vim behave mostly like Vi, even though a .vimrc file exists.
-dStart in diff mode. There should be two, three or four file name arguments. vim will 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).
-DDebugging mode. Go to debugging mode when executing the first command from a script.
-eStart vim in ex mode, just like if the executable is called "ex".
-EStart vim in improved ex mode, just like if the executable was called "exim".
-fForeground 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.
--noforkForeground mode. For the GUI version, vim will not fork and detach from the shell it was started in.
-FIf 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 vim aborts.
-gIf 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.
-hGive a bit of help about the command line arguments and options. After this vim exits.
-HIf 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".
-LSame as -r.
-lLisp mode. Sets the 'lisp' and 'showmatch' options on.
-mModifying files is disabled. Resets the 'write' option. You can still modify the buffer, but writing a file is not possible.
-MModifications 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.
-NNo-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.
-nNo 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".
-nbBecome 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.
-RRead-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 -R option also implies the -n option (see below). The 'readonly' option can be reset with ":set noro". See ":help 'readonly'".
-rList 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".
-sSilent 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.
-vStart 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.
-xUse encryption when writing files. Will prompt for a crypt key.
-XDon't connect to the X server. Shortens startup time in a terminal, but the window title and clipboard will not be used.
-yStart vim in easy mode, just like the executable was called "evim" or "eview". Makes vim behave like a click-and-type editor.
-ZRestricted 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-widGTK GUI only: Echo the Window ID on standard output.
--helpGive a help message and exit, just like "-h".
--literalTake file name arguments literally, do not expand wildcards. This has no effect on Unix where the shell expands wildcards.
--nopluginSkip loading plugins. Implied by -u NONE.
--remoteConnect 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-silentAs --remote, but without the warning when no server is found.
--remote-waitAs --remote, but vim does not exit until the files have been edited.
--remote-wait-silentAs --remote-wait, but without the warning when no server is found.
--serverlistList 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.
--versionPrint 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 <Tab> 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 <Enter> after the word text to start the new line). Finally you press the <Esc> 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 Esc 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 using these keys:

hleft
jdown
kup
lright

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 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 do it hundreds of times an hour, this can take a significant amount of time. Also, there are keyboards that do not have arrow keys or 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 to use them. Use the "i" command to insert more lines of text. Then use the hjkl keys to move around and insert a word. Don't forget to press Esc 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

<Esc>

This begins an insert (the i), inserts the words "Here is", and then exits insert mode (<Esc>). 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 <Esc> 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 <Esc> 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!!!<Esc>". Another way to do this is to use the command "3a!<Esc>". 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 q command, 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", vim would 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:

This is a line with example text 
                    _<---b
          _<--------2b 
        _<b 
     _<-b 
_<---b 

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 text 
   <-   <--- ----->   ---->
   ge    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 <End> 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 <Home> 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 <Esc>. So "f<Esc>" is an aborted forward search and doesn't do anything. <Esc> cancels most operations, not just searches.

Matching a parenthesis

When writing a program you often end up with nested <v>()</v> 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 vim for 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, HM, 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 <BS>) to make corrections. Use the <Left> and <Right> cursor keys when necessary. Pressing <Enter> 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 <Enter>. If you press <Up> (the cursor key), vim puts "/three" on the command line. Pressing <Enter> at this point searches for three. If you do not press <Enter>, but press <Up> instead, vim changes the prompt to "/two". Another press of <Up> moves you to "/one".

You can also use the <Down> 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 <Up>. With the previous example, you can type "/o<Up>" 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:

/\<the\>

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 <Enter> 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<Esc>

"G" moves to the end of the file. "o" starts a new line, where you type the ":set" command. You end insert mode with <Esc>. 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, vim remembers 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-O command 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 <Tab>.

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 (a through 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 
   ------->
 c2wbe<Esc>
To be human

This "c2wbe<Esc>" contains these bits:

cThe change operator.
2wMove two words (they are deleted and Insert mode started).
beInsert this text.
<Esc>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.

More changes

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:
xd1Delete character under the cursor.
XdhDelete character left of the cursor.
Dd$Delete to end of the line.
Cc$Change to end of the line.
sc1Change one character.
SccChange 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 <Esc>

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<Enter>". This deletes one character and inserts a line break. Using a count here only applies to the number of characters deleted: "4r<Enter>" replaces four characters with one line break.

Repeating a change

The "." command is one of the most simple yet powerful commands in vim. It repeats the last change. For instance, suppose you are editing an HTML file and want to delete all the <B> tags. You position the cursor on the first < and delete the <B> with the command "df>". You then go to the < of the next </B> and kill it using the "." command. The "." command executes the last change command (in this case, "df>"). To delete another tag, position the cursor on the < and use the "." command.

  To <B>generate</B> a table of <B>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<Enter>Find the first string "four".
cwfive<Esc>Change the word to "five".
nFind the next "four".
.Repeat the change to "five".
nFind 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 press <Esc> and 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, use Ctrl-V to 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". Press Ctrl-V to 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 using the p command. (The vim name for this is "put").

Take a look at how this works. First you 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

vim makes 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 a vim name 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 of vim (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. In vim itself too.

If you have copied text to the clipboard in another application, you can paste it in vim with 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 your vim has 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 of vim that 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 in vim. 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 causes vim to enter replace mode. In this mode, each character you type replaces the one under the cursor. This continues until you type <Esc>.

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

This is text. 
Rinteresting.<Esc>
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 the <Insert> key.

When you use <BS> (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:

xDelete character under the cursor (short for "dl").
XDelete character before the cursor (short for "dh").
DDelete from cursor to end of line (short for "d$").
dwDelete from cursor to next start of word.
dbDelete from cursor to previous start of word.
diwDelete word under the cursor (excluding white space).
dawDelete word under the cursor (including white space).
dGDelete until the end of the file.
dggDelete 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.
IStart Insert mode after moving the cursor to the first non-blank in the line.
AStart 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 start vim with all your favorite option settings and mappings, you write them in what is called the vimrc file. vim executes the commands in this file when it starts up.

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

:edit $MYVIMRC

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

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

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

The vimrc file can contain all the commands that you type after a colon. The most simple ones are for setting options. For example, if you want vim to always start with the 'incsearch' option on, add this line you your vimrc file:

set incsearch

For this new line to take effect you need to exit vim and start it again. Later you will learn how to do this without exiting vim.

Simple mappings

A mapping enables you to bind a set of vim commands 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 :map command, you can tell vim that the F5 key does this job. The command is as follows:

:map <F5> i{<Esc>ea}<Esc>

When entering this command, you must enter <F5> by typing four characters. Similarly, <Esc> is not entered by pressing the <Esc> key, but by typing five characters. Watch out for this difference.

Let's break this down:

<F5>The F5 function key. This is the trigger key that causes the command to be executed as the key is pressed.
i{<Esc>Insert the { character. The <Esc> key ends Insert mode.
eMove to the end of the word.
a}<Esc>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 press F5.

In this example, the trigger is a single key; it can be any string. But when you use an existing vim command, 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(<Esc>ea)<Esc>
:map \c i{<Esc>ea}<Esc>

You need to type the \ and the p quickly after another, so that vim knows they belong together.

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

Adding a global plugin

vim's functionality can be extended by adding plugins. A plugin is nothing more than a vim script file that is loaded automatically when vim starts. You can add a plugin very easily by dropping it in your plugin directory. {not available when vim was compiled without the |+eval| feature}

There are two types of plugins: global plugins, which are used for all kinds of files; and filetype plugins, which are only used for a specific type of file.

When you start vim, it will automatically load a number of global plugins. You don't have to do anything for this. They add functionality that most people will want to use, but which was implemented as a vim script instead of being compiled in.

You can add a global plugin to add functionality that will always be present when you use vim. There are only two steps for adding a global plugin: get a copy of the plugin, and drop it in the right directory.

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, https://vim.sourceforge.io/.

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:

systemplugin directory
Unix~/.vim/plugin/
PC and OS/2$HOME/vimfiles/plugin or $VIM/vimfiles/plugin
Amigas:vimfiles/plugin
Macintosh$VIM:vimfiles:plugin
macOS X~/.vim/plugin/
RISC-OSChoices: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.

Often used options

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 <BS> key, when used in the first position of a line, to move the cursor to the end of the previous line. And the <Space> key moves from the end of a line to the start of the next one.

To allow the cursor keys <Left> and <Right> to also wrap, use this command:

:set whichwrap=b,s,<,>

This is still only for Normal mode. To let <Left> and <Right> 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 vim directory. 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:

termattributes in a B&W terminal
ctermattributes in a color terminal
ctermfgforeground color in a color terminal
ctermbgbackground color in a color terminal
guiattributes in the GUI
guifgforeground color in the GUI
guibgbackground 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 still creates 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 keeps a copy of the unchanged file under the name "data.txt.orig".

If you make further changes to the file, vim notices 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 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 fl 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 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 remove the protection:

:set modifiable
:set write

Saving as a new file name

A clever way to start editing a new file is 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 writes the file under the given name, and edit that file. Thus the next time you do ":write," it writes "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 jumps 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 is 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.

Options

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 vim equalize 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 causes 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 hMove to the window on the left.
Ctrl-W jMove to the window below.
Ctrl-W kMove to the window above.
Ctrl-W lMove to the window on the right.
Ctrl-W tMove to the TOP window.
Ctrl-W bMove 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 HMove window to the far left.
Ctrl-W JMove window to the bottom.
Ctrl-W LMove 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, vim will 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~" contains the previous version of the file.

Type this command in a shell (not in vim):

vimdiff main.c~ main.c

vim starts, with two windows side by side. You 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 opens, and you can see the text that it contains.

The fold column contains a minus sign for an open fold. If you click this -, the fold closes. 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. vim will 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:

0never
1only when there are split windows (the default)
2always

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 "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 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:

qaStart recording a macro in register a.
^Move to the beginning of the line.
i#include "<Esc>Insert the string #include " at the beginning of the line.
$Move to the end of the line.
a"<Esc>Append the character double quotation mark (") to the end of the line.
jGo to the next line.
qStop 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 causes 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 "@@" uses 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:

GGo to the end of the file.
o<Esc>Create an empty line.
"npPut 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.
0Go to the start of the line.
"ny$Yank the corrected commands into the n register.
ddDelete 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\<Enter\>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:

yYes; make this change.
nNo; skip this match.
aAll; make this change and all remaining ones without further confirmation.
qQuit; don't make any more changes.
lLast; make this change and then quit.
Ctrl-EScroll the text one line up.
Ctrl-YScroll 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 :normal command 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}<Esc>" 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 <Esc> 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.<Esc>

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 <Esc>". 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<Esc>, 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_<Esc>", 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<Esc>" 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)
Umake uppercase (a -> A and A -> A)
umake 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. vim protects 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 <input.txt >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 vim editor 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<Enter>

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<Enter>" 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, 47 words 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.

Useful tricks

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/\\<four/4/g

Obviously, this still goes wrong on "fourteen". Use "\>" to match the end of a word:

:%s/\<four\>/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/\<four\>/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 *.cppStart vim, defining the argument list to contain all the C++ files. You are now in the first file.
qqStart recording into the q register
:%s/\<GetResp\>/GetAnswer/gDo the replacements in the first file.
:wnextWrite this file and move to the next one.
qStop recording.
@qExecute the q register. This will replay the substitution and ":wnext". You can verify that this doesn't produce an error message.
999@qExecute 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/\<GetResp\>/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 \<Esc>". 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 <Enter> 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 <Leader>, 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 "/<Space><Tab>". 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<Tab>

Which will result in the same command. What happened? The <Tab> key does completion of the word before the cursor. In this case "b". vim looks 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<Tab>

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 <Tab> again, you get:

:edit intro.txt

Thus, if the first <Tab> 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 <Tab> 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:

  <────────────────────<Tab>──────────────────────────┐
								  |
		 <Tab> ──>		 <Tab> ──>
	: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 <Tab> 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 <Tab>vim will cycle through all matches. There are quite a few, it's better to type more characters first:

:set isk<Tab>

Gives:

:set iskeyword

Now type "=" and press <Tab>:

: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 <Tab> 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 <Tab> 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 <BS> to correct the word. If there are many matches, type a few more characters before pressing <Tab> 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.

Examples

vim

Launches vim, placing you in normal mode with a new document.

vim document.txt

Launches vim and opens the file document.txt, or a blank document if document.txt does not already exist.

ed — A simple text editor.
emacs — A highly extensible text editor.
ex — Line-editor mode of the vi text editor.
pico — A simple text editor.

来自 https://www.computerhope.com/unix/vim.htm







Duplicate tip

This tip is very similar to the following:

These tips need to be merged – see the merge guidelines.

Tip 462 Printable Monobook Previous Next

created 2003 · complexity basic · author Nitya · version 6.0


Place the cursor on any variable in your program.

  • gd will take you to the local declaration.

  • gD will take you to the global declaration.

  • g* search for the word under the cursor (like *, but g* on 'rain' will find words like 'rainbow').

  • g# same as g* but in backward direction.

  • gg goes to the first line in the buffer (or provide a count before the command for a specific line).

  • G goes to the last line (or provide a count before the command for a specific line).

See alsoedit | edit source


https://www.computerhope.com/unix/vim.htm


普通分类: