在neovim中如何将自动缩进设置为空格?

18

我想知道如何在启动neovim时将自动缩进设置为四个空格,因为我使用空格进行缩进。

提前致谢。

3个回答

24

我不了解Neovim,但根据我在这里读到的内容,我猜它在这个问题上与Vim兼容。因此,下面的解释适用于纯Vim。

您要查找的选项是'expandtab'。但是,为了清楚起见,在进入此选项之前,我将解释缩进宽度。

缩进宽度

缩进的宽度由几个选项控制。在这里,“缩进”指的是例如在插入模式下按<Tab>(或<BS>,即回退空格,可以撤消现有的缩进)或自动增加缩进级别(取决于语言)。

:help tabstop
:help softtabstop
:help shiftwidth

整数选项'tabstop'指定用于显示实际制表符(\t)的宽度(不是您感兴趣的直接内容,但请参见下文)。
整数选项'softtabstop'表示应该跨越缩进的宽度。特殊值0表示复制'tabstop'的值(或更确切地说,禁用“软制表符停止”功能),特殊值-1表示复制'shiftwidth'的值。
整数选项'shiftwidth'给出了用于移位命令(例如<<>>==)的宽度。特殊值0表示复制'tabstop'的值。

使用空格进行缩进

当设置'expandtab'时,始终使用空格字符进行缩进。否则,按下<Tab>将插入尽可能多的制表符,并使用空格字符补齐缩进宽度。
:help expandtab

示例

例如,如果tabstop=8softtabstop=3,则在插入模式下:

  1. 在空行上按<Tab>将插入3个空格,使总缩进为3列宽度;
  2. 再次按<Tab>将插入3个空格,使总缩进为6列宽度;
  3. <Tab>将使总缩进为9列宽度; 如果设置了'expandtab',则会使用9个空格进行写入; 否则,它将使用制表符(替换以前的空格)后跟一个空格字符;
  4. <BS>将撤消步骤3;
  5. <BS>将撤消步骤2;
  6. <BS>将撤消步骤1。

配置示例

通常,您希望简单化并为三个宽度选项设置相同的值。这是一个示例配置,它识别了所有三个选项,因此您只需要更改'tabstop'的值即可。它还按照您的要求设置'expandtab'。最后,由于您调用了自动缩进,我包括了相关选项:'autoindent''smartindent''cindent'; 但是您应该使用特定于语言的插件。

" length of an actual \t character:
set tabstop=4
" length to use when editing text (eg. TAB and BS keys)
" (0 for ‘tabstop’, -1 for ‘shiftwidth’):
set softtabstop=-1
" length to use when shifting text (eg. <<, >> and == commands)
" (0 for ‘tabstop’):
set shiftwidth=0
" round indentation to multiples of 'shiftwidth' when shifting text
" (so that it behaves like Ctrl-D / Ctrl-T):
set shiftround

" if set, only insert spaces; otherwise insert \t and complete with spaces:
set expandtab

" reproduce the indentation of the previous line:
set autoindent
" keep indentation produced by 'autoindent' if leaving the line blank:
"set cpoptions+=I
" try to be smart (increase the indenting level after ‘{’,
" decrease it after ‘}’, and so on):
"set smartindent
" a stricter alternative which works better for the C language:
"set cindent
" use language‐specific plugins for indenting (better):
filetype plugin indent on

您可以调整这些设置并将它们写在您的.vimrc.nvimrc文件中。

当然,此外,您还可以根据文件类型为每个缓冲区选择特定的设置。例如:

" do NOT expand tabulations in Makefiles:
autocmd FileType make setlocal noexpandtab

" for the C language, indent using 4‐column wide tabulation characters,
" but make <Tab> insert half‐indentations as 2 spaces (useful for labels):
autocmd FileType c setlocal noexpandtab shiftwidth=2

" use shorter indentation for Bash scripts:
autocmd FileType sh setlocal tabstop=2

1
是的,在这个方面和许多其他方面都完全兼容。由于您提供了如此全面的答案,您可能也会对“shiftround”感兴趣,即使它与问题没有直接关系。 - Amadan

12

如果你想使用两个空格进行缩进,请在你的配置文件中添加以下内容:

set tabstop=2
set shiftwidth=2
set expandtab
set smartindent

10
Lua:
local o = vim.o

o.expandtab = true # expand tab input with spaces characters
o.smartindent = true # syntax aware indentations for newline inserts
o.tabstop = 2 # num of space characters per tab
o.shiftwidth = 2 # spaces per indentation level

解释制表符设置的文章


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接