Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid indentation error after changing tab stops in Vim?

Tags:

vim

vi

I used to have 8-space tabs in Vim. Then I changed to 4 spaces, but now whenever I add a line to some code I had written before changing to 4 spaces, it gives me an indentation mismatch error even though everything is lining up nicely. Is there any way to avoid this problem?

like image 472
rick Avatar asked Nov 29 '22 05:11

rick


2 Answers

Have you done a :%retab ...?

like image 147
Alex Martelli Avatar answered Jan 18 '23 22:01

Alex Martelli


Have you changed just the tabstop option?

I use 4 spaces (fill with spaces when I hit tab, to insert actual tab hit ctrl-v tab). Here are the tab related settings from .vimrc:

" tabs
set tabstop=4
set shiftwidth=4
set expandtab

When you fill tab with spaces you will always insert spaces instead of tab and your code will always look the same.

When you use tabs each tool displays tab differently and you end up spending your time setting up how many spaces should be displayed for tab (8,4,3.5) instead of doing productive work.

Or choose one of these (from vim 7.1 help tabstop):

    Note: Setting 'tabstop' to any other value than 8 can make your file
    appear wrong in many places (e.g., when printing it).


    There are four main ways to use tabs in Vim:
    1. Always keep 'tabstop' at 8, set 'softtabstop' and 'shiftwidth' to 4
       (or 3 or whatever you prefer) and use 'noexpandtab'.  Then Vim
       will use a mix of tabs and spaces, but typing <Tab> and <BS> will
       behave like a tab appears every 4 (or 3) characters.
    2. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use
       'expandtab'.  This way you will always insert spaces.  The
       formatting will never be messed up when 'tabstop' is changed.
    3. Set 'tabstop' and 'shiftwidth' to whatever you prefer and use a
       |modeline| to set these values when editing the file again.  Only
       works when using Vim to edit the file.
    4. Always set 'tabstop' and 'shiftwidth' to the same value, and
       'noexpandtab'.  This should then work (for initial indents only)
       for any tabstop setting that people use.  It might be nice to have
       tabs after the first non-blank inserted as spaces if you do this
       though.  Otherwise aligned comments will be wrong when 'tabstop' is
       changed.
like image 40
stefanB Avatar answered Jan 19 '23 00:01

stefanB