5

Using vim, I would like to effectively have expandtabs off if I'm to the left of any text on the line and on if I'm to the right of any non-whitespace character. (I would like to use tabs for indentation and spaces for alignment.)

Can this be done?

1
  • I strongly believe it can be done. I just don't think it will be any easy, though. Commented Jul 20, 2009 at 2:17

2 Answers 2

6

Yes. Use the Smart Tabs plugin.

This script allows you to use your normal tab settings for the beginning of the line, and have tabs expanded as spaces anywhere else. This effectively distinguishes 'indent' from 'alignment'.

<tab> Uses editor tab settings to insert a tab at the beginning of the line (before the first non-space character), and inserts spaces otherwise.

<BS> Uses editor tab settings to delete tabs or 'expanded' tabs ala smarttab

To make Vim line up function arguments, add

set cindent
set cinoptions=(0,u0,U0

to .vimrc. The plugin will encode the whitespace as such:

int f(int x,
......int y) {
--->return g(x,
--->.........y);
}

This makes the alignment of "x" and "y" independent of the tab size (tabstop).

4

Try something like this:

function! TabMaybeIndent()
    if strpart(getline('.'), 0, col('.') - 1) =~ '^\s*$'
        return "\<Tab>"
    else
        return "    "
    endif
endfunction

set noexpandtab
imap <Tab> <C-r>=TabMaybeIndent()<CR>
1
  • This looks like a reasonable approach. With minor adjustments, you could even follow the current softtabstop setting instead of blindly inserting 4 spaces.
    – ephemient
    Commented Jul 20, 2009 at 2:37

Not the answer you're looking for? Browse other questions tagged or ask your own question.