def run(self, page): """Open page.""" try: import mdpopups import pymdownx has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3124) fmatter = mdpopups.format_frontmatter(frontmatter) if pymdownx.version_info[:3] >= (4, 3, 0) else '' except Exception: fmatter = '' has_phantom_support = False if not has_phantom_support: sublime.run_command('open_file', {"file": page}) else: text = sublime.load_resource(page.replace('${packages}', 'Packages')) view = self.window.new_file() view.set_name('QuickCal - Quick Start') view.settings().set('gutter', False) view.settings().set('word_wrap', False) if has_phantom_support: mdpopups.add_phantom( view, 'quickstart', sublime.Region(0), fmatter + text, sublime.LAYOUT_INLINE, css=CSS, wrapper_class="quick-cal", on_navigate=self.on_navigate ) else: view.run_command('insert', {"characters": text}) view.set_read_only(True) view.set_scratch(True)
def save_all_file(self): # window = sublime.active_window() # views = window.views() # for view in views: # if view.file_name(): # view.save sublime.run_command("save_all")
def select_configuration( window: sublime.Window, index: int) -> core.awaitable[Optional[Configuration]]: try: configs = all_configurations(window) except Exception as e: core.display(e) show_settings(window) done = core.main_loop.create_future() names = list(map(lambda x: x.name, configs)) + ["-" ] + ["Add configuration"] index = yield from core.sublime_show_quick_panel_async( window, names, index) if index < 0: return None if index >= len(configs): project = window.project_file_name() if project: sublime.run_command("new_window") window = sublime.active_window() window.open_file(project) else: window.run_command( 'edit_settings', {"base_file": "${packages}/sublime_db/debug.sublime-settings"}) return None return configs[index]
def make_views(self, files): count = len(files)+1 sublime.run_command("new_window") newwin = sublime.active_window() newwin.run_command( 'toggle_side_bar' ) newwin.run_command( 'toggle_menu' ) newwin.run_command( 'toggle_minimap' ) cols = [ i/100 for i in range(0 , 101, round(100/count)) ] colscount = len(cols)-1 cells = [ [indx, 0, indx+1, 1] for indx, cell in enumerate(cols) if indx < colscount ] #print( str(count) + " " + json.JSONEncoder().encode(files)+ " " + json.JSONEncoder().encode(cols) + " " + json.JSONEncoder().encode(cells)) newwin.set_layout( { "cols": cols, "rows": [0.0, 1.0], "cells": cells } ) view = newwin.new_file( ) view.settings().set( "l18ion_keysview", True ) newwin.set_view_index( view, 0, 0 ) for indx,c in enumerate(files): view = newwin.open_file( c ) newwin.set_view_index( view, indx+1, 0 ) self.make_view_content( newwin, files )
def rename_note(self, title): global db self.notes_dir = os.path.expanduser(root) self.file_path = self.window.active_view().file_name() filename = title.split("/") if len(filename) > 1: title = filename[len(filename)-1] directory = self.notes_dir + os.path.sep + filename[0] tag = filename[0] else: title = filename[0] directory = self.notes_dir tag = "" if not os.path.exists(directory): os.makedirs(directory) if any(title.endswith("." + ext) for ext in settings().get("note_file_extensions")): ext = "" else: ext = "." + settings().get("note_save_extension") new_file_path = os.path.join(directory, title + ext) # pardir = os.path.abspath(os.path.join(self.file_path, '..')) if not os.path.isfile(new_file_path): os.rename(self.file_path,new_file_path) self.window.run_command("close_file") sublime.run_command("notes_open", {"file_path": new_file_path}) # update color scheme db update_color(self.file_path, new_file_path) else: sublime.error_message("Note already exists!") self.window.show_input_panel("New Name:", "", self.rename_note, None, None)
def on_close(self, view): if view.name() == EDIT_ISSUE_VIEW_NAME: content_region = sublime.Region(0, view.size()) content_string = _multi_replace(view.substr(content_region), {"'": "'"}) content_dict = ast.literal_eval(content_string) arg_dict = { "iid": content_dict["iid"], "title": content_dict["title"], "desc": content_dict["description"], "state": content_dict["state"], "labels": _multi_replace(content_dict["labels"], { "'": "", '[': '', ']': '' }), #might need to do a little more work here "milestone": content_dict["milestone"] } if content_dict["assignee"] != "": arg_dict["assign_to"] = content_dict["assignee"] sublime.run_command("gli_edit_issue", arg_dict)
def openUrl(url): arduino_root = const.settings.get('arduino_root') arduino_root = getRealPath(arduino_root) reference_path = os.path.join(arduino_root, 'reference') reference_path = reference_path.replace(os.path.sep, '/') ref_file = 'file://%s/%s.html' % (reference_path, url) sublime.run_command('open_url', {'url': ref_file})
def cache(mode=["bin.cache"] + CACHE_NAMES): tools.LtxSettings().set("ltx_rebuild_cache", True) if "bin.cache" in mode: cache_bin() if "pkg.cache" in mode: cache_pkg() if "doc.cache" in mode: cache_doc() if "bibsonomy.cache" in mode: cache_bibsonomy() if "citeulike.cache" in mode: cache_citeulike() if "mendeley.cache" in mode: cache_mendeley() if "zotero.cache" in mode: cache_zotero() if "tex.cache" in mode: cache_tex() if "bib.cache" in mode: cache_bib() tools.LtxSettings().set("ltx_rebuild_cache", False) sublime.run_command("ltx_save_cache")
def run(self, cache=True, save=False, synchronise=False, fill_source=False): cache_timeout = self.settings["cache"]["bibsonomy"] if "bibsonomy" in self.settings["cache"] else 0 if cache_timeout and not save: cached_data = CACHE.get_cache_data("bibsonomy.cache") else: cached_data = {} if cached_data and not synchronise and not CACHE.is_cache_outdated("bibsonomy.cache", cache_timeout): self.data = cached_data else: if fill_source: if not cache_timeout: sublime.error_message("Bibsonomy.cache disabled! Please activate the cache to use this function.") elif not tools.LtxSettings().get("ltx_offline", False) and sublime.ok_cancel_dialog("Bibsonomy.cache outdated, would you like to synchronise the data now? The items are available for the next call!", "Synchronise"): sublime.run_command("ltx_sync_data", {"mode": "bibsonomy"}) else: self.data = cached_data else: c = bibsonomy.Bibsonomy() c.run() self.status = c.status if self.status in ["Error", "Waiting"]: return if self.status == "Ok": # Build cite keys for item in c.items: item["cite_key"] = self.build_cite_key(item) # Save items self.data["cites"] = c.items if cache and cache_timeout: CACHE.set_cache_data("bibsonomy.cache", self.data, True)
def check_python(self): """Python requirement Check if python 2 is installed """ self.version = None cmd = [self.SYMLINK, '--version'] out = run_command(cmd) if(out[0] == 0): self.version = sub(r'\D', '', out[1]) if(int(self.version[0]) is 3): self.check_sym_link() # show error and link to download if(out[0] > 0 or int(self.version[0]) is 3): from ..libraries.I18n import I18n _ = I18n().translate go_to = sublime.ok_cancel_dialog( _("deviot_need_python"), _("button_download_python")) if(go_to): sublime.run_command( 'open_url', {'url': 'https://www.python.org/downloads/'}) exit(0)
def test_error(self): # Run unittesting for an non existing package sublime.run_command("unit_testing", {"package": "_Error"}) with open(os.path.join(outputdir, "_Error"), 'r') as f: txt = f.read() m = re.search('^ERROR', txt, re.MULTILINE) self.assertEqual(hasattr(m, "group"), True)
def open_workspace_window3(abs_path, cb): def finish(w): w.set_project_data({'folders': [{'path': abs_path}]}) cb(w) def get_empty_window(): for w in sublime.windows(): project_data = w.project_data() try: folders = project_data.get('folders', []) if len(folders) == 0 or not folders[0].get('path'): # no project data. co-opt this window return w except Exception as e: print(str_e(e)) def wait_empty_window(i): if i > 10: print('Too many failures trying to find an empty window. Using active window.') return finish(sublime.active_window()) w = get_empty_window() if w: return finish(w) return utils.set_timeout(wait_empty_window, 50, i + 1) w = get_workspace_window(abs_path) or get_empty_window() if w: return finish(w) sublime.run_command('new_window') wait_empty_window(0)
def run(self): if self.syntax_test: sublime.run_command("unit_testing_syntax", { "package": self.package, "output": self.output }) elif self.syntax_compatibility: sublime.run_command("unit_testing_syntax_compatibility", { "package": self.package, "output": self.output }) elif self.color_scheme_test: sublime.run_command("unit_testing_color_scheme", { "package": self.package, "output": self.output }) elif self.coverage: sublime.run_command("unit_testing_coverage", { "package": self.package, "output": self.output }) else: sublime.run_command("unit_testing", { "package": self.package, "output": self.output })
def load_branch(self, branch, root): print("running def load_branch(self, " + str(branch) + ", " + str(root) + "):") if not root: print("load: off of git") else: print("load branch: " + branch) path = root + "/.git/BranchedProjects.sublime" obj = defaultdict(lambda: defaultdict(list)) if os.path.isfile(path): with open(path, "rb") as f: tmp = pickle.load(f) for o in tmp: obj[o] = tmp[o] f.close() for win in obj[branch]: sublime.run_command("new_window") new_win = sublime.active_window() new_win.set_project_data({"folders": [{"path": root, "follow_symlinks": True}]}) for doc in obj[branch][win]: if os.path.isfile(doc): print("loading file " + doc) new_win.open_file(doc) no_win = True for win in sublime.windows(): win_root = win.folders() win_root = win_root[0] if win_root != [] else None if win_root == root: no_win = False break if no_win: sublime.run_command("new_window") new_win = sublime.active_window() new_win.set_project_data({"folders": [{"path": root, "follow_symlinks": True}]})
def run(self, edit, event): base_path, input_path = self.get_path(event) abspath = computer_friendly(os.path.join(base_path, input_path)) sublime.run_command("fm_creater", { "abspath": abspath, "input_path": input_path })
def run(self): sublime.run_command('sublimeserver_stop') sublime.set_timeout(lambda: sublime.run_command('sublimeserver_reload'), 0) sublime.set_timeout(lambda: sublime.run_command('sublimeserver_start'), settings.get('interval') )
def run(self): response = gemsRequest('student_gets_report', {}) if response != None: json_obj = json.loads(response) report = {} total_points = 0 for i in json_obj: Date, Points, Filename = i['Date'], i['Points'], i['Filename'] if Date not in report: report[Date] = [] if '.' in Filename: prefix, ext = Filename.rsplit('.', 1) else: prefix = Filename report[Date].append((Points, prefix)) total_points += Points with open(gemsFILE, 'r') as f: info = json.loads(f.read()) report_file = os.path.join(info['Folder'], 'Points.txt') with open(report_file, 'w', encoding='utf-8') as f: f.write('Total points: {}\n'.format(total_points)) for d, v in reversed(sorted(report.items())): date = datetime.datetime.fromtimestamp(d).strftime( '%Y-%m-%d') for entry in v: f.write('{}\t{}\t{}\n'.format(date, entry[0], entry[1])) sublime.run_command('new_window') sublime.active_window().open_file(report_file)
def handle_flagged_output(self, output): split = output.split(self.stdout_flag) action = split[1] arg = split[2].rstrip() if action in ['open_file', 'open_startup']: if not os.path.isfile(arg): if action == 'open_file': return if action == 'open_startup': open(arg, 'a').close() if len(sublime.windows()) is 0: sublime.run_command('new_window') window = sublime.active_window() window.open_file(arg) elif action == 'open_dir': if sublime.platform() == 'osx': subprocess.Popen(['open', arg]) elif sublime.platform() == 'linux': subprocess.Popen(['xdg-open', arg]) elif sublime.platform() == 'windows': os.startfile(arg)
def run(self, edit): global preview_view, PREVIEW_VIEWS """ Description: If the file is saved exists on disk, we close it, - and reopen it in a new window. Otherwise, we copy the content, - erase it all (to close the file without a dialog) - and re-insert it into a new view into a new window """ original_view = self.view original_window_id = original_view.window().id() file_name = original_view.file_name() syntax_file = original_view.settings().get("syntax") if file_name: original_view.close() else: # the file isn't saved, we need to restore the content manually total_region = sublime.Region(0, original_view.size()) content = original_view.substr(total_region) original_view.erase(edit, total_region) original_view.close() # FIXME: save the document to a temporary file, so that if we crash, # - the user doesn't lose what he wrote sublime.run_command("new_window") preview_window = sublime.active_window() preview_window.run_command( "set_layout", { "cols": [0.0, 0.5, 1.0], "rows": [0.0, 1.0], "cells": [[0, 0, 1, 1], [1, 0, 2, 1]], }, ) preview_window.focus_group(1) preview_view = mdpopups.new_html_sheet(window=preview_window, name="Preview", contents="") preview_window.focus_group(0) if file_name: markdown_view = preview_window.open_file(file_name) else: markdown_view = preview_window.new_file() markdown_view.run_command("mdlp_insert", { "point": 0, "content": content }) markdown_view.set_scratch(True) markdown_view.set_syntax_file(syntax_file) markdown_view.settings().set( MD_VIEW_INFO, { "original_window_id": original_window_id, }, ) PREVIEW_VIEWS[markdown_view.id()] = preview_view.id()
def run(self): global settings sublime.run_command('sublimeserver_stop') sublime.set_timeout( lambda: sublime.run_command('sublimeserver_reload'), 0) sublime.set_timeout(lambda: sublime.run_command('sublimeserver_start'), settings.get('interval'))
def plugin_loaded(): global SUB_NOTIFY_READY # Create icon folder for systems that need a icon from path graphics = join(sublime.packages_path(), "SubNotify", "graphics") # Setup Notify notify.setup_notifications( "Sublime Text", join(graphics, "SublimeBubble.png"), join(graphics, "SublimeBubble.ico"), ( get_settings().get( "terminal_notifier_path", "/Library/Ruby/Gems/2.0.0/gems/terminal-notifier-1.5.1/bin/terminal-notifier" ), "com.sublimetext.3" ) ) # Try to enable notification systems enable_notifications() # Annouce that subnotify is ready SUB_NOTIFY_READY = True sublime.run_command("sub_notify_is_ready") if get_settings().get("debug", False): sublime.set_timeout(lambda: sublime.run_command("sub_notify_test"), 3000)
def open_folder(self): # taken from # https://github.com/rosshemsley/iOpener/blob/a35117a201290b63b53ba6372dbf8bbfc68f28b9/i_opener.py#L203-L205 sublime.run_command("new_window") project_data = dict( folders=[dict(follow_symlinks=True, path=self.suggested_git_root)]) sublime.active_window().set_project_data(project_data)
def create_unfocused_color_scheme(): sublime_settings = sublime.load_settings("Preferences.sublime-settings") original_scheme = sublime_settings.get("color_scheme") active_view = sublime.active_window().active_view() # Get active scheme. current_scheme = active_view.settings().get("color_scheme") # Method to restore the current color scheme. def restore_original_scheme(): sublime_settings.set("color_scheme", original_scheme) # Tweak current scheme with ThemeTweaker. sublime_settings.set("color_scheme", current_scheme) new_scheme = get_unfocused_scheme_path(active_view) tweaker_settings = sublime_settings.get("unfocused_pane_tweaker") if tweaker_settings is None: tweaker_settings = "brightness(0.97);saturation(0.85);" sublime.run_command("theme_tweaker_custom", {"filters": tweaker_settings}) try: # Copy the tweaked scheme to its final destination. if not os.path.exists(os.path.normpath(os.path.dirname(new_scheme))): os.makedirs(os.path.dirname(os.path.normpath(new_scheme))) copyfile(os.path.normpath(os.path.join(sublime.packages_path(), "User/ThemeTweaker/tweak-" + os.path.basename(current_scheme))), new_scheme) sublime.set_timeout_async(restore_original_scheme, 1000) # Return unfocused scheme path. return new_scheme except Exception as e: restore_original_scheme() print(e) return
def on_navigate(self, href): """Handle links.""" if href.startswith('sub://Packages'): sublime.run_command('open_file', {"file": self.re_pkgs.sub('${packages}', href[6:])}) else: webbrowser.open_new_tab(href)
def run(self, edit): try: page = self.view.substr(sublime.Region(0, self.view.size())) encoded = {'sass': page} send = urllib.urlencode(encoded) url = 'http://178.62.31.223/s/jakebown/sassy/?' #url += send print(url) response = urllib2.urlopen(url, send) page = response.read() length = self.view.size() reg = sublime.Region(0, length) sublime.run_command("new_window") sublime.active_window().run_command("insert_snippet", {"contents": page}) #sublime.active_window().open_file(page) #sublime.view.replace(0, 1, page) #self.view.replace(edit, reg, page) except Exception as (e): response = e; print("********* Sassy Error *********") print(response) print("********* Sassy Exit *********")
def notify(msg): """Notify with SubNotify if possible and enabled.""" if load_settings().get("use_sub_notify", False) and Notify.is_ready(): sublime.run_command("sub_notify", {"title": "EasyDiff", "msg": msg}) else: sublime.status_message(msg)
def run(self): if not sublime.active_window(): sublime.run_command("new_window") self.use_active_window = True else: self.use_active_window = False if not self.cache or not self.folder_list: settings = sublime.load_settings('GotoFolder.sublime-settings') self.cache = settings.get("cache", False); root_folders = settings.get("root_folders", [{'folder': sublime.packages_path(), 'alias': 'Plugin'}]) self.folder_list = []; self.folder_info = []; folder_count = 0; for root in root_folders: if 'alias' not in root: root['alias'] = "" else: root['alias'] += ":" try: for f in os.listdir(root['folder']): if f.startswith(".") or (os.path.isfile(root['folder']+"/"+f) and not f.endswith(".sublime-project")): continue self.folder_list.append([root['alias']+f]) a = [root['folder']+"/"+f] if 'extra' in root: a += root['extra'] self.folder_info.append(a) folder_count+=1 except Exception as e: print(e, ". Check GotoFolder.sublime-settings file") #print "GotoFolder Plugin:", folder_count, "folders added to the list" sublime.active_window().show_quick_panel(self.folder_list, self.on_select)
def run(self, edit): sublime.run_command('refresh_folder_list') current_folder = sublime.active_window().folders()[0] git_path = self.which('git') if not git_path: self.print_with_error("git not found in PATH") return pr = subprocess.Popen( git_path + " diff --name-only $(git symbolic-ref HEAD 2>/dev/null)" , cwd = current_folder, shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE ) (filenames, error) = pr.communicate() if error: self.print_with_error(error) return else: filenames_split = bytes.decode(filenames).splitlines() filename_pattern = re.compile("([^" + self.system_folder_seperator() + "]+$)") sorted_filenames = sorted(filenames_split, key=lambda fn: filename_pattern.findall(fn)) for file_modified in sorted_filenames: filename = current_folder + self.system_folder_seperator() + file_modified if os.path.isfile(filename): sublime.active_window().open_file(filename) self.print_with_status("Git: Opened files modified in branch")
def create_snippet(snippet, labels, library_guid): url = "{0}/sublime/snippets".format(util.settings().get("apiHost")) data = { "snippet": snippet, "labels": labels, "libraryGuid": library_guid } try: req = urllib.request.Request(url, headers=util.request_headers(), method="POST") json_data = json.dumps(data) json_data_bytes = json_data.encode("utf-8") req.add_header("Content-Type", "application/json; charset=utf-8") req.add_header("Content-Length", len(json_data_bytes)) urllib.request.urlopen(req, json_data_bytes) sublime.status_message("Cacher: Saved \"{0}\"".format( snippet["title"])) sublime.run_command("cacher_refresh") except urllib.error.HTTPError as e: sublime.error_message( "There was an error creating your snippet. Please try again.") print(e) except IOError: util.prompt_user_setup() except ValueError: util.show_credentials_parse_error()
def run(self, edit): original_view = self.view syntax_file = original_view.settings().get("syntax") total_region = sublime.Region(0, original_view.size()) content = original_view.substr(total_region) sublime.run_command("new_window") preview_window = sublime.active_window() preview_window.run_command( "set_layout", { "cols": [0.0, 0.5, 1.0], "rows": [0.0, 1.0], "cells": [[0, 0, 1, 1], [1, 0, 2, 1]], }, ) preview_window.focus_group(1) preview_view = preview_window.new_file() preview_view.set_scratch(True) preview_view.set_name("Preview") preview_view.sel().clear() preview_window.focus_group(0) jq_view = preview_window.new_file() jq_view.run_command("jq_insert_pretty_json", {"string": content}) jq_view.set_read_only(True) jq_view.set_scratch(True) jq_view.sel().clear() jq_view.set_syntax_file(syntax_file) preview_view.set_syntax_file(json_syntax)
def run(self, edit): """Show Sketch Folder.""" file_path = self.view.file_name() if file_path: dir_path = os.path.dirname(file_path) url = 'file://' + dir_path sublime.run_command('open_url', {'url': url})
def open_directory(self, directory): if self.window.project_data(): sublime.run_command('new_window') sublime.active_window().set_project_data( {'folders': [{ 'path': directory }]})
def rename_note(self, title): global db self.notes_dir = os.path.expanduser(root) self.file_path = self.window.active_view().file_name() filename = title.split("/") if len(filename) > 1: title = filename[len(filename) - 1] directory = self.notes_dir + os.path.sep + filename[0] tag = filename[0] else: title = filename[0] directory = self.notes_dir tag = "" if not os.path.exists(directory): os.makedirs(directory) if any(title.endswith("." + ext) for ext in settings().get("note_file_extensions")): ext = "" else: ext = "." + settings().get("note_save_extension") new_file_path = os.path.join(directory, title + ext) # pardir = os.path.abspath(os.path.join(self.file_path, '..')) if not os.path.isfile(new_file_path): os.rename(self.file_path, new_file_path) self.window.run_command("close_file") sublime.run_command("notes_open", {"file_path": new_file_path}) # update color scheme db update_color(self.file_path, new_file_path) else: sublime.error_message("Note already exists!") self.window.show_input_panel("New Name:", "", self.rename_note, None, None)
def open_workspace_window3(cb): def finish(w): G.WORKSPACE_WINDOW = w msg.debug('Setting project data. Path: %s' % G.PROJECT_PATH) G.WORKSPACE_WINDOW.set_project_data({'folders': [{'path': G.PROJECT_PATH}]}) cb() def get_empty_window(): for w in sublime.windows(): project_data = w.project_data() try: folders = project_data.get('folders', []) if len(folders) == 0 or not folders[0].get('path'): # no project data. co-opt this window return w except Exception as e: print(e) def wait_empty_window(i): if i > 10: print('Too many failures trying to find an empty window. Using active window.') return finish(sublime.active_window()) w = get_empty_window() if w: return finish(w) return utils.set_timeout(wait_empty_window, 50, i + 1) w = get_workspace_window() or get_empty_window() if w: return finish(w) sublime.run_command('new_window') wait_empty_window(0)
def run(self): sublime.run_command('new_window') new_window = sublime.active_window() new_window.run_command('set_layout', { 'cols': [0.0, 0.5, 1.0], 'rows': [0.0, 1.0], 'cells': [[0, 0, 1, 1], [1, 0, 2, 1]] }) new_window.focus_group(0) edit_view = new_window.new_file() edit_view_settings = edit_view.settings() edit_view_settings.set('minihtml_preview_edit_view', True) edit_view.set_scratch(True) edit_view.set_syntax_file('Packages/HTML/HTML.sublime-syntax') # Unfortunately Sublime indents on 'insert' edit_view.settings().set('auto_indent', False) edit_view.run_command('insert', {'characters': template}) edit_view.settings().set('auto_indent', True) new_window.focus_group(1) output_view = new_window.new_file() output_view.set_scratch(True) edit_view_settings.set('minihtml_preview_output_view_id', output_view.id()) new_window.focus_group(0)
def rename_file(self, title): global db filename = title.split("/") if len(filename) > 1: title = filename[len(filename)-1] directory = self.notes_dir +"/"+ filename[0] tag = filename[0] else: title = filename[0] directory = self.notes_dir tag = "" if not os.path.exists(directory): os.makedirs(directory) ext = "." + settings().get("note_save_extension") fname = os.path.join(directory, title + ext) os.path.isfile(fname) pardir = os.path.abspath(os.path.join(self.file_path, '..')) if not os.path.isfile(fname): os.rename(self.file_path,fname) sublime.run_command("notes_open", {"file_path": fname}) # update color scheme db f_id = file_id(fname) # print(f_id) if not db.get(f_id): db[f_id] = {} db[f_id]["color_scheme"] = db[file_id(self.file_path)]["color_scheme"] save_to_brain() else: sublime.error_message("Note already exists!") self.window.show_input_panel("New Name:", "", self.rename_file, None, None)
def check_python(self): """Python requirement Check if python 2 is installed """ self.version = None cmd = [self.SYMLINK, '--version'] out = run_command(cmd) if (out[0] == 0): self.version = sub(r'\D', '', out[1]) if (self.version and int(self.version[0]) is 3): self.check_sym_link() # show error and link to download if (out[0] > 0 or int(self.version[0]) is 3): from ..libraries.I18n import I18n _ = I18n().translate go_to = sublime.ok_cancel_dialog(_("deviot_need_python"), _("button_download_python")) if (go_to): sublime.run_command( 'open_url', {'url': 'https://www.python.org/downloads/'}) exit(0)
def update_remote_bibliography(self): settings = tools.load_settings("LaTeXing", bibname="Remote.bib", update_remote_bibliography=True) # Fetch all available remote citations remote_cites = {item.key: item for file_path, item in cite.find_remote_cites()} if settings["update_remote_bibliography"] and remote_cites: # Just search through the remote bib file, defined in the settings bib_path = os.path.join(os.path.dirname(self.tex_file.root_file_path()), settings["bibname"]) bib_file = cache.BibFile(bib_path) bib_file.run() cites = [] for key in bib_file.cite_keys(): if key in remote_cites and remote_cites[key].string(plain=True) != bib_file.cite_source(key): cites += [remote_cites[key]] log.debug(key) log.debug(bib_file.cite_source(key)) log.debug(remote_cites[key].string(plain=True)) # save cites in bib file and update cache if cites and sublime.ok_cancel_dialog("%d Citation(s) in %s have been updated in your remote bibliography, update the item(s) prior the typeset?" % (len(cites), bib_file.file_name), "Update"): bib_file.update_cites(cites) bib_file.save() sublime.run_command("ltx_save_cache", {"mode": ["bib.cache"]})
def open_file(self, path): """ Open the given path. Can be a directory OR a file. """ path = expanduser(path) # Ignore empty paths. if not path: sublime.status_message("Warning: Ignoring empty path.") return self.add_to_history(path) directory = "" filename = "" # If the user enters a path without a filename. if path[-1] == sep: directory = path else: directory, filename = split(path) # Path doesn't exist, ask the user if they want to create it. if not isdir(directory): create = sublime.ok_cancel_dialog( "The path you entered does not exist, create it?", "Yes") if not create: return else: try: makedirs(directory) except OSError as e: sublime.error_message( "Failed to create path with error: " + str(e)) return if isdir(path): if is_sublime_text_2(): # Project folders can not be added using the ST2 API. sublime.status_message( "Warning: Opening folders requires ST v3.") elif OPEN_FOLDERS_IN_NEW_WINDOW: sublime.run_command("new_window") project_data = dict( folders=[dict(follow_symlinks=True, path=path)]) sublime.active_window().set_project_data(project_data) else: project_data = sublime.active_window().project_data() or {} project_folders = project_data.get('folders') or [] folder = dict(path=path, follow_symlinks=True, folder_exclude_patterns=['.*']) if all(folder['path'] != path for folder in project_folders): project_data['folders'].append(folder) sublime.active_window().set_project_data(project_data) else: # If file doesn't exist, add a message in the status bar. if not isfile(path): sublime.status_message("Created new buffer '" + filename + "'") sublime.active_window().open_file(path) iOpenerCommand.input_panel = None
def launch_stata(): stata_fn = settings.get("stata_path") if not check_correct_executable(stata_fn): print('Stata path not found in settings') sublime.run_command('stata_update_executable_path') return # stata_fn = settings.get("stata_path") # if not check_correct_executable(stata_fn): # sublime.error_message("Cannot run Stata; the path does not exist: {}".format(stata_fn)) try: win32api.WinExec(stata_fn, win32con.SW_SHOWMINNOACTIVE) sublime.stata = win32com.client.Dispatch("stata.StataOLEApp") except: sublime.run_command('stata_register_automation') sublime.error_message("StataEditor: Stata Automation type library appears to be unregistered, see http://www.stata.com/automation/#install") # Stata takes a while to start and will silently discard commands sent until it finishes starting # Workaround: call a trivial command and see if it was executed (-local- in this case) seed = int(random.random()*1e6) # Any number for i in range(50): sublime.stata.DoCommand('local {} ok'.format(seed)) sublime.stata.DoCommand('macro list') rc = sublime.stata.MacroValue('_{}'.format(seed)) if rc=='ok': sublime.stata.DoCommand('local {}'.format(seed)) # Empty it sublime.stata.DoCommand('cap cls') print("Stata process started (waited {}ms)".format((1+i)/10)) sublime.status_message("Stata opened!") break else: time.sleep(0.1) else: raise IOError('Stata process did not start before timeout')
def plugin_loaded(): """Setup plugin.""" global SUB_NOTIFY_READY # Create icon folder for systems that need a icon from path png_path, ico_path = get_icon_files() # Setup Notify notify.setup_notifications("Sublime Text", png_path, ico_path, (get_settings( ).get( "terminal_notifier_path", "/Library/Ruby/Gems/2.0.0/gems/terminal-notifier-1.5.1/bin/terminal-notifier" ), "com.sublimetext.3")) # Try to enable notification systems enable_notifications() # Annouce that subnotify is ready SUB_NOTIFY_READY = True sublime.run_command("sub_notify_is_ready") if get_settings().get("debug", False): sublime.set_timeout(lambda: sublime.run_command("sub_notify_test"), 3000)
def test_stoplackd(self): # set up self.view.run_command("blackd_start") self.assertTrue( sublack.check_blackd_on_http(self.port), "ensure blackd is running for the test", ) # already running, normal way sublime.run_command("blackd_stop") self.assertRaises( requests.ConnectionError, lambda: requests.post( "http://localhost:" + self.port, "server should be down" ), ) self.assertEqual( self.view.get_status(sublack.STATUS_KEY), sublack.BLACKD_STOPPED, "should tell it stops", ) # already stopped sublime.run_command("blackd_stop") self.assertEqual( self.view.get_status(sublack.STATUS_KEY), sublack.BLACKD_STOP_FAILED, "status tell stop failed", )
def run(self, edit): v = self.view for sel in v.sel(): file_index = v.rowcol(sel.a)[0] files = v.settings().get('notes_buffer_files') file_path = files[file_index][1] sublime.run_command("notes_open", {"file_path": file_path})
def run(self, page): """Open page.""" try: import mdpopups has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3118) except Exception: has_phantom_support = False if not has_phantom_support: sublime.run_command('open_file', {"file": page}) else: text = sublime.load_resource(page.replace('${packages}', 'Packages')) view = self.window.new_file() view.set_name('ExportHtml - Quick Start') view.settings().set('gutter', False) view.settings().set('word_wrap', False) if has_phantom_support: mdpopups.add_phantom( view, 'quickstart', sublime.Region(0), text, sublime.LAYOUT_INLINE, css=CSS, wrapper_class="export-html", on_navigate=self.on_navigate ) else: view.run_command('insert', {"characters": text}) view.set_read_only(True) view.set_scratch(True)
def run(self, edit): point = self.view.sel()[0] cur_line_region = self.view.full_line(point) old_line = self.view.substr(cur_line_region) task_content = old_line.lstrip() indent = '' for c in old_line: if not c in [' ', '\t']: break indent += c new_line = indent if task_content[0] == '!': new_line += task_content[1:] elif task_content[0] in ['+', '.'] and task_content[1] == '!': new_line += task_content[0] + task_content[2:] elif task_content[0] in ['+', '.'] and task_content[1] == '-': new_line += task_content[0] + '!' + task_content[1:] else: new_line += '!' + task_content self.view.replace(edit, cur_line_region, new_line) sublime.status_message("Emergency Task: %s" % task_content) sublime.run_command( 'sub_notify', { 'title': 'ToDone Emergency Task:', 'msg': old_line.lstrip(), 'sound': False })
def load(self, session): with open(session) as sess_file: data = json.load(sess_file) groups = data['groups'] layout = data['layout'] window = self.window open_files = [view.file_name() for view in window.views() if view.file_name()] # if the current window has open files, load the session in a new one if open_files: sublime.run_command('new_window') window = sublime.active_window() window.set_layout(layout) for group, files in groups.items(): window.focus_group(int(group)) for file in files: # if the string starts with buffer, it's an inline buffer and not a filename if file.startswith('buffer:'): window.new_file().run_command('insert', {'characters': file[7:]}) else: window.open_file(file) for view in window.views(): view.set_status('ss', path.basename(session))
def run(self): """Inspired by the edit_settings command""" current_view = sublime.active_window().active_view() file_name = current_view.file_name() if get_settings().get('keep_open_when_opening_preview') is False: current_view.close() if file_name is None: return sublime.error_message('MarkdownLivePreview: Not supporting ' 'unsaved file for now') sublime.run_command('new_window') self.window = sublime.active_window() self.window.settings().set(PREVIEW_WINDOW, True) self.window.run_command( 'set_layout', { 'cols': [0.0, 0.5, 1.0], 'rows': [0.0, 1.0], 'cells': [[0, 0, 1, 1], [1, 0, 2, 1]] }) self.window.focus_group(1) preview = create_preview(self.window, current_view) self.window.focus_group(0) md_view = self.window.open_file(file_name) mdsettings = md_view.settings() mdsettings.set(PREVIEW_ENABLED, True) mdsettings.set(PREVIEW_ID, preview.id())
def gema_gets(self, index, priority): global gemaStudentSubmissions response = gemaRequest('teacher_gets', { 'index': index, 'priority': priority }) if response is not None: sub = json.loads(response) if sub['Content'] != '': filename = sub['Filename'] sid = str(sub['Sid']) dir = os.path.join(gemaFOLDER, sid) if not os.path.exists(dir): os.mkdir(dir) local_file = os.path.join(dir, filename) with open(local_file, 'w', encoding='utf-8') as fp: fp.write(sub['Content']) gemaStudentSubmissions[sid] = sub['Content'] if sublime.active_window().id() == 0: sublime.run_command('new_window') sublime.active_window().open_file(local_file) if sub['Priority'] == 2: sublime.message_dialog('This student asked for help.') elif priority == 0: sublime.message_dialog('There are no submissions.') elif priority > 0: sublime.message_dialog( 'There are no submissions with priority {}.'.format(priority)) elif index >= 0: sublime.message_dialog( 'There are no submission with index {}.'.format(index))
def run(self, page): """Open page.""" try: import mdpopups has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3118) except Exception: has_phantom_support = False if not has_phantom_support: sublime.run_command('open_file', {"file": page}) else: text = sublime.load_resource(page.replace('${packages}', 'Packages')) view = self.window.new_file() view.set_name('BracketHighlighter - Quick Start') view.settings().set('gutter', False) view.settings().set('word_wrap', False) if has_phantom_support: mdpopups.add_phantom( view, 'quickstart', sublime.Region(0), text, sublime.LAYOUT_INLINE, css=CSS, wrapper_class="bracket-highlighter", on_navigate=self.on_navigate ) else: view.run_command('insert', {"characters": text}) view.set_read_only(True) view.set_scratch(True)
def run(self, edit): pkg_name = self.pkg_for_file() # For unknown files, open the default topic for a default package. # # TODO: Should be user configurable? if pkg_name is None: return sublime.run_command("hyperhelp_topic", {"package": "SublimeAPI"}) # Get the help index for the type of file currently focused. pkg_info = help_index_list().get(pkg_name) # Get an initial topic; the selected text or the word under the cursor. extract = self.view.sel()[0] if extract.empty(): topic = _word_under_cursor(self.view) else: topic = self.view.substr(extract) # If the initial topic exists and is unique, open it directly. if topic and lookup_help_topic(pkg_info, topic): return sublime.run_command("hyperhelp_topic", { "package": pkg_info.package, "topic": topic }) # Open the root of the help package if the topic is empty, or open the # index popup if it has some text. In the latter case, also use it as # the default filter so the user can self disambiguate. sublime.run_command("hyperhelp_index" if topic else "hyperhelp_topic", {"package": pkg_info.package}) if topic: self.view.window().run_command("insert", {"characters": topic})
def color_picker_available(): """Check if color picker is available.""" s = sublime.load_settings('color_helper_share.sublime-settings') s.set('color_pick_return', None) sublime.run_command('color_pick_api_is_available', {'settings': 'color_helper_share.sublime-settings'}) return s.get('color_pick_return', None)
def on_done(path): if not os.path.isdir(path): os.makedirs(path) if os.path.isdir(path): if os.listdir(path): if sublime.ok_cancel_dialog("The selected folder is not empty, would you like to continue and override your local settings?", "Continue"): override = True else: self.window.show_input_panel("Sync Folder", path, on_done, None, None) return else: override = False # Adjust settings s.set("sync", True) s.set("sync_folder", path) # Reset last-run file file_path = os.path.join(sublime.packages_path(), "User", "Package Control.last-run") if os.path.isfile(file_path): os.remove(file_path) # Reset last-run file file_path = os.path.join(sublime.packages_path(), "User", "Package Syncing.last-run") if os.path.isfile(file_path): os.remove(file_path) sublime.save_settings("Package Syncing.sublime-settings") sublime.status_message("sync_folder successfully set to \"%s\"" % path) # sublime.run_command("pkg_sync", {"mode": ["pull", "push"], "override": override}) else: sublime.error_message("Invalid Path %s" % path)
def run(self, edit): sublime.run_command('refresh_folder_list') current_folder = sublime.active_window().folders()[0] if sublime.platform() == "windows": git_name = 'git.exe' else: git_name = 'git' git_path = self.which(git_name) if not git_path: self.print_with_error("git not found in PATH") return compare_branch_to = settings.get('compare_branch_to', 'origin/master') pr = subprocess.Popen("git diff --name-only origin/master" , cwd = current_folder, shell = True, stdout = subprocess.PIPE, stderr = subprocess.PIPE ) (filenames, error) = pr.communicate() if error: self.print_with_error('Could not run git command. Ensure you have git properly installed: ' + str(error)) return else: filenames_split = bytes.decode(filenames).splitlines() filename_pattern = re.compile("([^" + self.system_folder_seperator() + "]+$)") sorted_filenames = sorted(filenames_split, key=lambda fn: filename_pattern.findall(fn)) for file_modified in sorted_filenames: filename = current_folder + self.system_folder_seperator() + file_modified if os.path.isfile(filename): sublime.active_window().open_file(filename) self.print_with_status("Git: Opened files modified in branch")