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