completer.py 115 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347
  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 :kbd:`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. :std:configtrait:`Completer.backslash_combining_completions` option to
  40. ``False``.
  41. Experimental
  42. ============
  43. Starting with IPython 6.0, this module can make use of the Jedi library to
  44. generate completions both using static analysis of the code, and dynamically
  45. inspecting multiple namespaces. Jedi is an autocompletion and static analysis
  46. for Python. The APIs attached to this new mechanism is unstable and will
  47. raise unless use in an :any:`provisionalcompleter` context manager.
  48. You will find that the following are experimental:
  49. - :any:`provisionalcompleter`
  50. - :any:`IPCompleter.completions`
  51. - :any:`Completion`
  52. - :any:`rectify_completions`
  53. .. note::
  54. better name for :any:`rectify_completions` ?
  55. We welcome any feedback on these new API, and we also encourage you to try this
  56. module in debug mode (start IPython with ``--Completer.debug=True``) in order
  57. to have extra logging information if :any:`jedi` is crashing, or if current
  58. IPython completer pending deprecations are returning results not yet handled
  59. by :any:`jedi`
  60. Using Jedi for tab completion allow snippets like the following to work without
  61. having to execute any code:
  62. >>> myvar = ['hello', 42]
  63. ... myvar[1].bi<tab>
  64. Tab completion will be able to infer that ``myvar[1]`` is a real number without
  65. executing almost any code unlike the deprecated :any:`IPCompleter.greedy`
  66. option.
  67. Be sure to update :any:`jedi` to the latest stable version or to try the
  68. current development version to get better completions.
  69. Matchers
  70. ========
  71. All completions routines are implemented using unified *Matchers* API.
  72. The matchers API is provisional and subject to change without notice.
  73. The built-in matchers include:
  74. - :any:`IPCompleter.dict_key_matcher`: dictionary key completions,
  75. - :any:`IPCompleter.magic_matcher`: completions for magics,
  76. - :any:`IPCompleter.unicode_name_matcher`,
  77. :any:`IPCompleter.fwd_unicode_matcher`
  78. and :any:`IPCompleter.latex_name_matcher`: see `Forward latex/unicode completion`_,
  79. - :any:`back_unicode_name_matcher` and :any:`back_latex_name_matcher`: see `Backward latex completion`_,
  80. - :any:`IPCompleter.file_matcher`: paths to files and directories,
  81. - :any:`IPCompleter.python_func_kw_matcher` - function keywords,
  82. - :any:`IPCompleter.python_matches` - globals and attributes (v1 API),
  83. - ``IPCompleter.jedi_matcher`` - static analysis with Jedi,
  84. - :any:`IPCompleter.custom_completer_matcher` - pluggable completer with a default
  85. implementation in :any:`InteractiveShell` which uses IPython hooks system
  86. (`complete_command`) with string dispatch (including regular expressions).
  87. Differently to other matchers, ``custom_completer_matcher`` will not suppress
  88. Jedi results to match behaviour in earlier IPython versions.
  89. Custom matchers can be added by appending to ``IPCompleter.custom_matchers`` list.
  90. Matcher API
  91. -----------
  92. Simplifying some details, the ``Matcher`` interface can described as
  93. .. code-block::
  94. MatcherAPIv1 = Callable[[str], list[str]]
  95. MatcherAPIv2 = Callable[[CompletionContext], SimpleMatcherResult]
  96. Matcher = MatcherAPIv1 | MatcherAPIv2
  97. The ``MatcherAPIv1`` reflects the matcher API as available prior to IPython 8.6.0
  98. and remains supported as a simplest way for generating completions. This is also
  99. currently the only API supported by the IPython hooks system `complete_command`.
  100. To distinguish between matcher versions ``matcher_api_version`` attribute is used.
  101. More precisely, the API allows to omit ``matcher_api_version`` for v1 Matchers,
  102. and requires a literal ``2`` for v2 Matchers.
  103. Once the API stabilises future versions may relax the requirement for specifying
  104. ``matcher_api_version`` by switching to :any:`functools.singledispatch`, therefore
  105. please do not rely on the presence of ``matcher_api_version`` for any purposes.
  106. Suppression of competing matchers
  107. ---------------------------------
  108. By default results from all matchers are combined, in the order determined by
  109. their priority. Matchers can request to suppress results from subsequent
  110. matchers by setting ``suppress`` to ``True`` in the ``MatcherResult``.
  111. When multiple matchers simultaneously request surpression, the results from of
  112. the matcher with higher priority will be returned.
  113. Sometimes it is desirable to suppress most but not all other matchers;
  114. this can be achieved by adding a set of identifiers of matchers which
  115. should not be suppressed to ``MatcherResult`` under ``do_not_suppress`` key.
  116. The suppression behaviour can is user-configurable via
  117. :std:configtrait:`IPCompleter.suppress_competing_matchers`.
  118. """
  119. # Copyright (c) IPython Development Team.
  120. # Distributed under the terms of the Modified BSD License.
  121. #
  122. # Some of this code originated from rlcompleter in the Python standard library
  123. # Copyright (C) 2001 Python Software Foundation, www.python.org
  124. from __future__ import annotations
  125. import builtins as builtin_mod
  126. import enum
  127. import glob
  128. import inspect
  129. import itertools
  130. import keyword
  131. import os
  132. import re
  133. import string
  134. import sys
  135. import tokenize
  136. import time
  137. import unicodedata
  138. import uuid
  139. import warnings
  140. from ast import literal_eval
  141. from collections import defaultdict
  142. from contextlib import contextmanager
  143. from dataclasses import dataclass
  144. from functools import cached_property, partial
  145. from types import SimpleNamespace
  146. from typing import (
  147. Iterable,
  148. Iterator,
  149. List,
  150. Tuple,
  151. Union,
  152. Any,
  153. Sequence,
  154. Dict,
  155. Optional,
  156. TYPE_CHECKING,
  157. Set,
  158. Sized,
  159. TypeVar,
  160. Literal,
  161. )
  162. from IPython.core.guarded_eval import guarded_eval, EvaluationContext
  163. from IPython.core.error import TryNext
  164. from IPython.core.inputtransformer2 import ESC_MAGIC
  165. from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
  166. from IPython.core.oinspect import InspectColors
  167. from IPython.testing.skipdoctest import skip_doctest
  168. from IPython.utils import generics
  169. from IPython.utils.decorators import sphinx_options
  170. from IPython.utils.dir2 import dir2, get_real_method
  171. from IPython.utils.docs import GENERATING_DOCUMENTATION
  172. from IPython.utils.path import ensure_dir_exists
  173. from IPython.utils.process import arg_split
  174. from traitlets import (
  175. Bool,
  176. Enum,
  177. Int,
  178. List as ListTrait,
  179. Unicode,
  180. Dict as DictTrait,
  181. Union as UnionTrait,
  182. observe,
  183. )
  184. from traitlets.config.configurable import Configurable
  185. import __main__
  186. # skip module docstests
  187. __skip_doctest__ = True
  188. try:
  189. import jedi
  190. jedi.settings.case_insensitive_completion = False
  191. import jedi.api.helpers
  192. import jedi.api.classes
  193. JEDI_INSTALLED = True
  194. except ImportError:
  195. JEDI_INSTALLED = False
  196. if TYPE_CHECKING or GENERATING_DOCUMENTATION and sys.version_info >= (3, 11):
  197. from typing import cast
  198. from typing_extensions import TypedDict, NotRequired, Protocol, TypeAlias, TypeGuard
  199. else:
  200. from typing import Generic
  201. def cast(type_, obj):
  202. """Workaround for `TypeError: MatcherAPIv2() takes no arguments`"""
  203. return obj
  204. # do not require on runtime
  205. NotRequired = Tuple # requires Python >=3.11
  206. TypedDict = Dict # by extension of `NotRequired` requires 3.11 too
  207. Protocol = object # requires Python >=3.8
  208. TypeAlias = Any # requires Python >=3.10
  209. TypeGuard = Generic # requires Python >=3.10
  210. if GENERATING_DOCUMENTATION:
  211. from typing import TypedDict
  212. # -----------------------------------------------------------------------------
  213. # Globals
  214. #-----------------------------------------------------------------------------
  215. # ranges where we have most of the valid unicode names. We could be more finer
  216. # grained but is it worth it for performance While unicode have character in the
  217. # range 0, 0x110000, we seem to have name for about 10% of those. (131808 as I
  218. # write this). With below range we cover them all, with a density of ~67%
  219. # biggest next gap we consider only adds up about 1% density and there are 600
  220. # gaps that would need hard coding.
  221. _UNICODE_RANGES = [(32, 0x323B0), (0xE0001, 0xE01F0)]
  222. # Public API
  223. __all__ = ["Completer", "IPCompleter"]
  224. if sys.platform == 'win32':
  225. PROTECTABLES = ' '
  226. else:
  227. PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
  228. # Protect against returning an enormous number of completions which the frontend
  229. # may have trouble processing.
  230. MATCHES_LIMIT = 500
  231. # Completion type reported when no type can be inferred.
  232. _UNKNOWN_TYPE = "<unknown>"
  233. # sentinel value to signal lack of a match
  234. not_found = object()
  235. class ProvisionalCompleterWarning(FutureWarning):
  236. """
  237. Exception raise by an experimental feature in this module.
  238. Wrap code in :any:`provisionalcompleter` context manager if you
  239. are certain you want to use an unstable feature.
  240. """
  241. pass
  242. warnings.filterwarnings('error', category=ProvisionalCompleterWarning)
  243. @skip_doctest
  244. @contextmanager
  245. def provisionalcompleter(action='ignore'):
  246. """
  247. This context manager has to be used in any place where unstable completer
  248. behavior and API may be called.
  249. >>> with provisionalcompleter():
  250. ... completer.do_experimental_things() # works
  251. >>> completer.do_experimental_things() # raises.
  252. .. note::
  253. Unstable
  254. By using this context manager you agree that the API in use may change
  255. without warning, and that you won't complain if they do so.
  256. You also understand that, if the API is not to your liking, you should report
  257. a bug to explain your use case upstream.
  258. We'll be happy to get your feedback, feature requests, and improvements on
  259. any of the unstable APIs!
  260. """
  261. with warnings.catch_warnings():
  262. warnings.filterwarnings(action, category=ProvisionalCompleterWarning)
  263. yield
  264. def has_open_quotes(s):
  265. """Return whether a string has open quotes.
  266. This simply counts whether the number of quote characters of either type in
  267. the string is odd.
  268. Returns
  269. -------
  270. If there is an open quote, the quote character is returned. Else, return
  271. False.
  272. """
  273. # We check " first, then ', so complex cases with nested quotes will get
  274. # the " to take precedence.
  275. if s.count('"') % 2:
  276. return '"'
  277. elif s.count("'") % 2:
  278. return "'"
  279. else:
  280. return False
  281. def protect_filename(s, protectables=PROTECTABLES):
  282. """Escape a string to protect certain characters."""
  283. if set(s) & set(protectables):
  284. if sys.platform == "win32":
  285. return '"' + s + '"'
  286. else:
  287. return "".join(("\\" + c if c in protectables else c) for c in s)
  288. else:
  289. return s
  290. def expand_user(path:str) -> Tuple[str, bool, str]:
  291. """Expand ``~``-style usernames in strings.
  292. This is similar to :func:`os.path.expanduser`, but it computes and returns
  293. extra information that will be useful if the input was being used in
  294. computing completions, and you wish to return the completions with the
  295. original '~' instead of its expanded value.
  296. Parameters
  297. ----------
  298. path : str
  299. String to be expanded. If no ~ is present, the output is the same as the
  300. input.
  301. Returns
  302. -------
  303. newpath : str
  304. Result of ~ expansion in the input path.
  305. tilde_expand : bool
  306. Whether any expansion was performed or not.
  307. tilde_val : str
  308. The value that ~ was replaced with.
  309. """
  310. # Default values
  311. tilde_expand = False
  312. tilde_val = ''
  313. newpath = path
  314. if path.startswith('~'):
  315. tilde_expand = True
  316. rest = len(path)-1
  317. newpath = os.path.expanduser(path)
  318. if rest:
  319. tilde_val = newpath[:-rest]
  320. else:
  321. tilde_val = newpath
  322. return newpath, tilde_expand, tilde_val
  323. def compress_user(path:str, tilde_expand:bool, tilde_val:str) -> str:
  324. """Does the opposite of expand_user, with its outputs.
  325. """
  326. if tilde_expand:
  327. return path.replace(tilde_val, '~')
  328. else:
  329. return path
  330. def completions_sorting_key(word):
  331. """key for sorting completions
  332. This does several things:
  333. - Demote any completions starting with underscores to the end
  334. - Insert any %magic and %%cellmagic completions in the alphabetical order
  335. by their name
  336. """
  337. prio1, prio2 = 0, 0
  338. if word.startswith('__'):
  339. prio1 = 2
  340. elif word.startswith('_'):
  341. prio1 = 1
  342. if word.endswith('='):
  343. prio1 = -1
  344. if word.startswith('%%'):
  345. # If there's another % in there, this is something else, so leave it alone
  346. if not "%" in word[2:]:
  347. word = word[2:]
  348. prio2 = 2
  349. elif word.startswith('%'):
  350. if not "%" in word[1:]:
  351. word = word[1:]
  352. prio2 = 1
  353. return prio1, word, prio2
  354. class _FakeJediCompletion:
  355. """
  356. This is a workaround to communicate to the UI that Jedi has crashed and to
  357. report a bug. Will be used only id :any:`IPCompleter.debug` is set to true.
  358. Added in IPython 6.0 so should likely be removed for 7.0
  359. """
  360. def __init__(self, name):
  361. self.name = name
  362. self.complete = name
  363. self.type = 'crashed'
  364. self.name_with_symbols = name
  365. self.signature = ""
  366. self._origin = "fake"
  367. self.text = "crashed"
  368. def __repr__(self):
  369. return '<Fake completion object jedi has crashed>'
  370. _JediCompletionLike = Union["jedi.api.Completion", _FakeJediCompletion]
  371. class Completion:
  372. """
  373. Completion object used and returned by IPython completers.
  374. .. warning::
  375. Unstable
  376. This function is unstable, API may change without warning.
  377. It will also raise unless use in proper context manager.
  378. This act as a middle ground :any:`Completion` object between the
  379. :any:`jedi.api.classes.Completion` object and the Prompt Toolkit completion
  380. object. While Jedi need a lot of information about evaluator and how the
  381. code should be ran/inspected, PromptToolkit (and other frontend) mostly
  382. need user facing information.
  383. - Which range should be replaced replaced by what.
  384. - Some metadata (like completion type), or meta information to displayed to
  385. the use user.
  386. For debugging purpose we can also store the origin of the completion (``jedi``,
  387. ``IPython.python_matches``, ``IPython.magics_matches``...).
  388. """
  389. __slots__ = ['start', 'end', 'text', 'type', 'signature', '_origin']
  390. def __init__(
  391. self,
  392. start: int,
  393. end: int,
  394. text: str,
  395. *,
  396. type: Optional[str] = None,
  397. _origin="",
  398. signature="",
  399. ) -> None:
  400. warnings.warn(
  401. "``Completion`` is a provisional API (as of IPython 6.0). "
  402. "It may change without warnings. "
  403. "Use in corresponding context manager.",
  404. category=ProvisionalCompleterWarning,
  405. stacklevel=2,
  406. )
  407. self.start = start
  408. self.end = end
  409. self.text = text
  410. self.type = type
  411. self.signature = signature
  412. self._origin = _origin
  413. def __repr__(self):
  414. return '<Completion start=%s end=%s text=%r type=%r, signature=%r,>' % \
  415. (self.start, self.end, self.text, self.type or '?', self.signature or '?')
  416. def __eq__(self, other) -> bool:
  417. """
  418. Equality and hash do not hash the type (as some completer may not be
  419. able to infer the type), but are use to (partially) de-duplicate
  420. completion.
  421. Completely de-duplicating completion is a bit tricker that just
  422. comparing as it depends on surrounding text, which Completions are not
  423. aware of.
  424. """
  425. return self.start == other.start and \
  426. self.end == other.end and \
  427. self.text == other.text
  428. def __hash__(self):
  429. return hash((self.start, self.end, self.text))
  430. class SimpleCompletion:
  431. """Completion item to be included in the dictionary returned by new-style Matcher (API v2).
  432. .. warning::
  433. Provisional
  434. This class is used to describe the currently supported attributes of
  435. simple completion items, and any additional implementation details
  436. should not be relied on. Additional attributes may be included in
  437. future versions, and meaning of text disambiguated from the current
  438. dual meaning of "text to insert" and "text to used as a label".
  439. """
  440. __slots__ = ["text", "type"]
  441. def __init__(self, text: str, *, type: Optional[str] = None):
  442. self.text = text
  443. self.type = type
  444. def __repr__(self):
  445. return f"<SimpleCompletion text={self.text!r} type={self.type!r}>"
  446. class _MatcherResultBase(TypedDict):
  447. """Definition of dictionary to be returned by new-style Matcher (API v2)."""
  448. #: Suffix of the provided ``CompletionContext.token``, if not given defaults to full token.
  449. matched_fragment: NotRequired[str]
  450. #: Whether to suppress results from all other matchers (True), some
  451. #: matchers (set of identifiers) or none (False); default is False.
  452. suppress: NotRequired[Union[bool, Set[str]]]
  453. #: Identifiers of matchers which should NOT be suppressed when this matcher
  454. #: requests to suppress all other matchers; defaults to an empty set.
  455. do_not_suppress: NotRequired[Set[str]]
  456. #: Are completions already ordered and should be left as-is? default is False.
  457. ordered: NotRequired[bool]
  458. @sphinx_options(show_inherited_members=True, exclude_inherited_from=["dict"])
  459. class SimpleMatcherResult(_MatcherResultBase, TypedDict):
  460. """Result of new-style completion matcher."""
  461. # note: TypedDict is added again to the inheritance chain
  462. # in order to get __orig_bases__ for documentation
  463. #: List of candidate completions
  464. completions: Sequence[SimpleCompletion] | Iterator[SimpleCompletion]
  465. class _JediMatcherResult(_MatcherResultBase):
  466. """Matching result returned by Jedi (will be processed differently)"""
  467. #: list of candidate completions
  468. completions: Iterator[_JediCompletionLike]
  469. AnyMatcherCompletion = Union[_JediCompletionLike, SimpleCompletion]
  470. AnyCompletion = TypeVar("AnyCompletion", AnyMatcherCompletion, Completion)
  471. @dataclass
  472. class CompletionContext:
  473. """Completion context provided as an argument to matchers in the Matcher API v2."""
  474. # rationale: many legacy matchers relied on completer state (`self.text_until_cursor`)
  475. # which was not explicitly visible as an argument of the matcher, making any refactor
  476. # prone to errors; by explicitly passing `cursor_position` we can decouple the matchers
  477. # from the completer, and make substituting them in sub-classes easier.
  478. #: Relevant fragment of code directly preceding the cursor.
  479. #: The extraction of token is implemented via splitter heuristic
  480. #: (following readline behaviour for legacy reasons), which is user configurable
  481. #: (by switching the greedy mode).
  482. token: str
  483. #: The full available content of the editor or buffer
  484. full_text: str
  485. #: Cursor position in the line (the same for ``full_text`` and ``text``).
  486. cursor_position: int
  487. #: Cursor line in ``full_text``.
  488. cursor_line: int
  489. #: The maximum number of completions that will be used downstream.
  490. #: Matchers can use this information to abort early.
  491. #: The built-in Jedi matcher is currently excepted from this limit.
  492. # If not given, return all possible completions.
  493. limit: Optional[int]
  494. @cached_property
  495. def text_until_cursor(self) -> str:
  496. return self.line_with_cursor[: self.cursor_position]
  497. @cached_property
  498. def line_with_cursor(self) -> str:
  499. return self.full_text.split("\n")[self.cursor_line]
  500. #: Matcher results for API v2.
  501. MatcherResult = Union[SimpleMatcherResult, _JediMatcherResult]
  502. class _MatcherAPIv1Base(Protocol):
  503. def __call__(self, text: str) -> List[str]:
  504. """Call signature."""
  505. ...
  506. #: Used to construct the default matcher identifier
  507. __qualname__: str
  508. class _MatcherAPIv1Total(_MatcherAPIv1Base, Protocol):
  509. #: API version
  510. matcher_api_version: Optional[Literal[1]]
  511. def __call__(self, text: str) -> List[str]:
  512. """Call signature."""
  513. ...
  514. #: Protocol describing Matcher API v1.
  515. MatcherAPIv1: TypeAlias = Union[_MatcherAPIv1Base, _MatcherAPIv1Total]
  516. class MatcherAPIv2(Protocol):
  517. """Protocol describing Matcher API v2."""
  518. #: API version
  519. matcher_api_version: Literal[2] = 2
  520. def __call__(self, context: CompletionContext) -> MatcherResult:
  521. """Call signature."""
  522. ...
  523. #: Used to construct the default matcher identifier
  524. __qualname__: str
  525. Matcher: TypeAlias = Union[MatcherAPIv1, MatcherAPIv2]
  526. def _is_matcher_v1(matcher: Matcher) -> TypeGuard[MatcherAPIv1]:
  527. api_version = _get_matcher_api_version(matcher)
  528. return api_version == 1
  529. def _is_matcher_v2(matcher: Matcher) -> TypeGuard[MatcherAPIv2]:
  530. api_version = _get_matcher_api_version(matcher)
  531. return api_version == 2
  532. def _is_sizable(value: Any) -> TypeGuard[Sized]:
  533. """Determines whether objects is sizable"""
  534. return hasattr(value, "__len__")
  535. def _is_iterator(value: Any) -> TypeGuard[Iterator]:
  536. """Determines whether objects is sizable"""
  537. return hasattr(value, "__next__")
  538. def has_any_completions(result: MatcherResult) -> bool:
  539. """Check if any result includes any completions."""
  540. completions = result["completions"]
  541. if _is_sizable(completions):
  542. return len(completions) != 0
  543. if _is_iterator(completions):
  544. try:
  545. old_iterator = completions
  546. first = next(old_iterator)
  547. result["completions"] = cast(
  548. Iterator[SimpleCompletion],
  549. itertools.chain([first], old_iterator),
  550. )
  551. return True
  552. except StopIteration:
  553. return False
  554. raise ValueError(
  555. "Completions returned by matcher need to be an Iterator or a Sizable"
  556. )
  557. def completion_matcher(
  558. *,
  559. priority: Optional[float] = None,
  560. identifier: Optional[str] = None,
  561. api_version: int = 1,
  562. ):
  563. """Adds attributes describing the matcher.
  564. Parameters
  565. ----------
  566. priority : Optional[float]
  567. The priority of the matcher, determines the order of execution of matchers.
  568. Higher priority means that the matcher will be executed first. Defaults to 0.
  569. identifier : Optional[str]
  570. identifier of the matcher allowing users to modify the behaviour via traitlets,
  571. and also used to for debugging (will be passed as ``origin`` with the completions).
  572. Defaults to matcher function's ``__qualname__`` (for example,
  573. ``IPCompleter.file_matcher`` for the built-in matched defined
  574. as a ``file_matcher`` method of the ``IPCompleter`` class).
  575. api_version: Optional[int]
  576. version of the Matcher API used by this matcher.
  577. Currently supported values are 1 and 2.
  578. Defaults to 1.
  579. """
  580. def wrapper(func: Matcher):
  581. func.matcher_priority = priority or 0 # type: ignore
  582. func.matcher_identifier = identifier or func.__qualname__ # type: ignore
  583. func.matcher_api_version = api_version # type: ignore
  584. if TYPE_CHECKING:
  585. if api_version == 1:
  586. func = cast(MatcherAPIv1, func)
  587. elif api_version == 2:
  588. func = cast(MatcherAPIv2, func)
  589. return func
  590. return wrapper
  591. def _get_matcher_priority(matcher: Matcher):
  592. return getattr(matcher, "matcher_priority", 0)
  593. def _get_matcher_id(matcher: Matcher):
  594. return getattr(matcher, "matcher_identifier", matcher.__qualname__)
  595. def _get_matcher_api_version(matcher):
  596. return getattr(matcher, "matcher_api_version", 1)
  597. context_matcher = partial(completion_matcher, api_version=2)
  598. _IC = Iterable[Completion]
  599. def _deduplicate_completions(text: str, completions: _IC)-> _IC:
  600. """
  601. Deduplicate a set of completions.
  602. .. warning::
  603. Unstable
  604. This function is unstable, API may change without warning.
  605. Parameters
  606. ----------
  607. text : str
  608. text that should be completed.
  609. completions : Iterator[Completion]
  610. iterator over the completions to deduplicate
  611. Yields
  612. ------
  613. `Completions` objects
  614. Completions coming from multiple sources, may be different but end up having
  615. the same effect when applied to ``text``. If this is the case, this will
  616. consider completions as equal and only emit the first encountered.
  617. Not folded in `completions()` yet for debugging purpose, and to detect when
  618. the IPython completer does return things that Jedi does not, but should be
  619. at some point.
  620. """
  621. completions = list(completions)
  622. if not completions:
  623. return
  624. new_start = min(c.start for c in completions)
  625. new_end = max(c.end for c in completions)
  626. seen = set()
  627. for c in completions:
  628. new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
  629. if new_text not in seen:
  630. yield c
  631. seen.add(new_text)
  632. def rectify_completions(text: str, completions: _IC, *, _debug: bool = False) -> _IC:
  633. """
  634. Rectify a set of completions to all have the same ``start`` and ``end``
  635. .. warning::
  636. Unstable
  637. This function is unstable, API may change without warning.
  638. It will also raise unless use in proper context manager.
  639. Parameters
  640. ----------
  641. text : str
  642. text that should be completed.
  643. completions : Iterator[Completion]
  644. iterator over the completions to rectify
  645. _debug : bool
  646. Log failed completion
  647. Notes
  648. -----
  649. :any:`jedi.api.classes.Completion` s returned by Jedi may not have the same start and end, though
  650. the Jupyter Protocol requires them to behave like so. This will readjust
  651. the completion to have the same ``start`` and ``end`` by padding both
  652. extremities with surrounding text.
  653. During stabilisation should support a ``_debug`` option to log which
  654. completion are return by the IPython completer and not found in Jedi in
  655. order to make upstream bug report.
  656. """
  657. warnings.warn("`rectify_completions` is a provisional API (as of IPython 6.0). "
  658. "It may change without warnings. "
  659. "Use in corresponding context manager.",
  660. category=ProvisionalCompleterWarning, stacklevel=2)
  661. completions = list(completions)
  662. if not completions:
  663. return
  664. starts = (c.start for c in completions)
  665. ends = (c.end for c in completions)
  666. new_start = min(starts)
  667. new_end = max(ends)
  668. seen_jedi = set()
  669. seen_python_matches = set()
  670. for c in completions:
  671. new_text = text[new_start:c.start] + c.text + text[c.end:new_end]
  672. if c._origin == 'jedi':
  673. seen_jedi.add(new_text)
  674. elif c._origin == 'IPCompleter.python_matches':
  675. seen_python_matches.add(new_text)
  676. yield Completion(new_start, new_end, new_text, type=c.type, _origin=c._origin, signature=c.signature)
  677. diff = seen_python_matches.difference(seen_jedi)
  678. if diff and _debug:
  679. print('IPython.python matches have extras:', diff)
  680. if sys.platform == 'win32':
  681. DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
  682. else:
  683. DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
  684. GREEDY_DELIMS = ' =\r\n'
  685. class CompletionSplitter(object):
  686. """An object to split an input line in a manner similar to readline.
  687. By having our own implementation, we can expose readline-like completion in
  688. a uniform manner to all frontends. This object only needs to be given the
  689. line of text to be split and the cursor position on said line, and it
  690. returns the 'word' to be completed on at the cursor after splitting the
  691. entire line.
  692. What characters are used as splitting delimiters can be controlled by
  693. setting the ``delims`` attribute (this is a property that internally
  694. automatically builds the necessary regular expression)"""
  695. # Private interface
  696. # A string of delimiter characters. The default value makes sense for
  697. # IPython's most typical usage patterns.
  698. _delims = DELIMS
  699. # The expression (a normal string) to be compiled into a regular expression
  700. # for actual splitting. We store it as an attribute mostly for ease of
  701. # debugging, since this type of code can be so tricky to debug.
  702. _delim_expr = None
  703. # The regular expression that does the actual splitting
  704. _delim_re = None
  705. def __init__(self, delims=None):
  706. delims = CompletionSplitter._delims if delims is None else delims
  707. self.delims = delims
  708. @property
  709. def delims(self):
  710. """Return the string of delimiter characters."""
  711. return self._delims
  712. @delims.setter
  713. def delims(self, delims):
  714. """Set the delimiters for line splitting."""
  715. expr = '[' + ''.join('\\'+ c for c in delims) + ']'
  716. self._delim_re = re.compile(expr)
  717. self._delims = delims
  718. self._delim_expr = expr
  719. def split_line(self, line, cursor_pos=None):
  720. """Split a line of text with a cursor at the given position.
  721. """
  722. l = line if cursor_pos is None else line[:cursor_pos]
  723. return self._delim_re.split(l)[-1]
  724. class Completer(Configurable):
  725. greedy = Bool(
  726. False,
  727. help="""Activate greedy completion.
  728. .. deprecated:: 8.8
  729. Use :std:configtrait:`Completer.evaluation` and :std:configtrait:`Completer.auto_close_dict_keys` instead.
  730. When enabled in IPython 8.8 or newer, changes configuration as follows:
  731. - ``Completer.evaluation = 'unsafe'``
  732. - ``Completer.auto_close_dict_keys = True``
  733. """,
  734. ).tag(config=True)
  735. evaluation = Enum(
  736. ("forbidden", "minimal", "limited", "unsafe", "dangerous"),
  737. default_value="limited",
  738. help="""Policy for code evaluation under completion.
  739. Successive options allow to enable more eager evaluation for better
  740. completion suggestions, including for nested dictionaries, nested lists,
  741. or even results of function calls.
  742. Setting ``unsafe`` or higher can lead to evaluation of arbitrary user
  743. code on :kbd:`Tab` with potentially unwanted or dangerous side effects.
  744. Allowed values are:
  745. - ``forbidden``: no evaluation of code is permitted,
  746. - ``minimal``: evaluation of literals and access to built-in namespace;
  747. no item/attribute evaluationm no access to locals/globals,
  748. no evaluation of any operations or comparisons.
  749. - ``limited``: access to all namespaces, evaluation of hard-coded methods
  750. (for example: :any:`dict.keys`, :any:`object.__getattr__`,
  751. :any:`object.__getitem__`) on allow-listed objects (for example:
  752. :any:`dict`, :any:`list`, :any:`tuple`, ``pandas.Series``),
  753. - ``unsafe``: evaluation of all methods and function calls but not of
  754. syntax with side-effects like `del x`,
  755. - ``dangerous``: completely arbitrary evaluation.
  756. """,
  757. ).tag(config=True)
  758. use_jedi = Bool(default_value=JEDI_INSTALLED,
  759. help="Experimental: Use Jedi to generate autocompletions. "
  760. "Default to True if jedi is installed.").tag(config=True)
  761. jedi_compute_type_timeout = Int(default_value=400,
  762. help="""Experimental: restrict time (in milliseconds) during which Jedi can compute types.
  763. Set to 0 to stop computing types. Non-zero value lower than 100ms may hurt
  764. performance by preventing jedi to build its cache.
  765. """).tag(config=True)
  766. debug = Bool(default_value=False,
  767. help='Enable debug for the Completer. Mostly print extra '
  768. 'information for experimental jedi integration.')\
  769. .tag(config=True)
  770. backslash_combining_completions = Bool(True,
  771. help="Enable unicode completions, e.g. \\alpha<tab> . "
  772. "Includes completion of latex commands, unicode names, and expanding "
  773. "unicode characters back to latex commands.").tag(config=True)
  774. auto_close_dict_keys = Bool(
  775. False,
  776. help="""
  777. Enable auto-closing dictionary keys.
  778. When enabled string keys will be suffixed with a final quote
  779. (matching the opening quote), tuple keys will also receive a
  780. separating comma if needed, and keys which are final will
  781. receive a closing bracket (``]``).
  782. """,
  783. ).tag(config=True)
  784. def __init__(self, namespace=None, global_namespace=None, **kwargs):
  785. """Create a new completer for the command line.
  786. Completer(namespace=ns, global_namespace=ns2) -> completer instance.
  787. If unspecified, the default namespace where completions are performed
  788. is __main__ (technically, __main__.__dict__). Namespaces should be
  789. given as dictionaries.
  790. An optional second namespace can be given. This allows the completer
  791. to handle cases where both the local and global scopes need to be
  792. distinguished.
  793. """
  794. # Don't bind to namespace quite yet, but flag whether the user wants a
  795. # specific namespace or to use __main__.__dict__. This will allow us
  796. # to bind to __main__.__dict__ at completion time, not now.
  797. if namespace is None:
  798. self.use_main_ns = True
  799. else:
  800. self.use_main_ns = False
  801. self.namespace = namespace
  802. # The global namespace, if given, can be bound directly
  803. if global_namespace is None:
  804. self.global_namespace = {}
  805. else:
  806. self.global_namespace = global_namespace
  807. self.custom_matchers = []
  808. super(Completer, self).__init__(**kwargs)
  809. def complete(self, text, state):
  810. """Return the next possible completion for 'text'.
  811. This is called successively with state == 0, 1, 2, ... until it
  812. returns None. The completion should begin with 'text'.
  813. """
  814. if self.use_main_ns:
  815. self.namespace = __main__.__dict__
  816. if state == 0:
  817. if "." in text:
  818. self.matches = self.attr_matches(text)
  819. else:
  820. self.matches = self.global_matches(text)
  821. try:
  822. return self.matches[state]
  823. except IndexError:
  824. return None
  825. def global_matches(self, text):
  826. """Compute matches when text is a simple name.
  827. Return a list of all keywords, built-in functions and names currently
  828. defined in self.namespace or self.global_namespace that match.
  829. """
  830. matches = []
  831. match_append = matches.append
  832. n = len(text)
  833. for lst in [
  834. keyword.kwlist,
  835. builtin_mod.__dict__.keys(),
  836. list(self.namespace.keys()),
  837. list(self.global_namespace.keys()),
  838. ]:
  839. for word in lst:
  840. if word[:n] == text and word != "__builtins__":
  841. match_append(word)
  842. snake_case_re = re.compile(r"[^_]+(_[^_]+)+?\Z")
  843. for lst in [list(self.namespace.keys()), list(self.global_namespace.keys())]:
  844. shortened = {
  845. "_".join([sub[0] for sub in word.split("_")]): word
  846. for word in lst
  847. if snake_case_re.match(word)
  848. }
  849. for word in shortened.keys():
  850. if word[:n] == text and word != "__builtins__":
  851. match_append(shortened[word])
  852. return matches
  853. def attr_matches(self, text):
  854. """Compute matches when text contains a dot.
  855. Assuming the text is of the form NAME.NAME....[NAME], and is
  856. evaluatable in self.namespace or self.global_namespace, it will be
  857. evaluated and its attributes (as revealed by dir()) are used as
  858. possible completions. (For class instances, class members are
  859. also considered.)
  860. WARNING: this can still invoke arbitrary C code, if an object
  861. with a __getattr__ hook is evaluated.
  862. """
  863. m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
  864. if not m2:
  865. return []
  866. expr, attr = m2.group(1, 2)
  867. obj = self._evaluate_expr(expr)
  868. if obj is not_found:
  869. return []
  870. if self.limit_to__all__ and hasattr(obj, '__all__'):
  871. words = get__all__entries(obj)
  872. else:
  873. words = dir2(obj)
  874. try:
  875. words = generics.complete_object(obj, words)
  876. except TryNext:
  877. pass
  878. except AssertionError:
  879. raise
  880. except Exception:
  881. # Silence errors from completion function
  882. pass
  883. # Build match list to return
  884. n = len(attr)
  885. # Note: ideally we would just return words here and the prefix
  886. # reconciliator would know that we intend to append to rather than
  887. # replace the input text; this requires refactoring to return range
  888. # which ought to be replaced (as does jedi).
  889. tokens = _parse_tokens(expr)
  890. rev_tokens = reversed(tokens)
  891. skip_over = {tokenize.ENDMARKER, tokenize.NEWLINE}
  892. name_turn = True
  893. parts = []
  894. for token in rev_tokens:
  895. if token.type in skip_over:
  896. continue
  897. if token.type == tokenize.NAME and name_turn:
  898. parts.append(token.string)
  899. name_turn = False
  900. elif token.type == tokenize.OP and token.string == "." and not name_turn:
  901. parts.append(token.string)
  902. name_turn = True
  903. else:
  904. # short-circuit if not empty nor name token
  905. break
  906. prefix_after_space = "".join(reversed(parts))
  907. return ["%s.%s" % (prefix_after_space, w) for w in words if w[:n] == attr]
  908. def _evaluate_expr(self, expr):
  909. obj = not_found
  910. done = False
  911. while not done and expr:
  912. try:
  913. obj = guarded_eval(
  914. expr,
  915. EvaluationContext(
  916. globals=self.global_namespace,
  917. locals=self.namespace,
  918. evaluation=self.evaluation,
  919. ),
  920. )
  921. done = True
  922. except Exception as e:
  923. if self.debug:
  924. print("Evaluation exception", e)
  925. # trim the expression to remove any invalid prefix
  926. # e.g. user starts `(d[`, so we get `expr = '(d'`,
  927. # where parenthesis is not closed.
  928. # TODO: make this faster by reusing parts of the computation?
  929. expr = expr[1:]
  930. return obj
  931. def get__all__entries(obj):
  932. """returns the strings in the __all__ attribute"""
  933. try:
  934. words = getattr(obj, '__all__')
  935. except:
  936. return []
  937. return [w for w in words if isinstance(w, str)]
  938. class _DictKeyState(enum.Flag):
  939. """Represent state of the key match in context of other possible matches.
  940. - given `d1 = {'a': 1}` completion on `d1['<tab>` will yield `{'a': END_OF_ITEM}` as there is no tuple.
  941. - given `d2 = {('a', 'b'): 1}`: `d2['a', '<tab>` will yield `{'b': END_OF_TUPLE}` as there is no tuple members to add beyond `'b'`.
  942. - given `d3 = {('a', 'b'): 1}`: `d3['<tab>` will yield `{'a': IN_TUPLE}` as `'a'` can be added.
  943. - given `d4 = {'a': 1, ('a', 'b'): 2}`: `d4['<tab>` will yield `{'a': END_OF_ITEM & END_OF_TUPLE}`
  944. """
  945. BASELINE = 0
  946. END_OF_ITEM = enum.auto()
  947. END_OF_TUPLE = enum.auto()
  948. IN_TUPLE = enum.auto()
  949. def _parse_tokens(c):
  950. """Parse tokens even if there is an error."""
  951. tokens = []
  952. token_generator = tokenize.generate_tokens(iter(c.splitlines()).__next__)
  953. while True:
  954. try:
  955. tokens.append(next(token_generator))
  956. except tokenize.TokenError:
  957. return tokens
  958. except StopIteration:
  959. return tokens
  960. def _match_number_in_dict_key_prefix(prefix: str) -> Union[str, None]:
  961. """Match any valid Python numeric literal in a prefix of dictionary keys.
  962. References:
  963. - https://docs.python.org/3/reference/lexical_analysis.html#numeric-literals
  964. - https://docs.python.org/3/library/tokenize.html
  965. """
  966. if prefix[-1].isspace():
  967. # if user typed a space we do not have anything to complete
  968. # even if there was a valid number token before
  969. return None
  970. tokens = _parse_tokens(prefix)
  971. rev_tokens = reversed(tokens)
  972. skip_over = {tokenize.ENDMARKER, tokenize.NEWLINE}
  973. number = None
  974. for token in rev_tokens:
  975. if token.type in skip_over:
  976. continue
  977. if number is None:
  978. if token.type == tokenize.NUMBER:
  979. number = token.string
  980. continue
  981. else:
  982. # we did not match a number
  983. return None
  984. if token.type == tokenize.OP:
  985. if token.string == ",":
  986. break
  987. if token.string in {"+", "-"}:
  988. number = token.string + number
  989. else:
  990. return None
  991. return number
  992. _INT_FORMATS = {
  993. "0b": bin,
  994. "0o": oct,
  995. "0x": hex,
  996. }
  997. def match_dict_keys(
  998. keys: List[Union[str, bytes, Tuple[Union[str, bytes], ...]]],
  999. prefix: str,
  1000. delims: str,
  1001. extra_prefix: Optional[Tuple[Union[str, bytes], ...]] = None,
  1002. ) -> Tuple[str, int, Dict[str, _DictKeyState]]:
  1003. """Used by dict_key_matches, matching the prefix to a list of keys
  1004. Parameters
  1005. ----------
  1006. keys
  1007. list of keys in dictionary currently being completed.
  1008. prefix
  1009. Part of the text already typed by the user. E.g. `mydict[b'fo`
  1010. delims
  1011. String of delimiters to consider when finding the current key.
  1012. extra_prefix : optional
  1013. Part of the text already typed in multi-key index cases. E.g. for
  1014. `mydict['foo', "bar", 'b`, this would be `('foo', 'bar')`.
  1015. Returns
  1016. -------
  1017. A tuple of three elements: ``quote``, ``token_start``, ``matched``, with
  1018. ``quote`` being the quote that need to be used to close current string.
  1019. ``token_start`` the position where the replacement should start occurring,
  1020. ``matches`` a dictionary of replacement/completion keys on keys and values
  1021. indicating whether the state.
  1022. """
  1023. prefix_tuple = extra_prefix if extra_prefix else ()
  1024. prefix_tuple_size = sum(
  1025. [
  1026. # for pandas, do not count slices as taking space
  1027. not isinstance(k, slice)
  1028. for k in prefix_tuple
  1029. ]
  1030. )
  1031. text_serializable_types = (str, bytes, int, float, slice)
  1032. def filter_prefix_tuple(key):
  1033. # Reject too short keys
  1034. if len(key) <= prefix_tuple_size:
  1035. return False
  1036. # Reject keys which cannot be serialised to text
  1037. for k in key:
  1038. if not isinstance(k, text_serializable_types):
  1039. return False
  1040. # Reject keys that do not match the prefix
  1041. for k, pt in zip(key, prefix_tuple):
  1042. if k != pt and not isinstance(pt, slice):
  1043. return False
  1044. # All checks passed!
  1045. return True
  1046. filtered_key_is_final: Dict[
  1047. Union[str, bytes, int, float], _DictKeyState
  1048. ] = defaultdict(lambda: _DictKeyState.BASELINE)
  1049. for k in keys:
  1050. # If at least one of the matches is not final, mark as undetermined.
  1051. # This can happen with `d = {111: 'b', (111, 222): 'a'}` where
  1052. # `111` appears final on first match but is not final on the second.
  1053. if isinstance(k, tuple):
  1054. if filter_prefix_tuple(k):
  1055. key_fragment = k[prefix_tuple_size]
  1056. filtered_key_is_final[key_fragment] |= (
  1057. _DictKeyState.END_OF_TUPLE
  1058. if len(k) == prefix_tuple_size + 1
  1059. else _DictKeyState.IN_TUPLE
  1060. )
  1061. elif prefix_tuple_size > 0:
  1062. # we are completing a tuple but this key is not a tuple,
  1063. # so we should ignore it
  1064. pass
  1065. else:
  1066. if isinstance(k, text_serializable_types):
  1067. filtered_key_is_final[k] |= _DictKeyState.END_OF_ITEM
  1068. filtered_keys = filtered_key_is_final.keys()
  1069. if not prefix:
  1070. return "", 0, {repr(k): v for k, v in filtered_key_is_final.items()}
  1071. quote_match = re.search("(?:\"|')", prefix)
  1072. is_user_prefix_numeric = False
  1073. if quote_match:
  1074. quote = quote_match.group()
  1075. valid_prefix = prefix + quote
  1076. try:
  1077. prefix_str = literal_eval(valid_prefix)
  1078. except Exception:
  1079. return "", 0, {}
  1080. else:
  1081. # If it does not look like a string, let's assume
  1082. # we are dealing with a number or variable.
  1083. number_match = _match_number_in_dict_key_prefix(prefix)
  1084. # We do not want the key matcher to suggest variable names so we yield:
  1085. if number_match is None:
  1086. # The alternative would be to assume that user forgort the quote
  1087. # and if the substring matches, suggest adding it at the start.
  1088. return "", 0, {}
  1089. prefix_str = number_match
  1090. is_user_prefix_numeric = True
  1091. quote = ""
  1092. pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
  1093. token_match = re.search(pattern, prefix, re.UNICODE)
  1094. assert token_match is not None # silence mypy
  1095. token_start = token_match.start()
  1096. token_prefix = token_match.group()
  1097. matched: Dict[str, _DictKeyState] = {}
  1098. str_key: Union[str, bytes]
  1099. for key in filtered_keys:
  1100. if isinstance(key, (int, float)):
  1101. # User typed a number but this key is not a number.
  1102. if not is_user_prefix_numeric:
  1103. continue
  1104. str_key = str(key)
  1105. if isinstance(key, int):
  1106. int_base = prefix_str[:2].lower()
  1107. # if user typed integer using binary/oct/hex notation:
  1108. if int_base in _INT_FORMATS:
  1109. int_format = _INT_FORMATS[int_base]
  1110. str_key = int_format(key)
  1111. else:
  1112. # User typed a string but this key is a number.
  1113. if is_user_prefix_numeric:
  1114. continue
  1115. str_key = key
  1116. try:
  1117. if not str_key.startswith(prefix_str):
  1118. continue
  1119. except (AttributeError, TypeError, UnicodeError) as e:
  1120. # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
  1121. continue
  1122. # reformat remainder of key to begin with prefix
  1123. rem = str_key[len(prefix_str) :]
  1124. # force repr wrapped in '
  1125. rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"')
  1126. rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
  1127. if quote == '"':
  1128. # The entered prefix is quoted with ",
  1129. # but the match is quoted with '.
  1130. # A contained " hence needs escaping for comparison:
  1131. rem_repr = rem_repr.replace('"', '\\"')
  1132. # then reinsert prefix from start of token
  1133. match = "%s%s" % (token_prefix, rem_repr)
  1134. matched[match] = filtered_key_is_final[key]
  1135. return quote, token_start, matched
  1136. def cursor_to_position(text:str, line:int, column:int)->int:
  1137. """
  1138. Convert the (line,column) position of the cursor in text to an offset in a
  1139. string.
  1140. Parameters
  1141. ----------
  1142. text : str
  1143. The text in which to calculate the cursor offset
  1144. line : int
  1145. Line of the cursor; 0-indexed
  1146. column : int
  1147. Column of the cursor 0-indexed
  1148. Returns
  1149. -------
  1150. Position of the cursor in ``text``, 0-indexed.
  1151. See Also
  1152. --------
  1153. position_to_cursor : reciprocal of this function
  1154. """
  1155. lines = text.split('\n')
  1156. assert line <= len(lines), '{} <= {}'.format(str(line), str(len(lines)))
  1157. return sum(len(l) + 1 for l in lines[:line]) + column
  1158. def position_to_cursor(text:str, offset:int)->Tuple[int, int]:
  1159. """
  1160. Convert the position of the cursor in text (0 indexed) to a line
  1161. number(0-indexed) and a column number (0-indexed) pair
  1162. Position should be a valid position in ``text``.
  1163. Parameters
  1164. ----------
  1165. text : str
  1166. The text in which to calculate the cursor offset
  1167. offset : int
  1168. Position of the cursor in ``text``, 0-indexed.
  1169. Returns
  1170. -------
  1171. (line, column) : (int, int)
  1172. Line of the cursor; 0-indexed, column of the cursor 0-indexed
  1173. See Also
  1174. --------
  1175. cursor_to_position : reciprocal of this function
  1176. """
  1177. assert 0 <= offset <= len(text) , "0 <= %s <= %s" % (offset , len(text))
  1178. before = text[:offset]
  1179. blines = before.split('\n') # ! splitnes trim trailing \n
  1180. line = before.count('\n')
  1181. col = len(blines[-1])
  1182. return line, col
  1183. def _safe_isinstance(obj, module, class_name, *attrs):
  1184. """Checks if obj is an instance of module.class_name if loaded
  1185. """
  1186. if module in sys.modules:
  1187. m = sys.modules[module]
  1188. for attr in [class_name, *attrs]:
  1189. m = getattr(m, attr)
  1190. return isinstance(obj, m)
  1191. @context_matcher()
  1192. def back_unicode_name_matcher(context: CompletionContext):
  1193. """Match Unicode characters back to Unicode name
  1194. Same as :any:`back_unicode_name_matches`, but adopted to new Matcher API.
  1195. """
  1196. fragment, matches = back_unicode_name_matches(context.text_until_cursor)
  1197. return _convert_matcher_v1_result_to_v2(
  1198. matches, type="unicode", fragment=fragment, suppress_if_matches=True
  1199. )
  1200. def back_unicode_name_matches(text: str) -> Tuple[str, Sequence[str]]:
  1201. """Match Unicode characters back to Unicode name
  1202. This does ``☃`` -> ``\\snowman``
  1203. Note that snowman is not a valid python3 combining character but will be expanded.
  1204. Though it will not recombine back to the snowman character by the completion machinery.
  1205. This will not either back-complete standard sequences like \\n, \\b ...
  1206. .. deprecated:: 8.6
  1207. You can use :meth:`back_unicode_name_matcher` instead.
  1208. Returns
  1209. =======
  1210. Return a tuple with two elements:
  1211. - The Unicode character that was matched (preceded with a backslash), or
  1212. empty string,
  1213. - a sequence (of 1), name for the match Unicode character, preceded by
  1214. backslash, or empty if no match.
  1215. """
  1216. if len(text)<2:
  1217. return '', ()
  1218. maybe_slash = text[-2]
  1219. if maybe_slash != '\\':
  1220. return '', ()
  1221. char = text[-1]
  1222. # no expand on quote for completion in strings.
  1223. # nor backcomplete standard ascii keys
  1224. if char in string.ascii_letters or char in ('"',"'"):
  1225. return '', ()
  1226. try :
  1227. unic = unicodedata.name(char)
  1228. return '\\'+char,('\\'+unic,)
  1229. except KeyError:
  1230. pass
  1231. return '', ()
  1232. @context_matcher()
  1233. def back_latex_name_matcher(context: CompletionContext):
  1234. """Match latex characters back to unicode name
  1235. Same as :any:`back_latex_name_matches`, but adopted to new Matcher API.
  1236. """
  1237. fragment, matches = back_latex_name_matches(context.text_until_cursor)
  1238. return _convert_matcher_v1_result_to_v2(
  1239. matches, type="latex", fragment=fragment, suppress_if_matches=True
  1240. )
  1241. def back_latex_name_matches(text: str) -> Tuple[str, Sequence[str]]:
  1242. """Match latex characters back to unicode name
  1243. This does ``\\ℵ`` -> ``\\aleph``
  1244. .. deprecated:: 8.6
  1245. You can use :meth:`back_latex_name_matcher` instead.
  1246. """
  1247. if len(text)<2:
  1248. return '', ()
  1249. maybe_slash = text[-2]
  1250. if maybe_slash != '\\':
  1251. return '', ()
  1252. char = text[-1]
  1253. # no expand on quote for completion in strings.
  1254. # nor backcomplete standard ascii keys
  1255. if char in string.ascii_letters or char in ('"',"'"):
  1256. return '', ()
  1257. try :
  1258. latex = reverse_latex_symbol[char]
  1259. # '\\' replace the \ as well
  1260. return '\\'+char,[latex]
  1261. except KeyError:
  1262. pass
  1263. return '', ()
  1264. def _formatparamchildren(parameter) -> str:
  1265. """
  1266. Get parameter name and value from Jedi Private API
  1267. Jedi does not expose a simple way to get `param=value` from its API.
  1268. Parameters
  1269. ----------
  1270. parameter
  1271. Jedi's function `Param`
  1272. Returns
  1273. -------
  1274. A string like 'a', 'b=1', '*args', '**kwargs'
  1275. """
  1276. description = parameter.description
  1277. if not description.startswith('param '):
  1278. raise ValueError('Jedi function parameter description have change format.'
  1279. 'Expected "param ...", found %r".' % description)
  1280. return description[6:]
  1281. def _make_signature(completion)-> str:
  1282. """
  1283. Make the signature from a jedi completion
  1284. Parameters
  1285. ----------
  1286. completion : jedi.Completion
  1287. object does not complete a function type
  1288. Returns
  1289. -------
  1290. a string consisting of the function signature, with the parenthesis but
  1291. without the function name. example:
  1292. `(a, *args, b=1, **kwargs)`
  1293. """
  1294. return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for p in completion.params) if f])
  1295. # it looks like this might work on jedi 0.17
  1296. if hasattr(completion, 'get_signatures'):
  1297. signatures = completion.get_signatures()
  1298. if not signatures:
  1299. return '(?)'
  1300. c0 = completion.get_signatures()[0]
  1301. return '('+c0.to_string().split('(', maxsplit=1)[1]
  1302. return '(%s)'% ', '.join([f for f in (_formatparamchildren(p) for signature in completion.get_signatures()
  1303. for p in signature.defined_names()) if f])
  1304. _CompleteResult = Dict[str, MatcherResult]
  1305. DICT_MATCHER_REGEX = re.compile(
  1306. r"""(?x)
  1307. ( # match dict-referring - or any get item object - expression
  1308. .+
  1309. )
  1310. \[ # open bracket
  1311. \s* # and optional whitespace
  1312. # Capture any number of serializable objects (e.g. "a", "b", 'c')
  1313. # and slices
  1314. ((?:(?:
  1315. (?: # closed string
  1316. [uUbB]? # string prefix (r not handled)
  1317. (?:
  1318. '(?:[^']|(?<!\\)\\')*'
  1319. |
  1320. "(?:[^"]|(?<!\\)\\")*"
  1321. )
  1322. )
  1323. |
  1324. # capture integers and slices
  1325. (?:[-+]?\d+)?(?::(?:[-+]?\d+)?){0,2}
  1326. |
  1327. # integer in bin/hex/oct notation
  1328. 0[bBxXoO]_?(?:\w|\d)+
  1329. )
  1330. \s*,\s*
  1331. )*)
  1332. ((?:
  1333. (?: # unclosed string
  1334. [uUbB]? # string prefix (r not handled)
  1335. (?:
  1336. '(?:[^']|(?<!\\)\\')*
  1337. |
  1338. "(?:[^"]|(?<!\\)\\")*
  1339. )
  1340. )
  1341. |
  1342. # unfinished integer
  1343. (?:[-+]?\d+)
  1344. |
  1345. # integer in bin/hex/oct notation
  1346. 0[bBxXoO]_?(?:\w|\d)+
  1347. )
  1348. )?
  1349. $
  1350. """
  1351. )
  1352. def _convert_matcher_v1_result_to_v2(
  1353. matches: Sequence[str],
  1354. type: str,
  1355. fragment: Optional[str] = None,
  1356. suppress_if_matches: bool = False,
  1357. ) -> SimpleMatcherResult:
  1358. """Utility to help with transition"""
  1359. result = {
  1360. "completions": [SimpleCompletion(text=match, type=type) for match in matches],
  1361. "suppress": (True if matches else False) if suppress_if_matches else False,
  1362. }
  1363. if fragment is not None:
  1364. result["matched_fragment"] = fragment
  1365. return cast(SimpleMatcherResult, result)
  1366. class IPCompleter(Completer):
  1367. """Extension of the completer class with IPython-specific features"""
  1368. @observe('greedy')
  1369. def _greedy_changed(self, change):
  1370. """update the splitter and readline delims when greedy is changed"""
  1371. if change["new"]:
  1372. self.evaluation = "unsafe"
  1373. self.auto_close_dict_keys = True
  1374. self.splitter.delims = GREEDY_DELIMS
  1375. else:
  1376. self.evaluation = "limited"
  1377. self.auto_close_dict_keys = False
  1378. self.splitter.delims = DELIMS
  1379. dict_keys_only = Bool(
  1380. False,
  1381. help="""
  1382. Whether to show dict key matches only.
  1383. (disables all matchers except for `IPCompleter.dict_key_matcher`).
  1384. """,
  1385. )
  1386. suppress_competing_matchers = UnionTrait(
  1387. [Bool(allow_none=True), DictTrait(Bool(None, allow_none=True))],
  1388. default_value=None,
  1389. help="""
  1390. Whether to suppress completions from other *Matchers*.
  1391. When set to ``None`` (default) the matchers will attempt to auto-detect
  1392. whether suppression of other matchers is desirable. For example, at
  1393. the beginning of a line followed by `%` we expect a magic completion
  1394. to be the only applicable option, and after ``my_dict['`` we usually
  1395. expect a completion with an existing dictionary key.
  1396. If you want to disable this heuristic and see completions from all matchers,
  1397. set ``IPCompleter.suppress_competing_matchers = False``.
  1398. To disable the heuristic for specific matchers provide a dictionary mapping:
  1399. ``IPCompleter.suppress_competing_matchers = {'IPCompleter.dict_key_matcher': False}``.
  1400. Set ``IPCompleter.suppress_competing_matchers = True`` to limit
  1401. completions to the set of matchers with the highest priority;
  1402. this is equivalent to ``IPCompleter.merge_completions`` and
  1403. can be beneficial for performance, but will sometimes omit relevant
  1404. candidates from matchers further down the priority list.
  1405. """,
  1406. ).tag(config=True)
  1407. merge_completions = Bool(
  1408. True,
  1409. help="""Whether to merge completion results into a single list
  1410. If False, only the completion results from the first non-empty
  1411. completer will be returned.
  1412. As of version 8.6.0, setting the value to ``False`` is an alias for:
  1413. ``IPCompleter.suppress_competing_matchers = True.``.
  1414. """,
  1415. ).tag(config=True)
  1416. disable_matchers = ListTrait(
  1417. Unicode(),
  1418. help="""List of matchers to disable.
  1419. The list should contain matcher identifiers (see :any:`completion_matcher`).
  1420. """,
  1421. ).tag(config=True)
  1422. omit__names = Enum(
  1423. (0, 1, 2),
  1424. default_value=2,
  1425. help="""Instruct the completer to omit private method names
  1426. Specifically, when completing on ``object.<tab>``.
  1427. When 2 [default]: all names that start with '_' will be excluded.
  1428. When 1: all 'magic' names (``__foo__``) will be excluded.
  1429. When 0: nothing will be excluded.
  1430. """
  1431. ).tag(config=True)
  1432. limit_to__all__ = Bool(False,
  1433. help="""
  1434. DEPRECATED as of version 5.0.
  1435. Instruct the completer to use __all__ for the completion
  1436. Specifically, when completing on ``object.<tab>``.
  1437. When True: only those names in obj.__all__ will be included.
  1438. When False [default]: the __all__ attribute is ignored
  1439. """,
  1440. ).tag(config=True)
  1441. profile_completions = Bool(
  1442. default_value=False,
  1443. help="If True, emit profiling data for completion subsystem using cProfile."
  1444. ).tag(config=True)
  1445. profiler_output_dir = Unicode(
  1446. default_value=".completion_profiles",
  1447. help="Template for path at which to output profile data for completions."
  1448. ).tag(config=True)
  1449. @observe('limit_to__all__')
  1450. def _limit_to_all_changed(self, change):
  1451. warnings.warn('`IPython.core.IPCompleter.limit_to__all__` configuration '
  1452. 'value has been deprecated since IPython 5.0, will be made to have '
  1453. 'no effects and then removed in future version of IPython.',
  1454. UserWarning)
  1455. def __init__(
  1456. self, shell=None, namespace=None, global_namespace=None, config=None, **kwargs
  1457. ):
  1458. """IPCompleter() -> completer
  1459. Return a completer object.
  1460. Parameters
  1461. ----------
  1462. shell
  1463. a pointer to the ipython shell itself. This is needed
  1464. because this completer knows about magic functions, and those can
  1465. only be accessed via the ipython instance.
  1466. namespace : dict, optional
  1467. an optional dict where completions are performed.
  1468. global_namespace : dict, optional
  1469. secondary optional dict for completions, to
  1470. handle cases (such as IPython embedded inside functions) where
  1471. both Python scopes are visible.
  1472. config : Config
  1473. traitlet's config object
  1474. **kwargs
  1475. passed to super class unmodified.
  1476. """
  1477. self.magic_escape = ESC_MAGIC
  1478. self.splitter = CompletionSplitter()
  1479. # _greedy_changed() depends on splitter and readline being defined:
  1480. super().__init__(
  1481. namespace=namespace,
  1482. global_namespace=global_namespace,
  1483. config=config,
  1484. **kwargs,
  1485. )
  1486. # List where completion matches will be stored
  1487. self.matches = []
  1488. self.shell = shell
  1489. # Regexp to split filenames with spaces in them
  1490. self.space_name_re = re.compile(r'([^\\] )')
  1491. # Hold a local ref. to glob.glob for speed
  1492. self.glob = glob.glob
  1493. # Determine if we are running on 'dumb' terminals, like (X)Emacs
  1494. # buffers, to avoid completion problems.
  1495. term = os.environ.get('TERM','xterm')
  1496. self.dumb_terminal = term in ['dumb','emacs']
  1497. # Special handling of backslashes needed in win32 platforms
  1498. if sys.platform == "win32":
  1499. self.clean_glob = self._clean_glob_win32
  1500. else:
  1501. self.clean_glob = self._clean_glob
  1502. #regexp to parse docstring for function signature
  1503. self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
  1504. self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
  1505. #use this if positional argument name is also needed
  1506. #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
  1507. self.magic_arg_matchers = [
  1508. self.magic_config_matcher,
  1509. self.magic_color_matcher,
  1510. ]
  1511. # This is set externally by InteractiveShell
  1512. self.custom_completers = None
  1513. # This is a list of names of unicode characters that can be completed
  1514. # into their corresponding unicode value. The list is large, so we
  1515. # lazily initialize it on first use. Consuming code should access this
  1516. # attribute through the `@unicode_names` property.
  1517. self._unicode_names = None
  1518. self._backslash_combining_matchers = [
  1519. self.latex_name_matcher,
  1520. self.unicode_name_matcher,
  1521. back_latex_name_matcher,
  1522. back_unicode_name_matcher,
  1523. self.fwd_unicode_matcher,
  1524. ]
  1525. if not self.backslash_combining_completions:
  1526. for matcher in self._backslash_combining_matchers:
  1527. self.disable_matchers.append(_get_matcher_id(matcher))
  1528. if not self.merge_completions:
  1529. self.suppress_competing_matchers = True
  1530. @property
  1531. def matchers(self) -> List[Matcher]:
  1532. """All active matcher routines for completion"""
  1533. if self.dict_keys_only:
  1534. return [self.dict_key_matcher]
  1535. if self.use_jedi:
  1536. return [
  1537. *self.custom_matchers,
  1538. *self._backslash_combining_matchers,
  1539. *self.magic_arg_matchers,
  1540. self.custom_completer_matcher,
  1541. self.magic_matcher,
  1542. self._jedi_matcher,
  1543. self.dict_key_matcher,
  1544. self.file_matcher,
  1545. ]
  1546. else:
  1547. return [
  1548. *self.custom_matchers,
  1549. *self._backslash_combining_matchers,
  1550. *self.magic_arg_matchers,
  1551. self.custom_completer_matcher,
  1552. self.dict_key_matcher,
  1553. # TODO: convert python_matches to v2 API
  1554. self.magic_matcher,
  1555. self.python_matches,
  1556. self.file_matcher,
  1557. self.python_func_kw_matcher,
  1558. ]
  1559. def all_completions(self, text:str) -> List[str]:
  1560. """
  1561. Wrapper around the completion methods for the benefit of emacs.
  1562. """
  1563. prefix = text.rpartition('.')[0]
  1564. with provisionalcompleter():
  1565. return ['.'.join([prefix, c.text]) if prefix and self.use_jedi else c.text
  1566. for c in self.completions(text, len(text))]
  1567. return self.complete(text)[1]
  1568. def _clean_glob(self, text:str):
  1569. return self.glob("%s*" % text)
  1570. def _clean_glob_win32(self, text:str):
  1571. return [f.replace("\\","/")
  1572. for f in self.glob("%s*" % text)]
  1573. @context_matcher()
  1574. def file_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
  1575. """Same as :any:`file_matches`, but adopted to new Matcher API."""
  1576. matches = self.file_matches(context.token)
  1577. # TODO: add a heuristic for suppressing (e.g. if it has OS-specific delimiter,
  1578. # starts with `/home/`, `C:\`, etc)
  1579. return _convert_matcher_v1_result_to_v2(matches, type="path")
  1580. def file_matches(self, text: str) -> List[str]:
  1581. """Match filenames, expanding ~USER type strings.
  1582. Most of the seemingly convoluted logic in this completer is an
  1583. attempt to handle filenames with spaces in them. And yet it's not
  1584. quite perfect, because Python's readline doesn't expose all of the
  1585. GNU readline details needed for this to be done correctly.
  1586. For a filename with a space in it, the printed completions will be
  1587. only the parts after what's already been typed (instead of the
  1588. full completions, as is normally done). I don't think with the
  1589. current (as of Python 2.3) Python readline it's possible to do
  1590. better.
  1591. .. deprecated:: 8.6
  1592. You can use :meth:`file_matcher` instead.
  1593. """
  1594. # chars that require escaping with backslash - i.e. chars
  1595. # that readline treats incorrectly as delimiters, but we
  1596. # don't want to treat as delimiters in filename matching
  1597. # when escaped with backslash
  1598. if text.startswith('!'):
  1599. text = text[1:]
  1600. text_prefix = u'!'
  1601. else:
  1602. text_prefix = u''
  1603. text_until_cursor = self.text_until_cursor
  1604. # track strings with open quotes
  1605. open_quotes = has_open_quotes(text_until_cursor)
  1606. if '(' in text_until_cursor or '[' in text_until_cursor:
  1607. lsplit = text
  1608. else:
  1609. try:
  1610. # arg_split ~ shlex.split, but with unicode bugs fixed by us
  1611. lsplit = arg_split(text_until_cursor)[-1]
  1612. except ValueError:
  1613. # typically an unmatched ", or backslash without escaped char.
  1614. if open_quotes:
  1615. lsplit = text_until_cursor.split(open_quotes)[-1]
  1616. else:
  1617. return []
  1618. except IndexError:
  1619. # tab pressed on empty line
  1620. lsplit = ""
  1621. if not open_quotes and lsplit != protect_filename(lsplit):
  1622. # if protectables are found, do matching on the whole escaped name
  1623. has_protectables = True
  1624. text0,text = text,lsplit
  1625. else:
  1626. has_protectables = False
  1627. text = os.path.expanduser(text)
  1628. if text == "":
  1629. return [text_prefix + protect_filename(f) for f in self.glob("*")]
  1630. # Compute the matches from the filesystem
  1631. if sys.platform == 'win32':
  1632. m0 = self.clean_glob(text)
  1633. else:
  1634. m0 = self.clean_glob(text.replace('\\', ''))
  1635. if has_protectables:
  1636. # If we had protectables, we need to revert our changes to the
  1637. # beginning of filename so that we don't double-write the part
  1638. # of the filename we have so far
  1639. len_lsplit = len(lsplit)
  1640. matches = [text_prefix + text0 +
  1641. protect_filename(f[len_lsplit:]) for f in m0]
  1642. else:
  1643. if open_quotes:
  1644. # if we have a string with an open quote, we don't need to
  1645. # protect the names beyond the quote (and we _shouldn't_, as
  1646. # it would cause bugs when the filesystem call is made).
  1647. matches = m0 if sys.platform == "win32" else\
  1648. [protect_filename(f, open_quotes) for f in m0]
  1649. else:
  1650. matches = [text_prefix +
  1651. protect_filename(f) for f in m0]
  1652. # Mark directories in input list by appending '/' to their names.
  1653. return [x+'/' if os.path.isdir(x) else x for x in matches]
  1654. @context_matcher()
  1655. def magic_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
  1656. """Match magics."""
  1657. text = context.token
  1658. matches = self.magic_matches(text)
  1659. result = _convert_matcher_v1_result_to_v2(matches, type="magic")
  1660. is_magic_prefix = len(text) > 0 and text[0] == "%"
  1661. result["suppress"] = is_magic_prefix and bool(result["completions"])
  1662. return result
  1663. def magic_matches(self, text: str):
  1664. """Match magics.
  1665. .. deprecated:: 8.6
  1666. You can use :meth:`magic_matcher` instead.
  1667. """
  1668. # Get all shell magics now rather than statically, so magics loaded at
  1669. # runtime show up too.
  1670. lsm = self.shell.magics_manager.lsmagic()
  1671. line_magics = lsm['line']
  1672. cell_magics = lsm['cell']
  1673. pre = self.magic_escape
  1674. pre2 = pre+pre
  1675. explicit_magic = text.startswith(pre)
  1676. # Completion logic:
  1677. # - user gives %%: only do cell magics
  1678. # - user gives %: do both line and cell magics
  1679. # - no prefix: do both
  1680. # In other words, line magics are skipped if the user gives %% explicitly
  1681. #
  1682. # We also exclude magics that match any currently visible names:
  1683. # https://github.com/ipython/ipython/issues/4877, unless the user has
  1684. # typed a %:
  1685. # https://github.com/ipython/ipython/issues/10754
  1686. bare_text = text.lstrip(pre)
  1687. global_matches = self.global_matches(bare_text)
  1688. if not explicit_magic:
  1689. def matches(magic):
  1690. """
  1691. Filter magics, in particular remove magics that match
  1692. a name present in global namespace.
  1693. """
  1694. return ( magic.startswith(bare_text) and
  1695. magic not in global_matches )
  1696. else:
  1697. def matches(magic):
  1698. return magic.startswith(bare_text)
  1699. comp = [ pre2+m for m in cell_magics if matches(m)]
  1700. if not text.startswith(pre2):
  1701. comp += [ pre+m for m in line_magics if matches(m)]
  1702. return comp
  1703. @context_matcher()
  1704. def magic_config_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
  1705. """Match class names and attributes for %config magic."""
  1706. # NOTE: uses `line_buffer` equivalent for compatibility
  1707. matches = self.magic_config_matches(context.line_with_cursor)
  1708. return _convert_matcher_v1_result_to_v2(matches, type="param")
  1709. def magic_config_matches(self, text: str) -> List[str]:
  1710. """Match class names and attributes for %config magic.
  1711. .. deprecated:: 8.6
  1712. You can use :meth:`magic_config_matcher` instead.
  1713. """
  1714. texts = text.strip().split()
  1715. if len(texts) > 0 and (texts[0] == 'config' or texts[0] == '%config'):
  1716. # get all configuration classes
  1717. classes = sorted(set([ c for c in self.shell.configurables
  1718. if c.__class__.class_traits(config=True)
  1719. ]), key=lambda x: x.__class__.__name__)
  1720. classnames = [ c.__class__.__name__ for c in classes ]
  1721. # return all classnames if config or %config is given
  1722. if len(texts) == 1:
  1723. return classnames
  1724. # match classname
  1725. classname_texts = texts[1].split('.')
  1726. classname = classname_texts[0]
  1727. classname_matches = [ c for c in classnames
  1728. if c.startswith(classname) ]
  1729. # return matched classes or the matched class with attributes
  1730. if texts[1].find('.') < 0:
  1731. return classname_matches
  1732. elif len(classname_matches) == 1 and \
  1733. classname_matches[0] == classname:
  1734. cls = classes[classnames.index(classname)].__class__
  1735. help = cls.class_get_help()
  1736. # strip leading '--' from cl-args:
  1737. help = re.sub(re.compile(r'^--', re.MULTILINE), '', help)
  1738. return [ attr.split('=')[0]
  1739. for attr in help.strip().splitlines()
  1740. if attr.startswith(texts[1]) ]
  1741. return []
  1742. @context_matcher()
  1743. def magic_color_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
  1744. """Match color schemes for %colors magic."""
  1745. # NOTE: uses `line_buffer` equivalent for compatibility
  1746. matches = self.magic_color_matches(context.line_with_cursor)
  1747. return _convert_matcher_v1_result_to_v2(matches, type="param")
  1748. def magic_color_matches(self, text: str) -> List[str]:
  1749. """Match color schemes for %colors magic.
  1750. .. deprecated:: 8.6
  1751. You can use :meth:`magic_color_matcher` instead.
  1752. """
  1753. texts = text.split()
  1754. if text.endswith(' '):
  1755. # .split() strips off the trailing whitespace. Add '' back
  1756. # so that: '%colors ' -> ['%colors', '']
  1757. texts.append('')
  1758. if len(texts) == 2 and (texts[0] == 'colors' or texts[0] == '%colors'):
  1759. prefix = texts[1]
  1760. return [ color for color in InspectColors.keys()
  1761. if color.startswith(prefix) ]
  1762. return []
  1763. @context_matcher(identifier="IPCompleter.jedi_matcher")
  1764. def _jedi_matcher(self, context: CompletionContext) -> _JediMatcherResult:
  1765. matches = self._jedi_matches(
  1766. cursor_column=context.cursor_position,
  1767. cursor_line=context.cursor_line,
  1768. text=context.full_text,
  1769. )
  1770. return {
  1771. "completions": matches,
  1772. # static analysis should not suppress other matchers
  1773. "suppress": False,
  1774. }
  1775. def _jedi_matches(
  1776. self, cursor_column: int, cursor_line: int, text: str
  1777. ) -> Iterator[_JediCompletionLike]:
  1778. """
  1779. Return a list of :any:`jedi.api.Completion`\\s object from a ``text`` and
  1780. cursor position.
  1781. Parameters
  1782. ----------
  1783. cursor_column : int
  1784. column position of the cursor in ``text``, 0-indexed.
  1785. cursor_line : int
  1786. line position of the cursor in ``text``, 0-indexed
  1787. text : str
  1788. text to complete
  1789. Notes
  1790. -----
  1791. If ``IPCompleter.debug`` is ``True`` may return a :any:`_FakeJediCompletion`
  1792. object containing a string with the Jedi debug information attached.
  1793. .. deprecated:: 8.6
  1794. You can use :meth:`_jedi_matcher` instead.
  1795. """
  1796. namespaces = [self.namespace]
  1797. if self.global_namespace is not None:
  1798. namespaces.append(self.global_namespace)
  1799. completion_filter = lambda x:x
  1800. offset = cursor_to_position(text, cursor_line, cursor_column)
  1801. # filter output if we are completing for object members
  1802. if offset:
  1803. pre = text[offset-1]
  1804. if pre == '.':
  1805. if self.omit__names == 2:
  1806. completion_filter = lambda c:not c.name.startswith('_')
  1807. elif self.omit__names == 1:
  1808. completion_filter = lambda c:not (c.name.startswith('__') and c.name.endswith('__'))
  1809. elif self.omit__names == 0:
  1810. completion_filter = lambda x:x
  1811. else:
  1812. raise ValueError("Don't understand self.omit__names == {}".format(self.omit__names))
  1813. interpreter = jedi.Interpreter(text[:offset], namespaces, column=cursor_column, line=cursor_line + 1)
  1814. try_jedi = True
  1815. try:
  1816. # find the first token in the current tree -- if it is a ' or " then we are in a string
  1817. completing_string = False
  1818. try:
  1819. first_child = next(c for c in interpreter._get_module().tree_node.children if hasattr(c, 'value'))
  1820. except StopIteration:
  1821. pass
  1822. else:
  1823. # note the value may be ', ", or it may also be ''' or """, or
  1824. # in some cases, """what/you/typed..., but all of these are
  1825. # strings.
  1826. completing_string = len(first_child.value) > 0 and first_child.value[0] in {"'", '"'}
  1827. # if we are in a string jedi is likely not the right candidate for
  1828. # now. Skip it.
  1829. try_jedi = not completing_string
  1830. except Exception as e:
  1831. # many of things can go wrong, we are using private API just don't crash.
  1832. if self.debug:
  1833. print("Error detecting if completing a non-finished string :", e, '|')
  1834. if not try_jedi:
  1835. return iter([])
  1836. try:
  1837. return filter(completion_filter, interpreter.completions())
  1838. except Exception as e:
  1839. if self.debug:
  1840. return iter(
  1841. [
  1842. _FakeJediCompletion(
  1843. 'Oops Jedi has crashed, please report a bug with the following:\n"""\n%s\ns"""'
  1844. % (e)
  1845. )
  1846. ]
  1847. )
  1848. else:
  1849. return iter([])
  1850. @completion_matcher(api_version=1)
  1851. def python_matches(self, text: str) -> Iterable[str]:
  1852. """Match attributes or global python names"""
  1853. if "." in text:
  1854. try:
  1855. matches = self.attr_matches(text)
  1856. if text.endswith('.') and self.omit__names:
  1857. if self.omit__names == 1:
  1858. # true if txt is _not_ a __ name, false otherwise:
  1859. no__name = (lambda txt:
  1860. re.match(r'.*\.__.*?__',txt) is None)
  1861. else:
  1862. # true if txt is _not_ a _ name, false otherwise:
  1863. no__name = (lambda txt:
  1864. re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
  1865. matches = filter(no__name, matches)
  1866. except NameError:
  1867. # catches <undefined attributes>.<tab>
  1868. matches = []
  1869. else:
  1870. matches = self.global_matches(text)
  1871. return matches
  1872. def _default_arguments_from_docstring(self, doc):
  1873. """Parse the first line of docstring for call signature.
  1874. Docstring should be of the form 'min(iterable[, key=func])\n'.
  1875. It can also parse cython docstring of the form
  1876. 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
  1877. """
  1878. if doc is None:
  1879. return []
  1880. #care only the firstline
  1881. line = doc.lstrip().splitlines()[0]
  1882. #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
  1883. #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
  1884. sig = self.docstring_sig_re.search(line)
  1885. if sig is None:
  1886. return []
  1887. # iterable[, key=func]' -> ['iterable[' ,' key=func]']
  1888. sig = sig.groups()[0].split(',')
  1889. ret = []
  1890. for s in sig:
  1891. #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
  1892. ret += self.docstring_kwd_re.findall(s)
  1893. return ret
  1894. def _default_arguments(self, obj):
  1895. """Return the list of default arguments of obj if it is callable,
  1896. or empty list otherwise."""
  1897. call_obj = obj
  1898. ret = []
  1899. if inspect.isbuiltin(obj):
  1900. pass
  1901. elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
  1902. if inspect.isclass(obj):
  1903. #for cython embedsignature=True the constructor docstring
  1904. #belongs to the object itself not __init__
  1905. ret += self._default_arguments_from_docstring(
  1906. getattr(obj, '__doc__', ''))
  1907. # for classes, check for __init__,__new__
  1908. call_obj = (getattr(obj, '__init__', None) or
  1909. getattr(obj, '__new__', None))
  1910. # for all others, check if they are __call__able
  1911. elif hasattr(obj, '__call__'):
  1912. call_obj = obj.__call__
  1913. ret += self._default_arguments_from_docstring(
  1914. getattr(call_obj, '__doc__', ''))
  1915. _keeps = (inspect.Parameter.KEYWORD_ONLY,
  1916. inspect.Parameter.POSITIONAL_OR_KEYWORD)
  1917. try:
  1918. sig = inspect.signature(obj)
  1919. ret.extend(k for k, v in sig.parameters.items() if
  1920. v.kind in _keeps)
  1921. except ValueError:
  1922. pass
  1923. return list(set(ret))
  1924. @context_matcher()
  1925. def python_func_kw_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
  1926. """Match named parameters (kwargs) of the last open function."""
  1927. matches = self.python_func_kw_matches(context.token)
  1928. return _convert_matcher_v1_result_to_v2(matches, type="param")
  1929. def python_func_kw_matches(self, text):
  1930. """Match named parameters (kwargs) of the last open function.
  1931. .. deprecated:: 8.6
  1932. You can use :meth:`python_func_kw_matcher` instead.
  1933. """
  1934. if "." in text: # a parameter cannot be dotted
  1935. return []
  1936. try: regexp = self.__funcParamsRegex
  1937. except AttributeError:
  1938. regexp = self.__funcParamsRegex = re.compile(r'''
  1939. '.*?(?<!\\)' | # single quoted strings or
  1940. ".*?(?<!\\)" | # double quoted strings or
  1941. \w+ | # identifier
  1942. \S # other characters
  1943. ''', re.VERBOSE | re.DOTALL)
  1944. # 1. find the nearest identifier that comes before an unclosed
  1945. # parenthesis before the cursor
  1946. # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
  1947. tokens = regexp.findall(self.text_until_cursor)
  1948. iterTokens = reversed(tokens); openPar = 0
  1949. for token in iterTokens:
  1950. if token == ')':
  1951. openPar -= 1
  1952. elif token == '(':
  1953. openPar += 1
  1954. if openPar > 0:
  1955. # found the last unclosed parenthesis
  1956. break
  1957. else:
  1958. return []
  1959. # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
  1960. ids = []
  1961. isId = re.compile(r'\w+$').match
  1962. while True:
  1963. try:
  1964. ids.append(next(iterTokens))
  1965. if not isId(ids[-1]):
  1966. ids.pop(); break
  1967. if not next(iterTokens) == '.':
  1968. break
  1969. except StopIteration:
  1970. break
  1971. # Find all named arguments already assigned to, as to avoid suggesting
  1972. # them again
  1973. usedNamedArgs = set()
  1974. par_level = -1
  1975. for token, next_token in zip(tokens, tokens[1:]):
  1976. if token == '(':
  1977. par_level += 1
  1978. elif token == ')':
  1979. par_level -= 1
  1980. if par_level != 0:
  1981. continue
  1982. if next_token != '=':
  1983. continue
  1984. usedNamedArgs.add(token)
  1985. argMatches = []
  1986. try:
  1987. callableObj = '.'.join(ids[::-1])
  1988. namedArgs = self._default_arguments(eval(callableObj,
  1989. self.namespace))
  1990. # Remove used named arguments from the list, no need to show twice
  1991. for namedArg in set(namedArgs) - usedNamedArgs:
  1992. if namedArg.startswith(text):
  1993. argMatches.append("%s=" %namedArg)
  1994. except:
  1995. pass
  1996. return argMatches
  1997. @staticmethod
  1998. def _get_keys(obj: Any) -> List[Any]:
  1999. # Objects can define their own completions by defining an
  2000. # _ipy_key_completions_() method.
  2001. method = get_real_method(obj, '_ipython_key_completions_')
  2002. if method is not None:
  2003. return method()
  2004. # Special case some common in-memory dict-like types
  2005. if isinstance(obj, dict) or _safe_isinstance(obj, "pandas", "DataFrame"):
  2006. try:
  2007. return list(obj.keys())
  2008. except Exception:
  2009. return []
  2010. elif _safe_isinstance(obj, "pandas", "core", "indexing", "_LocIndexer"):
  2011. try:
  2012. return list(obj.obj.keys())
  2013. except Exception:
  2014. return []
  2015. elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
  2016. _safe_isinstance(obj, 'numpy', 'void'):
  2017. return obj.dtype.names or []
  2018. return []
  2019. @context_matcher()
  2020. def dict_key_matcher(self, context: CompletionContext) -> SimpleMatcherResult:
  2021. """Match string keys in a dictionary, after e.g. ``foo[``."""
  2022. matches = self.dict_key_matches(context.token)
  2023. return _convert_matcher_v1_result_to_v2(
  2024. matches, type="dict key", suppress_if_matches=True
  2025. )
  2026. def dict_key_matches(self, text: str) -> List[str]:
  2027. """Match string keys in a dictionary, after e.g. ``foo[``.
  2028. .. deprecated:: 8.6
  2029. You can use :meth:`dict_key_matcher` instead.
  2030. """
  2031. # Short-circuit on closed dictionary (regular expression would
  2032. # not match anyway, but would take quite a while).
  2033. if self.text_until_cursor.strip().endswith("]"):
  2034. return []
  2035. match = DICT_MATCHER_REGEX.search(self.text_until_cursor)
  2036. if match is None:
  2037. return []
  2038. expr, prior_tuple_keys, key_prefix = match.groups()
  2039. obj = self._evaluate_expr(expr)
  2040. if obj is not_found:
  2041. return []
  2042. keys = self._get_keys(obj)
  2043. if not keys:
  2044. return keys
  2045. tuple_prefix = guarded_eval(
  2046. prior_tuple_keys,
  2047. EvaluationContext(
  2048. globals=self.global_namespace,
  2049. locals=self.namespace,
  2050. evaluation=self.evaluation, # type: ignore
  2051. in_subscript=True,
  2052. ),
  2053. )
  2054. closing_quote, token_offset, matches = match_dict_keys(
  2055. keys, key_prefix, self.splitter.delims, extra_prefix=tuple_prefix
  2056. )
  2057. if not matches:
  2058. return []
  2059. # get the cursor position of
  2060. # - the text being completed
  2061. # - the start of the key text
  2062. # - the start of the completion
  2063. text_start = len(self.text_until_cursor) - len(text)
  2064. if key_prefix:
  2065. key_start = match.start(3)
  2066. completion_start = key_start + token_offset
  2067. else:
  2068. key_start = completion_start = match.end()
  2069. # grab the leading prefix, to make sure all completions start with `text`
  2070. if text_start > key_start:
  2071. leading = ''
  2072. else:
  2073. leading = text[text_start:completion_start]
  2074. # append closing quote and bracket as appropriate
  2075. # this is *not* appropriate if the opening quote or bracket is outside
  2076. # the text given to this method, e.g. `d["""a\nt
  2077. can_close_quote = False
  2078. can_close_bracket = False
  2079. continuation = self.line_buffer[len(self.text_until_cursor) :].strip()
  2080. if continuation.startswith(closing_quote):
  2081. # do not close if already closed, e.g. `d['a<tab>'`
  2082. continuation = continuation[len(closing_quote) :]
  2083. else:
  2084. can_close_quote = True
  2085. continuation = continuation.strip()
  2086. # e.g. `pandas.DataFrame` has different tuple indexer behaviour,
  2087. # handling it is out of scope, so let's avoid appending suffixes.
  2088. has_known_tuple_handling = isinstance(obj, dict)
  2089. can_close_bracket = (
  2090. not continuation.startswith("]") and self.auto_close_dict_keys
  2091. )
  2092. can_close_tuple_item = (
  2093. not continuation.startswith(",")
  2094. and has_known_tuple_handling
  2095. and self.auto_close_dict_keys
  2096. )
  2097. can_close_quote = can_close_quote and self.auto_close_dict_keys
  2098. # fast path if closing qoute should be appended but not suffix is allowed
  2099. if not can_close_quote and not can_close_bracket and closing_quote:
  2100. return [leading + k for k in matches]
  2101. results = []
  2102. end_of_tuple_or_item = _DictKeyState.END_OF_TUPLE | _DictKeyState.END_OF_ITEM
  2103. for k, state_flag in matches.items():
  2104. result = leading + k
  2105. if can_close_quote and closing_quote:
  2106. result += closing_quote
  2107. if state_flag == end_of_tuple_or_item:
  2108. # We do not know which suffix to add,
  2109. # e.g. both tuple item and string
  2110. # match this item.
  2111. pass
  2112. if state_flag in end_of_tuple_or_item and can_close_bracket:
  2113. result += "]"
  2114. if state_flag == _DictKeyState.IN_TUPLE and can_close_tuple_item:
  2115. result += ", "
  2116. results.append(result)
  2117. return results
  2118. @context_matcher()
  2119. def unicode_name_matcher(self, context: CompletionContext):
  2120. """Same as :any:`unicode_name_matches`, but adopted to new Matcher API."""
  2121. fragment, matches = self.unicode_name_matches(context.text_until_cursor)
  2122. return _convert_matcher_v1_result_to_v2(
  2123. matches, type="unicode", fragment=fragment, suppress_if_matches=True
  2124. )
  2125. @staticmethod
  2126. def unicode_name_matches(text: str) -> Tuple[str, List[str]]:
  2127. """Match Latex-like syntax for unicode characters base
  2128. on the name of the character.
  2129. This does ``\\GREEK SMALL LETTER ETA`` -> ``η``
  2130. Works only on valid python 3 identifier, or on combining characters that
  2131. will combine to form a valid identifier.
  2132. """
  2133. slashpos = text.rfind('\\')
  2134. if slashpos > -1:
  2135. s = text[slashpos+1:]
  2136. try :
  2137. unic = unicodedata.lookup(s)
  2138. # allow combining chars
  2139. if ('a'+unic).isidentifier():
  2140. return '\\'+s,[unic]
  2141. except KeyError:
  2142. pass
  2143. return '', []
  2144. @context_matcher()
  2145. def latex_name_matcher(self, context: CompletionContext):
  2146. """Match Latex syntax for unicode characters.
  2147. This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``α``
  2148. """
  2149. fragment, matches = self.latex_matches(context.text_until_cursor)
  2150. return _convert_matcher_v1_result_to_v2(
  2151. matches, type="latex", fragment=fragment, suppress_if_matches=True
  2152. )
  2153. def latex_matches(self, text: str) -> Tuple[str, Sequence[str]]:
  2154. """Match Latex syntax for unicode characters.
  2155. This does both ``\\alp`` -> ``\\alpha`` and ``\\alpha`` -> ``α``
  2156. .. deprecated:: 8.6
  2157. You can use :meth:`latex_name_matcher` instead.
  2158. """
  2159. slashpos = text.rfind('\\')
  2160. if slashpos > -1:
  2161. s = text[slashpos:]
  2162. if s in latex_symbols:
  2163. # Try to complete a full latex symbol to unicode
  2164. # \\alpha -> α
  2165. return s, [latex_symbols[s]]
  2166. else:
  2167. # If a user has partially typed a latex symbol, give them
  2168. # a full list of options \al -> [\aleph, \alpha]
  2169. matches = [k for k in latex_symbols if k.startswith(s)]
  2170. if matches:
  2171. return s, matches
  2172. return '', ()
  2173. @context_matcher()
  2174. def custom_completer_matcher(self, context):
  2175. """Dispatch custom completer.
  2176. If a match is found, suppresses all other matchers except for Jedi.
  2177. """
  2178. matches = self.dispatch_custom_completer(context.token) or []
  2179. result = _convert_matcher_v1_result_to_v2(
  2180. matches, type=_UNKNOWN_TYPE, suppress_if_matches=True
  2181. )
  2182. result["ordered"] = True
  2183. result["do_not_suppress"] = {_get_matcher_id(self._jedi_matcher)}
  2184. return result
  2185. def dispatch_custom_completer(self, text):
  2186. """
  2187. .. deprecated:: 8.6
  2188. You can use :meth:`custom_completer_matcher` instead.
  2189. """
  2190. if not self.custom_completers:
  2191. return
  2192. line = self.line_buffer
  2193. if not line.strip():
  2194. return None
  2195. # Create a little structure to pass all the relevant information about
  2196. # the current completion to any custom completer.
  2197. event = SimpleNamespace()
  2198. event.line = line
  2199. event.symbol = text
  2200. cmd = line.split(None,1)[0]
  2201. event.command = cmd
  2202. event.text_until_cursor = self.text_until_cursor
  2203. # for foo etc, try also to find completer for %foo
  2204. if not cmd.startswith(self.magic_escape):
  2205. try_magic = self.custom_completers.s_matches(
  2206. self.magic_escape + cmd)
  2207. else:
  2208. try_magic = []
  2209. for c in itertools.chain(self.custom_completers.s_matches(cmd),
  2210. try_magic,
  2211. self.custom_completers.flat_matches(self.text_until_cursor)):
  2212. try:
  2213. res = c(event)
  2214. if res:
  2215. # first, try case sensitive match
  2216. withcase = [r for r in res if r.startswith(text)]
  2217. if withcase:
  2218. return withcase
  2219. # if none, then case insensitive ones are ok too
  2220. text_low = text.lower()
  2221. return [r for r in res if r.lower().startswith(text_low)]
  2222. except TryNext:
  2223. pass
  2224. except KeyboardInterrupt:
  2225. """
  2226. If custom completer take too long,
  2227. let keyboard interrupt abort and return nothing.
  2228. """
  2229. break
  2230. return None
  2231. def completions(self, text: str, offset: int)->Iterator[Completion]:
  2232. """
  2233. Returns an iterator over the possible completions
  2234. .. warning::
  2235. Unstable
  2236. This function is unstable, API may change without warning.
  2237. It will also raise unless use in proper context manager.
  2238. Parameters
  2239. ----------
  2240. text : str
  2241. Full text of the current input, multi line string.
  2242. offset : int
  2243. Integer representing the position of the cursor in ``text``. Offset
  2244. is 0-based indexed.
  2245. Yields
  2246. ------
  2247. Completion
  2248. Notes
  2249. -----
  2250. The cursor on a text can either be seen as being "in between"
  2251. characters or "On" a character depending on the interface visible to
  2252. the user. For consistency the cursor being on "in between" characters X
  2253. and Y is equivalent to the cursor being "on" character Y, that is to say
  2254. the character the cursor is on is considered as being after the cursor.
  2255. Combining characters may span more that one position in the
  2256. text.
  2257. .. note::
  2258. If ``IPCompleter.debug`` is :any:`True` will yield a ``--jedi/ipython--``
  2259. fake Completion token to distinguish completion returned by Jedi
  2260. and usual IPython completion.
  2261. .. note::
  2262. Completions are not completely deduplicated yet. If identical
  2263. completions are coming from different sources this function does not
  2264. ensure that each completion object will only be present once.
  2265. """
  2266. warnings.warn("_complete is a provisional API (as of IPython 6.0). "
  2267. "It may change without warnings. "
  2268. "Use in corresponding context manager.",
  2269. category=ProvisionalCompleterWarning, stacklevel=2)
  2270. seen = set()
  2271. profiler:Optional[cProfile.Profile]
  2272. try:
  2273. if self.profile_completions:
  2274. import cProfile
  2275. profiler = cProfile.Profile()
  2276. profiler.enable()
  2277. else:
  2278. profiler = None
  2279. for c in self._completions(text, offset, _timeout=self.jedi_compute_type_timeout/1000):
  2280. if c and (c in seen):
  2281. continue
  2282. yield c
  2283. seen.add(c)
  2284. except KeyboardInterrupt:
  2285. """if completions take too long and users send keyboard interrupt,
  2286. do not crash and return ASAP. """
  2287. pass
  2288. finally:
  2289. if profiler is not None:
  2290. profiler.disable()
  2291. ensure_dir_exists(self.profiler_output_dir)
  2292. output_path = os.path.join(self.profiler_output_dir, str(uuid.uuid4()))
  2293. print("Writing profiler output to", output_path)
  2294. profiler.dump_stats(output_path)
  2295. def _completions(self, full_text: str, offset: int, *, _timeout) -> Iterator[Completion]:
  2296. """
  2297. Core completion module.Same signature as :any:`completions`, with the
  2298. extra `timeout` parameter (in seconds).
  2299. Computing jedi's completion ``.type`` can be quite expensive (it is a
  2300. lazy property) and can require some warm-up, more warm up than just
  2301. computing the ``name`` of a completion. The warm-up can be :
  2302. - Long warm-up the first time a module is encountered after
  2303. install/update: actually build parse/inference tree.
  2304. - first time the module is encountered in a session: load tree from
  2305. disk.
  2306. We don't want to block completions for tens of seconds so we give the
  2307. completer a "budget" of ``_timeout`` seconds per invocation to compute
  2308. completions types, the completions that have not yet been computed will
  2309. be marked as "unknown" an will have a chance to be computed next round
  2310. are things get cached.
  2311. Keep in mind that Jedi is not the only thing treating the completion so
  2312. keep the timeout short-ish as if we take more than 0.3 second we still
  2313. have lots of processing to do.
  2314. """
  2315. deadline = time.monotonic() + _timeout
  2316. before = full_text[:offset]
  2317. cursor_line, cursor_column = position_to_cursor(full_text, offset)
  2318. jedi_matcher_id = _get_matcher_id(self._jedi_matcher)
  2319. def is_non_jedi_result(
  2320. result: MatcherResult, identifier: str
  2321. ) -> TypeGuard[SimpleMatcherResult]:
  2322. return identifier != jedi_matcher_id
  2323. results = self._complete(
  2324. full_text=full_text, cursor_line=cursor_line, cursor_pos=cursor_column
  2325. )
  2326. non_jedi_results: Dict[str, SimpleMatcherResult] = {
  2327. identifier: result
  2328. for identifier, result in results.items()
  2329. if is_non_jedi_result(result, identifier)
  2330. }
  2331. jedi_matches = (
  2332. cast(_JediMatcherResult, results[jedi_matcher_id])["completions"]
  2333. if jedi_matcher_id in results
  2334. else ()
  2335. )
  2336. iter_jm = iter(jedi_matches)
  2337. if _timeout:
  2338. for jm in iter_jm:
  2339. try:
  2340. type_ = jm.type
  2341. except Exception:
  2342. if self.debug:
  2343. print("Error in Jedi getting type of ", jm)
  2344. type_ = None
  2345. delta = len(jm.name_with_symbols) - len(jm.complete)
  2346. if type_ == 'function':
  2347. signature = _make_signature(jm)
  2348. else:
  2349. signature = ''
  2350. yield Completion(start=offset - delta,
  2351. end=offset,
  2352. text=jm.name_with_symbols,
  2353. type=type_,
  2354. signature=signature,
  2355. _origin='jedi')
  2356. if time.monotonic() > deadline:
  2357. break
  2358. for jm in iter_jm:
  2359. delta = len(jm.name_with_symbols) - len(jm.complete)
  2360. yield Completion(
  2361. start=offset - delta,
  2362. end=offset,
  2363. text=jm.name_with_symbols,
  2364. type=_UNKNOWN_TYPE, # don't compute type for speed
  2365. _origin="jedi",
  2366. signature="",
  2367. )
  2368. # TODO:
  2369. # Suppress this, right now just for debug.
  2370. if jedi_matches and non_jedi_results and self.debug:
  2371. some_start_offset = before.rfind(
  2372. next(iter(non_jedi_results.values()))["matched_fragment"]
  2373. )
  2374. yield Completion(
  2375. start=some_start_offset,
  2376. end=offset,
  2377. text="--jedi/ipython--",
  2378. _origin="debug",
  2379. type="none",
  2380. signature="",
  2381. )
  2382. ordered: List[Completion] = []
  2383. sortable: List[Completion] = []
  2384. for origin, result in non_jedi_results.items():
  2385. matched_text = result["matched_fragment"]
  2386. start_offset = before.rfind(matched_text)
  2387. is_ordered = result.get("ordered", False)
  2388. container = ordered if is_ordered else sortable
  2389. # I'm unsure if this is always true, so let's assert and see if it
  2390. # crash
  2391. assert before.endswith(matched_text)
  2392. for simple_completion in result["completions"]:
  2393. completion = Completion(
  2394. start=start_offset,
  2395. end=offset,
  2396. text=simple_completion.text,
  2397. _origin=origin,
  2398. signature="",
  2399. type=simple_completion.type or _UNKNOWN_TYPE,
  2400. )
  2401. container.append(completion)
  2402. yield from list(self._deduplicate(ordered + self._sort(sortable)))[
  2403. :MATCHES_LIMIT
  2404. ]
  2405. def complete(self, text=None, line_buffer=None, cursor_pos=None) -> Tuple[str, Sequence[str]]:
  2406. """Find completions for the given text and line context.
  2407. Note that both the text and the line_buffer are optional, but at least
  2408. one of them must be given.
  2409. Parameters
  2410. ----------
  2411. text : string, optional
  2412. Text to perform the completion on. If not given, the line buffer
  2413. is split using the instance's CompletionSplitter object.
  2414. line_buffer : string, optional
  2415. If not given, the completer attempts to obtain the current line
  2416. buffer via readline. This keyword allows clients which are
  2417. requesting for text completions in non-readline contexts to inform
  2418. the completer of the entire text.
  2419. cursor_pos : int, optional
  2420. Index of the cursor in the full line buffer. Should be provided by
  2421. remote frontends where kernel has no access to frontend state.
  2422. Returns
  2423. -------
  2424. Tuple of two items:
  2425. text : str
  2426. Text that was actually used in the completion.
  2427. matches : list
  2428. A list of completion matches.
  2429. Notes
  2430. -----
  2431. This API is likely to be deprecated and replaced by
  2432. :any:`IPCompleter.completions` in the future.
  2433. """
  2434. warnings.warn('`Completer.complete` is pending deprecation since '
  2435. 'IPython 6.0 and will be replaced by `Completer.completions`.',
  2436. PendingDeprecationWarning)
  2437. # potential todo, FOLD the 3rd throw away argument of _complete
  2438. # into the first 2 one.
  2439. # TODO: Q: does the above refer to jedi completions (i.e. 0-indexed?)
  2440. # TODO: should we deprecate now, or does it stay?
  2441. results = self._complete(
  2442. line_buffer=line_buffer, cursor_pos=cursor_pos, text=text, cursor_line=0
  2443. )
  2444. jedi_matcher_id = _get_matcher_id(self._jedi_matcher)
  2445. return self._arrange_and_extract(
  2446. results,
  2447. # TODO: can we confirm that excluding Jedi here was a deliberate choice in previous version?
  2448. skip_matchers={jedi_matcher_id},
  2449. # this API does not support different start/end positions (fragments of token).
  2450. abort_if_offset_changes=True,
  2451. )
  2452. def _arrange_and_extract(
  2453. self,
  2454. results: Dict[str, MatcherResult],
  2455. skip_matchers: Set[str],
  2456. abort_if_offset_changes: bool,
  2457. ):
  2458. sortable: List[AnyMatcherCompletion] = []
  2459. ordered: List[AnyMatcherCompletion] = []
  2460. most_recent_fragment = None
  2461. for identifier, result in results.items():
  2462. if identifier in skip_matchers:
  2463. continue
  2464. if not result["completions"]:
  2465. continue
  2466. if not most_recent_fragment:
  2467. most_recent_fragment = result["matched_fragment"]
  2468. if (
  2469. abort_if_offset_changes
  2470. and result["matched_fragment"] != most_recent_fragment
  2471. ):
  2472. break
  2473. if result.get("ordered", False):
  2474. ordered.extend(result["completions"])
  2475. else:
  2476. sortable.extend(result["completions"])
  2477. if not most_recent_fragment:
  2478. most_recent_fragment = "" # to satisfy typechecker (and just in case)
  2479. return most_recent_fragment, [
  2480. m.text for m in self._deduplicate(ordered + self._sort(sortable))
  2481. ]
  2482. def _complete(self, *, cursor_line, cursor_pos, line_buffer=None, text=None,
  2483. full_text=None) -> _CompleteResult:
  2484. """
  2485. Like complete but can also returns raw jedi completions as well as the
  2486. origin of the completion text. This could (and should) be made much
  2487. cleaner but that will be simpler once we drop the old (and stateful)
  2488. :any:`complete` API.
  2489. With current provisional API, cursor_pos act both (depending on the
  2490. caller) as the offset in the ``text`` or ``line_buffer``, or as the
  2491. ``column`` when passing multiline strings this could/should be renamed
  2492. but would add extra noise.
  2493. Parameters
  2494. ----------
  2495. cursor_line
  2496. Index of the line the cursor is on. 0 indexed.
  2497. cursor_pos
  2498. Position of the cursor in the current line/line_buffer/text. 0
  2499. indexed.
  2500. line_buffer : optional, str
  2501. The current line the cursor is in, this is mostly due to legacy
  2502. reason that readline could only give a us the single current line.
  2503. Prefer `full_text`.
  2504. text : str
  2505. The current "token" the cursor is in, mostly also for historical
  2506. reasons. as the completer would trigger only after the current line
  2507. was parsed.
  2508. full_text : str
  2509. Full text of the current cell.
  2510. Returns
  2511. -------
  2512. An ordered dictionary where keys are identifiers of completion
  2513. matchers and values are ``MatcherResult``s.
  2514. """
  2515. # if the cursor position isn't given, the only sane assumption we can
  2516. # make is that it's at the end of the line (the common case)
  2517. if cursor_pos is None:
  2518. cursor_pos = len(line_buffer) if text is None else len(text)
  2519. if self.use_main_ns:
  2520. self.namespace = __main__.__dict__
  2521. # if text is either None or an empty string, rely on the line buffer
  2522. if (not line_buffer) and full_text:
  2523. line_buffer = full_text.split('\n')[cursor_line]
  2524. if not text: # issue #11508: check line_buffer before calling split_line
  2525. text = (
  2526. self.splitter.split_line(line_buffer, cursor_pos) if line_buffer else ""
  2527. )
  2528. # If no line buffer is given, assume the input text is all there was
  2529. if line_buffer is None:
  2530. line_buffer = text
  2531. # deprecated - do not use `line_buffer` in new code.
  2532. self.line_buffer = line_buffer
  2533. self.text_until_cursor = self.line_buffer[:cursor_pos]
  2534. if not full_text:
  2535. full_text = line_buffer
  2536. context = CompletionContext(
  2537. full_text=full_text,
  2538. cursor_position=cursor_pos,
  2539. cursor_line=cursor_line,
  2540. token=text,
  2541. limit=MATCHES_LIMIT,
  2542. )
  2543. # Start with a clean slate of completions
  2544. results: Dict[str, MatcherResult] = {}
  2545. jedi_matcher_id = _get_matcher_id(self._jedi_matcher)
  2546. suppressed_matchers: Set[str] = set()
  2547. matchers = {
  2548. _get_matcher_id(matcher): matcher
  2549. for matcher in sorted(
  2550. self.matchers, key=_get_matcher_priority, reverse=True
  2551. )
  2552. }
  2553. for matcher_id, matcher in matchers.items():
  2554. matcher_id = _get_matcher_id(matcher)
  2555. if matcher_id in self.disable_matchers:
  2556. continue
  2557. if matcher_id in results:
  2558. warnings.warn(f"Duplicate matcher ID: {matcher_id}.")
  2559. if matcher_id in suppressed_matchers:
  2560. continue
  2561. result: MatcherResult
  2562. try:
  2563. if _is_matcher_v1(matcher):
  2564. result = _convert_matcher_v1_result_to_v2(
  2565. matcher(text), type=_UNKNOWN_TYPE
  2566. )
  2567. elif _is_matcher_v2(matcher):
  2568. result = matcher(context)
  2569. else:
  2570. api_version = _get_matcher_api_version(matcher)
  2571. raise ValueError(f"Unsupported API version {api_version}")
  2572. except:
  2573. # Show the ugly traceback if the matcher causes an
  2574. # exception, but do NOT crash the kernel!
  2575. sys.excepthook(*sys.exc_info())
  2576. continue
  2577. # set default value for matched fragment if suffix was not selected.
  2578. result["matched_fragment"] = result.get("matched_fragment", context.token)
  2579. if not suppressed_matchers:
  2580. suppression_recommended: Union[bool, Set[str]] = result.get(
  2581. "suppress", False
  2582. )
  2583. suppression_config = (
  2584. self.suppress_competing_matchers.get(matcher_id, None)
  2585. if isinstance(self.suppress_competing_matchers, dict)
  2586. else self.suppress_competing_matchers
  2587. )
  2588. should_suppress = (
  2589. (suppression_config is True)
  2590. or (suppression_recommended and (suppression_config is not False))
  2591. ) and has_any_completions(result)
  2592. if should_suppress:
  2593. suppression_exceptions: Set[str] = result.get(
  2594. "do_not_suppress", set()
  2595. )
  2596. if isinstance(suppression_recommended, Iterable):
  2597. to_suppress = set(suppression_recommended)
  2598. else:
  2599. to_suppress = set(matchers)
  2600. suppressed_matchers = to_suppress - suppression_exceptions
  2601. new_results = {}
  2602. for previous_matcher_id, previous_result in results.items():
  2603. if previous_matcher_id not in suppressed_matchers:
  2604. new_results[previous_matcher_id] = previous_result
  2605. results = new_results
  2606. results[matcher_id] = result
  2607. _, matches = self._arrange_and_extract(
  2608. results,
  2609. # TODO Jedi completions non included in legacy stateful API; was this deliberate or omission?
  2610. # if it was omission, we can remove the filtering step, otherwise remove this comment.
  2611. skip_matchers={jedi_matcher_id},
  2612. abort_if_offset_changes=False,
  2613. )
  2614. # populate legacy stateful API
  2615. self.matches = matches
  2616. return results
  2617. @staticmethod
  2618. def _deduplicate(
  2619. matches: Sequence[AnyCompletion],
  2620. ) -> Iterable[AnyCompletion]:
  2621. filtered_matches: Dict[str, AnyCompletion] = {}
  2622. for match in matches:
  2623. text = match.text
  2624. if (
  2625. text not in filtered_matches
  2626. or filtered_matches[text].type == _UNKNOWN_TYPE
  2627. ):
  2628. filtered_matches[text] = match
  2629. return filtered_matches.values()
  2630. @staticmethod
  2631. def _sort(matches: Sequence[AnyCompletion]):
  2632. return sorted(matches, key=lambda x: completions_sorting_key(x.text))
  2633. @context_matcher()
  2634. def fwd_unicode_matcher(self, context: CompletionContext):
  2635. """Same as :any:`fwd_unicode_match`, but adopted to new Matcher API."""
  2636. # TODO: use `context.limit` to terminate early once we matched the maximum
  2637. # number that will be used downstream; can be added as an optional to
  2638. # `fwd_unicode_match(text: str, limit: int = None)` or we could re-implement here.
  2639. fragment, matches = self.fwd_unicode_match(context.text_until_cursor)
  2640. return _convert_matcher_v1_result_to_v2(
  2641. matches, type="unicode", fragment=fragment, suppress_if_matches=True
  2642. )
  2643. def fwd_unicode_match(self, text: str) -> Tuple[str, Sequence[str]]:
  2644. """
  2645. Forward match a string starting with a backslash with a list of
  2646. potential Unicode completions.
  2647. Will compute list of Unicode character names on first call and cache it.
  2648. .. deprecated:: 8.6
  2649. You can use :meth:`fwd_unicode_matcher` instead.
  2650. Returns
  2651. -------
  2652. At tuple with:
  2653. - matched text (empty if no matches)
  2654. - list of potential completions, empty tuple otherwise)
  2655. """
  2656. # TODO: self.unicode_names is here a list we traverse each time with ~100k elements.
  2657. # We could do a faster match using a Trie.
  2658. # Using pygtrie the following seem to work:
  2659. # s = PrefixSet()
  2660. # for c in range(0,0x10FFFF + 1):
  2661. # try:
  2662. # s.add(unicodedata.name(chr(c)))
  2663. # except ValueError:
  2664. # pass
  2665. # [''.join(k) for k in s.iter(prefix)]
  2666. # But need to be timed and adds an extra dependency.
  2667. slashpos = text.rfind('\\')
  2668. # if text starts with slash
  2669. if slashpos > -1:
  2670. # PERF: It's important that we don't access self._unicode_names
  2671. # until we're inside this if-block. _unicode_names is lazily
  2672. # initialized, and it takes a user-noticeable amount of time to
  2673. # initialize it, so we don't want to initialize it unless we're
  2674. # actually going to use it.
  2675. s = text[slashpos + 1 :]
  2676. sup = s.upper()
  2677. candidates = [x for x in self.unicode_names if x.startswith(sup)]
  2678. if candidates:
  2679. return s, candidates
  2680. candidates = [x for x in self.unicode_names if sup in x]
  2681. if candidates:
  2682. return s, candidates
  2683. splitsup = sup.split(" ")
  2684. candidates = [
  2685. x for x in self.unicode_names if all(u in x for u in splitsup)
  2686. ]
  2687. if candidates:
  2688. return s, candidates
  2689. return "", ()
  2690. # if text does not start with slash
  2691. else:
  2692. return '', ()
  2693. @property
  2694. def unicode_names(self) -> List[str]:
  2695. """List of names of unicode code points that can be completed.
  2696. The list is lazily initialized on first access.
  2697. """
  2698. if self._unicode_names is None:
  2699. names = []
  2700. for c in range(0,0x10FFFF + 1):
  2701. try:
  2702. names.append(unicodedata.name(chr(c)))
  2703. except ValueError:
  2704. pass
  2705. self._unicode_names = _unicode_name_compute(_UNICODE_RANGES)
  2706. return self._unicode_names
  2707. def _unicode_name_compute(ranges:List[Tuple[int,int]]) -> List[str]:
  2708. names = []
  2709. for start,stop in ranges:
  2710. for c in range(start, stop) :
  2711. try:
  2712. names.append(unicodedata.name(chr(c)))
  2713. except ValueError:
  2714. pass
  2715. return names