completerlib.py 12 KB

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