robin/laufey
git clone https://git.robinwobin.dev/robin/laufey
7d0adc08f7
master
1"pythoncomplete.vim - Omni Completion for python 2" Maintainer: <vacancy> 3" Previous Maintainer: Aaron Griffin <aaronmgriffin@gmail.com> 4" Version: 0.10 5" Last Updated: 2026 Jun 21 6" 7" Changes 8" TODO: 9" 'info' item output can use some formatting work 10" Add an "unsafe eval" mode, to allow for return type evaluation 11" Complete basic syntax along with import statements 12" i.e. "import url<c-x,c-o>" 13" Continue parsing on invalid line?? 14" 15" v 0.10 by Vim project 16" * disables importing local modules, unless the global Vim variable 17" g:pythoncomplete_allow_import is set to non-zero 18" * strip default values and annotations from function parameter lists 19" before exec(), and whitelist class base lists to dotted names: the 20" previous code passed buffer-supplied expressions to exec() which 21" Python evaluates at definition time, allowing arbitrary code 22" execution via crafted def/class headers 23" * use repr() on doc strings to prevent code execution 24" 25" v 0.9 26" * Fixed docstring parsing for classes and functions 27" * Fixed parsing of *args and **kwargs type arguments 28" * Better function param parsing to handle things like tuples and 29" lambda defaults args 30" 31" v 0.8 32" * Fixed an issue where the FIRST assignment was always used instead of 33" using a subsequent assignment for a variable 34" * Fixed a scoping issue when working inside a parameterless function 35" 36" 37" v 0.7 38" * Fixed function list sorting (_ and __ at the bottom) 39" * Removed newline removal from docs. It appears vim handles these better in 40" recent patches 41" 42" v 0.6: 43" * Fixed argument completion 44" * Removed the 'kind' completions, as they are better indicated 45" with real syntax 46" * Added tuple assignment parsing (whoops, that was forgotten) 47" * Fixed import handling when flattening scope 48" 49" v 0.5: 50" Yeah, I skipped a version number - 0.4 was never public. 51" It was a bugfix version on top of 0.3. This is a complete 52" rewrite. 53" 54 55if ! has ( 'python' ) 56echo 'Error: Requires python + pynvim. :help provider-python' 57finish 58endif 59 60function ! pythoncomplete#Complete ( findstart , base ) 61"findstart = 1 when we need to get the text length 62if a: findstart == 1 63let line = getline ( '.' ) 64let idx = col ( '.' ) 65while idx > 0 66let idx -= 1 67let c = line [ idx ] 68if c =~ '\w' 69continue 70elseif ! c =~ '\.' 71let idx = -1 72break 73else 74break 75endif 76endwhile 77 78return idx 79"findstart = 0 when we need to return the list of completions 80else 81"vim no longer moves the cursor upon completion... fix that 82let line = getline ( '.' ) 83let idx = col ( '.' ) 84let cword = '' 85while idx > 0 86let idx -= 1 87let c = line [ idx ] 88if c =~ '\w' || c =~ '\.' 89let cword = c . cword 90continue 91elseif strlen ( cword ) > 0 || idx == 0 92break 93endif 94endwhile 95execute "python vimcomplete('" . escape ( cword , "'" ) . "', '" . escape ( a: base , "'" ) . "')" 96return g: pythoncomplete_completions 97endif 98endfunction 99 100function ! s: DefPython () 101python << PYTHONEOF 102import sys ,tokenize ,cStringIO ,types 103from token import NAME ,DEDENT ,NEWLINE ,STRING 104import re 105 106# Used by Class.get_code(): a base class expression is only included in the 107# code passed to exec() if it is a pure dotted name (e.g. "Base", "mod.Base", 108# "pkg.sub.Cls"). Anything containing calls, subscripts, "=", ":" or other 109# operators is dropped, since exec()-ing it would evaluate buffer-supplied 110# expressions. See the security note in the file header. 111_DOTTED_NAME_RE = re .compile (r'^[A-Za-z_]\w*(\s*\.\s*[A-Za-z_]\w*)*$' ) 112 113def _strip_param (p ): 114# Return the bare parameter name from a parameter spec harvested by 115# _parenparse(), discarding any default value or annotation. Default 116# values and annotations would otherwise be evaluated by exec() at 117# function-definition time. Star prefixes ("*args", "**kw") and bare 118# "*" / "/" are preserved as written. 119p = p .split ('=' ,1 )[0 ] 120p = p .split (':' ,1 )[0 ] 121return p .strip () 122 123debugstmts = [] 124def dbg (s ):debugstmts .append (s ) 125def showdbg (): 126for d in debugstmts :"DBG: %s " % d 127 128def vimcomplete (context ,match ): 129global debugstmts 130debugstmts = [] 131try : 132import vim 133def complsort (x ,y ): 134try : 135xa = x ['abbr' ] 136ya = y ['abbr' ] 137if xa [0 ]== '_' : 138if xa [1 ]== '_' and ya [0 :2 ]== '__' : 139return xa > ya 140elif ya [0 :2 ]== '__' : 141return - 1 142elif y [0 ]== '_' : 143return xa > ya 144else : 145return 1 146elif ya [0 ]== '_' : 147return - 1 148else : 149return xa > ya 150except : 151return 0 152cmpl = Completer () 153cmpl .evalsource ('\n' .join (vim .current .buffer ),vim .eval ("line('.')" )) 154all = cmpl .get_completions (context ,match ) 155all .sort (complsort ) 156dictstr = '[' 157# have to do this for double quoting 158for cmpl in all : 159dictstr += '{' 160for x in cmpl :dictstr += '"%s":"%s",' % (x ,cmpl [x ]) 161dictstr += '"icase":0},' 162if dictstr [- 1 ]== ',' :dictstr = dictstr [:- 1 ] 163dictstr += ']' 164#dbg("dict: %s" % dictstr) 165vim .command ("silent let g:pythoncomplete_completions = %s" % dictstr ) 166#dbg("Completion dict:\n%s" % all) 167except vim .error : 168dbg ("VIM Error: %s" % vim .error ) 169 170class Completer (object ): 171def __init__ (self ): 172self .compldict = {} 173self .parser = PyParser () 174 175def evalsource (self ,text ,line = 0 ): 176# vim is imported locally in vimcomplete(); re-import here so the 177# vim.eval() below works (otherwise NameError, silently caught). 178import vim 179sc = self .parser .parse (text ,line ) 180try :allow_imports = int ( 181vim .eval ("get(g:, 'pythoncomplete_allow_import', 0)" )) 182except Exception : 183allow_imports = 0 184src = sc .get_code () 185dbg ("source: %s" % src ) 186try :exec (src )in self .compldict 187except :dbg ("parser: %s, %s" % (sys .exc_info ()[0 ],sys .exc_info ()[1 ])) 188for l in sc .locals : 189# Executing import/from statements harvested from the buffer runs 190# arbitrary package code; only do so when the user opted in. 191if not allow_imports and (l .startswith ('import' ) 192or l .startswith ('from ' )): 193continue 194try :exec (l )in self .compldict 195except :dbg ("locals: %s, %s [%s]" % (sys .exc_info ()[0 ],sys .exc_info ()[1 ],l )) 196 197def _cleanstr (self ,doc ): 198return doc .replace ('"' ,' ' ).replace ("'" ,' ' ) 199 200def get_arguments (self ,func_obj ): 201def _ctor (obj ): 202try :return class_ob .__init__ .im_func 203except AttributeError : 204for base in class_ob .__bases__ : 205rc = _find_constructor (base ) 206if rc is not None :return rc 207return None 208 209arg_offset = 1 210if type (func_obj )== types .ClassType :func_obj = _ctor (func_obj ) 211elif type (func_obj )== types .MethodType :func_obj = func_obj .im_func 212else :arg_offset = 0 213 214arg_text = '' 215if type (func_obj )in [types .FunctionType ,types .LambdaType ]: 216try : 217cd = func_obj .func_code 218real_args = cd .co_varnames [arg_offset :cd .co_argcount ] 219defaults = func_obj .func_defaults or '' 220defaults = map (lambda name :"=%s" % name ,defaults ) 221defaults = ["" ]* (len (real_args )- len (defaults ))+ defaults 222items = map (lambda a ,d :a + d ,real_args ,defaults ) 223if func_obj .func_code .co_flags & 0x4 : 224items .append ("..." ) 225if func_obj .func_code .co_flags & 0x8 : 226items .append ("***" ) 227arg_text = (',' .join (items ))+ ')' 228 229except : 230dbg ("arg completion: %s: %s" % (sys .exc_info ()[0 ],sys .exc_info ()[1 ])) 231pass 232if len (arg_text )== 0 : 233# The doc string sometimes contains the function signature 234# this works for a lot of C modules that are part of the 235# standard library 236doc = func_obj .__doc__ 237if doc : 238doc = doc .lstrip () 239pos = doc .find ('\n' ) 240if pos > 0 : 241sigline = doc [:pos ] 242lidx = sigline .find ('(' ) 243ridx = sigline .find (')' ) 244if lidx > 0 and ridx > 0 : 245arg_text = sigline [lidx + 1 :ridx ]+ ')' 246if len (arg_text )== 0 :arg_text = ')' 247return arg_text 248 249def get_completions (self ,context ,match ): 250dbg ("get_completions('%s','%s')" % (context ,match )) 251stmt = '' 252if context :stmt += str (context ) 253if match :stmt += str (match ) 254try : 255result = None 256all = {} 257ridx = stmt .rfind ('.' ) 258if len (stmt )> 0 and stmt [- 1 ]== '(' : 259result = eval (_sanitize (stmt [:- 1 ]),self .compldict ) 260doc = result .__doc__ 261if doc is None :doc = '' 262args = self .get_arguments (result ) 263return [{'word' :self ._cleanstr (args ),'info' :self ._cleanstr (doc )}] 264elif ridx == - 1 : 265match = stmt 266all = self .compldict 267else : 268match = stmt [ridx + 1 :] 269stmt = _sanitize (stmt [:ridx ]) 270result = eval (stmt ,self .compldict ) 271all = dir (result ) 272 273dbg ("completing: stmt:%s" % stmt ) 274completions = [] 275 276try :maindoc = result .__doc__ 277except :maindoc = ' ' 278if maindoc is None :maindoc = ' ' 279for m in all : 280if m == "_PyCmplNoType" :continue #this is internal 281try : 282dbg ('possible completion: %s' % m ) 283if m .find (match )== 0 : 284if result is None :inst = all [m ] 285else :inst = getattr (result ,m ) 286try :doc = inst .__doc__ 287except :doc = maindoc 288typestr = str (inst ) 289if doc is None or doc == '' :doc = maindoc 290 291wrd = m [len (match ):] 292c = {'word' :wrd ,'abbr' :m ,'info' :self ._cleanstr (doc )} 293if "function" in typestr : 294c ['word' ]+= '(' 295c ['abbr' ]+= '(' + self ._cleanstr (self .get_arguments (inst )) 296elif "method" in typestr : 297c ['word' ]+= '(' 298c ['abbr' ]+= '(' + self ._cleanstr (self .get_arguments (inst )) 299elif "module" in typestr : 300c ['word' ]+= '.' 301elif "class" in typestr : 302c ['word' ]+= '(' 303c ['abbr' ]+= '(' 304completions .append (c ) 305except : 306i = sys .exc_info () 307dbg ("inner completion: %s,%s [stmt='%s']" % (i [0 ],i [1 ],stmt )) 308return completions 309except : 310i = sys .exc_info () 311dbg ("completion: %s,%s [stmt='%s']" % (i [0 ],i [1 ],stmt )) 312return [] 313 314class Scope (object ): 315def __init__ (self ,name ,indent ,docstr = '' ): 316self .subscopes = [] 317self .docstr = docstr 318self .locals = [] 319self .parent = None 320self .name = name 321self .indent = indent 322 323def add (self ,sub ): 324#print 'push scope: [%s@%s]' % (sub.name,sub.indent) 325sub .parent = self 326self .subscopes .append (sub ) 327return sub 328 329def doc (self ,str ): 330""" Clean up a docstring """ 331d = str .replace ('\n' ,' ' ) 332d = d .replace ('\t' ,' ' ) 333while d .find (' ' )> - 1 :d = d .replace (' ' ,' ' ) 334while d [0 ]in '"\'\t ' :d = d [1 :] 335while d [- 1 ]in '"\'\t ' :d = d [:- 1 ] 336dbg ("Scope(%s)::docstr = %s" % (self ,d )) 337self .docstr = d 338 339def local (self ,loc ): 340self ._checkexisting (loc ) 341self .locals .append (loc ) 342 343def copy_decl (self ,indent = 0 ): 344""" Copy a scope's declaration only, at the specified indent level - not local variables """ 345return Scope (self .name ,indent ,self .docstr ) 346 347def _checkexisting (self ,test ): 348"Convienance function... keep out duplicates" 349if test .find ('=' )> - 1 : 350var = test .split ('=' )[0 ].strip () 351for l in self .locals : 352if l .find ('=' )> - 1 and var == l .split ('=' )[0 ].strip (): 353self .locals .remove (l ) 354 355def get_code (self ): 356str = "" 357if len (self .docstr )> 0 :str += repr (self .docstr )+ '\n' 358str += 'class _PyCmplNoType:\n def __getattr__(self,name):\n return None\n' 359for sub in self .subscopes : 360str += sub .get_code () 361for l in self .locals : 362if not l .startswith ('import' )and not l .startswith ('from ' ):str += l + '\n' 363 364return str 365 366def pop (self ,indent ): 367#print 'pop scope: [%s] to [%s]' % (self.indent,indent) 368outer = self 369while outer .parent != None and outer .indent >= indent : 370outer = outer .parent 371return outer 372 373def currentindent (self ): 374#print 'parse current indent: %s' % self.indent 375return ' ' * self .indent 376 377def childindent (self ): 378#print 'parse child indent: [%s]' % (self.indent+1) 379return ' ' * (self .indent + 1 ) 380 381class Class (Scope ): 382def __init__ (self ,name ,supers ,indent ,docstr = '' ): 383Scope .__init__ (self ,name ,indent ,docstr ) 384self .supers = supers 385def copy_decl (self ,indent = 0 ): 386c = Class (self .name ,self .supers ,indent ,self .docstr ) 387for s in self .subscopes : 388c .add (s .copy_decl (indent + 1 )) 389return c 390def get_code (self ): 391str = '%sclass %s' % (self .currentindent (),self .name ) 392# Only include base class expressions that are pure dotted names. 393# Anything else (calls, subscripts, conditionals, ...) is dropped 394# because exec() would evaluate it at class-definition time. See 395# the security note in the file header. 396safe_supers = [s .strip ()for s in self .supers 397if _DOTTED_NAME_RE .match (s .strip ())] 398if len (safe_supers )> 0 :str += '(%s)' % ',' .join (safe_supers ) 399str += ':\n' 400if len (self .docstr )> 0 :str += self .childindent ()+ repr (self .docstr )+ '\n' 401if len (self .subscopes )> 0 : 402for s in self .subscopes :str += s .get_code () 403else : 404str += '%spass\n' % self .childindent () 405return str 406 407 408class Function (Scope ): 409def __init__ (self ,name ,params ,indent ,docstr = '' ): 410Scope .__init__ (self ,name ,indent ,docstr ) 411self .params = params 412def copy_decl (self ,indent = 0 ): 413return Function (self .name ,self .params ,indent ,self .docstr ) 414def get_code (self ): 415# Strip default values and annotations from each parameter before 416# joining: exec() evaluates these at definition time and a hostile 417# buffer could otherwise execute arbitrary code via crafted def 418# headers. See file header for details. 419safe_params = [_strip_param (p )for p in self .params ] 420safe_params = [p for p in safe_params if p ] 421str = "%sdef %s(%s):\n" % \ 422 (self .currentindent (),self .name ,',' .join (safe_params )) 423if len (self .docstr )> 0 :str += self .childindent ()+ repr (self .docstr )+ '\n' 424str += "%spass\n" % self .childindent () 425return str 426 427class PyParser : 428def __init__ (self ): 429self .top = Scope ('global' ,0 ) 430self .scope = self .top 431self .parserline = 0 432 433def _parsedotname (self ,pre = None ): 434#returns (dottedname, nexttoken) 435name = [] 436if pre is None : 437tokentype ,token ,indent = self .next () 438if tokentype != NAME and token != '*' : 439return ('' ,token ) 440else :token = pre 441name .append (token ) 442while True : 443tokentype ,token ,indent = self .next () 444if token != '.' :break 445tokentype ,token ,indent = self .next () 446if tokentype != NAME :break 447name .append (token ) 448return ("." .join (name ),token ) 449 450def _parseimportlist (self ): 451imports = [] 452while True : 453name ,token = self ._parsedotname () 454if not name :break 455name2 = '' 456if token == 'as' :name2 ,token = self ._parsedotname () 457imports .append ((name ,name2 )) 458while token != "," and "\n" not in token : 459tokentype ,token ,indent = self .next () 460if token != "," :break 461return imports 462 463def _parenparse (self ): 464name = '' 465names = [] 466level = 1 467while True : 468tokentype ,token ,indent = self .next () 469if token in (')' ,',' )and level == 1 : 470if '=' not in name :name = name .replace (' ' ,'' ) 471names .append (name .strip ()) 472name = '' 473if token == '(' : 474level += 1 475name += "(" 476elif token == ')' : 477level -= 1 478if level == 0 :break 479else :name += ")" 480elif token == ',' and level == 1 : 481pass 482else : 483name += "%s " % str (token ) 484return names 485 486def _parsefunction (self ,indent ): 487self .scope = self .scope .pop (indent ) 488tokentype ,fname ,ind = self .next () 489if tokentype != NAME :return None 490 491tokentype ,open ,ind = self .next () 492if open != '(' :return None 493params = self ._parenparse () 494 495tokentype ,colon ,ind = self .next () 496if colon != ':' :return None 497 498return Function (fname ,params ,indent ) 499 500def _parseclass (self ,indent ): 501self .scope = self .scope .pop (indent ) 502tokentype ,cname ,ind = self .next () 503if tokentype != NAME :return None 504 505super = [] 506tokentype ,next ,ind = self .next () 507if next == '(' : 508super = self ._parenparse () 509elif next != ':' :return None 510 511return Class (cname ,super ,indent ) 512 513def _parseassignment (self ): 514assign = '' 515tokentype ,token ,indent = self .next () 516if tokentype == tokenize .STRING or token == 'str' : 517return '""' 518elif token == '(' or token == 'tuple' : 519return '()' 520elif token == '[' or token == 'list' : 521return '[]' 522elif token == '{' or token == 'dict' : 523return '{}' 524elif tokentype == tokenize .NUMBER : 525return '0' 526elif token == 'open' or token == 'file' : 527return 'file' 528elif token == 'None' : 529return '_PyCmplNoType()' 530elif token == 'type' : 531return 'type(_PyCmplNoType)' #only for method resolution 532else : 533assign += token 534level = 0 535while True : 536tokentype ,token ,indent = self .next () 537if token in ('(' ,'{' ,'[' ): 538level += 1 539elif token in (']' ,'}' ,')' ): 540level -= 1 541if level == 0 :break 542elif level == 0 : 543if token in (';' ,'\n' ):break 544assign += token 545return "%s" % assign 546 547def next (self ): 548type ,token , (lineno ,indent ),end ,self .parserline = self .gen .next () 549if lineno == self .curline : 550#print 'line found [%s] scope=%s' % (line.replace('\n',''),self.scope.name) 551self .currentscope = self .scope 552return (type ,token ,indent ) 553 554def _adjustvisibility (self ): 555newscope = Scope ('result' ,0 ) 556scp = self .currentscope 557while scp != None : 558if type (scp )== Function : 559slice = 0 560#Handle 'self' params 561if scp .parent != None and type (scp .parent )== Class : 562slice = 1 563newscope .local ('%s = %s' % (scp .params [0 ],scp .parent .name )) 564for p in scp .params [slice :]: 565i = p .find ('=' ) 566if len (p )== 0 :continue 567pvar = '' 568ptype = '' 569if i == - 1 : 570pvar = p 571ptype = '_PyCmplNoType()' 572else : 573pvar = p [:i ] 574ptype = _sanitize (p [i + 1 :]) 575if pvar .startswith ('**' ): 576pvar = pvar [2 :] 577ptype = '{}' 578elif pvar .startswith ('*' ): 579pvar = pvar [1 :] 580ptype = '[]' 581 582newscope .local ('%s = %s' % (pvar ,ptype )) 583 584for s in scp .subscopes : 585ns = s .copy_decl (0 ) 586newscope .add (ns ) 587for l in scp .locals :newscope .local (l ) 588scp = scp .parent 589 590self .currentscope = newscope 591return self .currentscope 592 593#p.parse(vim.current.buffer[:],vim.eval("line('.')")) 594def parse (self ,text ,curline = 0 ): 595self .curline = int (curline ) 596buf = cStringIO .StringIO ('' .join (text )+ '\n' ) 597self .gen = tokenize .generate_tokens (buf .readline ) 598self .currentscope = self .scope 599 600try : 601freshscope = True 602while True : 603tokentype ,token ,indent = self .next () 604#dbg( 'main: token=[%s] indent=[%s]' % (token,indent)) 605 606if tokentype == DEDENT or token == "pass" : 607self .scope = self .scope .pop (indent ) 608elif token == 'def' : 609func = self ._parsefunction (indent ) 610if func is None : 611"function: syntax error..." 612continue 613dbg ("new scope: function" ) 614freshscope = True 615self .scope = self .scope .add (func ) 616elif token == 'class' : 617cls = self ._parseclass (indent ) 618if cls is None : 619"class: syntax error..." 620continue 621freshscope = True 622dbg ("new scope: class" ) 623self .scope = self .scope .add (cls ) 624 625elif token == 'import' : 626imports = self ._parseimportlist () 627for mod ,alias in imports : 628loc = "import %s" % mod 629if len (alias )> 0 :loc += " as %s" % alias 630self .scope .local (loc ) 631freshscope = False 632elif token == 'from' : 633mod ,token = self ._parsedotname () 634if not mod or token != "import" : 635"from: syntax error..." 636continue 637names = self ._parseimportlist () 638for name ,alias in names : 639loc = "from %s import %s" % (mod ,name ) 640if len (alias )> 0 :loc += " as %s" % alias 641self .scope .local (loc ) 642freshscope = False 643elif tokentype == STRING : 644if freshscope :self .scope .doc (token ) 645elif tokentype == NAME : 646name ,token = self ._parsedotname (token ) 647if token == '=' : 648stmt = self ._parseassignment () 649dbg ("parseassignment: %s = %s" % (name ,stmt )) 650if stmt != None : 651self .scope .local ("%s = %s" % (name ,stmt )) 652freshscope = False 653except StopIteration :#thrown on EOF 654pass 655except : 656dbg ("parse error: %s, %s @ %s" % 657 (sys .exc_info ()[0 ],sys .exc_info ()[1 ],self .parserline )) 658return self ._adjustvisibility () 659 660def _sanitize (str ): 661val = '' 662level = 0 663for c in str : 664if c in ('(' ,'{' ,'[' ): 665level += 1 666elif c in (']' ,'}' ,')' ): 667level -= 1 668elif level == 0 : 669val += c 670return val 671 672sys .path .extend (['.' ,'..' ]) 673PYTHONEOF 674endfunction 675 676call s: DefPython () 677" vim: set et ts=4: