如何为编辑Python文件正确设置Vim自动缩进?

96 投票
8 回答
137882 浏览
提问于 2025-04-11 09:20

我在设置Vim(7.1.xxx)来编辑Python文件(*.py)时遇到了问题。缩进好像不太正常(理想的缩进是4个空格)。我按照网上找到的一些教程去做,但还是没有效果 :/ 请帮帮我。

8 个回答

15

一个更简单的办法就是:把 /etc/vim/vimrc 文件中下面这部分配置的注释去掉(原本是被注释掉的)。

    if has("autocmd")
      filetype plugin indent on
    endif
15

我使用的是:

$ cat ~/.vimrc
syntax on
set showmatch
set ts=4
set sts=4
set sw=4
set autoindent
set smartindent
set smarttab
set expandtab
set number

不过,我打算试试Daren的方案。

86

我在我的MacBook上使用这个:

" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set expandtab
au BufRead,BufNewFile *.h set expandtab
au BufRead,BufNewFile Makefile* set noexpandtab

" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab           " enter spaces when tab is pressed
set textwidth=120       " break lines when line length increases
set tabstop=4           " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4        " number of spaces to use for auto indent
set autoindent          " copy indent from current line when starting a new line

" make backspaces more powerfull
set backspace=indent,eol,start

set ruler               " show line and column number
syntax on               " syntax highlighting
set showcmd             " show (partial) command in status line

(编辑过,只显示与缩进/制表符相关的内容)

撰写回答