示例#1
0
def beautifyCCode(event):
    '''Beautify all C code in the selected tree.'''
    c = event.get('c')
    if not c: return
    if should_kill_beautify(c.p):
        return
    u, undoType = c.undoer, 'beautify-c'
    pp = CPrettyPrinter(c)
    u.beforeChangeGroup(c.p, undoType)
    dirtyVnodeList = []
    changed = False
    for p in c.p.self_and_subtree():
        if g.scanForAtLanguage(c, p) == "c":
            bunch = u.beforeChangeNodeContents(p)
            s = pp.indent(p)
            if p.b != s:
                # g.es('changed: %s' % (p.h))
                p.b = s
                p.v.setDirty()
                dirtyVnodeList.append(p.v)
                u.afterChangeNodeContents(p, undoType, bunch)
                changed = True
    if changed:
        u.afterChangeGroup(c.p, undoType,
            reportFlag=False, dirtyVnodeList=dirtyVnodeList)
    c.bodyWantsFocus()
示例#2
0
def prettyPrintPythonNode(event):
    '''Beautify a single Python node.'''
    c = event.get('c')
    if not c: return
    pp = PythonTokenBeautifier(c)
    if g.scanForAtLanguage(c, c.p) == "python":
        pp.prettyPrintNode(c.p)
    pp.end_undo()
示例#3
0
def prettyPrintPythonNode(event):
    '''Beautify a single Python node.'''
    c = event.get('c')
    if not c: return
    pp = PythonTokenBeautifier(c)
    if g.scanForAtLanguage(c, c.p) == "python":
        pp.prettyPrintNode(c.p)
    pp.end_undo()
示例#4
0
 def import_from_string(self, s):
     '''Import from s into a temp outline.'''
     cc = self  # (ConvertController)
     c = cc.c
     ic = c.importCommands
     root = cc.root
     language = g.scanForAtLanguage(c, root)
     ext = '.' + g.app.language_extension_dict.get(language)
     scanner = ic.scanner_for_ext(ext)
     # g.trace(language,ext,scanner.__name__)
     p = root.insertAfter()
     ok = scanner(atAuto=True, parent=p, s=s)
     p.h = root.h.replace('@file', '@auto' if ok else '@@auto')
     return ok, p
示例#5
0
 def import_from_string(self,s):
     '''Import from s into a temp outline.'''
     cc = self # (ConvertController)
     c = cc.c
     ic = c.importCommands
     root = cc.root
     language = g.scanForAtLanguage(c,root) 
     ext = '.'+g.app.language_extension_dict.get(language)
     scanner = ic.scanner_for_ext(ext)
     # g.trace(language,ext,scanner.__name__)
     p = root.insertAfter()
     ok = scanner(atAuto=True,parent=p,s=s)
     p.h = root.h.replace('@file','@auto' if ok else '@@auto')
     return ok,p
示例#6
0
def beautifyPythonTree(event):
    '''Beautify the Python code in the selected outline.'''

    def plural(n):
        return 's' if n > 1 else ''

    c = event.get('c')
    p0 = event.get('p0')
    is_auto = bool(p0)
    p0 = p0 or c.p
    if should_kill_beautify(p0):
        return
    t1 = time.clock()
    pp = PythonTokenBeautifier(c)
    prev_changed = 0
    for p in p0.self_and_subtree():
        if g.scanForAtLanguage(c, p) == "python":
            if p.isAnyAtFileNode():
                # Report changed nodes in previous @<file> node.
                if pp.n_changed_nodes != prev_changed and not is_auto:
                    if not g.unitTesting:
                        n = pp.n_changed_nodes - prev_changed
                        g.es_print('beautified %s node%s' % (
                            n, plural(n)))
                prev_changed = pp.n_changed_nodes
                if not is_auto:
                    g.es_print(p.h)
            pp.prettyPrintNode(p)
    # Report any nodes in the last @<file> tree.
    if not g.unitTesting:
        if pp.n_changed_nodes != prev_changed and not is_auto:
            n = pp.n_changed_nodes - prev_changed
            g.es_print('beautified %s node%s' % (
                n, plural(n)))
    pp.end_undo()
    t2 = time.clock()
    # pp.print_stats()
    if not g.unitTesting:
        if is_auto:
            if pp.n_changed_nodes > 0:
                g.es_print('auto-beautified %s node%s in\n%s' % (
                    pp.n_changed_nodes,
                    plural(pp.n_changed_nodes),
                    p0.h))
        else:
            g.es_print('beautified total %s node%s in %4.2f sec.' % (
                pp.n_changed_nodes, plural(pp.n_changed_nodes), t2 - t1))
示例#7
0
def beautifyPythonTree(event):
    '''Beautify the Python code in the selected outline.'''
    def plural(n):
        return 's' if n > 1 else ''

    c = event.get('c')
    p0 = event.get('p0')
    is_auto = bool(p0)
    p0 = p0 or c.p
    if should_kill_beautify(p0):
        return
    t1 = time.clock()
    pp = PythonTokenBeautifier(c)
    prev_changed = 0
    for p in p0.self_and_subtree():
        if g.scanForAtLanguage(c, p) == "python":
            if p.isAnyAtFileNode():
                # Report changed nodes in previous @<file> node.
                if pp.n_changed_nodes != prev_changed and not is_auto:
                    if not g.unitTesting:
                        n = pp.n_changed_nodes - prev_changed
                        g.es_print('beautified %s node%s' % (n, plural(n)))
                prev_changed = pp.n_changed_nodes
                if not is_auto:
                    g.es_print(p.h)
            pp.prettyPrintNode(p)
    # Report any nodes in the last @<file> tree.
    if not g.unitTesting:
        if pp.n_changed_nodes != prev_changed and not is_auto:
            n = pp.n_changed_nodes - prev_changed
            g.es_print('beautified %s node%s' % (n, plural(n)))
    pp.end_undo()
    t2 = time.clock()
    # pp.print_stats()
    if not g.unitTesting:
        if is_auto:
            if pp.n_changed_nodes > 0:
                g.es_print(
                    'auto-beautified %s node%s in\n%s' %
                    (pp.n_changed_nodes, plural(pp.n_changed_nodes), p0.h))
        else:
            g.es_print(
                'beautified total %s node%s in %4.2f sec.' %
                (pp.n_changed_nodes, plural(pp.n_changed_nodes), t2 - t1))
示例#8
0
    def pretty_print_tree(self, p):

        c = self.c
        if should_kill_beautify(p):
            return
        u, undoType = c.undoer, 'beautify-c'
        u.beforeChangeGroup(c.p, undoType)
        changed = False
        for p in c.p.self_and_subtree():
            if g.scanForAtLanguage(c, p) == "c":
                bunch = u.beforeChangeNodeContents(p)
                s = self.indent(p)
                if p.b != s:
                    p.b = s
                    p.setDirty()
                    u.afterChangeNodeContents(p, undoType, bunch)
                    changed = True
        if changed:
            u.afterChangeGroup(c.p, undoType, reportFlag=False)
        c.bodyWantsFocus()
示例#9
0
 def set_expected_imported_headlines(self, root):
     '''Set v._imported_headline for every vnode.'''
     trace = False and not g.unitTesting
     cc = self
     c = cc.c
     ic = cc.c.importCommands
     language = g.scanForAtLanguage(c, root)
     ext = '.' + g.app.language_extension_dict.get(language)
     aClass = ic.classDispatchDict.get(ext)
     scanner = aClass(importCommands=ic, atAuto=True)
     # Duplicate the fn logic from ic.createOutline.
     theDir = g.setDefaultDirectory(c, root, importing=True)
     fn = c.os_path_finalize_join(theDir, root.h)
     fn = root.h.replace('\\', '/')
     junk, fn = g.os_path_split(fn)
     fn, junk = g.os_path_splitext(fn)
     if aClass and hasattr(scanner, 'headlineForNode'):
         for p in root.subtree():
             if not hasattr(p.v, '_imported_headline'):
                 h = scanner.headlineForNode(fn, p)
                 setattr(p.v, '_imported_headline', h)
                 if trace and h != p.h:
                     g.trace('==>', h)  # p.h,'==>',h
示例#10
0
 def set_expected_imported_headlines(self,root):
     '''Set v._imported_headline for every vnode.'''
     trace = False and not g.unitTesting
     cc = self
     c = cc.c
     ic = cc.c.importCommands
     language = g.scanForAtLanguage(c,root) 
     ext = '.'+g.app.language_extension_dict.get(language)
     aClass = ic.classDispatchDict.get(ext)
     scanner = aClass(importCommands=ic,atAuto=True)
     # Duplicate the fn logic from ic.createOutline.
     theDir = g.setDefaultDirectory(c,root,importing=True)
     fn = c.os_path_finalize_join(theDir,root.h)
     fn = root.h.replace('\\','/')
     junk,fn = g.os_path_split(fn)
     fn,junk = g.os_path_splitext(fn)
     if aClass and hasattr(scanner,'headlineForNode'):
         for p in root.subtree():
             if not hasattr(p.v,'_imported_headline'):
                 h = scanner.headlineForNode(fn,p)
                 setattr(p.v,'_imported_headline',h)
                 if trace and h != p.h:
                     g.trace('==>',h) # p.h,'==>',h
示例#11
0
 def prepass(self, root):
     '''Make sure root's tree has no hard-to-handle nodes.'''
     c, pd = self.c, self
     ic = c.importCommands
     ic.tab_width = c.getTabWidth()
     language = g.scanForAtLanguage(c, root)
     ext = g.app.language_extension_dict.get(language)
     if not ext: return
     if not ext.startswith('.'): ext = '.' + ext
     scanner = ic.scanner_for_ext(ext)
     if not scanner:
         g.trace('no scanner for', root.h)
         return True  # Pretend all went well.
     # Pass 1: determine the nodes to be inserted.
     ok, parts_list = True, []
     for p in root.subtree():
         ok2, parts = pd.regularize_node(p, scanner)
         ok = ok and (ok2 or parts)
         if parts: parts_list.append(parts)
     # Pass 2: actually insert the nodes.
     if ok:
         for parts in reversed(parts_list):
             p0 = None
             for part in reversed(parts):
                 i1, i2, headline, p = part
                 if p0 is None:
                     p0 = p
                 else:
                     assert p == p0, (p, p0)
                 s = p.b
                 g.trace(p.h, '-->', headline)
                 p2 = p.insertAfter()
                 p2.b = s[i1:i2]
                 p2.h = headline
             p0.doDelete()
     return ok
示例#12
0
 def prepass(self,root):
     '''Make sure root's tree has no hard-to-handle nodes.'''
     c,pd = self.c,self
     ic = c.importCommands
     ic.tab_width = c.getTabWidth()
     language = g.scanForAtLanguage(c,root)
     ext = g.app.language_extension_dict.get(language)
     if not ext: return
     if not ext.startswith('.'): ext = '.' + ext
     scanner = ic.scanner_for_ext(ext)
     if not scanner:
         g.trace('no scanner for',root.h)
         return True # Pretend all went well.
     # Pass 1: determine the nodes to be inserted.
     ok,parts_list = True,[]
     for p in root.subtree():
         ok2,parts = pd.regularize_node(p,scanner)
         ok = ok and (ok2 or parts)
         if parts: parts_list.append(parts)
     # Pass 2: actually insert the nodes.
     if ok:
         for parts in reversed(parts_list):
             p0 = None
             for part in reversed(parts):
                 i1,i2,headline,p = part
                 if p0 is None:
                     p0 = p
                 else:
                     assert p == p0,(p,p0)
                 s = p.b
                 g.trace(p.h,'-->',headline)
                 p2 = p.insertAfter()
                 p2.b = s[i1:i2]
                 p2.h = headline
             p0.doDelete()
     return ok
示例#13
0
    def _babelExec(babelG, babelCmdr, babelRoot):
        """ Execute a Script

        Arguments:
            babelG: Babel globals
            babelCmdr: Leo-Editor commander for the file containing
                the script to execute
            babelRoot:  The "Babel Root" for the script to execute

        Returns:
            None

        Side Effects:
            For each line <line> in the target node body,
                A child node is created with empty body and headline "<elapsed time> - <line>"
                If <line> writes any non-blanks to stdout, then a child node is created with
                headline "stdout - <line>" and body containing the standard output.
                If <line> writes any non-blanks to stderr, then a child node is created with
                headline "stderr - <line>" and body containing the standard error output.

        Most importantly the output nodes are created in real time when they occur, not
        later when the <line> terminates.

        If there is a selected range, then this selected range is executed.
        If there is no selected range, then the whole body of the currently selected
        node is executed.

        If the language at the current cursor position is "python," then the
        Python interpreter executes the target text.
        If the language at the current cursor position is "shell," then the
        Bash interpreter executes the target text.

        The scheme for real-time streaming of stdout and stderr while the script is still executing is taken from:

        http://stackoverflow.com/questions/18421757/live-output-from-subprocess-command


        """

        script = getScript(cmdr,
                           babelRoot,
                           useSelectedText=False,
                           language='python')
        code = compile(script, 'Babel Parameter Script', 'exec')

        gld = {
            'babel': babelG.babel_api,
            'b': babelG.babel_api,
            '__file__': 'Babel Parameter Script',
            'c': cmdr,
            'g': leoG,
            'p': babelRoot
        }
        exec(code, gld)

        # Create Nodes?
        createNodes = gld.get('babel_node_creation')
        if createNodes is None:
            createNodes = babelCmdr.nodeCreationDefault
        cmdrScr, scriptRoot = scrOrResRoot(cmdr, gld, babelG, babelRoot,
                                           'script')
        if createNodes:
            cmdrRes, resultsRoot = scrOrResRoot(cmdr, gld, babelG, babelRoot,
                                                'results')
        else:
            cmdrRes = None
            resultsRoot = None

        # Determine the language and then the interpreter
        langx = leoG.scanForAtLanguage(cmdrScr, scriptRoot)
        if langx == 'python':
            interpreter = gld.get('babel_python')
            if not interpreter:
                interpreter = babelCmdr.interpreterPython
            cmdList = [interpreter, '-u']
        elif langx == 'shell':
            interpreter = gld.get('babel_shell')
            if not interpreter:
                interpreter = babelCmdr.interpreterShell
            cmdList = [interpreter]
        else:
            babelCmdr.babelExecCnt += 1
            raise babelG.babel_api.BABEL_LANGUAGE(
                'Unknown language "{0}"'.format(langx))

        script = getScript(cmdrScr,
                           scriptRoot,
                           useSelectedText=False,
                           language=langx)

        cmdrScr.setCurrentDirectoryFromContext(scriptRoot)
        cwd = leoG.os_path_abspath(os.getcwd())

        pathScript = cmdr.writeScriptFile(script)
        cmdList.append(pathScript)
        babel_script_args = gld.get('babel_script_args')
        if babel_script_args:
            cmdList.extend(babel_script_args)
        # pylint: disable=unexpected-keyword-arg
        wro = tempfile.NamedTemporaryFile(buffering=0)
        wre = tempfile.NamedTemporaryFile(buffering=0)
        reo = io.open(wro.name, 'rb', buffering=0)
        ree = io.open(wre.name, 'rb', buffering=0)

        if gld.get('babel_redirect_stdout'):
            # Redirect stdout to stderr
            wro = wre

        babelCmdr.cmdDoneFlag = False
        babelCmdr.cmdDoneStdPolled = False
        babelCmdr.cmdDoneErrPolled = False

        start = time.time()
        subPscript = subprocess.Popen(cmdList, cwd=cwd, stdout=wro, stderr=wre)
        subPbabKill = subprocess.Popen(
            [babelG.pathBabelKill, str(subPscript.pid)])

        babelCmdr.reo = reo  # Kludge to allow itf() to determine which output it polls
        itOut = leoG.IdleTime(
            (lambda ito: itf(babelCmdr.colorStdout, reo, babelCmdr)),
            delay=1000)
        itErr = leoG.IdleTime(
            (lambda ito: itf(babelCmdr.colorStderr, ree, babelCmdr)),
            delay=1000)
        if (not itOut) or (not itErr):
            raise babelG.babel_api.BABEL_ERROR('leoG.IdleTime() failed')
        itOut.start()
        itErr.start()

        itPoll = leoG.IdleTime((lambda itobj: itp(
            itobj, cmdr, cmdrRes, resultsRoot, subPscript, subPbabKill, wro,
            reo, wre, ree, itOut, itErr, start, createNodes)),
                               delay=1000)
        if not itPoll:
            raise babelG.babel_api.BABEL_ERROR('leoG.IdleTime() failed')
        itPoll.start()
示例#14
0
    def _babelExec(babelG, babelCmdr, babelRoot):
        """ Execute a Script

        Arguments:
            babelG: Babel globals
            babelCmdr: Leo-Editor commander for the file containing
                the script to execute
            babelRoot:  The "Babel Root" for the script to execute

        Returns:
            None

        Side Effects:
            For each line <line> in the target node body,
                A child node is created with empty body and headline "<elapsed time> - <line>"
                If <line> writes any non-blanks to stdout, then a child node is created with
                headline "stdout - <line>" and body containing the standard output.
                If <line> writes any non-blanks to stderr, then a child node is created with
                headline "stderr - <line>" and body containing the standard error output.

        Most importantly the output nodes are created in real time when they occur, not
        later when the <line> terminates.

        If there is a selected range, then this selected range is executed.
        If there is no selected range, then the whole body of the currently selected
        node is executed.

        If the language at the current cursor position is "python," then the
        Python interpreter executes the target text.
        If the language at the current cursor position is "shell," then the
        Bash interpreter executes the target text.

        The scheme for real-time streaming of stdout and stderr while the script is still executing is taken from:

        http://stackoverflow.com/questions/18421757/live-output-from-subprocess-command


        """

        script = getScript(cmdr, babelRoot, useSelectedText=False, language='python')
        code = compile(script, 'Babel Parameter Script', 'exec')

        gld = {'babel': babelG.babel_api,
            'b': babelG.babel_api,
            '__file__': 'Babel Parameter Script',
            'c': cmdr,
            'g': leoG,
            'p': babelRoot}
        exec(code, gld)

        # Create Nodes?
        createNodes = gld.get('babel_node_creation')
        if createNodes is None:
            createNodes = babelCmdr.nodeCreationDefault
        cmdrScr, scriptRoot = scrOrResRoot(cmdr, gld, babelG, babelRoot, 'script')
        if createNodes:
            cmdrRes, resultsRoot = scrOrResRoot(cmdr, gld, babelG, babelRoot, 'results')
        else:
            cmdrRes = None
            resultsRoot = None

        # Determine the language and then the interpreter
        langx = leoG.scanForAtLanguage(cmdrScr, scriptRoot)
        if langx == 'python':
            interpreter = gld.get('babel_python')
            if not interpreter:
                interpreter = babelCmdr.interpreterPython
            cmdList = [interpreter, '-u']
        elif langx == 'shell':
            interpreter = gld.get('babel_shell')
            if not interpreter:
                interpreter =  babelCmdr.interpreterShell
            cmdList = [interpreter]
        else:
            babelCmdr.babelExecCnt += 1
            raise  babelG.babel_api.BABEL_LANGUAGE('Unknown language "{0}"'.format(langx))

        script = getScript(cmdrScr, scriptRoot, useSelectedText=False, language=langx)

        cmdrScr.setCurrentDirectoryFromContext(scriptRoot)
        cwd = leoG.os_path_abspath(os.getcwd())

        pathScript = cmdr.writeScriptFile(script)
        cmdList.append(pathScript)
        babel_script_args = gld.get('babel_script_args')
        if babel_script_args:
            cmdList.extend(babel_script_args)
        # pylint: disable=unexpected-keyword-arg
        wro = tempfile.NamedTemporaryFile(buffering=0)
        wre = tempfile.NamedTemporaryFile(buffering=0)
        reo = io.open(wro.name, 'rb', buffering=0)
        ree = io.open(wre.name, 'rb', buffering=0)

        if gld.get('babel_redirect_stdout'):
            # Redirect stdout to stderr
            wro = wre

        babelCmdr.cmdDoneFlag = False
        babelCmdr.cmdDoneStdPolled = False
        babelCmdr.cmdDoneErrPolled = False

        start = time.time()
        subPscript = subprocess.Popen(cmdList, cwd=cwd, stdout=wro, stderr=wre)
        subPbabKill = subprocess.Popen([babelG.pathBabelKill, str(subPscript.pid)])

        babelCmdr.reo = reo     # Kludge to allow itf() to determine which output it polls
        itOut = leoG.IdleTime((lambda ito: itf(babelCmdr.colorStdout, reo, babelCmdr)), delay=1000)
        itErr = leoG.IdleTime((lambda ito: itf(babelCmdr.colorStderr, ree, babelCmdr)), delay=1000)
        if (not itOut) or (not itErr):
            raise babelG.babel_api.BABEL_ERROR('leoG.IdleTime() failed')
        itOut.start()
        itErr.start()

        itPoll = leoG.IdleTime((lambda itobj: itp(itobj, cmdr, cmdrRes, resultsRoot,
            subPscript, subPbabKill, wro, reo, wre, ree, itOut, itErr, start,
            createNodes)), delay=1000)
        if not itPoll:
            raise babelG.babel_api.BABEL_ERROR('leoG.IdleTime() failed')
        itPoll.start()