Editing Basics

Buffers

当你编辑一个文件时, Vim 将磁盘上的文件内容读取到计算机的 RAM 中. 这意味这文件的一个备份被存储到了计算机的内存中,你对文件做出的任何修改,是直接映射到内存中的,并且会立即展示出来. 一旦完成了编辑,你可以保存文件,这意味着 Vim 将内存中的内容要写回磁盘. 临时存储文件的内存被称为缓存 (Buffer) . 所以,这就是为什么编辑完后要保存文件的原因.

Swap

当你编辑文件时, 会在相同目录下会创建一个类似于 .hello.txt.swp 的文件. 查看确切的文件名可以使用如下命令:

1
:swapname

Vim 维护了文件缓存区 (buffer) 的一个文件备份, 会定期保存到该文件中, 以避免出现问题时进行恢复 (如 计算机或者 Vim 程序崩溃). 这个文件被称为 swap file, 因为 Vim 会不断交换内存中的内容到磁盘上的文件中.

Save my file

当你修改了文件时, 并且没有保存, 在另一个窗口查看时, 此时是不会看到之前修改的内容的, 这也很好理解, 因为 Vim 只修改了 buffer 中的内容, 还没有保存到磁盘上. 可以通过 :write 命令来完成保存过程, 将内存中的内存写到磁盘中.

为了让生活变得容易一点, 你可以使用快捷键映射, 在 vimrc 文件中:

1
2
3
#To save,ctrl-s.
nmap <c-s> :w<CR>
imap <c-s> <Esc>:w<CR>a

Cut, Copy and paste

desktop vim word operation
cut delete d
copy yank y
paste put p

剪切操作在 Vim 中意味着从 buffer 中删除文本, 并将其存储到寄存器中

复制操作中同样也意味着拉取 (yank) 文本,并将其放到寄存器中

粘贴没有其特殊含义

Why yank not copy ?

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.

– Vim User Manual

如何在 Vim 中指定要在哪些文本上应用 cut/copy/paste 操作?

你可以:

command operation
dl 删除单个字符
dw 删除一个单词
dd 删除一行
d$ 删除光标位置到行尾的所有字符
dwwP 交换两个单词
…… ……

是不是很棒, 这里最让人激动的事情在于, 你可以结合之前的移动等命令, 更多的可能不是吗? 一般的编辑器, 可能没有办法做到如此简洁, 有力 , 并保持方便记忆 !

还记得清空当前文档的操作吗 ?

words

  • w
  • e

Sentence

  • (
  • )

Paragraph

  • {
  • }

Visual Mode Select

  • aw

    select a word

  • ap

    select a paragraph

  • ab

    select a block (anything with a pair of parentheses)

  • a"

    select a quoted string (like “this is a quoted string”)

Marking your territory

  • create a mark where you can jump here later

    ma (a-zA-Z ) then you create a mark called ‘a’

  • return the cursor to the mark

    'a take you to the exact line and column of the mark

Time machine using undo/redo

  • u undo :leftwards_arrow_with_hook:

  • ctrl-r redo :arrow_right_hook:

  • more…

1
2
3
4
5
6
7
8
9
10
11
# take you back by 4 minutes
:earlier 4m

# take you later by 45 seconds
:later 45s

# go back 5 changes
undo 5

# view the undo tree
undolist

Powerful search engine

  • basic search*
1
2
3
4
5
6
7
8
# search
/the<cr> # /the followed by the enter key

# next occurrence
press `n`

# previous occurrence
press `N`

还记得我们第一次介绍 Vim 的骚操作吗 * 搜索当前光标所在的单词

  • start searching as and when you type the search phrase
1
set incsearch
  • ignore the case of the text that you are searching for
1
set ignorecase
  • smart case
1
set smartcase
  • searching for /step, then it will search for any combination of upper and lower case text. So eventually, “Step”, “Stephen”,”stepbrother”
  • searching for /Step, only “Step”, “Stephen”, but not “stepbrother”
  • basic patterns
1
2
3
4
5
6
7
# exactly search the word 'step' and not 'stepfather'
/\<step\>

# search numbers
/\d\+

# see :help pattern for more details

永远不要去死记硬背这些操作, 试着理解, 并练习, 最终成为肌肉记忆.

vim doc