##// END OF EJS Templates
Merge pull request #5321 from takluyver/i5305...
Thomas Kluyver -
r15798:9aa711b1 merge
parent child Browse files
Show More
@@ -1,542 +1,549 b''
1 """Input transformer classes to support IPython special syntax.
1 """Input transformer classes to support IPython special syntax.
2
2
3 This includes the machinery to recognise and transform ``%magic`` commands,
3 This includes the machinery to recognise and transform ``%magic`` commands,
4 ``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
4 ``!system`` commands, ``help?`` querying, prompt stripping, and so forth.
5 """
5 """
6 import abc
6 import abc
7 import functools
7 import functools
8 import re
8 import re
9
9
10 from IPython.core.splitinput import LineInfo
10 from IPython.core.splitinput import LineInfo
11 from IPython.utils import tokenize2
11 from IPython.utils import tokenize2
12 from IPython.utils.openpy import cookie_comment_re
12 from IPython.utils.openpy import cookie_comment_re
13 from IPython.utils.py3compat import with_metaclass, PY3
13 from IPython.utils.py3compat import with_metaclass, PY3
14 from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
14 from IPython.utils.tokenize2 import generate_tokens, untokenize, TokenError
15
15
16 if PY3:
16 if PY3:
17 from io import StringIO
17 from io import StringIO
18 else:
18 else:
19 from StringIO import StringIO
19 from StringIO import StringIO
20
20
21 #-----------------------------------------------------------------------------
21 #-----------------------------------------------------------------------------
22 # Globals
22 # Globals
23 #-----------------------------------------------------------------------------
23 #-----------------------------------------------------------------------------
24
24
25 # The escape sequences that define the syntax transformations IPython will
25 # The escape sequences that define the syntax transformations IPython will
26 # apply to user input. These can NOT be just changed here: many regular
26 # apply to user input. These can NOT be just changed here: many regular
27 # expressions and other parts of the code may use their hardcoded values, and
27 # expressions and other parts of the code may use their hardcoded values, and
28 # for all intents and purposes they constitute the 'IPython syntax', so they
28 # for all intents and purposes they constitute the 'IPython syntax', so they
29 # should be considered fixed.
29 # should be considered fixed.
30
30
31 ESC_SHELL = '!' # Send line to underlying system shell
31 ESC_SHELL = '!' # Send line to underlying system shell
32 ESC_SH_CAP = '!!' # Send line to system shell and capture output
32 ESC_SH_CAP = '!!' # Send line to system shell and capture output
33 ESC_HELP = '?' # Find information about object
33 ESC_HELP = '?' # Find information about object
34 ESC_HELP2 = '??' # Find extra-detailed information about object
34 ESC_HELP2 = '??' # Find extra-detailed information about object
35 ESC_MAGIC = '%' # Call magic function
35 ESC_MAGIC = '%' # Call magic function
36 ESC_MAGIC2 = '%%' # Call cell-magic function
36 ESC_MAGIC2 = '%%' # Call cell-magic function
37 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
37 ESC_QUOTE = ',' # Split args on whitespace, quote each as string and call
38 ESC_QUOTE2 = ';' # Quote all args as a single string, call
38 ESC_QUOTE2 = ';' # Quote all args as a single string, call
39 ESC_PAREN = '/' # Call first argument with rest of line as arguments
39 ESC_PAREN = '/' # Call first argument with rest of line as arguments
40
40
41 ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\
41 ESC_SEQUENCES = [ESC_SHELL, ESC_SH_CAP, ESC_HELP ,\
42 ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\
42 ESC_HELP2, ESC_MAGIC, ESC_MAGIC2,\
43 ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
43 ESC_QUOTE, ESC_QUOTE2, ESC_PAREN ]
44
44
45
45
46 class InputTransformer(with_metaclass(abc.ABCMeta, object)):
46 class InputTransformer(with_metaclass(abc.ABCMeta, object)):
47 """Abstract base class for line-based input transformers."""
47 """Abstract base class for line-based input transformers."""
48
48
49 @abc.abstractmethod
49 @abc.abstractmethod
50 def push(self, line):
50 def push(self, line):
51 """Send a line of input to the transformer, returning the transformed
51 """Send a line of input to the transformer, returning the transformed
52 input or None if the transformer is waiting for more input.
52 input or None if the transformer is waiting for more input.
53
53
54 Must be overridden by subclasses.
54 Must be overridden by subclasses.
55
55
56 Implementations may raise ``SyntaxError`` if the input is invalid. No
56 Implementations may raise ``SyntaxError`` if the input is invalid. No
57 other exceptions may be raised.
57 other exceptions may be raised.
58 """
58 """
59 pass
59 pass
60
60
61 @abc.abstractmethod
61 @abc.abstractmethod
62 def reset(self):
62 def reset(self):
63 """Return, transformed any lines that the transformer has accumulated,
63 """Return, transformed any lines that the transformer has accumulated,
64 and reset its internal state.
64 and reset its internal state.
65
65
66 Must be overridden by subclasses.
66 Must be overridden by subclasses.
67 """
67 """
68 pass
68 pass
69
69
70 @classmethod
70 @classmethod
71 def wrap(cls, func):
71 def wrap(cls, func):
72 """Can be used by subclasses as a decorator, to return a factory that
72 """Can be used by subclasses as a decorator, to return a factory that
73 will allow instantiation with the decorated object.
73 will allow instantiation with the decorated object.
74 """
74 """
75 @functools.wraps(func)
75 @functools.wraps(func)
76 def transformer_factory(**kwargs):
76 def transformer_factory(**kwargs):
77 return cls(func, **kwargs)
77 return cls(func, **kwargs)
78
78
79 return transformer_factory
79 return transformer_factory
80
80
81 class StatelessInputTransformer(InputTransformer):
81 class StatelessInputTransformer(InputTransformer):
82 """Wrapper for a stateless input transformer implemented as a function."""
82 """Wrapper for a stateless input transformer implemented as a function."""
83 def __init__(self, func):
83 def __init__(self, func):
84 self.func = func
84 self.func = func
85
85
86 def __repr__(self):
86 def __repr__(self):
87 return "StatelessInputTransformer(func={0!r})".format(self.func)
87 return "StatelessInputTransformer(func={0!r})".format(self.func)
88
88
89 def push(self, line):
89 def push(self, line):
90 """Send a line of input to the transformer, returning the
90 """Send a line of input to the transformer, returning the
91 transformed input."""
91 transformed input."""
92 return self.func(line)
92 return self.func(line)
93
93
94 def reset(self):
94 def reset(self):
95 """No-op - exists for compatibility."""
95 """No-op - exists for compatibility."""
96 pass
96 pass
97
97
98 class CoroutineInputTransformer(InputTransformer):
98 class CoroutineInputTransformer(InputTransformer):
99 """Wrapper for an input transformer implemented as a coroutine."""
99 """Wrapper for an input transformer implemented as a coroutine."""
100 def __init__(self, coro, **kwargs):
100 def __init__(self, coro, **kwargs):
101 # Prime it
101 # Prime it
102 self.coro = coro(**kwargs)
102 self.coro = coro(**kwargs)
103 next(self.coro)
103 next(self.coro)
104
104
105 def __repr__(self):
105 def __repr__(self):
106 return "CoroutineInputTransformer(coro={0!r})".format(self.coro)
106 return "CoroutineInputTransformer(coro={0!r})".format(self.coro)
107
107
108 def push(self, line):
108 def push(self, line):
109 """Send a line of input to the transformer, returning the
109 """Send a line of input to the transformer, returning the
110 transformed input or None if the transformer is waiting for more
110 transformed input or None if the transformer is waiting for more
111 input.
111 input.
112 """
112 """
113 return self.coro.send(line)
113 return self.coro.send(line)
114
114
115 def reset(self):
115 def reset(self):
116 """Return, transformed any lines that the transformer has
116 """Return, transformed any lines that the transformer has
117 accumulated, and reset its internal state.
117 accumulated, and reset its internal state.
118 """
118 """
119 return self.coro.send(None)
119 return self.coro.send(None)
120
120
121 class TokenInputTransformer(InputTransformer):
121 class TokenInputTransformer(InputTransformer):
122 """Wrapper for a token-based input transformer.
122 """Wrapper for a token-based input transformer.
123
123
124 func should accept a list of tokens (5-tuples, see tokenize docs), and
124 func should accept a list of tokens (5-tuples, see tokenize docs), and
125 return an iterable which can be passed to tokenize.untokenize().
125 return an iterable which can be passed to tokenize.untokenize().
126 """
126 """
127 def __init__(self, func):
127 def __init__(self, func):
128 self.func = func
128 self.func = func
129 self.current_line = ""
129 self.current_line = ""
130 self.line_used = False
130 self.line_used = False
131 self.reset_tokenizer()
131 self.reset_tokenizer()
132
132
133 def reset_tokenizer(self):
133 def reset_tokenizer(self):
134 self.tokenizer = generate_tokens(self.get_line)
134 self.tokenizer = generate_tokens(self.get_line)
135
135
136 def get_line(self):
136 def get_line(self):
137 if self.line_used:
137 if self.line_used:
138 raise TokenError
138 raise TokenError
139 self.line_used = True
139 self.line_used = True
140 return self.current_line
140 return self.current_line
141
141
142 def push(self, line):
142 def push(self, line):
143 self.current_line += line + "\n"
143 self.current_line += line + "\n"
144 if self.current_line.isspace():
144 if self.current_line.isspace():
145 return self.reset()
145 return self.reset()
146
146
147 self.line_used = False
147 self.line_used = False
148 tokens = []
148 tokens = []
149 stop_at_NL = False
149 stop_at_NL = False
150 try:
150 try:
151 for intok in self.tokenizer:
151 for intok in self.tokenizer:
152 tokens.append(intok)
152 tokens.append(intok)
153 t = intok[0]
153 t = intok[0]
154 if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL):
154 if t == tokenize2.NEWLINE or (stop_at_NL and t == tokenize2.NL):
155 # Stop before we try to pull a line we don't have yet
155 # Stop before we try to pull a line we don't have yet
156 break
156 break
157 elif t == tokenize2.ERRORTOKEN:
157 elif t == tokenize2.ERRORTOKEN:
158 stop_at_NL = True
158 stop_at_NL = True
159 except TokenError:
159 except TokenError:
160 # Multi-line statement - stop and try again with the next line
160 # Multi-line statement - stop and try again with the next line
161 self.reset_tokenizer()
161 self.reset_tokenizer()
162 return None
162 return None
163
163
164 return self.output(tokens)
164 return self.output(tokens)
165
165
166 def output(self, tokens):
166 def output(self, tokens):
167 self.current_line = ""
167 self.current_line = ""
168 self.reset_tokenizer()
168 self.reset_tokenizer()
169 return untokenize(self.func(tokens)).rstrip('\n')
169 return untokenize(self.func(tokens)).rstrip('\n')
170
170
171 def reset(self):
171 def reset(self):
172 l = self.current_line
172 l = self.current_line
173 self.current_line = ""
173 self.current_line = ""
174 self.reset_tokenizer()
174 self.reset_tokenizer()
175 if l:
175 if l:
176 return l.rstrip('\n')
176 return l.rstrip('\n')
177
177
178 class assemble_python_lines(TokenInputTransformer):
178 class assemble_python_lines(TokenInputTransformer):
179 def __init__(self):
179 def __init__(self):
180 super(assemble_python_lines, self).__init__(None)
180 super(assemble_python_lines, self).__init__(None)
181
181
182 def output(self, tokens):
182 def output(self, tokens):
183 return self.reset()
183 return self.reset()
184
184
185 @CoroutineInputTransformer.wrap
185 @CoroutineInputTransformer.wrap
186 def assemble_logical_lines():
186 def assemble_logical_lines():
187 """Join lines following explicit line continuations (\)"""
187 """Join lines following explicit line continuations (\)"""
188 line = ''
188 line = ''
189 while True:
189 while True:
190 line = (yield line)
190 line = (yield line)
191 if not line or line.isspace():
191 if not line or line.isspace():
192 continue
192 continue
193
193
194 parts = []
194 parts = []
195 while line is not None:
195 while line is not None:
196 if line.endswith('\\') and (not has_comment(line)):
196 if line.endswith('\\') and (not has_comment(line)):
197 parts.append(line[:-1])
197 parts.append(line[:-1])
198 line = (yield None) # Get another line
198 line = (yield None) # Get another line
199 else:
199 else:
200 parts.append(line)
200 parts.append(line)
201 break
201 break
202
202
203 # Output
203 # Output
204 line = ''.join(parts)
204 line = ''.join(parts)
205
205
206 # Utilities
206 # Utilities
207 def _make_help_call(target, esc, lspace, next_input=None):
207 def _make_help_call(target, esc, lspace, next_input=None):
208 """Prepares a pinfo(2)/psearch call from a target name and the escape
208 """Prepares a pinfo(2)/psearch call from a target name and the escape
209 (i.e. ? or ??)"""
209 (i.e. ? or ??)"""
210 method = 'pinfo2' if esc == '??' \
210 method = 'pinfo2' if esc == '??' \
211 else 'psearch' if '*' in target \
211 else 'psearch' if '*' in target \
212 else 'pinfo'
212 else 'pinfo'
213 arg = " ".join([method, target])
213 arg = " ".join([method, target])
214 if next_input is None:
214 if next_input is None:
215 return '%sget_ipython().magic(%r)' % (lspace, arg)
215 return '%sget_ipython().magic(%r)' % (lspace, arg)
216 else:
216 else:
217 return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \
217 return '%sget_ipython().set_next_input(%r);get_ipython().magic(%r)' % \
218 (lspace, next_input, arg)
218 (lspace, next_input, arg)
219
219
220 # These define the transformations for the different escape characters.
220 # These define the transformations for the different escape characters.
221 def _tr_system(line_info):
221 def _tr_system(line_info):
222 "Translate lines escaped with: !"
222 "Translate lines escaped with: !"
223 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
223 cmd = line_info.line.lstrip().lstrip(ESC_SHELL)
224 return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
224 return '%sget_ipython().system(%r)' % (line_info.pre, cmd)
225
225
226 def _tr_system2(line_info):
226 def _tr_system2(line_info):
227 "Translate lines escaped with: !!"
227 "Translate lines escaped with: !!"
228 cmd = line_info.line.lstrip()[2:]
228 cmd = line_info.line.lstrip()[2:]
229 return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
229 return '%sget_ipython().getoutput(%r)' % (line_info.pre, cmd)
230
230
231 def _tr_help(line_info):
231 def _tr_help(line_info):
232 "Translate lines escaped with: ?/??"
232 "Translate lines escaped with: ?/??"
233 # A naked help line should just fire the intro help screen
233 # A naked help line should just fire the intro help screen
234 if not line_info.line[1:]:
234 if not line_info.line[1:]:
235 return 'get_ipython().show_usage()'
235 return 'get_ipython().show_usage()'
236
236
237 return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
237 return _make_help_call(line_info.ifun, line_info.esc, line_info.pre)
238
238
239 def _tr_magic(line_info):
239 def _tr_magic(line_info):
240 "Translate lines escaped with: %"
240 "Translate lines escaped with: %"
241 tpl = '%sget_ipython().magic(%r)'
241 tpl = '%sget_ipython().magic(%r)'
242 if line_info.line.startswith(ESC_MAGIC2):
242 if line_info.line.startswith(ESC_MAGIC2):
243 return line_info.line
243 return line_info.line
244 cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
244 cmd = ' '.join([line_info.ifun, line_info.the_rest]).strip()
245 return tpl % (line_info.pre, cmd)
245 return tpl % (line_info.pre, cmd)
246
246
247 def _tr_quote(line_info):
247 def _tr_quote(line_info):
248 "Translate lines escaped with: ,"
248 "Translate lines escaped with: ,"
249 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
249 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
250 '", "'.join(line_info.the_rest.split()) )
250 '", "'.join(line_info.the_rest.split()) )
251
251
252 def _tr_quote2(line_info):
252 def _tr_quote2(line_info):
253 "Translate lines escaped with: ;"
253 "Translate lines escaped with: ;"
254 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
254 return '%s%s("%s")' % (line_info.pre, line_info.ifun,
255 line_info.the_rest)
255 line_info.the_rest)
256
256
257 def _tr_paren(line_info):
257 def _tr_paren(line_info):
258 "Translate lines escaped with: /"
258 "Translate lines escaped with: /"
259 return '%s%s(%s)' % (line_info.pre, line_info.ifun,
259 return '%s%s(%s)' % (line_info.pre, line_info.ifun,
260 ", ".join(line_info.the_rest.split()))
260 ", ".join(line_info.the_rest.split()))
261
261
262 tr = { ESC_SHELL : _tr_system,
262 tr = { ESC_SHELL : _tr_system,
263 ESC_SH_CAP : _tr_system2,
263 ESC_SH_CAP : _tr_system2,
264 ESC_HELP : _tr_help,
264 ESC_HELP : _tr_help,
265 ESC_HELP2 : _tr_help,
265 ESC_HELP2 : _tr_help,
266 ESC_MAGIC : _tr_magic,
266 ESC_MAGIC : _tr_magic,
267 ESC_QUOTE : _tr_quote,
267 ESC_QUOTE : _tr_quote,
268 ESC_QUOTE2 : _tr_quote2,
268 ESC_QUOTE2 : _tr_quote2,
269 ESC_PAREN : _tr_paren }
269 ESC_PAREN : _tr_paren }
270
270
271 @StatelessInputTransformer.wrap
271 @StatelessInputTransformer.wrap
272 def escaped_commands(line):
272 def escaped_commands(line):
273 """Transform escaped commands - %magic, !system, ?help + various autocalls.
273 """Transform escaped commands - %magic, !system, ?help + various autocalls.
274 """
274 """
275 if not line or line.isspace():
275 if not line or line.isspace():
276 return line
276 return line
277 lineinf = LineInfo(line)
277 lineinf = LineInfo(line)
278 if lineinf.esc not in tr:
278 if lineinf.esc not in tr:
279 return line
279 return line
280
280
281 return tr[lineinf.esc](lineinf)
281 return tr[lineinf.esc](lineinf)
282
282
283 _initial_space_re = re.compile(r'\s*')
283 _initial_space_re = re.compile(r'\s*')
284
284
285 _help_end_re = re.compile(r"""(%{0,2}
285 _help_end_re = re.compile(r"""(%{0,2}
286 [a-zA-Z_*][\w*]* # Variable name
286 [a-zA-Z_*][\w*]* # Variable name
287 (\.[a-zA-Z_*][\w*]*)* # .etc.etc
287 (\.[a-zA-Z_*][\w*]*)* # .etc.etc
288 )
288 )
289 (\?\??)$ # ? or ??
289 (\?\??)$ # ? or ??
290 """,
290 """,
291 re.VERBOSE)
291 re.VERBOSE)
292
292
293 # Extra pseudotokens for multiline strings and data structures
293 # Extra pseudotokens for multiline strings and data structures
294 _MULTILINE_STRING = object()
294 _MULTILINE_STRING = object()
295 _MULTILINE_STRUCTURE = object()
295 _MULTILINE_STRUCTURE = object()
296
296
297 def _line_tokens(line):
297 def _line_tokens(line):
298 """Helper for has_comment and ends_in_comment_or_string."""
298 """Helper for has_comment and ends_in_comment_or_string."""
299 readline = StringIO(line).readline
299 readline = StringIO(line).readline
300 toktypes = set()
300 toktypes = set()
301 try:
301 try:
302 for t in generate_tokens(readline):
302 for t in generate_tokens(readline):
303 toktypes.add(t[0])
303 toktypes.add(t[0])
304 except TokenError as e:
304 except TokenError as e:
305 # There are only two cases where a TokenError is raised.
305 # There are only two cases where a TokenError is raised.
306 if 'multi-line string' in e.args[0]:
306 if 'multi-line string' in e.args[0]:
307 toktypes.add(_MULTILINE_STRING)
307 toktypes.add(_MULTILINE_STRING)
308 else:
308 else:
309 toktypes.add(_MULTILINE_STRUCTURE)
309 toktypes.add(_MULTILINE_STRUCTURE)
310 return toktypes
310 return toktypes
311
311
312 def has_comment(src):
312 def has_comment(src):
313 """Indicate whether an input line has (i.e. ends in, or is) a comment.
313 """Indicate whether an input line has (i.e. ends in, or is) a comment.
314
314
315 This uses tokenize, so it can distinguish comments from # inside strings.
315 This uses tokenize, so it can distinguish comments from # inside strings.
316
316
317 Parameters
317 Parameters
318 ----------
318 ----------
319 src : string
319 src : string
320 A single line input string.
320 A single line input string.
321
321
322 Returns
322 Returns
323 -------
323 -------
324 comment : bool
324 comment : bool
325 True if source has a comment.
325 True if source has a comment.
326 """
326 """
327 return (tokenize2.COMMENT in _line_tokens(src))
327 return (tokenize2.COMMENT in _line_tokens(src))
328
328
329 def ends_in_comment_or_string(src):
329 def ends_in_comment_or_string(src):
330 """Indicates whether or not an input line ends in a comment or within
330 """Indicates whether or not an input line ends in a comment or within
331 a multiline string.
331 a multiline string.
332
332
333 Parameters
333 Parameters
334 ----------
334 ----------
335 src : string
335 src : string
336 A single line input string.
336 A single line input string.
337
337
338 Returns
338 Returns
339 -------
339 -------
340 comment : bool
340 comment : bool
341 True if source ends in a comment or multiline string.
341 True if source ends in a comment or multiline string.
342 """
342 """
343 toktypes = _line_tokens(src)
343 toktypes = _line_tokens(src)
344 return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes)
344 return (tokenize2.COMMENT in toktypes) or (_MULTILINE_STRING in toktypes)
345
345
346
346
347 @StatelessInputTransformer.wrap
347 @StatelessInputTransformer.wrap
348 def help_end(line):
348 def help_end(line):
349 """Translate lines with ?/?? at the end"""
349 """Translate lines with ?/?? at the end"""
350 m = _help_end_re.search(line)
350 m = _help_end_re.search(line)
351 if m is None or ends_in_comment_or_string(line):
351 if m is None or ends_in_comment_or_string(line):
352 return line
352 return line
353 target = m.group(1)
353 target = m.group(1)
354 esc = m.group(3)
354 esc = m.group(3)
355 lspace = _initial_space_re.match(line).group(0)
355 lspace = _initial_space_re.match(line).group(0)
356
356
357 # If we're mid-command, put it back on the next prompt for the user.
357 # If we're mid-command, put it back on the next prompt for the user.
358 next_input = line.rstrip('?') if line.strip() != m.group(0) else None
358 next_input = line.rstrip('?') if line.strip() != m.group(0) else None
359
359
360 return _make_help_call(target, esc, lspace, next_input)
360 return _make_help_call(target, esc, lspace, next_input)
361
361
362
362
363 @CoroutineInputTransformer.wrap
363 @CoroutineInputTransformer.wrap
364 def cellmagic(end_on_blank_line=False):
364 def cellmagic(end_on_blank_line=False):
365 """Captures & transforms cell magics.
365 """Captures & transforms cell magics.
366
366
367 After a cell magic is started, this stores up any lines it gets until it is
367 After a cell magic is started, this stores up any lines it gets until it is
368 reset (sent None).
368 reset (sent None).
369 """
369 """
370 tpl = 'get_ipython().run_cell_magic(%r, %r, %r)'
370 tpl = 'get_ipython().run_cell_magic(%r, %r, %r)'
371 cellmagic_help_re = re.compile('%%\w+\?')
371 cellmagic_help_re = re.compile('%%\w+\?')
372 line = ''
372 line = ''
373 while True:
373 while True:
374 line = (yield line)
374 line = (yield line)
375 # consume leading empty lines
375 # consume leading empty lines
376 while not line:
376 while not line:
377 line = (yield line)
377 line = (yield line)
378
378
379 if not line.startswith(ESC_MAGIC2):
379 if not line.startswith(ESC_MAGIC2):
380 # This isn't a cell magic, idle waiting for reset then start over
380 # This isn't a cell magic, idle waiting for reset then start over
381 while line is not None:
381 while line is not None:
382 line = (yield line)
382 line = (yield line)
383 continue
383 continue
384
384
385 if cellmagic_help_re.match(line):
385 if cellmagic_help_re.match(line):
386 # This case will be handled by help_end
386 # This case will be handled by help_end
387 continue
387 continue
388
388
389 first = line
389 first = line
390 body = []
390 body = []
391 line = (yield None)
391 line = (yield None)
392 while (line is not None) and \
392 while (line is not None) and \
393 ((line.strip() != '') or not end_on_blank_line):
393 ((line.strip() != '') or not end_on_blank_line):
394 body.append(line)
394 body.append(line)
395 line = (yield None)
395 line = (yield None)
396
396
397 # Output
397 # Output
398 magic_name, _, first = first.partition(' ')
398 magic_name, _, first = first.partition(' ')
399 magic_name = magic_name.lstrip(ESC_MAGIC2)
399 magic_name = magic_name.lstrip(ESC_MAGIC2)
400 line = tpl % (magic_name, first, u'\n'.join(body))
400 line = tpl % (magic_name, first, u'\n'.join(body))
401
401
402
402
403 def _strip_prompts(prompt_re, initial_re=None):
403 def _strip_prompts(prompt_re, initial_re=None):
404 """Remove matching input prompts from a block of input.
404 """Remove matching input prompts from a block of input.
405
405
406 Parameters
406 Parameters
407 ----------
407 ----------
408 prompt_re : regular expression
408 prompt_re : regular expression
409 A regular expression matching any input prompt (including continuation)
409 A regular expression matching any input prompt (including continuation)
410 initial_re : regular expression, optional
410 initial_re : regular expression, optional
411 A regular expression matching only the initial prompt, but not continuation.
411 A regular expression matching only the initial prompt, but not continuation.
412 If no initial expression is given, prompt_re will be used everywhere.
412 If no initial expression is given, prompt_re will be used everywhere.
413 Used mainly for plain Python prompts, where the continuation prompt
413 Used mainly for plain Python prompts, where the continuation prompt
414 ``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
414 ``...`` is a valid Python expression in Python 3, so shouldn't be stripped.
415
415
416 If initial_re and prompt_re differ,
416 If initial_re and prompt_re differ,
417 only initial_re will be tested against the first line.
417 only initial_re will be tested against the first line.
418 If any prompt is found on the first two lines,
418 If any prompt is found on the first two lines,
419 prompts will be stripped from the rest of the block.
419 prompts will be stripped from the rest of the block.
420 """
420 """
421 if initial_re is None:
421 if initial_re is None:
422 initial_re = prompt_re
422 initial_re = prompt_re
423 line = ''
423 line = ''
424 while True:
424 while True:
425 line = (yield line)
425 line = (yield line)
426
426
427 # First line of cell
427 # First line of cell
428 if line is None:
428 if line is None:
429 continue
429 continue
430 out, n1 = initial_re.subn('', line, count=1)
430 out, n1 = initial_re.subn('', line, count=1)
431 line = (yield out)
431 line = (yield out)
432
432
433 if line is None:
433 if line is None:
434 continue
434 continue
435 # check for any prompt on the second line of the cell,
435 # check for any prompt on the second line of the cell,
436 # because people often copy from just after the first prompt,
436 # because people often copy from just after the first prompt,
437 # so we might not see it in the first line.
437 # so we might not see it in the first line.
438 out, n2 = prompt_re.subn('', line, count=1)
438 out, n2 = prompt_re.subn('', line, count=1)
439 line = (yield out)
439 line = (yield out)
440
440
441 if n1 or n2:
441 if n1 or n2:
442 # Found a prompt in the first two lines - check for it in
442 # Found a prompt in the first two lines - check for it in
443 # the rest of the cell as well.
443 # the rest of the cell as well.
444 while line is not None:
444 while line is not None:
445 line = (yield prompt_re.sub('', line, count=1))
445 line = (yield prompt_re.sub('', line, count=1))
446
446
447 else:
447 else:
448 # Prompts not in input - wait for reset
448 # Prompts not in input - wait for reset
449 while line is not None:
449 while line is not None:
450 line = (yield line)
450 line = (yield line)
451
451
452 @CoroutineInputTransformer.wrap
452 @CoroutineInputTransformer.wrap
453 def classic_prompt():
453 def classic_prompt():
454 """Strip the >>>/... prompts of the Python interactive shell."""
454 """Strip the >>>/... prompts of the Python interactive shell."""
455 # FIXME: non-capturing version (?:...) usable?
455 # FIXME: non-capturing version (?:...) usable?
456 prompt_re = re.compile(r'^(>>> ?|\.\.\. ?)')
456 prompt_re = re.compile(r'^(>>> ?|\.\.\. ?)')
457 initial_re = re.compile(r'^(>>> ?)')
457 initial_re = re.compile(r'^(>>> ?)')
458 return _strip_prompts(prompt_re, initial_re)
458 return _strip_prompts(prompt_re, initial_re)
459
459
460 @CoroutineInputTransformer.wrap
460 @CoroutineInputTransformer.wrap
461 def ipy_prompt():
461 def ipy_prompt():
462 """Strip IPython's In [1]:/...: prompts."""
462 """Strip IPython's In [1]:/...: prompts."""
463 # FIXME: non-capturing version (?:...) usable?
463 # FIXME: non-capturing version (?:...) usable?
464 prompt_re = re.compile(r'^(In \[\d+\]: |\ {3,}\.{3,}: )')
464 prompt_re = re.compile(r'^(In \[\d+\]: |\ {3,}\.{3,}: )')
465 return _strip_prompts(prompt_re)
465 return _strip_prompts(prompt_re)
466
466
467
467
468 @CoroutineInputTransformer.wrap
468 @CoroutineInputTransformer.wrap
469 def leading_indent():
469 def leading_indent():
470 """Remove leading indentation.
470 """Remove leading indentation.
471
471
472 If the first line starts with a spaces or tabs, the same whitespace will be
472 If the first line starts with a spaces or tabs, the same whitespace will be
473 removed from each following line until it is reset.
473 removed from each following line until it is reset.
474 """
474 """
475 space_re = re.compile(r'^[ \t]+')
475 space_re = re.compile(r'^[ \t]+')
476 line = ''
476 line = ''
477 while True:
477 while True:
478 line = (yield line)
478 line = (yield line)
479
479
480 if line is None:
480 if line is None:
481 continue
481 continue
482
482
483 m = space_re.match(line)
483 m = space_re.match(line)
484 if m:
484 if m:
485 space = m.group(0)
485 space = m.group(0)
486 while line is not None:
486 while line is not None:
487 if line.startswith(space):
487 if line.startswith(space):
488 line = line[len(space):]
488 line = line[len(space):]
489 line = (yield line)
489 line = (yield line)
490 else:
490 else:
491 # No leading spaces - wait for reset
491 # No leading spaces - wait for reset
492 while line is not None:
492 while line is not None:
493 line = (yield line)
493 line = (yield line)
494
494
495
495
496 @CoroutineInputTransformer.wrap
496 @CoroutineInputTransformer.wrap
497 def strip_encoding_cookie():
497 def strip_encoding_cookie():
498 """Remove encoding comment if found in first two lines
498 """Remove encoding comment if found in first two lines
499
499
500 If the first or second line has the `# coding: utf-8` comment,
500 If the first or second line has the `# coding: utf-8` comment,
501 it will be removed.
501 it will be removed.
502 """
502 """
503 line = ''
503 line = ''
504 while True:
504 while True:
505 line = (yield line)
505 line = (yield line)
506 # check comment on first two lines
506 # check comment on first two lines
507 for i in range(2):
507 for i in range(2):
508 if line is None:
508 if line is None:
509 break
509 break
510 if cookie_comment_re.match(line):
510 if cookie_comment_re.match(line):
511 line = (yield "")
511 line = (yield "")
512 else:
512 else:
513 line = (yield line)
513 line = (yield line)
514
514
515 # no-op on the rest of the cell
515 # no-op on the rest of the cell
516 while line is not None:
516 while line is not None:
517 line = (yield line)
517 line = (yield line)
518
518
519 _assign_pat = \
520 r'''(?P<lhs>(\s*)
521 ([\w\.]+) # Initial identifier
522 (\s*,\s*
523 \*?[\w\.]+)* # Further identifiers for unpacking
524 \s*?,? # Trailing comma
525 )
526 \s*=\s*
527 '''
519
528
520 assign_system_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
529 assign_system_re = re.compile(r'{}!\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
521 r'\s*=\s*!\s*(?P<cmd>.*)')
522 assign_system_template = '%s = get_ipython().getoutput(%r)'
530 assign_system_template = '%s = get_ipython().getoutput(%r)'
523 @StatelessInputTransformer.wrap
531 @StatelessInputTransformer.wrap
524 def assign_from_system(line):
532 def assign_from_system(line):
525 """Transform assignment from system commands (e.g. files = !ls)"""
533 """Transform assignment from system commands (e.g. files = !ls)"""
526 m = assign_system_re.match(line)
534 m = assign_system_re.match(line)
527 if m is None:
535 if m is None:
528 return line
536 return line
529
537
530 return assign_system_template % m.group('lhs', 'cmd')
538 return assign_system_template % m.group('lhs', 'cmd')
531
539
532 assign_magic_re = re.compile(r'(?P<lhs>(\s*)([\w\.]+)((\s*,\s*[\w\.]+)*))'
540 assign_magic_re = re.compile(r'{}%\s*(?P<cmd>.*)'.format(_assign_pat), re.VERBOSE)
533 r'\s*=\s*%\s*(?P<cmd>.*)')
534 assign_magic_template = '%s = get_ipython().magic(%r)'
541 assign_magic_template = '%s = get_ipython().magic(%r)'
535 @StatelessInputTransformer.wrap
542 @StatelessInputTransformer.wrap
536 def assign_from_magic(line):
543 def assign_from_magic(line):
537 """Transform assignment from magic commands (e.g. a = %who_ls)"""
544 """Transform assignment from magic commands (e.g. a = %who_ls)"""
538 m = assign_magic_re.match(line)
545 m = assign_magic_re.match(line)
539 if m is None:
546 if m is None:
540 return line
547 return line
541
548
542 return assign_magic_template % m.group('lhs', 'cmd')
549 return assign_magic_template % m.group('lhs', 'cmd')
@@ -1,475 +1,488 b''
1 import tokenize
1 import tokenize
2 import nose.tools as nt
2 import nose.tools as nt
3
3
4 from IPython.testing import tools as tt
4 from IPython.testing import tools as tt
5 from IPython.utils import py3compat
5 from IPython.utils import py3compat
6 u_fmt = py3compat.u_format
6 u_fmt = py3compat.u_format
7
7
8 from IPython.core import inputtransformer as ipt
8 from IPython.core import inputtransformer as ipt
9
9
10 def transform_and_reset(transformer):
10 def transform_and_reset(transformer):
11 transformer = transformer()
11 transformer = transformer()
12 def transform(inp):
12 def transform(inp):
13 try:
13 try:
14 return transformer.push(inp)
14 return transformer.push(inp)
15 finally:
15 finally:
16 transformer.reset()
16 transformer.reset()
17
17
18 return transform
18 return transform
19
19
20 # Transformer tests
20 # Transformer tests
21 def transform_checker(tests, transformer, **kwargs):
21 def transform_checker(tests, transformer, **kwargs):
22 """Utility to loop over test inputs"""
22 """Utility to loop over test inputs"""
23 transformer = transformer(**kwargs)
23 transformer = transformer(**kwargs)
24 try:
24 try:
25 for inp, tr in tests:
25 for inp, tr in tests:
26 if inp is None:
26 if inp is None:
27 out = transformer.reset()
27 out = transformer.reset()
28 else:
28 else:
29 out = transformer.push(inp)
29 out = transformer.push(inp)
30 nt.assert_equal(out, tr)
30 nt.assert_equal(out, tr)
31 finally:
31 finally:
32 transformer.reset()
32 transformer.reset()
33
33
34 # Data for all the syntax tests in the form of lists of pairs of
34 # Data for all the syntax tests in the form of lists of pairs of
35 # raw/transformed input. We store it here as a global dict so that we can use
35 # raw/transformed input. We store it here as a global dict so that we can use
36 # it both within single-function tests and also to validate the behavior of the
36 # it both within single-function tests and also to validate the behavior of the
37 # larger objects
37 # larger objects
38
38
39 syntax = \
39 syntax = \
40 dict(assign_system =
40 dict(assign_system =
41 [(i,py3compat.u_format(o)) for i,o in \
41 [(i,py3compat.u_format(o)) for i,o in \
42 [(u'a =! ls', "a = get_ipython().getoutput({u}'ls')"),
42 [(u'a =! ls', "a = get_ipython().getoutput({u}'ls')"),
43 (u'b = !ls', "b = get_ipython().getoutput({u}'ls')"),
43 (u'b = !ls', "b = get_ipython().getoutput({u}'ls')"),
44 (u'c= !ls', "c = get_ipython().getoutput({u}'ls')"),
45 (u'd == !ls', u'd == !ls'), # Invalid syntax, but we leave == alone.
44 ('x=1', 'x=1'), # normal input is unmodified
46 ('x=1', 'x=1'), # normal input is unmodified
45 (' ',' '), # blank lines are kept intact
47 (' ',' '), # blank lines are kept intact
48 # Tuple unpacking
49 (u"a, b = !echo 'a\\nb'", u"a, b = get_ipython().getoutput({u}\"echo 'a\\\\nb'\")"),
50 (u"a,= !echo 'a'", u"a, = get_ipython().getoutput({u}\"echo 'a'\")"),
51 (u"a, *bc = !echo 'a\\nb\\nc'", u"a, *bc = get_ipython().getoutput({u}\"echo 'a\\\\nb\\\\nc'\")"),
52 # Tuple unpacking with regular Python expressions, not our syntax.
53 (u"a, b = range(2)", u"a, b = range(2)"),
54 (u"a, = range(1)", u"a, = range(1)"),
55 (u"a, *bc = range(3)", u"a, *bc = range(3)"),
46 ]],
56 ]],
47
57
48 assign_magic =
58 assign_magic =
49 [(i,py3compat.u_format(o)) for i,o in \
59 [(i,py3compat.u_format(o)) for i,o in \
50 [(u'a =% who', "a = get_ipython().magic({u}'who')"),
60 [(u'a =% who', "a = get_ipython().magic({u}'who')"),
51 (u'b = %who', "b = get_ipython().magic({u}'who')"),
61 (u'b = %who', "b = get_ipython().magic({u}'who')"),
62 (u'c= %ls', "c = get_ipython().magic({u}'ls')"),
63 (u'd == %ls', u'd == %ls'), # Invalid syntax, but we leave == alone.
52 ('x=1', 'x=1'), # normal input is unmodified
64 ('x=1', 'x=1'), # normal input is unmodified
53 (' ',' '), # blank lines are kept intact
65 (' ',' '), # blank lines are kept intact
66 (u"a, b = %foo", u"a, b = get_ipython().magic({u}'foo')"),
54 ]],
67 ]],
55
68
56 classic_prompt =
69 classic_prompt =
57 [('>>> x=1', 'x=1'),
70 [('>>> x=1', 'x=1'),
58 ('x=1', 'x=1'), # normal input is unmodified
71 ('x=1', 'x=1'), # normal input is unmodified
59 (' ', ' '), # blank lines are kept intact
72 (' ', ' '), # blank lines are kept intact
60 ],
73 ],
61
74
62 ipy_prompt =
75 ipy_prompt =
63 [('In [1]: x=1', 'x=1'),
76 [('In [1]: x=1', 'x=1'),
64 ('x=1', 'x=1'), # normal input is unmodified
77 ('x=1', 'x=1'), # normal input is unmodified
65 (' ',' '), # blank lines are kept intact
78 (' ',' '), # blank lines are kept intact
66 ],
79 ],
67
80
68 strip_encoding_cookie =
81 strip_encoding_cookie =
69 [
82 [
70 ('# -*- encoding: utf-8 -*-', ''),
83 ('# -*- encoding: utf-8 -*-', ''),
71 ('# coding: latin-1', ''),
84 ('# coding: latin-1', ''),
72 ],
85 ],
73
86
74
87
75 # Tests for the escape transformer to leave normal code alone
88 # Tests for the escape transformer to leave normal code alone
76 escaped_noesc =
89 escaped_noesc =
77 [ (' ', ' '),
90 [ (' ', ' '),
78 ('x=1', 'x=1'),
91 ('x=1', 'x=1'),
79 ],
92 ],
80
93
81 # System calls
94 # System calls
82 escaped_shell =
95 escaped_shell =
83 [(i,py3compat.u_format(o)) for i,o in \
96 [(i,py3compat.u_format(o)) for i,o in \
84 [ (u'!ls', "get_ipython().system({u}'ls')"),
97 [ (u'!ls', "get_ipython().system({u}'ls')"),
85 # Double-escape shell, this means to capture the output of the
98 # Double-escape shell, this means to capture the output of the
86 # subprocess and return it
99 # subprocess and return it
87 (u'!!ls', "get_ipython().getoutput({u}'ls')"),
100 (u'!!ls', "get_ipython().getoutput({u}'ls')"),
88 ]],
101 ]],
89
102
90 # Help/object info
103 # Help/object info
91 escaped_help =
104 escaped_help =
92 [(i,py3compat.u_format(o)) for i,o in \
105 [(i,py3compat.u_format(o)) for i,o in \
93 [ (u'?', 'get_ipython().show_usage()'),
106 [ (u'?', 'get_ipython().show_usage()'),
94 (u'?x1', "get_ipython().magic({u}'pinfo x1')"),
107 (u'?x1', "get_ipython().magic({u}'pinfo x1')"),
95 (u'??x2', "get_ipython().magic({u}'pinfo2 x2')"),
108 (u'??x2', "get_ipython().magic({u}'pinfo2 x2')"),
96 (u'?a.*s', "get_ipython().magic({u}'psearch a.*s')"),
109 (u'?a.*s', "get_ipython().magic({u}'psearch a.*s')"),
97 (u'?%hist1', "get_ipython().magic({u}'pinfo %hist1')"),
110 (u'?%hist1', "get_ipython().magic({u}'pinfo %hist1')"),
98 (u'?%%hist2', "get_ipython().magic({u}'pinfo %%hist2')"),
111 (u'?%%hist2', "get_ipython().magic({u}'pinfo %%hist2')"),
99 (u'?abc = qwe', "get_ipython().magic({u}'pinfo abc')"),
112 (u'?abc = qwe', "get_ipython().magic({u}'pinfo abc')"),
100 ]],
113 ]],
101
114
102 end_help =
115 end_help =
103 [(i,py3compat.u_format(o)) for i,o in \
116 [(i,py3compat.u_format(o)) for i,o in \
104 [ (u'x3?', "get_ipython().magic({u}'pinfo x3')"),
117 [ (u'x3?', "get_ipython().magic({u}'pinfo x3')"),
105 (u'x4??', "get_ipython().magic({u}'pinfo2 x4')"),
118 (u'x4??', "get_ipython().magic({u}'pinfo2 x4')"),
106 (u'%hist1?', "get_ipython().magic({u}'pinfo %hist1')"),
119 (u'%hist1?', "get_ipython().magic({u}'pinfo %hist1')"),
107 (u'%hist2??', "get_ipython().magic({u}'pinfo2 %hist2')"),
120 (u'%hist2??', "get_ipython().magic({u}'pinfo2 %hist2')"),
108 (u'%%hist3?', "get_ipython().magic({u}'pinfo %%hist3')"),
121 (u'%%hist3?', "get_ipython().magic({u}'pinfo %%hist3')"),
109 (u'%%hist4??', "get_ipython().magic({u}'pinfo2 %%hist4')"),
122 (u'%%hist4??', "get_ipython().magic({u}'pinfo2 %%hist4')"),
110 (u'f*?', "get_ipython().magic({u}'psearch f*')"),
123 (u'f*?', "get_ipython().magic({u}'psearch f*')"),
111 (u'ax.*aspe*?', "get_ipython().magic({u}'psearch ax.*aspe*')"),
124 (u'ax.*aspe*?', "get_ipython().magic({u}'psearch ax.*aspe*')"),
112 (u'a = abc?', "get_ipython().set_next_input({u}'a = abc');"
125 (u'a = abc?', "get_ipython().set_next_input({u}'a = abc');"
113 "get_ipython().magic({u}'pinfo abc')"),
126 "get_ipython().magic({u}'pinfo abc')"),
114 (u'a = abc.qe??', "get_ipython().set_next_input({u}'a = abc.qe');"
127 (u'a = abc.qe??', "get_ipython().set_next_input({u}'a = abc.qe');"
115 "get_ipython().magic({u}'pinfo2 abc.qe')"),
128 "get_ipython().magic({u}'pinfo2 abc.qe')"),
116 (u'a = *.items?', "get_ipython().set_next_input({u}'a = *.items');"
129 (u'a = *.items?', "get_ipython().set_next_input({u}'a = *.items');"
117 "get_ipython().magic({u}'psearch *.items')"),
130 "get_ipython().magic({u}'psearch *.items')"),
118 (u'plot(a?', "get_ipython().set_next_input({u}'plot(a');"
131 (u'plot(a?', "get_ipython().set_next_input({u}'plot(a');"
119 "get_ipython().magic({u}'pinfo a')"),
132 "get_ipython().magic({u}'pinfo a')"),
120 (u'a*2 #comment?', 'a*2 #comment?'),
133 (u'a*2 #comment?', 'a*2 #comment?'),
121 ]],
134 ]],
122
135
123 # Explicit magic calls
136 # Explicit magic calls
124 escaped_magic =
137 escaped_magic =
125 [(i,py3compat.u_format(o)) for i,o in \
138 [(i,py3compat.u_format(o)) for i,o in \
126 [ (u'%cd', "get_ipython().magic({u}'cd')"),
139 [ (u'%cd', "get_ipython().magic({u}'cd')"),
127 (u'%cd /home', "get_ipython().magic({u}'cd /home')"),
140 (u'%cd /home', "get_ipython().magic({u}'cd /home')"),
128 # Backslashes need to be escaped.
141 # Backslashes need to be escaped.
129 (u'%cd C:\\User', "get_ipython().magic({u}'cd C:\\\\User')"),
142 (u'%cd C:\\User', "get_ipython().magic({u}'cd C:\\\\User')"),
130 (u' %magic', " get_ipython().magic({u}'magic')"),
143 (u' %magic', " get_ipython().magic({u}'magic')"),
131 ]],
144 ]],
132
145
133 # Quoting with separate arguments
146 # Quoting with separate arguments
134 escaped_quote =
147 escaped_quote =
135 [ (',f', 'f("")'),
148 [ (',f', 'f("")'),
136 (',f x', 'f("x")'),
149 (',f x', 'f("x")'),
137 (' ,f y', ' f("y")'),
150 (' ,f y', ' f("y")'),
138 (',f a b', 'f("a", "b")'),
151 (',f a b', 'f("a", "b")'),
139 ],
152 ],
140
153
141 # Quoting with single argument
154 # Quoting with single argument
142 escaped_quote2 =
155 escaped_quote2 =
143 [ (';f', 'f("")'),
156 [ (';f', 'f("")'),
144 (';f x', 'f("x")'),
157 (';f x', 'f("x")'),
145 (' ;f y', ' f("y")'),
158 (' ;f y', ' f("y")'),
146 (';f a b', 'f("a b")'),
159 (';f a b', 'f("a b")'),
147 ],
160 ],
148
161
149 # Simply apply parens
162 # Simply apply parens
150 escaped_paren =
163 escaped_paren =
151 [ ('/f', 'f()'),
164 [ ('/f', 'f()'),
152 ('/f x', 'f(x)'),
165 ('/f x', 'f(x)'),
153 (' /f y', ' f(y)'),
166 (' /f y', ' f(y)'),
154 ('/f a b', 'f(a, b)'),
167 ('/f a b', 'f(a, b)'),
155 ],
168 ],
156
169
157 # Check that we transform prompts before other transforms
170 # Check that we transform prompts before other transforms
158 mixed =
171 mixed =
159 [(i,py3compat.u_format(o)) for i,o in \
172 [(i,py3compat.u_format(o)) for i,o in \
160 [ (u'In [1]: %lsmagic', "get_ipython().magic({u}'lsmagic')"),
173 [ (u'In [1]: %lsmagic', "get_ipython().magic({u}'lsmagic')"),
161 (u'>>> %lsmagic', "get_ipython().magic({u}'lsmagic')"),
174 (u'>>> %lsmagic', "get_ipython().magic({u}'lsmagic')"),
162 (u'In [2]: !ls', "get_ipython().system({u}'ls')"),
175 (u'In [2]: !ls', "get_ipython().system({u}'ls')"),
163 (u'In [3]: abs?', "get_ipython().magic({u}'pinfo abs')"),
176 (u'In [3]: abs?', "get_ipython().magic({u}'pinfo abs')"),
164 (u'In [4]: b = %who', "b = get_ipython().magic({u}'who')"),
177 (u'In [4]: b = %who', "b = get_ipython().magic({u}'who')"),
165 ]],
178 ]],
166 )
179 )
167
180
168 # multiline syntax examples. Each of these should be a list of lists, with
181 # multiline syntax examples. Each of these should be a list of lists, with
169 # each entry itself having pairs of raw/transformed input. The union (with
182 # each entry itself having pairs of raw/transformed input. The union (with
170 # '\n'.join() of the transformed inputs is what the splitter should produce
183 # '\n'.join() of the transformed inputs is what the splitter should produce
171 # when fed the raw lines one at a time via push.
184 # when fed the raw lines one at a time via push.
172 syntax_ml = \
185 syntax_ml = \
173 dict(classic_prompt =
186 dict(classic_prompt =
174 [ [('>>> for i in range(10):','for i in range(10):'),
187 [ [('>>> for i in range(10):','for i in range(10):'),
175 ('... print i',' print i'),
188 ('... print i',' print i'),
176 ('... ', ''),
189 ('... ', ''),
177 ],
190 ],
178 [('>>> a="""','a="""'),
191 [('>>> a="""','a="""'),
179 ('... 123"""','123"""'),
192 ('... 123"""','123"""'),
180 ],
193 ],
181 [('a="""','a="""'),
194 [('a="""','a="""'),
182 ('... 123','123'),
195 ('... 123','123'),
183 ('... 456"""','456"""'),
196 ('... 456"""','456"""'),
184 ],
197 ],
185 [('a="""','a="""'),
198 [('a="""','a="""'),
186 ('>>> 123','123'),
199 ('>>> 123','123'),
187 ('... 456"""','456"""'),
200 ('... 456"""','456"""'),
188 ],
201 ],
189 [('a="""','a="""'),
202 [('a="""','a="""'),
190 ('123','123'),
203 ('123','123'),
191 ('... 456"""','... 456"""'),
204 ('... 456"""','... 456"""'),
192 ],
205 ],
193 [('....__class__','....__class__'),
206 [('....__class__','....__class__'),
194 ],
207 ],
195 [('a=5', 'a=5'),
208 [('a=5', 'a=5'),
196 ('...', ''),
209 ('...', ''),
197 ],
210 ],
198 [('>>> def f(x):', 'def f(x):'),
211 [('>>> def f(x):', 'def f(x):'),
199 ('...', ''),
212 ('...', ''),
200 ('... return x', ' return x'),
213 ('... return x', ' return x'),
201 ],
214 ],
202 ],
215 ],
203
216
204 ipy_prompt =
217 ipy_prompt =
205 [ [('In [24]: for i in range(10):','for i in range(10):'),
218 [ [('In [24]: for i in range(10):','for i in range(10):'),
206 (' ....: print i',' print i'),
219 (' ....: print i',' print i'),
207 (' ....: ', ''),
220 (' ....: ', ''),
208 ],
221 ],
209 [('In [24]: for i in range(10):','for i in range(10):'),
222 [('In [24]: for i in range(10):','for i in range(10):'),
210 # Qt console prompts expand with spaces, not dots
223 # Qt console prompts expand with spaces, not dots
211 (' ...: print i',' print i'),
224 (' ...: print i',' print i'),
212 (' ...: ', ''),
225 (' ...: ', ''),
213 ],
226 ],
214 [('In [2]: a="""','a="""'),
227 [('In [2]: a="""','a="""'),
215 (' ...: 123"""','123"""'),
228 (' ...: 123"""','123"""'),
216 ],
229 ],
217 [('a="""','a="""'),
230 [('a="""','a="""'),
218 (' ...: 123','123'),
231 (' ...: 123','123'),
219 (' ...: 456"""','456"""'),
232 (' ...: 456"""','456"""'),
220 ],
233 ],
221 [('a="""','a="""'),
234 [('a="""','a="""'),
222 ('In [1]: 123','123'),
235 ('In [1]: 123','123'),
223 (' ...: 456"""','456"""'),
236 (' ...: 456"""','456"""'),
224 ],
237 ],
225 [('a="""','a="""'),
238 [('a="""','a="""'),
226 ('123','123'),
239 ('123','123'),
227 (' ...: 456"""',' ...: 456"""'),
240 (' ...: 456"""',' ...: 456"""'),
228 ],
241 ],
229 ],
242 ],
230
243
231 strip_encoding_cookie =
244 strip_encoding_cookie =
232 [
245 [
233 [
246 [
234 ('# -*- coding: utf-8 -*-', ''),
247 ('# -*- coding: utf-8 -*-', ''),
235 ('foo', 'foo'),
248 ('foo', 'foo'),
236 ],
249 ],
237 [
250 [
238 ('#!/usr/bin/env python', '#!/usr/bin/env python'),
251 ('#!/usr/bin/env python', '#!/usr/bin/env python'),
239 ('# -*- coding: latin-1 -*-', ''),
252 ('# -*- coding: latin-1 -*-', ''),
240 # only the first-two lines
253 # only the first-two lines
241 ('# -*- coding: latin-1 -*-', '# -*- coding: latin-1 -*-'),
254 ('# -*- coding: latin-1 -*-', '# -*- coding: latin-1 -*-'),
242 ],
255 ],
243 ],
256 ],
244
257
245 multiline_datastructure_prompt =
258 multiline_datastructure_prompt =
246 [ [('>>> a = [1,','a = [1,'),
259 [ [('>>> a = [1,','a = [1,'),
247 ('... 2]','2]'),
260 ('... 2]','2]'),
248 ],
261 ],
249 ],
262 ],
250
263
251 multiline_datastructure =
264 multiline_datastructure =
252 [ [('b = ("%s"', None),
265 [ [('b = ("%s"', None),
253 ('# comment', None),
266 ('# comment', None),
254 ('%foo )', 'b = ("%s"\n# comment\n%foo )'),
267 ('%foo )', 'b = ("%s"\n# comment\n%foo )'),
255 ],
268 ],
256 ],
269 ],
257
270
258 multiline_string =
271 multiline_string =
259 [ [("'''foo?", None),
272 [ [("'''foo?", None),
260 ("bar'''", "'''foo?\nbar'''"),
273 ("bar'''", "'''foo?\nbar'''"),
261 ],
274 ],
262 ],
275 ],
263
276
264 leading_indent =
277 leading_indent =
265 [ [(' print "hi"','print "hi"'),
278 [ [(' print "hi"','print "hi"'),
266 ],
279 ],
267 [(' for a in range(5):','for a in range(5):'),
280 [(' for a in range(5):','for a in range(5):'),
268 (' a*2',' a*2'),
281 (' a*2',' a*2'),
269 ],
282 ],
270 [(' a="""','a="""'),
283 [(' a="""','a="""'),
271 (' 123"""','123"""'),
284 (' 123"""','123"""'),
272 ],
285 ],
273 [('a="""','a="""'),
286 [('a="""','a="""'),
274 (' 123"""',' 123"""'),
287 (' 123"""',' 123"""'),
275 ],
288 ],
276 ],
289 ],
277
290
278 cellmagic =
291 cellmagic =
279 [ [(u'%%foo a', None),
292 [ [(u'%%foo a', None),
280 (None, u_fmt("get_ipython().run_cell_magic({u}'foo', {u}'a', {u}'')")),
293 (None, u_fmt("get_ipython().run_cell_magic({u}'foo', {u}'a', {u}'')")),
281 ],
294 ],
282 [(u'%%bar 123', None),
295 [(u'%%bar 123', None),
283 (u'hello', None),
296 (u'hello', None),
284 (None , u_fmt("get_ipython().run_cell_magic({u}'bar', {u}'123', {u}'hello')")),
297 (None , u_fmt("get_ipython().run_cell_magic({u}'bar', {u}'123', {u}'hello')")),
285 ],
298 ],
286 [(u'a=5', 'a=5'),
299 [(u'a=5', 'a=5'),
287 (u'%%cellmagic', '%%cellmagic'),
300 (u'%%cellmagic', '%%cellmagic'),
288 ],
301 ],
289 ],
302 ],
290
303
291 escaped =
304 escaped =
292 [ [('%abc def \\', None),
305 [ [('%abc def \\', None),
293 ('ghi', u_fmt("get_ipython().magic({u}'abc def ghi')")),
306 ('ghi', u_fmt("get_ipython().magic({u}'abc def ghi')")),
294 ],
307 ],
295 [('%abc def \\', None),
308 [('%abc def \\', None),
296 ('ghi\\', None),
309 ('ghi\\', None),
297 (None, u_fmt("get_ipython().magic({u}'abc def ghi')")),
310 (None, u_fmt("get_ipython().magic({u}'abc def ghi')")),
298 ],
311 ],
299 ],
312 ],
300
313
301 assign_magic =
314 assign_magic =
302 [ [(u'a = %bc de \\', None),
315 [ [(u'a = %bc de \\', None),
303 (u'fg', u_fmt("a = get_ipython().magic({u}'bc de fg')")),
316 (u'fg', u_fmt("a = get_ipython().magic({u}'bc de fg')")),
304 ],
317 ],
305 [(u'a = %bc de \\', None),
318 [(u'a = %bc de \\', None),
306 (u'fg\\', None),
319 (u'fg\\', None),
307 (None, u_fmt("a = get_ipython().magic({u}'bc de fg')")),
320 (None, u_fmt("a = get_ipython().magic({u}'bc de fg')")),
308 ],
321 ],
309 ],
322 ],
310
323
311 assign_system =
324 assign_system =
312 [ [(u'a = !bc de \\', None),
325 [ [(u'a = !bc de \\', None),
313 (u'fg', u_fmt("a = get_ipython().getoutput({u}'bc de fg')")),
326 (u'fg', u_fmt("a = get_ipython().getoutput({u}'bc de fg')")),
314 ],
327 ],
315 [(u'a = !bc de \\', None),
328 [(u'a = !bc de \\', None),
316 (u'fg\\', None),
329 (u'fg\\', None),
317 (None, u_fmt("a = get_ipython().getoutput({u}'bc de fg')")),
330 (None, u_fmt("a = get_ipython().getoutput({u}'bc de fg')")),
318 ],
331 ],
319 ],
332 ],
320 )
333 )
321
334
322
335
323 def test_assign_system():
336 def test_assign_system():
324 tt.check_pairs(transform_and_reset(ipt.assign_from_system), syntax['assign_system'])
337 tt.check_pairs(transform_and_reset(ipt.assign_from_system), syntax['assign_system'])
325
338
326 def test_assign_magic():
339 def test_assign_magic():
327 tt.check_pairs(transform_and_reset(ipt.assign_from_magic), syntax['assign_magic'])
340 tt.check_pairs(transform_and_reset(ipt.assign_from_magic), syntax['assign_magic'])
328
341
329 def test_classic_prompt():
342 def test_classic_prompt():
330 tt.check_pairs(transform_and_reset(ipt.classic_prompt), syntax['classic_prompt'])
343 tt.check_pairs(transform_and_reset(ipt.classic_prompt), syntax['classic_prompt'])
331 for example in syntax_ml['classic_prompt']:
344 for example in syntax_ml['classic_prompt']:
332 transform_checker(example, ipt.classic_prompt)
345 transform_checker(example, ipt.classic_prompt)
333 for example in syntax_ml['multiline_datastructure_prompt']:
346 for example in syntax_ml['multiline_datastructure_prompt']:
334 transform_checker(example, ipt.classic_prompt)
347 transform_checker(example, ipt.classic_prompt)
335
348
336
349
337 def test_ipy_prompt():
350 def test_ipy_prompt():
338 tt.check_pairs(transform_and_reset(ipt.ipy_prompt), syntax['ipy_prompt'])
351 tt.check_pairs(transform_and_reset(ipt.ipy_prompt), syntax['ipy_prompt'])
339 for example in syntax_ml['ipy_prompt']:
352 for example in syntax_ml['ipy_prompt']:
340 transform_checker(example, ipt.ipy_prompt)
353 transform_checker(example, ipt.ipy_prompt)
341
354
342 def test_coding_cookie():
355 def test_coding_cookie():
343 tt.check_pairs(transform_and_reset(ipt.strip_encoding_cookie), syntax['strip_encoding_cookie'])
356 tt.check_pairs(transform_and_reset(ipt.strip_encoding_cookie), syntax['strip_encoding_cookie'])
344 for example in syntax_ml['strip_encoding_cookie']:
357 for example in syntax_ml['strip_encoding_cookie']:
345 transform_checker(example, ipt.strip_encoding_cookie)
358 transform_checker(example, ipt.strip_encoding_cookie)
346
359
347 def test_assemble_logical_lines():
360 def test_assemble_logical_lines():
348 tests = \
361 tests = \
349 [ [(u"a = \\", None),
362 [ [(u"a = \\", None),
350 (u"123", u"a = 123"),
363 (u"123", u"a = 123"),
351 ],
364 ],
352 [(u"a = \\", None), # Test resetting when within a multi-line string
365 [(u"a = \\", None), # Test resetting when within a multi-line string
353 (u"12 *\\", None),
366 (u"12 *\\", None),
354 (None, u"a = 12 *"),
367 (None, u"a = 12 *"),
355 ],
368 ],
356 [(u"# foo\\", u"# foo\\"), # Comments can't be continued like this
369 [(u"# foo\\", u"# foo\\"), # Comments can't be continued like this
357 ],
370 ],
358 ]
371 ]
359 for example in tests:
372 for example in tests:
360 transform_checker(example, ipt.assemble_logical_lines)
373 transform_checker(example, ipt.assemble_logical_lines)
361
374
362 def test_assemble_python_lines():
375 def test_assemble_python_lines():
363 tests = \
376 tests = \
364 [ [(u"a = '''", None),
377 [ [(u"a = '''", None),
365 (u"abc'''", u"a = '''\nabc'''"),
378 (u"abc'''", u"a = '''\nabc'''"),
366 ],
379 ],
367 [(u"a = '''", None), # Test resetting when within a multi-line string
380 [(u"a = '''", None), # Test resetting when within a multi-line string
368 (u"def", None),
381 (u"def", None),
369 (None, u"a = '''\ndef"),
382 (None, u"a = '''\ndef"),
370 ],
383 ],
371 [(u"a = [1,", None),
384 [(u"a = [1,", None),
372 (u"2]", u"a = [1,\n2]"),
385 (u"2]", u"a = [1,\n2]"),
373 ],
386 ],
374 [(u"a = [1,", None), # Test resetting when within a multi-line string
387 [(u"a = [1,", None), # Test resetting when within a multi-line string
375 (u"2,", None),
388 (u"2,", None),
376 (None, u"a = [1,\n2,"),
389 (None, u"a = [1,\n2,"),
377 ],
390 ],
378 ] + syntax_ml['multiline_datastructure']
391 ] + syntax_ml['multiline_datastructure']
379 for example in tests:
392 for example in tests:
380 transform_checker(example, ipt.assemble_python_lines)
393 transform_checker(example, ipt.assemble_python_lines)
381
394
382
395
383 def test_help_end():
396 def test_help_end():
384 tt.check_pairs(transform_and_reset(ipt.help_end), syntax['end_help'])
397 tt.check_pairs(transform_and_reset(ipt.help_end), syntax['end_help'])
385
398
386 def test_escaped_noesc():
399 def test_escaped_noesc():
387 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_noesc'])
400 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_noesc'])
388
401
389
402
390 def test_escaped_shell():
403 def test_escaped_shell():
391 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_shell'])
404 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_shell'])
392
405
393
406
394 def test_escaped_help():
407 def test_escaped_help():
395 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_help'])
408 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_help'])
396
409
397
410
398 def test_escaped_magic():
411 def test_escaped_magic():
399 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_magic'])
412 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_magic'])
400
413
401
414
402 def test_escaped_quote():
415 def test_escaped_quote():
403 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote'])
416 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote'])
404
417
405
418
406 def test_escaped_quote2():
419 def test_escaped_quote2():
407 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote2'])
420 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_quote2'])
408
421
409
422
410 def test_escaped_paren():
423 def test_escaped_paren():
411 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_paren'])
424 tt.check_pairs(transform_and_reset(ipt.escaped_commands), syntax['escaped_paren'])
412
425
413
426
414 def test_cellmagic():
427 def test_cellmagic():
415 for example in syntax_ml['cellmagic']:
428 for example in syntax_ml['cellmagic']:
416 transform_checker(example, ipt.cellmagic)
429 transform_checker(example, ipt.cellmagic)
417
430
418 line_example = [(u'%%bar 123', None),
431 line_example = [(u'%%bar 123', None),
419 (u'hello', None),
432 (u'hello', None),
420 (u'' , u_fmt("get_ipython().run_cell_magic({u}'bar', {u}'123', {u}'hello')")),
433 (u'' , u_fmt("get_ipython().run_cell_magic({u}'bar', {u}'123', {u}'hello')")),
421 ]
434 ]
422 transform_checker(line_example, ipt.cellmagic, end_on_blank_line=True)
435 transform_checker(line_example, ipt.cellmagic, end_on_blank_line=True)
423
436
424 def test_has_comment():
437 def test_has_comment():
425 tests = [('text', False),
438 tests = [('text', False),
426 ('text #comment', True),
439 ('text #comment', True),
427 ('text #comment\n', True),
440 ('text #comment\n', True),
428 ('#comment', True),
441 ('#comment', True),
429 ('#comment\n', True),
442 ('#comment\n', True),
430 ('a = "#string"', False),
443 ('a = "#string"', False),
431 ('a = "#string" # comment', True),
444 ('a = "#string" # comment', True),
432 ('a #comment not "string"', True),
445 ('a #comment not "string"', True),
433 ]
446 ]
434 tt.check_pairs(ipt.has_comment, tests)
447 tt.check_pairs(ipt.has_comment, tests)
435
448
436 @ipt.TokenInputTransformer.wrap
449 @ipt.TokenInputTransformer.wrap
437 def decistmt(tokens):
450 def decistmt(tokens):
438 """Substitute Decimals for floats in a string of statements.
451 """Substitute Decimals for floats in a string of statements.
439
452
440 Based on an example from the tokenize module docs.
453 Based on an example from the tokenize module docs.
441 """
454 """
442 result = []
455 result = []
443 for toknum, tokval, _, _, _ in tokens:
456 for toknum, tokval, _, _, _ in tokens:
444 if toknum == tokenize.NUMBER and '.' in tokval: # replace NUMBER tokens
457 if toknum == tokenize.NUMBER and '.' in tokval: # replace NUMBER tokens
445 for newtok in [
458 for newtok in [
446 (tokenize.NAME, 'Decimal'),
459 (tokenize.NAME, 'Decimal'),
447 (tokenize.OP, '('),
460 (tokenize.OP, '('),
448 (tokenize.STRING, repr(tokval)),
461 (tokenize.STRING, repr(tokval)),
449 (tokenize.OP, ')')
462 (tokenize.OP, ')')
450 ]:
463 ]:
451 yield newtok
464 yield newtok
452 else:
465 else:
453 yield (toknum, tokval)
466 yield (toknum, tokval)
454
467
455
468
456
469
457 def test_token_input_transformer():
470 def test_token_input_transformer():
458 tests = [(u'1.2', u_fmt(u"Decimal ({u}'1.2')")),
471 tests = [(u'1.2', u_fmt(u"Decimal ({u}'1.2')")),
459 (u'"1.2"', u'"1.2"'),
472 (u'"1.2"', u'"1.2"'),
460 ]
473 ]
461 tt.check_pairs(transform_and_reset(decistmt), tests)
474 tt.check_pairs(transform_and_reset(decistmt), tests)
462 ml_tests = \
475 ml_tests = \
463 [ [(u"a = 1.2; b = '''x", None),
476 [ [(u"a = 1.2; b = '''x", None),
464 (u"y'''", u_fmt(u"a =Decimal ({u}'1.2');b ='''x\ny'''")),
477 (u"y'''", u_fmt(u"a =Decimal ({u}'1.2');b ='''x\ny'''")),
465 ],
478 ],
466 [(u"a = [1.2,", None),
479 [(u"a = [1.2,", None),
467 (u"3]", u_fmt(u"a =[Decimal ({u}'1.2'),\n3 ]")),
480 (u"3]", u_fmt(u"a =[Decimal ({u}'1.2'),\n3 ]")),
468 ],
481 ],
469 [(u"a = '''foo", None), # Test resetting when within a multi-line string
482 [(u"a = '''foo", None), # Test resetting when within a multi-line string
470 (u"bar", None),
483 (u"bar", None),
471 (None, u"a = '''foo\nbar"),
484 (None, u"a = '''foo\nbar"),
472 ],
485 ],
473 ]
486 ]
474 for example in ml_tests:
487 for example in ml_tests:
475 transform_checker(example, decistmt)
488 transform_checker(example, decistmt)
General Comments 0
You need to be logged in to leave comments. Login now