Show More
@@ -1,206 +1,206 b'' | |||||
1 | """Extra magics for terminal use.""" |
|
1 | """Extra magics for terminal use.""" | |
2 |
|
2 | |||
3 | # Copyright (c) IPython Development Team. |
|
3 | # Copyright (c) IPython Development Team. | |
4 | # Distributed under the terms of the Modified BSD License. |
|
4 | # Distributed under the terms of the Modified BSD License. | |
5 |
|
5 | |||
6 |
|
6 | |||
7 | from logging import error |
|
7 | from logging import error | |
8 | import os |
|
8 | import os | |
9 | import sys |
|
9 | import sys | |
10 |
|
10 | |||
11 | from IPython.core.error import TryNext, UsageError |
|
11 | from IPython.core.error import TryNext, UsageError | |
12 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
12 | from IPython.core.inputsplitter import IPythonInputSplitter | |
13 | from IPython.core.magic import Magics, magics_class, line_magic |
|
13 | from IPython.core.magic import Magics, magics_class, line_magic | |
14 | from IPython.lib.clipboard import ClipboardEmpty |
|
14 | from IPython.lib.clipboard import ClipboardEmpty | |
15 | from IPython.utils.text import SList, strip_email_quotes |
|
15 | from IPython.utils.text import SList, strip_email_quotes | |
16 | from IPython.utils import py3compat |
|
16 | from IPython.utils import py3compat | |
17 |
|
17 | |||
18 | def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False): |
|
18 | def get_pasted_lines(sentinel, l_input=py3compat.input, quiet=False): | |
19 | """ Yield pasted lines until the user enters the given sentinel value. |
|
19 | """ Yield pasted lines until the user enters the given sentinel value. | |
20 | """ |
|
20 | """ | |
21 | if not quiet: |
|
21 | if not quiet: | |
22 | print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ |
|
22 | print("Pasting code; enter '%s' alone on the line to stop or use Ctrl-D." \ | |
23 | % sentinel) |
|
23 | % sentinel) | |
24 | prompt = ":" |
|
24 | prompt = ":" | |
25 | else: |
|
25 | else: | |
26 | prompt = "" |
|
26 | prompt = "" | |
27 | while True: |
|
27 | while True: | |
28 | try: |
|
28 | try: | |
29 |
l = |
|
29 | l = l_input(prompt) | |
30 | if l == sentinel: |
|
30 | if l == sentinel: | |
31 | return |
|
31 | return | |
32 | else: |
|
32 | else: | |
33 | yield l |
|
33 | yield l | |
34 | except EOFError: |
|
34 | except EOFError: | |
35 | print('<EOF>') |
|
35 | print('<EOF>') | |
36 | return |
|
36 | return | |
37 |
|
37 | |||
38 |
|
38 | |||
39 | @magics_class |
|
39 | @magics_class | |
40 | class TerminalMagics(Magics): |
|
40 | class TerminalMagics(Magics): | |
41 | def __init__(self, shell): |
|
41 | def __init__(self, shell): | |
42 | super(TerminalMagics, self).__init__(shell) |
|
42 | super(TerminalMagics, self).__init__(shell) | |
43 | self.input_splitter = IPythonInputSplitter() |
|
43 | self.input_splitter = IPythonInputSplitter() | |
44 |
|
44 | |||
45 | def store_or_execute(self, block, name): |
|
45 | def store_or_execute(self, block, name): | |
46 | """ Execute a block, or store it in a variable, per the user's request. |
|
46 | """ Execute a block, or store it in a variable, per the user's request. | |
47 | """ |
|
47 | """ | |
48 | if name: |
|
48 | if name: | |
49 | # If storing it for further editing |
|
49 | # If storing it for further editing | |
50 | self.shell.user_ns[name] = SList(block.splitlines()) |
|
50 | self.shell.user_ns[name] = SList(block.splitlines()) | |
51 | print("Block assigned to '%s'" % name) |
|
51 | print("Block assigned to '%s'" % name) | |
52 | else: |
|
52 | else: | |
53 | b = self.preclean_input(block) |
|
53 | b = self.preclean_input(block) | |
54 | self.shell.user_ns['pasted_block'] = b |
|
54 | self.shell.user_ns['pasted_block'] = b | |
55 | self.shell.using_paste_magics = True |
|
55 | self.shell.using_paste_magics = True | |
56 | try: |
|
56 | try: | |
57 | self.shell.run_cell(b) |
|
57 | self.shell.run_cell(b) | |
58 | finally: |
|
58 | finally: | |
59 | self.shell.using_paste_magics = False |
|
59 | self.shell.using_paste_magics = False | |
60 |
|
60 | |||
61 | def preclean_input(self, block): |
|
61 | def preclean_input(self, block): | |
62 | lines = block.splitlines() |
|
62 | lines = block.splitlines() | |
63 | while lines and not lines[0].strip(): |
|
63 | while lines and not lines[0].strip(): | |
64 | lines = lines[1:] |
|
64 | lines = lines[1:] | |
65 | return strip_email_quotes('\n'.join(lines)) |
|
65 | return strip_email_quotes('\n'.join(lines)) | |
66 |
|
66 | |||
67 | def rerun_pasted(self, name='pasted_block'): |
|
67 | def rerun_pasted(self, name='pasted_block'): | |
68 | """ Rerun a previously pasted command. |
|
68 | """ Rerun a previously pasted command. | |
69 | """ |
|
69 | """ | |
70 | b = self.shell.user_ns.get(name) |
|
70 | b = self.shell.user_ns.get(name) | |
71 |
|
71 | |||
72 | # Sanity checks |
|
72 | # Sanity checks | |
73 | if b is None: |
|
73 | if b is None: | |
74 | raise UsageError('No previous pasted block available') |
|
74 | raise UsageError('No previous pasted block available') | |
75 | if not isinstance(b, str): |
|
75 | if not isinstance(b, str): | |
76 | raise UsageError( |
|
76 | raise UsageError( | |
77 | "Variable 'pasted_block' is not a string, can't execute") |
|
77 | "Variable 'pasted_block' is not a string, can't execute") | |
78 |
|
78 | |||
79 | print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))) |
|
79 | print("Re-executing '%s...' (%d chars)"% (b.split('\n',1)[0], len(b))) | |
80 | self.shell.run_cell(b) |
|
80 | self.shell.run_cell(b) | |
81 |
|
81 | |||
82 | @line_magic |
|
82 | @line_magic | |
83 | def autoindent(self, parameter_s = ''): |
|
83 | def autoindent(self, parameter_s = ''): | |
84 | """Toggle autoindent on/off (if available).""" |
|
84 | """Toggle autoindent on/off (if available).""" | |
85 |
|
85 | |||
86 | self.shell.set_autoindent() |
|
86 | self.shell.set_autoindent() | |
87 | print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent]) |
|
87 | print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent]) | |
88 |
|
88 | |||
89 | @line_magic |
|
89 | @line_magic | |
90 | def cpaste(self, parameter_s=''): |
|
90 | def cpaste(self, parameter_s=''): | |
91 | """Paste & execute a pre-formatted code block from clipboard. |
|
91 | """Paste & execute a pre-formatted code block from clipboard. | |
92 |
|
92 | |||
93 | You must terminate the block with '--' (two minus-signs) or Ctrl-D |
|
93 | You must terminate the block with '--' (two minus-signs) or Ctrl-D | |
94 | alone on the line. You can also provide your own sentinel with '%paste |
|
94 | alone on the line. You can also provide your own sentinel with '%paste | |
95 | -s %%' ('%%' is the new sentinel for this operation). |
|
95 | -s %%' ('%%' is the new sentinel for this operation). | |
96 |
|
96 | |||
97 | The block is dedented prior to execution to enable execution of method |
|
97 | The block is dedented prior to execution to enable execution of method | |
98 | definitions. '>' and '+' characters at the beginning of a line are |
|
98 | definitions. '>' and '+' characters at the beginning of a line are | |
99 | ignored, to allow pasting directly from e-mails, diff files and |
|
99 | ignored, to allow pasting directly from e-mails, diff files and | |
100 | doctests (the '...' continuation prompt is also stripped). The |
|
100 | doctests (the '...' continuation prompt is also stripped). The | |
101 | executed block is also assigned to variable named 'pasted_block' for |
|
101 | executed block is also assigned to variable named 'pasted_block' for | |
102 | later editing with '%edit pasted_block'. |
|
102 | later editing with '%edit pasted_block'. | |
103 |
|
103 | |||
104 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. |
|
104 | You can also pass a variable name as an argument, e.g. '%cpaste foo'. | |
105 | This assigns the pasted block to variable 'foo' as string, without |
|
105 | This assigns the pasted block to variable 'foo' as string, without | |
106 | dedenting or executing it (preceding >>> and + is still stripped) |
|
106 | dedenting or executing it (preceding >>> and + is still stripped) | |
107 |
|
107 | |||
108 | '%cpaste -r' re-executes the block previously entered by cpaste. |
|
108 | '%cpaste -r' re-executes the block previously entered by cpaste. | |
109 | '%cpaste -q' suppresses any additional output messages. |
|
109 | '%cpaste -q' suppresses any additional output messages. | |
110 |
|
110 | |||
111 | Do not be alarmed by garbled output on Windows (it's a readline bug). |
|
111 | Do not be alarmed by garbled output on Windows (it's a readline bug). | |
112 | Just press enter and type -- (and press enter again) and the block |
|
112 | Just press enter and type -- (and press enter again) and the block | |
113 | will be what was just pasted. |
|
113 | will be what was just pasted. | |
114 |
|
114 | |||
115 | IPython statements (magics, shell escapes) are not supported (yet). |
|
115 | IPython statements (magics, shell escapes) are not supported (yet). | |
116 |
|
116 | |||
117 | See also |
|
117 | See also | |
118 | -------- |
|
118 | -------- | |
119 | paste: automatically pull code from clipboard. |
|
119 | paste: automatically pull code from clipboard. | |
120 |
|
120 | |||
121 | Examples |
|
121 | Examples | |
122 | -------- |
|
122 | -------- | |
123 | :: |
|
123 | :: | |
124 |
|
124 | |||
125 | In [8]: %cpaste |
|
125 | In [8]: %cpaste | |
126 | Pasting code; enter '--' alone on the line to stop. |
|
126 | Pasting code; enter '--' alone on the line to stop. | |
127 | :>>> a = ["world!", "Hello"] |
|
127 | :>>> a = ["world!", "Hello"] | |
128 | :>>> print " ".join(sorted(a)) |
|
128 | :>>> print " ".join(sorted(a)) | |
129 | :-- |
|
129 | :-- | |
130 | Hello world! |
|
130 | Hello world! | |
131 | """ |
|
131 | """ | |
132 | opts, name = self.parse_options(parameter_s, 'rqs:', mode='string') |
|
132 | opts, name = self.parse_options(parameter_s, 'rqs:', mode='string') | |
133 | if 'r' in opts: |
|
133 | if 'r' in opts: | |
134 | self.rerun_pasted() |
|
134 | self.rerun_pasted() | |
135 | return |
|
135 | return | |
136 |
|
136 | |||
137 | quiet = ('q' in opts) |
|
137 | quiet = ('q' in opts) | |
138 |
|
138 | |||
139 | sentinel = opts.get('s', u'--') |
|
139 | sentinel = opts.get('s', u'--') | |
140 | block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet)) |
|
140 | block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet)) | |
141 | self.store_or_execute(block, name) |
|
141 | self.store_or_execute(block, name) | |
142 |
|
142 | |||
143 | @line_magic |
|
143 | @line_magic | |
144 | def paste(self, parameter_s=''): |
|
144 | def paste(self, parameter_s=''): | |
145 | """Paste & execute a pre-formatted code block from clipboard. |
|
145 | """Paste & execute a pre-formatted code block from clipboard. | |
146 |
|
146 | |||
147 | The text is pulled directly from the clipboard without user |
|
147 | The text is pulled directly from the clipboard without user | |
148 | intervention and printed back on the screen before execution (unless |
|
148 | intervention and printed back on the screen before execution (unless | |
149 | the -q flag is given to force quiet mode). |
|
149 | the -q flag is given to force quiet mode). | |
150 |
|
150 | |||
151 | The block is dedented prior to execution to enable execution of method |
|
151 | The block is dedented prior to execution to enable execution of method | |
152 | definitions. '>' and '+' characters at the beginning of a line are |
|
152 | definitions. '>' and '+' characters at the beginning of a line are | |
153 | ignored, to allow pasting directly from e-mails, diff files and |
|
153 | ignored, to allow pasting directly from e-mails, diff files and | |
154 | doctests (the '...' continuation prompt is also stripped). The |
|
154 | doctests (the '...' continuation prompt is also stripped). The | |
155 | executed block is also assigned to variable named 'pasted_block' for |
|
155 | executed block is also assigned to variable named 'pasted_block' for | |
156 | later editing with '%edit pasted_block'. |
|
156 | later editing with '%edit pasted_block'. | |
157 |
|
157 | |||
158 | You can also pass a variable name as an argument, e.g. '%paste foo'. |
|
158 | You can also pass a variable name as an argument, e.g. '%paste foo'. | |
159 | This assigns the pasted block to variable 'foo' as string, without |
|
159 | This assigns the pasted block to variable 'foo' as string, without | |
160 | executing it (preceding >>> and + is still stripped). |
|
160 | executing it (preceding >>> and + is still stripped). | |
161 |
|
161 | |||
162 | Options: |
|
162 | Options: | |
163 |
|
163 | |||
164 | -r: re-executes the block previously entered by cpaste. |
|
164 | -r: re-executes the block previously entered by cpaste. | |
165 |
|
165 | |||
166 | -q: quiet mode: do not echo the pasted text back to the terminal. |
|
166 | -q: quiet mode: do not echo the pasted text back to the terminal. | |
167 |
|
167 | |||
168 | IPython statements (magics, shell escapes) are not supported (yet). |
|
168 | IPython statements (magics, shell escapes) are not supported (yet). | |
169 |
|
169 | |||
170 | See also |
|
170 | See also | |
171 | -------- |
|
171 | -------- | |
172 | cpaste: manually paste code into terminal until you mark its end. |
|
172 | cpaste: manually paste code into terminal until you mark its end. | |
173 | """ |
|
173 | """ | |
174 | opts, name = self.parse_options(parameter_s, 'rq', mode='string') |
|
174 | opts, name = self.parse_options(parameter_s, 'rq', mode='string') | |
175 | if 'r' in opts: |
|
175 | if 'r' in opts: | |
176 | self.rerun_pasted() |
|
176 | self.rerun_pasted() | |
177 | return |
|
177 | return | |
178 | try: |
|
178 | try: | |
179 | block = self.shell.hooks.clipboard_get() |
|
179 | block = self.shell.hooks.clipboard_get() | |
180 | except TryNext as clipboard_exc: |
|
180 | except TryNext as clipboard_exc: | |
181 | message = getattr(clipboard_exc, 'args') |
|
181 | message = getattr(clipboard_exc, 'args') | |
182 | if message: |
|
182 | if message: | |
183 | error(message[0]) |
|
183 | error(message[0]) | |
184 | else: |
|
184 | else: | |
185 | error('Could not get text from the clipboard.') |
|
185 | error('Could not get text from the clipboard.') | |
186 | return |
|
186 | return | |
187 | except ClipboardEmpty: |
|
187 | except ClipboardEmpty: | |
188 | raise UsageError("The clipboard appears to be empty") |
|
188 | raise UsageError("The clipboard appears to be empty") | |
189 |
|
189 | |||
190 | # By default, echo back to terminal unless quiet mode is requested |
|
190 | # By default, echo back to terminal unless quiet mode is requested | |
191 | if 'q' not in opts: |
|
191 | if 'q' not in opts: | |
192 | write = self.shell.write |
|
192 | write = self.shell.write | |
193 | write(self.shell.pycolorize(block)) |
|
193 | write(self.shell.pycolorize(block)) | |
194 | if not block.endswith('\n'): |
|
194 | if not block.endswith('\n'): | |
195 | write('\n') |
|
195 | write('\n') | |
196 | write("## -- End pasted text --\n") |
|
196 | write("## -- End pasted text --\n") | |
197 |
|
197 | |||
198 | self.store_or_execute(block, name) |
|
198 | self.store_or_execute(block, name) | |
199 |
|
199 | |||
200 | # Class-level: add a '%cls' magic only on Windows |
|
200 | # Class-level: add a '%cls' magic only on Windows | |
201 | if sys.platform == 'win32': |
|
201 | if sys.platform == 'win32': | |
202 | @line_magic |
|
202 | @line_magic | |
203 | def cls(self, s): |
|
203 | def cls(self, s): | |
204 | """Clear screen. |
|
204 | """Clear screen. | |
205 | """ |
|
205 | """ | |
206 | os.system("cls") |
|
206 | os.system("cls") |
General Comments 0
You need to be logged in to leave comments.
Login now