completer.py 72 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118
  1. """Completion for IPython.
  2. This module started as fork of the rlcompleter module in the Python standard
  3. library. The original enhancements made to rlcompleter have been sent
  4. upstream and were accepted as of Python 2.3,
  5. This module now support a wide variety of completion mechanism both available
  6. for normal classic Python code, as well as completer for IPython specific
  7. Syntax like magics.
  8. Latex and Unicode completion
  9. ============================
  10. IPython and compatible frontends not only can complete your code, but can help
  11. you to input a wide range of characters. In particular we allow you to insert
  12. a unicode character using the tab completion mechanism.
  13. Forward latex/unicode completion
  14. --------------------------------
  15. Forward completion allows you to easily type a unicode character using its latex
  16. name, or unicode long description. To do so type a backslash follow by the
  17. relevant name and press tab:
  18. Using latex completion:
  19. .. code::
  20. \\alpha<tab>
  21. α
  22. or using unicode completion:
  23. .. code::
  24. \\greek small letter alpha<tab>
  25. α
  26. Only valid Python identifiers will complete. Combining characters (like arrow or
  27. dots) are also available, unlike latex they need to be put after the their
  28. counterpart that is to say, `F\\\\vec<tab>` is correct, not `\\\\vec<tab>F`.
  29. Some browsers are known to display combining characters incorrectly.
  30. Backward latex completion
  31. -------------------------
  32. It is sometime challenging to know how to type a character, if you are using
  33. IPython, or any compatible frontend you can prepend backslash to the character
  34. and press `<tab>` to expand it to its latex form.
  35. .. code::
  36. \\α<tab>
  37. \\alpha
  38. Both forward and backward completions can be deactivated by setting the
  39. ``Completer.backslash_combining_completions`` option to ``False``.
  40. Experimental
  41. ============
  42. Starting with IPython 6.0, this module can make use of the Jedi library to
  43. generate completions both using static analysis of the code, and dynamically
  44. inspecting multiple namespaces. Jedi is an autocompletion and static analysis
  45. for Python. The APIs attached to this new mechanism is unstable and will
  46. raise unless use in an :any:`provisionalcompleter` context manager.
  47. You will find that the following are experimental:
  48. - :any:`provisionalcompleter`
  49. - :any:`IPCompleter.completions`
  50. - :any:`Completion`
  51. - :any:`rectify_completions`
  52. .. note::
  53. better name for :any:`rectify_completions` ?
  54. We welcome any feedback on these new API, and we also encourage you to try this
  55. module in debug mode (start IPython with ``--Completer.debug=True``) in order
  56. to have extra logging information if :any:`jedi` is crashing, or if current
  57. IPython completer pending deprecations are returning results not yet handled
  58. by :any:`jedi`
  59. Using Jedi for tab completion allow snippets like the following to work without
  60. having to execute any code:
  61. >>> myvar = ['hello', 42]
  62. ... myvar[1].bi<tab>
  63. Tab completion will be able to infer that ``myvar[1]`` is a real number without
  64. executing any code unlike the previously available ``IPCompleter.greedy``
  65. option.
  66. Be sure to update :any:`jedi` to the latest stable version or to try the
  67. current development version to get better completions.
  68. """
  69. # Copyright (c) IPython Development Team.
  70. # Distributed under the terms of the Modified BSD License.
  71. #
  72. # Some of this code originated from rlcompleter in the Python standard library
  73. # Copyright (C) 2001 Python Software Foundation, www.python.org
  74. import builtins as builtin_mod
  75. import glob
  76. import inspect
  77. import itertools
  78. import keyword
  79. import os
  80. import re
  81. import string
  82. import sys
  83. import time
  84. import unicodedata
  85. import warnings
  86. from contextlib import contextmanager
  87. from importlib import import_module
  88. from types import SimpleNamespace
  89. from typing import Iterable, Iterator, List, Tuple
  90. from IPython.core.error import TryNext
  91. from IPython.core.inputtransformer2 import ESC_MAGIC
  92. from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
  93. from IPython.core.oinspect import InspectColors
  94. from IPython.utils import generics
  95. from IPython.utils.dir2 import dir2, get_real_method
  96. from IPython.utils.process import arg_split
  97. from traitlets import Bool, Enum, Int, observe
  98. from traitlets.config.configurable import Configurable
  99. import __main__
  100. # skip module docstests
  101. skip_doctest = True
  102. try:
  103. import jedi
  104. jedi.settings.case_insensitive_completion = False
  105. import jedi.api.helpers
  106. import jedi.api.classes
  107. JEDI_INSTALLED = True
  108. except ImportError:
  109. JEDI_INSTALLED = False
  110. #-----------------------------------------------------------------------------
  111. # Globals
  112. #-----------------------------------------------------------------------------
  113. # Public API
  114. __all__ = ['Completer','IPCompleter']
  115. if sys.platform == 'win32':
  116. PROTECTABLES = ' '
  117. else:
  118. PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
  119. # Protect against returning an enormous number of completions which the frontend
  120. # may have trouble processing.
  121. MATCHES_LIMIT = 500
  122. class Sentinel:
  123. def __repr__(self):
  124. return "<deprecated sentinel>"
  125. _deprecation_readline_sentinel = Sentinel()
  126. class ProvisionalCompleterWarning(FutureWarning):
  127. """
  128. Exception raise by an experimental feature in this module.
  129. Wrap code in :any:`provisionalcompleter` context manager if you
  130. are certain you want to use an unstable feature.
  131. """
  132. pass
  133. warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
  134. @contextmanager
  135. def provisionalcompleter(action='ignore'):
  136. """
  137. This context manager has to be used in any place where unstable completer
  138. behavior and API may be called.
  139. >>> with provisionalcompleter():
  140. ... completer.do_experimental_things() # works
  141. >>> completer.do_experimental_things() # raises.
  142. .. note::
  143. Unstable
  144. By using this context manager you agree that the API in use may change
  145. without warning, and that you won't complain if they do so.
  146. You also understand that, if the API is not to your liking, you should report
  147. a bug to explain your use case upstream.
  148. We'll be happy to get your feedback, feature requests, and improvements on
  149. any of the unstable APIs!
  150. """
  151. with warnings.catch_warnings():
  152. warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
  153. yield
  154. def has_open_quotes(s):
  155. """Return whether a string has open quotes.
  156. This simply counts whether the number of quote characters of either type in
  157. the string is odd.
  158. Returns
  159. -------
  160. If there is an open quote, the quote character is returned. Else, return
  161. False.
  162. """
  163. # We check " first, then ', so complex cases with nested quotes will get
  164. # the " to take precedence.
  165. if s.count('"') % 2:
  166. return '"'
  167. elif s.count("'") % 2:
  168. return "'"
  169. else:
  170. return False
  171. def protect_filename(s, protectables=PROTECTABLES):
  172. """Escape a string to protect certain characters."""
  173. if set(s) & set(protectables):
  174. if sys.platform == "win32":
  175. return '"' + s + '"'
  176. else:
  177. return "".join(("\\" + c if c in protectables else c) for c in s)
  178. else:
  179. return s
  180. def expand_user(path:str) -> Tuple[str, bool, str]:
  181. """Expand ``~``-style usernames in strings.
  182. This is similar to :func:`os.path.expanduser`, but it computes and returns
  183. extra information that will be useful if the input was being used in
  184. computing completions, and you wish to return the completions with the
  185. original '~' instead of its expanded value.
  186. Parameters
  187. ----------
  188. path : str
  189. String to be expanded. If no ~ is present, the output is the same as the
  190. input.
  191. Returns
  192. -------
  193. newpath : str
  194. Result of ~ expansion in the input path.
  195. tilde_expand : bool
  196. Whether any expansion was performed or not.
  197. tilde_val : str
  198. The value that ~ was replaced with.
  199. """
  200. # Default values
  201. tilde_expand = False
  202. tilde_val = ''
  203. newpath = path
  204. if path.startswith('~'):
  205. tilde_expand = True
  206. rest = len(path)-1
  207. newpath = os.path.expanduser(path)
  208. if rest:
  209. tilde_val = newpath[:-rest]
  210. else:
  211. tilde_val = newpath
  212. return newpath, tilde_expand, tilde_val
  213. def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
  214. """Does the opposite of expand_user, with its outputs.
  215. """
  216. if tilde_expand:
  217. return path.replace(tilde_val, '~')
  218. else:
  219. return path
  220. def completions_sorting_key(word):
  221. """key for sorting completions
  222. This does several things:
  223. - Demote any completions starting with underscores to the end
  224. - Insert any %magic and %%cellmagic completions in the alphabetical order
  225. by their name
  226. """
  227. prio1, prio2 = 0, 0
  228. if word.startswith('__'):
  229. prio1 = 2
  230. elif word.startswith('_'):
  231. prio1 = 1
  232. if word.endswith('='):
  233. prio1 = -1
  234. if word.startswith('%%'):
  235. # If there's another % in there, this is something else, so leave it alone
  236. if not "%" in word[2:]:
  237. word = word[2:]
  238. prio2 = 2
  239. elif word.startswith('%'):
  240. if not "%" in word[1:]:
  241. word = word[1:]
  242. prio2 = 1
  243. return prio1, word, prio2
  244. class _FakeJediCompletion:
  245. """
  246. This is a workaround to communicate to the UI that Jedi has crashed and to
  247. report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
  248. Added in IPython 6.0 so should likely be removed for 7.0
  249. """
  250. def __init__(self, name):
  251. self.name = name
  252. self.complete = name
  253. self.type = 'crashed'
  254. self.name_with_symbols = name
  255. self.signature = ''
  256. self._origin = 'fake'
  257. def __repr__(self):
  258. return '<Fake completion object jedi has crashed>'
  259. class Completion:
  260. """
  261. Completion object used and return by IPython completers.
  262. .. warning::
  263. Unstable
  264. This function is unstable, API may change without warning.
  265. It will also raise unless use in proper context manager.
  266. This act as a middle ground :any:`Completion` object between the
  267. :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
  268. object. While Jedi need a lot of information about evaluator and how the
  269. code should be ran/inspected, PromptToolkit (and other frontend) mostly
  270. need user facing information.
  271. - Which range should be replaced replaced by what.
  272. - Some metadata (like completion type), or meta information to displayed to
  273. the use user.
  274. For debugging purpose we can also store the origin of the completion (``jedi``,
  275. ``IPython.python_matches``, ``IPython.magics_matches``...).
  276. """
  277. __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
  278. def __init__(self, start: int, end: int, text: str, *, type: str=None, _origin='', signature='') -> None:
  279. warnings.warn("``Completion`` is a provisional API (as of IPython 6.0). "
  280. "It may change without warnings. "
  281. "Use in corresponding context manager.",
  282. category=ProvisionalCompleterWarning, stacklevel=2)
  283. self.start = start
  284. self.end = end
  285. self.text = text
  286. self.type = type
  287. self.signature = signature
  288. self._origin = _origin
  289. def __repr__(self):
  290. return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
  291. (self.start, self.end, self.text, self.type or '?', self.signature or '?')
  292. def __eq__(self, other)->Bool:
  293. """
  294. Equality and hash do not hash the type (as some completer may not be
  295. able to infer the type), but are use to (partially) de-duplicate
  296. completion.
  297. Completely de-duplicating completion is a bit tricker that just
  298. comparing as it depends on surrounding text, which Completions are not
  299. aware of.
  300. """
  301. return self.start == other.start and \
  302. self.end == other.end and \
  303. self.text == other.text
  304. def __hash__(self):
  305. return hash((self.start, self.end, self.text))
  306. _IC = Iterable[Completion]
  307. def _deduplicate_completions(text: str, completions: _IC)-> _IC:
  308. """
  309. Deduplicate a set of completions.
  310. .. warning::
  311. Unstable
  312. This function is unstable, API may change without warning.
  313. Parameters
  314. ----------
  315. text: str
  316. text that should be completed.
  317. completions: Iterator[Completion]
  318. iterator over the completions to deduplicate
  319. Yields
  320. ------
  321. `Completions` objects
  322. Completions coming from multiple sources, may be different but end up having
  323. the same effect when applied to ``text``. If this is the case, this will
  324. consider completions as equal and only emit the first encountered.
  325. Not folded in `completions()` yet for debugging purpose, and to detect when
  326. the IPython completer does return things that Jedi does not, but should be
  327. at some point.
  328. """
  329. completions = list(completions)
  330. if not completions:
  331. return
  332. new_start = min(c.start for c in completions)
  333. new_end = max(c.end for c in completions)
  334. seen = set()
  335. for c in completions:
  336. new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
  337. if new_text not in seen:
  338. yield c
  339. seen.add(new_text)
  340. def rectify_completions(text: str, completions: _IC, *, _debug=False)->_IC:
  341. """
  342. Rectify a set of completions to all have the same ``start`` and ``end``
  343. .. warning::
  344. Unstable
  345. This function is unstable, API may change without warning.
  346. It will also raise unless use in proper context manager.
  347. Parameters
  348. ----------
  349. text: str
  350. text that should be completed.
  351. completions: Iterator[Completion]
  352. iterator over the completions to rectify
  353. :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
  354. the Jupyter Protocol requires them to behave like so. This will readjust
  355. the completion to have the same ``start`` and ``end`` by padding both
  356. extremities with surrounding text.
  357. During stabilisation should support a ``_debug`` option to log which
  358. completion are return by the IPython completer and not found in Jedi in
  359. order to make upstream bug report.
  360. """
  361. warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
  362. "It may change without warnings. "
  363. "Use in corresponding context manager.",
  364. category=ProvisionalCompleterWarning, stacklevel=2)
  365. completions = list(completions)
  366. if not completions:
  367. return
  368. starts = (c.start for c in completions)
  369. ends = (c.end for c in completions)
  370. new_start = min(starts)
  371. new_end = max(ends)
  372. seen_jedi = set()
  373. seen_python_matches = set()
  374. for c in completions:
  375. new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
  376. if c._origin == 'jedi':
  377. seen_jedi.add(new_text)
  378. elif c._origin == 'IPCompleter.python_matches':
  379. seen_python_matches.add(new_text)
  380. yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
  381. diff = seen_python_matches.difference(seen_jedi)
  382. if diff and _debug:
  383. print('IPython.python matches have extras:', diff)
  384. if sys.platform == 'win32':
  385. DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
  386. else:
  387. DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
  388. GREEDY_DELIMS = ' =\r\n'
  389. class CompletionSplitter(object):
  390. """An object to split an input line in a manner similar to readline.
  391. By having our own implementation, we can expose readline-like completion in
  392. a uniform manner to all frontends. This object only needs to be given the
  393. line of text to be split and the cursor position on said line, and it
  394. returns the 'word' to be completed on at the cursor after splitting the
  395. entire line.
  396. What characters are used as splitting delimiters can be controlled by
  397. setting the ``delims`` attribute (this is a property that internally
  398. automatically builds the necessary regular expression)"""
  399. # Private interface
  400. # A string of delimiter characters. The default value makes sense for
  401. # IPython's most typical usage patterns.
  402. _delims = DELIMS
  403. # The expression (a normal string) to be compiled into a regular expression
  404. # for actual splitting. We store it as an attribute mostly for ease of
  405. # debugging, since this type of code can be so tricky to debug.
  406. _delim_expr = None
  407. # The regular expression that does the actual splitting
  408. _delim_re = None
  409. def __init__(self, delims=None):
  410. delims = CompletionSplitter._delims if delims is None else delims
  411. self.delims = delims
  412. @property
  413. def delims(self):
  414. """Return the string of delimiter characters."""
  415. return self._delims
  416. @delims.setter
  417. def delims(self, delims):
  418. """Set the delimiters for line splitting."""
  419. expr = '[' + ''.join('\\'+ c for c in delims) + ']'
  420. self._delim_re = re.compile(expr)
  421. self._delims = delims
  422. self._delim_expr = expr
  423. def split_line(self, line, cursor_pos=None):
  424. """Split a line of text with a cursor at the given position.
  425. """
  426. l = line if cursor_pos is None else line[:cursor_pos]
  427. return self._delim_re.split(l)[-1]
  428. class Completer(Configurable):
  429. greedy = Bool(False,
  430. help="""Activate greedy completion
  431. PENDING DEPRECTION. this is now mostly taken care of with Jedi.
  432. This will enable completion on elements of lists, results of function calls, etc.,
  433. but can be unsafe because the code is actually evaluated on TAB.
  434. """
  435. ).tag(config=True)
  436. use_jedi = Bool(default_value=JEDI_INSTALLED,
  437. help="Experimental: Use Jedi to generate autocompletions. "
  438. "Default to True if jedi is installed.").tag(config=True)
  439. jedi_compute_type_timeout = Int(default_value=400,
  440. help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
  441. Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
  442. performance by preventing jedi to build its cache.
  443. """).tag(config=True)
  444. debug = Bool(default_value=False,
  445. help='Enable debug for the Completer. Mostly print extra '
  446. 'information for experimental jedi integration.')\
  447. .tag(config=True)
  448. backslash_combining_completions = Bool(True,
  449. help="Enable unicode completions, e.g. \\alpha<tab> . "
  450. "Includes completion of latex commands, unicode names, and expanding "
  451. "unicode characters back to latex commands.").tag(config=True)
  452. def __init__(self, namespace=None, global_namespace=None, **kwargs):
  453. """Create a new completer for the command line.
  454. Completer(namespace=ns, global_namespace=ns2) -> completer instance.
  455. If unspecified, the default namespace where completions are performed
  456. is __main__ (technically, __main__.__dict__). Namespaces should be
  457. given as dictionaries.
  458. An optional second namespace can be given. This allows the completer
  459. to handle cases where both the local and global scopes need to be
  460. distinguished.
  461. """
  462. # Don't bind to namespace quite yet, but flag whether the user wants a
  463. # specific namespace or to use __main__.__dict__. This will allow us
  464. # to bind to __main__.__dict__ at completion time, not now.
  465. if namespace is None:
  466. self.use_main_ns = True
  467. else:
  468. self.use_main_ns = False
  469. self.namespace = namespace
  470. # The global namespace, if given, can be bound directly
  471. if global_namespace is None:
  472. self.global_namespace = {}
  473. else:
  474. self.global_namespace = global_namespace
  475. self.custom_matchers = []
  476. super(Completer, self).__init__(**kwargs)
  477. def complete(self, text, state):
  478. """Return the next possible completion for 'text'.
  479. This is called successively with state == 0, 1, 2, ... until it
  480. returns None. The completion should begin with 'text'.
  481. """
  482. if self.use_main_ns:
  483. self.namespace = __main__.__dict__
  484. if state == 0:
  485. if "." in text:
  486. self.matches = self.attr_matches(text)
  487. else:
  488. self.matches = self.global_matches(text)
  489. try:
  490. return self.matches[state]
  491. except IndexError:
  492. return None
  493. def global_matches(self, text):
  494. """Compute matches when text is a simple name.
  495. Return a list of all keywords, built-in functions and names currently
  496. defined in self.namespace or self.global_namespace that match.
  497. """
  498. matches = []
  499. match_append = matches.append
  500. n = len(text)
  501. for lst in [keyword.kwlist,
  502. builtin_mod.__dict__.keys(),
  503. self.namespace.keys(),
  504. self.global_namespace.keys()]:
  505. for word in lst:
  506. if word[:n] == text and word != "__builtins__":
  507. match_append(word)
  508. snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
  509. for lst in [self.namespace.keys(),
  510. self.global_namespace.keys()]:
  511. shortened = {"_".join([sub[0] for sub in word.split('_')]) : word
  512. for word in lst if snake_case_re.match(word)}
  513. for word in shortened.keys():
  514. if word[:n] == text and word != "__builtins__":
  515. match_append(shortened[word])
  516. return matches
  517. def attr_matches(self, text):
  518. """Compute matches when text contains a dot.
  519. Assuming the text is of the form NAME.NAME....[NAME], and is
  520. evaluatable in self.namespace or self.global_namespace, it will be
  521. evaluated and its attributes (as revealed by dir()) are used as
  522. possible completions. (For class instances, class members are
  523. also considered.)
  524. WARNING: this can still invoke arbitrary C code, if an object
  525. with a __getattr__ hook is evaluated.
  526. """
  527. # Another option, seems to work great. Catches things like ''.<tab>
  528. m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
  529. if m:
  530. expr, attr = m.group(1, 3)
  531. elif self.greedy:
  532. m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
  533. if not m2:
  534. return []
  535. expr, attr = m2.group(1,2)
  536. else:
  537. return []
  538. try:
  539. obj = eval(expr, self.namespace)
  540. except:
  541. try:
  542. obj = eval(expr, self.global_namespace)
  543. except:
  544. return []
  545. if self.limit_to__all__ and hasattr(obj, '__all__'):
  546. words = get__all__entries(obj)
  547. else:
  548. words = dir2(obj)
  549. try:
  550. words = generics.complete_object(obj, words)
  551. except TryNext:
  552. pass
  553. except AssertionError:
  554. raise
  555. except Exception:
  556. # Silence errors from completion function
  557. #raise # dbg
  558. pass
  559. # Build match list to return
  560. n = len(attr)
  561. return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
  562. def get__all__entries(obj):
  563. """returns the strings in the __all__ attribute"""
  564. try:
  565. words = getattr(obj, '__all__')
  566. except:
  567. return []
  568. return [w for w in words if isinstance(w, str)]
  569. def match_dict_keys(keys: List[str], prefix: str, delims: str):
  570. """Used by dict_key_matches, matching the prefix to a list of keys
  571. Parameters
  572. ==========
  573. keys:
  574. list of keys in dictionary currently being completed.
  575. prefix:
  576. Part of the text already typed by the user. e.g. `mydict[b'fo`
  577. delims:
  578. String of delimiters to consider when finding the current key.
  579. Returns
  580. =======
  581. A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
  582. ``quote`` being the quote that need to be used to close current string.
  583. ``token_start`` the position where the replacement should start occurring,
  584. ``matches`` a list of replacement/completion
  585. """
  586. if not prefix:
  587. return None, 0, [repr(k) for k in keys
  588. if isinstance(k, (str, bytes))]
  589. quote_match = re.search('["\']', prefix)
  590. quote = quote_match.group()
  591. try:
  592. prefix_str = eval(prefix + quote, {})
  593. except Exception:
  594. return None, 0, []
  595. pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
  596. token_match = re.search(pattern, prefix, re.UNICODE)
  597. token_start = token_match.start()
  598. token_prefix = token_match.group()
  599. matched = []
  600. for key in keys:
  601. try:
  602. if not key.startswith(prefix_str):
  603. continue
  604. except (AttributeError, TypeError, UnicodeError):
  605. # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
  606. continue
  607. # reformat remainder of key to begin with prefix
  608. rem = key[len(prefix_str):]
  609. # force repr wrapped in '
  610. rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
  611. if rem_repr.startswith('u') and prefix[0] not in 'uU':
  612. # Found key is unicode, but prefix is Py2 string.
  613. # Therefore attempt to interpret key as string.
  614. try:
  615. rem_repr = repr(rem.encode('ascii') + '"')
  616. except UnicodeEncodeError:
  617. continue
  618. rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
  619. if quote == '"':
  620. # The entered prefix is quoted with ",
  621. # but the match is quoted with '.
  622. # A contained " hence needs escaping for comparison:
  623. rem_repr = rem_repr.replace('"', '\\"')
  624. # then reinsert prefix from start of token
  625. matched.append('%s%s' % (token_prefix, rem_repr))
  626. return quote, token_start, matched
  627. def cursor_to_position(text:str, line:int, column:int)->int:
  628. """
  629. Convert the (line,column) position of the cursor in text to an offset in a
  630. string.
  631. Parameters
  632. ----------
  633. text : str
  634. The text in which to calculate the cursor offset
  635. line : int
  636. Line of the cursor; 0-indexed
  637. column : int
  638. Column of the cursor 0-indexed
  639. Return
  640. ------
  641. Position of the cursor in ``text``, 0-indexed.
  642. See Also
  643. --------
  644. position_to_cursor: reciprocal of this function
  645. """
  646. lines = text.split('\n')
  647. assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
  648. return sum(len(l) + 1 for l in lines[:line]) + column
  649. def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
  650. """
  651. Convert the position of the cursor in text (0 indexed) to a line
  652. number(0-indexed) and a column number (0-indexed) pair
  653. Position should be a valid position in ``text``.
  654. Parameters
  655. ----------
  656. text : str
  657. The text in which to calculate the cursor offset
  658. offset : int
  659. Position of the cursor in ``text``, 0-indexed.
  660. Return
  661. ------
  662. (line, column) : (int, int)
  663. Line of the cursor; 0-indexed, column of the cursor 0-indexed
  664. See Also
  665. --------
  666. cursor_to_position : reciprocal of this function
  667. """
  668. assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
  669. before = text[:offset]
  670. blines = before.split('\n') # ! splitnes trim trailing \n
  671. line = before.count('\n')
  672. col = len(blines[-1])
  673. return line, col
  674. def _safe_isinstance(obj, module, class_name):
  675. """Checks if obj is an instance of module.class_name if loaded
  676. """
  677. return (module in sys.modules and
  678. isinstance(obj, getattr(import_module(module), class_name)))
  679. def back_unicode_name_matches(text):
  680. u"""Match unicode characters back to unicode name
  681. This does ``☃`` -> ``\\snowman``
  682. Note that snowman is not a valid python3 combining character but will be expanded.
  683. Though it will not recombine back to the snowman character by the completion machinery.
  684. This will not either back-complete standard sequences like \\n, \\b ...
  685. Used on Python 3 only.
  686. """
  687. if len(text)<2:
  688. return u'', ()
  689. maybe_slash = text[-2]
  690. if maybe_slash != '\\':
  691. return u'', ()
  692. char = text[-1]
  693. # no expand on quote for completion in strings.
  694. # nor backcomplete standard ascii keys
  695. if char in string.ascii_letters or char in ['"',"'"]:
  696. return u'', ()
  697. try :
  698. unic = unicodedata.name(char)
  699. return '\\'+char,['\\'+unic]
  700. except KeyError:
  701. pass
  702. return u'', ()
  703. def back_latex_name_matches(text:str):
  704. """Match latex characters back to unicode name
  705. This does ``\\ℵ`` -> ``\\aleph``
  706. Used on Python 3 only.
  707. """
  708. if len(text)<2:
  709. return u'', ()
  710. maybe_slash = text[-2]
  711. if maybe_slash != '\\':
  712. return u'', ()
  713. char = text[-1]
  714. # no expand on quote for completion in strings.
  715. # nor backcomplete standard ascii keys
  716. if char in string.ascii_letters or char in ['"',"'"]:
  717. return u'', ()
  718. try :
  719. latex = reverse_latex_symbol[char]
  720. # '\\' replace the \ as well
  721. return '\\'+char,[latex]
  722. except KeyError:
  723. pass
  724. return u'', ()
  725. def _formatparamchildren(parameter) -> str:
  726. """
  727. Get parameter name and value from Jedi Private API
  728. Jedi does not expose a simple way to get `param=value` from its API.
  729. Parameter
  730. =========
  731. parameter:
  732. Jedi's function `Param`
  733. Returns
  734. =======
  735. A string like 'a', 'b=1', '*args', '**kwargs'
  736. """
  737. description = parameter.description
  738. if not description.startswith('param '):
  739. raise ValueError('Jedi function parameter description have change format.'
  740. 'Expected "param ...", found %r".' % description)
  741. return description[6:]
  742. def _make_signature(completion)-> str:
  743. """
  744. Make the signature from a jedi completion
  745. Parameter
  746. =========
  747. completion: jedi.Completion
  748. object does not complete a function type
  749. Returns
  750. =======
  751. a string consisting of the function signature, with the parenthesis but
  752. without the function name. example:
  753. `(a, *args, b=1, **kwargs)`
  754. """
  755. return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for p in completion.params) if f])
  756. # it looks like this might work on jedi 0.17
  757. if hasattr(completion, 'get_signatures'):
  758. signatures = completion.get_signatures()
  759. if not signatures:
  760. return '(?)'
  761. c0 = completion.get_signatures()[0]
  762. return '('+c0.to_string().split('(', maxsplit=1)[1]
  763. return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
  764. for p in signature.defined_names()) if f])
  765. class IPCompleter(Completer):
  766. """Extension of the completer class with IPython-specific features"""
  767. _names = None
  768. @observe('greedy')
  769. def _greedy_changed(self, change):
  770. """update the splitter and readline delims when greedy is changed"""
  771. if change['new']:
  772. self.splitter.delims = GREEDY_DELIMS
  773. else:
  774. self.splitter.delims = DELIMS
  775. dict_keys_only = Bool(False,
  776. help="""Whether to show dict key matches only""")
  777. merge_completions = Bool(True,
  778. help="""Whether to merge completion results into a single list
  779. If False, only the completion results from the first non-empty
  780. completer will be returned.
  781. """
  782. ).tag(config=True)
  783. omit__names = Enum((0,1,2), default_value=2,
  784. help="""Instruct the completer to omit private method names
  785. Specifically, when completing on ``object.<tab>``.
  786. When 2 [default]: all names that start with '_' will be excluded.
  787. When 1: all 'magic' names (``__foo__``) will be excluded.
  788. When 0: nothing will be excluded.
  789. """
  790. ).tag(config=True)
  791. limit_to__all__ = Bool(False,
  792. help="""
  793. DEPRECATED as of version 5.0.
  794. Instruct the completer to use __all__ for the completion
  795. Specifically, when completing on ``object.<tab>``.
  796. When True: only those names in obj.__all__ will be included.
  797. When False [default]: the __all__ attribute is ignored
  798. """,
  799. ).tag(config=True)
  800. @observe('limit_to__all__')
  801. def _limit_to_all_changed(self, change):
  802. warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
  803. 'value has been deprecated since IPython 5.0, will be made to have '
  804. 'no effects and then removed in future version of IPython.',
  805. UserWarning)
  806. def __init__(self, shell=None, namespace=None, global_namespace=None,
  807. use_readline=_deprecation_readline_sentinel, config=None, **kwargs):
  808. """IPCompleter() -> completer
  809. Return a completer object.
  810. Parameters
  811. ----------
  812. shell
  813. a pointer to the ipython shell itself. This is needed
  814. because this completer knows about magic functions, and those can
  815. only be accessed via the ipython instance.
  816. namespace : dict, optional
  817. an optional dict where completions are performed.
  818. global_namespace : dict, optional
  819. secondary optional dict for completions, to
  820. handle cases (such as IPython embedded inside functions) where
  821. both Python scopes are visible.
  822. use_readline : bool, optional
  823. DEPRECATED, ignored since IPython 6.0, will have no effects
  824. """
  825. self.magic_escape = ESC_MAGIC
  826. self.splitter = CompletionSplitter()
  827. if use_readline is not _deprecation_readline_sentinel:
  828. warnings.warn('The `use_readline` parameter is deprecated and ignored since IPython 6.0.',
  829. DeprecationWarning, stacklevel=2)
  830. # _greedy_changed() depends on splitter and readline being defined:
  831. Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
  832. config=config, **kwargs)
  833. # List where completion matches will be stored
  834. self.matches = []
  835. self.shell = shell
  836. # Regexp to split filenames with spaces in them
  837. self.space_name_re = re.compile(r'([^\\] )')
  838. # Hold a local ref. to glob.glob for speed
  839. self.glob = glob.glob
  840. # Determine if we are running on 'dumb' terminals, like (X)Emacs
  841. # buffers, to avoid completion problems.
  842. term = os.environ.get('TERM','xterm')
  843. self.dumb_terminal = term in ['dumb','emacs']
  844. # Special handling of backslashes needed in win32 platforms
  845. if sys.platform == "win32":
  846. self.clean_glob = self._clean_glob_win32
  847. else:
  848. self.clean_glob = self._clean_glob
  849. #regexp to parse docstring for function signature
  850. self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
  851. self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
  852. #use this if positional argument name is also needed
  853. #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
  854. self.magic_arg_matchers = [
  855. self.magic_config_matches,
  856. self.magic_color_matches,
  857. ]
  858. # This is set externally by InteractiveShell
  859. self.custom_completers = None
  860. @property
  861. def matchers(self):
  862. """All active matcher routines for completion"""
  863. if self.dict_keys_only:
  864. return [self.dict_key_matches]
  865. if self.use_jedi:
  866. return [
  867. *self.custom_matchers,
  868. self.dict_key_matches,
  869. self.file_matches,
  870. self.magic_matches,
  871. ]
  872. else:
  873. return [
  874. *self.custom_matchers,
  875. self.dict_key_matches,
  876. self.python_matches,
  877. self.file_matches,
  878. self.magic_matches,
  879. self.python_func_kw_matches,
  880. ]
  881. def all_completions(self, text) -> List[str]:
  882. """
  883. Wrapper around the completion methods for the benefit of emacs.
  884. """
  885. prefix = text.rpartition('.')[0]
  886. with provisionalcompleter():
  887. return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
  888. for c in self.completions(text, len(text))]
  889. return self.complete(text)[1]
  890. def _clean_glob(self, text):
  891. return self.glob("%s*" % text)
  892. def _clean_glob_win32(self,text):
  893. return [f.replace("\\","/")
  894. for f in self.glob("%s*" % text)]
  895. def file_matches(self, text):
  896. """Match filenames, expanding ~USER type strings.
  897. Most of the seemingly convoluted logic in this completer is an
  898. attempt to handle filenames with spaces in them. And yet it's not
  899. quite perfect, because Python's readline doesn't expose all of the
  900. GNU readline details needed for this to be done correctly.
  901. For a filename with a space in it, the printed completions will be
  902. only the parts after what's already been typed (instead of the
  903. full completions, as is normally done). I don't think with the
  904. current (as of Python 2.3) Python readline it's possible to do
  905. better."""
  906. # chars that require escaping with backslash - i.e. chars
  907. # that readline treats incorrectly as delimiters, but we
  908. # don't want to treat as delimiters in filename matching
  909. # when escaped with backslash
  910. if text.startswith('!'):
  911. text = text[1:]
  912. text_prefix = u'!'
  913. else:
  914. text_prefix = u''
  915. text_until_cursor = self.text_until_cursor
  916. # track strings with open quotes
  917. open_quotes = has_open_quotes(text_until_cursor)
  918. if '(' in text_until_cursor or '[' in text_until_cursor:
  919. lsplit = text
  920. else:
  921. try:
  922. # arg_split ~ shlex.split, but with unicode bugs fixed by us
  923. lsplit = arg_split(text_until_cursor)[-1]
  924. except ValueError:
  925. # typically an unmatched ", or backslash without escaped char.
  926. if open_quotes:
  927. lsplit = text_until_cursor.split(open_quotes)[-1]
  928. else:
  929. return []
  930. except IndexError:
  931. # tab pressed on empty line
  932. lsplit = ""
  933. if not open_quotes and lsplit != protect_filename(lsplit):
  934. # if protectables are found, do matching on the whole escaped name
  935. has_protectables = True
  936. text0,text = text,lsplit
  937. else:
  938. has_protectables = False
  939. text = os.path.expanduser(text)
  940. if text == "":
  941. return [text_prefix + protect_filename(f) for f in self.glob("*")]
  942. # Compute the matches from the filesystem
  943. if sys.platform == 'win32':
  944. m0 = self.clean_glob(text)
  945. else:
  946. m0 = self.clean_glob(text.replace('\\', ''))
  947. if has_protectables:
  948. # If we had protectables, we need to revert our changes to the
  949. # beginning of filename so that we don't double-write the part
  950. # of the filename we have so far
  951. len_lsplit = len(lsplit)
  952. matches = [text_prefix + text0 +
  953. protect_filename(f[len_lsplit:]) for f in m0]
  954. else:
  955. if open_quotes:
  956. # if we have a string with an open quote, we don't need to
  957. # protect the names beyond the quote (and we _shouldn't_, as
  958. # it would cause bugs when the filesystem call is made).
  959. matches = m0 if sys.platform == "win32" else\
  960. [protect_filename(f, open_quotes) for f in m0]
  961. else:
  962. matches = [text_prefix +
  963. protect_filename(f) for f in m0]
  964. # Mark directories in input list by appending '/' to their names.
  965. return [x+'/' if os.path.isdir(x) else x for x in matches]
  966. def magic_matches(self, text):
  967. """Match magics"""
  968. # Get all shell magics now rather than statically, so magics loaded at
  969. # runtime show up too.
  970. lsm = self.shell.magics_manager.lsmagic()
  971. line_magics = lsm['line']
  972. cell_magics = lsm['cell']
  973. pre = self.magic_escape
  974. pre2 = pre+pre
  975. explicit_magic = text.startswith(pre)
  976. # Completion logic:
  977. # - user gives %%: only do cell magics
  978. # - user gives %: do both line and cell magics
  979. # - no prefix: do both
  980. # In other words, line magics are skipped if the user gives %% explicitly
  981. #
  982. # We also exclude magics that match any currently visible names:
  983. # https://github.com/ipython/ipython/issues/4877, unless the user has
  984. # typed a %:
  985. # https://github.com/ipython/ipython/issues/10754
  986. bare_text = text.lstrip(pre)
  987. global_matches = self.global_matches(bare_text)
  988. if not explicit_magic:
  989. def matches(magic):
  990. """
  991. Filter magics, in particular remove magics that match
  992. a name present in global namespace.
  993. """
  994. return ( magic.startswith(bare_text) and
  995. magic not in global_matches )
  996. else:
  997. def matches(magic):
  998. return magic.startswith(bare_text)
  999. comp = [ pre2+m for m in cell_magics if matches(m)]
  1000. if not text.startswith(pre2):
  1001. comp += [ pre+m for m in line_magics if matches(m)]
  1002. return comp
  1003. def magic_config_matches(self, text:str) -> List[str]:
  1004. """ Match class names and attributes for %config magic """
  1005. texts = text.strip().split()
  1006. if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
  1007. # get all configuration classes
  1008. classes = sorted(set([ c for c in self.shell.configurables
  1009. if c.__class__.class_traits(config=True)
  1010. ]), key=lambda x: x.__class__.__name__)
  1011. classnames = [ c.__class__.__name__ for c in classes ]
  1012. # return all classnames if config or %config is given
  1013. if len(texts) == 1:
  1014. return classnames
  1015. # match classname
  1016. classname_texts = texts[1].split('.')
  1017. classname = classname_texts[0]
  1018. classname_matches = [ c for c in classnames
  1019. if c.startswith(classname) ]
  1020. # return matched classes or the matched class with attributes
  1021. if texts[1].find('.') < 0:
  1022. return classname_matches
  1023. elif len(classname_matches) == 1 and \
  1024. classname_matches[0] == classname:
  1025. cls = classes[classnames.index(classname)].__class__
  1026. help = cls.class_get_help()
  1027. # strip leading '--' from cl-args:
  1028. help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
  1029. return [ attr.split('=')[0]
  1030. for attr in help.strip().splitlines()
  1031. if attr.startswith(texts[1]) ]
  1032. return []
  1033. def magic_color_matches(self, text:str) -> List[str] :
  1034. """ Match color schemes for %colors magic"""
  1035. texts = text.split()
  1036. if text.endswith(' '):
  1037. # .split() strips off the trailing whitespace. Add '' back
  1038. # so that: '%colors ' -> ['%colors', '']
  1039. texts.append('')
  1040. if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
  1041. prefix = texts[1]
  1042. return [ color for color in InspectColors.keys()
  1043. if color.startswith(prefix) ]
  1044. return []
  1045. def _jedi_matches(self, cursor_column:int, cursor_line:int, text:str):
  1046. """
  1047. Return a list of :any:`jedi.api.Completions` object from a ``text`` and
  1048. cursor position.
  1049. Parameters
  1050. ----------
  1051. cursor_column : int
  1052. column position of the cursor in ``text``, 0-indexed.
  1053. cursor_line : int
  1054. line position of the cursor in ``text``, 0-indexed
  1055. text : str
  1056. text to complete
  1057. Debugging
  1058. ---------
  1059. If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
  1060. object containing a string with the Jedi debug information attached.
  1061. """
  1062. namespaces = [self.namespace]
  1063. if self.global_namespace is not None:
  1064. namespaces.append(self.global_namespace)
  1065. completion_filter = lambda x:x
  1066. offset = cursor_to_position(text, cursor_line, cursor_column)
  1067. # filter output if we are completing for object members
  1068. if offset:
  1069. pre = text[offset-1]
  1070. if pre == '.':
  1071. if self.omit__names == 2:
  1072. completion_filter = lambda c:not c.name.startswith('_')
  1073. elif self.omit__names == 1:
  1074. completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
  1075. elif self.omit__names == 0:
  1076. completion_filter = lambda x:x
  1077. else:
  1078. raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
  1079. interpreter = jedi.Interpreter(text[:offset], namespaces, column=cursor_column, line=cursor_line + 1)
  1080. try_jedi = True
  1081. try:
  1082. # find the first token in the current tree -- if it is a ' or " then we are in a string
  1083. completing_string = False
  1084. try:
  1085. first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
  1086. except StopIteration:
  1087. pass
  1088. else:
  1089. # note the value may be ', ", or it may also be ''' or """, or
  1090. # in some cases, """what/you/typed..., but all of these are
  1091. # strings.
  1092. completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
  1093. # if we are in a string jedi is likely not the right candidate for
  1094. # now. Skip it.
  1095. try_jedi = not completing_string
  1096. except Exception as e:
  1097. # many of things can go wrong, we are using private API just don't crash.
  1098. if self.debug:
  1099. print("Error detecting if completing a non-finished string :", e, '|')
  1100. if not try_jedi:
  1101. return []
  1102. try:
  1103. return filter(completion_filter, interpreter.completions())
  1104. except Exception as e:
  1105. if self.debug:
  1106. return [_FakeJediCompletion('Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""' % (e))]
  1107. else:
  1108. return []
  1109. def python_matches(self, text):
  1110. """Match attributes or global python names"""
  1111. if "." in text:
  1112. try:
  1113. matches = self.attr_matches(text)
  1114. if text.endswith('.') and self.omit__names:
  1115. if self.omit__names == 1:
  1116. # true if txt is _not_ a __ name, false otherwise:
  1117. no__name = (lambda txt:
  1118. re.match(r'.*\.__.*?__',txt) is None)
  1119. else:
  1120. # true if txt is _not_ a _ name, false otherwise:
  1121. no__name = (lambda txt:
  1122. re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
  1123. matches = filter(no__name, matches)
  1124. except NameError:
  1125. # catches <undefined attributes>.<tab>
  1126. matches = []
  1127. else:
  1128. matches = self.global_matches(text)
  1129. return matches
  1130. def _default_arguments_from_docstring(self, doc):
  1131. """Parse the first line of docstring for call signature.
  1132. Docstring should be of the form 'min(iterable[, key=func])\n'.
  1133. It can also parse cython docstring of the form
  1134. 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
  1135. """
  1136. if doc is None:
  1137. return []
  1138. #care only the firstline
  1139. line = doc.lstrip().splitlines()[0]
  1140. #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
  1141. #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
  1142. sig = self.docstring_sig_re.search(line)
  1143. if sig is None:
  1144. return []
  1145. # iterable[, key=func]' -> ['iterable[' ,' key=func]']
  1146. sig = sig.groups()[0].split(',')
  1147. ret = []
  1148. for s in sig:
  1149. #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
  1150. ret += self.docstring_kwd_re.findall(s)
  1151. return ret
  1152. def _default_arguments(self, obj):
  1153. """Return the list of default arguments of obj if it is callable,
  1154. or empty list otherwise."""
  1155. call_obj = obj
  1156. ret = []
  1157. if inspect.isbuiltin(obj):
  1158. pass
  1159. elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
  1160. if inspect.isclass(obj):
  1161. #for cython embedsignature=True the constructor docstring
  1162. #belongs to the object itself not __init__
  1163. ret += self._default_arguments_from_docstring(
  1164. getattr(obj, '__doc__', ''))
  1165. # for classes, check for __init__,__new__
  1166. call_obj = (getattr(obj, '__init__', None) or
  1167. getattr(obj, '__new__', None))
  1168. # for all others, check if they are __call__able
  1169. elif hasattr(obj, '__call__'):
  1170. call_obj = obj.__call__
  1171. ret += self._default_arguments_from_docstring(
  1172. getattr(call_obj, '__doc__', ''))
  1173. _keeps = (inspect.Parameter.KEYWORD_ONLY,
  1174. inspect.Parameter.POSITIONAL_OR_KEYWORD)
  1175. try:
  1176. sig = inspect.signature(obj)
  1177. ret.extend(k for k, v in sig.parameters.items() if
  1178. v.kind in _keeps)
  1179. except ValueError:
  1180. pass
  1181. return list(set(ret))
  1182. def python_func_kw_matches(self,text):
  1183. """Match named parameters (kwargs) of the last open function"""
  1184. if "." in text: # a parameter cannot be dotted
  1185. return []
  1186. try: regexp = self.__funcParamsRegex
  1187. except AttributeError:
  1188. regexp = self.__funcParamsRegex = re.compile(r'''
  1189. '.*?(?<!\\)' | # single quoted strings or
  1190. ".*?(?<!\\)" | # double quoted strings or
  1191. \w+ | # identifier
  1192. \S # other characters
  1193. ''', re.VERBOSE | re.DOTALL)
  1194. # 1. find the nearest identifier that comes before an unclosed
  1195. # parenthesis before the cursor
  1196. # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
  1197. tokens = regexp.findall(self.text_until_cursor)
  1198. iterTokens = reversed(tokens); openPar = 0
  1199. for token in iterTokens:
  1200. if token == ')':
  1201. openPar -= 1
  1202. elif token == '(':
  1203. openPar += 1
  1204. if openPar > 0:
  1205. # found the last unclosed parenthesis
  1206. break
  1207. else:
  1208. return []
  1209. # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
  1210. ids = []
  1211. isId = re.compile(r'\w+$').match
  1212. while True:
  1213. try:
  1214. ids.append(next(iterTokens))
  1215. if not isId(ids[-1]):
  1216. ids.pop(); break
  1217. if not next(iterTokens) == '.':
  1218. break
  1219. except StopIteration:
  1220. break
  1221. # Find all named arguments already assigned to, as to avoid suggesting
  1222. # them again
  1223. usedNamedArgs = set()
  1224. par_level = -1
  1225. for token, next_token in zip(tokens, tokens[1:]):
  1226. if token == '(':
  1227. par_level += 1
  1228. elif token == ')':
  1229. par_level -= 1
  1230. if par_level != 0:
  1231. continue
  1232. if next_token != '=':
  1233. continue
  1234. usedNamedArgs.add(token)
  1235. argMatches = []
  1236. try:
  1237. callableObj = '.'.join(ids[::-1])
  1238. namedArgs = self._default_arguments(eval(callableObj,
  1239. self.namespace))
  1240. # Remove used named arguments from the list, no need to show twice
  1241. for namedArg in set(namedArgs) - usedNamedArgs:
  1242. if namedArg.startswith(text):
  1243. argMatches.append(u"%s=" %namedArg)
  1244. except:
  1245. pass
  1246. return argMatches
  1247. def dict_key_matches(self, text):
  1248. "Match string keys in a dictionary, after e.g. 'foo[' "
  1249. def get_keys(obj):
  1250. # Objects can define their own completions by defining an
  1251. # _ipy_key_completions_() method.
  1252. method = get_real_method(obj, '_ipython_key_completions_')
  1253. if method is not None:
  1254. return method()
  1255. # Special case some common in-memory dict-like types
  1256. if isinstance(obj, dict) or\
  1257. _safe_isinstance(obj, 'pandas', 'DataFrame'):
  1258. try:
  1259. return list(obj.keys())
  1260. except Exception:
  1261. return []
  1262. elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
  1263. _safe_isinstance(obj, 'numpy', 'void'):
  1264. return obj.dtype.names or []
  1265. return []
  1266. try:
  1267. regexps = self.__dict_key_regexps
  1268. except AttributeError:
  1269. dict_key_re_fmt = r'''(?x)
  1270. ( # match dict-referring expression wrt greedy setting
  1271. %s
  1272. )
  1273. \[ # open bracket
  1274. \s* # and optional whitespace
  1275. ([uUbB]? # string prefix (r not handled)
  1276. (?: # unclosed string
  1277. '(?:[^']|(?<!\\)\\')*
  1278. |
  1279. "(?:[^"]|(?<!\\)\\")*
  1280. )
  1281. )?
  1282. $
  1283. '''
  1284. regexps = self.__dict_key_regexps = {
  1285. False: re.compile(dict_key_re_fmt % r'''
  1286. # identifiers separated by .
  1287. (?!\d)\w+
  1288. (?:\.(?!\d)\w+)*
  1289. '''),
  1290. True: re.compile(dict_key_re_fmt % '''
  1291. .+
  1292. ''')
  1293. }
  1294. match = regexps[self.greedy].search(self.text_until_cursor)
  1295. if match is None:
  1296. return []
  1297. expr, prefix = match.groups()
  1298. try:
  1299. obj = eval(expr, self.namespace)
  1300. except Exception:
  1301. try:
  1302. obj = eval(expr, self.global_namespace)
  1303. except Exception:
  1304. return []
  1305. keys = get_keys(obj)
  1306. if not keys:
  1307. return keys
  1308. closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
  1309. if not matches:
  1310. return matches
  1311. # get the cursor position of
  1312. # - the text being completed
  1313. # - the start of the key text
  1314. # - the start of the completion
  1315. text_start = len(self.text_until_cursor) - len(text)
  1316. if prefix:
  1317. key_start = match.start(2)
  1318. completion_start = key_start + token_offset
  1319. else:
  1320. key_start = completion_start = match.end()
  1321. # grab the leading prefix, to make sure all completions start with `text`
  1322. if text_start > key_start:
  1323. leading = ''
  1324. else:
  1325. leading = text[text_start:completion_start]
  1326. # the index of the `[` character
  1327. bracket_idx = match.end(1)
  1328. # append closing quote and bracket as appropriate
  1329. # this is *not* appropriate if the opening quote or bracket is outside
  1330. # the text given to this method
  1331. suf = ''
  1332. continuation = self.line_buffer[len(self.text_until_cursor):]
  1333. if key_start > text_start and closing_quote:
  1334. # quotes were opened inside text, maybe close them
  1335. if continuation.startswith(closing_quote):
  1336. continuation = continuation[len(closing_quote):]
  1337. else:
  1338. suf += closing_quote
  1339. if bracket_idx > text_start:
  1340. # brackets were opened inside text, maybe close them
  1341. if not continuation.startswith(']'):
  1342. suf += ']'
  1343. return [leading + k + suf for k in matches]
  1344. def unicode_name_matches(self, text):
  1345. u"""Match Latex-like syntax for unicode characters base
  1346. on the name of the character.
  1347. This does ``\\GREEK SMALL LETTER ETA`` -> ``η``
  1348. Works only on valid python 3 identifier, or on combining characters that
  1349. will combine to form a valid identifier.
  1350. Used on Python 3 only.
  1351. """
  1352. slashpos = text.rfind('\\')
  1353. if slashpos > -1:
  1354. s = text[slashpos+1:]
  1355. try :
  1356. unic = unicodedata.lookup(s)
  1357. # allow combining chars
  1358. if ('a'+unic).isidentifier():
  1359. return '\\'+s,[unic]
  1360. except KeyError:
  1361. pass
  1362. return u'', []
  1363. def latex_matches(self, text):
  1364. u"""Match Latex syntax for unicode characters.
  1365. This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``α``
  1366. """
  1367. slashpos = text.rfind('\\')
  1368. if slashpos > -1:
  1369. s = text[slashpos:]
  1370. if s in latex_symbols:
  1371. # Try to complete a full latex symbol to unicode
  1372. # \\alpha -> α
  1373. return s, [latex_symbols[s]]
  1374. else:
  1375. # If a user has partially typed a latex symbol, give them
  1376. # a full list of options \al -> [\aleph, \alpha]
  1377. matches = [k for k in latex_symbols if k.startswith(s)]
  1378. if matches:
  1379. return s, matches
  1380. return u'', []
  1381. def dispatch_custom_completer(self, text):
  1382. if not self.custom_completers:
  1383. return
  1384. line = self.line_buffer
  1385. if not line.strip():
  1386. return None
  1387. # Create a little structure to pass all the relevant information about
  1388. # the current completion to any custom completer.
  1389. event = SimpleNamespace()
  1390. event.line = line
  1391. event.symbol = text
  1392. cmd = line.split(None,1)[0]
  1393. event.command = cmd
  1394. event.text_until_cursor = self.text_until_cursor
  1395. # for foo etc, try also to find completer for %foo
  1396. if not cmd.startswith(self.magic_escape):
  1397. try_magic = self.custom_completers.s_matches(
  1398. self.magic_escape + cmd)
  1399. else:
  1400. try_magic = []
  1401. for c in itertools.chain(self.custom_completers.s_matches(cmd),
  1402. try_magic,
  1403. self.custom_completers.flat_matches(self.text_until_cursor)):
  1404. try:
  1405. res = c(event)
  1406. if res:
  1407. # first, try case sensitive match
  1408. withcase = [r for r in res if r.startswith(text)]
  1409. if withcase:
  1410. return withcase
  1411. # if none, then case insensitive ones are ok too
  1412. text_low = text.lower()
  1413. return [r for r in res if r.lower().startswith(text_low)]
  1414. except TryNext:
  1415. pass
  1416. except KeyboardInterrupt:
  1417. """
  1418. If custom completer take too long,
  1419. let keyboard interrupt abort and return nothing.
  1420. """
  1421. break
  1422. return None
  1423. def completions(self, text: str, offset: int)->Iterator[Completion]:
  1424. """
  1425. Returns an iterator over the possible completions
  1426. .. warning::
  1427. Unstable
  1428. This function is unstable, API may change without warning.
  1429. It will also raise unless use in proper context manager.
  1430. Parameters
  1431. ----------
  1432. text:str
  1433. Full text of the current input, multi line string.
  1434. offset:int
  1435. Integer representing the position of the cursor in ``text``. Offset
  1436. is 0-based indexed.
  1437. Yields
  1438. ------
  1439. :any:`Completion` object
  1440. The cursor on a text can either be seen as being "in between"
  1441. characters or "On" a character depending on the interface visible to
  1442. the user. For consistency the cursor being on "in between" characters X
  1443. and Y is equivalent to the cursor being "on" character Y, that is to say
  1444. the character the cursor is on is considered as being after the cursor.
  1445. Combining characters may span more that one position in the
  1446. text.
  1447. .. note::
  1448. If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
  1449. fake Completion token to distinguish completion returned by Jedi
  1450. and usual IPython completion.
  1451. .. note::
  1452. Completions are not completely deduplicated yet. If identical
  1453. completions are coming from different sources this function does not
  1454. ensure that each completion object will only be present once.
  1455. """
  1456. warnings.warn("_complete is a provisional API (as of IPython 6.0). "
  1457. "It may change without warnings. "
  1458. "Use in corresponding context manager.",
  1459. category=ProvisionalCompleterWarning, stacklevel=2)
  1460. seen = set()
  1461. try:
  1462. for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
  1463. if c and (c in seen):
  1464. continue
  1465. yield c
  1466. seen.add(c)
  1467. except KeyboardInterrupt:
  1468. """if completions take too long and users send keyboard interrupt,
  1469. do not crash and return ASAP. """
  1470. pass
  1471. def _completions(self, full_text: str, offset: int, *, _timeout)->Iterator[Completion]:
  1472. """
  1473. Core completion module.Same signature as :any:`completions`, with the
  1474. extra `timeout` parameter (in seconds).
  1475. Computing jedi's completion ``.type`` can be quite expensive (it is a
  1476. lazy property) and can require some warm-up, more warm up than just
  1477. computing the ``name`` of a completion. The warm-up can be :
  1478. - Long warm-up the first time a module is encountered after
  1479. install/update: actually build parse/inference tree.
  1480. - first time the module is encountered in a session: load tree from
  1481. disk.
  1482. We don't want to block completions for tens of seconds so we give the
  1483. completer a "budget" of ``_timeout`` seconds per invocation to compute
  1484. completions types, the completions that have not yet been computed will
  1485. be marked as "unknown" an will have a chance to be computed next round
  1486. are things get cached.
  1487. Keep in mind that Jedi is not the only thing treating the completion so
  1488. keep the timeout short-ish as if we take more than 0.3 second we still
  1489. have lots of processing to do.
  1490. """
  1491. deadline = time.monotonic() + _timeout
  1492. before = full_text[:offset]
  1493. cursor_line, cursor_column = position_to_cursor(full_text, offset)
  1494. matched_text, matches, matches_origin, jedi_matches = self._complete(
  1495. full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column)
  1496. iter_jm = iter(jedi_matches)
  1497. if _timeout:
  1498. for jm in iter_jm:
  1499. try:
  1500. type_ = jm.type
  1501. except Exception:
  1502. if self.debug:
  1503. print("Error in Jedi getting type of ", jm)
  1504. type_ = None
  1505. delta = len(jm.name_with_symbols) - len(jm.complete)
  1506. if type_ == 'function':
  1507. signature = _make_signature(jm)
  1508. else:
  1509. signature = ''
  1510. yield Completion(start=offset - delta,
  1511. end=offset,
  1512. text=jm.name_with_symbols,
  1513. type=type_,
  1514. signature=signature,
  1515. _origin='jedi')
  1516. if time.monotonic() > deadline:
  1517. break
  1518. for jm in iter_jm:
  1519. delta = len(jm.name_with_symbols) - len(jm.complete)
  1520. yield Completion(start=offset - delta,
  1521. end=offset,
  1522. text=jm.name_with_symbols,
  1523. type='<unknown>', # don't compute type for speed
  1524. _origin='jedi',
  1525. signature='')
  1526. start_offset = before.rfind(matched_text)
  1527. # TODO:
  1528. # Suppress this, right now just for debug.
  1529. if jedi_matches and matches and self.debug:
  1530. yield Completion(start=start_offset, end=offset, text='--jedi/ipython--',
  1531. _origin='debug', type='none', signature='')
  1532. # I'm unsure if this is always true, so let's assert and see if it
  1533. # crash
  1534. assert before.endswith(matched_text)
  1535. for m, t in zip(matches, matches_origin):
  1536. yield Completion(start=start_offset, end=offset, text=m, _origin=t, signature='', type='<unknown>')
  1537. def complete(self, text=None, line_buffer=None, cursor_pos=None):
  1538. """Find completions for the given text and line context.
  1539. Note that both the text and the line_buffer are optional, but at least
  1540. one of them must be given.
  1541. Parameters
  1542. ----------
  1543. text : string, optional
  1544. Text to perform the completion on. If not given, the line buffer
  1545. is split using the instance's CompletionSplitter object.
  1546. line_buffer : string, optional
  1547. If not given, the completer attempts to obtain the current line
  1548. buffer via readline. This keyword allows clients which are
  1549. requesting for text completions in non-readline contexts to inform
  1550. the completer of the entire text.
  1551. cursor_pos : int, optional
  1552. Index of the cursor in the full line buffer. Should be provided by
  1553. remote frontends where kernel has no access to frontend state.
  1554. Returns
  1555. -------
  1556. text : str
  1557. Text that was actually used in the completion.
  1558. matches : list
  1559. A list of completion matches.
  1560. .. note::
  1561. This API is likely to be deprecated and replaced by
  1562. :any:`IPCompleter.completions` in the future.
  1563. """
  1564. warnings.warn('`Completer.complete` is pending deprecation since '
  1565. 'IPython 6.0 and will be replaced by `Completer.completions`.',
  1566. PendingDeprecationWarning)
  1567. # potential todo, FOLD the 3rd throw away argument of _complete
  1568. # into the first 2 one.
  1569. return self._complete(line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0)[:2]
  1570. def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
  1571. full_text=None) -> Tuple[str, List[str], List[str], Iterable[_FakeJediCompletion]]:
  1572. """
  1573. Like complete but can also returns raw jedi completions as well as the
  1574. origin of the completion text. This could (and should) be made much
  1575. cleaner but that will be simpler once we drop the old (and stateful)
  1576. :any:`complete` API.
  1577. With current provisional API, cursor_pos act both (depending on the
  1578. caller) as the offset in the ``text`` or ``line_buffer``, or as the
  1579. ``column`` when passing multiline strings this could/should be renamed
  1580. but would add extra noise.
  1581. """
  1582. # if the cursor position isn't given, the only sane assumption we can
  1583. # make is that it's at the end of the line (the common case)
  1584. if cursor_pos is None:
  1585. cursor_pos = len(line_buffer) if text is None else len(text)
  1586. if self.use_main_ns:
  1587. self.namespace = __main__.__dict__
  1588. # if text is either None or an empty string, rely on the line buffer
  1589. if (not line_buffer) and full_text:
  1590. line_buffer = full_text.split('\n')[cursor_line]
  1591. if not text: # issue #11508: check line_buffer before calling split_line
  1592. text = self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ''
  1593. if self.backslash_combining_completions:
  1594. # allow deactivation of these on windows.
  1595. base_text = text if not line_buffer else line_buffer[:cursor_pos]
  1596. latex_text, latex_matches = self.latex_matches(base_text)
  1597. if latex_matches:
  1598. return latex_text, latex_matches, ['latex_matches']*len(latex_matches), ()
  1599. name_text = ''
  1600. name_matches = []
  1601. # need to add self.fwd_unicode_match() function here when done
  1602. for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches, self.fwd_unicode_match):
  1603. name_text, name_matches = meth(base_text)
  1604. if name_text:
  1605. return name_text, name_matches[:MATCHES_LIMIT], \
  1606. [meth.__qualname__]*min(len(name_matches), MATCHES_LIMIT), ()
  1607. # If no line buffer is given, assume the input text is all there was
  1608. if line_buffer is None:
  1609. line_buffer = text
  1610. self.line_buffer = line_buffer
  1611. self.text_until_cursor = self.line_buffer[:cursor_pos]
  1612. # Do magic arg matches
  1613. for matcher in self.magic_arg_matchers:
  1614. matches = list(matcher(line_buffer))[:MATCHES_LIMIT]
  1615. if matches:
  1616. origins = [matcher.__qualname__] * len(matches)
  1617. return text, matches, origins, ()
  1618. # Start with a clean slate of completions
  1619. matches = []
  1620. # FIXME: we should extend our api to return a dict with completions for
  1621. # different types of objects. The rlcomplete() method could then
  1622. # simply collapse the dict into a list for readline, but we'd have
  1623. # richer completion semantics in other environments.
  1624. completions = ()
  1625. if self.use_jedi:
  1626. if not full_text:
  1627. full_text = line_buffer
  1628. completions = self._jedi_matches(
  1629. cursor_pos, cursor_line, full_text)
  1630. if self.merge_completions:
  1631. matches = []
  1632. for matcher in self.matchers:
  1633. try:
  1634. matches.extend([(m, matcher.__qualname__)
  1635. for m in matcher(text)])
  1636. except:
  1637. # Show the ugly traceback if the matcher causes an
  1638. # exception, but do NOT crash the kernel!
  1639. sys.excepthook(*sys.exc_info())
  1640. else:
  1641. for matcher in self.matchers:
  1642. matches = [(m, matcher.__qualname__)
  1643. for m in matcher(text)]
  1644. if matches:
  1645. break
  1646. seen = set()
  1647. filtered_matches = set()
  1648. for m in matches:
  1649. t, c = m
  1650. if t not in seen:
  1651. filtered_matches.add(m)
  1652. seen.add(t)
  1653. _filtered_matches = sorted(filtered_matches, key=lambda x: completions_sorting_key(x[0]))
  1654. custom_res = [(m, 'custom') for m in self.dispatch_custom_completer(text) or []]
  1655. _filtered_matches = custom_res or _filtered_matches
  1656. _filtered_matches = _filtered_matches[:MATCHES_LIMIT]
  1657. _matches = [m[0] for m in _filtered_matches]
  1658. origins = [m[1] for m in _filtered_matches]
  1659. self.matches = _matches
  1660. return text, _matches, origins, completions
  1661. def fwd_unicode_match(self, text:str) -> Tuple[str, list]:
  1662. if self._names is None:
  1663. self._names = []
  1664. for c in range(0,0x10FFFF + 1):
  1665. try:
  1666. self._names.append(unicodedata.name(chr(c)))
  1667. except ValueError:
  1668. pass
  1669. slashpos = text.rfind('\\')
  1670. # if text starts with slash
  1671. if slashpos > -1:
  1672. s = text[slashpos+1:]
  1673. candidates = [x for x in self._names if x.startswith(s)]
  1674. if candidates:
  1675. return s, candidates
  1676. else:
  1677. return '', ()
  1678. # if text does not start with slash
  1679. else:
  1680. return u'', ()