pythonvimindentationauto-indent

Convert entire (Python) file from 2-space indent to 4-space indent


I regularly work with Python files that are provided to me as templates, which use an indentation of 2. However, I personally prefer working with an indentation width of 4, which is what I've set in my .vimrc. However, because of the indentation-sensitivity of Python, the typical gg=G way to fix indentation to my preferred indentation width does not work well at all to convert a file to my preferred indentation. Furthermore, just leaving the indentation at a width of 2 screws up with my tabstop settings.

To fix this, what I'd like to do is have some system to convert a 2-space indented file into a 4-space indented file. I don't know what the easiest way to do this would be, but I'm thinking to vmap <Tab> to increase the tab width of the selected lines by 1, and vmap <S-Tab> to decrease the width by 1. I don't know if there is some built-in method to do this, or if this would require some find/replace rule, but I think having some way to fix the indentation to my preferred width would be useful, given that the autoindent is not smart enough to fix this properly.


Solution

  • In vim:

    " Convert 2-spaces indent to tabs
    :set noexpandtab tabstop=2
    :retab!
    
    " Convert tabs to 4-spaces indent
    :set expandtab tabstop=4
    :retab