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