completer.py 41 KB

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