completerlib.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  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, only_modules):
  161. if only_modules:
  162. return inspect.ismodule(getattr(module, attr))
  163. else:
  164. return not(attr[:2] == '__' and attr[-2:] == '__')
  165. def is_possible_submodule(module, attr):
  166. try:
  167. obj = getattr(module, attr)
  168. except AttributeError:
  169. # Is possilby an unimported submodule
  170. return True
  171. except TypeError:
  172. # https://github.com/ipython/ipython/issues/9678
  173. return False
  174. return inspect.ismodule(obj)
  175. def try_import(mod: str, only_modules=False) -> List[str]:
  176. """
  177. Try to import given module and return list of potential completions.
  178. """
  179. mod = mod.rstrip('.')
  180. try:
  181. m = import_module(mod)
  182. except:
  183. return []
  184. filename = getattr(m, '__file__', '')
  185. m_is_init = '__init__' in (filename or '') or filename == mod
  186. completions = []
  187. if (not hasattr(m, '__file__')) or (not only_modules) or m_is_init:
  188. completions.extend( [attr for attr in dir(m) if
  189. is_importable(m, attr, only_modules)])
  190. m_all = getattr(m, "__all__", [])
  191. if only_modules:
  192. completions.extend(attr for attr in m_all if is_possible_submodule(m, attr))
  193. else:
  194. completions.extend(m_all)
  195. if m_is_init:
  196. file_ = m.__file__
  197. file_path = os.path.dirname(file_) # type: ignore
  198. if file_path is not None:
  199. completions.extend(module_list(file_path))
  200. completions.extend(arcadia_module_list(mod))
  201. completions_set = {c for c in completions if isinstance(c, str)}
  202. completions_set.discard('__init__')
  203. return sorted(completions_set)
  204. #-----------------------------------------------------------------------------
  205. # Completion-related functions.
  206. #-----------------------------------------------------------------------------
  207. def quick_completer(cmd, completions):
  208. r""" Easily create a trivial completer for a command.
  209. Takes either a list of completions, or all completions in string (that will
  210. be split on whitespace).
  211. Example::
  212. [d:\ipython]|1> import ipy_completers
  213. [d:\ipython]|2> ipy_completers.quick_completer('foo', ['bar','baz'])
  214. [d:\ipython]|3> foo b<TAB>
  215. bar baz
  216. [d:\ipython]|3> foo ba
  217. """
  218. if isinstance(completions, str):
  219. completions = completions.split()
  220. def do_complete(self, event):
  221. return completions
  222. get_ipython().set_hook('complete_command',do_complete, str_key = cmd)
  223. def module_completion(line):
  224. """
  225. Returns a list containing the completion possibilities for an import line.
  226. The line looks like this :
  227. 'import xml.d'
  228. 'from xml.dom import'
  229. """
  230. words = line.split(' ')
  231. nwords = len(words)
  232. # from whatever <tab> -> 'import '
  233. if nwords == 3 and words[0] == 'from':
  234. return ['import ']
  235. # 'from xy<tab>' or 'import xy<tab>'
  236. if nwords < 3 and (words[0] in {'%aimport', 'import', 'from'}) :
  237. if nwords == 1:
  238. return arcadia_get_root_modules()
  239. mod = words[1].split('.')
  240. if len(mod) < 2:
  241. return arcadia_get_root_modules()
  242. completion_list = try_import('.'.join(mod[:-1]), True)
  243. return ['.'.join(mod[:-1] + [el]) for el in completion_list]
  244. # 'from xyz import abc<tab>'
  245. if nwords >= 3 and words[0] == 'from':
  246. mod = words[1]
  247. return try_import(mod)
  248. #-----------------------------------------------------------------------------
  249. # Completers
  250. #-----------------------------------------------------------------------------
  251. # These all have the func(self, event) signature to be used as custom
  252. # completers
  253. def module_completer(self,event):
  254. """Give completions after user has typed 'import ...' or 'from ...'"""
  255. # This works in all versions of python. While 2.5 has
  256. # pkgutil.walk_packages(), that particular routine is fairly dangerous,
  257. # since it imports *EVERYTHING* on sys.path. That is: a) very slow b) full
  258. # of possibly problematic side effects.
  259. # This search the folders in the sys.path for available modules.
  260. return module_completion(event.line)
  261. # FIXME: there's a lot of logic common to the run, cd and builtin file
  262. # completers, that is currently reimplemented in each.
  263. def magic_run_completer(self, event):
  264. """Complete files that end in .py or .ipy or .ipynb for the %run command.
  265. """
  266. comps = arg_split(event.line, strict=False)
  267. # relpath should be the current token that we need to complete.
  268. if (len(comps) > 1) and (not event.line.endswith(' ')):
  269. relpath = comps[-1].strip("'\"")
  270. else:
  271. relpath = ''
  272. #print("\nev=", event) # dbg
  273. #print("rp=", relpath) # dbg
  274. #print('comps=', comps) # dbg
  275. lglob = glob.glob
  276. isdir = os.path.isdir
  277. relpath, tilde_expand, tilde_val = expand_user(relpath)
  278. # Find if the user has already typed the first filename, after which we
  279. # should complete on all files, since after the first one other files may
  280. # be arguments to the input script.
  281. if any(magic_run_re.match(c) for c in comps):
  282. matches = [f.replace('\\','/') + ('/' if isdir(f) else '')
  283. for f in lglob(relpath+'*')]
  284. else:
  285. dirs = [f.replace('\\','/') + "/" for f in lglob(relpath+'*') if isdir(f)]
  286. pys = [f.replace('\\','/')
  287. for f in lglob(relpath+'*.py') + lglob(relpath+'*.ipy') +
  288. lglob(relpath+'*.ipynb') + lglob(relpath + '*.pyw')]
  289. matches = dirs + pys
  290. #print('run comp:', dirs+pys) # dbg
  291. return [compress_user(p, tilde_expand, tilde_val) for p in matches]
  292. def cd_completer(self, event):
  293. """Completer function for cd, which only returns directories."""
  294. ip = get_ipython()
  295. relpath = event.symbol
  296. #print(event) # dbg
  297. if event.line.endswith('-b') or ' -b ' in event.line:
  298. # return only bookmark completions
  299. bkms = self.db.get('bookmarks', None)
  300. if bkms:
  301. return bkms.keys()
  302. else:
  303. return []
  304. if event.symbol == '-':
  305. width_dh = str(len(str(len(ip.user_ns['_dh']) + 1)))
  306. # jump in directory history by number
  307. fmt = '-%0' + width_dh +'d [%s]'
  308. ents = [ fmt % (i,s) for i,s in enumerate(ip.user_ns['_dh'])]
  309. if len(ents) > 1:
  310. return ents
  311. return []
  312. if event.symbol.startswith('--'):
  313. return ["--" + os.path.basename(d) for d in ip.user_ns['_dh']]
  314. # Expand ~ in path and normalize directory separators.
  315. relpath, tilde_expand, tilde_val = expand_user(relpath)
  316. relpath = relpath.replace('\\','/')
  317. found = []
  318. for d in [f.replace('\\','/') + '/' for f in glob.glob(relpath+'*')
  319. if os.path.isdir(f)]:
  320. if ' ' in d:
  321. # we don't want to deal with any of that, complex code
  322. # for this is elsewhere
  323. raise TryNext
  324. found.append(d)
  325. if not found:
  326. if os.path.isdir(relpath):
  327. return [compress_user(relpath, tilde_expand, tilde_val)]
  328. # if no completions so far, try bookmarks
  329. bks = self.db.get('bookmarks',{})
  330. bkmatches = [s for s in bks if s.startswith(event.symbol)]
  331. if bkmatches:
  332. return bkmatches
  333. raise TryNext
  334. return [compress_user(p, tilde_expand, tilde_val) for p in found]
  335. def reset_completer(self, event):
  336. "A completer for %reset magic"
  337. return '-f -s in out array dhist'.split()