使用vim自动延伸python else语句

时间:2013-12-06 15:28:25

标签: python vim

中,我想编写以下代码:

def a():
    if a: pass
    elif b: pass
    else: pass

我使用autoindenting,但代码将缩进为:

def a():
    if a: pass
    elif b: pass
else: pass

自动缩进else语句是错误的。我该如何解决这个问题?

请注意,以下代码段正确缩进:

def a():
    if a: pass
    else: pass

这是我的完整.vimrc

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => General
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Sets how many lines of history VIM has to remember
set history=700

" Enable filetype plugins
filetype plugin on
filetype indent on

" Set to auto read when a file is changed from the outside
set autoread

" With a map leader it's possible to do extra key combinations
" like <leader>w saves the current file
let mapleader = ","
let g:mapleader = ","

" Fast saving
nmap <leader>w :w!<cr>

inoremap jj <ESC>
noremap <leader>q :qa<cr>

""" Bash shortcut
set shell=bash\ --rcfile\ ~/.vimbashrc
noremap <leader>bh :shell<cr>

noremap <leader><cr> @:
nmap <leader>bc <Plug>Kwbd
""" Replace grep command with user function smartgrep as old grep doesn't support --exclude-dir option
noremap <leader>gr :!bash -c ". ~/.alias; smartgrep "
"noremap <leader>gr :!grep -ir --color --exclude="*\.svn/*" --exclude="*obj/"
noremap <leader>nt :NERDTreeToggle<cr>

""" Open the python interpreter
noremap <leader>py :!python<cr>

""" Check for differences between file in buffer and on disk
command Wdiff :w !diff -u % -

let g:yankring_history_dir='$HOME/.vim/temp'
let MRU_File=expand('$HOME/.vim/temp/mru.txt')

set nocompatible    " Use Vim defaults instead of 100% vi compatibility
" modelines have historically been a source of security/resource
" vulnerabilities -- disable by default, even when 'nocompatible' is set
set nomodeline

" Set this, so the background color will not change inside tmux (http://snk.tuxfamily.org/log/vim-256color-bce.html)
set t_ut=

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => VIM user interface
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Set 12 lines to the cursor - when moving vertically using j/k
set so=8

" Turn on the WiLd menu
set wildmenu
set wildmode=list:longest

" Suffixes that get lower priority when doing tab completion for filenames.
" These are files we are not likely to want to edit or read.
set suffixes=.bak,~,.swp,.o,.info,.aux,.log,.dvi,.bbl,.blg,.brf,.cb,.ind,.idx,.ilg,.inx,.out,.toc

" Ignore compiled files
set wildignore=*.o,*~,*.pyc
if has("win16") || has("win32")
    set wildignore+=*/.git/*,*/.hg/*,*/.svn/*,*/.DS_Store
else
    set wildignore+=.git\*,.hg\*,.svn\*
endif

"Always show current position
set ruler

" Height of the command bar
set cmdheight=2

" A buffer becomes hidden when it is abandoned
set hid

" Configure backspace so it acts as it should act
set backspace=eol,start,indent
set whichwrap+=<,>,h,l

" Ignore case when searching
set ignorecase

" When searching try to be smart about cases 
set smartcase

" Highlight search results
set hlsearch

" Makes search act like search in modern browsers
set incsearch 

" Don't redraw while executing macros (good performance config)
set lazyredraw 

" For regular expressions turn magic on
set magic

" Show matching brackets when text indicator is over them
set showmatch 
" How many tenths of a second to blink when matching brackets
set mat=2

" No annoying sound on errors
set noerrorbells
set novisualbell
set vb t_vb=
set tm=500

" Add a bit extra margin to the left
set foldcolumn=1


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Colors and Fonts
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Enable syntax highlighting
syntax enable 

""" Use peaksea as graphical highlighting
""" When activating 256 colors, no bold fonts are shown
set t_Co=256 

" feel free to choose :set background=light for a different style 
set background=dark 
colors peaksea

""" Show line numbers
set number

""" Use mouse for all (a)
set mouse=a

" Set utf8 as standard encoding and en_US as the standard language
set encoding=utf8

" Use Unix as the standard file type
set ffs=unix,dos,mac

" Set colors for tabbar
hi TabLineFill ctermbg=240
hi TabLine ctermbg=22
hi TabLineSel ctermbg=58

"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Files, backups and undo
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Turn backup off, since most stuff is in SVN, git etc anyway...
set nobackup
set nowb
set noswapfile


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Text, tab and indent related
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Use spaces instead of tabs
set expandtab

" Be smart when using tabs ;)
set smarttab

" 1 tab == 4 spaces
set shiftwidth=4
set tabstop=4

" Linebreak on 160 characters
set lbr
set tw=160

set ai "Auto indent
"set si "Smart indent
set cindent
set wrap "Wrap lines

map <leader>tn :tabnew<CR>
map <leader>tc :tabclose<CR>
map <leader>1 1gt
map <leader>2 2gt
map <leader>3 3gt
map <leader>4 4gt
map <leader>5 5gt
map <leader>6 6gt
map <leader>7 7gt
map <leader>8 8gt
map <leader>9 9gt
map <leader>0 10gt

""""""""""""""""""""""""""""""
" => Visual mode related
""""""""""""""""""""""""""""""
" Visual mode pressing * or # searches for the current selection
" Super useful! From an idea by Michael Naumann
vnoremap <silent> * :call VisualSelection('f', '')<CR>
vnoremap <silent> # :call VisualSelection('b', '')<CR>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Moving around, tabs, windows and buffers
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Treat long lines as break lines (useful when moving around in them)
map j gj
map k gk


" Smart way to move between windows (deactivated as I use those shortcuts in tmux)
"map <C-j> <C-W>j
"map <C-k> <C-W>k
"map <C-h> <C-W>h
"map <C-l> <C-W>l

" Specify the behavior when switching between buffers 
try
  set switchbuf=useopen,usetab,newtab
  set stal=2
catch
endtry

" Return to last edit position when opening files (You want this!)
autocmd BufReadPost *
     \ if line("'\"") > 0 && line("'\"") <= line("$") |
     \   exe "normal! g`\"" |
     \ endif
" Remember info about open buffers on close
set viminfo^=%


""""""""""""""""""""""""""""""
" => Status line
""""""""""""""""""""""""""""""
" Always show the status line
set laststatus=2


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Editing mappings
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Delete trailing white space on save, useful for Python and CoffeeScript ;)
func! DeleteTrailingWS()
  exe "normal mz"
  %s/\s\+$//ge
  exe "normal `z"
endfunc
autocmd BufWrite *.py :call DeleteTrailingWS()


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Spell checking
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Pressing ,ss will toggle and untoggle spell checking
map <leader>ss :setlocal spell!<cr>

" Shortcuts using <leader>
map <leader>sn ]s
map <leader>sp [s
map <leader>sa zg
map <leader>s? z=


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Misc
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" Quickly open a buffer for scribble
map <leader>bu :e ~/Downloads/vim-buffer<cr>
noremap <leader>ch :!evince ~/Pictures/vi-vim-cheat-sheet.gif &<cr><cr>
map <leader>to :tabnew ~/notes/todo<cr>
map <leader>pr :!evince 201*.pdf<cr>


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Turn persistent undo on 
"    means that you can undo even when you close a buffer/VIM
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
try
    set undodir=~/.vim/temp_dirs/undodir
    set undofile
catch
endtry


"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Programming
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
noremap <leader>tl :TlistToggle<cr>:wincmd j<cr>:wincmd l<cr> 
noremap <leader>al :A<cr>

""" Path (command) to ctags
let Tlist_Ctags_Cmd = "ctags"
"let Tlist_WinWidth = 50

""" This command builds (updates) the ctags file for the SusyNt project, it can be enhanced (or split) later to account for other projects
map <leader>tu :!ctags -R --sort=1 --c++-kinds=+p --fields=+iaS --extra=+q --language-force=C++ --exclude=.svn -f ~/.vim/ctags/SusyNt ~/SusyNt/SusyNtuple/Root/ ~/SusyNt/SusyNtuple/SusyNtuple/<cr><cr>
set tags=~/.vim/ctags/SusyNt

""" Taglist should be on the right to not interfere with NERDTree
let Tlist_Use_Right_Window = 1

""" Define paths for alternate to look for its partner files (sfr means the path is relative)
let g:alternateSearchPath = 'sfr:.,sfr:../source,sfr:../src,sfr:../include,sfr:../Root,sfr:../inc,sfr:../HistFitterTree,sfr:../MultiLep,sfr:../SusyNtuple'

""" If there is no partner file, do nothing
let g:alternateNoDefaultAlternate = 1 

""" Taglist gets updated when saving
autocmd BufWritePost * :TlistUpdate

set makeprg=./vim-make
""" make and jump to warning/error if any
map <leader>m :make<cr>
""" make without jump to warning/error
map <leader>n :make!<cr>



"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
" => Sessions
"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""
function! RestoreSession()
    if argc() == 0 "vim called without arguments
        execute 'source .Session.vim'
   end
endfunction

autocmd VimEnter * call RestoreSession()
autocmd VimLeave * :mksession! .Session.vim

" Store foldings
au BufWinLeave ?* mkview
au BufWinEnter ?* silent loadview

"From http://vim.1045645.n5.nabble.com/Custom-tabline-Non-gui-vim-td1190544.html
"if exists("+guioptions") 
"        set go-=a go-=e go+=tc 
"        " remove a  no autoselect to * register 
"        " remove e  always use text-style tabs 
"        " add    t  include tearoff menu items if possible 
"        " add    c  avoid popup dialogs for small choices 
"endif 

" define our text-style tabline 
" this is adapted (with some enhancements) from the example 
" at :help setting-tabline 
if exists("+showtabline") 
     function MyTabLine() 
         let s = '' 
         let t = tabpagenr() 
         let i = 1 
         while i <= tabpagenr('$') 
             let buflist = tabpagebuflist(i) 
             let winnr = tabpagewinnr(i) 
             let s .= '%' . i . 'T' 
             let s .= (i == t ? '%1*' : '%2*') 
             let s .= ' ' 
             let s .= i . ':' 
"             let s .= winnr . '/' . tabpagewinnr(i,'$') 
             let s .= ' %*' 
             let s .= (i == t ? '%#TabLineSel#' : '%#TabLine#') 
             let file = bufname(buflist[winnr - 1]) 
             let file = fnamemodify(file, ':p:t') 
             if file == '' 
                 let file = '[No Name]' 
             endif 
             "let s .= file 
             let s .= (getbufvar(buflist[winnr - 1], "&mod")?'+ ':'')
             let s .= file
             let s .= (getbufvar(buflist[winnr - 1], "&mod")?' +':'')
             let i = i + 1
         endwhile
         let s .= '%T%#TabLineFill#%=' 
         let s .= (tabpagenr('$') > 1 ? '%999XX' : 'X') 
         return s 
     endfunction 
     set stal=2 
     set tabline=%!MyTabLine() 
"   map     <F10>    :tabnext<CR> 
"   map!    <F10>    <C-O>:tabnext<CR> 
"   map     <S-F10>  :tabprev<CR> 
"   map!    <S-F10>  <C-O>:tabprev<CR> 
endif 

2 个答案:

答案 0 :(得分:2)

Vim这样做是因为你的代码不是惯用的,所以它做出了正确的假设。问题在于将pass(或任何其他表达式)放在同一行上。如果你把它们放在新的线上,这不会发生。事实上,vim可能期望(或隐含地试图鼓励)PEP-008这是Python的风格指南。我在那里链接的部分(到最后)准确地说明了你所遇到的问题,而不是如何让vim屈服于你的意愿。

我会假设您不关心编写惯用的Python,并回答您的问题:

在安装了vim的非可执行文件的目录中,您将找到一个名为indent的目录,其中您将找到一个名为python.vim的文件。

line 168上,您会看到默认情况下会自动为您排队。如果前一行是以iffortry语句开头的“单行”,则不会这样做。

您可以制作自己的,或者您可以向vim提交修复,但没有设置供您在此期间使用。 “修复”将复制文件并应用您的更改,然后告诉vim使用它。

答案 1 :(得分:1)

我认为这是Vim版本中包含的indent/python.vim文件中的一个错误。

要检查它,请将文件从$VIMRUNTIME/indent/python.py复制到您的家庭vim目录(例如$HOME/.vim/indent/python.py)并查找以下段落(靠近文件末尾):

    " Unless the previous line was a one-liner
    if getline(plnumstart) =~ '^\s*\(for\|if\|try\)\>'
      return plindent
    endif

更改条件以检查关键字elif

    " Unless the previous line was a one-liner
    if getline(plnumstart) =~ '^\s*\(for\|if\|elif\|try\)\>'
      return plindent
    endif

重启Vim并完成!