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
settabstop=4
setshiftwidth=4
set smartindent
set showcmd
setmouse=a
setbackground=light
set clipboard+=unnamed
set foldenable
setfoldmethod=indent
setfoldmethod=syntax
setfoldmethod=syntax
set nofoldenable
syntax on
系统管理员的重要工作就是得要修改与设定某些重要软件的配置文件,因此至少得要学会一种以上的文字接口的文书编辑器。 在所有的 Linux distributions 上头都会有的一套文书编辑器就是 vi ,而且很多软件默认也是使用 vi 做为他们编辑的接口, 因此鸟哥建议您务必要学会使用 vi 这个正规的文书编辑器。此外,vim 是进阶版的 vi , vim 不但可以用不同颜色显示文字内容,还能够进行诸如 shell script, C program 等程序编辑功能, 你可以将 vim 视为一种程序编辑器!鸟哥也是用 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 的文本模式下,会觉得文书编辑程序都没有窗口接口来的直观与方便。
其实重点是上述的第二点,因为有太多 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 档名』就能够进入 vi 的一般模式了。请注意,记得 vi 后面一定要加档名,不管该档名存在与否! 整个画面主要分为两部份,上半部与最底下一行两者可以视为独立的。如下图 2.1.1 所示,图中那个虚线是不存在的, 鸟哥用来说明而已啦!上半部显示的是档案的实际内容,最底下一行则是状态显示列(如下图的[New File]信息), 或者是命令下达列喔!
除了上面简易范例的 i, [Esc], :wq 之外,其实 vim 还有非常多的按键可以使用喔!在介绍之前还是要再次强调, vim 的三种模式只有一般模式可以与编辑、指令列模式切换,编辑模式与指令列模式之间并不能切换的! 这点在图2.1里面有介绍到,注意去看看喔!底下就来谈谈 vim 软件中会用到的按键功能吧!
先『 1G 』去到第一行,然后按下大写的『 O 』便新增一行且在插入模式;开始输入『I am a student...』后, 按下[Esc]回到一般模式等待后续工作;
『: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 喔!
其实,目前大部分的 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』
图3.0.1、 vim 的图示示意
上面是 vim 的画面示意图,在这个画面中有几点特色要说明喔:
由于 man.config 是系统规划的配置文件,因此 vim 会进行语法检验,所以你会看到画面中内部主要为深蓝色, 且深蓝色那一行是以批注符号 (#) 为开头;
假设一个例子,你想要将刚刚我们的 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 档案内,那可以怎么进行呢?可以这样啊:
透过『 vim hosts /etc/hosts 』指令来使用一个 vim 开启两个档案;
在 vim 中先使用『 :files 』察看一下编辑的档案数据有啥?结果如下所示。 至于下图的最后一行显示的是『按下任意键』就会回到 vim 的一般模式中!
有没有发现,如果我们以 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
一般来说, 如果我们按下 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 教育训练手册, 发现底下这张图非常值得大家参考!可以更快速有效的查询到需要的功能喔!看看吧!
图 3.5.1 、 vim 常用指令示意图
其他 vim 使用注意事项
vim 其实不是那么好学,虽然他的功能确实非常强大!所以底下我们还有一些需要注意的地方要来跟大家分享喔!
中文编码的问题
很多朋友常常哀嚎,说他们的 vim 里面怎么无法显示正常的中文啊?其实这很有可能是因为编码的问题! 因为中文编码有 big5 与 utf8 两种,如果你的档案是使用 big5 编码制作的,但在 vim 的终端接口中你使用的是万国码(utf8), 由于编码的不同,你的中文档案内容当然就是一堆乱码了!怎么办?这时你得要考虑许多东西啦!有这些:
一般来说,中文编码使用 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 来转换一下断行格式啊!
在 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 让你在指令列模
在 前面我們所談的那些可以說是比較基本的東西,但是對於一份文件來說,光有前面所介紹的游標移動、刪除等等功能是不足夠的。面對一份文件我們通常會因為某些 緣故而使得我們必須去修改當中固定出現的字串樣式(pattern)成我們想要的樣子。最常遇到的就像中文文件的標點符號問題,或是 un*ix 和 DOS 文件格式之間轉換常會有個 ^M 結尾會讓人覺得很討厭,又或是我們想要把一份 HTML 格式的文件去除掉它的 HTML tag。 對於這些事情來說,拿中文標點符號置換這個很多編輯器都做得到,簡單地說如果想更動的 pattern 是一個固定的字串,那對於一般編輯器來說都不會太困難,但是對於具有固定格式,但字串內容卻不一定的該怎麼辦?就像要去掉 HTML 格式中的所有 HTML tag?這就是 vim 開始大顯身手的地方了。
今天我們不談別的其他指令,就光談在 vim 中的「 :s 」指令。小寫 :s 表示置換(substitute)的意思,不過通常你用 vim 下 :h :s 指令的時候會看到這樣的畫面:
最前面的「%」就是表示全域,也就是現在編輯的這一份文件都要作後面取代的工作。那這個指令就是說要把半形的逗點「,」變成全形「,」。那後面 「g」又代表什麼意思呢?在 g 這個欄位上的東西是用來表示對目前這個指令所做的額外的選項。就拿 g 來說, g 代表在文件中每一個出現的半形逗點都要置換成全形。或許你會問剛剛不是已經用「%」表示全域了嗎,怎麼又要用 g 呢?我應該這樣說,「%」用來表示從文件的第一行到最後一行。但是在比對(match)的時候,如果不加「g」這個額外選項的話, vim 只會把每一行比對到的第一個作取代,同行其他也 match 到的就不管了。所以用「g」表示每一行中每一個比對到的都要置換。 所以同理,如果你要把那些因為 un*ix 和 DOS 之間格式不合所造成的^M消掉的話,也只需要下成這樣就可以了:
:%s/^M//g
可是有時候你想要作置換的只是文件中的某一部份的話怎麼辦?不要緊,還記得選取模式嗎?在你想置換部分的開頭按下大寫「V」然後用移動游標(我們之前講的 vim 移動游標的方法在選取模式下都可以用)到你想要的位置之後按「:」就會跳到輸入指令的狀態,如下圖最下面那行看到的一樣:
這就是說你給了一個起始行數比結束行數還要大的範圍。這是因為 vim 所定的範圍都是從小到大,如果你要從大到小不是不行,只是多個訊息確認你沒有打錯罷了。 Pattern: 像前面說,固定字串像把半形逗點換成全形逗點這都還容易,如果只是格式固定,但是字串內容會變動怎麼辦?就像去 HTML tag 的時候就很麻煩。 還記得我們在淺談vim那時候提過的指令嗎?
:%s/\n/^V/g
:%s/《[^<》]*>//g
:%s/^V/\n/g
在中間的那一些 [^<>]*看起來像外星文字的,就是 pattern 比對的主力。事實上關於這些東西,我們在談 vim 的 search 搜尋功能的時候也有提到過一些。所以我們今天就來補一些上次沒有講到的東西。 假如我現在有一筆人名、電話的資料,由於是隨手記的,上面自然就是沒有排序過。那沒排序過對於想要在上面找資料的人就很麻煩。萬一人名記不太清楚, 電話號碼也記得七七八八,雖然說有 vim 方便的 search 功能,但總是感覺不足。(當然這只是假設情況,因為實際上可能大家都已經建立某種方便搜尋的資料庫了) 我們先假設人名、電話的對應長成這樣:
表示在按 之後按下「/」這個按鍵。這樣就可以把搜尋的字串叫出來並用之於置換指令上。+r> 額外指令: 我們剛剛在前面談到可以作像「g」這些的額外控制。那有哪些控制可以作呢? 比方說在我們作置換的時候,由於 vim 預設是有大小寫的差別,如果你不管大小寫都要取代的話,那可以用「i」這個額外參數來控制 vim 取代的時候就不管大小寫都會作取代的工作。 不過有時候,我們可能不太能確定是不是整份文件中的每一個都要取代,那我們就可以加「c」 confirm 確認參數來控制,那使用上也很容易。 vim 會在比對到之後問
(y/n/a/q/l/^E/^Y)?
y 是代表執行目前的取代。
n 是跳過。
a 代表 always ,就是從目前以後的取代都會執行。
q 則是不要作取代,並且離開詢問要不要取代的狀態,並回到指令模式或原來的模式下。
l 則是 last 的意思,就是目前這個取代執行後就離開詢問的取代模式,回到指令模式或原來的模式下。
^E 表示往前一頁。
^Y 表示往後一頁。
對於 :s 的用法到這裡我們就已經把常用的幾個方式都說完了。礙於篇幅,我也決定先寫到這裡就好,不然寫一大篇,可能連有興趣進來瞭解 vim 的人光看到就害怕了,怎麼還有辦法體會 vim 的好呢?其實關於 :s 的用法,還有 pattern 還有很多的方式在本篇中沒有提到,你可以在 vim 中用 :h :s 看到更多詳細的資料。今天就來 vim 吧!
On Unix-like operating systems, vim, which stands for "Vi Improved", is a texteditor. It can be used for editing any kind of text and is especially suited for editing computer programs.
vim is a text editor that is upwards compatible to Vi. There are a lot of enhancements above Vi: multi level undo, multiple windows and buffers, syntax highlighting, command line editing, file name completion, a complete help system, visual selection, and others.
Starting vim
Most often, vim is started to edit a single file using the following command.
vim file
More generally, the syntax for starting vim is as follows:
vim [options] [filelist]
If the filelist is missing, the editor will start with an empty buffer. Otherwise, one out of the following four options may be used to choose one or more files to be edited.
Main options
file...
A list of one or more file names. The first one will be the current file and read into the buffer. The cursor will be positioned on the first line of the buffer. You can get to the other files with the ":next" command. To edit a file that starts with a dash, precede the filelist with a double dash ("--").
-
A single dash specifies that the file to edit is to be read from standard input.
-t {tag}
The file to edit and the initial cursor position depends on a "tag", a sort of goto label. The {tag} is looked up in the tags file, the associated file becomes the current file and the associated command is executed. Mostly this is used for C programs, in which case {tag} could be a function name. The effect is that the file containing that function becomes the current file and the cursor is positioned on the start of the function. For more information within vim, use the command ":help tag-commands".
-q [errorfile]
Start in quickFix mode. The file errorfile is read and the first error is displayed. If errorfile is omitted, the file name is obtained from the 'errorfile' option (defaults to "errors.err" on most systems). Further errors can be jumped to with the ":cn" command. For more information within vim, use the command ":help quickfix".
Invoking vim
vim behaves differently depending on the name of the command used to invoke it. For example, if you create a symbolic link to the vimexecutable with one of the following names, it will behave in the following fashion:
command name
behavior
vim
"Normal" execution. Everything is default.
ex
Start in Ex mode. Go to Normal mode with the ":vi" command. Can also be done with the "-e" argument.
view
Start in read-only mode. You will be protected from writing the files. Can also be done with the "-R" argument.
gvim, gview
The GUI version (if installed). Starts a new window. Can also be done with the "-g" argument.
evim, eview
Runs GUI vim in "easy mode". This command is a simplified mode of vim operation, which is a lot like a normal text editor. This is the same as running vim with the "-y" argument.
rvim, rview, rgvim, rgview
Like 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.
-A
If vim has been compiled with Arabic support for editing right-to-left oriented files and Arabic keyboard mapping, this option starts vim in Arabic mode, i.e. 'arabic' is set. Otherwise, an error message is given and vim aborts.
-b
Binary mode. A few options will be set that makes it possible to edit a binary or executable file.
-C
Compatible mode. Sets the 'compatible' option. This will make vim behave mostly like Vi, even though a .vimrc file exists.
-d
Start in diff mode. There should be two, three or four file name arguments. 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).
-D
Debugging mode. Go to debugging mode when executing the first command from a script.
-e
Start vim in ex mode, just like if the executable is called "ex".
-E
Start vim in improved ex mode, just like if the executable was called "exim".
-f
Foreground mode. For the GUI version, vim will not fork and detach from the shell it was started in. On the Amiga, vim is not restarted to open a new window. This option should be used when vim is executed by a program that will wait for the edit session to finish (e.g., mail). On the Amiga the ":sh" and ":!" commands will not work.
--nofork
Foreground mode. For the GUI version, vim will not fork and detach from the shell it was started in.
-F
If vim has been compiled with FKMAP support for editing right-to-left oriented files and Farsi keyboard mapping, this option starts vim in Farsi mode, i.e. 'fkmap' and 'rightleft' are set. Otherwise, an error message is given and vim aborts.
-g
If vim has been compiled with GUI support, this option enables the GUI. If no GUI support was compiled in, an error message is given and vim aborts.
-h
Give a bit of help about the command line arguments and options. After this vim exits.
-H
If vim has been compiled with RIGHTLEFT support for editing right-to-left oriented files and Hebrew keyboard mapping, this option starts vim in Hebrew mode, i.e. 'hkmap' and 'rightleft' are set. Otherwise, an error message is given and vim aborts.
-i {viminfo}
When using the viminfo file is enabled, this option sets the file name to use, instead of the default "~/.viminfo". This can also be used to skip the use of the .viminfo file, by giving the name "NONE".
-L
Same as -r.
-l
Lisp mode. Sets the 'lisp' and 'showmatch' options on.
-m
Modifying files is disabled. Resets the 'write' option. You can still modify the buffer, but writing a file is not possible.
-M
Modifications not allowed. The 'modifiable' and 'write' options will be unset, so that changes are not allowed and files can not be written. Note that these options can be set to enable making modifications.
-N
No-compatible mode. Reset the 'compatible' option. This will make vim behave a bit better, but less Vi compatible, even though a .vimrc file does not exist.
-n
No swap file will be used. Recovery after a crash will be impossible. Handy if you want to edit a file on a very slow medium (e.g., floppy). Can also be done with ":set uc=0". Can be undone with ":set uc=200".
-nb
Become an editor server for NetBeans.
-o[N]
Open N windows stacked. When N is omitted, open one window for each file.
-O[N]
Open N windows side by side. When N is omitted, open one window for each file.
-p[N]
Open N tab pages. When N is omitted, open one tab page for each file.
-R
Read-only mode. The 'readonly' option will be set. You can still edit the buffer, but will be prevented from accidently overwriting a file. If you do want to overwrite a file, add an exclamation mark to the Ex command, as in ":w!". The -R option also implies the -n option (see below). The 'readonly' option can be reset with ":set noro". See ":help 'readonly'".
-r
List swap files, with information about using them for recovery.
-r {file}
Recovery mode. The swap file is used to recover a crashed editing session. The swap file is a file with the same file name as the text file with ".swp" appended. See ":help recovery".
-s
Silent mode. Only when started as "Ex" or when the "-e" option was given before the "-s" option.
-s {scriptin}
The script file {scriptin} is read. The characters in the file are interpreted as if you had typed them. The same can be done with the command ":source! {scriptin}". If the end of the file is reached before the editor exits, further characters are read from the keyboard.
-T {terminal}
Tells vim the name of the terminal you are using. Only required when the automatic way doesn't work. Should be a terminal known to vim (builtin) or defined in the termcap or terminfo file.
-u {vimrc}
Use the commands in the file {vimrc} for initializations. All the other initializations are skipped. Use this to edit a special kind of files. It can also be used to skip all initializations by giving the name "NONE". See ":help initialization" within vim for more details.
-U {gvimrc}
Use the commands in the file {gvimrc} for GUI initializations. All the other GUI initializations are skipped. It can also be used to skip all GUI initializations by giving the name "NONE". See ":help gui-init" within vim for more details.
-V[N]
Verbose. Give messages about which files are sourced and for reading and writing a viminfo file. The optional number N is the value for 'verbose'. Default is 10.
-v
Start vim in Vi mode, just like the executable was called "vi". This only has effect when the executable is called "ex".
-w {scriptout}
All the characters that you type are recorded in the file {scriptout}, until you exit vim. This is useful if you want to create a script file to be used with "vim -s" or ":source!". If the {scriptout} file exists, characters are appended.
-W {scriptout}
Like -w, but an existing file is overwritten.
-x
Use encryption when writing files. Will prompt for a crypt key.
-X
Don't connect to the X server. Shortens startup time in a terminal, but the window title and clipboard will not be used.
-y
Start vim in easy mode, just like the executable was called "evim" or "eview". Makes vim behave like a click-and-type editor.
-Z
Restricted mode. Works like the executable starts with "r".
--
Denotes the end of the options. Arguments after this will be handled as a file name. This can be used to edit a file name that starts with a '-'.
--echo-wid
GTK GUI only: Echo the Window ID on standard output.
--help
Give a help message and exit, just like "-h".
--literal
Take file name arguments literally, do not expand wildcards. This has no effect on Unix where the shell expands wildcards.
--noplugin
Skip loading plugins. Implied by -u NONE.
--remote
Connect to a vim server and make it edit the files given in the rest of the arguments. If no server is found a warning is given and the files are edited in the current vim.
--remote-expr {expr}
Connect to a vim server, evaluate {expr} in it and print the result on stdout.
--remote-send {keys}
Connect to a vim server and send {keys} to it.
--remote-silent
As --remote, but without the warning when no server is found.
--remote-wait
As --remote, but vim does not exit until the files have been edited.
--remote-wait-silent
As --remote-wait, but without the warning when no server is found.
--serverlist
List the names of all vim servers that can be found.
--servername {name}
Use {name} as the server name. Used for the current vim, unless used with a --remote argument, then it's the name of the server to connect to.
--socketid {id}
GTK GUI only: Use the GtkPlug mechanism to run gvim in another window.
--version
Print version information, and exit.
Accessing help from within vim
Type ":help" in vim to get started. Type ":help subject" to get help on a specific subject. For example: ":help ZZ" to get help for the "ZZ" command. Use <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 MicrosoftWindows 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:
h
left
j
down
k
up
l
right
These keys may seem like odd choices for moving the cursor, but there is a very good reason for these: Moving the cursor is the most common thing you do in an editor, and these keys are on the home row of your right hand. In other words, these commands are placed where you can type them the fastest (especially when you type with ten fingers).
You can also move the cursor 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:
gebwe
_< _< -->_ -->_
This is-a line, with special/separated/words (and some more).
_<---- _<--- ------------------->_ ---->_
gEBWE
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.
_<--------- --------->_
Thtn
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 | gg7G | text text text text |
| text text text text
| text text text text
V text text text text |
text text text text | G
text text text text |
last line of a file V
Another way to move to a line is using the "%" command with a count, which moves you that percent through the file. For example "50%" moves you to halfway the file. "90%" goes to near the end.
The previous assumes that you want to move to a line in the file, no matter if it's currently visible or not. What if you want to move to one of the lines you can see? This figure shows the three commands you can use, H, M, and L.
H moves you to the top of the visible screen, M to the middle, and L to the end. For example:
┌───────────────────────────┐
H --> | sample text |
| sample text |
| sample text |
| sample text |
M --> | sample text |
| sample text |
| sample text |
| sample text |
L --> | sample text |
└───────────────────────────┘
"H" stands for Home, "M" stands for Middle and "L" stands for Last.
Determining where you are
To see where you are in a file, there are three ways:
Use the Ctrl-G command. You get a message like this:
"usr_03.txt" line 233 of 650 --35%-- col 45-52
This shows the name of the file you are editing, the line number where the cursor is, the total number of lines, the percentage of the way through the file and the column of the cursor.
Sometimes you will see a split column number. For example, "col 2-9". This indicates that the cursor is positioned on the second character, but because character one is a tab, occupying eight spaces worth of columns, the screen column is 9.
Set the 'number' option. This displays a line number in front of every line:
:set number
To switch this off again:
:set nonumber
Since 'number' is a boolean option, prepending "no" to its name has the effect of switching it off. A boolean option has only these two values, it is either on or off.
vim has many options. Besides the boolean ones there are options with a numerical value and string options. You will see examples of this where they are used.
Set the 'ruler' option. This displays the cursor position in the lower right corner of the vim window:
:set ruler
Scrolling
The Ctrl-U command scrolls down half a screen of text. Think of looking through a viewing window at the text and moving this window up by half the height of the window. Thus the window moves up over the text, which is backward in the file. Don't worry if you have a little trouble remembering which end is up. Most users have the same problem.
The Ctrl-D command moves the viewing window down half a screen in the file, thus scrolls the text up half a screen.
┌────────────────┐
| some text |
| some text |
| some text |
┌───────────────┐ | some text |
| some text | Ctrl-U --> | |
| | | 123456 |
| 123456 | └────────────────┘
| 7890 |
| | ┌────────────────┐
| example | Ctrl-D --> | 7890 |
└───────────────┘ | |
| example |
| example |
| example |
| example |
└────────────────┘
To scroll one line at a time use Ctrl-E (scroll up) and Ctrl-Y (scroll down). Think of Ctrl-E to give you one line Extra. If you use MSWindows-compatible key mappings Ctrl-Y will redo a change instead of scroll.
To scroll forward by a whole screen (except for two lines) use Ctrl-F. The other way is backward, Ctrl-B is the command to use. Fortunately Ctrl-F is Forward and Ctrl-B is Backward, that's easy to remember.
A common issue is that after moving down many lines with "j" your cursor is at the bottom of the screen. You would like to see the context of the line with the cursor. That's done with the "zz" command.
┌──────────────────┐ ┌──────────────────┐
| some text | | some text |
| some text | | some text |
| some text | | some text |
| some text | zz --> | line with cursor |
| some text | | some text |
| some text | | some text |
| line with cursor | | some text |
└──────────────────┘ └──────────────────┘
The "zt" command puts the cursor line at the top, "zb" at the bottom. To always keep a few lines of context around the cursor, use the 'scrolloff' option (":set scrolloff").
Simple searches
To search for a string, use the "/string" command. To find the word "include", for example, use the command:
/include
You will notice that when you type the "/" the cursor jumps to the last line of the vim window, like with colon commands. That is where you type the word. You can press the backspace key (backarrow or <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:
超讚的 没看人家寫 vi 的 search replace 寫得這麼棒的喔 !
回覆實用 3Q!!學了幾招
回覆謝謝,介紹得很仔細,很受用,感恩
回覆