ipython_widget.py
562 lines
| 23.1 KiB
| text/x-python
|
PythonLexer
epatters
|
r2850 | """ A FrontendWidget that emulates the interface of the console IPython and | ||
supports the additional functionality provided by the IPython kernel. | ||||
""" | ||||
epatters
|
r2916 | #----------------------------------------------------------------------------- | ||
# Imports | ||||
#----------------------------------------------------------------------------- | ||||
epatters
|
r2793 | # Standard library imports | ||
epatters
|
r2883 | from collections import namedtuple | ||
Evan Patterson
|
r3797 | import os.path | ||
epatters
|
r2920 | import re | ||
epatters
|
r2793 | from subprocess import Popen | ||
Evan Patterson
|
r3797 | import sys | ||
MinRK
|
r4701 | import time | ||
Brian Granger
|
r3036 | from textwrap import dedent | ||
epatters
|
r2793 | |||
epatters
|
r2630 | # System library imports | ||
Evan Patterson
|
r3304 | from IPython.external.qt import QtCore, QtGui | ||
epatters
|
r2630 | |||
# Local imports | ||||
epatters
|
r2971 | from IPython.core.inputsplitter import IPythonInputSplitter, \ | ||
transform_ipy_prompt | ||||
Thomas Kluyver
|
r4046 | from IPython.utils.traitlets import Bool, Unicode | ||
epatters
|
r2627 | from frontend_widget import FrontendWidget | ||
MinRK
|
r3971 | import styles | ||
epatters
|
r2627 | |||
epatters
|
r2916 | #----------------------------------------------------------------------------- | ||
# Constants | ||||
#----------------------------------------------------------------------------- | ||||
Fernando Perez
|
r2926 | # Default strings to build and display input and output prompts (and separators | ||
# in between) | ||||
epatters
|
r2884 | default_in_prompt = 'In [<span class="in-prompt-number">%i</span>]: ' | ||
default_out_prompt = 'Out[<span class="out-prompt-number">%i</span>]: ' | ||||
Fernando Perez
|
r2926 | default_input_sep = '\n' | ||
default_output_sep = '' | ||||
default_output_sep2 = '' | ||||
epatters
|
r2884 | |||
epatters
|
r3041 | # Base path for most payload sources. | ||
zmq_shell_source = 'IPython.zmq.zmqshell.ZMQInteractiveShell' | ||||
MinRK
|
r3977 | if sys.platform.startswith('win'): | ||
default_editor = 'notepad' | ||||
else: | ||||
default_editor = '' | ||||
epatters
|
r2916 | #----------------------------------------------------------------------------- | ||
# IPythonWidget class | ||||
#----------------------------------------------------------------------------- | ||||
epatters
|
r2627 | |||
class IPythonWidget(FrontendWidget): | ||||
""" A FrontendWidget for an IPython kernel. | ||||
""" | ||||
epatters
|
r2884 | # If set, the 'custom_edit_requested(str, int)' signal will be emitted when | ||
# an editor is needed for a file. This overrides 'editor' and 'editor_line' | ||||
# settings. | ||||
custom_edit = Bool(False) | ||||
Evan Patterson
|
r3304 | custom_edit_requested = QtCore.Signal(object, object) | ||
epatters
|
r2793 | |||
MinRK
|
r3977 | editor = Unicode(default_editor, config=True, | ||
MinRK
|
r3971 | help=""" | ||
A command for invoking a system text editor. If the string contains a | ||||
epatters
|
r4056 | {filename} format specifier, it will be used. Otherwise, the filename | ||
will be appended to the end the command. | ||||
MinRK
|
r3971 | """) | ||
editor_line = Unicode(config=True, | ||||
help=""" | ||||
The editor command to use when a specific line number is requested. The | ||||
string should contain two format specifiers: {line} and {filename}. If | ||||
epatters
|
r4056 | this parameter is not specified, the line number option to the %edit | ||
magic will be ignored. | ||||
MinRK
|
r3971 | """) | ||
style_sheet = Unicode(config=True, | ||||
help=""" | ||||
A CSS stylesheet. The stylesheet can contain classes for: | ||||
1. Qt: QPlainTextEdit, QFrame, QWidget, etc | ||||
2. Pygments: .c, .k, .o, etc. (see PygmentsHighlighter) | ||||
3. IPython: .error, .in-prompt, .out-prompt, etc | ||||
""") | ||||
Bernardo B. Marques
|
r4872 | |||
Thomas Kluyver
|
r4046 | syntax_style = Unicode(config=True, | ||
MinRK
|
r3971 | help=""" | ||
epatters
|
r4056 | If not empty, use this Pygments style for syntax highlighting. | ||
Otherwise, the style sheet is queried for Pygments style | ||||
information. | ||||
MinRK
|
r3971 | """) | ||
epatters
|
r2733 | |||
epatters
|
r2884 | # Prompts. | ||
Thomas Kluyver
|
r4046 | in_prompt = Unicode(default_in_prompt, config=True) | ||
out_prompt = Unicode(default_out_prompt, config=True) | ||||
input_sep = Unicode(default_input_sep, config=True) | ||||
output_sep = Unicode(default_output_sep, config=True) | ||||
output_sep2 = Unicode(default_output_sep2, config=True) | ||||
epatters
|
r2883 | |||
epatters
|
r2835 | # FrontendWidget protected class variables. | ||
Fernando Perez
|
r2861 | _input_splitter_class = IPythonInputSplitter | ||
epatters
|
r2800 | |||
epatters
|
r2835 | # IPythonWidget protected class variables. | ||
epatters
|
r2884 | _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number']) | ||
epatters
|
r3041 | _payload_source_edit = zmq_shell_source + '.edit_magic' | ||
_payload_source_exit = zmq_shell_source + '.ask_exit' | ||||
Thomas Kluyver
|
r3864 | _payload_source_next_input = zmq_shell_source + '.set_next_input' | ||
epatters
|
r2835 | _payload_source_page = 'IPython.zmq.page.page' | ||
MinRK
|
r4701 | _retrying_history_request = False | ||
epatters
|
r2835 | |||
epatters
|
r2627 | #--------------------------------------------------------------------------- | ||
epatters
|
r2736 | # 'object' interface | ||
epatters
|
r2627 | #--------------------------------------------------------------------------- | ||
Bernardo B. Marques
|
r4872 | |||
epatters
|
r2736 | def __init__(self, *args, **kw): | ||
super(IPythonWidget, self).__init__(*args, **kw) | ||||
epatters
|
r2627 | |||
epatters
|
r2789 | # IPythonWidget protected variables. | ||
Bernardo B. Marques
|
r4872 | self._payload_handlers = { | ||
Fernando Perez
|
r2950 | self._payload_source_edit : self._handle_payload_edit, | ||
self._payload_source_exit : self._handle_payload_exit, | ||||
Brian Granger
|
r3036 | self._payload_source_page : self._handle_payload_page, | ||
Thomas Kluyver
|
r3864 | self._payload_source_next_input : self._handle_payload_next_input } | ||
epatters
|
r2961 | self._previous_prompt_obj = None | ||
Erik Tollerud
|
r3183 | self._keep_kernel_on_exit = None | ||
epatters
|
r2715 | |||
epatters
|
r2884 | # Initialize widget styling. | ||
epatters
|
r2916 | if self.style_sheet: | ||
self._style_sheet_changed() | ||||
self._syntax_style_changed() | ||||
else: | ||||
self.set_default_style() | ||||
epatters
|
r2688 | |||
#--------------------------------------------------------------------------- | ||||
epatters
|
r2770 | # 'BaseFrontendMixin' abstract interface | ||
#--------------------------------------------------------------------------- | ||||
epatters
|
r2867 | def _handle_complete_reply(self, rep): | ||
""" Reimplemented to support IPython's improved completion machinery. | ||||
""" | ||||
MinRK
|
r4793 | self.log.debug("complete: %s", rep.get('content', '')) | ||
epatters
|
r2867 | cursor = self._get_cursor() | ||
epatters
|
r2934 | info = self._request_info.get('complete') | ||
if info and info.id == rep['parent_header']['msg_id'] and \ | ||||
info.pos == cursor.position(): | ||||
epatters
|
r2920 | matches = rep['content']['matches'] | ||
epatters
|
r2867 | text = rep['content']['matched_text'] | ||
epatters
|
r2939 | offset = len(text) | ||
# Clean up matches with period and path separators if the matched | ||||
# text has not been transformed. This is done by truncating all | ||||
# but the last component and then suitably decreasing the offset | ||||
# between the current cursor position and the start of completion. | ||||
if len(matches) > 1 and matches[0][:offset] == text: | ||||
Bernardo B. Marques
|
r4872 | parts = re.split(r'[./\\]', text) | ||
epatters
|
r2939 | sep_count = len(parts) - 1 | ||
if sep_count: | ||||
chop_length = sum(map(len, parts[:sep_count])) + sep_count | ||||
matches = [ match[chop_length:] for match in matches ] | ||||
offset -= chop_length | ||||
epatters
|
r2920 | |||
# Move the cursor to the start of the match and complete. | ||||
epatters
|
r2939 | cursor.movePosition(QtGui.QTextCursor.Left, n=offset) | ||
epatters
|
r2920 | self._complete_with_items(cursor, matches) | ||
epatters
|
r2867 | |||
epatters
|
r2934 | def _handle_execute_reply(self, msg): | ||
""" Reimplemented to support prompt requests. | ||||
""" | ||||
info = self._request_info.get('execute') | ||||
if info and info.id == msg['parent_header']['msg_id']: | ||||
if info.kind == 'prompt': | ||||
number = msg['content']['execution_count'] + 1 | ||||
self._show_interpreter_prompt(number) | ||||
else: | ||||
super(IPythonWidget, self)._handle_execute_reply(msg) | ||||
Thomas Kluyver
|
r3820 | def _handle_history_reply(self, msg): | ||
Thomas Kluyver
|
r3397 | """ Implemented to handle history tail replies, which are only supported | ||
by the IPython kernel. | ||||
epatters
|
r2844 | """ | ||
MinRK
|
r4793 | self.log.debug("history: %s", msg.get('content', '')) | ||
MinRK
|
r4700 | content = msg['content'] | ||
if 'history' not in content: | ||||
self.log.error("History request failed: %r"%content) | ||||
MinRK
|
r4701 | if content.get('status', '') == 'aborted' and \ | ||
not self._retrying_history_request: | ||||
# a *different* action caused this request to be aborted, so | ||||
# we should try again. | ||||
self.log.error("Retrying aborted history request") | ||||
# prevent multiple retries of aborted requests: | ||||
self._retrying_history_request = True | ||||
# wait out the kernel's queue flush, which is currently timed at 0.1s | ||||
time.sleep(0.25) | ||||
self.kernel_manager.shell_channel.history(hist_access_type='tail',n=1000) | ||||
else: | ||||
self._retrying_history_request = False | ||||
MinRK
|
r4700 | return | ||
MinRK
|
r4701 | # reset retry flag | ||
self._retrying_history_request = False | ||||
MinRK
|
r4700 | history_items = content['history'] | ||
Thomas Kluyver
|
r5310 | items = [] | ||
last_cell = u"" | ||||
for _, _, cell in history_items: | ||||
cell = cell.rstrip() | ||||
if cell != last_cell: | ||||
items.append(cell) | ||||
last_cell = cell | ||||
epatters
|
r2844 | self._set_history(items) | ||
epatters
|
r2806 | def _handle_pyout(self, msg): | ||
epatters
|
r2770 | """ Reimplemented for IPython-style "display hook". | ||
""" | ||||
MinRK
|
r4793 | self.log.debug("pyout: %s", msg.get('content', '')) | ||
epatters
|
r2824 | if not self._hidden and self._is_from_this_session(msg): | ||
content = msg['content'] | ||||
Fernando Perez
|
r2926 | prompt_number = content['execution_count'] | ||
Brian Granger
|
r3278 | data = content['data'] | ||
if data.has_key('text/html'): | ||||
epatters
|
r4056 | self._append_plain_text(self.output_sep, True) | ||
self._append_html(self._make_out_prompt(prompt_number), True) | ||||
Brian Granger
|
r3278 | html = data['text/html'] | ||
epatters
|
r4056 | self._append_plain_text('\n', True) | ||
self._append_html(html + self.output_sep2, True) | ||||
Brian Granger
|
r3278 | elif data.has_key('text/plain'): | ||
epatters
|
r4056 | self._append_plain_text(self.output_sep, True) | ||
self._append_html(self._make_out_prompt(prompt_number), True) | ||||
Brian Granger
|
r3278 | text = data['text/plain'] | ||
Thomas Kluyver
|
r3932 | # If the repr is multiline, make sure we start on a new line, | ||
# so that its lines are aligned. | ||||
if "\n" in text and not self.output_sep.endswith("\n"): | ||||
epatters
|
r4056 | self._append_plain_text('\n', True) | ||
self._append_plain_text(text + self.output_sep2, True) | ||||
epatters
|
r2770 | |||
Brian Granger
|
r3277 | def _handle_display_data(self, msg): | ||
""" The base handler for the ``display_data`` message. | ||||
""" | ||||
MinRK
|
r4793 | self.log.debug("display: %s", msg.get('content', '')) | ||
Bernardo B. Marques
|
r4872 | # For now, we don't display data from other frontends, but we | ||
Brian Granger
|
r3277 | # eventually will as this allows all frontends to monitor the display | ||
# data. But we need to figure out how to handle this in the GUI. | ||||
if not self._hidden and self._is_from_this_session(msg): | ||||
source = msg['content']['source'] | ||||
data = msg['content']['data'] | ||||
metadata = msg['content']['metadata'] | ||||
# In the regular IPythonWidget, we simply print the plain text | ||||
# representation. | ||||
Brian Granger
|
r3278 | if data.has_key('text/html'): | ||
html = data['text/html'] | ||||
epatters
|
r4057 | self._append_html(html, True) | ||
Brian Granger
|
r3278 | elif data.has_key('text/plain'): | ||
text = data['text/plain'] | ||||
epatters
|
r4057 | self._append_plain_text(text, True) | ||
Brian Granger
|
r3279 | # This newline seems to be needed for text and html output. | ||
epatters
|
r4057 | self._append_plain_text(u'\n', True) | ||
Brian Granger
|
r3277 | |||
epatters
|
r2844 | def _started_channels(self): | ||
""" Reimplemented to make a history request. | ||||
""" | ||||
super(IPythonWidget, self)._started_channels() | ||||
epatters
|
r4056 | self.kernel_manager.shell_channel.history(hist_access_type='tail', | ||
n=1000) | ||||
epatters
|
r2770 | #--------------------------------------------------------------------------- | ||
epatters
|
r2971 | # 'ConsoleWidget' public interface | ||
#--------------------------------------------------------------------------- | ||||
def copy(self): | ||||
""" Copy the currently selected text to the clipboard, removing prompts | ||||
if possible. | ||||
""" | ||||
Evan Patterson
|
r3304 | text = self._control.textCursor().selection().toPlainText() | ||
epatters
|
r2971 | if text: | ||
lines = map(transform_ipy_prompt, text.splitlines()) | ||||
text = '\n'.join(lines) | ||||
epatters
|
r3022 | QtGui.QApplication.clipboard().setText(text) | ||
epatters
|
r2971 | |||
#--------------------------------------------------------------------------- | ||||
# 'FrontendWidget' public interface | ||||
epatters
|
r2688 | #--------------------------------------------------------------------------- | ||
def execute_file(self, path, hidden=False): | ||||
""" Reimplemented to use the 'run' magic. | ||||
""" | ||||
Evan Patterson
|
r3797 | # Use forward slashes on Windows to avoid escaping each separator. | ||
if sys.platform == 'win32': | ||||
path = os.path.normpath(path).replace('\\', '/') | ||||
jdmarch
|
r4716 | # Perhaps we should not be using %run directly, but while we | ||
Jonathan March
|
r4717 | # are, it is necessary to quote filenames containing spaces or quotes. | ||
# Escaping quotes in filename in %run seems tricky and inconsistent, | ||||
# so not trying it at present. | ||||
if '"' in path: | ||||
if "'" in path: | ||||
jdmarch
|
r4716 | raise ValueError("Can't run filename containing both single " | ||
"and double quotes: %s" % path) | ||||
Jonathan March
|
r4717 | path = "'%s'" % path | ||
elif ' ' in path or "'" in path: | ||||
path = '"%s"' % path | ||||
jdmarch
|
r4716 | |||
Fernando Perez
|
r2838 | self.execute('%%run %s' % path, hidden=hidden) | ||
epatters
|
r2627 | |||
#--------------------------------------------------------------------------- | ||||
epatters
|
r2714 | # 'FrontendWidget' protected interface | ||
#--------------------------------------------------------------------------- | ||||
epatters
|
r2867 | def _complete(self): | ||
""" Reimplemented to support IPython's improved completion machinery. | ||||
""" | ||||
# We let the kernel split the input line, so we *always* send an empty | ||||
# text field. Readline-based frontends do get a real text field which | ||||
# they can use. | ||||
text = '' | ||||
Bernardo B. Marques
|
r4872 | |||
epatters
|
r2867 | # Send the completion request to the kernel | ||
MinRK
|
r3974 | msg_id = self.kernel_manager.shell_channel.complete( | ||
epatters
|
r2867 | text, # text | ||
self._get_input_buffer_cursor_line(), # line | ||||
self._get_input_buffer_cursor_column(), # cursor_pos | ||||
Bernardo B. Marques
|
r4872 | self.input_buffer) # block | ||
epatters
|
r2934 | pos = self._get_cursor().position() | ||
info = self._CompletionRequest(msg_id, pos) | ||||
self._request_info['complete'] = info | ||||
epatters
|
r2867 | |||
epatters
|
r2770 | def _process_execute_error(self, msg): | ||
""" Reimplemented for IPython-style traceback formatting. | ||||
""" | ||||
content = msg['content'] | ||||
epatters
|
r2841 | traceback = '\n'.join(content['traceback']) + '\n' | ||
if False: | ||||
# FIXME: For now, tracebacks come as plain text, so we can't use | ||||
Fernando Perez
|
r2838 | # the html renderer yet. Once we refactor ultratb to produce | ||
# properly styled tracebacks, this branch should be the default | ||||
traceback = traceback.replace(' ', ' ') | ||||
traceback = traceback.replace('\n', '<br/>') | ||||
ename = content['ename'] | ||||
ename_styled = '<span class="error">%s</span>' % ename | ||||
traceback = traceback.replace(ename, ename_styled) | ||||
self._append_html(traceback) | ||||
else: | ||||
# This is the fallback for now, using plain text with ansi escapes | ||||
Bernardo B. Marques
|
r4872 | self._append_plain_text(traceback) | ||
Fernando Perez
|
r2950 | |||
epatters
|
r2835 | def _process_execute_payload(self, item): | ||
epatters
|
r2961 | """ Reimplemented to dispatch payloads to handler methods. | ||
epatters
|
r2835 | """ | ||
Fernando Perez
|
r2950 | handler = self._payload_handlers.get(item['source']) | ||
if handler is None: | ||||
# We have no handler for this type of payload, simply ignore it | ||||
epatters
|
r2835 | return False | ||
Fernando Perez
|
r2950 | else: | ||
handler(item) | ||||
return True | ||||
Bernardo B. Marques
|
r4872 | |||
Fernando Perez
|
r2926 | def _show_interpreter_prompt(self, number=None): | ||
epatters
|
r2715 | """ Reimplemented for IPython-style prompts. | ||
""" | ||||
epatters
|
r2844 | # If a number was not specified, make a prompt number request. | ||
epatters
|
r2797 | if number is None: | ||
MinRK
|
r3974 | msg_id = self.kernel_manager.shell_channel.execute('', silent=True) | ||
epatters
|
r2934 | info = self._ExecutionRequest(msg_id, 'prompt') | ||
self._request_info['execute'] = info | ||||
return | ||||
epatters
|
r2797 | |||
epatters
|
r2806 | # Show a new prompt and save information about it so that it can be | ||
# updated later if the prompt number turns out to be wrong. | ||||
Fernando Perez
|
r2926 | self._prompt_sep = self.input_sep | ||
epatters
|
r2797 | self._show_prompt(self._make_in_prompt(number), html=True) | ||
epatters
|
r2806 | block = self._control.document().lastBlock() | ||
length = len(self._prompt) | ||||
epatters
|
r2883 | self._previous_prompt_obj = self._PromptBlock(block, length, number) | ||
epatters
|
r2715 | |||
# Update continuation prompt to reflect (possibly) new prompt length. | ||||
epatters
|
r2733 | self._set_continuation_prompt( | ||
self._make_continuation_prompt(self._prompt), html=True) | ||||
epatters
|
r2715 | |||
epatters
|
r2797 | def _show_interpreter_prompt_for_reply(self, msg): | ||
""" Reimplemented for IPython-style prompts. | ||||
""" | ||||
# Update the old prompt number if necessary. | ||||
content = msg['content'] | ||||
MinRK
|
r5188 | # abort replies do not have any keys: | ||
if content['status'] == 'aborted': | ||||
if self._previous_prompt_obj: | ||||
previous_prompt_number = self._previous_prompt_obj.number | ||||
else: | ||||
previous_prompt_number = 0 | ||||
else: | ||||
previous_prompt_number = content['execution_count'] | ||||
epatters
|
r2797 | if self._previous_prompt_obj and \ | ||
self._previous_prompt_obj.number != previous_prompt_number: | ||||
block = self._previous_prompt_obj.block | ||||
epatters
|
r2846 | |||
# Make sure the prompt block has not been erased. | ||||
epatters
|
r3307 | if block.isValid() and block.text(): | ||
epatters
|
r2800 | |||
# Remove the old prompt and insert a new prompt. | ||||
epatters
|
r2797 | cursor = QtGui.QTextCursor(block) | ||
cursor.movePosition(QtGui.QTextCursor.Right, | ||||
Bernardo B. Marques
|
r4872 | QtGui.QTextCursor.KeepAnchor, | ||
epatters
|
r2797 | self._previous_prompt_obj.length) | ||
prompt = self._make_in_prompt(previous_prompt_number) | ||||
epatters
|
r2800 | self._prompt = self._insert_html_fetching_plain_text( | ||
cursor, prompt) | ||||
epatters
|
r2825 | # When the HTML is inserted, Qt blows away the syntax | ||
# highlighting for the line, so we need to rehighlight it. | ||||
epatters
|
r2800 | self._highlighter.rehighlightBlock(cursor.block()) | ||
epatters
|
r2797 | self._previous_prompt_obj = None | ||
# Show a new prompt with the kernel's estimated prompt number. | ||||
epatters
|
r3041 | self._show_interpreter_prompt(previous_prompt_number + 1) | ||
epatters
|
r2797 | |||
epatters
|
r2714 | #--------------------------------------------------------------------------- | ||
epatters
|
r2916 | # 'IPythonWidget' interface | ||
#--------------------------------------------------------------------------- | ||||
MinRK
|
r3173 | def set_default_style(self, colors='lightbg'): | ||
epatters
|
r2916 | """ Sets the widget style to the class defaults. | ||
Parameters: | ||||
----------- | ||||
MinRK
|
r3173 | colors : str, optional (default lightbg) | ||
epatters
|
r2916 | Whether to use the default IPython light background or dark | ||
MinRK
|
r3171 | background or B&W style. | ||
epatters
|
r2916 | """ | ||
MinRK
|
r3173 | colors = colors.lower() | ||
if colors=='lightbg': | ||||
MinRK
|
r3971 | self.style_sheet = styles.default_light_style_sheet | ||
self.syntax_style = styles.default_light_syntax_style | ||||
MinRK
|
r3173 | elif colors=='linux': | ||
MinRK
|
r3971 | self.style_sheet = styles.default_dark_style_sheet | ||
self.syntax_style = styles.default_dark_syntax_style | ||||
MinRK
|
r3173 | elif colors=='nocolor': | ||
MinRK
|
r3971 | self.style_sheet = styles.default_bw_style_sheet | ||
self.syntax_style = styles.default_bw_syntax_style | ||||
MinRK
|
r3173 | else: | ||
raise KeyError("No such color scheme: %s"%colors) | ||||
epatters
|
r2916 | |||
#--------------------------------------------------------------------------- | ||||
epatters
|
r2733 | # 'IPythonWidget' protected interface | ||
#--------------------------------------------------------------------------- | ||||
epatters
|
r2850 | def _edit(self, filename, line=None): | ||
""" Opens a Python script for editing. | ||||
Parameters: | ||||
----------- | ||||
filename : str | ||||
A path to a local system file. | ||||
line : int, optional | ||||
A line of interest in the file. | ||||
""" | ||||
epatters
|
r2884 | if self.custom_edit: | ||
epatters
|
r2850 | self.custom_edit_requested.emit(filename, line) | ||
MinRK
|
r3977 | elif not self.editor: | ||
self._append_plain_text('No default editor available.\n' | ||||
epatters
|
r4056 | 'Specify a GUI text editor in the `IPythonWidget.editor` ' | ||
'configurable to enable the %edit magic') | ||||
epatters
|
r2850 | else: | ||
try: | ||||
filename = '"%s"' % filename | ||||
epatters
|
r2884 | if line and self.editor_line: | ||
command = self.editor_line.format(filename=filename, | ||||
line=line) | ||||
epatters
|
r2850 | else: | ||
try: | ||||
epatters
|
r2884 | command = self.editor.format() | ||
epatters
|
r2850 | except KeyError: | ||
epatters
|
r2884 | command = self.editor.format(filename=filename) | ||
epatters
|
r2850 | else: | ||
command += ' ' + filename | ||||
except KeyError: | ||||
self._append_plain_text('Invalid editor command.\n') | ||||
else: | ||||
try: | ||||
Popen(command, shell=True) | ||||
except OSError: | ||||
msg = 'Opening editor with command "%s" failed.\n' | ||||
self._append_plain_text(msg % command) | ||||
epatters
|
r2733 | def _make_in_prompt(self, number): | ||
""" Given a prompt number, returns an HTML In prompt. | ||||
""" | ||||
MinRK
|
r4478 | try: | ||
body = self.in_prompt % number | ||||
except TypeError: | ||||
# allow in_prompt to leave out number, e.g. '>>> ' | ||||
body = self.in_prompt | ||||
epatters
|
r2733 | return '<span class="in-prompt">%s</span>' % body | ||
def _make_continuation_prompt(self, prompt): | ||||
""" Given a plain text version of an In prompt, returns an HTML | ||||
continuation prompt. | ||||
""" | ||||
end_chars = '...: ' | ||||
space_count = len(prompt.lstrip('\n')) - len(end_chars) | ||||
body = ' ' * space_count + end_chars | ||||
return '<span class="in-prompt">%s</span>' % body | ||||
Bernardo B. Marques
|
r4872 | |||
epatters
|
r2733 | def _make_out_prompt(self, number): | ||
""" Given a prompt number, returns an HTML Out prompt. | ||||
""" | ||||
body = self.out_prompt % number | ||||
return '<span class="out-prompt">%s</span>' % body | ||||
epatters
|
r2884 | |||
epatters
|
r2961 | #------ Payload handlers -------------------------------------------------- | ||
# Payload handlers with a generic interface: each takes the opaque payload | ||||
# dict, unpacks it and calls the underlying functions with the necessary | ||||
# arguments. | ||||
def _handle_payload_edit(self, item): | ||||
self._edit(item['filename'], item['line_number']) | ||||
def _handle_payload_exit(self, item): | ||||
Erik Tollerud
|
r3183 | self._keep_kernel_on_exit = item['keepkernel'] | ||
Matthias BUSSONNIER
|
r5035 | self.exit_requested.emit(self) | ||
epatters
|
r2961 | |||
Thomas Kluyver
|
r3864 | def _handle_payload_next_input(self, item): | ||
Evan Patterson
|
r3931 | self.input_buffer = dedent(item['text'].rstrip()) | ||
epatters
|
r3041 | |||
epatters
|
r2961 | def _handle_payload_page(self, item): | ||
epatters
|
r3014 | # Since the plain text widget supports only a very small subset of HTML | ||
# and we have no control over the HTML source, we only page HTML | ||||
# payloads in the rich text widget. | ||||
if item['html'] and self.kind == 'rich': | ||||
self._page(item['html'], html=True) | ||||
else: | ||||
self._page(item['text'], html=False) | ||||
epatters
|
r2961 | |||
Brian Granger
|
r3277 | #------ Trait change handlers -------------------------------------------- | ||
epatters
|
r2884 | |||
def _style_sheet_changed(self): | ||||
""" Set the style sheets of the underlying widgets. | ||||
""" | ||||
self.setStyleSheet(self.style_sheet) | ||||
self._control.document().setDefaultStyleSheet(self.style_sheet) | ||||
if self._page_control: | ||||
self._page_control.document().setDefaultStyleSheet(self.style_sheet) | ||||
Evan Patterson
|
r3305 | bg_color = self._control.palette().window().color() | ||
epatters
|
r2884 | self._ansi_processor.set_background_color(bg_color) | ||
MinRK
|
r3971 | |||
epatters
|
r2884 | def _syntax_style_changed(self): | ||
""" Set the style for the syntax highlighter. | ||||
""" | ||||
MinRK
|
r3971 | if self._highlighter is None: | ||
# ignore premature calls | ||||
return | ||||
epatters
|
r2884 | if self.syntax_style: | ||
self._highlighter.set_style(self.syntax_style) | ||||
else: | ||||
self._highlighter.set_style_sheet(self.style_sheet) | ||||
Brian Granger
|
r3277 | |||
epatters
|
r4689 | #------ Trait default initializers ----------------------------------------- | ||
def _banner_default(self): | ||||
from IPython.core.usage import default_gui_banner | ||||
return default_gui_banner | ||||