为什么 Vim 选项记录为 "local to buffer" 由新缓冲区继承?

Why are Vim options documented to be "local to buffer" inherited by new buffers?

我在空目录下启动Vim

vim -u NONE foo.txt

然后我在Vim.

中输入以下命令
:set ts=40

现在,如果我按 Tab,光标确实移动到第 41 列。

现在我在Vim中输入以下命令。

:e! bar.txt

现在,如果我按 Tab 键,光标会再次移动到第 41 列。这让我很吃惊。我期待光标移动到第 9 列。

事实上,:help 'ts显示如下。

                        *'tabstop'* *'ts'*
'tabstop' 'ts'      number  (default 8)
            local to buffer
    Number of spaces that a <Tab> in the file counts for.  Also see
    |:retab| command, and 'softtabstop' option.

帮助说ts选项是local to buffer。为什么我在一个缓冲区中设置的 ts=40 选项被应用到另一个新缓冲区?

set tabstop=40 设置默认为40。你想设置你需要使用的本地版本setlocal tabstop=40。如果已设置,本地版本将覆盖全球版本。

"Local to buffer" 表示新值不会影响其他 现有 缓冲区。

假设 vimrc 中的 tabstop 设置为 4 并且您使用两个缓冲区开始 vim:

$ vim a.txt b.txt

tabstop 的初始值由两个缓冲区继承,因此 a.txtb.txttabstop 设置为 4

如果您在 a.txt 中执行 :set tabstop=7b.txt 仍将具有之前的值 4。这就是"local to buffer"的意思。

但是当你创建一个新缓冲区时,新缓冲区继承当前缓冲区的设置,所以你将在新缓冲区中得到一个ts=7如果当前缓冲区有7,如果是4,则有ts=4,依此类推。

然后是 :setlocal,它设置了一个不会被新缓冲区继承的本地值。

这里"local to buffer"意味着可以为每个缓冲区设置不同的值,而不是只在全局设置一个值。其他选项标记为 "global",表示整个 vim 实例只有一个值,并且每个缓冲区必须共享该单个值。还有一些是 "local to window",类似于 "local to buffer",但在 window 范围内。

来自:help option-summary

Most options are the same in all windows and buffers. There are a few that are specific to how the text is presented in a window. These can be set to a different value in each window. For example the list option can be set in one window and reset in another for the same text, giving both types of view at the same time. There are a few options that are specific to a certain file. These can have a different value for each file or buffer. For example the textwidth option can be 78 for a normal text file and 0 for a C program.

  • global: one option for all buffers and windows
  • local to window: each window has its own copy of this option
  • local to buffer: each buffer has its own copy of this option

When creating a new window the option values from the currently active window are used as a default value for the window-specific options. For the buffer-specific options this depends on the s and S flags in the cpoptions option. If s is included (which is the default) the values for buffer options are copied from the currently active buffer when a buffer is first entered. If S is present the options are copied each time the buffer is entered, this is almost like having global options. If s and S are not present, the options are copied from the currently active buffer when the buffer is created.

另见 :help :setlocal