在Vim的插入模式中,注释(#)会移到行首

64 投票
4 回答
11482 浏览
提问于 2025-04-15 18:00

每当我想在vim中给一个缩进的行添加注释时,我会按下 Shift-o(这会在当前行上方打开一个新行,并切换到插入模式),然后开始输入Python的注释(用 #)。可是,这个井号会神奇地移动到行的开头(没有缩进),我还得按几次Tab键来调整缩进。

有没有人知道怎么解决这个问题?

4 个回答

2

我遇到这个问题是因为在使用cindent的时候,我在haskell中也碰到了同样的情况。

你可以通过修改cinkeys的内容来设置什么情况下会重新缩进。

我在我的vimrc文件中添加了以下内容,以防止#触发这种行为。

"when you type a hash as the first character stop it triggering reindent
set cinkeys -=0#
10

试着把这个放到你的 .vimrc 文件里:

autocmd BufRead *.py inoremap # X<c-h>#

这样做会让你在编辑 Python 源文件时,每次输入井号(#)符号时,都会自动缩进。

70

我想你在你的 .vimrc 文件里设置了 set smartindent

你可以查看 :h smartindent 来了解更多信息。

When typing '#' as the first character in a new line, the indent for
that line is removed, the '#' is put in the first column.  The indent
is restored for the next line.  If you don't want this, use this
mapping: ":inoremap # X^H#", where ^H is entered with CTRL-V CTRL-H.
When using the ">>" command, lines starting with '#' are not shifted
right.

我觉得在写 Python 代码的时候,其实不需要这个智能缩进功能。所以你可以把它从你的设置里去掉,或者在你的 .vimrc 文件里加上以下内容:

au! FileType python setl nosmartindent

撰写回答