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