Пример #1
0
 def __repr__(self):
     '''IdleTime repr.'''
     tag = self.tag
     if tag:
         return '<IdleTime: %s>' % (tag if g.isString(tag) else repr(tag))
     else:
         return '<IdleTime: id: %s>' % id(self)
Пример #2
0
 def addParentMatches(self, parent_list):
     lineMatchHits = 0
     for parent_key, parent_value in parent_list.items():
         if g.isString(parent_key):
             v = self.c.fileCommands.gnxDict.get(parent_key)
             h = v.h if v else parent_key
             it = QtWidgets.QListWidgetItem(h, self.lw)
         else:
             it = QtWidgets.QListWidgetItem(parent_key.h, self.lw)
         f = it.font()
         f.setItalic(True)
         it.setFont(f)
         if self.addItem(it, (parent_key, None)): return lineMatchHits
         for p in parent_value:
             it = QtWidgets.QListWidgetItem("    "+p.h, self.lw)
             f = it.font()
             f.setBold(True)
             it.setFont(f)
             if self.addItem(it, (p, None)):return lineMatchHits
             if hasattr(p,"matchiter"): #p might be not have body matches
                 ms = matchlines(p.b, p.matchiter)
                 for ml, pos in ms:
                     lineMatchHits += 1
                     it = QtWidgets.QListWidgetItem("    "+"    "+ml, self.lw)
                     if self.addItem(it, (p, pos)):return lineMatchHits
     return lineMatchHits
Пример #3
0
 def addParentMatches(self, parent_list):
     lineMatchHits = 0
     for parent_key, parent_value in parent_list.items():
         if g.isString(parent_key):
             it = QtWidgets.QListWidgetItem(parent_key, self.lw)
         else:
             it = QtWidgets.QListWidgetItem(parent_key.h, self.lw)
         f = it.font()
         f.setItalic(True)
         it.setFont(f)
         self.its[id(it)] = (parent_key, None)
         for p in parent_value:
             it = QtWidgets.QListWidgetItem("    " + p.h, self.lw)
             f = it.font()
             f.setBold(True)
             it.setFont(f)
             self.its[id(it)] = (p, None)
             if hasattr(p, "matchiter"):  #p might be not have body matches
                 ms = matchlines(p.b, p.matchiter)
                 for ml, pos in ms:
                     lineMatchHits += 1
                     it = QtWidgets.QListWidgetItem("    " + "    " + ml,
                                                    self.lw)
                     self.its[id(it)] = (p, pos)
     return lineMatchHits
Пример #4
0
 def getMenuEntryInfo(self, data, menu):
     done = False
     if g.isString(data):
         # A single string is both the label and the command.
         s = data
         removeHyphens = s and s[0] == '*'
         if removeHyphens: s = s[1:]
         label = self.capitalizeMinibufferMenuName(s, removeHyphens)
         command = s.replace('&', '').lower()
         if label == '-':
             self.add_separator(menu)
             done = True # That's all.
     else:
         ok = isinstance(data, (list, tuple)) and len(data) in (2, 3)
         if ok:
             if len(data) == 2:
                 # Command can be a minibuffer-command name.
                 label, command = data
             else:
                 # Ignore shortcuts bound in menu tables.
                 label, junk, command = data
             if label in (None, '-'):
                 self.add_separator(menu)
                 done = True # That's all.
         else:
             g.trace('bad data in menu table: %s' % repr(data))
             done = True # Ignore bad data
     return label, command, done
Пример #5
0
def getColor(name, default=None):
    """ Translate a named color into #rrggbb' format.

    if 'name' is not a string it is returned unchanged.

    If 'name' is already in '#rrggbb' format then it is returned unchanged.

    If 'name' is not in global_color_database then getColor(default, None)
    is called and that result returned.


    """
    if not g.isString(name):
        return name
    #g.trace(name, default)
    if name[0] == '#':
        return name
    name = name.replace(' ', '').lower().strip()
    if name in leo_color_database:
        name2 = leo_color_database[name]
        # g.trace(name,name2)
        return name2
    if default:
        return getColor(default, default=None)
    return None
Пример #6
0
 def __repr__(self):
     '''IdleTime repr.'''
     tag = self.tag
     if tag:
         return '<IdleTime: %s>' % (tag if g.isString(tag) else repr(tag))
     else:
         return '<IdleTime: id: %s>' % id(self)
Пример #7
0
 def addParentMatches(self, parent_list):
     lineMatchHits = 0
     for parent_key, parent_value in parent_list.items():
         if g.isString(parent_key):
             v = self.c.fileCommands.gnxDict.get(parent_key)
             h = v.h if v else parent_key
             it = QtWidgets.QListWidgetItem(h, self.lw)
         else:
             it = QtWidgets.QListWidgetItem(parent_key.h, self.lw)
         f = it.font()
         f.setItalic(True)
         it.setFont(f)
         if self.addItem(it, (parent_key, None)): return lineMatchHits
         for p in parent_value:
             it = QtWidgets.QListWidgetItem("    " + p.h, self.lw)
             f = it.font()
             f.setBold(True)
             it.setFont(f)
             if self.addItem(it, (p, None)): return lineMatchHits
             if hasattr(p, "matchiter"):  #p might be not have body matches
                 ms = matchlines(p.b, p.matchiter)
                 for ml, pos in ms:
                     lineMatchHits += 1
                     it = QtWidgets.QListWidgetItem("    " + "    " + ml,
                                                    self.lw)
                     if self.addItem(it, (p, pos)): return lineMatchHits
     return lineMatchHits
Пример #8
0
    def unl_to_pos(self, c2, for_p, bookmark=False):
        """"c2 may be an outline (like c) or an UNL (string)
        
        return c, p where c is an outline and p is a node to copy data to
        in that outline
        
        for_p is the p to be copied - needed to check for invalid recursive
        copy / move
        """

        if g.isString(c2):
            # c2 is an UNL indicating where to insert
            full_path = c2
            path, unl = full_path.split('#', 1)
            c2 = g.openWithFileName(path, old_c=self.c)
            self.c.bringToFront(c2=self.c)
            found, maxdepth, maxp = g.recursiveUNLFind(unl.split('-->'), c2)
            
            if found:
                
                if not bookmark and (for_p == maxp or for_p.isAncestorOf(maxp)):
                    g.es("Invalid move")
                    return None, None
                
                nd = maxp.insertAsNthChild(0)
            else:
                g.es("Could not find '%s'"%full_path)
                self.c.bringToFront(c2=self.c)
                return None, None
        else:
            # c2 is an outline, insert at top
            nd = c2.rootPosition().insertAfter()
            nd.copy().back().moveAfter(nd)

        return c2, nd
Пример #9
0
    def unl_to_pos(self, c2, for_p, bookmark=False):
        """"c2 may be an outline (like c) or an UNL (string)
        
        return c, p where c is an outline and p is a node to copy data to
        in that outline
        
        for_p is the p to be copied - needed to check for invalid recursive
        copy / move
        """

        if g.isString(c2):
            # c2 is an UNL indicating where to insert
            full_path = c2
            path, unl = full_path.split('#', 1)
            c2 = g.openWithFileName(path, old_c=self.c)
            self.c.bringToFront(c2=self.c)
            found, maxdepth, maxp = g.recursiveUNLFind(unl.split('-->'), c2)
            
            if found:
                
                if not bookmark and (for_p == maxp or for_p.isAncestorOf(maxp)):
                    g.es("Invalid move")
                    return None, None
                
                nd = maxp.insertAsNthChild(0)
            else:
                g.es("Could not find '%s'"%full_path)
                self.c.bringToFront(c2=self.c)
                return None, None
        else:
            # c2 is an outline, insert at top
            nd = c2.rootPosition().insertAfter()
            nd.copy().back().moveAfter(nd)

        return c2, nd
Пример #10
0
 def init_tree_abbrev(self):
     '''Init tree_abbrevs_d from @data tree-abbreviations nodes.'''
     c = self.c
     #
     # Careful. This happens early in startup.
     root = c.rootPosition()
     if not root:
         return
     if not c.p:
         c.selectPosition(root)
     if not c.p:
         return
     data = c.config.getOutlineData('tree-abbreviations')
     if data is None:
         return
     d = {}
     # #904: data may be a string or a list of two strings.
     aList = [data] if g.isString(data) else data
     for tree_s in aList:
         #
         # Expand the tree so we can traverse it.
         if not c.canPasteOutline(tree_s):
             return
         c.fileCommands.leo_file_encoding = 'utf-8'
         #
         # As part of #427, disable all redraws.
         try:
             old_disable = g.app.disable_redraw
             g.app.disable_redraw = True
             self.init_tree_abbrev_helper(d, tree_s)
         finally:
             g.app.disable_redraw = old_disable
     self.tree_abbrevs_d = d
Пример #11
0
 def create_child_node(self, parent, body, headline):
     '''Create a child node of parent.'''
     child = parent.insertAsLastChild()
     self.inject_lines_ivar(child)
     if body:
         self.add_line(child, body)
     assert g.isString(headline), repr(headline)
     child.h = headline.strip()
     return child
Пример #12
0
    def render_value(self, p, value):
        '''Put the rendered value in p's body pane.'''

        if isinstance(value, SList):
            p.b = value.n
        elif g.isString(value):  # Works with Python 3.x.
            p.b = value
        else:
            p.b = pprint.pformat(value)
Пример #13
0
 def create_child_node(self, parent, body, headline):
     '''Create a child node of parent.'''
     child = parent.insertAsLastChild()
     self.inject_lines_ivar(child)
     if body:
         self.add_line(child, body)
     assert g.isString(headline), repr(headline)
     child.h = headline.strip()
     return child
Пример #14
0
    def render_value(self,p,value):
        
        '''Put the rendered value in p's body pane.'''

        if isinstance(value, SList):
            p.b = value.n
        elif g.isString(value): # Works with Python 3.x.
            p.b = value
        else:
            p.b = pprint.pformat(value)
Пример #15
0
 def getMenuEntryBindings(self, command, dynamicMenu, label):
     '''Compute commandName from command.'''
     c = self.c
     if g.isString(command):
         # Command is really a command name.
         commandName = command
     else:
         # First, get the old-style name.
         commandName = self.computeOldStyleShortcutKey(label)
     command = c.commandsDict.get(commandName)
     return commandName
Пример #16
0
 def do_FunctionDef(self, node):
     old_context = self.context
     self.context = node
     # Visit the tree in token order.
     for z in node.decorator_list:
         self.visit(z)
     assert g.isString(node.name)
     self.visit(node.args)
     for z in node.body:
         self.visit(z)
     self.context = old_context
Пример #17
0
 def create_child_node(self, parent, body, headline):
     '''Create a child node of parent.'''
     child = parent.insertAsLastChild()
     self.inject_lines_ivar(child)
     if body:
         self.add_line(child, body)
     assert g.isString(headline), repr(headline)
     child.h = headline
         # #1037: do rstrip, not strip.
         # #1087: do not strip at all!
     return child
Пример #18
0
 def getMenuEntryBindings(self, command, dynamicMenu, label):
     '''Compute commandName from command.'''
     c = self.c
     if g.isString(command):
         # Command is really a command name.
         commandName = command
     else:
         # First, get the old-style name.
         commandName = self.computeOldStyleShortcutKey(label)
     command = c.commandsDict.get(commandName)
     return commandName
Пример #19
0
 def do_FunctionDef(self, node):
     old_context = self.context
     self.context = node
     # Visit the tree in token order.
     for z in node.decorator_list:
         self.visit(z)
     assert g.isString(node.name)
     self.visit(node.args)
     for z in node.body:
         self.visit(z)
     self.context = old_context
Пример #20
0
 def create_child_node(self, parent, body, headline):
     '''Create a child node of parent.'''
     child = parent.insertAsLastChild()
     self.inject_lines_ivar(child)
     if body:
         self.add_line(child, body)
     assert g.isString(headline), repr(headline)
     child.h = headline
         # #1037: do rstrip, not strip.
         # #1087: do not strip at all!
     return child
Пример #21
0
    def do_any(self, key, val):

        # if key == 'output_type': g.trace(val.__class__.__name__)
        if key == 'source':
            self.do_source(key, val)
        elif g.isString(val):
            self.do_string(key, val)
        elif isinstance(val, (list, tuple)):
            self.do_list(key, val)
        elif self.is_dict(val):
            self.do_dict(key, val)
        else:
            # Can be ints, None, etc.
            self.do_other(key, val)
Пример #22
0
 def v2_create_child_node(self, parent, body, headline):
     '''
     Create a child node of parent.
     Unlike i.v2_create_child_node, we DO NOT strip lws from the headline!
     '''
     trace = False and g.unitTesting
     child = parent.insertAsLastChild()
     self.inject_lines_ivar(child)
     if body:
         self.add_line(child, body)
     assert g.isString(headline), repr(headline)
     child.h = headline
         # Not headline.strip()!
     if trace: g.trace(repr(child.h))
     return child
Пример #23
0
 def find_gnx(self, root, gnx, vnodeName):
     '''
     Scan root's tree for a node with the given gnx and vnodeName.
     return (p,found)
     '''
     if gnx:
         assert g.isString(gnx)
         gnx = g.toUnicode(gnx)
         for p in root.self_and_subtree(copy=False):
             if p.matchHeadline(vnodeName):
                 if p.v.fileIndex == gnx:
                     return p.copy(), True
         return None, False
     else:
         return root, False
Пример #24
0
 def v2_create_child_node(self, parent, body, headline):
     '''
     Create a child node of parent.
     Unlike i.v2_create_child_node, we DO NOT strip lws from the headline!
     '''
     trace = False and g.unitTesting
     child = parent.insertAsLastChild()
     self.inject_lines_ivar(child)
     if body:
         self.add_line(child, body)
     assert g.isString(headline), repr(headline)
     child.h = headline
     # Not headline.strip()!
     if trace: g.trace(repr(child.h))
     return child
Пример #25
0
 def getMenuEntryBindings(self, command, dynamicMenu, label):
     '''Compute commandName from command.'''
     trace = False and not g.unitTesting
     c = self.c
     if g.isString(command):
         # Command is really a command name.
         commandName = command
     else:
         # First, get the old-style name.
         commandName = self.computeOldStyleShortcutKey(label)
     command = c.commandsDict.get(commandName)
     if trace and not command and not dynamicMenu:
         # This may come from a plugin that normally isn't enabled.
         g.trace('No inverse for %s' % commandName)
     return commandName
Пример #26
0
 def find_gnx(self, root, gnx, vnodeName):
     '''
     Scan root's tree for a node with the given gnx and vnodeName.
     return (p,found)
     '''
     if gnx:
         assert g.isString(gnx)
         gnx = g.toUnicode(gnx)
         for p in root.self_and_subtree():
             if p.matchHeadline(vnodeName):
                 if p.v.fileIndex == gnx:
                     return p.copy(), True
         return None, False
     else:
         return root, False
Пример #27
0
 def __init__(self, c, kind, fn, link_pattern, link_root, shell):
     '''Ctor for the ProcessData class.'''
     self.c = c
     self.callback = None
     self.fn = fn
     self.kind = kind
     self.link_pattern = None
     self.link_root = link_root
     self.shell = shell
     #
     # Check and compile the link pattern.
     if link_pattern and g.isString(link_pattern):
         try:
             self.link_pattern = re.compile(link_pattern)
         except Exception:
             g.trace('Invalid link pattern: %s' % link_pattern)
             self.link_pattern = None
Пример #28
0
 def __init__(self, c, kind, fn, link_pattern, link_root, shell):
     '''Ctor for the ProcessData class.'''
     self.c = c
     self.callback = None
     self.fn = fn
     self.kind = kind
     self.link_pattern = None
     self.link_root = link_root
     self.shell = shell
     #
     # Check and compile the link pattern.
     if link_pattern and g.isString(link_pattern):
         try:
             self.link_pattern = re.compile(link_pattern)
         except Exception:
             g.trace('Invalid link pattern: %s' % link_pattern)
             self.link_pattern = None
Пример #29
0
 def find_gnx(self, root, gnx, vnodeName):
     '''
     Scan root's tree for a node with the given gnx and vnodeName.
     return (p,found)
     '''
     trace = False and not g.unitTesting
     if gnx:
         assert g.isString(gnx)
         gnx = g.toUnicode(gnx)
         for p in root.self_and_subtree():
             if p.matchHeadline(vnodeName):
                 if p.v.fileIndex == gnx:
                     return p.copy(), True
         if trace: g.trace('not found! %s, %s' % (gnx, repr(vnodeName)))
         return None, False
     else:
         return root, False
Пример #30
0
 def find_gnx(self, root, gnx, vnodeName):
     '''
     Scan root's tree for a node with the given gnx and vnodeName.
     return (p,found)
     '''
     trace = False and not g.unitTesting
     if gnx:
         assert g.isString(gnx)
         gnx = g.toUnicode(gnx)
         for p in root.self_and_subtree():
             if p.matchHeadline(vnodeName):
                 if p.v.fileIndex == gnx:
                     return p.copy(), True
         if trace: g.trace('not found! %s, %s' % (gnx, repr(vnodeName)))
         return None, False
     else:
         return root, False
Пример #31
0
def dump_list(heading, aList):
    if heading:
        print('\n%s...\n' % heading)
    for aTuple in aList:
        key, val = aTuple
        if g.isString(val):
            if key.endswith(('leo_expanded', 'leo_marked')):
                if val:
                    print('%30s:' % key)
                    g.printObj(val.split(','))
                else:
                    print('%30s: []' % key)
            else:
                print('%30s: %s' % (key, val))
        elif isinstance(val, (int, float)):
            print('%30s: %s' % (key, val))
        else:
            print('%30s:' % key)
            g.printObj(val)
Пример #32
0
def dump_list(heading, aList):
    if heading:
        print('\n%s...\n' % heading)
    for aTuple in aList:
        key, val = aTuple
        if g.isString(val):
            if key.endswith(('leo_expanded', 'leo_marked')):
                if val:
                    print('%30s:' % key)
                    g.printObj(val.split(','))
                else:
                    print('%30s: []' % key)
            else:
                print('%30s: %s' % (key, val))   
        elif isinstance(val, (int, float)):
            print('%30s: %s' % (key, val))    
        else:
            print('%30s:' % key)
            g.printObj(val)
Пример #33
0
 def dump_d(self, d, tag):
     '''Print dictionary d.  Similar to g.printDict.'''
     if d:
         indent = ''
         n = 6
         for key in sorted(d):
             if g.isString(key):
                 n = max(n, len(key))
         g.pr('%s...{' % (tag) if tag else '{')
         for key in sorted(d):
             val = d.get(key)
             if key == 'body':
                 val = 'len(body) = %s' % (len(val))
             else:
                 val = repr(val).strip()
             # g.pr("%s%*s: %s" % (indent,n,key,repr(d.get(key)).strip()))
             g.pr("%s%*s: %s" % (indent, n, key, val))
         g.pr('}')
     else:
         g.pr('%s...{}' % (tag) if tag else '{}')
Пример #34
0
 def dump_d(self, d, tag):
     '''Print dictionary d.  Similar to g.printDict.'''
     if d:
         indent = ''
         n = 6
         for key in sorted(d):
             if g.isString(key):
                 n = max(n, len(key))
         g.pr('%s...{' % (tag) if tag else '{')
         for key in sorted(d):
             val = d.get(key)
             if key == 'body':
                 val = 'len(body) = %s' % (len(val))
             else:
                 val = repr(val).strip()
             # g.pr("%s%*s: %s" % (indent,n,key,repr(d.get(key)).strip()))
             g.pr("%s%*s: %s" % (indent, n, key, val))
         g.pr('}')
     else:
         g.pr('%s...{}' % (tag) if tag else '{}')
Пример #35
0
    def do_string(self, key, val):

        assert g.isString(val)
        is_cell = self.parent == self.cell
        if is_cell and key == 'cell_type':
            # Do *not* create a cell_type child.
            pass
        else:
            # Do create all other nodes.
            if self.in_data or len(g.splitLines(val.strip())) > 1:
                key = 'list:' + key
            else:
                key = 'str:' + key
            p = self.new_node('# ' + key)
            if key.startswith('list:'):
                if key.endswith('html'):
                    val = '@language html\n\n' + val
                elif key.endswith('xml'):
                    val = '@language html\n\n' + val
                else:
                    val = '@nocolor-node\n\n' + val
            # g.trace(key, g.splitLines(val)[:5])
            p.b = val
Пример #36
0
 def addParentMatches(self, parent_list):
     lineMatchHits = 0
     for parent_key, parent_value in parent_list.items():
         if g.isString(parent_key):
             it = QtWidgets.QListWidgetItem(parent_key, self.lw)
         else:
             it = QtWidgets.QListWidgetItem(parent_key.h, self.lw)
         f = it.font()
         f.setItalic(True)
         it.setFont(f)
         self.its[id(it)] = (parent_key, None)
         for p in parent_value:
             it = QtWidgets.QListWidgetItem("    "+p.h, self.lw)
             f = it.font()
             f.setBold(True)
             it.setFont(f)
             self.its[id(it)] = (p, None)
             if hasattr(p,"matchiter"): #p might be not have body matches
                 ms = matchlines(p.b, p.matchiter)
                 for ml, pos in ms:
                     lineMatchHits += 1
                     it = QtWidgets.QListWidgetItem("    "+"    "+ml, self.lw)
                     self.its[id(it)] = (p,pos)
     return lineMatchHits
Пример #37
0
 def unary_op(self, s):
     '''Add an operator request to the code list.'''
     assert s and g.isString(s), repr(s)
     self.blank()
     self.add_token('unary-op', s)
Пример #38
0
 def op_blank(self, s):
     '''Remove a preceding blank token, then add op and blank tokens.'''
     assert s and g.isString(s), repr(s)
     self.clean('blank')
     self.add_token('op', s)
     self.blank()
Пример #39
0
 def op(self, s):
     '''Add op token to code list.'''
     assert s and g.isString(s), repr(s)
     self.blank()
     self.add_token('op', s)
     self.blank()
Пример #40
0
    def find_setting(self, setting):
        # g.es("Settings finder: find %s" % setting)
        key = g.app.config.canonicalizeSettingName(setting)
        value = self.c.config.settingsDict.get(key)
        which = None
        while value and g.isString(value.val) and value.val.startswith('@'):
            msg = ("The relevant setting, '@{specific}', is using the value of "
            "a more general setting, '{general}'.  Would you like to edit the "
            "more specific setting, '@{specific}', or the more general setting, "
            "'{general}'?  The more general setting may alter appearance / "
            "behavior in more places, which may or may not be what you prefer."
            ).format(specific=setting, general=value.val)
            which = g.app.gui.runAskYesNoCancelDialog(self.c, "Which setting?",
                message=msg, yesMessage='Edit Specific', noMessage='Edit General')
            if which != 'no':
                break
            setting = value.val
            key = g.app.config.canonicalizeSettingName(setting[1:])
            value = self.c.config.settingsDict.get(key)
        if which == 'cancel' or not value:
            return
        unl = value and value.unl
        if (
            g.os_path_realpath(value.path) == g.os_path_realpath(g.os_path_join(
            g.app.loadManager.computeGlobalConfigDir(), 'leoSettings.leo')
        )):

            msg = ("The setting '@{specific}' is in the Leo global configuration "
            "file 'leoSettings.leo'\nand should be copied to "
            "'myLeoSettings.leo' before editing.\n"
            "It may make more sense to copy a group or category of settings.\nIf "
            "'myLeoSettings.leo' contains duplicate settings, the last definition "
            "is used."
            "\n\nChoice:\n"
            "1. just select the node in 'leoSettings.leo', I will decide how much\n"
            "   to copy into 'myLeoSettings.leo' (Recommended).\n"
            "2. copy the one setting, '@{specific}'\n")

            # get the settings already defined in myLeoSettings
            my_settings_c = self.c.openMyLeoSettings()
            _, settingsDict = g.app.loadManager.createSettingsDicts(my_settings_c, False)
            # find this setting's node
            path, src_unl = unl.split('#', 1)
            path = path.replace("file://", "").replace("unl://", "")
            src_unl = src_unl.replace('%20', ' ').split("-->")
            c2 = g.app.loadManager.openSettingsFile(path)
            found, maxdepth, maxp = g.recursiveUNLFind(src_unl, c2)
            # scan this setting's group and category for conflicts
            up = maxp.parent()
            if up and self.no_conflict(up, settingsDict):
                msg += "3. copy the setting group, '{group}'\n"
                up = up.parent()
                if up and self.no_conflict(up, settingsDict):
                    msg += "4. copy the whole setting category, '{category}'\n"

            msg = msg.format(specific=setting.lstrip('@'),
                group=unl.split('-->')[-2].split(':', 1)[0].replace('%20', ' '),
                category=unl.split('-->')[-3].split(':', 1)[0].replace('%20', ' '))
            which = g.app.gui.runAskOkCancelNumberDialog(
                self.c, "Copy setting?", message=msg)
            if which is None:
                return
            which = int(which)
            if which > 1:
                unl = self.copy_to_my_settings(unl, which-1)
        if unl:
            g.handleUnl(unl, c=self.c)
Пример #41
0
 def to_string(self):
     '''Convert an output token to a string.'''
     return self.value if g.isString(self.value) else ''
Пример #42
0
 def op_blank(self, s):
     '''Remove a preceding blank token, then add op and blank tokens.'''
     assert s and g.isString(s), repr(s)
     self.clean('blank')
     self.add_token('op', s)
     self.blank()
Пример #43
0
 def op(self, s):
     '''Add op token to code list.'''
     assert s and g.isString(s), repr(s)
     self.blank()
     self.add_token('op', s)
     self.blank()
Пример #44
0
 def unary_op(self, s):
     '''Add an operator request to the code list.'''
     assert s and g.isString(s), repr(s)
     self.blank()
     self.add_token('unary-op', s)
Пример #45
0
 def word_op(self, s):
     '''Add a word-op request to the code list.'''
     assert s and g.isString(s), repr(s)
     self.blank()
     self.add_token('word-op', s)
     self.blank()
Пример #46
0
def importCiscoConfig(c):

    if not c or not c.exists: return
    current = c.p
    #@+<< open file >>
    #@+node:edream.110203113231.673: *3* << open file >>
    # name = tkFileDialog.askopenfilename(
        # title="Import Cisco Configuration File",
        # filetypes=[("All files", "*")]
        # )

    name = g.app.gui.runOpenFileDialog (c,
        title="Import Cisco Configuration File",
        filetypes=[("All files", "*")],
        defaultextension='ini',
    )

    if not name:	return

    p = current.insertAsNthChild(0)
    c.setHeadString(p,"cisco config: %s" % name)
    c.redraw()

    try:
        fh = open(name)
        g.es("importing: %s" % name)
        linelist = fh.read().splitlines()
        fh.close()
    except IOError as msg:
        g.es("error reading %s: %s" % (name, msg))
        return
    #@-<< open file >>

    # define which additional child nodes will be created
    # these keywords must NOT be followed by indented blocks
    customBlocks = ['aaa','ip as-path','ip prefix-list','ip route',
                    'ip community-list','access-list','snmp-server','ntp',
                    'boot','service','logging']
    out = []
    blocks = {}
    children = []
    lines = len(linelist)
    i = 0
    skipToNextLine = 0
    # create level-0 and level-1 children
    while i<(lines-1):
        for customLine in customBlocks:
            if (linelist[i].startswith(customLine) or
                linelist[i].startswith('no %s' % customLine)):
                #@+<< process custom line >>
                #@+node:edream.110203113231.674: *3* << process custom line >>
                if customLine not in blocks:
                    blocks[customLine] = []
                    out.append(g.angleBrackets(customLine))
                    # create first-level child
                    child = p.insertAsNthChild(0)
                    c.setHeadString(child,g.angleBrackets(customLine))
                    children.append(child)

                blocks[customLine].append(linelist[i])
                #@-<< process custom line >>
                skipToNextLine = 1
                break
        if skipToNextLine:
            skipToNextLine = 0
        else:
            if linelist[i+1].startswith(' '):
                #@+<< process indented block >>
                #@+node:edream.110203113231.675: *3* << process indented block >>
                space = linelist[i].find(' ')
                if space == -1:
                    space = len(linelist[i])
                key = linelist[i][:space]
                if key in blocks:
                    blocks[key] = []
                    out.append(g.angleBrackets(key))
                    # create first-level child
                    child = p.insertAsNthChild(0)
                    c.setHeadString(child,g.angleBrackets(key))
                    children.append(child)

                value = [linelist[i]]
                # loop through the indented lines
                i = i+1
                try:
                    while linelist[i].startswith(' '):
                        value.append(linelist[i])
                        i = i+1
                except Exception:
                    # EOF
                    pass
                i = i-1 # restore index
                # now add the value to the dictionary
                blocks[key].append(value)
                #@-<< process indented block >>
            else:
                out.append(linelist[i])
        i=i+1
    # process last line
    out.append(linelist[i])

    #@+<< complete outline >>
    #@+node:edream.110203113231.676: *3* << complete outline >>
    # first print the level-0 text
    outClean = []
    prev = ''
    for line in out:
        if line=='!' and prev=='!':
            pass # skip repeated comment lines
        else:
            outClean.append(line)
        prev = line
    c.setBodyString(p,'\n'.join(outClean))

    # scan through the created outline and add children
    for child in children:
        # extract the key from the headline. Uhm... :)
        key = child.h.split('<<'
            )[1].split('>>')[0].strip()
        if key in blocks:
            # if type(blocks[key][0]) == type(''):
            if g.isString(blocks[key][0]):
                # it's a string, no sub-children, so just print the text
                c.setBodyString(child,'\n'.join(blocks[key]))
            else:
                # it's a multi-level node
                for value in blocks[key]:
                    # each value is a list containing the headline and then the text
                    subchild = child.insertAsNthChild(0)
                    c.setHeadString(subchild,value[0])
                    c.setBodyString(subchild,'\n'.join(value))
            # child.sortChildren()
        else:
            # this should never happen
            g.es("Unknown key: %s" % key)
    # p.sortChildren()
    current.expand()
    c.redraw_now()
Пример #47
0
 def word_op(self, s):
     '''Add a word-op request to the code list.'''
     assert s and g.isString(s), repr(s)
     self.blank()
     self.add_token('word-op', s)
     self.blank()
Пример #48
0
 def add_line(self, p, s):
     '''Append the line s to p.v._import_lines.'''
     assert s and g.isString(s), (repr(s), g.callers())
     # *Never* change p unexpectedly!
     assert hasattr(p.v, '_import_lines'), (repr(s), g.callers())
     p.v._import_lines.append(s)
Пример #49
0
 def to_string(self):
     '''Convert an output token to a string.'''
     return self.value if g.isString(self.value) else ''
Пример #50
0
 def add_line(self, p, s):
     '''Append the line s to p.v._import_lines.'''
     assert s and g.isString(s), (repr(s), g.callers())
     # *Never* change p unexpectedly!
     assert hasattr(p.v, '_import_lines'), (repr(s), g.callers())
     p.v._import_lines.append(s)