Python的.vimrc配置

19 投票
6 回答
33311 浏览
提问于 2025-04-15 14:50

我现在的 .vimrc 配置如下:

set nohlsearch
set ai
set bg=dark
set showmatch
highlight SpecialKey ctermfg=DarkGray
set listchars=tab:>-,trail:~
set list
autocmd BufRead *.py set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class
set tabstop=4
set shiftwidth=4
set expandtab
set autoindent
set smartindent
syntax on
set listchars=tab:>-
set listchars+=trail:.
set ignorecase
set smartcase
map <C-t><up> :tabr<cr>
map <C-t><down> :tabl<cr>
map <C-t><left> :tabp<cr>
map <C-t><right> :tabn<cr>

但是,当我写 Python 脚本时,每当我按下 "ENTER" 键,它就会跳到下一行的开头。我该添加什么内容才能让它自动缩进呢?

6 个回答

7

可以看看官方的 .vimrc 文件,它遵循了 PEP 7 和 PEP 8 的规范。你可以在这里找到它。

http://svn.python.org/projects/python/trunk/Misc/Vim/vimrc

15

试试这个:

filetype indent on
filetype on
filetype plugin on

我主要做Python编程,这就是我vimrc的核心内容。

set nobackup
set nowritebackup
set noswapfile
set lines=40
set columns=80
set tabstop=4
set shiftwidth=4
set softtabstop=4
set autoindent
set smarttab
filetype indent on
filetype on
filetype plugin on
12

简单来说,你的自动命令(autocmd)缺少了 BufEnter 这个触发器,所以在你创建新文件时它没有被执行。你可以试试这样:

 au BufEnter,BufRead *.py setlocal smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class

注意,我还把 set 改成了 setlocal。这样做可以防止这些选项影响到你其他文件的设置。

想要正确实现你想做的事情,应该在你的 .vimrc 文件中添加 filetype indent on。这样可以开启基于文件类型的自动缩进。Vim 自带对 Python 的缩进支持。想了解更多信息,可以查看 :help filetype-indent-on

撰写回答