2
votes

Is it possible to make VIM use spaces for tabs, when the cursor has non-whitespace characters before it?

eg:

(Assuming TAB is --->, is a space.)

--->function(arg);••••••/* comment */
    //            ^ use spaces when pressing TAB after non-whitespace chars.

Otherwise I want real tabs when pressing tab.

This is useful when tabs are used for initial indentation, but the alignment for all text after uses spaces.

2

2 Answers

2
votes

This is not possible to do automatically without scripting or a plugin.

The "Smart Tabs" plugin was designed for this task. http://www.vim.org/scripts/script.php?script_id=231

To make the problem happen a little less frequently there are the built-in preserveindent and copyindent options to prevent losing your existing tab indent when expandtab is set.

1
votes

Use :set expandtab.
This will expand all tabs to spaces, during insert, even the ones at the beginning of the line (which probably is the best).
Use CTRL-V<Tab> to insert a tab.

From vim help (:help expandtab)

'expandtab' 'et'        boolean (default off)
                        local to buffer
                        {not in Vi}
        In Insert mode: Use the appropriate number of spaces to insert a
        <Tab>.  Spaces are used in indents with the '>' and '<' commands and
        when 'autoindent' is on.  To insert a real tab when 'expandtab' is
        on, use CTRL-V<Tab>.  See also :retab and ins-expandtab.
        NOTE: This option is reset when 'compatible' is set.

Use :set shiftwidth=4 (or :set shiftwidth=8) to control how many spaces are added per indent.

'shiftwidth' 'sw'       number  (default 8)
                        local to buffer
        Number of spaces to use for each step of (auto)indent.  Used for
        'cindent', >>, <<, etc.

Other settings of interest are softtabstop, tabstop and autoindent.