##// END OF EJS Templates
autoindent deprecated since IPython 5
Thomas Kluyver -
Show More
@@ -1,207 +1,207 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 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 (deprecated)"""
85 print("%autoindent is deprecated: you can now paste multiple lines "
86 "without turning autoindentation off.")
85 print("%autoindent is deprecated since IPython 5: you can now paste "
86 "multiple lines without turning autoindentation off.")
87 87 self.shell.set_autoindent()
88 88 print("Automatic indentation is:",['OFF','ON'][self.shell.autoindent])
89 89
90 90 @line_magic
91 91 def cpaste(self, parameter_s=''):
92 92 """Paste & execute a pre-formatted code block from clipboard.
93 93
94 94 You must terminate the block with '--' (two minus-signs) or Ctrl-D
95 95 alone on the line. You can also provide your own sentinel with '%paste
96 96 -s %%' ('%%' is the new sentinel for this operation).
97 97
98 98 The block is dedented prior to execution to enable execution of method
99 99 definitions. '>' and '+' characters at the beginning of a line are
100 100 ignored, to allow pasting directly from e-mails, diff files and
101 101 doctests (the '...' continuation prompt is also stripped). The
102 102 executed block is also assigned to variable named 'pasted_block' for
103 103 later editing with '%edit pasted_block'.
104 104
105 105 You can also pass a variable name as an argument, e.g. '%cpaste foo'.
106 106 This assigns the pasted block to variable 'foo' as string, without
107 107 dedenting or executing it (preceding >>> and + is still stripped)
108 108
109 109 '%cpaste -r' re-executes the block previously entered by cpaste.
110 110 '%cpaste -q' suppresses any additional output messages.
111 111
112 112 Do not be alarmed by garbled output on Windows (it's a readline bug).
113 113 Just press enter and type -- (and press enter again) and the block
114 114 will be what was just pasted.
115 115
116 116 IPython statements (magics, shell escapes) are not supported (yet).
117 117
118 118 See also
119 119 --------
120 120 paste: automatically pull code from clipboard.
121 121
122 122 Examples
123 123 --------
124 124 ::
125 125
126 126 In [8]: %cpaste
127 127 Pasting code; enter '--' alone on the line to stop.
128 128 :>>> a = ["world!", "Hello"]
129 129 :>>> print " ".join(sorted(a))
130 130 :--
131 131 Hello world!
132 132 """
133 133 opts, name = self.parse_options(parameter_s, 'rqs:', mode='string')
134 134 if 'r' in opts:
135 135 self.rerun_pasted()
136 136 return
137 137
138 138 quiet = ('q' in opts)
139 139
140 140 sentinel = opts.get('s', u'--')
141 141 block = '\n'.join(get_pasted_lines(sentinel, quiet=quiet))
142 142 self.store_or_execute(block, name)
143 143
144 144 @line_magic
145 145 def paste(self, parameter_s=''):
146 146 """Paste & execute a pre-formatted code block from clipboard.
147 147
148 148 The text is pulled directly from the clipboard without user
149 149 intervention and printed back on the screen before execution (unless
150 150 the -q flag is given to force quiet mode).
151 151
152 152 The block is dedented prior to execution to enable execution of method
153 153 definitions. '>' and '+' characters at the beginning of a line are
154 154 ignored, to allow pasting directly from e-mails, diff files and
155 155 doctests (the '...' continuation prompt is also stripped). The
156 156 executed block is also assigned to variable named 'pasted_block' for
157 157 later editing with '%edit pasted_block'.
158 158
159 159 You can also pass a variable name as an argument, e.g. '%paste foo'.
160 160 This assigns the pasted block to variable 'foo' as string, without
161 161 executing it (preceding >>> and + is still stripped).
162 162
163 163 Options:
164 164
165 165 -r: re-executes the block previously entered by cpaste.
166 166
167 167 -q: quiet mode: do not echo the pasted text back to the terminal.
168 168
169 169 IPython statements (magics, shell escapes) are not supported (yet).
170 170
171 171 See also
172 172 --------
173 173 cpaste: manually paste code into terminal until you mark its end.
174 174 """
175 175 opts, name = self.parse_options(parameter_s, 'rq', mode='string')
176 176 if 'r' in opts:
177 177 self.rerun_pasted()
178 178 return
179 179 try:
180 180 block = self.shell.hooks.clipboard_get()
181 181 except TryNext as clipboard_exc:
182 182 message = getattr(clipboard_exc, 'args')
183 183 if message:
184 184 error(message[0])
185 185 else:
186 186 error('Could not get text from the clipboard.')
187 187 return
188 188 except ClipboardEmpty:
189 189 raise UsageError("The clipboard appears to be empty")
190 190
191 191 # By default, echo back to terminal unless quiet mode is requested
192 192 if 'q' not in opts:
193 193 write = self.shell.write
194 194 write(self.shell.pycolorize(block))
195 195 if not block.endswith('\n'):
196 196 write('\n')
197 197 write("## -- End pasted text --\n")
198 198
199 199 self.store_or_execute(block, name)
200 200
201 201 # Class-level: add a '%cls' magic only on Windows
202 202 if sys.platform == 'win32':
203 203 @line_magic
204 204 def cls(self, s):
205 205 """Clear screen.
206 206 """
207 207 os.system("cls")
General Comments 0
You need to be logged in to leave comments. Login now