コード例 #1
0
    def update_tree(self, ed, lexer):
        getter = self.get_getter(lexer)
        if not getter: return

        filename = ed.get_filename()
        lines = ed.get_text_all().split("\n")
        heads = list(getter(filename, lines))

        ed.set_prop(app.PROP_CODETREE, False)
        app.tree_proc(self.h_tree, app.TREE_LOCK)
        app.tree_proc(self.h_tree, app.TREE_ITEM_DELETE, 0)
        last_levels = {0: 0}
        for index, data in enumerate(heads):
            pos = data[0]
            level = data[1]
            header = data[2]
            icon_index = data[3] if len(data) > 3 else -1

            for test_level in reversed(range(level)):
                parent = last_levels.get(test_level)
                if parent is None:
                    continue
                identity = app.tree_proc(self.h_tree,
                                         app.TREE_ITEM_ADD,
                                         parent,
                                         index=-1,
                                         text=header,
                                         image_index=icon_index)
                # when adding level K, forget all levels > K
                last_levels = {
                    k: v
                    for k, v in last_levels.items() if k <= level
                }
                last_levels[level] = identity

                if type(pos) == int:
                    if index == len(heads) - 1:
                        end_y = len(lines) - 1
                        s = ed.get_text_line(end_y)
                        if s is None:
                            end_x = 0
                        else:
                            end_x = len(s)
                    else:
                        end_y = heads[index +
                                      1][0]  # line_index of next header
                        end_x = 0
                    rng = (0, pos, end_x, end_y)
                else:
                    rng = pos

                app.tree_proc(self.h_tree,
                              app.TREE_ITEM_SET_RANGE,
                              identity,
                              index=-1,
                              text=rng)
                break

        app.tree_proc(self.h_tree, app.TREE_UNLOCK)
コード例 #2
0
    def execCurrentFileAsPlugin(self):
        fn  = ed.get_filename()
        if not fn.endswith('.py'):
            return app.msg_status(_('Fail. Use only for python file.'))
        ed.save()
        app.app_log(app.LOG_CONSOLE_CLEAR, 'm')
        cmd = r'exec(open(r"{fn}", encoding="UTF-8").read().lstrip("\uFEFF"))'
#       cmd = f(r'exec(open(r"{}", encoding="UTF-8").read().lstrip("\uFEFF"))', fn)
        pass;                  #log('cmd={!r}',(cmd))
        ans     = app.app_proc(app.PROC_EXEC_PYTHON, cmd)
        print('>>> run {!r}'.format(fn))
        print(ans)
コード例 #3
0
ファイル: cd_ext.py プロジェクト: modulexcite/CudaText
 def open_selected(self):
     pass;                  #LOG and log('ok',)
     bs_dir  = os.path.dirname(ed.get_filename())
     crts    = ed.get_carets()
     for (cCrt, rCrt, cEnd, rEnd) in crts:
         if -1==cEnd: continue
         if rCrt!=rEnd: continue
         (rTx1, cTx1), (rTx2, cTx2) = apx.minmax((rCrt, cCrt), (rEnd, cEnd))
         selTx   = ed.get_text_substr(cTx1, rTx1, cTx2, rTx2)
         op_file = os.path.join(bs_dir, selTx)
         if not os.path.exists(op_file):
             app.msg_status(NO_FILE_FOR_OPEN.format(op_file))
             continue
         op_ed   = _file_open(op_file)
         op_ed.focus()
コード例 #4
0
def do_report(fn):
    lex = ed.get_prop(app.PROP_LEXER_CARET)
    def_json = os.path.join(apx.get_def_setting_dir(), "default.json")
    usr_json = os.path.join(app.app_path(app.APP_DIR_SETTINGS), "user.json")
    lex_json = os.path.join(app.app_path(app.APP_DIR_SETTINGS), "lexer {}.json".format(lex))

    #   def_opts    = apx.get_app_default_opts()
    #   pass;                       LOG and log('?? get_app_default_opts')
    #   def_opts    = apx.get_app_default_opts(         object_pairs_hook=collections.OrderedDict)

    #   if 'font_name' != list(def_opts.keys())[0]:
    #       pass;                   apx.log('Not natural order')
    #       return False

    def_opts = apx._get_file_opts(def_json, {}, object_pairs_hook=collections.OrderedDict)
    usr_opts = apx._get_file_opts(usr_json, {}, object_pairs_hook=collections.OrderedDict)
    lex_opts = apx._get_file_opts(lex_json, {}, object_pairs_hook=collections.OrderedDict)

    def_opts = pickle.loads(pickle.dumps(def_opts))  # clone to pop
    usr_opts = pickle.loads(pickle.dumps(usr_opts))  # clone to pop
    lex_opts = pickle.loads(pickle.dumps(lex_opts))  # clone to pop

    fil_opts = get_ovrd_ed_opts(ed)
    cmt_opts = {}
    # Find Commentary for def opts in def file
    # Rely: _commentary_ is some (0+) lines between opt-line and prev opt-line
    def_body = open(def_json).read()
    def_body = def_body.replace("\r\n", "\n").replace("\r", "\n")
    def_body = def_body[def_body.find("{") + 1 :]  # Cut head with start '{'
    def_body = def_body.lstrip()
    for opt in def_opts.keys():
        pos_opt = def_body.find('"{}"'.format(opt))
        cmt = def_body[:pos_opt].strip()
        cmt = re.sub("^\s*//", "", cmt, flags=re.M)
        cmt = cmt.strip()
        cmt_opts[opt] = html.escape(cmt)
        def_body = def_body[def_body.find("\n", pos_opt) + 1 :]  # Cut the opt

    with open(fn, "w", encoding="utf8") as f:
        f.write(RPT_HEAD)
        f.write("<h4>Hign priority: editor options</h4>")
        f.write("<table>\n")
        f.write("<tr>\n")
        f.write("<th>Option name</th>\n")
        f.write("<th>Value in<br>default</th>\n")
        f.write("<th>Value in<br>user</th>\n")
        f.write("<th>Value in<br>lexer<br>{}</th>\n".format(lex))
        f.write(
            '<th title="{}">Value in<br>file<br>{}</th>\n'.format(
                ed.get_filename(), os.path.basename(ed.get_filename())
            )
        )
        f.write("<th>Comment</th>\n")
        f.write("</tr>\n")
        for opt in fil_opts.keys():
            winner = "def"
            winner = "usr" if opt in usr_opts else winner
            winner = "lex" if opt in lex_opts else winner
            winner = "fil" if opt in fil_opts else winner
            f.write("<tr>\n")
            f.write("<td>{}</td>\n".format(opt))
            f.write('<td class="{}">{}</td>\n'.format("win" if winner == "def" else "nxt", def_opts.get(opt, "")))
            f.write('<td class="{}">{}</td>\n'.format("win" if winner == "usr" else "nxt", usr_opts.get(opt, "")))
            f.write('<td class="{}">{}</td>\n'.format("win" if winner == "lex" else "nxt", lex_opts.get(opt, "")))
            f.write('<td class="{}">{}</td>\n'.format("win" if winner == "fil" else "nxt", fil_opts.get(opt, "")))
            f.write("<td><pre>{}</pre></td>\n".format(cmt_opts.get(opt, "")))
            f.write("</tr>\n")
            def_opts.pop(opt, None)
            usr_opts.pop(opt, None)
            lex_opts.pop(opt, None)
        f.write("</table><br/>\n")
        f.write("<h4>Overridden default options</h4>")
        f.write("<table>\n")
        f.write("<tr>\n")
        f.write("<th>Option name</th>\n")
        f.write("<th>Value in<br>default</th>\n")
        f.write("<th>Value in<br>user</th>\n")
        f.write("<th>Value in<br>lexer<br>{}</th>\n".format(lex))
        f.write("<th>Comment</th>\n")
        f.write("</tr>\n")
        for opt in def_opts.keys():
            winner = "def"
            winner = "usr" if opt in usr_opts else winner
            winner = "lex" if opt in lex_opts else winner
            winner = "fil" if opt in fil_opts else winner
            f.write("<tr>\n")
            f.write("<td>{}</td>\n".format(opt))
            f.write('<td class="{}">{}</td>\n'.format("win" if winner == "def" else "nxt", def_opts.get(opt, "")))
            f.write('<td class="{}">{}</td>\n'.format("win" if winner == "usr" else "nxt", usr_opts.get(opt, "")))
            f.write('<td class="{}">{}</td>\n'.format("win" if winner == "lex" else "nxt", lex_opts.get(opt, "")))
            f.write("<td><pre>{}</pre></td>\n".format(cmt_opts.get(opt, "")))
            f.write("</tr>\n")
            usr_opts.pop(opt, None)
            lex_opts.pop(opt, None)
        f.write("</table><br/>\n")
        f.write("<h4>Overridden user-only options</h4>")
        f.write("<table>\n")
        f.write("<tr>\n")
        f.write("<th>Option name</th>\n")
        f.write("<th>Value in<br>user</th>\n")
        f.write("<th>Value in<br>lexer<br>{}</th>\n".format(lex))
        f.write("<th>Comment</th>\n")
        f.write("</tr>\n")
        for opt in usr_opts.keys():
            winner = "usr"
            winner = "lex" if opt in lex_opts else winner
            f.write("<tr>\n")
            f.write("<td>{}</td>\n".format(opt))
            f.write('<td class="{}">{}</td>\n'.format("win" if winner == "usr" else "nxt", usr_opts.get(opt, "")))
            f.write('<td class="{}">{}</td>\n'.format("win" if winner == "lex" else "nxt", lex_opts.get(opt, "")))
            f.write("<td><pre>{}</pre></td>\n".format(cmt_opts.get(opt, "")))
            f.write("</tr>\n")
            lex_opts.pop(opt, None)
        for opt in lex_opts.keys():
            winner = "lex"
            f.write("<tr>\n")
            f.write("<td>{}</td>\n".format(opt))
            f.write('<td class="{}"></td>  \n'.format("non"))
            f.write('<td class="{}">{}</td>\n'.format("win", lex_opts.get(opt, "")))
            f.write("<td><pre>{}</pre></td>\n".format(cmt_opts.get(opt, "")))
            f.write("</tr>\n")
            lex_opts.pop(opt, None)
        f.write("</table><br/>\n")
        f.write(RPT_FOOT)
        return True
コード例 #5
0
ファイル: cd_favs.py プロジェクト: kvichans/cuda_favorites
    def dlg(self):
        if app.app_api_version()<'1.0.146':  return app.msg_status(_("Need update CudaText"))   # dlg_custom: "type=tabs"
        pass;                  #LOG and log('=',())
        fvdata  = get_fav_data()
        tab_nms = fvdata.get('fv_tabs', [_('Fi&les'), _('Pro&jects')])
        tabs    = fvdata.get('fv_tab', 0)
        files   = fvdata.get('fv_files', [])
        projs   = fvdata.get('fv_projs', [])
        fold    = fvdata.get('fv_fold', True)
        last    = fvdata.get('fv_last', 0)
        fvrs_h  = _('Choose file to open.')
        brow_h  = _('Choose file to append.'
                '\r    Shift+Click to choose folder'
                   )
        def n2c(n):
            if  1<=n<=10:                   return str(n%10)
            if 11<=n<=11+ord('Z')-ord('A'): return chr(n-11+ord('A'))
            return ' '
        while True:
            paths   = files if tabs==0 else projs
            last    = min(max(0, last), len(paths)-1)
            hasf    = bool(paths)
            itms    = [f('{}: {}{}'
                    , n2c(1+nf)
                    , os.path.basename(fn) 
                        if os.path.isfile(fn) else 
                      '['+os.path.basename(fn)+']' 
                        if os.path.isdir(fn) else 
                      '? '+os.path.basename(fn) 
                    , ' ('+os.path.dirname(fn)+')' if fold else ''
                    ) 
                    for nf,fn in enumerate(paths)]
            itms    = itms if itms else [' ']
            aid,vals,chds   = dlg_wrapper(_('Favorites'), 500+10,300+10,
                 [
#                 dict(           tp='lb'   ,t=5            ,l=5            ,w=400      ,cap=_('&Files:')   ,hint=fvrs_h        ) # &f
                  dict(cid='tabs',tp='tabs' ,t=5,h=30       ,l=5            ,w=400-3    ,items=tab_nms          ,act='1'        ) # 
                 ,dict(cid='fvrs',tp='lbx'  ,t=5+23,h=240   ,l=5            ,w=400-5    ,items=itms                     ,en=hasf)
                 ,dict(cid='open',tp='bt'   ,t=5+20         ,l=5+400        ,w=100      ,cap=_('&Open')     ,props='1'  ,en=hasf) #     default
                 ,dict(cid='addc',tp='bt'   ,t=5+65         ,l=5+400        ,w=100      ,cap=_('&Add opened')           ,en=(tabs==0)) # &a
                 ,dict(cid='brow',tp='bt'   ,t=5+90         ,l=5+400        ,w=100      ,cap=_('Add&...')   ,hint=brow_h        ) # &.
                 ,dict(cid='delt',tp='bt'   ,t=5+135        ,l=5+400        ,w=100      ,cap=_('&Delete')               ,en=hasf) # &d
                 ,dict(cid='fvup',tp='bt'   ,t=5+180        ,l=5+400        ,w=100      ,cap=_('Move &up')              ,en=hasf) # &u
                 ,dict(cid='fvdn',tp='bt'   ,t=5+205        ,l=5+400        ,w=100      ,cap=_('Move do&wn')            ,en=hasf) # &w
                 ,dict(cid='fold',tp='ch'   ,tid='-'        ,l=5            ,w=120      ,cap=_('Show &paths')   ,act='1'        ) # &p
                 ,dict(cid='help',tp='bt'   ,t=5+300-53     ,l=5+500-100    ,w=100      ,cap=_('&Help')                         ) # &h
                 ,dict(cid='-'   ,tp='bt'   ,t=5+300-28     ,l=5+500-100    ,w=100      ,cap=_('Close')                         )
                 ]+
                 [dict(cid='act'+str(n),tp='bt',cap='&'+str((n+1)%10),t=0,l=0,w=0) for n in range(10)]                           # &1 - &0
                 ,    dict(fvrs=last
                          ,tabs=tabs
                          ,fold=fold), focus_cid='fvrs')
            if aid is None or aid=='-': return None
            scam    = app.app_proc(app.PROC_GET_KEYSTATE, '')
            if aid=='help':
                dlg_wrapper(_('Help for "Favorites"'), 410, 310,
                     [dict(cid='htxt',tp='me'    ,t=5  ,h=300-28,l=5          ,w=400  ,props='1,0,1'  ) #  ro,mono,border
                     ,dict(cid='-'   ,tp='bt'    ,t=5+300-23    ,l=5+400-80   ,w=80   ,cap=_('&Close'))
                     ], dict(htxt=_(  '• Quick opening.'
                                    '\rUse Alt+1, Alt+2, ..., Alt+9, Alt+0'
                                    '\rto direct open file'
                                    '\r"1: *", "2: *",..., "9: *", "0: *"'
                                    '\r '
                                    '\r• Import. '
                                    '\rSelect "SynFav.ini" for "Add..." to import Favorites from SynWrite.'
                                    '\rSee "SynFav.ini" in folder "SynWrite/Settings".'
                                    )
                     ), focus_cid='htxt')
                continue#while
            
            fold    = vals['fold']
            last    = vals['fvrs']
            tabs    = vals['tabs']
            def save_and_open(path):
                fvdata['fv_tab']    = tabs
                fvdata['fv_files']  = files
                fvdata['fv_projs']  = projs
                fvdata['fv_fold' ]  = fold 
                fvdata['fv_last' ]  = last 
                save_fav_data(fvdata)
                if os.path.isdir( path):
                    path= app.dlg_file(True, '', path, '')
                    if not path:    return False
                app.file_open(path)
                return True
               #def save_and_open
            if aid=='open' and paths and last>=0:
                if save_and_open(paths[last]):
                    break#while
            if aid[0:3]=='act' and paths:
                nf  = int(aid[3])
                if nf<len(paths) and save_and_open(paths[nf]):
                    break#while
                    
            if aid=='tabs':
                pass;          #LOG and log('tabs={}',(tabs))
                continue#while
            
            # Modify
            store_b = 'fold' in chds
            if False:pass
            elif aid=='addc':
                fn      = ed.get_filename()
                if fn and not any([os.path.samefile(fn, f) for f in paths]):
                    paths  += [fn]
                    store_b = True
#           elif aid=='brow' and scam=='s': 
#               # Ask dir
#               dr      = dlg_dir('')
#               if dr
            elif aid=='brow':
                # Ask file
                fn      = app.dlg_dir('') if scam=='s' else app.dlg_file(True, '', '', '')
                if fn and os.path.basename(fn).upper()=='SynFav.ini'.upper():
                    store_b = import_SynFav(fn, paths)
                elif fn and not any([os.path.samefile(fn, f) for f in paths]):
                    paths  += [fn]
                    store_b = True
            elif aid=='delt' and paths and last>=0:
                del paths[last]
                last    = min(max(0, last), len(paths)-1)
                store_b = True
            elif aid in ('fvup', 'fvdn') and paths:
                newp    = last + (-1 if aid=='fvup' else +1)
                if 0<=newp<len(paths):
                    paths[last], paths[newp] = paths[newp], paths[last]
                    last    = newp
                    store_b = True
            
            # Store
            if store_b:
                fvdata['fv_tab']    = tabs
                fvdata['fv_files']  = files
                fvdata['fv_projs']  = projs
                fvdata['fv_fold' ]  = fold 
                fvdata['fv_last' ]  = last 
                save_fav_data(fvdata)
コード例 #6
0
ファイル: cd_favs.py プロジェクト: kvichans/cuda_favorites
 def add_cur_file(self):
     self._add_filename(ed.get_filename())