##// END OF EJS Templates
Merge pull request #8209 from melund/patch-1...
Matthias Bussonnier -
r21032:04def206 merge
parent child Browse files
Show More
@@ -1,811 +1,811 b''
1 """Frontend widget for the Qt Console"""
1 """Frontend widget for the Qt Console"""
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 from __future__ import print_function
6 from __future__ import print_function
7
7
8 from collections import namedtuple
8 from collections import namedtuple
9 import sys
9 import sys
10 import uuid
10 import uuid
11
11
12 from IPython.external import qt
12 from IPython.external import qt
13 from IPython.external.qt import QtCore, QtGui
13 from IPython.external.qt import QtCore, QtGui
14 from IPython.utils import py3compat
14 from IPython.utils import py3compat
15 from IPython.utils.importstring import import_item
15 from IPython.utils.importstring import import_item
16
16
17 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
17 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
18 from IPython.core.inputtransformer import classic_prompt
18 from IPython.core.inputtransformer import classic_prompt
19 from IPython.core.oinspect import call_tip
19 from IPython.core.oinspect import call_tip
20 from IPython.qt.base_frontend_mixin import BaseFrontendMixin
20 from IPython.qt.base_frontend_mixin import BaseFrontendMixin
21 from IPython.utils.traitlets import Any, Bool, Instance, Unicode, DottedObjectName
21 from IPython.utils.traitlets import Any, Bool, Instance, Unicode, DottedObjectName
22 from .bracket_matcher import BracketMatcher
22 from .bracket_matcher import BracketMatcher
23 from .call_tip_widget import CallTipWidget
23 from .call_tip_widget import CallTipWidget
24 from .history_console_widget import HistoryConsoleWidget
24 from .history_console_widget import HistoryConsoleWidget
25 from .pygments_highlighter import PygmentsHighlighter
25 from .pygments_highlighter import PygmentsHighlighter
26
26
27
27
28 class FrontendHighlighter(PygmentsHighlighter):
28 class FrontendHighlighter(PygmentsHighlighter):
29 """ A PygmentsHighlighter that understands and ignores prompts.
29 """ A PygmentsHighlighter that understands and ignores prompts.
30 """
30 """
31
31
32 def __init__(self, frontend, lexer=None):
32 def __init__(self, frontend, lexer=None):
33 super(FrontendHighlighter, self).__init__(frontend._control.document(), lexer=lexer)
33 super(FrontendHighlighter, self).__init__(frontend._control.document(), lexer=lexer)
34 self._current_offset = 0
34 self._current_offset = 0
35 self._frontend = frontend
35 self._frontend = frontend
36 self.highlighting_on = False
36 self.highlighting_on = False
37
37
38 def highlightBlock(self, string):
38 def highlightBlock(self, string):
39 """ Highlight a block of text. Reimplemented to highlight selectively.
39 """ Highlight a block of text. Reimplemented to highlight selectively.
40 """
40 """
41 if not self.highlighting_on:
41 if not self.highlighting_on:
42 return
42 return
43
43
44 # The input to this function is a unicode string that may contain
44 # The input to this function is a unicode string that may contain
45 # paragraph break characters, non-breaking spaces, etc. Here we acquire
45 # paragraph break characters, non-breaking spaces, etc. Here we acquire
46 # the string as plain text so we can compare it.
46 # the string as plain text so we can compare it.
47 current_block = self.currentBlock()
47 current_block = self.currentBlock()
48 string = self._frontend._get_block_plain_text(current_block)
48 string = self._frontend._get_block_plain_text(current_block)
49
49
50 # Decide whether to check for the regular or continuation prompt.
50 # Decide whether to check for the regular or continuation prompt.
51 if current_block.contains(self._frontend._prompt_pos):
51 if current_block.contains(self._frontend._prompt_pos):
52 prompt = self._frontend._prompt
52 prompt = self._frontend._prompt
53 else:
53 else:
54 prompt = self._frontend._continuation_prompt
54 prompt = self._frontend._continuation_prompt
55
55
56 # Only highlight if we can identify a prompt, but make sure not to
56 # Only highlight if we can identify a prompt, but make sure not to
57 # highlight the prompt.
57 # highlight the prompt.
58 if string.startswith(prompt):
58 if string.startswith(prompt):
59 self._current_offset = len(prompt)
59 self._current_offset = len(prompt)
60 string = string[len(prompt):]
60 string = string[len(prompt):]
61 super(FrontendHighlighter, self).highlightBlock(string)
61 super(FrontendHighlighter, self).highlightBlock(string)
62
62
63 def rehighlightBlock(self, block):
63 def rehighlightBlock(self, block):
64 """ Reimplemented to temporarily enable highlighting if disabled.
64 """ Reimplemented to temporarily enable highlighting if disabled.
65 """
65 """
66 old = self.highlighting_on
66 old = self.highlighting_on
67 self.highlighting_on = True
67 self.highlighting_on = True
68 super(FrontendHighlighter, self).rehighlightBlock(block)
68 super(FrontendHighlighter, self).rehighlightBlock(block)
69 self.highlighting_on = old
69 self.highlighting_on = old
70
70
71 def setFormat(self, start, count, format):
71 def setFormat(self, start, count, format):
72 """ Reimplemented to highlight selectively.
72 """ Reimplemented to highlight selectively.
73 """
73 """
74 start += self._current_offset
74 start += self._current_offset
75 super(FrontendHighlighter, self).setFormat(start, count, format)
75 super(FrontendHighlighter, self).setFormat(start, count, format)
76
76
77
77
78 class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin):
78 class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin):
79 """ A Qt frontend for a generic Python kernel.
79 """ A Qt frontend for a generic Python kernel.
80 """
80 """
81
81
82 # The text to show when the kernel is (re)started.
82 # The text to show when the kernel is (re)started.
83 banner = Unicode(config=True)
83 banner = Unicode(config=True)
84 kernel_banner = Unicode()
84 kernel_banner = Unicode()
85 # Whether to show the banner
85 # Whether to show the banner
86 _display_banner = Bool(False)
86 _display_banner = Bool(False)
87
87
88 # An option and corresponding signal for overriding the default kernel
88 # An option and corresponding signal for overriding the default kernel
89 # interrupt behavior.
89 # interrupt behavior.
90 custom_interrupt = Bool(False)
90 custom_interrupt = Bool(False)
91 custom_interrupt_requested = QtCore.Signal()
91 custom_interrupt_requested = QtCore.Signal()
92
92
93 # An option and corresponding signals for overriding the default kernel
93 # An option and corresponding signals for overriding the default kernel
94 # restart behavior.
94 # restart behavior.
95 custom_restart = Bool(False)
95 custom_restart = Bool(False)
96 custom_restart_kernel_died = QtCore.Signal(float)
96 custom_restart_kernel_died = QtCore.Signal(float)
97 custom_restart_requested = QtCore.Signal()
97 custom_restart_requested = QtCore.Signal()
98
98
99 # Whether to automatically show calltips on open-parentheses.
99 # Whether to automatically show calltips on open-parentheses.
100 enable_calltips = Bool(True, config=True,
100 enable_calltips = Bool(True, config=True,
101 help="Whether to draw information calltips on open-parentheses.")
101 help="Whether to draw information calltips on open-parentheses.")
102
102
103 clear_on_kernel_restart = Bool(True, config=True,
103 clear_on_kernel_restart = Bool(True, config=True,
104 help="Whether to clear the console when the kernel is restarted")
104 help="Whether to clear the console when the kernel is restarted")
105
105
106 confirm_restart = Bool(True, config=True,
106 confirm_restart = Bool(True, config=True,
107 help="Whether to ask for user confirmation when restarting kernel")
107 help="Whether to ask for user confirmation when restarting kernel")
108
108
109 lexer_class = DottedObjectName(config=True,
109 lexer_class = DottedObjectName(config=True,
110 help="The pygments lexer class to use."
110 help="The pygments lexer class to use."
111 )
111 )
112 def _lexer_class_changed(self, name, old, new):
112 def _lexer_class_changed(self, name, old, new):
113 lexer_class = import_item(new)
113 lexer_class = import_item(new)
114 self.lexer = lexer_class()
114 self.lexer = lexer_class()
115
115
116 def _lexer_class_default(self):
116 def _lexer_class_default(self):
117 if py3compat.PY3:
117 if py3compat.PY3:
118 return 'pygments.lexers.Python3Lexer'
118 return 'pygments.lexers.Python3Lexer'
119 else:
119 else:
120 return 'pygments.lexers.PythonLexer'
120 return 'pygments.lexers.PythonLexer'
121
121
122 lexer = Any()
122 lexer = Any()
123 def _lexer_default(self):
123 def _lexer_default(self):
124 lexer_class = import_item(self.lexer_class)
124 lexer_class = import_item(self.lexer_class)
125 return lexer_class()
125 return lexer_class()
126
126
127 # Emitted when a user visible 'execute_request' has been submitted to the
127 # Emitted when a user visible 'execute_request' has been submitted to the
128 # kernel from the FrontendWidget. Contains the code to be executed.
128 # kernel from the FrontendWidget. Contains the code to be executed.
129 executing = QtCore.Signal(object)
129 executing = QtCore.Signal(object)
130
130
131 # Emitted when a user-visible 'execute_reply' has been received from the
131 # Emitted when a user-visible 'execute_reply' has been received from the
132 # kernel and processed by the FrontendWidget. Contains the response message.
132 # kernel and processed by the FrontendWidget. Contains the response message.
133 executed = QtCore.Signal(object)
133 executed = QtCore.Signal(object)
134
134
135 # Emitted when an exit request has been received from the kernel.
135 # Emitted when an exit request has been received from the kernel.
136 exit_requested = QtCore.Signal(object)
136 exit_requested = QtCore.Signal(object)
137
137
138 # Protected class variables.
138 # Protected class variables.
139 _prompt_transformer = IPythonInputSplitter(physical_line_transforms=[classic_prompt()],
139 _prompt_transformer = IPythonInputSplitter(physical_line_transforms=[classic_prompt()],
140 logical_line_transforms=[],
140 logical_line_transforms=[],
141 python_line_transforms=[],
141 python_line_transforms=[],
142 )
142 )
143 _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos'])
143 _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos'])
144 _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos'])
144 _CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos'])
145 _ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind'])
145 _ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind'])
146 _input_splitter_class = InputSplitter
146 _input_splitter_class = InputSplitter
147 _local_kernel = False
147 _local_kernel = False
148 _highlighter = Instance(FrontendHighlighter)
148 _highlighter = Instance(FrontendHighlighter)
149
149
150 #---------------------------------------------------------------------------
150 #---------------------------------------------------------------------------
151 # 'object' interface
151 # 'object' interface
152 #---------------------------------------------------------------------------
152 #---------------------------------------------------------------------------
153
153
154 def __init__(self, *args, **kw):
154 def __init__(self, *args, **kw):
155 super(FrontendWidget, self).__init__(*args, **kw)
155 super(FrontendWidget, self).__init__(*args, **kw)
156 # FIXME: remove this when PySide min version is updated past 1.0.7
156 # FIXME: remove this when PySide min version is updated past 1.0.7
157 # forcefully disable calltips if PySide is < 1.0.7, because they crash
157 # forcefully disable calltips if PySide is < 1.0.7, because they crash
158 if qt.QT_API == qt.QT_API_PYSIDE:
158 if qt.QT_API == qt.QT_API_PYSIDE:
159 import PySide
159 import PySide
160 if PySide.__version_info__ < (1,0,7):
160 if PySide.__version_info__ < (1,0,7):
161 self.log.warn("PySide %s < 1.0.7 detected, disabling calltips" % PySide.__version__)
161 self.log.warn("PySide %s < 1.0.7 detected, disabling calltips" % PySide.__version__)
162 self.enable_calltips = False
162 self.enable_calltips = False
163
163
164 # FrontendWidget protected variables.
164 # FrontendWidget protected variables.
165 self._bracket_matcher = BracketMatcher(self._control)
165 self._bracket_matcher = BracketMatcher(self._control)
166 self._call_tip_widget = CallTipWidget(self._control)
166 self._call_tip_widget = CallTipWidget(self._control)
167 self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None)
167 self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None)
168 self._hidden = False
168 self._hidden = False
169 self._highlighter = FrontendHighlighter(self, lexer=self.lexer)
169 self._highlighter = FrontendHighlighter(self, lexer=self.lexer)
170 self._input_splitter = self._input_splitter_class()
170 self._input_splitter = self._input_splitter_class()
171 self._kernel_manager = None
171 self._kernel_manager = None
172 self._kernel_client = None
172 self._kernel_client = None
173 self._request_info = {}
173 self._request_info = {}
174 self._request_info['execute'] = {};
174 self._request_info['execute'] = {};
175 self._callback_dict = {}
175 self._callback_dict = {}
176 self._display_banner = True
176 self._display_banner = True
177
177
178 # Configure the ConsoleWidget.
178 # Configure the ConsoleWidget.
179 self.tab_width = 4
179 self.tab_width = 4
180 self._set_continuation_prompt('... ')
180 self._set_continuation_prompt('... ')
181
181
182 # Configure the CallTipWidget.
182 # Configure the CallTipWidget.
183 self._call_tip_widget.setFont(self.font)
183 self._call_tip_widget.setFont(self.font)
184 self.font_changed.connect(self._call_tip_widget.setFont)
184 self.font_changed.connect(self._call_tip_widget.setFont)
185
185
186 # Configure actions.
186 # Configure actions.
187 action = self._copy_raw_action
187 action = self._copy_raw_action
188 key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C
188 key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C
189 action.setEnabled(False)
189 action.setEnabled(False)
190 action.setShortcut(QtGui.QKeySequence(key))
190 action.setShortcut(QtGui.QKeySequence(key))
191 action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
191 action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
192 action.triggered.connect(self.copy_raw)
192 action.triggered.connect(self.copy_raw)
193 self.copy_available.connect(action.setEnabled)
193 self.copy_available.connect(action.setEnabled)
194 self.addAction(action)
194 self.addAction(action)
195
195
196 # Connect signal handlers.
196 # Connect signal handlers.
197 document = self._control.document()
197 document = self._control.document()
198 document.contentsChange.connect(self._document_contents_change)
198 document.contentsChange.connect(self._document_contents_change)
199
199
200 # Set flag for whether we are connected via localhost.
200 # Set flag for whether we are connected via localhost.
201 self._local_kernel = kw.get('local_kernel',
201 self._local_kernel = kw.get('local_kernel',
202 FrontendWidget._local_kernel)
202 FrontendWidget._local_kernel)
203
203
204 # Whether or not a clear_output call is pending new output.
204 # Whether or not a clear_output call is pending new output.
205 self._pending_clearoutput = False
205 self._pending_clearoutput = False
206
206
207 #---------------------------------------------------------------------------
207 #---------------------------------------------------------------------------
208 # 'ConsoleWidget' public interface
208 # 'ConsoleWidget' public interface
209 #---------------------------------------------------------------------------
209 #---------------------------------------------------------------------------
210
210
211 def copy(self):
211 def copy(self):
212 """ Copy the currently selected text to the clipboard, removing prompts.
212 """ Copy the currently selected text to the clipboard, removing prompts.
213 """
213 """
214 if self._page_control is not None and self._page_control.hasFocus():
214 if self._page_control is not None and self._page_control.hasFocus():
215 self._page_control.copy()
215 self._page_control.copy()
216 elif self._control.hasFocus():
216 elif self._control.hasFocus():
217 text = self._control.textCursor().selection().toPlainText()
217 text = self._control.textCursor().selection().toPlainText()
218 if text:
218 if text:
219 was_newline = text[-1] == '\n'
219 was_newline = text[-1] == '\n'
220 text = self._prompt_transformer.transform_cell(text)
220 text = self._prompt_transformer.transform_cell(text)
221 if not was_newline: # user doesn't need newline
221 if not was_newline: # user doesn't need newline
222 text = text[:-1]
222 text = text[:-1]
223 QtGui.QApplication.clipboard().setText(text)
223 QtGui.QApplication.clipboard().setText(text)
224 else:
224 else:
225 self.log.debug("frontend widget : unknown copy target")
225 self.log.debug("frontend widget : unknown copy target")
226
226
227 #---------------------------------------------------------------------------
227 #---------------------------------------------------------------------------
228 # 'ConsoleWidget' abstract interface
228 # 'ConsoleWidget' abstract interface
229 #---------------------------------------------------------------------------
229 #---------------------------------------------------------------------------
230
230
231 def _is_complete(self, source, interactive):
231 def _is_complete(self, source, interactive):
232 """ Returns whether 'source' can be completely processed and a new
232 """ Returns whether 'source' can be completely processed and a new
233 prompt created. When triggered by an Enter/Return key press,
233 prompt created. When triggered by an Enter/Return key press,
234 'interactive' is True; otherwise, it is False.
234 'interactive' is True; otherwise, it is False.
235 """
235 """
236 self._input_splitter.reset()
236 self._input_splitter.reset()
237 try:
237 try:
238 complete = self._input_splitter.push(source)
238 complete = self._input_splitter.push(source)
239 except SyntaxError:
239 except SyntaxError:
240 return True
240 return True
241 if interactive:
241 if interactive:
242 complete = not self._input_splitter.push_accepts_more()
242 complete = not self._input_splitter.push_accepts_more()
243 return complete
243 return complete
244
244
245 def _execute(self, source, hidden):
245 def _execute(self, source, hidden):
246 """ Execute 'source'. If 'hidden', do not show any output.
246 """ Execute 'source'. If 'hidden', do not show any output.
247
247
248 See parent class :meth:`execute` docstring for full details.
248 See parent class :meth:`execute` docstring for full details.
249 """
249 """
250 msg_id = self.kernel_client.execute(source, hidden)
250 msg_id = self.kernel_client.execute(source, hidden)
251 self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'user')
251 self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'user')
252 self._hidden = hidden
252 self._hidden = hidden
253 if not hidden:
253 if not hidden:
254 self.executing.emit(source)
254 self.executing.emit(source)
255
255
256 def _prompt_started_hook(self):
256 def _prompt_started_hook(self):
257 """ Called immediately after a new prompt is displayed.
257 """ Called immediately after a new prompt is displayed.
258 """
258 """
259 if not self._reading:
259 if not self._reading:
260 self._highlighter.highlighting_on = True
260 self._highlighter.highlighting_on = True
261
261
262 def _prompt_finished_hook(self):
262 def _prompt_finished_hook(self):
263 """ Called immediately after a prompt is finished, i.e. when some input
263 """ Called immediately after a prompt is finished, i.e. when some input
264 will be processed and a new prompt displayed.
264 will be processed and a new prompt displayed.
265 """
265 """
266 # Flush all state from the input splitter so the next round of
266 # Flush all state from the input splitter so the next round of
267 # reading input starts with a clean buffer.
267 # reading input starts with a clean buffer.
268 self._input_splitter.reset()
268 self._input_splitter.reset()
269
269
270 if not self._reading:
270 if not self._reading:
271 self._highlighter.highlighting_on = False
271 self._highlighter.highlighting_on = False
272
272
273 def _tab_pressed(self):
273 def _tab_pressed(self):
274 """ Called when the tab key is pressed. Returns whether to continue
274 """ Called when the tab key is pressed. Returns whether to continue
275 processing the event.
275 processing the event.
276 """
276 """
277 # Perform tab completion if:
277 # Perform tab completion if:
278 # 1) The cursor is in the input buffer.
278 # 1) The cursor is in the input buffer.
279 # 2) There is a non-whitespace character before the cursor.
279 # 2) There is a non-whitespace character before the cursor.
280 text = self._get_input_buffer_cursor_line()
280 text = self._get_input_buffer_cursor_line()
281 if text is None:
281 if text is None:
282 return False
282 return False
283 complete = bool(text[:self._get_input_buffer_cursor_column()].strip())
283 complete = bool(text[:self._get_input_buffer_cursor_column()].strip())
284 if complete:
284 if complete:
285 self._complete()
285 self._complete()
286 return not complete
286 return not complete
287
287
288 #---------------------------------------------------------------------------
288 #---------------------------------------------------------------------------
289 # 'ConsoleWidget' protected interface
289 # 'ConsoleWidget' protected interface
290 #---------------------------------------------------------------------------
290 #---------------------------------------------------------------------------
291
291
292 def _context_menu_make(self, pos):
292 def _context_menu_make(self, pos):
293 """ Reimplemented to add an action for raw copy.
293 """ Reimplemented to add an action for raw copy.
294 """
294 """
295 menu = super(FrontendWidget, self)._context_menu_make(pos)
295 menu = super(FrontendWidget, self)._context_menu_make(pos)
296 for before_action in menu.actions():
296 for before_action in menu.actions():
297 if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \
297 if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \
298 QtGui.QKeySequence.ExactMatch:
298 QtGui.QKeySequence.ExactMatch:
299 menu.insertAction(before_action, self._copy_raw_action)
299 menu.insertAction(before_action, self._copy_raw_action)
300 break
300 break
301 return menu
301 return menu
302
302
303 def request_interrupt_kernel(self):
303 def request_interrupt_kernel(self):
304 if self._executing:
304 if self._executing:
305 self.interrupt_kernel()
305 self.interrupt_kernel()
306
306
307 def request_restart_kernel(self):
307 def request_restart_kernel(self):
308 message = 'Are you sure you want to restart the kernel?'
308 message = 'Are you sure you want to restart the kernel?'
309 self.restart_kernel(message, now=False)
309 self.restart_kernel(message, now=False)
310
310
311 def _event_filter_console_keypress(self, event):
311 def _event_filter_console_keypress(self, event):
312 """ Reimplemented for execution interruption and smart backspace.
312 """ Reimplemented for execution interruption and smart backspace.
313 """
313 """
314 key = event.key()
314 key = event.key()
315 if self._control_key_down(event.modifiers(), include_command=False):
315 if self._control_key_down(event.modifiers(), include_command=False):
316
316
317 if key == QtCore.Qt.Key_C and self._executing:
317 if key == QtCore.Qt.Key_C and self._executing:
318 self.request_interrupt_kernel()
318 self.request_interrupt_kernel()
319 return True
319 return True
320
320
321 elif key == QtCore.Qt.Key_Period:
321 elif key == QtCore.Qt.Key_Period:
322 self.request_restart_kernel()
322 self.request_restart_kernel()
323 return True
323 return True
324
324
325 elif not event.modifiers() & QtCore.Qt.AltModifier:
325 elif not event.modifiers() & QtCore.Qt.AltModifier:
326
326
327 # Smart backspace: remove four characters in one backspace if:
327 # Smart backspace: remove four characters in one backspace if:
328 # 1) everything left of the cursor is whitespace
328 # 1) everything left of the cursor is whitespace
329 # 2) the four characters immediately left of the cursor are spaces
329 # 2) the four characters immediately left of the cursor are spaces
330 if key == QtCore.Qt.Key_Backspace:
330 if key == QtCore.Qt.Key_Backspace:
331 col = self._get_input_buffer_cursor_column()
331 col = self._get_input_buffer_cursor_column()
332 cursor = self._control.textCursor()
332 cursor = self._control.textCursor()
333 if col > 3 and not cursor.hasSelection():
333 if col > 3 and not cursor.hasSelection():
334 text = self._get_input_buffer_cursor_line()[:col]
334 text = self._get_input_buffer_cursor_line()[:col]
335 if text.endswith(' ') and not text.strip():
335 if text.endswith(' ') and not text.strip():
336 cursor.movePosition(QtGui.QTextCursor.Left,
336 cursor.movePosition(QtGui.QTextCursor.Left,
337 QtGui.QTextCursor.KeepAnchor, 4)
337 QtGui.QTextCursor.KeepAnchor, 4)
338 cursor.removeSelectedText()
338 cursor.removeSelectedText()
339 return True
339 return True
340
340
341 return super(FrontendWidget, self)._event_filter_console_keypress(event)
341 return super(FrontendWidget, self)._event_filter_console_keypress(event)
342
342
343 def _insert_continuation_prompt(self, cursor):
343 def _insert_continuation_prompt(self, cursor):
344 """ Reimplemented for auto-indentation.
344 """ Reimplemented for auto-indentation.
345 """
345 """
346 super(FrontendWidget, self)._insert_continuation_prompt(cursor)
346 super(FrontendWidget, self)._insert_continuation_prompt(cursor)
347 cursor.insertText(' ' * self._input_splitter.indent_spaces)
347 cursor.insertText(' ' * self._input_splitter.indent_spaces)
348
348
349 #---------------------------------------------------------------------------
349 #---------------------------------------------------------------------------
350 # 'BaseFrontendMixin' abstract interface
350 # 'BaseFrontendMixin' abstract interface
351 #---------------------------------------------------------------------------
351 #---------------------------------------------------------------------------
352 def _handle_clear_output(self, msg):
352 def _handle_clear_output(self, msg):
353 """Handle clear output messages."""
353 """Handle clear output messages."""
354 if include_output(msg):
354 if self.include_output(msg):
355 wait = msg['content'].get('wait', True)
355 wait = msg['content'].get('wait', True)
356 if wait:
356 if wait:
357 self._pending_clearoutput = True
357 self._pending_clearoutput = True
358 else:
358 else:
359 self.clear_output()
359 self.clear_output()
360
360
361 def _silent_exec_callback(self, expr, callback):
361 def _silent_exec_callback(self, expr, callback):
362 """Silently execute `expr` in the kernel and call `callback` with reply
362 """Silently execute `expr` in the kernel and call `callback` with reply
363
363
364 the `expr` is evaluated silently in the kernel (without) output in
364 the `expr` is evaluated silently in the kernel (without) output in
365 the frontend. Call `callback` with the
365 the frontend. Call `callback` with the
366 `repr <http://docs.python.org/library/functions.html#repr> `_ as first argument
366 `repr <http://docs.python.org/library/functions.html#repr> `_ as first argument
367
367
368 Parameters
368 Parameters
369 ----------
369 ----------
370 expr : string
370 expr : string
371 valid string to be executed by the kernel.
371 valid string to be executed by the kernel.
372 callback : function
372 callback : function
373 function accepting one argument, as a string. The string will be
373 function accepting one argument, as a string. The string will be
374 the `repr` of the result of evaluating `expr`
374 the `repr` of the result of evaluating `expr`
375
375
376 The `callback` is called with the `repr()` of the result of `expr` as
376 The `callback` is called with the `repr()` of the result of `expr` as
377 first argument. To get the object, do `eval()` on the passed value.
377 first argument. To get the object, do `eval()` on the passed value.
378
378
379 See Also
379 See Also
380 --------
380 --------
381 _handle_exec_callback : private method, deal with calling callback with reply
381 _handle_exec_callback : private method, deal with calling callback with reply
382
382
383 """
383 """
384
384
385 # generate uuid, which would be used as an indication of whether or
385 # generate uuid, which would be used as an indication of whether or
386 # not the unique request originated from here (can use msg id ?)
386 # not the unique request originated from here (can use msg id ?)
387 local_uuid = str(uuid.uuid1())
387 local_uuid = str(uuid.uuid1())
388 msg_id = self.kernel_client.execute('',
388 msg_id = self.kernel_client.execute('',
389 silent=True, user_expressions={ local_uuid:expr })
389 silent=True, user_expressions={ local_uuid:expr })
390 self._callback_dict[local_uuid] = callback
390 self._callback_dict[local_uuid] = callback
391 self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_callback')
391 self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_callback')
392
392
393 def _handle_exec_callback(self, msg):
393 def _handle_exec_callback(self, msg):
394 """Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback``
394 """Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback``
395
395
396 Parameters
396 Parameters
397 ----------
397 ----------
398 msg : raw message send by the kernel containing an `user_expressions`
398 msg : raw message send by the kernel containing an `user_expressions`
399 and having a 'silent_exec_callback' kind.
399 and having a 'silent_exec_callback' kind.
400
400
401 Notes
401 Notes
402 -----
402 -----
403 This function will look for a `callback` associated with the
403 This function will look for a `callback` associated with the
404 corresponding message id. Association has been made by
404 corresponding message id. Association has been made by
405 `_silent_exec_callback`. `callback` is then called with the `repr()`
405 `_silent_exec_callback`. `callback` is then called with the `repr()`
406 of the value of corresponding `user_expressions` as argument.
406 of the value of corresponding `user_expressions` as argument.
407 `callback` is then removed from the known list so that any message
407 `callback` is then removed from the known list so that any message
408 coming again with the same id won't trigger it.
408 coming again with the same id won't trigger it.
409
409
410 """
410 """
411
411
412 user_exp = msg['content'].get('user_expressions')
412 user_exp = msg['content'].get('user_expressions')
413 if not user_exp:
413 if not user_exp:
414 return
414 return
415 for expression in user_exp:
415 for expression in user_exp:
416 if expression in self._callback_dict:
416 if expression in self._callback_dict:
417 self._callback_dict.pop(expression)(user_exp[expression])
417 self._callback_dict.pop(expression)(user_exp[expression])
418
418
419 def _handle_execute_reply(self, msg):
419 def _handle_execute_reply(self, msg):
420 """ Handles replies for code execution.
420 """ Handles replies for code execution.
421 """
421 """
422 self.log.debug("execute: %s", msg.get('content', ''))
422 self.log.debug("execute: %s", msg.get('content', ''))
423 msg_id = msg['parent_header']['msg_id']
423 msg_id = msg['parent_header']['msg_id']
424 info = self._request_info['execute'].get(msg_id)
424 info = self._request_info['execute'].get(msg_id)
425 # unset reading flag, because if execute finished, raw_input can't
425 # unset reading flag, because if execute finished, raw_input can't
426 # still be pending.
426 # still be pending.
427 self._reading = False
427 self._reading = False
428 if info and info.kind == 'user' and not self._hidden:
428 if info and info.kind == 'user' and not self._hidden:
429 # Make sure that all output from the SUB channel has been processed
429 # Make sure that all output from the SUB channel has been processed
430 # before writing a new prompt.
430 # before writing a new prompt.
431 self.kernel_client.iopub_channel.flush()
431 self.kernel_client.iopub_channel.flush()
432
432
433 # Reset the ANSI style information to prevent bad text in stdout
433 # Reset the ANSI style information to prevent bad text in stdout
434 # from messing up our colors. We're not a true terminal so we're
434 # from messing up our colors. We're not a true terminal so we're
435 # allowed to do this.
435 # allowed to do this.
436 if self.ansi_codes:
436 if self.ansi_codes:
437 self._ansi_processor.reset_sgr()
437 self._ansi_processor.reset_sgr()
438
438
439 content = msg['content']
439 content = msg['content']
440 status = content['status']
440 status = content['status']
441 if status == 'ok':
441 if status == 'ok':
442 self._process_execute_ok(msg)
442 self._process_execute_ok(msg)
443 elif status == 'error':
443 elif status == 'error':
444 self._process_execute_error(msg)
444 self._process_execute_error(msg)
445 elif status == 'aborted':
445 elif status == 'aborted':
446 self._process_execute_abort(msg)
446 self._process_execute_abort(msg)
447
447
448 self._show_interpreter_prompt_for_reply(msg)
448 self._show_interpreter_prompt_for_reply(msg)
449 self.executed.emit(msg)
449 self.executed.emit(msg)
450 self._request_info['execute'].pop(msg_id)
450 self._request_info['execute'].pop(msg_id)
451 elif info and info.kind == 'silent_exec_callback' and not self._hidden:
451 elif info and info.kind == 'silent_exec_callback' and not self._hidden:
452 self._handle_exec_callback(msg)
452 self._handle_exec_callback(msg)
453 self._request_info['execute'].pop(msg_id)
453 self._request_info['execute'].pop(msg_id)
454 else:
454 else:
455 super(FrontendWidget, self)._handle_execute_reply(msg)
455 super(FrontendWidget, self)._handle_execute_reply(msg)
456
456
457 def _handle_input_request(self, msg):
457 def _handle_input_request(self, msg):
458 """ Handle requests for raw_input.
458 """ Handle requests for raw_input.
459 """
459 """
460 self.log.debug("input: %s", msg.get('content', ''))
460 self.log.debug("input: %s", msg.get('content', ''))
461 if self._hidden:
461 if self._hidden:
462 raise RuntimeError('Request for raw input during hidden execution.')
462 raise RuntimeError('Request for raw input during hidden execution.')
463
463
464 # Make sure that all output from the SUB channel has been processed
464 # Make sure that all output from the SUB channel has been processed
465 # before entering readline mode.
465 # before entering readline mode.
466 self.kernel_client.iopub_channel.flush()
466 self.kernel_client.iopub_channel.flush()
467
467
468 def callback(line):
468 def callback(line):
469 self.kernel_client.input(line)
469 self.kernel_client.input(line)
470 if self._reading:
470 if self._reading:
471 self.log.debug("Got second input request, assuming first was interrupted.")
471 self.log.debug("Got second input request, assuming first was interrupted.")
472 self._reading = False
472 self._reading = False
473 self._readline(msg['content']['prompt'], callback=callback)
473 self._readline(msg['content']['prompt'], callback=callback)
474
474
475 def _kernel_restarted_message(self, died=True):
475 def _kernel_restarted_message(self, died=True):
476 msg = "Kernel died, restarting" if died else "Kernel restarting"
476 msg = "Kernel died, restarting" if died else "Kernel restarting"
477 self._append_html("<br>%s<hr><br>" % msg,
477 self._append_html("<br>%s<hr><br>" % msg,
478 before_prompt=False
478 before_prompt=False
479 )
479 )
480
480
481 def _handle_kernel_died(self, since_last_heartbeat):
481 def _handle_kernel_died(self, since_last_heartbeat):
482 """Handle the kernel's death (if we do not own the kernel).
482 """Handle the kernel's death (if we do not own the kernel).
483 """
483 """
484 self.log.warn("kernel died: %s", since_last_heartbeat)
484 self.log.warn("kernel died: %s", since_last_heartbeat)
485 if self.custom_restart:
485 if self.custom_restart:
486 self.custom_restart_kernel_died.emit(since_last_heartbeat)
486 self.custom_restart_kernel_died.emit(since_last_heartbeat)
487 else:
487 else:
488 self._kernel_restarted_message(died=True)
488 self._kernel_restarted_message(died=True)
489 self.reset()
489 self.reset()
490
490
491 def _handle_kernel_restarted(self, died=True):
491 def _handle_kernel_restarted(self, died=True):
492 """Notice that the autorestarter restarted the kernel.
492 """Notice that the autorestarter restarted the kernel.
493
493
494 There's nothing to do but show a message.
494 There's nothing to do but show a message.
495 """
495 """
496 self.log.warn("kernel restarted")
496 self.log.warn("kernel restarted")
497 self._kernel_restarted_message(died=died)
497 self._kernel_restarted_message(died=died)
498 self.reset()
498 self.reset()
499
499
500 def _handle_inspect_reply(self, rep):
500 def _handle_inspect_reply(self, rep):
501 """Handle replies for call tips."""
501 """Handle replies for call tips."""
502 self.log.debug("oinfo: %s", rep.get('content', ''))
502 self.log.debug("oinfo: %s", rep.get('content', ''))
503 cursor = self._get_cursor()
503 cursor = self._get_cursor()
504 info = self._request_info.get('call_tip')
504 info = self._request_info.get('call_tip')
505 if info and info.id == rep['parent_header']['msg_id'] and \
505 if info and info.id == rep['parent_header']['msg_id'] and \
506 info.pos == cursor.position():
506 info.pos == cursor.position():
507 content = rep['content']
507 content = rep['content']
508 if content.get('status') == 'ok' and content.get('found', False):
508 if content.get('status') == 'ok' and content.get('found', False):
509 self._call_tip_widget.show_inspect_data(content)
509 self._call_tip_widget.show_inspect_data(content)
510
510
511 def _handle_execute_result(self, msg):
511 def _handle_execute_result(self, msg):
512 """ Handle display hook output.
512 """ Handle display hook output.
513 """
513 """
514 self.log.debug("execute_result: %s", msg.get('content', ''))
514 self.log.debug("execute_result: %s", msg.get('content', ''))
515 if self.include_output(msg):
515 if self.include_output(msg):
516 self.flush_clearoutput()
516 self.flush_clearoutput()
517 text = msg['content']['data']
517 text = msg['content']['data']
518 self._append_plain_text(text + '\n', before_prompt=True)
518 self._append_plain_text(text + '\n', before_prompt=True)
519
519
520 def _handle_stream(self, msg):
520 def _handle_stream(self, msg):
521 """ Handle stdout, stderr, and stdin.
521 """ Handle stdout, stderr, and stdin.
522 """
522 """
523 self.log.debug("stream: %s", msg.get('content', ''))
523 self.log.debug("stream: %s", msg.get('content', ''))
524 if self.include_output(msg):
524 if self.include_output(msg):
525 self.flush_clearoutput()
525 self.flush_clearoutput()
526 self.append_stream(msg['content']['text'])
526 self.append_stream(msg['content']['text'])
527
527
528 def _handle_shutdown_reply(self, msg):
528 def _handle_shutdown_reply(self, msg):
529 """ Handle shutdown signal, only if from other console.
529 """ Handle shutdown signal, only if from other console.
530 """
530 """
531 self.log.info("shutdown: %s", msg.get('content', ''))
531 self.log.info("shutdown: %s", msg.get('content', ''))
532 restart = msg.get('content', {}).get('restart', False)
532 restart = msg.get('content', {}).get('restart', False)
533 if not self._hidden and not self.from_here(msg):
533 if not self._hidden and not self.from_here(msg):
534 # got shutdown reply, request came from session other than ours
534 # got shutdown reply, request came from session other than ours
535 if restart:
535 if restart:
536 # someone restarted the kernel, handle it
536 # someone restarted the kernel, handle it
537 self._handle_kernel_restarted(died=False)
537 self._handle_kernel_restarted(died=False)
538 else:
538 else:
539 # kernel was shutdown permanently
539 # kernel was shutdown permanently
540 # this triggers exit_requested if the kernel was local,
540 # this triggers exit_requested if the kernel was local,
541 # and a dialog if the kernel was remote,
541 # and a dialog if the kernel was remote,
542 # so we don't suddenly clear the qtconsole without asking.
542 # so we don't suddenly clear the qtconsole without asking.
543 if self._local_kernel:
543 if self._local_kernel:
544 self.exit_requested.emit(self)
544 self.exit_requested.emit(self)
545 else:
545 else:
546 title = self.window().windowTitle()
546 title = self.window().windowTitle()
547 reply = QtGui.QMessageBox.question(self, title,
547 reply = QtGui.QMessageBox.question(self, title,
548 "Kernel has been shutdown permanently. "
548 "Kernel has been shutdown permanently. "
549 "Close the Console?",
549 "Close the Console?",
550 QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
550 QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
551 if reply == QtGui.QMessageBox.Yes:
551 if reply == QtGui.QMessageBox.Yes:
552 self.exit_requested.emit(self)
552 self.exit_requested.emit(self)
553
553
554 def _handle_status(self, msg):
554 def _handle_status(self, msg):
555 """Handle status message"""
555 """Handle status message"""
556 # This is where a busy/idle indicator would be triggered,
556 # This is where a busy/idle indicator would be triggered,
557 # when we make one.
557 # when we make one.
558 state = msg['content'].get('execution_state', '')
558 state = msg['content'].get('execution_state', '')
559 if state == 'starting':
559 if state == 'starting':
560 # kernel started while we were running
560 # kernel started while we were running
561 if self._executing:
561 if self._executing:
562 self._handle_kernel_restarted(died=True)
562 self._handle_kernel_restarted(died=True)
563 elif state == 'idle':
563 elif state == 'idle':
564 pass
564 pass
565 elif state == 'busy':
565 elif state == 'busy':
566 pass
566 pass
567
567
568 def _started_channels(self):
568 def _started_channels(self):
569 """ Called when the KernelManager channels have started listening or
569 """ Called when the KernelManager channels have started listening or
570 when the frontend is assigned an already listening KernelManager.
570 when the frontend is assigned an already listening KernelManager.
571 """
571 """
572 self.reset(clear=True)
572 self.reset(clear=True)
573
573
574 #---------------------------------------------------------------------------
574 #---------------------------------------------------------------------------
575 # 'FrontendWidget' public interface
575 # 'FrontendWidget' public interface
576 #---------------------------------------------------------------------------
576 #---------------------------------------------------------------------------
577
577
578 def copy_raw(self):
578 def copy_raw(self):
579 """ Copy the currently selected text to the clipboard without attempting
579 """ Copy the currently selected text to the clipboard without attempting
580 to remove prompts or otherwise alter the text.
580 to remove prompts or otherwise alter the text.
581 """
581 """
582 self._control.copy()
582 self._control.copy()
583
583
584 def execute_file(self, path, hidden=False):
584 def execute_file(self, path, hidden=False):
585 """ Attempts to execute file with 'path'. If 'hidden', no output is
585 """ Attempts to execute file with 'path'. If 'hidden', no output is
586 shown.
586 shown.
587 """
587 """
588 self.execute('execfile(%r)' % path, hidden=hidden)
588 self.execute('execfile(%r)' % path, hidden=hidden)
589
589
590 def interrupt_kernel(self):
590 def interrupt_kernel(self):
591 """ Attempts to interrupt the running kernel.
591 """ Attempts to interrupt the running kernel.
592
592
593 Also unsets _reading flag, to avoid runtime errors
593 Also unsets _reading flag, to avoid runtime errors
594 if raw_input is called again.
594 if raw_input is called again.
595 """
595 """
596 if self.custom_interrupt:
596 if self.custom_interrupt:
597 self._reading = False
597 self._reading = False
598 self.custom_interrupt_requested.emit()
598 self.custom_interrupt_requested.emit()
599 elif self.kernel_manager:
599 elif self.kernel_manager:
600 self._reading = False
600 self._reading = False
601 self.kernel_manager.interrupt_kernel()
601 self.kernel_manager.interrupt_kernel()
602 else:
602 else:
603 self._append_plain_text('Cannot interrupt a kernel I did not start.\n')
603 self._append_plain_text('Cannot interrupt a kernel I did not start.\n')
604
604
605 def reset(self, clear=False):
605 def reset(self, clear=False):
606 """ Resets the widget to its initial state if ``clear`` parameter
606 """ Resets the widget to its initial state if ``clear`` parameter
607 is True, otherwise
607 is True, otherwise
608 prints a visual indication of the fact that the kernel restarted, but
608 prints a visual indication of the fact that the kernel restarted, but
609 does not clear the traces from previous usage of the kernel before it
609 does not clear the traces from previous usage of the kernel before it
610 was restarted. With ``clear=True``, it is similar to ``%clear``, but
610 was restarted. With ``clear=True``, it is similar to ``%clear``, but
611 also re-writes the banner and aborts execution if necessary.
611 also re-writes the banner and aborts execution if necessary.
612 """
612 """
613 if self._executing:
613 if self._executing:
614 self._executing = False
614 self._executing = False
615 self._request_info['execute'] = {}
615 self._request_info['execute'] = {}
616 self._reading = False
616 self._reading = False
617 self._highlighter.highlighting_on = False
617 self._highlighter.highlighting_on = False
618
618
619 if clear:
619 if clear:
620 self._control.clear()
620 self._control.clear()
621 if self._display_banner:
621 if self._display_banner:
622 self._append_plain_text(self.banner)
622 self._append_plain_text(self.banner)
623 if self.kernel_banner:
623 if self.kernel_banner:
624 self._append_plain_text(self.kernel_banner)
624 self._append_plain_text(self.kernel_banner)
625
625
626 # update output marker for stdout/stderr, so that startup
626 # update output marker for stdout/stderr, so that startup
627 # messages appear after banner:
627 # messages appear after banner:
628 self._append_before_prompt_pos = self._get_cursor().position()
628 self._append_before_prompt_pos = self._get_cursor().position()
629 self._show_interpreter_prompt()
629 self._show_interpreter_prompt()
630
630
631 def restart_kernel(self, message, now=False):
631 def restart_kernel(self, message, now=False):
632 """ Attempts to restart the running kernel.
632 """ Attempts to restart the running kernel.
633 """
633 """
634 # FIXME: now should be configurable via a checkbox in the dialog. Right
634 # FIXME: now should be configurable via a checkbox in the dialog. Right
635 # now at least the heartbeat path sets it to True and the manual restart
635 # now at least the heartbeat path sets it to True and the manual restart
636 # to False. But those should just be the pre-selected states of a
636 # to False. But those should just be the pre-selected states of a
637 # checkbox that the user could override if so desired. But I don't know
637 # checkbox that the user could override if so desired. But I don't know
638 # enough Qt to go implementing the checkbox now.
638 # enough Qt to go implementing the checkbox now.
639
639
640 if self.custom_restart:
640 if self.custom_restart:
641 self.custom_restart_requested.emit()
641 self.custom_restart_requested.emit()
642 return
642 return
643
643
644 if self.kernel_manager:
644 if self.kernel_manager:
645 # Pause the heart beat channel to prevent further warnings.
645 # Pause the heart beat channel to prevent further warnings.
646 self.kernel_client.hb_channel.pause()
646 self.kernel_client.hb_channel.pause()
647
647
648 # Prompt the user to restart the kernel. Un-pause the heartbeat if
648 # Prompt the user to restart the kernel. Un-pause the heartbeat if
649 # they decline. (If they accept, the heartbeat will be un-paused
649 # they decline. (If they accept, the heartbeat will be un-paused
650 # automatically when the kernel is restarted.)
650 # automatically when the kernel is restarted.)
651 if self.confirm_restart:
651 if self.confirm_restart:
652 buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
652 buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
653 result = QtGui.QMessageBox.question(self, 'Restart kernel?',
653 result = QtGui.QMessageBox.question(self, 'Restart kernel?',
654 message, buttons)
654 message, buttons)
655 do_restart = result == QtGui.QMessageBox.Yes
655 do_restart = result == QtGui.QMessageBox.Yes
656 else:
656 else:
657 # confirm_restart is False, so we don't need to ask user
657 # confirm_restart is False, so we don't need to ask user
658 # anything, just do the restart
658 # anything, just do the restart
659 do_restart = True
659 do_restart = True
660 if do_restart:
660 if do_restart:
661 try:
661 try:
662 self.kernel_manager.restart_kernel(now=now)
662 self.kernel_manager.restart_kernel(now=now)
663 except RuntimeError as e:
663 except RuntimeError as e:
664 self._append_plain_text(
664 self._append_plain_text(
665 'Error restarting kernel: %s\n' % e,
665 'Error restarting kernel: %s\n' % e,
666 before_prompt=True
666 before_prompt=True
667 )
667 )
668 else:
668 else:
669 self._append_html("<br>Restarting kernel...\n<hr><br>",
669 self._append_html("<br>Restarting kernel...\n<hr><br>",
670 before_prompt=True,
670 before_prompt=True,
671 )
671 )
672 else:
672 else:
673 self.kernel_client.hb_channel.unpause()
673 self.kernel_client.hb_channel.unpause()
674
674
675 else:
675 else:
676 self._append_plain_text(
676 self._append_plain_text(
677 'Cannot restart a Kernel I did not start\n',
677 'Cannot restart a Kernel I did not start\n',
678 before_prompt=True
678 before_prompt=True
679 )
679 )
680
680
681 def append_stream(self, text):
681 def append_stream(self, text):
682 """Appends text to the output stream."""
682 """Appends text to the output stream."""
683 # Most consoles treat tabs as being 8 space characters. Convert tabs
683 # Most consoles treat tabs as being 8 space characters. Convert tabs
684 # to spaces so that output looks as expected regardless of this
684 # to spaces so that output looks as expected regardless of this
685 # widget's tab width.
685 # widget's tab width.
686 text = text.expandtabs(8)
686 text = text.expandtabs(8)
687 self._append_plain_text(text, before_prompt=True)
687 self._append_plain_text(text, before_prompt=True)
688 self._control.moveCursor(QtGui.QTextCursor.End)
688 self._control.moveCursor(QtGui.QTextCursor.End)
689
689
690 def flush_clearoutput(self):
690 def flush_clearoutput(self):
691 """If a clearoutput is pending, execute it."""
691 """If a clearoutput is pending, execute it."""
692 if self._pending_clearoutput:
692 if self._pending_clearoutput:
693 self._pending_clearoutput = False
693 self._pending_clearoutput = False
694 self.clear_output()
694 self.clear_output()
695
695
696 def clear_output(self):
696 def clear_output(self):
697 """Clears the current line of output."""
697 """Clears the current line of output."""
698 cursor = self._control.textCursor()
698 cursor = self._control.textCursor()
699 cursor.beginEditBlock()
699 cursor.beginEditBlock()
700 cursor.movePosition(cursor.StartOfLine, cursor.KeepAnchor)
700 cursor.movePosition(cursor.StartOfLine, cursor.KeepAnchor)
701 cursor.insertText('')
701 cursor.insertText('')
702 cursor.endEditBlock()
702 cursor.endEditBlock()
703
703
704 #---------------------------------------------------------------------------
704 #---------------------------------------------------------------------------
705 # 'FrontendWidget' protected interface
705 # 'FrontendWidget' protected interface
706 #---------------------------------------------------------------------------
706 #---------------------------------------------------------------------------
707
707
708 def _auto_call_tip(self):
708 def _auto_call_tip(self):
709 """Trigger call tip automatically on open parenthesis
709 """Trigger call tip automatically on open parenthesis
710
710
711 Call tips can be requested explcitly with `_call_tip`.
711 Call tips can be requested explcitly with `_call_tip`.
712 """
712 """
713 cursor = self._get_cursor()
713 cursor = self._get_cursor()
714 cursor.movePosition(QtGui.QTextCursor.Left)
714 cursor.movePosition(QtGui.QTextCursor.Left)
715 if cursor.document().characterAt(cursor.position()) == '(':
715 if cursor.document().characterAt(cursor.position()) == '(':
716 # trigger auto call tip on open paren
716 # trigger auto call tip on open paren
717 self._call_tip()
717 self._call_tip()
718
718
719 def _call_tip(self):
719 def _call_tip(self):
720 """Shows a call tip, if appropriate, at the current cursor location."""
720 """Shows a call tip, if appropriate, at the current cursor location."""
721 # Decide if it makes sense to show a call tip
721 # Decide if it makes sense to show a call tip
722 if not self.enable_calltips or not self.kernel_client.shell_channel.is_alive():
722 if not self.enable_calltips or not self.kernel_client.shell_channel.is_alive():
723 return False
723 return False
724 cursor_pos = self._get_input_buffer_cursor_pos()
724 cursor_pos = self._get_input_buffer_cursor_pos()
725 code = self.input_buffer
725 code = self.input_buffer
726 # Send the metadata request to the kernel
726 # Send the metadata request to the kernel
727 msg_id = self.kernel_client.inspect(code, cursor_pos)
727 msg_id = self.kernel_client.inspect(code, cursor_pos)
728 pos = self._get_cursor().position()
728 pos = self._get_cursor().position()
729 self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos)
729 self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos)
730 return True
730 return True
731
731
732 def _complete(self):
732 def _complete(self):
733 """ Performs completion at the current cursor location.
733 """ Performs completion at the current cursor location.
734 """
734 """
735 # Send the completion request to the kernel
735 # Send the completion request to the kernel
736 msg_id = self.kernel_client.complete(
736 msg_id = self.kernel_client.complete(
737 code=self.input_buffer,
737 code=self.input_buffer,
738 cursor_pos=self._get_input_buffer_cursor_pos(),
738 cursor_pos=self._get_input_buffer_cursor_pos(),
739 )
739 )
740 pos = self._get_cursor().position()
740 pos = self._get_cursor().position()
741 info = self._CompletionRequest(msg_id, pos)
741 info = self._CompletionRequest(msg_id, pos)
742 self._request_info['complete'] = info
742 self._request_info['complete'] = info
743
743
744 def _process_execute_abort(self, msg):
744 def _process_execute_abort(self, msg):
745 """ Process a reply for an aborted execution request.
745 """ Process a reply for an aborted execution request.
746 """
746 """
747 self._append_plain_text("ERROR: execution aborted\n")
747 self._append_plain_text("ERROR: execution aborted\n")
748
748
749 def _process_execute_error(self, msg):
749 def _process_execute_error(self, msg):
750 """ Process a reply for an execution request that resulted in an error.
750 """ Process a reply for an execution request that resulted in an error.
751 """
751 """
752 content = msg['content']
752 content = msg['content']
753 # If a SystemExit is passed along, this means exit() was called - also
753 # If a SystemExit is passed along, this means exit() was called - also
754 # all the ipython %exit magic syntax of '-k' to be used to keep
754 # all the ipython %exit magic syntax of '-k' to be used to keep
755 # the kernel running
755 # the kernel running
756 if content['ename']=='SystemExit':
756 if content['ename']=='SystemExit':
757 keepkernel = content['evalue']=='-k' or content['evalue']=='True'
757 keepkernel = content['evalue']=='-k' or content['evalue']=='True'
758 self._keep_kernel_on_exit = keepkernel
758 self._keep_kernel_on_exit = keepkernel
759 self.exit_requested.emit(self)
759 self.exit_requested.emit(self)
760 else:
760 else:
761 traceback = ''.join(content['traceback'])
761 traceback = ''.join(content['traceback'])
762 self._append_plain_text(traceback)
762 self._append_plain_text(traceback)
763
763
764 def _process_execute_ok(self, msg):
764 def _process_execute_ok(self, msg):
765 """ Process a reply for a successful execution request.
765 """ Process a reply for a successful execution request.
766 """
766 """
767 payload = msg['content']['payload']
767 payload = msg['content']['payload']
768 for item in payload:
768 for item in payload:
769 if not self._process_execute_payload(item):
769 if not self._process_execute_payload(item):
770 warning = 'Warning: received unknown payload of type %s'
770 warning = 'Warning: received unknown payload of type %s'
771 print(warning % repr(item['source']))
771 print(warning % repr(item['source']))
772
772
773 def _process_execute_payload(self, item):
773 def _process_execute_payload(self, item):
774 """ Process a single payload item from the list of payload items in an
774 """ Process a single payload item from the list of payload items in an
775 execution reply. Returns whether the payload was handled.
775 execution reply. Returns whether the payload was handled.
776 """
776 """
777 # The basic FrontendWidget doesn't handle payloads, as they are a
777 # The basic FrontendWidget doesn't handle payloads, as they are a
778 # mechanism for going beyond the standard Python interpreter model.
778 # mechanism for going beyond the standard Python interpreter model.
779 return False
779 return False
780
780
781 def _show_interpreter_prompt(self):
781 def _show_interpreter_prompt(self):
782 """ Shows a prompt for the interpreter.
782 """ Shows a prompt for the interpreter.
783 """
783 """
784 self._show_prompt('>>> ')
784 self._show_prompt('>>> ')
785
785
786 def _show_interpreter_prompt_for_reply(self, msg):
786 def _show_interpreter_prompt_for_reply(self, msg):
787 """ Shows a prompt for the interpreter given an 'execute_reply' message.
787 """ Shows a prompt for the interpreter given an 'execute_reply' message.
788 """
788 """
789 self._show_interpreter_prompt()
789 self._show_interpreter_prompt()
790
790
791 #------ Signal handlers ----------------------------------------------------
791 #------ Signal handlers ----------------------------------------------------
792
792
793 def _document_contents_change(self, position, removed, added):
793 def _document_contents_change(self, position, removed, added):
794 """ Called whenever the document's content changes. Display a call tip
794 """ Called whenever the document's content changes. Display a call tip
795 if appropriate.
795 if appropriate.
796 """
796 """
797 # Calculate where the cursor should be *after* the change:
797 # Calculate where the cursor should be *after* the change:
798 position += added
798 position += added
799
799
800 document = self._control.document()
800 document = self._control.document()
801 if position == self._get_cursor().position():
801 if position == self._get_cursor().position():
802 self._auto_call_tip()
802 self._auto_call_tip()
803
803
804 #------ Trait default initializers -----------------------------------------
804 #------ Trait default initializers -----------------------------------------
805
805
806 def _banner_default(self):
806 def _banner_default(self):
807 """ Returns the standard Python banner.
807 """ Returns the standard Python banner.
808 """
808 """
809 banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \
809 banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \
810 '"license" for more information.'
810 '"license" for more information.'
811 return banner % (sys.version, sys.platform)
811 return banner % (sys.version, sys.platform)
General Comments 0
You need to be logged in to leave comments. Login now