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