##// END OF EJS Templates
update component to master (font-awesome 4.3)...
update component to master (font-awesome 4.3) closes #7544

File last commit:

r19784:080fb686 merge
r20144:d4b1c635
Show More
ipython_widget.py
594 lines | 24.2 KiB | text/x-python | PythonLexer
Thomas Kluyver
Standardise some module docstring first lines
r13888 """A FrontendWidget that emulates the interface of the console IPython.
This supports the additional functionality provided by the IPython kernel.
epatters
Reimplemented IPythonWidget's edit magic handling to support line numbers. Also, removed the code path for launching the file with the system default Python application, as this is too dangerous.
r2850 """
MinRK
pyout -> execute_result...
r16568 # Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
epatters
Added a method on IPythonWidget for setting the style to the IPython defaults.
r2916
epatters
Replaced internal storage object with namedtuple.
r2883 from collections import namedtuple
Evan Patterson
Fix Windows-specific bug in path handling for Qt console.
r3797 import os.path
epatters
* Fixed bug with terminal-style tab completion for multi-line input....
r2920 import re
epatters
Added preliminary editor support to IPythonWidget.
r2793 from subprocess import Popen
Evan Patterson
Fix Windows-specific bug in path handling for Qt console.
r3797 import sys
MinRK
retry aborted history requests in qtconsole
r4701 import time
Brian Granger
Implemented %loadpy magic for loading .py scripts into Qt console.
r3036 from textwrap import dedent
epatters
Added preliminary editor support to IPythonWidget.
r2793
Evan Patterson
Paved the way for PySide support....
r3304 from IPython.external.qt import QtCore, QtGui
epatters
* Updated FrontendWidget to use BlockBreaker for parsing input...
r2630
Thomas Kluyver
Fix starting the Qt console
r10099 from IPython.core.inputsplitter import IPythonInputSplitter
MinRK
add kernel banner to terminal and qt frontends
r16583 from IPython.core.release import version
Thomas Kluyver
Fix starting the Qt console
r10099 from IPython.core.inputtransformer import ipy_prompt
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 from IPython.utils.traitlets import Bool, Unicode
Thomas Kluyver
Use explicit relative imports...
r13347 from .frontend_widget import FrontendWidget
from . import styles
epatters
* Created an IPythonWidget subclass of FrontendWidget to contain IPython specific functionality....
r2627
epatters
Added a method on IPythonWidget for setting the style to the IPython defaults.
r2916 #-----------------------------------------------------------------------------
# Constants
#-----------------------------------------------------------------------------
Fernando Perez
Rework messaging to better conform to our spec....
r2926 # Default strings to build and display input and output prompts (and separators
# in between)
epatters
Made IPythonWidget and its subclasses Configurable.
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
Rework messaging to better conform to our spec....
r2926 default_input_sep = '\n'
default_output_sep = ''
default_output_sep2 = ''
epatters
Made IPythonWidget and its subclasses Configurable.
r2884
epatters
Minor cleanup in IPythonWidget (fix long lines, method order, etc).
r3041 # Base path for most payload sources.
MinRK
mv IPython.zmq to IPython.kernel.zmq
r9372 zmq_shell_source = 'IPython.kernel.zmq.zmqshell.ZMQInteractiveShell'
epatters
Minor cleanup in IPythonWidget (fix long lines, method order, etc).
r3041
MinRK
expand default_editor message to include configurable...
r3977 if sys.platform.startswith('win'):
default_editor = 'notepad'
else:
default_editor = ''
epatters
Added a method on IPythonWidget for setting the style to the IPython defaults.
r2916 #-----------------------------------------------------------------------------
# IPythonWidget class
#-----------------------------------------------------------------------------
epatters
* Created an IPythonWidget subclass of FrontendWidget to contain IPython specific functionality....
r2627
class IPythonWidget(FrontendWidget):
""" A FrontendWidget for an IPython kernel.
"""
epatters
Made IPythonWidget and its subclasses Configurable.
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
Paved the way for PySide support....
r3304 custom_edit_requested = QtCore.Signal(object, object)
epatters
Added preliminary editor support to IPythonWidget.
r2793
MinRK
expand default_editor message to include configurable...
r3977 editor = Unicode(default_editor, config=True,
MinRK
QtConsole now uses newapp
r3971 help="""
A command for invoking a system text editor. If the string contains a
epatters
First cut at safe appending in the Qt console.
r4056 {filename} format specifier, it will be used. Otherwise, the filename
will be appended to the end the command.
MinRK
QtConsole now uses newapp
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
First cut at safe appending in the Qt console.
r4056 this parameter is not specified, the line number option to the %edit
magic will be ignored.
MinRK
QtConsole now uses newapp
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
remove all trailling spaces
r4872
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
r4046 syntax_style = Unicode(config=True,
MinRK
QtConsole now uses newapp
r3971 help="""
epatters
First cut at safe appending in the Qt console.
r4056 If not empty, use this Pygments style for syntax highlighting.
Otherwise, the style sheet is queried for Pygments style
information.
MinRK
QtConsole now uses newapp
r3971 """)
epatters
Added machinery to IPythonWidget for updating the previous prompt number.
r2733
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 # Prompts.
Thomas Kluyver
Eliminate Str and CStr trait types except in IPython.parallel
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
Replaced internal storage object with namedtuple.
r2883
epatters
* Refactored payload handling mechanism....
r2835 # FrontendWidget protected class variables.
Fernando Perez
Fix bug with IPythonInputSplitter in block input mode.
r2861 _input_splitter_class = IPythonInputSplitter
Thomas Kluyver
Fix for starting the Qt console
r10113 _prompt_transformer = IPythonInputSplitter(physical_line_transforms=[ipy_prompt()],
logical_line_transforms=[],
python_line_transforms=[],
)
epatters
* Fixed bug where syntax highlighting was lost after updating a prompt with a bad number....
r2800
epatters
* Refactored payload handling mechanism....
r2835 # IPythonWidget protected class variables.
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 _PromptBlock = namedtuple('_PromptBlock', ['block', 'length', 'number'])
Min RK
update payloads for msg spec 5...
r19025 _payload_source_edit = 'edit'
MinRK
update payload source...
r11839 _payload_source_exit = 'ask_exit'
_payload_source_next_input = 'set_next_input'
_payload_source_page = 'page'
MinRK
retry aborted history requests in qtconsole
r4701 _retrying_history_request = False
MinRK
add kernel banner to terminal and qt frontends
r16583 _starting = False
epatters
* Refactored payload handling mechanism....
r2835
epatters
* Created an IPythonWidget subclass of FrontendWidget to contain IPython specific functionality....
r2627 #---------------------------------------------------------------------------
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
* Created an IPythonWidget subclass of FrontendWidget to contain IPython specific functionality....
r2627 #---------------------------------------------------------------------------
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(IPythonWidget, self).__init__(*args, **kw)
epatters
* Created an IPythonWidget subclass of FrontendWidget to contain IPython specific functionality....
r2627
epatters
Integrated new IPythonInputSplitter into IPythonWidget.
r2789 # IPythonWidget protected variables.
Bernardo B. Marques
remove all trailling spaces
r4872 self._payload_handlers = {
Fernando Perez
Implement exit/quit/Exit/Quit recognition....
r2950 self._payload_source_edit : self._handle_payload_edit,
self._payload_source_exit : self._handle_payload_exit,
Brian Granger
Implemented %loadpy magic for loading .py scripts into Qt console.
r3036 self._payload_source_page : self._handle_payload_page,
Thomas Kluyver
Add set_next_input method to ZMQInteractiveShell, so that %recall can put code at the next prompt.
r3864 self._payload_source_next_input : self._handle_payload_next_input }
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
r2961 self._previous_prompt_obj = None
Erik Tollerud
Expanded %exit magic in qtconsole to not exit without prompting and...
r3183 self._keep_kernel_on_exit = None
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 # Initialize widget styling.
epatters
Added a method on IPythonWidget for setting the style to the IPython defaults.
r2916 if self.style_sheet:
self._style_sheet_changed()
self._syntax_style_changed()
else:
self.set_default_style()
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688
Angus Griffith
only load %guiref in qtconsole with python kernels - fixes #4787
r14164 self._guiref_loaded = False
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 #---------------------------------------------------------------------------
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
Fixed regressions in the pure Python kernel.
r2867 def _handle_complete_reply(self, rep):
""" Reimplemented to support IPython's improved completion machinery.
"""
MinRK
add debug messages to qt handlers
r4793 self.log.debug("complete: %s", rep.get('content', ''))
epatters
Fixed regressions in the pure Python kernel.
r2867 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():
MinRK
complete_reply has cursor_start and cursor_end, not matched_text
r16588 content = rep['content']
matches = content['matches']
start = content['cursor_start']
end = content['cursor_end']
Steven Silvester
Improve handling of cursor_start and cursor_end for completions....
r18322 start = max(start, 0)
Steven Silvester
Do not force the end to be later than the start
r18421 end = max(end, start)
Steven Silvester
Improve handling of cursor_start and cursor_end for completions....
r18322
Steven Silvester
Add comments
r18357 # Move the control's cursor to the desired end point
Steven Silvester
Improve handling of cursor_start and cursor_end for completions....
r18322 cursor_pos = self._get_input_buffer_cursor_pos()
if end < cursor_pos:
cursor.movePosition(QtGui.QTextCursor.Left,
n=(cursor_pos - end))
elif end > cursor_pos:
cursor.movePosition(QtGui.QTextCursor.Right,
n=(end - cursor_pos))
Steven Silvester
Add comments
r18357 # This line actually applies the move to control's cursor
Steven Silvester
Improve handling of cursor_start and cursor_end for completions....
r18322 self._control.setTextCursor(cursor)
MinRK
complete_reply has cursor_start and cursor_end, not matched_text
r16588 offset = end - start
Steven Silvester
Add comments
r18357 # Move the local cursor object to the start of the match and
# complete.
epatters
Fixed numerous bugs with tab completion, including the one recently reported by fperez.
r2939 cursor.movePosition(QtGui.QTextCursor.Left, n=offset)
epatters
* Fixed bug with terminal-style tab completion for multi-line input....
r2920 self._complete_with_items(cursor, matches)
epatters
Fixed regressions in the pure Python kernel.
r2867
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934 def _handle_execute_reply(self, msg):
""" Reimplemented to support prompt requests.
"""
Matthias BUSSONNIER
fix to minrk suggestion
r5520 msg_id = msg['parent_header'].get('msg_id')
info = self._request_info['execute'].get(msg_id)
if info and info.kind == 'prompt':
Pankaj Pandey
Qt frontend: Handle 'aborted' prompt replies....
r14189 content = msg['content']
if content['status'] == 'aborted':
self._show_interpreter_prompt()
else:
number = content['execution_count'] + 1
self._show_interpreter_prompt(number)
self._request_info['execute'].pop(msg_id)
Matthias BUSSONNIER
fix to minrk suggestion
r5520 else:
Pankaj Pandey
Qt frontend: Handle 'aborted' prompt replies....
r14189 super(IPythonWidget, self)._handle_execute_reply(msg)
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934
Thomas Kluyver
Rename history_tail_reply back to history_reply.
r3820 def _handle_history_reply(self, msg):
Thomas Kluyver
ipython-qtconsole now calls the right function.
r3397 """ Implemented to handle history tail replies, which are only supported
by the IPython kernel.
epatters
* Added support for prompt and history requests to the kernel manager and Qt console frontend....
r2844 """
MinRK
Don't assume history request succeeded...
r4700 content = msg['content']
if 'history' not in content:
self.log.error("History request failed: %r"%content)
MinRK
retry aborted history requests in qtconsole
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)
Thomas Kluyver
Use messaging methods on kernel client instead of channel objects
r19213 self.kernel_client.history(hist_access_type='tail',n=1000)
MinRK
retry aborted history requests in qtconsole
r4701 else:
self._retrying_history_request = False
MinRK
Don't assume history request succeeded...
r4700 return
MinRK
retry aborted history requests in qtconsole
r4701 # reset retry flag
self._retrying_history_request = False
MinRK
Don't assume history request succeeded...
r4700 history_items = content['history']
MinRK
Don't log complete contents of history replies, even in debug
r6057 self.log.debug("Received history reply with %i entries", len(history_items))
Thomas Kluyver
Eliminate duplicate entries when filling readline-like history in the Qt console.
r5310 items = []
last_cell = u""
for _, _, cell in history_items:
cell = cell.rstrip()
if cell != last_cell:
items.append(cell)
last_cell = cell
epatters
* Added support for prompt and history requests to the kernel manager and Qt console frontend....
r2844 self._set_history(items)
MinRK
highlight input from other front ends...
r18376
def _insert_other_input(self, cursor, content):
"""Insert function for input from other frontends"""
cursor.beginEditBlock()
start = cursor.position()
n = content.get('execution_count', 0)
cursor.insertText('\n')
self._insert_html(cursor, self._make_in_prompt(n))
cursor.insertText(content['code'])
self._highlighter.rehighlightBlock(cursor.block())
cursor.endEditBlock()
MinRK
add ConsoleWidget.include_other_output...
r18374 def _handle_execute_input(self, msg):
"""Handle an execute_input message"""
self.log.debug("execute_input: %s", msg.get('content', ''))
if self.include_output(msg):
MinRK
highlight input from other front ends...
r18376 self._append_custom(self._insert_other_input, msg['content'], before_prompt=True)
MinRK
add ConsoleWidget.include_other_output...
r18374
MinRK
pyout -> execute_result...
r16568 def _handle_execute_result(self, msg):
Min RK
move some debug statements to terminal RichIPythonWidget class
r19737 """Reimplemented for IPython-style "display hook"."""
MinRK
add ConsoleWidget.include_other_output...
r18374 if self.include_output(msg):
Jonathan Frederic
Make qtconsole aware of clear_output.
r16194 self.flush_clearoutput()
epatters
* The Qt console frontend now ignores cross chatter from other frontends....
r2824 content = msg['content']
Toby Gilham
making it PEP8 compliant
r6153 prompt_number = content.get('execution_count', 0)
Brian Granger
Display system is fully working now....
r3278 data = content['data']
MinRK
remove HTML repr support from the qtconsole...
r16507 if 'text/plain' in data:
epatters
First cut at safe appending in the Qt console.
r4056 self._append_plain_text(self.output_sep, True)
self._append_html(self._make_out_prompt(prompt_number), True)
Brian Granger
Display system is fully working now....
r3278 text = data['text/plain']
Thomas Kluyver
Add a new line before displaying multiline strings in the Qt console....
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
First cut at safe appending in the Qt console.
r4056 self._append_plain_text('\n', True)
self._append_plain_text(text + self.output_sep2, 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
Brian Granger
Mostly final version of display data....
r3277 def _handle_display_data(self, msg):
Min RK
move some debug statements to terminal RichIPythonWidget class
r19737 """The base handler for the ``display_data`` message."""
Bernardo B. Marques
remove all trailling spaces
r4872 # For now, we don't display data from other frontends, but we
Brian Granger
Mostly final version of display data....
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.
MinRK
add ConsoleWidget.include_other_output...
r18374 if self.include_output(msg):
Jonathan Frederic
Make qtconsole aware of clear_output.
r16194 self.flush_clearoutput()
Brian Granger
Mostly final version of display data....
r3277 data = msg['content']['data']
metadata = msg['content']['metadata']
# In the regular IPythonWidget, we simply print the plain text
# representation.
MinRK
remove HTML repr support from the qtconsole...
r16507 if 'text/plain' in data:
Brian Granger
Display system is fully working now....
r3278 text = data['text/plain']
epatters
Use safe appending in RichIPythonWidget.
r4057 self._append_plain_text(text, True)
Brian Granger
More improvements to the display system....
r3279 # This newline seems to be needed for text and html output.
epatters
Use safe appending in RichIPythonWidget.
r4057 self._append_plain_text(u'\n', True)
Brian Granger
Mostly final version of display data....
r3277
Angus Griffith
only load %guiref in qtconsole with python kernels - fixes #4787
r14164 def _handle_kernel_info_reply(self, rep):
MinRK
add kernel banner to terminal and qt frontends
r16583 """Handle kernel info replies."""
content = rep['content']
Angus Griffith
only load %guiref in qtconsole with python kernels - fixes #4787
r14164 if not self._guiref_loaded:
Carlos Cordoba
Improve detection of when to load guiref magic
r19525 if content.get('implementation') == 'ipython':
Angus Griffith
only load %guiref in qtconsole with python kernels - fixes #4787
r14164 self._load_guiref_magic()
self._guiref_loaded = True
MinRK
add kernel banner to terminal and qt frontends
r16583
self.kernel_banner = content.get('banner', '')
if self._starting:
# finish handling started channels
self._starting = False
super(IPythonWidget, self)._started_channels()
Angus Griffith
only load %guiref in qtconsole with python kernels - fixes #4787
r14164
epatters
* Added support for prompt and history requests to the kernel manager and Qt console frontend....
r2844 def _started_channels(self):
MinRK
load %guiref magic on kernel start
r7080 """Reimplemented to make a history request and load %guiref."""
MinRK
add kernel banner to terminal and qt frontends
r16583 self._starting = True
Angus Griffith
only load %guiref in qtconsole with python kernels - fixes #4787
r14164 # The reply will trigger %guiref load provided language=='python'
self.kernel_client.kernel_info()
Thomas Kluyver
Use messaging methods on kernel client instead of channel objects
r19213 self.kernel_client.history(hist_access_type='tail', n=1000)
MinRK
load %guiref magic on kernel start
r7080
def _load_guiref_magic(self):
"""Load %guiref magic."""
Thomas Kluyver
Use messaging methods on kernel client instead of channel objects
r19213 self.kernel_client.execute('\n'.join([
Bradley M. Froehle
qtconsole: Fix non-empty namespace at startup....
r7908 "try:",
" _usage",
"except:",
" from IPython.core import usage as _usage",
" get_ipython().register_magic_function(_usage.page_guiref, 'line', 'guiref')",
" del _usage",
MinRK
load %guiref magic on kernel start
r7080 ]), silent=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 # 'ConsoleWidget' public interface
#---------------------------------------------------------------------------
#---------------------------------------------------------------------------
# 'FrontendWidget' public interface
epatters
* Refactored ConsoleWidget execution API for greater flexibility and clarity....
r2688 #---------------------------------------------------------------------------
def execute_file(self, path, hidden=False):
""" Reimplemented to use the 'run' magic.
"""
Evan Patterson
Fix Windows-specific bug in path handling for Qt console.
r3797 # Use forward slashes on Windows to avoid escaping each separator.
if sys.platform == 'win32':
path = os.path.normpath(path).replace('\\', '/')
jdmarch
BUG: Improve hack. Issue #755. execute_file fails if filename has spaces
r4716 # Perhaps we should not be using %run directly, but while we
Jonathan March
BUG: Issue #755 qt IPythonWidget.execute_file fails if filename contains single and double quotes
r5697 # are, it is necessary to quote or escape filenames containing spaces
Jonathan March
BUG: execute_file fix failed on Windows....
r5699 # or quotes.
# In earlier code here, to minimize escaping, we sometimes quoted the
# filename with single quotes. But to do this, this code must be
# platform-aware, because run uses shlex rather than python string
# parsing, so that:
# * In Win: single quotes can be used in the filename without quoting,
# and we cannot use single quotes to quote the filename.
# * In *nix: we can escape double quotes in a double quoted filename,
# but can't escape single quotes in a single quoted filename.
# So to keep this code non-platform-specific and simple, we now only
# use double quotes to quote filenames, and escape when needed:
if ' ' in path or "'" in path or '"' in path:
Jonathan March
Cleaner fix for qt execute_file bug:...
r5698 path = '"%s"' % path.replace('"', '\\"')
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 self.execute('%%run %s' % path, hidden=hidden)
epatters
* Created an IPythonWidget subclass of FrontendWidget to contain IPython specific functionality....
r2627
#---------------------------------------------------------------------------
epatters
Added banners to FrontendWidget and IPythonWidget.
r2714 # 'FrontendWidget' protected 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 def _process_execute_error(self, msg):
""" Reimplemented for IPython-style traceback formatting.
"""
content = msg['content']
epatters
* Tab completion now uses the correct cursor position....
r2841 traceback = '\n'.join(content['traceback']) + '\n'
if False:
# FIXME: For now, tracebacks come as plain text, so we can't use
Fernando Perez
Improvements to exception handling to transport structured tracebacks....
r2838 # the html renderer yet. Once we refactor ultratb to produce
# properly styled tracebacks, this branch should be the default
traceback = traceback.replace(' ', '&nbsp;')
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
remove all trailling spaces
r4872 self._append_plain_text(traceback)
Fernando Perez
Implement exit/quit/Exit/Quit recognition....
r2950
epatters
* Refactored payload handling mechanism....
r2835 def _process_execute_payload(self, item):
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
r2961 """ Reimplemented to dispatch payloads to handler methods.
epatters
* Refactored payload handling mechanism....
r2835 """
Fernando Perez
Implement exit/quit/Exit/Quit recognition....
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
* Refactored payload handling mechanism....
r2835 return False
Fernando Perez
Implement exit/quit/Exit/Quit recognition....
r2950 else:
handler(item)
return True
Bernardo B. Marques
remove all trailling spaces
r4872
Fernando Perez
Rework messaging to better conform to our spec....
r2926 def _show_interpreter_prompt(self, number=None):
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715 """ Reimplemented for IPython-style prompts.
"""
epatters
* Added support for prompt and history requests to the kernel manager and Qt console frontend....
r2844 # If a number was not specified, make a prompt number request.
epatters
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
r2797 if number is None:
Thomas Kluyver
Use messaging methods on kernel client instead of channel objects
r19213 msg_id = self.kernel_client.execute('', silent=True)
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934 info = self._ExecutionRequest(msg_id, 'prompt')
Matthias BUSSONNIER
qtconsole: fix race-cond, handle multiple exec...
r5506 self._request_info['execute'][msg_id] = info
epatters
* Updated prompt request code to support the new silent execution mechanism....
r2934 return
epatters
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
r2797
epatters
IPythonWidget now supports 'input_sep'.
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
Rework messaging to better conform to our spec....
r2926 self._prompt_sep = self.input_sep
epatters
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
r2797 self._show_prompt(self._make_in_prompt(number), html=True)
epatters
IPythonWidget now supports 'input_sep'.
r2806 block = self._control.document().lastBlock()
length = len(self._prompt)
epatters
Replaced internal storage object with namedtuple.
r2883 self._previous_prompt_obj = self._PromptBlock(block, length, number)
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715
# Update continuation prompt to reflect (possibly) new prompt length.
epatters
Added machinery to IPythonWidget for updating the previous prompt number.
r2733 self._set_continuation_prompt(
self._make_continuation_prompt(self._prompt), html=True)
epatters
* IPythonWidget now has IPython-style prompts that are futher stylabla via CSS...
r2715
epatters
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
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
various small fixes in qtconsole...
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
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
r2797 if self._previous_prompt_obj and \
self._previous_prompt_obj.number != previous_prompt_number:
block = self._previous_prompt_obj.block
epatters
Fixed bug introduced by the recent payload processing refactor.
r2846
# Make sure the prompt block has not been erased.
epatters
Yet more PySide compatibility fixes.
r3307 if block.isValid() and block.text():
epatters
* Fixed bug where syntax highlighting was lost after updating a prompt with a bad number....
r2800
# Remove the old prompt and insert a new prompt.
epatters
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
r2797 cursor = QtGui.QTextCursor(block)
cursor.movePosition(QtGui.QTextCursor.Right,
Bernardo B. Marques
remove all trailling spaces
r4872 QtGui.QTextCursor.KeepAnchor,
epatters
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
r2797 self._previous_prompt_obj.length)
prompt = self._make_in_prompt(previous_prompt_number)
epatters
* Fixed bug where syntax highlighting was lost after updating a prompt with a bad number....
r2800 self._prompt = self._insert_html_fetching_plain_text(
cursor, prompt)
epatters
Minor cleanup.
r2825 # When the HTML is inserted, Qt blows away the syntax
# highlighting for the line, so we need to rehighlight it.
epatters
* Fixed bug where syntax highlighting was lost after updating a prompt with a bad number....
r2800 self._highlighter.rehighlightBlock(cursor.block())
epatters
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
r2797 self._previous_prompt_obj = None
# Show a new prompt with the kernel's estimated prompt number.
epatters
Minor cleanup in IPythonWidget (fix long lines, method order, etc).
r3041 self._show_interpreter_prompt(previous_prompt_number + 1)
epatters
Updated IPythonWidget to use new prompt information. Initial prompt requests are not implemented.
r2797
epatters
Added banners to FrontendWidget and IPythonWidget.
r2714 #---------------------------------------------------------------------------
epatters
Added a method on IPythonWidget for setting the style to the IPython defaults.
r2916 # 'IPythonWidget' interface
#---------------------------------------------------------------------------
MinRK
color settings from ipythonqt propagate down to the ZMQInteractiveShell in the Kernel
r3173 def set_default_style(self, colors='lightbg'):
epatters
Added a method on IPythonWidget for setting the style to the IPython defaults.
r2916 """ Sets the widget style to the class defaults.
Thomas Kluyver
Clean up numpydoc section headers
r13587 Parameters
----------
MinRK
color settings from ipythonqt propagate down to the ZMQInteractiveShell in the Kernel
r3173 colors : str, optional (default lightbg)
epatters
Added a method on IPythonWidget for setting the style to the IPython defaults.
r2916 Whether to use the default IPython light background or dark
MinRK
added --colors flag to ipythonqt
r3171 background or B&W style.
epatters
Added a method on IPythonWidget for setting the style to the IPython defaults.
r2916 """
MinRK
color settings from ipythonqt propagate down to the ZMQInteractiveShell in the Kernel
r3173 colors = colors.lower()
if colors=='lightbg':
MinRK
QtConsole now uses newapp
r3971 self.style_sheet = styles.default_light_style_sheet
self.syntax_style = styles.default_light_syntax_style
MinRK
color settings from ipythonqt propagate down to the ZMQInteractiveShell in the Kernel
r3173 elif colors=='linux':
MinRK
QtConsole now uses newapp
r3971 self.style_sheet = styles.default_dark_style_sheet
self.syntax_style = styles.default_dark_syntax_style
MinRK
color settings from ipythonqt propagate down to the ZMQInteractiveShell in the Kernel
r3173 elif colors=='nocolor':
MinRK
QtConsole now uses newapp
r3971 self.style_sheet = styles.default_bw_style_sheet
self.syntax_style = styles.default_bw_syntax_style
MinRK
color settings from ipythonqt propagate down to the ZMQInteractiveShell in the Kernel
r3173 else:
raise KeyError("No such color scheme: %s"%colors)
epatters
Added a method on IPythonWidget for setting the style to the IPython defaults.
r2916
#---------------------------------------------------------------------------
epatters
Added machinery to IPythonWidget for updating the previous prompt number.
r2733 # 'IPythonWidget' protected interface
#---------------------------------------------------------------------------
epatters
Reimplemented IPythonWidget's edit magic handling to support line numbers. Also, removed the code path for launching the file with the system default Python application, as this is too dangerous.
r2850 def _edit(self, filename, line=None):
""" Opens a Python script for editing.
Thomas Kluyver
Clean up numpydoc section headers
r13587 Parameters
----------
epatters
Reimplemented IPythonWidget's edit magic handling to support line numbers. Also, removed the code path for launching the file with the system default Python application, as this is too dangerous.
r2850 filename : str
A path to a local system file.
line : int, optional
A line of interest in the file.
"""
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 if self.custom_edit:
epatters
Reimplemented IPythonWidget's edit magic handling to support line numbers. Also, removed the code path for launching the file with the system default Python application, as this is too dangerous.
r2850 self.custom_edit_requested.emit(filename, line)
MinRK
expand default_editor message to include configurable...
r3977 elif not self.editor:
self._append_plain_text('No default editor available.\n'
epatters
First cut at safe appending in the Qt console.
r4056 'Specify a GUI text editor in the `IPythonWidget.editor` '
'configurable to enable the %edit magic')
epatters
Reimplemented IPythonWidget's edit magic handling to support line numbers. Also, removed the code path for launching the file with the system default Python application, as this is too dangerous.
r2850 else:
try:
filename = '"%s"' % filename
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 if line and self.editor_line:
command = self.editor_line.format(filename=filename,
line=line)
epatters
Reimplemented IPythonWidget's edit magic handling to support line numbers. Also, removed the code path for launching the file with the system default Python application, as this is too dangerous.
r2850 else:
try:
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 command = self.editor.format()
epatters
Reimplemented IPythonWidget's edit magic handling to support line numbers. Also, removed the code path for launching the file with the system default Python application, as this is too dangerous.
r2850 except KeyError:
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 command = self.editor.format(filename=filename)
epatters
Reimplemented IPythonWidget's edit magic handling to support line numbers. Also, removed the code path for launching the file with the system default Python application, as this is too dangerous.
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
Added machinery to IPythonWidget for updating the previous prompt number.
r2733 def _make_in_prompt(self, number):
""" Given a prompt number, returns an HTML In prompt.
"""
MinRK
allow IPythonWidget.in_prompt to exclude input number...
r4478 try:
body = self.in_prompt % number
except TypeError:
# allow in_prompt to leave out number, e.g. '>>> '
Carlos Cordoba
Allow output prompt to leave out numbers for qtconsole
r17672 from xml.sax.saxutils import escape
body = escape(self.in_prompt)
epatters
Added machinery to IPythonWidget for updating the previous prompt number.
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 = '&nbsp;' * space_count + end_chars
return '<span class="in-prompt">%s</span>' % body
Bernardo B. Marques
remove all trailling spaces
r4872
epatters
Added machinery to IPythonWidget for updating the previous prompt number.
r2733 def _make_out_prompt(self, number):
""" Given a prompt number, returns an HTML Out prompt.
"""
Carlos Cordoba
Allow output prompt to leave out numbers for qtconsole
r17672 try:
body = self.out_prompt % number
except TypeError:
# allow out_prompt to leave out number, e.g. '<<< '
from xml.sax.saxutils import escape
body = escape(self.out_prompt)
epatters
Added machinery to IPythonWidget for updating the previous prompt number.
r2733 return '<span class="out-prompt">%s</span>' % body
epatters
Made IPythonWidget and its subclasses Configurable.
r2884
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
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
Expanded %exit magic in qtconsole to not exit without prompting and...
r3183 self._keep_kernel_on_exit = item['keepkernel']
Matthias BUSSONNIER
tab management new/existing kernel....
r5035 self.exit_requested.emit(self)
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
r2961
Thomas Kluyver
Add set_next_input method to ZMQInteractiveShell, so that %recall can put code at the next prompt.
r3864 def _handle_payload_next_input(self, item):
MinRK
don't interfere with set_next_input contents in qtconsole...
r13703 self.input_buffer = item['text']
epatters
Minor cleanup in IPythonWidget (fix long lines, method order, etc).
r3041
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
r2961 def _handle_payload_page(self, item):
epatters
Added support for HTML paging and HTML page payloads.
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.
MinRK
pager payload is a mime-bundle
r16586 data = item['data']
if 'text/html' in data and self.kind == 'rich':
self._page(data['text/html'], html=True)
epatters
Added support for HTML paging and HTML page payloads.
r3014 else:
MinRK
pager payload is a mime-bundle
r16586 self._page(data['text/plain'], html=False)
epatters
* Moved shutdown_kernel method from FrontendWidget to KernelManager....
r2961
Brian Granger
Mostly final version of display data....
r3277 #------ Trait change handlers --------------------------------------------
epatters
Made IPythonWidget and its subclasses Configurable.
r2884
def _style_sheet_changed(self):
""" Set the style sheets of the underlying widgets.
"""
self.setStyleSheet(self.style_sheet)
MinRK
protect Widget._style_sheet_changed from being called before _control exists...
r6055 if self._control is not None:
self._control.document().setDefaultStyleSheet(self.style_sheet)
bg_color = self._control.palette().window().color()
self._ansi_processor.set_background_color(bg_color)
if self._page_control is not None:
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 self._page_control.document().setDefaultStyleSheet(self.style_sheet)
MinRK
QtConsole now uses newapp
r3971
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 def _syntax_style_changed(self):
""" Set the style for the syntax highlighter.
"""
MinRK
QtConsole now uses newapp
r3971 if self._highlighter is None:
# ignore premature calls
return
epatters
Made IPythonWidget and its subclasses Configurable.
r2884 if self.syntax_style:
self._highlighter.set_style(self.syntax_style)
else:
self._highlighter.set_style_sheet(self.style_sheet)
Brian Granger
Mostly final version of display data....
r3277
epatters
ENH: Allow FrontendWidget banner to be changed without subclassing.
r4689 #------ Trait default initializers -----------------------------------------
def _banner_default(self):
MinRK
add kernel banner to terminal and qt frontends
r16583 return "IPython QtConsole {version}\n".format(version=version)