admin 管理员组

文章数量: 887018

【Vim】

一、什么是Vim?

Vim 是一个历史悠久的文本编辑器,可以追溯到 qed。 Bram Moolenaar 于 1991 年发布初始版本。Vim 有着悠久的历史;它起源于 Vi 编辑器(1976 年),至今仍在开发中。(Vim has a rich history; it originated from the Vi editor (1976), and it’s still being developed today.) 

编程时,您大部分时间都花在阅读/编辑上,而不是写作上。出于这个原因,Vim 是一个模态编辑器:它有不同的插入文本和操作文本的模式。Vim 是可编程的(使用 Vimscript 和 Python 等其他语言),而 Vim 的界面本身就是一种编程语言:击键(带有助记词名称)是命令,这些命令是可组合的。Vim 避免使用鼠标,因为它太慢了;Vim 甚至避免使用箭头键,因为它需要太多的移动。 最终结果是一个可以匹配您思维速度的编辑器。 

(When programming, you spend most of your time reading/editing, not writing. For this reason, Vim is a modal editor: it has different modes for inserting text vs manipulating text. Vim is programmable (with Vimscript and also other languages like Python), and Vim’s interface itself is a programming language: keystrokes (with mnemonic names) are commands, and these commands are composable. Vim avoids the use of the mouse, because it’s too slow; Vim even avoids using the arrow keys because it requires too much movement.

The end result is an editor that can match the speed at which you think.)

二、Vim安装

①在VScode上的扩展插件中有vim的插件,我们选择install即可。

②Ubuntu虚拟中,打开终端terminal,键入

sudo apt install vim

这里我已经下载完成。(可以用vim -version检验一下)

三、vim的编辑模式

  • Normal: for moving around a file and making edits
  • Insert: for inserting text
  • Replace: for replacing text
  • Visual (plain, line, or block): for selecting blocks of text
  • Command-line: for running a command

击键在不同的操作模式下有不同的含义。例如,在“插入”模式下,字母 x 只会插入一个文字字符“x”,但在“正常”模式下,它将删除光标下的字符,而在“可视”模式下,它将删除所选内容。

您可以通过按<ESC>(转义键)从任何模式切换回正常模式来更改模式。从“正常模式”中,使用 i 输入插入模式,使用 R 输入替换模式,使用 v 输入可视模式,使用 V 输入可视线模式,使用 (<C-v>Ctrl-V,有时也写入 ^V)进入可视块模式,使用 : 输入命令行模式。 

四、vim基础 

4.1、Inserting text

从正常模式,按 i 进入插入模式。现在,Vim 的行为与任何其他文本编辑器一样,直到您按<ESC>下返回正常模式。这些,以及上面解释的基础知识,就是你开始使用 Vim 编辑文件所需要的一切(尽管不是特别有效,如果你把所有时间都花在插入模式下编辑)。

现在是normal模式:

按i后进入插入模式:

4.2、Buffers, tabs, and windows

Vim 维护着一组打开的文件,称为 “buffers”。一个 Vim 会话有许多选项卡,每个选项卡都有多个窗口(拆分窗格)。每个窗口显示一个缓冲区。与您熟悉的其他程序(如 Web 浏览器)不同,缓冲区和 Windows 之间没有一一对应关系;窗户只是视图。给定的缓冲区可以在多个窗口中打开,甚至在同一选项卡中也是如此。例如,这非常方便,可以同时查看文件的两个不同部分。

默认情况下,Vim 打开时只有一个选项卡,其中包含一个窗口。 

(Vim maintains a set of open files, called “buffers”. A Vim session has a number of tabs, each of which has a number of windows (split panes). Each window shows a single buffer. Unlike other programs you are familiar with, like web browsers, there is not a 1-to-1 correspondence between buffers and windows; windows are merely views. A given buffer may be open in multiple windows, even within the same tab. This can be quite handy, for example, to view two different parts of a file at the same time.

By default, Vim opens with a single tab, which contains a single window.)

Vim 是一个文本编辑器。每次文本都是作为缓冲区的一部分显示的。每一份文件都是在他们自己独有的缓冲区打开的,插件显示的内容也在它们自己的缓冲区中。

缓冲区有很多属性,比如这个缓冲区的内容是否可以修改,或者这个缓冲区是否和文件相关联,是否需要同步保存到磁盘上。

窗口 是缓冲区上一层的视窗。如果你想同时查看几个文件或者查看同一文件的不同位置,那样你会需要窗口。

请别把他们叫做 分屏 。你可以把一个窗口分割成两个,但是这并没有让这两个窗口完全 分离

窗口可以水平或者竖直分割并且现有窗口的高度和宽度都是可以被调节设置的,因此,如果你需要多种窗口布局,请考虑使用标签。

标签页 (标签)是窗口的集合。因此当你想使用多种窗口布局时候请使用标签。

简单的说,如果你启动 Vim 的时候没有附带任何参数,你会得到一个包含着一个呈现一个缓冲区的窗口的标签。

顺带提一下,缓冲区列表是全局可见的,你可以在任何标签中访问任何一个缓冲区。

4.3、Command-line

Command mode can be entered by typing : in Normal mode. Your cursor will jump to the command line at the bottom of the screen upon pressing :. This mode has many functionalities, including opening, saving, and closing files, and quitting Vim.

在正常模式下,可以通过键入":"来进入命令模式。按":",您的光标将跳转到屏幕底部的命令行。此模式具有许多功能,包括打开、保存和关闭文件,以及退出 Vim。

  • :q quit (close window) - 退出(关闭窗口)
  • :w save (“write”) - 保存("写入")
  • :wq save and quit - 保存并退出
  • :e {name of file} open file for editing - {文件名}打开文件进行编辑
  • :ls show open buffers - 显示打开的缓冲区
  • :help {topic} open help
    • :help :w opens help for the :w command
    • :help w opens help for the w movement

五、vim的界面是一种编程语言

Vim 中最重要的思想是 Vim 的界面本身就是一种编程语言。击键(带有助记词名称)是命令,这些命令组成。这样可以进行有效的移动和编辑,尤其是当命令成为肌肉记忆时。

5.1、Movement

  • Basic movement: hjkl (left, down, up, right)
  • Words: w (next word), b (beginning of word), e (end of word)
  • Lines: 0 (beginning of line), ^ (first non-blank character), $ (end of line)
  • Screen: H (top of screen), M (middle of screen), L (bottom of screen)
  • Scroll: Ctrl-u (up), Ctrl-d (down)
  • File: gg (beginning of file), G (end of file)
  • Line numbers: :{number}<CR> or {number}G (line {number})
  • Misc: % (corresponding item)
  • Find: f{character}t{character}F{character}T{character}
    • find/to forward/backward {character} on the current line
    • , / ; for navigating matches
  • Search: /{regex}n / N for navigating matches

5.2、Selection

Visual modes:

  • Visual: v
  • Visual Line: V
  • Visual Block: Ctrl-v

5.3、Edits

  • i enter Insert mode
    • but for manipulating/deleting text, want to use something more than backspace
  • o / O insert line below / above
  • d{motion} delete {motion}
    • e.g. dw is delete word, d$ is delete to end of line, d0 is delete to beginning of line
  • c{motion} change {motion}
    • e.g. cw is change word
    • like d{motion} followed by i
  • x delete character (equal do dl)
  • s substitute character (equal to cl)
  • Visual mode + manipulation
    • select text, d to delete it or c to change it
  • u to undo, <C-r> to redo
  • y to copy / “yank” (some other commands like d also copy)
  • p to paste
  • Lots more to learn: e.g. ~ flips the case of a character

5.4、Counts

您可以将名词和动词与计数组合在一起,计数将多次执行给定的动作。

  • 3w move 3 words forward
  • 5j move 5 lines down
  • 7dw delete 7 words

5.5、Modifiers

您可以使用修饰符来更改名词的含义。一些修饰词是 i,意思是“内部”或“内部”,以及 a,意思是“周围”。(You can use modifiers to change the meaning of a noun. Some modifiers are i, which means “inner” or “inside”, and a, which means “around”.)

  • ci( change the contents inside the current pair of parentheses - 更改当前括号对内的内容
  • ci[ change the contents inside the current pair of square brackets - 更改当前方括号对内的内容
  • da' delete a single-quoted string, including the surrounding single quotes - 删除单引号字符串,包括周围的单引号

六、Advanced Vim

Here are a few examples to show you the power of the editor. We can’t teach you all of these kinds of things, but you’ll learn them as you go. A good heuristic: whenever you’re using your editor and you think “there must be a better way of doing this”, there probably is: look it up online.

6.1、Search and replace

:s (substitute) command (documentation).

  • %s/foo/bar/g
    • replace foo with bar globally in file(全局替换)
  • %s/\[.*\](\(.*\))/\1/g
    • replace named Markdown links with plain URLs

6.2、Multiple windows

  • :sp / :vsp to split windows
  • Can have multiple views of the same buffer.

6.3、Macros(宏)

你可以在 Vim 中录制一系列按键,并把他们存储到寄存器中。对于一些需要临时使用多次的一系列操作,把它们作为宏保存起来会显著地提升效率。对于一些复杂的操作,建议使用 Vim 脚本来实现。

  • q{character} to start recording a macro in register {character} - 开始记录寄存器 {character} 中的宏
  • q to stop recording
  • @{character} replays the macro
  • Macro execution stops on error
  • {number}@{character} executes a macro {number} times - 执行宏 {number} 次
  • Macros can be recursive
    • first clear the macro with q{character}q - 首先用 q{character}q 清除宏
    • record the macro, with @{character} to invoke the macro recursively (will be a no-op until recording is complete) - 记录宏,使用 @{character} 递归调用宏(在录制完成之前将是一个无操作)
  • Example: convert xml to json (file)
    • Array of objects with keys “name” / “email”
    • Use a Python program?
    • Use sed / regexes
      • g/people/d
      • %s/<person>/{/g
      • %s/<name>\(.*\)<\/name>/"name": "\1",/g
    • Vim commands / macros
      • Gddggdd delete first and last lines - 删除第一行和最后一行
      • Macro to format a single element (register e)
        • Go to line with <name>
        • qe^r"f>s": "<ESC>f<C"<ESC>q
      • Macro to format a person
        • Go to line with <person>
        • qpS{<ESC>j@eA,<ESC>j@ejS},<ESC>q
      • Macro to format a person and go to the next person
        • Go to line with <person>
        • qq@pjq
      • Execute macro until end of file
        • 999@q
      • Manually remove last , and add [ and ] delimiters

七、Resources

  • vimtutor is a tutorial that comes installed with Vim - if Vim is installed, you should be able to run vimtutor from your shell
  • Vim Adventures is a game to learn Vim
  • Vim Tips Wiki
  • Vim Advent Calendar has various Vim tips
  • Vim Golf is code golf, but where the programming language is Vim’s UI
  • Vi/Vim Stack Exchange
  • Vim Screencasts
  • Practical Vim (book)

八、Exercises

  1. Complete vimtutor. Note: it looks best in a 80x24 (80 columns by 24 lines) terminal window.
  2. Download our basic vimrc and save it to ~/.vimrc. Read through the well-commented file (using Vim!), and observe how Vim looks and behaves slightly differently with the new config.
  3. Install and configure a plugin: ctrlp.vim.
    1. Create the plugins directory with mkdir -p ~/.vim/pack/vendor/start
    2. Download the plugin: cd ~/.vim/pack/vendor/start; git clone .vim
    3. Read the documentation for the plugin. Try using CtrlP to locate a file by navigating to a project directory, opening Vim, and using the Vim command-line to start :CtrlP.
    4. Customize CtrlP by adding configuration to your ~/.vimrc to open CtrlP by pressing Ctrl-P.
  4. To practice using Vim, re-do the Demo from lecture on your own machine.
  5. Use Vim for all your text editing for the next month. Whenever something seems inefficient, or when you think “there must be a better way”, try Googling it, there probably is. If you get stuck, come to office hours or send us an email.
  6. Configure your other tools to use Vim bindings (see instructions above).
  7. Further customize your ~/.vimrc and install more plugins.
  8. (Advanced) Convert XML to JSON (example file) using Vim macros. Try to do this on your own, but you can look at the macros section above if you get stuck.

本文标签: vim