ChatGPT解决这个技术问题 Extra ChatGPT

How to insert tab character when expandtab option is on in Vim

vim

When I'm in insert mode and I have the expandtab option switched on, pressing Tab ↹ results in inserting the configured number of spaces.

But occasionally I want to insert an actual tab character.

Do you know how to do this?


M
Matthias Braun

You can use <CTRL-V><Tab> in "insert mode". In insert mode, <CTRL-V> inserts a literal copy of your next character.

If you need to do this often, @Dee`Kej suggested (in the comments) setting Shift+Tab to insert a real tab with this mapping:

:inoremap <S-Tab> <C-V><Tab>

Also, as noted by @feedbackloop, on Windows you may need to press <CTRL-Q> rather than <CTRL-V>.


And then use . to repeat the last command if you want to insert multiple tabs.
I had some problems using this combination because I was in Command mode. Make sure you execute this command in EDIT mode.
Note: If you're using gVim on Windows, you'll likely need to use CTRL + Q instead - see stackoverflow.com/questions/6951672/…
I've just my a simple shortcut for this case and it seems to be working (not breaking anything else): inoremap <S-Tab> <C-V><Tab> -- You can put it in your ~/.vimrc file.
@TriNguyen Its likely that your OS is using Shift+Tab for something else, and vim is never seeing it. You may be able to disable this key binding when vim is active, or just choose something your OS is not using.
J
Jahanzeb Farooq

You can disable expandtab option from within Vim as below:

:set expandtab!

or

:set noet

PS: And set it back when you are done with inserting tab, with "set expandtab" or "set et"

PS: If you have tab set equivalent to 4 spaces in .vimrc (softtabstop), you may also like to set it to 8 spaces in order to be able to insert a tab by pressing tab key once instead of twice (set softtabstop=8).


In short: set et and set noet to switch tab and space as need.
Ctrl+V caused paste to happen and I did not have time to adjust keybindings. This helped
E
Eugene Yarmash

From the documentation on expandtab:

To insert a real tab when expandtab is on, use CTRL-V. See also :retab and ins-expandtab. This option is reset when the paste option is set and restored when the paste option is reset.

So if you have a mapping for toggling the paste option, e.g.

set pastetoggle=<F2>

you could also do <F2>Tab<F2>.