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