简体   繁体   中英

vim - python autoindent not working correctly when set in .vimrc

I am having issues with my .vimrc file: I am correctly writing python code. But I have indentation issue. When I put is in my .vimrc file:

" indentation python
au BufNewFile,BufRead *.py
    \ set tabstop=4
    \ set softtabstop=4
    \ set shiftwidth=4
    \ set textwidth=79
    \ set expandtab
    \ set ts=4
    \ set sw=4
    \ set ai
    \ set autoindent
    \ set fileformat=unix
    \ set expandtab ts=4 sw=4 ai

But as soon as a python file is open, if I run set expandtab ts=4 sw=4 ai vim will start-indent correctly when select code and hit S-= . Any idea?

This is not a valid syntax in Vim. \\ only cancels the newline, it does not let you chain commands (you have | for that). What you wrote is equivalent to (truncated to just a subset of your options):

au BufNewFile,BufRead *.py set tabstop=4 set softtabstop=4 set shiftwidth=4 set textwidth=79

which obviously doesn't make sense, since set is not a valid option.

So you can either do

au BufNewFile,BufRead *.py
  \ set tabstop=4
  \     softtabstop=4
  \     shiftwidth=4
  \     textwidth=79

(make it a single set command with multiple settings), or you can do

au BufNewFile,BufRead *.py
    \ set tabstop=4 |
    \ set softtabstop=4 |
    \ set shiftwidth=4 |
    \ set textwidth=79

(make it multiple set commands).

However, this is bad practice, since the options will be set globally; eg if you load a JavaScript file then a Python file, then go back to your JavaScript buffer it will have your Python settings. You should prefer to use setlocal instead.

Also, it generally makes sense to use FileType python instead of BufNewFile,BufRead *.py - maybe not specifically in Python's case, but some languages can have multiple extensions.

And finally, this allows you to clean up your .vimrc by placing your language-dependent settings in .vim/after/ftplugin/python.py . You don't need autocmd there - just write your setlocal , and be secure in the knowledge that your settings will be executed for each buffer of python filetype.

Thus, my final recommendation:

" .vim/after/ftplugin/python.py
setlocal tabstop=4
setlocal softtabstop=4
setlocal shiftwidth=4
setlocal textwidth=79
setlocal expandtab
setlocal autoindent
setlocal fileformat=unix

or equivalently

" .vim/after/ftplugin/python.py
setlocal ts=4 sts=4 sw=4 tw=79 et ai ff=unix

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM