示例#1
0
    def duplicate(self):
        if ed.get_sel_mode() != app.SEL_NORMAL:
            return app.msg_status(ONLY_NORM_SEL_MODE.format(DUPLICATION))

        crts    = ed.get_carets()
        if len(crts)>1:
            return app.msg_status(ONLY_SINGLE_CRT.format(DUPLICATION))

        (cCrt, rCrt, cEnd, rEnd)    = crts[0]
        if -1==cEnd:
            # Empty sel -- dup whole row
            row_txt    = ed.get_text_line(rCrt)
            ed.insert(0, rCrt, row_txt+'\n')

            # Move crt to next row
            if (rCrt+1)<ed.get_line_count():
                colCrt  = pos2pos(cCrt  , rCrt,   'smb2col')
                smbCrt1 = pos2pos(colCrt, rCrt+1, 'col2smb')
                ed.set_caret(smbCrt1, rCrt+1)
            return

        (rFr, cFr), (rTo, cTo)  = minmax((rCrt, cCrt), (rEnd, cEnd))
        #pass;                   LOG and log('(cCrt, rCrt, cEnd, rEnd)={}',(cCrt, rCrt, cEnd, rEnd))
        pass;                   LOG and log('(cFr , rFr , cTo , rTo) ={}',(cFr , rFr , cTo , rTo))
        sel_txt = ed.get_text_substr(cFr, rFr, cTo, rTo)
        pass;                   LOG and log('sel_txt={}',repr(sel_txt))
        ed.insert(cFr, rFr, sel_txt)
        if -1==rEnd: # or rCrt==rEnd:
            # Move crt to next row
            colCrt  = pos2pos(cCrt  , rCrt,   'smb2col')
            smbCrt1 = pos2pos(colCrt, rCrt+1, 'col2smb')
            ed.set_caret(smbCrt1, rCrt+1)
 def save(self):
     ''' Save cur session to file '''
     if not _checkAPI(): return
     sscur       = app.app_path(app.APP_FILE_SESSION)
     app.app_proc(app.PROC_SAVE_SESSION, sscur)
     app.msg_status(SAVED.format(stem=juststem(sscur)))
     self.top_sess(sscur)
 def _jump_to_ibm(self, what):
     ibms,   \
     msg     = self._ibms_in_tab(ed, self.bm_signs)
     if not ibms and msg: return app.msg_status(msg)
     if not ibms: return app.msg_status(_('No in-text bookmarks'))
     rCrt = ed.get_carets()[0][1]
     if  1==len(ibms) \
     and rCrt==ibms[0][1]:
         return app.msg_status(_('No more bookmarks'))
     line_ns = [
         line_n for (tab_id, line_n, bm_msg, line_s, tab_info) in ibms
     ]
     if self.wrap:
         line_ns = [-line_ns[-1]] + line_ns + [line_ns[0] + 0xFFFFFFFF]
     line_cns = [
         line_n for line_n in line_ns
         if (line_n > rCrt if what == 'next' else line_n < rCrt)
     ]
     if not line_cns: return app.msg_status(_('No bookmark for jump'))
     line_n = min(line_cns) if what == 'next' else max(line_cns)
     line_n = -line_n if line_n < 0 else line_n
     line_n = line_n - 0xFFFFFFFF if line_n >= 0xFFFFFFFF else line_n
     ed.set_caret(0, line_n)
     if not (ed.get_prop(app.PROP_LINE_TOP) <= line_n <= ed.get_prop(
             app.PROP_LINE_BOTTOM)):
         ed.set_prop(
             app.PROP_LINE_TOP,
             str(max(0, line_n - max(5, apx.get_opt('find_indent_vert')))))
    def on_mouse_stop(self, ed_self, x, y):

        ct.msg_status("")
        res = ed_self.convert(ct.CONVERT_PIXELS_TO_CARET, x, y, "")
        if res is None:
            return
        x, y = res
        if y == 0:
            return

        s = ed_self.get_text_line(y)
        if not s:
            return
        if x >= len(s):
            return

        sep = self.get_sep(ed_self)
        res = parse_csv_line(s, sep=sep)
        if not res:
            return

        for x1, x2, kind in res:
            if x1 <= x < x2:
                if kind >= 0:
                    cap = self.get_header(ed_self, kind, sep) or "?"
                    ct.msg_status("Column %d (%s)" % (kind + 1, cap))
                break
示例#5
0
    def show_docstring(self):
        if not self.app.environment:
            return

        cursor = self.app.cursor
        if not cursor:
            return

        items = self.app.script.goto(
            line=cursor.row,
            column=cursor.x)

        if items:
            text = items[0].docstring()
        else:
            return

        if text:
            ct.app_log(ct.LOG_CLEAR, '', panel=ct.LOG_PANEL_OUTPUT)
            for s in text.splitlines():
                ct.app_log(ct.LOG_ADD, s, panel=ct.LOG_PANEL_OUTPUT)

            ct.ed.cmd(cmds.cmd_ShowPanelOutput)
            ct.ed.focus()
        else:
            ct.msg_status('Cannot find doc-string')
def process_ocurrences(sel_occurrences=False):
    global occurrences

    ed.attr(app.MARKERS_DELETE_BY_TAG, MARKTAG)
    app.msg_status('')

    if sel_occurrences:
        # In this part of the events, occurrences variable must have data.
        # If not, force matches considering no min length selection.
        if len(occurrences) == 0 and opt.MARK_IGNORE_MIN_LEN:
            log("No previous occurrences information")
            res = _get_occurrences(sel_occurrences)

            if not res:
                occurrences = ()
                return
            else:
                occurrences = res

        return occurrences

    else:

        # The highlight function on_caret event only works with one caret.
        if len(ed.get_carets()) != 1: return

        res = _get_occurrences()

        if res is None:
            occurrences = ()
            return
        else:
            occurrences = res

        return occurrences
 def run(self):
     # pass;                   apx.log('??')
     # pass;                   apx.log('apx.get_def_setting_dir()={}',apx.get_def_setting_dir())
     htm_file = os.path.join(tempfile.gettempdir(), "CudaText_overided_options.html")
     if do_report(htm_file):
         webbrowser.open_new_tab("file://" + htm_file)
         app.msg_status("Opened browser with file " + htm_file)
示例#8
0
    def duplicate(self):
        if ed.get_sel_mode() != app.SEL_NORMAL:
            return app.msg_status(ONLY_NORM_SEL_MODE.format(DUPLICATION))

        crts    = ed.get_carets()
        if len(crts)>1:
            return app.msg_status(ONLY_SINGLE_CRT.format(DUPLICATION))

        (cCrt, rCrt, cEnd, rEnd)    = crts[0]
        bEmpSel = -1==rEnd
        bUseFLn = get_opt('duplicate_full_line_if_no_sel', True)
        bSkip   = get_opt('duplicate_move_down', True)
        if bEmpSel:
            if not bUseFLn:
                return
            # Dup whole row
            row_txt    = ed.get_text_line(rCrt)
            ed.insert(0, rCrt, row_txt+'\n')

            # Move crt to next row
            if bSkip and (rCrt+1)<ed.get_line_count():
                _move_caret_down(cCrt, rCrt)
            return

        (rFr, cFr), (rTo, cTo)  = minmax((rCrt, cCrt), (rEnd, cEnd))
        pass;                  #LOG and log('(cFr , rFr , cTo , rTo) ={}',(cFr , rFr , cTo , rTo))
        sel_txt = ed.get_text_substr(cFr, rFr, cTo, rTo)
        pass;                  #LOG and log('sel_txt={}',repr(sel_txt))
        ed.insert(cFr, rFr, sel_txt)
 def dlg_ibms_in_tab(self):
     ibms,   \
     msg     = self._ibms_in_tab(ed, self.bm_signs)
     if not ibms and msg:    return app.msg_status(msg)
     if not ibms:            return app.msg_status(_('No in-text bookmarks'))
     line_max= max([line_n for (tab_id, line_n, bm_msg, line_s, tab_info) in ibms])
     ln_wd   = len(str(line_max))
     pass;                  #LOG and log('ln_wd={}',(ln_wd))
     ibms    = [(bm_msg, line_n, f('{} {}', str(1+line_n).rjust(ln_wd, ' '), line_s)) 
             for (tab_id, line_n, bm_msg, line_s, tab_info) in ibms]
     pass;                  #LOG and log('ibms=¶{}',pf(ibms))
     rCrt    = ed.get_carets()[0][1]
     near    = min([(abs(line_n-rCrt), ind) 
             for ind, (bm_msg, line_n, line_s) in enumerate(ibms)])[1]
     if self.show_wo_alt:
         ans = app.dlg_menu(app.MENU_LIST, '\n'.join(
                 [f('{}\t{}', line_nd, bm_msg) for bm_msg, line_n, line_nd in ibms]
             ), near)
     else:
         ans = app.dlg_menu(app.MENU_LIST_ALT, '\n'.join(
                 [f('{}\t{}', bm_msg, line_nd) for bm_msg, line_n, line_nd in ibms]
             ), near)
     if ans is None:     return
     bm_msg, line_n, line_nd    = ibms[ans]
     ed.set_caret(0, line_n)
     if not (ed.get_prop(app.PROP_LINE_TOP) <= line_n <= ed.get_prop(app.PROP_LINE_BOTTOM)):
         ed.set_prop(app.PROP_LINE_TOP, str(max(0, line_n - max(5, apx.get_opt('find_indent_vert')))))
示例#10
0
    def __init__(self):
        cmd_nms = [
            nm for nm in dir(cmds)
            if nm.startswith('cCommand_') or nm.startswith('cmd_')
        ]
        cmd_nm2id = {nm: eval('cmds.{}'.format(nm)) for nm in cmd_nms}
        self.CMD_ID2NM = {str(cmd_id): nm for nm, cmd_id in cmd_nm2id.items()}
        if len(self.CMD_ID2NM) < len(cmd_nm2id):
            app.msg_status('Repeated values in cudatext_cmd.py')
        pass
        #LOG and log('cmd_nm2id={}',cmd_nm2id)
        pass
        #LOG and log('CMD_ID2NM={}',self.CMD_ID2NM)

        ver_macros = apx._json_loads(
            open(MACROS_JSON).read()) if os.path.exists(MACROS_JSON) else {
                'ver': JSON_FORMAT_VER,
                'list': []
            }
        if ver_macros['ver'] < JSON_FORMAT_VER:
            # Adapt to new format
            pass
        self.tm_ctrl = ver_macros.get('tm_ctrl', {})
        self.dlg_prs = ver_macros.get('dlg_prs', {})
        self.macros = ver_macros['list']
        self.mcr4id = {str(mcr['id']): mcr for mcr in self.macros}

        self.need_dlg = False
        self.last_mcr_id = 0

        pass
        LOG and log('\n\n\nMacros start', )
    def _subst(self, which, wdex):
        """ Do completion.
            Params
                which   Which variant to use
                            'next' / 'prev' / '#N'
                wdex    What list to use
                            'word' / 'expr' / 'curr'
        """
        pass
        #LOG and log('which, wdex={}',(which, wdex))
        if wdex!='curr' and \
           not self._prep_sess(wdex):
            return
        if not self.sess.bids:
            return app.msg_status(_('No in-text completions'))
        shft = 1 if which == 'next' else -1 if which == 'prev' else 0
        bids_i  = int(which)                if which.isdigit()  else \
                  self.sess.bids_i + shft   if self.incr_bfr    else \
                  self.sess.bids_i
        bids_i = bids_i % len(self.sess.bids)
        sub_s = self.sess.bids[bids_i]
        add_s = sub_s[len(self.sess.src_what):]
        pass
        #LOG and log('i, sub_s, add_s={}',(bids_i, sub_s, add_s))

        if self.sess.added:
            ed.cmd(cmds.cCommand_Undo)
            pass
            #LOG and log('undo mod_ver, line={}',(ed.get_prop(app.PROP_MODIFIED_VERSION), ed.get_text_line(self.sess.row)))
        ed.delete(self.sess.src_kill_b, self.sess.row, self.sess.src_kill_e,
                  self.sess.row)
        pass
        #LOG and log('kill mod_ver, line={}',(ed.get_prop(app.PROP_MODIFIED_VERSION), ed.get_text_line(self.sess.row)))
        ed.insert(self.sess.src_what_e, self.sess.row, add_s)
        pass
        #LOG and log('insr mod_ver, line={}',(ed.get_prop(app.PROP_MODIFIED_VERSION), ed.get_text_line(self.sess.row)))
        self.sess.added = True
        if False: pass
        elif self.sess.sel_sub == 'be':
            ed.set_caret(self.sess.src_what_e + len(add_s), self.sess.row,
                         self.sess.src_what_b, self.sess.row)
        elif self.sess.sel_sub == 'eb':
            ed.set_caret(self.sess.src_what_b, self.sess.row,
                         self.sess.src_what_e + len(add_s), self.sess.row)
        else:
            ed.set_caret(self.sess.src_what_e + len(add_s), self.sess.row)
#           ed.set_caret(self.sess.src_crt,                 self.sess.row)
        self.sess.pre_mver = ed.get_prop(app.PROP_MODIFIED_VERSION)
        self.sess.pre_crt0 = ed.get_carets()[0]

        #       next_i      = (self.sess.bids_i+shft) % len(self.sess.bids)
        #       next_info   = '' if 1==len(self.sess.bids) else \
        #                     f(_('. Next #{}: "{}"'), next_i, self.sess.bids[next_i][:50])
        #       app.msg_status(f(_('In-text completion #{} ({}){}'), 1+self.sess.bids_i, len(self.sess.bids), next_info))
        app.msg_status(
            f(_('In-text completion #{} ({})'), 1 + self.sess.bids_i,
              len(self.sess.bids)))
        #       shft                = 1 if which=='next' or which[0]=='#' else -1
        self.sess.bids_i = bids_i
        self.incr_bfr = True
    def open(self, ssnew=None):
        ''' Open new session from file ssnew or after user asking '''
        if not _checkAPI(): return
        #       in_dir      = app.app_path(app.APP_DIR_DATA)
        sscur = app.app_path(app.APP_FILE_SESSION)
        sscur_save = app.app_proc(app.PROC_SAVE_SESSION, sscur)
        pass
        #LOG and log('sscur_save={}',(sscur_save))
        if sscur_save == False:
            return
        if ssnew is None:
            ssnew = app.dlg_file(
                is_open=True,
                filters=DLG_ALL_FILTER,
                init_filename='!'  # '!' to disable check "filename exists"
                ,
                init_dir='')
        if ssnew is None: return
        if ssnew.endswith(SWSESS_EXT) and os.path.isfile(ssnew):
            # Import from Syn
            sssyn = ssnew
            sscud = ssnew[:-len(SWSESS_EXT)] + CDSESS_EXT
            if os.path.isfile(sscud):
                sscud = app.dlg_file(is_open=False,
                                     filters=DLG_CUD_FILTER,
                                     init_filename=os.path.basename(sscud),
                                     init_dir=os.path.dirname(sscud))
                if not sscud: return
            if not import_syn_sess(sssyn, sscud): return
            ssnew = sscud

        pass
        #LOG and log('ssnew={}',(ssnew))
        ssnew = apx.icase(False, '', ssnew.endswith(CDSESS_EXT), ssnew,
                          os.path.isfile(ssnew), ssnew, True,
                          ssnew + CDSESS_EXT)
        pass
        #LOG and log('ssnew={}',(ssnew))
        if os.path.isfile(ssnew):
            # Open
            #           app.app_proc(app.PROC_SAVE_SESSION, sscur)
            ssnew_load = app.app_proc(app.PROC_LOAD_SESSION, ssnew)
            pass
            #LOG and log('ssnew_load={}',(ssnew_load))
            if ssnew_load == False:
                return
            app.app_proc(app.PROC_SET_SESSION, ssnew)
            app.msg_status(OPENED.format(stem=juststem(ssnew)))
            self.top_sess(ssnew)
        else:
            # New
            if app.ID_NO == app.msg_box(
                    CREATE_ASK.format(stem=juststem(ssnew)), app.MB_YESNO):
                return
            #           app.app_proc(app.PROC_SAVE_SESSION, sscur)
            app.ed.cmd(cmds.cmd_FileCloseAll)
            app.app_proc(app.PROC_SET_SESSION, ssnew)
            app.app_proc(app.PROC_SAVE_SESSION, ssnew)
            app.msg_status(CREATED.format(stem=juststem(ssnew)))
            self.top_sess(ssnew)
示例#13
0
    def duplicate(self):
        if ed.get_sel_mode() != app.SEL_NORMAL:
            return app.msg_status(ONLY_NORM_SEL_MODE.format(DUPLICATION))

        crts = ed.get_carets()
        if len(crts) > 1:
            return app.msg_status(ONLY_SINGLE_CRT.format(DUPLICATION))

        (cCrt, rCrt, cEnd, rEnd) = crts[0]
        bEmpSel = -1 == rEnd
        bUseFLn = get_opt('duplicate_full_line_if_no_sel', True)
        bSkip = get_opt('duplicate_move_down', True)
        if bEmpSel:
            if not bUseFLn:
                return
            # Dup whole row
            row_txt = ed.get_text_line(rCrt)
            ed.insert(0, rCrt, row_txt + '\n')

            # Move crt to next row
            if bSkip and (rCrt + 1) < ed.get_line_count():
                _move_caret_down(cCrt, rCrt)
            return

        (rFr, cFr), (rTo, cTo) = minmax((rCrt, cCrt), (rEnd, cEnd))
        pass
        #LOG and log('(cFr , rFr , cTo , rTo) ={}',(cFr , rFr , cTo , rTo))
        sel_txt = ed.get_text_substr(cFr, rFr, cTo, rTo)
        pass
        #LOG and log('sel_txt={}',repr(sel_txt))
        ed.insert(cFr, rFr, sel_txt)
示例#14
0
	def report_to_html(self):
		if app_name=='CudaText' and app.app_api_version()<'1.0.105':
			app.msg_box('Plugin needs newer app version', app.MB_OK)
			return

		htm_file = os.path.join(tempfile.gettempdir(), '{}_keymapping.html'.format(app_name))
		do_report(htm_file)
		webbrowser.open_new_tab('file://'+htm_file)
		app.msg_status('Opened browser with file '+htm_file)
示例#15
0
 def goto_file(self, filename, row, col=0):
     """open definition file and mark line"""
     if not os.path.isfile(filename):
         return
     ct.file_open(filename)
     ct.ed.set_prop(ct.PROP_LINE_TOP, str(max(0, row - 5)))  # 5 = Offset
     ct.ed.set_caret(col, row - 1)
     ct.msg_status('Goto "%s", Line %d' % (filename, row))
     return True
示例#16
0
    def disable(self):
        self.en = False
        app.msg_status('CudaLint disabled')

        # clear bookmarks
        for h in app.ed_handles():
            e = app.Editor(h)
            e.bookmark(app.BOOKMARK_CLEAR_ALL, 0)
        self.clear_valid_pan()
示例#17
0
    def disable(self):
        self.en = False
        app.msg_status('CudaLint disabled')

        # clear bookmarks
        for h in app.ed_handles():
            e = app.Editor(h)
            e.bookmark(app.BOOKMARK_DELETE_BY_TAG, 0, tag=options.MY_TAG)
        self.clear_valid_pan()
示例#18
0
	def report_to_html(self):
#		if app_name=='CudaText' and app.app_api_version()<'1.0.105':
		if app_name=='CudaText' and app.app_api_version()<'1.0.212':     # depr PROC_GET_COMMAND, PROC_GET_COMMAND_PLUGIN
			app.msg_box(_('Plugin needs newer app version'), app.MB_OK)
			return

		htm_file = os.path.join(tempfile.gettempdir(), '{}_keymapping.html'.format(app_name))
		do_report(htm_file)
		webbrowser.open_new_tab('file://'+htm_file)
		app.msg_status(_('Opened browser with file ')+htm_file)
示例#19
0
    def install(self, *args, **kwargs):
        ext = self.exts[self.item_index]
        ct.dlg_proc(self.h, ct.DLG_HIDE)
        ct.msg_status(' '.join(
            [_("Installing: "), ext['display_name'], ext['version']]),
                      process_messages=True)

        self.data = vs.download(ext['url'])
        if not self.data:
            return
示例#20
0
 def _add_filename(self, fn, is_project=False):
     if not fn:  return
     s_key = 'fv_projs' if is_project else 'fv_files'
     fvdata  = get_fav_data()
     files   = fvdata.get(s_key, [])
     if any([os.path.samefile(fn, f) for f in files]):
         return app.msg_status(_('Already in Favorites: ')+fn)
     files  += [fn]
     fvdata[s_key] = files
     save_fav_data(fvdata)
     app.msg_status(_('Added to Favorites: ')+fn)
示例#21
0
    def do_insert(self, s):

        x, y, x1, y1 = ed.get_carets()[0]
        if y1 >= 0:
            if (y, x) > (y1, x1):
                x, y, x1, y1 = x1, y1, x, y
            ed.set_caret(x, y)
            ed.replace(x, y, x1, y1, s)
        else:
            ed.insert(x, y, s)

        app.msg_status('Date/time inserted')
示例#22
0
 def compare_with(self):
     fn0 = ct.ed.get_filename()
     if not fn0:
         ct.msg_status('Cannot compare untitled document')
         return
     if ct.ed.get_prop(ct.PROP_MODIFIED):
         ct.msg_status('Cannot compare modified document, save it first')
         return
     fn = ct.dlg_file(True, '!', '', '')
     if not fn:
         return
     self.set_files(fn0, fn)
    def save(self):
        ''' Save cur session to file '''
        if not _checkAPI(): return
        sscur = app.app_path(app.APP_FILE_SESSION)
        sscur_save = app.app_proc(app.PROC_SAVE_SESSION, sscur)
        if sscur_save == False:
            return


#       app.app_proc(app.PROC_SAVE_SESSION, sscur)
        app.msg_status(SAVED.format(stem=juststem(sscur)))
        self.top_sess(sscur)
    def _subst(self, which, wdex):
        """ Do completion.
            Params
                which   Which variant to use
                            'next' / 'prev' / '#N'
                wdex    What list to use
                            'word' / 'expr' / 'curr'
        """
        pass;                  #LOG and log('which, wdex={}',(which, wdex))
        if wdex!='curr' and \
           not self._prep_sess(wdex): return
        if not self.sess.bids:
            return app.msg_status(_('No in-text completions'))
        shft                = 1 if which=='next' else -1 if which=='prev' else 0
        bids_i  = int(which)                if which.isdigit()  else \
                  self.sess.bids_i + shft   if self.incr_bfr    else \
                  self.sess.bids_i
        bids_i  = bids_i % len(self.sess.bids)
        sub_s   = self.sess.bids[bids_i]
        add_s   = sub_s[len(self.sess.src_what):]
        pass;                  #LOG and log('i, sub_s, add_s={}',(bids_i, sub_s, add_s))

        if self.sess.added:
            ed.cmd(cmds.cCommand_Undo)
            pass;              #LOG and log('undo mod_ver, line={}',(ed.get_prop(app.PROP_MODIFIED_VERSION), ed.get_text_line(self.sess.row)))
        ed.delete(       self.sess.src_kill_b,              self.sess.row
                        ,self.sess.src_kill_e,              self.sess.row)
        pass;                  #LOG and log('kill mod_ver, line={}',(ed.get_prop(app.PROP_MODIFIED_VERSION), ed.get_text_line(self.sess.row)))
        ed.insert(       self.sess.src_what_e,              self.sess.row,  add_s)
        pass;                  #LOG and log('insr mod_ver, line={}',(ed.get_prop(app.PROP_MODIFIED_VERSION), ed.get_text_line(self.sess.row)))
        self.sess.added     = True
        if False:pass
        elif self.sess.sel_sub=='be':
            ed.set_caret(self.sess.src_what_e+len(add_s),   self.sess.row
                        ,self.sess.src_what_b,              self.sess.row)
        elif self.sess.sel_sub=='eb':
            ed.set_caret(self.sess.src_what_b,              self.sess.row
                        ,self.sess.src_what_e+len(add_s),   self.sess.row)
        else:
            ed.set_caret(self.sess.src_what_e+len(add_s),   self.sess.row)
#           ed.set_caret(self.sess.src_crt,                 self.sess.row)
        self.sess.pre_mver  = ed.get_prop(app.PROP_MODIFIED_VERSION)
        self.sess.pre_crt0  = ed.get_carets()[0]
        
#       next_i      = (self.sess.bids_i+shft) % len(self.sess.bids)
#       next_info   = '' if 1==len(self.sess.bids) else \
#                     f(_('. Next #{}: "{}"'), next_i, self.sess.bids[next_i][:50])
#       app.msg_status(f(_('In-text completion #{} ({}){}'), 1+self.sess.bids_i, len(self.sess.bids), next_info))
        app.msg_status(f(_('In-text completion #{} ({})'),   1+self.sess.bids_i, len(self.sess.bids)))
#       shft                = 1 if which=='next' or which[0]=='#' else -1
        self.sess.bids_i    = bids_i
        self.incr_bfr       = True
示例#25
0
    def dlg_export(self):
        ''' Show dlg for export some macros.
        '''
        if app.app_api_version()<FROM_API_VERSION:  return app.msg_status(_('Need update CudaText'))
        if 0==len(self.macros):                     return app.msg_status(_('No macros for export'))
        exp_file= app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros')
        exp_file= '' if exp_file is None else exp_file
        exp_file= exp_file+('' if ''==exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros')
        (WD_LST
        ,HT_LST)= (500
                  ,500)
        
        lmcrs   = len(self.macros)
        crt,sels= '0', ['0'] * lmcrs
        while True:
            pass;               LOG and log('sels={}',sels)

            cnts    = ([
  dict(              tp='lb'    ,tid='file'         ,l=GAP             ,w=70            ,cap=_('Export &to')                    )
 ,dict(cid='file'   ,tp='ed'    ,t=GAP              ,l=GAP+70          ,r=GAP+WD_LST-35 ,en='0'                                 )
 ,dict(cid='brow'   ,tp='bt'    ,tid='file'         ,l=GAP+HT_LST-35   ,r=GAP+WD_LST    ,cap=_('&...')                          )
 ,dict(cid='mcrs'   ,tp='ch-lbx',t=35   ,h=HT_LST   ,l=GAP             ,w=    WD_LST    ,items=[mcr['nm'] for mcr in self.macros])
 ,dict(cid='ch-a'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP*1           ,w=100           ,cap=_('Check &all')                    )
 ,dict(cid='ch-n'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP*2+100       ,w=100           ,cap=_('U&ncheck all')                  )
 ,dict(cid='expo'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=    WD_LST-70*2 ,w=70            ,cap=_('&Export')       ,props='1'      )   # default
 ,dict(cid='-'      ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP+WD_LST-70*1 ,w=70            ,cap=_('Close')                         )
                    ])
            vals    = dict( file=exp_file
                           ,mcrs=(crt, sels)
                        )
            btn,    \
            vals,   \
            chds    = dlg_wrapper(_('Export macros')   ,GAP+WD_LST+GAP, GAP*5+HT_LST+25*2-GAP, cnts, vals, focus_cid='mrcs')
            if btn is None or btn=='-': return
            crt,sels= vals['mcrs']
            pass;               LOG and log('sels={}',sels)
            if False:pass
            elif btn=='brow': #ans_s=='file':
                new_exp_file= app.dlg_file(False, '', '', 'Cuda macros|*.cuda-macros')
                if new_exp_file is not None:
                    exp_file    = new_exp_file
                    exp_file    = exp_file+('' if ''==exp_file or exp_file.endswith('.cuda-macros') else '.cuda-macros')
            elif btn=='ch-a': #ans_s=='all':
                sels    = ['1'] * lmcrs
            elif btn=='ch-n': #ans_s=='no':
                sels    = ['0'] * lmcrs
            elif btn=='expo': #ans_s=='exp':
                if '1' not in sels:
                    app.msg_box(_('Select some names'), app.MB_OK)
                    continue
                self.export_to_file(exp_file, [mcr for (ind, mcr) in enumerate(self.macros) if sels[ind]=='1'])
                return
 def show_list(self, wdex):
     if app.app_api_version()<'1.0.144': return app.msg_status(_('Need update CudaText'))
     if not self._prep_sess(wdex): return
     if not self.sess.bids:
         return app.msg_status(_('No in-text completions'))
     if self.sngl and 1==len(self.sess.bids):
         return self._subst('#0', 'curr')
     ed.complete_alt(c10.join([bd.replace(c9, '¬')                   # main text
                             +c9+f(':{}', 1+self.sess.bids_c[ibd])   # right text ":row"
                             +c9+str(ibd)                            # hidden text
                             for (ibd, bd) in enumerate(self.sess.bids)])
                    ,'in-te-co', 0
                    ,self.sess.bids_i)
示例#27
0
 def add_cur_proj(self):
     try:
         import cuda_project_man
     except ImportError:
         app.msg_status(_('Project Manager plugin not installed'))
         return
     
     pjm_info= cuda_project_man.global_project_info
     fn      = pjm_info.get('filename', '')
     if fn:
         self._add_filename(fn, True)
     else:
         app.msg_status(_('Project Manager plugin has not opened project'))
示例#28
0
def goto_file(filename, num_line, num_col):
    if not os.path.isfile(filename):
        return
    filename = str(filename)

    ct.file_open(filename, options="/nohistory")

    # needed because edaction_show_pos don't scroll w/o it
    ct.app_idle(False)
    ct.ed.action(ct.EDACTION_SHOW_POS, (num_col, num_line), (0, LINE_GOTO_OFFSET))
    ct.ed.set_caret(num_col, num_line, options=ct.CARET_OPTION_UNFOLD)

    ct.msg_status('Go to file: '+filename)
示例#29
0
def check_cudatext():

    fn = os.path.join(tempfile.gettempdir(), 'cudatext_download.html')
    app.msg_status('Downloading: '+DOWNLOAD_PAGE, True)
    get_url(DOWNLOAD_PAGE, fn, True)
    app.msg_status('')

    if not os.path.isfile(fn):
        app.msg_status('Cannot download: '+DOWNLOAD_PAGE)
        return

    text = open(fn, encoding='utf8').read()
    items = re.findall(DOWNLOAD_REGEX, text)
    if not items:
        app.msg_status('Cannot find download links')
        return

    items = sorted(items, key=lambda i:i[REGEX_GROUP_VER], reverse=True)
    print('Found links:')
    for i in items:
        print('  '+i[0])

    url = items[0][0]
    ver_inet = items[0][REGEX_GROUP_VER]
    ver_local = app.app_exe_version()

    if versions_ordered(ver_inet, ver_local):
        app.msg_box('Latest CudaText is already here.\nHere: %s\nInternet: %s'
                   %(ver_local, ver_inet), app.MB_OK+app.MB_ICONINFO)
        return

    if app.msg_box('Newer CudaText is available.\nHere: %s\nInternet: %s\n\nOpen download URL in browser?'
                  %(ver_local, ver_inet), app.MB_YESNO+app.MB_ICONINFO) == app.ID_YES:
        webbrowser.open_new_tab(url)
        print('Opened download URL')
示例#30
0
 def menu_dlg(self, items):
     names = [str(item) for item in items]
     if not names:
         ct.msg_status(_('No snippets for current lexer'))
         return
     try:
         focused = items.index(self.last_snippet)
     except ValueError:
         focused = 0
     i = ct.dlg_menu(ct.MENU_LIST, names, focused=focused, caption=_('Snippets'))
     if i is None:
         return
     self.last_snippet = items[i]
     self.last_snippet.insert(ct.ed)
示例#31
0
def check_cudatext():

    fn = os.path.join(tempfile.gettempdir(), 'cudatext_download.html')
    app.msg_status('Downloading: '+DOWNLOAD_PAGE, True)
    get_url(DOWNLOAD_PAGE, fn, True)
    app.msg_status('')

    if not os.path.isfile(fn):
        app.msg_status('Cannot download: '+DOWNLOAD_PAGE)
        return

    text = open(fn, encoding='utf8', errors='replace').read()
    items = re.findall(FILE_RE, text)
    if not items:
        app.msg_status('Cannot find download links')
        return

    items = sorted(items, reverse=True)
    print('Found links:')
    for i in items:
        print('  '+i[0])

    url = items[0][0]
    ver_inet = items[0][REGEX_GROUP_VER]
    ver_local = app.app_exe_version()

    if versions_ordered(ver_inet, ver_local):
        app.msg_box('Latest CudaText is already here.\nLocal: %s\nInternet: %s'
                   %(ver_local, ver_inet), app.MB_OK+app.MB_ICONINFO)
        return

    if app.msg_box('CudaText update is available.\nLocal: %s\nInternet: %s\n\nOpen download URL in browser?'
                  %(ver_local, ver_inet), app.MB_YESNO+app.MB_ICONINFO) == app.ID_YES:
        webbrowser.open_new_tab(url)
        print('Opened download URL')
示例#32
0
def go_back_tab():
    if app.app_api_version() < '1.0.253':
        return app.msg_status(NEED_UPDATE)
    pass
    #log("###",( ))
    eds = [app.Editor(h) for h in app.ed_handles()]  # Native order
    ed_tats = [(ed_, ed_.get_prop(app.PROP_ACTIVATION_TIME, ''))
               for ed_ in eds]
    ed_tats = [(at, ed_) for (ed_, at) in ed_tats if at]  # Only activated
    if len(ed_tats) < 2:
        return app.msg_status(_('No yet other activated tab'))
    ed_tats.sort(reverse=True, key=lambda ae: ae[0])
    ed_back = ed_tats[1][1]
    ed_back.focus()
示例#33
0
    def do_rprt(self, aid, ag):
        m,M         = self,CfgKeysDlg
        if False:pass
        elif aid=='trpt':
            # Compact report to tab
            app.file_open('')
            ed.set_text_all(get_str_report())

        elif aid=='hrpt':
            # Full report to HTML
            htm_file = os.path.join(tempfile.gettempdir(), '{}_keymapping.html'.format(app_name))
            do_report(htm_file)
            webbrowser.open_new_tab('file://'+htm_file)
            app.msg_status(_('Opened browser with file ')+htm_file)
        return []
示例#34
0
 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()
示例#35
0
    def remove_vs_snip(self):
        rec = self.vs_local_dirs()

        if not rec:
            ct.msg_status(_('No VSCode snippets found'))
            return

        mnu = [s['name'] for s in rec]
        res = ct.dlg_menu(ct.MENU_LIST, mnu, caption=_('Remove snippets'))
        if res is None:
            return

        vs_snip_dir = rec[res]['dir']
        shutil.rmtree(vs_snip_dir)
        ct.msg_status(_('Snippets folder removed; restart CudaText to forget about it'))
示例#36
0
    def do_rprt(self, aid, ag, data=''):
        m,M         = self,self.__class__
        if False:pass
        elif aid=='trpt':
            # Compact report to tab
            app.file_open('')
            ed.set_text_all(get_str_report())

        elif aid=='hrpt':
            # Full report to HTML
            htm_file = os.path.join(tempfile.gettempdir(), '{}_keymapping.html'.format(app_name))
            do_report(htm_file)
            webbrowser.open_new_tab('file://'+htm_file)
            app.msg_status(_('Opened browser with file ')+htm_file)
        return []
示例#37
0
 def on_goto_def(self, ed_self):
     """go to definition call"""
     self.parser(ed_self)
     cursor = self.get_cursor()
     if not cursor:
         return
     word, _ = self.get_word_under_cursor(*cursor)
     if not word:
         return
     df = self.definitions.get(word.lower())  # [file, line_number] and None
     if df:
         self.goto_file(*df)
         return True
     else:
         ct.msg_status('Goto - no definition found for : ' + word)
def paint_occurrences(ed_self, occurrences):
    items, text, is_selection, x0, y0 = occurrences

    ncount = len(items)
    nlen = len(text)

    idx = 0

    # First item
    if items[0] == (x0, y0):
        idx = 1

    # Last item
    if items[ncount - 1] == (x0, y0):
        idx = ncount

    # Middle item
    if idx == 0:
        idx = next((i for i in range(1, ncount, 1)
                    if items[i - 1] == (x0, y0)), 0)

    items = [i for i in items if i != (x0, y0)]
    xx = [i[0] for i in items]
    yy = [i[1] for i in items]
    nn = [nlen] * len(items)

    ed_self.attr(app.MARKERS_ADD_MANY, MARKTAG, xx, yy, nn,
                 color_font=opt.COLOR_FONT_OTHER,
                 color_bg=opt.COLOR_BG_OTHER,
                 color_border=opt.COLOR_BRD_OTHER,
                 border_left=opt.BRD_OTHER,
                 border_right=opt.BRD_OTHER,
                 border_up=opt.BRD_OTHER,
                 border_down=opt.BRD_OTHER,
                 )

    if opt.CARET_ALLOW and not is_selection:
        ed_self.attr(app.MARKERS_ADD, MARKTAG, x0, y0, nlen,
                     color_font=opt.COLOR_FONT_CURRENT,
                     color_bg=opt.COLOR_BG_CURRENT,
                     color_border=opt.COLOR_BRD_CURRENT,
                     border_left=opt.BRD_CURRENT,
                     border_right=opt.BRD_CURRENT,
                     border_up=opt.BRD_CURRENT,
                     border_down=opt.BRD_CURRENT,
                     )

    app.msg_status('Matches highlighted: {}/{}'.format(idx, ncount))
 def dlg_ibms_in_tabs(self):
     ibms    = []
     for h_tab in app.ed_handles(): 
         ted     = app.Editor(h_tab)
         t_ibms, \
         msg     = self._ibms_in_tab(ted, self.bm_signs)
         ibms   += t_ibms
        #for h_tab
     if not ibms:    return app.msg_status(_('No in-text bookmarks in tabs'))
     line_max= max([line_n for (tab_id, line_n, bm_msg, line_s, tab_info) in ibms])
     ln_wd   = len(str(line_max))
     ibms    = [(tab_id, line_n, bm_msg, f('{} {}', str(1+line_n).rjust(ln_wd, ' '), line_s), tab_info) 
                 for (tab_id, line_n, bm_msg, line_s, tab_info) in ibms]
     tid     = ed.get_prop(app.PROP_TAB_ID)
     rCrt    = ed.get_carets()[0][1]
     near    = min([(abs(line_n-rCrt) if tid==tab_id else 0xFFFFFF, ind) 
                 for ind, (tab_id, line_n, bm_msg, line_s, tab_info) in enumerate(ibms)])[1]
     ans     = app.dlg_menu(app.MENU_LIST_ALT, '\n'.join(
                 [f('({}) {}\t{}', tab_info, bm_msg, line_s) for tab_id, line_n, bm_msg, line_s, tab_info in ibms]
             ), near)
     if ans is None: return
     tab_id, line_n, bm_msg, line_s, tab_info    = ibms[ans]
     ted     = apx.get_tab_by_id(tab_id)
     ted.focus()
     ed.set_caret(0, line_n)
     if not (ed.get_prop(app.PROP_LINE_TOP) <= line_n <= ed.get_prop(app.PROP_LINE_BOTTOM)):
         ed.set_prop(app.PROP_LINE_TOP, str(max(0, line_n - max(5, apx.get_opt('find_indent_vert')))))
 def __init__(self):  #NOTE: init
     if app.app_api_version() < FROM_API_VERSION:
         return app.msg_status(_('Need update application'))
     self.wrap = apx.get_opt('intextbookmk_wrap',
                             apx.get_opt('ibm_wrap', True))
     self.show_wo_alt = apx.get_opt('intextbookmk_compact_show',
                                    apx.get_opt('ibm_compact_show', True))
     #       self.show_wo_alt= apx.get_opt('intextbookmk_compact_show'    , apx.get_opt('ibm_compact_show'    , False))
     self.unlxr_cmnt = apx.get_opt(
         'intextbookmk_no_lexer_comment',
         apx.get_opt('ibm_no_lexer_comment', '//'))
     self.bm_signs = apx.get_opt(
         'intextbookmk_signs',
         apx.get_opt('ibm_signs',
                     ['NOTE:', 'NB!', 'TODO:', 'todo:', 'todo.', 'FIX:']))
     self.bm_signs = [self.bm_signs] if type(
         self.bm_signs) == str else self.bm_signs
     self.bm_sign = self.bm_signs[0]
     self.lxr2cmnt = {NO_LXR_SIGN: self.unlxr_cmnt}
     self.ext2lxr = {}
     for lxr in apx.get_enabled_lexers():
         cmnt = app.lexer_proc(app.LEXER_GET_PROP, lxr)['c_line']
         #           cmnt                    = app.lexer_proc(app.LEXER_GET_COMMENT, lxr)
         if not cmnt:
             continue  #for lxr
         self.lxr2cmnt[lxr] = cmnt
         for ext in app.lexer_proc(app.LEXER_GET_PROP, lxr)['typ']:
             self.ext2lxr[ext] = lxr
示例#41
0
    def jump(self, to_next=True):
        if not self.diff.diffmap:
            self.refresh()
        if len(self.diff.diffmap) == 0:
            return ct.msg_status("No differences were found")
        fc, eds = self.focused

        i = None
        if fc == 0:
            p = 0 if to_next else 1
        else:
            p = 2 if to_next else 3
        y = eds[fc].get_carets()[0][1]
        for n, df in enumerate(self.diff.diffmap):
            if y < df[p]:
                i = n if to_next else n - 1
                break

        if i is None:
            i = 0 if to_next else len(self.diff.diffmap) - 1
        elif i >= len(self.diff.diffmap):
            i = 0
        elif i < 0:
            i = len(self.diff.diffmap) - 1
        to = self.diff.diffmap[i]
        eds[0].set_caret(0, to[0], 0, to[1], ct.CARET_SET_ONE)
        eds[1].set_caret(0, to[2], 0, to[3], ct.CARET_SET_ONE)
示例#42
0
 def replace_all_sel_to_cb(self):
     pass;                   LOG and log('ok',)
     pass;                   return
     crts    = ed.get_carets()
     if len(crts)>1:
         return app.msg_status(ONLY_SINGLE_CRT.format('Command'))
     (cCrt, rCrt, cEnd, rEnd)    = crts[0]
    def _ibms_in_tab(self, ted, bm_signs):
        """ Collect in-text bm in the ted.
            Params
                ted         tab
                bm_signs    list of parsed signs
            Return
                list        [(tab_id, line_n, bm_msg, line_s, tab_info)]
                msg         Reason of empty list
        """
        lxr     = ted.get_prop(app.PROP_LEXER_FILE)
        lxr     = lxr if lxr else NO_LXR_SIGN
        if lxr not in self.lxr2cmnt:    return [], app.msg_status(f(_('No in-text bookmark into document with Lexer {}'), lxr))
        cmnt    =     self.lxr2cmnt[lxr]

        tab_sps = ' '*ted.get_prop(app.PROP_TAB_SIZE)
        tab_grp = ted.get_prop(app.PROP_INDEX_GROUP)
        tab_num = ted.get_prop(app.PROP_INDEX_TAB)
        tab_cap = ted.get_prop(app.PROP_TAB_TITLE)
        tab_id  = ted.get_prop(app.PROP_TAB_ID)
        tab_info= f('{}:{}. {}', 1+tab_grp, 1+tab_num, tab_cap)
        signs   = [cmnt + sign + ' ' for sign in bm_signs]
        pass;                  #LOG and log('signs={}',(signs))
        ibms    = []
        for line_n in range(ted.get_line_count()):
            line_s  = ted.get_text_line(line_n)
            for sign in signs:
                if sign in line_s:
                    line_s  = line_s.replace('\t', tab_sps)
                    bm_msg  = line_s[line_s.index(sign)+len(sign):]
                    ibms   += [(tab_id, line_n, bm_msg, line_s, tab_info)]
                    break#for sign
               #for sign
           #for line_n
        return ibms, ''
  def on_caret(self, ed_self):
    ed_self.attr(app.MARKERS_DELETE_BY_TAG, MARKTAG)

    if ed_self.get_line_count()>opt.MAX_LINES:
        return

    current_text = _get_current_text(ed_self)
    if not current_text: return

    text, caret_pos, is_selection = current_text

    if caret_pos[1] != caret_pos[3]: return # no multiline
    if not opt.SEL_ALLOW_WHITE_SPACE: text = text.strip()
    if not text: return

    if is_selection:
      case_sensitive = opt.SEL_CASE_SENSITIVE
      words_only     = opt.SEL_WORDS_ONLY
      whole_words    = opt.SEL_WHOLE_WORDS if opt.SEL_WORDS_ONLY else False
    else:
      case_sensitive = opt.CARET_CASE_SENSITIVE
      words_only     = True
      whole_words    = opt.CARET_WHOLE_WORDS

    if len(text) < opt.MIN_LEN: return

    carets = ed_self.get_carets()
    if len(carets) != 1: return

    x0, y0, x1, y1 = caret_pos
    if x0 > x1: x0, x1 = x1, x0

    items = find_all_occurrences(ed_self, text, case_sensitive, whole_words, words_only)

    if not items or (len(items) == 1 and items[0] == (x0, y1)):
        app.msg_status('')
        return

    for item in items:
      if item == (x0, y0): continue

      ed_self.attr(app.MARKERS_ADD, MARKTAG, item[0], item[1], len(text), opt.COLOR_FONT_OTHER, opt.COLOR_BG_OTHER)
    else:
      if opt.CARET_ALLOW and not is_selection:
        ed_self.attr(app.MARKERS_ADD, MARKTAG, x0, y0, len(text), opt.COLOR_FONT_CURRENT, opt.COLOR_BG_CURRENT)

    app.msg_status('Matches hilited: {}'.format(len(items)))
示例#45
0
  def on_caret(self, ed_self):
    ed_self.attr(_ct.MARKERS_DELETE_BY_TAG, MARKTAG)

    # TODO: ...
    if MAX_SIZE: pass
    #  if MAX_SIZE < ??? : return

    current_text = _get_current_text(ed_self) # if not (SEL_ALLOW or CARET_ALLOW): bool(current_text) == False

    if not current_text: return

    text, caret_pos, is_selection = current_text

    if caret_pos[1] != caret_pos[3]: return # no multiline
    if not SEL_ALLOW_WHITE_SPACE: text = text.strip()
    if not text: return

    if is_selection:
      case_sensitive = SEL_CASE_SENSITIVE
      words_only     = SEL_WORDS_ONLY
      whole_words    = SEL_WHOLE_WORDS if SEL_WORDS_ONLY else False
    else:
      case_sensitive = CARET_CASE_SENSITIVE
      words_only     = True
      whole_words    = CARET_WHOLE_WORDS

    if len(text) < MIN_LEN: return

    carets = ed_self.get_carets()
    if len(carets) != 1: return

    x0, y0, x1, y1 = caret_pos
    if x0 > x1: x0, x1 = x1, x0

    items = find_all_occurrences(ed_self, text, case_sensitive, whole_words, words_only)

    if not items or (len(items) == 1 and items[0] == (x0, y1)): return

    for item in items:
      if item == (x0, y0): continue

      ed_self.attr(_ct.MARKERS_ADD, MARKTAG, item[0], item[1], len(text), COLOR_FONT_OTHER, COLOR_BG_OTHER)
    else:
      if CARET_ALLOW and not is_selection:
        ed_self.attr(_ct.MARKERS_ADD, MARKTAG, x0, y0, len(text), COLOR_FONT_CURRENT, COLOR_BG_CURRENT)

    _ct.msg_status('Matches hilited: {}'.format(len(items)))
示例#46
0
    def show_usages(self):
        if not self.app.environment:
            return

        cursor = self.app.cursor
        if not cursor:
            return

        items = self.app.script.get_references(
            line=cursor.row,
            column=cursor.x)

        if items:
            usages = []
            for d in items:
                modfile = d.module_path
                if modfile and os.path.isfile(modfile):
                    usages += [(modfile, d.line-1, d.column)]
        else:
            return

        if not usages:
            ct.msg_status('Cannot find usages')
            return

        items_show = []
        for item in usages:
            _fn = item[0]
            _fn1 = os.path.basename(_fn)
            _dir = pretty_path(os.path.dirname(_fn))
            _line = item[1]
            _col = item[2]
            _s = '?'
            if os.path.isfile(_fn):
                with open(_fn, encoding='utf8', errors='replace') as f:
                    for i in range(_line+1):
                        _s = f.readline()
            _s = _s.lstrip(' \t').rstrip('\n\r')
            items_show.append('{}:{}:{} ({})\t  {}'.format(_fn1, _line+1, _col+1, _dir, _s))

        res = ct.dlg_menu(ct.MENU_LIST_ALT, items_show, caption='Usages', w=opt_menu_w, h=opt_menu_h)
        if res is None:
            return

        item = usages[res]
        goto_file(item[0], item[1], item[2])
示例#47
0
    def run(self, mcr_id, times=1, waits=0, while_chngs=False, till_endln=False):
        ''' Main (and single) way to run any macro
        '''
        pass;                   LOG and log('mcr_id, times, waits, while_chngs, till_endln={}',(mcr_id, times, waits, while_chngs, till_endln))
        mcr     = self.mcr4id.get(str(mcr_id))
        if mcr is None:
            pass;               LOG and log('no id',)
            return app.msg_status(_('No macros: {}').format(mcr_id))
        cmds4eval   = ';'.join(mcr['evl'])
        pass;                   LOG and log('nm, cmds4eval={}',(mcr['nm'], cmds4eval))
        how_t       = 'wait'
        rp_ctrl     = self.tm_ctrl.get('rp_ctrl', 1000)                     # testing one of 1000 execution
        tm_wait     = waits if waits>0 else self.tm_ctrl.get('tm_wait', 10) # sec
        start_t     = datetime.datetime.now()
        pre_body    = '' if not while_chngs else ed.get_text_all()
        for rp in range(times if times>0 else 0xffffffff):
            exec(cmds4eval)
            if till_endln and ed.get_carets()[0][1] == ed.get_line_count()-1:
                pass;           LOG and log('break endln',)
                break   #for rp
            if while_chngs:
                new_body    = ed.get_text_all()
                if pre_body == new_body:    
                    pass;       LOG and log('break no change',)
                    break   #for rp
                pre_body    = new_body
            if  (how_t=='wait'
            and (rp_ctrl-1) == rp % rp_ctrl
            and tm_wait < (datetime.datetime.now()-start_t).seconds):
                cnts    = ([
  dict(              tp='lb'    ,t=GAP          ,l=GAP  ,w=400   ,cap=_('Macro "{}" playback time is too long'.format(mcr['nm'])))
 ,dict(cid='wait'   ,tp='bt'    ,t=GAP*2+25*1   ,l=GAP  ,w=400   ,cap=_('Wait &another {} sec').format(tm_wait)  ,props='1'      )   # default
 ,dict(cid='cont'   ,tp='bt'    ,t=GAP*3+25*2   ,l=GAP  ,w=400   ,cap=_('Continue &without control')                             )
 ,dict(cid='stop'   ,tp='bt'    ,t=GAP*6+25*3   ,l=GAP  ,w=300   ,cap=_('&Cancel playback [ESC]')                                )
                        ])
                btn,vals,chds= dlg_wrapper(_('Playback macro'), GAP*2+400, GAP*7+4*25, cnts, {})
                if btn is None or btn=='stop':
                    pass;       LOG and log('break by user',)
                    app.msg_status(_('Cancel playback macro: {}'.format(mcr['nm'])))
                    break   #for rp
                if btn=='cont': #ans=='cont':
                    how_t   = 'work'
                if btn=='wait': #ans=='wait':
                    start_t = datetime.datetime.now()
           #for rp
        self.last_mcr_id = mcr_id
示例#48
0
def to_tab_ask_num():
    while True:
        grp_num = app.dlg_input(
            _('What tab number to activate? Input: [group:]number'), '')
        if grp_num is None: return
        if re.match(r'(\d:)?\d+', grp_num):
            break
    me_grp = ed.get_prop(app.PROP_INDEX_GROUP)
    grp = int(grp_num.split(':')[0]) - 1 if ':' in grp_num else me_grp
    num = int(
        grp_num.split(':')[1]) - 1 if ':' in grp_num else int(grp_num) - 1
    for h in app.ed_handles():
        ed_ = app.Editor(h)
        if grp == ed_.get_prop(app.PROP_INDEX_GROUP) and \
           num == ed_.get_prop(app.PROP_INDEX_TAB):
            ed_.focus()
    app.msg_status(f(_('No tab "{}"'), grp_num))
示例#49
0
    def dlg_import(self):
        ''' Show dlg for import some macros.
        '''
        if app.app_api_version()<FROM_API_VERSION:  return app.msg_status(_('Need update CudaText'))
        (imp_file
        ,mcrs)  = self.dlg_import_choose_mcrs()
        if imp_file is None:    return
        lmcrs   = len(mcrs)
        
        WD_LST, \
        HT_LST  = (500
                  ,500)
        crt,sels= '0', ['1'] * lmcrs
        while True:

            cnts    = ([
  dict(              tp='lb'    ,tid='file'         ,l=GAP             ,w=85            ,cap=_('Import &from')              )
 ,dict(cid='file'   ,tp='ed'    ,t=GAP              ,l=GAP+85          ,r=GAP+WD_LST-35 ,en='0'                             )
 ,dict(cid='brow'   ,tp='bt'    ,tid='file'         ,l=GAP+HT_LST-35   ,r=GAP+WD_LST    ,cap=_('&...')                      )
 ,dict(cid='mcrs'   ,tp='ch-lbx',t=35  ,h=HT_LST    ,l=GAP             ,w=    WD_LST    ,items=[mcr['nm'] for mcr in mcrs]  )
 ,dict(cid='ch-a'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP*1           ,w=100           ,cap=_('Check &all')                )
 ,dict(cid='ch-n'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP*2+100       ,w=100           ,cap=_('U&ncheck all')              )
 ,dict(cid='impo'   ,tp='bt'    ,t=GAP+35+HT_LST    ,l=    WD_LST-70*2 ,w=70            ,cap=_('&Import')       ,props='1'  )   # default
 ,dict(cid='-'      ,tp='bt'    ,t=GAP+35+HT_LST    ,l=GAP+WD_LST-70*1 ,w=70            ,cap=_('Close')                     )
                    ])
            vals    = dict( file=imp_file
                           ,mcrs=(crt, sels)
                        )
            btn,    \
            vals,   \
            chds    = dlg_wrapper(_('Import macros'), GAP+WD_LST+GAP, GAP*4+HT_LST+25*2, cnts, vals, focus_cid='mrcs')
            if btn is None or btn=='-': return
            crt,sels= vals['mcrs']
            pass;               LOG and log('sels={}',sels)
            if False:pass
            elif btn=='brow': #ans_s=='file':
                (new_imp_file
                ,new_mcrs)  = self.dlg_import_choose_mcrs()
                if new_imp_file is None:    continue #while
                imp_file    = new_imp_file
                mcrs        = new_mcrs
                lmcrs       = len(mcrs)
                crt,sels    = '0', ['1'] * lmcrs
            elif btn=='ch-a': #ans_s=='all':
                sels    = ['1'] * lmcrs
            elif btn=='ch-n': #ans_s=='no':
                sels    = ['0'] * lmcrs
            elif btn=='impo': #ans_s=='imp':
                if '1' not in sels:
                    app.msg_box(_('Select some names'), app.MB_OK)
                    continue
                (good_nms
                ,fail_nms) = self.import_from_list([mcr for (ind, mcr) in enumerate(mcrs) if sels[ind]=='1'])
                l,lt    = '\n', '\n      '
                app.msg_box(   _('Import macros:')     +lt+lt.join(good_nms)
                            +l+''
                            +l+_('Skip duplicates:')   +lt+lt.join(fail_nms)
                           ,app.MB_OK)
示例#50
0
    def cmt_toggle_stream(self):
        ''' '''
        if ed.get_sel_mode() != app.SEL_NORMAL:
            return app.msg_status(ONLY_NORM_SEL_MODE.format(COMMENTING))
        lex     = ed.get_prop(app.PROP_LEXER_CARET)
        (bgn
        ,end)   = self._get_cmt_pair(lex)
        if not bgn:
            return app.msg_status(CMT_NO_STRM_4LEX.format(lex))
        crts    = ed.get_carets()
        pass;                   LOG and log('lex, get_carets()={}', (lex, crts))
        pass;                   LOG and log('bgn,end={}', (bgn,end))
        for icrt, (c1, r1, c2, r2) in enumerate(crts):
            pass;               LOG and log('(r1, c1), (r2, c2)={}', ((r1, c1), (r2, c2)))
            if -1==c2:
                # Empty sel
                continue
            (r1, c1), (r2, c2) = minmax((r1, c1), (r2, c2))
            pass;               LOG and log('(r1, c1), (r2, c2)={}', ((r1, c1), (r2, c2)))
            selTx   = ed.get_text_substr(c1, r1, c2, r2)
            cmted   = selTx.startswith(bgn) and selTx.endswith(end)
            pass;               LOG and log('cmted, selTx={}', (cmted, selTx))

            if False:pass
            elif not cmted and r1==r2:
                # Comment ON, sel into one row
                ed.insert(c2, r2, end)
                ed.insert(c1, r1, bgn)
                ed.set_caret(c1, r1, c2+len(bgn)+len(end), r2, app.CARET_SET_INDEX+icrt)
            elif not cmted and r1!=r2:
                # Comment ON, sel ends on diff rows
                ed.insert(c2, r2, end)
                ed.insert(c1, r1, bgn)
                ed.set_caret(c1, r1, c2         +len(end), r2, app.CARET_SET_INDEX+icrt)

            elif cmted and r1==r2:
                # Comment OFF, sel into one row
                ed.delete(c2-len(end), r2, c2, r2)
                ed.delete(c1, r1, c1+len(bgn), r1)
                ed.set_caret(c1, r1, c2-len(bgn)-len(end), r2, app.CARET_SET_INDEX+icrt)
            elif cmted and r1!=r2:
                # Comment OFF, sel ends on diff rows
                ed.delete(c2-len(end), r2, c2, r2)
                ed.delete(c1, r1, c1+len(bgn), r1)
                ed.set_caret(c1, r1, c2         -len(end), r2, app.CARET_SET_INDEX+icrt)
    def open(self, ssnew=None):
        ''' Open new session from file ssnew or after user asking '''
        if not _checkAPI(): return
#       in_dir      = app.app_path(app.APP_DIR_DATA)
        sscur       = app.app_path(app.APP_FILE_SESSION)
        if ssnew is None:
            ssnew   = app.dlg_file(is_open=True, filters=DLG_ALL_FILTER
                    , init_filename='!'     # '!' to disable check "filename exists"
                    , init_dir=     ''
                    )
        if ssnew is None: return
        if ssnew.endswith(SWSESS_EXT) and os.path.isfile(ssnew):
            # Import from Syn
            sssyn   = ssnew
            sscud   = ssnew[:-len(SWSESS_EXT)]+CDSESS_EXT
            if os.path.isfile(sscud):
                sscud   = app.dlg_file(is_open=False, filters=DLG_CUD_FILTER
                        , init_filename=os.path.basename(sscud)
                        , init_dir=     os.path.dirname( sscud)
                        )
                if not sscud: return
            if not import_syn_sess(sssyn, sscud): return
            ssnew   = sscud
            
        ssnew       = apx.icase(False,''
                    ,   ssnew.endswith(CDSESS_EXT)  , ssnew
                    ,   os.path.isfile(ssnew)       , ssnew
                    ,   True                        , ssnew+CDSESS_EXT
                    )
        if os.path.isfile(ssnew):
            # Open
            app.app_proc(app.PROC_SAVE_SESSION, sscur)
            app.app_proc(app.PROC_LOAD_SESSION, ssnew)
            app.app_proc(app.PROC_SET_SESSION,  ssnew)
            app.msg_status(OPENED.format(stem=juststem(ssnew)))
            self.top_sess(ssnew)
        else:
            # New
            if app.ID_NO==app.msg_box(CREATE_ASK.format(stem=juststem(ssnew)), app.MB_YESNO):   return
            app.app_proc(app.PROC_SAVE_SESSION, sscur)
            app.ed.cmd(cmds.cmd_FileCloseAll)
            app.app_proc(app.PROC_SET_SESSION,  ssnew)
            app.app_proc(app.PROC_SAVE_SESSION, ssnew)
            app.msg_status(CREATED.format(stem=juststem(ssnew)))
            self.top_sess(ssnew)
示例#52
0
 def on_macro(self, ed_self, mcr_record):
     ''' Finish for macro-recording.
         Params
             mcr_record   "\n"-separated list of
                             number
                             number,string
                             py:string_module,string_method,string_param
     '''
     pass;                   LOG and log('mcr_record={}',mcr_record)
     if ''==mcr_record:   return app.msg_status('Empty record')
     def_nm      = ''
     nms     = [mcr['nm'] for mcr in self.macros]
     for num in range(1,1000):
         def_nm  = 'Macro{}'.format(num)
         if def_nm not in nms:
             break #for num
     while True:
         mcr_nm      = app.dlg_input('Macro name. Tricks: "!NM" overwrite NM, "=NM" show NM in dialog', def_nm)
         if mcr_nm is None:   return
         mcr_nm      = mcr_nm.strip()
         if ''==mcr_nm:  continue #while
         if mcr_nm[0]=='=':
             self.need_dlg = True
             mcr_nm  = mcr_nm[1:]
         use_old     = False
         if ''==mcr_nm:  continue #while
         if mcr_nm[0]=='!':
             use_old = True
             mcr_nm  = mcr_nm[1:]
         if ''!=mcr_nm:  break #while
     pass;                   LOG and log('self.need_dlg, use_old, mcr_nm={}',(self.need_dlg, use_old, mcr_nm))
     
     if use_old and mcr_nm in nms:
         mcr_ind     = nms.index(mcr_nm)
         self.macros[mcr_ind]['rec'] = mcr_record
         self.macros[mcr_ind]['evl'] = self._record_data_to_cmds(mcr_record)
         id4mcr      = self.macros[mcr_ind]['id']
     else:
         while mcr_nm in nms:
             app.msg_box('Select other name.\nMacros names now:\n\n'+'\n'.join(nms), app.MB_OK)
             mcr_nm  = app.dlg_input('Macro name', mcr_nm)
             if mcr_nm is None:   return
     
         id4mcr      = random.randint(10000, 99999)
         while id4mcr in self.mcr4id:
             id4mcr  = random.randint(10000, 99999)
         self.macros += [{'id' :id4mcr       ##?? conflicts?
                         ,'nm' :mcr_nm
                         ,'rec':mcr_record
                         ,'evl':self._record_data_to_cmds(mcr_record)
                         }]
     self._do_acts()
     
     if self.need_dlg:
         self.need_dlg   = False
         self.last_mcr_id= id4mcr
         self.dlg_config()
    def dlg_config(self):
        DLG_W,  \
        DLG_H   = 400, 95
        lxrs_l  = apx.get_enabled_lexers()
        
        sgns_h  = _('Space delimeted list.\rThe first word will be inserted by command.')
        dfcm_h  = _('Default comment sign.\rIt is used when lexer has no line comment or file has no lexer.')
        cnts    =[dict(           tp='lb'   ,tid='sgns' ,l=GAP          ,w=130          ,cap=_('&Bookmark signs:')  ,hint=sgns_h    ) # &b
                 ,dict(cid='sgns',tp='ed'   ,t=GAP      ,l=130          ,w=DLG_W-130-GAP                                            ) #  
                 ,dict(           tp='lb'   ,tid='dfcm' ,l=GAP          ,w=130          ,cap=_('&Comment sign:')    ,hint=dfcm_h    ) # &c 
                 ,dict(cid='dfcm',tp='ed'   ,t=35       ,l=130          ,w=DLG_W-130-GAP                                            ) #  
                 ,dict(cid='wrap',tp='ch'   ,tid='!'    ,l=GAP          ,w=120          ,cap=_('&Wrap for next/prev')               ) # &w
#                ,dict(cid='help',tp='bt'   ,t=DLG_H-60 ,l=DLG_W-GAP-80 ,w=80           ,cap=_('Help')                              ) #  
                 ,dict(cid='!'   ,tp='bt'   ,t=DLG_H-30 ,l=DLG_W-GAP-165,w=80           ,cap=_('Save')          ,props='1'          ) #     default
                 ,dict(cid='-'   ,tp='bt'   ,t=DLG_H-30 ,l=DLG_W-GAP-80 ,w=80           ,cap=_('Close')                             ) #  
                ]#NOTE: cfg
        focused = 'sgns'
        while True:
            act_cid, vals, chds = dlg_wrapper(_('In-text bookmarks'), DLG_W, DLG_H, cnts
                , dict(sgns=' '.join(self.bm_signs)
                      ,dfcm=         self.unlxr_cmnt
                      ,wrap=         self.wrap
                      ), focus_cid=focused)
            if act_cid is None or act_cid=='-':    return#while True
            focused = chds[0] if 1==len(chds) else focused
            if act_cid=='!':
                if not vals['sgns'].strip():
                    app.msg_status(_('Need Bookmark sign'))
                    focused = 'sgns'
                    continue#while
                if not vals['dfcm'].strip():
                    app.msg_status(_('Need Comment sign'))
                    focused = 'dfcm'
                    continue#while
                if  self.bm_signs  != vals['sgns'].split():
                    self.bm_signs   = vals['sgns'].split()
                    apx.set_opt('intextbookmk_signs', self.bm_signs)
                if  self.unlxr_cmnt!= vals['dfcm'].strip():
                    self.unlxr_cmnt = vals['dfcm'].strip()
                    apx.set_opt('intextbookmk_no_lexer_comment', self.unlxr_cmnt)
                if  self.wrap      != vals['wrap']:
                    self.wrap       = vals['wrap']
                    apx.set_opt('intextbookmk_wrap', self.wrap)
                break#while
示例#54
0
    def jump_to_matching_bracket(self):
        ''' Jump single (only!) caret to matching bracket.
            Pairs: [] {} () <> «»
        '''
        pass;                  #LOG and log('')
        crts    = ed.get_carets()
        if len(crts)>1:
            return app.msg_status(ONLY_SINGLE_CRT.format('Command'))
        (cCrt, rCrt, cEnd, rEnd)    = crts[0]
        if cEnd!=-1:
            return app.msg_status(ONLY_FOR_NO_SEL.format('Command'))

        (c_opn, c_cls
        ,col, row)  = find_matching_char(ed, cCrt, rCrt)

        if c_opn!='' and -1!=col:
            pass;              #LOG and log('set_caret(col, row)={}', (col, row))
            ed.set_caret(col, row)
        else:
            return app.msg_status(NO_PAIR_BRACKET.format(c_opn))
 def openPrev(self, recent_pos=1):
     ''' Open session that was opened before.
         Params
             recent_pos  Position in recent list
     '''
     if not _checkAPI(): return
     sess    = self._loadSess(existing=True)
     rcnt    = sess['recent']
     if len(rcnt)<1+recent_pos:
         return app.msg_status(NO_PREV)
     self.open(rcnt[recent_pos])
 def _jump_to_ibm(self, what):
     ibms,   \
     msg     = self._ibms_in_tab(ed, self.bm_signs)
     if not ibms and msg:    return app.msg_status(msg)
     if not ibms:            return app.msg_status(_('No in-text bookmarks'))
     rCrt    = ed.get_carets()[0][1]
     if  1==len(ibms) \
     and rCrt==ibms[0][1]:   return app.msg_status(_('No more bookmarks'))
     line_ns = [line_n for (tab_id, line_n, bm_msg, line_s, tab_info) in ibms]
     if self.wrap:
         line_ns = [-line_ns[-1]] + line_ns + [line_ns[0]+0xFFFFFFFF]
     line_cns= [line_n for line_n in line_ns 
                 if (line_n>rCrt if what=='next' else line_n<rCrt)]
     if not line_cns:        return app.msg_status(_('No bookmark for jump'))
     line_n  = min(line_cns)         if what=='next'         else max(line_cns)
     line_n  = -line_n               if line_n<0             else line_n
     line_n  =  line_n-0xFFFFFFFF    if line_n>=0xFFFFFFFF   else line_n
     ed.set_caret(0, line_n)
     if not (ed.get_prop(app.PROP_LINE_TOP) <= line_n <= ed.get_prop(app.PROP_LINE_BOTTOM)):
         ed.set_prop(app.PROP_LINE_TOP, str(max(0, line_n - max(5, apx.get_opt('find_indent_vert')))))
    def add_ibm(self):
        lxr         = ed.get_prop(app.PROP_LEXER_FILE)
        lxr         = lxr if lxr else NO_LXR_SIGN
#       if lxr not in self.lxr2cmnt:    return app.msg_status(f(_('Cannot add in-text bookmark into document with Lexer {}. No to-end-of-line comment.'), lxr))
        if lxr not in self.lxr2cmnt:    return app.msg_status(f(_('Cannot add in-text bookmark: no line-comments defined for lexer {}.'), lxr))
        cmnt        = self.lxr2cmnt[lxr]
        bm_msg      = app.dlg_input(_('Enter message for in-text bookmark. Empty is good.'), '')
        if bm_msg is None:              return
        (cCrt, rCrt
        ,cEnd, rEnd)= ed.get_carets()[0]
        line_s      = ed.get_text_line( rCrt)
        ed.set_text_line(               rCrt, line_s + cmnt + self.bm_sign + ' ' + bm_msg)