completerlib.py 12 KB

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