##// END OF EJS Templates
Adding tests and limiting CM mode to python 3.
Brian E. Granger -
Show More
@@ -1,677 +1,698 b''
1 # encoding: utf-8
1 # encoding: utf-8
2 """Tests for the IPython tab-completion machinery."""
2 """Tests for the IPython tab-completion machinery."""
3
3
4 # Copyright (c) IPython Development Team.
4 # Copyright (c) IPython Development Team.
5 # Distributed under the terms of the Modified BSD License.
5 # Distributed under the terms of the Modified BSD License.
6
6
7 import os
7 import os
8 import sys
8 import sys
9 import unittest
9 import unittest
10
10
11 from contextlib import contextmanager
11 from contextlib import contextmanager
12
12
13 import nose.tools as nt
13 import nose.tools as nt
14
14
15 from IPython.config.loader import Config
15 from IPython.config.loader import Config
16 from IPython.core import completer
16 from IPython.core import completer
17 from IPython.external.decorators import knownfailureif
17 from IPython.external.decorators import knownfailureif
18 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
18 from IPython.utils.tempdir import TemporaryDirectory, TemporaryWorkingDirectory
19 from IPython.utils.generics import complete_object
19 from IPython.utils.generics import complete_object
20 from IPython.utils import py3compat
20 from IPython.utils import py3compat
21 from IPython.utils.py3compat import string_types, unicode_type
21 from IPython.utils.py3compat import string_types, unicode_type
22 from IPython.testing import decorators as dec
22 from IPython.testing import decorators as dec
23
23
24 #-----------------------------------------------------------------------------
24 #-----------------------------------------------------------------------------
25 # Test functions
25 # Test functions
26 #-----------------------------------------------------------------------------
26 #-----------------------------------------------------------------------------
27
27
28 @contextmanager
28 @contextmanager
29 def greedy_completion():
29 def greedy_completion():
30 ip = get_ipython()
30 ip = get_ipython()
31 greedy_original = ip.Completer.greedy
31 greedy_original = ip.Completer.greedy
32 try:
32 try:
33 ip.Completer.greedy = True
33 ip.Completer.greedy = True
34 yield
34 yield
35 finally:
35 finally:
36 ip.Completer.greedy = greedy_original
36 ip.Completer.greedy = greedy_original
37
37
38 def test_protect_filename():
38 def test_protect_filename():
39 pairs = [ ('abc','abc'),
39 pairs = [ ('abc','abc'),
40 (' abc',r'\ abc'),
40 (' abc',r'\ abc'),
41 ('a bc',r'a\ bc'),
41 ('a bc',r'a\ bc'),
42 ('a bc',r'a\ \ bc'),
42 ('a bc',r'a\ \ bc'),
43 (' bc',r'\ \ bc'),
43 (' bc',r'\ \ bc'),
44 ]
44 ]
45 # On posix, we also protect parens and other special characters
45 # On posix, we also protect parens and other special characters
46 if sys.platform != 'win32':
46 if sys.platform != 'win32':
47 pairs.extend( [('a(bc',r'a\(bc'),
47 pairs.extend( [('a(bc',r'a\(bc'),
48 ('a)bc',r'a\)bc'),
48 ('a)bc',r'a\)bc'),
49 ('a( )bc',r'a\(\ \)bc'),
49 ('a( )bc',r'a\(\ \)bc'),
50 ('a[1]bc', r'a\[1\]bc'),
50 ('a[1]bc', r'a\[1\]bc'),
51 ('a{1}bc', r'a\{1\}bc'),
51 ('a{1}bc', r'a\{1\}bc'),
52 ('a#bc', r'a\#bc'),
52 ('a#bc', r'a\#bc'),
53 ('a?bc', r'a\?bc'),
53 ('a?bc', r'a\?bc'),
54 ('a=bc', r'a\=bc'),
54 ('a=bc', r'a\=bc'),
55 ('a\\bc', r'a\\bc'),
55 ('a\\bc', r'a\\bc'),
56 ('a|bc', r'a\|bc'),
56 ('a|bc', r'a\|bc'),
57 ('a;bc', r'a\;bc'),
57 ('a;bc', r'a\;bc'),
58 ('a:bc', r'a\:bc'),
58 ('a:bc', r'a\:bc'),
59 ("a'bc", r"a\'bc"),
59 ("a'bc", r"a\'bc"),
60 ('a*bc', r'a\*bc'),
60 ('a*bc', r'a\*bc'),
61 ('a"bc', r'a\"bc'),
61 ('a"bc', r'a\"bc'),
62 ('a^bc', r'a\^bc'),
62 ('a^bc', r'a\^bc'),
63 ('a&bc', r'a\&bc'),
63 ('a&bc', r'a\&bc'),
64 ] )
64 ] )
65 # run the actual tests
65 # run the actual tests
66 for s1, s2 in pairs:
66 for s1, s2 in pairs:
67 s1p = completer.protect_filename(s1)
67 s1p = completer.protect_filename(s1)
68 nt.assert_equal(s1p, s2)
68 nt.assert_equal(s1p, s2)
69
69
70
70
71 def check_line_split(splitter, test_specs):
71 def check_line_split(splitter, test_specs):
72 for part1, part2, split in test_specs:
72 for part1, part2, split in test_specs:
73 cursor_pos = len(part1)
73 cursor_pos = len(part1)
74 line = part1+part2
74 line = part1+part2
75 out = splitter.split_line(line, cursor_pos)
75 out = splitter.split_line(line, cursor_pos)
76 nt.assert_equal(out, split)
76 nt.assert_equal(out, split)
77
77
78
78
79 def test_line_split():
79 def test_line_split():
80 """Basic line splitter test with default specs."""
80 """Basic line splitter test with default specs."""
81 sp = completer.CompletionSplitter()
81 sp = completer.CompletionSplitter()
82 # The format of the test specs is: part1, part2, expected answer. Parts 1
82 # The format of the test specs is: part1, part2, expected answer. Parts 1
83 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
83 # and 2 are joined into the 'line' sent to the splitter, as if the cursor
84 # was at the end of part1. So an empty part2 represents someone hitting
84 # was at the end of part1. So an empty part2 represents someone hitting
85 # tab at the end of the line, the most common case.
85 # tab at the end of the line, the most common case.
86 t = [('run some/scrip', '', 'some/scrip'),
86 t = [('run some/scrip', '', 'some/scrip'),
87 ('run scripts/er', 'ror.py foo', 'scripts/er'),
87 ('run scripts/er', 'ror.py foo', 'scripts/er'),
88 ('echo $HOM', '', 'HOM'),
88 ('echo $HOM', '', 'HOM'),
89 ('print sys.pa', '', 'sys.pa'),
89 ('print sys.pa', '', 'sys.pa'),
90 ('print(sys.pa', '', 'sys.pa'),
90 ('print(sys.pa', '', 'sys.pa'),
91 ("execfile('scripts/er", '', 'scripts/er'),
91 ("execfile('scripts/er", '', 'scripts/er'),
92 ('a[x.', '', 'x.'),
92 ('a[x.', '', 'x.'),
93 ('a[x.', 'y', 'x.'),
93 ('a[x.', 'y', 'x.'),
94 ('cd "some_file/', '', 'some_file/'),
94 ('cd "some_file/', '', 'some_file/'),
95 ]
95 ]
96 check_line_split(sp, t)
96 check_line_split(sp, t)
97 # Ensure splitting works OK with unicode by re-running the tests with
97 # Ensure splitting works OK with unicode by re-running the tests with
98 # all inputs turned into unicode
98 # all inputs turned into unicode
99 check_line_split(sp, [ map(unicode_type, p) for p in t] )
99 check_line_split(sp, [ map(unicode_type, p) for p in t] )
100
100
101
101
102 def test_custom_completion_error():
102 def test_custom_completion_error():
103 """Test that errors from custom attribute completers are silenced."""
103 """Test that errors from custom attribute completers are silenced."""
104 ip = get_ipython()
104 ip = get_ipython()
105 class A(object): pass
105 class A(object): pass
106 ip.user_ns['a'] = A()
106 ip.user_ns['a'] = A()
107
107
108 @complete_object.when_type(A)
108 @complete_object.when_type(A)
109 def complete_A(a, existing_completions):
109 def complete_A(a, existing_completions):
110 raise TypeError("this should be silenced")
110 raise TypeError("this should be silenced")
111
111
112 ip.complete("a.")
112 ip.complete("a.")
113
113
114
114
115 def test_unicode_completions():
115 def test_unicode_completions():
116 ip = get_ipython()
116 ip = get_ipython()
117 # Some strings that trigger different types of completion. Check them both
117 # Some strings that trigger different types of completion. Check them both
118 # in str and unicode forms
118 # in str and unicode forms
119 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
119 s = ['ru', '%ru', 'cd /', 'floa', 'float(x)/']
120 for t in s + list(map(unicode_type, s)):
120 for t in s + list(map(unicode_type, s)):
121 # We don't need to check exact completion values (they may change
121 # We don't need to check exact completion values (they may change
122 # depending on the state of the namespace, but at least no exceptions
122 # depending on the state of the namespace, but at least no exceptions
123 # should be thrown and the return value should be a pair of text, list
123 # should be thrown and the return value should be a pair of text, list
124 # values.
124 # values.
125 text, matches = ip.complete(t)
125 text, matches = ip.complete(t)
126 nt.assert_true(isinstance(text, string_types))
126 nt.assert_true(isinstance(text, string_types))
127 nt.assert_true(isinstance(matches, list))
127 nt.assert_true(isinstance(matches, list))
128
128
129 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
130 def test_latex_completions():
131 from IPython.core.latex_symbols import latex_symbols
132 import random
133 ip = get_ipython()
134 # Test some random unicode symbols
135 keys = random.sample(latex_symbols.keys(), 10)
136 for k in keys:
137 text, matches = ip.complete(k)
138 nt.assert_equal(len(matches),1)
139 nt.assert_equal(text, k)
140 mt.assert_equal(matches[0], latex_symbols[k])
141 # Test a more complex line
142 text, matches = ip.complete(u'print(\\alpha')
143 nt.assert_equals(text, u'\\alpha')
144 nt.assert_equals(matches[0], latex_symbols['\\alpha'])
145 # Test multiple matching latex symbols
146 text, matches = ip.complete(u'\\al')
147 nt.assert_in('\\alpha', matches)
148 nt.assert_in('\\aleph', matches)
149
129
150
130 class CompletionSplitterTestCase(unittest.TestCase):
151 class CompletionSplitterTestCase(unittest.TestCase):
131 def setUp(self):
152 def setUp(self):
132 self.sp = completer.CompletionSplitter()
153 self.sp = completer.CompletionSplitter()
133
154
134 def test_delim_setting(self):
155 def test_delim_setting(self):
135 self.sp.delims = ' '
156 self.sp.delims = ' '
136 nt.assert_equal(self.sp.delims, ' ')
157 nt.assert_equal(self.sp.delims, ' ')
137 nt.assert_equal(self.sp._delim_expr, '[\ ]')
158 nt.assert_equal(self.sp._delim_expr, '[\ ]')
138
159
139 def test_spaces(self):
160 def test_spaces(self):
140 """Test with only spaces as split chars."""
161 """Test with only spaces as split chars."""
141 self.sp.delims = ' '
162 self.sp.delims = ' '
142 t = [('foo', '', 'foo'),
163 t = [('foo', '', 'foo'),
143 ('run foo', '', 'foo'),
164 ('run foo', '', 'foo'),
144 ('run foo', 'bar', 'foo'),
165 ('run foo', 'bar', 'foo'),
145 ]
166 ]
146 check_line_split(self.sp, t)
167 check_line_split(self.sp, t)
147
168
148
169
149 def test_has_open_quotes1():
170 def test_has_open_quotes1():
150 for s in ["'", "'''", "'hi' '"]:
171 for s in ["'", "'''", "'hi' '"]:
151 nt.assert_equal(completer.has_open_quotes(s), "'")
172 nt.assert_equal(completer.has_open_quotes(s), "'")
152
173
153
174
154 def test_has_open_quotes2():
175 def test_has_open_quotes2():
155 for s in ['"', '"""', '"hi" "']:
176 for s in ['"', '"""', '"hi" "']:
156 nt.assert_equal(completer.has_open_quotes(s), '"')
177 nt.assert_equal(completer.has_open_quotes(s), '"')
157
178
158
179
159 def test_has_open_quotes3():
180 def test_has_open_quotes3():
160 for s in ["''", "''' '''", "'hi' 'ipython'"]:
181 for s in ["''", "''' '''", "'hi' 'ipython'"]:
161 nt.assert_false(completer.has_open_quotes(s))
182 nt.assert_false(completer.has_open_quotes(s))
162
183
163
184
164 def test_has_open_quotes4():
185 def test_has_open_quotes4():
165 for s in ['""', '""" """', '"hi" "ipython"']:
186 for s in ['""', '""" """', '"hi" "ipython"']:
166 nt.assert_false(completer.has_open_quotes(s))
187 nt.assert_false(completer.has_open_quotes(s))
167
188
168
189
169 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
190 @knownfailureif(sys.platform == 'win32', "abspath completions fail on Windows")
170 def test_abspath_file_completions():
191 def test_abspath_file_completions():
171 ip = get_ipython()
192 ip = get_ipython()
172 with TemporaryDirectory() as tmpdir:
193 with TemporaryDirectory() as tmpdir:
173 prefix = os.path.join(tmpdir, 'foo')
194 prefix = os.path.join(tmpdir, 'foo')
174 suffixes = ['1', '2']
195 suffixes = ['1', '2']
175 names = [prefix+s for s in suffixes]
196 names = [prefix+s for s in suffixes]
176 for n in names:
197 for n in names:
177 open(n, 'w').close()
198 open(n, 'w').close()
178
199
179 # Check simple completion
200 # Check simple completion
180 c = ip.complete(prefix)[1]
201 c = ip.complete(prefix)[1]
181 nt.assert_equal(c, names)
202 nt.assert_equal(c, names)
182
203
183 # Now check with a function call
204 # Now check with a function call
184 cmd = 'a = f("%s' % prefix
205 cmd = 'a = f("%s' % prefix
185 c = ip.complete(prefix, cmd)[1]
206 c = ip.complete(prefix, cmd)[1]
186 comp = [prefix+s for s in suffixes]
207 comp = [prefix+s for s in suffixes]
187 nt.assert_equal(c, comp)
208 nt.assert_equal(c, comp)
188
209
189
210
190 def test_local_file_completions():
211 def test_local_file_completions():
191 ip = get_ipython()
212 ip = get_ipython()
192 with TemporaryWorkingDirectory():
213 with TemporaryWorkingDirectory():
193 prefix = './foo'
214 prefix = './foo'
194 suffixes = ['1', '2']
215 suffixes = ['1', '2']
195 names = [prefix+s for s in suffixes]
216 names = [prefix+s for s in suffixes]
196 for n in names:
217 for n in names:
197 open(n, 'w').close()
218 open(n, 'w').close()
198
219
199 # Check simple completion
220 # Check simple completion
200 c = ip.complete(prefix)[1]
221 c = ip.complete(prefix)[1]
201 nt.assert_equal(c, names)
222 nt.assert_equal(c, names)
202
223
203 # Now check with a function call
224 # Now check with a function call
204 cmd = 'a = f("%s' % prefix
225 cmd = 'a = f("%s' % prefix
205 c = ip.complete(prefix, cmd)[1]
226 c = ip.complete(prefix, cmd)[1]
206 comp = [prefix+s for s in suffixes]
227 comp = [prefix+s for s in suffixes]
207 nt.assert_equal(c, comp)
228 nt.assert_equal(c, comp)
208
229
209
230
210 def test_greedy_completions():
231 def test_greedy_completions():
211 ip = get_ipython()
232 ip = get_ipython()
212 ip.ex('a=list(range(5))')
233 ip.ex('a=list(range(5))')
213 _,c = ip.complete('.',line='a[0].')
234 _,c = ip.complete('.',line='a[0].')
214 nt.assert_false('a[0].real' in c,
235 nt.assert_false('a[0].real' in c,
215 "Shouldn't have completed on a[0]: %s"%c)
236 "Shouldn't have completed on a[0]: %s"%c)
216 with greedy_completion():
237 with greedy_completion():
217 _,c = ip.complete('.',line='a[0].')
238 _,c = ip.complete('.',line='a[0].')
218 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
239 nt.assert_true('a[0].real' in c, "Should have completed on a[0]: %s"%c)
219
240
220
241
221 def test_omit__names():
242 def test_omit__names():
222 # also happens to test IPCompleter as a configurable
243 # also happens to test IPCompleter as a configurable
223 ip = get_ipython()
244 ip = get_ipython()
224 ip._hidden_attr = 1
245 ip._hidden_attr = 1
225 c = ip.Completer
246 c = ip.Completer
226 ip.ex('ip=get_ipython()')
247 ip.ex('ip=get_ipython()')
227 cfg = Config()
248 cfg = Config()
228 cfg.IPCompleter.omit__names = 0
249 cfg.IPCompleter.omit__names = 0
229 c.update_config(cfg)
250 c.update_config(cfg)
230 s,matches = c.complete('ip.')
251 s,matches = c.complete('ip.')
231 nt.assert_in('ip.__str__', matches)
252 nt.assert_in('ip.__str__', matches)
232 nt.assert_in('ip._hidden_attr', matches)
253 nt.assert_in('ip._hidden_attr', matches)
233 cfg.IPCompleter.omit__names = 1
254 cfg.IPCompleter.omit__names = 1
234 c.update_config(cfg)
255 c.update_config(cfg)
235 s,matches = c.complete('ip.')
256 s,matches = c.complete('ip.')
236 nt.assert_not_in('ip.__str__', matches)
257 nt.assert_not_in('ip.__str__', matches)
237 nt.assert_in('ip._hidden_attr', matches)
258 nt.assert_in('ip._hidden_attr', matches)
238 cfg.IPCompleter.omit__names = 2
259 cfg.IPCompleter.omit__names = 2
239 c.update_config(cfg)
260 c.update_config(cfg)
240 s,matches = c.complete('ip.')
261 s,matches = c.complete('ip.')
241 nt.assert_not_in('ip.__str__', matches)
262 nt.assert_not_in('ip.__str__', matches)
242 nt.assert_not_in('ip._hidden_attr', matches)
263 nt.assert_not_in('ip._hidden_attr', matches)
243 del ip._hidden_attr
264 del ip._hidden_attr
244
265
245
266
246 def test_limit_to__all__False_ok():
267 def test_limit_to__all__False_ok():
247 ip = get_ipython()
268 ip = get_ipython()
248 c = ip.Completer
269 c = ip.Completer
249 ip.ex('class D: x=24')
270 ip.ex('class D: x=24')
250 ip.ex('d=D()')
271 ip.ex('d=D()')
251 cfg = Config()
272 cfg = Config()
252 cfg.IPCompleter.limit_to__all__ = False
273 cfg.IPCompleter.limit_to__all__ = False
253 c.update_config(cfg)
274 c.update_config(cfg)
254 s, matches = c.complete('d.')
275 s, matches = c.complete('d.')
255 nt.assert_in('d.x', matches)
276 nt.assert_in('d.x', matches)
256
277
257
278
258 def test_limit_to__all__True_ok():
279 def test_limit_to__all__True_ok():
259 ip = get_ipython()
280 ip = get_ipython()
260 c = ip.Completer
281 c = ip.Completer
261 ip.ex('class D: x=24')
282 ip.ex('class D: x=24')
262 ip.ex('d=D()')
283 ip.ex('d=D()')
263 ip.ex("d.__all__=['z']")
284 ip.ex("d.__all__=['z']")
264 cfg = Config()
285 cfg = Config()
265 cfg.IPCompleter.limit_to__all__ = True
286 cfg.IPCompleter.limit_to__all__ = True
266 c.update_config(cfg)
287 c.update_config(cfg)
267 s, matches = c.complete('d.')
288 s, matches = c.complete('d.')
268 nt.assert_in('d.z', matches)
289 nt.assert_in('d.z', matches)
269 nt.assert_not_in('d.x', matches)
290 nt.assert_not_in('d.x', matches)
270
291
271
292
272 def test_get__all__entries_ok():
293 def test_get__all__entries_ok():
273 class A(object):
294 class A(object):
274 __all__ = ['x', 1]
295 __all__ = ['x', 1]
275 words = completer.get__all__entries(A())
296 words = completer.get__all__entries(A())
276 nt.assert_equal(words, ['x'])
297 nt.assert_equal(words, ['x'])
277
298
278
299
279 def test_get__all__entries_no__all__ok():
300 def test_get__all__entries_no__all__ok():
280 class A(object):
301 class A(object):
281 pass
302 pass
282 words = completer.get__all__entries(A())
303 words = completer.get__all__entries(A())
283 nt.assert_equal(words, [])
304 nt.assert_equal(words, [])
284
305
285
306
286 def test_func_kw_completions():
307 def test_func_kw_completions():
287 ip = get_ipython()
308 ip = get_ipython()
288 c = ip.Completer
309 c = ip.Completer
289 ip.ex('def myfunc(a=1,b=2): return a+b')
310 ip.ex('def myfunc(a=1,b=2): return a+b')
290 s, matches = c.complete(None, 'myfunc(1,b')
311 s, matches = c.complete(None, 'myfunc(1,b')
291 nt.assert_in('b=', matches)
312 nt.assert_in('b=', matches)
292 # Simulate completing with cursor right after b (pos==10):
313 # Simulate completing with cursor right after b (pos==10):
293 s, matches = c.complete(None, 'myfunc(1,b)', 10)
314 s, matches = c.complete(None, 'myfunc(1,b)', 10)
294 nt.assert_in('b=', matches)
315 nt.assert_in('b=', matches)
295 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
316 s, matches = c.complete(None, 'myfunc(a="escaped\\")string",b')
296 nt.assert_in('b=', matches)
317 nt.assert_in('b=', matches)
297 #builtin function
318 #builtin function
298 s, matches = c.complete(None, 'min(k, k')
319 s, matches = c.complete(None, 'min(k, k')
299 nt.assert_in('key=', matches)
320 nt.assert_in('key=', matches)
300
321
301
322
302 def test_default_arguments_from_docstring():
323 def test_default_arguments_from_docstring():
303 doc = min.__doc__
324 doc = min.__doc__
304 ip = get_ipython()
325 ip = get_ipython()
305 c = ip.Completer
326 c = ip.Completer
306 kwd = c._default_arguments_from_docstring(
327 kwd = c._default_arguments_from_docstring(
307 'min(iterable[, key=func]) -> value')
328 'min(iterable[, key=func]) -> value')
308 nt.assert_equal(kwd, ['key'])
329 nt.assert_equal(kwd, ['key'])
309 #with cython type etc
330 #with cython type etc
310 kwd = c._default_arguments_from_docstring(
331 kwd = c._default_arguments_from_docstring(
311 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
332 'Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
312 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
333 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
313 #white spaces
334 #white spaces
314 kwd = c._default_arguments_from_docstring(
335 kwd = c._default_arguments_from_docstring(
315 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
336 '\n Minuit.migrad(self, int ncall=10000, resume=True, int nsplit=1)\n')
316 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
337 nt.assert_equal(kwd, ['ncall', 'resume', 'nsplit'])
317
338
318 def test_line_magics():
339 def test_line_magics():
319 ip = get_ipython()
340 ip = get_ipython()
320 c = ip.Completer
341 c = ip.Completer
321 s, matches = c.complete(None, 'lsmag')
342 s, matches = c.complete(None, 'lsmag')
322 nt.assert_in('%lsmagic', matches)
343 nt.assert_in('%lsmagic', matches)
323 s, matches = c.complete(None, '%lsmag')
344 s, matches = c.complete(None, '%lsmag')
324 nt.assert_in('%lsmagic', matches)
345 nt.assert_in('%lsmagic', matches)
325
346
326
347
327 def test_cell_magics():
348 def test_cell_magics():
328 from IPython.core.magic import register_cell_magic
349 from IPython.core.magic import register_cell_magic
329
350
330 @register_cell_magic
351 @register_cell_magic
331 def _foo_cellm(line, cell):
352 def _foo_cellm(line, cell):
332 pass
353 pass
333
354
334 ip = get_ipython()
355 ip = get_ipython()
335 c = ip.Completer
356 c = ip.Completer
336
357
337 s, matches = c.complete(None, '_foo_ce')
358 s, matches = c.complete(None, '_foo_ce')
338 nt.assert_in('%%_foo_cellm', matches)
359 nt.assert_in('%%_foo_cellm', matches)
339 s, matches = c.complete(None, '%%_foo_ce')
360 s, matches = c.complete(None, '%%_foo_ce')
340 nt.assert_in('%%_foo_cellm', matches)
361 nt.assert_in('%%_foo_cellm', matches)
341
362
342
363
343 def test_line_cell_magics():
364 def test_line_cell_magics():
344 from IPython.core.magic import register_line_cell_magic
365 from IPython.core.magic import register_line_cell_magic
345
366
346 @register_line_cell_magic
367 @register_line_cell_magic
347 def _bar_cellm(line, cell):
368 def _bar_cellm(line, cell):
348 pass
369 pass
349
370
350 ip = get_ipython()
371 ip = get_ipython()
351 c = ip.Completer
372 c = ip.Completer
352
373
353 # The policy here is trickier, see comments in completion code. The
374 # The policy here is trickier, see comments in completion code. The
354 # returned values depend on whether the user passes %% or not explicitly,
375 # returned values depend on whether the user passes %% or not explicitly,
355 # and this will show a difference if the same name is both a line and cell
376 # and this will show a difference if the same name is both a line and cell
356 # magic.
377 # magic.
357 s, matches = c.complete(None, '_bar_ce')
378 s, matches = c.complete(None, '_bar_ce')
358 nt.assert_in('%_bar_cellm', matches)
379 nt.assert_in('%_bar_cellm', matches)
359 nt.assert_in('%%_bar_cellm', matches)
380 nt.assert_in('%%_bar_cellm', matches)
360 s, matches = c.complete(None, '%_bar_ce')
381 s, matches = c.complete(None, '%_bar_ce')
361 nt.assert_in('%_bar_cellm', matches)
382 nt.assert_in('%_bar_cellm', matches)
362 nt.assert_in('%%_bar_cellm', matches)
383 nt.assert_in('%%_bar_cellm', matches)
363 s, matches = c.complete(None, '%%_bar_ce')
384 s, matches = c.complete(None, '%%_bar_ce')
364 nt.assert_not_in('%_bar_cellm', matches)
385 nt.assert_not_in('%_bar_cellm', matches)
365 nt.assert_in('%%_bar_cellm', matches)
386 nt.assert_in('%%_bar_cellm', matches)
366
387
367
388
368 def test_magic_completion_order():
389 def test_magic_completion_order():
369
390
370 ip = get_ipython()
391 ip = get_ipython()
371 c = ip.Completer
392 c = ip.Completer
372
393
373 # Test ordering of magics and non-magics with the same name
394 # Test ordering of magics and non-magics with the same name
374 # We want the non-magic first
395 # We want the non-magic first
375
396
376 # Before importing matplotlib, there should only be one option:
397 # Before importing matplotlib, there should only be one option:
377
398
378 text, matches = c.complete('mat')
399 text, matches = c.complete('mat')
379 nt.assert_equal(matches, ["%matplotlib"])
400 nt.assert_equal(matches, ["%matplotlib"])
380
401
381
402
382 ip.run_cell("matplotlib = 1") # introduce name into namespace
403 ip.run_cell("matplotlib = 1") # introduce name into namespace
383
404
384 # After the import, there should be two options, ordered like this:
405 # After the import, there should be two options, ordered like this:
385 text, matches = c.complete('mat')
406 text, matches = c.complete('mat')
386 nt.assert_equal(matches, ["matplotlib", "%matplotlib"])
407 nt.assert_equal(matches, ["matplotlib", "%matplotlib"])
387
408
388
409
389 ip.run_cell("timeit = 1") # define a user variable called 'timeit'
410 ip.run_cell("timeit = 1") # define a user variable called 'timeit'
390
411
391 # Order of user variable and line and cell magics with same name:
412 # Order of user variable and line and cell magics with same name:
392 text, matches = c.complete('timeit')
413 text, matches = c.complete('timeit')
393 nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])
414 nt.assert_equal(matches, ["timeit", "%timeit","%%timeit"])
394
415
395
416
396 def test_dict_key_completion_string():
417 def test_dict_key_completion_string():
397 """Test dictionary key completion for string keys"""
418 """Test dictionary key completion for string keys"""
398 ip = get_ipython()
419 ip = get_ipython()
399 complete = ip.Completer.complete
420 complete = ip.Completer.complete
400
421
401 ip.user_ns['d'] = {'abc': None}
422 ip.user_ns['d'] = {'abc': None}
402
423
403 # check completion at different stages
424 # check completion at different stages
404 _, matches = complete(line_buffer="d[")
425 _, matches = complete(line_buffer="d[")
405 nt.assert_in("'abc'", matches)
426 nt.assert_in("'abc'", matches)
406 nt.assert_not_in("'abc']", matches)
427 nt.assert_not_in("'abc']", matches)
407
428
408 _, matches = complete(line_buffer="d['")
429 _, matches = complete(line_buffer="d['")
409 nt.assert_in("abc", matches)
430 nt.assert_in("abc", matches)
410 nt.assert_not_in("abc']", matches)
431 nt.assert_not_in("abc']", matches)
411
432
412 _, matches = complete(line_buffer="d['a")
433 _, matches = complete(line_buffer="d['a")
413 nt.assert_in("abc", matches)
434 nt.assert_in("abc", matches)
414 nt.assert_not_in("abc']", matches)
435 nt.assert_not_in("abc']", matches)
415
436
416 # check use of different quoting
437 # check use of different quoting
417 _, matches = complete(line_buffer="d[\"")
438 _, matches = complete(line_buffer="d[\"")
418 nt.assert_in("abc", matches)
439 nt.assert_in("abc", matches)
419 nt.assert_not_in('abc\"]', matches)
440 nt.assert_not_in('abc\"]', matches)
420
441
421 _, matches = complete(line_buffer="d[\"a")
442 _, matches = complete(line_buffer="d[\"a")
422 nt.assert_in("abc", matches)
443 nt.assert_in("abc", matches)
423 nt.assert_not_in('abc\"]', matches)
444 nt.assert_not_in('abc\"]', matches)
424
445
425 # check sensitivity to following context
446 # check sensitivity to following context
426 _, matches = complete(line_buffer="d[]", cursor_pos=2)
447 _, matches = complete(line_buffer="d[]", cursor_pos=2)
427 nt.assert_in("'abc'", matches)
448 nt.assert_in("'abc'", matches)
428
449
429 _, matches = complete(line_buffer="d['']", cursor_pos=3)
450 _, matches = complete(line_buffer="d['']", cursor_pos=3)
430 nt.assert_in("abc", matches)
451 nt.assert_in("abc", matches)
431 nt.assert_not_in("abc'", matches)
452 nt.assert_not_in("abc'", matches)
432 nt.assert_not_in("abc']", matches)
453 nt.assert_not_in("abc']", matches)
433
454
434 # check multiple solutions are correctly returned and that noise is not
455 # check multiple solutions are correctly returned and that noise is not
435 ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None,
456 ip.user_ns['d'] = {'abc': None, 'abd': None, 'bad': None, object(): None,
436 5: None}
457 5: None}
437
458
438 _, matches = complete(line_buffer="d['a")
459 _, matches = complete(line_buffer="d['a")
439 nt.assert_in("abc", matches)
460 nt.assert_in("abc", matches)
440 nt.assert_in("abd", matches)
461 nt.assert_in("abd", matches)
441 nt.assert_not_in("bad", matches)
462 nt.assert_not_in("bad", matches)
442 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
463 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
443
464
444 # check escaping and whitespace
465 # check escaping and whitespace
445 ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None}
466 ip.user_ns['d'] = {'a\nb': None, 'a\'b': None, 'a"b': None, 'a word': None}
446 _, matches = complete(line_buffer="d['a")
467 _, matches = complete(line_buffer="d['a")
447 nt.assert_in("a\\nb", matches)
468 nt.assert_in("a\\nb", matches)
448 nt.assert_in("a\\'b", matches)
469 nt.assert_in("a\\'b", matches)
449 nt.assert_in("a\"b", matches)
470 nt.assert_in("a\"b", matches)
450 nt.assert_in("a word", matches)
471 nt.assert_in("a word", matches)
451 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
472 assert not any(m.endswith((']', '"', "'")) for m in matches), matches
452
473
453 # - can complete on non-initial word of the string
474 # - can complete on non-initial word of the string
454 _, matches = complete(line_buffer="d['a w")
475 _, matches = complete(line_buffer="d['a w")
455 nt.assert_in("word", matches)
476 nt.assert_in("word", matches)
456
477
457 # - understands quote escaping
478 # - understands quote escaping
458 _, matches = complete(line_buffer="d['a\\'")
479 _, matches = complete(line_buffer="d['a\\'")
459 nt.assert_in("b", matches)
480 nt.assert_in("b", matches)
460
481
461 # - default quoting should work like repr
482 # - default quoting should work like repr
462 _, matches = complete(line_buffer="d[")
483 _, matches = complete(line_buffer="d[")
463 nt.assert_in("\"a'b\"", matches)
484 nt.assert_in("\"a'b\"", matches)
464
485
465 # - when opening quote with ", possible to match with unescaped apostrophe
486 # - when opening quote with ", possible to match with unescaped apostrophe
466 _, matches = complete(line_buffer="d[\"a'")
487 _, matches = complete(line_buffer="d[\"a'")
467 nt.assert_in("b", matches)
488 nt.assert_in("b", matches)
468
489
469
490
470 def test_dict_key_completion_contexts():
491 def test_dict_key_completion_contexts():
471 """Test expression contexts in which dict key completion occurs"""
492 """Test expression contexts in which dict key completion occurs"""
472 ip = get_ipython()
493 ip = get_ipython()
473 complete = ip.Completer.complete
494 complete = ip.Completer.complete
474 d = {'abc': None}
495 d = {'abc': None}
475 ip.user_ns['d'] = d
496 ip.user_ns['d'] = d
476
497
477 class C:
498 class C:
478 data = d
499 data = d
479 ip.user_ns['C'] = C
500 ip.user_ns['C'] = C
480 ip.user_ns['get'] = lambda: d
501 ip.user_ns['get'] = lambda: d
481
502
482 def assert_no_completion(**kwargs):
503 def assert_no_completion(**kwargs):
483 _, matches = complete(**kwargs)
504 _, matches = complete(**kwargs)
484 nt.assert_not_in('abc', matches)
505 nt.assert_not_in('abc', matches)
485 nt.assert_not_in('abc\'', matches)
506 nt.assert_not_in('abc\'', matches)
486 nt.assert_not_in('abc\']', matches)
507 nt.assert_not_in('abc\']', matches)
487 nt.assert_not_in('\'abc\'', matches)
508 nt.assert_not_in('\'abc\'', matches)
488 nt.assert_not_in('\'abc\']', matches)
509 nt.assert_not_in('\'abc\']', matches)
489
510
490 def assert_completion(**kwargs):
511 def assert_completion(**kwargs):
491 _, matches = complete(**kwargs)
512 _, matches = complete(**kwargs)
492 nt.assert_in("'abc'", matches)
513 nt.assert_in("'abc'", matches)
493 nt.assert_not_in("'abc']", matches)
514 nt.assert_not_in("'abc']", matches)
494
515
495 # no completion after string closed, even if reopened
516 # no completion after string closed, even if reopened
496 assert_no_completion(line_buffer="d['a'")
517 assert_no_completion(line_buffer="d['a'")
497 assert_no_completion(line_buffer="d[\"a\"")
518 assert_no_completion(line_buffer="d[\"a\"")
498 assert_no_completion(line_buffer="d['a' + ")
519 assert_no_completion(line_buffer="d['a' + ")
499 assert_no_completion(line_buffer="d['a' + '")
520 assert_no_completion(line_buffer="d['a' + '")
500
521
501 # completion in non-trivial expressions
522 # completion in non-trivial expressions
502 assert_completion(line_buffer="+ d[")
523 assert_completion(line_buffer="+ d[")
503 assert_completion(line_buffer="(d[")
524 assert_completion(line_buffer="(d[")
504 assert_completion(line_buffer="C.data[")
525 assert_completion(line_buffer="C.data[")
505
526
506 # greedy flag
527 # greedy flag
507 def assert_completion(**kwargs):
528 def assert_completion(**kwargs):
508 _, matches = complete(**kwargs)
529 _, matches = complete(**kwargs)
509 nt.assert_in("get()['abc']", matches)
530 nt.assert_in("get()['abc']", matches)
510
531
511 assert_no_completion(line_buffer="get()[")
532 assert_no_completion(line_buffer="get()[")
512 with greedy_completion():
533 with greedy_completion():
513 assert_completion(line_buffer="get()[")
534 assert_completion(line_buffer="get()[")
514 assert_completion(line_buffer="get()['")
535 assert_completion(line_buffer="get()['")
515 assert_completion(line_buffer="get()['a")
536 assert_completion(line_buffer="get()['a")
516 assert_completion(line_buffer="get()['ab")
537 assert_completion(line_buffer="get()['ab")
517 assert_completion(line_buffer="get()['abc")
538 assert_completion(line_buffer="get()['abc")
518
539
519
540
520
541
521 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
542 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
522 def test_dict_key_completion_bytes():
543 def test_dict_key_completion_bytes():
523 """Test handling of bytes in dict key completion"""
544 """Test handling of bytes in dict key completion"""
524 ip = get_ipython()
545 ip = get_ipython()
525 complete = ip.Completer.complete
546 complete = ip.Completer.complete
526
547
527 ip.user_ns['d'] = {'abc': None, b'abd': None}
548 ip.user_ns['d'] = {'abc': None, b'abd': None}
528
549
529 _, matches = complete(line_buffer="d[")
550 _, matches = complete(line_buffer="d[")
530 nt.assert_in("'abc'", matches)
551 nt.assert_in("'abc'", matches)
531 nt.assert_in("b'abd'", matches)
552 nt.assert_in("b'abd'", matches)
532
553
533 if False: # not currently implemented
554 if False: # not currently implemented
534 _, matches = complete(line_buffer="d[b")
555 _, matches = complete(line_buffer="d[b")
535 nt.assert_in("b'abd'", matches)
556 nt.assert_in("b'abd'", matches)
536 nt.assert_not_in("b'abc'", matches)
557 nt.assert_not_in("b'abc'", matches)
537
558
538 _, matches = complete(line_buffer="d[b'")
559 _, matches = complete(line_buffer="d[b'")
539 nt.assert_in("abd", matches)
560 nt.assert_in("abd", matches)
540 nt.assert_not_in("abc", matches)
561 nt.assert_not_in("abc", matches)
541
562
542 _, matches = complete(line_buffer="d[B'")
563 _, matches = complete(line_buffer="d[B'")
543 nt.assert_in("abd", matches)
564 nt.assert_in("abd", matches)
544 nt.assert_not_in("abc", matches)
565 nt.assert_not_in("abc", matches)
545
566
546 _, matches = complete(line_buffer="d['")
567 _, matches = complete(line_buffer="d['")
547 nt.assert_in("abc", matches)
568 nt.assert_in("abc", matches)
548 nt.assert_not_in("abd", matches)
569 nt.assert_not_in("abd", matches)
549
570
550
571
551 @dec.onlyif(sys.version_info[0] < 3, 'This test only applies in Py<3')
572 @dec.onlyif(sys.version_info[0] < 3, 'This test only applies in Py<3')
552 def test_dict_key_completion_unicode_py2():
573 def test_dict_key_completion_unicode_py2():
553 """Test handling of unicode in dict key completion"""
574 """Test handling of unicode in dict key completion"""
554 ip = get_ipython()
575 ip = get_ipython()
555 complete = ip.Completer.complete
576 complete = ip.Completer.complete
556
577
557 ip.user_ns['d'] = {u'abc': None,
578 ip.user_ns['d'] = {u'abc': None,
558 u'a\u05d0b': None}
579 u'a\u05d0b': None}
559
580
560 _, matches = complete(line_buffer="d[")
581 _, matches = complete(line_buffer="d[")
561 nt.assert_in("u'abc'", matches)
582 nt.assert_in("u'abc'", matches)
562 nt.assert_in("u'a\\u05d0b'", matches)
583 nt.assert_in("u'a\\u05d0b'", matches)
563
584
564 _, matches = complete(line_buffer="d['a")
585 _, matches = complete(line_buffer="d['a")
565 nt.assert_in("abc", matches)
586 nt.assert_in("abc", matches)
566 nt.assert_not_in("a\\u05d0b", matches)
587 nt.assert_not_in("a\\u05d0b", matches)
567
588
568 _, matches = complete(line_buffer="d[u'a")
589 _, matches = complete(line_buffer="d[u'a")
569 nt.assert_in("abc", matches)
590 nt.assert_in("abc", matches)
570 nt.assert_in("a\\u05d0b", matches)
591 nt.assert_in("a\\u05d0b", matches)
571
592
572 _, matches = complete(line_buffer="d[U'a")
593 _, matches = complete(line_buffer="d[U'a")
573 nt.assert_in("abc", matches)
594 nt.assert_in("abc", matches)
574 nt.assert_in("a\\u05d0b", matches)
595 nt.assert_in("a\\u05d0b", matches)
575
596
576 # query using escape
597 # query using escape
577 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
598 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
578 nt.assert_in("u05d0b", matches) # tokenized after \\
599 nt.assert_in("u05d0b", matches) # tokenized after \\
579
600
580 # query using character
601 # query using character
581 _, matches = complete(line_buffer=u"d[u'a\u05d0")
602 _, matches = complete(line_buffer=u"d[u'a\u05d0")
582 nt.assert_in(u"a\u05d0b", matches)
603 nt.assert_in(u"a\u05d0b", matches)
583
604
584 with greedy_completion():
605 with greedy_completion():
585 _, matches = complete(line_buffer="d[")
606 _, matches = complete(line_buffer="d[")
586 nt.assert_in("d[u'abc']", matches)
607 nt.assert_in("d[u'abc']", matches)
587 nt.assert_in("d[u'a\\u05d0b']", matches)
608 nt.assert_in("d[u'a\\u05d0b']", matches)
588
609
589 _, matches = complete(line_buffer="d['a")
610 _, matches = complete(line_buffer="d['a")
590 nt.assert_in("d['abc']", matches)
611 nt.assert_in("d['abc']", matches)
591 nt.assert_not_in("d[u'a\\u05d0b']", matches)
612 nt.assert_not_in("d[u'a\\u05d0b']", matches)
592
613
593 _, matches = complete(line_buffer="d[u'a")
614 _, matches = complete(line_buffer="d[u'a")
594 nt.assert_in("d[u'abc']", matches)
615 nt.assert_in("d[u'abc']", matches)
595 nt.assert_in("d[u'a\\u05d0b']", matches)
616 nt.assert_in("d[u'a\\u05d0b']", matches)
596
617
597 _, matches = complete(line_buffer="d[U'a")
618 _, matches = complete(line_buffer="d[U'a")
598 nt.assert_in("d[U'abc']", matches)
619 nt.assert_in("d[U'abc']", matches)
599 nt.assert_in("d[U'a\\u05d0b']", matches)
620 nt.assert_in("d[U'a\\u05d0b']", matches)
600
621
601 # query using escape
622 # query using escape
602 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
623 _, matches = complete(line_buffer=u"d[u'a\\u05d0")
603 nt.assert_in("d[u'a\\u05d0b']", matches) # tokenized after \\
624 nt.assert_in("d[u'a\\u05d0b']", matches) # tokenized after \\
604
625
605 # query using character
626 # query using character
606 _, matches = complete(line_buffer=u"d[u'a\u05d0")
627 _, matches = complete(line_buffer=u"d[u'a\u05d0")
607 nt.assert_in(u"d[u'a\u05d0b']", matches)
628 nt.assert_in(u"d[u'a\u05d0b']", matches)
608
629
609
630
610 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
631 @dec.onlyif(sys.version_info[0] >= 3, 'This test only applies in Py>=3')
611 def test_dict_key_completion_unicode_py3():
632 def test_dict_key_completion_unicode_py3():
612 """Test handling of unicode in dict key completion"""
633 """Test handling of unicode in dict key completion"""
613 ip = get_ipython()
634 ip = get_ipython()
614 complete = ip.Completer.complete
635 complete = ip.Completer.complete
615
636
616 ip.user_ns['d'] = {u'a\u05d0': None}
637 ip.user_ns['d'] = {u'a\u05d0': None}
617
638
618 # query using escape
639 # query using escape
619 _, matches = complete(line_buffer="d['a\\u05d0")
640 _, matches = complete(line_buffer="d['a\\u05d0")
620 nt.assert_in("u05d0", matches) # tokenized after \\
641 nt.assert_in("u05d0", matches) # tokenized after \\
621
642
622 # query using character
643 # query using character
623 _, matches = complete(line_buffer="d['a\u05d0")
644 _, matches = complete(line_buffer="d['a\u05d0")
624 nt.assert_in(u"a\u05d0", matches)
645 nt.assert_in(u"a\u05d0", matches)
625
646
626 with greedy_completion():
647 with greedy_completion():
627 # query using escape
648 # query using escape
628 _, matches = complete(line_buffer="d['a\\u05d0")
649 _, matches = complete(line_buffer="d['a\\u05d0")
629 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
650 nt.assert_in("d['a\\u05d0']", matches) # tokenized after \\
630
651
631 # query using character
652 # query using character
632 _, matches = complete(line_buffer="d['a\u05d0")
653 _, matches = complete(line_buffer="d['a\u05d0")
633 nt.assert_in(u"d['a\u05d0']", matches)
654 nt.assert_in(u"d['a\u05d0']", matches)
634
655
635
656
636
657
637 @dec.skip_without('numpy')
658 @dec.skip_without('numpy')
638 def test_struct_array_key_completion():
659 def test_struct_array_key_completion():
639 """Test dict key completion applies to numpy struct arrays"""
660 """Test dict key completion applies to numpy struct arrays"""
640 import numpy
661 import numpy
641 ip = get_ipython()
662 ip = get_ipython()
642 complete = ip.Completer.complete
663 complete = ip.Completer.complete
643 ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')])
664 ip.user_ns['d'] = numpy.array([], dtype=[('hello', 'f'), ('world', 'f')])
644 _, matches = complete(line_buffer="d['")
665 _, matches = complete(line_buffer="d['")
645 nt.assert_in("hello", matches)
666 nt.assert_in("hello", matches)
646 nt.assert_in("world", matches)
667 nt.assert_in("world", matches)
647
668
648
669
649 @dec.skip_without('pandas')
670 @dec.skip_without('pandas')
650 def test_dataframe_key_completion():
671 def test_dataframe_key_completion():
651 """Test dict key completion applies to pandas DataFrames"""
672 """Test dict key completion applies to pandas DataFrames"""
652 import pandas
673 import pandas
653 ip = get_ipython()
674 ip = get_ipython()
654 complete = ip.Completer.complete
675 complete = ip.Completer.complete
655 ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
676 ip.user_ns['d'] = pandas.DataFrame({'hello': [1], 'world': [2]})
656 _, matches = complete(line_buffer="d['")
677 _, matches = complete(line_buffer="d['")
657 nt.assert_in("hello", matches)
678 nt.assert_in("hello", matches)
658 nt.assert_in("world", matches)
679 nt.assert_in("world", matches)
659
680
660
681
661 def test_dict_key_completion_invalids():
682 def test_dict_key_completion_invalids():
662 """Smoke test cases dict key completion can't handle"""
683 """Smoke test cases dict key completion can't handle"""
663 ip = get_ipython()
684 ip = get_ipython()
664 complete = ip.Completer.complete
685 complete = ip.Completer.complete
665
686
666 ip.user_ns['no_getitem'] = None
687 ip.user_ns['no_getitem'] = None
667 ip.user_ns['no_keys'] = []
688 ip.user_ns['no_keys'] = []
668 ip.user_ns['cant_call_keys'] = dict
689 ip.user_ns['cant_call_keys'] = dict
669 ip.user_ns['empty'] = {}
690 ip.user_ns['empty'] = {}
670 ip.user_ns['d'] = {'abc': 5}
691 ip.user_ns['d'] = {'abc': 5}
671
692
672 _, matches = complete(line_buffer="no_getitem['")
693 _, matches = complete(line_buffer="no_getitem['")
673 _, matches = complete(line_buffer="no_keys['")
694 _, matches = complete(line_buffer="no_keys['")
674 _, matches = complete(line_buffer="cant_call_keys['")
695 _, matches = complete(line_buffer="cant_call_keys['")
675 _, matches = complete(line_buffer="empty['")
696 _, matches = complete(line_buffer="empty['")
676 _, matches = complete(line_buffer="name_error['")
697 _, matches = complete(line_buffer="name_error['")
677 _, matches = complete(line_buffer="d['\\") # incomplete escape
698 _, matches = complete(line_buffer="d['\\") # incomplete escape
@@ -1,23 +1,28 b''
1 // IPython mode is just a slightly altered Python Mode with `?` beeing a extra
1 // IPython mode is just a slightly altered Python Mode with `?` beeing a extra
2 // single operator. Here we define `ipython` mode in the require `python`
2 // single operator. Here we define `ipython` mode in the require `python`
3 // callback to auto-load python mode, which is more likely not the best things
3 // callback to auto-load python mode, which is more likely not the best things
4 // to do, but at least the simple one for now.
4 // to do, but at least the simple one for now.
5
5
6 CodeMirror.requireMode('python',function(){
6 CodeMirror.requireMode('python',function(){
7 "use strict";
7 "use strict";
8
8
9 CodeMirror.defineMode("ipython", function(conf, parserConf) {
9 CodeMirror.defineMode("ipython", function(conf, parserConf) {
10 var pythonConf = {};
10 var pythonConf = {};
11 for (var prop in parserConf) {
11 for (var prop in parserConf) {
12 if (parserConf.hasOwnProperty(prop)) {
12 if (parserConf.hasOwnProperty(prop)) {
13 pythonConf[prop] = parserConf[prop];
13 pythonConf[prop] = parserConf[prop];
14 }
14 }
15 }
15 }
16 pythonConf.name = 'python';
16 pythonConf.name = 'python';
17 pythonConf.singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\\?]");
17 pythonConf.singleOperators = new RegExp("^[\\+\\-\\*/%&|\\^~<>!\\?]");
18 pythonConf.identifiers = new RegExp("^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*");
18 if (pythonConf.version === 3) {
19 console.log('setting up for python 3');
20 pythonConf.identifiers = new RegExp("^[_A-Za-z\u00A1-\uFFFF][_A-Za-z0-9\u00A1-\uFFFF]*");
21 } else if (pythonConf.version === 2) {
22 pythonConf.identifiers = new RegExp("^[_A-Za-z][_A-Za-z0-9]*");
23 }
19 return CodeMirror.getMode(conf, pythonConf);
24 return CodeMirror.getMode(conf, pythonConf);
20 }, 'python');
25 }, 'python');
21
26
22 CodeMirror.defineMIME("text/x-ipython", "ipython");
27 CodeMirror.defineMIME("text/x-ipython", "ipython");
23 })
28 })
General Comments 0
You need to be logged in to leave comments. Login now