示例#1
0
 def attrsToList(self, attrs):
     '''
     Convert the attributes to a list of g.Bunches.
     attrs: an Attributes item passed to startElement.
     '''
     return [g.Bunch(name=name, val=attrs.getValue(name))
         for name in attrs.getNames()]
示例#2
0
 def registerOneHandler(self, tag, fn):
     """Register one handler"""
     try:
         moduleName = self.loadingModuleNameStack[-1]
     except IndexError:
         moduleName = '<no module>'
     # print(f"{g.unitTesting:6} {moduleName:15} {tag:25} {fn.__name__}")
     items = self.handlers.get(tag, [])
     functions = [z.fn for z in items]
     if fn not in functions:  # Vitalije
         bunch = g.Bunch(fn=fn, moduleName=moduleName, tag='handler')
         items.append(bunch)
     self.handlers[tag] = items
示例#3
0
 def registerOneHandler(self, tag, fn):
     """Register one handler"""
     try:
         moduleName = self.loadingModuleNameStack[-1]
     except IndexError:
         moduleName = '<no module>'
     if 0:
         if g.app.unitTesting: g.pr('')
         g.pr('%6s %15s %25s %s' % (g.app.unitTesting, moduleName, tag, fn.__name__))
     items = self.handlers.get(tag, [])
     if fn not in items:
         bunch = g.Bunch(fn=fn, moduleName=moduleName, tag='handler')
         items.append(bunch)
     self.handlers[tag] = items
示例#4
0
def computeVnodeInfoDict(c):
    """
    We don't know yet which nodes will be affected by the paste, so we remember
    everything. This is expensive, but foolproof.
    
    The alternative is to try to remember the 'before' values of nodes in the
    FileCommands read logic. Several experiments failed, and the code is very ugly.
    In short, it seems wise to do things the foolproof way.
    """
    d = {}
    for v in c.all_unique_nodes():
        if v not in d:
            d[v] = g.Bunch(v=v, head=v.h, body=v.b)
    return d
示例#5
0
 def registerOneExclusiveHandler(self, tag, fn):
     """Register one exclusive handler"""
     try:
         moduleName = self.loadingModuleNameStack[-1]
     except IndexError:
         moduleName = '<no module>'
     if 0:
         if g.app.unitTesting: g.pr('')
         g.pr('%6s %15s %25s %s' % (g.app.unitTesting, moduleName, tag, fn.__name__))
     if g.app.unitTesting: return
     if tag in self.handlers:
         g.es("*** Two exclusive handlers for", "'%s'" % (tag))
     else:
         bunch = g.Bunch(fn=fn, moduleName=moduleName, tag='handler')
         self.handlers[tag] = [bunch] # Vitalije
示例#6
0
 def registerOneExclusiveHandler(self, tag, fn):
     """Register one exclusive handler"""
     try:
         moduleName = self.loadingModuleNameStack[-1]
     except IndexError:
         moduleName = '<no module>'
     if 0:
         if g.app.unitTesting: g.pr('')
         g.pr(f"{g.app.unitTesting:6} {moduleName:15} {tag:25} {fn.__name__}")
     if g.app.unitTesting: return
     if tag in self.handlers:
         g.es(f"*** Two exclusive handlers for '{tag}'")
     else:
         bunch = g.Bunch(fn=fn, moduleName=moduleName, tag='handler')
         self.handlers[tag] = [bunch]  # Vitalije
示例#7
0
 def registerOneExclusiveHandler(self, tag, fn):
     """Register one exclusive handler"""
     try:
         moduleName = self.loadingModuleNameStack[-1]
     except IndexError:
         moduleName = '<no module>'
     # print(f"{g.unitTesting:6} {moduleName:15} {tag:25} {fn.__name__}")
     if g.unitTesting:
         return
     if tag in self.handlers:
         g.es(f"*** Two exclusive handlers for '{tag}'")
     else:
         bunch = g.Bunch(fn=fn, moduleName=moduleName, tag='handler')
         aList = self.handlers.get(tag, [])
         aList.append(bunch)
         self.handlers[tag] = aList
示例#8
0
 def beginCommand(self, w, undoType='Typing'):
     """Do the common processing at the start of each command."""
     c, p, u = self.c, self.c.p, self.c.undoer
     name = c.widget_name(w)
     if name.startswith('body'):
         self.undoData = b = g.Bunch()
         # To keep pylint happy.
         b.ch = ''
         b.name = name
         b.oldSel = w.getSelectionRange()
         b.oldText = p.b
         b.w = w
         b.undoType = undoType
         b.undoer_bunch = u.beforeChangeBody(p)  # #1733.
     else:
         self.undoData = None
     return w
示例#9
0
 def beginCommand(self, w, undoType='Typing'):
     '''Do the common processing at the start of each command.'''
     c, p = self.c, self.c.p
     name = c.widget_name(w)
     if name.startswith('body'):
         oldSel = w.getSelectionRange()
         oldText = p.b
         self.undoData = b = g.Bunch()
         # To keep pylint happy.
         b.ch = ''
         b.name = name
         b.oldSel = oldSel
         b.oldText = oldText
         b.w = w
         b.undoType = undoType
     else:
         self.undoData = None
     return w
示例#10
0
 def chapterSelectHelper(self, w=None, selectEditor=True):
     trace = False and not g.unitTesting
     c, cc = self.c, self.cc
     if trace: g.trace('-----------', self, 'w:', bool(w))
     cc.selectedChapter = self
     if self.name == 'main':
         return  # 2016/04/20
     # Remember the root (it may have changed) for dehoist.
     self.root = root = self.findRootNode()
     if not root:
         # Might happen during unit testing or startup.
         return
     if self.p and not c.positionExists(self.p):
         self.p = p = root.copy()
         if trace: g.trace('switch to root', self)
     # Next, recompute p and possibly select a new editor.
     if w:
         assert w == c.frame.body.wrapper
         assert w.leo_p
         self.p = p = self.findPositionInChapter(w.leo_p) or root.copy()
         if trace: g.trace('recomputed1:', self)
     else:
         # This must be done *after* switching roots.
         self.p = p = self.findPositionInChapter(self.p) or root.copy()
         if trace: g.trace('recomputed2', self)
         if selectEditor:
             # Careful: c.selectPosition would pop the hoist stack.
             w = self.findEditorInChapter(p)
             c.frame.body.selectEditor(w)  # Switches text.
             self.p = p  # 2016/04/20: Apparently essential.
         if trace: g.trace('recomputed3', self)
     if g.match_word(p.h, 0, '@chapter'):
         if p.hasChildren():
             self.p = p = p.firstChild()
         else:
             # 2016/04/20: Create a dummy first child.
             self.p = p = p.insertAsLastChild()
             p.h = 'New Headline'
             if trace: g.trace('inserted child of @chapter node', p.h)
     c.hoistStack.append(g.Bunch(p=root.copy(), expanded=True))
     # Careful: c.selectPosition would pop the hoist stack.
     if trace: g.trace('done:', self)
     c.setCurrentPosition(p)
     g.doHook('hoist-changed', c=c)
示例#11
0
    def __init__(self, c, chapterController, name):

        self.c = c
        self.cc = cc = chapterController
        self.hoistStack = []
        self.name = name
        self.selectLockout = False  # True: in chapter.select logic.

        # State variables: saved/restored when the chapter is unselected/selected.
        if self.name == 'main':
            self.p = c.p or c.rootPosition()
        else:
            self.p = None  # Set later.
            root = self.root()
            self.hoistStack.append(
                g.Bunch(p=root and root.copy(), expanded=True))

        if cc.tt:
            # g.trace('(chapter) calling cc.tt.createTab(%s)' % (name))
            cc.tt.createTab(name)
示例#12
0
def hoist(self, event=None):
    """Make only the selected outline visible."""
    c = self
    p = c.p
    if not p:
        return
    # Don't hoist an @chapter node.
    if c.chapterController and p.h.startswith('@chapter '):
        if not g.unitTesting:
            g.es('can not hoist an @chapter node.', color='blue')
        return
    # Remember the expansion state.
    bunch = g.Bunch(p=p.copy(), expanded=p.isExpanded())
    c.hoistStack.append(bunch)
    p.expand()
    c.redraw(p)
    c.frame.clearStatusLine()
    c.frame.putStatusLine("Hoist: " + p.h)
    c.undoer.afterHoist(p, 'Hoist')
    g.doHook('hoist-changed', c=c)
示例#13
0
 def chapterSelectHelper(self, w=None, selectEditor=True):
     trace = False and not g.unitTesting
     c, cc, name = self.c, self.cc, self.name
     if trace:
         g.trace('%s exists: %s p: %s' % (
             name, c.positionExists(self.p), self.p))
     cc.selectedChapter = self
     root = self.findRootNode()
     if not root:
         return # New. Might happen during unit testing or startup.
     if self.p and not c.positionExists(self.p):
         self.p = root.copy()
         if trace: g.trace('*** switching to root', self.p)
     p = self.p
     # Next, recompute p and possibly select a new editor.
     if w:
         assert w == c.frame.body.wrapper
         assert w.leo_p
         self.p = p = self.findPositionInChapter(w.leo_p) or root.copy()
         if trace: g.trace('recomputed: %s' % (self.p))
     else:
         # This must be done *after* switching roots.
         self.p = p = self.findPositionInChapter(p) or root.copy()
         if trace: g.trace('recomputed: %s' % (self.p))
         if selectEditor:
             c.selectPosition(p)
             w = self.findEditorInChapter(p)
             c.frame.body.selectEditor(w) # Switches text.
     if name != 'main' and g.match_word(p.h, 0, '@chapter'):
         if p.hasChildren():
             p = p.firstChild()
         else:
             if trace: g.trace('can not happen: no child of @chapter node')
     chaptersNode = cc.findChaptersNode()
     if name == 'main' and chaptersNode:
         chaptersNode.contract()
     if name != 'main':
         c.hoistStack.append(g.Bunch(p=root and root.copy(), expanded=True))
     c.selectPosition(p)
     g.doHook('hoist-changed', c=c)
     c.redraw_now(p)
示例#14
0
    def get_settings(self) -> Any:
        """
        Return a g.bunch representing all widget values.

        Similar to LeoFind.default_settings, but only for find-tab values.
        """
        return g.Bunch(
            # Find/change strings...
            find_text=self.find_findbox.text(),
            change_text=self.find_replacebox.text(),
            # Find options...
            ignore_case=self.check_box_ignore_case.isChecked(),
            mark_changes=self.check_box_mark_changes.isChecked(),
            mark_finds=self.check_box_mark_finds.isChecked(),
            node_only=self.radio_button_node_only.isChecked(),
            pattern_match=self.check_box_regexp.isChecked(),
            search_body=self.check_box_search_body.isChecked(),
            search_headline=self.check_box_search_headline.isChecked(),
            suboutline_only=self.radio_button_suboutline_only.isChecked(),
            whole_word=self.check_box_whole_word.isChecked(),
        )
示例#15
0
 def handleClick(url, w=w):
     event = g.Bunch(c=c, w=w)
     g.openUrlOnClick(event, url=url)
示例#16
0
 def handleClick(url, w=w):
     import leo.plugins.qt_text as qt_text
     wrapper = qt_text.QTextEditWrapper(w, name='vr-body', c=c)
     event = g.Bunch(c=c, w=wrapper)
     g.openUrlOnClick(event, url=url)
示例#17
0
class ConfigShim(config_base):
    def __init__(self):
        config_base.__init__(self)
        g.pr('\n===== ConfigShim: new_config: %s\n' % new_config)
        self.setObjectName('ConfigShim')

    if new_config:
        #@+<< define bunch settings >>
        #@+node:ekr.20190331082353.1: *3* << define bunch settings >>
        # '(\w+)': With: \1 =

        advanced = g.Bunch(
            autoCompDelay=200,
            fileExtensionsToLoadFromDir='py,pyw,pyx,txt,bat',
            find_autoHide_timeout=10,
            homeAndEndWorkOnDisplayedLine=0,
            shellMaxLines=10000,
            titleText='{fileName} ({fullPath}) - Interactive Editor for Python',
        )

        settings = g.Bunch(
            allowFloatingShell=0,
            autoCallTip=1,
            autoClose_Brackets=1,
            autoClose_Quotes=1,
            autoComplete=1,
            autoComplete_acceptKeys='Tab',
            autoComplete_caseSensitive=0,
            autoComplete_fillups='\n',
            autoComplete_keywords=1,
            autoIndent=1,
            changeDirOnFileExec=0,
            defaultIndentUsingSpaces=1,
            defaultIndentWidth=4,
            defaultLineEndings='CRLF',
            defaultStyle='python',
            justificationWidth=70,
            language='English (US)',
            removeTrailingWhitespaceWhenSaving=0,
        )

        shellConfigs2 = [
            g.Bunch(
                argv='',
                environ='',
                exe='c:\\anaconda3\\python.exe',
                gui='auto',
                ipython='yes',
                name='Python',
                projectPath='',
                pythonPath='',
                scriptFile='',
                startDir='',
                startupScript='',
            )
        ]

        shortcuts2 = g.bunch(
            #@+<< define bunch shortcuts2 >>
            #@+node:ekr.20190331082549.1: *4* << define bunch shortcuts2 >>
            edit__comment='Ctrl+R,',
            edit__copy='Ctrl+C,Ctrl+Insert',
            edit__cut='Ctrl+X,Shift+Delete',
            edit__dedent='Shift+Tab,',
            edit__delete_line='Ctrl+D,',
            edit__duplicate_line='Ctrl+Shift+D,',
            edit__find_next='Ctrl+G,F3',
            edit__find_or_replace='Ctrl+F,',
            edit__find_previous='Ctrl+Shift+G,Shift+F3',
            edit__find_selection='Ctrl+F3,',
            edit__find_selection_backward='Ctrl+Shift+F3,',
            edit__indent='Tab,',
            edit__justify_commentdocstring='Ctrl+J,',
            edit__paste='Ctrl+V,Shift+Insert',
            edit__paste_and_select='Ctrl+Shift+V',
            edit__redo='Ctrl+Y,',
            edit__select_all='Ctrl+A,',
            edit__toggle_breakpoint='Ctrl+B,',
            edit__uncomment='Ctrl+T,',
            edit__undo='Ctrl+Z,',
            file__close='Ctrl+W,',
            file__new='Ctrl+N,',
            file__open='Ctrl+O,',
            file__save='Ctrl+S,',
            run__execute_cell='Ctrl+Return,Ctrl+Enter',
            run__execute_cell_and_advance='Ctrl+Shift+Return,Ctrl+Shift+Enter',
            run__execute_file='Ctrl+E,F5',
            run__execute_main_file='Ctrl+M,F6',
            run__execute_selection='Alt+Return,F9',
            run__execute_selection_and_advance='Shift+F9,Shift+Alt+Return',
            run__run_file_as_script='Ctrl+Shift+E,Ctrl+F5',
            run__run_main_file_as_script='Ctrl+Shift+M,Ctrl+F6',
            shell__clear_screen='Ctrl+L,',
            shell__close='Alt+K,',
            shell__create_shell_1_='Ctrl+1,',
            shell__create_shell_2_='Ctrl+2,',
            shell__create_shell_3_='Ctrl+3,',
            shell__create_shell_4_='Ctrl+4,',
            shell__create_shell_5_='Ctrl+5,',
            shell__create_shell_6_='Ctrl+6,',
            shell__create_shell_7_='Ctrl+7,',
            shell__create_shell_8_='Ctrl+8,',
            shell__interrupt='Ctrl+I,Meta+C',
            shell__postmortem_debug_from_last_traceback='Ctrl+P,',
            shell__restart='Ctrl+K,',
            shell__terminate='Ctrl+Shift+K,',
            view__select_editor='Ctrl+9,F2',
            view__select_previous_file='Ctrl+Tab,',
            view__select_shell='Ctrl+0,F1',
            view__zooming__zoom_in='Ctrl+=,Ctrl++',
            view__zooming__zoom_out='Ctrl+-,',
            view__zooming__zoom_reset='Ctrl+\\,'
            #@-<< define bunch shortcuts2 >>
        )

        state = g.Bunch(
            editorState2=[
                #@+<< define editorState2 >>
                #@+node:ekr.20190331082353.2: *4* << define editorState2 >>
                [
                    'C:\\apps\\pyzo\\source\\pyzo\\codeeditor\\highlighter.py',
                    3279, 96
                ],
                [
                    'C:\\apps\\pyzo\\source\\pyzo\\core\\editorTabs.py', 22913,
                    693
                ],
                [
                    'C:\\apps\\pyzo\\source\\pyzo\\codeeditor\\highlighter.py',
                    'hist'
                ],
                ['C:\\apps\\pyzo\\source\\pyzo\\core\\editorTabs.py', 'hist']
                #@-<< define editorState2 >>
            ],
            find_autoHide=1,
            find_matchCase=0,
            find_regExp=0,
            find_show=0,
            find_wholeWord=1,
            loadedTools=[
                'pyzofilebrowser', 'pyzologger', 'pyzosourcestructure'
            ],
            newUser=1,
            windowGeometry=
            'AdnQywACAAAAAAGjAAAA2AAABv0AAANWAAABqwAAAPcAAAb1AAADTgAAAAAAAAAAB4A=\n',
            windowState=
            ('AAAA/wAAAAD9AAAAAgAAAAAAAACeAAACRPwCAAAAAfwAAAAUAAACRAAAAYgA/////AIAAAAC+wAA\n'
             'AB4AcAB5AHoAbwBmAGkAbABlAGIAcgBvAHcAcwBlAHIBAAAAFAAAAWEAAAEIAP////sAAAAmAHAA\n'
             'eQB6AG8AcwBvAHUAcgBjAGUAcwB0AHIAdQBjAHQAdQByAGUBAAABewAAAN0AAAB6AP///wAAAAEA\n'
             'AAGEAAACRPwCAAAABvsAAAAMAHMAaABlAGwAbABzAQAAABQAAAD/AAAAcwD////7AAAAFABwAHkA\n'
             'egBvAGwAbwBnAGcAZQByAQAAARkAAAE/AAAAWQD////7AAAAGgBwAHkAegBvAHcAbwByAGsAcwBw\n'
             'AGEAYwBlAAAAAT4AAAEaAAAAAAAAAAD7AAAAJgBwAHkAegBvAGkAbgB0AGUAcgBhAGMAdABpAHYA\n'
             'ZQBoAGUAbABwAAAAAnkAAAB6AAAAAAAAAAD7AAAAIgBwAHkAegBvAGgAaQBzAHQAbwByAHkAdgBp\n'
             'AGUAdwBlAHIAAAACGgAAAVsAAAAAAAAAAPsAAAAcAHAAeQB6AG8AdwBlAGIAYgByAG8AdwBzAGUA\n'
             'cgAAAAKwAAAAxQAAAAAAAAAAAAADHQAAAkQAAAAEAAAABAAAAAgAAAAI/AAAAAA=\n'
             ))

        tools = g.Bunch(pyzofilebrowser=g.Bunch(),
                        pyzofilebrowser2=g.Bunch(
                            expandedDirs=['c:\\apps\\pyzo\\source\\pyzo'],
                            nameFilter='!*.pyc',
                            path='c:\\apps\\pyzo\\source\\pyzo',
                            searchMatchCase=0,
                            searchRegExp=0,
                            searchSubDirs=1,
                            starredDirs=[
                                g.Bunch(
                                    addToPythonpath=0,
                                    name='Pyzo sources',
                                    path='c:\\apps\\pyzo\\source',
                                )
                            ]),
                        pyzohistoryviewer=g.Bunch(),
                        pyzointeractivehelp=g.Bunch(fontSize=14,
                                                    noNewlines=1,
                                                    smartNewlines=1),
                        pyzologger=g.Bunch(),
                        pyzosourcestructure=g.Bunch(
                            level=1,
                            showTypes=['class', 'def', 'cell', 'todo'],
                        ),
                        pyzowebbrowser=g.Bunch(
                            bookMarks=[
                                'docs.python.org',
                                'scipy.org',
                                'doc.qt.nokia.com/4.5/',
                                'pyzo.org',
                            ],
                            zoomFactor=1.0,
                        ),
                        pyzoworkspace=g.Bunch(
                            hideTypes=[],
                            typeTranslation=g.Bunch(
                                builtin_function_or_method='function',
                                method='function')))

        view = g.Bunch(autoComplete_popupSize=[300, 100],
                       codeFolding=0,
                       doBraceMatch=1,
                       edgeColumn=80,
                       fontname='DejaVu Sans Mono',
                       highlightCurrentLine=1,
                       highlightMatchingBracket=1,
                       qtstyle='fusion',
                       showIndentationGuides=1,
                       showLineEndings=0,
                       showStatusbar=0,
                       showWhitespace=0,
                       showWrapSymbols=0,
                       tabWidth=4,
                       wrap=1,
                       zoom=2)

        #@-<< define bunch settings >>
        #@+<< new config methods >>
        #@+node:ekr.20190331052308.1: *3* << new config methods >>
        #@+others
        #@+node:ekr.20190331052308.2: *4* ConfigShim.__repr__
        def __repr__(self):

            return 'ConfigShim'
            # return g.obj2string(self)
            # Can't do this: it calls repr!

        #@+node:ekr.20190331052308.3: *4* ConfigShim.__getattribute__
        def __getattribute__(self, key):
            '''The usual shinanigans...'''
            ### return object.__getattribute__(self, key)
            try:
                val = object.__getattribute__(self, key)
            except AttributeError:
                if key in self:
                    val = self[key]
                else:
                    raise
            if key not in config_shim_seen:
                config_shim_seen[key] = True
                g.pr('\n===== ConfigShim.__getattribute__', key, val)
            return val

        #@+node:ekr.20190331052308.4: *4* ConfigShim.__setattr__ (not used)
        # def __setattr__(self, key, val):
        # if key in Dict.__reserved_names__:
        # # Either let OrderedDict do its work, or disallow
        # if key not in Dict.__pure_names__:
        # return _dict.__setattr__(self, key, val)
        # else:
        # raise AttributeError('Reserved name, this key can only ' +
        # 'be set via ``d[%r] = X``' % key)
        # else:
        # # if isinstance(val, dict): val = Dict(val) -> no, makes a copy!
        # self[key] = val
        #@-others
        #@-<< new config methods >>
    else:
        #@+<< old config methods >>
        #@+node:ekr.20190331052251.1: *3* << old config methods >>
        #@+others
        #@+node:ekr.20190317082751.2: *4* ConfigShim.__repr__
        def __repr__(self):

            from pyzo.util.zon import isidentifier
            # Changed import.
            identifier_items = []
            nonidentifier_items = []
            for key, val in self.items():
                if isidentifier(key):
                    identifier_items.append('%s=%r' % (key, val))
                else:
                    nonidentifier_items.append('(%r, %r)' % (key, val))
            if nonidentifier_items:
                return 'Dict([%s], %s)' % (', '.join(nonidentifier_items),
                                           ', '.join(identifier_items))
            else:
                return 'Dict(%s)' % (', '.join(identifier_items))

        #@+node:ekr.20190317082751.3: *4* ConfigShim.__getattribute__
        def __getattribute__(self, key):
            try:
                ### return object.__getattribute__(self, key)
                val = object.__getattribute__(self, key)
                if False and key not in ('advanced', 'shortcuts2', 'settings'):
                    # g.pr('===== LeoPyzoConfig 1: %r: %r' % (key, val))
                    g.pr('===== LeoPyzoConfig 1: %r' % key)
                return val
            except AttributeError:
                if key in self:
                    if False and key not in ('advanced', 'shortcuts2',
                                             'settings'):
                        # g.pr('===== LeoPyzoConfig 1: %r: %r' % (key, g.truncate(self[key], 50)))
                        g.pr('===== LeoPyzoConfig 2: %r' % key)
                    return self[key]
                else:
                    raise

        #@+node:ekr.20190317082751.4: *4* ConfigShim.__setattr__
        def __setattr__(self, key, val):
            if key in Dict.__reserved_names__:
                # Either let OrderedDict do its work, or disallow
                if key not in Dict.__pure_names__:
                    return _dict.__setattr__(self, key, val)
                else:
                    raise AttributeError('Reserved name, this key can only ' +
                                         'be set via ``d[%r] = X``' % key)
            else:
                # if isinstance(val, dict): val = Dict(val) -> no, makes a copy!
                self[key] = val