python-else语句的vim自动缩进

2024-05-16 15:05:26 发布

您现在位置:Python中文网/ 问答频道 /正文

中,我想编写以下代码:

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

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

^{pr2}$

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 

Tags: thetomapforifonvimfile
2条回答

Vim这样做是因为您的代码不是惯用的,所以它会做出其他正确的假设。问题在于将pass(或任何其他表达式)放在同一行上。如果你把它们放在新的线路上,这是不会发生的。事实上,vim可能期望(或者隐含地试图鼓励)PEP-008,这是Python的风格指南。我在那里链接的部分(接近结尾)确切地讨论了你所面临的问题,但不是如何让维姆屈从于你的意愿。在

不过,我假设您不关心编写惯用的Python,然后回答您的问题:

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

line 168上,您将看到默认情况下它会自动为您删除该行。只有当前一行是以iffor、或try语句开头的“一行代码”时,它才不会这样做。在

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

我认为这是Vim发行版附带的indent/python.vim文件中的一个bug。在

要检查它,请将文件从$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的情况:

^{pr2}$

重新启动Vim并完成!在

相关问题 更多 >