completerlib.py 13 KB

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