Show More
@@ -1,293 +1,293 b'' | |||
|
1 | 1 | # Standard library imports |
|
2 | 2 | from subprocess import Popen |
|
3 | 3 | |
|
4 | 4 | # System library imports |
|
5 | 5 | from PyQt4 import QtCore, QtGui |
|
6 | 6 | |
|
7 | 7 | # Local imports |
|
8 | 8 | from IPython.core.inputsplitter import IPythonInputSplitter |
|
9 | 9 | from IPython.core.usage import default_banner |
|
10 | 10 | from frontend_widget import FrontendWidget |
|
11 | 11 | |
|
12 | 12 | |
|
13 | 13 | class IPythonPromptBlock(object): |
|
14 | 14 | """ An internal storage object for IPythonWidget. |
|
15 | 15 | """ |
|
16 | 16 | def __init__(self, block, length, number): |
|
17 | 17 | self.block = block |
|
18 | 18 | self.length = length |
|
19 | 19 | self.number = number |
|
20 | 20 | |
|
21 | 21 | |
|
22 | 22 | class IPythonWidget(FrontendWidget): |
|
23 | 23 | """ A FrontendWidget for an IPython kernel. |
|
24 | 24 | """ |
|
25 | 25 | |
|
26 | 26 | # Signal emitted when an editor is needed for a file and the editor has been |
|
27 | 27 | # specified as 'custom'. See 'set_editor' for more information. |
|
28 |
custom_edit_requested = QtCore.pyqtSignal(object, |
|
|
28 | custom_edit_requested = QtCore.pyqtSignal(object, object) | |
|
29 | 29 | |
|
30 | 30 | # The default stylesheet: black text on a white background. |
|
31 | 31 | default_stylesheet = """ |
|
32 | 32 | .error { color: red; } |
|
33 | 33 | .in-prompt { color: navy; } |
|
34 | 34 | .in-prompt-number { font-weight: bold; } |
|
35 | 35 | .out-prompt { color: darkred; } |
|
36 | 36 | .out-prompt-number { font-weight: bold; } |
|
37 | 37 | """ |
|
38 | 38 | |
|
39 | 39 | # A dark stylesheet: white text on a black background. |
|
40 | 40 | dark_stylesheet = """ |
|
41 | 41 | QPlainTextEdit, QTextEdit { background-color: black; color: white } |
|
42 | 42 | QFrame { border: 1px solid grey; } |
|
43 | 43 | .error { color: red; } |
|
44 | 44 | .in-prompt { color: lime; } |
|
45 | 45 | .in-prompt-number { color: lime; font-weight: bold; } |
|
46 | 46 | .out-prompt { color: red; } |
|
47 | 47 | .out-prompt-number { color: red; font-weight: bold; } |
|
48 | 48 | """ |
|
49 | 49 | |
|
50 | 50 | # Default prompts. |
|
51 | 51 | in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' |
|
52 | 52 | out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' |
|
53 | 53 | |
|
54 | 54 | # FrontendWidget protected class variables. |
|
55 | 55 | #_input_splitter_class = IPythonInputSplitter |
|
56 | 56 | |
|
57 | 57 | # IPythonWidget protected class variables. |
|
58 | 58 | _payload_source_edit = 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic' |
|
59 | 59 | _payload_source_page = 'IPython.zmq.page.page' |
|
60 | 60 | |
|
61 | 61 | #--------------------------------------------------------------------------- |
|
62 | 62 | # 'object' interface |
|
63 | 63 | #--------------------------------------------------------------------------- |
|
64 | 64 | |
|
65 | 65 | def __init__(self, *args, **kw): |
|
66 | 66 | super(IPythonWidget, self).__init__(*args, **kw) |
|
67 | 67 | |
|
68 | 68 | # IPythonWidget protected variables. |
|
69 | 69 | self._previous_prompt_obj = None |
|
70 | 70 | |
|
71 | 71 | # Set a default editor and stylesheet. |
|
72 | 72 | self.set_editor('default') |
|
73 | 73 | self.reset_styling() |
|
74 | 74 | |
|
75 | 75 | #--------------------------------------------------------------------------- |
|
76 | 76 | # 'BaseFrontendMixin' abstract interface |
|
77 | 77 | #--------------------------------------------------------------------------- |
|
78 | 78 | |
|
79 | 79 | def _handle_pyout(self, msg): |
|
80 | 80 | """ Reimplemented for IPython-style "display hook". |
|
81 | 81 | """ |
|
82 | 82 | if not self._hidden and self._is_from_this_session(msg): |
|
83 | 83 | content = msg['content'] |
|
84 | 84 | prompt_number = content['prompt_number'] |
|
85 | 85 | self._append_plain_text(content['output_sep']) |
|
86 | 86 | self._append_html(self._make_out_prompt(prompt_number)) |
|
87 | 87 | self._append_plain_text(content['data'] + '\n' + |
|
88 | 88 | content['output_sep2']) |
|
89 | 89 | |
|
90 | 90 | #--------------------------------------------------------------------------- |
|
91 | 91 | # 'FrontendWidget' interface |
|
92 | 92 | #--------------------------------------------------------------------------- |
|
93 | 93 | |
|
94 | 94 | def execute_file(self, path, hidden=False): |
|
95 | 95 | """ Reimplemented to use the 'run' magic. |
|
96 | 96 | """ |
|
97 | 97 | self.execute('run %s' % path, hidden=hidden) |
|
98 | 98 | |
|
99 | 99 | #--------------------------------------------------------------------------- |
|
100 | 100 | # 'FrontendWidget' protected interface |
|
101 | 101 | #--------------------------------------------------------------------------- |
|
102 | 102 | |
|
103 | 103 | def _get_banner(self): |
|
104 | 104 | """ Reimplemented to return IPython's default banner. |
|
105 | 105 | """ |
|
106 | 106 | return default_banner + '\n' |
|
107 | 107 | |
|
108 | 108 | def _process_execute_error(self, msg): |
|
109 | 109 | """ Reimplemented for IPython-style traceback formatting. |
|
110 | 110 | """ |
|
111 | 111 | content = msg['content'] |
|
112 | 112 | traceback_lines = content['traceback'][:] |
|
113 | 113 | traceback = ''.join(traceback_lines) |
|
114 | 114 | traceback = traceback.replace(' ', ' ') |
|
115 | 115 | traceback = traceback.replace('\n', '<br/>') |
|
116 | 116 | |
|
117 | 117 | ename = content['ename'] |
|
118 | 118 | ename_styled = '<span class="error">%s</span>' % ename |
|
119 | 119 | traceback = traceback.replace(ename, ename_styled) |
|
120 | 120 | |
|
121 | 121 | self._append_html(traceback) |
|
122 | 122 | |
|
123 | 123 | def _process_execute_payload(self, item): |
|
124 | 124 | """ Reimplemented to handle %edit and paging payloads. |
|
125 | 125 | """ |
|
126 | 126 | if item['source'] == self._payload_source_edit: |
|
127 | 127 | self.edit(item['filename'], item['line_number']) |
|
128 | 128 | return True |
|
129 | 129 | elif item['source'] == self._payload_source_page: |
|
130 | 130 | self._page(item['data']) |
|
131 | 131 | return True |
|
132 | 132 | else: |
|
133 | 133 | return False |
|
134 | 134 | |
|
135 | 135 | def _show_interpreter_prompt(self, number=None, input_sep='\n'): |
|
136 | 136 | """ Reimplemented for IPython-style prompts. |
|
137 | 137 | """ |
|
138 | 138 | # TODO: If a number was not specified, make a prompt number request. |
|
139 | 139 | if number is None: |
|
140 | 140 | number = 0 |
|
141 | 141 | |
|
142 | 142 | # Show a new prompt and save information about it so that it can be |
|
143 | 143 | # updated later if the prompt number turns out to be wrong. |
|
144 | 144 | self._append_plain_text(input_sep) |
|
145 | 145 | self._show_prompt(self._make_in_prompt(number), html=True) |
|
146 | 146 | block = self._control.document().lastBlock() |
|
147 | 147 | length = len(self._prompt) |
|
148 | 148 | self._previous_prompt_obj = IPythonPromptBlock(block, length, number) |
|
149 | 149 | |
|
150 | 150 | # Update continuation prompt to reflect (possibly) new prompt length. |
|
151 | 151 | self._set_continuation_prompt( |
|
152 | 152 | self._make_continuation_prompt(self._prompt), html=True) |
|
153 | 153 | |
|
154 | 154 | def _show_interpreter_prompt_for_reply(self, msg): |
|
155 | 155 | """ Reimplemented for IPython-style prompts. |
|
156 | 156 | """ |
|
157 | 157 | # Update the old prompt number if necessary. |
|
158 | 158 | content = msg['content'] |
|
159 | 159 | previous_prompt_number = content['prompt_number'] |
|
160 | 160 | if self._previous_prompt_obj and \ |
|
161 | 161 | self._previous_prompt_obj.number != previous_prompt_number: |
|
162 | 162 | block = self._previous_prompt_obj.block |
|
163 | 163 | if block.isValid(): |
|
164 | 164 | |
|
165 | 165 | # Remove the old prompt and insert a new prompt. |
|
166 | 166 | cursor = QtGui.QTextCursor(block) |
|
167 | 167 | cursor.movePosition(QtGui.QTextCursor.Right, |
|
168 | 168 | QtGui.QTextCursor.KeepAnchor, |
|
169 | 169 | self._previous_prompt_obj.length) |
|
170 | 170 | prompt = self._make_in_prompt(previous_prompt_number) |
|
171 | 171 | self._prompt = self._insert_html_fetching_plain_text( |
|
172 | 172 | cursor, prompt) |
|
173 | 173 | |
|
174 | 174 | # When the HTML is inserted, Qt blows away the syntax |
|
175 | 175 | # highlighting for the line, so we need to rehighlight it. |
|
176 | 176 | self._highlighter.rehighlightBlock(cursor.block()) |
|
177 | 177 | |
|
178 | 178 | self._previous_prompt_obj = None |
|
179 | 179 | |
|
180 | 180 | # Show a new prompt with the kernel's estimated prompt number. |
|
181 | 181 | next_prompt = content['next_prompt'] |
|
182 | 182 | self._show_interpreter_prompt(next_prompt['prompt_number'], |
|
183 | 183 | next_prompt['input_sep']) |
|
184 | 184 | |
|
185 | 185 | #--------------------------------------------------------------------------- |
|
186 | 186 | # 'IPythonWidget' interface |
|
187 | 187 | #--------------------------------------------------------------------------- |
|
188 | 188 | |
|
189 | 189 | def edit(self, filename, line=None): |
|
190 | 190 | """ Opens a Python script for editing. |
|
191 | 191 | |
|
192 | 192 | Parameters: |
|
193 | 193 | ----------- |
|
194 | 194 | filename : str |
|
195 | 195 | A path to a local system file. |
|
196 | 196 | |
|
197 | 197 | line : int, optional |
|
198 | 198 | A line of interest in the file. |
|
199 | 199 | |
|
200 | 200 | Raises: |
|
201 | 201 | ------- |
|
202 | 202 | OSError |
|
203 | 203 | If the editor command cannot be executed. |
|
204 | 204 | """ |
|
205 | 205 | if self._editor == 'default': |
|
206 | 206 | url = QtCore.QUrl.fromLocalFile(filename) |
|
207 | 207 | if not QtGui.QDesktopServices.openUrl(url): |
|
208 | 208 | message = 'Failed to open %s with the default application' |
|
209 | 209 | raise OSError(message % repr(filename)) |
|
210 | 210 | elif self._editor is None: |
|
211 | 211 | self.custom_edit_requested.emit(filename, line) |
|
212 | 212 | else: |
|
213 | 213 | Popen(self._editor + [filename]) |
|
214 | 214 | |
|
215 | 215 | def reset_styling(self): |
|
216 | 216 | """ Restores the default IPythonWidget styling. |
|
217 | 217 | """ |
|
218 | 218 | self.set_styling(self.default_stylesheet, syntax_style='default') |
|
219 | 219 | #self.set_styling(self.dark_stylesheet, syntax_style='monokai') |
|
220 | 220 | |
|
221 | 221 | def set_editor(self, editor): |
|
222 | 222 | """ Sets the editor to use with the %edit magic. |
|
223 | 223 | |
|
224 | 224 | Parameters: |
|
225 | 225 | ----------- |
|
226 | 226 | editor : str or sequence of str |
|
227 | 227 | A command suitable for use with Popen. This command will be executed |
|
228 | 228 | with a single argument--a filename--when editing is requested. |
|
229 | 229 | |
|
230 | 230 | This parameter also takes two special values: |
|
231 | 231 | 'default' : Files will be edited with the system default |
|
232 | 232 | application for Python files. |
|
233 | 233 | 'custom' : Emit a 'custom_edit_requested(str, int)' signal |
|
234 | 234 | instead of opening an editor. |
|
235 | 235 | """ |
|
236 | 236 | if editor == 'default': |
|
237 | 237 | self._editor = 'default' |
|
238 | 238 | elif editor == 'custom': |
|
239 | 239 | self._editor = None |
|
240 | 240 | elif isinstance(editor, basestring): |
|
241 | 241 | self._editor = [ editor ] |
|
242 | 242 | else: |
|
243 | 243 | self._editor = list(editor) |
|
244 | 244 | |
|
245 | 245 | def set_styling(self, stylesheet, syntax_style=None): |
|
246 | 246 | """ Sets the IPythonWidget styling. |
|
247 | 247 | |
|
248 | 248 | Parameters: |
|
249 | 249 | ----------- |
|
250 | 250 | stylesheet : str |
|
251 | 251 | A CSS stylesheet. The stylesheet can contain classes for: |
|
252 | 252 | 1. Qt: QPlainTextEdit, QFrame, QWidget, etc |
|
253 | 253 | 2. Pygments: .c, .k, .o, etc (see PygmentsHighlighter) |
|
254 | 254 | 3. IPython: .error, .in-prompt, .out-prompt, etc. |
|
255 | 255 | |
|
256 | 256 | syntax_style : str or None [default None] |
|
257 | 257 | If specified, use the Pygments style with given name. Otherwise, |
|
258 | 258 | the stylesheet is queried for Pygments style information. |
|
259 | 259 | """ |
|
260 | 260 | self.setStyleSheet(stylesheet) |
|
261 | 261 | self._control.document().setDefaultStyleSheet(stylesheet) |
|
262 | 262 | if self._page_control: |
|
263 | 263 | self._page_control.document().setDefaultStyleSheet(stylesheet) |
|
264 | 264 | |
|
265 | 265 | if syntax_style is None: |
|
266 | 266 | self._highlighter.set_style_sheet(stylesheet) |
|
267 | 267 | else: |
|
268 | 268 | self._highlighter.set_style(syntax_style) |
|
269 | 269 | |
|
270 | 270 | #--------------------------------------------------------------------------- |
|
271 | 271 | # 'IPythonWidget' protected interface |
|
272 | 272 | #--------------------------------------------------------------------------- |
|
273 | 273 | |
|
274 | 274 | def _make_in_prompt(self, number): |
|
275 | 275 | """ Given a prompt number, returns an HTML In prompt. |
|
276 | 276 | """ |
|
277 | 277 | body = self.in_prompt % number |
|
278 | 278 | return '<span class="in-prompt">%s</span>' % body |
|
279 | 279 | |
|
280 | 280 | def _make_continuation_prompt(self, prompt): |
|
281 | 281 | """ Given a plain text version of an In prompt, returns an HTML |
|
282 | 282 | continuation prompt. |
|
283 | 283 | """ |
|
284 | 284 | end_chars = '...: ' |
|
285 | 285 | space_count = len(prompt.lstrip('\n')) - len(end_chars) |
|
286 | 286 | body = ' ' * space_count + end_chars |
|
287 | 287 | return '<span class="in-prompt">%s</span>' % body |
|
288 | 288 | |
|
289 | 289 | def _make_out_prompt(self, number): |
|
290 | 290 | """ Given a prompt number, returns an HTML Out prompt. |
|
291 | 291 | """ |
|
292 | 292 | body = self.out_prompt % number |
|
293 | 293 | return '<span class="out-prompt">%s</span>' % body |
@@ -1,359 +1,365 b'' | |||
|
1 | 1 | import inspect |
|
2 | 2 | import re |
|
3 | 3 | import sys |
|
4 | 4 | from subprocess import Popen, PIPE |
|
5 | 5 | |
|
6 | 6 | from IPython.core.interactiveshell import ( |
|
7 | 7 | InteractiveShell, InteractiveShellABC |
|
8 | 8 | ) |
|
9 | 9 | from IPython.core.displayhook import DisplayHook |
|
10 | 10 | from IPython.core.macro import Macro |
|
11 | 11 | from IPython.utils.path import get_py_filename |
|
12 | 12 | from IPython.utils.text import StringTypes |
|
13 | 13 | from IPython.utils.traitlets import Instance, Type, Dict |
|
14 | 14 | from IPython.utils.warn import warn |
|
15 | 15 | from IPython.zmq.session import extract_header |
|
16 | 16 | from IPython.core.payloadpage import install_payload_page |
|
17 | 17 | |
|
18 | 18 | |
|
19 | 19 | # Install the payload version of page. |
|
20 | 20 | install_payload_page() |
|
21 | 21 | |
|
22 | 22 | |
|
23 | 23 | class ZMQDisplayHook(DisplayHook): |
|
24 | 24 | |
|
25 | 25 | session = Instance('IPython.zmq.session.Session') |
|
26 | 26 | pub_socket = Instance('zmq.Socket') |
|
27 | 27 | parent_header = Dict({}) |
|
28 | 28 | |
|
29 | 29 | def set_parent(self, parent): |
|
30 | 30 | """Set the parent for outbound messages.""" |
|
31 | 31 | self.parent_header = extract_header(parent) |
|
32 | 32 | |
|
33 | 33 | def start_displayhook(self): |
|
34 | 34 | self.msg = self.session.msg(u'pyout', {}, parent=self.parent_header) |
|
35 | 35 | |
|
36 | 36 | def write_output_prompt(self): |
|
37 | 37 | """Write the output prompt.""" |
|
38 | 38 | if self.do_full_cache: |
|
39 | 39 | self.msg['content']['output_sep'] = self.output_sep |
|
40 | 40 | self.msg['content']['prompt_string'] = str(self.prompt_out) |
|
41 | 41 | self.msg['content']['prompt_number'] = self.prompt_count |
|
42 | 42 | self.msg['content']['output_sep2'] = self.output_sep2 |
|
43 | 43 | |
|
44 | 44 | def write_result_repr(self, result_repr): |
|
45 | 45 | self.msg['content']['data'] = result_repr |
|
46 | 46 | |
|
47 | 47 | def finish_displayhook(self): |
|
48 | 48 | """Finish up all displayhook activities.""" |
|
49 | 49 | self.pub_socket.send_json(self.msg) |
|
50 | 50 | self.msg = None |
|
51 | 51 | |
|
52 | 52 | |
|
53 | 53 | class ZMQInteractiveShell(InteractiveShell): |
|
54 | 54 | """A subclass of InteractiveShell for ZMQ.""" |
|
55 | 55 | |
|
56 | 56 | displayhook_class = Type(ZMQDisplayHook) |
|
57 | 57 | |
|
58 | 58 | def system(self, cmd): |
|
59 | 59 | cmd = self.var_expand(cmd, depth=2) |
|
60 | 60 | sys.stdout.flush() |
|
61 | 61 | sys.stderr.flush() |
|
62 | 62 | p = Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE) |
|
63 | 63 | for line in p.stdout.read().split('\n'): |
|
64 | 64 | if len(line) > 0: |
|
65 | 65 | print line |
|
66 | 66 | for line in p.stderr.read().split('\n'): |
|
67 | 67 | if len(line) > 0: |
|
68 | 68 | print line |
|
69 | 69 | p.wait() |
|
70 | 70 | |
|
71 | 71 | def init_io(self): |
|
72 | 72 | # This will just use sys.stdout and sys.stderr. If you want to |
|
73 | 73 | # override sys.stdout and sys.stderr themselves, you need to do that |
|
74 | 74 | # *before* instantiating this class, because Term holds onto |
|
75 | 75 | # references to the underlying streams. |
|
76 | 76 | import IPython.utils.io |
|
77 | 77 | Term = IPython.utils.io.IOTerm() |
|
78 | 78 | IPython.utils.io.Term = Term |
|
79 | 79 | |
|
80 | 80 | def magic_edit(self,parameter_s='',last_call=['','']): |
|
81 | 81 | """Bring up an editor and execute the resulting code. |
|
82 | 82 | |
|
83 | 83 | Usage: |
|
84 | 84 | %edit [options] [args] |
|
85 | 85 | |
|
86 | 86 | %edit runs IPython's editor hook. The default version of this hook is |
|
87 | 87 | set to call the __IPYTHON__.rc.editor command. This is read from your |
|
88 | 88 | environment variable $EDITOR. If this isn't found, it will default to |
|
89 | 89 | vi under Linux/Unix and to notepad under Windows. See the end of this |
|
90 | 90 | docstring for how to change the editor hook. |
|
91 | 91 | |
|
92 | 92 | You can also set the value of this editor via the command line option |
|
93 | 93 | '-editor' or in your ipythonrc file. This is useful if you wish to use |
|
94 | 94 | specifically for IPython an editor different from your typical default |
|
95 | 95 | (and for Windows users who typically don't set environment variables). |
|
96 | 96 | |
|
97 | 97 | This command allows you to conveniently edit multi-line code right in |
|
98 | 98 | your IPython session. |
|
99 | 99 | |
|
100 | 100 | If called without arguments, %edit opens up an empty editor with a |
|
101 | 101 | temporary file and will execute the contents of this file when you |
|
102 | 102 | close it (don't forget to save it!). |
|
103 | 103 | |
|
104 | 104 | |
|
105 | 105 | Options: |
|
106 | 106 | |
|
107 | 107 | -n <number>: open the editor at a specified line number. By default, |
|
108 | 108 | the IPython editor hook uses the unix syntax 'editor +N filename', but |
|
109 | 109 | you can configure this by providing your own modified hook if your |
|
110 | 110 | favorite editor supports line-number specifications with a different |
|
111 | 111 | syntax. |
|
112 | 112 | |
|
113 | 113 | -p: this will call the editor with the same data as the previous time |
|
114 | 114 | it was used, regardless of how long ago (in your current session) it |
|
115 | 115 | was. |
|
116 | 116 | |
|
117 | 117 | -r: use 'raw' input. This option only applies to input taken from the |
|
118 | 118 | user's history. By default, the 'processed' history is used, so that |
|
119 | 119 | magics are loaded in their transformed version to valid Python. If |
|
120 | 120 | this option is given, the raw input as typed as the command line is |
|
121 | 121 | used instead. When you exit the editor, it will be executed by |
|
122 | 122 | IPython's own processor. |
|
123 | 123 | |
|
124 | 124 | -x: do not execute the edited code immediately upon exit. This is |
|
125 | 125 | mainly useful if you are editing programs which need to be called with |
|
126 | 126 | command line arguments, which you can then do using %run. |
|
127 | 127 | |
|
128 | 128 | |
|
129 | 129 | Arguments: |
|
130 | 130 | |
|
131 | 131 | If arguments are given, the following possibilites exist: |
|
132 | 132 | |
|
133 | 133 | - The arguments are numbers or pairs of colon-separated numbers (like |
|
134 | 134 | 1 4:8 9). These are interpreted as lines of previous input to be |
|
135 | 135 | loaded into the editor. The syntax is the same of the %macro command. |
|
136 | 136 | |
|
137 | 137 | - If the argument doesn't start with a number, it is evaluated as a |
|
138 | 138 | variable and its contents loaded into the editor. You can thus edit |
|
139 | 139 | any string which contains python code (including the result of |
|
140 | 140 | previous edits). |
|
141 | 141 | |
|
142 | 142 | - If the argument is the name of an object (other than a string), |
|
143 | 143 | IPython will try to locate the file where it was defined and open the |
|
144 | 144 | editor at the point where it is defined. You can use `%edit function` |
|
145 | 145 | to load an editor exactly at the point where 'function' is defined, |
|
146 | 146 | edit it and have the file be executed automatically. |
|
147 | 147 | |
|
148 | 148 | If the object is a macro (see %macro for details), this opens up your |
|
149 | 149 | specified editor with a temporary file containing the macro's data. |
|
150 | 150 | Upon exit, the macro is reloaded with the contents of the file. |
|
151 | 151 | |
|
152 | 152 | Note: opening at an exact line is only supported under Unix, and some |
|
153 | 153 | editors (like kedit and gedit up to Gnome 2.8) do not understand the |
|
154 | 154 | '+NUMBER' parameter necessary for this feature. Good editors like |
|
155 | 155 | (X)Emacs, vi, jed, pico and joe all do. |
|
156 | 156 | |
|
157 | 157 | - If the argument is not found as a variable, IPython will look for a |
|
158 | 158 | file with that name (adding .py if necessary) and load it into the |
|
159 | 159 | editor. It will execute its contents with execfile() when you exit, |
|
160 | 160 | loading any code in the file into your interactive namespace. |
|
161 | 161 | |
|
162 | 162 | After executing your code, %edit will return as output the code you |
|
163 | 163 | typed in the editor (except when it was an existing file). This way |
|
164 | 164 | you can reload the code in further invocations of %edit as a variable, |
|
165 | 165 | via _<NUMBER> or Out[<NUMBER>], where <NUMBER> is the prompt number of |
|
166 | 166 | the output. |
|
167 | 167 | |
|
168 | 168 | Note that %edit is also available through the alias %ed. |
|
169 | 169 | |
|
170 | 170 | This is an example of creating a simple function inside the editor and |
|
171 | 171 | then modifying it. First, start up the editor: |
|
172 | 172 | |
|
173 | 173 | In [1]: ed |
|
174 | 174 | Editing... done. Executing edited code... |
|
175 | 175 | Out[1]: 'def foo():n print "foo() was defined in an editing session"n' |
|
176 | 176 | |
|
177 | 177 | We can then call the function foo(): |
|
178 | 178 | |
|
179 | 179 | In [2]: foo() |
|
180 | 180 | foo() was defined in an editing session |
|
181 | 181 | |
|
182 | 182 | Now we edit foo. IPython automatically loads the editor with the |
|
183 | 183 | (temporary) file where foo() was previously defined: |
|
184 | 184 | |
|
185 | 185 | In [3]: ed foo |
|
186 | 186 | Editing... done. Executing edited code... |
|
187 | 187 | |
|
188 | 188 | And if we call foo() again we get the modified version: |
|
189 | 189 | |
|
190 | 190 | In [4]: foo() |
|
191 | 191 | foo() has now been changed! |
|
192 | 192 | |
|
193 | 193 | Here is an example of how to edit a code snippet successive |
|
194 | 194 | times. First we call the editor: |
|
195 | 195 | |
|
196 | 196 | In [5]: ed |
|
197 | 197 | Editing... done. Executing edited code... |
|
198 | 198 | hello |
|
199 | 199 | Out[5]: "print 'hello'n" |
|
200 | 200 | |
|
201 | 201 | Now we call it again with the previous output (stored in _): |
|
202 | 202 | |
|
203 | 203 | In [6]: ed _ |
|
204 | 204 | Editing... done. Executing edited code... |
|
205 | 205 | hello world |
|
206 | 206 | Out[6]: "print 'hello world'n" |
|
207 | 207 | |
|
208 | 208 | Now we call it with the output #8 (stored in _8, also as Out[8]): |
|
209 | 209 | |
|
210 | 210 | In [7]: ed _8 |
|
211 | 211 | Editing... done. Executing edited code... |
|
212 | 212 | hello again |
|
213 | 213 | Out[7]: "print 'hello again'n" |
|
214 | 214 | |
|
215 | 215 | |
|
216 | 216 | Changing the default editor hook: |
|
217 | 217 | |
|
218 | 218 | If you wish to write your own editor hook, you can put it in a |
|
219 | 219 | configuration file which you load at startup time. The default hook |
|
220 | 220 | is defined in the IPython.core.hooks module, and you can use that as a |
|
221 | 221 | starting example for further modifications. That file also has |
|
222 | 222 | general instructions on how to set a new hook for use once you've |
|
223 | 223 | defined it.""" |
|
224 | 224 | |
|
225 | 225 | # FIXME: This function has become a convoluted mess. It needs a |
|
226 | 226 | # ground-up rewrite with clean, simple logic. |
|
227 | 227 | |
|
228 | 228 | def make_filename(arg): |
|
229 | 229 | "Make a filename from the given args" |
|
230 | 230 | try: |
|
231 | 231 | filename = get_py_filename(arg) |
|
232 | 232 | except IOError: |
|
233 | 233 | if args.endswith('.py'): |
|
234 | 234 | filename = arg |
|
235 | 235 | else: |
|
236 | 236 | filename = None |
|
237 | 237 | return filename |
|
238 | 238 | |
|
239 | 239 | # custom exceptions |
|
240 | 240 | class DataIsObject(Exception): pass |
|
241 | 241 | |
|
242 | 242 | opts,args = self.parse_options(parameter_s,'prn:') |
|
243 | 243 | # Set a few locals from the options for convenience: |
|
244 | 244 | opts_p = opts.has_key('p') |
|
245 | 245 | opts_r = opts.has_key('r') |
|
246 | 246 | |
|
247 | 247 | # Default line number value |
|
248 | 248 | lineno = opts.get('n',None) |
|
249 | if lineno is not None: | |
|
250 | try: | |
|
251 | lineno = int(lineno) | |
|
252 | except: | |
|
253 | warn("The -n argument must be an integer.") | |
|
254 | return | |
|
249 | 255 | |
|
250 | 256 | if opts_p: |
|
251 | 257 | args = '_%s' % last_call[0] |
|
252 | 258 | if not self.shell.user_ns.has_key(args): |
|
253 | 259 | args = last_call[1] |
|
254 | 260 | |
|
255 | 261 | # use last_call to remember the state of the previous call, but don't |
|
256 | 262 | # let it be clobbered by successive '-p' calls. |
|
257 | 263 | try: |
|
258 | 264 | last_call[0] = self.shell.displayhook.prompt_count |
|
259 | 265 | if not opts_p: |
|
260 | 266 | last_call[1] = parameter_s |
|
261 | 267 | except: |
|
262 | 268 | pass |
|
263 | 269 | |
|
264 | 270 | # by default this is done with temp files, except when the given |
|
265 | 271 | # arg is a filename |
|
266 | 272 | use_temp = 1 |
|
267 | 273 | |
|
268 | 274 | if re.match(r'\d',args): |
|
269 | 275 | # Mode where user specifies ranges of lines, like in %macro. |
|
270 | 276 | # This means that you can't edit files whose names begin with |
|
271 | 277 | # numbers this way. Tough. |
|
272 | 278 | ranges = args.split() |
|
273 | 279 | data = ''.join(self.extract_input_slices(ranges,opts_r)) |
|
274 | 280 | elif args.endswith('.py'): |
|
275 | 281 | filename = make_filename(args) |
|
276 | 282 | data = '' |
|
277 | 283 | use_temp = 0 |
|
278 | 284 | elif args: |
|
279 | 285 | try: |
|
280 | 286 | # Load the parameter given as a variable. If not a string, |
|
281 | 287 | # process it as an object instead (below) |
|
282 | 288 | |
|
283 | 289 | #print '*** args',args,'type',type(args) # dbg |
|
284 | 290 | data = eval(args,self.shell.user_ns) |
|
285 | 291 | if not type(data) in StringTypes: |
|
286 | 292 | raise DataIsObject |
|
287 | 293 | |
|
288 | 294 | except (NameError,SyntaxError): |
|
289 | 295 | # given argument is not a variable, try as a filename |
|
290 | 296 | filename = make_filename(args) |
|
291 | 297 | if filename is None: |
|
292 | 298 | warn("Argument given (%s) can't be found as a variable " |
|
293 | 299 | "or as a filename." % args) |
|
294 | 300 | return |
|
295 | 301 | |
|
296 | 302 | data = '' |
|
297 | 303 | use_temp = 0 |
|
298 | 304 | except DataIsObject: |
|
299 | 305 | |
|
300 | 306 | # macros have a special edit function |
|
301 | 307 | if isinstance(data,Macro): |
|
302 | 308 | self._edit_macro(args,data) |
|
303 | 309 | return |
|
304 | 310 | |
|
305 | 311 | # For objects, try to edit the file where they are defined |
|
306 | 312 | try: |
|
307 | 313 | filename = inspect.getabsfile(data) |
|
308 | 314 | if 'fakemodule' in filename.lower() and inspect.isclass(data): |
|
309 | 315 | # class created by %edit? Try to find source |
|
310 | 316 | # by looking for method definitions instead, the |
|
311 | 317 | # __module__ in those classes is FakeModule. |
|
312 | 318 | attrs = [getattr(data, aname) for aname in dir(data)] |
|
313 | 319 | for attr in attrs: |
|
314 | 320 | if not inspect.ismethod(attr): |
|
315 | 321 | continue |
|
316 | 322 | filename = inspect.getabsfile(attr) |
|
317 | 323 | if filename and 'fakemodule' not in filename.lower(): |
|
318 | 324 | # change the attribute to be the edit target instead |
|
319 | 325 | data = attr |
|
320 | 326 | break |
|
321 | 327 | |
|
322 | 328 | datafile = 1 |
|
323 | 329 | except TypeError: |
|
324 | 330 | filename = make_filename(args) |
|
325 | 331 | datafile = 1 |
|
326 | 332 | warn('Could not find file where `%s` is defined.\n' |
|
327 | 333 | 'Opening a file named `%s`' % (args,filename)) |
|
328 | 334 | # Now, make sure we can actually read the source (if it was in |
|
329 | 335 | # a temp file it's gone by now). |
|
330 | 336 | if datafile: |
|
331 | 337 | try: |
|
332 | 338 | if lineno is None: |
|
333 | 339 | lineno = inspect.getsourcelines(data)[1] |
|
334 | 340 | except IOError: |
|
335 | 341 | filename = make_filename(args) |
|
336 | 342 | if filename is None: |
|
337 | 343 | warn('The file `%s` where `%s` was defined cannot ' |
|
338 | 344 | 'be read.' % (filename,data)) |
|
339 | 345 | return |
|
340 | 346 | use_temp = 0 |
|
341 | 347 | else: |
|
342 | 348 | data = '' |
|
343 | 349 | |
|
344 | 350 | if use_temp: |
|
345 | 351 | filename = self.shell.mktempfile(data) |
|
346 | 352 | print 'IPython will make a temporary file named:',filename |
|
347 | 353 | |
|
348 | 354 | payload = { |
|
349 | 355 | 'source' : 'IPython.zmq.zmqshell.ZMQInteractiveShell.edit_magic', |
|
350 | 356 | 'filename' : filename, |
|
351 | 357 | 'line_number' : lineno |
|
352 | 358 | } |
|
353 | 359 | self.payload_manager.write_payload(payload) |
|
354 | 360 | |
|
355 | 361 | |
|
356 | 362 | InteractiveShellABC.register(ZMQInteractiveShell) |
|
357 | 363 | |
|
358 | 364 | |
|
359 | 365 |
General Comments 0
You need to be logged in to leave comments.
Login now