completer.py 42 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  1. # encoding: utf-8
  2. """Word completion for IPython.
  3. This module started as fork of the rlcompleter module in the Python standard
  4. library. The original enhancements made to rlcompleter have been sent
  5. upstream and were accepted as of Python 2.3,
  6. """
  7. # Copyright (c) IPython Development Team.
  8. # Distributed under the terms of the Modified BSD License.
  9. #
  10. # Some of this code originated from rlcompleter in the Python standard library
  11. # Copyright (C) 2001 Python Software Foundation, www.python.org
  12. from __future__ import print_function
  13. import __main__
  14. import glob
  15. import inspect
  16. import itertools
  17. import keyword
  18. import os
  19. import re
  20. import sys
  21. import unicodedata
  22. import string
  23. from traitlets.config.configurable import Configurable
  24. from IPython.core.error import TryNext
  25. from IPython.core.inputsplitter import ESC_MAGIC
  26. from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol
  27. from IPython.utils import generics
  28. from IPython.utils.decorators import undoc
  29. from IPython.utils.dir2 import dir2, get_real_method
  30. from IPython.utils.process import arg_split
  31. from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2
  32. from traitlets import Bool, Enum, observe
  33. from functools import wraps
  34. #-----------------------------------------------------------------------------
  35. # Globals
  36. #-----------------------------------------------------------------------------
  37. # Public API
  38. __all__ = ['Completer','IPCompleter']
  39. if sys.platform == 'win32':
  40. PROTECTABLES = ' '
  41. else:
  42. PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&'
  43. #-----------------------------------------------------------------------------
  44. # Work around BUG decorators.
  45. #-----------------------------------------------------------------------------
  46. def _strip_single_trailing_space(complete):
  47. """
  48. This is a workaround for a weird IPython/Prompt_toolkit behavior,
  49. that can be removed once we rely on a slightly more recent prompt_toolkit
  50. version (likely > 1.0.3). So this can likely be removed in IPython 6.0
  51. cf https://github.com/ipython/ipython/issues/9658
  52. and https://github.com/jonathanslenders/python-prompt-toolkit/pull/328
  53. The bug is due to the fact that in PTK the completer will reinvoke itself
  54. after trying to completer to the longuest common prefix of all the
  55. completions, unless only one completion is available.
  56. This logic is faulty if the completion ends with space, which can happen in
  57. case like::
  58. from foo import im<ta>
  59. which only matching completion is `import `. Note the leading space at the
  60. end. So leaving a space at the end is a reasonable request, but for now
  61. we'll strip it.
  62. """
  63. @wraps(complete)
  64. def comp(*args, **kwargs):
  65. text, matches = complete(*args, **kwargs)
  66. if len(matches) == 1:
  67. return text, [matches[0].rstrip()]
  68. return text, matches
  69. return comp
  70. #-----------------------------------------------------------------------------
  71. # Main functions and classes
  72. #-----------------------------------------------------------------------------
  73. def has_open_quotes(s):
  74. """Return whether a string has open quotes.
  75. This simply counts whether the number of quote characters of either type in
  76. the string is odd.
  77. Returns
  78. -------
  79. If there is an open quote, the quote character is returned. Else, return
  80. False.
  81. """
  82. # We check " first, then ', so complex cases with nested quotes will get
  83. # the " to take precedence.
  84. if s.count('"') % 2:
  85. return '"'
  86. elif s.count("'") % 2:
  87. return "'"
  88. else:
  89. return False
  90. def protect_filename(s):
  91. """Escape a string to protect certain characters."""
  92. if set(s) & set(PROTECTABLES):
  93. if sys.platform == "win32":
  94. return '"' + s + '"'
  95. else:
  96. return "".join(("\\" + c if c in PROTECTABLES else c) for c in s)
  97. else:
  98. return s
  99. def expand_user(path):
  100. """Expand '~'-style usernames in strings.
  101. This is similar to :func:`os.path.expanduser`, but it computes and returns
  102. extra information that will be useful if the input was being used in
  103. computing completions, and you wish to return the completions with the
  104. original '~' instead of its expanded value.
  105. Parameters
  106. ----------
  107. path : str
  108. String to be expanded. If no ~ is present, the output is the same as the
  109. input.
  110. Returns
  111. -------
  112. newpath : str
  113. Result of ~ expansion in the input path.
  114. tilde_expand : bool
  115. Whether any expansion was performed or not.
  116. tilde_val : str
  117. The value that ~ was replaced with.
  118. """
  119. # Default values
  120. tilde_expand = False
  121. tilde_val = ''
  122. newpath = path
  123. if path.startswith('~'):
  124. tilde_expand = True
  125. rest = len(path)-1
  126. newpath = os.path.expanduser(path)
  127. if rest:
  128. tilde_val = newpath[:-rest]
  129. else:
  130. tilde_val = newpath
  131. return newpath, tilde_expand, tilde_val
  132. def compress_user(path, tilde_expand, tilde_val):
  133. """Does the opposite of expand_user, with its outputs.
  134. """
  135. if tilde_expand:
  136. return path.replace(tilde_val, '~')
  137. else:
  138. return path
  139. def completions_sorting_key(word):
  140. """key for sorting completions
  141. This does several things:
  142. - Lowercase all completions, so they are sorted alphabetically with
  143. upper and lower case words mingled
  144. - Demote any completions starting with underscores to the end
  145. - Insert any %magic and %%cellmagic completions in the alphabetical order
  146. by their name
  147. """
  148. # Case insensitive sort
  149. word = word.lower()
  150. prio1, prio2 = 0, 0
  151. if word.startswith('__'):
  152. prio1 = 2
  153. elif word.startswith('_'):
  154. prio1 = 1
  155. if word.endswith('='):
  156. prio1 = -1
  157. if word.startswith('%%'):
  158. # If there's another % in there, this is something else, so leave it alone
  159. if not "%" in word[2:]:
  160. word = word[2:]
  161. prio2 = 2
  162. elif word.startswith('%'):
  163. if not "%" in word[1:]:
  164. word = word[1:]
  165. prio2 = 1
  166. return prio1, word, prio2
  167. @undoc
  168. class Bunch(object): pass
  169. if sys.platform == 'win32':
  170. DELIMS = ' \t\n`!@#$^&*()=+[{]}|;\'",<>?'
  171. else:
  172. DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?'
  173. GREEDY_DELIMS = ' =\r\n'
  174. class CompletionSplitter(object):
  175. """An object to split an input line in a manner similar to readline.
  176. By having our own implementation, we can expose readline-like completion in
  177. a uniform manner to all frontends. This object only needs to be given the
  178. line of text to be split and the cursor position on said line, and it
  179. returns the 'word' to be completed on at the cursor after splitting the
  180. entire line.
  181. What characters are used as splitting delimiters can be controlled by
  182. setting the `delims` attribute (this is a property that internally
  183. automatically builds the necessary regular expression)"""
  184. # Private interface
  185. # A string of delimiter characters. The default value makes sense for
  186. # IPython's most typical usage patterns.
  187. _delims = DELIMS
  188. # The expression (a normal string) to be compiled into a regular expression
  189. # for actual splitting. We store it as an attribute mostly for ease of
  190. # debugging, since this type of code can be so tricky to debug.
  191. _delim_expr = None
  192. # The regular expression that does the actual splitting
  193. _delim_re = None
  194. def __init__(self, delims=None):
  195. delims = CompletionSplitter._delims if delims is None else delims
  196. self.delims = delims
  197. @property
  198. def delims(self):
  199. """Return the string of delimiter characters."""
  200. return self._delims
  201. @delims.setter
  202. def delims(self, delims):
  203. """Set the delimiters for line splitting."""
  204. expr = '[' + ''.join('\\'+ c for c in delims) + ']'
  205. self._delim_re = re.compile(expr)
  206. self._delims = delims
  207. self._delim_expr = expr
  208. def split_line(self, line, cursor_pos=None):
  209. """Split a line of text with a cursor at the given position.
  210. """
  211. l = line if cursor_pos is None else line[:cursor_pos]
  212. return self._delim_re.split(l)[-1]
  213. class Completer(Configurable):
  214. greedy = Bool(False,
  215. help="""Activate greedy completion
  216. PENDING DEPRECTION. this is now mostly taken care of with Jedi.
  217. This will enable completion on elements of lists, results of function calls, etc.,
  218. but can be unsafe because the code is actually evaluated on TAB.
  219. """
  220. ).tag(config=True)
  221. def __init__(self, namespace=None, global_namespace=None, **kwargs):
  222. """Create a new completer for the command line.
  223. Completer(namespace=ns, global_namespace=ns2) -> completer instance.
  224. If unspecified, the default namespace where completions are performed
  225. is __main__ (technically, __main__.__dict__). Namespaces should be
  226. given as dictionaries.
  227. An optional second namespace can be given. This allows the completer
  228. to handle cases where both the local and global scopes need to be
  229. distinguished.
  230. Completer instances should be used as the completion mechanism of
  231. readline via the set_completer() call:
  232. readline.set_completer(Completer(my_namespace).complete)
  233. """
  234. # Don't bind to namespace quite yet, but flag whether the user wants a
  235. # specific namespace or to use __main__.__dict__. This will allow us
  236. # to bind to __main__.__dict__ at completion time, not now.
  237. if namespace is None:
  238. self.use_main_ns = 1
  239. else:
  240. self.use_main_ns = 0
  241. self.namespace = namespace
  242. # The global namespace, if given, can be bound directly
  243. if global_namespace is None:
  244. self.global_namespace = {}
  245. else:
  246. self.global_namespace = global_namespace
  247. super(Completer, self).__init__(**kwargs)
  248. def complete(self, text, state):
  249. """Return the next possible completion for 'text'.
  250. This is called successively with state == 0, 1, 2, ... until it
  251. returns None. The completion should begin with 'text'.
  252. """
  253. if self.use_main_ns:
  254. self.namespace = __main__.__dict__
  255. if state == 0:
  256. if "." in text:
  257. self.matches = self.attr_matches(text)
  258. else:
  259. self.matches = self.global_matches(text)
  260. try:
  261. return self.matches[state]
  262. except IndexError:
  263. return None
  264. def global_matches(self, text):
  265. """Compute matches when text is a simple name.
  266. Return a list of all keywords, built-in functions and names currently
  267. defined in self.namespace or self.global_namespace that match.
  268. """
  269. matches = []
  270. match_append = matches.append
  271. n = len(text)
  272. for lst in [keyword.kwlist,
  273. builtin_mod.__dict__.keys(),
  274. self.namespace.keys(),
  275. self.global_namespace.keys()]:
  276. for word in lst:
  277. if word[:n] == text and word != "__builtins__":
  278. match_append(word)
  279. return [cast_unicode_py2(m) for m in matches]
  280. def attr_matches(self, text):
  281. """Compute matches when text contains a dot.
  282. Assuming the text is of the form NAME.NAME....[NAME], and is
  283. evaluatable in self.namespace or self.global_namespace, it will be
  284. evaluated and its attributes (as revealed by dir()) are used as
  285. possible completions. (For class instances, class members are are
  286. also considered.)
  287. WARNING: this can still invoke arbitrary C code, if an object
  288. with a __getattr__ hook is evaluated.
  289. """
  290. # Another option, seems to work great. Catches things like ''.<tab>
  291. m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text)
  292. if m:
  293. expr, attr = m.group(1, 3)
  294. elif self.greedy:
  295. m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer)
  296. if not m2:
  297. return []
  298. expr, attr = m2.group(1,2)
  299. else:
  300. return []
  301. try:
  302. obj = eval(expr, self.namespace)
  303. except:
  304. try:
  305. obj = eval(expr, self.global_namespace)
  306. except:
  307. return []
  308. if self.limit_to__all__ and hasattr(obj, '__all__'):
  309. words = get__all__entries(obj)
  310. else:
  311. words = dir2(obj)
  312. try:
  313. words = generics.complete_object(obj, words)
  314. except TryNext:
  315. pass
  316. except Exception:
  317. # Silence errors from completion function
  318. #raise # dbg
  319. pass
  320. # Build match list to return
  321. n = len(attr)
  322. return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ]
  323. def get__all__entries(obj):
  324. """returns the strings in the __all__ attribute"""
  325. try:
  326. words = getattr(obj, '__all__')
  327. except:
  328. return []
  329. return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)]
  330. def match_dict_keys(keys, prefix, delims):
  331. """Used by dict_key_matches, matching the prefix to a list of keys"""
  332. if not prefix:
  333. return None, 0, [repr(k) for k in keys
  334. if isinstance(k, (string_types, bytes))]
  335. quote_match = re.search('["\']', prefix)
  336. quote = quote_match.group()
  337. try:
  338. prefix_str = eval(prefix + quote, {})
  339. except Exception:
  340. return None, 0, []
  341. pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$'
  342. token_match = re.search(pattern, prefix, re.UNICODE)
  343. token_start = token_match.start()
  344. token_prefix = token_match.group()
  345. # TODO: support bytes in Py3k
  346. matched = []
  347. for key in keys:
  348. try:
  349. if not key.startswith(prefix_str):
  350. continue
  351. except (AttributeError, TypeError, UnicodeError):
  352. # Python 3+ TypeError on b'a'.startswith('a') or vice-versa
  353. continue
  354. # reformat remainder of key to begin with prefix
  355. rem = key[len(prefix_str):]
  356. # force repr wrapped in '
  357. rem_repr = repr(rem + '"')
  358. if rem_repr.startswith('u') and prefix[0] not in 'uU':
  359. # Found key is unicode, but prefix is Py2 string.
  360. # Therefore attempt to interpret key as string.
  361. try:
  362. rem_repr = repr(rem.encode('ascii') + '"')
  363. except UnicodeEncodeError:
  364. continue
  365. rem_repr = rem_repr[1 + rem_repr.index("'"):-2]
  366. if quote == '"':
  367. # The entered prefix is quoted with ",
  368. # but the match is quoted with '.
  369. # A contained " hence needs escaping for comparison:
  370. rem_repr = rem_repr.replace('"', '\\"')
  371. # then reinsert prefix from start of token
  372. matched.append('%s%s' % (token_prefix, rem_repr))
  373. return quote, token_start, matched
  374. def _safe_isinstance(obj, module, class_name):
  375. """Checks if obj is an instance of module.class_name if loaded
  376. """
  377. return (module in sys.modules and
  378. isinstance(obj, getattr(__import__(module), class_name)))
  379. def back_unicode_name_matches(text):
  380. u"""Match unicode characters back to unicode name
  381. This does ☃ -> \\snowman
  382. Note that snowman is not a valid python3 combining character but will be expanded.
  383. Though it will not recombine back to the snowman character by the completion machinery.
  384. This will not either back-complete standard sequences like \\n, \\b ...
  385. Used on Python 3 only.
  386. """
  387. if len(text)<2:
  388. return u'', ()
  389. maybe_slash = text[-2]
  390. if maybe_slash != '\\':
  391. return u'', ()
  392. char = text[-1]
  393. # no expand on quote for completion in strings.
  394. # nor backcomplete standard ascii keys
  395. if char in string.ascii_letters or char in ['"',"'"]:
  396. return u'', ()
  397. try :
  398. unic = unicodedata.name(char)
  399. return '\\'+char,['\\'+unic]
  400. except KeyError:
  401. pass
  402. return u'', ()
  403. def back_latex_name_matches(text):
  404. u"""Match latex characters back to unicode name
  405. This does ->\\sqrt
  406. Used on Python 3 only.
  407. """
  408. if len(text)<2:
  409. return u'', ()
  410. maybe_slash = text[-2]
  411. if maybe_slash != '\\':
  412. return u'', ()
  413. char = text[-1]
  414. # no expand on quote for completion in strings.
  415. # nor backcomplete standard ascii keys
  416. if char in string.ascii_letters or char in ['"',"'"]:
  417. return u'', ()
  418. try :
  419. latex = reverse_latex_symbol[char]
  420. # '\\' replace the \ as well
  421. return '\\'+char,[latex]
  422. except KeyError:
  423. pass
  424. return u'', ()
  425. class IPCompleter(Completer):
  426. """Extension of the completer class with IPython-specific features"""
  427. @observe('greedy')
  428. def _greedy_changed(self, change):
  429. """update the splitter and readline delims when greedy is changed"""
  430. if change['new']:
  431. self.splitter.delims = GREEDY_DELIMS
  432. else:
  433. self.splitter.delims = DELIMS
  434. if self.readline:
  435. self.readline.set_completer_delims(self.splitter.delims)
  436. merge_completions = Bool(True,
  437. help="""Whether to merge completion results into a single list
  438. If False, only the completion results from the first non-empty
  439. completer will be returned.
  440. """
  441. ).tag(config=True)
  442. omit__names = Enum((0,1,2), default_value=2,
  443. help="""Instruct the completer to omit private method names
  444. Specifically, when completing on ``object.<tab>``.
  445. When 2 [default]: all names that start with '_' will be excluded.
  446. When 1: all 'magic' names (``__foo__``) will be excluded.
  447. When 0: nothing will be excluded.
  448. """
  449. ).tag(config=True)
  450. limit_to__all__ = Bool(False,
  451. help="""
  452. DEPRECATED as of version 5.0.
  453. Instruct the completer to use __all__ for the completion
  454. Specifically, when completing on ``object.<tab>``.
  455. When True: only those names in obj.__all__ will be included.
  456. When False [default]: the __all__ attribute is ignored
  457. """,
  458. ).tag(config=True)
  459. def __init__(self, shell=None, namespace=None, global_namespace=None,
  460. use_readline=True, config=None, **kwargs):
  461. """IPCompleter() -> completer
  462. Return a completer object suitable for use by the readline library
  463. via readline.set_completer().
  464. Inputs:
  465. - shell: a pointer to the ipython shell itself. This is needed
  466. because this completer knows about magic functions, and those can
  467. only be accessed via the ipython instance.
  468. - namespace: an optional dict where completions are performed.
  469. - global_namespace: secondary optional dict for completions, to
  470. handle cases (such as IPython embedded inside functions) where
  471. both Python scopes are visible.
  472. use_readline : bool, optional
  473. If true, use the readline library. This completer can still function
  474. without readline, though in that case callers must provide some extra
  475. information on each call about the current line."""
  476. self.magic_escape = ESC_MAGIC
  477. self.splitter = CompletionSplitter()
  478. # Readline configuration, only used by the rlcompleter method.
  479. if use_readline:
  480. # We store the right version of readline so that later code
  481. import IPython.utils.rlineimpl as readline
  482. self.readline = readline
  483. else:
  484. self.readline = None
  485. # _greedy_changed() depends on splitter and readline being defined:
  486. Completer.__init__(self, namespace=namespace, global_namespace=global_namespace,
  487. config=config, **kwargs)
  488. # List where completion matches will be stored
  489. self.matches = []
  490. self.shell = shell
  491. # Regexp to split filenames with spaces in them
  492. self.space_name_re = re.compile(r'([^\\] )')
  493. # Hold a local ref. to glob.glob for speed
  494. self.glob = glob.glob
  495. # Determine if we are running on 'dumb' terminals, like (X)Emacs
  496. # buffers, to avoid completion problems.
  497. term = os.environ.get('TERM','xterm')
  498. self.dumb_terminal = term in ['dumb','emacs']
  499. # Special handling of backslashes needed in win32 platforms
  500. if sys.platform == "win32":
  501. self.clean_glob = self._clean_glob_win32
  502. else:
  503. self.clean_glob = self._clean_glob
  504. #regexp to parse docstring for function signature
  505. self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
  506. self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
  507. #use this if positional argument name is also needed
  508. #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)')
  509. # All active matcher routines for completion
  510. self.matchers = [
  511. self.python_matches,
  512. self.file_matches,
  513. self.magic_matches,
  514. self.python_func_kw_matches,
  515. self.dict_key_matches,
  516. ]
  517. # This is set externally by InteractiveShell
  518. self.custom_completers = None
  519. def all_completions(self, text):
  520. """
  521. Wrapper around the complete method for the benefit of emacs.
  522. """
  523. return self.complete(text)[1]
  524. def _clean_glob(self, text):
  525. return self.glob("%s*" % text)
  526. def _clean_glob_win32(self,text):
  527. return [f.replace("\\","/")
  528. for f in self.glob("%s*" % text)]
  529. def file_matches(self, text):
  530. """Match filenames, expanding ~USER type strings.
  531. Most of the seemingly convoluted logic in this completer is an
  532. attempt to handle filenames with spaces in them. And yet it's not
  533. quite perfect, because Python's readline doesn't expose all of the
  534. GNU readline details needed for this to be done correctly.
  535. For a filename with a space in it, the printed completions will be
  536. only the parts after what's already been typed (instead of the
  537. full completions, as is normally done). I don't think with the
  538. current (as of Python 2.3) Python readline it's possible to do
  539. better."""
  540. # chars that require escaping with backslash - i.e. chars
  541. # that readline treats incorrectly as delimiters, but we
  542. # don't want to treat as delimiters in filename matching
  543. # when escaped with backslash
  544. if text.startswith('!'):
  545. text = text[1:]
  546. text_prefix = u'!'
  547. else:
  548. text_prefix = u''
  549. text_until_cursor = self.text_until_cursor
  550. # track strings with open quotes
  551. open_quotes = has_open_quotes(text_until_cursor)
  552. if '(' in text_until_cursor or '[' in text_until_cursor:
  553. lsplit = text
  554. else:
  555. try:
  556. # arg_split ~ shlex.split, but with unicode bugs fixed by us
  557. lsplit = arg_split(text_until_cursor)[-1]
  558. except ValueError:
  559. # typically an unmatched ", or backslash without escaped char.
  560. if open_quotes:
  561. lsplit = text_until_cursor.split(open_quotes)[-1]
  562. else:
  563. return []
  564. except IndexError:
  565. # tab pressed on empty line
  566. lsplit = ""
  567. if not open_quotes and lsplit != protect_filename(lsplit):
  568. # if protectables are found, do matching on the whole escaped name
  569. has_protectables = True
  570. text0,text = text,lsplit
  571. else:
  572. has_protectables = False
  573. text = os.path.expanduser(text)
  574. if text == "":
  575. return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")]
  576. # Compute the matches from the filesystem
  577. if sys.platform == 'win32':
  578. m0 = self.clean_glob(text)
  579. else:
  580. m0 = self.clean_glob(text.replace('\\', ''))
  581. if has_protectables:
  582. # If we had protectables, we need to revert our changes to the
  583. # beginning of filename so that we don't double-write the part
  584. # of the filename we have so far
  585. len_lsplit = len(lsplit)
  586. matches = [text_prefix + text0 +
  587. protect_filename(f[len_lsplit:]) for f in m0]
  588. else:
  589. if open_quotes:
  590. # if we have a string with an open quote, we don't need to
  591. # protect the names at all (and we _shouldn't_, as it
  592. # would cause bugs when the filesystem call is made).
  593. matches = m0
  594. else:
  595. matches = [text_prefix +
  596. protect_filename(f) for f in m0]
  597. # Mark directories in input list by appending '/' to their names.
  598. return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches]
  599. def magic_matches(self, text):
  600. """Match magics"""
  601. # Get all shell magics now rather than statically, so magics loaded at
  602. # runtime show up too.
  603. lsm = self.shell.magics_manager.lsmagic()
  604. line_magics = lsm['line']
  605. cell_magics = lsm['cell']
  606. pre = self.magic_escape
  607. pre2 = pre+pre
  608. # Completion logic:
  609. # - user gives %%: only do cell magics
  610. # - user gives %: do both line and cell magics
  611. # - no prefix: do both
  612. # In other words, line magics are skipped if the user gives %% explicitly
  613. bare_text = text.lstrip(pre)
  614. comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)]
  615. if not text.startswith(pre2):
  616. comp += [ pre+m for m in line_magics if m.startswith(bare_text)]
  617. return [cast_unicode_py2(c) for c in comp]
  618. def python_matches(self, text):
  619. """Match attributes or global python names"""
  620. if "." in text:
  621. try:
  622. matches = self.attr_matches(text)
  623. if text.endswith('.') and self.omit__names:
  624. if self.omit__names == 1:
  625. # true if txt is _not_ a __ name, false otherwise:
  626. no__name = (lambda txt:
  627. re.match(r'.*\.__.*?__',txt) is None)
  628. else:
  629. # true if txt is _not_ a _ name, false otherwise:
  630. no__name = (lambda txt:
  631. re.match(r'\._.*?',txt[txt.rindex('.'):]) is None)
  632. matches = filter(no__name, matches)
  633. except NameError:
  634. # catches <undefined attributes>.<tab>
  635. matches = []
  636. else:
  637. matches = self.global_matches(text)
  638. return matches
  639. def _default_arguments_from_docstring(self, doc):
  640. """Parse the first line of docstring for call signature.
  641. Docstring should be of the form 'min(iterable[, key=func])\n'.
  642. It can also parse cython docstring of the form
  643. 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'.
  644. """
  645. if doc is None:
  646. return []
  647. #care only the firstline
  648. line = doc.lstrip().splitlines()[0]
  649. #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*')
  650. #'min(iterable[, key=func])\n' -> 'iterable[, key=func]'
  651. sig = self.docstring_sig_re.search(line)
  652. if sig is None:
  653. return []
  654. # iterable[, key=func]' -> ['iterable[' ,' key=func]']
  655. sig = sig.groups()[0].split(',')
  656. ret = []
  657. for s in sig:
  658. #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)')
  659. ret += self.docstring_kwd_re.findall(s)
  660. return ret
  661. def _default_arguments(self, obj):
  662. """Return the list of default arguments of obj if it is callable,
  663. or empty list otherwise."""
  664. call_obj = obj
  665. ret = []
  666. if inspect.isbuiltin(obj):
  667. pass
  668. elif not (inspect.isfunction(obj) or inspect.ismethod(obj)):
  669. if inspect.isclass(obj):
  670. #for cython embededsignature=True the constructor docstring
  671. #belongs to the object itself not __init__
  672. ret += self._default_arguments_from_docstring(
  673. getattr(obj, '__doc__', ''))
  674. # for classes, check for __init__,__new__
  675. call_obj = (getattr(obj, '__init__', None) or
  676. getattr(obj, '__new__', None))
  677. # for all others, check if they are __call__able
  678. elif hasattr(obj, '__call__'):
  679. call_obj = obj.__call__
  680. ret += self._default_arguments_from_docstring(
  681. getattr(call_obj, '__doc__', ''))
  682. if PY3:
  683. _keeps = (inspect.Parameter.KEYWORD_ONLY,
  684. inspect.Parameter.POSITIONAL_OR_KEYWORD)
  685. signature = inspect.signature
  686. else:
  687. import IPython.utils.signatures
  688. _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY,
  689. IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD)
  690. signature = IPython.utils.signatures.signature
  691. try:
  692. sig = signature(call_obj)
  693. ret.extend(k for k, v in sig.parameters.items() if
  694. v.kind in _keeps)
  695. except ValueError:
  696. pass
  697. return list(set(ret))
  698. def python_func_kw_matches(self,text):
  699. """Match named parameters (kwargs) of the last open function"""
  700. if "." in text: # a parameter cannot be dotted
  701. return []
  702. try: regexp = self.__funcParamsRegex
  703. except AttributeError:
  704. regexp = self.__funcParamsRegex = re.compile(r'''
  705. '.*?(?<!\\)' | # single quoted strings or
  706. ".*?(?<!\\)" | # double quoted strings or
  707. \w+ | # identifier
  708. \S # other characters
  709. ''', re.VERBOSE | re.DOTALL)
  710. # 1. find the nearest identifier that comes before an unclosed
  711. # parenthesis before the cursor
  712. # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo"
  713. tokens = regexp.findall(self.text_until_cursor)
  714. tokens.reverse()
  715. iterTokens = iter(tokens); openPar = 0
  716. for token in iterTokens:
  717. if token == ')':
  718. openPar -= 1
  719. elif token == '(':
  720. openPar += 1
  721. if openPar > 0:
  722. # found the last unclosed parenthesis
  723. break
  724. else:
  725. return []
  726. # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" )
  727. ids = []
  728. isId = re.compile(r'\w+$').match
  729. while True:
  730. try:
  731. ids.append(next(iterTokens))
  732. if not isId(ids[-1]):
  733. ids.pop(); break
  734. if not next(iterTokens) == '.':
  735. break
  736. except StopIteration:
  737. break
  738. # lookup the candidate callable matches either using global_matches
  739. # or attr_matches for dotted names
  740. if len(ids) == 1:
  741. callableMatches = self.global_matches(ids[0])
  742. else:
  743. callableMatches = self.attr_matches('.'.join(ids[::-1]))
  744. argMatches = []
  745. for callableMatch in callableMatches:
  746. try:
  747. namedArgs = self._default_arguments(eval(callableMatch,
  748. self.namespace))
  749. except:
  750. continue
  751. for namedArg in namedArgs:
  752. if namedArg.startswith(text):
  753. argMatches.append(u"%s=" %namedArg)
  754. return argMatches
  755. def dict_key_matches(self, text):
  756. "Match string keys in a dictionary, after e.g. 'foo[' "
  757. def get_keys(obj):
  758. # Objects can define their own completions by defining an
  759. # _ipy_key_completions_() method.
  760. method = get_real_method(obj, '_ipython_key_completions_')
  761. if method is not None:
  762. return method()
  763. # Special case some common in-memory dict-like types
  764. if isinstance(obj, dict) or\
  765. _safe_isinstance(obj, 'pandas', 'DataFrame'):
  766. try:
  767. return list(obj.keys())
  768. except Exception:
  769. return []
  770. elif _safe_isinstance(obj, 'numpy', 'ndarray') or\
  771. _safe_isinstance(obj, 'numpy', 'void'):
  772. return obj.dtype.names or []
  773. return []
  774. try:
  775. regexps = self.__dict_key_regexps
  776. except AttributeError:
  777. dict_key_re_fmt = r'''(?x)
  778. ( # match dict-referring expression wrt greedy setting
  779. %s
  780. )
  781. \[ # open bracket
  782. \s* # and optional whitespace
  783. ([uUbB]? # string prefix (r not handled)
  784. (?: # unclosed string
  785. '(?:[^']|(?<!\\)\\')*
  786. |
  787. "(?:[^"]|(?<!\\)\\")*
  788. )
  789. )?
  790. $
  791. '''
  792. regexps = self.__dict_key_regexps = {
  793. False: re.compile(dict_key_re_fmt % '''
  794. # identifiers separated by .
  795. (?!\d)\w+
  796. (?:\.(?!\d)\w+)*
  797. '''),
  798. True: re.compile(dict_key_re_fmt % '''
  799. .+
  800. ''')
  801. }
  802. match = regexps[self.greedy].search(self.text_until_cursor)
  803. if match is None:
  804. return []
  805. expr, prefix = match.groups()
  806. try:
  807. obj = eval(expr, self.namespace)
  808. except Exception:
  809. try:
  810. obj = eval(expr, self.global_namespace)
  811. except Exception:
  812. return []
  813. keys = get_keys(obj)
  814. if not keys:
  815. return keys
  816. closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims)
  817. if not matches:
  818. return matches
  819. # get the cursor position of
  820. # - the text being completed
  821. # - the start of the key text
  822. # - the start of the completion
  823. text_start = len(self.text_until_cursor) - len(text)
  824. if prefix:
  825. key_start = match.start(2)
  826. completion_start = key_start + token_offset
  827. else:
  828. key_start = completion_start = match.end()
  829. # grab the leading prefix, to make sure all completions start with `text`
  830. if text_start > key_start:
  831. leading = ''
  832. else:
  833. leading = text[text_start:completion_start]
  834. # the index of the `[` character
  835. bracket_idx = match.end(1)
  836. # append closing quote and bracket as appropriate
  837. # this is *not* appropriate if the opening quote or bracket is outside
  838. # the text given to this method
  839. suf = ''
  840. continuation = self.line_buffer[len(self.text_until_cursor):]
  841. if key_start > text_start and closing_quote:
  842. # quotes were opened inside text, maybe close them
  843. if continuation.startswith(closing_quote):
  844. continuation = continuation[len(closing_quote):]
  845. else:
  846. suf += closing_quote
  847. if bracket_idx > text_start:
  848. # brackets were opened inside text, maybe close them
  849. if not continuation.startswith(']'):
  850. suf += ']'
  851. return [leading + k + suf for k in matches]
  852. def unicode_name_matches(self, text):
  853. u"""Match Latex-like syntax for unicode characters base
  854. on the name of the character.
  855. This does \\GREEK SMALL LETTER ETA -> η
  856. Works only on valid python 3 identifier, or on combining characters that
  857. will combine to form a valid identifier.
  858. Used on Python 3 only.
  859. """
  860. slashpos = text.rfind('\\')
  861. if slashpos > -1:
  862. s = text[slashpos+1:]
  863. try :
  864. unic = unicodedata.lookup(s)
  865. # allow combining chars
  866. if ('a'+unic).isidentifier():
  867. return '\\'+s,[unic]
  868. except KeyError:
  869. pass
  870. return u'', []
  871. def latex_matches(self, text):
  872. u"""Match Latex syntax for unicode characters.
  873. This does both \\alp -> \\alpha and \\alpha -> α
  874. Used on Python 3 only.
  875. """
  876. slashpos = text.rfind('\\')
  877. if slashpos > -1:
  878. s = text[slashpos:]
  879. if s in latex_symbols:
  880. # Try to complete a full latex symbol to unicode
  881. # \\alpha -> α
  882. return s, [latex_symbols[s]]
  883. else:
  884. # If a user has partially typed a latex symbol, give them
  885. # a full list of options \al -> [\aleph, \alpha]
  886. matches = [k for k in latex_symbols if k.startswith(s)]
  887. return s, matches
  888. return u'', []
  889. def dispatch_custom_completer(self, text):
  890. if not self.custom_completers:
  891. return
  892. line = self.line_buffer
  893. if not line.strip():
  894. return None
  895. # Create a little structure to pass all the relevant information about
  896. # the current completion to any custom completer.
  897. event = Bunch()
  898. event.line = line
  899. event.symbol = text
  900. cmd = line.split(None,1)[0]
  901. event.command = cmd
  902. event.text_until_cursor = self.text_until_cursor
  903. # for foo etc, try also to find completer for %foo
  904. if not cmd.startswith(self.magic_escape):
  905. try_magic = self.custom_completers.s_matches(
  906. self.magic_escape + cmd)
  907. else:
  908. try_magic = []
  909. for c in itertools.chain(self.custom_completers.s_matches(cmd),
  910. try_magic,
  911. self.custom_completers.flat_matches(self.text_until_cursor)):
  912. try:
  913. res = c(event)
  914. if res:
  915. # first, try case sensitive match
  916. withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)]
  917. if withcase:
  918. return withcase
  919. # if none, then case insensitive ones are ok too
  920. text_low = text.lower()
  921. return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)]
  922. except TryNext:
  923. pass
  924. return None
  925. @_strip_single_trailing_space
  926. def complete(self, text=None, line_buffer=None, cursor_pos=None):
  927. """Find completions for the given text and line context.
  928. Note that both the text and the line_buffer are optional, but at least
  929. one of them must be given.
  930. Parameters
  931. ----------
  932. text : string, optional
  933. Text to perform the completion on. If not given, the line buffer
  934. is split using the instance's CompletionSplitter object.
  935. line_buffer : string, optional
  936. If not given, the completer attempts to obtain the current line
  937. buffer via readline. This keyword allows clients which are
  938. requesting for text completions in non-readline contexts to inform
  939. the completer of the entire text.
  940. cursor_pos : int, optional
  941. Index of the cursor in the full line buffer. Should be provided by
  942. remote frontends where kernel has no access to frontend state.
  943. Returns
  944. -------
  945. text : str
  946. Text that was actually used in the completion.
  947. matches : list
  948. A list of completion matches.
  949. """
  950. # if the cursor position isn't given, the only sane assumption we can
  951. # make is that it's at the end of the line (the common case)
  952. if cursor_pos is None:
  953. cursor_pos = len(line_buffer) if text is None else len(text)
  954. if PY3:
  955. base_text = text if not line_buffer else line_buffer[:cursor_pos]
  956. latex_text, latex_matches = self.latex_matches(base_text)
  957. if latex_matches:
  958. return latex_text, latex_matches
  959. name_text = ''
  960. name_matches = []
  961. for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches):
  962. name_text, name_matches = meth(base_text)
  963. if name_text:
  964. return name_text, name_matches
  965. # if text is either None or an empty string, rely on the line buffer
  966. if not text:
  967. text = self.splitter.split_line(line_buffer, cursor_pos)
  968. # If no line buffer is given, assume the input text is all there was
  969. if line_buffer is None:
  970. line_buffer = text
  971. self.line_buffer = line_buffer
  972. self.text_until_cursor = self.line_buffer[:cursor_pos]
  973. # Start with a clean slate of completions
  974. self.matches[:] = []
  975. custom_res = self.dispatch_custom_completer(text)
  976. if custom_res is not None:
  977. # did custom completers produce something?
  978. self.matches = custom_res
  979. else:
  980. # Extend the list of completions with the results of each
  981. # matcher, so we return results to the user from all
  982. # namespaces.
  983. if self.merge_completions:
  984. self.matches = []
  985. for matcher in self.matchers:
  986. try:
  987. self.matches.extend(matcher(text))
  988. except:
  989. # Show the ugly traceback if the matcher causes an
  990. # exception, but do NOT crash the kernel!
  991. sys.excepthook(*sys.exc_info())
  992. else:
  993. for matcher in self.matchers:
  994. self.matches = matcher(text)
  995. if self.matches:
  996. break
  997. # FIXME: we should extend our api to return a dict with completions for
  998. # different types of objects. The rlcomplete() method could then
  999. # simply collapse the dict into a list for readline, but we'd have
  1000. # richer completion semantics in other evironments.
  1001. self.matches = sorted(set(self.matches), key=completions_sorting_key)
  1002. return text, self.matches