def saveAs(self): ''' Save cur session to new 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 pass app.msg_status(sscur) (ssdir, ssfname) = os.path.split(sscur) ssfname = ssfname.replace('.json', '') ssnew = app.dlg_file(is_open=False, filters=DLG_CUD_FILTER, init_filename=ssfname, init_dir=ssdir) pass app.msg_status(str(ssnew)) if ssnew is None: return ssnew = apx.icase(False, '', ssnew.endswith(CDSESS_EXT), ssnew, os.path.isfile(ssnew), ssnew, True, ssnew + CDSESS_EXT) if os.path.normpath(sscur) == os.path.normpath(ssnew): return # app.app_proc(app.PROC_SAVE_SESSION, sscur) app.app_proc(app.PROC_SAVE_SESSION, ssnew) app.app_proc(app.PROC_SET_SESSION, ssnew) app.msg_status(SAVED.format(stem=juststem(ssnew))) self.top_sess(ssnew)
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 add_cud_plugins(cmdinfos, prfx, ctg): # {"commands":{ # "grp":{ # "0":{"caption":"***", "hotkey":"***"}, # "1":{"caption":"***", "hotkey":"***"}, # }, # }} # plugs_json = os.path.join(app.app_path(app.APP_DIR_SETTINGS), 'plugins.json') keys_json = os.path.join(app.app_path(app.APP_DIR_SETTINGS), 'keys.json') # plugs = json_loads(open(plugs_json).read(), object_pairs_hook=collections.OrderedDict) keys = json_loads(open(keys_json).read()) for n in itertools.count(): if not app.app_proc(app.PROC_GET_COMMAND_PLUGIN, str(n)): break#for n (cap ,modul ,meth ,par ,lxrs) = app.app_proc(app.PROC_GET_COMMAND_PLUGIN, str(n)) plug_id = modul+','+meth+(','+par if par else '') dct_keys= keys.get(plug_id, {}) cmdinfos += [(ctg , prfx+cap , ' * '.join(dct_keys.get('s1', [])) , ' * '.join(dct_keys.get('s2', [])) )] #for n return cmdinfos
def toggle(self, on=True): if on: ev = 'on_tab_change,on_state,on_caret,on_change_slow' if ct.ed.get_prop(ct.PROP_TAB_ID) in self.tab_id: ev = 'on_scroll,on_tab_change,on_state,on_caret,on_change_slow' else: ev = 'on_state,on_caret,on_change_slow' ct.app_proc(ct.PROC_SET_EVENTS, self.name + ';' + ev + ';;')
def do_show(ag, key, data=None): pass log__("", (), __=(log4fun, _log4mod)) if 'c' not in app.app_proc(app.PROC_GET_KEYSTATE, ''): ag.hide() app.timer_proc( app.TIMER_START_ONE, lambda tag: ag.hide() if 'c' not in app.app_proc(app.PROC_GET_KEYSTATE, '') else 0, 200) return []
def close(self): 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.app_proc( app.PROC_SET_SESSION, 'history session.json') # w/o path to use "settings" portable way pass
def _call_cmd(self, ed_self, cid, rpt, prm): for rp in range(int(rpt) if rpt else 1): if False:pass elif type(cid)==int or cid.isdigit(): # Core cmd number ed_self.cmd(int(cid)) elif cid in CO_SGN2CID: # Core cmd name ed_self.cmd(CO_SGN2CID[cid]) else: # Plugin cmd app.app_proc(app.PROC_EXEC_PLUGIN, cid)
def _do_acts(self, what='', acts='|save|second|reg|keys|menu|'): ''' Use macro list ''' pass #LOG and log('what, acts={}',(what, acts)) # Save if '|save|' in acts: open(MACROS_JSON, 'w').write( json.dumps( { 'ver': JSON_FORMAT_VER, 'list': self.macros, 'dlg_prs': self.dlg_prs, 'tm_ctrl': { 'rp_ctrl': self.tm_ctrl.get('rp_ctrl', 1000), 'tm_wait': self.tm_ctrl.get('tm_wait', 10) } }, indent=4)) # Secondary data if '|second|' in acts: self.mcr4id = {str(mcr['id']): mcr for mcr in self.macros} # Register new subcommands if '|reg|' in acts: reg_subs = 'cuda_macros;run;{}'.format('\n'.join( 'macro: {}\t{}'.format(mcr['nm'], mcr['id']) for mcr in self.macros)) pass #LOG and log('reg_subs={}',reg_subs) app.app_proc(app.PROC_SET_SUBCOMMANDS, reg_subs) # Clear keys.json if '|keys|' in acts and ':' in what: # Need delete a key 'cuda_macros,run,NNNNN' mcr_id = what[1 + what.index(':'):] mcr_key = 'cuda_macros,run,{}'.format(mcr_id) keys_json = app.app_path( app.APP_DIR_SETTINGS) + os.sep + 'keys.json' if not os.path.exists(keys_json): return keys = apx._json_loads(open(keys_json).read()) pass #LOG and log('??? key={}',mcr_key) if keys.pop(mcr_key, None) is not None: pass #LOG and log('UPD keys.json deleted key={}',mcr_key) open(keys_json, 'w').write(json.dumps(keys, indent=2)) # [Re]Build menu if '|menu|' in acts: self._adapt_menu()
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)
def get_theme(): data = ct.app_proc(ct.PROC_THEME_SYNTAX_DICT_GET, '') th = {} th['color_changed'] = data['LightBG2']['color_back'] th['color_added'] = data['LightBG3']['color_back'] th['color_deleted'] = data['LightBG1']['color_back'] return th
def collect_keys(): keys_json = os.path.join(app.app_path(app.APP_DIR_SETTINGS), 'keys.json') keys = apx._json_loads(open(keys_json).read()) if os.path.isfile(keys_json) else {} cmdinfos = [] pass; #LOG and log('app.app_api_version()={}',(app.app_api_version())) # if True: # app.app_api_version()>='1.0.212': lcmds = app.app_proc(app.PROC_GET_COMMANDS, '') cmdinfos = [('Plugins' ,cmd['name'] ,cmd['key1'] ,cmd['key2'] ,f('{},{},{}', cmd['p_module'], cmd['p_method'], cmd['p_method_params']).rstrip(',') ) if cmd['type']=='plugin' else ('Commands' ,cmd['name'] ,cmd['key1'] ,cmd['key2'] ,cmd['cmd'] ) for cmd in lcmds if cmd['type'] in ('plugin', 'cmd') # if cmd['type']!='lexer' ] return cmdinfos
def do_update_colors(): theme = app.app_proc(app.PROC_THEME_SYNTAX_DICT_GET, '') item_cur = theme.get(opt.THEME_CURRENT) item_oth = theme.get(opt.THEME_OTHER) opt.COLOR_FONT_CURRENT = app.COLOR_NONE opt.COLOR_FONT_OTHER = app.COLOR_NONE if item_cur and item_oth: opt.COLOR_BG_CURRENT = item_cur['color_back'] opt.COLOR_BRD_CURRENT = item_cur['color_border'] opt.BRD_CURRENT = item_cur['border_bottom'] opt.COLOR_BG_OTHER = item_oth['color_back'] opt.COLOR_BRD_OTHER = item_oth['color_border'] opt.BRD_OTHER = item_oth['border_bottom'] else: log('Incorrect theme item(s) "%s", "%s" in "%s"' % (opt.THEME_CURRENT, opt.THEME_OTHER, fn_config)) opt.COLOR_BG_CURRENT = 0x80e080 opt.COLOR_BG_OTHER = 0x00e0e0 opt.COLOR_BRD_CURRENT = 0 opt.COLOR_BRD_OTHER = 0 opt.BRD_CURRENT = 0 opt.BRD_OTHER = 0
def __init__(self): self.h_tree = app.app_proc(app.PROC_GET_CODETREE, '') dir = app.app_path(app.APP_DIR_PY) dirs = os.listdir(dir) dirs = [ os.path.join(dir, s) for s in dirs if s.startswith('cuda_tree_') ] for dir in dirs: fn_inf = os.path.join(dir, 'install.inf') s_module = app.ini_read(fn_inf, 'info', 'subdir', '') for index in range(1, MAX_SECTIONS + 1): section = 'treehelper' + str(index) s_method = app.ini_read(fn_inf, section, 'method', '') if not s_method: continue s_lexers = app.ini_read(fn_inf, section, 'lexers', '') if not s_lexers: continue for s_lex in s_lexers.split(','): self.helpers[s_lex] = { 'module': s_module, 'method': s_method, } #print('module', s_module, 'lexers', s_lexers, 'method', s_method) items = sorted(list(self.helpers.keys())) if items: print('TreeHelpers: ' + ', '.join(items))
def collect_keys(): keys_json = os.path.join(app.app_path(app.APP_DIR_SETTINGS), 'keys.json') keys = apx._json_loads(open(keys_json).read()) if os.path.isfile(keys_json) else {} cmdinfos = [] pass; #LOG and log('app.app_api_version()={}',(app.app_api_version())) # if True: # app.app_api_version()>='1.0.212': lcmds = app.app_proc(app.PROC_GET_COMMANDS, '') cmdinfos = [('Commands' ,cmd['name'] ,cmd['key1'] ,cmd['key2'] ,cmd['cmd'] ) if cmd['type']=='cmd' else ('Plugins' ,cmd['name'] ,cmd['key1'] ,cmd['key2'] ,f('{},{},{}', cmd['p_module'], cmd['p_method'], cmd['p_method_params']).rstrip(',') ) for cmd in lcmds if cmd['type']!='lexer' ] return cmdinfos
def get_translation(plug_file): ''' Part of i18n. Full i18n-cycle: 1. All GUI-string in code are used in form _('') 2. These string are extracted from code to lang/messages.pot with run python.exe <pypython-root>\Tools\i18n\pygettext.py -p lang <plugin>.py 3. Poedit (or same program) create <module>\lang\ru_RU\LC_MESSAGES\<module>.po from (cmd "Update from POT") lang/messages.pot It allows to translate all "strings" It creates (cmd "Save") <module>\lang\ru_RU\LC_MESSAGES\<module>.mo 4. get_translation uses the file to realize _('') ''' plug_dir= os.path.dirname(plug_file) plug_mod= os.path.basename(plug_dir) lng = app.app_proc(app.PROC_GET_LANG, '') lng_mo = plug_dir+'/lang/{}/LC_MESSAGES/{}.mo'.format(lng, plug_mod) if os.path.isfile(lng_mo): t = gettext.translation(plug_mod, plug_dir+'/lang', languages=[lng]) _ = t.gettext t.install() else: _ = lambda x: x return _
def __init__(self, ed: ct.Editor): self.fp = ed.get_filename() if op.exists(self.fp): self.fn = op.basename(self.fp) self.fdir = op.dirname(self.fp) else: self.fn = '' self.fdir = '' x0, y0, x1, y1 = ed.get_carets()[0] self.line_index = y0 self.text_sel = ed.get_text_sel() self.clipboard = ct.app_proc(ct.PROC_GET_CLIP, '') self.line = ed.get_text_line(y0) self.word, _ = get_word_under_cursor(self.line, x0) self.lexer = ed.get_prop(ct.PROP_LEXER_FILE) prop = ct.lexer_proc(ct.LEXER_GET_PROP, self.lexer) if prop: prop_str = prop.get('c_str') prop_line = prop.get('c_line') self.cmt_start = prop_str[0] if prop_str else '' self.cmt_end = prop_str[1] if prop_str else '' self.cmt_line = prop_line if prop_line else '' else: self.cmt_start = '' self.cmt_end = '' self.cmt_line = ''
def check_and_update(self, ed_self): if not app.app_proc(app.PROC_SHOW_SIDEPANEL_GET, ''): return lexer = ed_self.get_prop(app.PROP_LEXER_FILE) if lexer and (lexer in self.helpers): self.update_tree(ed_self, lexer)
def config(self): opt_time = os.path.getmtime(JSONPATH) if os.path.exists( JSONPATH) else 0 theme_name = ct.app_proc(ct.PROC_THEME_SYNTAX_GET, '') if self.cfg.get('opt_time') == opt_time and \ self.cfg.get('theme_name') == theme_name: return self.cfg = self.get_config()
def on_state(self, ed_self, state): global _theme if state == ct.APPSTATE_THEME_SYNTAX: _theme = ct.app_proc(ct.PROC_THEME_SYNTAX_DICT_GET, "") if self.update_colors(): self.ed_ = ed_self self.update()
def _do_acts(self, what='', acts='|save|second|reg|keys|menu|'): ''' Use macro list ''' pass; #LOG and log('what, acts={}',(what, acts)) # Save if '|save|' in acts: open(MACROS_JSON, 'w').write(json.dumps({ 'ver':JSON_FORMAT_VER ,'list':self.macros ,'dlg_prs':self.dlg_prs ,'tm_ctrl':{'rp_ctrl':self.tm_ctrl.get('rp_ctrl', 1000) ,'tm_wait':self.tm_ctrl.get('tm_wait', 10)} }, indent=4)) # Secondary data if '|second|' in acts: self.mcr4id = {str(mcr['id']):mcr for mcr in self.macros} # Register new subcommands if '|reg|' in acts: reg_subs = 'cuda_macros;run;{}'.format('\n'.join( 'macro: {}\t{}'.format(mcr['nm'],mcr['id']) for mcr in self.macros) ) pass; #LOG and log('reg_subs={}',reg_subs) app.app_proc(app.PROC_SET_SUBCOMMANDS, reg_subs) # Clear keys.json if '|keys|' in acts and ':' in what: # Need delete a key 'cuda_macros,run,NNNNN' mcr_id = what[1+what.index(':'):] mcr_key = 'cuda_macros,run,{}'.format(mcr_id) keys_json = app.app_path(app.APP_DIR_SETTINGS)+os.sep+'keys.json' if not os.path.exists(keys_json): return keys = apx._json_loads(open(keys_json).read()) pass; #LOG and log('??? key={}',mcr_key) if keys.pop(mcr_key, None) is not None: pass; #LOG and log('UPD keys.json deleted key={}',mcr_key) open(keys_json, 'w').write(json.dumps(keys, indent=2)) # [Re]Build menu if '|menu|' in acts: self._adapt_menu()
def get_config(): def get_color(key, default_color): s = get_opt(key, '') if s: return ctx.html_color_to_int(s) else: return default_color def new_nkind(val, color): ct.ed.bookmark(ct.BOOKMARK_SETUP, 0, nkind=val, ncolor=color, text='') def get_theme(): data = ct.app_proc(ct.PROC_THEME_SYNTAX_DICT_GET, '') th = {} th['color_changed'] = data['LightBG2']['color_back'] th['color_added'] = data['LightBG3']['color_back'] th['color_deleted'] = data['LightBG1']['color_back'] return th t = get_theme() config = { 'opt_time': os.path.getmtime(JSONPATH) if os.path.exists(JSONPATH) else 0, 'theme_name': ct.app_proc(ct.PROC_THEME_SYNTAX_GET, ''), 'color_changed': get_color('changed_color', t.get('color_changed')), 'color_added': get_color('added_color', t.get('color_added')), 'color_deleted': get_color('deleted_color', t.get('color_deleted')), 'color_gaps': get_color('gap_color', ct.COLOR_NONE), 'sync_scroll': get_opt('sync_scroll', DEFAULT_SYNC_SCROLL == '1'), 'compare_with_details': get_opt('compare_with_details', True), 'ratio': get_opt('ratio_percents', 75) / 100, 'enable_sync_caret': get_opt('enable_sync_caret', False), 'enable_auto_refresh': get_opt('enable_auto_refresh', False), } new_nkind(NKIND_DELETED, config.get('color_deleted')) new_nkind(NKIND_ADDED, config.get('color_added')) new_nkind(NKIND_CHANGED, config.get('color_changed')) return config
def do_key_down(ag, key, data=''): scam = data if data else app.app_proc(app.PROC_GET_KEYSTATE, '') pass; #log('key,data,scam={}',(key,data,scam)) if iflog(log4fun,_log4mod) else 0 if 0:pass elif (scam,key)==('s',VK_ENTER): # Shift+Enter ag.update(do_next(ag, 'prev')) elif (scam,key)==('s',VK_ESCAPE): # Shift+Esc ed.set_caret(*ed_crts[0]) return None else: return [] # Nothing return False # Stop event
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 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)
def saveAs(self): ''' Save cur session to new file ''' if not _checkAPI(): return sscur = app.app_path(app.APP_FILE_SESSION) pass; app.msg_status(sscur) (ssdir ,ssfname) = os.path.split(sscur) ssfname = ssfname.replace('.json', '') ssnew = app.dlg_file(is_open=False, filters=DLG_CUD_FILTER , init_filename=ssfname , init_dir= ssdir ) pass; app.msg_status(str(ssnew)) if ssnew is None: return ssnew = apx.icase(False,'' , ssnew.endswith(CDSESS_EXT) , ssnew , os.path.isfile(ssnew) , ssnew , True , ssnew+CDSESS_EXT ) if os.path.normpath(sscur)==os.path.normpath(ssnew): return app.app_proc(app.PROC_SAVE_SESSION, sscur) app.app_proc(app.PROC_SAVE_SESSION, ssnew) app.app_proc(app.PROC_SET_SESSION, ssnew) app.msg_status(SAVED.format(stem=juststem(ssnew))) self.top_sess(ssnew)
def do_code(self, aid, ag): m,M = self,CfgKeysDlg lwks_n = ag.cval('lwks') if lwks_n==-1: return [] #continue#while m.cmd_id = m.fl_Is[lwks_n] pass; #LOG and log('m.fl_Is={}',(m.fl_Is)) pass; #LOG and log('lwks_n,m.cmd_id={}',(lwks_n,m.cmd_id)) if False:pass elif aid=='cpnm': cmd_nkk = m.id2nkks[m.cmd_id] app.app_proc(app.PROC_SET_CLIP, cmd_nkk[0]) elif aid=='open': pass; LOG and log('m.cmd_id={}',(m.cmd_id)) if type(m.cmd_id)!=str: return [] #continue#while plug_mdl, \ plug_mth = m.cmd_id.split(',')[0:2] plug_mth = 'def '+ plug_mth + '(self):' plug_dir = app.app_path(app.APP_DIR_PY)+os.sep+plug_mdl plug_py = plug_dir+os.sep+'__init__.py' plug_body = open(plug_py, encoding='UTF-8').read() pass; LOG and log('plug_mdl,plug_mth,plug_dir,plug_py={}',(plug_mdl,plug_mth,plug_dir,plug_py)) mch = re.search(r'from\s+\.(\w+)\s+import\s+Command', plug_body) if mch: # from .other_py import Command plug_py = plug_dir+os.sep+mch.group(1)+'.py' pass; LOG and log('plug_py={}',(plug_py)) plug_body=open(plug_py, encoding='UTF-8').read() if plug_mth not in plug_body: return [] #continue#while # Open app.file_open(plug_py) # Locate user_opt= app.app_proc(app.PROC_GET_FINDER_PROP, '') \ if app.app_api_version()>='1.0.248' else \ app.app_proc(app.PROC_GET_FIND_OPTIONS, '') # Deprecated ed.cmd(cmds.cmd_FinderAction, chr(1).join([] +['findnext'] +[plug_mth] +[''] +['fa'] )) if app.app_api_version()>='1.0.248': app.app_proc(app.PROC_SET_FINDER_PROP, user_opt) else: app.app_proc(app.PROC_SET_FIND_OPTIONS, user_opt) # Deprecated return None #break#while return []
def do_code(self, aid, ag, data=''): m,M = self,self.__class__ lwks_n = ag.cval('lwks') if lwks_n==-1: return [] #continue#while m.cmd_id = m.fl_Is[lwks_n] pass; #LOG and log('m.fl_Is={}',(m.fl_Is)) pass; #LOG and log('lwks_n,m.cmd_id={}',(lwks_n,m.cmd_id)) if False:pass elif aid=='cpnm': cmd_nkk = m.id2nkks[m.cmd_id] app.app_proc(app.PROC_SET_CLIP, cmd_nkk[0]) elif aid=='open': pass; LOG and log('m.cmd_id={}',(m.cmd_id)) if type(m.cmd_id)!=str: return [] #continue#while plug_mdl, \ plug_mth = m.cmd_id.split(',')[0:2] plug_mth = 'def '+ plug_mth + '(self):' plug_dir = app.app_path(app.APP_DIR_PY)+os.sep+plug_mdl plug_py = plug_dir+os.sep+'__init__.py' plug_body = open(plug_py, encoding='UTF-8').read() pass; LOG and log('plug_mdl,plug_mth,plug_dir,plug_py={}',(plug_mdl,plug_mth,plug_dir,plug_py)) mch = re.search(r'from\s+\.(\w+)\s+import\s+Command', plug_body) if mch: # from .other_py import Command plug_py = plug_dir+os.sep+mch.group(1)+'.py' pass; LOG and log('plug_py={}',(plug_py)) plug_body=open(plug_py, encoding='UTF-8').read() if plug_mth not in plug_body: return [] #continue#while # Open app.file_open(plug_py) # Locate user_opt= app.app_proc(app.PROC_GET_FINDER_PROP, '') \ if app.app_api_version()>='1.0.248' else \ app.app_proc(app.PROC_GET_FIND_OPTIONS, '') # Deprecated ed.cmd(cmds.cmd_FinderAction, chr(1).join([] +['findnext'] +[plug_mth] +[''] +['fa'] )) if app.app_api_version()>='1.0.248': app.app_proc(app.PROC_SET_FINDER_PROP, user_opt) else: app.app_proc(app.PROC_SET_FIND_OPTIONS, user_opt) # Deprecated return None #break#while return []
def tree_path_to_status(): pass; #log('?',()) path_l, gap = _get_best_tree_path(ed.get_carets()[0][1]) if not path_l: return ID_TREE = app.app_proc(app.PROC_SIDEPANEL_GET_CONTROL, 'Code tree') if not ID_TREE: return id_sel = app.tree_proc(ID_TREE, app.TREE_ITEM_GET_SELECTED) id_need = path_l[-1][0] if id_need != id_sel: app.tree_proc(ID_TREE, app.TREE_ITEM_SELECT, id_need) path = '['+ '] / ['.join([cap.rstrip(':')[:40] for (nid,cap) in path_l]) + ']' return app.msg_status_alt( path if gap==0 else f('[{:+}] {}', -gap, path) , 10)
def set_files(self, *files): for f in files: for h in ct.ed_handles(): e = ct.Editor(h) file_name = e.get_filename() if file_name == f: if e.get_prop(ct.PROP_MODIFIED): text = 'First you must save file:\n' + \ file_name + \ '\nYES: save and continue\n' + \ "NO: don't save (changes will be lost)" mb = ct.msg_box(text, ct.MB_YESNOCANCEL + ct.MB_ICONQUESTION) if mb == ct.ID_YES: e.save(file_name) elif mb == ct.ID_NO: e.set_prop(ct.PROP_MODIFIED, False) else: return e.focus() e.cmd(ct_cmd.cmd_FileClose) ct.app_idle(True) # better close file sleep(0.3) ct.app_idle(True) # better close file break ct.file_open(files, options='/nohistory') # if file was in group-2, and now group-2 is empty, set "one group" mode if ct.app_proc(ct.PROC_GET_GROUPING, '') in [ct.GROUPS_2VERT, ct.GROUPS_2HORZ]: e = ct.ed_group(1) # Editor obj in group-2 if not e: ct.app_proc(ct.PROC_SET_GROUPING, ct.GROUPS_ONE) self.refresh()
def get_groups_count(): dct = { app.GROUPS_ONE: 1, app.GROUPS_2VERT: 2, app.GROUPS_2HORZ: 2, app.GROUPS_3VERT: 3, app.GROUPS_3HORZ: 3, app.GROUPS_3PLUS: 3, app.GROUPS_1P2VERT: 3, app.GROUPS_1P2HORZ: 3, app.GROUPS_4VERT: 4, app.GROUPS_4HORZ: 4, app.GROUPS_4GRID: 4, app.GROUPS_6GRID: 6 } gr_mode = app.app_proc(app.PROC_GET_GROUPING, '') return dct.get(gr_mode, 1)
def get_groups_count(): dct = { app.GROUPS_ONE : 1, app.GROUPS_2VERT : 2, app.GROUPS_2HORZ : 2, app.GROUPS_3VERT : 3, app.GROUPS_3HORZ : 3, app.GROUPS_3PLUS : 3, app.GROUPS_1P2VERT : 3, app.GROUPS_1P2HORZ : 3, app.GROUPS_4VERT : 4, app.GROUPS_4HORZ : 4, app.GROUPS_4GRID : 4, app.GROUPS_6GRID : 6 } gr_mode = app.app_proc(app.PROC_GET_GROUPING, '') return dct.get(gr_mode, 1)
def get_translation(plug_file): ''' Part of i18n. Full i18n-cycle: 1. All GUI-string in code are used in form _('') 2. These string are extracted from code to lang/messages.pot with run python.exe <python-root>\Tools\i18n\pygettext.py -p lang <plugin>.py 3. Poedit (or same program) create <module>\lang\ru_RU\LC_MESSAGES\<module>.po from (cmd "Update from POT") lang/messages.pot It allows to translate all "strings" It creates (cmd "Save") <module>\lang\ru_RU\LC_MESSAGES\<module>.mo 4. <module>.mo can be placed also in dir CudaText\data\langpy\ru_RU\LC_MESSAGES\<module>.mo The dir is used first. 5. get_translation uses the file to realize _('') ''' lng = app.app_proc(app.PROC_GET_LANG, '') plug_dir = os.path.dirname(plug_file) plug_mod = os.path.basename(plug_dir) lng_dirs = [ app.app_path(app.APP_DIR_DATA) + os.sep + 'langpy', plug_dir + os.sep + 'lang', ] _ = lambda x: x pass #return _ for lng_dir in lng_dirs: lng_mo = lng_dir + '/{}/LC_MESSAGES/{}.mo'.format(lng, plug_mod) if os.path.isfile(lng_mo): t = gettext.translation(plug_mod, lng_dir, languages=[lng]) _ = t.gettext t.install() break return _
def _load_CID2NMS(): cid2nms = OrdDict() if True: #app.app_api_version()>='1.0.212': lcmds = app.app_proc(app.PROC_GET_COMMANDS, '') for cmd in lcmds: if cmd['type'] not in ('cmd', 'plugin'): continue cid2nms[cmd['cmd'] if cmd['type']=='cmd' else f('{},{},{}', cmd['p_module'], cmd['p_method'], cmd['p_method_params']).rstrip(',') ] = cmd['name'] # else: # old version # # Core cmds # for n in itertools.count(): # if not app.app_proc(app.PROC_GET_COMMAND, str(n)): break#for n # cid,cnm,\ # ck1,ck2 = app.app_proc(app.PROC_GET_COMMAND, str(n)) # if cid<=0: continue#for n # if cnm.endswith(r'\-'): continue#for n # command for separator in menu # if cnm.startswith('lexer:'): continue#for n # ?? lexer? smth-more? # if cnm.startswith('plugin:'): continue#for n # ?? plugin? smth-more? # cid2nms[cid] = cnm # #for n # pass; #LOG and log('|cid2nms|={}',len(cid2nms)) # pass; #LOG and log('|CO_CID2SGN|={}',len(CO_CID2SGN)) # pass; #LOG and log('diff={}',({cid for cid in cid2nms}-{cid for cid in CO_CID2SGN})) # pass; #LOG and log('diff={}',({cid for cid in CO_CID2SGN}-{cid for cid in cid2nms})) # pass; #LOG and log('diff={}',({cid:sgn for cid,sgn in CO_CID2SGN.items() if cid not in cid2nms})) # pass; #assert {cid for cid in cid2nms}=={cid for cid in CO_CID2SGN} # for n in itertools.count(): # if not app.app_proc(app.PROC_GET_COMMAND_PLUGIN, str(n)): break#for n # pnm, \ # modul, \ # meth, \ # par, \ # lxrs = app.app_proc(app.PROC_GET_COMMAND_PLUGIN, str(n)) # if pnm.endswith(r'\-'): continue#for n # command for separator in menu # pid = modul+','+meth+(','+par if par else '') # cid2nms[pid] = 'plugin: '+pnm.replace('&', '').replace('\\', ': ') # #for n return cid2nms
def run(self): global file_history self.ready = False open_files = [] for h in ct.ed_handles(): f = ct.Editor(h).get_filename() if os.path.isfile(f): open_files.append(f) items = "\t".join(open_files + file_history.items) self.f1 = ct.ed.get_filename() self.f2 = '' if ct.app_proc(ct.PROC_GET_GROUPING, '') == ct.GROUPS_ONE: # if 2 files opened in group-1, suggest these 2 files hh = ct.ed_handles() if len(hh) == 2: name1 = ct.Editor(hh[0]).get_filename() name2 = ct.Editor(hh[1]).get_filename() if name1 and name2: self.f1 = name1 self.f2 = name2 else: e1 = ct.ed_group(0) e2 = ct.ed_group(1) if e1 and e2: self.f1 = e1.get_filename() self.f2 = e2.get_filename() dlg = self.dialog(items) ct.dlg_proc(dlg, ct.DLG_SHOW_MODAL) ct.dlg_proc(dlg, ct.DLG_FREE) if self.ready: return (self.f1, self.f2)
def paste_to_1st_col(self): ''' Paste from clipboard without replacement caret/selection but only insert before current line ''' pass; #LOG and log('') clip = app.app_proc(app.PROC_GET_CLIP, '') if not clip: return clip = clip.replace('\r\n', '\n').replace('\r', '\n') if not (clip[-1] in '\r\n'): clip= clip + '\n' rnews = clip.count('\n') crts = ed.get_carets() if len(crts)>1: return app.msg_status(ONLY_SINGLE_CRT.format('Command')) (cCrt, rCrt, cEnd, rEnd) = crts[0] r4ins = min(rCrt, rCrt if -1==rEnd else rEnd) ed.insert(0, r4ins, clip) rCrtN = rCrt+ rnews rEndN = rEnd+(rnews if -1!=rEnd else 0) pass; #LOG and log('(rCrtN, rEndN)={}',(rCrtN, rEndN)) ed.set_caret(cCrt, rCrtN ,cEnd, rEndN) pass; return ##?? for icrt, (cCrt, rCrt, cEnd, rEnd) in reversed(list(enumerate(crts))): # for icrt, (cCrt, rCrt, cEnd, rEnd) in enumerate(crts): pass; #LOG and log('icrt, (cCrt, rCrt, cEnd, rEnd), rnews={}',(icrt, (cCrt, rCrt, cEnd, rEnd), rnews)) rCrtA = rCrt+rnews*icrt rEndA = rEnd+rnews*icrt if -1!=rEnd else -1 r4ins = min(rCrt, rCrt if -1==rEnd else rEnd) pass; #LOG and log('(rCrtA, rEndA), r4ins={}',((rCrtA, rEndA), r4ins)) ed.insert(0, r4ins, clip) rCrtN = rCrt+ rnews rEndN = rEnd+(rnews if -1!=rEnd else 0) pass; #LOG and log('(rCrtN, rEndN)={}',(rCrtN, rEndN)) ed.set_caret(cCrt, rCrtN ,cEnd, rEndN ,app.CARET_SET_INDEX+icrt)
def arrange_tabs_grps(): GMAP = { app.GROUPS_ONE: 1, app.GROUPS_2VERT: 2, app.GROUPS_2HORZ: 2, app.GROUPS_3VERT: 3, app.GROUPS_3HORZ: 3, app.GROUPS_1P2VERT: 3, app.GROUPS_1P2HORZ: 3, app.GROUPS_4VERT: 4, app.GROUPS_4HORZ: 4, app.GROUPS_4GRID: 4, app.GROUPS_6VERT: 6, app.GROUPS_6HORZ: 6, app.GROUPS_6GRID: 6, } hh = list(app.ed_handles()) hnum = len(hh) gg = app.app_proc(app.PROC_GET_GROUPING, '') gnum = GMAP.get(gg) if gnum is None or gnum < 2: app.msg_status(_('Cannot arrange tabs with single group')) return hh = hh[:gnum] for (i, h) in reversed(list(enumerate(hh))): if i == 0: break h = app.Editor(h).get_prop(app.PROP_HANDLE_SELF) app.Editor(h).set_prop(app.PROP_INDEX_GROUP, i) hh = app.ed_handles() app.Editor(hh[0]).focus() app.msg_status(_('Arranged %d tab(s) across %d group(s)') % (hnum, gnum))
def dlg_valign_consts(): pass; #log('ok') UP = '/\\' UP = '↑↑' # UP = 'ΛΛΛ' DN = '\\/' DN = '↓↓' # DN = 'VVV' DLG_W, \ DLG_H = 335, 280 fits = dict( _sp1=fit_top_by_env('check') ,_sp2=fit_top_by_env('edit') ,_sp3=fit_top_by_env('button') ,_sp4=fit_top_by_env('combo_ro') ,_sp5=fit_top_by_env('combo') ,_sp6=fit_top_by_env('checkbutton') ,_sp7=fit_top_by_env('linklabel') ,_sp8=fit_top_by_env('spinedit') ) vals = dict( ch1 =False ,ed2 ='=======?' ,cbo4=0 ,cb5 ='=======?' ,chb6=0 ,sp8 =4444444 ) focused = '-' while True: aid, vals, fid, chds = dlg_wrapper(_('Adjust vertical alignments') ,DLG_W, DLG_H, [dict(cid='lb1' ,tp='lb' ,t= 10 ,l= 5 ,w=100 ,cap='===============' ) ,dict(cid='ch1' ,tp='ch' ,t= 10+fits['_sp1'] ,l=115 ,w=100 ,cap='=======?' ,hint=fits['_sp1'] ) ,dict(cid='up1' ,tp='bt' ,t= 10-3 ,l=230 ,w=50 ,cap=UP ) ,dict(cid='dn1' ,tp='bt' ,t= 10-3 ,l=280 ,w=50 ,cap=DN ) ,dict(cid='lb2' ,tp='lb' ,t= 40 ,l= 5 ,w=100 ,cap='===============' ) ,dict(cid='ed2' ,tp='ed' ,t= 40+fits['_sp2'] ,l=115 ,w=100 ,hint=fits['_sp2'] ) ,dict(cid='up2' ,tp='bt' ,t= 40-3 ,l=230 ,w=50 ,cap=UP ) ,dict(cid='dn2' ,tp='bt' ,t= 40-3 ,l=280 ,w=50 ,cap=DN ) ,dict(cid='lb3' ,tp='lb' ,t= 70 ,l= 5 ,w=100 ,cap='===============' ) ,dict(cid='bt3' ,tp='bt' ,t= 70+fits['_sp3'] ,l=115 ,w=100 ,cap='=======?' ,hint=fits['_sp3'] ) ,dict(cid='up3' ,tp='bt' ,t= 70-3 ,l=230 ,w=50 ,cap=UP ) ,dict(cid='dn3' ,tp='bt' ,t= 70-3 ,l=280 ,w=50 ,cap=DN ) ,dict(cid='lb4' ,tp='lb' ,t=100 ,l= 5 ,w=100 ,cap='===============' ) ,dict(cid='cbo4' ,tp='cb-ro' ,t=100+fits['_sp4'] ,l=115 ,w=100 ,items=['=======?'] ,hint=fits['_sp4'] ) ,dict(cid='up4' ,tp='bt' ,t=100-3 ,l=230 ,w=50 ,cap=UP ) ,dict(cid='dn4' ,tp='bt' ,t=100-3 ,l=280 ,w=50 ,cap=DN ) ,dict(cid='lb5' ,tp='lb' ,t=130 ,l= 5 ,w=100 ,cap='===============' ) ,dict(cid='cb5' ,tp='cb' ,t=130+fits['_sp5'] ,l=115 ,w=100 ,items=['=======?'] ,hint=fits['_sp5'] ) ,dict(cid='up5' ,tp='bt' ,t=130-3 ,l=230 ,w=50 ,cap=UP ) ,dict(cid='dn5' ,tp='bt' ,t=130-3 ,l=280 ,w=50 ,cap=DN ) ,dict(cid='lb6' ,tp='lb' ,t=160 ,l= 5 ,w=100 ,cap='===============' ) ,dict(cid='chb6' ,tp='ch-bt' ,t=160+fits['_sp6'] ,l=115 ,w=100 ,cap='=======?' ,hint=fits['_sp6'] ) ,dict(cid='up6' ,tp='bt' ,t=160-3 ,l=230 ,w=50 ,cap=UP ) ,dict(cid='dn6' ,tp='bt' ,t=160-3 ,l=280 ,w=50 ,cap=DN ) ,dict(cid='lb7' ,tp='lb' ,t=190 ,l= 5 ,w=100 ,cap='===============' ) ,dict(cid='chb7' ,tp='ln-lb' ,t=190+fits['_sp7'] ,l=115 ,w=100 ,cap='=======?',props='-' ,hint=fits['_sp7'] ) ,dict(cid='up7' ,tp='bt' ,t=190-3 ,l=230 ,w=50 ,cap=UP ) ,dict(cid='dn7' ,tp='bt' ,t=190-3 ,l=280 ,w=50 ,cap=DN ) ,dict(cid='lb8' ,tp='lb' ,t=220 ,l= 5 ,w=100 ,cap='4444444444444444' ) ,dict(cid='sp8' ,tp='sp-ed' ,t=220+fits['_sp8'] ,l=115 ,w=100 ,props='0,4444444,1' ,hint=fits['_sp8'] ) ,dict(cid='up8' ,tp='bt' ,t=220-3 ,l=230 ,w=50 ,cap=UP ) ,dict(cid='dn8' ,tp='bt' ,t=220-3 ,l=280 ,w=50 ,cap=DN ) ,dict(cid='save' ,tp='bt' ,t=DLG_H-30 ,l=115 ,w=100 ,cap=_('&Save') ,hint=_('Apply the fittings to controls of all dialogs.' '\rCtrl+Click - Show data to mail report.')) ,dict(cid='-' ,tp='bt' ,t=DLG_H-30 ,l=230 ,w=100 ,cap=_('Cancel') ) ], vals, focus_cid=focused) if aid is None or aid=='-': return#while True scam = app.app_proc(app.PROC_GET_KEYSTATE, '') if app.app_api_version()>='1.0.143' else '' aid_m = scam + '/' + aid if scam and scam!='a' else aid # smth == a/smth focused = chds[0] if 1==len(chds) else focused if aid[:2]=='up' or aid[:2]=='dn': pos = aid[2] fits['_sp'+pos] = fits['_sp'+pos] + (-1 if aid[:2]=='up' else 1) if aid_m=='save': ctrls = ['check' ,'edit' ,'button' ,'combo_ro' ,'combo' ,'checkbutton' ,'linklabel' ,'spinedit' ] for ic, nc in enumerate(ctrls): fit = fits['_sp'+str(1+ic)] if fit==fit_top_by_env(nc): continue#for ic, nc apx.set_opt('dlg_wrapper_fit_va_for_'+nc, fit) #for ic, nc fit_top_by_env__clear() break#while if aid_m=='c/save': # Report rpt = 'env:'+get_desktop_environment() rpt+= c13+'check:' +str(fits['_sp1']) rpt+= c13+'edit:' +str(fits['_sp2']) rpt+= c13+'button:' +str(fits['_sp3']) rpt+= c13+'combo_ro:' +str(fits['_sp4']) rpt+= c13+'combo:' +str(fits['_sp5']) rpt+= c13+'checkbutton:'+str(fits['_sp6']) rpt+= c13+'linklabel:' +str(fits['_sp7']) rpt+= c13+'spinedit:' +str(fits['_sp8']) aid_r, *_t = dlg_wrapper(_('Report'), 230,310, [dict(cid='rprt',tp='me' ,t=5 ,l=5 ,h=200 ,w=220) ,dict( tp='lb' ,t=215 ,l=5 ,w=220 ,cap=_('Send the report to the address')) ,dict(cid='mail',tp='ed' ,t=235 ,l=5 ,w=220) ,dict( tp='lb' ,t=265 ,l=5 ,w=150 ,cap=_('or post it on')) ,dict(cid='gith',tp='ln-lb' ,t=265 ,l=155 ,w=70 ,cap='GitHub',props='https://github.com/kvichans/cuda_fit_v_alignments/issues') ,dict(cid='-' ,tp='bt' ,t=280 ,l=205-80 ,w=80 ,cap=_('Close')) ], dict(rprt=rpt ,mail='*****@*****.**'), focus_cid='rprt')
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)
def insert_snip_into_editor(ed, snip_lines): items = list(snip_lines) #copy list value if not items: return carets = ed.get_carets() if len(carets)!=1: return x0, y0, x1, y1 = carets[0] tab_spaces = ed.get_prop(ct.PROP_TAB_SPACES) tab_size = ed.get_prop(ct.PROP_TAB_SIZE) text_sel = ed.get_text_sel() text_clip = ct.app_proc(ct.PROC_GET_CLIP, '') text_filename = os.path.basename(ed.get_filename()) #strip file-ext n = text_filename.rfind('.') if n>=0: text_filename = text_filename[:n] #delete selection if text_sel: #sort coords (x0/y0 is left) if (y1>y0) or ((y1==y0) and (x1>=x0)): pass else: x0, y0, x1, y1 = x1, y1, x0, y0 ed.delete(x0, y0, x1, y1) ed.set_caret(x0, y0) #apply indent to lines from second x_col, y_col = ed.convert(ct.CONVERT_CHAR_TO_COL, x0, y0) indent = ' '*x_col if not tab_spaces: indent = indent.replace(' '*tab_size, '\t') for i in range(1, len(items)): items[i] = indent+items[i] #replace tab-chars if tab_spaces: indent = ' '*tab_size items = [item.replace('\t', indent) for item in items] #parse macros snip_replace_macros_in_lines(items, text_sel, text_clip, text_filename) #parse tabstops ${0}, ${0:text} stops = [] for index in range(len(items)): s = items[index] while True: digit = 0 deftext = '' n = s.find('${') if n<0: break if n+3>=len(s): break if not s[n+3] in ':}': break try: digit = int(s[n+2]) except: break #text in tabstop if s[n+3]==':': deftext = s[n+4:] nn = deftext.find('}') if nn<0: break deftext = deftext[:nn] s = s[:n]+deftext+s[n+5+nn:] else: s = s[:n]+s[n+4:] stops += [(digit, deftext, index, n)] items[index] = s #print('tabstops', stops) #insert ed.insert(x0, y0, '\n'.join(items)) #place markers mark_placed = False ed.markers(ct.MARKERS_DELETE_ALL) for digit in [0,9,8,7,6,5,4,3,2,1]: #order of stops: 1..9, 0 for stop in reversed(stops): #reversed is for Emmet: many stops with ${0} if stop[0]==digit: pos_x = stop[3] pos_y = stop[2] if pos_y==0: pos_x += x0 pos_y += y0 deftext = stop[1] ed.markers(ct.MARKERS_ADD, pos_x, pos_y, digit, len(deftext)) mark_placed = True if mark_placed: ed.set_prop(ct.PROP_TAB_COLLECT_MARKERS, '1') ed.cmd(cudatext_cmd.cmd_Markers_GotoLastAndDelete)
def do_work(self, aid, ag): m,M = self,CfgKeysDlg lwks_n = ag.cval('lwks') if lwks_n==-1: return [] #continue#while m.cmd_id = m.fl_Is[lwks_n] if False:pass elif aid in ('del1', 'del2'): # Delete the hotkeys cmd_nkk = m.id2nkks[m.cmd_id] del_i = 1 if aid=='del1' else 2 if not cmd_nkk[del_i]: return [] #continue#while cmd_nkk[del_i] = '' if cmd_nkk[2]: cmd_nkk[1] = cmd_nkk[2] cmd_nkk[2] = '' set_ok = app.app_proc(app.PROC_SET_HOTKEY, f('{}|{}|{}', m.cmd_id, cmd_nkk[1], cmd_nkk[2])) if not set_ok: log('Fail to use PROC_SET_HOTKEY for cmd "{}"', m.cmd_id) m.nkki_l, \ m.id2nkks, \ m.ks2id = M.prep_keys_info() elif aid in ('add1', 'add2'): ext_k = app.dlg_hotkey() pass; #LOG and log('ext_k={}',(ext_k,)) if ext_k is None: return [] #continue#while cmd_nkk = m.id2nkks[m.cmd_id] add_i = 1 if aid=='add1' else 2 old_k = cmd_nkk[add_i] new_k = old_k + ' * ' + ext_k if old_k else ext_k pass; #LOG and log('cmd_nkk,old_k,new_k={}',(cmd_nkk,old_k,new_k)) if new_k in m.ks2id: dbl_id = m.ks2id[new_k] dbl_nkk = m.id2nkks[dbl_id] if app.msg_box(f(_('Hotkey "{}" is already assigned ' '\nto command "{}".' '\n' '\nDo you want to reassign the hotkey ' '\nto selected command "{}"?') , new_k, dbl_nkk[0], cmd_nkk[0]), app.MB_OKCANCEL)==app.ID_CANCEL: return [] #continue#while dbl_i = 1 if dbl_nkk[1]==new_k else 2 pass; #LOG and log('dbl_id, dbl_nkk={}',(dbl_id, dbl_nkk)) dbl_nkk[dbl_i] = '' if dbl_nkk[2]: dbl_nkk[1], dbl_nkk[2] = dbl_nkk[2], '' pass; #LOG and log('dbl_id, dbl_nkk={}',(dbl_id, dbl_nkk)) set_ok = app.app_proc(app.PROC_SET_HOTKEY, f('{}|{}|{}', dbl_id, dbl_nkk[1], dbl_nkk[2])) if not set_ok: log('Fail to use PROC_SET_HOTKEY for cmd "{}"', dbl_id) cmd_nkk[add_i] = new_k pass; #LOG and log('cmd_id, cmd_nkk={}',(cmd_id, cmd_nkk)) set_ok = app.app_proc(app.PROC_SET_HOTKEY, f('{}|{}|{}', m.cmd_id, cmd_nkk[1], cmd_nkk[2])) if not set_ok: log('Fail to use PROC_SET_HOTKEY for cmd "{}"', m.cmd_id) m.nkki_l, \ m.id2nkks, \ m.ks2id = M.prep_keys_info() elif aid=='asnp' and sndt: cnm = sndt.get_name(m.cmd_id) new_sn = app.dlg_input(f(_('Add snip for "{}"'), cnm), '') if not new_sn: return [] #continue#while while not SnipData.is_snip(new_sn): app.msg_status(SnipData.msg_correct_snip) new_sn = app.dlg_input(f(_('Snip for "{}"'), cnm), new_sn) if not new_sn: break if not new_sn: return [] #continue#while pre_cid = sndt.get_cmdid(new_sn) if pre_cid: pre_cnm = sndt.get_name(pre_cid) if app.msg_box(f(_('Snip "{}" is already assigned ' '\nto command "{}".' '\n' '\nDo you want to reassign the snip ' '\nto command "{}"?') , new_sn, pre_cnm, cnm), app.MB_OKCANCEL)==app.ID_CANCEL: return [] #continue#while sndt.set(new_sn, cmd_id) elif aid=='rsnp' and sndt: cnm = sndt.get_name(m.cmd_id) snp_l = sndt.get_snips(m.cmd_id) snps = ', '.join(snp_l) if app.msg_box(f(_('Do you want to remove snip(s) ' '\n {}' '\nfor command "{}"?') , snps, cnm), app.MB_OKCANCEL)==app.ID_CANCEL: return [] #continue#while for snp in snp_l: sndt.free(snp) return dict(ctrls=self.get_cnts('lwks') , vals =self.get_vals('lwks') , fid ='lwks' )
def close(self): sscur = app.app_path(app.APP_FILE_SESSION) app.app_proc(app.PROC_SAVE_SESSION, sscur) app.app_proc(app.PROC_SET_SESSION, 'history session.json') # w/o path to use "settings" portable way pass; #LOG and log('ok',())
pass; pf=lambda d:pformat(d,width=150) pass; pf80=lambda d:pformat(d,width=80) pass; pf60=lambda d:pformat(d,width=60) pass; ##!! waits correction _ = apx.get_translation(__file__) # I18N VERSION = re.split('Version:', __doc__)[1].split("'")[1] VERSION_V, \ VERSION_D = VERSION.split(' ') MAX_HIST = apx.get_opt('ui_max_history_edits', 20) CFG_JSON = app.app_path(app.APP_DIR_SETTINGS)+os.sep+'cuda_options_editor.json' HTM_RPT_FILE= str(Path(tempfile.gettempdir()) / 'CudaText_option_report.html') FONT_LST = ['default'] \ + [font for font in app.app_proc(app.PROC_ENUM_FONTS, '') if not font.startswith('@')] NO_CHAP = _('_no_') pass; #FONT_LST=FONT_LST[:3] def f(s, *args, **kwargs):return s.format(*args, **kwargs) def log(msg='', *args, **kwargs): if args or kwargs: msg = msg.format(*args, **kwargs) return msg
def adapt_menu(self,id_menu=0): ''' Add or change top-level menu Macros Param id_menu points to exist menu item (ie by ConfigMenu) for filling ''' pass; LOG and log('id_menu={}',id_menu) PLUG_HINT = '_'+'cuda_macros:adapt_menu' # "_" is sign for ConfigMenu. ":" is subst for "," to avoid call "import ..." if id_menu!=0: # Use this id app.app_proc(app.PROC_MENU_CLEAR, str(id_menu)) else: top_nms = app.app_proc(app.PROC_MENU_ENUM, 'top') if PLUG_HINT in top_nms: # Reuse id from 'top' inf = [inf for inf in top_nms.splitlines() if PLUG_HINT in inf][0] ##?? id_menu = inf.split('|')[2] app.app_proc(app.PROC_MENU_CLEAR, id_menu) else: # Create BEFORE Plugins top_nms = top_nms.splitlines() pass; #LOG and log('top_nms={}',top_nms) if app.app_exe_version() >= '1.0.131': plg_ind = [i for (i,nm) in enumerate(top_nms) if '|plugins' in nm][0] else: # old, pre i18n plg_ind = top_nms.index('&Plugins|') ##?? id_menu = app.app_proc( app.PROC_MENU_ADD, '{};{};{};{}'.format('top', PLUG_HINT, _('&Macros'), plg_ind)) # Fill def hotkeys_desc(cmd_id): hk_s= get_hotkeys_desc(cmd_id) hk_s= '\t\t'+hk_s if hk_s else hk_s return hk_s hk_s = hotkeys_desc( 'cuda_macros,dlg_config') app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, 'cuda_macros,dlg_config',_('&Macros...')+hk_s)) app.app_proc(app.PROC_MENU_ADD, '{};;-'.format( id_menu)) hk_s = hotkeys_desc( cmds.cmd_MacroStart) app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, cmds.cmd_MacroStart, _('&Start record')+hk_s)) hk_s = hotkeys_desc( cmds.cmd_MacroStop) app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, cmds.cmd_MacroStop, _('St&op record')+hk_s)) hk_s = hotkeys_desc( cmds.cmd_MacroCancel) app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, cmds.cmd_MacroCancel, _('&Cancel record')+hk_s)) app.app_proc(app.PROC_MENU_ADD, '{};;-'.format( id_menu)) hk_s = hotkeys_desc( 'cuda_macros,dlg_export') app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, 'cuda_macros,dlg_export',_('&Export...')+hk_s)) hk_s = hotkeys_desc( 'cuda_macros,dlg_import') app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, 'cuda_macros,dlg_import',_('&Import...')+hk_s)) if 0==len(self.macros): return app.app_proc(app.PROC_MENU_ADD, '{};;-'.format( id_menu)) id_sub = app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, 0, _('&Run'))) for mcr in self.macros: hk_s= hotkeys_desc( f('cuda_macros,run,{}',mcr['id'])) app.app_proc(app.PROC_MENU_ADD, '{};{}{};{}'.format(id_sub, 'cuda_macros,run,' ,mcr['id'], mcr['nm']+hk_s))
def collect_data(): ''' Collect data ''' keys2nms = {} has_series = False dblkeys = [] ctgs = [] cmdinfos = [] n=0 while True: # Cud (5 ,'smth', 'Shift+Ctrl+F1', 'Alt+Q * Ctrl+T') # Syn (5,'ctg','smth', 'Shift+Ctrl+F1', 'Alt+Q · Ctrl+T') cmdinfo = app.app_proc(app.PROC_GET_COMMAND, str(n)) n += 1 if cmdinfo is None: break if cmdinfo[0]<=0: continue if app_name=='CudaText': # Add default category cmdinfo = ('Commands', cmdinfo[1], cmdinfo[2], cmdinfo[3]) else: cmdinfo = (cmdinfo[1], cmdinfo[2], cmdinfo[3], cmdinfo[4]) ctg, name, keys1, keys2 = cmdinfo if name.startswith('lexer:'): continue # ?? lexer? smth-more? if (app_name=='CudaText' and name.startswith('plugin:')): continue # ?? plugin? smth-more? if (app_name=='SynWrite' and ctg=='Plugin'): cmdinfo = (ctg, 'Plugin: '+name, keys1, keys2) cmdinfos += [cmdinfo] if app_name=='CudaText': cmdinfos = add_cud_plugins(cmdinfos, 'plugin: ', 'Plugins') for ctg, name, keys1, keys2 in cmdinfos: if ctg not in ctgs: ctgs += [ctg] for keys in (keys1, keys2): if not keys: continue if srs_dlm in keys: # Series: Alt+Q * Ctrl+T # It will be parsed later when all single keys are done has_series = True continue # see Repeat... else: btn = ('+'+keys).split('+')[-1] # 'B' from 'Shift+Ctrl+B' save_btn_mod_name( btn , keys[:-len(btn)].rstrip('+') # 'Shift+Ctrl' from 'Shift+Ctrl+B' , name, keys , mods, btns, keys2nms, dblkeys ) # Repeat to parse series for ctg, name, keys1, keys2 in cmdinfos: for keys in (keys1, keys2): if srs_dlm not in keys: continue # Series: Alt+Q * Ctrl+T # 1. Check a conflict with head # (Alt+)(Q) keys_hd = keys.split(srs_dlm)[0] # 'Alt+Q' from 'Alt+Q * Ctrl+T' if keys_hd in keys2nms: # Conflict! dblkeys += [keys_hd] keys2nms[keys_hd] += [name] # 2. Save as # (Alt+Q * Ctrl+)(T) btn = ('+'+keys.split(srs_dlm)[-1]).split('+')[-1] # 'T' from 'Alt+Q * Ctrl+T' or 'Alt+Q * T' save_btn_mod_name( btn , keys[:-len(btn)].rstrip('+') # 'Alt+Q * Ctrl' from 'Alt+Q * Ctrl+T' , name, keys , mods, btns, keys2nms, dblkeys ) return (keys2nms ,has_series ,dblkeys ,ctgs ,cmdinfos)
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)
def insert_snip_into_editor(ed, snip_lines): items = list(snip_lines) #copy list value if not items: return carets = ed.get_carets() if len(carets)!=1: return x0, y0, x1, y1 = carets[0] tab_spaces = ed.get_prop(ct.PROP_TAB_SPACES) tab_size = ed.get_prop(ct.PROP_TAB_SIZE) text_sel = ed.get_text_sel() text_clip = ct.app_proc(ct.PROC_GET_CLIP, '') text_filename = os.path.basename(ed.get_filename()) #strip file-ext n = text_filename.rfind('.') if n>=0: text_filename = text_filename[:n] #delete selection if text_sel: #sort coords (x0/y0 is left) if (y1>y0) or ((y1==y0) and (x1>=x0)): pass else: x0, y0, x1, y1 = x1, y1, x0, y0 ed.delete(x0, y0, x1, y1) ed.set_caret(x0, y0) #apply indent to lines from second x_col, y_col = ed.convert(ct.CONVERT_CHAR_TO_COL, x0, y0) indent = ' '*x_col if not tab_spaces: indent = indent.replace(' '*tab_size, '\t') for i in range(1, len(items)): items[i] = indent+items[i] #replace tab-chars if tab_spaces: indent = ' '*tab_size items = [item.replace('\t', indent) for item in items] #parse macros snip_replace_macros_in_lines(items, text_sel, text_clip, text_filename) #parse tabstops ${0}, ${0:text} stops = [] s_text = '\n'.join(items) s_text = s_text.replace('\\\\', chr(2)).replace('\\$', chr(1)) #handle escaped '$' while True: digit = 0 deftext = '' n = s_text.find('${') if n<0: break n_end = find_matching_bracket(s_text, n+1, '{}') if n_end is None: print('Incorrect brackets ${..}') return text_in = s_text[n+2:n_end] nested = False nested_shift = 0 nested_on_1st_line = True #find nested ins-point nn = text_in.find('${') if nn>=0: n = n+2+nn n_end = find_matching_bracket(s_text, n+1, '{}') if n_end is None: print('Incorrect nested brackets ${..}') return nested_on_1st_line = text_in.count('\n', 0, nn) == 0 text_in = s_text[n+2:n_end] nested = True try: if ':' in text_in: _separ = text_in.split(':') digit = int(_separ[0]) deftext = _separ[1] else: digit = int(text_in) except: print('Incorrect ins-point index: '+s_text) return if nested and nested_on_1st_line: nested_shift = len(str(digit))+3 #delete spec-chars s_text = s_text[:n]+deftext+s_text[n_end+1:] pos_y = s_text.count('\n', 0, n) eol_pos = -1 for k in range(pos_y): eol_pos = s_text.find('\n', eol_pos+1) pos_x = n-nested_shift-eol_pos-1 stops += [(digit, deftext, pos_y, pos_x)] #print('tabstops', stops) #insert s_text = s_text.replace(chr(2), '\\').replace(chr(1), '$') #handle escaped '$' ed.insert(x0, y0, s_text) #place markers mark_placed = False ed.markers(ct.MARKERS_DELETE_ALL) #list: 0,max,max-1,...,3,2,1 digit_list = [0] + list(range(SNIP_MAX_POINTS, 0, -1)) for digit in digit_list: #order of stops: 1..max, 0 for stop in reversed(stops): #reversed is for Emmet: many stops with ${0} if stop[0]==digit: deftext = stop[1] pos_y = stop[2] pos_x = stop[3] if pos_y==0: pos_x += x0 pos_y += y0 len_x, len_y = snip_get_lens(deftext) ed.markers(ct.MARKERS_ADD, pos_x, pos_y, digit, len_x, len_y ) mark_placed = True if mark_placed: ed.set_prop(ct.PROP_TAB_COLLECT_MARKERS, '1') ed.cmd(cudatext_cmd.cmd_Markers_GotoLastAndDelete) else: #place caret after text len_x, len_y = snip_get_lens(s_text) if len_y<=1: ed.set_caret(x0+len_x, y0) else: ed.set_caret(len_x, y0+len_y)
def _adapt_menu(self): ''' Add or change top-level menu Macros ''' id_menu = 0 if 'macros_id_menu' in dir(ed): ##?? dirty hack! id_menu = ed.macros_id_menu ##?? dirty hack! # Clear old app.app_proc(app.PROC_MENU_CLEAR, id_menu) else: # if 0==self.id_menu: # Create top_nms = app.app_proc(app.PROC_MENU_ENUM, 'top').splitlines() pass; #LOG and log('top_nms={}',top_nms) plg_ind = top_nms.index('&Plugins|') ##?? id_menu = app.app_proc( app.PROC_MENU_ADD, '{};{};{};{}'.format('top', 0, '&Macros', plg_ind)) ed.macros_id_menu = id_menu ##?? dirty hack! # Fill app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, 'cuda_macros,dlg_config','&Macros...')) app.app_proc(app.PROC_MENU_ADD, '{};;-'.format( id_menu)) app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, cmds.cmd_MacroStart, '&Start record')) app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, cmds.cmd_MacroStop, 'St&op record')) app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, cmds.cmd_MacroCancel, '&Cancel record')) app.app_proc(app.PROC_MENU_ADD, '{};;-'.format( id_menu)) app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, 'cuda_macros,dlg_export','&Export...')) app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, 'cuda_macros,dlg_import','&Import...')) if 0==len(self.macros): return app.app_proc(app.PROC_MENU_ADD, '{};;-'.format( id_menu)) id_sub = app.app_proc(app.PROC_MENU_ADD, '{};{};{}'.format(id_menu, 0, '&Run')) for mcr in self.macros: app.app_proc(app.PROC_MENU_ADD, '{};{}{};{}'.format(id_sub, 'cuda_macros,run,',mcr['id'], mcr['nm']))
def find_cb_string(self, updn, bgn_crt_fin='crt'): ''' Find clipboard value in text. Params updn 'up'|'dn' - direction bgn_crt_fin 'bgn'|'crt'|'fin' - start point ''' clip = app.app_proc(app.PROC_GET_CLIP, '') if ''==clip: return clip = clip.replace('\r\n', '\n').replace('\r', '\n') pass; #LOG and log('clip={}',repr(clip)) crts = ed.get_carets() if len(crts)>1: return app.msg_status(ONLY_SINGLE_CRT.format('Command')) # Prepare bgn-, crt-, fin-point (cBgn, rBgn) = (0, 0) (cCrt, rCrt ,cEnd, rEnd) = crts[0] lst_line_ind = ed.get_line_count()-1 lst_line = ed.get_text_line(lst_line_ind) (cFin, rFin) = (max(0, len(lst_line)-1), lst_line_ind) if bgn_crt_fin=='crt': # Some cases for natural (not wrap) find if updn=='dn' and (cFin, rFin) == (cCrt, rCrt): # Caret at finish - immediately find from start return self.find_cb_string(updn, bgn_crt_fin='bgn') if updn=='up' and (cBgn, rBgn) == (cCrt, rCrt): # Caret at start - immediately find from finish return self.find_cb_string(updn, bgn_crt_fin='fin') if updn=='dn' and (cBgn, rBgn) == (cCrt, rCrt): # Caret already at start - switch wrap off bgn_crt_fin = 'bgn' if updn=='up' and (cFin, rFin) == (cCrt, rCrt): # Caret already at finish - switch wrap off bgn_crt_fin = 'fin' (cPnt, rPnt ,cEnd, rEnd) = apx.icase(False,0 ,bgn_crt_fin=='bgn', (cBgn, rBgn, cBgn, rBgn) ,bgn_crt_fin=='crt', (cCrt, rCrt, cEnd, rEnd) ,bgn_crt_fin=='fin', (cFin, rFin, cFin, rFin) ) # Main part if '\n' not in clip: # 1) Find inside each line row = rPnt line = ed.get_text_line(row) pos = line.find(clip, cPnt) if updn=='dn' else line.rfind(clip, 0, cPnt) while -1==pos: row = apx.icase(updn=='dn', row+1, updn=='up', row-1, -1) if row<0 or row==ed.get_line_count(): break #while line = ed.get_text_line(row) pos = line.find(clip) if updn=='dn' else line.rfind(clip) if False:pass elif -1==pos and bgn_crt_fin!='crt': return app.msg_status(FIND_FAIL_FOR_STR.format(clip)) elif -1==pos:#and bgn_crt_fin=='crt' # Wrap! return self.find_cb_string(updn, bgn_crt_fin=apx.icase(updn=='dn', 'bgn', 'fin')) elif updn=='dn': ed.set_caret(pos+len(clip), row, pos, row) elif updn=='up': ed.set_caret(pos, row, pos+len(clip), row) return # 2) Find m-line pass; #LOG and log('') clpls = clip.split('\n') pass; #LOG and log('clpls={}',(clpls)) clip = repr(clip) if False:pass elif updn=='dn': found = False row = max(rPnt, rEnd if rEnd!=-1 else rPnt) if row+len(clpls) < ed.get_line_count(): txtls = [ed.get_text_line(r) for r in range(row, row+len(clpls))] pass; #LOG and log('txtls={}',(txtls)) while True: if self._find_cb_string_included_mlines(txtls, clpls): # Found! found = True break #while row = row+1 pass; #LOG and log('row={}',(row)) if row+len(clpls) >= ed.get_line_count(): pass; #LOG and log('nfnd12',) break #while txtls = txtls[1:]+[ed.get_text_line(row+len(clpls)-1)] pass; #LOG and log('txtls={}',(txtls)) #while if False:pass elif not found and bgn_crt_fin!='crt': return app.msg_status(FIND_FAIL_FOR_STR.format(clip)) elif not found:#and bgn_crt_fin=='crt' # Wrap! return self.find_cb_string(updn, bgn_crt_fin=apx.icase(updn=='dn', 'bgn', 'fin')) ed.set_caret(len(clpls[-1]), row+len(clpls)-1, len(txtls[0])-len(clpls[0]), row) elif updn=='up': found = False row = min(rPnt, rEnd if rEnd!=-1 else rPnt) if row-len(clpls)+1 >= 0: txtls = [ed.get_text_line(r) for r in range(row-len(clpls)+1, row+1)] pass; #LOG and log('txtls={}',(txtls)) while True: if self._find_cb_string_included_mlines(txtls, clpls): # Found! found = True break #while row = row-1 pass; #LOG and log('row={}',(row)) if row-len(clpls)+1 < 0: break #while txtls = [ed.get_text_line(row-len(clpls)+1)]+txtls[:-1] pass; #LOG and log('txtls={}',(txtls)) #while if False:pass elif not found and bgn_crt_fin!='crt': return app.msg_status(FIND_FAIL_FOR_STR.format(clip)) elif not found:#and bgn_crt_fin=='crt' # Wrap! return self.find_cb_string(updn, bgn_crt_fin=apx.icase(updn=='dn', 'bgn', 'fin')) ed.set_caret(len(clpls[-1]), row, len(txtls[0])-len(clpls[0]), row-len(clpls)+1)