def run(self): global ON ON = not ON if ON: run_Jshint(self.window) else: sublime.active_window().run_command("hide_panel", {"panel": "show_results", "toggle": False})
def get_default(self, name, default, force=False): # Temporary name fix for when we're given a setting name with the prefix # In the future, this test will be gone and no setting will have # the 'lldb.' prefix if not name.startswith(self.__prefix): # Final code should be: name = self.__prefix + name else: debug(debugAny, 'Setting name has lldb prefix: %s' % name) import traceback traceback.print_stack() if not force and name in self.__values: return self.__values[name] setting = default if sublime.active_window() and sublime.active_window().active_view(): setting = sublime.active_window().active_view().settings().get(name, default) if setting is default: setting = self.__settings.get(name, default) # Cache the setting value and setup a listener self.__values[name] = setting if name not in self.__settings_keys: self.__settings_keys.append(name) listener = self.create_listener(name) self.__settings.add_on_change(name, listener.on_change) debug(debugSettings, 'setting %s: %s' % (name, repr(setting))) return setting
def run(self): sublime.active_window().run_command( 'open_dir', { 'dir': self.backups_path() } )
def find_declaration(data): data = data['Data'] fname = data['File'] row = data['Line'] + 1 col = data['Column'] + 1 encoded = "{0}:{1}:{2}".format(fname, row, col) sublime.active_window().open_file(encoded, sublime.ENCODED_POSITION)
def handler(self, name, data): if name == 'create_user': del data['name'] try: floorc = BASE_FLOORC + '\n'.join(['%s %s' % (k, v) for k, v in data.items()]) + '\n' with open(G.FLOORC_PATH, 'wb') as floorc_fd: floorc_fd.write(floorc.encode('utf-8')) utils.reload_settings() if False in [bool(x) for x in (G.USERNAME, G.API_KEY, G.SECRET)]: sublime.message_dialog('Something went wrong. You will need to sign up for an account to use Floobits.') api.send_error({'message': 'No username or secret'}) else: p = os.path.join(G.BASE_DIR, 'welcome.md') with open(p, 'wb') as fd: text = welcome_text % (G.USERNAME, self.host) fd.write(text.encode('utf-8')) d = utils.get_persistent_data() d['auto_generated_account'] = True utils.update_persistent_data(d) G.AUTO_GENERATED_ACCOUNT = True sublime.active_window().open_file(p) except Exception as e: msg.error(e) try: d = utils.get_persistent_data() d['disable_account_creation'] = True utils.update_persistent_data(d) finally: self.stop()
def file_preview(self, path, line): GtagsNavigation().lock() if path is not None: logger.info("preview file: %s:%s", line, path) position = '%s:%d:0' % (os.path.normpath(path), int(line)) sublime.active_window().open_file(position, sublime.ENCODED_POSITION | sublime.TRANSIENT) GtagsNavigation().unlock()
def run(self): sublime.active_window().run_command( 'open_dir', { 'dir': self.templates_path_string() } )
def run(self, edit): print("SELF.VIEW IS: " + str(self.view)) print("SELF.VIEW.WINDOW().VIEWS() IS: " + str(self.view.window().views())) print("SUBLIME.WINDOWS() IS: " + str(sublime.windows())) print("SUBLIME.ACTIVE_WINDOW().VIEWS() IS: " + str(sublime.active_window().views())) print("SUBLIME.ACTIVE_WINDOW().ACTIVE_VIEW() IS: " + str(sublime.active_window().active_view())) self.view.sel().clear()
def run(self, edit, event): if self.symbol_details: view_path = self.symbol_details[0] focus_region = self.symbol_details[1] # collapse the region to a single point, the region start focus_region = sublime.Region(focus_region.begin(), focus_region.begin()) # get the view with this path view = sublime.active_window().find_open_file(view_path) if view: self.showSymbol(view, focus_region) else: # weird issue, but unless we open the file with 'ENCODED_POSITION' it won't scroll afterwards # https://github.com/SublimeTextIssues/Core/issues/538 view = sublime.active_window().open_file("%s:%d:%d" % (view_path, 1, 0), sublime.ENCODED_POSITION) def viewLoadedTimeout(): # we can run methods only on loaded views if not view.is_loading(): self.showSymbol(view, focus_region) else: sublime.set_timeout(viewLoadedTimeout, 100) # open is asynchronous, wait for a bit and then try to focus sublime.set_timeout(viewLoadedTimeout, 100)
def _fn(*args, **kwargs): try: return fn(*args, **kwargs) except MissingCredentialsException: sublime.error_message("Gist: GitHub username or password isn't provided in Gist.sublime-settings file") user_settings_path = os.path.join(sublime.packages_path(), 'User', 'Gist.sublime-settings') if not os.path.exists(user_settings_path): default_settings_path = os.path.join(sublime.packages_path(), 'Gist', 'Gist.sublime-settings') shutil.copy(default_settings_path, user_settings_path) sublime.active_window().open_file(user_settings_path) except subprocess.CalledProcessError as err: sublime.error_message("Gist: Error while contacting GitHub: cURL returned %d" % err.returncode) except EnvironmentError as err: traceback.print_exc() if type(err) == OSError and err.errno == 2 and api_request == api_request_curl: sublime.error_message("Gist: Unable to find Python SSL module or cURL") else: msg = "Gist: Error while contacting GitHub" if err.strerror: msg += err.strerror sublime.error_message(msg) except SimpleHTTPError as err: msg = "Gist: GitHub returned error %d" % err.code try: response_json = json.loads(err.response) response_msg = response_json.get('message') if response_msg: msg += ": " + response_msg except ValueError: pass sublime.error_message(msg) except: traceback.print_exc() sublime.error_message("Gist: unknown error (please, report a bug!)")
def run(self): user_settings = os.path.join( sublime.packages_path(), "User", "LaTeXTools.sublime-settings" ) load_default = False if not os.path.exists(user_settings): migrate = sublime.ok_cancel_dialog( 'You do not currently have a personalized ' 'LaTeXTools.sublime-settings file.\n\n' 'Create a copy of the default settings file in ' 'your User directory?' ) if migrate: sublime.active_window().run_command('latextools_migrate') else: load_default = True self.view = sublime.active_window().open_file(user_settings) if load_default: sublime.set_timeout(self.set_content, 1)
def _get_cache(): if _ST3: cache_path = os.path.normpath( os.path.join(sublime.cache_path(), "LaTeXTools")) else: cache_path = os.path.normpath( os.path.join(sublime.packages_path(), "User")) pkg_cache_file = os.path.normpath( os.path.join(cache_path, 'pkg_cache.cache' if _ST3 else 'latextools_pkg_cache.cache')) cache = None if not os.path.exists(pkg_cache_file): gen_cache = sublime.ok_cancel_dialog( "Cache files for installed packages, " "classes and bibliographystyles do not exists, " "would you like to generate it? After generating complete, " "please re-run this completion action!" ) if gen_cache: sublime.active_window().run_command("latex_gen_pkg_cache") else: with open(pkg_cache_file) as f: cache = json.load(f) return cache
def on_list_selected_done(self, picked): if picked == -1: self.view.sel().clear() for each in self.return_to: self.view.sel().add(each) self.view.show(self.view.sel()) else: titles = self.get_comment_titles() title = titles[picked] row = title['line'] point = self.view.text_point(row, 0) line_region = self.view.line(point) # Reference the 'text' within the line only text = title['text'] text = re.escape(text) text = text.replace('\>', '>') # ">" does not work when escaped text_region = self.view.find(text, line_region.a) # view.rowcol() returns a zero based line number line = int(title['line'])+1 # Use goto_line to move the document then highlight if sublime.active_window().active_view(): sublime.active_window().active_view().run_command( "goto_line", {"line": line} ) self.view.sel().clear() self.view.sel().add(text_region)
def run(self, edit, template): window = sublime.active_window() view = self.view # Path variables folders = window.folders() filename = view.file_name() if (len(folders) > 0): folder = folders[0] + '/' filename = filename.replace(folder, '') namespaces = Utils().get_psr4_namespaces() if namespaces: for namespace, folder in namespaces.items(): dirname = os.path.dirname(filename) print(folder, dirname) if dirname.startswith(folder): # Now extract the namespace and classname namespace = dirname.replace(folder, namespace).rstrip("\\") classname = os.path.basename(filename).replace('.php', '') xml = ElementTree.parse(template) snippet = xml.getroot().find('content').text sublime.active_window().run_command('insert_snippet', dict(contents=snippet, NAMESPACE=namespace, CLASSNAME=classname))
def createWindowWithText(self, textToDisplay, fileType, showResultInSameFile): if not(showResultInSameFile): view = sublime.active_window().new_file() openedNewView = True else: view = self.findHttpResponseView() openedNewView = False if view is None: view = sublime.active_window().new_file() openedNewView = True edit = view.begin_edit() if not(openedNewView): view.insert(edit, 0, "\n\n\n") view.insert(edit, 0, textToDisplay) view.end_edit(edit) view.set_scratch(True) view.set_read_only(False) view.set_name("http response") if fileType == HttpRequester.FILE_TYPE_HTML: view.set_syntax_file("Packages/HTML/HTML.tmLanguage") if fileType == HttpRequester.FILE_TYPE_JSON: view.set_syntax_file("Packages/JavaScript/JSON.tmLanguage") if fileType == HttpRequester.FILE_TYPE_XML: view.set_syntax_file("Packages/XML/XML.tmLanguage") return view.id()
def on_done(self, index): global g_selectedItems if index > -1: g_selectedItems = 1 sublime.active_window().focus_view(self.view_list[index]) self.name_list = [] self.view_list = []
def on_open_declaration(location): """Call this callback when link to type is clicked in info popup. Opens location with type declaration """ sublime.active_window().open_file(location, sublime.ENCODED_POSITION)
def get_project_name(context=None): if context != None: if isinstance(context, sublime.View): view = context window = view.window() elif isinstance(context, sublime.Window): window = context view = window.active_view() else: window = sublime.active_window() view = window.active_view() else: window = sublime.active_window() view = window.active_view() if is_mm_project(window): if context == None: try: return os.path.basename(sublime.active_window().folders()[0]) except: return None else: try: return os.path.basename(window.folders()[0]) except: return None else: return None
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")
def run(self, should_split_view): pfe_settings.set('should_split_view', should_split_view) current_file = sublime.active_window().active_view().file_name() schema = sublime.active_window().active_view().file_name().split('/').pop(-2) file_name = sublime.active_window().active_view().file_name().split('/').pop() if (schema == "testing") or (schema == "public"): if schema == "testing": new_file = "../"+"public" + "/" + file_name[5:] else: new_file = "../"+"testing" + "/" + "test_" + file_name else: if(file_name.startswith("test_")): print(file_name) new_file = "../" + schema.rstrip("testing").rstrip("_") + "/" + file_name[5:] else: new_file = "../" + schema + "_testing" + "/" + "test_" + file_name if self.window.find_open_file(new_file): if should_split_view is True: self.split_view() self.window.open_file(new_file) else: self.window.show_input_panel("file_name:", new_file, self.on_done, None, None)
def plugin_loaded(): current_path = os.path.dirname(os.path.realpath(__file__)) sublime_dir = os.path.dirname(sublime.packages_path()) packages_dir = os.path.join(sublime_dir, 'Packages') user_dir = os.path.join(packages_dir, 'User') status_panel = sublime.active_window().create_output_panel("sublimious_status_panel") sublime.active_window().run_command("show_panel", {"panel": "output.sublimious_status_panel", "toggle": False}) pcontrol_settings = os.path.join(user_dir, 'Package Control.sublime-settings') settings_file = os.path.join(user_dir, 'Preferences.sublime-settings') collector = Collector(current_path) if not collector.get_user_config().nuke_everything: status_panel.run_command("status", {"text": "Sublimious is currently off."}) status_panel.run_command("status", {"text": "Since this might be your first start, I created a ~/.sublimious file"}) status_panel.run_command("status", {"text": "Open that file and change 'nuke_everything' to True to proceed\n"}) sys.exit() status_panel.run_command("status", {"text": "Welcome to Sublimious."}) # Nuke everything settings_current = [os.path.join(current_path, f) for f in os.listdir(current_path) if f.endswith(".sublime-settings")] settings_user = [os.path.join(user_dir, f) for f in os.listdir(user_dir) if f.endswith(".sublime-settings")] filelist = settings_current + settings_user for f in filelist: os.remove(f) # Second iteration to initialise all layers with config collected_config = collector.get_collected_config() for layer in collector.get_layers(): layer.init(collected_config) status_panel.run_command("status", {"text": "'%s' layer loaded..." % layer.name}) # Collect all packages status_panel.run_command("status", {"text": "Collecting all packages..."}) all_packages = collector.collect_key("required_packages") + collector.get_user_config().additional_packages write_sublimious_file(pcontrol_settings, json.dumps({'installed_packages': all_packages})) # Get all keybinding definitions and save to keymapfile status_panel.run_command("status", {"text": "Building keymap..."}) write_sublimious_file("%s/Default.sublime-keymap" % current_path, json.dumps(collector.collect_key("sublime_keymap"))) # Generate a bunch of syntax files depending on layer config syntax_definitions = collector.collect_syntax_specific_settings() for syntax, value in syntax_definitions.items(): write_sublimious_file("%s/%s.sublime-settings" % (current_path, syntax), json.dumps(value)) status_panel.run_command("status", {"text": "Collected %s syntax definition..." % syntax}) # Generate package specific settings for package, setting in collector.get_collected_config()["package_settings"].items(): write_sublimious_file("%s/%s.sublime-settings" % (user_dir, package), json.dumps(setting)) # Take control over sublime settings file status_panel.run_command("status", {"text": "Taking control over Preferences.sublime-settings..."}) write_sublimious_file(settings_file, json.dumps(collected_config)) status_panel.run_command("status", {"text": "ALL DONE!"})
def on_done( self , inp, cur_type ) : fn = self.classpath; parts = inp.split(".") pack = [] while( len(parts) > 0 ): p = parts.pop(0) fn = os.path.join( fn , p ) if hxsrctools.is_type.match( p ) : cl = p break; else : pack.append(p) if len(parts) > 0 : cl = parts[0] fn += ".hx" src = "\npackage " + ".".join(pack) + ";\n\n"+cur_type+" "+cl+" " if cur_type == "typedef" : src += "= " src += "{\n\n\t\n\n}" current_create_type_info[fn] = src sublime.active_window().open_file( fn )
def handle_result(self, cmd, outfile, retCode, output): if retCode: if output: sublime.error_message(' '.join(cmd) + '\r\n\r\n' + output.decode('utf-8')) else: if self.get_setting('open_file'): sublime.active_window().open_file(outfile)
def connection_error(message): """ Template for showing error message on connection error/loss. Keyword arguments: message -- Exception/reason of connection error/loss. """ sublime.error_message("Please restart Xdebug debugging session.\nDisconnected from Xdebug debugger engine.\n" + message) info("Connection lost with debugger engine.") debug(message) # Reset connection try: S.SESSION.clear() except: pass finally: S.SESSION = None S.SESSION_BUSY = False S.BREAKPOINT_EXCEPTION = None S.BREAKPOINT_ROW = None S.BREAKPOINT_RUN = None S.CONTEXT_DATA.clear() async_session = SocketHandler(ACTION_WATCH) async_session.start() # Reset layout sublime.active_window().run_command('xdebug_layout') # Render breakpoint markers render_regions()
def packagesComplete(data): global INSTALLED_PACKAGES, DEFAULT_PACKAGES INSTALLED_PACKAGES = data["installed_packages"] DEFAULT_PACKAGES = data["default_packages"] installed_menu = { "selected_index": 1, "items": [["Back", "Back to previous menu"]], "actions": [ { "name": "package_manager" } ] } # Installed packages install_update = False for package in getInstalledPackages(): install_update = True installed_menu["actions"].append({"command": "javatar_install", "args": {"installtype": "uninstall_package", "name": package["name"], "filename": package["path"]}}) installed_menu["items"].append([package["name"], "Installed (" + toReadableSize(package["path"]) + ")."]) if install_update: installed_menu["selected_index"] = 2 sublime.active_window().run_command("javatar", {"replaceMenu": { "name": "uninstall_packages", "menu": installed_menu }}) from .javatar_updater import updatePackages updatePackages()
def on_ch_settings_change(self): sets = sublime.load_settings(settings_file) enabled = sets.get("enabled") if enabled != self.settings["enabled"]: self.settings["enabled"] = enabled if not enabled: self.do_disable() else: self.do_enable() style = sets.get("style") if style != self.settings["style"]: self.settings["style"] = style self.on_selection_modified(sublime.active_window().active_view()) ha_style = sets.get("ha_style") if ha_style != self.settings["ha_style"]: self.settings["ha_style"] = ha_style self.on_activated(sublime.active_window().active_view()) icons_all = sets.get("icons_all") if icons_all != self.settings["icons_all"]: self.settings["icons_all"] = icons_all self.on_activated(sublime.active_window().active_view()) icons = sets.get("icons") if icons != self.settings["icons"]: self.settings["icons"] = icons self.on_selection_modified(sublime.active_window().active_view()) color_formats = sets.get("color_formats") if color_formats != self.settings["color_formats"]: self.settings["color_formats"] = color_formats self.settings["color_fmts"] = list(map(get_format, color_formats))
def get_target_ros_path(user_query=True): ros_path_settings = sublime.load_settings(ROS_PATH_KEY) path = ros_path_settings.get("path", "") if path == "" and user_query: sublime.message_dialog(MESSAGE_NO_KEY) sublime.active_window().show_input_panel("Target ROS path:", "", save_ros_target_path, None, None) return path
def run(self, edit): # print("test = " + str(Settings.get("test", "default"))) # print("Active window - " + sublime.active_window().project_file_name()) # deleteAllServers() # loc = "http://localhost:62562/ready" # print("Connecting to: " + loc) # proxies={'http':None} # # print(urllib.request.FancyURLopener({}).open(loc).read()) # # print(urllib.request.urlopen(loc, proxies={}).read()) # proxy_handler = urllib.request.ProxyHandler({}) # opener = urllib.request.build_opener(proxy_handler) # opener.open('http://localhost:62562/ready') # print(str(opener.open(loc))) # print(str(opener.open(loc).read())) # print(urllib.request.urlopen(loc, proxies={}).read()) window = sublime.active_window() pt = window.create_output_panel("paneltest") pt.set_read_only(False) # edit = pt.begin_edit() pt.insert(edit, pt.size(), "Writing...2") pt.set_read_only(True) # pt.end_edit(edit) window.run_command("show_panel", {"panel": "output.paneltest"}) window = sublime.active_window()
def run(self, edit): search_text = '' s = OnlineSearcher() for selection in self.view.sel(): search_text = self.view.substr(selection) sublime.active_window().show_input_panel('Search online for', search_text,s.search, None, None)
def run(self, edit): global Sockets, Infos, Cursors, OCursors, Started def onDone(message): global Sockets, Infos, Cursors, Started try: Host, Port = message.split(':', 1) Port = int(Port) Sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) Infos.append(self.view) Cursors.append(list(self.view.sel())) OCursors.append([]) try: Sock.connect((Host, Port)) Sockets.append(Sock) if not Started: Started = True sublime.set_timeout_async(Loop, 0) except: sublime.error_message('Unable to connect.') except: sublime.error_message('Please enter hostname:port.') sublime.active_window().show_input_panel('Hostname:port', '', onDone, None, None)
def __init__(self): self.view = sublime.active_window().active_view()
def get_window(): return sublime.active_window()
def search_base(self, log_name): srch_opt = get_prefs().get('search_base', []) srcn_en = srch_opt.get('enable', True) floating = self.view.settings().get('floating', True) if floating or (not srcn_en): self.search_base_success = True self.base_dir = "." sublime.status_message("Log Highlight : Skipped to search base directory") return file_name = self.get_rel_path_file() self.search_base_success = True self.base_dir = "" if file_name == "": return excludes = srch_opt.get('ignore_dir', []) max_scan = srch_opt.get('max_scan_path', MAX_SCAN_PATH) old_path = ["", 0] _path = os.path.dirname(log_name) _depth = _path.count(os.path.sep) new_path = [_path, _depth] scan_path = 0 found = False try: # check projct file prjf = self.view.window().project_file_name() if isinstance(prjf, str) and prjf != "": pdat = self.view.window().project_data() root = pdat.get('base_dir') if isinstance(root, str) and os.path.isfile(os.path.join(root, file_name)): self.base_dir = root found = True # check open folder first if not found: for root in sublime.active_window().folders(): if os.path.isfile(os.path.join(root, file_name)): self.base_dir = root found = True break if not found: # scanning near the log for i in range(MAX_STAIR_UP_PATH): for root, dirs, files in os.walk(new_path[0]): dirs[:] = [d for d in dirs if (d not in excludes) and d[0] != '.'] if i == 0 or not root.startswith(old_path[0]): sublime.status_message("Log Highlight : Searching - " + root) # print (root) if os.path.isfile(os.path.join(root, file_name)): self.base_dir = root found = True break else: scan_path = scan_path + 1 if scan_path > max_scan - 1: break if found or scan_path > max_scan - 1: break else: # print ("Searching Uppder Directory") old_path = [new_path[0], new_path[0].count(os.path.sep)] _path = os.path.dirname(old_path[0]) _depth = _path.count(os.path.sep) if old_path[1] == _depth or _depth < 1: # to stop level 1 (old_path[1] == _depth == 1) break else: new_path = [_path, _depth] pass except Exception: disp_exept() if found: sublime.status_message("Log Highlight : Found base directory (" + str(scan_path) + ") - " + self.base_dir) else: sublime.status_message("Log Highlight : Fail to find (" + str(scan_path) + ") - " + file_name) self.search_base_success = found return
def is_relevant_file(self): return sublime.active_window().active_view().scope_name( sublime.active_window().active_view().sel()[0].begin()).find( 'source.js') != -1
def edit(self): return sublime.active_window().open_file(self.path())
def pathRelativeFromView(self): return os.path.relpath( self.path(), os.path.dirname( sublime.active_window().active_view().file_name())).replace( '\\', '/')
def guess_view(self): if sublime.active_window() and sublime.active_window().active_view(): Pref.view = sublime.active_window().active_view()
def get_view_by_buffer_id(self, buffer_id): for view in sublime.active_window().views(): if view.buffer_id() == buffer_id: return view return None
def setUp(self): self.view = sublime.active_window().new_file() s = sublime.load_settings("Preferences.sublime-settings") s.set("close_windows_when_empty", False)
import flower from .core import Preset, Runner from .compilerutils import getCompiler, Flow, COMPILER_KEY from ..pathutils import isFlowFile, getExt, FLOW_EXT log = logging.getLogger(flower.NAME) _PRESET = None _RUNNER = None _ACTION = None PRESETS = { "CURRENT": lambda: Preset( name='Current File', main=sublime.active_window().active_view().file_name(), ) } RUNNERS = {} # private stuff def _getPreset(key): if isinstance(key, dict): return Preset.fromdict(key) preset = PRESETS.get(key) if callable(preset): return preset()
def setUp(self): self.window = sublime.active_window() self.window.run_command('initialize_setup')
def run(self, edit): import_groups = [] code_lines = [] line_offset = 0 filename = sublime.Window.active_view( sublime.active_window()).file_name() for line in self.view.lines(sublime.Region(0, self.view.size())): line = self.view.substr(line) if not line.strip().startswith('# -*- '): code_lines.append(line) else: line_offset += 1 code = '\n'.join(code_lines) try: tree = compile(code, filename, 'exec', _ast.PyCF_ONLY_AST) except: tree = None else: unused_imports = set() # for error in pyflakes.Checker(tree, filename).messages: # if isinstance(error, pyflakes.messages.UnusedImport): # print type(error) # unused_imports.add(error.name) st = ast.parse(code) current_group = None for stmt in st.body: if stmt.__class__ in [ast.Import, ast.ImportFrom]: line_region = self.view.full_line( self.view.text_point(stmt.lineno - 1 + line_offset, 0)) if not current_group: current_group = ImportGroup(line_region.a, line_region.b) import_groups.append(current_group) current_group.imports.append(stmt) current_group.end = max(line_region.b, current_group.end) else: current_group = None edit = self.view.begin_edit('OrganizePythonImportsCommand') for g in import_groups[-1::-1]: imports, from_imports = set(), {} for imp in g.imports: if isinstance(imp, ast.Import): for alias in imp.names: if alias.asname: if alias.asname not in unused_imports: imports.add('import {0} as {1}'.format( alias.name, alias.asname)) elif alias.name not in unused_imports: imports.add('import {0}'.format(alias.name)) else: from_imports.setdefault(imp.module, set()) for alias in imp.names: if alias.asname: if alias.asname not in unused_imports: from_imports[imp.module].add( '{0} as {1}'.format( alias.name, alias.asname)) elif alias.name not in unused_imports: from_imports[imp.module].add('{0}'.format( alias.name)) import_str = '\n'.join(sorted(imports)) + '\n' for p in sorted(from_imports.keys()): v = from_imports[p] if v: import_str += 'from {0} import {1}'.format( p, ', '.join(sorted(v))) + '\n' self.view.replace(edit, sublime.Region(g.start, g.end), import_str.strip('\n') + '\n') self.view.end_edit(edit)
def generate_project_auto_complete(self, base): folders = sublime.active_window().folders() folders = map(lambda f: os.path.basename(f), folders) return self.generate_auto_complete(base, folders)
def setUp(self): self.view = sublime.active_window().new_file() # make sure we have a window to work with s = sublime.load_settings("Preferences.sublime-settings") s.set("close_windows_when_empty", False)
def console_open(self): window = sublime.active_window() window.run_command("show_panel", {"panel": "console", "toggle": False}) self.console_blur()
def open_settings(self): sublime.active_window().open_file(sublime.packages_path() + "/User/" + self.SETTINGS)
def run(self): # These tests are quite human-readable, but not so human-writable (: as it may seems :). But this is intentional, as in # case of small typo exception is raised instead of "smart" guessing what you possibly wanted, and running without fail # [and may be even improperly showing test as CORRECTly passed whilst it was INcorrectly parsed]. tests = """\ (1) 1. Select THIS 2. Additionally [multi-] select THIS2 [also (e.g. with Ctrl+mouse)]. 3. Copy [to clipboard (e.g. press Ctrl+C)]. 4. Set cursor to here -><-, and [also (via Ctrl+click)] to here -><-. 5. Paste [from clipboard (e.g. press Ctrl+V)]. [This works correctly in SublimeText by default (and this plugin SHOULD NOT break this behaviour/functionality).] This is CORRECT result: 4. Set cursor to here ->THIS<-, and [also (via Ctrl+click)] to here ->THIS2<-. (2) 1. Select THIS 2. Additionally select THIS2 3. Cut [to clipboard (e.g. press Ctrl+X)]. 4. Paste [from clipboard (e.g. press Ctrl+V)]. 5. Paste [again]. [This test was added based on wbond's comment[https://github.com/SublimeTextIssues/Core/issues/1435#issuecomment-258159654 "When performing editing in multiple selections, if the user cuts and then pastes, the obvious functionality it to cut text from each line and then paste the same text back to where the cursor currently is. This allows you to batch edit lines."]. This works correctly in SublimeText by default (and this plugin SHOULD NOT break this behaviour/functionality).] This is WRONG result: 1. Select THIS THIS2THIS THIS2 2. Additionally select THIS THIS2THIS THIS2 This is CORRECT result: 1. Select THISTHIS 2. Additionally select THIS2THIS2 (3) 1. Select T-H- . . . . . .-I-S 2. Copy. 3. Set cursor to here -><-, and to here -><-. 4. Paste. [This does not work correctly in SublimeText by default (issue[https://github.com/SublimeTextIssues/Core/issues/1435]).] This is WRONG result: 3. Set cursor to here ->T-H-<-, and to here ->. . . . . .-I-S<-. [But SHOULD works correctly after installing this plugin.] This is CORRECT result: 3. Set cursor to here ->T-H- . . . . . .-I-S<-, and to here ->T-H- . . . . . .-I-S<-. (4) 1. Select THIS 2. Additionally select THIS 3. Copy 4. Set cursor to here -><- 5. Paste [This does not work correctly in SublimeText by default (issue[https://github.com/SublimeTextIssues/Core/issues/1461]).] This is WRONG result: 4. Set cursor to here ->THIS THIS<- This is ALSO WRONG result [observed in CopyEdit up to version 9b68204818258c33889bc923a15f1d83cad8423e]: 4. Set cursor to here ->THISTHIS<- This is CORRECT result: 4. Set cursor to here ->THIS<- (4a) 1. Select THIS 2. Additionally select THIS 3. Cut 4. Set cursor to here -><- 5. Paste This is CORRECT result: 1. Select 2. Additionally select 4. Set cursor to here ->THIS<- (5) 1. Select THIS 2. Additionally select THIS 3. Copy 4. Set cursor to here -><-, and to here -><-. 5. Paste [This works correctly in SublimeText by default (this test was added just to designate particularity of test (4) and to check that this [(5) test] behaviour should remain working as well).] This is CORRECT result: 4. Set cursor to here ->THIS<-, and to here ->THIS<-. (6) 1. Set cursor to here -><- 2. Copy 3. Set cursor to here -><- 4. Paste This is CORRECT result: 3. Set cursor to here -><- to here -><- This is WRONG result: 3. Set cursor to here -> to here -><- <- (7) 1. Set cursor to here -><-, and to here -><-. 2. Copy. 3. Set cursor to here -><-, and to here -><-. 4. Paste. [This test was added based on my comment[https://github.com/SublimeTextIssues/Core/issues/1461#issuecomment-258406270 "... multi-caret [multi-line] cut (Ctrl+X) in SublimeText without selection is even more broken $'`"\U0001f615"`' than pasting in multiple selections (#1435) ..."].] This is WRONG result: 3. Set cursor to here -><-, and to here -><-. to here -><-, to here -><-, and to here -><-. and to here -><-. This is ALSO WRONG result: 3. Set cursor to here -> to here -><-, <-, and to here -> and to here -><-. <-. This is CORRECT result: 3. Set cursor to here -><-, to here -><-, and to here -><-. and to here -><-. [Nothing interesting here. This following checks are just for completeness.] (8) 1. Set cursor to here -><- 2. Cut 3. Set cursor to here -><- 4. Paste This is CORRECT result: 1. Set cursor 3. Set cursor to here -><- to here -><- (9) 1. Set cursor to here -><-, and to here -><-. 2. Cut. 3. Set cursor to here -><-. 4. Paste. This is CORRECT result: 1. Set cursor 3. Set cursor to here -><-, and to here -><-. to here -><-. (10) 1. Select THIS. 2. Copy. 3. Character-by-character select THIS. 4. Paste. This is WRONG result: 3. Character-by-character select THISTHISITHIS. This is CORRECT result: 3. Character-by-character select THISTHISTHISTHIS. """ pos = 0 def read_re(rexp): nonlocal pos r = re.compile(rexp).match(tests, pos) # re.match(rexp, tests[pos:]) if not r: raise "?" pos = r.end() # pos += r.end() return r.groups() def read_list_of_commands(): nonlocal pos commands = [] while True: commands.append(read_re(R"(\d+)\. ([\s\S]+?)\n(?=\d+\.|\n(?! )|$)")) if pos == len(tests): break if tests[pos] == "\n": pos += 1 # skip \n break return commands def skip_comments(): nonlocal pos while tests[pos] == '[': # [ #read_re(R"\[[^\[\]]+(?:\[[^\]]+\])?[^\]]+\]\n\n?") nesting_level = 0 while True: ch = tests[pos] if ch == "[": nesting_level += 1 elif ch == "]": nesting_level -= 1 if nesting_level == 0: pos += 1 break pos += 1 if pos == len(tests): raise 'Unpaired `[`' assert(tests[pos] == "\n") pos += 1 if tests[pos] == "\n": pos += 1 # Create scratch buffer just for testing purposes buffer = sublime.active_window().new_file() buffer.set_scratch(True) while pos < len(tests): # Read test id [test number] skip_comments() test_id = read_re(R"(\(\w+\))\n")[0] # Read commands commands = read_list_of_commands() # Prepare scratch buffer buffer.run_command("select_all") buffer.run_command("right_delete") buffer.run_command("append", { "characters": "".join([c[0] + '. ' + c[1] + "\n" for c in commands]) } ) # || "insert" is not working totally correctly here, so "append" is used instead # \\ To see what is the difference try # Process commands # \\ `view.run_command("append", { "characters": " a\nb" } )` for command in commands: # \\ and cmd = re.sub(R' \[[^]]+]', '', command[1]) # remove comments # \\ `view.run_command("insert", { "characters": " a\nb" } )` cmd = cmd.rstrip('.')#rstrip('.', 1) # remove ending `.` if present if cmd in ["Cut", "Copy", "Paste"]: #buffer.run_command(cmd.lower()) # this does not work, so emulate correct behaviour manually: overrided_command = sublime_plugin.on_text_command(buffer.id(), cmd.lower(), None) buffer.run_command(*overrided_command if overrided_command[0] else (cmd.lower(),)) continue def where_command_starts(next = 0): # (using this function below is not totally fair, but much easier) return buffer.find("^" + str(int(command[0])+next) + ". ", 0) r = re.match(R"Select (T[-\.\s]*?H[-\.\s]*?I[-\.\s]*?S\d*)$", cmd) if r: buffer.sel().clear() buffer.sel().add(buffer.find(r.group(1), where_command_starts().b, sublime.LITERAL)) continue r = re.match(R"Additionally select (THIS\d*)$", cmd) if r: buffer.sel().add(buffer.find(r.group(1), where_command_starts().b, sublime.LITERAL)) continue r = re.match(R"Character-by-character select (THIS)$", cmd) if r: buffer.sel().clear() start = buffer.find(r.group(1), where_command_starts().b, sublime.LITERAL).begin() for x in range(len(r.group(1))): buffer.sel().add(sublime.Region(start + x, start + x + 1)) continue r = re.match(R"Set cursor\s+to here -><-(?:,\s+and to here -><-)?$", cmd) if r: buffer.sel().clear() pos_ = where_command_starts().b end_ = where_command_starts(1).a while True: pos_ = buffer.find("-><-", pos_, sublime.LITERAL).a if pos_ == -1 or pos_ > end_: break pos_ += 2 buffer.sel().add(sublime.Region(pos_, pos_)) continue raise "Unknown command" obtained_result = buffer.substr(sublime.Region(0, buffer.size())) # Read predetermined results compared_result_type = None while True: skip_comments() # [ type_of_result = read_re(R"This is (.+) result(?: \[[^\]]+])?:\n")[0] rcommands = read_list_of_commands() # Compare this result with processed result ccommands = list(commands) # create copy of commands for c in rcommands: # write rcommands over ccommands assert(ccommands[int(c[0])-1][0] == c[0] and ccommands[int(c[0])-1][1] != c[1]) ccommands[int(c[0])-1] = c if "".join([c[0] + '. ' + c[1] + "\n" for c in ccommands]) == obtained_result: assert(compared_result_type == None) compared_result_type = type_of_result #break # break is commented out for more accurate correctness testing/checking # Check break conditions if pos == len(tests): break if tests[pos] == "\n": pos += 1 # skip \n break print(test_id + ' ' + (compared_result_type if compared_result_type else "INCORRECT")) if not compared_result_type: return # to skip buffer.close() call buffer.close() # Those tests_neo (below) allow do testing much more accurately, and they can also check cursor/selection position after command was executed tests_neo = """ TN 0 // Test Number 0 — basic syntax [of this new language for tests] tests/checks """+0*""" DA 1234 CU 1>‘2’<34 //select/‘set CUrsor’ just one character ‘2’ CR 1>‘2’<34 //paranoiac check result 1|2|34 CU >>‘’. // just like pressing right arrow key → 12||34 CR 12>‘’<34 CU >‘’> // once more → 123||4 CR 123>‘’<4 CU .‘’> // like pressing Shift + → 123|4| CR 123>‘4’< CU <‘’. // like pressing Shift + ← 12|34| CR 12>‘34’< CU <‘’< // 1|23|4 CR 1>‘23’<4 CU .‘’< 1|2|34 CR 1>‘2’<34 CU <‘’. |12|34 CR >‘12’<34 CU .‘’<< ||1234 CR >‘’<1234 CU >‘’>> 1|234| CR 1>‘234’< CU <<‘’>> // select all |1234| CR >‘1234’< // check/correct result CU >>‘’>> // End 1234|| CR 1234>‘’< CU <<‘’<< // Home ||1234 CR >‘’<1234 """+""" TN 1 // Just copy of (1) test DA‘1. Select >‘THIS’< 2. Additionally [multi-] select >‘THIS2’< [also (e.g. with Ctrl+mouse)].’ CO copy DA‘Set cursor to here ->>‘’<<-, and [also (via Ctrl+click)] to here ->>‘’<<-.’ CO paste CR‘Set cursor to here ->THIS>‘’<<-, and [also (via Ctrl+click)] to here ->THIS2>‘’<<-.’ TN 2 // Some newly discovered bug (for the sake of what all this new language (tests_neo) was created) DA >‘Test’<Test CO copy CO paste IR TestTest>‘’< // incorrect result CR Test>‘’<Test TN 3 // Just copy of (10) test (incorrect result observed at revision 55d7187e204f6159af33c257a4ebcc5bd4174cbb) DA 1. Select >‘THIS’<. CO copy DA 3. Character-by-character select >‘T’<>‘H’<>‘I’<>‘S’<. CO paste IR 3. Character-by-character select THIST>‘’<HIST>‘’<HIST>‘’<HIS.>‘’< CR 3. Character-by-character select THIS>‘’<THIS>‘’<THIS>‘’<THIS>‘’<. TN 4 // Something like test (10) (incorrect result observed at revision f70397b75fde9a1a6ff082d8acdd1a800bc613e5) DA >‘?’< CO copy DA >‘╚════’< CO split_selection_into_characters CR >‘╚’<>‘═’<>‘═’<>‘═’<>‘═’< CO paste IR ?>‘’<?>‘’<═?>‘’<?>‘’< CR ?>‘’<?>‘’<?>‘’<?>‘’<?>‘’< TN 5 // In accordance with Eyenseo's fix e07420b70dcc46c031e86f5f87b702430bd19c9a (incorrect result observed at revision 276f8a7790939301fe181bd66288d24febd56923) DA‘aaaa bb>‘’<bb cccc’ CO copy CO paste IR‘aaaa bbbb >‘’<bbbb cccc’ CR‘aaaa bbbb bb>‘’<bb cccc’ TN 6 DA lin>‘’<e CO copy CO paste CR‘line lin>‘’<e’ TN 7 DA‘>‘1’< >‘2’<’ CO copy DA‘’ CO paste IR 12>‘’< CR‘1 2>‘’<’ TN 8 DA‘1>‘’< 2’ CO copy DA‘>‘1 ’<2’ CO paste CR‘1 >‘’<2’ """ # Create scratch buffer just for testing purposes buffer = sublime.active_window().new_file() buffer.set_scratch(True) def switch_test(): print("passed") pos = 0 while True: # Skip empty lines while pos < len(tests_neo) and tests_neo[pos] == '\n': pos += 1 if pos == len(tests_neo): break # Read command cmd = tests_neo[pos:pos+2] pos += 2 # Read command data if tests_neo[pos] == " ": end_of_data = tests_neo.find("\n", pos) data = tests_neo[pos+1: end_of_data] comment_start = data.find("//") if comment_start != -1: data = data[:comment_start] data = data.rstrip() pos = end_of_data elif tests_neo[pos] == "‘": # ’ i = pos nesting_level = 0 while True: ch = tests_neo[i] if ch == "‘": nesting_level += 1 elif ch == "’": nesting_level -= 1 if nesting_level == 0: break i += 1 if i == len(tests_neo): raise 'Unpaired quote' data = tests_neo[pos+1:i] pos = i + 1 else: print(tests_neo[pos:pos+33]) assert(False) if cmd == "TN": # Test Number if data != "0": switch_test() print("Test " + data, end = " ") elif cmd == "DA": # set DAta # Find all selection/cursor marks in the data new_sel = [] i = 0 while True: sel_start = data.find(">‘", i) if sel_start == -1: break sel_end = data.find("’<", sel_start + 2) assert(sel_end != -1) data = data[:sel_start] + data[sel_start+2:sel_end] + data[sel_end+2:] # remove service characters (i.e. cursor>‘’</select>‘ion’< mark) new_sel.append(sublime.Region(sel_start, sel_end-2)) # Fill up the scratch buffer with new data buffer.run_command("select_all") buffer.run_command("right_delete") buffer.run_command("append", { "characters": data } ) # "insert" is not working totally correctly here, so "append" is used instead buffer.sel().clear() if new_sel: buffer.sel().add_all(new_sel) else: buffer.sel().add(sublime.Region(0)) elif cmd == "CU": # CUrsor/selection manipulation # [-not implemented yet-] pass elif cmd == "CO": overrided_command = sublime_plugin.on_text_command(buffer.id(), data, None) buffer.run_command(*overrided_command if overrided_command[0] else (data,)) elif cmd == "IR" or cmd == "CR": # Put all cursors/selections marks in buffer's text and compare it with data buffer_data = buffer.substr(sublime.Region(0, buffer.size())) new_data = "" prev_pos = 0 for sel in buffer.sel(): new_data += buffer_data[prev_pos:sel.begin()] + ">‘" + buffer_data[sel.begin():sel.end()] + "’<" prev_pos = sel.end() new_data += buffer_data[prev_pos:] if cmd == "IR": if new_data == data: print("incorrect result detected (command: IR‘"+data+"’)") return # to skip buffer.close() call else: assert(cmd == "CR") if new_data != data: print("check result failed (command: CR‘"+data+"’)") return # to skip buffer.close() call else: raise 'Unknown command ' + cmd switch_test() buffer.close()
def setUp(self, edit): self.console_blur() window = sublime.active_window() self.tools = ViewHelper(window, window.new_file(), edit)
def cb(): view = sublime.active_window().new_file() view.run_command('gosublime_doesnt_support_sublime_text2')
def console_blur(self): window = sublime.active_window() window.focus_group(0) window.focus_view(window.active_view())
def get_active_view(self): """Return the active view in the currently active window.""" return sublime.active_window().active_view()
def plugin_loaded(): global plugin_manager plugin_manager = PluginManager() view = sublime.active_window().active_view() _init_vintageous(view)
def on_done(self, idx): if idx == -1: return gist = self.gists[idx] sublime.active_window().run_command('open_url', {'url': gist['html_url']})
def is_visible(self, popup_type): return (popup_type in self.popup_types and self.popup_types[popup_type]["visible"] and sublime.active_window().active_view().is_popup_visible())
def plugin_loaded(): State.update({ 'active_view': sublime.active_window().active_view() })
def on_done(self): sublime.active_window().run_command('open_url', {'url': self.url})
def setProjectJson(self, data): return sublime.active_window().set_project_data(data)
def on_close(self, view): window = sublime.active_window() if window is None or not window.views(): send_command("shutdown")
def getProjectJson(self): return sublime.active_window().project_data()
def refresh(self): sublime.active_window().run_command("refresh_folder_list")