Show More
The requested changes are too big and content was truncated. Show full diff
@@ -1,1276 +1,1176 b'' | |||||
1 | # encoding: utf-8 |
|
1 | # encoding: utf-8 | |
2 | """Word completion for IPython. |
|
2 | """Word completion for IPython. | |
3 |
|
3 | |||
4 |
This module |
|
4 | This module stared as fork of the rlcompleter module in the Python standard | |
5 | library. The original enhancements made to rlcompleter have been sent |
|
5 | library. The original enhancements made to rlcompleter have been sent | |
6 |
upstream and were accepted as of Python 2.3, |
|
6 | upstream and were accepted as of Python 2.3, | |
7 | functionality specific to IPython, so this module will continue to live as an |
|
|||
8 | IPython-specific utility. |
|
|||
9 |
|
7 | |||
10 | Original rlcompleter documentation: |
|
|||
11 |
|
8 | |||
12 | This requires the latest extension to the readline module (the |
|
9 | This is now mostly Completer implementation made to function with | |
13 | completes keywords, built-ins and globals in __main__; when completing |
|
10 | prompt_toolkit, but that should still work with readline. | |
14 | NAME.NAME..., it evaluates (!) the expression up to the last dot and |
|
|||
15 | completes its attributes. |
|
|||
16 |
|
||||
17 | It's very cool to do "import string" type "string.", hit the |
|
|||
18 | completion key (twice), and see the list of names defined by the |
|
|||
19 | string module! |
|
|||
20 |
|
||||
21 | Tip: to use the tab key as the completion key, call |
|
|||
22 |
|
||||
23 | readline.parse_and_bind("tab: complete") |
|
|||
24 |
|
||||
25 | Notes: |
|
|||
26 |
|
||||
27 | - Exceptions raised by the completer function are *ignored* (and |
|
|||
28 | generally cause the completion to fail). This is a feature -- since |
|
|||
29 | readline sets the tty device in raw (or cbreak) mode, printing a |
|
|||
30 | traceback wouldn't work well without some complicated hoopla to save, |
|
|||
31 | reset and restore the tty state. |
|
|||
32 |
|
||||
33 | - The evaluation of the NAME.NAME... form may cause arbitrary |
|
|||
34 | application defined code to be executed if an object with a |
|
|||
35 | ``__getattr__`` hook is found. Since it is the responsibility of the |
|
|||
36 | application (or the user) to enable this feature, I consider this an |
|
|||
37 | acceptable risk. More complicated expressions (e.g. function calls or |
|
|||
38 | indexing operations) are *not* evaluated. |
|
|||
39 |
|
||||
40 | - GNU readline is also used by the built-in functions input() and |
|
|||
41 | raw_input(), and thus these also benefit/suffer from the completer |
|
|||
42 | features. Clearly an interactive application can benefit by |
|
|||
43 | specifying its own completer function and using raw_input() for all |
|
|||
44 | its input. |
|
|||
45 |
|
||||
46 | - When the original stdin is not a tty device, GNU readline is never |
|
|||
47 | used, and this module (and the readline module) are silently inactive. |
|
|||
48 | """ |
|
11 | """ | |
49 |
|
12 | |||
50 | # Copyright (c) IPython Development Team. |
|
13 | # Copyright (c) IPython Development Team. | |
51 | # Distributed under the terms of the Modified BSD License. |
|
14 | # Distributed under the terms of the Modified BSD License. | |
52 | # |
|
15 | # | |
53 | # Some of this code originated from rlcompleter in the Python standard library |
|
16 | # Some of this code originated from rlcompleter in the Python standard library | |
54 | # Copyright (C) 2001 Python Software Foundation, www.python.org |
|
17 | # Copyright (C) 2001 Python Software Foundation, www.python.org | |
55 |
|
18 | |||
56 | from __future__ import print_function |
|
19 | from __future__ import print_function | |
57 |
|
20 | |||
58 | import __main__ |
|
21 | import __main__ | |
59 | import glob |
|
22 | import glob | |
60 | import inspect |
|
23 | import inspect | |
61 | import itertools |
|
24 | import itertools | |
62 | import keyword |
|
25 | import keyword | |
63 | import os |
|
26 | import os | |
64 | import re |
|
27 | import re | |
65 | import sys |
|
28 | import sys | |
66 | import unicodedata |
|
29 | import unicodedata | |
67 | import string |
|
30 | import string | |
68 |
|
31 | |||
69 | from traitlets.config.configurable import Configurable |
|
32 | from traitlets.config.configurable import Configurable | |
70 | from IPython.core.error import TryNext |
|
33 | from IPython.core.error import TryNext | |
71 | from IPython.core.inputsplitter import ESC_MAGIC |
|
34 | from IPython.core.inputsplitter import ESC_MAGIC | |
72 | from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol |
|
35 | from IPython.core.latex_symbols import latex_symbols, reverse_latex_symbol | |
73 | from IPython.utils import generics |
|
36 | from IPython.utils import generics | |
74 | from IPython.utils.decorators import undoc |
|
37 | from IPython.utils.decorators import undoc | |
75 | from IPython.utils.dir2 import dir2, get_real_method |
|
38 | from IPython.utils.dir2 import dir2, get_real_method | |
76 | from IPython.utils.process import arg_split |
|
39 | from IPython.utils.process import arg_split | |
77 | from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2 |
|
40 | from IPython.utils.py3compat import builtin_mod, string_types, PY3, cast_unicode_py2 | |
78 | from traitlets import Bool, Enum, observe |
|
41 | from traitlets import Bool, Enum, observe | |
79 |
|
42 | |||
80 | #----------------------------------------------------------------------------- |
|
43 | #----------------------------------------------------------------------------- | |
81 | # Globals |
|
44 | # Globals | |
82 | #----------------------------------------------------------------------------- |
|
45 | #----------------------------------------------------------------------------- | |
83 |
|
46 | |||
84 | # Public API |
|
47 | # Public API | |
85 | __all__ = ['Completer','IPCompleter'] |
|
48 | __all__ = ['Completer','IPCompleter'] | |
86 |
|
49 | |||
87 | if sys.platform == 'win32': |
|
50 | if sys.platform == 'win32': | |
88 | PROTECTABLES = ' ' |
|
51 | PROTECTABLES = ' ' | |
89 | else: |
|
52 | else: | |
90 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' |
|
53 | PROTECTABLES = ' ()[]{}?=\\|;:\'#*"^&' | |
91 |
|
54 | |||
92 |
|
55 | |||
93 | #----------------------------------------------------------------------------- |
|
56 | #----------------------------------------------------------------------------- | |
94 | # Main functions and classes |
|
57 | # Main functions and classes | |
95 | #----------------------------------------------------------------------------- |
|
58 | #----------------------------------------------------------------------------- | |
96 |
|
59 | |||
97 | def has_open_quotes(s): |
|
60 | def has_open_quotes(s): | |
98 | """Return whether a string has open quotes. |
|
61 | """Return whether a string has open quotes. | |
99 |
|
62 | |||
100 | This simply counts whether the number of quote characters of either type in |
|
63 | This simply counts whether the number of quote characters of either type in | |
101 | the string is odd. |
|
64 | the string is odd. | |
102 |
|
65 | |||
103 | Returns |
|
66 | Returns | |
104 | ------- |
|
67 | ------- | |
105 | If there is an open quote, the quote character is returned. Else, return |
|
68 | If there is an open quote, the quote character is returned. Else, return | |
106 | False. |
|
69 | False. | |
107 | """ |
|
70 | """ | |
108 | # We check " first, then ', so complex cases with nested quotes will get |
|
71 | # We check " first, then ', so complex cases with nested quotes will get | |
109 | # the " to take precedence. |
|
72 | # the " to take precedence. | |
110 | if s.count('"') % 2: |
|
73 | if s.count('"') % 2: | |
111 | return '"' |
|
74 | return '"' | |
112 | elif s.count("'") % 2: |
|
75 | elif s.count("'") % 2: | |
113 | return "'" |
|
76 | return "'" | |
114 | else: |
|
77 | else: | |
115 | return False |
|
78 | return False | |
116 |
|
79 | |||
117 |
|
80 | |||
118 | def protect_filename(s): |
|
81 | def protect_filename(s): | |
119 | """Escape a string to protect certain characters.""" |
|
82 | """Escape a string to protect certain characters.""" | |
120 | if set(s) & set(PROTECTABLES): |
|
83 | if set(s) & set(PROTECTABLES): | |
121 | if sys.platform == "win32": |
|
84 | if sys.platform == "win32": | |
122 | return '"' + s + '"' |
|
85 | return '"' + s + '"' | |
123 | else: |
|
86 | else: | |
124 | return "".join(("\\" + c if c in PROTECTABLES else c) for c in s) |
|
87 | return "".join(("\\" + c if c in PROTECTABLES else c) for c in s) | |
125 | else: |
|
88 | else: | |
126 | return s |
|
89 | return s | |
127 |
|
90 | |||
128 |
|
91 | |||
129 | def expand_user(path): |
|
92 | def expand_user(path): | |
130 | """Expand '~'-style usernames in strings. |
|
93 | """Expand '~'-style usernames in strings. | |
131 |
|
94 | |||
132 | This is similar to :func:`os.path.expanduser`, but it computes and returns |
|
95 | This is similar to :func:`os.path.expanduser`, but it computes and returns | |
133 | extra information that will be useful if the input was being used in |
|
96 | extra information that will be useful if the input was being used in | |
134 | computing completions, and you wish to return the completions with the |
|
97 | computing completions, and you wish to return the completions with the | |
135 | original '~' instead of its expanded value. |
|
98 | original '~' instead of its expanded value. | |
136 |
|
99 | |||
137 | Parameters |
|
100 | Parameters | |
138 | ---------- |
|
101 | ---------- | |
139 | path : str |
|
102 | path : str | |
140 | String to be expanded. If no ~ is present, the output is the same as the |
|
103 | String to be expanded. If no ~ is present, the output is the same as the | |
141 | input. |
|
104 | input. | |
142 |
|
105 | |||
143 | Returns |
|
106 | Returns | |
144 | ------- |
|
107 | ------- | |
145 | newpath : str |
|
108 | newpath : str | |
146 | Result of ~ expansion in the input path. |
|
109 | Result of ~ expansion in the input path. | |
147 | tilde_expand : bool |
|
110 | tilde_expand : bool | |
148 | Whether any expansion was performed or not. |
|
111 | Whether any expansion was performed or not. | |
149 | tilde_val : str |
|
112 | tilde_val : str | |
150 | The value that ~ was replaced with. |
|
113 | The value that ~ was replaced with. | |
151 | """ |
|
114 | """ | |
152 | # Default values |
|
115 | # Default values | |
153 | tilde_expand = False |
|
116 | tilde_expand = False | |
154 | tilde_val = '' |
|
117 | tilde_val = '' | |
155 | newpath = path |
|
118 | newpath = path | |
156 |
|
119 | |||
157 | if path.startswith('~'): |
|
120 | if path.startswith('~'): | |
158 | tilde_expand = True |
|
121 | tilde_expand = True | |
159 | rest = len(path)-1 |
|
122 | rest = len(path)-1 | |
160 | newpath = os.path.expanduser(path) |
|
123 | newpath = os.path.expanduser(path) | |
161 | if rest: |
|
124 | if rest: | |
162 | tilde_val = newpath[:-rest] |
|
125 | tilde_val = newpath[:-rest] | |
163 | else: |
|
126 | else: | |
164 | tilde_val = newpath |
|
127 | tilde_val = newpath | |
165 |
|
128 | |||
166 | return newpath, tilde_expand, tilde_val |
|
129 | return newpath, tilde_expand, tilde_val | |
167 |
|
130 | |||
168 |
|
131 | |||
169 | def compress_user(path, tilde_expand, tilde_val): |
|
132 | def compress_user(path, tilde_expand, tilde_val): | |
170 | """Does the opposite of expand_user, with its outputs. |
|
133 | """Does the opposite of expand_user, with its outputs. | |
171 | """ |
|
134 | """ | |
172 | if tilde_expand: |
|
135 | if tilde_expand: | |
173 | return path.replace(tilde_val, '~') |
|
136 | return path.replace(tilde_val, '~') | |
174 | else: |
|
137 | else: | |
175 | return path |
|
138 | return path | |
176 |
|
139 | |||
177 |
|
140 | |||
178 | def completions_sorting_key(word): |
|
141 | def completions_sorting_key(word): | |
179 | """key for sorting completions |
|
142 | """key for sorting completions | |
180 |
|
143 | |||
181 | This does several things: |
|
144 | This does several things: | |
182 |
|
145 | |||
183 | - Lowercase all completions, so they are sorted alphabetically with |
|
146 | - Lowercase all completions, so they are sorted alphabetically with | |
184 | upper and lower case words mingled |
|
147 | upper and lower case words mingled | |
185 | - Demote any completions starting with underscores to the end |
|
148 | - Demote any completions starting with underscores to the end | |
186 | - Insert any %magic and %%cellmagic completions in the alphabetical order |
|
149 | - Insert any %magic and %%cellmagic completions in the alphabetical order | |
187 | by their name |
|
150 | by their name | |
188 | """ |
|
151 | """ | |
189 | # Case insensitive sort |
|
152 | # Case insensitive sort | |
190 | word = word.lower() |
|
153 | word = word.lower() | |
191 |
|
154 | |||
192 | prio1, prio2 = 0, 0 |
|
155 | prio1, prio2 = 0, 0 | |
193 |
|
156 | |||
194 | if word.startswith('__'): |
|
157 | if word.startswith('__'): | |
195 | prio1 = 2 |
|
158 | prio1 = 2 | |
196 | elif word.startswith('_'): |
|
159 | elif word.startswith('_'): | |
197 | prio1 = 1 |
|
160 | prio1 = 1 | |
198 |
|
161 | |||
199 | if word.endswith('='): |
|
162 | if word.endswith('='): | |
200 | prio1 = -1 |
|
163 | prio1 = -1 | |
201 |
|
164 | |||
202 | if word.startswith('%%'): |
|
165 | if word.startswith('%%'): | |
203 | # If there's another % in there, this is something else, so leave it alone |
|
166 | # If there's another % in there, this is something else, so leave it alone | |
204 | if not "%" in word[2:]: |
|
167 | if not "%" in word[2:]: | |
205 | word = word[2:] |
|
168 | word = word[2:] | |
206 | prio2 = 2 |
|
169 | prio2 = 2 | |
207 | elif word.startswith('%'): |
|
170 | elif word.startswith('%'): | |
208 | if not "%" in word[1:]: |
|
171 | if not "%" in word[1:]: | |
209 | word = word[1:] |
|
172 | word = word[1:] | |
210 | prio2 = 1 |
|
173 | prio2 = 1 | |
211 |
|
174 | |||
212 | return prio1, word, prio2 |
|
175 | return prio1, word, prio2 | |
213 |
|
176 | |||
214 |
|
177 | |||
215 | @undoc |
|
178 | @undoc | |
216 | class Bunch(object): pass |
|
179 | class Bunch(object): pass | |
217 |
|
180 | |||
218 |
|
181 | |||
219 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' |
|
182 | DELIMS = ' \t\n`!@#$^&*()=+[{]}\\|;:\'",<>?' | |
220 | GREEDY_DELIMS = ' =\r\n' |
|
183 | GREEDY_DELIMS = ' =\r\n' | |
221 |
|
184 | |||
222 |
|
185 | |||
223 | class CompletionSplitter(object): |
|
186 | class CompletionSplitter(object): | |
224 | """An object to split an input line in a manner similar to readline. |
|
187 | """An object to split an input line in a manner similar to readline. | |
225 |
|
188 | |||
226 | By having our own implementation, we can expose readline-like completion in |
|
189 | By having our own implementation, we can expose readline-like completion in | |
227 | a uniform manner to all frontends. This object only needs to be given the |
|
190 | a uniform manner to all frontends. This object only needs to be given the | |
228 | line of text to be split and the cursor position on said line, and it |
|
191 | line of text to be split and the cursor position on said line, and it | |
229 | returns the 'word' to be completed on at the cursor after splitting the |
|
192 | returns the 'word' to be completed on at the cursor after splitting the | |
230 | entire line. |
|
193 | entire line. | |
231 |
|
194 | |||
232 | What characters are used as splitting delimiters can be controlled by |
|
195 | What characters are used as splitting delimiters can be controlled by | |
233 | setting the `delims` attribute (this is a property that internally |
|
196 | setting the `delims` attribute (this is a property that internally | |
234 | automatically builds the necessary regular expression)""" |
|
197 | automatically builds the necessary regular expression)""" | |
235 |
|
198 | |||
236 | # Private interface |
|
199 | # Private interface | |
237 |
|
200 | |||
238 | # A string of delimiter characters. The default value makes sense for |
|
201 | # A string of delimiter characters. The default value makes sense for | |
239 | # IPython's most typical usage patterns. |
|
202 | # IPython's most typical usage patterns. | |
240 | _delims = DELIMS |
|
203 | _delims = DELIMS | |
241 |
|
204 | |||
242 | # The expression (a normal string) to be compiled into a regular expression |
|
205 | # The expression (a normal string) to be compiled into a regular expression | |
243 | # for actual splitting. We store it as an attribute mostly for ease of |
|
206 | # for actual splitting. We store it as an attribute mostly for ease of | |
244 | # debugging, since this type of code can be so tricky to debug. |
|
207 | # debugging, since this type of code can be so tricky to debug. | |
245 | _delim_expr = None |
|
208 | _delim_expr = None | |
246 |
|
209 | |||
247 | # The regular expression that does the actual splitting |
|
210 | # The regular expression that does the actual splitting | |
248 | _delim_re = None |
|
211 | _delim_re = None | |
249 |
|
212 | |||
250 | def __init__(self, delims=None): |
|
213 | def __init__(self, delims=None): | |
251 | delims = CompletionSplitter._delims if delims is None else delims |
|
214 | delims = CompletionSplitter._delims if delims is None else delims | |
252 | self.delims = delims |
|
215 | self.delims = delims | |
253 |
|
216 | |||
254 | @property |
|
217 | @property | |
255 | def delims(self): |
|
218 | def delims(self): | |
256 | """Return the string of delimiter characters.""" |
|
219 | """Return the string of delimiter characters.""" | |
257 | return self._delims |
|
220 | return self._delims | |
258 |
|
221 | |||
259 | @delims.setter |
|
222 | @delims.setter | |
260 | def delims(self, delims): |
|
223 | def delims(self, delims): | |
261 | """Set the delimiters for line splitting.""" |
|
224 | """Set the delimiters for line splitting.""" | |
262 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' |
|
225 | expr = '[' + ''.join('\\'+ c for c in delims) + ']' | |
263 | self._delim_re = re.compile(expr) |
|
226 | self._delim_re = re.compile(expr) | |
264 | self._delims = delims |
|
227 | self._delims = delims | |
265 | self._delim_expr = expr |
|
228 | self._delim_expr = expr | |
266 |
|
229 | |||
267 | def split_line(self, line, cursor_pos=None): |
|
230 | def split_line(self, line, cursor_pos=None): | |
268 | """Split a line of text with a cursor at the given position. |
|
231 | """Split a line of text with a cursor at the given position. | |
269 | """ |
|
232 | """ | |
270 | l = line if cursor_pos is None else line[:cursor_pos] |
|
233 | l = line if cursor_pos is None else line[:cursor_pos] | |
271 | return self._delim_re.split(l)[-1] |
|
234 | return self._delim_re.split(l)[-1] | |
272 |
|
235 | |||
273 |
|
236 | |||
274 | class Completer(Configurable): |
|
237 | class Completer(Configurable): | |
275 |
|
238 | |||
276 | greedy = Bool(False, |
|
239 | greedy = Bool(False, | |
277 | help="""Activate greedy completion |
|
240 | help="""Activate greedy completion | |
278 | PENDING DEPRECTION. this is now mostly taken care of with Jedi. |
|
241 | PENDING DEPRECTION. this is now mostly taken care of with Jedi. | |
279 |
|
242 | |||
280 | This will enable completion on elements of lists, results of function calls, etc., |
|
243 | This will enable completion on elements of lists, results of function calls, etc., | |
281 | but can be unsafe because the code is actually evaluated on TAB. |
|
244 | but can be unsafe because the code is actually evaluated on TAB. | |
282 | """ |
|
245 | """ | |
283 | ).tag(config=True) |
|
246 | ).tag(config=True) | |
284 |
|
247 | |||
285 |
|
248 | |||
286 | def __init__(self, namespace=None, global_namespace=None, **kwargs): |
|
249 | def __init__(self, namespace=None, global_namespace=None, **kwargs): | |
287 | """Create a new completer for the command line. |
|
250 | """Create a new completer for the command line. | |
288 |
|
251 | |||
289 | Completer(namespace=ns, global_namespace=ns2) -> completer instance. |
|
252 | Completer(namespace=ns, global_namespace=ns2) -> completer instance. | |
290 |
|
253 | |||
291 | If unspecified, the default namespace where completions are performed |
|
254 | If unspecified, the default namespace where completions are performed | |
292 | is __main__ (technically, __main__.__dict__). Namespaces should be |
|
255 | is __main__ (technically, __main__.__dict__). Namespaces should be | |
293 | given as dictionaries. |
|
256 | given as dictionaries. | |
294 |
|
257 | |||
295 | An optional second namespace can be given. This allows the completer |
|
258 | An optional second namespace can be given. This allows the completer | |
296 | to handle cases where both the local and global scopes need to be |
|
259 | to handle cases where both the local and global scopes need to be | |
297 | distinguished. |
|
260 | distinguished. | |
298 |
|
261 | |||
299 | Completer instances should be used as the completion mechanism of |
|
262 | Completer instances should be used as the completion mechanism of | |
300 | readline via the set_completer() call: |
|
263 | readline via the set_completer() call: | |
301 |
|
264 | |||
302 | readline.set_completer(Completer(my_namespace).complete) |
|
265 | readline.set_completer(Completer(my_namespace).complete) | |
303 | """ |
|
266 | """ | |
304 |
|
267 | |||
305 | # Don't bind to namespace quite yet, but flag whether the user wants a |
|
268 | # Don't bind to namespace quite yet, but flag whether the user wants a | |
306 | # specific namespace or to use __main__.__dict__. This will allow us |
|
269 | # specific namespace or to use __main__.__dict__. This will allow us | |
307 | # to bind to __main__.__dict__ at completion time, not now. |
|
270 | # to bind to __main__.__dict__ at completion time, not now. | |
308 | if namespace is None: |
|
271 | if namespace is None: | |
309 | self.use_main_ns = 1 |
|
272 | self.use_main_ns = 1 | |
310 | else: |
|
273 | else: | |
311 | self.use_main_ns = 0 |
|
274 | self.use_main_ns = 0 | |
312 | self.namespace = namespace |
|
275 | self.namespace = namespace | |
313 |
|
276 | |||
314 | # The global namespace, if given, can be bound directly |
|
277 | # The global namespace, if given, can be bound directly | |
315 | if global_namespace is None: |
|
278 | if global_namespace is None: | |
316 | self.global_namespace = {} |
|
279 | self.global_namespace = {} | |
317 | else: |
|
280 | else: | |
318 | self.global_namespace = global_namespace |
|
281 | self.global_namespace = global_namespace | |
319 |
|
282 | |||
320 | super(Completer, self).__init__(**kwargs) |
|
283 | super(Completer, self).__init__(**kwargs) | |
321 |
|
284 | |||
322 | def complete(self, text, state): |
|
285 | def complete(self, text, state): | |
323 | """Return the next possible completion for 'text'. |
|
286 | """Return the next possible completion for 'text'. | |
324 |
|
287 | |||
325 | This is called successively with state == 0, 1, 2, ... until it |
|
288 | This is called successively with state == 0, 1, 2, ... until it | |
326 | returns None. The completion should begin with 'text'. |
|
289 | returns None. The completion should begin with 'text'. | |
327 |
|
290 | |||
328 | """ |
|
291 | """ | |
329 | if self.use_main_ns: |
|
292 | if self.use_main_ns: | |
330 | self.namespace = __main__.__dict__ |
|
293 | self.namespace = __main__.__dict__ | |
331 |
|
294 | |||
332 | if state == 0: |
|
295 | if state == 0: | |
333 | if "." in text: |
|
296 | if "." in text: | |
334 | self.matches = self.attr_matches(text) |
|
297 | self.matches = self.attr_matches(text) | |
335 | else: |
|
298 | else: | |
336 | self.matches = self.global_matches(text) |
|
299 | self.matches = self.global_matches(text) | |
337 | try: |
|
300 | try: | |
338 | return self.matches[state] |
|
301 | return self.matches[state] | |
339 | except IndexError: |
|
302 | except IndexError: | |
340 | return None |
|
303 | return None | |
341 |
|
304 | |||
342 | def global_matches(self, text): |
|
305 | def global_matches(self, text): | |
343 | """Compute matches when text is a simple name. |
|
306 | """Compute matches when text is a simple name. | |
344 |
|
307 | |||
345 | Return a list of all keywords, built-in functions and names currently |
|
308 | Return a list of all keywords, built-in functions and names currently | |
346 | defined in self.namespace or self.global_namespace that match. |
|
309 | defined in self.namespace or self.global_namespace that match. | |
347 |
|
310 | |||
348 | """ |
|
311 | """ | |
349 | matches = [] |
|
312 | matches = [] | |
350 | match_append = matches.append |
|
313 | match_append = matches.append | |
351 | n = len(text) |
|
314 | n = len(text) | |
352 | for lst in [keyword.kwlist, |
|
315 | for lst in [keyword.kwlist, | |
353 | builtin_mod.__dict__.keys(), |
|
316 | builtin_mod.__dict__.keys(), | |
354 | self.namespace.keys(), |
|
317 | self.namespace.keys(), | |
355 | self.global_namespace.keys()]: |
|
318 | self.global_namespace.keys()]: | |
356 | for word in lst: |
|
319 | for word in lst: | |
357 | if word[:n] == text and word != "__builtins__": |
|
320 | if word[:n] == text and word != "__builtins__": | |
358 | match_append(word) |
|
321 | match_append(word) | |
359 | return [cast_unicode_py2(m) for m in matches] |
|
322 | return [cast_unicode_py2(m) for m in matches] | |
360 |
|
323 | |||
361 | def attr_matches(self, text): |
|
324 | def attr_matches(self, text): | |
362 | """Compute matches when text contains a dot. |
|
325 | """Compute matches when text contains a dot. | |
363 |
|
326 | |||
364 | Assuming the text is of the form NAME.NAME....[NAME], and is |
|
327 | Assuming the text is of the form NAME.NAME....[NAME], and is | |
365 | evaluatable in self.namespace or self.global_namespace, it will be |
|
328 | evaluatable in self.namespace or self.global_namespace, it will be | |
366 | evaluated and its attributes (as revealed by dir()) are used as |
|
329 | evaluated and its attributes (as revealed by dir()) are used as | |
367 | possible completions. (For class instances, class members are are |
|
330 | possible completions. (For class instances, class members are are | |
368 | also considered.) |
|
331 | also considered.) | |
369 |
|
332 | |||
370 | WARNING: this can still invoke arbitrary C code, if an object |
|
333 | WARNING: this can still invoke arbitrary C code, if an object | |
371 | with a __getattr__ hook is evaluated. |
|
334 | with a __getattr__ hook is evaluated. | |
372 |
|
335 | |||
373 | """ |
|
336 | """ | |
374 |
|
337 | |||
375 | # Another option, seems to work great. Catches things like ''.<tab> |
|
338 | # Another option, seems to work great. Catches things like ''.<tab> | |
376 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) |
|
339 | m = re.match(r"(\S+(\.\w+)*)\.(\w*)$", text) | |
377 |
|
340 | |||
378 | if m: |
|
341 | if m: | |
379 | expr, attr = m.group(1, 3) |
|
342 | expr, attr = m.group(1, 3) | |
380 | elif self.greedy: |
|
343 | elif self.greedy: | |
381 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) |
|
344 | m2 = re.match(r"(.+)\.(\w*)$", self.line_buffer) | |
382 | if not m2: |
|
345 | if not m2: | |
383 | return [] |
|
346 | return [] | |
384 | expr, attr = m2.group(1,2) |
|
347 | expr, attr = m2.group(1,2) | |
385 | else: |
|
348 | else: | |
386 | return [] |
|
349 | return [] | |
387 |
|
350 | |||
388 | try: |
|
351 | try: | |
389 | obj = eval(expr, self.namespace) |
|
352 | obj = eval(expr, self.namespace) | |
390 | except: |
|
353 | except: | |
391 | try: |
|
354 | try: | |
392 | obj = eval(expr, self.global_namespace) |
|
355 | obj = eval(expr, self.global_namespace) | |
393 | except: |
|
356 | except: | |
394 | return [] |
|
357 | return [] | |
395 |
|
358 | |||
396 | if self.limit_to__all__ and hasattr(obj, '__all__'): |
|
359 | if self.limit_to__all__ and hasattr(obj, '__all__'): | |
397 | words = get__all__entries(obj) |
|
360 | words = get__all__entries(obj) | |
398 | else: |
|
361 | else: | |
399 | words = dir2(obj) |
|
362 | words = dir2(obj) | |
400 |
|
363 | |||
401 | try: |
|
364 | try: | |
402 | words = generics.complete_object(obj, words) |
|
365 | words = generics.complete_object(obj, words) | |
403 | except TryNext: |
|
366 | except TryNext: | |
404 | pass |
|
367 | pass | |
405 | except Exception: |
|
368 | except Exception: | |
406 | # Silence errors from completion function |
|
369 | # Silence errors from completion function | |
407 | #raise # dbg |
|
370 | #raise # dbg | |
408 | pass |
|
371 | pass | |
409 | # Build match list to return |
|
372 | # Build match list to return | |
410 | n = len(attr) |
|
373 | n = len(attr) | |
411 | return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] |
|
374 | return [u"%s.%s" % (expr, w) for w in words if w[:n] == attr ] | |
412 |
|
375 | |||
413 |
|
376 | |||
414 | def get__all__entries(obj): |
|
377 | def get__all__entries(obj): | |
415 | """returns the strings in the __all__ attribute""" |
|
378 | """returns the strings in the __all__ attribute""" | |
416 | try: |
|
379 | try: | |
417 | words = getattr(obj, '__all__') |
|
380 | words = getattr(obj, '__all__') | |
418 | except: |
|
381 | except: | |
419 | return [] |
|
382 | return [] | |
420 |
|
383 | |||
421 | return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)] |
|
384 | return [cast_unicode_py2(w) for w in words if isinstance(w, string_types)] | |
422 |
|
385 | |||
423 |
|
386 | |||
424 | def match_dict_keys(keys, prefix, delims): |
|
387 | def match_dict_keys(keys, prefix, delims): | |
425 | """Used by dict_key_matches, matching the prefix to a list of keys""" |
|
388 | """Used by dict_key_matches, matching the prefix to a list of keys""" | |
426 | if not prefix: |
|
389 | if not prefix: | |
427 | return None, 0, [repr(k) for k in keys |
|
390 | return None, 0, [repr(k) for k in keys | |
428 | if isinstance(k, (string_types, bytes))] |
|
391 | if isinstance(k, (string_types, bytes))] | |
429 | quote_match = re.search('["\']', prefix) |
|
392 | quote_match = re.search('["\']', prefix) | |
430 | quote = quote_match.group() |
|
393 | quote = quote_match.group() | |
431 | try: |
|
394 | try: | |
432 | prefix_str = eval(prefix + quote, {}) |
|
395 | prefix_str = eval(prefix + quote, {}) | |
433 | except Exception: |
|
396 | except Exception: | |
434 | return None, 0, [] |
|
397 | return None, 0, [] | |
435 |
|
398 | |||
436 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' |
|
399 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' | |
437 | token_match = re.search(pattern, prefix, re.UNICODE) |
|
400 | token_match = re.search(pattern, prefix, re.UNICODE) | |
438 | token_start = token_match.start() |
|
401 | token_start = token_match.start() | |
439 | token_prefix = token_match.group() |
|
402 | token_prefix = token_match.group() | |
440 |
|
403 | |||
441 | # TODO: support bytes in Py3k |
|
404 | # TODO: support bytes in Py3k | |
442 | matched = [] |
|
405 | matched = [] | |
443 | for key in keys: |
|
406 | for key in keys: | |
444 | try: |
|
407 | try: | |
445 | if not key.startswith(prefix_str): |
|
408 | if not key.startswith(prefix_str): | |
446 | continue |
|
409 | continue | |
447 | except (AttributeError, TypeError, UnicodeError): |
|
410 | except (AttributeError, TypeError, UnicodeError): | |
448 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa |
|
411 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa | |
449 | continue |
|
412 | continue | |
450 |
|
413 | |||
451 | # reformat remainder of key to begin with prefix |
|
414 | # reformat remainder of key to begin with prefix | |
452 | rem = key[len(prefix_str):] |
|
415 | rem = key[len(prefix_str):] | |
453 | # force repr wrapped in ' |
|
416 | # force repr wrapped in ' | |
454 | rem_repr = repr(rem + '"') |
|
417 | rem_repr = repr(rem + '"') | |
455 | if rem_repr.startswith('u') and prefix[0] not in 'uU': |
|
418 | if rem_repr.startswith('u') and prefix[0] not in 'uU': | |
456 | # Found key is unicode, but prefix is Py2 string. |
|
419 | # Found key is unicode, but prefix is Py2 string. | |
457 | # Therefore attempt to interpret key as string. |
|
420 | # Therefore attempt to interpret key as string. | |
458 | try: |
|
421 | try: | |
459 | rem_repr = repr(rem.encode('ascii') + '"') |
|
422 | rem_repr = repr(rem.encode('ascii') + '"') | |
460 | except UnicodeEncodeError: |
|
423 | except UnicodeEncodeError: | |
461 | continue |
|
424 | continue | |
462 |
|
425 | |||
463 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] |
|
426 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] | |
464 | if quote == '"': |
|
427 | if quote == '"': | |
465 | # The entered prefix is quoted with ", |
|
428 | # The entered prefix is quoted with ", | |
466 | # but the match is quoted with '. |
|
429 | # but the match is quoted with '. | |
467 | # A contained " hence needs escaping for comparison: |
|
430 | # A contained " hence needs escaping for comparison: | |
468 | rem_repr = rem_repr.replace('"', '\\"') |
|
431 | rem_repr = rem_repr.replace('"', '\\"') | |
469 |
|
432 | |||
470 | # then reinsert prefix from start of token |
|
433 | # then reinsert prefix from start of token | |
471 | matched.append('%s%s' % (token_prefix, rem_repr)) |
|
434 | matched.append('%s%s' % (token_prefix, rem_repr)) | |
472 | return quote, token_start, matched |
|
435 | return quote, token_start, matched | |
473 |
|
436 | |||
474 |
|
437 | |||
475 | def _safe_isinstance(obj, module, class_name): |
|
438 | def _safe_isinstance(obj, module, class_name): | |
476 | """Checks if obj is an instance of module.class_name if loaded |
|
439 | """Checks if obj is an instance of module.class_name if loaded | |
477 | """ |
|
440 | """ | |
478 | return (module in sys.modules and |
|
441 | return (module in sys.modules and | |
479 | isinstance(obj, getattr(__import__(module), class_name))) |
|
442 | isinstance(obj, getattr(__import__(module), class_name))) | |
480 |
|
443 | |||
481 |
|
444 | |||
482 | def back_unicode_name_matches(text): |
|
445 | def back_unicode_name_matches(text): | |
483 | u"""Match unicode characters back to unicode name |
|
446 | u"""Match unicode characters back to unicode name | |
484 |
|
447 | |||
485 | This does β -> \\snowman |
|
448 | This does β -> \\snowman | |
486 |
|
449 | |||
487 | Note that snowman is not a valid python3 combining character but will be expanded. |
|
450 | Note that snowman is not a valid python3 combining character but will be expanded. | |
488 | Though it will not recombine back to the snowman character by the completion machinery. |
|
451 | Though it will not recombine back to the snowman character by the completion machinery. | |
489 |
|
452 | |||
490 | This will not either back-complete standard sequences like \\n, \\b ... |
|
453 | This will not either back-complete standard sequences like \\n, \\b ... | |
491 |
|
454 | |||
492 | Used on Python 3 only. |
|
455 | Used on Python 3 only. | |
493 | """ |
|
456 | """ | |
494 | if len(text)<2: |
|
457 | if len(text)<2: | |
495 | return u'', () |
|
458 | return u'', () | |
496 | maybe_slash = text[-2] |
|
459 | maybe_slash = text[-2] | |
497 | if maybe_slash != '\\': |
|
460 | if maybe_slash != '\\': | |
498 | return u'', () |
|
461 | return u'', () | |
499 |
|
462 | |||
500 | char = text[-1] |
|
463 | char = text[-1] | |
501 | # no expand on quote for completion in strings. |
|
464 | # no expand on quote for completion in strings. | |
502 | # nor backcomplete standard ascii keys |
|
465 | # nor backcomplete standard ascii keys | |
503 | if char in string.ascii_letters or char in ['"',"'"]: |
|
466 | if char in string.ascii_letters or char in ['"',"'"]: | |
504 | return u'', () |
|
467 | return u'', () | |
505 | try : |
|
468 | try : | |
506 | unic = unicodedata.name(char) |
|
469 | unic = unicodedata.name(char) | |
507 | return '\\'+char,['\\'+unic] |
|
470 | return '\\'+char,['\\'+unic] | |
508 | except KeyError: |
|
471 | except KeyError: | |
509 | pass |
|
472 | pass | |
510 | return u'', () |
|
473 | return u'', () | |
511 |
|
474 | |||
512 | def back_latex_name_matches(text): |
|
475 | def back_latex_name_matches(text): | |
513 | u"""Match latex characters back to unicode name |
|
476 | u"""Match latex characters back to unicode name | |
514 |
|
477 | |||
515 | This does ->\\sqrt |
|
478 | This does ->\\sqrt | |
516 |
|
479 | |||
517 | Used on Python 3 only. |
|
480 | Used on Python 3 only. | |
518 | """ |
|
481 | """ | |
519 | if len(text)<2: |
|
482 | if len(text)<2: | |
520 | return u'', () |
|
483 | return u'', () | |
521 | maybe_slash = text[-2] |
|
484 | maybe_slash = text[-2] | |
522 | if maybe_slash != '\\': |
|
485 | if maybe_slash != '\\': | |
523 | return u'', () |
|
486 | return u'', () | |
524 |
|
487 | |||
525 |
|
488 | |||
526 | char = text[-1] |
|
489 | char = text[-1] | |
527 | # no expand on quote for completion in strings. |
|
490 | # no expand on quote for completion in strings. | |
528 | # nor backcomplete standard ascii keys |
|
491 | # nor backcomplete standard ascii keys | |
529 | if char in string.ascii_letters or char in ['"',"'"]: |
|
492 | if char in string.ascii_letters or char in ['"',"'"]: | |
530 | return u'', () |
|
493 | return u'', () | |
531 | try : |
|
494 | try : | |
532 | latex = reverse_latex_symbol[char] |
|
495 | latex = reverse_latex_symbol[char] | |
533 | # '\\' replace the \ as well |
|
496 | # '\\' replace the \ as well | |
534 | return '\\'+char,[latex] |
|
497 | return '\\'+char,[latex] | |
535 | except KeyError: |
|
498 | except KeyError: | |
536 | pass |
|
499 | pass | |
537 | return u'', () |
|
500 | return u'', () | |
538 |
|
501 | |||
539 |
|
502 | |||
540 | class IPCompleter(Completer): |
|
503 | class IPCompleter(Completer): | |
541 | """Extension of the completer class with IPython-specific features""" |
|
504 | """Extension of the completer class with IPython-specific features""" | |
542 |
|
505 | |||
543 | @observe('greedy') |
|
506 | @observe('greedy') | |
544 | def _greedy_changed(self, change): |
|
507 | def _greedy_changed(self, change): | |
545 | """update the splitter and readline delims when greedy is changed""" |
|
508 | """update the splitter and readline delims when greedy is changed""" | |
546 | if change['new']: |
|
509 | if change['new']: | |
547 | self.splitter.delims = GREEDY_DELIMS |
|
510 | self.splitter.delims = GREEDY_DELIMS | |
548 | else: |
|
511 | else: | |
549 | self.splitter.delims = DELIMS |
|
512 | self.splitter.delims = DELIMS | |
550 |
|
513 | |||
551 | if self.readline: |
|
514 | if self.readline: | |
552 | self.readline.set_completer_delims(self.splitter.delims) |
|
515 | self.readline.set_completer_delims(self.splitter.delims) | |
553 |
|
516 | |||
554 | merge_completions = Bool(True, |
|
517 | merge_completions = Bool(True, | |
555 | help="""Whether to merge completion results into a single list |
|
518 | help="""Whether to merge completion results into a single list | |
556 |
|
519 | |||
557 | If False, only the completion results from the first non-empty |
|
520 | If False, only the completion results from the first non-empty | |
558 | completer will be returned. |
|
521 | completer will be returned. | |
559 | """ |
|
522 | """ | |
560 | ).tag(config=True) |
|
523 | ).tag(config=True) | |
561 | omit__names = Enum((0,1,2), default_value=2, |
|
524 | omit__names = Enum((0,1,2), default_value=2, | |
562 | help="""Instruct the completer to omit private method names |
|
525 | help="""Instruct the completer to omit private method names | |
563 |
|
526 | |||
564 | Specifically, when completing on ``object.<tab>``. |
|
527 | Specifically, when completing on ``object.<tab>``. | |
565 |
|
528 | |||
566 | When 2 [default]: all names that start with '_' will be excluded. |
|
529 | When 2 [default]: all names that start with '_' will be excluded. | |
567 |
|
530 | |||
568 | When 1: all 'magic' names (``__foo__``) will be excluded. |
|
531 | When 1: all 'magic' names (``__foo__``) will be excluded. | |
569 |
|
532 | |||
570 | When 0: nothing will be excluded. |
|
533 | When 0: nothing will be excluded. | |
571 | """ |
|
534 | """ | |
572 | ).tag(config=True) |
|
535 | ).tag(config=True) | |
573 | limit_to__all__ = Bool(False, |
|
536 | limit_to__all__ = Bool(False, | |
574 | help=""" |
|
537 | help=""" | |
575 | DEPRECATED as of version 5.0. |
|
538 | DEPRECATED as of version 5.0. | |
576 |
|
539 | |||
577 | Instruct the completer to use __all__ for the completion |
|
540 | Instruct the completer to use __all__ for the completion | |
578 |
|
541 | |||
579 | Specifically, when completing on ``object.<tab>``. |
|
542 | Specifically, when completing on ``object.<tab>``. | |
580 |
|
543 | |||
581 | When True: only those names in obj.__all__ will be included. |
|
544 | When True: only those names in obj.__all__ will be included. | |
582 |
|
545 | |||
583 | When False [default]: the __all__ attribute is ignored |
|
546 | When False [default]: the __all__ attribute is ignored | |
584 | """, |
|
547 | """, | |
585 | ).tag(config=True) |
|
548 | ).tag(config=True) | |
586 |
|
549 | |||
587 | def __init__(self, shell=None, namespace=None, global_namespace=None, |
|
550 | def __init__(self, shell=None, namespace=None, global_namespace=None, | |
588 | use_readline=True, config=None, **kwargs): |
|
551 | use_readline=True, config=None, **kwargs): | |
589 | """IPCompleter() -> completer |
|
552 | """IPCompleter() -> completer | |
590 |
|
553 | |||
591 | Return a completer object suitable for use by the readline library |
|
554 | Return a completer object suitable for use by the readline library | |
592 | via readline.set_completer(). |
|
555 | via readline.set_completer(). | |
593 |
|
556 | |||
594 | Inputs: |
|
557 | Inputs: | |
595 |
|
558 | |||
596 | - shell: a pointer to the ipython shell itself. This is needed |
|
559 | - shell: a pointer to the ipython shell itself. This is needed | |
597 | because this completer knows about magic functions, and those can |
|
560 | because this completer knows about magic functions, and those can | |
598 | only be accessed via the ipython instance. |
|
561 | only be accessed via the ipython instance. | |
599 |
|
562 | |||
600 | - namespace: an optional dict where completions are performed. |
|
563 | - namespace: an optional dict where completions are performed. | |
601 |
|
564 | |||
602 | - global_namespace: secondary optional dict for completions, to |
|
565 | - global_namespace: secondary optional dict for completions, to | |
603 | handle cases (such as IPython embedded inside functions) where |
|
566 | handle cases (such as IPython embedded inside functions) where | |
604 | both Python scopes are visible. |
|
567 | both Python scopes are visible. | |
605 |
|
568 | |||
606 | use_readline : bool, optional |
|
569 | use_readline : bool, optional | |
607 | If true, use the readline library. This completer can still function |
|
570 | If true, use the readline library. This completer can still function | |
608 | without readline, though in that case callers must provide some extra |
|
571 | without readline, though in that case callers must provide some extra | |
609 | information on each call about the current line.""" |
|
572 | information on each call about the current line.""" | |
610 |
|
573 | |||
611 | self.magic_escape = ESC_MAGIC |
|
574 | self.magic_escape = ESC_MAGIC | |
612 | self.splitter = CompletionSplitter() |
|
575 | self.splitter = CompletionSplitter() | |
613 |
|
576 | |||
614 | # Readline configuration, only used by the rlcompleter method. |
|
577 | # Readline configuration, only used by the rlcompleter method. | |
615 | if use_readline: |
|
578 | if use_readline: | |
616 | # We store the right version of readline so that later code |
|
579 | # We store the right version of readline so that later code | |
617 | import IPython.utils.rlineimpl as readline |
|
580 | import IPython.utils.rlineimpl as readline | |
618 | self.readline = readline |
|
581 | self.readline = readline | |
619 | else: |
|
582 | else: | |
620 | self.readline = None |
|
583 | self.readline = None | |
621 |
|
584 | |||
622 | # _greedy_changed() depends on splitter and readline being defined: |
|
585 | # _greedy_changed() depends on splitter and readline being defined: | |
623 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, |
|
586 | Completer.__init__(self, namespace=namespace, global_namespace=global_namespace, | |
624 | config=config, **kwargs) |
|
587 | config=config, **kwargs) | |
625 |
|
588 | |||
626 | # List where completion matches will be stored |
|
589 | # List where completion matches will be stored | |
627 | self.matches = [] |
|
590 | self.matches = [] | |
628 | self.shell = shell |
|
591 | self.shell = shell | |
629 | # Regexp to split filenames with spaces in them |
|
592 | # Regexp to split filenames with spaces in them | |
630 | self.space_name_re = re.compile(r'([^\\] )') |
|
593 | self.space_name_re = re.compile(r'([^\\] )') | |
631 | # Hold a local ref. to glob.glob for speed |
|
594 | # Hold a local ref. to glob.glob for speed | |
632 | self.glob = glob.glob |
|
595 | self.glob = glob.glob | |
633 |
|
596 | |||
634 | # Determine if we are running on 'dumb' terminals, like (X)Emacs |
|
597 | # Determine if we are running on 'dumb' terminals, like (X)Emacs | |
635 | # buffers, to avoid completion problems. |
|
598 | # buffers, to avoid completion problems. | |
636 | term = os.environ.get('TERM','xterm') |
|
599 | term = os.environ.get('TERM','xterm') | |
637 | self.dumb_terminal = term in ['dumb','emacs'] |
|
600 | self.dumb_terminal = term in ['dumb','emacs'] | |
638 |
|
601 | |||
639 | # Special handling of backslashes needed in win32 platforms |
|
602 | # Special handling of backslashes needed in win32 platforms | |
640 | if sys.platform == "win32": |
|
603 | if sys.platform == "win32": | |
641 | self.clean_glob = self._clean_glob_win32 |
|
604 | self.clean_glob = self._clean_glob_win32 | |
642 | else: |
|
605 | else: | |
643 | self.clean_glob = self._clean_glob |
|
606 | self.clean_glob = self._clean_glob | |
644 |
|
607 | |||
645 | #regexp to parse docstring for function signature |
|
608 | #regexp to parse docstring for function signature | |
646 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
609 | self.docstring_sig_re = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') | |
647 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
610 | self.docstring_kwd_re = re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') | |
648 | #use this if positional argument name is also needed |
|
611 | #use this if positional argument name is also needed | |
649 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') |
|
612 | #= re.compile(r'[\s|\[]*(\w+)(?:\s*=?\s*.*)') | |
650 |
|
613 | |||
651 | # All active matcher routines for completion |
|
614 | # All active matcher routines for completion | |
652 | self.matchers = [ |
|
615 | self.matchers = [ | |
653 | self.python_matches, |
|
616 | self.python_matches, | |
654 | self.file_matches, |
|
617 | self.file_matches, | |
655 | self.magic_matches, |
|
618 | self.magic_matches, | |
656 | self.python_func_kw_matches, |
|
619 | self.python_func_kw_matches, | |
657 | self.dict_key_matches, |
|
620 | self.dict_key_matches, | |
658 | ] |
|
621 | ] | |
659 |
|
622 | |||
660 | # This is set externally by InteractiveShell |
|
623 | # This is set externally by InteractiveShell | |
661 | self.custom_completers = None |
|
624 | self.custom_completers = None | |
662 |
|
625 | |||
663 | def all_completions(self, text): |
|
626 | def all_completions(self, text): | |
664 | """ |
|
627 | """ | |
665 | Wrapper around the complete method for the benefit of emacs. |
|
628 | Wrapper around the complete method for the benefit of emacs. | |
666 | """ |
|
629 | """ | |
667 | return self.complete(text)[1] |
|
630 | return self.complete(text)[1] | |
668 |
|
631 | |||
669 | def _clean_glob(self, text): |
|
632 | def _clean_glob(self, text): | |
670 | return self.glob("%s*" % text) |
|
633 | return self.glob("%s*" % text) | |
671 |
|
634 | |||
672 | def _clean_glob_win32(self,text): |
|
635 | def _clean_glob_win32(self,text): | |
673 | return [f.replace("\\","/") |
|
636 | return [f.replace("\\","/") | |
674 | for f in self.glob("%s*" % text)] |
|
637 | for f in self.glob("%s*" % text)] | |
675 |
|
638 | |||
676 | def file_matches(self, text): |
|
639 | def file_matches(self, text): | |
677 | """Match filenames, expanding ~USER type strings. |
|
640 | """Match filenames, expanding ~USER type strings. | |
678 |
|
641 | |||
679 | Most of the seemingly convoluted logic in this completer is an |
|
642 | Most of the seemingly convoluted logic in this completer is an | |
680 | attempt to handle filenames with spaces in them. And yet it's not |
|
643 | attempt to handle filenames with spaces in them. And yet it's not | |
681 | quite perfect, because Python's readline doesn't expose all of the |
|
644 | quite perfect, because Python's readline doesn't expose all of the | |
682 | GNU readline details needed for this to be done correctly. |
|
645 | GNU readline details needed for this to be done correctly. | |
683 |
|
646 | |||
684 | For a filename with a space in it, the printed completions will be |
|
647 | For a filename with a space in it, the printed completions will be | |
685 | only the parts after what's already been typed (instead of the |
|
648 | only the parts after what's already been typed (instead of the | |
686 | full completions, as is normally done). I don't think with the |
|
649 | full completions, as is normally done). I don't think with the | |
687 | current (as of Python 2.3) Python readline it's possible to do |
|
650 | current (as of Python 2.3) Python readline it's possible to do | |
688 | better.""" |
|
651 | better.""" | |
689 |
|
652 | |||
690 | # chars that require escaping with backslash - i.e. chars |
|
653 | # chars that require escaping with backslash - i.e. chars | |
691 | # that readline treats incorrectly as delimiters, but we |
|
654 | # that readline treats incorrectly as delimiters, but we | |
692 | # don't want to treat as delimiters in filename matching |
|
655 | # don't want to treat as delimiters in filename matching | |
693 | # when escaped with backslash |
|
656 | # when escaped with backslash | |
694 | if text.startswith('!'): |
|
657 | if text.startswith('!'): | |
695 | text = text[1:] |
|
658 | text = text[1:] | |
696 | text_prefix = u'!' |
|
659 | text_prefix = u'!' | |
697 | else: |
|
660 | else: | |
698 | text_prefix = u'' |
|
661 | text_prefix = u'' | |
699 |
|
662 | |||
700 | text_until_cursor = self.text_until_cursor |
|
663 | text_until_cursor = self.text_until_cursor | |
701 | # track strings with open quotes |
|
664 | # track strings with open quotes | |
702 | open_quotes = has_open_quotes(text_until_cursor) |
|
665 | open_quotes = has_open_quotes(text_until_cursor) | |
703 |
|
666 | |||
704 | if '(' in text_until_cursor or '[' in text_until_cursor: |
|
667 | if '(' in text_until_cursor or '[' in text_until_cursor: | |
705 | lsplit = text |
|
668 | lsplit = text | |
706 | else: |
|
669 | else: | |
707 | try: |
|
670 | try: | |
708 | # arg_split ~ shlex.split, but with unicode bugs fixed by us |
|
671 | # arg_split ~ shlex.split, but with unicode bugs fixed by us | |
709 | lsplit = arg_split(text_until_cursor)[-1] |
|
672 | lsplit = arg_split(text_until_cursor)[-1] | |
710 | except ValueError: |
|
673 | except ValueError: | |
711 | # typically an unmatched ", or backslash without escaped char. |
|
674 | # typically an unmatched ", or backslash without escaped char. | |
712 | if open_quotes: |
|
675 | if open_quotes: | |
713 | lsplit = text_until_cursor.split(open_quotes)[-1] |
|
676 | lsplit = text_until_cursor.split(open_quotes)[-1] | |
714 | else: |
|
677 | else: | |
715 | return [] |
|
678 | return [] | |
716 | except IndexError: |
|
679 | except IndexError: | |
717 | # tab pressed on empty line |
|
680 | # tab pressed on empty line | |
718 | lsplit = "" |
|
681 | lsplit = "" | |
719 |
|
682 | |||
720 | if not open_quotes and lsplit != protect_filename(lsplit): |
|
683 | if not open_quotes and lsplit != protect_filename(lsplit): | |
721 | # if protectables are found, do matching on the whole escaped name |
|
684 | # if protectables are found, do matching on the whole escaped name | |
722 | has_protectables = True |
|
685 | has_protectables = True | |
723 | text0,text = text,lsplit |
|
686 | text0,text = text,lsplit | |
724 | else: |
|
687 | else: | |
725 | has_protectables = False |
|
688 | has_protectables = False | |
726 | text = os.path.expanduser(text) |
|
689 | text = os.path.expanduser(text) | |
727 |
|
690 | |||
728 | if text == "": |
|
691 | if text == "": | |
729 | return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")] |
|
692 | return [text_prefix + cast_unicode_py2(protect_filename(f)) for f in self.glob("*")] | |
730 |
|
693 | |||
731 | # Compute the matches from the filesystem |
|
694 | # Compute the matches from the filesystem | |
732 | m0 = self.clean_glob(text.replace('\\','')) |
|
695 | m0 = self.clean_glob(text.replace('\\','')) | |
733 |
|
696 | |||
734 | if has_protectables: |
|
697 | if has_protectables: | |
735 | # If we had protectables, we need to revert our changes to the |
|
698 | # If we had protectables, we need to revert our changes to the | |
736 | # beginning of filename so that we don't double-write the part |
|
699 | # beginning of filename so that we don't double-write the part | |
737 | # of the filename we have so far |
|
700 | # of the filename we have so far | |
738 | len_lsplit = len(lsplit) |
|
701 | len_lsplit = len(lsplit) | |
739 | matches = [text_prefix + text0 + |
|
702 | matches = [text_prefix + text0 + | |
740 | protect_filename(f[len_lsplit:]) for f in m0] |
|
703 | protect_filename(f[len_lsplit:]) for f in m0] | |
741 | else: |
|
704 | else: | |
742 | if open_quotes: |
|
705 | if open_quotes: | |
743 | # if we have a string with an open quote, we don't need to |
|
706 | # if we have a string with an open quote, we don't need to | |
744 | # protect the names at all (and we _shouldn't_, as it |
|
707 | # protect the names at all (and we _shouldn't_, as it | |
745 | # would cause bugs when the filesystem call is made). |
|
708 | # would cause bugs when the filesystem call is made). | |
746 | matches = m0 |
|
709 | matches = m0 | |
747 | else: |
|
710 | else: | |
748 | matches = [text_prefix + |
|
711 | matches = [text_prefix + | |
749 | protect_filename(f) for f in m0] |
|
712 | protect_filename(f) for f in m0] | |
750 |
|
713 | |||
751 | # Mark directories in input list by appending '/' to their names. |
|
714 | # Mark directories in input list by appending '/' to their names. | |
752 | return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches] |
|
715 | return [cast_unicode_py2(x+'/') if os.path.isdir(x) else x for x in matches] | |
753 |
|
716 | |||
754 | def magic_matches(self, text): |
|
717 | def magic_matches(self, text): | |
755 | """Match magics""" |
|
718 | """Match magics""" | |
756 | # Get all shell magics now rather than statically, so magics loaded at |
|
719 | # Get all shell magics now rather than statically, so magics loaded at | |
757 | # runtime show up too. |
|
720 | # runtime show up too. | |
758 | lsm = self.shell.magics_manager.lsmagic() |
|
721 | lsm = self.shell.magics_manager.lsmagic() | |
759 | line_magics = lsm['line'] |
|
722 | line_magics = lsm['line'] | |
760 | cell_magics = lsm['cell'] |
|
723 | cell_magics = lsm['cell'] | |
761 | pre = self.magic_escape |
|
724 | pre = self.magic_escape | |
762 | pre2 = pre+pre |
|
725 | pre2 = pre+pre | |
763 |
|
726 | |||
764 | # Completion logic: |
|
727 | # Completion logic: | |
765 | # - user gives %%: only do cell magics |
|
728 | # - user gives %%: only do cell magics | |
766 | # - user gives %: do both line and cell magics |
|
729 | # - user gives %: do both line and cell magics | |
767 | # - no prefix: do both |
|
730 | # - no prefix: do both | |
768 | # In other words, line magics are skipped if the user gives %% explicitly |
|
731 | # In other words, line magics are skipped if the user gives %% explicitly | |
769 | bare_text = text.lstrip(pre) |
|
732 | bare_text = text.lstrip(pre) | |
770 | comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] |
|
733 | comp = [ pre2+m for m in cell_magics if m.startswith(bare_text)] | |
771 | if not text.startswith(pre2): |
|
734 | if not text.startswith(pre2): | |
772 | comp += [ pre+m for m in line_magics if m.startswith(bare_text)] |
|
735 | comp += [ pre+m for m in line_magics if m.startswith(bare_text)] | |
773 | return [cast_unicode_py2(c) for c in comp] |
|
736 | return [cast_unicode_py2(c) for c in comp] | |
774 |
|
737 | |||
775 |
|
738 | |||
776 | def python_matches(self, text): |
|
739 | def python_matches(self, text): | |
777 | """Match attributes or global python names""" |
|
740 | """Match attributes or global python names""" | |
778 | if "." in text: |
|
741 | if "." in text: | |
779 | try: |
|
742 | try: | |
780 | matches = self.attr_matches(text) |
|
743 | matches = self.attr_matches(text) | |
781 | if text.endswith('.') and self.omit__names: |
|
744 | if text.endswith('.') and self.omit__names: | |
782 | if self.omit__names == 1: |
|
745 | if self.omit__names == 1: | |
783 | # true if txt is _not_ a __ name, false otherwise: |
|
746 | # true if txt is _not_ a __ name, false otherwise: | |
784 | no__name = (lambda txt: |
|
747 | no__name = (lambda txt: | |
785 | re.match(r'.*\.__.*?__',txt) is None) |
|
748 | re.match(r'.*\.__.*?__',txt) is None) | |
786 | else: |
|
749 | else: | |
787 | # true if txt is _not_ a _ name, false otherwise: |
|
750 | # true if txt is _not_ a _ name, false otherwise: | |
788 | no__name = (lambda txt: |
|
751 | no__name = (lambda txt: | |
789 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) |
|
752 | re.match(r'\._.*?',txt[txt.rindex('.'):]) is None) | |
790 | matches = filter(no__name, matches) |
|
753 | matches = filter(no__name, matches) | |
791 | except NameError: |
|
754 | except NameError: | |
792 | # catches <undefined attributes>.<tab> |
|
755 | # catches <undefined attributes>.<tab> | |
793 | matches = [] |
|
756 | matches = [] | |
794 | else: |
|
757 | else: | |
795 | matches = self.global_matches(text) |
|
758 | matches = self.global_matches(text) | |
796 | return matches |
|
759 | return matches | |
797 |
|
760 | |||
798 | def _default_arguments_from_docstring(self, doc): |
|
761 | def _default_arguments_from_docstring(self, doc): | |
799 | """Parse the first line of docstring for call signature. |
|
762 | """Parse the first line of docstring for call signature. | |
800 |
|
763 | |||
801 | Docstring should be of the form 'min(iterable[, key=func])\n'. |
|
764 | Docstring should be of the form 'min(iterable[, key=func])\n'. | |
802 | It can also parse cython docstring of the form |
|
765 | It can also parse cython docstring of the form | |
803 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. |
|
766 | 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)'. | |
804 | """ |
|
767 | """ | |
805 | if doc is None: |
|
768 | if doc is None: | |
806 | return [] |
|
769 | return [] | |
807 |
|
770 | |||
808 | #care only the firstline |
|
771 | #care only the firstline | |
809 | line = doc.lstrip().splitlines()[0] |
|
772 | line = doc.lstrip().splitlines()[0] | |
810 |
|
773 | |||
811 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') |
|
774 | #p = re.compile(r'^[\w|\s.]+\(([^)]*)\).*') | |
812 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' |
|
775 | #'min(iterable[, key=func])\n' -> 'iterable[, key=func]' | |
813 | sig = self.docstring_sig_re.search(line) |
|
776 | sig = self.docstring_sig_re.search(line) | |
814 | if sig is None: |
|
777 | if sig is None: | |
815 | return [] |
|
778 | return [] | |
816 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] |
|
779 | # iterable[, key=func]' -> ['iterable[' ,' key=func]'] | |
817 | sig = sig.groups()[0].split(',') |
|
780 | sig = sig.groups()[0].split(',') | |
818 | ret = [] |
|
781 | ret = [] | |
819 | for s in sig: |
|
782 | for s in sig: | |
820 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') |
|
783 | #re.compile(r'[\s|\[]*(\w+)(?:\s*=\s*.*)') | |
821 | ret += self.docstring_kwd_re.findall(s) |
|
784 | ret += self.docstring_kwd_re.findall(s) | |
822 | return ret |
|
785 | return ret | |
823 |
|
786 | |||
824 | def _default_arguments(self, obj): |
|
787 | def _default_arguments(self, obj): | |
825 | """Return the list of default arguments of obj if it is callable, |
|
788 | """Return the list of default arguments of obj if it is callable, | |
826 | or empty list otherwise.""" |
|
789 | or empty list otherwise.""" | |
827 | call_obj = obj |
|
790 | call_obj = obj | |
828 | ret = [] |
|
791 | ret = [] | |
829 | if inspect.isbuiltin(obj): |
|
792 | if inspect.isbuiltin(obj): | |
830 | pass |
|
793 | pass | |
831 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): |
|
794 | elif not (inspect.isfunction(obj) or inspect.ismethod(obj)): | |
832 | if inspect.isclass(obj): |
|
795 | if inspect.isclass(obj): | |
833 | #for cython embededsignature=True the constructor docstring |
|
796 | #for cython embededsignature=True the constructor docstring | |
834 | #belongs to the object itself not __init__ |
|
797 | #belongs to the object itself not __init__ | |
835 | ret += self._default_arguments_from_docstring( |
|
798 | ret += self._default_arguments_from_docstring( | |
836 | getattr(obj, '__doc__', '')) |
|
799 | getattr(obj, '__doc__', '')) | |
837 | # for classes, check for __init__,__new__ |
|
800 | # for classes, check for __init__,__new__ | |
838 | call_obj = (getattr(obj, '__init__', None) or |
|
801 | call_obj = (getattr(obj, '__init__', None) or | |
839 | getattr(obj, '__new__', None)) |
|
802 | getattr(obj, '__new__', None)) | |
840 | # for all others, check if they are __call__able |
|
803 | # for all others, check if they are __call__able | |
841 | elif hasattr(obj, '__call__'): |
|
804 | elif hasattr(obj, '__call__'): | |
842 | call_obj = obj.__call__ |
|
805 | call_obj = obj.__call__ | |
843 | ret += self._default_arguments_from_docstring( |
|
806 | ret += self._default_arguments_from_docstring( | |
844 | getattr(call_obj, '__doc__', '')) |
|
807 | getattr(call_obj, '__doc__', '')) | |
845 |
|
808 | |||
846 | if PY3: |
|
809 | if PY3: | |
847 | _keeps = (inspect.Parameter.KEYWORD_ONLY, |
|
810 | _keeps = (inspect.Parameter.KEYWORD_ONLY, | |
848 | inspect.Parameter.POSITIONAL_OR_KEYWORD) |
|
811 | inspect.Parameter.POSITIONAL_OR_KEYWORD) | |
849 | signature = inspect.signature |
|
812 | signature = inspect.signature | |
850 | else: |
|
813 | else: | |
851 | import IPython.utils.signatures |
|
814 | import IPython.utils.signatures | |
852 | _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY, |
|
815 | _keeps = (IPython.utils.signatures.Parameter.KEYWORD_ONLY, | |
853 | IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD) |
|
816 | IPython.utils.signatures.Parameter.POSITIONAL_OR_KEYWORD) | |
854 | signature = IPython.utils.signatures.signature |
|
817 | signature = IPython.utils.signatures.signature | |
855 |
|
818 | |||
856 | try: |
|
819 | try: | |
857 | sig = signature(call_obj) |
|
820 | sig = signature(call_obj) | |
858 | ret.extend(k for k, v in sig.parameters.items() if |
|
821 | ret.extend(k for k, v in sig.parameters.items() if | |
859 | v.kind in _keeps) |
|
822 | v.kind in _keeps) | |
860 | except ValueError: |
|
823 | except ValueError: | |
861 | pass |
|
824 | pass | |
862 |
|
825 | |||
863 | return list(set(ret)) |
|
826 | return list(set(ret)) | |
864 |
|
827 | |||
865 | def python_func_kw_matches(self,text): |
|
828 | def python_func_kw_matches(self,text): | |
866 | """Match named parameters (kwargs) of the last open function""" |
|
829 | """Match named parameters (kwargs) of the last open function""" | |
867 |
|
830 | |||
868 | if "." in text: # a parameter cannot be dotted |
|
831 | if "." in text: # a parameter cannot be dotted | |
869 | return [] |
|
832 | return [] | |
870 | try: regexp = self.__funcParamsRegex |
|
833 | try: regexp = self.__funcParamsRegex | |
871 | except AttributeError: |
|
834 | except AttributeError: | |
872 | regexp = self.__funcParamsRegex = re.compile(r''' |
|
835 | regexp = self.__funcParamsRegex = re.compile(r''' | |
873 | '.*?(?<!\\)' | # single quoted strings or |
|
836 | '.*?(?<!\\)' | # single quoted strings or | |
874 | ".*?(?<!\\)" | # double quoted strings or |
|
837 | ".*?(?<!\\)" | # double quoted strings or | |
875 | \w+ | # identifier |
|
838 | \w+ | # identifier | |
876 | \S # other characters |
|
839 | \S # other characters | |
877 | ''', re.VERBOSE | re.DOTALL) |
|
840 | ''', re.VERBOSE | re.DOTALL) | |
878 | # 1. find the nearest identifier that comes before an unclosed |
|
841 | # 1. find the nearest identifier that comes before an unclosed | |
879 | # parenthesis before the cursor |
|
842 | # parenthesis before the cursor | |
880 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" |
|
843 | # e.g. for "foo (1+bar(x), pa<cursor>,a=1)", the candidate is "foo" | |
881 | tokens = regexp.findall(self.text_until_cursor) |
|
844 | tokens = regexp.findall(self.text_until_cursor) | |
882 | tokens.reverse() |
|
845 | tokens.reverse() | |
883 | iterTokens = iter(tokens); openPar = 0 |
|
846 | iterTokens = iter(tokens); openPar = 0 | |
884 |
|
847 | |||
885 | for token in iterTokens: |
|
848 | for token in iterTokens: | |
886 | if token == ')': |
|
849 | if token == ')': | |
887 | openPar -= 1 |
|
850 | openPar -= 1 | |
888 | elif token == '(': |
|
851 | elif token == '(': | |
889 | openPar += 1 |
|
852 | openPar += 1 | |
890 | if openPar > 0: |
|
853 | if openPar > 0: | |
891 | # found the last unclosed parenthesis |
|
854 | # found the last unclosed parenthesis | |
892 | break |
|
855 | break | |
893 | else: |
|
856 | else: | |
894 | return [] |
|
857 | return [] | |
895 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) |
|
858 | # 2. Concatenate dotted names ("foo.bar" for "foo.bar(x, pa" ) | |
896 | ids = [] |
|
859 | ids = [] | |
897 | isId = re.compile(r'\w+$').match |
|
860 | isId = re.compile(r'\w+$').match | |
898 |
|
861 | |||
899 | while True: |
|
862 | while True: | |
900 | try: |
|
863 | try: | |
901 | ids.append(next(iterTokens)) |
|
864 | ids.append(next(iterTokens)) | |
902 | if not isId(ids[-1]): |
|
865 | if not isId(ids[-1]): | |
903 | ids.pop(); break |
|
866 | ids.pop(); break | |
904 | if not next(iterTokens) == '.': |
|
867 | if not next(iterTokens) == '.': | |
905 | break |
|
868 | break | |
906 | except StopIteration: |
|
869 | except StopIteration: | |
907 | break |
|
870 | break | |
908 | # lookup the candidate callable matches either using global_matches |
|
871 | # lookup the candidate callable matches either using global_matches | |
909 | # or attr_matches for dotted names |
|
872 | # or attr_matches for dotted names | |
910 | if len(ids) == 1: |
|
873 | if len(ids) == 1: | |
911 | callableMatches = self.global_matches(ids[0]) |
|
874 | callableMatches = self.global_matches(ids[0]) | |
912 | else: |
|
875 | else: | |
913 | callableMatches = self.attr_matches('.'.join(ids[::-1])) |
|
876 | callableMatches = self.attr_matches('.'.join(ids[::-1])) | |
914 | argMatches = [] |
|
877 | argMatches = [] | |
915 | for callableMatch in callableMatches: |
|
878 | for callableMatch in callableMatches: | |
916 | try: |
|
879 | try: | |
917 | namedArgs = self._default_arguments(eval(callableMatch, |
|
880 | namedArgs = self._default_arguments(eval(callableMatch, | |
918 | self.namespace)) |
|
881 | self.namespace)) | |
919 | except: |
|
882 | except: | |
920 | continue |
|
883 | continue | |
921 |
|
884 | |||
922 | for namedArg in namedArgs: |
|
885 | for namedArg in namedArgs: | |
923 | if namedArg.startswith(text): |
|
886 | if namedArg.startswith(text): | |
924 | argMatches.append(u"%s=" %namedArg) |
|
887 | argMatches.append(u"%s=" %namedArg) | |
925 | return argMatches |
|
888 | return argMatches | |
926 |
|
889 | |||
927 | def dict_key_matches(self, text): |
|
890 | def dict_key_matches(self, text): | |
928 | "Match string keys in a dictionary, after e.g. 'foo[' " |
|
891 | "Match string keys in a dictionary, after e.g. 'foo[' " | |
929 | def get_keys(obj): |
|
892 | def get_keys(obj): | |
930 | # Objects can define their own completions by defining an |
|
893 | # Objects can define their own completions by defining an | |
931 | # _ipy_key_completions_() method. |
|
894 | # _ipy_key_completions_() method. | |
932 | method = get_real_method(obj, '_ipython_key_completions_') |
|
895 | method = get_real_method(obj, '_ipython_key_completions_') | |
933 | if method is not None: |
|
896 | if method is not None: | |
934 | return method() |
|
897 | return method() | |
935 |
|
898 | |||
936 | # Special case some common in-memory dict-like types |
|
899 | # Special case some common in-memory dict-like types | |
937 | if isinstance(obj, dict) or\ |
|
900 | if isinstance(obj, dict) or\ | |
938 | _safe_isinstance(obj, 'pandas', 'DataFrame'): |
|
901 | _safe_isinstance(obj, 'pandas', 'DataFrame'): | |
939 | try: |
|
902 | try: | |
940 | return list(obj.keys()) |
|
903 | return list(obj.keys()) | |
941 | except Exception: |
|
904 | except Exception: | |
942 | return [] |
|
905 | return [] | |
943 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ |
|
906 | elif _safe_isinstance(obj, 'numpy', 'ndarray') or\ | |
944 | _safe_isinstance(obj, 'numpy', 'void'): |
|
907 | _safe_isinstance(obj, 'numpy', 'void'): | |
945 | return obj.dtype.names or [] |
|
908 | return obj.dtype.names or [] | |
946 | return [] |
|
909 | return [] | |
947 |
|
910 | |||
948 | try: |
|
911 | try: | |
949 | regexps = self.__dict_key_regexps |
|
912 | regexps = self.__dict_key_regexps | |
950 | except AttributeError: |
|
913 | except AttributeError: | |
951 | dict_key_re_fmt = r'''(?x) |
|
914 | dict_key_re_fmt = r'''(?x) | |
952 | ( # match dict-referring expression wrt greedy setting |
|
915 | ( # match dict-referring expression wrt greedy setting | |
953 | %s |
|
916 | %s | |
954 | ) |
|
917 | ) | |
955 | \[ # open bracket |
|
918 | \[ # open bracket | |
956 | \s* # and optional whitespace |
|
919 | \s* # and optional whitespace | |
957 | ([uUbB]? # string prefix (r not handled) |
|
920 | ([uUbB]? # string prefix (r not handled) | |
958 | (?: # unclosed string |
|
921 | (?: # unclosed string | |
959 | '(?:[^']|(?<!\\)\\')* |
|
922 | '(?:[^']|(?<!\\)\\')* | |
960 | | |
|
923 | | | |
961 | "(?:[^"]|(?<!\\)\\")* |
|
924 | "(?:[^"]|(?<!\\)\\")* | |
962 | ) |
|
925 | ) | |
963 | )? |
|
926 | )? | |
964 | $ |
|
927 | $ | |
965 | ''' |
|
928 | ''' | |
966 | regexps = self.__dict_key_regexps = { |
|
929 | regexps = self.__dict_key_regexps = { | |
967 | False: re.compile(dict_key_re_fmt % ''' |
|
930 | False: re.compile(dict_key_re_fmt % ''' | |
968 | # identifiers separated by . |
|
931 | # identifiers separated by . | |
969 | (?!\d)\w+ |
|
932 | (?!\d)\w+ | |
970 | (?:\.(?!\d)\w+)* |
|
933 | (?:\.(?!\d)\w+)* | |
971 | '''), |
|
934 | '''), | |
972 | True: re.compile(dict_key_re_fmt % ''' |
|
935 | True: re.compile(dict_key_re_fmt % ''' | |
973 | .+ |
|
936 | .+ | |
974 | ''') |
|
937 | ''') | |
975 | } |
|
938 | } | |
976 |
|
939 | |||
977 | match = regexps[self.greedy].search(self.text_until_cursor) |
|
940 | match = regexps[self.greedy].search(self.text_until_cursor) | |
978 | if match is None: |
|
941 | if match is None: | |
979 | return [] |
|
942 | return [] | |
980 |
|
943 | |||
981 | expr, prefix = match.groups() |
|
944 | expr, prefix = match.groups() | |
982 | try: |
|
945 | try: | |
983 | obj = eval(expr, self.namespace) |
|
946 | obj = eval(expr, self.namespace) | |
984 | except Exception: |
|
947 | except Exception: | |
985 | try: |
|
948 | try: | |
986 | obj = eval(expr, self.global_namespace) |
|
949 | obj = eval(expr, self.global_namespace) | |
987 | except Exception: |
|
950 | except Exception: | |
988 | return [] |
|
951 | return [] | |
989 |
|
952 | |||
990 | keys = get_keys(obj) |
|
953 | keys = get_keys(obj) | |
991 | if not keys: |
|
954 | if not keys: | |
992 | return keys |
|
955 | return keys | |
993 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) |
|
956 | closing_quote, token_offset, matches = match_dict_keys(keys, prefix, self.splitter.delims) | |
994 | if not matches: |
|
957 | if not matches: | |
995 | return matches |
|
958 | return matches | |
996 |
|
959 | |||
997 | # get the cursor position of |
|
960 | # get the cursor position of | |
998 | # - the text being completed |
|
961 | # - the text being completed | |
999 | # - the start of the key text |
|
962 | # - the start of the key text | |
1000 | # - the start of the completion |
|
963 | # - the start of the completion | |
1001 | text_start = len(self.text_until_cursor) - len(text) |
|
964 | text_start = len(self.text_until_cursor) - len(text) | |
1002 | if prefix: |
|
965 | if prefix: | |
1003 | key_start = match.start(2) |
|
966 | key_start = match.start(2) | |
1004 | completion_start = key_start + token_offset |
|
967 | completion_start = key_start + token_offset | |
1005 | else: |
|
968 | else: | |
1006 | key_start = completion_start = match.end() |
|
969 | key_start = completion_start = match.end() | |
1007 |
|
970 | |||
1008 | # grab the leading prefix, to make sure all completions start with `text` |
|
971 | # grab the leading prefix, to make sure all completions start with `text` | |
1009 | if text_start > key_start: |
|
972 | if text_start > key_start: | |
1010 | leading = '' |
|
973 | leading = '' | |
1011 | else: |
|
974 | else: | |
1012 | leading = text[text_start:completion_start] |
|
975 | leading = text[text_start:completion_start] | |
1013 |
|
976 | |||
1014 | # the index of the `[` character |
|
977 | # the index of the `[` character | |
1015 | bracket_idx = match.end(1) |
|
978 | bracket_idx = match.end(1) | |
1016 |
|
979 | |||
1017 | # append closing quote and bracket as appropriate |
|
980 | # append closing quote and bracket as appropriate | |
1018 | # this is *not* appropriate if the opening quote or bracket is outside |
|
981 | # this is *not* appropriate if the opening quote or bracket is outside | |
1019 | # the text given to this method |
|
982 | # the text given to this method | |
1020 | suf = '' |
|
983 | suf = '' | |
1021 | continuation = self.line_buffer[len(self.text_until_cursor):] |
|
984 | continuation = self.line_buffer[len(self.text_until_cursor):] | |
1022 | if key_start > text_start and closing_quote: |
|
985 | if key_start > text_start and closing_quote: | |
1023 | # quotes were opened inside text, maybe close them |
|
986 | # quotes were opened inside text, maybe close them | |
1024 | if continuation.startswith(closing_quote): |
|
987 | if continuation.startswith(closing_quote): | |
1025 | continuation = continuation[len(closing_quote):] |
|
988 | continuation = continuation[len(closing_quote):] | |
1026 | else: |
|
989 | else: | |
1027 | suf += closing_quote |
|
990 | suf += closing_quote | |
1028 | if bracket_idx > text_start: |
|
991 | if bracket_idx > text_start: | |
1029 | # brackets were opened inside text, maybe close them |
|
992 | # brackets were opened inside text, maybe close them | |
1030 | if not continuation.startswith(']'): |
|
993 | if not continuation.startswith(']'): | |
1031 | suf += ']' |
|
994 | suf += ']' | |
1032 |
|
995 | |||
1033 | return [leading + k + suf for k in matches] |
|
996 | return [leading + k + suf for k in matches] | |
1034 |
|
997 | |||
1035 | def unicode_name_matches(self, text): |
|
998 | def unicode_name_matches(self, text): | |
1036 | u"""Match Latex-like syntax for unicode characters base |
|
999 | u"""Match Latex-like syntax for unicode characters base | |
1037 | on the name of the character. |
|
1000 | on the name of the character. | |
1038 |
|
1001 | |||
1039 | This does \\GREEK SMALL LETTER ETA -> Ξ· |
|
1002 | This does \\GREEK SMALL LETTER ETA -> Ξ· | |
1040 |
|
1003 | |||
1041 | Works only on valid python 3 identifier, or on combining characters that |
|
1004 | Works only on valid python 3 identifier, or on combining characters that | |
1042 | will combine to form a valid identifier. |
|
1005 | will combine to form a valid identifier. | |
1043 |
|
1006 | |||
1044 | Used on Python 3 only. |
|
1007 | Used on Python 3 only. | |
1045 | """ |
|
1008 | """ | |
1046 | slashpos = text.rfind('\\') |
|
1009 | slashpos = text.rfind('\\') | |
1047 | if slashpos > -1: |
|
1010 | if slashpos > -1: | |
1048 | s = text[slashpos+1:] |
|
1011 | s = text[slashpos+1:] | |
1049 | try : |
|
1012 | try : | |
1050 | unic = unicodedata.lookup(s) |
|
1013 | unic = unicodedata.lookup(s) | |
1051 | # allow combining chars |
|
1014 | # allow combining chars | |
1052 | if ('a'+unic).isidentifier(): |
|
1015 | if ('a'+unic).isidentifier(): | |
1053 | return '\\'+s,[unic] |
|
1016 | return '\\'+s,[unic] | |
1054 | except KeyError: |
|
1017 | except KeyError: | |
1055 | pass |
|
1018 | pass | |
1056 | return u'', [] |
|
1019 | return u'', [] | |
1057 |
|
1020 | |||
1058 |
|
1021 | |||
1059 |
|
1022 | |||
1060 |
|
1023 | |||
1061 | def latex_matches(self, text): |
|
1024 | def latex_matches(self, text): | |
1062 | u"""Match Latex syntax for unicode characters. |
|
1025 | u"""Match Latex syntax for unicode characters. | |
1063 |
|
1026 | |||
1064 | This does both \\alp -> \\alpha and \\alpha -> Ξ± |
|
1027 | This does both \\alp -> \\alpha and \\alpha -> Ξ± | |
1065 |
|
1028 | |||
1066 | Used on Python 3 only. |
|
1029 | Used on Python 3 only. | |
1067 | """ |
|
1030 | """ | |
1068 | slashpos = text.rfind('\\') |
|
1031 | slashpos = text.rfind('\\') | |
1069 | if slashpos > -1: |
|
1032 | if slashpos > -1: | |
1070 | s = text[slashpos:] |
|
1033 | s = text[slashpos:] | |
1071 | if s in latex_symbols: |
|
1034 | if s in latex_symbols: | |
1072 | # Try to complete a full latex symbol to unicode |
|
1035 | # Try to complete a full latex symbol to unicode | |
1073 | # \\alpha -> Ξ± |
|
1036 | # \\alpha -> Ξ± | |
1074 | return s, [latex_symbols[s]] |
|
1037 | return s, [latex_symbols[s]] | |
1075 | else: |
|
1038 | else: | |
1076 | # If a user has partially typed a latex symbol, give them |
|
1039 | # If a user has partially typed a latex symbol, give them | |
1077 | # a full list of options \al -> [\aleph, \alpha] |
|
1040 | # a full list of options \al -> [\aleph, \alpha] | |
1078 | matches = [k for k in latex_symbols if k.startswith(s)] |
|
1041 | matches = [k for k in latex_symbols if k.startswith(s)] | |
1079 | return s, matches |
|
1042 | return s, matches | |
1080 | return u'', [] |
|
1043 | return u'', [] | |
1081 |
|
1044 | |||
1082 | def dispatch_custom_completer(self, text): |
|
1045 | def dispatch_custom_completer(self, text): | |
1083 | if not self.custom_completers: |
|
1046 | if not self.custom_completers: | |
1084 | return |
|
1047 | return | |
1085 |
|
1048 | |||
1086 | line = self.line_buffer |
|
1049 | line = self.line_buffer | |
1087 | if not line.strip(): |
|
1050 | if not line.strip(): | |
1088 | return None |
|
1051 | return None | |
1089 |
|
1052 | |||
1090 | # Create a little structure to pass all the relevant information about |
|
1053 | # Create a little structure to pass all the relevant information about | |
1091 | # the current completion to any custom completer. |
|
1054 | # the current completion to any custom completer. | |
1092 | event = Bunch() |
|
1055 | event = Bunch() | |
1093 | event.line = line |
|
1056 | event.line = line | |
1094 | event.symbol = text |
|
1057 | event.symbol = text | |
1095 | cmd = line.split(None,1)[0] |
|
1058 | cmd = line.split(None,1)[0] | |
1096 | event.command = cmd |
|
1059 | event.command = cmd | |
1097 | event.text_until_cursor = self.text_until_cursor |
|
1060 | event.text_until_cursor = self.text_until_cursor | |
1098 |
|
1061 | |||
1099 | # for foo etc, try also to find completer for %foo |
|
1062 | # for foo etc, try also to find completer for %foo | |
1100 | if not cmd.startswith(self.magic_escape): |
|
1063 | if not cmd.startswith(self.magic_escape): | |
1101 | try_magic = self.custom_completers.s_matches( |
|
1064 | try_magic = self.custom_completers.s_matches( | |
1102 | self.magic_escape + cmd) |
|
1065 | self.magic_escape + cmd) | |
1103 | else: |
|
1066 | else: | |
1104 | try_magic = [] |
|
1067 | try_magic = [] | |
1105 |
|
1068 | |||
1106 | for c in itertools.chain(self.custom_completers.s_matches(cmd), |
|
1069 | for c in itertools.chain(self.custom_completers.s_matches(cmd), | |
1107 | try_magic, |
|
1070 | try_magic, | |
1108 | self.custom_completers.flat_matches(self.text_until_cursor)): |
|
1071 | self.custom_completers.flat_matches(self.text_until_cursor)): | |
1109 | try: |
|
1072 | try: | |
1110 | res = c(event) |
|
1073 | res = c(event) | |
1111 | if res: |
|
1074 | if res: | |
1112 | # first, try case sensitive match |
|
1075 | # first, try case sensitive match | |
1113 | withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)] |
|
1076 | withcase = [cast_unicode_py2(r) for r in res if r.startswith(text)] | |
1114 | if withcase: |
|
1077 | if withcase: | |
1115 | return withcase |
|
1078 | return withcase | |
1116 | # if none, then case insensitive ones are ok too |
|
1079 | # if none, then case insensitive ones are ok too | |
1117 | text_low = text.lower() |
|
1080 | text_low = text.lower() | |
1118 | return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)] |
|
1081 | return [cast_unicode_py2(r) for r in res if r.lower().startswith(text_low)] | |
1119 | except TryNext: |
|
1082 | except TryNext: | |
1120 | pass |
|
1083 | pass | |
1121 |
|
1084 | |||
1122 | return None |
|
1085 | return None | |
1123 |
|
1086 | |||
1124 | def complete(self, text=None, line_buffer=None, cursor_pos=None): |
|
1087 | def complete(self, text=None, line_buffer=None, cursor_pos=None): | |
1125 | """Find completions for the given text and line context. |
|
1088 | """Find completions for the given text and line context. | |
1126 |
|
1089 | |||
1127 | Note that both the text and the line_buffer are optional, but at least |
|
1090 | Note that both the text and the line_buffer are optional, but at least | |
1128 | one of them must be given. |
|
1091 | one of them must be given. | |
1129 |
|
1092 | |||
1130 | Parameters |
|
1093 | Parameters | |
1131 | ---------- |
|
1094 | ---------- | |
1132 | text : string, optional |
|
1095 | text : string, optional | |
1133 | Text to perform the completion on. If not given, the line buffer |
|
1096 | Text to perform the completion on. If not given, the line buffer | |
1134 | is split using the instance's CompletionSplitter object. |
|
1097 | is split using the instance's CompletionSplitter object. | |
1135 |
|
1098 | |||
1136 | line_buffer : string, optional |
|
1099 | line_buffer : string, optional | |
1137 | If not given, the completer attempts to obtain the current line |
|
1100 | If not given, the completer attempts to obtain the current line | |
1138 | buffer via readline. This keyword allows clients which are |
|
1101 | buffer via readline. This keyword allows clients which are | |
1139 | requesting for text completions in non-readline contexts to inform |
|
1102 | requesting for text completions in non-readline contexts to inform | |
1140 | the completer of the entire text. |
|
1103 | the completer of the entire text. | |
1141 |
|
1104 | |||
1142 | cursor_pos : int, optional |
|
1105 | cursor_pos : int, optional | |
1143 | Index of the cursor in the full line buffer. Should be provided by |
|
1106 | Index of the cursor in the full line buffer. Should be provided by | |
1144 | remote frontends where kernel has no access to frontend state. |
|
1107 | remote frontends where kernel has no access to frontend state. | |
1145 |
|
1108 | |||
1146 | Returns |
|
1109 | Returns | |
1147 | ------- |
|
1110 | ------- | |
1148 | text : str |
|
1111 | text : str | |
1149 | Text that was actually used in the completion. |
|
1112 | Text that was actually used in the completion. | |
1150 |
|
1113 | |||
1151 | matches : list |
|
1114 | matches : list | |
1152 | A list of completion matches. |
|
1115 | A list of completion matches. | |
1153 | """ |
|
1116 | """ | |
1154 | # if the cursor position isn't given, the only sane assumption we can |
|
1117 | # if the cursor position isn't given, the only sane assumption we can | |
1155 | # make is that it's at the end of the line (the common case) |
|
1118 | # make is that it's at the end of the line (the common case) | |
1156 | if cursor_pos is None: |
|
1119 | if cursor_pos is None: | |
1157 | cursor_pos = len(line_buffer) if text is None else len(text) |
|
1120 | cursor_pos = len(line_buffer) if text is None else len(text) | |
1158 |
|
1121 | |||
1159 | if PY3: |
|
1122 | if PY3: | |
1160 |
|
1123 | |||
1161 | base_text = text if not line_buffer else line_buffer[:cursor_pos] |
|
1124 | base_text = text if not line_buffer else line_buffer[:cursor_pos] | |
1162 | latex_text, latex_matches = self.latex_matches(base_text) |
|
1125 | latex_text, latex_matches = self.latex_matches(base_text) | |
1163 | if latex_matches: |
|
1126 | if latex_matches: | |
1164 | return latex_text, latex_matches |
|
1127 | return latex_text, latex_matches | |
1165 | name_text = '' |
|
1128 | name_text = '' | |
1166 | name_matches = [] |
|
1129 | name_matches = [] | |
1167 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches): |
|
1130 | for meth in (self.unicode_name_matches, back_latex_name_matches, back_unicode_name_matches): | |
1168 | name_text, name_matches = meth(base_text) |
|
1131 | name_text, name_matches = meth(base_text) | |
1169 | if name_text: |
|
1132 | if name_text: | |
1170 | return name_text, name_matches |
|
1133 | return name_text, name_matches | |
1171 |
|
1134 | |||
1172 | # if text is either None or an empty string, rely on the line buffer |
|
1135 | # if text is either None or an empty string, rely on the line buffer | |
1173 | if not text: |
|
1136 | if not text: | |
1174 | text = self.splitter.split_line(line_buffer, cursor_pos) |
|
1137 | text = self.splitter.split_line(line_buffer, cursor_pos) | |
1175 |
|
1138 | |||
1176 | # If no line buffer is given, assume the input text is all there was |
|
1139 | # If no line buffer is given, assume the input text is all there was | |
1177 | if line_buffer is None: |
|
1140 | if line_buffer is None: | |
1178 | line_buffer = text |
|
1141 | line_buffer = text | |
1179 |
|
1142 | |||
1180 | self.line_buffer = line_buffer |
|
1143 | self.line_buffer = line_buffer | |
1181 | self.text_until_cursor = self.line_buffer[:cursor_pos] |
|
1144 | self.text_until_cursor = self.line_buffer[:cursor_pos] | |
1182 |
|
1145 | |||
1183 | # Start with a clean slate of completions |
|
1146 | # Start with a clean slate of completions | |
1184 | self.matches[:] = [] |
|
1147 | self.matches[:] = [] | |
1185 | custom_res = self.dispatch_custom_completer(text) |
|
1148 | custom_res = self.dispatch_custom_completer(text) | |
1186 | if custom_res is not None: |
|
1149 | if custom_res is not None: | |
1187 | # did custom completers produce something? |
|
1150 | # did custom completers produce something? | |
1188 | self.matches = custom_res |
|
1151 | self.matches = custom_res | |
1189 | else: |
|
1152 | else: | |
1190 | # Extend the list of completions with the results of each |
|
1153 | # Extend the list of completions with the results of each | |
1191 | # matcher, so we return results to the user from all |
|
1154 | # matcher, so we return results to the user from all | |
1192 | # namespaces. |
|
1155 | # namespaces. | |
1193 | if self.merge_completions: |
|
1156 | if self.merge_completions: | |
1194 | self.matches = [] |
|
1157 | self.matches = [] | |
1195 | for matcher in self.matchers: |
|
1158 | for matcher in self.matchers: | |
1196 | try: |
|
1159 | try: | |
1197 | self.matches.extend(matcher(text)) |
|
1160 | self.matches.extend(matcher(text)) | |
1198 | except: |
|
1161 | except: | |
1199 | # Show the ugly traceback if the matcher causes an |
|
1162 | # Show the ugly traceback if the matcher causes an | |
1200 | # exception, but do NOT crash the kernel! |
|
1163 | # exception, but do NOT crash the kernel! | |
1201 | sys.excepthook(*sys.exc_info()) |
|
1164 | sys.excepthook(*sys.exc_info()) | |
1202 | else: |
|
1165 | else: | |
1203 | for matcher in self.matchers: |
|
1166 | for matcher in self.matchers: | |
1204 | self.matches = matcher(text) |
|
1167 | self.matches = matcher(text) | |
1205 | if self.matches: |
|
1168 | if self.matches: | |
1206 | break |
|
1169 | break | |
1207 | # FIXME: we should extend our api to return a dict with completions for |
|
1170 | # FIXME: we should extend our api to return a dict with completions for | |
1208 | # different types of objects. The rlcomplete() method could then |
|
1171 | # different types of objects. The rlcomplete() method could then | |
1209 | # simply collapse the dict into a list for readline, but we'd have |
|
1172 | # simply collapse the dict into a list for readline, but we'd have | |
1210 | # richer completion semantics in other evironments. |
|
1173 | # richer completion semantics in other evironments. | |
1211 | self.matches = sorted(set(self.matches), key=completions_sorting_key) |
|
1174 | self.matches = sorted(set(self.matches), key=completions_sorting_key) | |
1212 |
|
1175 | |||
1213 | return text, self.matches |
|
1176 | return text, self.matches | |
1214 |
|
||||
1215 | def rlcomplete(self, text, state): |
|
|||
1216 | """Return the state-th possible completion for 'text'. |
|
|||
1217 |
|
||||
1218 | This is called successively with state == 0, 1, 2, ... until it |
|
|||
1219 | returns None. The completion should begin with 'text'. |
|
|||
1220 |
|
||||
1221 | Parameters |
|
|||
1222 | ---------- |
|
|||
1223 | text : string |
|
|||
1224 | Text to perform the completion on. |
|
|||
1225 |
|
||||
1226 | state : int |
|
|||
1227 | Counter used by readline. |
|
|||
1228 | """ |
|
|||
1229 | if state==0: |
|
|||
1230 |
|
||||
1231 | self.line_buffer = line_buffer = self.readline.get_line_buffer() |
|
|||
1232 | cursor_pos = self.readline.get_endidx() |
|
|||
1233 |
|
||||
1234 | #io.rprint("\nRLCOMPLETE: %r %r %r" % |
|
|||
1235 | # (text, line_buffer, cursor_pos) ) # dbg |
|
|||
1236 |
|
||||
1237 | # if there is only a tab on a line with only whitespace, instead of |
|
|||
1238 | # the mostly useless 'do you want to see all million completions' |
|
|||
1239 | # message, just do the right thing and give the user his tab! |
|
|||
1240 | # Incidentally, this enables pasting of tabbed text from an editor |
|
|||
1241 | # (as long as autoindent is off). |
|
|||
1242 |
|
||||
1243 | # It should be noted that at least pyreadline still shows file |
|
|||
1244 | # completions - is there a way around it? |
|
|||
1245 |
|
||||
1246 | # don't apply this on 'dumb' terminals, such as emacs buffers, so |
|
|||
1247 | # we don't interfere with their own tab-completion mechanism. |
|
|||
1248 | if not (self.dumb_terminal or line_buffer.strip()): |
|
|||
1249 | self.readline.insert_text('\t') |
|
|||
1250 | sys.stdout.flush() |
|
|||
1251 | return None |
|
|||
1252 |
|
||||
1253 | # Note: debugging exceptions that may occur in completion is very |
|
|||
1254 | # tricky, because readline unconditionally silences them. So if |
|
|||
1255 | # during development you suspect a bug in the completion code, turn |
|
|||
1256 | # this flag on temporarily by uncommenting the second form (don't |
|
|||
1257 | # flip the value in the first line, as the '# dbg' marker can be |
|
|||
1258 | # automatically detected and is used elsewhere). |
|
|||
1259 | DEBUG = False |
|
|||
1260 | #DEBUG = True # dbg |
|
|||
1261 | if DEBUG: |
|
|||
1262 | try: |
|
|||
1263 | self.complete(text, line_buffer, cursor_pos) |
|
|||
1264 | except: |
|
|||
1265 | import traceback; traceback.print_exc() |
|
|||
1266 | else: |
|
|||
1267 | # The normal production version is here |
|
|||
1268 |
|
||||
1269 | # This method computes the self.matches array |
|
|||
1270 | self.complete(text, line_buffer, cursor_pos) |
|
|||
1271 |
|
||||
1272 | try: |
|
|||
1273 | return self.matches[state] |
|
|||
1274 | except IndexError: |
|
|||
1275 | return None |
|
|||
1276 |
|
1 | NO CONTENT: modified file |
|
NO CONTENT: modified file | ||
The requested commit or file is too big and content was truncated. Show full diff |
@@ -1,355 +1,351 b'' | |||||
1 | # -*- coding: utf-8 -*- |
|
1 | # -*- coding: utf-8 -*- | |
2 | """Usage information for the main IPython applications. |
|
2 | """Usage information for the main IPython applications. | |
3 | """ |
|
3 | """ | |
4 | #----------------------------------------------------------------------------- |
|
4 | #----------------------------------------------------------------------------- | |
5 | # Copyright (C) 2008-2011 The IPython Development Team |
|
5 | # Copyright (C) 2008-2011 The IPython Development Team | |
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> |
|
6 | # Copyright (C) 2001-2007 Fernando Perez. <fperez@colorado.edu> | |
7 | # |
|
7 | # | |
8 | # Distributed under the terms of the BSD License. The full license is in |
|
8 | # Distributed under the terms of the BSD License. The full license is in | |
9 | # the file COPYING, distributed as part of this software. |
|
9 | # the file COPYING, distributed as part of this software. | |
10 | #----------------------------------------------------------------------------- |
|
10 | #----------------------------------------------------------------------------- | |
11 |
|
11 | |||
12 | import sys |
|
12 | import sys | |
13 | from IPython.core import release |
|
13 | from IPython.core import release | |
14 |
|
14 | |||
15 | cl_usage = """\ |
|
15 | cl_usage = """\ | |
16 | ========= |
|
16 | ========= | |
17 | IPython |
|
17 | IPython | |
18 | ========= |
|
18 | ========= | |
19 |
|
19 | |||
20 | Tools for Interactive Computing in Python |
|
20 | Tools for Interactive Computing in Python | |
21 | ========================================= |
|
21 | ========================================= | |
22 |
|
22 | |||
23 | A Python shell with automatic history (input and output), dynamic object |
|
23 | A Python shell with automatic history (input and output), dynamic object | |
24 | introspection, easier configuration, command completion, access to the |
|
24 | introspection, easier configuration, command completion, access to the | |
25 | system shell and more. IPython can also be embedded in running programs. |
|
25 | system shell and more. IPython can also be embedded in running programs. | |
26 |
|
26 | |||
27 |
|
27 | |||
28 | Usage |
|
28 | Usage | |
29 |
|
29 | |||
30 | ipython [subcommand] [options] [-c cmd | -m mod | file] [--] [arg] ... |
|
30 | ipython [subcommand] [options] [-c cmd | -m mod | file] [--] [arg] ... | |
31 |
|
31 | |||
32 | If invoked with no options, it executes the file and exits, passing the |
|
32 | If invoked with no options, it executes the file and exits, passing the | |
33 | remaining arguments to the script, just as if you had specified the same |
|
33 | remaining arguments to the script, just as if you had specified the same | |
34 | command with python. You may need to specify `--` before args to be passed |
|
34 | command with python. You may need to specify `--` before args to be passed | |
35 | to the script, to prevent IPython from attempting to parse them. If you |
|
35 | to the script, to prevent IPython from attempting to parse them. If you | |
36 | specify the option `-i` before the filename, it will enter an interactive |
|
36 | specify the option `-i` before the filename, it will enter an interactive | |
37 | IPython session after running the script, rather than exiting. Files ending |
|
37 | IPython session after running the script, rather than exiting. Files ending | |
38 | in .py will be treated as normal Python, but files ending in .ipy can |
|
38 | in .py will be treated as normal Python, but files ending in .ipy can | |
39 | contain special IPython syntax (magic commands, shell expansions, etc.). |
|
39 | contain special IPython syntax (magic commands, shell expansions, etc.). | |
40 |
|
40 | |||
41 | Almost all configuration in IPython is available via the command-line. Do |
|
41 | Almost all configuration in IPython is available via the command-line. Do | |
42 | `ipython --help-all` to see all available options. For persistent |
|
42 | `ipython --help-all` to see all available options. For persistent | |
43 | configuration, look into your `ipython_config.py` configuration file for |
|
43 | configuration, look into your `ipython_config.py` configuration file for | |
44 | details. |
|
44 | details. | |
45 |
|
45 | |||
46 | This file is typically installed in the `IPYTHONDIR` directory, and there |
|
46 | This file is typically installed in the `IPYTHONDIR` directory, and there | |
47 | is a separate configuration directory for each profile. The default profile |
|
47 | is a separate configuration directory for each profile. The default profile | |
48 | directory will be located in $IPYTHONDIR/profile_default. IPYTHONDIR |
|
48 | directory will be located in $IPYTHONDIR/profile_default. IPYTHONDIR | |
49 | defaults to to `$HOME/.ipython`. For Windows users, $HOME resolves to |
|
49 | defaults to to `$HOME/.ipython`. For Windows users, $HOME resolves to | |
50 | C:\\Users\\YourUserName in most instances. |
|
50 | C:\\Users\\YourUserName in most instances. | |
51 |
|
51 | |||
52 | To initialize a profile with the default configuration file, do:: |
|
52 | To initialize a profile with the default configuration file, do:: | |
53 |
|
53 | |||
54 | $> ipython profile create |
|
54 | $> ipython profile create | |
55 |
|
55 | |||
56 | and start editing `IPYTHONDIR/profile_default/ipython_config.py` |
|
56 | and start editing `IPYTHONDIR/profile_default/ipython_config.py` | |
57 |
|
57 | |||
58 | In IPython's documentation, we will refer to this directory as |
|
58 | In IPython's documentation, we will refer to this directory as | |
59 | `IPYTHONDIR`, you can change its default location by creating an |
|
59 | `IPYTHONDIR`, you can change its default location by creating an | |
60 | environment variable with this name and setting it to the desired path. |
|
60 | environment variable with this name and setting it to the desired path. | |
61 |
|
61 | |||
62 | For more information, see the manual available in HTML and PDF in your |
|
62 | For more information, see the manual available in HTML and PDF in your | |
63 | installation, or online at http://ipython.org/documentation.html. |
|
63 | installation, or online at http://ipython.org/documentation.html. | |
64 | """ |
|
64 | """ | |
65 |
|
65 | |||
66 | interactive_usage = """ |
|
66 | interactive_usage = """ | |
67 | IPython -- An enhanced Interactive Python |
|
67 | IPython -- An enhanced Interactive Python | |
68 | ========================================= |
|
68 | ========================================= | |
69 |
|
69 | |||
70 | IPython offers a combination of convenient shell features, special commands |
|
70 | IPython offers a combination of convenient shell features, special commands | |
71 | and a history mechanism for both input (command history) and output (results |
|
71 | and a history mechanism for both input (command history) and output (results | |
72 | caching, similar to Mathematica). It is intended to be a fully compatible |
|
72 | caching, similar to Mathematica). It is intended to be a fully compatible | |
73 | replacement for the standard Python interpreter, while offering vastly |
|
73 | replacement for the standard Python interpreter, while offering vastly | |
74 | improved functionality and flexibility. |
|
74 | improved functionality and flexibility. | |
75 |
|
75 | |||
76 | At your system command line, type 'ipython -h' to see the command line |
|
76 | At your system command line, type 'ipython -h' to see the command line | |
77 | options available. This document only describes interactive features. |
|
77 | options available. This document only describes interactive features. | |
78 |
|
78 | |||
79 | MAIN FEATURES |
|
79 | MAIN FEATURES | |
80 | ------------- |
|
80 | ------------- | |
81 |
|
81 | |||
82 | * Access to the standard Python help. As of Python 2.1, a help system is |
|
82 | * Access to the standard Python help. As of Python 2.1, a help system is | |
83 | available with access to object docstrings and the Python manuals. Simply |
|
83 | available with access to object docstrings and the Python manuals. Simply | |
84 | type 'help' (no quotes) to access it. |
|
84 | type 'help' (no quotes) to access it. | |
85 |
|
85 | |||
86 | * Magic commands: type %magic for information on the magic subsystem. |
|
86 | * Magic commands: type %magic for information on the magic subsystem. | |
87 |
|
87 | |||
88 | * System command aliases, via the %alias command or the configuration file(s). |
|
88 | * System command aliases, via the %alias command or the configuration file(s). | |
89 |
|
89 | |||
90 | * Dynamic object information: |
|
90 | * Dynamic object information: | |
91 |
|
91 | |||
92 | Typing ?word or word? prints detailed information about an object. If |
|
92 | Typing ?word or word? prints detailed information about an object. If | |
93 | certain strings in the object are too long (docstrings, code, etc.) they get |
|
93 | certain strings in the object are too long (docstrings, code, etc.) they get | |
94 | snipped in the center for brevity. |
|
94 | snipped in the center for brevity. | |
95 |
|
95 | |||
96 | Typing ??word or word?? gives access to the full information without |
|
96 | Typing ??word or word?? gives access to the full information without | |
97 | snipping long strings. Long strings are sent to the screen through the less |
|
97 | snipping long strings. Long strings are sent to the screen through the less | |
98 | pager if longer than the screen, printed otherwise. |
|
98 | pager if longer than the screen, printed otherwise. | |
99 |
|
99 | |||
100 | The ?/?? system gives access to the full source code for any object (if |
|
100 | The ?/?? system gives access to the full source code for any object (if | |
101 | available), shows function prototypes and other useful information. |
|
101 | available), shows function prototypes and other useful information. | |
102 |
|
102 | |||
103 | If you just want to see an object's docstring, type '%pdoc object' (without |
|
103 | If you just want to see an object's docstring, type '%pdoc object' (without | |
104 | quotes, and without % if you have automagic on). |
|
104 | quotes, and without % if you have automagic on). | |
105 |
|
105 | |||
106 | * Completion in the local namespace, by typing TAB at the prompt. |
|
106 | * Completion in the local namespace, by typing TAB at the prompt. | |
107 |
|
107 | |||
108 | At any time, hitting tab will complete any available python commands or |
|
108 | At any time, hitting tab will complete any available python commands or | |
109 | variable names, and show you a list of the possible completions if there's |
|
109 | variable names, and show you a list of the possible completions if there's | |
110 | no unambiguous one. It will also complete filenames in the current directory. |
|
110 | no unambiguous one. It will also complete filenames in the current directory. | |
111 |
|
111 | |||
112 | This feature requires the readline and rlcomplete modules, so it won't work |
|
112 | * Search previous command history in two ways: | |
113 | if your Python lacks readline support (such as under Windows). |
|
|||
114 |
|
113 | |||
115 | * Search previous command history in two ways (also requires readline): |
|
114 | - Start typing, and then use Ctrl-p (previous, up) and Ctrl-n (next,down) to | |
116 |
|
||||
117 | - Start typing, and then use Ctrl-p (previous,up) and Ctrl-n (next,down) to |
|
|||
118 | search through only the history items that match what you've typed so |
|
115 | search through only the history items that match what you've typed so | |
119 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like |
|
116 | far. If you use Ctrl-p/Ctrl-n at a blank prompt, they just behave like | |
120 | normal arrow keys. |
|
117 | normal arrow keys. | |
121 |
|
118 | |||
122 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches |
|
119 | - Hit Ctrl-r: opens a search prompt. Begin typing and the system searches | |
123 | your history for lines that match what you've typed so far, completing as |
|
120 | your history for lines that match what you've typed so far, completing as | |
124 | much as it can. |
|
121 | much as it can. | |
125 |
|
122 | |||
126 |
- %hist: search history by index |
|
123 | - %hist: search history by index. | |
127 |
|
124 | |||
128 | * Persistent command history across sessions. |
|
125 | * Persistent command history across sessions. | |
129 |
|
126 | |||
130 | * Logging of input with the ability to save and restore a working session. |
|
127 | * Logging of input with the ability to save and restore a working session. | |
131 |
|
128 | |||
132 | * System escape with !. Typing !ls will run 'ls' in the current directory. |
|
129 | * System escape with !. Typing !ls will run 'ls' in the current directory. | |
133 |
|
130 | |||
134 | * The reload command does a 'deep' reload of a module: changes made to the |
|
131 | * The reload command does a 'deep' reload of a module: changes made to the | |
135 | module since you imported will actually be available without having to exit. |
|
132 | module since you imported will actually be available without having to exit. | |
136 |
|
133 | |||
137 | * Verbose and colored exception traceback printouts. See the magic xmode and |
|
134 | * Verbose and colored exception traceback printouts. See the magic xmode and | |
138 | xcolor functions for details (just type %magic). |
|
135 | xcolor functions for details (just type %magic). | |
139 |
|
136 | |||
140 | * Input caching system: |
|
137 | * Input caching system: | |
141 |
|
138 | |||
142 | IPython offers numbered prompts (In/Out) with input and output caching. All |
|
139 | IPython offers numbered prompts (In/Out) with input and output caching. All | |
143 | input is saved and can be retrieved as variables (besides the usual arrow |
|
140 | input is saved and can be retrieved as variables (besides the usual arrow | |
144 | key recall). |
|
141 | key recall). | |
145 |
|
142 | |||
146 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
143 | The following GLOBAL variables always exist (so don't overwrite them!): | |
147 | _i: stores previous input. |
|
144 | _i: stores previous input. | |
148 | _ii: next previous. |
|
145 | _ii: next previous. | |
149 | _iii: next-next previous. |
|
146 | _iii: next-next previous. | |
150 | _ih : a list of all input _ih[n] is the input from line n. |
|
147 | _ih : a list of all input _ih[n] is the input from line n. | |
151 |
|
148 | |||
152 | Additionally, global variables named _i<n> are dynamically created (<n> |
|
149 | Additionally, global variables named _i<n> are dynamically created (<n> | |
153 | being the prompt counter), such that _i<n> == _ih[<n>] |
|
150 | being the prompt counter), such that _i<n> == _ih[<n>] | |
154 |
|
151 | |||
155 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. |
|
152 | For example, what you typed at prompt 14 is available as _i14 and _ih[14]. | |
156 |
|
153 | |||
157 | You can create macros which contain multiple input lines from this history, |
|
154 | You can create macros which contain multiple input lines from this history, | |
158 | for later re-execution, with the %macro function. |
|
155 | for later re-execution, with the %macro function. | |
159 |
|
156 | |||
160 | The history function %hist allows you to see any part of your input history |
|
157 | The history function %hist allows you to see any part of your input history | |
161 | by printing a range of the _i variables. Note that inputs which contain |
|
158 | by printing a range of the _i variables. Note that inputs which contain | |
162 | magic functions (%) appear in the history with a prepended comment. This is |
|
159 | magic functions (%) appear in the history with a prepended comment. This is | |
163 | because they aren't really valid Python code, so you can't exec them. |
|
160 | because they aren't really valid Python code, so you can't exec them. | |
164 |
|
161 | |||
165 | * Output caching system: |
|
162 | * Output caching system: | |
166 |
|
163 | |||
167 | For output that is returned from actions, a system similar to the input |
|
164 | For output that is returned from actions, a system similar to the input | |
168 | cache exists but using _ instead of _i. Only actions that produce a result |
|
165 | cache exists but using _ instead of _i. Only actions that produce a result | |
169 | (NOT assignments, for example) are cached. If you are familiar with |
|
166 | (NOT assignments, for example) are cached. If you are familiar with | |
170 | Mathematica, IPython's _ variables behave exactly like Mathematica's % |
|
167 | Mathematica, IPython's _ variables behave exactly like Mathematica's % | |
171 | variables. |
|
168 | variables. | |
172 |
|
169 | |||
173 | The following GLOBAL variables always exist (so don't overwrite them!): |
|
170 | The following GLOBAL variables always exist (so don't overwrite them!): | |
174 | _ (one underscore): previous output. |
|
171 | _ (one underscore): previous output. | |
175 | __ (two underscores): next previous. |
|
172 | __ (two underscores): next previous. | |
176 | ___ (three underscores): next-next previous. |
|
173 | ___ (three underscores): next-next previous. | |
177 |
|
174 | |||
178 | Global variables named _<n> are dynamically created (<n> being the prompt |
|
175 | Global variables named _<n> are dynamically created (<n> being the prompt | |
179 | counter), such that the result of output <n> is always available as _<n>. |
|
176 | counter), such that the result of output <n> is always available as _<n>. | |
180 |
|
177 | |||
181 | Finally, a global dictionary named _oh exists with entries for all lines |
|
178 | Finally, a global dictionary named _oh exists with entries for all lines | |
182 | which generated output. |
|
179 | which generated output. | |
183 |
|
180 | |||
184 | * Directory history: |
|
181 | * Directory history: | |
185 |
|
182 | |||
186 | Your history of visited directories is kept in the global list _dh, and the |
|
183 | Your history of visited directories is kept in the global list _dh, and the | |
187 | magic %cd command can be used to go to any entry in that list. |
|
184 | magic %cd command can be used to go to any entry in that list. | |
188 |
|
185 | |||
189 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) |
|
186 | * Auto-parentheses and auto-quotes (adapted from Nathan Gray's LazyPython) | |
190 |
|
187 | |||
191 | 1. Auto-parentheses |
|
188 | 1. Auto-parentheses | |
192 |
|
189 | |||
193 | Callable objects (i.e. functions, methods, etc) can be invoked like |
|
190 | Callable objects (i.e. functions, methods, etc) can be invoked like | |
194 | this (notice the commas between the arguments):: |
|
191 | this (notice the commas between the arguments):: | |
195 |
|
192 | |||
196 | In [1]: callable_ob arg1, arg2, arg3 |
|
193 | In [1]: callable_ob arg1, arg2, arg3 | |
197 |
|
194 | |||
198 | and the input will be translated to this:: |
|
195 | and the input will be translated to this:: | |
199 |
|
196 | |||
200 | callable_ob(arg1, arg2, arg3) |
|
197 | callable_ob(arg1, arg2, arg3) | |
201 |
|
198 | |||
202 | This feature is off by default (in rare cases it can produce |
|
199 | This feature is off by default (in rare cases it can produce | |
203 | undesirable side-effects), but you can activate it at the command-line |
|
200 | undesirable side-effects), but you can activate it at the command-line | |
204 | by starting IPython with `--autocall 1`, set it permanently in your |
|
201 | by starting IPython with `--autocall 1`, set it permanently in your | |
205 | configuration file, or turn on at runtime with `%autocall 1`. |
|
202 | configuration file, or turn on at runtime with `%autocall 1`. | |
206 |
|
203 | |||
207 | You can force auto-parentheses by using '/' as the first character |
|
204 | You can force auto-parentheses by using '/' as the first character | |
208 | of a line. For example:: |
|
205 | of a line. For example:: | |
209 |
|
206 | |||
210 | In [1]: /globals # becomes 'globals()' |
|
207 | In [1]: /globals # becomes 'globals()' | |
211 |
|
208 | |||
212 | Note that the '/' MUST be the first character on the line! This |
|
209 | Note that the '/' MUST be the first character on the line! This | |
213 | won't work:: |
|
210 | won't work:: | |
214 |
|
211 | |||
215 | In [2]: print /globals # syntax error |
|
212 | In [2]: print /globals # syntax error | |
216 |
|
213 | |||
217 | In most cases the automatic algorithm should work, so you should |
|
214 | In most cases the automatic algorithm should work, so you should | |
218 | rarely need to explicitly invoke /. One notable exception is if you |
|
215 | rarely need to explicitly invoke /. One notable exception is if you | |
219 | are trying to call a function with a list of tuples as arguments (the |
|
216 | are trying to call a function with a list of tuples as arguments (the | |
220 | parenthesis will confuse IPython):: |
|
217 | parenthesis will confuse IPython):: | |
221 |
|
218 | |||
222 | In [1]: zip (1,2,3),(4,5,6) # won't work |
|
219 | In [1]: zip (1,2,3),(4,5,6) # won't work | |
223 |
|
220 | |||
224 | but this will work:: |
|
221 | but this will work:: | |
225 |
|
222 | |||
226 | In [2]: /zip (1,2,3),(4,5,6) |
|
223 | In [2]: /zip (1,2,3),(4,5,6) | |
227 | ------> zip ((1,2,3),(4,5,6)) |
|
224 | ------> zip ((1,2,3),(4,5,6)) | |
228 | Out[2]= [(1, 4), (2, 5), (3, 6)] |
|
225 | Out[2]= [(1, 4), (2, 5), (3, 6)] | |
229 |
|
226 | |||
230 | IPython tells you that it has altered your command line by |
|
227 | IPython tells you that it has altered your command line by | |
231 | displaying the new command line preceded by -->. e.g.:: |
|
228 | displaying the new command line preceded by -->. e.g.:: | |
232 |
|
229 | |||
233 | In [18]: callable list |
|
230 | In [18]: callable list | |
234 | -------> callable (list) |
|
231 | -------> callable (list) | |
235 |
|
232 | |||
236 | 2. Auto-Quoting |
|
233 | 2. Auto-Quoting | |
237 |
|
234 | |||
238 | You can force auto-quoting of a function's arguments by using ',' as |
|
235 | You can force auto-quoting of a function's arguments by using ',' as | |
239 | the first character of a line. For example:: |
|
236 | the first character of a line. For example:: | |
240 |
|
237 | |||
241 | In [1]: ,my_function /home/me # becomes my_function("/home/me") |
|
238 | In [1]: ,my_function /home/me # becomes my_function("/home/me") | |
242 |
|
239 | |||
243 | If you use ';' instead, the whole argument is quoted as a single |
|
240 | If you use ';' instead, the whole argument is quoted as a single | |
244 | string (while ',' splits on whitespace):: |
|
241 | string (while ',' splits on whitespace):: | |
245 |
|
242 | |||
246 | In [2]: ,my_function a b c # becomes my_function("a","b","c") |
|
243 | In [2]: ,my_function a b c # becomes my_function("a","b","c") | |
247 | In [3]: ;my_function a b c # becomes my_function("a b c") |
|
244 | In [3]: ;my_function a b c # becomes my_function("a b c") | |
248 |
|
245 | |||
249 | Note that the ',' MUST be the first character on the line! This |
|
246 | Note that the ',' MUST be the first character on the line! This | |
250 | won't work:: |
|
247 | won't work:: | |
251 |
|
248 | |||
252 | In [4]: x = ,my_function /home/me # syntax error |
|
249 | In [4]: x = ,my_function /home/me # syntax error | |
253 | """ |
|
250 | """ | |
254 |
|
251 | |||
255 | interactive_usage_min = """\ |
|
252 | interactive_usage_min = """\ | |
256 | An enhanced console for Python. |
|
253 | An enhanced console for Python. | |
257 | Some of its features are: |
|
254 | Some of its features are: | |
258 | - Readline support if the readline library is present. |
|
|||
259 | - Tab completion in the local namespace. |
|
255 | - Tab completion in the local namespace. | |
260 | - Logging of input, see command-line options. |
|
256 | - Logging of input, see command-line options. | |
261 | - System shell escape via ! , eg !ls. |
|
257 | - System shell escape via ! , eg !ls. | |
262 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) |
|
258 | - Magic commands, starting with a % (like %ls, %pwd, %cd, etc.) | |
263 | - Keeps track of locally defined variables via %who, %whos. |
|
259 | - Keeps track of locally defined variables via %who, %whos. | |
264 | - Show object information with a ? eg ?x or x? (use ?? for more info). |
|
260 | - Show object information with a ? eg ?x or x? (use ?? for more info). | |
265 | """ |
|
261 | """ | |
266 |
|
262 | |||
267 | quick_reference = r""" |
|
263 | quick_reference = r""" | |
268 | IPython -- An enhanced Interactive Python - Quick Reference Card |
|
264 | IPython -- An enhanced Interactive Python - Quick Reference Card | |
269 | ================================================================ |
|
265 | ================================================================ | |
270 |
|
266 | |||
271 | obj?, obj?? : Get help, or more help for object (also works as |
|
267 | obj?, obj?? : Get help, or more help for object (also works as | |
272 | ?obj, ??obj). |
|
268 | ?obj, ??obj). | |
273 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. |
|
269 | ?foo.*abc* : List names in 'foo' containing 'abc' in them. | |
274 | %magic : Information about IPython's 'magic' % functions. |
|
270 | %magic : Information about IPython's 'magic' % functions. | |
275 |
|
271 | |||
276 | Magic functions are prefixed by % or %%, and typically take their arguments |
|
272 | Magic functions are prefixed by % or %%, and typically take their arguments | |
277 | without parentheses, quotes or even commas for convenience. Line magics take a |
|
273 | without parentheses, quotes or even commas for convenience. Line magics take a | |
278 | single % and cell magics are prefixed with two %%. |
|
274 | single % and cell magics are prefixed with two %%. | |
279 |
|
275 | |||
280 | Example magic function calls: |
|
276 | Example magic function calls: | |
281 |
|
277 | |||
282 | %alias d ls -F : 'd' is now an alias for 'ls -F' |
|
278 | %alias d ls -F : 'd' is now an alias for 'ls -F' | |
283 | alias d ls -F : Works if 'alias' not a python name |
|
279 | alias d ls -F : Works if 'alias' not a python name | |
284 | alist = %alias : Get list of aliases to 'alist' |
|
280 | alist = %alias : Get list of aliases to 'alist' | |
285 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. |
|
281 | cd /usr/share : Obvious. cd -<tab> to choose from visited dirs. | |
286 | %cd?? : See help AND source for magic %cd |
|
282 | %cd?? : See help AND source for magic %cd | |
287 | %timeit x=10 : time the 'x=10' statement with high precision. |
|
283 | %timeit x=10 : time the 'x=10' statement with high precision. | |
288 | %%timeit x=2**100 |
|
284 | %%timeit x=2**100 | |
289 | x**100 : time 'x**100' with a setup of 'x=2**100'; setup code is not |
|
285 | x**100 : time 'x**100' with a setup of 'x=2**100'; setup code is not | |
290 | counted. This is an example of a cell magic. |
|
286 | counted. This is an example of a cell magic. | |
291 |
|
287 | |||
292 | System commands: |
|
288 | System commands: | |
293 |
|
289 | |||
294 | !cp a.txt b/ : System command escape, calls os.system() |
|
290 | !cp a.txt b/ : System command escape, calls os.system() | |
295 | cp a.txt b/ : after %rehashx, most system commands work without ! |
|
291 | cp a.txt b/ : after %rehashx, most system commands work without ! | |
296 | cp ${f}.txt $bar : Variable expansion in magics and system commands |
|
292 | cp ${f}.txt $bar : Variable expansion in magics and system commands | |
297 | files = !ls /usr : Capture sytem command output |
|
293 | files = !ls /usr : Capture sytem command output | |
298 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' |
|
294 | files.s, files.l, files.n: "a b c", ['a','b','c'], 'a\nb\nc' | |
299 |
|
295 | |||
300 | History: |
|
296 | History: | |
301 |
|
297 | |||
302 | _i, _ii, _iii : Previous, next previous, next next previous input |
|
298 | _i, _ii, _iii : Previous, next previous, next next previous input | |
303 | _i4, _ih[2:5] : Input history line 4, lines 2-4 |
|
299 | _i4, _ih[2:5] : Input history line 4, lines 2-4 | |
304 | exec _i81 : Execute input history line #81 again |
|
300 | exec _i81 : Execute input history line #81 again | |
305 | %rep 81 : Edit input history line #81 |
|
301 | %rep 81 : Edit input history line #81 | |
306 | _, __, ___ : previous, next previous, next next previous output |
|
302 | _, __, ___ : previous, next previous, next next previous output | |
307 | _dh : Directory history |
|
303 | _dh : Directory history | |
308 | _oh : Output history |
|
304 | _oh : Output history | |
309 | %hist : Command history of current session. |
|
305 | %hist : Command history of current session. | |
310 | %hist -g foo : Search command history of (almost) all sessions for 'foo'. |
|
306 | %hist -g foo : Search command history of (almost) all sessions for 'foo'. | |
311 | %hist -g : Command history of (almost) all sessions. |
|
307 | %hist -g : Command history of (almost) all sessions. | |
312 | %hist 1/2-8 : Command history containing lines 2-8 of session 1. |
|
308 | %hist 1/2-8 : Command history containing lines 2-8 of session 1. | |
313 | %hist 1/ ~2/ : Command history of session 1 and 2 sessions before current. |
|
309 | %hist 1/ ~2/ : Command history of session 1 and 2 sessions before current. | |
314 | %hist ~8/1-~6/5 : Command history from line 1 of 8 sessions ago to |
|
310 | %hist ~8/1-~6/5 : Command history from line 1 of 8 sessions ago to | |
315 | line 5 of 6 sessions ago. |
|
311 | line 5 of 6 sessions ago. | |
316 | %edit 0/ : Open editor to execute code with history of current session. |
|
312 | %edit 0/ : Open editor to execute code with history of current session. | |
317 |
|
313 | |||
318 | Autocall: |
|
314 | Autocall: | |
319 |
|
315 | |||
320 | f 1,2 : f(1,2) # Off by default, enable with %autocall magic. |
|
316 | f 1,2 : f(1,2) # Off by default, enable with %autocall magic. | |
321 | /f 1,2 : f(1,2) (forced autoparen) |
|
317 | /f 1,2 : f(1,2) (forced autoparen) | |
322 | ,f 1 2 : f("1","2") |
|
318 | ,f 1 2 : f("1","2") | |
323 | ;f 1 2 : f("1 2") |
|
319 | ;f 1 2 : f("1 2") | |
324 |
|
320 | |||
325 | Remember: TAB completion works in many contexts, not just file names |
|
321 | Remember: TAB completion works in many contexts, not just file names | |
326 | or python names. |
|
322 | or python names. | |
327 |
|
323 | |||
328 | The following magic functions are currently available: |
|
324 | The following magic functions are currently available: | |
329 |
|
325 | |||
330 | """ |
|
326 | """ | |
331 |
|
327 | |||
332 | quick_guide = """\ |
|
328 | quick_guide = """\ | |
333 | ? -> Introduction and overview of IPython's features. |
|
329 | ? -> Introduction and overview of IPython's features. | |
334 | %quickref -> Quick reference. |
|
330 | %quickref -> Quick reference. | |
335 | help -> Python's own help system. |
|
331 | help -> Python's own help system. | |
336 | object? -> Details about 'object', use 'object??' for extra details. |
|
332 | object? -> Details about 'object', use 'object??' for extra details. | |
337 | """ |
|
333 | """ | |
338 |
|
334 | |||
339 | default_banner_parts = [ |
|
335 | default_banner_parts = [ | |
340 | 'Python %s\n' % (sys.version.split('\n')[0],), |
|
336 | 'Python %s\n' % (sys.version.split('\n')[0],), | |
341 | 'Type "copyright", "credits" or "license" for more information.\n\n', |
|
337 | 'Type "copyright", "credits" or "license" for more information.\n\n', | |
342 | 'IPython {version} -- An enhanced Interactive Python.\n'.format( |
|
338 | 'IPython {version} -- An enhanced Interactive Python.\n'.format( | |
343 | version=release.version, |
|
339 | version=release.version, | |
344 | ), |
|
340 | ), | |
345 | quick_guide |
|
341 | quick_guide | |
346 | ] |
|
342 | ] | |
347 |
|
343 | |||
348 | default_banner = ''.join(default_banner_parts) |
|
344 | default_banner = ''.join(default_banner_parts) | |
349 |
|
345 | |||
350 | # deprecated GUI banner |
|
346 | # deprecated GUI banner | |
351 |
|
347 | |||
352 | default_gui_banner = '\n'.join([ |
|
348 | default_gui_banner = '\n'.join([ | |
353 | 'DEPRECATED: IPython.core.usage.default_gui_banner is deprecated and will be removed', |
|
349 | 'DEPRECATED: IPython.core.usage.default_gui_banner is deprecated and will be removed', | |
354 | default_banner, |
|
350 | default_banner, | |
355 | ]) |
|
351 | ]) |
@@ -1,300 +1,288 b'' | |||||
1 | #!/usr/bin/env python |
|
1 | #!/usr/bin/env python | |
2 | # -*- coding: utf-8 -*- |
|
2 | # -*- coding: utf-8 -*- | |
3 | """Setup script for IPython. |
|
3 | """Setup script for IPython. | |
4 |
|
4 | |||
5 | Under Posix environments it works like a typical setup.py script. |
|
5 | Under Posix environments it works like a typical setup.py script. | |
6 | Under Windows, the command sdist is not supported, since IPython |
|
6 | Under Windows, the command sdist is not supported, since IPython | |
7 | requires utilities which are not available under Windows.""" |
|
7 | requires utilities which are not available under Windows.""" | |
8 |
|
8 | |||
9 | #----------------------------------------------------------------------------- |
|
9 | #----------------------------------------------------------------------------- | |
10 | # Copyright (c) 2008-2011, IPython Development Team. |
|
10 | # Copyright (c) 2008-2011, IPython Development Team. | |
11 | # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu> |
|
11 | # Copyright (c) 2001-2007, Fernando Perez <fernando.perez@colorado.edu> | |
12 | # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de> |
|
12 | # Copyright (c) 2001, Janko Hauser <jhauser@zscout.de> | |
13 | # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu> |
|
13 | # Copyright (c) 2001, Nathaniel Gray <n8gray@caltech.edu> | |
14 | # |
|
14 | # | |
15 | # Distributed under the terms of the Modified BSD License. |
|
15 | # Distributed under the terms of the Modified BSD License. | |
16 | # |
|
16 | # | |
17 | # The full license is in the file COPYING.rst, distributed with this software. |
|
17 | # The full license is in the file COPYING.rst, distributed with this software. | |
18 | #----------------------------------------------------------------------------- |
|
18 | #----------------------------------------------------------------------------- | |
19 |
|
19 | |||
20 | #----------------------------------------------------------------------------- |
|
20 | #----------------------------------------------------------------------------- | |
21 | # Minimal Python version sanity check |
|
21 | # Minimal Python version sanity check | |
22 | #----------------------------------------------------------------------------- |
|
22 | #----------------------------------------------------------------------------- | |
23 | from __future__ import print_function |
|
23 | from __future__ import print_function | |
24 |
|
24 | |||
25 | import sys |
|
25 | import sys | |
26 |
|
26 | |||
27 | # This check is also made in IPython/__init__, don't forget to update both when |
|
27 | # This check is also made in IPython/__init__, don't forget to update both when | |
28 | # changing Python version requirements. |
|
28 | # changing Python version requirements. | |
29 | v = sys.version_info |
|
29 | v = sys.version_info | |
30 | if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)): |
|
30 | if v[:2] < (2,7) or (v[0] >= 3 and v[:2] < (3,3)): | |
31 | error = "ERROR: IPython requires Python version 2.7 or 3.3 or above." |
|
31 | error = "ERROR: IPython requires Python version 2.7 or 3.3 or above." | |
32 | print(error, file=sys.stderr) |
|
32 | print(error, file=sys.stderr) | |
33 | sys.exit(1) |
|
33 | sys.exit(1) | |
34 |
|
34 | |||
35 | PY3 = (sys.version_info[0] >= 3) |
|
35 | PY3 = (sys.version_info[0] >= 3) | |
36 |
|
36 | |||
37 | # At least we're on the python version we need, move on. |
|
37 | # At least we're on the python version we need, move on. | |
38 |
|
38 | |||
39 | #------------------------------------------------------------------------------- |
|
39 | #------------------------------------------------------------------------------- | |
40 | # Imports |
|
40 | # Imports | |
41 | #------------------------------------------------------------------------------- |
|
41 | #------------------------------------------------------------------------------- | |
42 |
|
42 | |||
43 | # Stdlib imports |
|
43 | # Stdlib imports | |
44 | import os |
|
44 | import os | |
45 |
|
45 | |||
46 | from glob import glob |
|
46 | from glob import glob | |
47 |
|
47 | |||
48 | # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly |
|
48 | # BEFORE importing distutils, remove MANIFEST. distutils doesn't properly | |
49 | # update it when the contents of directories change. |
|
49 | # update it when the contents of directories change. | |
50 | if os.path.exists('MANIFEST'): os.remove('MANIFEST') |
|
50 | if os.path.exists('MANIFEST'): os.remove('MANIFEST') | |
51 |
|
51 | |||
52 | from distutils.core import setup |
|
52 | from distutils.core import setup | |
53 |
|
53 | |||
54 | # Our own imports |
|
54 | # Our own imports | |
55 | from setupbase import target_update |
|
55 | from setupbase import target_update | |
56 |
|
56 | |||
57 | from setupbase import ( |
|
57 | from setupbase import ( | |
58 | setup_args, |
|
58 | setup_args, | |
59 | find_packages, |
|
59 | find_packages, | |
60 | find_package_data, |
|
60 | find_package_data, | |
61 | check_package_data_first, |
|
61 | check_package_data_first, | |
62 | find_entry_points, |
|
62 | find_entry_points, | |
63 | build_scripts_entrypt, |
|
63 | build_scripts_entrypt, | |
64 | find_data_files, |
|
64 | find_data_files, | |
65 | git_prebuild, |
|
65 | git_prebuild, | |
66 | install_symlinked, |
|
66 | install_symlinked, | |
67 | install_lib_symlink, |
|
67 | install_lib_symlink, | |
68 | install_scripts_for_symlink, |
|
68 | install_scripts_for_symlink, | |
69 | unsymlink, |
|
69 | unsymlink, | |
70 | ) |
|
70 | ) | |
71 |
|
71 | |||
72 | isfile = os.path.isfile |
|
72 | isfile = os.path.isfile | |
73 | pjoin = os.path.join |
|
73 | pjoin = os.path.join | |
74 |
|
74 | |||
75 | #------------------------------------------------------------------------------- |
|
75 | #------------------------------------------------------------------------------- | |
76 | # Handle OS specific things |
|
76 | # Handle OS specific things | |
77 | #------------------------------------------------------------------------------- |
|
77 | #------------------------------------------------------------------------------- | |
78 |
|
78 | |||
79 | if os.name in ('nt','dos'): |
|
79 | if os.name in ('nt','dos'): | |
80 | os_name = 'windows' |
|
80 | os_name = 'windows' | |
81 | else: |
|
81 | else: | |
82 | os_name = os.name |
|
82 | os_name = os.name | |
83 |
|
83 | |||
84 | # Under Windows, 'sdist' has not been supported. Now that the docs build with |
|
84 | # Under Windows, 'sdist' has not been supported. Now that the docs build with | |
85 | # Sphinx it might work, but let's not turn it on until someone confirms that it |
|
85 | # Sphinx it might work, but let's not turn it on until someone confirms that it | |
86 | # actually works. |
|
86 | # actually works. | |
87 | if os_name == 'windows' and 'sdist' in sys.argv: |
|
87 | if os_name == 'windows' and 'sdist' in sys.argv: | |
88 | print('The sdist command is not available under Windows. Exiting.') |
|
88 | print('The sdist command is not available under Windows. Exiting.') | |
89 | sys.exit(1) |
|
89 | sys.exit(1) | |
90 |
|
90 | |||
91 |
|
91 | |||
92 | #------------------------------------------------------------------------------- |
|
92 | #------------------------------------------------------------------------------- | |
93 | # Things related to the IPython documentation |
|
93 | # Things related to the IPython documentation | |
94 | #------------------------------------------------------------------------------- |
|
94 | #------------------------------------------------------------------------------- | |
95 |
|
95 | |||
96 | # update the manuals when building a source dist |
|
96 | # update the manuals when building a source dist | |
97 | if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'): |
|
97 | if len(sys.argv) >= 2 and sys.argv[1] in ('sdist','bdist_rpm'): | |
98 |
|
98 | |||
99 | # List of things to be updated. Each entry is a triplet of args for |
|
99 | # List of things to be updated. Each entry is a triplet of args for | |
100 | # target_update() |
|
100 | # target_update() | |
101 | to_update = [ |
|
101 | to_update = [ | |
102 | ('docs/man/ipython.1.gz', |
|
102 | ('docs/man/ipython.1.gz', | |
103 | ['docs/man/ipython.1'], |
|
103 | ['docs/man/ipython.1'], | |
104 | 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz'), |
|
104 | 'cd docs/man && gzip -9c ipython.1 > ipython.1.gz'), | |
105 | ] |
|
105 | ] | |
106 |
|
106 | |||
107 |
|
107 | |||
108 | [ target_update(*t) for t in to_update ] |
|
108 | [ target_update(*t) for t in to_update ] | |
109 |
|
109 | |||
110 | #--------------------------------------------------------------------------- |
|
110 | #--------------------------------------------------------------------------- | |
111 | # Find all the packages, package data, and data_files |
|
111 | # Find all the packages, package data, and data_files | |
112 | #--------------------------------------------------------------------------- |
|
112 | #--------------------------------------------------------------------------- | |
113 |
|
113 | |||
114 | packages = find_packages() |
|
114 | packages = find_packages() | |
115 | package_data = find_package_data() |
|
115 | package_data = find_package_data() | |
116 |
|
116 | |||
117 | data_files = find_data_files() |
|
117 | data_files = find_data_files() | |
118 |
|
118 | |||
119 | setup_args['packages'] = packages |
|
119 | setup_args['packages'] = packages | |
120 | setup_args['package_data'] = package_data |
|
120 | setup_args['package_data'] = package_data | |
121 | setup_args['data_files'] = data_files |
|
121 | setup_args['data_files'] = data_files | |
122 |
|
122 | |||
123 | #--------------------------------------------------------------------------- |
|
123 | #--------------------------------------------------------------------------- | |
124 | # custom distutils commands |
|
124 | # custom distutils commands | |
125 | #--------------------------------------------------------------------------- |
|
125 | #--------------------------------------------------------------------------- | |
126 | # imports here, so they are after setuptools import if there was one |
|
126 | # imports here, so they are after setuptools import if there was one | |
127 | from distutils.command.sdist import sdist |
|
127 | from distutils.command.sdist import sdist | |
128 | from distutils.command.upload import upload |
|
128 | from distutils.command.upload import upload | |
129 |
|
129 | |||
130 | class UploadWindowsInstallers(upload): |
|
130 | class UploadWindowsInstallers(upload): | |
131 |
|
131 | |||
132 | description = "Upload Windows installers to PyPI (only used from tools/release_windows.py)" |
|
132 | description = "Upload Windows installers to PyPI (only used from tools/release_windows.py)" | |
133 | user_options = upload.user_options + [ |
|
133 | user_options = upload.user_options + [ | |
134 | ('files=', 'f', 'exe file (or glob) to upload') |
|
134 | ('files=', 'f', 'exe file (or glob) to upload') | |
135 | ] |
|
135 | ] | |
136 | def initialize_options(self): |
|
136 | def initialize_options(self): | |
137 | upload.initialize_options(self) |
|
137 | upload.initialize_options(self) | |
138 | meta = self.distribution.metadata |
|
138 | meta = self.distribution.metadata | |
139 | base = '{name}-{version}'.format( |
|
139 | base = '{name}-{version}'.format( | |
140 | name=meta.get_name(), |
|
140 | name=meta.get_name(), | |
141 | version=meta.get_version() |
|
141 | version=meta.get_version() | |
142 | ) |
|
142 | ) | |
143 | self.files = os.path.join('dist', '%s.*.exe' % base) |
|
143 | self.files = os.path.join('dist', '%s.*.exe' % base) | |
144 |
|
144 | |||
145 | def run(self): |
|
145 | def run(self): | |
146 | for dist_file in glob(self.files): |
|
146 | for dist_file in glob(self.files): | |
147 | self.upload_file('bdist_wininst', 'any', dist_file) |
|
147 | self.upload_file('bdist_wininst', 'any', dist_file) | |
148 |
|
148 | |||
149 | setup_args['cmdclass'] = { |
|
149 | setup_args['cmdclass'] = { | |
150 | 'build_py': \ |
|
150 | 'build_py': \ | |
151 | check_package_data_first(git_prebuild('IPython')), |
|
151 | check_package_data_first(git_prebuild('IPython')), | |
152 | 'sdist' : git_prebuild('IPython', sdist), |
|
152 | 'sdist' : git_prebuild('IPython', sdist), | |
153 | 'upload_wininst' : UploadWindowsInstallers, |
|
153 | 'upload_wininst' : UploadWindowsInstallers, | |
154 | 'symlink': install_symlinked, |
|
154 | 'symlink': install_symlinked, | |
155 | 'install_lib_symlink': install_lib_symlink, |
|
155 | 'install_lib_symlink': install_lib_symlink, | |
156 | 'install_scripts_sym': install_scripts_for_symlink, |
|
156 | 'install_scripts_sym': install_scripts_for_symlink, | |
157 | 'unsymlink': unsymlink, |
|
157 | 'unsymlink': unsymlink, | |
158 | } |
|
158 | } | |
159 |
|
159 | |||
160 |
|
160 | |||
161 | #--------------------------------------------------------------------------- |
|
161 | #--------------------------------------------------------------------------- | |
162 | # Handle scripts, dependencies, and setuptools specific things |
|
162 | # Handle scripts, dependencies, and setuptools specific things | |
163 | #--------------------------------------------------------------------------- |
|
163 | #--------------------------------------------------------------------------- | |
164 |
|
164 | |||
165 | # For some commands, use setuptools. Note that we do NOT list install here! |
|
165 | # For some commands, use setuptools. Note that we do NOT list install here! | |
166 | # If you want a setuptools-enhanced install, just run 'setupegg.py install' |
|
166 | # If you want a setuptools-enhanced install, just run 'setupegg.py install' | |
167 | needs_setuptools = set(('develop', 'release', 'bdist_egg', 'bdist_rpm', |
|
167 | needs_setuptools = set(('develop', 'release', 'bdist_egg', 'bdist_rpm', | |
168 | 'bdist', 'bdist_dumb', 'bdist_wininst', 'bdist_wheel', |
|
168 | 'bdist', 'bdist_dumb', 'bdist_wininst', 'bdist_wheel', | |
169 | 'egg_info', 'easy_install', 'upload', 'install_egg_info', |
|
169 | 'egg_info', 'easy_install', 'upload', 'install_egg_info', | |
170 | )) |
|
170 | )) | |
171 |
|
171 | |||
172 | if len(needs_setuptools.intersection(sys.argv)) > 0: |
|
172 | if len(needs_setuptools.intersection(sys.argv)) > 0: | |
173 | import setuptools |
|
173 | import setuptools | |
174 |
|
174 | |||
175 | # This dict is used for passing extra arguments that are setuptools |
|
175 | # This dict is used for passing extra arguments that are setuptools | |
176 | # specific to setup |
|
176 | # specific to setup | |
177 | setuptools_extra_args = {} |
|
177 | setuptools_extra_args = {} | |
178 |
|
178 | |||
179 | # setuptools requirements |
|
179 | # setuptools requirements | |
180 |
|
180 | |||
181 | extras_require = dict( |
|
181 | extras_require = dict( | |
182 | parallel = ['ipyparallel'], |
|
182 | parallel = ['ipyparallel'], | |
183 | qtconsole = ['qtconsole'], |
|
183 | qtconsole = ['qtconsole'], | |
184 | doc = ['Sphinx>=1.3'], |
|
184 | doc = ['Sphinx>=1.3'], | |
185 | test = ['nose>=0.10.1', 'requests', 'testpath', 'pygments', 'nbformat', 'ipykernel', 'numpy'], |
|
185 | test = ['nose>=0.10.1', 'requests', 'testpath', 'pygments', 'nbformat', 'ipykernel', 'numpy'], | |
186 | terminal = [], |
|
186 | terminal = [], | |
187 | kernel = ['ipykernel'], |
|
187 | kernel = ['ipykernel'], | |
188 | nbformat = ['nbformat'], |
|
188 | nbformat = ['nbformat'], | |
189 | notebook = ['notebook', 'ipywidgets'], |
|
189 | notebook = ['notebook', 'ipywidgets'], | |
190 | nbconvert = ['nbconvert'], |
|
190 | nbconvert = ['nbconvert'], | |
191 | ) |
|
191 | ) | |
192 |
|
192 | |||
193 | install_requires = [ |
|
193 | install_requires = [ | |
194 | 'setuptools>=18.5', |
|
194 | 'setuptools>=18.5', | |
195 | 'decorator', |
|
195 | 'decorator', | |
196 | 'pickleshare', |
|
196 | 'pickleshare', | |
197 | 'simplegeneric>0.8', |
|
197 | 'simplegeneric>0.8', | |
198 | 'traitlets>=4.2', |
|
198 | 'traitlets>=4.2', | |
199 | 'prompt_toolkit>=1.0.3,<2.0.0', |
|
199 | 'prompt_toolkit>=1.0.3,<2.0.0', | |
200 | 'pygments', |
|
200 | 'pygments', | |
201 | ] |
|
201 | ] | |
202 |
|
202 | |||
203 | # Platform-specific dependencies: |
|
203 | # Platform-specific dependencies: | |
204 | # This is the correct way to specify these, |
|
204 | # This is the correct way to specify these, | |
205 | # but requires pip >= 6. pip < 6 ignores these. |
|
205 | # but requires pip >= 6. pip < 6 ignores these. | |
206 |
|
206 | |||
207 | extras_require.update({ |
|
207 | extras_require.update({ | |
208 | ':python_version == "2.7"': ['backports.shutil_get_terminal_size'], |
|
208 | ':python_version == "2.7"': ['backports.shutil_get_terminal_size'], | |
209 | ':python_version == "2.7" or python_version == "3.3"': ['pathlib2'], |
|
209 | ':python_version == "2.7" or python_version == "3.3"': ['pathlib2'], | |
210 | ':sys_platform != "win32"': ['pexpect'], |
|
210 | ':sys_platform != "win32"': ['pexpect'], | |
211 | ':sys_platform == "darwin"': ['appnope'], |
|
211 | ':sys_platform == "darwin"': ['appnope'], | |
212 | ':sys_platform == "win32"': ['colorama', 'win_unicode_console>=0.5'], |
|
212 | ':sys_platform == "win32"': ['colorama', 'win_unicode_console>=0.5'], | |
213 | 'test:python_version == "2.7"': ['mock'], |
|
213 | 'test:python_version == "2.7"': ['mock'], | |
214 | }) |
|
214 | }) | |
215 | # FIXME: re-specify above platform dependencies for pip < 6 |
|
215 | # FIXME: re-specify above platform dependencies for pip < 6 | |
216 | # These would result in non-portable bdists. |
|
216 | # These would result in non-portable bdists. | |
217 | if not any(arg.startswith('bdist') for arg in sys.argv): |
|
217 | if not any(arg.startswith('bdist') for arg in sys.argv): | |
218 | if sys.version_info < (3, 3): |
|
218 | if sys.version_info < (3, 3): | |
219 | extras_require['test'].append('mock') |
|
219 | extras_require['test'].append('mock') | |
220 |
|
220 | |||
221 | if sys.platform == 'darwin': |
|
221 | if sys.platform == 'darwin': | |
222 | install_requires.extend(['appnope']) |
|
222 | install_requires.extend(['appnope']) | |
223 | have_readline = False |
|
223 | ||
224 | try: |
|
224 | if not sys.platform.startswith('win'): | |
225 | import readline |
|
|||
226 | except ImportError: |
|
|||
227 | pass |
|
|||
228 | else: |
|
|||
229 | if 'libedit' not in readline.__doc__: |
|
|||
230 | have_readline = True |
|
|||
231 | if not have_readline: |
|
|||
232 | install_requires.extend(['gnureadline']) |
|
|||
233 |
|
||||
234 | if sys.platform.startswith('win'): |
|
|||
235 | extras_require['terminal'].append('pyreadline>=2.0') |
|
|||
236 | else: |
|
|||
237 | install_requires.append('pexpect') |
|
225 | install_requires.append('pexpect') | |
238 |
|
226 | |||
239 | # workaround pypa/setuptools#147, where setuptools misspells |
|
227 | # workaround pypa/setuptools#147, where setuptools misspells | |
240 | # platform_python_implementation as python_implementation |
|
228 | # platform_python_implementation as python_implementation | |
241 | if 'setuptools' in sys.modules: |
|
229 | if 'setuptools' in sys.modules: | |
242 | for key in list(extras_require): |
|
230 | for key in list(extras_require): | |
243 | if 'platform_python_implementation' in key: |
|
231 | if 'platform_python_implementation' in key: | |
244 | new_key = key.replace('platform_python_implementation', 'python_implementation') |
|
232 | new_key = key.replace('platform_python_implementation', 'python_implementation') | |
245 | extras_require[new_key] = extras_require.pop(key) |
|
233 | extras_require[new_key] = extras_require.pop(key) | |
246 |
|
234 | |||
247 | everything = set() |
|
235 | everything = set() | |
248 | for key, deps in extras_require.items(): |
|
236 | for key, deps in extras_require.items(): | |
249 | if ':' not in key: |
|
237 | if ':' not in key: | |
250 | everything.update(deps) |
|
238 | everything.update(deps) | |
251 | extras_require['all'] = everything |
|
239 | extras_require['all'] = everything | |
252 |
|
240 | |||
253 | if 'setuptools' in sys.modules: |
|
241 | if 'setuptools' in sys.modules: | |
254 | setuptools_extra_args['zip_safe'] = False |
|
242 | setuptools_extra_args['zip_safe'] = False | |
255 | setuptools_extra_args['entry_points'] = { |
|
243 | setuptools_extra_args['entry_points'] = { | |
256 | 'console_scripts': find_entry_points(), |
|
244 | 'console_scripts': find_entry_points(), | |
257 | 'pygments.lexers': [ |
|
245 | 'pygments.lexers': [ | |
258 | 'ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer', |
|
246 | 'ipythonconsole = IPython.lib.lexers:IPythonConsoleLexer', | |
259 | 'ipython = IPython.lib.lexers:IPythonLexer', |
|
247 | 'ipython = IPython.lib.lexers:IPythonLexer', | |
260 | 'ipython3 = IPython.lib.lexers:IPython3Lexer', |
|
248 | 'ipython3 = IPython.lib.lexers:IPython3Lexer', | |
261 | ], |
|
249 | ], | |
262 | } |
|
250 | } | |
263 | setup_args['extras_require'] = extras_require |
|
251 | setup_args['extras_require'] = extras_require | |
264 | requires = setup_args['install_requires'] = install_requires |
|
252 | requires = setup_args['install_requires'] = install_requires | |
265 |
|
253 | |||
266 | # Script to be run by the windows binary installer after the default setup |
|
254 | # Script to be run by the windows binary installer after the default setup | |
267 | # routine, to add shortcuts and similar windows-only things. Windows |
|
255 | # routine, to add shortcuts and similar windows-only things. Windows | |
268 | # post-install scripts MUST reside in the scripts/ dir, otherwise distutils |
|
256 | # post-install scripts MUST reside in the scripts/ dir, otherwise distutils | |
269 | # doesn't find them. |
|
257 | # doesn't find them. | |
270 | if 'bdist_wininst' in sys.argv: |
|
258 | if 'bdist_wininst' in sys.argv: | |
271 | if len(sys.argv) > 2 and \ |
|
259 | if len(sys.argv) > 2 and \ | |
272 | ('sdist' in sys.argv or 'bdist_rpm' in sys.argv): |
|
260 | ('sdist' in sys.argv or 'bdist_rpm' in sys.argv): | |
273 | print("ERROR: bdist_wininst must be run alone. Exiting.", file=sys.stderr) |
|
261 | print("ERROR: bdist_wininst must be run alone. Exiting.", file=sys.stderr) | |
274 | sys.exit(1) |
|
262 | sys.exit(1) | |
275 | setup_args['data_files'].append( |
|
263 | setup_args['data_files'].append( | |
276 | ['Scripts', ('scripts/ipython.ico', 'scripts/ipython_nb.ico')]) |
|
264 | ['Scripts', ('scripts/ipython.ico', 'scripts/ipython_nb.ico')]) | |
277 | setup_args['scripts'] = [pjoin('scripts','ipython_win_post_install.py')] |
|
265 | setup_args['scripts'] = [pjoin('scripts','ipython_win_post_install.py')] | |
278 | setup_args['options'] = {"bdist_wininst": |
|
266 | setup_args['options'] = {"bdist_wininst": | |
279 | {"install_script": |
|
267 | {"install_script": | |
280 | "ipython_win_post_install.py"}} |
|
268 | "ipython_win_post_install.py"}} | |
281 |
|
269 | |||
282 | else: |
|
270 | else: | |
283 | # scripts has to be a non-empty list, or install_scripts isn't called |
|
271 | # scripts has to be a non-empty list, or install_scripts isn't called | |
284 | setup_args['scripts'] = [e.split('=')[0].strip() for e in find_entry_points()] |
|
272 | setup_args['scripts'] = [e.split('=')[0].strip() for e in find_entry_points()] | |
285 |
|
273 | |||
286 | setup_args['cmdclass']['build_scripts'] = build_scripts_entrypt |
|
274 | setup_args['cmdclass']['build_scripts'] = build_scripts_entrypt | |
287 |
|
275 | |||
288 | #--------------------------------------------------------------------------- |
|
276 | #--------------------------------------------------------------------------- | |
289 | # Do the actual setup now |
|
277 | # Do the actual setup now | |
290 | #--------------------------------------------------------------------------- |
|
278 | #--------------------------------------------------------------------------- | |
291 |
|
279 | |||
292 | setup_args.update(setuptools_extra_args) |
|
280 | setup_args.update(setuptools_extra_args) | |
293 |
|
281 | |||
294 |
|
282 | |||
295 |
|
283 | |||
296 | def main(): |
|
284 | def main(): | |
297 | setup(**setup_args) |
|
285 | setup(**setup_args) | |
298 |
|
286 | |||
299 | if __name__ == '__main__': |
|
287 | if __name__ == '__main__': | |
300 | main() |
|
288 | main() |
General Comments 0
You need to be logged in to leave comments.
Login now