Thursday, November 19, 2009

Shift-Tab'ing

I have the following in my vimrc:

set sts=4
set et

This allows me to take advantage of the convenience of the tab key when editing while actually inserting spaces into the current buffer. Intuitively I've always wished I could shift-tab to unindent the current line one tab stop. After a minute of fiddling with my vimrc, I found a solution.

imap <S-Tab> <C-o><<

I should also mention that << and >> shifts the provided text based on your shiftwidth setting.

9 comments:

graywh said...

Vim already has <C-t> and <C-d> in insert mode that change the indent level. Bonus: they work no matter where the cursor is on the line, just like doing <C-o>>> or <C-o><<.

Also, you should mention that Vim uses 'shiftwidth' for the number of spaces for each indent level.

Travis Whitton said...

I did not know about <C-t> and <C-d>. Thanks for pointing that out. I will update the tip to mention shiftwidth as well as that may not be obvious to some readers.

schrierc said...

Great idea, I like the idea of using shift tab since, as you said, it seems more natural. When indenting large blocks I tend to use visual mode and > or < though.

Bill Odom said...

These are pretty widely-used already, but I thought they were worth mentioning for anyone that wasn't already aware of them:

vmap <Tab> >gv
vmap <S-Tab> <gv

They provide indenting/unindenting for Visual selections using Tab and Shift+Tab. I use them all the time.

Chic said...

That's great!
i didn't realize ^O can take me out of insert for a sake of one command =)

(frankly, only because it never crossed my mind)

Douglas said...

Bill, don't < and > achieve exactly the same thing in visual mode?

Bill Odom said...

Douglas: The mappings I posted have a couple of advantages over < and >. For one thing, they work well in both Visual and Select modes, as opposed to just Visual mode. (Hitting < or > in Select mode overwrites the selection.)

The biggest advantage, though, is that they maintain the current selection after each keypress, so you can press Tab or Shift+Tab multiple times to adjust the indentation as much as you want, without having to reselect the block of text.

nornagon said...

Please don't use 'sts'! Use 'smarttab' instead. 'sts' will use a mixture of tabs and spaces to indent your code, and guarantees that it looks like total arse on every editor everywhere.

Cheap Viagra said...

Thanks for sharing this information because I know it could be useful for many people who don't know about this application.