From: stack Date: Wed, 17 Oct 2012 20:42:33 +0000 (+0200) Subject: new config, more plugins divided per file type and config cleaning X-Git-Url: https://v.licheni.net/stack/conf/vim.git/commitdiff_plain/e3a81b6e6b87654168e0aba4a4d3a1d854ba5c58?ds=sidebyside new config, more plugins divided per file type and config cleaning --- diff --git a/.gitmodules b/.gitmodules index 65c480d..bbe1632 100644 --- a/.gitmodules +++ b/.gitmodules @@ -34,3 +34,9 @@ [submodule "addons/Vim-R-plugin"] path = addons/Vim-R-plugin url = git://github.com/jcfaria/Vim-R-plugin +[submodule "addons/supertab"] + path = addons/supertab + url = https://github.com/ervandew/supertab.git +[submodule "addons/The_NERD_tree"] + path = addons/The_NERD_tree + url = git://github.com/scrooloose/nerdtree diff --git a/.vimrc b/.vimrc index 6de923f..a03fc2c 100644 --- a/.vimrc +++ b/.vimrc @@ -8,7 +8,8 @@ set cf " enable error files and error jumping set ffs=unix,dos,mac " support all three, in this order set viminfo+=! " make sure it can save viminfo set isk+=_,@,- " none of these should be word dividers, so make them not be -set nobackup " real man don't use backups ;) +set nobackup + """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Theme/Colors """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" @@ -25,7 +26,7 @@ colorscheme desert """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" set wildmenu " turn on wild menu set ruler " Always show current positions along the bottom -"set number " turn on line numbers +set number " turn on line numbers set lz " do not redraw while running macros (much faster) (LazyRedraw) set hid " you can change buffer without saving set backspace=2 " make backspace work normal @@ -40,13 +41,12 @@ set fillchars=vert:\ ,stl:\ ,stlnc:\ """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" set showmatch " show matching brackets set mat=5 " how many tenths of a second to blink matching brackets for -set nohlsearch " do not highlight searched for phrases -set incsearch " BUT do highlight as you type you search phrase +set hlsearch " highlight searched for phrases +set incsearch " do highlight as you type you search phrase set listchars=tab:\|\ ,trail:.,extends:>,precedes:<,eol:$ " what to show when I hit :set list set so=10 " Keep 10 lines (top/bottom) for scope set novisualbell " don't blink set noerrorbells " no noises -"set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [ASCII=\%03.3b]\ [HEX=\%02.2B]\ [POS=%04l,%04v][%p%%]\ [LEN=%L] set statusline=%F%m%r%h%w\ [FORMAT=%{&ff}]\ [TYPE=%Y]\ [POS=%04l,%04v][%p%%] set laststatus=2 " always show the status line @@ -58,12 +58,10 @@ set si " smartindent set tabstop=4 " tab spacing (settings below are just to unify it) set softtabstop=4 " unify set shiftwidth=4 " unify -set expandtab " space instead of tabs please! +set expandtab " space instead of tabs +set smarttab "Use the "shiftwidth" setting for inserting s instead of the "tabstop" setting, when at the beginning of a line. set nowrap " do not wrap lines -autocmd FileType c,cpp,slang set cindent -autocmd FileType c,cpp,slang set textwidth=79 - - + """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Folding " Enable folding, but by default make it act like folding is off, because folding is annoying in anything but a few rare cases @@ -85,6 +83,9 @@ nmap p i imap cmap +" map to clear search +nmap :nohlsearch + " this makes the mouse paste a block of text without formatting it " (good for code) map "*p @@ -121,11 +122,6 @@ let perl_extended_vars=1 " highlight advanced perl vars inside strings """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Custom Functions """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -" Select range, then hit :SuperRetab($width) - by p0g and FallingCow -function! SuperRetab(width) range - silent! exe a:firstline . ',' . a:lastline . 's/\v%(^ *)@<= {'. a:width .'}/\t/g' -endfunction - "switch spellcheck languages let g:myLangList = [ "none", "it", "en_us" ] function! MySpellLang() @@ -148,34 +144,61 @@ endfunction """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " alt-i (normal mode) inserts a single char, and then switches back to normal map i r -map ggVG:call SuperRetab() +" set F4 to toogle number/nonumber +map :set invnumber " encypt the file (toggle) map ggVGg? map :call MySpellLang() -map :TlistOpen +" Map NERDTree show and hide +map :NERDTreeToggle +imap :NERDTreeToggle +" Taglist toggle +map :TlistOpen +imap :TlistClose + + """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Autocommands """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" -autocmd BufEnter * :syntax sync fromstart " ensure every file does syntax highlighting (full) -autocmd BufNewFile *.sh call append(0, "#!/bin/bash") -autocmd BufNewFile *.pl call append(0, "#!/usr/bin/perl") -autocmd BufNewFile *.py call append(0, "#!/bin/python") +if has ("autocmd") + " Enable file type detection ('filetype on'). + " Syntax of these languages is fussy over tabs Vs spaces + autocmd FileType make setlocal ts=8 sts=8 sw=8 noexpandtab + autocmd FileType yaml setlocal ts=2 sts=2 sw=2 expandtab + " Customisations based on house-style (arbitrary) + autocmd FileType html setlocal ts=2 sts=2 sw=2 expandtab + autocmd FileType css setlocal ts=2 sts=2 sw=2 expandtab + " Treat sh correctly + autocmd FileType sh setlocal ts=4 sts=4 sw=4 expandtab + " Treat .rss files as XML + autocmd BufNewFile,BufRead *.rss,*.atom setfiletype xml + + autocmd FileType c,cpp,slang set cindent + autocmd FileType c,cpp,slang set textwidth=79 + + autocmd BufEnter * :syntax sync fromstart " ensure every file does syntax highlighting (full) + autocmd BufNewFile *.sh call append(0, "#!/bin/bash") + autocmd BufNewFile *.pl call append(0, "#!/usr/bin/perl") + autocmd BufNewFile *.py call append(0, "#!/bin/python") + + " When editing a file, always jump to the last known cursor position. + " Don't do it when the position is invalid or when inside an event handler + " (happens when dropping a file on gvim). + autocmd BufReadPost * + \ if line("'\"") > 0 && line("'\"") <= line("$") | + \ exe "normal g`\"" | + \ endif +endif + """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " Useful abbrevs """"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" iab xdate =strftime("%d/%m/%y %H:%M:%S") -" Latex abbrevs -"iab cha \chapter{}i -"iab sub \subsection{} -"iab sec \section{} -"iab ite \item -"iab enu \begin{enumerate}\end{enumerate}O -"iab footn \footnote{} -"iab tabb \begin{tabbing}\end{tabbing}O - -""""""""""""""""""""""""""" +""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +" General configs +""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" set titlestring=%t%(\ %M%)%(\ (%{expand(\"%:~:h\")})%)%(\ %a%)\ -\ %{v:servername} if &term == "screen" set t_ts=^[k @@ -185,29 +208,20 @@ if &term == "screen" || &term == "xterm" set title endif +""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" +" Plugin activation +""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" " vim-addon-manager " -fun SetupVAM() - let addons_base = expand('$HOME') . '/.vim/addons' - exec 'set runtimepath+='.addons_base.'/vim-addon-manager' - - try - - " Plugins that should be always enabled - call vam#ActivateAddons(['surround','checksyntax','snipmate','snipmate-snippets','gnupg','LargeFile','taglist-plus'], {'auto_install' : 0}) - - catch /.*/ - echoe v:exception - endtry -endf -call SetupVAM() - +let vam_install_path = expand('$HOME') . '/.vim/addons' +exec 'set runtimepath+='.vam_install_path.'/vim-addon-manager' " Enable addons with vim-addon-manager using file type recognition let ft_addons = { - \ '^\%(R\|r\)$': [ 'Screen_vim__gnu_screentmux', 'Vim-R-plugin' ], + \ 'always': ['surround', 'checksyntax', 'LargeFile', 'snipmate', 'snipmate-snippets', 'The_NERD_tree'], + \ 'r': [ 'Screen_vim__gnu_screentmux', 'Vim-R-plugin' ], + \ '^\%(c\|cpp\|javascript\|python\|php\|html\|xml\|r\|sh\|css\|java\|make\|xslt\|vim\)$': [ 'taglist-plus' ], + \ 'python': ['pythoncomplete', 'pydoc', 'python%790'], + \ 'gpg': ['gnupg'], \ } +call vam#ActivateAddons(ft_addons['always'], {'auto_install': 1}) au FileType * for l in values(filter(copy(ft_addons), string(expand('')).' =~ v:key')) | call vam#ActivateAddons(l, {'force_loading_plugins_now':1}) | endfor - - - - diff --git a/addons/The_NERD_tree b/addons/The_NERD_tree new file mode 160000 index 0000000..d62180d --- /dev/null +++ b/addons/The_NERD_tree @@ -0,0 +1 @@ +Subproject commit d62180d0ff26d308b815205ca2f2cd651a112b49 diff --git a/addons/pydoc/archive/pydoc.vim b/addons/pydoc/archive/pydoc.vim new file mode 100644 index 0000000..4af9120 --- /dev/null +++ b/addons/pydoc/archive/pydoc.vim @@ -0,0 +1,130 @@ +" pydoc.vim 0.4 (initial public version) +" Allow the user to pull pydoc information into Vim +" Mike Repass +" October 2004 + +" USAGE: +" Put this in ftplugin/python/ or just manually source it using a FileType +" autocommand in your vimrc. It registers the command Pydoc (try ':Pydoc re' +" for regular expression docs). Also, it remaps K so that you can position the +" cursor over a module or module.method etc and hit K to bring up the docs. +" Make sure PYDOC_CMD points to the pydoc script. I use a 'pydoc.bat' batch +" file on my WinXP system. +" +" A nice little side effect of using this is that the documentation buffers +" become sources for keyword completion. For instance, say you're working on a +" program that uses urllib2 and you're having trouble remembering the methods. +" Simply do a ':Pydoc urllib2' and close the window. The buffer will remain +" hidden and Ctrl-N and Ctrl-P will pick up all the text when you need to +" complete. +" +" Btw just doing ':Pydoc modules' should bring up a list of all available +" modules. Very handy just to leave open, as you can now just press 'K' over a +" module to load it up. + +" NOTES: +" The 'cleanest' or most 'pythonic' way to do this would be use the +" vim-python interface and write some supporting python code to manually +" import pydoc and call the associated functions. However, I don't always use +" the version of python for which my vim is compiled, so I decided to +" externally call the pydoc script. Also, it sets up the buffers to go +" 'hidden' when closed, so that when you do the same Pydoc command again, it +" will load the buffer and thus avoid the overhead of the external call +" (basically a cheap cache system). If you don't want this, set the NO_HIDE +" option to 1. + +" BUGS: +" I am not aware of any major bugs, but of course there are some minor +" interface glitches. For instance, if you put the cursor over an operator +" which also has significance in your particular shell, invoking the command +" might result in a shell error. I feel having some little 'oopses' like this +" is pretty inevitable, but I'll be happy to work on anything that causes you +" problems. If you come across any bug you feel impairs your ability to use +" Vim, drop me an email and I'll get right on it. + +" OPTIONS: +let s:PYDOC_CMD = "pydoc" " this must point to the pydoc script +let s:NO_HIDE = 0 " when 1, pydoc buffers will be deleted (instead of hidden) + +" command interface +com! -nargs=+ Pydoc call :PydocLoad("") + +" remap the K (or 'help') key +nnoremap K :call :KeyPydocLoad(expand("")) + +" prepares the cWORD argument for PydocLoad... +func! :KeyPydocLoad(cword) + " make sure we got something + if a:cword == "" + return + endif + " we want the current WORD just up to the first parenthesis + " this allows us to get math.acos from math.acos(.2) etc + let prep = substitute(a:cword, "\(.*", "", "") + call :PydocLoad(prep) +endfunc + +" opens a new buffer, filling it with the result of calling pydoc with pyargs +func! :PydocLoad(pyargs) + " first, check if we've already loaded the pydoc info for this search and + " if so, open it and bail... this creates an ad hoc caching mechanism + let window_name = "pydoc - " . a:pyargs + if bufloaded(window_name) + exec "new " . window_name + return + endif + + " build and execute the command + let cmd = "new +r!" . escape(s:PYDOC_CMD," ") " new buff, call pydoc + let cmd = cmd . "\\ " . escape(a:pyargs," ") " the pydoc args + let cmd = cmd . " " . window_name " the name of the window + try + silent exec cmd + catch + redraw | + \ echohl WarningMSG | + \ echomsg "Error occurred while attempting to invoke Pydoc." | + \ echohl None + return + endtry + + + " make sure the command succeeded and we're in the right buffer + if bufname("") != "pydoc - " . a:pyargs + " hmmm something didn't work... lets bail + return + endif + + " roll back, delete empty lines at beginning + normal gg + while getline(1) =~ "^\s\*$" + normal dd + endwhile + + " set some convenient options to avoid error messages etc + setlocal nomodifiable + setlocal buftype=nowrite + setlocal bufhidden=hide + if s:NO_HIDE + setlocal bufhidden=delete + endif + + " bail if no documentation was found + if getline(1) =~ "^no Python documentation found" + redraw | + \ echohl WarningMsg | + \ echomsg "No Python documentation for " . a:pyargs | + \ echohl None + setlocal bufhidden=delete + quit + return + endif + + " key map to these functions for these buffers + nnoremap K :call :KeyPydocLoad(expand("")) + + " some _very_ basic syntax highlighting + syn match pydocTitle "^[A-Z]\+$" + hi link pydocTitle Tag + +endfunc diff --git a/addons/pydoc/plugin/pydoc.vim b/addons/pydoc/plugin/pydoc.vim new file mode 100644 index 0000000..4af9120 --- /dev/null +++ b/addons/pydoc/plugin/pydoc.vim @@ -0,0 +1,130 @@ +" pydoc.vim 0.4 (initial public version) +" Allow the user to pull pydoc information into Vim +" Mike Repass +" October 2004 + +" USAGE: +" Put this in ftplugin/python/ or just manually source it using a FileType +" autocommand in your vimrc. It registers the command Pydoc (try ':Pydoc re' +" for regular expression docs). Also, it remaps K so that you can position the +" cursor over a module or module.method etc and hit K to bring up the docs. +" Make sure PYDOC_CMD points to the pydoc script. I use a 'pydoc.bat' batch +" file on my WinXP system. +" +" A nice little side effect of using this is that the documentation buffers +" become sources for keyword completion. For instance, say you're working on a +" program that uses urllib2 and you're having trouble remembering the methods. +" Simply do a ':Pydoc urllib2' and close the window. The buffer will remain +" hidden and Ctrl-N and Ctrl-P will pick up all the text when you need to +" complete. +" +" Btw just doing ':Pydoc modules' should bring up a list of all available +" modules. Very handy just to leave open, as you can now just press 'K' over a +" module to load it up. + +" NOTES: +" The 'cleanest' or most 'pythonic' way to do this would be use the +" vim-python interface and write some supporting python code to manually +" import pydoc and call the associated functions. However, I don't always use +" the version of python for which my vim is compiled, so I decided to +" externally call the pydoc script. Also, it sets up the buffers to go +" 'hidden' when closed, so that when you do the same Pydoc command again, it +" will load the buffer and thus avoid the overhead of the external call +" (basically a cheap cache system). If you don't want this, set the NO_HIDE +" option to 1. + +" BUGS: +" I am not aware of any major bugs, but of course there are some minor +" interface glitches. For instance, if you put the cursor over an operator +" which also has significance in your particular shell, invoking the command +" might result in a shell error. I feel having some little 'oopses' like this +" is pretty inevitable, but I'll be happy to work on anything that causes you +" problems. If you come across any bug you feel impairs your ability to use +" Vim, drop me an email and I'll get right on it. + +" OPTIONS: +let s:PYDOC_CMD = "pydoc" " this must point to the pydoc script +let s:NO_HIDE = 0 " when 1, pydoc buffers will be deleted (instead of hidden) + +" command interface +com! -nargs=+ Pydoc call :PydocLoad("") + +" remap the K (or 'help') key +nnoremap K :call :KeyPydocLoad(expand("")) + +" prepares the cWORD argument for PydocLoad... +func! :KeyPydocLoad(cword) + " make sure we got something + if a:cword == "" + return + endif + " we want the current WORD just up to the first parenthesis + " this allows us to get math.acos from math.acos(.2) etc + let prep = substitute(a:cword, "\(.*", "", "") + call :PydocLoad(prep) +endfunc + +" opens a new buffer, filling it with the result of calling pydoc with pyargs +func! :PydocLoad(pyargs) + " first, check if we've already loaded the pydoc info for this search and + " if so, open it and bail... this creates an ad hoc caching mechanism + let window_name = "pydoc - " . a:pyargs + if bufloaded(window_name) + exec "new " . window_name + return + endif + + " build and execute the command + let cmd = "new +r!" . escape(s:PYDOC_CMD," ") " new buff, call pydoc + let cmd = cmd . "\\ " . escape(a:pyargs," ") " the pydoc args + let cmd = cmd . " " . window_name " the name of the window + try + silent exec cmd + catch + redraw | + \ echohl WarningMSG | + \ echomsg "Error occurred while attempting to invoke Pydoc." | + \ echohl None + return + endtry + + + " make sure the command succeeded and we're in the right buffer + if bufname("") != "pydoc - " . a:pyargs + " hmmm something didn't work... lets bail + return + endif + + " roll back, delete empty lines at beginning + normal gg + while getline(1) =~ "^\s\*$" + normal dd + endwhile + + " set some convenient options to avoid error messages etc + setlocal nomodifiable + setlocal buftype=nowrite + setlocal bufhidden=hide + if s:NO_HIDE + setlocal bufhidden=delete + endif + + " bail if no documentation was found + if getline(1) =~ "^no Python documentation found" + redraw | + \ echohl WarningMsg | + \ echomsg "No Python documentation for " . a:pyargs | + \ echohl None + setlocal bufhidden=delete + quit + return + endif + + " key map to these functions for these buffers + nnoremap K :call :KeyPydocLoad(expand("")) + + " some _very_ basic syntax highlighting + syn match pydocTitle "^[A-Z]\+$" + hi link pydocTitle Tag + +endfunc diff --git a/addons/pydoc/version b/addons/pydoc/version new file mode 100644 index 0000000..e6adf3f --- /dev/null +++ b/addons/pydoc/version @@ -0,0 +1 @@ +0.4 \ No newline at end of file diff --git a/addons/python%790/archive/python3.0.vim b/addons/python%790/archive/python3.0.vim new file mode 100644 index 0000000..7383876 --- /dev/null +++ b/addons/python%790/archive/python3.0.vim @@ -0,0 +1,370 @@ +" Vim syntax file +" Language: Python +" Maintainer: Dmitry Vasiliev +" URL: https://github.com/hdima/vim-scripts/blob/master/syntax/python/python3.0.vim +" Last Change: 2012-02-11 +" Filenames: *.py +" Version: 3.0.7 +" +" Based on python.vim (from Vim 6.1 distribution) +" by Neil Schemenauer +" +" Thanks: +" +" Jeroen Ruigrok van der Werven +" for the idea to highlight erroneous operators +" Pedro Algarvio +" for the patch to enable spell checking only for the right spots +" (strings and comments) +" John Eikenberry +" for the patch fixing small typo +" Caleb Adamantine +" for the patch fixing highlighting for decorators +" Andrea Riciputi +" for the patch with new configuration options +" Anton Butanaev +" for the patch fixing bytes literals highlighting +" for the patch fixing str.format syntax highlighting + +" +" Options: +" +" For set option do: let OPTION_NAME = 1 +" For clear option do: let OPTION_NAME = 0 +" +" Option names: +" +" For highlight builtin functions: +" python_highlight_builtins +" +" For highlight builtin objects: +" python_highlight_builtin_objs +" +" For highlight builtin funtions: +" python_highlight_builtin_funcs +" +" For highlight standard exceptions: +" python_highlight_exceptions +" +" For highlight string formatting: +" python_highlight_string_formatting +" +" For highlight str.format syntax: +" python_highlight_string_format +" +" For highlight string.Template syntax: +" python_highlight_string_templates +" +" For highlight indentation errors: +" python_highlight_indent_errors +" +" For highlight trailing spaces: +" python_highlight_space_errors +" +" For highlight doc-tests: +" python_highlight_doctests +" +" If you want all Python highlightings above: +" python_highlight_all +" (This option not override previously set options) +" +" For fast machines: +" python_slow_sync + +" For version 5.x: Clear all syntax items +" For version 6.x: Quit when a syntax file was already loaded +if version < 600 + syntax clear +elseif exists("b:current_syntax") + finish +endif + +if exists("python_highlight_all") && python_highlight_all != 0 + " Not override previously set options + if !exists("python_highlight_builtins") + if !exists("python_highlight_builtin_objs") + let python_highlight_builtin_objs = 1 + endif + if !exists("python_highlight_builtin_funcs") + let python_highlight_builtin_funcs = 1 + endif + endif + if !exists("python_highlight_exceptions") + let python_highlight_exceptions = 1 + endif + if !exists("python_highlight_string_formatting") + let python_highlight_string_formatting = 1 + endif + if !exists("python_highlight_string_format") + let python_highlight_string_format = 1 + endif + if !exists("python_highlight_string_templates") + let python_highlight_string_templates = 1 + endif + if !exists("python_highlight_indent_errors") + let python_highlight_indent_errors = 1 + endif + if !exists("python_highlight_space_errors") + let python_highlight_space_errors = 1 + endif + if !exists("python_highlight_doctests") + let python_highlight_doctests = 1 + endif +endif + +" Keywords +syn keyword pythonStatement break continue del +syn keyword pythonStatement exec return as +syn keyword pythonStatement pass raise +syn keyword pythonStatement global assert +syn keyword pythonStatement lambda yield +syn keyword pythonStatement with nonlocal +syn keyword pythonStatement False None True +syn keyword pythonStatement def class nextgroup=pythonFunction skipwhite +syn match pythonFunction "\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" display contained +syn keyword pythonRepeat for while +syn keyword pythonConditional if elif else +syn keyword pythonPreCondit import from +syn keyword pythonException try except finally +syn keyword pythonOperator and in is not or + +" Decorators (new in Python 2.4) +syn match pythonDecorator "@" display nextgroup=pythonDottedName skipwhite +syn match pythonDottedName "[a-zA-Z_][a-zA-Z0-9_]*\(\.[a-zA-Z_][a-zA-Z0-9_]*\)*" display contained +syn match pythonDot "\." display containedin=pythonDottedName + +" Comments +syn match pythonComment "#.*$" display contains=pythonTodo,@Spell +syn match pythonRun "\%^#!.*$" +syn match pythonCoding "\%^.*\%(\n.*\)\?#.*coding[:=]\s*[0-9A-Za-z-_.]\+.*$" +syn keyword pythonTodo TODO FIXME XXX contained + +" Errors +syn match pythonError "\<\d\+\D\+\>" display +syn match pythonError "[$?]" display +syn match pythonError "[&|]\{2,}" display +syn match pythonError "[=]\{3,}" display + +" TODO: Mixing spaces and tabs also may be used for pretty formatting multiline +" statements. For now I don't know how to work around this. +if exists("python_highlight_indent_errors") && python_highlight_indent_errors != 0 + syn match pythonIndentError "^\s*\%( \t\|\t \)\s*\S"me=e-1 display +endif + +" Trailing space errors +if exists("python_highlight_space_errors") && python_highlight_space_errors != 0 + syn match pythonSpaceError "\s\+$" display +endif + +" Strings +syn region pythonString start=+'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonEscape,pythonEscapeError,@Spell +syn region pythonString start=+"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonEscape,pythonEscapeError,@Spell +syn region pythonString start=+"""+ end=+"""+ keepend contains=pythonEscape,pythonEscapeError,pythonDocTest2,pythonSpaceError,@Spell +syn region pythonString start=+'''+ end=+'''+ keepend contains=pythonEscape,pythonEscapeError,pythonDocTest,pythonSpaceError,@Spell + +syn match pythonEscape +\\[abfnrtv'"\\]+ display contained +syn match pythonEscape "\\\o\o\=\o\=" display contained +syn match pythonEscapeError "\\\o\{,2}[89]" display contained +syn match pythonEscape "\\x\x\{2}" display contained +syn match pythonEscapeError "\\x\x\=\X" display contained +syn match pythonEscape "\\$" +syn match pythonEscape "\\u\x\{4}" display contained +syn match pythonEscapeError "\\u\x\{,3}\X" display contained +syn match pythonEscape "\\U\x\{8}" display contained +syn match pythonEscapeError "\\U\x\{,7}\X" display contained +syn match pythonEscape "\\N{[A-Z ]\+}" display contained +syn match pythonEscapeError "\\N{[^A-Z ]\+}" display contained + +" Raw strings +syn region pythonRawString start=+[bB]\=[rR]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonRawEscape,@Spell +syn region pythonRawString start=+[bB]\=[rR]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonRawEscape,@Spell +syn region pythonRawString start=+[bB]\=[rR]"""+ end=+"""+ keepend contains=pythonDocTest2,pythonSpaceError,@Spell +syn region pythonRawString start=+[bB]\=[rR]'''+ end=+'''+ keepend contains=pythonDocTest,pythonSpaceError,@Spell + +syn match pythonRawEscape +\\['"]+ display transparent contained + +" Bytes +syn region pythonBytes start=+[bB]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonBytesError,pythonBytesContent,@Spell +syn region pythonBytes start=+[bB]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonBytesError,pythonBytesContent,@Spell +syn region pythonBytes start=+[bB]"""+ end=+"""+ keepend contains=pythonBytesError,pythonBytesContent,pythonDocTest2,pythonSpaceError,@Spell +syn region pythonBytes start=+[bB]'''+ end=+'''+ keepend contains=pythonBytesError,pythonBytesContent,pythonDocTest,pythonSpaceError,@Spell + +syn match pythonBytesError ".\+" display contained +syn match pythonBytesContent "[\u0000-\u00ff]\+" display contained contains=pythonBytesEscape,pythonBytesEscapeError + +syn match pythonBytesEscape +\\[abfnrtv'"\\]+ display contained +syn match pythonBytesEscape "\\\o\o\=\o\=" display contained +syn match pythonBytesEscapeError "\\\o\{,2}[89]" display contained +syn match pythonBytesEscape "\\x\x\{2}" display contained +syn match pythonBytesEscapeError "\\x\x\=\X" display contained +syn match pythonBytesEscape "\\$" + +if exists("python_highlight_string_formatting") && python_highlight_string_formatting != 0 + " String formatting + syn match pythonStrFormatting "%\%(([^)]\+)\)\=[-#0 +]*\d*\%(\.\d\+\)\=[hlL]\=[diouxXeEfFgGcrs%]" contained containedin=pythonString,pythonRawString + syn match pythonStrFormatting "%[-#0 +]*\%(\*\|\d\+\)\=\%(\.\%(\*\|\d\+\)\)\=[hlL]\=[diouxXeEfFgGcrs%]" contained containedin=pythonString,pythonRawString +endif + +if exists("python_highlight_string_format") && python_highlight_string_format != 0 + " str.format syntax + syn match pythonStrFormat "{{\|}}" contained containedin=pythonString,pythonRawString + syn match pythonStrFormat "{\%(\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\d\+\)\=\%(\.\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\[\%(\d\+\|[^!:\}]\+\)\]\)*\%(![rsa]\)\=\%(:\%({\%(\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\d\+\)}\|\%([^}]\=[<>=^]\)\=[ +-]\=#\=0\=\d*,\=\%(\.\d\+\)\=[bcdeEfFgGnosxX%]\=\)\=\)\=}" contained containedin=pythonString,pythonRawString +endif + +if exists("python_highlight_string_templates") && python_highlight_string_templates != 0 + " String templates + syn match pythonStrTemplate "\$\$" contained containedin=pythonString,pythonRawString + syn match pythonStrTemplate "\${[a-zA-Z_][a-zA-Z0-9_]*}" contained containedin=pythonString,pythonRawString + syn match pythonStrTemplate "\$[a-zA-Z_][a-zA-Z0-9_]*" contained containedin=pythonString,pythonRawString +endif + +if exists("python_highlight_doctests") && python_highlight_doctests != 0 + " DocTests + syn region pythonDocTest start="^\s*>>>" end=+'''+he=s-1 end="^\s*$" contained + syn region pythonDocTest2 start="^\s*>>>" end=+"""+he=s-1 end="^\s*$" contained +endif + +" Numbers (ints, longs, floats, complex) +syn match pythonHexError "\<0[xX]\x*[g-zG-Z]\x*\>" display + +syn match pythonHexNumber "\<0[xX]\x\+\>" display +syn match pythonOctNumber "\<0[oO]\o\+\>" display +syn match pythonBinNumber "\<0[bB][01]\+\>" display + +syn match pythonNumberError "\<\d\+\D\>" display +syn match pythonNumberError "\<0\d\+\>" display +syn match pythonNumber "\<\d\>" display +syn match pythonNumber "\<[1-9]\d\+\>" display +syn match pythonNumber "\<\d\+[jJ]\>" display + +syn match pythonFloat "\.\d\+\%([eE][+-]\=\d\+\)\=[jJ]\=\>" display +syn match pythonFloat "\<\d\+[eE][+-]\=\d\+[jJ]\=\>" display +syn match pythonFloat "\<\d\+\.\d*\%([eE][+-]\=\d\+\)\=[jJ]\=" display + +syn match pythonOctError "\<0[oO]\=\o*[8-9]\d*\>" display +syn match pythonBinError "\<0[bB][01]*[2-9]\d*\>" display + +if exists("python_highlight_builtin_objs") && python_highlight_builtin_objs != 0 + " Builtin objects and types + syn keyword pythonBuiltinObj Ellipsis NotImplemented + syn keyword pythonBuiltinObj __debug__ __doc__ __file__ __name__ __package__ +endif + +if exists("python_highlight_builtin_funcs") && python_highlight_builtin_funcs != 0 + " Builtin functions + syn keyword pythonBuiltinFunc __import__ abs all any ascii + syn keyword pythonBuiltinFunc bin bool bytearray bytes + syn keyword pythonBuiltinFunc chr classmethod cmp compile complex + syn keyword pythonBuiltinFunc delattr dict dir divmod enumerate eval + syn keyword pythonBuiltinFunc exec filter float format frozenset getattr + syn keyword pythonBuiltinFunc globals hasattr hash hex id + syn keyword pythonBuiltinFunc input int isinstance + syn keyword pythonBuiltinFunc issubclass iter len list locals map max + syn keyword pythonBuiltinFunc memoryview min next object oct open ord + syn keyword pythonBuiltinFunc pow print property range + syn keyword pythonBuiltinFunc repr reversed round set setattr + syn keyword pythonBuiltinFunc slice sorted staticmethod str sum super tuple + syn keyword pythonBuiltinFunc type vars zip +endif + +if exists("python_highlight_exceptions") && python_highlight_exceptions != 0 + " Builtin exceptions and warnings + syn keyword pythonExClass BaseException + syn keyword pythonExClass Exception ArithmeticError + syn keyword pythonExClass LookupError EnvironmentError + + syn keyword pythonExClass AssertionError AttributeError BufferError EOFError + syn keyword pythonExClass FloatingPointError GeneratorExit IOError + syn keyword pythonExClass ImportError IndexError KeyError + syn keyword pythonExClass KeyboardInterrupt MemoryError NameError + syn keyword pythonExClass NotImplementedError OSError OverflowError + syn keyword pythonExClass ReferenceError RuntimeError StopIteration + syn keyword pythonExClass SyntaxError IndentationError TabError + syn keyword pythonExClass SystemError SystemExit TypeError + syn keyword pythonExClass UnboundLocalError UnicodeError + syn keyword pythonExClass UnicodeEncodeError UnicodeDecodeError + syn keyword pythonExClass UnicodeTranslateError ValueError VMSError + syn keyword pythonExClass WindowsError ZeroDivisionError + + syn keyword pythonExClass Warning UserWarning BytesWarning DeprecationWarning + syn keyword pythonExClass PendingDepricationWarning SyntaxWarning + syn keyword pythonExClass RuntimeWarning FutureWarning + syn keyword pythonExClass ImportWarning UnicodeWarning +endif + +if exists("python_slow_sync") && python_slow_sync != 0 + syn sync minlines=2000 +else + " This is fast but code inside triple quoted strings screws it up. It + " is impossible to fix because the only way to know if you are inside a + " triple quoted string is to start from the beginning of the file. + syn sync match pythonSync grouphere NONE "):$" + syn sync maxlines=200 +endif + +if version >= 508 || !exists("did_python_syn_inits") + if version <= 508 + let did_python_syn_inits = 1 + command -nargs=+ HiLink hi link + else + command -nargs=+ HiLink hi def link + endif + + HiLink pythonStatement Statement + HiLink pythonPreCondit Statement + HiLink pythonFunction Function + HiLink pythonConditional Conditional + HiLink pythonRepeat Repeat + HiLink pythonException Exception + HiLink pythonOperator Operator + + HiLink pythonDecorator Define + HiLink pythonDottedName Function + HiLink pythonDot Normal + + HiLink pythonComment Comment + HiLink pythonCoding Special + HiLink pythonRun Special + HiLink pythonTodo Todo + + HiLink pythonError Error + HiLink pythonIndentError Error + HiLink pythonSpaceError Error + + HiLink pythonString String + HiLink pythonRawString String + HiLink pythonEscape Special + HiLink pythonEscapeError Error + + HiLink pythonBytes String + HiLink pythonBytesContent String + HiLink pythonBytesError Error + HiLink pythonBytesEscape Special + HiLink pythonBytesEscapeError Error + + HiLink pythonStrFormatting Special + HiLink pythonStrFormat Special + HiLink pythonStrTemplate Special + + HiLink pythonDocTest Special + HiLink pythonDocTest2 Special + + HiLink pythonNumber Number + HiLink pythonHexNumber Number + HiLink pythonOctNumber Number + HiLink pythonBinNumber Number + HiLink pythonFloat Float + HiLink pythonNumberError Error + HiLink pythonOctError Error + HiLink pythonHexError Error + HiLink pythonBinError Error + + HiLink pythonBuiltinObj Structure + HiLink pythonBuiltinFunc Function + + HiLink pythonExClass Structure + + delcommand HiLink +endif + +let b:current_syntax = "python" diff --git a/addons/python%790/syntax/python3.0.vim b/addons/python%790/syntax/python3.0.vim new file mode 100644 index 0000000..7383876 --- /dev/null +++ b/addons/python%790/syntax/python3.0.vim @@ -0,0 +1,370 @@ +" Vim syntax file +" Language: Python +" Maintainer: Dmitry Vasiliev +" URL: https://github.com/hdima/vim-scripts/blob/master/syntax/python/python3.0.vim +" Last Change: 2012-02-11 +" Filenames: *.py +" Version: 3.0.7 +" +" Based on python.vim (from Vim 6.1 distribution) +" by Neil Schemenauer +" +" Thanks: +" +" Jeroen Ruigrok van der Werven +" for the idea to highlight erroneous operators +" Pedro Algarvio +" for the patch to enable spell checking only for the right spots +" (strings and comments) +" John Eikenberry +" for the patch fixing small typo +" Caleb Adamantine +" for the patch fixing highlighting for decorators +" Andrea Riciputi +" for the patch with new configuration options +" Anton Butanaev +" for the patch fixing bytes literals highlighting +" for the patch fixing str.format syntax highlighting + +" +" Options: +" +" For set option do: let OPTION_NAME = 1 +" For clear option do: let OPTION_NAME = 0 +" +" Option names: +" +" For highlight builtin functions: +" python_highlight_builtins +" +" For highlight builtin objects: +" python_highlight_builtin_objs +" +" For highlight builtin funtions: +" python_highlight_builtin_funcs +" +" For highlight standard exceptions: +" python_highlight_exceptions +" +" For highlight string formatting: +" python_highlight_string_formatting +" +" For highlight str.format syntax: +" python_highlight_string_format +" +" For highlight string.Template syntax: +" python_highlight_string_templates +" +" For highlight indentation errors: +" python_highlight_indent_errors +" +" For highlight trailing spaces: +" python_highlight_space_errors +" +" For highlight doc-tests: +" python_highlight_doctests +" +" If you want all Python highlightings above: +" python_highlight_all +" (This option not override previously set options) +" +" For fast machines: +" python_slow_sync + +" For version 5.x: Clear all syntax items +" For version 6.x: Quit when a syntax file was already loaded +if version < 600 + syntax clear +elseif exists("b:current_syntax") + finish +endif + +if exists("python_highlight_all") && python_highlight_all != 0 + " Not override previously set options + if !exists("python_highlight_builtins") + if !exists("python_highlight_builtin_objs") + let python_highlight_builtin_objs = 1 + endif + if !exists("python_highlight_builtin_funcs") + let python_highlight_builtin_funcs = 1 + endif + endif + if !exists("python_highlight_exceptions") + let python_highlight_exceptions = 1 + endif + if !exists("python_highlight_string_formatting") + let python_highlight_string_formatting = 1 + endif + if !exists("python_highlight_string_format") + let python_highlight_string_format = 1 + endif + if !exists("python_highlight_string_templates") + let python_highlight_string_templates = 1 + endif + if !exists("python_highlight_indent_errors") + let python_highlight_indent_errors = 1 + endif + if !exists("python_highlight_space_errors") + let python_highlight_space_errors = 1 + endif + if !exists("python_highlight_doctests") + let python_highlight_doctests = 1 + endif +endif + +" Keywords +syn keyword pythonStatement break continue del +syn keyword pythonStatement exec return as +syn keyword pythonStatement pass raise +syn keyword pythonStatement global assert +syn keyword pythonStatement lambda yield +syn keyword pythonStatement with nonlocal +syn keyword pythonStatement False None True +syn keyword pythonStatement def class nextgroup=pythonFunction skipwhite +syn match pythonFunction "\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*" display contained +syn keyword pythonRepeat for while +syn keyword pythonConditional if elif else +syn keyword pythonPreCondit import from +syn keyword pythonException try except finally +syn keyword pythonOperator and in is not or + +" Decorators (new in Python 2.4) +syn match pythonDecorator "@" display nextgroup=pythonDottedName skipwhite +syn match pythonDottedName "[a-zA-Z_][a-zA-Z0-9_]*\(\.[a-zA-Z_][a-zA-Z0-9_]*\)*" display contained +syn match pythonDot "\." display containedin=pythonDottedName + +" Comments +syn match pythonComment "#.*$" display contains=pythonTodo,@Spell +syn match pythonRun "\%^#!.*$" +syn match pythonCoding "\%^.*\%(\n.*\)\?#.*coding[:=]\s*[0-9A-Za-z-_.]\+.*$" +syn keyword pythonTodo TODO FIXME XXX contained + +" Errors +syn match pythonError "\<\d\+\D\+\>" display +syn match pythonError "[$?]" display +syn match pythonError "[&|]\{2,}" display +syn match pythonError "[=]\{3,}" display + +" TODO: Mixing spaces and tabs also may be used for pretty formatting multiline +" statements. For now I don't know how to work around this. +if exists("python_highlight_indent_errors") && python_highlight_indent_errors != 0 + syn match pythonIndentError "^\s*\%( \t\|\t \)\s*\S"me=e-1 display +endif + +" Trailing space errors +if exists("python_highlight_space_errors") && python_highlight_space_errors != 0 + syn match pythonSpaceError "\s\+$" display +endif + +" Strings +syn region pythonString start=+'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonEscape,pythonEscapeError,@Spell +syn region pythonString start=+"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonEscape,pythonEscapeError,@Spell +syn region pythonString start=+"""+ end=+"""+ keepend contains=pythonEscape,pythonEscapeError,pythonDocTest2,pythonSpaceError,@Spell +syn region pythonString start=+'''+ end=+'''+ keepend contains=pythonEscape,pythonEscapeError,pythonDocTest,pythonSpaceError,@Spell + +syn match pythonEscape +\\[abfnrtv'"\\]+ display contained +syn match pythonEscape "\\\o\o\=\o\=" display contained +syn match pythonEscapeError "\\\o\{,2}[89]" display contained +syn match pythonEscape "\\x\x\{2}" display contained +syn match pythonEscapeError "\\x\x\=\X" display contained +syn match pythonEscape "\\$" +syn match pythonEscape "\\u\x\{4}" display contained +syn match pythonEscapeError "\\u\x\{,3}\X" display contained +syn match pythonEscape "\\U\x\{8}" display contained +syn match pythonEscapeError "\\U\x\{,7}\X" display contained +syn match pythonEscape "\\N{[A-Z ]\+}" display contained +syn match pythonEscapeError "\\N{[^A-Z ]\+}" display contained + +" Raw strings +syn region pythonRawString start=+[bB]\=[rR]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonRawEscape,@Spell +syn region pythonRawString start=+[bB]\=[rR]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonRawEscape,@Spell +syn region pythonRawString start=+[bB]\=[rR]"""+ end=+"""+ keepend contains=pythonDocTest2,pythonSpaceError,@Spell +syn region pythonRawString start=+[bB]\=[rR]'''+ end=+'''+ keepend contains=pythonDocTest,pythonSpaceError,@Spell + +syn match pythonRawEscape +\\['"]+ display transparent contained + +" Bytes +syn region pythonBytes start=+[bB]'+ skip=+\\\\\|\\'\|\\$+ excludenl end=+'+ end=+$+ keepend contains=pythonBytesError,pythonBytesContent,@Spell +syn region pythonBytes start=+[bB]"+ skip=+\\\\\|\\"\|\\$+ excludenl end=+"+ end=+$+ keepend contains=pythonBytesError,pythonBytesContent,@Spell +syn region pythonBytes start=+[bB]"""+ end=+"""+ keepend contains=pythonBytesError,pythonBytesContent,pythonDocTest2,pythonSpaceError,@Spell +syn region pythonBytes start=+[bB]'''+ end=+'''+ keepend contains=pythonBytesError,pythonBytesContent,pythonDocTest,pythonSpaceError,@Spell + +syn match pythonBytesError ".\+" display contained +syn match pythonBytesContent "[\u0000-\u00ff]\+" display contained contains=pythonBytesEscape,pythonBytesEscapeError + +syn match pythonBytesEscape +\\[abfnrtv'"\\]+ display contained +syn match pythonBytesEscape "\\\o\o\=\o\=" display contained +syn match pythonBytesEscapeError "\\\o\{,2}[89]" display contained +syn match pythonBytesEscape "\\x\x\{2}" display contained +syn match pythonBytesEscapeError "\\x\x\=\X" display contained +syn match pythonBytesEscape "\\$" + +if exists("python_highlight_string_formatting") && python_highlight_string_formatting != 0 + " String formatting + syn match pythonStrFormatting "%\%(([^)]\+)\)\=[-#0 +]*\d*\%(\.\d\+\)\=[hlL]\=[diouxXeEfFgGcrs%]" contained containedin=pythonString,pythonRawString + syn match pythonStrFormatting "%[-#0 +]*\%(\*\|\d\+\)\=\%(\.\%(\*\|\d\+\)\)\=[hlL]\=[diouxXeEfFgGcrs%]" contained containedin=pythonString,pythonRawString +endif + +if exists("python_highlight_string_format") && python_highlight_string_format != 0 + " str.format syntax + syn match pythonStrFormat "{{\|}}" contained containedin=pythonString,pythonRawString + syn match pythonStrFormat "{\%(\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\d\+\)\=\%(\.\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\[\%(\d\+\|[^!:\}]\+\)\]\)*\%(![rsa]\)\=\%(:\%({\%(\%([^[:cntrl:][:space:][:punct:][:digit:]]\|_\)\%([^[:cntrl:][:punct:][:space:]]\|_\)*\|\d\+\)}\|\%([^}]\=[<>=^]\)\=[ +-]\=#\=0\=\d*,\=\%(\.\d\+\)\=[bcdeEfFgGnosxX%]\=\)\=\)\=}" contained containedin=pythonString,pythonRawString +endif + +if exists("python_highlight_string_templates") && python_highlight_string_templates != 0 + " String templates + syn match pythonStrTemplate "\$\$" contained containedin=pythonString,pythonRawString + syn match pythonStrTemplate "\${[a-zA-Z_][a-zA-Z0-9_]*}" contained containedin=pythonString,pythonRawString + syn match pythonStrTemplate "\$[a-zA-Z_][a-zA-Z0-9_]*" contained containedin=pythonString,pythonRawString +endif + +if exists("python_highlight_doctests") && python_highlight_doctests != 0 + " DocTests + syn region pythonDocTest start="^\s*>>>" end=+'''+he=s-1 end="^\s*$" contained + syn region pythonDocTest2 start="^\s*>>>" end=+"""+he=s-1 end="^\s*$" contained +endif + +" Numbers (ints, longs, floats, complex) +syn match pythonHexError "\<0[xX]\x*[g-zG-Z]\x*\>" display + +syn match pythonHexNumber "\<0[xX]\x\+\>" display +syn match pythonOctNumber "\<0[oO]\o\+\>" display +syn match pythonBinNumber "\<0[bB][01]\+\>" display + +syn match pythonNumberError "\<\d\+\D\>" display +syn match pythonNumberError "\<0\d\+\>" display +syn match pythonNumber "\<\d\>" display +syn match pythonNumber "\<[1-9]\d\+\>" display +syn match pythonNumber "\<\d\+[jJ]\>" display + +syn match pythonFloat "\.\d\+\%([eE][+-]\=\d\+\)\=[jJ]\=\>" display +syn match pythonFloat "\<\d\+[eE][+-]\=\d\+[jJ]\=\>" display +syn match pythonFloat "\<\d\+\.\d*\%([eE][+-]\=\d\+\)\=[jJ]\=" display + +syn match pythonOctError "\<0[oO]\=\o*[8-9]\d*\>" display +syn match pythonBinError "\<0[bB][01]*[2-9]\d*\>" display + +if exists("python_highlight_builtin_objs") && python_highlight_builtin_objs != 0 + " Builtin objects and types + syn keyword pythonBuiltinObj Ellipsis NotImplemented + syn keyword pythonBuiltinObj __debug__ __doc__ __file__ __name__ __package__ +endif + +if exists("python_highlight_builtin_funcs") && python_highlight_builtin_funcs != 0 + " Builtin functions + syn keyword pythonBuiltinFunc __import__ abs all any ascii + syn keyword pythonBuiltinFunc bin bool bytearray bytes + syn keyword pythonBuiltinFunc chr classmethod cmp compile complex + syn keyword pythonBuiltinFunc delattr dict dir divmod enumerate eval + syn keyword pythonBuiltinFunc exec filter float format frozenset getattr + syn keyword pythonBuiltinFunc globals hasattr hash hex id + syn keyword pythonBuiltinFunc input int isinstance + syn keyword pythonBuiltinFunc issubclass iter len list locals map max + syn keyword pythonBuiltinFunc memoryview min next object oct open ord + syn keyword pythonBuiltinFunc pow print property range + syn keyword pythonBuiltinFunc repr reversed round set setattr + syn keyword pythonBuiltinFunc slice sorted staticmethod str sum super tuple + syn keyword pythonBuiltinFunc type vars zip +endif + +if exists("python_highlight_exceptions") && python_highlight_exceptions != 0 + " Builtin exceptions and warnings + syn keyword pythonExClass BaseException + syn keyword pythonExClass Exception ArithmeticError + syn keyword pythonExClass LookupError EnvironmentError + + syn keyword pythonExClass AssertionError AttributeError BufferError EOFError + syn keyword pythonExClass FloatingPointError GeneratorExit IOError + syn keyword pythonExClass ImportError IndexError KeyError + syn keyword pythonExClass KeyboardInterrupt MemoryError NameError + syn keyword pythonExClass NotImplementedError OSError OverflowError + syn keyword pythonExClass ReferenceError RuntimeError StopIteration + syn keyword pythonExClass SyntaxError IndentationError TabError + syn keyword pythonExClass SystemError SystemExit TypeError + syn keyword pythonExClass UnboundLocalError UnicodeError + syn keyword pythonExClass UnicodeEncodeError UnicodeDecodeError + syn keyword pythonExClass UnicodeTranslateError ValueError VMSError + syn keyword pythonExClass WindowsError ZeroDivisionError + + syn keyword pythonExClass Warning UserWarning BytesWarning DeprecationWarning + syn keyword pythonExClass PendingDepricationWarning SyntaxWarning + syn keyword pythonExClass RuntimeWarning FutureWarning + syn keyword pythonExClass ImportWarning UnicodeWarning +endif + +if exists("python_slow_sync") && python_slow_sync != 0 + syn sync minlines=2000 +else + " This is fast but code inside triple quoted strings screws it up. It + " is impossible to fix because the only way to know if you are inside a + " triple quoted string is to start from the beginning of the file. + syn sync match pythonSync grouphere NONE "):$" + syn sync maxlines=200 +endif + +if version >= 508 || !exists("did_python_syn_inits") + if version <= 508 + let did_python_syn_inits = 1 + command -nargs=+ HiLink hi link + else + command -nargs=+ HiLink hi def link + endif + + HiLink pythonStatement Statement + HiLink pythonPreCondit Statement + HiLink pythonFunction Function + HiLink pythonConditional Conditional + HiLink pythonRepeat Repeat + HiLink pythonException Exception + HiLink pythonOperator Operator + + HiLink pythonDecorator Define + HiLink pythonDottedName Function + HiLink pythonDot Normal + + HiLink pythonComment Comment + HiLink pythonCoding Special + HiLink pythonRun Special + HiLink pythonTodo Todo + + HiLink pythonError Error + HiLink pythonIndentError Error + HiLink pythonSpaceError Error + + HiLink pythonString String + HiLink pythonRawString String + HiLink pythonEscape Special + HiLink pythonEscapeError Error + + HiLink pythonBytes String + HiLink pythonBytesContent String + HiLink pythonBytesError Error + HiLink pythonBytesEscape Special + HiLink pythonBytesEscapeError Error + + HiLink pythonStrFormatting Special + HiLink pythonStrFormat Special + HiLink pythonStrTemplate Special + + HiLink pythonDocTest Special + HiLink pythonDocTest2 Special + + HiLink pythonNumber Number + HiLink pythonHexNumber Number + HiLink pythonOctNumber Number + HiLink pythonBinNumber Number + HiLink pythonFloat Float + HiLink pythonNumberError Error + HiLink pythonOctError Error + HiLink pythonHexError Error + HiLink pythonBinError Error + + HiLink pythonBuiltinObj Structure + HiLink pythonBuiltinFunc Function + + HiLink pythonExClass Structure + + delcommand HiLink +endif + +let b:current_syntax = "python" diff --git a/addons/python%790/version b/addons/python%790/version new file mode 100644 index 0000000..3a8b971 --- /dev/null +++ b/addons/python%790/version @@ -0,0 +1 @@ +3.0.7 \ No newline at end of file diff --git a/addons/pythoncomplete/archive/pythoncomplete.vim b/addons/pythoncomplete/archive/pythoncomplete.vim new file mode 100644 index 0000000..57add71 --- /dev/null +++ b/addons/pythoncomplete/archive/pythoncomplete.vim @@ -0,0 +1,625 @@ +"pythoncomplete.vim - Omni Completion for python +" Maintainer: Aaron Griffin +" Version: 0.9 +" Last Updated: 18 Jun 2009 +" +" Changes +" TODO: +" 'info' item output can use some formatting work +" Add an "unsafe eval" mode, to allow for return type evaluation +" Complete basic syntax along with import statements +" i.e. "import url" +" Continue parsing on invalid line?? +" +" v 0.9 +" * Fixed docstring parsing for classes and functions +" * Fixed parsing of *args and **kwargs type arguments +" * Better function param parsing to handle things like tuples and +" lambda defaults args +" +" v 0.8 +" * Fixed an issue where the FIRST assignment was always used instead of +" using a subsequent assignment for a variable +" * Fixed a scoping issue when working inside a parameterless function +" +" +" v 0.7 +" * Fixed function list sorting (_ and __ at the bottom) +" * Removed newline removal from docs. It appears vim handles these better in +" recent patches +" +" v 0.6: +" * Fixed argument completion +" * Removed the 'kind' completions, as they are better indicated +" with real syntax +" * Added tuple assignment parsing (whoops, that was forgotten) +" * Fixed import handling when flattening scope +" +" v 0.5: +" Yeah, I skipped a version number - 0.4 was never public. +" It was a bugfix version on top of 0.3. This is a complete +" rewrite. +" + +if !has('python') + echo "Error: Required vim compiled with +python" + finish +endif + +function! pythoncomplete#Complete(findstart, base) + "findstart = 1 when we need to get the text length + if a:findstart == 1 + let line = getline('.') + let idx = col('.') + while idx > 0 + let idx -= 1 + let c = line[idx] + if c =~ '\w' + continue + elseif ! c =~ '\.' + let idx = -1 + break + else + break + endif + endwhile + + return idx + "findstart = 0 when we need to return the list of completions + else + "vim no longer moves the cursor upon completion... fix that + let line = getline('.') + let idx = col('.') + let cword = '' + while idx > 0 + let idx -= 1 + let c = line[idx] + if c =~ '\w' || c =~ '\.' + let cword = c . cword + continue + elseif strlen(cword) > 0 || idx == 0 + break + endif + endwhile + execute "python vimcomplete('" . cword . "', '" . a:base . "')" + return g:pythoncomplete_completions + endif +endfunction + +function! s:DefPython() +python << PYTHONEOF +import sys, tokenize, cStringIO, types +from token import NAME, DEDENT, NEWLINE, STRING + +debugstmts=[] +def dbg(s): debugstmts.append(s) +def showdbg(): + for d in debugstmts: print "DBG: %s " % d + +def vimcomplete(context,match): + global debugstmts + debugstmts = [] + try: + import vim + def complsort(x,y): + try: + xa = x['abbr'] + ya = y['abbr'] + if xa[0] == '_': + if xa[1] == '_' and ya[0:2] == '__': + return xa > ya + elif ya[0:2] == '__': + return -1 + elif y[0] == '_': + return xa > ya + else: + return 1 + elif ya[0] == '_': + return -1 + else: + return xa > ya + except: + return 0 + cmpl = Completer() + cmpl.evalsource('\n'.join(vim.current.buffer),vim.eval("line('.')")) + all = cmpl.get_completions(context,match) + all.sort(complsort) + dictstr = '[' + # have to do this for double quoting + for cmpl in all: + dictstr += '{' + for x in cmpl: dictstr += '"%s":"%s",' % (x,cmpl[x]) + dictstr += '"icase":0},' + if dictstr[-1] == ',': dictstr = dictstr[:-1] + dictstr += ']' + #dbg("dict: %s" % dictstr) + vim.command("silent let g:pythoncomplete_completions = %s" % dictstr) + #dbg("Completion dict:\n%s" % all) + except vim.error: + dbg("VIM Error: %s" % vim.error) + +class Completer(object): + def __init__(self): + self.compldict = {} + self.parser = PyParser() + + def evalsource(self,text,line=0): + sc = self.parser.parse(text,line) + src = sc.get_code() + dbg("source: %s" % src) + try: exec(src) in self.compldict + except: dbg("parser: %s, %s" % (sys.exc_info()[0],sys.exc_info()[1])) + for l in sc.locals: + try: exec(l) in self.compldict + except: dbg("locals: %s, %s [%s]" % (sys.exc_info()[0],sys.exc_info()[1],l)) + + def _cleanstr(self,doc): + return doc.replace('"',' ').replace("'",' ') + + def get_arguments(self,func_obj): + def _ctor(obj): + try: return class_ob.__init__.im_func + except AttributeError: + for base in class_ob.__bases__: + rc = _find_constructor(base) + if rc is not None: return rc + return None + + arg_offset = 1 + if type(func_obj) == types.ClassType: func_obj = _ctor(func_obj) + elif type(func_obj) == types.MethodType: func_obj = func_obj.im_func + else: arg_offset = 0 + + arg_text='' + if type(func_obj) in [types.FunctionType, types.LambdaType]: + try: + cd = func_obj.func_code + real_args = cd.co_varnames[arg_offset:cd.co_argcount] + defaults = func_obj.func_defaults or '' + defaults = map(lambda name: "=%s" % name, defaults) + defaults = [""] * (len(real_args)-len(defaults)) + defaults + items = map(lambda a,d: a+d, real_args, defaults) + if func_obj.func_code.co_flags & 0x4: + items.append("...") + if func_obj.func_code.co_flags & 0x8: + items.append("***") + arg_text = (','.join(items)) + ')' + + except: + dbg("arg completion: %s: %s" % (sys.exc_info()[0],sys.exc_info()[1])) + pass + if len(arg_text) == 0: + # The doc string sometimes contains the function signature + # this works for alot of C modules that are part of the + # standard library + doc = func_obj.__doc__ + if doc: + doc = doc.lstrip() + pos = doc.find('\n') + if pos > 0: + sigline = doc[:pos] + lidx = sigline.find('(') + ridx = sigline.find(')') + if lidx > 0 and ridx > 0: + arg_text = sigline[lidx+1:ridx] + ')' + if len(arg_text) == 0: arg_text = ')' + return arg_text + + def get_completions(self,context,match): + dbg("get_completions('%s','%s')" % (context,match)) + stmt = '' + if context: stmt += str(context) + if match: stmt += str(match) + try: + result = None + all = {} + ridx = stmt.rfind('.') + if len(stmt) > 0 and stmt[-1] == '(': + result = eval(_sanitize(stmt[:-1]), self.compldict) + doc = result.__doc__ + if doc is None: doc = '' + args = self.get_arguments(result) + return [{'word':self._cleanstr(args),'info':self._cleanstr(doc)}] + elif ridx == -1: + match = stmt + all = self.compldict + else: + match = stmt[ridx+1:] + stmt = _sanitize(stmt[:ridx]) + result = eval(stmt, self.compldict) + all = dir(result) + + dbg("completing: stmt:%s" % stmt) + completions = [] + + try: maindoc = result.__doc__ + except: maindoc = ' ' + if maindoc is None: maindoc = ' ' + for m in all: + if m == "_PyCmplNoType": continue #this is internal + try: + dbg('possible completion: %s' % m) + if m.find(match) == 0: + if result is None: inst = all[m] + else: inst = getattr(result,m) + try: doc = inst.__doc__ + except: doc = maindoc + typestr = str(inst) + if doc is None or doc == '': doc = maindoc + + wrd = m[len(match):] + c = {'word':wrd, 'abbr':m, 'info':self._cleanstr(doc)} + if "function" in typestr: + c['word'] += '(' + c['abbr'] += '(' + self._cleanstr(self.get_arguments(inst)) + elif "method" in typestr: + c['word'] += '(' + c['abbr'] += '(' + self._cleanstr(self.get_arguments(inst)) + elif "module" in typestr: + c['word'] += '.' + elif "class" in typestr: + c['word'] += '(' + c['abbr'] += '(' + completions.append(c) + except: + i = sys.exc_info() + dbg("inner completion: %s,%s [stmt='%s']" % (i[0],i[1],stmt)) + return completions + except: + i = sys.exc_info() + dbg("completion: %s,%s [stmt='%s']" % (i[0],i[1],stmt)) + return [] + +class Scope(object): + def __init__(self,name,indent,docstr=''): + self.subscopes = [] + self.docstr = docstr + self.locals = [] + self.parent = None + self.name = name + self.indent = indent + + def add(self,sub): + #print 'push scope: [%s@%s]' % (sub.name,sub.indent) + sub.parent = self + self.subscopes.append(sub) + return sub + + def doc(self,str): + """ Clean up a docstring """ + d = str.replace('\n',' ') + d = d.replace('\t',' ') + while d.find(' ') > -1: d = d.replace(' ',' ') + while d[0] in '"\'\t ': d = d[1:] + while d[-1] in '"\'\t ': d = d[:-1] + dbg("Scope(%s)::docstr = %s" % (self,d)) + self.docstr = d + + def local(self,loc): + self._checkexisting(loc) + self.locals.append(loc) + + def copy_decl(self,indent=0): + """ Copy a scope's declaration only, at the specified indent level - not local variables """ + return Scope(self.name,indent,self.docstr) + + def _checkexisting(self,test): + "Convienance function... keep out duplicates" + if test.find('=') > -1: + var = test.split('=')[0].strip() + for l in self.locals: + if l.find('=') > -1 and var == l.split('=')[0].strip(): + self.locals.remove(l) + + def get_code(self): + str = "" + if len(self.docstr) > 0: str += '"""'+self.docstr+'"""\n' + for l in self.locals: + if l.startswith('import'): str += l+'\n' + str += 'class _PyCmplNoType:\n def __getattr__(self,name):\n return None\n' + for sub in self.subscopes: + str += sub.get_code() + for l in self.locals: + if not l.startswith('import'): str += l+'\n' + + return str + + def pop(self,indent): + #print 'pop scope: [%s] to [%s]' % (self.indent,indent) + outer = self + while outer.parent != None and outer.indent >= indent: + outer = outer.parent + return outer + + def currentindent(self): + #print 'parse current indent: %s' % self.indent + return ' '*self.indent + + def childindent(self): + #print 'parse child indent: [%s]' % (self.indent+1) + return ' '*(self.indent+1) + +class Class(Scope): + def __init__(self, name, supers, indent, docstr=''): + Scope.__init__(self,name,indent, docstr) + self.supers = supers + def copy_decl(self,indent=0): + c = Class(self.name,self.supers,indent, self.docstr) + for s in self.subscopes: + c.add(s.copy_decl(indent+1)) + return c + def get_code(self): + str = '%sclass %s' % (self.currentindent(),self.name) + if len(self.supers) > 0: str += '(%s)' % ','.join(self.supers) + str += ':\n' + if len(self.docstr) > 0: str += self.childindent()+'"""'+self.docstr+'"""\n' + if len(self.subscopes) > 0: + for s in self.subscopes: str += s.get_code() + else: + str += '%spass\n' % self.childindent() + return str + + +class Function(Scope): + def __init__(self, name, params, indent, docstr=''): + Scope.__init__(self,name,indent, docstr) + self.params = params + def copy_decl(self,indent=0): + return Function(self.name,self.params,indent, self.docstr) + def get_code(self): + str = "%sdef %s(%s):\n" % \ + (self.currentindent(),self.name,','.join(self.params)) + if len(self.docstr) > 0: str += self.childindent()+'"""'+self.docstr+'"""\n' + str += "%spass\n" % self.childindent() + return str + +class PyParser: + def __init__(self): + self.top = Scope('global',0) + self.scope = self.top + + def _parsedotname(self,pre=None): + #returns (dottedname, nexttoken) + name = [] + if pre is None: + tokentype, token, indent = self.next() + if tokentype != NAME and token != '*': + return ('', token) + else: token = pre + name.append(token) + while True: + tokentype, token, indent = self.next() + if token != '.': break + tokentype, token, indent = self.next() + if tokentype != NAME: break + name.append(token) + return (".".join(name), token) + + def _parseimportlist(self): + imports = [] + while True: + name, token = self._parsedotname() + if not name: break + name2 = '' + if token == 'as': name2, token = self._parsedotname() + imports.append((name, name2)) + while token != "," and "\n" not in token: + tokentype, token, indent = self.next() + if token != ",": break + return imports + + def _parenparse(self): + name = '' + names = [] + level = 1 + while True: + tokentype, token, indent = self.next() + if token in (')', ',') and level == 1: + if '=' not in name: name = name.replace(' ', '') + names.append(name.strip()) + name = '' + if token == '(': + level += 1 + name += "(" + elif token == ')': + level -= 1 + if level == 0: break + else: name += ")" + elif token == ',' and level == 1: + pass + else: + name += "%s " % str(token) + return names + + def _parsefunction(self,indent): + self.scope=self.scope.pop(indent) + tokentype, fname, ind = self.next() + if tokentype != NAME: return None + + tokentype, open, ind = self.next() + if open != '(': return None + params=self._parenparse() + + tokentype, colon, ind = self.next() + if colon != ':': return None + + return Function(fname,params,indent) + + def _parseclass(self,indent): + self.scope=self.scope.pop(indent) + tokentype, cname, ind = self.next() + if tokentype != NAME: return None + + super = [] + tokentype, next, ind = self.next() + if next == '(': + super=self._parenparse() + elif next != ':': return None + + return Class(cname,super,indent) + + def _parseassignment(self): + assign='' + tokentype, token, indent = self.next() + if tokentype == tokenize.STRING or token == 'str': + return '""' + elif token == '(' or token == 'tuple': + return '()' + elif token == '[' or token == 'list': + return '[]' + elif token == '{' or token == 'dict': + return '{}' + elif tokentype == tokenize.NUMBER: + return '0' + elif token == 'open' or token == 'file': + return 'file' + elif token == 'None': + return '_PyCmplNoType()' + elif token == 'type': + return 'type(_PyCmplNoType)' #only for method resolution + else: + assign += token + level = 0 + while True: + tokentype, token, indent = self.next() + if token in ('(','{','['): + level += 1 + elif token in (']','}',')'): + level -= 1 + if level == 0: break + elif level == 0: + if token in (';','\n'): break + assign += token + return "%s" % assign + + def next(self): + type, token, (lineno, indent), end, self.parserline = self.gen.next() + if lineno == self.curline: + #print 'line found [%s] scope=%s' % (line.replace('\n',''),self.scope.name) + self.currentscope = self.scope + return (type, token, indent) + + def _adjustvisibility(self): + newscope = Scope('result',0) + scp = self.currentscope + while scp != None: + if type(scp) == Function: + slice = 0 + #Handle 'self' params + if scp.parent != None and type(scp.parent) == Class: + slice = 1 + newscope.local('%s = %s' % (scp.params[0],scp.parent.name)) + for p in scp.params[slice:]: + i = p.find('=') + if len(p) == 0: continue + pvar = '' + ptype = '' + if i == -1: + pvar = p + ptype = '_PyCmplNoType()' + else: + pvar = p[:i] + ptype = _sanitize(p[i+1:]) + if pvar.startswith('**'): + pvar = pvar[2:] + ptype = '{}' + elif pvar.startswith('*'): + pvar = pvar[1:] + ptype = '[]' + + newscope.local('%s = %s' % (pvar,ptype)) + + for s in scp.subscopes: + ns = s.copy_decl(0) + newscope.add(ns) + for l in scp.locals: newscope.local(l) + scp = scp.parent + + self.currentscope = newscope + return self.currentscope + + #p.parse(vim.current.buffer[:],vim.eval("line('.')")) + def parse(self,text,curline=0): + self.curline = int(curline) + buf = cStringIO.StringIO(''.join(text) + '\n') + self.gen = tokenize.generate_tokens(buf.readline) + self.currentscope = self.scope + + try: + freshscope=True + while True: + tokentype, token, indent = self.next() + #dbg( 'main: token=[%s] indent=[%s]' % (token,indent)) + + if tokentype == DEDENT or token == "pass": + self.scope = self.scope.pop(indent) + elif token == 'def': + func = self._parsefunction(indent) + if func is None: + print "function: syntax error..." + continue + dbg("new scope: function") + freshscope = True + self.scope = self.scope.add(func) + elif token == 'class': + cls = self._parseclass(indent) + if cls is None: + print "class: syntax error..." + continue + freshscope = True + dbg("new scope: class") + self.scope = self.scope.add(cls) + + elif token == 'import': + imports = self._parseimportlist() + for mod, alias in imports: + loc = "import %s" % mod + if len(alias) > 0: loc += " as %s" % alias + self.scope.local(loc) + freshscope = False + elif token == 'from': + mod, token = self._parsedotname() + if not mod or token != "import": + print "from: syntax error..." + continue + names = self._parseimportlist() + for name, alias in names: + loc = "from %s import %s" % (mod,name) + if len(alias) > 0: loc += " as %s" % alias + self.scope.local(loc) + freshscope = False + elif tokentype == STRING: + if freshscope: self.scope.doc(token) + elif tokentype == NAME: + name,token = self._parsedotname(token) + if token == '=': + stmt = self._parseassignment() + dbg("parseassignment: %s = %s" % (name, stmt)) + if stmt != None: + self.scope.local("%s = %s" % (name,stmt)) + freshscope = False + except StopIteration: #thrown on EOF + pass + except: + dbg("parse error: %s, %s @ %s" % + (sys.exc_info()[0], sys.exc_info()[1], self.parserline)) + return self._adjustvisibility() + +def _sanitize(str): + val = '' + level = 0 + for c in str: + if c in ('(','{','['): + level += 1 + elif c in (']','}',')'): + level -= 1 + elif level == 0: + val += c + return val + +sys.path.extend(['.','..']) +PYTHONEOF +endfunction + +call s:DefPython() +" vim: set et ts=4: diff --git a/addons/pythoncomplete/ftplugin/pythoncomplete.vim b/addons/pythoncomplete/ftplugin/pythoncomplete.vim new file mode 100644 index 0000000..57add71 --- /dev/null +++ b/addons/pythoncomplete/ftplugin/pythoncomplete.vim @@ -0,0 +1,625 @@ +"pythoncomplete.vim - Omni Completion for python +" Maintainer: Aaron Griffin +" Version: 0.9 +" Last Updated: 18 Jun 2009 +" +" Changes +" TODO: +" 'info' item output can use some formatting work +" Add an "unsafe eval" mode, to allow for return type evaluation +" Complete basic syntax along with import statements +" i.e. "import url" +" Continue parsing on invalid line?? +" +" v 0.9 +" * Fixed docstring parsing for classes and functions +" * Fixed parsing of *args and **kwargs type arguments +" * Better function param parsing to handle things like tuples and +" lambda defaults args +" +" v 0.8 +" * Fixed an issue where the FIRST assignment was always used instead of +" using a subsequent assignment for a variable +" * Fixed a scoping issue when working inside a parameterless function +" +" +" v 0.7 +" * Fixed function list sorting (_ and __ at the bottom) +" * Removed newline removal from docs. It appears vim handles these better in +" recent patches +" +" v 0.6: +" * Fixed argument completion +" * Removed the 'kind' completions, as they are better indicated +" with real syntax +" * Added tuple assignment parsing (whoops, that was forgotten) +" * Fixed import handling when flattening scope +" +" v 0.5: +" Yeah, I skipped a version number - 0.4 was never public. +" It was a bugfix version on top of 0.3. This is a complete +" rewrite. +" + +if !has('python') + echo "Error: Required vim compiled with +python" + finish +endif + +function! pythoncomplete#Complete(findstart, base) + "findstart = 1 when we need to get the text length + if a:findstart == 1 + let line = getline('.') + let idx = col('.') + while idx > 0 + let idx -= 1 + let c = line[idx] + if c =~ '\w' + continue + elseif ! c =~ '\.' + let idx = -1 + break + else + break + endif + endwhile + + return idx + "findstart = 0 when we need to return the list of completions + else + "vim no longer moves the cursor upon completion... fix that + let line = getline('.') + let idx = col('.') + let cword = '' + while idx > 0 + let idx -= 1 + let c = line[idx] + if c =~ '\w' || c =~ '\.' + let cword = c . cword + continue + elseif strlen(cword) > 0 || idx == 0 + break + endif + endwhile + execute "python vimcomplete('" . cword . "', '" . a:base . "')" + return g:pythoncomplete_completions + endif +endfunction + +function! s:DefPython() +python << PYTHONEOF +import sys, tokenize, cStringIO, types +from token import NAME, DEDENT, NEWLINE, STRING + +debugstmts=[] +def dbg(s): debugstmts.append(s) +def showdbg(): + for d in debugstmts: print "DBG: %s " % d + +def vimcomplete(context,match): + global debugstmts + debugstmts = [] + try: + import vim + def complsort(x,y): + try: + xa = x['abbr'] + ya = y['abbr'] + if xa[0] == '_': + if xa[1] == '_' and ya[0:2] == '__': + return xa > ya + elif ya[0:2] == '__': + return -1 + elif y[0] == '_': + return xa > ya + else: + return 1 + elif ya[0] == '_': + return -1 + else: + return xa > ya + except: + return 0 + cmpl = Completer() + cmpl.evalsource('\n'.join(vim.current.buffer),vim.eval("line('.')")) + all = cmpl.get_completions(context,match) + all.sort(complsort) + dictstr = '[' + # have to do this for double quoting + for cmpl in all: + dictstr += '{' + for x in cmpl: dictstr += '"%s":"%s",' % (x,cmpl[x]) + dictstr += '"icase":0},' + if dictstr[-1] == ',': dictstr = dictstr[:-1] + dictstr += ']' + #dbg("dict: %s" % dictstr) + vim.command("silent let g:pythoncomplete_completions = %s" % dictstr) + #dbg("Completion dict:\n%s" % all) + except vim.error: + dbg("VIM Error: %s" % vim.error) + +class Completer(object): + def __init__(self): + self.compldict = {} + self.parser = PyParser() + + def evalsource(self,text,line=0): + sc = self.parser.parse(text,line) + src = sc.get_code() + dbg("source: %s" % src) + try: exec(src) in self.compldict + except: dbg("parser: %s, %s" % (sys.exc_info()[0],sys.exc_info()[1])) + for l in sc.locals: + try: exec(l) in self.compldict + except: dbg("locals: %s, %s [%s]" % (sys.exc_info()[0],sys.exc_info()[1],l)) + + def _cleanstr(self,doc): + return doc.replace('"',' ').replace("'",' ') + + def get_arguments(self,func_obj): + def _ctor(obj): + try: return class_ob.__init__.im_func + except AttributeError: + for base in class_ob.__bases__: + rc = _find_constructor(base) + if rc is not None: return rc + return None + + arg_offset = 1 + if type(func_obj) == types.ClassType: func_obj = _ctor(func_obj) + elif type(func_obj) == types.MethodType: func_obj = func_obj.im_func + else: arg_offset = 0 + + arg_text='' + if type(func_obj) in [types.FunctionType, types.LambdaType]: + try: + cd = func_obj.func_code + real_args = cd.co_varnames[arg_offset:cd.co_argcount] + defaults = func_obj.func_defaults or '' + defaults = map(lambda name: "=%s" % name, defaults) + defaults = [""] * (len(real_args)-len(defaults)) + defaults + items = map(lambda a,d: a+d, real_args, defaults) + if func_obj.func_code.co_flags & 0x4: + items.append("...") + if func_obj.func_code.co_flags & 0x8: + items.append("***") + arg_text = (','.join(items)) + ')' + + except: + dbg("arg completion: %s: %s" % (sys.exc_info()[0],sys.exc_info()[1])) + pass + if len(arg_text) == 0: + # The doc string sometimes contains the function signature + # this works for alot of C modules that are part of the + # standard library + doc = func_obj.__doc__ + if doc: + doc = doc.lstrip() + pos = doc.find('\n') + if pos > 0: + sigline = doc[:pos] + lidx = sigline.find('(') + ridx = sigline.find(')') + if lidx > 0 and ridx > 0: + arg_text = sigline[lidx+1:ridx] + ')' + if len(arg_text) == 0: arg_text = ')' + return arg_text + + def get_completions(self,context,match): + dbg("get_completions('%s','%s')" % (context,match)) + stmt = '' + if context: stmt += str(context) + if match: stmt += str(match) + try: + result = None + all = {} + ridx = stmt.rfind('.') + if len(stmt) > 0 and stmt[-1] == '(': + result = eval(_sanitize(stmt[:-1]), self.compldict) + doc = result.__doc__ + if doc is None: doc = '' + args = self.get_arguments(result) + return [{'word':self._cleanstr(args),'info':self._cleanstr(doc)}] + elif ridx == -1: + match = stmt + all = self.compldict + else: + match = stmt[ridx+1:] + stmt = _sanitize(stmt[:ridx]) + result = eval(stmt, self.compldict) + all = dir(result) + + dbg("completing: stmt:%s" % stmt) + completions = [] + + try: maindoc = result.__doc__ + except: maindoc = ' ' + if maindoc is None: maindoc = ' ' + for m in all: + if m == "_PyCmplNoType": continue #this is internal + try: + dbg('possible completion: %s' % m) + if m.find(match) == 0: + if result is None: inst = all[m] + else: inst = getattr(result,m) + try: doc = inst.__doc__ + except: doc = maindoc + typestr = str(inst) + if doc is None or doc == '': doc = maindoc + + wrd = m[len(match):] + c = {'word':wrd, 'abbr':m, 'info':self._cleanstr(doc)} + if "function" in typestr: + c['word'] += '(' + c['abbr'] += '(' + self._cleanstr(self.get_arguments(inst)) + elif "method" in typestr: + c['word'] += '(' + c['abbr'] += '(' + self._cleanstr(self.get_arguments(inst)) + elif "module" in typestr: + c['word'] += '.' + elif "class" in typestr: + c['word'] += '(' + c['abbr'] += '(' + completions.append(c) + except: + i = sys.exc_info() + dbg("inner completion: %s,%s [stmt='%s']" % (i[0],i[1],stmt)) + return completions + except: + i = sys.exc_info() + dbg("completion: %s,%s [stmt='%s']" % (i[0],i[1],stmt)) + return [] + +class Scope(object): + def __init__(self,name,indent,docstr=''): + self.subscopes = [] + self.docstr = docstr + self.locals = [] + self.parent = None + self.name = name + self.indent = indent + + def add(self,sub): + #print 'push scope: [%s@%s]' % (sub.name,sub.indent) + sub.parent = self + self.subscopes.append(sub) + return sub + + def doc(self,str): + """ Clean up a docstring """ + d = str.replace('\n',' ') + d = d.replace('\t',' ') + while d.find(' ') > -1: d = d.replace(' ',' ') + while d[0] in '"\'\t ': d = d[1:] + while d[-1] in '"\'\t ': d = d[:-1] + dbg("Scope(%s)::docstr = %s" % (self,d)) + self.docstr = d + + def local(self,loc): + self._checkexisting(loc) + self.locals.append(loc) + + def copy_decl(self,indent=0): + """ Copy a scope's declaration only, at the specified indent level - not local variables """ + return Scope(self.name,indent,self.docstr) + + def _checkexisting(self,test): + "Convienance function... keep out duplicates" + if test.find('=') > -1: + var = test.split('=')[0].strip() + for l in self.locals: + if l.find('=') > -1 and var == l.split('=')[0].strip(): + self.locals.remove(l) + + def get_code(self): + str = "" + if len(self.docstr) > 0: str += '"""'+self.docstr+'"""\n' + for l in self.locals: + if l.startswith('import'): str += l+'\n' + str += 'class _PyCmplNoType:\n def __getattr__(self,name):\n return None\n' + for sub in self.subscopes: + str += sub.get_code() + for l in self.locals: + if not l.startswith('import'): str += l+'\n' + + return str + + def pop(self,indent): + #print 'pop scope: [%s] to [%s]' % (self.indent,indent) + outer = self + while outer.parent != None and outer.indent >= indent: + outer = outer.parent + return outer + + def currentindent(self): + #print 'parse current indent: %s' % self.indent + return ' '*self.indent + + def childindent(self): + #print 'parse child indent: [%s]' % (self.indent+1) + return ' '*(self.indent+1) + +class Class(Scope): + def __init__(self, name, supers, indent, docstr=''): + Scope.__init__(self,name,indent, docstr) + self.supers = supers + def copy_decl(self,indent=0): + c = Class(self.name,self.supers,indent, self.docstr) + for s in self.subscopes: + c.add(s.copy_decl(indent+1)) + return c + def get_code(self): + str = '%sclass %s' % (self.currentindent(),self.name) + if len(self.supers) > 0: str += '(%s)' % ','.join(self.supers) + str += ':\n' + if len(self.docstr) > 0: str += self.childindent()+'"""'+self.docstr+'"""\n' + if len(self.subscopes) > 0: + for s in self.subscopes: str += s.get_code() + else: + str += '%spass\n' % self.childindent() + return str + + +class Function(Scope): + def __init__(self, name, params, indent, docstr=''): + Scope.__init__(self,name,indent, docstr) + self.params = params + def copy_decl(self,indent=0): + return Function(self.name,self.params,indent, self.docstr) + def get_code(self): + str = "%sdef %s(%s):\n" % \ + (self.currentindent(),self.name,','.join(self.params)) + if len(self.docstr) > 0: str += self.childindent()+'"""'+self.docstr+'"""\n' + str += "%spass\n" % self.childindent() + return str + +class PyParser: + def __init__(self): + self.top = Scope('global',0) + self.scope = self.top + + def _parsedotname(self,pre=None): + #returns (dottedname, nexttoken) + name = [] + if pre is None: + tokentype, token, indent = self.next() + if tokentype != NAME and token != '*': + return ('', token) + else: token = pre + name.append(token) + while True: + tokentype, token, indent = self.next() + if token != '.': break + tokentype, token, indent = self.next() + if tokentype != NAME: break + name.append(token) + return (".".join(name), token) + + def _parseimportlist(self): + imports = [] + while True: + name, token = self._parsedotname() + if not name: break + name2 = '' + if token == 'as': name2, token = self._parsedotname() + imports.append((name, name2)) + while token != "," and "\n" not in token: + tokentype, token, indent = self.next() + if token != ",": break + return imports + + def _parenparse(self): + name = '' + names = [] + level = 1 + while True: + tokentype, token, indent = self.next() + if token in (')', ',') and level == 1: + if '=' not in name: name = name.replace(' ', '') + names.append(name.strip()) + name = '' + if token == '(': + level += 1 + name += "(" + elif token == ')': + level -= 1 + if level == 0: break + else: name += ")" + elif token == ',' and level == 1: + pass + else: + name += "%s " % str(token) + return names + + def _parsefunction(self,indent): + self.scope=self.scope.pop(indent) + tokentype, fname, ind = self.next() + if tokentype != NAME: return None + + tokentype, open, ind = self.next() + if open != '(': return None + params=self._parenparse() + + tokentype, colon, ind = self.next() + if colon != ':': return None + + return Function(fname,params,indent) + + def _parseclass(self,indent): + self.scope=self.scope.pop(indent) + tokentype, cname, ind = self.next() + if tokentype != NAME: return None + + super = [] + tokentype, next, ind = self.next() + if next == '(': + super=self._parenparse() + elif next != ':': return None + + return Class(cname,super,indent) + + def _parseassignment(self): + assign='' + tokentype, token, indent = self.next() + if tokentype == tokenize.STRING or token == 'str': + return '""' + elif token == '(' or token == 'tuple': + return '()' + elif token == '[' or token == 'list': + return '[]' + elif token == '{' or token == 'dict': + return '{}' + elif tokentype == tokenize.NUMBER: + return '0' + elif token == 'open' or token == 'file': + return 'file' + elif token == 'None': + return '_PyCmplNoType()' + elif token == 'type': + return 'type(_PyCmplNoType)' #only for method resolution + else: + assign += token + level = 0 + while True: + tokentype, token, indent = self.next() + if token in ('(','{','['): + level += 1 + elif token in (']','}',')'): + level -= 1 + if level == 0: break + elif level == 0: + if token in (';','\n'): break + assign += token + return "%s" % assign + + def next(self): + type, token, (lineno, indent), end, self.parserline = self.gen.next() + if lineno == self.curline: + #print 'line found [%s] scope=%s' % (line.replace('\n',''),self.scope.name) + self.currentscope = self.scope + return (type, token, indent) + + def _adjustvisibility(self): + newscope = Scope('result',0) + scp = self.currentscope + while scp != None: + if type(scp) == Function: + slice = 0 + #Handle 'self' params + if scp.parent != None and type(scp.parent) == Class: + slice = 1 + newscope.local('%s = %s' % (scp.params[0],scp.parent.name)) + for p in scp.params[slice:]: + i = p.find('=') + if len(p) == 0: continue + pvar = '' + ptype = '' + if i == -1: + pvar = p + ptype = '_PyCmplNoType()' + else: + pvar = p[:i] + ptype = _sanitize(p[i+1:]) + if pvar.startswith('**'): + pvar = pvar[2:] + ptype = '{}' + elif pvar.startswith('*'): + pvar = pvar[1:] + ptype = '[]' + + newscope.local('%s = %s' % (pvar,ptype)) + + for s in scp.subscopes: + ns = s.copy_decl(0) + newscope.add(ns) + for l in scp.locals: newscope.local(l) + scp = scp.parent + + self.currentscope = newscope + return self.currentscope + + #p.parse(vim.current.buffer[:],vim.eval("line('.')")) + def parse(self,text,curline=0): + self.curline = int(curline) + buf = cStringIO.StringIO(''.join(text) + '\n') + self.gen = tokenize.generate_tokens(buf.readline) + self.currentscope = self.scope + + try: + freshscope=True + while True: + tokentype, token, indent = self.next() + #dbg( 'main: token=[%s] indent=[%s]' % (token,indent)) + + if tokentype == DEDENT or token == "pass": + self.scope = self.scope.pop(indent) + elif token == 'def': + func = self._parsefunction(indent) + if func is None: + print "function: syntax error..." + continue + dbg("new scope: function") + freshscope = True + self.scope = self.scope.add(func) + elif token == 'class': + cls = self._parseclass(indent) + if cls is None: + print "class: syntax error..." + continue + freshscope = True + dbg("new scope: class") + self.scope = self.scope.add(cls) + + elif token == 'import': + imports = self._parseimportlist() + for mod, alias in imports: + loc = "import %s" % mod + if len(alias) > 0: loc += " as %s" % alias + self.scope.local(loc) + freshscope = False + elif token == 'from': + mod, token = self._parsedotname() + if not mod or token != "import": + print "from: syntax error..." + continue + names = self._parseimportlist() + for name, alias in names: + loc = "from %s import %s" % (mod,name) + if len(alias) > 0: loc += " as %s" % alias + self.scope.local(loc) + freshscope = False + elif tokentype == STRING: + if freshscope: self.scope.doc(token) + elif tokentype == NAME: + name,token = self._parsedotname(token) + if token == '=': + stmt = self._parseassignment() + dbg("parseassignment: %s = %s" % (name, stmt)) + if stmt != None: + self.scope.local("%s = %s" % (name,stmt)) + freshscope = False + except StopIteration: #thrown on EOF + pass + except: + dbg("parse error: %s, %s @ %s" % + (sys.exc_info()[0], sys.exc_info()[1], self.parserline)) + return self._adjustvisibility() + +def _sanitize(str): + val = '' + level = 0 + for c in str: + if c in ('(','{','['): + level += 1 + elif c in (']','}',')'): + level -= 1 + elif level == 0: + val += c + return val + +sys.path.extend(['.','..']) +PYTHONEOF +endfunction + +call s:DefPython() +" vim: set et ts=4: diff --git a/addons/pythoncomplete/version b/addons/pythoncomplete/version new file mode 100644 index 0000000..9a7d84f --- /dev/null +++ b/addons/pythoncomplete/version @@ -0,0 +1 @@ +0.9 \ No newline at end of file