2

This question already has an answer here:

I like to use tabs for indentation (hey, don't bully me!). But 33% of other programmers prefer spaces.

The norm with Python is to use spaces for indetation. Even so, I configured Vim to use tabs with Python since I recently worked on Python code that was indented with tabs. But right now I'm working on some other Python project which has spaces for indentation...

So now I want to make Vim figure out which kind of indentation the file uses and indent accordingly. So my question is how can I accomplish that?

I discovered the copyindent option, which seems to solve the problem. But I am unsure whether this is the correct way to solve the problem. Does it have any pitfall? Is there a better way to do this?


For the sake of completeness, these are the contents of my .vim/after/ftplugin/python.vim file, which is the one ensuring tabs are used for Python right now. I also have filetype plugin indent on in my .vimrc.

setlocal tabstop=4
setlocal softtabstop=4
setlocal shiftwidth=4
setlocal textwidth=80
setlocal smarttab
setlocal noexpandtab

marked as duplicate by Martin Tournoij Dec 17 '15 at 13:43

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

  • It depends somewhat on how robust you want this indentation detection to be. A simple solution would be to assume that leading tabs exist in a file only if tabs are used for indentation. Then you could do something simple like if search('^\t', 'wn') | setlocal noexpandtab | else | setlocal expandtab | endif, where you could replace those |s by newlines in your plugin. – garyjohn Oct 23 '15 at 23:42
  • 6
    Tim Pope had the same problem, and came up with a solution. – Sato Katsura Oct 24 '15 at 9:32
  • @SatoKatsura, I installed sleuth.vim and have been using it. It seems to work really well. Please consider writing an answer. – Gonçalo Ribeiro Nov 4 '15 at 1:57
  • 1
    @GonçaloRibeiro And then have a moderator chastise me for posting a "link-only answer" and asking me to "summarise the link"? Thanks, but no thanks. To be fair, I haven't seen that happen on Vi and Vim yet, but there are a few trigger-happy, rabidly anti-links moderators on Stack Overflow. Caveat emptor. – Sato Katsura Nov 4 '15 at 5:32
  • As a fellow Pythonic tab-lover, a little heads-up: newer version of Vim need autocmd FileType python setlocal ts=4 sts=4 sw=4 noexpandtab, as ftplugin/python.vim overwrites this. I sent a message to the mailinglist about this, but it didn't get changed, so well :-/ – Martin Tournoij Dec 17 '15 at 13:46