Diff for "UltimateVimPythonSetup"

Not logged in - Log In / Register

Differences between revisions 2 and 4 (spanning 2 versions)
Revision 2 as of 2009-08-04 15:59:01
Size: 4705
Comment:
Revision 4 as of 2009-08-04 16:44:18
Size: 5025
Comment:
Deletions are marked like this. Additions are marked like this.
Line 10: Line 10:

" This beauty remembers where you were the last time you edited the file, and returns to the same position.
au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif
Line 54: Line 57:
" The next three match commands don't work when executed from this file,
" but work fine when pasted into vim itself. Any ideas on WTF is wrong
" are welcome!
Line 58: Line 65:
" Show long lines. This does not work - suggestions anyone? " Show long lines.
Line 62: Line 69:
" Highlight bzr merge markers.  Not sure if this works. " Highlight bzr merge markers.

Configuration for setting up Vim to work with PythonStyleGuide

Here's a complete vimrc file that you can use. To call it add these lines to your ~/.vimrc:

if !exists("autocommands_loaded")
  let autocommands_loaded = 1
  autocmd BufRead,BufNewFile,FileReadPost *.py source ~/.vim/python
endif

" This beauty remembers where you were the last time you edited the file, and returns to the same position.
au BufReadPost * if line("'\"") > 0|if line("'\"") <= line("$")|exe("norm '\"")|else|exe "norm $"|endif|endif

And then create the ~/.vim/python file as below. A summary of what it does:

  • Set indent to 4 spaces with no tabs and wrapping at 78 columns.
  • Enable extra syntax highlighting
  • Smart indenting after some Python keywords
  • Autocompletion of keywords with ctrl-space. It will even offer a list of class methods/properties (very, very cool feature).
  • Press shift-k to see documentation for the keyword under the cursor.
  • Make comments wrap at 72 chars.
  • Highlight end of line whitespace.
  • Put the cursor on an import, type gf and it jumps to the file.

  • Sets up ctags (for more completion options)
  • :make will show syntax errors
  • Highlight some code (shift-v) and ctrl-h executes it.
  • F7/shift-F7 adds/removes breakpoints for pdb (really nice!)

" The magical turn-Vim-into-a-Python-IDE vim resource file!
"
" Mostly taken from http://www.sontek.net/category/Vim.aspx
" Other bits culled from various sources, Canonical guys, or made up by me.
"
" Julian Edwards 2008-05-30

" Wrapping and tabs.
set tw=78 ts=4 sw=4 sta et sts=4 ai

" More syntax highlighting.
let python_highlight_all = 1

" Smart indenting
set smartindent cinwords=if,elif,else,for,while,try,except,finally,def,class

" Auto completion via ctrl-space (instead of the nasty ctrl-x ctrl-o)
set omnifunc=pythoncomplete#Complete
inoremap <Nul> <C-x><C-o>

" Get this plugin from http://www.vim.org/scripts/script.php?script_id=1112
" Pressing "K" takes you to the documentation for the word under the cursor.
autocmd filetype python source ~/.vim/pydoc.vim

" Wrap at 72 chars for comments.
set formatoptions=cq textwidth=72 foldignore= wildignore+=*.py[co]

" The next three match commands don't work when executed from this file,
" but work fine when pasted into vim itself.  Any ideas on WTF is wrong
" are welcome!

" Highlight end of line whitespace.
highlight WhitespaceEOL ctermbg=red guibg=red
match WhitespaceEOL /\s\+$/

" Show long lines.
highlight LongLine guibg=red ctermbg=red
match LongLine /\%>79v.\+/

" Highlight bzr merge markers.
highlight MergeMarker guibg=red ctermbg=red
match MergeMarker /^[<=>\|]\{7\}\( [A-Z]\+\)?$/

" `gf` jumps to the filename under the cursor.  Point at an import statement
" and jump to it!
python << EOF
import os
import sys
import vim
for p in sys.path:
    if os.path.isdir(p):
        vim.command(r"set path+=%s" % (p.replace(" ", r"\ ")))
EOF

" Generate tags with: ctags -R -f ~/.vim/tags/python24.ctags /usr/lib/python2.4/
" ctrl-[ to go to the tag under the cursor, ctrl-T to go back.
set tags+=$HOME/.vim/tags/python24.ctags

" Use :make to see syntax errors. (:cn and :cp to move around, :dist to see
" all errors)
set makeprg=python\ -c\ \"import\ py_compile,sys;\ sys.stderr=sys.stdout;\ py_compile.compile(r'%')\"
set efm=%C\ %.%#,%A\ \ File\ \"%f\"\\,\ line\ %l%.%#,%Z%[%^\ ]%\\@=%m

" Execute a selection of code (very cool!)
" Use VISUAL to select a range and then hit ctrl-h to execute it.
python << EOL
import vim
def EvaluateCurrentRange():
    eval(compile('\n'.join(vim.current.range),'','exec'),globals())
EOL
map <C-h> :py EvaluateCurrentRange()

" Use F7/Shift-F7 to add/remove a breakpoint (pdb.set_trace)
" Totally cool.
python << EOF
def SetBreakpoint():
    import re
    nLine = int( vim.eval( 'line(".")'))

    strLine = vim.current.line
    strWhite = re.search( '^(\s*)', strLine).group(1)

    vim.current.buffer.append(
       "%(space)spdb.set_trace() %(mark)s Breakpoint %(mark)s" %
         {'space':strWhite, 'mark': '#' * 30}, nLine - 1)

    for strLine in vim.current.buffer:
        if strLine == "import pdb":
            break
    else:
        vim.current.buffer.append( 'import pdb', 0)
        vim.command( 'normal j1')

vim.command( 'map <f7> :py SetBreakpoint()<cr>')

def RemoveBreakpoints():
    import re

    nCurrentLine = int( vim.eval( 'line(".")'))

    nLines = []
    nLine = 1
    for strLine in vim.current.buffer:
        if strLine == "import pdb" or strLine.lstrip()[:15] == "pdb.set_trace()":
            nLines.append( nLine)
        nLine += 1

    nLines.reverse()

    for nLine in nLines:
        vim.command( "normal %dG" % nLine)
        vim.command( "normal dd")
        if nLine < nCurrentLine:
            nCurrentLine -= 1

    vim.command( "normal %dG" % nCurrentLine)

vim.command( "map <s-f7> :py RemoveBreakpoints()<cr>")
EOF

UltimateVimPythonSetup (last edited 2021-11-11 09:59:07 by cjwatson)