如何在 Vim 中插入真正的制表符?

当我在这里有我的 vimrc:

set tabstop=2
set shiftwidth=2
set softtabstop=2
set expandtab
set smarttab

我还安装了 supertab 插件。每当我在插入模式,我按制表符,它显示自动完成,但有时我想插入一个真正的制表符字符串文字喜欢。所以我的意思是,当我按下双引号字符串中的 tab 时,它应该输入一个真正的 tab 字符。

65907 次浏览

While in insert mode or command mode (the : prompt at the bottom of the editor), type CTRL + V then TAB.

Using CTRL + V signals Vim that it should take the next character literally. Even in insert mode.

UPDATE:

As noted by Herbert Sitz, if gVim is in Windows mode (default), you must use CRTL + Q in place of CTRL + V.

@Samnang: I have a similar setup as you; unfortunately, Jason's answer did not work, for me.

This is a workaround:

  • Substitute some character (e.g. a backtick: `) or characters (e.g. a unique alphanumeric string: zzz) where you want your tab(s)

  • Select the text (Visual mode) and do a search/replace,

    :'s/`/\t/g

Updated answer, inspired by @Cyryl1972 's comment.

To insert a tab at beginning of all lines (note also: no need to select lines, for any of the following code, as that's included in the line matching part of the expression):

:1,$s/^/\t\1/

Insert tab after first 10 characters in all lines:

:1,$s/^\(.\{10}\)/\1\t/

Explanation - first part:

:1,$      Match from line 1 to end of file
^(.{10}   Collect (preserve) all text from beginning of line to position 10
(you need to escape the parentheses, \( and \), as well the FIRST
(left) curly brace, only: \{ -- as it, { , appears to have special
meaning in regex when used for this purpose

Explanation - second part:

/1        Add back the preserved text
\t        Insert a tab

... and the rest of the line is automatically restored, as well.

Current line, only:

:s/^/\t\1/

Example: insert tab at position 10 (0-indexed) at lines 2-4:

1234567890abcdefghij
1234567890abcdefghij
1234567890abcdefghij
1234567890abcdefghij
1234567890abcdefghij


:2,4s/^\(.\{10}\)/\1\t/


1234567890abcdefghij
1234567890  abcdefghij
1234567890  abcdefghij
1234567890  abcdefghij
1234567890abcdefghij

References (StackOverflow):

References (other):