completer.py 118 KB

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