completerlib.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. # encoding: utf-8
  2. """Implementations for various useful completers.
  3. These are all loaded by default by IPython.
  4. """
  5. #-----------------------------------------------------------------------------
  6. # Copyright (C) 2010-2011 The IPython Development Team.
  7. #
  8. # Distributed under the terms of the BSD License.
  9. #
  10. # The full license is in the file COPYING.txt, distributed with this software.
  11. #-----------------------------------------------------------------------------
  12. #-----------------------------------------------------------------------------
  13. # Imports
  14. #-----------------------------------------------------------------------------
  15. # Stdlib imports
  16. import glob
  17. import inspect
  18. import itertools
  19. import os
  20. import re
  21. import sys
  22. from importlib import import_module
  23. from importlib.machinery import all_suffixes
  24. # Third-party imports
  25. from time import time
  26. from zipimport import zipimporter
  27. # Our own imports
  28. from .completer import expand_user, compress_user
  29. from .error import TryNext
  30. from ..utils._process_common import arg_split
  31. # FIXME: this should be pulled in with the right call via the component system
  32. from IPython import get_ipython
  33. from typing import List
  34. from __res import importer
  35. #-----------------------------------------------------------------------------
  36. # Globals and constants
  37. #-----------------------------------------------------------------------------
  38. _suffixes = all_suffixes()
  39. # Time in seconds after which the rootmodules will be stored permanently in the
  40. # ipython ip.db database (kept in the user's .ipython dir).
  41. TIMEOUT_STORAGE = 2
  42. # Time in seconds after which we give up
  43. TIMEOUT_GIVEUP = 20
  44. # Regular expression for the python import statement
  45. import_re = re.compile(r'(?P<name>[^\W\d]\w*?)'
  46. r'(?P<package>[/\\]__init__)?'
  47. r'(?P<suffix>%s)$' %
  48. r'|'.join(re.escape(s) for s in _suffixes))
  49. # RE for the ipython %run command (python + ipython scripts)
  50. magic_run_re = re.compile(r'.*(\.ipy|\.ipynb|\.py[w]?)$')
  51. #-----------------------------------------------------------------------------
  52. # Local utilities
  53. #-----------------------------------------------------------------------------
  54. arcadia_rootmodules_cache = None
  55. arcadia_modules_cache = None
  56. def arcadia_init_cache():
  57. global arcadia_rootmodules_cache, arcadia_modules_cache
  58. arcadia_rootmodules_cache = set()
  59. arcadia_modules_cache = {}
  60. all_modules = itertools.chain(
  61. sys.builtin_module_names,
  62. importer.memory
  63. )
  64. for name in all_modules:
  65. path = name.split('.')
  66. arcadia_rootmodules_cache.add(path[0])
  67. prefix = path[0]
  68. for element in path[1:]:
  69. if element == '__init__':
  70. continue
  71. arcadia_modules_cache.setdefault(prefix, set()).add(element)
  72. prefix += '.' + element
  73. arcadia_rootmodules_cache = sorted(arcadia_rootmodules_cache)
  74. arcadia_modules_cache = {k: sorted(v) for k, v in arcadia_modules_cache.items()}
  75. def arcadia_module_list(mod):
  76. if arcadia_modules_cache is None:
  77. arcadia_init_cache()
  78. return arcadia_modules_cache.get(mod, ())
  79. def arcadia_get_root_modules():
  80. if arcadia_rootmodules_cache is None:
  81. arcadia_init_cache()
  82. return arcadia_rootmodules_cache
  83. def module_list(path: str) -> List[str]:
  84. """
  85. Return the list containing the names of the modules available in the given
  86. folder.
  87. """
  88. # sys.path has the cwd as an empty string, but isdir/listdir need it as '.'
  89. if path == '':
  90. path = '.'
  91. # A few local constants to be used in loops below
  92. pjoin = os.path.join
  93. if os.path.isdir(path):
  94. # Build a list of all files in the directory and all files
  95. # in its subdirectories. For performance reasons, do not
  96. # recurse more than one level into subdirectories.
  97. files: List[str] = []
  98. for root, dirs, nondirs in os.walk(path, followlinks=True):
  99. subdir = root[len(path)+1:]
  100. if subdir:
  101. files.extend(pjoin(subdir, f) for f in nondirs)
  102. dirs[:] = [] # Do not recurse into additional subdirectories.
  103. else:
  104. files.extend(nondirs)
  105. else:
  106. try:
  107. files = list(zipimporter(path)._files.keys()) # type: ignore
  108. except Exception:
  109. files = []
  110. # Build a list of modules which match the import_re regex.
  111. modules = []
  112. for f in files:
  113. m = import_re.match(f)
  114. if m:
  115. modules.append(m.group('name'))
  116. return list(set(modules))
  117. def get_root_modules():
  118. """
  119. Returns a list containing the names of all the modules available in the
  120. folders of the pythonpath.
  121. ip.db['rootmodules_cache'] maps sys.path entries to list of modules.
  122. """
  123. ip = get_ipython()
  124. if ip is None:
  125. # No global shell instance to store cached list of modules.
  126. # Don't try to scan for modules every time.
  127. return list(sys.builtin_module_names)
  128. if getattr(ip.db, "_mock", False):
  129. rootmodules_cache = {}
  130. else:
  131. rootmodules_cache = ip.db.get("rootmodules_cache", {})
  132. rootmodules = list(sys.builtin_module_names)
  133. start_time = time()
  134. store = False
  135. for path in sys.path:
  136. try:
  137. modules = rootmodules_cache[path]
  138. except KeyError:
  139. modules = module_list(path)
  140. try:
  141. modules.remove('__init__')
  142. except ValueError:
  143. pass
  144. if path not in ('', '.'): # cwd modules should not be cached
  145. rootmodules_cache[path] = modules
  146. if time() - start_time > TIMEOUT_STORAGE and not store:
  147. store = True
  148. print("\nCaching the list of root modules, please wait!")
  149. print("(This will only be done once - type '%rehashx' to "
  150. "reset cache!)\n")
  151. sys.stdout.flush()
  152. if time() - start_time > TIMEOUT_GIVEUP:
  153. print("This is taking too long, we give up.\n")
  154. return []
  155. rootmodules.extend(modules)
  156. if store:
  157. ip.db['rootmodules_cache'] = rootmodules_cache
  158. rootmodules = list(set(rootmodules))
  159. return rootmodules
  160. def is_importable(module, attr: str, only_modules) -> bool:
  161. if only_modules:
  162. try:
  163. mod = getattr(module, attr)
  164. except ModuleNotFoundError:
  165. # See gh-14434
  166. return False
  167. return inspect.ismodule(mod)
  168. else:
  169. return not(attr[:2] == '__' and attr[-2:] == '__')
  170. def is_possible_submodule(module, attr):
  171. try:
  172. obj = getattr(module, attr)
  173. except AttributeError:
  174. # Is possibly an unimported submodule
  175. return True
  176. except TypeError:
  177. # https://github.com/ipython/ipython/issues/9678
  178. return False
  179. return inspect.ismodule(obj)
  180. def try_import(mod: str, only_modules=False) -> List[str]:
  181. """
  182. Try to import given module and return list of potential completions.
  183. """
  184. mod = mod.rstrip('.')
  185. try:
  186. m = import_module(mod)
  187. except:
  188. return []
  189. filename = getattr(m, '__file__', '')
  190. m_is_init = '__init__' in (filename or '') or filename == mod
  191. completions = []
  192. if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
  193. completions.extend( [attr for attr in dir(m) if
  194. is_importable(m, attr, only_modules)])
  195. m_all = getattr(m, "__all__", [])
  196. if only_modules:
  197. completions.extend(attr for attr in m_all if is_possible_submodule(m, attr))
  198. else:
  199. completions.extend(m_all)
  200. if m_is_init:
  201. file_ = m.__file__
  202. file_path = os.path.dirname(file_) # type: ignore
  203. if file_path is not None:
  204. completions.extend(module_list(file_path))
  205. completions.extend(arcadia_module_list(mod))
  206. completions_set = {c for c in completions if isinstance(c, str)}
  207. completions_set.discard('__init__')
  208. return sorted(completions_set)
  209. #-----------------------------------------------------------------------------
  210. # Completion-related functions.
  211. #-----------------------------------------------------------------------------
  212. def quick_completer(cmd, completions):
  213. r""" Easily create a trivial completer for a command.
  214. Takes either a list of completions, or all completions in string (that will
  215. be split on whitespace).
  216. Example::
  217. [d:\ipython]|1> import ipy_completers
  218. [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
  219. [d:\ipython]|3> foo b<TAB>
  220. bar baz
  221. [d:\ipython]|3> foo ba
  222. """
  223. if isinstance(completions, str):
  224. completions = completions.split()
  225. def do_complete(self, event):
  226. return completions
  227. get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
  228. def module_completion(line):
  229. """
  230. Returns a list containing the completion possibilities for an import line.
  231. The line looks like this :
  232. 'import xml.d'
  233. 'from xml.dom import'
  234. """
  235. words = line.split(' ')
  236. nwords = len(words)
  237. # from whatever <tab> -> 'import '
  238. if nwords == 3 and words[0] == 'from':
  239. return ['import ']
  240. # 'from xy<tab>' or 'import xy<tab>'
  241. if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
  242. if nwords == 1:
  243. return arcadia_get_root_modules()
  244. mod = words[1].split('.')
  245. if len(mod) < 2:
  246. return arcadia_get_root_modules()
  247. completion_list = try_import('.'.join(mod[:-1]), True)
  248. return ['.'.join(mod[:-1] + [el]) for el in completion_list]
  249. # 'from xyz import abc<tab>'
  250. if nwords >= 3 and words[0] == 'from':
  251. mod = words[1]
  252. return try_import(mod)
  253. #-----------------------------------------------------------------------------
  254. # Completers
  255. #-----------------------------------------------------------------------------
  256. # These all have the func(self, event) signature to be used as custom
  257. # completers
  258. def module_completer(self,event):
  259. """Give completions after user has typed 'import ...' or 'from ...'"""
  260. # This works in all versions of python. While 2.5 has
  261. # pkgutil.walk_packages(), that particular routine is fairly dangerous,
  262. # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
  263. # of possibly problematic side effects.
  264. # This search the folders in the sys.path for available modules.
  265. return module_completion(event.line)
  266. # FIXME: there's a lot of logic common to the run, cd and builtin file
  267. # completers, that is currently reimplemented in each.
  268. def magic_run_completer(self, event):
  269. """Complete files that end in .py or .ipy or .ipynb for the %run command.
  270. """
  271. comps = arg_split(event.line, strict=False)
  272. # relpath should be the current token that we need to complete.
  273. if (len(comps) > 1) and (not event.line.endswith(' ')):
  274. relpath = comps[-1].strip("'\"")
  275. else:
  276. relpath = ''
  277. #print("\nev=", event) # dbg
  278. #print("rp=", relpath) # dbg
  279. #print('comps=', comps) # dbg
  280. lglob = glob.glob
  281. isdir = os.path.isdir
  282. relpath, tilde_expand, tilde_val = expand_user(relpath)
  283. # Find if the user has already typed the first filename, after which we
  284. # should complete on all files, since after the first one other files may
  285. # be arguments to the input script.
  286. if any(magic_run_re.match(c) for c in comps):
  287. matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
  288. for f in lglob(relpath+'*')]
  289. else:
  290. dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
  291. pys = [f.replace('\\','/')
  292. for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
  293. lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
  294. matches = dirs + pys
  295. #print('run comp:', dirs+pys) # dbg
  296. return [compress_user(p, tilde_expand, tilde_val) for p in matches]
  297. def cd_completer(self, event):
  298. """Completer function for cd, which only returns directories."""
  299. ip = get_ipython()
  300. relpath = event.symbol
  301. #print(event) # dbg
  302. if event.line.endswith('-b') or ' -b ' in event.line:
  303. # return only bookmark completions
  304. bkms = self.db.get('bookmarks', None)
  305. if bkms:
  306. return bkms.keys()
  307. else:
  308. return []
  309. if event.symbol == '-':
  310. width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
  311. # jump in directory history by number
  312. fmt = '-%0' + width_dh +'d [%s]'
  313. ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
  314. if len(ents) > 1:
  315. return ents
  316. return []
  317. if event.symbol.startswith('--'):
  318. return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
  319. # Expand ~ in path and normalize directory separators.
  320. relpath, tilde_expand, tilde_val = expand_user(relpath)
  321. relpath = relpath.replace('\\','/')
  322. found = []
  323. for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
  324. if os.path.isdir(f)]:
  325. if ' ' in d:
  326. # we don't want to deal with any of that, complex code
  327. # for this is elsewhere
  328. raise TryNext
  329. found.append(d)
  330. if not found:
  331. if os.path.isdir(relpath):
  332. return [compress_user(relpath, tilde_expand, tilde_val)]
  333. # if no completions so far, try bookmarks
  334. bks = self.db.get('bookmarks',{})
  335. bkmatches = [s for s in bks if s.startswith(event.symbol)]
  336. if bkmatches:
  337. return bkmatches
  338. raise TryNext
  339. return [compress_user(p, tilde_expand, tilde_val) for p in found]
  340. def reset_completer(self, event):
  341. "A completer for %reset magic"
  342. return '-f -s in out array dhist'.split()