colors = colors.lower()<EOL>if colors=='<STR_LIT>':<EOL><INDENT>return default_light_style_template%get_colors(name)<EOL><DEDENT>elif colors=='<STR_LIT>':<EOL><INDENT>return default_dark_style_template%get_colors(name)<EOL><DEDENT>elif colors=='<STR_LIT>':<EOL><INDENT>return default_bw_style_sheet<EOL><DEDENT>else:<EOL><INDENT>raise KeyError("<STR_LIT>"%colors)<EOL><DEDENT>

Use one of the base templates, and set bg/fg/select colors.


self.intensity = <NUM_LIT:0><EOL>self.italic = False<EOL>self.bold = False<EOL>self.underline = False<EOL>self.foreground_color = None<EOL>self.background_color = None<EOL>

Reset graphics attributs to their default values.


self.actions = []<EOL>start = <NUM_LIT:0><EOL>last_char = '<STR_LIT:\n>' if len(string) > <NUM_LIT:0> and string[-<NUM_LIT:1>] == '<STR_LIT:\n>' else None<EOL>string = string[:-<NUM_LIT:1>] if last_char is not None else string<EOL>for match in ANSI_OR_SPECIAL_PATTERN.finditer(string):<EOL><INDENT>raw = string[start:match.start()]<EOL>substring = SPECIAL_PATTERN.sub(self._replace_special, raw)<EOL>if substring or self.actions:<EOL><INDENT>yield substring<EOL>self.actions = []<EOL><DEDENT>start = match.end()<EOL>groups = filter(lambda x: x is not None, match.groups())<EOL>g0 = groups[<NUM_LIT:0>]<EOL>if g0 == '<STR_LIT>':<EOL><INDENT>self.actions.append(BeepAction('<STR_LIT>'))<EOL>yield None<EOL>self.actions = []<EOL><DEDENT>elif g0 == '<STR_LIT:\r>':<EOL><INDENT>self.actions.append(CarriageReturnAction('<STR_LIT>'))<EOL>yield None<EOL>self.actions = []<EOL><DEDENT>elif g0 == '<STR_LIT>':<EOL><INDENT>self.actions.append(BackSpaceAction('<STR_LIT>'))<EOL>yield None<EOL>self.actions = []<EOL><DEDENT>elif g0 == '<STR_LIT:\n>' or g0 == '<STR_LIT:\r\n>':<EOL><INDENT>self.actions.append(NewLineAction('<STR_LIT>'))<EOL>yield g0<EOL>self.actions = []<EOL><DEDENT>else:<EOL><INDENT>params = [ param for param in groups[<NUM_LIT:1>].split('<STR_LIT:;>') if param ]<EOL>if g0.startswith('<STR_LIT:[>'):<EOL><INDENT>try:<EOL><INDENT>params = map(int, params)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDENT>else:<EOL><INDENT>self.set_csi_code(groups[<NUM_LIT:2>], params)<EOL><DEDENT><DEDENT>elif g0.startswith('<STR_LIT:]>'):<EOL><INDENT>self.set_osc_code(params)<EOL><DEDENT><DEDENT><DEDENT>raw = string[start:]<EOL>substring = SPECIAL_PATTERN.sub(self._replace_special, raw)<EOL>if substring or self.actions:<EOL><INDENT>yield substring<EOL><DEDENT>if last_char is not None:<EOL><INDENT>self.actions.append(NewLineAction('<STR_LIT>'))<EOL>yield last_char<EOL><DEDENT>

Yields substrings for which the same escape code applies.


def set_csi_code(self, command, params=[]):

if command == '<STR_LIT:m>':   <EOL><INDENT>if params:<EOL><INDENT>self.set_sgr_code(params)<EOL><DEDENT>else:<EOL><INDENT>self.set_sgr_code([<NUM_LIT:0>])<EOL><DEDENT><DEDENT>elif (command == '<STR_LIT>' or <EOL>command == '<STR_LIT>'):  <EOL><INDENT>code = params[<NUM_LIT:0>] if params else <NUM_LIT:0><EOL>if <NUM_LIT:0> <= code <= <NUM_LIT:2>:<EOL><INDENT>area = '<STR_LIT>' if command == '<STR_LIT>' else '<STR_LIT>'<EOL>if code == <NUM_LIT:0>:<EOL><INDENT>erase_to = '<STR_LIT:end>'<EOL><DEDENT>elif code == <NUM_LIT:1>:<EOL><INDENT>erase_to = '<STR_LIT:start>'<EOL><DEDENT>elif code == <NUM_LIT:2>:<EOL><INDENT>erase_to = '<STR_LIT:all>'<EOL><DEDENT>self.actions.append(EraseAction('<STR_LIT>', area, erase_to))<EOL><DEDENT><DEDENT>elif (command == '<STR_LIT:S>' or <EOL>command == '<STR_LIT:T>'):  <EOL><INDENT>dir = '<STR_LIT>' if command == '<STR_LIT:S>' else '<STR_LIT>'<EOL>count = params[<NUM_LIT:0>] if params else <NUM_LIT:1><EOL>self.actions.append(ScrollAction('<STR_LIT>', dir, '<STR_LIT>', count))<EOL><DEDENT>

Set attributes based on CSI (Control Sequence Introducer) code.

        Parameters
        ----------
        command : str
            The code identifier, i.e. the final character in the sequence.

        params : sequence of integers, optional
            The parameter codes for the command.


try:<EOL><INDENT>command = int(params.pop(<NUM_LIT:0>))<EOL><DEDENT>except (IndexError, ValueError):<EOL><INDENT>return<EOL><DEDENT>if command == <NUM_LIT:4>:<EOL><INDENT>try:<EOL><INDENT>color = int(params.pop(<NUM_LIT:0>))<EOL>spec = params.pop(<NUM_LIT:0>)<EOL>self.color_map[color] = self._parse_xterm_color_spec(spec)<EOL><DEDENT>except (IndexError, ValueError):<EOL><INDENT>pass<EOL><DEDENT><DEDENT>

Set attributes based on OSC (Operating System Command) parameters.

        Parameters
        ----------
        params : sequence of str
            The parameters for the command.


<EOL>if not params:<EOL><INDENT>return<EOL><DEDENT>code = params.pop(<NUM_LIT:0>)<EOL>if code == <NUM_LIT:0>:<EOL><INDENT>self.reset_sgr()<EOL><DEDENT>elif code == <NUM_LIT:1>:<EOL><INDENT>if self.bold_text_enabled:<EOL><INDENT>self.bold = True<EOL><DEDENT>else:<EOL><INDENT>self.intensity = <NUM_LIT:1><EOL><DEDENT><DEDENT>elif code == <NUM_LIT:2>:<EOL><INDENT>self.intensity = <NUM_LIT:0><EOL><DEDENT>elif code == <NUM_LIT:3>:<EOL><INDENT>self.italic = True<EOL><DEDENT>elif code == <NUM_LIT:4>:<EOL><INDENT>self.underline = True<EOL><DEDENT>elif code == <NUM_LIT>:<EOL><INDENT>self.intensity = <NUM_LIT:0><EOL>self.bold = False<EOL><DEDENT>elif code == <NUM_LIT>:<EOL><INDENT>self.italic = False<EOL><DEDENT>elif code == <NUM_LIT>:<EOL><INDENT>self.underline = False<EOL><DEDENT>elif code >= <NUM_LIT:30> and code <= <NUM_LIT>:<EOL><INDENT>self.foreground_color = code - <NUM_LIT:30><EOL><DEDENT>elif code == <NUM_LIT> and params and params.pop(<NUM_LIT:0>) == <NUM_LIT:5>:<EOL><INDENT>if params:<EOL><INDENT>self.foreground_color = params.pop(<NUM_LIT:0>)<EOL><DEDENT><DEDENT>elif code == <NUM_LIT>:<EOL><INDENT>self.foreground_color = None<EOL><DEDENT>elif code >= <NUM_LIT> and code <= <NUM_LIT>:<EOL><INDENT>self.background_color = code - <NUM_LIT><EOL><DEDENT>elif code == <NUM_LIT> and params and params.pop(<NUM_LIT:0>) == <NUM_LIT:5>:<EOL><INDENT>if params:<EOL><INDENT>self.background_color = params.pop(<NUM_LIT:0>)<EOL><DEDENT><DEDENT>elif code == <NUM_LIT>:<EOL><INDENT>self.background_color = None<EOL><DEDENT>self.set_sgr_code(params)<EOL>

Set attributes based on SGR (Select Graphic Rendition) codes.

        Parameters
        ----------
        params : sequence of ints
            A list of SGR codes for one or more SGR commands. Usually this
            sequence will have one element per command, although certain
            xterm-specific commands requires multiple elements.


def get_color(self, color, intensity=<NUM_LIT:0>):

if color is None:<EOL><INDENT>return None<EOL><DEDENT>if color < <NUM_LIT:8> and intensity > <NUM_LIT:0>:<EOL><INDENT>color += <NUM_LIT:8><EOL><DEDENT>constructor = self.color_map.get(color, None)<EOL>if isinstance(constructor, basestring):<EOL><INDENT>return QtGui.QColor(constructor)<EOL><DEDENT>elif isinstance(constructor, (tuple, list)):<EOL><INDENT>return QtGui.QColor(*constructor)<EOL><DEDENT>return None<EOL>

Returns a QColor for a given color code, or None if one cannot be
            constructed.


format = QtGui.QTextCharFormat()<EOL>qcolor = self.get_color(self.foreground_color, self.intensity)<EOL>if qcolor is not None:<EOL><INDENT>format.setForeground(qcolor)<EOL><DEDENT>qcolor = self.get_color(self.background_color, self.intensity)<EOL>if qcolor is not None:<EOL><INDENT>format.setBackground(qcolor)<EOL><DEDENT>if self.bold:<EOL><INDENT>format.setFontWeight(QtGui.QFont.Bold)<EOL><DEDENT>else:<EOL><INDENT>format.setFontWeight(QtGui.QFont.Normal)<EOL><DEDENT>format.setFontItalic(self.italic)<EOL>format.setFontUnderline(self.underline)<EOL>return format<EOL>

Returns a QTextCharFormat that encodes the current style attributes.


<EOL>self.default_color_map = self.darkbg_color_map.copy()<EOL>if color.value() >= <NUM_LIT>:<EOL><INDENT>for i in xrange(<NUM_LIT:8>):<EOL><INDENT>self.default_color_map[i + <NUM_LIT:8>] = self.default_color_map[i]<EOL><DEDENT>self.default_color_map[<NUM_LIT:7>] = self.default_color_map[<NUM_LIT:15>] = '<STR_LIT>'<EOL><DEDENT>self.color_map.update(self.default_color_map)<EOL>

Given a background color (a QColor), attempt to set a color map
            that will be aesthetically pleasing.


t = Thread(target=f)<EOL>t.start()<EOL>return t<EOL>

call a function in a simple thread, to prevent blocking


def __init__(self, app,<EOL>confirm_exit=True,<EOL>new_frontend_factory=None, slave_frontend_factory=None,<EOL>):

super(MainWindow, self).__init__()<EOL>self._kernel_counter = <NUM_LIT:0><EOL>self._app = app<EOL>self.confirm_exit = confirm_exit<EOL>self.new_frontend_factory = new_frontend_factory<EOL>self.slave_frontend_factory = slave_frontend_factory<EOL>self.tab_widget = QtGui.QTabWidget(self)<EOL>self.tab_widget.setDocumentMode(True)<EOL>self.tab_widget.setTabsClosable(True)<EOL>self.tab_widget.tabCloseRequested[int].connect(self.close_tab)<EOL>self.setCentralWidget(self.tab_widget)<EOL>self.tab_widget.tabBar().setVisible(False)<EOL>self.tab_widget.setFocusPolicy(QtCore.Qt.NoFocus)<EOL>

Create a tabbed MainWindow for managing IPython FrontendWidgets

        Parameters
        ----------

        app : reference to QApplication parent
        confirm_exit : bool, optional
            Whether we should prompt on close of tabs
        new_frontend_factory : callable
            A callable that returns a new IPythonWidget instance, attached to
            its own running kernel.
        slave_frontend_factory : callable
            A callable that takes an existing IPythonWidget, and  returns a new
            IPythonWidget instance, attached to the same kernel.


if self.tab_widget.count() <= <NUM_LIT:1>:<EOL><INDENT>self.tab_widget.tabBar().setVisible(False)<EOL><DEDENT>else:<EOL><INDENT>self.tab_widget.tabBar().setVisible(True)<EOL><DEDENT>if self.tab_widget.count()==<NUM_LIT:0> :<EOL><INDENT>self.close()<EOL><DEDENT>

update visibility of the tabBar depending of the number of tab

        0 or 1 tab, tabBar hidden
        2+ tabs, tabBar visible

        send a self.close if number of tab ==0

        need to be called explicitly, or be connected to tabInserted/tabRemoved


c = self._kernel_counter<EOL>self._kernel_counter += <NUM_LIT:1><EOL>return c<EOL>

constantly increasing counter for kernel IDs


widget = self.new_frontend_factory()<EOL>self.add_tab_with_frontend(widget)<EOL>

create a new frontend and attach it to a new tab


current_widget = self.tab_widget.currentWidget()<EOL>current_widget_index = self.tab_widget.indexOf(current_widget)<EOL>current_widget_name = self.tab_widget.tabText(current_widget_index)<EOL>widget = self.slave_frontend_factory(current_widget)<EOL>if '<STR_LIT>' in current_widget_name:<EOL><INDENT>name = current_widget_name<EOL><DEDENT>else:<EOL><INDENT>name = '<STR_LIT>' % current_widget_name<EOL><DEDENT>self.add_tab_with_frontend(widget,name=name)<EOL>

create a new frontend attached to the same kernel as the current tab


<EOL>if type(current_tab) is not int :<EOL><INDENT>current_tab = self.tab_widget.indexOf(current_tab)<EOL><DEDENT>closing_widget=self.tab_widget.widget(current_tab)<EOL>if closing_widget==None:<EOL><INDENT>return<EOL><DEDENT>slave_tabs = self.find_slave_widgets(closing_widget)<EOL>keepkernel = None <EOL>if hasattr(closing_widget,'<STR_LIT>'): <EOL><INDENT>keepkernel = closing_widget._keep_kernel_on_exit<EOL>if keepkernel is not None:<EOL><INDENT>for tab in slave_tabs:<EOL><INDENT>tab._hidden = True<EOL><DEDENT>if closing_widget in slave_tabs:<EOL><INDENT>try :<EOL><INDENT>self.find_master_tab(closing_widget).execute('<STR_LIT>')<EOL><DEDENT>except AttributeError:<EOL><INDENT>self.log.info("<STR_LIT>")<EOL>self.tab_widget.removeTab(current_tab)<EOL><DEDENT>self.update_tab_bar_visibility()<EOL>return<EOL><DEDENT><DEDENT><DEDENT>kernel_manager = closing_widget.kernel_manager<EOL>if keepkernel is None and not closing_widget._confirm_exit:<EOL><INDENT>keepkernel = closing_widget._existing<EOL><DEDENT>if keepkernel is None: <EOL><INDENT>if kernel_manager and kernel_manager.channels_running:<EOL><INDENT>title = self.window().windowTitle()<EOL>cancel = QtGui.QMessageBox.Cancel<EOL>okay = QtGui.QMessageBox.Ok<EOL>if closing_widget._may_close:<EOL><INDENT>msg = "<STR_LIT>"+'<STR_LIT:">'+self.tab_widget.tabText(current_tab)+'<STR_LIT:">'<EOL>info = "<STR_LIT>"<EOL>justthis = QtGui.QPushButton("<STR_LIT>", self)<EOL>justthis.setShortcut('<STR_LIT:N>')<EOL>closeall = QtGui.QPushButton("<STR_LIT>", self)<EOL>closeall.setShortcut('<STR_LIT:Y>')<EOL>closeall.setShortcut('<STR_LIT>')<EOL>box = QtGui.QMessageBox(QtGui.QMessageBox.Question,<EOL>title, msg)<EOL>box.setInformativeText(info)<EOL>box.addButton(cancel)<EOL>box.addButton(justthis, QtGui.QMessageBox.NoRole)<EOL>box.addButton(closeall, QtGui.QMessageBox.YesRole)<EOL>box.setDefaultButton(closeall)<EOL>box.setEscapeButton(cancel)<EOL>pixmap = QtGui.QPixmap(self._app.icon.pixmap(QtCore.QSize(<NUM_LIT:64>,<NUM_LIT:64>)))<EOL>box.setIconPixmap(pixmap)<EOL>reply = box.exec_()<EOL>if reply == <NUM_LIT:1>: <EOL><INDENT>for slave in slave_tabs:<EOL><INDENT>background(slave.kernel_manager.stop_channels)<EOL>self.tab_widget.removeTab(self.tab_widget.indexOf(slave))<EOL><DEDENT>closing_widget.execute("<STR_LIT>")<EOL>self.tab_widget.removeTab(current_tab)<EOL>background(kernel_manager.stop_channels)<EOL><DEDENT>elif reply == <NUM_LIT:0>: <EOL><INDENT>if not closing_widget._existing:<EOL><INDENT>closing_widget.execute("<STR_LIT>")<EOL><DEDENT>self.tab_widget.removeTab(current_tab)<EOL>background(kernel_manager.stop_channels)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>reply = QtGui.QMessageBox.question(self, title,<EOL>"<STR_LIT>"+<EOL>"<STR_LIT>",<EOL>okay|cancel,<EOL>defaultButton=okay<EOL>)<EOL>if reply == okay:<EOL><INDENT>self.tab_widget.removeTab(current_tab)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif keepkernel: <EOL><INDENT>self.tab_widget.removeTab(current_tab)<EOL>background(kernel_manager.stop_channels)<EOL><DEDENT>else: <EOL><INDENT>self.tab_widget.removeTab(current_tab)<EOL>if kernel_manager and kernel_manager.channels_running:<EOL><INDENT>for slave in slave_tabs:<EOL><INDENT>background(slave.kernel_manager.stop_channels)<EOL>self.tab_widget.removeTab(self.tab_widget.indexOf(slave))<EOL><DEDENT>kernel_manager.shutdown_kernel()<EOL>background(kernel_manager.stop_channels)<EOL><DEDENT><DEDENT>self.update_tab_bar_visibility()<EOL>

Called when you need to try to close a tab.

        It takes the number of the tab to be closed as argument, or a reference
        to the widget inside this tab


if not name:<EOL><INDENT>name = '<STR_LIT>' % self.next_kernel_id<EOL><DEDENT>self.tab_widget.addTab(frontend,name)<EOL>self.update_tab_bar_visibility()<EOL>self.make_frontend_visible(frontend)<EOL>frontend.exit_requested.connect(self.close_tab)<EOL>

insert a tab with a given frontend in the tab bar, and give it a name


<EOL>if isinstance(tab, int):<EOL><INDENT>tab = self.tab_widget.widget(tab)<EOL><DEDENT>km=tab.kernel_manager<EOL>widget_list = [self.tab_widget.widget(i) for i in range(self.tab_widget.count())]<EOL>filtered_widget_list = [ widget for widget in widget_list if<EOL>widget.kernel_manager.connection_file == km.connection_file and<EOL>hasattr(widget,'<STR_LIT>') ]<EOL>master_widget= [ widget for widget in filtered_widget_list if widget._may_close]<EOL>if as_list:<EOL><INDENT>return master_widget<EOL><DEDENT>assert(len(master_widget)<=<NUM_LIT:1> )<EOL>if len(master_widget)==<NUM_LIT:0>:<EOL><INDENT>return None<EOL><DEDENT>return master_widget[<NUM_LIT:0>]<EOL>

Try to return the frontend that owns the kernel attached to the given widget/tab.

    Only finds frontend owned by the current application. Selection
    based on port of the kernel might be inaccurate if several kernel
    on different ip use same port number.

    This function does the conversion tabNumber/widget if needed.
    Might return None if no master widget (non local kernel)
    Will crash IPython if more than 1 masterWidget

    When asList set to True, always return a list of widget(s) owning
    the kernel. The list might be empty or containing several Widget.


<EOL>if isinstance(tab, int):<EOL><INDENT>tab = self.tab_widget.widget(tab)<EOL><DEDENT>km=tab.kernel_manager<EOL>widget_list = [self.tab_widget.widget(i) for i in range(self.tab_widget.count())]<EOL>filtered_widget_list = ( widget for widget in widget_list if<EOL>widget.kernel_manager.connection_file == km.connection_file)<EOL>master_widget_list = self.find_master_tab(tab, as_list=True)<EOL>slave_list = [widget for widget in filtered_widget_list if widget not in master_widget_list]<EOL>return slave_list<EOL>

return all the frontends that do not own the kernel attached to the given widget/tab.

            Only find frontends owned by the current application. Selection
            based on connection file of the kernel.

            This function does the conversion tabNumber/widget if needed.


def add_menu_action(self, menu, action, defer_shortcut=False):

menu.addAction(action)<EOL>self.addAction(action)<EOL>if defer_shortcut:<EOL><INDENT>action.setShortcutContext(QtCore.Qt.WidgetShortcut)<EOL><DEDENT>

Add action to menu as well as self

        So that when the menu bar is invisible, its actions are still available.

        If defer_shortcut is True, set the shortcut context to widget-only,
        where it will avoid conflict with shortcuts already bound to the
        widgets themselves.


<EOL>def inner_dynamic_magic():<EOL><INDENT>self.active_frontend.execute(magic)<EOL><DEDENT>inner_dynamic_magic.__name__ = "<STR_LIT>"<EOL>return inner_dynamic_magic<EOL>

Return a function `fun` that will execute `magic` on active frontend.

        Parameters
        ----------
        magic : string
            string that will be executed as is when the returned function is called

        Returns
        -------
        fun : function
            function with no parameters, when called will execute `magic` on the
            current active frontend at call time

        See Also
        --------
        populate_all_magic_menu : generate the "All Magics..." menu

        Notes
        -----
        `fun` executes `magic` in active frontend at the moment it is triggered,
        not the active frontend at the moment it was created.

        This function is mostly used to create the "All Magics..." Menu at run time.


for k,v in self._magic_menu_dict.items():<EOL><INDENT>v.clear()<EOL><DEDENT>self.all_magic_menu.clear()<EOL>protected_magic = set(["<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>","<STR_LIT>"])<EOL>mlist=ast.literal_eval(listofmagic)<EOL>for magic in mlist:<EOL><INDENT>cell = (magic['<STR_LIT:type>'] == '<STR_LIT>')<EOL>name = magic['<STR_LIT:name>']<EOL>mclass = magic['<STR_LIT:class>']<EOL>if cell :<EOL><INDENT>prefix='<STR_LIT>'<EOL><DEDENT>else :<EOL><INDENT>prefix='<STR_LIT:%>'<EOL><DEDENT>magic_menu = self._get_magic_menu(mclass)<EOL>if name in protected_magic:<EOL><INDENT>suffix = '<STR_LIT:?>'<EOL><DEDENT>else :<EOL><INDENT>suffix = '<STR_LIT>'<EOL><DEDENT>pmagic = '<STR_LIT>'%(prefix,name,suffix)<EOL>xaction = QtGui.QAction(pmagic,<EOL>self,<EOL>triggered=self._make_dynamic_magic(pmagic)<EOL>)<EOL>magic_menu.addAction(xaction)<EOL>self.all_magic_menu.addAction(xaction)<EOL><DEDENT>

Clean "All Magics..." menu and repopulate it with `listofmagic`

        Parameters
        ----------
        listofmagic : string,
            repr() of a list of strings, send back by the kernel

        Notes
        -----
        `listofmagic`is a repr() of list because it is fed with the result of
        a 'user_expression'


self.active_frontend._silent_exec_callback('<STR_LIT>',<EOL>self.populate_all_magic_menu)<EOL>

Update the list of magics in the "All Magics..." Menu

        Request the kernel with the list of available magics and populate the
        menu with the list received back


menu = self._magic_menu_dict.get(menuidentifier,None)<EOL>if not menu :<EOL><INDENT>if not menulabel:<EOL><INDENT>menulabel = re.sub("<STR_LIT>","<STR_LIT>",menuidentifier)<EOL><DEDENT>menu = QtGui.QMenu(menulabel,self.magic_menu)<EOL>self._magic_menu_dict[menuidentifier]=menu<EOL>self.magic_menu.insertMenu(self.magic_menu_separator,menu)<EOL><DEDENT>return menu<EOL>

return a submagic menu by name, and create it if needed

        parameters:
        -----------

        menulabel : str
            Label for the menu

        Will infere the menu name from the identifier at creation if menulabel not given.
        To do so you have too give menuidentifier as a CamelCassedString


if self.tab_widget.count() == <NUM_LIT:0>:<EOL><INDENT>event.accept()<EOL>return<EOL><DEDENT>title = self.window().windowTitle()<EOL>cancel = QtGui.QMessageBox.Cancel<EOL>okay = QtGui.QMessageBox.Ok<EOL>if self.confirm_exit:<EOL><INDENT>if self.tab_widget.count() > <NUM_LIT:1>:<EOL><INDENT>msg = "<STR_LIT>"<EOL><DEDENT>else:<EOL><INDENT>msg = "<STR_LIT>"<EOL><DEDENT>info = "<STR_LIT>"<EOL>closeall = QtGui.QPushButton("<STR_LIT>", self)<EOL>closeall.setShortcut('<STR_LIT>')<EOL>box = QtGui.QMessageBox(QtGui.QMessageBox.Question,<EOL>title, msg)<EOL>box.setInformativeText(info)<EOL>box.addButton(cancel)<EOL>box.addButton(closeall, QtGui.QMessageBox.YesRole)<EOL>box.setDefaultButton(closeall)<EOL>box.setEscapeButton(cancel)<EOL>pixmap = QtGui.QPixmap(self._app.icon.pixmap(QtCore.QSize(<NUM_LIT:64>,<NUM_LIT:64>)))<EOL>box.setIconPixmap(pixmap)<EOL>reply = box.exec_()<EOL><DEDENT>else:<EOL><INDENT>reply = okay<EOL><DEDENT>if reply == cancel:<EOL><INDENT>event.ignore()<EOL>return<EOL><DEDENT>if reply == okay:<EOL><INDENT>while self.tab_widget.count() >= <NUM_LIT:1>:<EOL><INDENT>widget = self.active_frontend<EOL>widget._confirm_exit = False<EOL>self.close_tab(widget)<EOL><DEDENT>event.accept()<EOL><DEDENT>

Forward the close event to every tabs contained by the windows


def execute(self, source=None, hidden=False, interactive=False):

if not hidden:<EOL><INDENT>history = self.input_buffer if source is None else source<EOL><DEDENT>executed = super(HistoryConsoleWidget, self).execute(<EOL>source, hidden, interactive)<EOL>if executed and not hidden:<EOL><INDENT>history = history.rstrip()<EOL>if history and (not self._history or self._history[-<NUM_LIT:1>] != history):<EOL><INDENT>self._history.append(history)<EOL><DEDENT>self._history_edits = {}<EOL>self._history_index = len(self._history)<EOL><DEDENT>return executed<EOL>


prompt_cursor = self._get_prompt_cursor()<EOL>if self._get_cursor().blockNumber() == prompt_cursor.blockNumber():<EOL><INDENT>if self._history_locked() and not shift_modifier:<EOL><INDENT>return False<EOL><DEDENT>col = self._get_input_buffer_cursor_column()<EOL>input_buffer = self.input_buffer<EOL>if self._history_index == len(self._history) or(self._history_prefix and col != len(self._history_prefix)):<EOL><INDENT>self._history_index = len(self._history)<EOL>self._history_prefix = input_buffer[:col]<EOL><DEDENT>self.history_previous(self._history_prefix,<EOL>as_prefix=not shift_modifier)<EOL>cursor = self._get_prompt_cursor()<EOL>if self._history_prefix:<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.Right,<EOL>n=len(self._history_prefix))<EOL><DEDENT>else:<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.EndOfLine)<EOL><DEDENT>self._set_cursor(cursor)<EOL>return False<EOL><DEDENT>return True<EOL>

Called when the up key is pressed. Returns whether to continue
            processing the event.


end_cursor = self._get_end_cursor()<EOL>if self._get_cursor().blockNumber() == end_cursor.blockNumber():<EOL><INDENT>if self._history_locked() and not shift_modifier:<EOL><INDENT>return False<EOL><DEDENT>replaced = self.history_next(self._history_prefix,<EOL>as_prefix=not shift_modifier)<EOL>if self._history_prefix and replaced:<EOL><INDENT>cursor = self._get_prompt_cursor()<EOL>cursor.movePosition(QtGui.QTextCursor.Right,<EOL>n=len(self._history_prefix))<EOL>self._set_cursor(cursor)<EOL><DEDENT>return False<EOL><DEDENT>return True<EOL>

Called when the down key is pressed. Returns whether to continue
            processing the event.


def history_previous(self, substring='<STR_LIT>', as_prefix=True):

index = self._history_index<EOL>replace = False<EOL>while index > <NUM_LIT:0>:<EOL><INDENT>index -= <NUM_LIT:1><EOL>history = self._get_edited_history(index)<EOL>if (as_prefix and history.startswith(substring))or (not as_prefix and substring in history):<EOL><INDENT>replace = True<EOL>break<EOL><DEDENT><DEDENT>if replace:<EOL><INDENT>self._store_edits()<EOL>self._history_index = index<EOL>self.input_buffer = history<EOL><DEDENT>return replace<EOL>

If possible, set the input buffer to a previous history item.

        Parameters:
        -----------
        substring : str, optional
            If specified, search for an item with this substring.
        as_prefix : bool, optional
            If True, the substring must match at the beginning (default).

        Returns:
        --------
        Whether the input buffer was changed.


def history_next(self, substring='<STR_LIT>', as_prefix=True):

index = self._history_index<EOL>replace = False<EOL>while self._history_index < len(self._history):<EOL><INDENT>index += <NUM_LIT:1><EOL>history = self._get_edited_history(index)<EOL>if (as_prefix and history.startswith(substring))or (not as_prefix and substring in history):<EOL><INDENT>replace = True<EOL>break<EOL><DEDENT><DEDENT>if replace:<EOL><INDENT>self._store_edits()<EOL>self._history_index = index<EOL>self.input_buffer = history<EOL><DEDENT>return replace<EOL>

If possible, set the input buffer to a subsequent history item.

        Parameters:
        -----------
        substring : str, optional
            If specified, search for an item with this substring.
        as_prefix : bool, optional
            If True, the substring must match at the beginning (default).

        Returns:
        --------
        Whether the input buffer was changed.


return self._history[-n:]<EOL>

Get the local history list.

        Parameters:
        -----------
        n : int
            The (maximum) number of history items to get.


msg_id = msg['<STR_LIT>']['<STR_LIT>']<EOL>info = self._request_info['<STR_LIT>'].pop(msg_id,None)<EOL>if info and info.kind == '<STR_LIT>' and not self._hidden:<EOL><INDENT>content = msg['<STR_LIT:content>']<EOL>status = content['<STR_LIT:status>']<EOL>if status == '<STR_LIT>':<EOL><INDENT>self._max_session_history=(int(content['<STR_LIT>']['<STR_LIT>']))<EOL><DEDENT><DEDENT>

Handles replies for code execution, here only session history length


return (self.history_lock and<EOL>(self._get_edited_history(self._history_index) !=<EOL>self.input_buffer) and<EOL>(self._get_prompt_cursor().blockNumber() !=<EOL>self._get_end_cursor().blockNumber()))<EOL>

Returns whether history movement is locked.


if index in self._history_edits:<EOL><INDENT>return self._history_edits[index]<EOL><DEDENT>elif index == len(self._history):<EOL><INDENT>return unicode()<EOL><DEDENT>return self._history[index]<EOL>

Retrieves a history item, possibly with temporary edits.


self._history = list(history)<EOL>self._history_edits = {}<EOL>self._history_index = len(self._history)<EOL>

Replace the current history with a sequence of history items.


current = self.input_buffer<EOL>if self._history_index == len(self._history) orself._history[self._history_index] != current:<EOL><INDENT>self._history_edits[self._history_index] = current<EOL><DEDENT>

If there are edits to the current input buffer, store them.


<EOL>first_match  = ESCAPE_RE.match(min(items))<EOL>last_match  = ESCAPE_RE.match(max(items))<EOL>if first_match and last_match:<EOL><INDENT>prefix = os.path.commonprefix((first_match.group(<NUM_LIT:0>)[::-<NUM_LIT:1>], last_match.group(<NUM_LIT:0>)[::-<NUM_LIT:1>]))[::-<NUM_LIT:1>]<EOL><DEDENT>else:<EOL><INDENT>prefix = '<STR_LIT>'<EOL><DEDENT>items = [s.lstrip(ESCAPE_CHARS) for s in items]<EOL>return prefix+os.path.commonprefix(items)<EOL>

Get common prefix for completions

    Return the longest common prefix of a list of strings, but with special
    treatment of escape characters that might precede commands in IPython,
    such as %magic functions. Used in tab completion.

    For a more general function, see os.path.commonprefix


cat = category(char)<EOL>return cat.startswith('<STR_LIT:L>') or cat.startswith('<STR_LIT:N>')<EOL>

Returns whether the specified unicode character is a letter or a number.


QtGui.QWidget.__init__(self, parent)<EOL>LoggingConfigurable.__init__(self, **kw)<EOL>self._pager_scroll_events = [QtCore.QEvent.Wheel]<EOL>if hasattr(QtCore.QEvent, '<STR_LIT>'):<EOL><INDENT>self._pager_scroll_events.append(QtCore.QEvent.NativeGesture)<EOL><DEDENT>layout = QtGui.QStackedLayout(self)<EOL>layout.setContentsMargins(<NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>, <NUM_LIT:0>)<EOL>self._control = self._create_control()<EOL>if self.paging in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>self._splitter = QtGui.QSplitter()<EOL>if self.paging == '<STR_LIT>':<EOL><INDENT>self._splitter.setOrientation(QtCore.Qt.Horizontal)<EOL><DEDENT>else:<EOL><INDENT>self._splitter.setOrientation(QtCore.Qt.Vertical)<EOL><DEDENT>self._splitter.addWidget(self._control)<EOL>layout.addWidget(self._splitter)<EOL><DEDENT>else:<EOL><INDENT>layout.addWidget(self._control)<EOL><DEDENT>if self.paging in ('<STR_LIT>', '<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>self._page_control = self._create_page_control()<EOL>if self._splitter:<EOL><INDENT>self._page_control.hide()<EOL>self._splitter.addWidget(self._page_control)<EOL><DEDENT>else:<EOL><INDENT>layout.addWidget(self._page_control)<EOL><DEDENT><DEDENT>self._append_before_prompt_pos = <NUM_LIT:0><EOL>self._ansi_processor = QtAnsiCodeProcessor()<EOL>if self.gui_completion == '<STR_LIT>':<EOL><INDENT>self._completion_widget = CompletionHtml(self)<EOL><DEDENT>elif self.gui_completion == '<STR_LIT>':<EOL><INDENT>self._completion_widget = CompletionWidget(self)<EOL><DEDENT>elif self.gui_completion == '<STR_LIT>':<EOL><INDENT>self._completion_widget = CompletionPlain(self)<EOL><DEDENT>self._continuation_prompt = '<STR_LIT>'<EOL>self._continuation_prompt_html = None<EOL>self._executing = False<EOL>self._filter_drag = False<EOL>self._filter_resize = False<EOL>self._html_exporter = HtmlExporter(self._control)<EOL>self._input_buffer_executing = '<STR_LIT>'<EOL>self._input_buffer_pending = '<STR_LIT>'<EOL>self._kill_ring = QtKillRing(self._control)<EOL>self._prompt = '<STR_LIT>'<EOL>self._prompt_html = None<EOL>self._prompt_pos = <NUM_LIT:0><EOL>self._prompt_sep = '<STR_LIT>'<EOL>self._reading = False<EOL>self._reading_callback = None<EOL>self._tab_width = <NUM_LIT:8><EOL>self.reset_font()<EOL>action = QtGui.QAction('<STR_LIT>', None)<EOL>action.setEnabled(True)<EOL>printkey = QtGui.QKeySequence(QtGui.QKeySequence.Print)<EOL>if printkey.matches("<STR_LIT>") and sys.platform != '<STR_LIT>':<EOL><INDENT>printkey = "<STR_LIT>"<EOL><DEDENT>action.setShortcut(printkey)<EOL>action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)<EOL>action.triggered.connect(self.print_)<EOL>self.addAction(action)<EOL>self.print_action = action<EOL>action = QtGui.QAction('<STR_LIT>', None)<EOL>action.setShortcut(QtGui.QKeySequence.Save)<EOL>action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)<EOL>action.triggered.connect(self.export_html)<EOL>self.addAction(action)<EOL>self.export_action = action<EOL>action = QtGui.QAction('<STR_LIT>', None)<EOL>action.setEnabled(True)<EOL>selectall = QtGui.QKeySequence(QtGui.QKeySequence.SelectAll)<EOL>if selectall.matches("<STR_LIT>") and sys.platform != '<STR_LIT>':<EOL><INDENT>selectall = "<STR_LIT>"<EOL><DEDENT>action.setShortcut(selectall)<EOL>action.setShortcutContext(QtCore.Qt.WidgetWithChildrenShortcut)<EOL>action.triggered.connect(self.select_all)<EOL>self.addAction(action)<EOL>self.select_all_action = action<EOL>self.increase_font_size = QtGui.QAction("<STR_LIT>",<EOL>self,<EOL>shortcut=QtGui.QKeySequence.ZoomIn,<EOL>shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,<EOL>statusTip="<STR_LIT>",<EOL>triggered=self._increase_font_size)<EOL>self.addAction(self.increase_font_size)<EOL>self.decrease_font_size = QtGui.QAction("<STR_LIT>",<EOL>self,<EOL>shortcut=QtGui.QKeySequence.ZoomOut,<EOL>shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,<EOL>statusTip="<STR_LIT>",<EOL>triggered=self._decrease_font_size)<EOL>self.addAction(self.decrease_font_size)<EOL>self.reset_font_size = QtGui.QAction("<STR_LIT>",<EOL>self,<EOL>shortcut="<STR_LIT>",<EOL>shortcutContext=QtCore.Qt.WidgetWithChildrenShortcut,<EOL>statusTip="<STR_LIT>",<EOL>triggered=self.reset_font)<EOL>self.addAction(self.reset_font_size)<EOL>

Create a ConsoleWidget.

        Parameters:
        -----------
        parent : QWidget, optional [default None]
            The parent for this widget.


etype = event.type()<EOL>if etype == QtCore.QEvent.KeyPress:<EOL><INDENT>key = event.key()<EOL>if self._control_key_down(event.modifiers()) andkey in self._ctrl_down_remap:<EOL><INDENT>new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,<EOL>self._ctrl_down_remap[key],<EOL>QtCore.Qt.NoModifier)<EOL>QtGui.qApp.sendEvent(obj, new_event)<EOL>return True<EOL><DEDENT>elif obj == self._control:<EOL><INDENT>return self._event_filter_console_keypress(event)<EOL><DEDENT>elif obj == self._page_control:<EOL><INDENT>return self._event_filter_page_keypress(event)<EOL><DEDENT><DEDENT>elif etype == QtCore.QEvent.MouseButtonRelease andevent.button() == QtCore.Qt.MidButton andobj == self._control.viewport():<EOL><INDENT>cursor = self._control.cursorForPosition(event.pos())<EOL>self._control.setTextCursor(cursor)<EOL>self.paste(QtGui.QClipboard.Selection)<EOL>return True<EOL><DEDENT>elif etype == QtCore.QEvent.Resize and not self._filter_resize:<EOL><INDENT>self._filter_resize = True<EOL>QtGui.qApp.sendEvent(obj, event)<EOL>self._adjust_scrollbars()<EOL>self._filter_resize = False<EOL>return True<EOL><DEDENT>elif etype == QtCore.QEvent.ShortcutOverride andself.override_shortcuts andself._control_key_down(event.modifiers()) andevent.key() in self._shortcuts:<EOL><INDENT>event.accept()<EOL><DEDENT>elif etype == QtCore.QEvent.DragEnter andobj == self._control.viewport() andevent.source() == self._control.viewport():<EOL><INDENT>self._filter_drag = True<EOL><DEDENT>elif etype == QtCore.QEvent.DragLeave andobj == self._control.viewport() andself._filter_drag:<EOL><INDENT>cursor = self._control.textCursor()<EOL>cursor.clearSelection()<EOL>self._control.setTextCursor(cursor)<EOL>self._filter_drag = False<EOL><DEDENT>elif etype == QtCore.QEvent.Drop and obj == self._control.viewport():<EOL><INDENT>cursor = self._control.cursorForPosition(event.pos())<EOL>if self._in_buffer(cursor.position()):<EOL><INDENT>text = event.mimeData().text()<EOL>self._insert_plain_text_into_buffer(cursor, text)<EOL><DEDENT>QtGui.qApp.sendEvent(obj, QtGui.QDragLeaveEvent())<EOL>return True<EOL><DEDENT>elif etype in self._pager_scroll_events andobj == self._page_control:<EOL><INDENT>self._page_control.repaint()<EOL>return True<EOL><DEDENT>return super(ConsoleWidget, self).eventFilter(obj, event)<EOL>

Reimplemented to ensure a console-like behavior in the underlying
            text widgets.


font_metrics = QtGui.QFontMetrics(self.font)<EOL>margin = (self._control.frameWidth() +<EOL>self._control.document().documentMargin()) * <NUM_LIT:2><EOL>style = self.style()<EOL>splitwidth = style.pixelMetric(QtGui.QStyle.PM_SplitterWidth)<EOL>width = font_metrics.width('<STR_LIT:U+0020>') * <NUM_LIT> + margin<EOL>width += style.pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)<EOL>if self.paging == '<STR_LIT>':<EOL><INDENT>width = width * <NUM_LIT:2> + splitwidth<EOL><DEDENT>height = font_metrics.height() * <NUM_LIT> + margin<EOL>if self.paging == '<STR_LIT>':<EOL><INDENT>height = height * <NUM_LIT:2> + splitwidth<EOL><DEDENT>return QtCore.QSize(width, height)<EOL>

Reimplemented to suggest a size that is 80 characters wide and
            25 lines high.


return self._control.textCursor().hasSelection()<EOL>

Returns whether text can be copied to the clipboard.


cursor = self._control.textCursor()<EOL>return (cursor.hasSelection() and<EOL>self._in_buffer(cursor.anchor()) and<EOL>self._in_buffer(cursor.position()))<EOL>

Returns whether text can be cut to the clipboard.


if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:<EOL><INDENT>return bool(QtGui.QApplication.clipboard().text())<EOL><DEDENT>return False<EOL>

Returns whether text can be pasted from the clipboard.


if self._executing:<EOL><INDENT>self._control.clear()<EOL><DEDENT>else:<EOL><INDENT>if keep_input:<EOL><INDENT>input_buffer = self.input_buffer<EOL><DEDENT>self._control.clear()<EOL>self._show_prompt()<EOL>if keep_input:<EOL><INDENT>self.input_buffer = input_buffer<EOL><DEDENT><DEDENT>

Clear the console.

        Parameters:
        -----------
        keep_input : bool, optional (default True)
            If set, restores the old input buffer if a new prompt is written.


self.layout().currentWidget().copy()<EOL>

Copy the currently selected text to the clipboard.


self.copy()<EOL>if self.can_cut():<EOL><INDENT>self._control.textCursor().removeSelectedText()<EOL><DEDENT>

Copy the currently selected text to the clipboard and delete it
            if it's inside the input buffer.


<EOL>if source is None:<EOL><INDENT>source = self.input_buffer<EOL>if not hidden:<EOL><INDENT>source += '<STR_LIT:\n>'<EOL><DEDENT><DEDENT>elif not hidden:<EOL><INDENT>self.input_buffer = source<EOL><DEDENT>complete = self._is_complete(source, interactive)<EOL>if hidden:<EOL><INDENT>if complete:<EOL><INDENT>self._execute(source, hidden)<EOL><DEDENT>else:<EOL><INDENT>error = '<STR_LIT>'<EOL>raise RuntimeError(error % source)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if complete:<EOL><INDENT>self._append_plain_text('<STR_LIT:\n>')<EOL>self._input_buffer_executing = self.input_buffer<EOL>self._executing = True<EOL>self._prompt_finished()<EOL>self._control.document().setMaximumBlockCount(self.buffer_size)<EOL>self._control.setUndoRedoEnabled(False)<EOL>self._execute(source, hidden)<EOL><DEDENT>else:<EOL><INDENT>cursor = self._get_end_cursor()<EOL>cursor.beginEditBlock()<EOL>cursor.insertText('<STR_LIT:\n>')<EOL>self._insert_continuation_prompt(cursor)<EOL>cursor.endEditBlock()<EOL>self._control.moveCursor(QtGui.QTextCursor.End)<EOL><DEDENT><DEDENT>return complete<EOL>

Executes source or the input buffer, possibly prompting for more
        input.

        Parameters:
        -----------
        source : str, optional

            The source to execute. If not specified, the input buffer will be
            used. If specified and 'hidden' is False, the input buffer will be
            replaced with the source before execution.

        hidden : bool, optional (default False)

            If set, no output will be shown and the prompt will not be modified.
            In other words, it will be completely invisible to the user that
            an execution has occurred.

        interactive : bool, optional (default False)

            Whether the console is to treat the source as having been manually
            entered by the user. The effect of this parameter depends on the
            subclass implementation.

        Raises:
        -------
        RuntimeError
            If incomplete input is given and 'hidden' is True. In this case,
            it is not possible to prompt for more input.

        Returns:
        --------
        A boolean indicating whether the source was executed.


Shows a dialog to export HTML/XML in various formats.


<EOL>if self._executing and not force:<EOL><INDENT>return self._input_buffer_executing<EOL><DEDENT>cursor = self._get_end_cursor()<EOL>cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)<EOL>input_buffer = cursor.selection().toPlainText()<EOL>return input_buffer.replace('<STR_LIT:\n>' + self._continuation_prompt, '<STR_LIT:\n>')<EOL>

The text that the user has entered entered at the current prompt.

        If the console is currently executing, the text that is executing will
        always be returned.


<EOL>if self._executing:<EOL><INDENT>self._input_buffer_pending = string<EOL>return<EOL><DEDENT>cursor = self._get_end_cursor()<EOL>cursor.beginEditBlock()<EOL>cursor.setPosition(self._prompt_pos, QtGui.QTextCursor.KeepAnchor)<EOL>cursor.removeSelectedText()<EOL>self._insert_plain_text_into_buffer(self._get_prompt_cursor(), string)<EOL>cursor.endEditBlock()<EOL>self._control.moveCursor(QtGui.QTextCursor.End)<EOL>

Sets the text in the input buffer.

        If the console is currently executing, this call has no *immediate*
        effect. When the execution is finished, the input buffer will be updated
        appropriately.


return self._control.document().defaultFont()<EOL>

The base font being used by the ConsoleWidget.


Sets the base font for the ConsoleWidget to the specified QFont.


if self._control.textInteractionFlags() & QtCore.Qt.TextEditable:<EOL><INDENT>self._keep_cursor_in_buffer()<EOL>cursor = self._control.textCursor()<EOL>text = QtGui.QApplication.clipboard().text(mode).rstrip()<EOL>self._insert_plain_text_into_buffer(cursor, dedent(text))<EOL><DEDENT>

Paste the contents of the clipboard into the input region.

        Parameters:
        -----------
        mode : QClipboard::Mode, optional [default QClipboard::Clipboard]

            Controls which part of the system clipboard is used. This can be
            used to access the selection clipboard in X11 and the Find buffer
            in Mac OS. By default, the regular clipboard is used.


if (not printer):<EOL><INDENT>printer = QtGui.QPrinter()<EOL>if(QtGui.QPrintDialog(printer).exec_() != QtGui.QDialog.Accepted):<EOL><INDENT>return<EOL><DEDENT><DEDENT>self._control.print_(printer)<EOL>

Print the contents of the ConsoleWidget to the specified QPrinter.


if not self._executing:<EOL><INDENT>prompt_cursor = self._get_prompt_cursor()<EOL>if self._get_cursor().blockNumber() < prompt_cursor.blockNumber():<EOL><INDENT>self._set_cursor(prompt_cursor)<EOL><DEDENT>self._set_top_cursor(prompt_cursor)<EOL><DEDENT>

Moves the prompt to the top of the viewport.


Redo the last operation. If there is no operation to redo, nothing
            happens.


if sys.platform == '<STR_LIT:win32>':<EOL><INDENT>fallback = '<STR_LIT>'<EOL><DEDENT>elif sys.platform == '<STR_LIT>':<EOL><INDENT>fallback = '<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>fallback = '<STR_LIT>'<EOL><DEDENT>font = get_font(self.font_family, fallback)<EOL>if self.font_size:<EOL><INDENT>font.setPointSize(self.font_size)<EOL><DEDENT>else:<EOL><INDENT>font.setPointSize(QtGui.qApp.font().pointSize())<EOL><DEDENT>font.setStyleHint(QtGui.QFont.TypeWriter)<EOL>self._set_font(font)<EOL>

Sets the font to the default fixed-width font for this platform.


font = self.font<EOL>size = max(font.pointSize() + delta, <NUM_LIT:1>) <EOL>font.setPointSize(size)<EOL>self._set_font(font)<EOL>

Change the font size by the specified amount (in points).


return self._tab_width<EOL>

The width (in terms of space characters) for tab characters.


font_metrics = QtGui.QFontMetrics(self.font)<EOL>self._control.setTabStopWidth(tab_width * font_metrics.width('<STR_LIT:U+0020>'))<EOL>self._tab_width = tab_width<EOL>

Sets the width (in terms of space characters) for tab characters.


Undo the last operation. If there is no operation to undo, nothing
            happens.


def _is_complete(self, source, interactive):

raise NotImplementedError<EOL>

Returns whether 'source' can be executed. When triggered by an
            Enter/Return key press, 'interactive' is True; otherwise, it is
            False.


raise NotImplementedError<EOL>

Execute 'source'. If 'hidden', do not show any output.


pass<EOL>

Called immediately after a new prompt is displayed.


pass<EOL>

Called immediately after a prompt is finished, i.e. when some input
            will be processed and a new prompt displayed.


return True<EOL>

Called when the up key is pressed. Returns whether to continue
            processing the event.


return True<EOL>

Called when the down key is pressed. Returns whether to continue
            processing the event.


return False<EOL>

Called when the tab key is pressed. Returns whether to continue
            processing the event.


def _append_custom(self, insert, input, before_prompt=False):

<EOL>cursor = self._control.textCursor()<EOL>if before_prompt and (self._reading or not self._executing):<EOL><INDENT>cursor.setPosition(self._append_before_prompt_pos)<EOL><DEDENT>else:<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.End)<EOL><DEDENT>start_pos = cursor.position()<EOL>result = insert(cursor, input)<EOL>if before_prompt and not self._executing:<EOL><INDENT>diff = cursor.position() - start_pos<EOL>self._append_before_prompt_pos += diff<EOL>self._prompt_pos += diff<EOL><DEDENT>return result<EOL>

A low-level method for appending content to the end of the buffer.

        If 'before_prompt' is enabled, the content will be inserted before the
        current prompt, if there is one.


def _append_html(self, html, before_prompt=False):

self._append_custom(self._insert_html, html, before_prompt)<EOL>

Appends HTML at the end of the console buffer.


def _append_html_fetching_plain_text(self, html, before_prompt=False):

return self._append_custom(self._insert_html_fetching_plain_text,<EOL>html, before_prompt)<EOL>

Appends HTML, then returns the plain text version of it.


def _append_plain_text(self, text, before_prompt=False):

self._append_custom(self._insert_plain_text, text, before_prompt)<EOL>

Appends plain text, processing ANSI codes if enabled.


self._completion_widget.cancel_completion()<EOL>

If text completion is progress, cancel it.


<EOL>cursor = self._get_prompt_cursor()<EOL>prompt = self._continuation_prompt.lstrip()<EOL>if(self._temp_buffer_filled):<EOL><INDENT>self._temp_buffer_filled = False<EOL>while cursor.movePosition(QtGui.QTextCursor.NextBlock):<EOL><INDENT>temp_cursor = QtGui.QTextCursor(cursor)<EOL>temp_cursor.select(QtGui.QTextCursor.BlockUnderCursor)<EOL>text = temp_cursor.selection().toPlainText().lstrip()<EOL>if not text.startswith(prompt):<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>return<EOL><DEDENT>cursor.movePosition(QtGui.QTextCursor.Left) <EOL>cursor.movePosition(QtGui.QTextCursor.End,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>cursor.removeSelectedText()<EOL>if self._control.isUndoRedoEnabled():<EOL><INDENT>self._control.setUndoRedoEnabled(False)<EOL>self._control.setUndoRedoEnabled(True)<EOL><DEDENT>

Clears the "temporary text" buffer, i.e. all the text following
            the prompt region.


def _complete_with_items(self, cursor, items):

self._cancel_completion()<EOL>if len(items) == <NUM_LIT:1>:<EOL><INDENT>cursor.setPosition(self._control.textCursor().position(),<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>cursor.insertText(items[<NUM_LIT:0>])<EOL><DEDENT>elif len(items) > <NUM_LIT:1>:<EOL><INDENT>current_pos = self._control.textCursor().position()<EOL>prefix = commonprefix(items)<EOL>if prefix:<EOL><INDENT>cursor.setPosition(current_pos, QtGui.QTextCursor.KeepAnchor)<EOL>cursor.insertText(prefix)<EOL>current_pos = cursor.position()<EOL><DEDENT>cursor.movePosition(QtGui.QTextCursor.Left, n=len(prefix))<EOL>self._completion_widget.show_items(cursor, items)<EOL><DEDENT>

Performs completion with 'items' at the specified cursor location.


def _fill_temporary_buffer(self, cursor, text, html=False):

fill the area below the active editting zone with text


menu = QtGui.QMenu(self)<EOL>self.cut_action = menu.addAction('<STR_LIT>', self.cut)<EOL>self.cut_action.setEnabled(self.can_cut())<EOL>self.cut_action.setShortcut(QtGui.QKeySequence.Cut)<EOL>self.copy_action = menu.addAction('<STR_LIT>', self.copy)<EOL>self.copy_action.setEnabled(self.can_copy())<EOL>self.copy_action.setShortcut(QtGui.QKeySequence.Copy)<EOL>self.paste_action = menu.addAction('<STR_LIT>', self.paste)<EOL>self.paste_action.setEnabled(self.can_paste())<EOL>self.paste_action.setShortcut(QtGui.QKeySequence.Paste)<EOL>menu.addSeparator()<EOL>menu.addAction(self.select_all_action)<EOL>menu.addSeparator()<EOL>menu.addAction(self.export_action)<EOL>menu.addAction(self.print_action)<EOL>return menu<EOL>

Creates a context menu for the given QPoint (in widget coordinates).


def _control_key_down(self, modifiers, include_command=False):

<EOL>if sys.platform == '<STR_LIT>':<EOL><INDENT>down = include_command and (modifiers & QtCore.Qt.ControlModifier)<EOL>return bool(down) ^ bool(modifiers & QtCore.Qt.MetaModifier)<EOL><DEDENT>else:<EOL><INDENT>return bool(modifiers & QtCore.Qt.ControlModifier)<EOL><DEDENT>

Given a KeyboardModifiers flags object, return whether the Control
        key is down.

        Parameters:
        -----------
        include_command : bool, optional (default True)
            Whether to treat the Command key as a (mutually exclusive) synonym
            for Control when in Mac OS.


Creates and connects the underlying text widget.


if self.custom_page_control:<EOL><INDENT>control = self.custom_page_control()<EOL><DEDENT>elif self.kind == '<STR_LIT>':<EOL><INDENT>control = QtGui.QPlainTextEdit()<EOL><DEDENT>elif self.kind == '<STR_LIT>':<EOL><INDENT>control = QtGui.QTextEdit()<EOL><DEDENT>control.installEventFilter(self)<EOL>viewport = control.viewport()<EOL>viewport.installEventFilter(self)<EOL>control.setReadOnly(True)<EOL>control.setUndoRedoEnabled(False)<EOL>control.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)<EOL>return control<EOL>

Creates and connects the underlying paging widget.


intercepted = False<EOL>cursor = self._control.textCursor()<EOL>position = cursor.position()<EOL>key = event.key()<EOL>ctrl_down = self._control_key_down(event.modifiers())<EOL>alt_down = event.modifiers() & QtCore.Qt.AltModifier<EOL>shift_down = event.modifiers() & QtCore.Qt.ShiftModifier<EOL>if event.matches(QtGui.QKeySequence.Copy):<EOL><INDENT>self.copy()<EOL>intercepted = True<EOL><DEDENT>elif event.matches(QtGui.QKeySequence.Cut):<EOL><INDENT>self.cut()<EOL>intercepted = True<EOL><DEDENT>elif event.matches(QtGui.QKeySequence.Paste):<EOL><INDENT>self.paste()<EOL>intercepted = True<EOL><DEDENT>elif key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter):<EOL><INDENT>intercepted = True<EOL>self._cancel_completion()<EOL>if self._in_buffer(position):<EOL><INDENT>if self._reading:<EOL><INDENT>self._append_plain_text('<STR_LIT:\n>')<EOL>self._reading = False<EOL>if self._reading_callback:<EOL><INDENT>self._reading_callback()<EOL><DEDENT><DEDENT>elif not self._executing:<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.End,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>at_end = len(cursor.selectedText().strip()) == <NUM_LIT:0><EOL>single_line = (self._get_end_cursor().blockNumber() ==<EOL>self._get_prompt_cursor().blockNumber())<EOL>if (at_end or shift_down or single_line) and not ctrl_down:<EOL><INDENT>self.execute(interactive = not shift_down)<EOL><DEDENT>else:<EOL><INDENT>cursor.beginEditBlock()<EOL>cursor.setPosition(position)<EOL>cursor.insertText('<STR_LIT:\n>')<EOL>self._insert_continuation_prompt(cursor)<EOL>cursor.endEditBlock()<EOL>self._control.moveCursor(QtGui.QTextCursor.End)<EOL>self._control.setTextCursor(cursor)<EOL><DEDENT><DEDENT><DEDENT><DEDENT>elif ctrl_down:<EOL><INDENT>if key == QtCore.Qt.Key_G:<EOL><INDENT>self._keyboard_quit()<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_K:<EOL><INDENT>if self._in_buffer(position):<EOL><INDENT>cursor.clearSelection()<EOL>cursor.movePosition(QtGui.QTextCursor.EndOfLine,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>if not cursor.hasSelection():<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.NextBlock,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>cursor.movePosition(QtGui.QTextCursor.Right,<EOL>QtGui.QTextCursor.KeepAnchor,<EOL>len(self._continuation_prompt))<EOL><DEDENT>self._kill_ring.kill_cursor(cursor)<EOL>self._set_cursor(cursor)<EOL><DEDENT>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_L:<EOL><INDENT>self.prompt_to_top()<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_O:<EOL><INDENT>if self._page_control and self._page_control.isVisible():<EOL><INDENT>self._page_control.setFocus()<EOL><DEDENT>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_U:<EOL><INDENT>if self._in_buffer(position):<EOL><INDENT>cursor.clearSelection()<EOL>start_line = cursor.blockNumber()<EOL>if start_line == self._get_prompt_cursor().blockNumber():<EOL><INDENT>offset = len(self._prompt)<EOL><DEDENT>else:<EOL><INDENT>offset = len(self._continuation_prompt)<EOL><DEDENT>cursor.movePosition(QtGui.QTextCursor.StartOfBlock,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>cursor.movePosition(QtGui.QTextCursor.Right,<EOL>QtGui.QTextCursor.KeepAnchor, offset)<EOL>self._kill_ring.kill_cursor(cursor)<EOL>self._set_cursor(cursor)<EOL><DEDENT>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_Y:<EOL><INDENT>self._keep_cursor_in_buffer()<EOL>self._kill_ring.yank()<EOL>intercepted = True<EOL><DEDENT>elif key in (QtCore.Qt.Key_Backspace, QtCore.Qt.Key_Delete):<EOL><INDENT>if key == QtCore.Qt.Key_Backspace:<EOL><INDENT>cursor = self._get_word_start_cursor(position)<EOL><DEDENT>else: <EOL><INDENT>cursor = self._get_word_end_cursor(position)<EOL><DEDENT>cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)<EOL>self._kill_ring.kill_cursor(cursor)<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_D:<EOL><INDENT>if len(self.input_buffer) == <NUM_LIT:0>:<EOL><INDENT>self.exit_requested.emit(self)<EOL><DEDENT>else:<EOL><INDENT>new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,<EOL>QtCore.Qt.Key_Delete,<EOL>QtCore.Qt.NoModifier)<EOL>QtGui.qApp.sendEvent(self._control, new_event)<EOL>intercepted = True<EOL><DEDENT><DEDENT><DEDENT>elif alt_down:<EOL><INDENT>if key == QtCore.Qt.Key_B:<EOL><INDENT>self._set_cursor(self._get_word_start_cursor(position))<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_F:<EOL><INDENT>self._set_cursor(self._get_word_end_cursor(position))<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_Y:<EOL><INDENT>self._kill_ring.rotate()<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_Backspace:<EOL><INDENT>cursor = self._get_word_start_cursor(position)<EOL>cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)<EOL>self._kill_ring.kill_cursor(cursor)<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_D:<EOL><INDENT>cursor = self._get_word_end_cursor(position)<EOL>cursor.setPosition(position, QtGui.QTextCursor.KeepAnchor)<EOL>self._kill_ring.kill_cursor(cursor)<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_Delete:<EOL><INDENT>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_Greater:<EOL><INDENT>self._control.moveCursor(QtGui.QTextCursor.End)<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_Less:<EOL><INDENT>self._control.setTextCursor(self._get_prompt_cursor())<EOL>intercepted = True<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if shift_down:<EOL><INDENT>anchormode = QtGui.QTextCursor.KeepAnchor<EOL><DEDENT>else:<EOL><INDENT>anchormode = QtGui.QTextCursor.MoveAnchor<EOL><DEDENT>if key == QtCore.Qt.Key_Escape:<EOL><INDENT>self._keyboard_quit()<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_Up:<EOL><INDENT>if self._reading or not self._up_pressed(shift_down):<EOL><INDENT>intercepted = True<EOL><DEDENT>else:<EOL><INDENT>prompt_line = self._get_prompt_cursor().blockNumber()<EOL>intercepted = cursor.blockNumber() <= prompt_line<EOL><DEDENT><DEDENT>elif key == QtCore.Qt.Key_Down:<EOL><INDENT>if self._reading or not self._down_pressed(shift_down):<EOL><INDENT>intercepted = True<EOL><DEDENT>else:<EOL><INDENT>end_line = self._get_end_cursor().blockNumber()<EOL>intercepted = cursor.blockNumber() == end_line<EOL><DEDENT><DEDENT>elif key == QtCore.Qt.Key_Tab:<EOL><INDENT>if not self._reading:<EOL><INDENT>if self._tab_pressed():<EOL><INDENT>cursor.insertText('<STR_LIT:U+0020>'*<NUM_LIT:4>)<EOL><DEDENT>intercepted = True<EOL><DEDENT><DEDENT>elif key == QtCore.Qt.Key_Left:<EOL><INDENT>line, col = cursor.blockNumber(), cursor.columnNumber()<EOL>if line > self._get_prompt_cursor().blockNumber() andcol == len(self._continuation_prompt):<EOL><INDENT>self._control.moveCursor(QtGui.QTextCursor.PreviousBlock,<EOL>mode=anchormode)<EOL>self._control.moveCursor(QtGui.QTextCursor.EndOfBlock,<EOL>mode=anchormode)<EOL>intercepted = True<EOL><DEDENT>else:<EOL><INDENT>intercepted = not self._in_buffer(position - <NUM_LIT:1>)<EOL><DEDENT><DEDENT>elif key == QtCore.Qt.Key_Right:<EOL><INDENT>original_block_number = cursor.blockNumber()<EOL>cursor.movePosition(QtGui.QTextCursor.Right,<EOL>mode=anchormode)<EOL>if cursor.blockNumber() != original_block_number:<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.Right,<EOL>n=len(self._continuation_prompt),<EOL>mode=anchormode)<EOL><DEDENT>self._set_cursor(cursor)<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_Home:<EOL><INDENT>start_line = cursor.blockNumber()<EOL>if start_line == self._get_prompt_cursor().blockNumber():<EOL><INDENT>start_pos = self._prompt_pos<EOL><DEDENT>else:<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.StartOfBlock,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>start_pos = cursor.position()<EOL>start_pos += len(self._continuation_prompt)<EOL>cursor.setPosition(position)<EOL><DEDENT>if shift_down and self._in_buffer(position):<EOL><INDENT>cursor.setPosition(start_pos, QtGui.QTextCursor.KeepAnchor)<EOL><DEDENT>else:<EOL><INDENT>cursor.setPosition(start_pos)<EOL><DEDENT>self._set_cursor(cursor)<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_Backspace:<EOL><INDENT>line, col = cursor.blockNumber(), cursor.columnNumber()<EOL>if not self._reading andcol == len(self._continuation_prompt) andline > self._get_prompt_cursor().blockNumber():<EOL><INDENT>cursor.beginEditBlock()<EOL>cursor.movePosition(QtGui.QTextCursor.StartOfBlock,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>cursor.removeSelectedText()<EOL>cursor.deletePreviousChar()<EOL>cursor.endEditBlock()<EOL>intercepted = True<EOL><DEDENT>else:<EOL><INDENT>anchor = cursor.anchor()<EOL>if anchor == position:<EOL><INDENT>intercepted = not self._in_buffer(position - <NUM_LIT:1>)<EOL><DEDENT>else:<EOL><INDENT>intercepted = not self._in_buffer(min(anchor, position))<EOL><DEDENT><DEDENT><DEDENT>elif key == QtCore.Qt.Key_Delete:<EOL><INDENT>if not self._reading and self._in_buffer(position) andcursor.atBlockEnd() and not cursor.hasSelection():<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.NextBlock,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>cursor.movePosition(QtGui.QTextCursor.Right,<EOL>QtGui.QTextCursor.KeepAnchor,<EOL>len(self._continuation_prompt))<EOL>cursor.removeSelectedText()<EOL>intercepted = True<EOL><DEDENT>else:<EOL><INDENT>anchor = cursor.anchor()<EOL>intercepted = (not self._in_buffer(anchor) or<EOL>not self._in_buffer(position))<EOL><DEDENT><DEDENT><DEDENT>if not (self._control_key_down(event.modifiers(), include_command=True)<EOL>or key in (QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown)<EOL>or (self._executing and not self._reading)):<EOL><INDENT>self._keep_cursor_in_buffer()<EOL><DEDENT>return intercepted<EOL>

Filter key events for the underlying text widget to create a
            console-like interface.


key = event.key()<EOL>ctrl_down = self._control_key_down(event.modifiers())<EOL>alt_down = event.modifiers() & QtCore.Qt.AltModifier<EOL>if ctrl_down:<EOL><INDENT>if key == QtCore.Qt.Key_O:<EOL><INDENT>self._control.setFocus()<EOL>intercept = True<EOL><DEDENT><DEDENT>elif alt_down:<EOL><INDENT>if key == QtCore.Qt.Key_Greater:<EOL><INDENT>self._page_control.moveCursor(QtGui.QTextCursor.End)<EOL>intercepted = True<EOL><DEDENT>elif key == QtCore.Qt.Key_Less:<EOL><INDENT>self._page_control.moveCursor(QtGui.QTextCursor.Start)<EOL>intercepted = True<EOL><DEDENT><DEDENT>elif key in (QtCore.Qt.Key_Q, QtCore.Qt.Key_Escape):<EOL><INDENT>if self._splitter:<EOL><INDENT>self._page_control.hide()<EOL>self._control.setFocus()<EOL><DEDENT>else:<EOL><INDENT>self.layout().setCurrentWidget(self._control)<EOL><DEDENT>return True<EOL><DEDENT>elif key in (QtCore.Qt.Key_Enter, QtCore.Qt.Key_Return,<EOL>QtCore.Qt.Key_Tab):<EOL><INDENT>new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,<EOL>QtCore.Qt.Key_PageDown,<EOL>QtCore.Qt.NoModifier)<EOL>QtGui.qApp.sendEvent(self._page_control, new_event)<EOL>return True<EOL><DEDENT>elif key == QtCore.Qt.Key_Backspace:<EOL><INDENT>new_event = QtGui.QKeyEvent(QtCore.QEvent.KeyPress,<EOL>QtCore.Qt.Key_PageUp,<EOL>QtCore.Qt.NoModifier)<EOL>QtGui.qApp.sendEvent(self._page_control, new_event)<EOL>return True<EOL><DEDENT>return False<EOL>

Filter key events for the paging widget to create console-like
            interface.


def _format_as_columns(self, items, separator='<STR_LIT:U+0020>'):

<EOL>width = self._control.viewport().width()<EOL>char_width = QtGui.QFontMetrics(self.font).width('<STR_LIT:U+0020>')<EOL>displaywidth = max(<NUM_LIT:10>, (width / char_width) - <NUM_LIT:1>)<EOL>return columnize(items, separator, displaywidth)<EOL>

Transform a list of strings into a single string with columns.

        Parameters
        ----------
        items : sequence of strings
            The strings to process.

        separator : str, optional [default is two spaces]
            The string that separates columns.

        Returns
        -------
        The formatted string.


Given a QTextBlock, return its unformatted text.


return self._control.textCursor()<EOL>

Convenience method that returns a cursor for the current position.


cursor = self._control.textCursor()<EOL>cursor.movePosition(QtGui.QTextCursor.End)<EOL>return cursor<EOL>

Convenience method that returns a cursor for the last character.


prompt = self._get_input_buffer_cursor_prompt()<EOL>if prompt is None:<EOL><INDENT>return -<NUM_LIT:1><EOL><DEDENT>else:<EOL><INDENT>cursor = self._control.textCursor()<EOL>return cursor.columnNumber() - len(prompt)<EOL><DEDENT>

Returns the column of the cursor in the input buffer, excluding the
            contribution by the prompt, or -1 if there is no such column.


prompt = self._get_input_buffer_cursor_prompt()<EOL>if prompt is None:<EOL><INDENT>return None<EOL><DEDENT>else:<EOL><INDENT>cursor = self._control.textCursor()<EOL>text = self._get_block_plain_text(cursor.block())<EOL>return text[len(prompt):]<EOL><DEDENT>

Returns the text of the line of the input buffer that contains the
            cursor, or None if there is no such line.


if self._executing:<EOL><INDENT>return None<EOL><DEDENT>cursor = self._control.textCursor()<EOL>if cursor.position() >= self._prompt_pos:<EOL><INDENT>if cursor.blockNumber() == self._get_prompt_cursor().blockNumber():<EOL><INDENT>return self._prompt<EOL><DEDENT>else:<EOL><INDENT>return self._continuation_prompt<EOL><DEDENT><DEDENT>else:<EOL><INDENT>return None<EOL><DEDENT>

Returns the (plain text) prompt for line of the input buffer that
            contains the cursor, or None if there is no such line.


cursor = self._control.textCursor()<EOL>cursor.setPosition(self._prompt_pos)<EOL>return cursor<EOL>

Convenience method that returns a cursor for the prompt position.


def _get_selection_cursor(self, start, end):

cursor = self._control.textCursor()<EOL>cursor.setPosition(start)<EOL>cursor.setPosition(end, QtGui.QTextCursor.KeepAnchor)<EOL>return cursor<EOL>

Convenience method that returns a cursor with text selected between
            the positions 'start' and 'end'.


document = self._control.document()<EOL>position -= <NUM_LIT:1><EOL>while position >= self._prompt_pos andnot is_letter_or_number(document.characterAt(position)):<EOL><INDENT>position -= <NUM_LIT:1><EOL><DEDENT>while position >= self._prompt_pos andis_letter_or_number(document.characterAt(position)):<EOL><INDENT>position -= <NUM_LIT:1><EOL><DEDENT>cursor = self._control.textCursor()<EOL>cursor.setPosition(position + <NUM_LIT:1>)<EOL>return cursor<EOL>

Find the start of the word to the left the given position. If a
            sequence of non-word characters precedes the first word, skip over
            them. (This emulates the behavior of bash, emacs, etc.)


document = self._control.document()<EOL>end = self._get_end_cursor().position()<EOL>while position < end andnot is_letter_or_number(document.characterAt(position)):<EOL><INDENT>position += <NUM_LIT:1><EOL><DEDENT>while position < end andis_letter_or_number(document.characterAt(position)):<EOL><INDENT>position += <NUM_LIT:1><EOL><DEDENT>cursor = self._control.textCursor()<EOL>cursor.setPosition(position)<EOL>return cursor<EOL>

Find the end of the word to the right the given position. If a
            sequence of non-word characters precedes the first word, skip over
            them. (This emulates the behavior of bash, emacs, etc.)


if self._continuation_prompt_html is None:<EOL><INDENT>self._insert_plain_text(cursor, self._continuation_prompt)<EOL><DEDENT>else:<EOL><INDENT>self._continuation_prompt = self._insert_html_fetching_plain_text(<EOL>cursor, self._continuation_prompt_html)<EOL><DEDENT>

Inserts new continuation prompt using the specified cursor.


Inserts HTML using the specified cursor in such a way that future
            formatting is unaffected.


def _insert_html_fetching_plain_text(self, cursor, html):

cursor.beginEditBlock()<EOL>cursor.removeSelectedText()<EOL>start = cursor.position()<EOL>self._insert_html(cursor, html)<EOL>end = cursor.position()<EOL>cursor.setPosition(start, QtGui.QTextCursor.KeepAnchor)<EOL>text = cursor.selection().toPlainText()<EOL>cursor.setPosition(end)<EOL>cursor.endEditBlock()<EOL>return text<EOL>

Inserts HTML using the specified cursor, then returns its plain text
            version.


def _insert_plain_text(self, cursor, text):

cursor.beginEditBlock()<EOL>if self.ansi_codes:<EOL><INDENT>for substring in self._ansi_processor.split_string(text):<EOL><INDENT>for act in self._ansi_processor.actions:<EOL><INDENT>if act.action == '<STR_LIT>' and act.area == '<STR_LIT>':<EOL><INDENT>cursor.select(QtGui.QTextCursor.Document)<EOL>cursor.removeSelectedText()<EOL><DEDENT>elif act.action == '<STR_LIT>' and act.unit == '<STR_LIT>':<EOL><INDENT>cursor.insertText('<STR_LIT:\n>')<EOL>cursor.endEditBlock()<EOL>self._set_top_cursor(cursor)<EOL>cursor.joinPreviousEditBlock()<EOL>cursor.deletePreviousChar()<EOL><DEDENT>elif act.action == '<STR_LIT>':<EOL><INDENT>cursor.movePosition(<EOL>cursor.StartOfLine, cursor.KeepAnchor)<EOL><DEDENT>elif act.action == '<STR_LIT>':<EOL><INDENT>QtGui.qApp.beep()<EOL><DEDENT>elif act.action == '<STR_LIT>':<EOL><INDENT>if not cursor.atBlockStart():<EOL><INDENT>cursor.movePosition(<EOL>cursor.PreviousCharacter, cursor.KeepAnchor)<EOL><DEDENT><DEDENT>elif act.action == '<STR_LIT>':<EOL><INDENT>cursor.movePosition(cursor.EndOfLine)<EOL><DEDENT><DEDENT>format = self._ansi_processor.get_format()<EOL>selection = cursor.selectedText()<EOL>if len(selection) == <NUM_LIT:0>:<EOL><INDENT>cursor.insertText(substring, format)<EOL><DEDENT>elif substring is not None:<EOL><INDENT>if len(substring) >= len(selection):<EOL><INDENT>cursor.insertText(substring, format)<EOL><DEDENT>else:<EOL><INDENT>old_text = selection[len(substring):]<EOL>cursor.insertText(substring + old_text, format)<EOL>cursor.movePosition(cursor.PreviousCharacter,<EOL>cursor.KeepAnchor, len(old_text))<EOL><DEDENT><DEDENT><DEDENT><DEDENT>else:<EOL><INDENT>cursor.insertText(text)<EOL><DEDENT>cursor.endEditBlock()<EOL>

Inserts plain text using the specified cursor, processing ANSI codes
            if enabled.


def _insert_plain_text_into_buffer(self, cursor, text):

lines = text.splitlines(True)<EOL>if lines:<EOL><INDENT>cursor.beginEditBlock()<EOL>cursor.insertText(lines[<NUM_LIT:0>])<EOL>for line in lines[<NUM_LIT:1>:]:<EOL><INDENT>if self._continuation_prompt_html is None:<EOL><INDENT>cursor.insertText(self._continuation_prompt)<EOL><DEDENT>else:<EOL><INDENT>self._continuation_prompt =self._insert_html_fetching_plain_text(<EOL>cursor, self._continuation_prompt_html)<EOL><DEDENT>cursor.insertText(line)<EOL><DEDENT>cursor.endEditBlock()<EOL><DEDENT>

Inserts text into the input buffer using the specified cursor (which
            must be in the input buffer), ensuring that continuation prompts are
            inserted as necessary.


cursor = self._control.textCursor()<EOL>if position is None:<EOL><INDENT>position = cursor.position()<EOL><DEDENT>else:<EOL><INDENT>cursor.setPosition(position)<EOL><DEDENT>line = cursor.blockNumber()<EOL>prompt_line = self._get_prompt_cursor().blockNumber()<EOL>if line == prompt_line:<EOL><INDENT>return position >= self._prompt_pos<EOL><DEDENT>elif line > prompt_line:<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.StartOfBlock)<EOL>prompt_pos = cursor.position() + len(self._continuation_prompt)<EOL>return position >= prompt_pos<EOL><DEDENT>return False<EOL>

Returns whether the current cursor (or, if specified, a position) is
            inside the editing region.


moved = not self._in_buffer()<EOL>if moved:<EOL><INDENT>cursor = self._control.textCursor()<EOL>cursor.movePosition(QtGui.QTextCursor.End)<EOL>self._control.setTextCursor(cursor)<EOL><DEDENT>return moved<EOL>

Ensures that the cursor is inside the editing region. Returns
            whether the cursor was moved.


if self._temp_buffer_filled :<EOL><INDENT>self._cancel_completion()<EOL>self._clear_temporary_buffer()<EOL><DEDENT>else:<EOL><INDENT>self.input_buffer = '<STR_LIT>'<EOL><DEDENT>

Cancels the current editing task ala Ctrl-G in Emacs.


line_height = QtGui.QFontMetrics(self.font).height()<EOL>minlines = self._control.viewport().height() / line_height<EOL>if self.paging != '<STR_LIT:none>' andre.match("<STR_LIT>" % minlines, text):<EOL><INDENT>if self.paging == '<STR_LIT>':<EOL><INDENT>self.custom_page_requested.emit(text)<EOL><DEDENT>else:<EOL><INDENT>self._page_control.clear()<EOL>cursor = self._page_control.textCursor()<EOL>if html:<EOL><INDENT>self._insert_html(cursor, text)<EOL><DEDENT>else:<EOL><INDENT>self._insert_plain_text(cursor, text)<EOL><DEDENT>self._page_control.moveCursor(QtGui.QTextCursor.Start)<EOL>self._page_control.viewport().resize(self._control.size())<EOL>if self._splitter:<EOL><INDENT>self._page_control.show()<EOL>self._page_control.setFocus()<EOL><DEDENT>else:<EOL><INDENT>self.layout().setCurrentWidget(self._page_control)<EOL><DEDENT><DEDENT><DEDENT>elif html:<EOL><INDENT>self._append_html(text)<EOL><DEDENT>else:<EOL><INDENT>self._append_plain_text(text)<EOL><DEDENT>

Displays text using the pager if it exceeds the height of the
        viewport.

        Parameters:
        -----------
        html : bool, optional (default False)
            If set, the text will be interpreted as HTML instead of plain text.


self._control.setReadOnly(True)<EOL>self._prompt_finished_hook()<EOL>

Called immediately after a prompt is finished, i.e. when some input
            will be processed and a new prompt displayed.


<EOL>self._control.document().setMaximumBlockCount(<NUM_LIT:0>)<EOL>self._control.setUndoRedoEnabled(True)<EOL>self._control.setReadOnly(False)<EOL>self._control.setAttribute(QtCore.Qt.WA_InputMethodEnabled, True)<EOL>if not self._reading:<EOL><INDENT>self._executing = False<EOL><DEDENT>self._prompt_started_hook()<EOL>if self._input_buffer_pending:<EOL><INDENT>self.input_buffer = self._input_buffer_pending<EOL>self._input_buffer_pending = '<STR_LIT>'<EOL><DEDENT>self._control.moveCursor(QtGui.QTextCursor.End)<EOL>

Called immediately after a new prompt is displayed.


def _readline(self, prompt='<STR_LIT>', callback=None):

if self._reading:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>if not callback and not self.isVisible():<EOL><INDENT>raise RuntimeError('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>self._reading = True<EOL>self._show_prompt(prompt, newline=False)<EOL>if callback is None:<EOL><INDENT>self._reading_callback = None<EOL>while self._reading:<EOL><INDENT>QtCore.QCoreApplication.processEvents()<EOL><DEDENT>return self._get_input_buffer(force=True).rstrip('<STR_LIT:\n>')<EOL><DEDENT>else:<EOL><INDENT>self._reading_callback = lambda:callback(self._get_input_buffer(force=True).rstrip('<STR_LIT:\n>'))<EOL><DEDENT>

Reads one line of input from the user.

        Parameters
        ----------
        prompt : str, optional
            The prompt to print before reading the line.

        callback : callable, optional
            A callback to execute with the read line. If not specified, input is
            read *synchronously* and this method does not return until it has
            been read.

        Returns
        -------
        If a callback is specified, returns nothing. Otherwise, returns the
        input string with the trailing newline stripped.


def _set_continuation_prompt(self, prompt, html=False):

if html:<EOL><INDENT>self._continuation_prompt_html = prompt<EOL><DEDENT>else:<EOL><INDENT>self._continuation_prompt = prompt<EOL>self._continuation_prompt_html = None<EOL><DEDENT>

Sets the continuation prompt.

        Parameters
        ----------
        prompt : str
            The prompt to show when more input is needed.

        html : bool, optional (default False)
            If set, the prompt will be inserted as formatted HTML. Otherwise,
            the prompt will be treated as plain text, though ANSI color codes
            will be handled.


self._control.setTextCursor(cursor)<EOL>

Convenience method to set the current cursor.


Scrolls the viewport so that the specified cursor is at the top.


def _show_prompt(self, prompt=None, html=False, newline=True):

<EOL>cursor = self._get_end_cursor()<EOL>self._append_before_prompt_pos = cursor.position()<EOL>if newline and cursor.position() > <NUM_LIT:0>:<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.Left,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>if cursor.selection().toPlainText() != '<STR_LIT:\n>':<EOL><INDENT>self._append_plain_text('<STR_LIT:\n>')<EOL><DEDENT><DEDENT>self._append_plain_text(self._prompt_sep)<EOL>if prompt is None:<EOL><INDENT>if self._prompt_html is None:<EOL><INDENT>self._append_plain_text(self._prompt)<EOL><DEDENT>else:<EOL><INDENT>self._append_html(self._prompt_html)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>if html:<EOL><INDENT>self._prompt = self._append_html_fetching_plain_text(prompt)<EOL>self._prompt_html = prompt<EOL><DEDENT>else:<EOL><INDENT>self._append_plain_text(prompt)<EOL>self._prompt = prompt<EOL>self._prompt_html = None<EOL><DEDENT><DEDENT>self._prompt_pos = self._get_end_cursor().position()<EOL>self._prompt_started()<EOL>

Writes a new prompt at the end of the buffer.

        Parameters
        ----------
        prompt : str, optional
            The prompt to show. If not specified, the previous prompt is used.

        html : bool, optional (default False)
            Only relevant when a prompt is specified. If set, the prompt will
            be inserted as formatted HTML. Otherwise, the prompt will be treated
            as plain text, though ANSI color codes will be handled.

        newline : bool, optional (default True)
            If set, a new line will be written before showing the prompt if
            there is not already a newline at the end of the buffer.


<EOL>document = self._control.document()<EOL>scrollbar = self._control.verticalScrollBar()<EOL>viewport_height = self._control.viewport().height()<EOL>if isinstance(self._control, QtGui.QPlainTextEdit):<EOL><INDENT>maximum = max(<NUM_LIT:0>, document.lineCount() - <NUM_LIT:1>)<EOL>step = viewport_height / self._control.fontMetrics().lineSpacing()<EOL><DEDENT>else:<EOL><INDENT>maximum = document.size().height()<EOL>step = viewport_height<EOL><DEDENT>diff = maximum - scrollbar.maximum()<EOL>scrollbar.setRange(<NUM_LIT:0>, maximum)<EOL>scrollbar.setPageStep(step)<EOL>if diff < <NUM_LIT:0> and document.blockCount() == document.maximumBlockCount():<EOL><INDENT>scrollbar.setValue(scrollbar.value() + diff)<EOL><DEDENT>

Expands the vertical scrollbar beyond the range set by Qt.


menu = self._context_menu_make(pos)<EOL>menu.exec_(self._control.mapToGlobal(pos))<EOL>

Shows a context menu at the given QPoint (in widget coordinates).


if not self.highlighting_on:<EOL><INDENT>return<EOL><DEDENT>current_block = self.currentBlock()<EOL>string = self._frontend._get_block_plain_text(current_block)<EOL>if current_block.contains(self._frontend._prompt_pos):<EOL><INDENT>prompt = self._frontend._prompt<EOL><DEDENT>else:<EOL><INDENT>prompt = self._frontend._continuation_prompt<EOL><DEDENT>if string.startswith(prompt):<EOL><INDENT>self._current_offset = len(prompt)<EOL>string = string[len(prompt):]<EOL>super(FrontendHighlighter, self).highlightBlock(string)<EOL><DEDENT>

Highlight a block of text. Reimplemented to highlight selectively.


old = self.highlighting_on<EOL>self.highlighting_on = True<EOL>super(FrontendHighlighter, self).rehighlightBlock(block)<EOL>self.highlighting_on = old<EOL>

Reimplemented to temporarily enable highlighting if disabled.


def setFormat(self, start, count, format):

start += self._current_offset<EOL>super(FrontendHighlighter, self).setFormat(start, count, format)<EOL>


if self._page_control is not None and self._page_control.hasFocus():<EOL><INDENT>self._page_control.copy()<EOL><DEDENT>elif self._control.hasFocus():<EOL><INDENT>text = self._control.textCursor().selection().toPlainText()<EOL>if text:<EOL><INDENT>lines = map(self._transform_prompt, text.splitlines())<EOL>text = '<STR_LIT:\n>'.join(lines)<EOL>QtGui.QApplication.clipboard().setText(text)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.log.debug("<STR_LIT>")<EOL><DEDENT>

Copy the currently selected text to the clipboard, removing prompts.


def _is_complete(self, source, interactive):

complete = self._input_splitter.push(source)<EOL>if interactive:<EOL><INDENT>complete = not self._input_splitter.push_accepts_more()<EOL><DEDENT>return complete<EOL>

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.


msg_id = self.kernel_manager.shell_channel.execute(source, hidden)<EOL>self._request_info['<STR_LIT>'][msg_id] = self._ExecutionRequest(msg_id, '<STR_LIT:user>')<EOL>self._hidden = hidden<EOL>if not hidden:<EOL><INDENT>self.executing.emit(source)<EOL><DEDENT>

Execute 'source'. If 'hidden', do not show any output.

        See parent class :meth:`execute` docstring for full details.


if not self._reading:<EOL><INDENT>self._highlighter.highlighting_on = True<EOL><DEDENT>


<EOL>self._input_splitter.reset()<EOL>if not self._reading:<EOL><INDENT>self._highlighter.highlighting_on = False<EOL><DEDENT>


<EOL>text = self._get_input_buffer_cursor_line()<EOL>if text is None:<EOL><INDENT>return False<EOL><DEDENT>complete = bool(text[:self._get_input_buffer_cursor_column()].strip())<EOL>if complete:<EOL><INDENT>self._complete()<EOL><DEDENT>return not complete<EOL>

Called when the tab key is pressed. Returns whether to continue
            processing the event.


menu = super(FrontendWidget, self)._context_menu_make(pos)<EOL>for before_action in menu.actions():<EOL><INDENT>if before_action.shortcut().matches(QtGui.QKeySequence.Paste) ==QtGui.QKeySequence.ExactMatch:<EOL><INDENT>menu.insertAction(before_action, self._copy_raw_action)<EOL>break<EOL><DEDENT><DEDENT>return menu<EOL>

Reimplemented to add an action for raw copy.


key = event.key()<EOL>if self._control_key_down(event.modifiers(), include_command=False):<EOL><INDENT>if key == QtCore.Qt.Key_C and self._executing:<EOL><INDENT>self.request_interrupt_kernel()<EOL>return True<EOL><DEDENT>elif key == QtCore.Qt.Key_Period:<EOL><INDENT>self.request_restart_kernel()<EOL>return True<EOL><DEDENT><DEDENT>elif not event.modifiers() & QtCore.Qt.AltModifier:<EOL><INDENT>if key == QtCore.Qt.Key_Backspace:<EOL><INDENT>col = self._get_input_buffer_cursor_column()<EOL>cursor = self._control.textCursor()<EOL>if col > <NUM_LIT:3> and not cursor.hasSelection():<EOL><INDENT>text = self._get_input_buffer_cursor_line()[:col]<EOL>if text.endswith('<STR_LIT:U+0020>') and not text.strip():<EOL><INDENT>cursor.movePosition(QtGui.QTextCursor.Left,<EOL>QtGui.QTextCursor.KeepAnchor, <NUM_LIT:4>)<EOL>cursor.removeSelectedText()<EOL>return True<EOL><DEDENT><DEDENT><DEDENT><DEDENT>return super(FrontendWidget, self)._event_filter_console_keypress(event)<EOL>

Reimplemented for execution interruption and smart backspace.


super(FrontendWidget, self)._insert_continuation_prompt(cursor)<EOL>cursor.insertText('<STR_LIT:U+0020>' * self._input_splitter.indent_spaces)<EOL>


self.log.debug("<STR_LIT>", rep.get('<STR_LIT:content>', '<STR_LIT>'))<EOL>cursor = self._get_cursor()<EOL>info = self._request_info.get('<STR_LIT>')<EOL>if info and info.id == rep['<STR_LIT>']['<STR_LIT>'] andinfo.pos == cursor.position():<EOL><INDENT>text = '<STR_LIT:.>'.join(self._get_context())<EOL>cursor.movePosition(QtGui.QTextCursor.Left, n=len(text))<EOL>self._complete_with_items(cursor, rep['<STR_LIT:content>']['<STR_LIT>'])<EOL><DEDENT>


def _silent_exec_callback(self, expr, callback):

<EOL>local_uuid = str(uuid.uuid1())<EOL>msg_id = self.kernel_manager.shell_channel.execute('<STR_LIT>',<EOL>silent=True, user_expressions={ local_uuid:expr })<EOL>self._callback_dict[local_uuid] = callback<EOL>self._request_info['<STR_LIT>'][msg_id] = self._ExecutionRequest(msg_id, '<STR_LIT>')<EOL>

Silently execute `expr` in the kernel and call `callback` with reply

        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
            function accepting one argument, as a string. The string will be
            the `repr` of the result of evaluating `expr`

        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.

        See Also
        --------
        _handle_exec_callback : private method, deal with calling callback with reply


user_exp = msg['<STR_LIT:content>'].get('<STR_LIT>')<EOL>if not user_exp:<EOL><INDENT>return<EOL><DEDENT>for expression in user_exp:<EOL><INDENT>if expression in self._callback_dict:<EOL><INDENT>self._callback_dict.pop(expression)(user_exp[expression])<EOL><DEDENT><DEDENT>

Execute `callback` corresponding to `msg` reply, after ``_silent_exec_callback``

        Parameters
        ----------
        msg : raw message send by the kernel containing an `user_expressions`
                and having a 'silent_exec_callback' kind.

        Notes
        -----
        This function will look for a `callback` associated with the
        corresponding message id. Association has been made by
        `_silent_exec_callback`. `callback` is then called with the `repr()`
        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.


self.log.debug("<STR_LIT>", msg.get('<STR_LIT:content>', '<STR_LIT>'))<EOL>msg_id = msg['<STR_LIT>']['<STR_LIT>']<EOL>info = self._request_info['<STR_LIT>'].get(msg_id)<EOL>self._reading = False<EOL>if info and info.kind == '<STR_LIT:user>' and not self._hidden:<EOL><INDENT>self.kernel_manager.sub_channel.flush()<EOL>if self.ansi_codes:<EOL><INDENT>self._ansi_processor.reset_sgr()<EOL><DEDENT>content = msg['<STR_LIT:content>']<EOL>status = content['<STR_LIT:status>']<EOL>if status == '<STR_LIT>':<EOL><INDENT>self._process_execute_ok(msg)<EOL><DEDENT>elif status == '<STR_LIT:error>':<EOL><INDENT>self._process_execute_error(msg)<EOL><DEDENT>elif status == '<STR_LIT>':<EOL><INDENT>self._process_execute_abort(msg)<EOL><DEDENT>self._show_interpreter_prompt_for_reply(msg)<EOL>self.executed.emit(msg)<EOL>self._request_info['<STR_LIT>'].pop(msg_id)<EOL><DEDENT>elif info and info.kind == '<STR_LIT>' and not self._hidden:<EOL><INDENT>self._handle_exec_callback(msg)<EOL>self._request_info['<STR_LIT>'].pop(msg_id)<EOL><DEDENT>else:<EOL><INDENT>super(FrontendWidget, self)._handle_execute_reply(msg)<EOL><DEDENT>


self.log.debug("<STR_LIT>", msg.get('<STR_LIT:content>', '<STR_LIT>'))<EOL>if self._hidden:<EOL><INDENT>raise RuntimeError('<STR_LIT>')<EOL><DEDENT>self.kernel_manager.sub_channel.flush()<EOL>def callback(line):<EOL><INDENT>self.kernel_manager.stdin_channel.input(line)<EOL><DEDENT>if self._reading:<EOL><INDENT>self.log.debug("<STR_LIT>")<EOL>self._reading = False<EOL><DEDENT>self._readline(msg['<STR_LIT:content>']['<STR_LIT>'], callback=callback)<EOL>


self.log.debug("<STR_LIT>", since_last_heartbeat)<EOL>if self.custom_restart:<EOL><INDENT>self.custom_restart_kernel_died.emit(since_last_heartbeat)<EOL><DEDENT>else:<EOL><INDENT>message = '<STR_LIT>''<STR_LIT>''<STR_LIT>' %since_last_heartbeat<EOL>self.restart_kernel(message, now=True)<EOL><DEDENT>

Handle the kernel's death by asking if the user wants to restart.


self.log.debug("<STR_LIT>", rep.get('<STR_LIT:content>', '<STR_LIT>'))<EOL>cursor = self._get_cursor()<EOL>info = self._request_info.get('<STR_LIT>')<EOL>if info and info.id == rep['<STR_LIT>']['<STR_LIT>'] andinfo.pos == cursor.position():<EOL><INDENT>content = rep['<STR_LIT:content>']<EOL>if content.get('<STR_LIT>', False):<EOL><INDENT>call_info, doc = None, None<EOL><DEDENT>else:<EOL><INDENT>call_info, doc = call_tip(content, format_call=True)<EOL><DEDENT>if call_info or doc:<EOL><INDENT>self._call_tip_widget.show_call_info(call_info, doc)<EOL><DEDENT><DEDENT>


self.log.debug("<STR_LIT>", msg.get('<STR_LIT:content>', '<STR_LIT>'))<EOL>if not self._hidden and self._is_from_this_session(msg):<EOL><INDENT>text = msg['<STR_LIT:content>']['<STR_LIT:data>']<EOL>self._append_plain_text(text + '<STR_LIT:\n>', before_prompt=True)<EOL><DEDENT>


self.log.debug("<STR_LIT>", msg.get('<STR_LIT:content>', '<STR_LIT>'))<EOL>if not self._hidden and self._is_from_this_session(msg):<EOL><INDENT>text = msg['<STR_LIT:content>']['<STR_LIT:data>'].expandtabs(<NUM_LIT:8>)<EOL>self._append_plain_text(text, before_prompt=True)<EOL>self._control.moveCursor(QtGui.QTextCursor.End)<EOL><DEDENT>


self.log.debug("<STR_LIT>", msg.get('<STR_LIT:content>', '<STR_LIT>'))<EOL>if not self._hidden and not self._is_from_this_session(msg):<EOL><INDENT>if self._local_kernel:<EOL><INDENT>if not msg['<STR_LIT:content>']['<STR_LIT>']:<EOL><INDENT>self.exit_requested.emit(self)<EOL><DEDENT>else:<EOL><INDENT>time.sleep(<NUM_LIT>) <EOL>self.reset()<EOL><DEDENT><DEDENT>else: <EOL><INDENT>title = self.window().windowTitle()<EOL>if not msg['<STR_LIT:content>']['<STR_LIT>']:<EOL><INDENT>reply = QtGui.QMessageBox.question(self, title,<EOL>"<STR_LIT>"<EOL>"<STR_LIT>",<EOL>QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)<EOL>if reply == QtGui.QMessageBox.Yes:<EOL><INDENT>self.exit_requested.emit(self)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>reply = QtGui.QMessageBox.question(self, title,<EOL>"<STR_LIT>",<EOL>QtGui.QMessageBox.Yes,QtGui.QMessageBox.No)<EOL>if reply == QtGui.QMessageBox.Yes:<EOL><INDENT>time.sleep(<NUM_LIT>) <EOL>self.reset()<EOL><DEDENT><DEDENT><DEDENT><DEDENT>

Handle shutdown signal, only if from other console.


self.reset(clear=True)<EOL>

Called when the KernelManager channels have started listening or
            when the frontend is assigned an already listening KernelManager.


Copy the currently selected text to the clipboard without attempting
            to remove prompts or otherwise alter the text.


def execute_file(self, path, hidden=False):

self.execute('<STR_LIT>' % path, hidden=hidden)<EOL>

Attempts to execute file with 'path'. If 'hidden', no output is
            shown.


if self.custom_interrupt:<EOL><INDENT>self._reading = False<EOL>self.custom_interrupt_requested.emit()<EOL><DEDENT>elif self.kernel_manager.has_kernel:<EOL><INDENT>self._reading = False<EOL>self.kernel_manager.interrupt_kernel()<EOL><DEDENT>else:<EOL><INDENT>self._append_plain_text('<STR_LIT>'<EOL>'<STR_LIT>')<EOL><DEDENT>

Attempts to interrupt the running kernel.

        Also unsets _reading flag, to avoid runtime errors
        if raw_input is called again.


if self._executing:<EOL><INDENT>self._executing = False<EOL>self._request_info['<STR_LIT>'] = {}<EOL><DEDENT>self._reading = False<EOL>self._highlighter.highlighting_on = False<EOL>if self.clear_on_kernel_restart or clear:<EOL><INDENT>self._control.clear()<EOL>self._append_plain_text(self.banner)<EOL><DEDENT>else:<EOL><INDENT>self._append_plain_text("<STR_LIT>")<EOL>self._append_html("<STR_LIT>")<EOL><DEDENT>self._append_before_prompt_pos = self._get_cursor().position()<EOL>self._show_interpreter_prompt()<EOL>

Resets the widget to its initial state if ``clear`` parameter or
        ``clear_on_kernel_restart`` configuration setting is True, otherwise
        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
        was restarted.  With ``clear=True``, it is similar to ``%clear``, but
        also re-writes the banner and aborts execution if necessary.


def restart_kernel(self, message, now=False):

<EOL>if self.custom_restart:<EOL><INDENT>self.custom_restart_requested.emit()<EOL><DEDENT>elif self.kernel_manager.has_kernel:<EOL><INDENT>self.kernel_manager.hb_channel.pause()<EOL>if self.confirm_restart:<EOL><INDENT>buttons = QtGui.QMessageBox.Yes | QtGui.QMessageBox.No<EOL>result = QtGui.QMessageBox.question(self, '<STR_LIT>',<EOL>message, buttons)<EOL>do_restart = result == QtGui.QMessageBox.Yes<EOL><DEDENT>else:<EOL><INDENT>do_restart = True<EOL><DEDENT>if do_restart:<EOL><INDENT>try:<EOL><INDENT>self.kernel_manager.restart_kernel(now=now)<EOL><DEDENT>except RuntimeError:<EOL><INDENT>self._append_plain_text('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>before_prompt=True<EOL>)<EOL><DEDENT>else:<EOL><INDENT>self.reset()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self.kernel_manager.hb_channel.unpause()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>self._append_plain_text('<STR_LIT>'<EOL>'<STR_LIT>',<EOL>before_prompt=True<EOL>)<EOL><DEDENT>


<EOL>if not self.enable_calltips:<EOL><INDENT>return False<EOL><DEDENT>cursor = self._get_cursor()<EOL>cursor.movePosition(QtGui.QTextCursor.Left)<EOL>if cursor.document().characterAt(cursor.position()) != '<STR_LIT:(>':<EOL><INDENT>return False<EOL><DEDENT>context = self._get_context(cursor)<EOL>if not context:<EOL><INDENT>return False<EOL><DEDENT>name = '<STR_LIT:.>'.join(context)<EOL>msg_id = self.kernel_manager.shell_channel.object_info(name)<EOL>pos = self._get_cursor().position()<EOL>self._request_info['<STR_LIT>'] = self._CallTipRequest(msg_id, pos)<EOL>return True<EOL>

Shows a call tip, if appropriate, at the current cursor location.


context = self._get_context()<EOL>if context:<EOL><INDENT>msg_id = self.kernel_manager.shell_channel.complete(<EOL>'<STR_LIT:.>'.join(context),                       <EOL>self._get_input_buffer_cursor_line(),    <EOL>self._get_input_buffer_cursor_column(),  <EOL>self.input_buffer)                       <EOL>pos = self._get_cursor().position()<EOL>info = self._CompletionRequest(msg_id, pos)<EOL>self._request_info['<STR_LIT>'] = info<EOL><DEDENT>

Performs completion at the current cursor location.


if cursor is None:<EOL><INDENT>cursor = self._get_cursor()<EOL><DEDENT>cursor.movePosition(QtGui.QTextCursor.StartOfBlock,<EOL>QtGui.QTextCursor.KeepAnchor)<EOL>text = cursor.selection().toPlainText()<EOL>return self._completion_lexer.get_context(text)<EOL>

Gets the context for the specified cursor (or the current cursor
            if none is specified).


self._append_plain_text("<STR_LIT>")<EOL>

Process a reply for an aborted execution request.


content = msg['<STR_LIT:content>']<EOL>if content['<STR_LIT>']=='<STR_LIT>':<EOL><INDENT>keepkernel = content['<STR_LIT>']=='<STR_LIT>' or content['<STR_LIT>']=='<STR_LIT:True>'<EOL>self._keep_kernel_on_exit = keepkernel<EOL>self.exit_requested.emit(self)<EOL><DEDENT>else:<EOL><INDENT>traceback = '<STR_LIT>'.join(content['<STR_LIT>'])<EOL>self._append_plain_text(traceback)<EOL><DEDENT>

Process a reply for an execution request that resulted in an error.


payload = msg['<STR_LIT:content>']['<STR_LIT>']<EOL>for item in payload:<EOL><INDENT>if not self._process_execute_payload(item):<EOL><INDENT>warning = '<STR_LIT>'<EOL>print(warning % repr(item['<STR_LIT:source>']))<EOL><DEDENT><DEDENT>

Process a reply for a successful execution request.


<EOL>return False<EOL>

Process a single payload item from the list of payload items in an
            execution reply. Returns whether the payload was handled.


Shows a prompt for the interpreter given an 'execute_reply' message.


def _document_contents_change(self, position, removed, added):

<EOL>position += added<EOL>document = self._control.document()<EOL>if position == self._get_cursor().position():<EOL><INDENT>self._call_tip()<EOL><DEDENT>

Called whenever the document's content changes. Display a call tip
            if appropriate.


banner = '<STR_LIT>''<STR_LIT>'<EOL>return banner % (sys.version, sys.platform)<EOL>


assert isinstance(console_widget._control, (QtGui.QTextEdit, QtGui.QPlainTextEdit))<EOL>super(CompletionPlain, self).__init__()<EOL>self._text_edit = console_widget._control<EOL>self._console_widget = console_widget<EOL>self._text_edit.installEventFilter(self)<EOL>

Create a completion widget that is attached to the specified Qt
            text edit widget.


if obj == self._text_edit:<EOL><INDENT>etype = event.type()<EOL>if etype in( QtCore.QEvent.KeyPress, QtCore.QEvent.FocusOut ):<EOL><INDENT>self.cancel_completion()<EOL><DEDENT><DEDENT>return super(CompletionPlain, self).eventFilter(obj, event)<EOL>

Reimplemented to handle keyboard input and to auto-hide when the
            text edit loses focus.


self._console_widget._clear_temporary_buffer()<EOL>

Cancel the completion, reseting internal variable, clearing buffer


if not items :<EOL><INDENT>return<EOL><DEDENT>self.cancel_completion()<EOL>strng = text.columnize(items)<EOL>self._console_widget._fill_temporary_buffer(cursor, strng, html=False)<EOL>

Shows the completion widget with 'items' at the position specified
            by 'cursor'.


ip = self.ip if self.ip in LOCAL_IPS else LOCALHOST<EOL>kernel_manager = self.kernel_manager_class(<EOL>ip=ip,<EOL>connection_file=self._new_connection_file(),<EOL>config=self.config,<EOL>)<EOL>kwargs = dict()<EOL>kwargs['<STR_LIT>'] = self.kernel_argv<EOL>kernel_manager.start_kernel(**kwargs)<EOL>kernel_manager.start_channels()<EOL>widget = self.widget_factory(config=self.config,<EOL>local_kernel=True)<EOL>self.init_colors(widget)<EOL>widget.kernel_manager = kernel_manager<EOL>widget._existing = False<EOL>widget._may_close = True<EOL>widget._confirm_exit = self.confirm_exit<EOL>return widget<EOL>

Create and return new frontend attached to new kernel, launched on localhost.


kernel_manager = self.kernel_manager_class(<EOL>connection_file=current_widget.kernel_manager.connection_file,<EOL>config = self.config,<EOL>)<EOL>kernel_manager.load_connection_file()<EOL>kernel_manager.start_channels()<EOL>widget = self.widget_factory(config=self.config,<EOL>local_kernel=False)<EOL>self.init_colors(widget)<EOL>widget._existing = True<EOL>widget._may_close = False<EOL>widget._confirm_exit = False<EOL>widget.kernel_manager = kernel_manager<EOL>return widget<EOL>

Create and return a new frontend attached to an existing kernel.

        Parameters
        ----------
        current_widget : IPythonWidget
            The IPythonWidget whose kernel this frontend is to share


<EOL>try:<EOL><INDENT>colors = self.config.ZMQInteractiveShell.colors<EOL><DEDENT>except AttributeError:<EOL><INDENT>colors = None<EOL><DEDENT>try:<EOL><INDENT>style = self.config.IPythonWidget.syntax_style<EOL><DEDENT>except AttributeError:<EOL><INDENT>style = None<EOL><DEDENT>try:<EOL><INDENT>sheet = self.config.IPythonWidget.style_sheet<EOL><DEDENT>except AttributeError:<EOL><INDENT>sheet = None<EOL><DEDENT>if colors:<EOL><INDENT>colors=colors.lower()<EOL>if colors in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>colors='<STR_LIT>'<EOL><DEDENT>elif colors in ('<STR_LIT>', '<STR_LIT>'):<EOL><INDENT>colors='<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>colors='<STR_LIT>'<EOL><DEDENT><DEDENT>elif style:<EOL><INDENT>if style=='<STR_LIT>':<EOL><INDENT>colors='<STR_LIT>'<EOL><DEDENT>elif styles.dark_style(style):<EOL><INDENT>colors='<STR_LIT>'<EOL><DEDENT>else:<EOL><INDENT>colors='<STR_LIT>'<EOL><DEDENT><DEDENT>else:<EOL><INDENT>colors=None<EOL><DEDENT>if style:<EOL><INDENT>widget.style_sheet = styles.sheet_from_template(style, colors)<EOL>widget.syntax_style = style<EOL>widget._syntax_style_changed()<EOL>widget._style_sheet_changed()<EOL><DEDENT>elif colors:<EOL><INDENT>widget.set_default_style(colors=colors)<EOL><DEDENT>if self.stylesheet:<EOL><INDENT>if os.path.isfile(self.stylesheet):<EOL><INDENT>with open(self.stylesheet) as f:<EOL><INDENT>sheet = f.read()<EOL><DEDENT><DEDENT>else:<EOL><INDENT>raise IOError("<STR_LIT>" % self.stylesheet)<EOL><DEDENT><DEDENT>if sheet:<EOL><INDENT>widget.style_sheet = sheet<EOL>widget._style_sheet_changed()<EOL><DEDENT>


signal.signal(signal.SIGINT, lambda sig, frame: self.exit(-<NUM_LIT:2>))<EOL>timer = QtCore.QTimer()<EOL>timer.timeout.connect(lambda: None)<EOL>timer.start(<NUM_LIT:200>)<EOL>self._sigint_timer = timer<EOL>


text_edit = console_widget._control<EOL>assert isinstance(text_edit, (QtGui.QTextEdit, QtGui.QPlainTextEdit))<EOL>super(CompletionWidget, self).__init__()<EOL>self._text_edit = text_edit<EOL>self.setAttribute(QtCore.Qt.WA_StaticContents)<EOL>self.setWindowFlags(QtCore.Qt.ToolTip | QtCore.Qt.WindowStaysOnTopHint)<EOL>self.setFocusProxy(self._text_edit)<EOL>self.setFrameShadow(QtGui.QFrame.Plain)<EOL>self.setFrameShape(QtGui.QFrame.StyledPanel)<EOL>self.itemActivated.connect(self._complete_current)<EOL>


if obj == self._text_edit:<EOL><INDENT>etype = event.type()<EOL>if etype == QtCore.QEvent.KeyPress:<EOL><INDENT>key, text = event.key(), event.text()<EOL>if key in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter,<EOL>QtCore.Qt.Key_Tab):<EOL><INDENT>self._complete_current()<EOL>return True<EOL><DEDENT>elif key == QtCore.Qt.Key_Escape:<EOL><INDENT>self.hide()<EOL>return True<EOL><DEDENT>elif key in (QtCore.Qt.Key_Up, QtCore.Qt.Key_Down,<EOL>QtCore.Qt.Key_PageUp, QtCore.Qt.Key_PageDown,<EOL>QtCore.Qt.Key_Home, QtCore.Qt.Key_End):<EOL><INDENT>self.keyPressEvent(event)<EOL>return True<EOL><DEDENT><DEDENT>elif etype == QtCore.QEvent.FocusOut:<EOL><INDENT>self.hide()<EOL><DEDENT><DEDENT>return super(CompletionWidget, self).eventFilter(obj, event)<EOL>


super(CompletionWidget, self).hideEvent(event)<EOL>self._text_edit.cursorPositionChanged.disconnect(self._update_current)<EOL>self._text_edit.removeEventFilter(self)<EOL>

Reimplemented to disconnect signal handlers and event filter.


super(CompletionWidget, self).showEvent(event)<EOL>self._text_edit.cursorPositionChanged.connect(self._update_current)<EOL>self._text_edit.installEventFilter(self)<EOL>

Reimplemented to connect signal handlers and event filter.


text_edit = self._text_edit<EOL>point = text_edit.cursorRect(cursor).bottomRight()<EOL>point = text_edit.mapToGlobal(point)<EOL>height = self.sizeHint().height()<EOL>screen_rect = QtGui.QApplication.desktop().availableGeometry(self)<EOL>if screen_rect.size().height() - point.y() - height < <NUM_LIT:0>:<EOL><INDENT>point = text_edit.mapToGlobal(text_edit.cursorRect().topRight())<EOL>point.setY(point.y() - height)<EOL><DEDENT>self.move(point)<EOL>self._start_position = cursor.position()<EOL>self.clear()<EOL>self.addItems(items)<EOL>self.setCurrentRow(<NUM_LIT:0>)<EOL>self.show()<EOL>