##// END OF EJS Templates
Moving new-embed.py
Moving new-embed.py

File last commit:

r14990:07072a49 merge
r16067:bd741719
Show More
frontend_widget.py
806 lines | 32.8 KiB | text/x-python | PythonLexer
/ IPython / qt / console / frontend_widget.py
Fernando Perez
Implement support for 'cell' mode with Ctrl-Enter....
r3004 from __future__ import print_function
epatters
* Added ability to interrupt a kernel to FrontendWidget...
r2687 # Standard library imports
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934 from collections import namedtuple
epatters
Added banners to FrontendWidget and IPythonWidget.
r2714 import sys
Matthias BUSSONNIER
Generate "All magics..." menu live...
r5392 import uuid
epatters
* Added ability to interrupt a kernel to FrontendWidget...
r2687
epatters
Initial checkin of Qt frontend code.
r2602 # System library imports
MinRK
disable calltips in PySide < 1.0.7 to prevent segfault...
r5258 from IPython.external import qt
Evan Patterson
Paved the way for PySide support....
r3304 from IPython.external.qt import QtCore, QtGui
MinRK
make QtConsole Lexer configurable...
r13733 from IPython.utils import py3compat
from IPython.utils.importstring import import_item
epatters
Initial checkin of Qt frontend code.
r2602
# Local imports
Thomas Kluyver
Fix starting the Qt console
r10099 from IPython.core.inputsplitter import InputSplitter, IPythonInputSplitter
from IPython.core.inputtransformer import classic_prompt
Fernando Perez
Add function signature info to calltips....
r3051 from IPython.core.oinspect import call_tip
Fernando Perez
Fix all imports for Qt console.
r11022 from IPython.qt.base_frontend_mixin import BaseFrontendMixin
MinRK
make QtConsole Lexer configurable...
r13733 from IPython.utils.traitlets import Any, Bool, Instance, Unicode, DottedObjectName
Thomas Kluyver
Use explicit relative imports...
r13347 from .bracket_matcher import BracketMatcher
from .call_tip_widget import CallTipWidget
from .completion_lexer import CompletionLexer
from .history_console_widget import HistoryConsoleWidget
from .pygments_highlighter import PygmentsHighlighter
epatters
Initial checkin of Qt frontend code.
r2602
class FrontendHighlighter(PygmentsHighlighter):
epatters
Improve Qt console's placement of text appended before a prompt.
r4058 """ A PygmentsHighlighter that understands and ignores prompts.
epatters
Initial checkin of Qt frontend code.
r2602 """
MinRK
make QtConsole Lexer configurable...
r13733 def __init__(self, frontend, lexer=None):
super(FrontendHighlighter, self).__init__(frontend._control.document(), lexer=lexer)
epatters
Initial checkin of Qt frontend code.
r2602 self._current_offset = 0
self._frontend = frontend
self.highlighting_on = False
Evan Patterson
Paved the way for PySide support....
r3304 def highlightBlock(self, string):
epatters
Initial checkin of Qt frontend code.
r2602 """ Highlight a block of text. Reimplemented to highlight selectively.
"""
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 if not self.highlighting_on:
return
Evan Patterson
Paved the way for PySide support....
r3304 # The input to this function is a unicode string that may contain
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 # paragraph break characters, non-breaking spaces, etc. Here we acquire
# the string as plain text so we can compare it.
current_block = self.currentBlock()
string = self._frontend._get_block_plain_text(current_block)
# Decide whether to check for the regular or continuation prompt.
if current_block.contains(self._frontend._prompt_pos):
prompt = self._frontend._prompt
else:
prompt = self._frontend._continuation_prompt
epatters
Improve Qt console's placement of text appended before a prompt.
r4058 # Only highlight if we can identify a prompt, but make sure not to
# highlight the prompt.
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 if string.startswith(prompt):
self._current_offset = len(prompt)
Evan Patterson
Paved the way for PySide support....
r3304 string = string[len(prompt):]
epatters
Improve Qt console's placement of text appended before a prompt.
r4058 super(FrontendHighlighter, self).highlightBlock(string)
epatters
Initial checkin of Qt frontend code.
r2602
epatters
Minor cleanup.
r2825 def rehighlightBlock(self, block):
""" Reimplemented to temporarily enable highlighting if disabled.
"""
old = self.highlighting_on
self.highlighting_on = True
super(FrontendHighlighter, self).rehighlightBlock(block)
self.highlighting_on = old
epatters
Initial checkin of Qt frontend code.
r2602 def setFormat(self, start, count, format):
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 """ Reimplemented to highlight selectively.
epatters
Initial checkin of Qt frontend code.
r2602 """
start += self._current_offset
epatters
Improve Qt console's placement of text appended before a prompt.
r4058 super(FrontendHighlighter, self).setFormat(start, count, format)
epatters
Initial checkin of Qt frontend code.
r2602
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 class FrontendWidget(HistoryConsoleWidget, BaseFrontendMixin):
epatters
* Created an IPythonWidget subclass of FrontendWidget to contain IPython specific functionality....
r2627 """ A Qt frontend for a generic Python kernel.
epatters
Initial checkin of Qt frontend code.
r2602 """
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851
epatters
ENH: Allow FrontendWidget banner to be changed without subclassing.
r4689 # The text to show when the kernel is (re)started.
Thomas Kluyver
Make Qt console banner configurable
r12271 banner = Unicode(config=True)
MinRK
make calltips configurable in qtconsole...
r4569
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 # An option and corresponding signal for overriding the default kernel
# interrupt behavior.
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 custom_interrupt = Bool(False)
Evan Patterson
Paved the way for PySide support....
r3304 custom_interrupt_requested = QtCore.Signal()
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851
epatters
* Improved frontend-side kernel restart support....
r2913 # An option and corresponding signals for overriding the default kernel
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 # restart behavior.
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 custom_restart = Bool(False)
Evan Patterson
Paved the way for PySide support....
r3304 custom_restart_kernel_died = QtCore.Signal(float)
custom_restart_requested = QtCore.Signal()
epatters
Add history_tail method to ConsoleWidget for retreiving the local history.
r3516
epatters
ENH: Allow FrontendWidget banner to be changed without subclassing.
r4689 # Whether to automatically show calltips on open-parentheses.
enable_calltips = Bool(True, config=True,
help="Whether to draw information calltips on open-parentheses.")
Paul Ivanov
add qt config option to clear_on_kernel_restart...
r6684 clear_on_kernel_restart = Bool(True, config=True,
help="Whether to clear the console when the kernel is restarted")
Paul Ivanov
added confirm_restart configuration option...
r7590 confirm_restart = Bool(True, config=True,
help="Whether to ask for user confirmation when restarting kernel")
MinRK
make QtConsole Lexer configurable...
r13733
lexer_class = DottedObjectName(config=True,
help="The pygments lexer class to use."
)
def _lexer_class_changed(self, name, old, new):
lexer_class = import_item(new)
self.lexer = lexer_class()
def _lexer_class_default(self):
if py3compat.PY3:
return 'pygments.lexers.Python3Lexer'
else:
return 'pygments.lexers.PythonLexer'
lexer = Any()
def _lexer_default(self):
lexer_class = import_item(self.lexer_class)
return lexer_class()
Paul Ivanov
added confirm_restart configuration option...
r7590
epatters
Add 'executing' signal to FrontendWidget for symmetry with 'executed' signal.
r3682 # Emitted when a user visible 'execute_request' has been submitted to the
# kernel from the FrontendWidget. Contains the code to be executed.
executing = QtCore.Signal(object)
epatters
Add history_tail method to ConsoleWidget for retreiving the local history.
r3516 # Emitted when a user-visible 'execute_reply' has been received from the
# kernel and processed by the FrontendWidget. Contains the response message.
Evan Patterson
Paved the way for PySide support....
r3304 executed = QtCore.Signal(object)
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
r2961
# Emitted when an exit request has been received from the kernel.
Matthias BUSSONNIER
tab management new/existing kernel....
r5035 exit_requested = QtCore.Signal(object)
Bernardo B. Marques
remove all trailling spaces
r4872
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 # Protected class variables.
Thomas Kluyver
Fix for starting the Qt console
r10113 _prompt_transformer = IPythonInputSplitter(physical_line_transforms=[classic_prompt()],
logical_line_transforms=[],
python_line_transforms=[],
)
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934 _CallTipRequest = namedtuple('_CallTipRequest', ['id', 'pos'])
_CompletionRequest = namedtuple('_CompletionRequest', ['id', 'pos'])
_ExecutionRequest = namedtuple('_ExecutionRequest', ['id', 'kind'])
epatters
First cut at a generic bracket matcher for Q[Plain]TextEdits.
r2894 _input_splitter_class = InputSplitter
MinRK
tweaked close dialog and added prompts to prevent silent remote close
r3129 _local_kernel = False
MinRK
QtConsole now uses newapp
r3971 _highlighter = Instance(FrontendHighlighter)
epatters
* Fixed bug where syntax highlighting was lost after updating a prompt with a bad number....
r2800
epatters
Initial checkin of Qt frontend code.
r2602 #---------------------------------------------------------------------------
epatters
Refactored ConsoleWidget to encapsulate, rather than inherit from, QPlainTextEdit. This permits a QTextEdit to be substituted for a QPlainTextEdit if desired. It also makes it more clear what is the public interface of ConsoleWidget.
r2736 # 'object' interface
epatters
Initial checkin of Qt frontend code.
r2602 #---------------------------------------------------------------------------
Bernardo B. Marques
remove all trailling spaces
r4872
epatters
Refactored ConsoleWidget to encapsulate, rather than inherit from, QPlainTextEdit. This permits a QTextEdit to be substituted for a QPlainTextEdit if desired. It also makes it more clear what is the public interface of ConsoleWidget.
r2736 def __init__(self, *args, **kw):
super(FrontendWidget, self).__init__(*args, **kw)
MinRK
warn when disabling calltips due to old PySide
r5285 # FIXME: remove this when PySide min version is updated past 1.0.7
MinRK
disable calltips in PySide < 1.0.7 to prevent segfault...
r5258 # forcefully disable calltips if PySide is < 1.0.7, because they crash
if qt.QT_API == qt.QT_API_PYSIDE:
import PySide
if PySide.__version_info__ < (1,0,7):
MinRK
warn when disabling calltips due to old PySide
r5285 self.log.warn("PySide %s < 1.0.7 detected, disabling calltips" % PySide.__version__)
MinRK
disable calltips in PySide < 1.0.7 to prevent segfault...
r5258 self.enable_calltips = False
epatters
Initial checkin of Qt frontend code.
r2602
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643 # FrontendWidget protected variables.
epatters
First cut at a generic bracket matcher for Q[Plain]TextEdits.
r2894 self._bracket_matcher = BracketMatcher(self._control)
epatters
Refactored ConsoleWidget to encapsulate, rather than inherit from, QPlainTextEdit. This permits a QTextEdit to be substituted for a QPlainTextEdit if desired. It also makes it more clear what is the public interface of ConsoleWidget.
r2736 self._call_tip_widget = CallTipWidget(self._control)
MinRK
make QtConsole Lexer configurable...
r13733 self._completion_lexer = CompletionLexer(self.lexer)
epatters
* Added Cut support to ConsoleWidget....
r2990 self._copy_raw_action = QtGui.QAction('Copy (Raw Text)', None)
epatters
* The Qt console frontend now ignores cross chatter from other frontends....
r2824 self._hidden = False
MinRK
make QtConsole Lexer configurable...
r13733 self._highlighter = FrontendHighlighter(self, lexer=self.lexer)
Thomas Kluyver
Simplify InputSplitter by stripping out input_mode distinction
r10251 self._input_splitter = self._input_splitter_class()
epatters
* Refactored KernelManager to use Traitlets and to have its channels as attributes...
r2611 self._kernel_manager = None
MinRK
update Qt to use KernelClient
r10288 self._kernel_client = None
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934 self._request_info = {}
Matthias BUSSONNIER
qtconsole: fix race-cond, handle multiple exec...
r5506 self._request_info['execute'] = {};
Matthias BUSSONNIER
fix @fperez suggestions
r5395 self._callback_dict = {}
epatters
Initial checkin of Qt frontend code.
r2602
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 # Configure the ConsoleWidget.
epatters
* ConsoleWidget now has better support for non-GUI tab completion. Multiple matches are formatted into columns....
r2723 self.tab_width = 4
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 self._set_continuation_prompt('... ')
epatters
Fixed font changes not being propagated to CallTipWidget.
r3031 # Configure the CallTipWidget.
self._call_tip_widget.setFont(self.font)
self.font_changed.connect(self._call_tip_widget.setFont)
epatters
* Added Cut support to ConsoleWidget....
r2990 # Configure actions.
action = self._copy_raw_action
key = QtCore.Qt.CTRL | QtCore.Qt.SHIFT | QtCore.Qt.Key_C
action.setEnabled(False)
action.setShortcut(QtGui.QKeySequence(key))
action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)
action.triggered.connect(self.copy_raw)
self.copy_available.connect(action.setEnabled)
self.addAction(action)
epatters
Refactored ConsoleWidget to encapsulate, rather than inherit from, QPlainTextEdit. This permits a QTextEdit to be substituted for a QPlainTextEdit if desired. It also makes it more clear what is the public interface of ConsoleWidget.
r2736 # Connect signal handlers.
document = self._control.document()
document.contentsChange.connect(self._document_contents_change)
Bernardo B. Marques
remove all trailling spaces
r4872
epatters
Refactored ConsoleWidget's HTML exportaton code + other minor code cleanup.
r3361 # Set flag for whether we are connected via localhost.
Bernardo B. Marques
remove all trailling spaces
r4872 self._local_kernel = kw.get('local_kernel',
epatters
Refactored ConsoleWidget's HTML exportaton code + other minor code cleanup.
r3361 FrontendWidget._local_kernel)
epatters
* Adding object_info_request support to prototype kernel....
r2612
epatters
Minor comment cleanup.
r2669 #---------------------------------------------------------------------------
epatters
* Added "smart copy" support to FrontendWidget and ConsoleWidget. Tabs are expanded and prompts are stripped....
r2971 # 'ConsoleWidget' public interface
#---------------------------------------------------------------------------
def copy(self):
""" Copy the currently selected text to the clipboard, removing prompts.
"""
Carlos Cordoba
Fix for copy action (Ctrl+C) when there is no pager in qtconsole...
r7552 if self._page_control is not None and self._page_control.hasFocus():
Matthias BUSSONNIER
qtconsole : allow copy with shortcut in pager...
r5561 self._page_control.copy()
MinRK
add Widget._transform_prompt staticmethod...
r5647 elif self._control.hasFocus():
Matthias BUSSONNIER
qtconsole : allow copy with shortcut in pager...
r5561 text = self._control.textCursor().selection().toPlainText()
if text:
Thomas Kluyver
Fix starting the Qt console
r10099 text = self._prompt_transformer.transform_cell(text)
Matthias BUSSONNIER
qtconsole : allow copy with shortcut in pager...
r5561 QtGui.QApplication.clipboard().setText(text)
else:
self.log.debug("frontend widget : unknown copy target")
epatters
* Added "smart copy" support to FrontendWidget and ConsoleWidget. Tabs are expanded and prompts are stripped....
r2971
#---------------------------------------------------------------------------
epatters
Initial checkin of Qt frontend code.
r2602 # 'ConsoleWidget' abstract interface
#---------------------------------------------------------------------------
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 def _is_complete(self, source, interactive):
""" Returns whether 'source' can be completely processed and a new
prompt created. When triggered by an Enter/Return key press,
'interactive' is True; otherwise, it is False.
epatters
Initial checkin of Qt frontend code.
r2602 """
Thomas Kluyver
Simplify InputSplitter by stripping out input_mode distinction
r10251 self._input_splitter.reset()
Thomas Kluyver
Protect Qt console against SyntaxError from input transformers.
r13529 try:
complete = self._input_splitter.push(source)
except SyntaxError:
return True
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 if interactive:
complete = not self._input_splitter.push_accepts_more()
return complete
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
r2961 def _execute(self, source, hidden):
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 """ Execute 'source'. If 'hidden', do not show any output.
Fernando Perez
Rework messaging to better conform to our spec....
r2926
See parent class :meth:`execute` docstring for full details.
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 """
MinRK
expose shell channel methods at the client level
r10294 msg_id = self.kernel_client.execute(source, hidden)
Matthias BUSSONNIER
qtconsole: fix race-cond, handle multiple exec...
r5506 self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'user')
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 self._hidden = hidden
epatters
Add 'executing' signal to FrontendWidget for symmetry with 'executed' signal.
r3682 if not hidden:
self.executing.emit(source)
Bernardo B. Marques
remove all trailling spaces
r4872
epatters
Initial checkin of Qt frontend code.
r2602 def _prompt_started_hook(self):
""" Called immediately after a new prompt is displayed.
"""
epatters
Fixed bug where syntax highlighting was enabled during raw_input mode.
r2709 if not self._reading:
self._highlighter.highlighting_on = True
epatters
Initial checkin of Qt frontend code.
r2602
def _prompt_finished_hook(self):
""" Called immediately after a prompt is finished, i.e. when some input
will be processed and a new prompt displayed.
"""
epatters
Refactored ConsoleWidget's HTML exportaton code + other minor code cleanup.
r3361 # Flush all state from the input splitter so the next round of
# reading input starts with a clean buffer.
self._input_splitter.reset()
epatters
Fixed bug where syntax highlighting was enabled during raw_input mode.
r2709 if not self._reading:
self._highlighter.highlighting_on = False
epatters
Initial checkin of Qt frontend code.
r2602
def _tab_pressed(self):
""" Called when the tab key is pressed. Returns whether to continue
processing the event.
"""
epatters
The FrontendWidget now performs tab-completion more aggressively.
r2847 # Perform tab completion if:
# 1) The cursor is in the input buffer.
# 2) There is a non-whitespace character before the cursor.
text = self._get_input_buffer_cursor_line()
if text is None:
return False
complete = bool(text[:self._get_input_buffer_cursor_column()].strip())
if complete:
self._complete()
return not complete
epatters
Initial checkin of Qt frontend code.
r2602
#---------------------------------------------------------------------------
epatters
Fixed bug with ConsoleWidget smart paste.
r2787 # 'ConsoleWidget' protected interface
#---------------------------------------------------------------------------
epatters
* Added Cut support to ConsoleWidget....
r2990 def _context_menu_make(self, pos):
""" Reimplemented to add an action for raw copy.
"""
menu = super(FrontendWidget, self)._context_menu_make(pos)
for before_action in menu.actions():
if before_action.shortcut().matches(QtGui.QKeySequence.Paste) == \
QtGui.QKeySequence.ExactMatch:
menu.insertAction(before_action, self._copy_raw_action)
break
return menu
Matthias BUSSONNIER
add copy_raw, interrupt kernel and restart kernel into menu
r5063 def request_interrupt_kernel(self):
if self._executing:
self.interrupt_kernel()
def request_restart_kernel(self):
message = 'Are you sure you want to restart the kernel?'
self.restart_kernel(message, now=False)
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 def _event_filter_console_keypress(self, event):
epatters
Removed use of hard tabs in FrontendWidget and implemented "smart" backspace.
r3022 """ Reimplemented for execution interruption and smart backspace.
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 """
key = event.key()
epatters
Cmd-C will no longer interrupt the kernel in Mac OS (only Ctrl-C will do this).
r2941 if self._control_key_down(event.modifiers(), include_command=False):
epatters
Removed use of hard tabs in FrontendWidget and implemented "smart" backspace.
r3022
epatters
Numerous usability enhancements to the Qt console widget, particularly with regard to key bindings.
r2897 if key == QtCore.Qt.Key_C and self._executing:
Matthias BUSSONNIER
add copy_raw, interrupt kernel and restart kernel into menu
r5063 self.request_interrupt_kernel()
epatters
Fixed scrolling bugs when using rich text mode. (Work around probable bug in Qt.)
r2914 return True
epatters
Removed use of hard tabs in FrontendWidget and implemented "smart" backspace.
r3022
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 elif key == QtCore.Qt.Key_Period:
Matthias BUSSONNIER
add copy_raw, interrupt kernel and restart kernel into menu
r5063 self.request_restart_kernel()
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 return True
epatters
Removed use of hard tabs in FrontendWidget and implemented "smart" backspace.
r3022
elif not event.modifiers() & QtCore.Qt.AltModifier:
# Smart backspace: remove four characters in one backspace if:
# 1) everything left of the cursor is whitespace
# 2) the four characters immediately left of the cursor are spaces
if key == QtCore.Qt.Key_Backspace:
col = self._get_input_buffer_cursor_column()
cursor = self._control.textCursor()
if col > 3 and not cursor.hasSelection():
text = self._get_input_buffer_cursor_line()[:col]
if text.endswith(' ') and not text.strip():
cursor.movePosition(QtGui.QTextCursor.Left,
QtGui.QTextCursor.KeepAnchor, 4)
cursor.removeSelectedText()
return True
epatters
First cut at allowing the kernel to be restarted from the frontend.
r2851 return super(FrontendWidget, self)._event_filter_console_keypress(event)
epatters
Fixed several bugs involving the insertion of new lines. Pressing Enter in the ConsoleWidget now works as expected.
r2896 def _insert_continuation_prompt(self, cursor):
epatters
Fixed bug with ConsoleWidget smart paste.
r2787 """ Reimplemented for auto-indentation.
"""
epatters
Fixed several bugs involving the insertion of new lines. Pressing Enter in the ConsoleWidget now works as expected.
r2896 super(FrontendWidget, self)._insert_continuation_prompt(cursor)
epatters
Removed use of hard tabs in FrontendWidget and implemented "smart" backspace.
r3022 cursor.insertText(' ' * self._input_splitter.indent_spaces)
epatters
Fixed bug with ConsoleWidget smart paste.
r2787
#---------------------------------------------------------------------------
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 # 'BaseFrontendMixin' abstract interface
epatters
Initial checkin of Qt frontend code.
r2602 #---------------------------------------------------------------------------
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def _handle_complete_reply(self, rep):
""" Handle replies for tab completion.
epatters
Initial checkin of Qt frontend code.
r2602 """
MinRK
add debug messages to qt handlers
r4793 self.log.debug("complete: %s", rep.get('content', ''))
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 cursor = self._get_cursor()
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934 info = self._request_info.get('complete')
if info and info.id == rep['parent_header']['msg_id'] and \
info.pos == cursor.position():
epatters
Fixed regressions in the pure Python kernel.
r2867 text = '.'.join(self._get_context())
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 cursor.movePosition(QtGui.QTextCursor.Left, n=len(text))
self._complete_with_items(cursor, rep['content']['matches'])
epatters
Initial checkin of Qt frontend code.
r2602
Matthias BUSSONNIER
fix @fperez suggestions
r5395 def _silent_exec_callback(self, expr, callback):
"""Silently execute `expr` in the kernel and call `callback` with reply
Matthias BUSSONNIER
Generate "All magics..." menu live...
r5392
Matthias BUSSONNIER
fix docstrig, replace eval by regExp...
r5396 the `expr` is evaluated silently in the kernel (without) output in
the frontend. Call `callback` with the
`repr <http://docs.python.org/library/functions.html#repr> `_ as first argument
Parameters
----------
expr : string
valid string to be executed by the kernel.
callback : function
Paul Ivanov
clean up of typos and awkward wording
r7589 function accepting one argument, as a string. The string will be
Matthias BUSSONNIER
fix docstrig, replace eval by regExp...
r5396 the `repr` of the result of evaluating `expr`
Matthias BUSSONNIER
Generate "All magics..." menu live...
r5392
Paul Ivanov
clean up of typos and awkward wording
r7589 The `callback` is called with the `repr()` of the result of `expr` as
first argument. To get the object, do `eval()` on the passed value.
Matthias BUSSONNIER
fix docstrig, replace eval by regExp...
r5396
See Also
--------
_handle_exec_callback : private method, deal with calling callback with reply
Matthias BUSSONNIER
Generate "All magics..." menu live...
r5392 """
Paul Ivanov
clean up of typos and awkward wording
r7589 # generate uuid, which would be used as an indication of whether or
# not the unique request originated from here (can use msg id ?)
Matthias BUSSONNIER
Generate "All magics..." menu live...
r5392 local_uuid = str(uuid.uuid1())
MinRK
expose shell channel methods at the client level
r10294 msg_id = self.kernel_client.execute('',
Matthias BUSSONNIER
fix @fperez suggestions
r5395 silent=True, user_expressions={ local_uuid:expr })
self._callback_dict[local_uuid] = callback
Matthias BUSSONNIER
qtconsole: fix race-cond, handle multiple exec...
r5506 self._request_info['execute'][msg_id] = self._ExecutionRequest(msg_id, 'silent_exec_callback')
Matthias BUSSONNIER
Generate "All magics..." menu live...
r5392
Matthias BUSSONNIER
fix @fperez suggestions
r5395 def _handle_exec_callback(self, msg):
Paul Ivanov
clean up of typos and awkward wording
r7589 """Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback``
Matthias BUSSONNIER
fix @fperez suggestions
r5395
Matthias BUSSONNIER
fix docstrig, replace eval by regExp...
r5396 Parameters
----------
msg : raw message send by the kernel containing an `user_expressions`
Matthias BUSSONNIER
fix @fperez suggestions
r5395 and having a 'silent_exec_callback' kind.
Matthias BUSSONNIER
Generate "All magics..." menu live...
r5392
Matthias BUSSONNIER
fix docstrig, replace eval by regExp...
r5396 Notes
-----
Paul Ivanov
clean up of typos and awkward wording
r7589 This function will look for a `callback` associated with the
Matthias BUSSONNIER
fix @fperez suggestions
r5395 corresponding message id. Association has been made by
Matthias BUSSONNIER
fix docstrig, replace eval by regExp...
r5396 `_silent_exec_callback`. `callback` is then called with the `repr()`
Matthias BUSSONNIER
fix @fperez suggestions
r5395 of the value of corresponding `user_expressions` as argument.
`callback` is then removed from the known list so that any message
coming again with the same id won't trigger it.
Matthias BUSSONNIER
fix docstrig, replace eval by regExp...
r5396
Matthias BUSSONNIER
Generate "All magics..." menu live...
r5392 """
Matthias BUSSONNIER
fix @fperez suggestions
r5395
Matthias BUSSONNIER
qtconsole --pure, avoid 'user_expression'...
r5562 user_exp = msg['content'].get('user_expressions')
if not user_exp:
return
Matthias BUSSONNIER
fix docstrig, replace eval by regExp...
r5396 for expression in user_exp:
if expression in self._callback_dict:
self._callback_dict.pop(expression)(user_exp[expression])
Matthias BUSSONNIER
Generate "All magics..." menu live...
r5392
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def _handle_execute_reply(self, msg):
""" Handles replies for code execution.
epatters
Initial checkin of Qt kernel manager. Began refactor of FrontendWidget.
r2609 """
MinRK
add debug messages to qt handlers
r4793 self.log.debug("execute: %s", msg.get('content', ''))
Matthias BUSSONNIER
qtconsole: fix race-cond, handle multiple exec...
r5506 msg_id = msg['parent_header']['msg_id']
Matthias BUSSONNIER
fix to minrk suggestion
r5520 info = self._request_info['execute'].get(msg_id)
MinRK
various small fixes in qtconsole...
r5188 # unset reading flag, because if execute finished, raw_input can't
# still be pending.
self._reading = False
Matthias BUSSONNIER
qtconsole: fix race-cond, handle multiple exec...
r5506 if info and info.kind == 'user' and not self._hidden:
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 # Make sure that all output from the SUB channel has been processed
# before writing a new prompt.
MinRK
update Qt to use KernelClient
r10288 self.kernel_client.iopub_channel.flush()
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770
epatters
Fixed ANSI compliance issue in AnsiCodeProcessor....
r3000 # Reset the ANSI style information to prevent bad text in stdout
# from messing up our colors. We're not a true terminal so we're
# allowed to do this.
if self.ansi_codes:
self._ansi_processor.reset_sgr()
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 content = msg['content']
status = content['status']
if status == 'ok':
self._process_execute_ok(msg)
elif status == 'error':
self._process_execute_error(msg)
MinRK
various small fixes in qtconsole...
r5188 elif status == 'aborted':
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 self._process_execute_abort(msg)
epatters
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
r2797 self._show_interpreter_prompt_for_reply(msg)
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 self.executed.emit(msg)
Matthias BUSSONNIER
fix to minrk suggestion
r5520 self._request_info['execute'].pop(msg_id)
Matthias BUSSONNIER
qtconsole: fix race-cond, handle multiple exec...
r5506 elif info and info.kind == 'silent_exec_callback' and not self._hidden:
Matthias BUSSONNIER
Generate "All magics..." menu live...
r5392 self._handle_exec_callback(msg)
Matthias BUSSONNIER
fix forgot one pop in execute callback
r5521 self._request_info['execute'].pop(msg_id)
Matthias BUSSONNIER
Improve 'save history' menu (%save)...
r5030 else:
super(FrontendWidget, self)._handle_execute_reply(msg)
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770
def _handle_input_request(self, msg):
""" Handle requests for raw_input.
"""
MinRK
add debug messages to qt handlers
r4793 self.log.debug("input: %s", msg.get('content', ''))
epatters
Minor cleanup and bug fix.
r2771 if self._hidden:
raise RuntimeError('Request for raw input during hidden execution.')
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 # Make sure that all output from the SUB channel has been processed
# before entering readline mode.
MinRK
update Qt to use KernelClient
r10288 self.kernel_client.iopub_channel.flush()
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770
def callback(line):
MinRK
update Qt to use KernelClient
r10288 self.kernel_client.stdin_channel.input(line)
MinRK
various small fixes in qtconsole...
r5188 if self._reading:
self.log.debug("Got second input request, assuming first was interrupted.")
self._reading = False
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 self._readline(msg['content']['prompt'], callback=callback)
epatters
Initial checkin of Qt kernel manager. Began refactor of FrontendWidget.
r2609
MinRK
qtconsole autorestarts
r10312 def _kernel_restarted_message(self, died=True):
msg = "Kernel died, restarting" if died else "Kernel restarting"
self._append_html("<br>%s<hr><br>" % msg,
before_prompt=False
)
epatters
* Improved frontend-side kernel restart support....
r2913 def _handle_kernel_died(self, since_last_heartbeat):
MinRK
qtconsole autorestarts
r10312 """Handle the kernel's death (if we do not own the kernel).
epatters
* Improved frontend-side kernel restart support....
r2913 """
MinRK
qtconsole autorestarts
r10312 self.log.warn("kernel died: %s", since_last_heartbeat)
epatters
* Improved frontend-side kernel restart support....
r2913 if self.custom_restart:
self.custom_restart_kernel_died.emit(since_last_heartbeat)
else:
MinRK
qtconsole autorestarts
r10312 self._kernel_restarted_message(died=True)
self.reset()
def _handle_kernel_restarted(self, died=True):
"""Notice that the autorestarter restarted the kernel.
There's nothing to do but show a message.
"""
self.log.warn("kernel restarted")
self._kernel_restarted_message(died=died)
self.reset()
epatters
* Improved frontend-side kernel restart support....
r2913
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def _handle_object_info_reply(self, rep):
""" Handle replies for call tips.
epatters
Initial checkin of Qt kernel manager. Began refactor of FrontendWidget.
r2609 """
MinRK
add debug messages to qt handlers
r4793 self.log.debug("oinfo: %s", rep.get('content', ''))
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 cursor = self._get_cursor()
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934 info = self._request_info.get('call_tip')
if info and info.id == rep['parent_header']['msg_id'] and \
info.pos == cursor.position():
Fernando Perez
Add function signature info to calltips....
r3051 # Get the information for a call tip. For now we format the call
# line as string, later we can pass False to format_call and
# syntax-highlight it ourselves for nicer formatting in the
# calltip.
MinRK
use dict.get(key) instead of dict[key] for pure kernel...
r3934 content = rep['content']
# if this is from pykernel, 'docstring' will be the only key
if content.get('ismagic', False):
David Warde-Farley
fix issue 337 with incorrect calltips being generated for magics
r3685 # Don't generate a call-tip for magics. Ideally, we should
# generate a tooltip, but not on ( like we do for actual
# callables.
call_info, doc = None, None
else:
MinRK
use dict.get(key) instead of dict[key] for pure kernel...
r3934 call_info, doc = call_tip(content, format_call=True)
Fernando Perez
Add function signature info to calltips....
r3051 if call_info or doc:
self._call_tip_widget.show_call_info(call_info, doc)
epatters
* Added 'started_listening' and 'stopped_listening' signals to QtKernelManager. The FrontendWidget listens for these signals....
r2643
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def _handle_pyout(self, msg):
""" Handle display hook output.
"""
MinRK
add debug messages to qt handlers
r4793 self.log.debug("pyout: %s", msg.get('content', ''))
epatters
* The Qt console frontend now ignores cross chatter from other frontends....
r2824 if not self._hidden and self._is_from_this_session(msg):
epatters
First cut at safe appending in the Qt console.
r4056 text = msg['content']['data']
self._append_plain_text(text + '\n', before_prompt=True)
epatters
Initial checkin of Qt kernel manager. Began refactor of FrontendWidget.
r2609
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def _handle_stream(self, msg):
""" Handle stdout, stderr, and stdin.
"""
MinRK
add debug messages to qt handlers
r4793 self.log.debug("stream: %s", msg.get('content', ''))
epatters
* The Qt console frontend now ignores cross chatter from other frontends....
r2824 if not self._hidden and self._is_from_this_session(msg):
Evan Patterson
FrontendWidget now treats tab characters in the std* streams like most consoles....
r2997 # Most consoles treat tabs as being 8 space characters. Convert tabs
# to spaces so that output looks as expected regardless of this
# widget's tab width.
text = msg['content']['data'].expandtabs(8)
Bernardo B. Marques
remove all trailling spaces
r4872
epatters
First cut at safe appending in the Qt console.
r4056 self._append_plain_text(text, before_prompt=True)
epatters
* The Qt console frontend now ignores cross chatter from other frontends....
r2824 self._control.moveCursor(QtGui.QTextCursor.End)
Brian Granger
Implementing kernel status messages.
r3035
MinRK
added shutdown notification handling to ipythonqt
r3090 def _handle_shutdown_reply(self, msg):
""" Handle shutdown signal, only if from other console.
"""
MinRK
qtconsole autorestarts
r10312 self.log.warn("shutdown: %s", msg.get('content', ''))
restart = msg.get('content', {}).get('restart', False)
MinRK
added shutdown notification handling to ipythonqt
r3090 if not self._hidden and not self._is_from_this_session(msg):
MinRK
qtconsole autorestarts
r10312 # got shutdown reply, request came from session other than ours
if restart:
# someone restarted the kernel, handle it
self._handle_kernel_restarted(died=False)
else:
# kernel was shutdown permanently
# this triggers exit_requested if the kernel was local,
# and a dialog if the kernel was remote,
# so we don't suddenly clear the qtconsole without asking.
if self._local_kernel:
Matthias BUSSONNIER
Handle all the case of tab closing and clean the code
r5038 self.exit_requested.emit(self)
MinRK
tweaked close dialog and added prompts to prevent silent remote close
r3129 else:
MinRK
qtconsole autorestarts
r10312 title = self.window().windowTitle()
MinRK
tweaked close dialog and added prompts to prevent silent remote close
r3129 reply = QtGui.QMessageBox.question(self, title,
epatters
Refactored ConsoleWidget's HTML exportaton code + other minor code cleanup.
r3361 "Kernel has been shutdown permanently. "
"Close the Console?",
MinRK
tweaked close dialog and added prompts to prevent silent remote close
r3129 QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)
if reply == QtGui.QMessageBox.Yes:
Matthias BUSSONNIER
tab management new/existing kernel....
r5035 self.exit_requested.emit(self)
MinRK
added shutdown notification handling to ipythonqt
r3090
MinRK
add handle_status to qtconsole...
r10339 def _handle_status(self, msg):
"""Handle status message"""
# This is where a busy/idle indicator would be triggered,
# when we make one.
state = msg['content'].get('execution_state', '')
if state == 'starting':
# kernel started while we were running
if self._executing:
self._handle_kernel_restarted(died=True)
elif state == 'idle':
pass
elif state == 'busy':
pass
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def _started_channels(self):
Bernardo B. Marques
remove all trailling spaces
r4872 """ Called when the KernelManager channels have started listening or
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 when the frontend is assigned an already listening KernelManager.
"""
Paul Ivanov
rename reset parameter to 'clear' for clarity
r6828 self.reset(clear=True)
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770
#---------------------------------------------------------------------------
epatters
* Added "smart copy" support to FrontendWidget and ConsoleWidget. Tabs are expanded and prompts are stripped....
r2971 # 'FrontendWidget' public interface
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 #---------------------------------------------------------------------------
epatters
* Added Cut support to ConsoleWidget....
r2990 def copy_raw(self):
""" Copy the currently selected text to the clipboard without attempting
to remove prompts or otherwise alter the text.
"""
self._control.copy()
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def execute_file(self, path, hidden=False):
""" Attempts to execute file with 'path'. If 'hidden', no output is
shown.
"""
Evan Patterson
Fix Windows-specific bug in path handling for Qt console.
r3797 self.execute('execfile(%r)' % path, hidden=hidden)
epatters
Initial checkin of Qt kernel manager. Began refactor of FrontendWidget.
r2609
epatters
* Improved frontend-side kernel restart support....
r2913 def interrupt_kernel(self):
""" Attempts to interrupt the running kernel.
MinRK
various small fixes in qtconsole...
r5188
Also unsets _reading flag, to avoid runtime errors
if raw_input is called again.
epatters
* Improved frontend-side kernel restart support....
r2913 """
if self.custom_interrupt:
MinRK
various small fixes in qtconsole...
r5188 self._reading = False
epatters
* Improved frontend-side kernel restart support....
r2913 self.custom_interrupt_requested.emit()
MinRK
update Qt to use KernelClient
r10288 elif self.kernel_manager:
MinRK
various small fixes in qtconsole...
r5188 self._reading = False
epatters
Implemented kernel interrupts for Windows.
r3027 self.kernel_manager.interrupt_kernel()
epatters
* Improved frontend-side kernel restart support....
r2913 else:
MinRK
qtconsole autorestarts
r10312 self._append_plain_text('Cannot interrupt a kernel I did not start.\n')
epatters
* Improved frontend-side kernel restart support....
r2913
Paul Ivanov
rename reset parameter to 'clear' for clarity
r6828 def reset(self, clear=False):
MinRK
qtconsole autorestarts
r10312 """ Resets the widget to its initial state if ``clear`` parameter
is True, otherwise
Paul Ivanov
move clear_on_kernel_restart back inside reset()...
r6824 prints a visual indication of the fact that the kernel restarted, but
does not clear the traces from previous usage of the kernel before it
Paul Ivanov
rename reset parameter to 'clear' for clarity
r6828 was restarted. With ``clear=True``, it is similar to ``%clear``, but
Paul Ivanov
move clear_on_kernel_restart back inside reset()...
r6824 also re-writes the banner and aborts execution if necessary.
Bernardo B. Marques
remove all trailling spaces
r4872 """
epatters
Cleaned up frontend-level kernel restart logic.
r3033 if self._executing:
self._executing = False
Matthias BUSSONNIER
qtconsole: fix race-cond, handle multiple exec...
r5506 self._request_info['execute'] = {}
epatters
Cleaned up frontend-level kernel restart logic.
r3033 self._reading = False
self._highlighter.highlighting_on = False
MinRK
qtconsole autorestarts
r10312 if clear:
Paul Ivanov
move clear_on_kernel_restart back inside reset()...
r6824 self._control.clear()
self._append_plain_text(self.banner)
# update output marker for stdout/stderr, so that startup
# messages appear after banner:
self._append_before_prompt_pos = self._get_cursor().position()
self._show_interpreter_prompt()
Paul Ivanov
add qt config option to clear_on_kernel_restart...
r6684
Fernando Perez
Rename 'instant_death' to 'now' as per code review.
r3030 def restart_kernel(self, message, now=False):
epatters
* Improved frontend-side kernel restart support....
r2913 """ Attempts to restart the running kernel.
"""
epatters
Cleaned up frontend-level kernel restart logic.
r3033 # FIXME: now should be configurable via a checkbox in the dialog. Right
# now at least the heartbeat path sets it to True and the manual restart
# to False. But those should just be the pre-selected states of a
# checkbox that the user could override if so desired. But I don't know
# enough Qt to go implementing the checkbox now.
if self.custom_restart:
self.custom_restart_requested.emit()
MinRK
qtconsole autorestarts
r10312 return
epatters
Cleaned up frontend-level kernel restart logic.
r3033
MinRK
qtconsole autorestarts
r10312 if self.kernel_manager:
epatters
Cleaned up frontend-level kernel restart logic.
r3033 # Pause the heart beat channel to prevent further warnings.
MinRK
update Qt to use KernelClient
r10288 self.kernel_client.hb_channel.pause()
epatters
Cleaned up frontend-level kernel restart logic.
r3033
# Prompt the user to restart the kernel. Un-pause the heartbeat if
# they decline. (If they accept, the heartbeat will be un-paused
# automatically when the kernel is restarted.)
Paul Ivanov
added confirm_restart configuration option...
r7590 if self.confirm_restart:
buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No
result = QtGui.QMessageBox.question(self, 'Restart kernel?',
message, buttons)
do_restart = result == QtGui.QMessageBox.Yes
else:
# confirm_restart is False, so we don't need to ask user
# anything, just do the restart
do_restart = True
if do_restart:
epatters
Cleaned up frontend-level kernel restart logic.
r3033 try:
self.kernel_manager.restart_kernel(now=now)
MinRK
qtconsole autorestarts
r10312 except RuntimeError as e:
self._append_plain_text(
'Error restarting kernel: %s\n' % e,
before_prompt=True
)
epatters
Cleaned up frontend-level kernel restart logic.
r3033 else:
MinRK
qtconsole autorestarts
r10312 self._append_html("<br>Restarting kernel...\n<hr><br>",
before_prompt=True,
)
epatters
* Improved frontend-side kernel restart support....
r2913 else:
MinRK
update Qt to use KernelClient
r10288 self.kernel_client.hb_channel.unpause()
epatters
Cleaned up frontend-level kernel restart logic.
r3033
else:
MinRK
qtconsole autorestarts
r10312 self._append_plain_text(
'Cannot restart a Kernel I did not start\n',
before_prompt=True
)
epatters
* Improved frontend-side kernel restart support....
r2913
epatters
Initial checkin of Qt frontend code.
r2602 #---------------------------------------------------------------------------
# 'FrontendWidget' protected interface
#---------------------------------------------------------------------------
def _call_tip(self):
""" Shows a call tip, if appropriate, at the current cursor location.
"""
# Decide if it makes sense to show a call tip
MinRK
make calltips configurable in qtconsole...
r4569 if not self.enable_calltips:
return False
epatters
Refactored ConsoleWidget to encapsulate, rather than inherit from, QPlainTextEdit. This permits a QTextEdit to be substituted for a QPlainTextEdit if desired. It also makes it more clear what is the public interface of ConsoleWidget.
r2736 cursor = self._get_cursor()
epatters
Initial checkin of Qt frontend code.
r2602 cursor.movePosition(QtGui.QTextCursor.Left)
Evan Patterson
Paved the way for PySide support....
r3304 if cursor.document().characterAt(cursor.position()) != '(':
epatters
Initial checkin of Qt frontend code.
r2602 return False
context = self._get_context(cursor)
if not context:
return False
# Send the metadata request to the kernel
epatters
* Adding object_info_request support to prototype kernel....
r2612 name = '.'.join(context)
MinRK
expose shell channel methods at the client level
r10294 msg_id = self.kernel_client.object_info(name)
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934 pos = self._get_cursor().position()
self._request_info['call_tip'] = self._CallTipRequest(msg_id, pos)
epatters
Initial checkin of Qt frontend code.
r2602 return True
def _complete(self):
""" Performs completion at the current cursor location.
"""
epatters
Fixed regressions in the pure Python kernel.
r2867 context = self._get_context()
if context:
# Send the completion request to the kernel
MinRK
expose shell channel methods at the client level
r10294 msg_id = self.kernel_client.complete(
epatters
Fixed regressions in the pure Python kernel.
r2867 '.'.join(context), # text
self._get_input_buffer_cursor_line(), # line
self._get_input_buffer_cursor_column(), # cursor_pos
Bernardo B. Marques
remove all trailling spaces
r4872 self.input_buffer) # block
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934 pos = self._get_cursor().position()
info = self._CompletionRequest(msg_id, pos)
self._request_info['complete'] = info
epatters
Initial checkin of Qt frontend code.
r2602
def _get_context(self, cursor=None):
epatters
* The ConsoleWidget now has full undo/redo support. Previously, the undo/redo history was cleared after every continuation prompt. This is no longer the case....
r2864 """ Gets the context for the specified cursor (or the current cursor
if none is specified).
epatters
Initial checkin of Qt frontend code.
r2602 """
if cursor is None:
epatters
Refactored ConsoleWidget to encapsulate, rather than inherit from, QPlainTextEdit. This permits a QTextEdit to be substituted for a QPlainTextEdit if desired. It also makes it more clear what is the public interface of ConsoleWidget.
r2736 cursor = self._get_cursor()
Bernardo B. Marques
remove all trailling spaces
r4872 cursor.movePosition(QtGui.QTextCursor.StartOfBlock,
epatters
Initial checkin of Qt frontend code.
r2602 QtGui.QTextCursor.KeepAnchor)
Evan Patterson
Paved the way for PySide support....
r3304 text = cursor.selection().toPlainText()
epatters
Initial checkin of Qt frontend code.
r2602 return self._completion_lexer.get_context(text)
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def _process_execute_abort(self, msg):
""" Process a reply for an aborted execution request.
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 """
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 self._append_plain_text("ERROR: execution aborted\n")
epatters
Initial checkin of Qt frontend code.
r2602
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def _process_execute_error(self, msg):
""" Process a reply for an execution request that resulted in an error.
epatters
Progress on raw_input.
r2705 """
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 content = msg['content']
Erik Tollerud
qtconsole with pure python kernel now properly catches the SystemExit exception, allowing python exit() function to work correctly
r3187 # If a SystemExit is passed along, this means exit() was called - also
# all the ipython %exit magic syntax of '-k' to be used to keep
# the kernel running
if content['ename']=='SystemExit':
keepkernel = content['evalue']=='-k' or content['evalue']=='True'
self._keep_kernel_on_exit = keepkernel
Matthias BUSSONNIER
tab management new/existing kernel....
r5035 self.exit_requested.emit(self)
Erik Tollerud
qtconsole with pure python kernel now properly catches the SystemExit exception, allowing python exit() function to work correctly
r3187 else:
traceback = ''.join(content['traceback'])
self._append_plain_text(traceback)
epatters
Progress on raw_input.
r2705
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def _process_execute_ok(self, msg):
Paul Ivanov
add qt config option to clear_on_kernel_restart...
r6684 """ Process a reply for a successful execution request.
epatters
Progress on raw_input.
r2705 """
epatters
* Refactored payload handling mechanism....
r2835 payload = msg['content']['payload']
for item in payload:
if not self._process_execute_payload(item):
epatters
* ConsoleWidget no longer stores contiguous identical lines...
r2969 warning = 'Warning: received unknown payload of type %s'
epatters
Form feeds are now properly supported by ConsoleWidget.
r3006 print(warning % repr(item['source']))
epatters
* Refactored payload handling mechanism....
r2835
def _process_execute_payload(self, item):
""" Process a single payload item from the list of payload items in an
execution reply. Returns whether the payload was handled.
"""
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 # The basic FrontendWidget doesn't handle payloads, as they are a
# mechanism for going beyond the standard Python interpreter model.
epatters
* Refactored payload handling mechanism....
r2835 return False
epatters
Progress on raw_input.
r2705
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 def _show_interpreter_prompt(self):
""" Shows a prompt for the interpreter.
"""
self._show_prompt('>>> ')
epatters
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
r2797 def _show_interpreter_prompt_for_reply(self, msg):
""" Shows a prompt for the interpreter given an 'execute_reply' message.
"""
self._show_interpreter_prompt()
epatters
* Moved KernelManager attribute management code in FrontendWidget into a mixin class usable in any Qt frontend. Registering handlers for message types is now trivial....
r2770 #------ Signal handlers ----------------------------------------------------
epatters
Initial checkin of Qt frontend code.
r2602 def _document_contents_change(self, position, removed, added):
epatters
* CallTipWidget and CompletionWidget no longer need to be fed key presses. This means that can be attached to any Q[Plain]TextEdit with zero hassle....
r2744 """ Called whenever the document's content changes. Display a call tip
epatters
Initial checkin of Qt frontend code.
r2602 if appropriate.
"""
# Calculate where the cursor should be *after* the change:
position += added
epatters
Refactored ConsoleWidget to encapsulate, rather than inherit from, QPlainTextEdit. This permits a QTextEdit to be substituted for a QPlainTextEdit if desired. It also makes it more clear what is the public interface of ConsoleWidget.
r2736 document = self._control.document()
if position == self._get_cursor().position():
epatters
Initial checkin of Qt frontend code.
r2602 self._call_tip()
epatters
ENH: Allow FrontendWidget banner to be changed without subclassing.
r4689
#------ Trait default initializers -----------------------------------------
def _banner_default(self):
""" Returns the standard Python banner.
"""
banner = 'Python %s on %s\nType "help", "copyright", "credits" or ' \
'"license" for more information.'
return banner % (sys.version, sys.platform)