def on_done(self, cwd, cmd_str): cmd = parse_cmd(cmd_str) if cmd['pipe'] and not cmd['redirect']: sublime.error_message("Build systems do not support input from STDIN") return settings = cmd_settings(cmd['shell_cmd']) before, after = settings['surround_cmd'] shell_cmd = before + cmd['shell_cmd'] + after # We can leverage Sublime's (async) build systems unless we're # redirecting the output into the view. In that case, we use Popen # synchronously. if cmd['redirect']: view = self.window.active_view() if not view: sublime.error_message("No active view to redirect output to.") return for sel in view.sel(): self.process_selection(view, sel, cwd, shell_cmd, cmd['pipe']) else: exec_args = settings['exec_args'] exec_args.update({'cmd': shell_cmd, 'shell': True, 'working_dir': cwd}) self.window.run_command("exec", exec_args)
def configure_linter(self, language): """Fill out the template and move the linter into Packages.""" try: if language is None: return if not self.fill_template(self.temp_dir, self.name, self.fullname, language): return git = util.which('git') if git: subprocess.call((git, 'init', self.temp_dest)) shutil.move(self.temp_dest, self.dest) util.open_directory(self.dest) self.wait_for_open(self.dest) except Exception as ex: sublime.error_message('An error occurred while configuring the plugin: {}'.format(str(ex))) finally: if self.temp_dir and os.path.exists(self.temp_dir): shutil.rmtree(self.temp_dir)
def run(self, edit): currentfile = self.view.file_name() for region in self.view.sel(): text = None # If nothing selected, send single line if region.empty(): line = self.view.line(region) text = self.view.substr(line) cmd = '{text};'.format(**locals()) _send_cmd_to_max(cmd) # Else send all lines where something is selected # This only works by saving to a tempfile first, # as the mini macro recorder does not accept multiline input else: line = self.view.line(region) self.view.run_command("expand_selection", {"to": line.begin()}) regiontext = self.view.substr(self.view.line(region)) _save_to_tempfile(regiontext) if os.path.exists(TEMP): if currentfile: if _is_maxscriptfile(currentfile): cmd = 'fileIn (@"%s")\r\n' % TEMP else: cmd = 'python.executefile (@"%s")\r\n' % TEMP _send_cmd_to_max(cmd) else: sublime.error_message(NO_FILE) else: sublime.error_message(NO_TEMP)
def add_done(self, message, result): if result.strip(): sublime.error_message("Error adding file:\n" + result) return self.run_command(['git', 'commit', '-m', message], callback=self.update_status)
def copy_linter(self, name): """Copy the template linter to a new linter with the given name.""" self.name = name self.fullname = 'SublimeLinter-contrib-{}'.format(name) self.dest = os.path.join(sublime.packages_path(), self.fullname) if os.path.exists(self.dest): sublime.error_message('The plugin “{}” already exists.'.format(self.fullname)) return src = os.path.join(sublime.packages_path(), persist.PLUGIN_DIRECTORY, 'linter-plugin-template') self.temp_dir = None try: self.temp_dir = tempfile.mkdtemp() self.temp_dest = os.path.join(self.temp_dir, self.fullname) shutil.copytree(src, self.temp_dest) self.get_linter_language(name, self.configure_linter) except Exception as ex: if self.temp_dir and os.path.exists(self.temp_dir): shutil.rmtree(self.temp_dir) sublime.error_message('An error occurred while copying the template plugin: {}'.format(str(ex)))
def create_tempdir(): """Create a directory within the system temp directory used to create temp files.""" try: if os.path.isdir(tempdir): shutil.rmtree(tempdir) os.mkdir(tempdir) # Make sure the directory can be removed by anyone in case the user # runs ST later as another user. os.chmod(tempdir, stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO) except PermissionError: if sublime.platform() != 'windows': current_user = pwd.getpwuid(os.geteuid())[0] temp_uid = os.stat(tempdir).st_uid temp_user = pwd.getpwuid(temp_uid)[0] message = ( 'The SublimeLinter temp directory:\n\n{0}\n\ncould not be cleared ' 'because it is owned by \'{1}\' and you are logged in as \'{2}\'. ' 'Please use sudo to remove the temp directory from a terminal.' ).format(tempdir, temp_user, current_user) else: message = ( 'The SublimeLinter temp directory ({}) could not be reset ' 'because it belongs to a different user.' ).format(tempdir) sublime.error_message(message) from . import persist persist.debug('temp directory:', tempdir)
def run(self, edit): fname = self.view.file_name() if not fname: sublime.error_message("Save the file!") return cmd = "source(\"" + escape_dq(fname) + "\")" sendtext(cmd)
def perform_action(self): """ Perform action on targed text """ status = True if self.action == 'fold': # Fold regions self.view.fold(self.ignore_ending_newlines(self.replace_obj.target_regions)) elif self.action == 'unfold': # Unfold regions try: self.view.unfold(self.ignore_ending_newlines(self.replace_obj.target_regions)) except: sublime.error_message("Cannot unfold! Please upgrade to the latest stable beta build to remove this error.") elif self.action == 'mark': # Mark targeted regions if 'key' in self.options: color = self.options['scope'].strip() if 'scope' in self.options else DEFAULT_HIGHLIGHT_COLOR style = self.options['style'].strip() if 'style' in self.options else DEFAULT_HIGHLIGHT_STYLE self.set_highlights(self.options['key'].strip(), style, color) elif self.action == 'unmark': # Unmark targeted regions if 'key' in self.options: self.clear_highlights(self.options['key'].strip()) else: # Not a valid action status = False return status
def protocol(self, req): self.buf += req while True: before, sep, after = self.buf.partition(NEWLINE) if not sep: break try: # Node.js sends invalid utf8 even though we're calling write(string, "utf8") # Python 2 can figure it out, but python 3 hates it and will die here with some byte sequences # Instead of crashing the plugin, we drop the data. Yes, this is horrible. before = before.decode('utf-8', 'ignore') data = json.loads(before) except Exception as e: msg.error('Unable to parse json: %s' % str(e)) msg.error('Data: %s' % before) # XXXX: THIS LOSES DATA self.buf = after continue name = data.get('name') try: if name == 'error': message = 'Floobits: Error! Message: %s' % str(data.get('msg')) msg.error(message) if data.get('flash'): sublime.error_message('Floobits: %s' % str(data.get('msg'))) elif name == 'disconnect': message = 'Floobits: Disconnected! Reason: %s' % str(data.get('reason')) msg.error(message) sublime.error_message(message) self.stop() else: self.handler(name, data) except Exception as e: msg.error('Error handling %s event with data %s: %s' % (name, data, e)) self.buf = after
def title_input(self, title, path=None): """Sanitize a file title, save and open Args: title (string): A post title path (string): A path string Returns: None """ post_dir = self.path_string() if path is None else path self.markup = get_setting(self.window.active_view(), 'jekyll_default_markup', 'Markdown') if self.markup == 'Textile': file_ext = '.textile' elif self.markup == 'HTML': file_ext = '.html' else: file_ext = '.markdown' clean_title = clean_title_input(title, self.IS_DRAFT) + file_ext full_path = os.path.join(post_dir, clean_title) if os.path.lexists(full_path): sublime.error_message('Jekyll: File already exists at "{0}"'.format(full_path)) return else: frontmatter = self.create_post_frontmatter(title) self.create_and_open_file(full_path, frontmatter)
def run(self, edit): template_filename = self.view.file_name() self.dissect_filename(template_filename) if not template_filename: return sublime.error_message("You have to provide a template path.") if not self.action.startswith("eton"): return sublime.error_message("Invalid eton template %s" % template_filename) if not os.path.exists(template_filename): return sublime.error_message("File does not exist") self.url = get_url(self.settings) + self.COMMAND_URL+self.partner+'/'+self.action.replace('eton_','') # get file names file_names = json.dumps(self.generate_file_list()) use_cache = self.settings.get('use_cache', DEFAULT_USE_CACHE_SETTING) print("Attempting to render %s for %s" % (self.action, self.partner)) print("url is %s" % self.url) params = dict(partner=self.partner, action=self.action, templates= json.dumps(self.generate_file_map())) try: response = urlopen(self.url, urllib.parse.urlencode(params).encode("utf-8")) except urllib.error.URLError as e: print(e) return str(e) temp = tempfile.NamedTemporaryFile(delete=False, suffix=".html") temp.write(response.read()) temp.close() webbrowser.open("file://"+temp.name)
def transformations(self): '''Generates a ranked list of available transformations.''' view = self.window.active_view() # hash of transformation ranks ranked = {} for label, settings in _s('transformations').items(): for scope in settings['scope'].keys(): score = view.score_selector(0, scope) if not score: continue if label not in ranked or ranked[label] < score: ranked[label] = score if not len(ranked): sublime.error_message( 'No transformations configured for the syntax ' + view.settings().get('syntax')) return # reverse sort self.options = list(OrderedDict(sorted( ranked.items(), key=lambda t: t[1])).keys()) self.options.reverse() return self.options
def run(self, edit, **args): DEFAULT_FORMAT = '%Y-%m-%d' view = self.view date_format = get_setting(view, 'jekyll_date_format', '%Y-%m-%d') datetime_format = get_setting(view, 'jekyll_datetime_format', '%Y-%m-%d %H:%M:%S') try: d = datetime.today() if args['format'] and args['format'] == 'date': text = d.strftime(date_format) elif args['format'] and args['format'] == 'datetime': text = d.strftime(datetime_format) else: text = d.strftime(DEFAULT_FORMAT) except Exception as e: sublime.error_message('Jekyll: {0}: {1}'.format(type(e).__name__, e)) return # Don't bother replacing selections if no text exists if text == '' or text.isspace(): return # Do replacements for r in self.view.sel(): # Insert when sel is empty to not select the contents if r.empty(): self.view.insert(edit, r.a, text) else: self.view.replace(edit, r, text)
def show_panel_or_open(self, fn, sym, line, col, text): win = sublime.active_window() self._current_res = list() if sym: for name, _, pos in win.lookup_symbol_in_index(sym): if name.endswith(fn): line, col = pos self._current_res.append((name, line, col, "f")) else: fn = fn.replace('/', os.sep) all_folders = win.folders() + [os.path.dirname(v.file_name()) for v in win.views() if v.file_name()] for folder in set(all_folders): for root, _, _ in os.walk(folder): name = os.path.abspath(os.path.join(root, fn)) if os.path.isfile(name): self._current_res.append((name, line or 0, col or 0, "f")) if os.path.isdir(name): self._current_res.append((name, 0, 0, "d")) if os.path.isfile(fn): # check for full path self._current_res.append((fn, line or 0, col or 0, "f")) elif os.path.isdir(fn): self._current_res.append((fn, 0, 0, "d")) self._current_res = list(set(self._current_res)) if not self._current_res: sublime.error_message('File was not found\n\n\t%s' % fn) if len(self._current_res) == 1: self._on_panel_selection(0) else: entries = [self._format_res(res) for res in self._current_res] win.show_quick_panel(entries, self._on_panel_selection)
def __createArchiveFilename(self): # Create our archive filename, from the mask in our settings. # Split filename int dir, base, and extension, then apply our mask path_base, extension = os.path.splitext(self.view.file_name()) dir = os.path.dirname(path_base) base = os.path.basename(path_base) sep = os.sep # Now build our new filename try: # This could fail, if someone messed up the mask in the # settings. So, if it did fail, use our default. archive_filename = self.archive_org_filemask.format( dir=dir, base=base, ext=extension, sep=sep) except: # Use our default mask archive_filename = self.archive_org_default_filemask.format( dir=dir, base=base, ext=extension, sep=sep) # Display error, letting the user know sublime.error_message(u"Error:\n\nInvalid filemask:{0}\nUsing default: {1}".format( self.archive_org_filemask, self.archive_org_default_filemask)) return archive_filename
def run_prettier(self, source, node_path, prettier_cli_path, prettier_args): self._error_message = None if self.is_str_none_or_empty(node_path): cmd = [prettier_cli_path] \ + ['--stdin'] \ + ['--color=false'] \ + prettier_args else: cmd = [node_path] \ + [prettier_cli_path] \ + ['--stdin'] \ + ['--color=false'] \ + prettier_args try: self.show_debug_message( 'Prettier CLI Command', self.list_to_str(cmd)) proc = Popen( cmd, stdin=PIPE, stderr=PIPE, stdout=PIPE, env=self.proc_env, shell=self.is_windows()) stdout, stderr = proc.communicate(input=source.encode('utf-8')) if stderr or proc.returncode != 0: self.format_error_message( stderr.decode('utf-8'), str(proc.returncode)) return None return stdout.decode('utf-8') except OSError as ex: sublime.error_message('{0} - {1}'.format(PLUGIN_NAME, ex)) raise
def process_status(self, vcs, path): global file_status_cache settings = sublime.load_settings('Tortoise.sublime-settings') if path in file_status_cache and file_status_cache[path]['time'] > \ time.time() - settings.get('cache_length'): if settings.get('debug'): print 'Fetching cached status for %s' % path return file_status_cache[path]['status'] if settings.get('debug'): start_time = time.time() try: status = vcs.check_status(path) except (Exception) as (exception): sublime.error_message(str(exception)) file_status_cache[path] = { 'time': time.time() + settings.get('cache_length'), 'status': status } if settings.get('debug'): print 'Fetching status for %s in %s seconds' % (path, str(time.time() - start_time)) return status
def create_class_file(self, info): """ Create a specified Java class and returns the status @param info: class informations """ contents = self.get_file_contents(info) if contents is None: return False if os.path.exists(info["file"]): sublime.error_message( "{class_type} \"{class_name}\" already exists".format_map({ "class_type": self.args["create_type"], "class_name": info["class_name"] }) ) return False open(info["file"], "w").close() view = sublime.active_window().open_file(info["file"]) view.set_syntax_file("Packages/Java/Java.tmLanguage") # File Header override view.settings().set("enable_add_template_to_empty_file", False) sublime.set_timeout( lambda: self.insert_and_save(view, contents, info), 100 ) return True
def on_done(self, text=""): """ Create a class with informations from the input text @param text: text from input panel """ self.hide_status() info = self.parse_create(text) if isinstance(info, str): sublime.error_message(info) return ActionHistory().add_action( "javatar.commands.create.create_class.on_done", "Create [info={info}]".format_map({ "info": info }) ) if JavaUtils().create_package_path( info["directory"], True) == JavaUtils().CREATE_ERROR: return if self.create_class_file(info): sublime.set_timeout(lambda: StatusManager().show_status( "{class_type} \"{class_name}\" is created within".format_map({ "class_type": self.args["create_type"], "class_name": info["class_name"] }) + " package \"{readable_package_path}\"".format_map({ "readable_package_path": JavaUtils().to_readable_class_path( info["package"].as_class_path(), as_class_path=True ) }) ), 500)
def on_input(self, input): if not input: sublime.error_message("Please input job ids that is separated by ','") return job_ids = input.split(",") processor.handle_close_jobs_thread(job_ids)
def execute(self, filelist, root_path): exceptions = [] for file_obj in filelist: file_url = file_obj['url'] file_ext = os.path.splitext(file_url)[1] file_name = file_obj['name'] locations = file_obj['locations'] try: contents = self.read_file(file_url) except DownloadError as e: exceptions.append('Could not load ' + file_url + '. [Reason]: ' + e.value) sublime.error_message("Unable to download:\n " + file_url + "\nReason:\n " + e.value + "\nNote: Sublime Text 2 on Linux cannot deal with https urls.") continue for location in locations: directory = os.path.join(root_path, location) # try to create directory listing if not present. try: os.makedirs(directory) except OSError as e: # if it is just reporting that it exists, fail silently. if e.errno != errno.EEXIST: raise e # write to location. filepath = os.path.join(directory, file_name + file_ext) self.write_file(contents, filepath) return exceptions
def get_lint_version(cls): """ Return the Pylint version as a (x, y, z) tuple """ pylint_path = cls.get_or('pylint_path', None) python_bin = cls.get_or('python_bin', 'python') found = None regex = re.compile(b"[lint.py|pylint] ([0-9]+).([0-9]+).([0-9]+)") if pylint_path: command = [python_bin, pylint_path] else: command = list(DEFAULT_PYLINT_COMMAND) command.append("--version") try: p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=STARTUPINFO) output, _ = p.communicate() found = regex.search(output) except OSError: msg = "Pylinter could not find '%s'" % command[-2] sublime.error_message(msg) if found: found = found.groups() if len(found) == 3: version = tuple(int(v) for v in found) speak("Pylint version %s found" % str(version)) return version speak("Could not determine Pylint version") return (1, 0, 0)
def update_build_settings(self, settings): val = settings.get("ANSI_process_trigger", "on_finish") if val in ["on_finish", "on_data"]: self.process_trigger = val else: self.process_trigger = None sublime.error_message("ANSIescape settings warning:\n\nThe setting ANSI_process_trigger has been set to an invalid value; must be one of 'on_finish' or 'on_data'.")
def curl_convert(self, data): try: import subprocess # It looks like the text does NOT need to be escaped and # surrounded with double quotes. # Tested in ubuntu 13.10, python 2.7.5+ shell_safe_json = data.decode("utf-8") curl_args = [ "curl", "-H", "Content-Type: application/json", "-d", shell_safe_json, "https://api.github.com/markdown", ] github_oauth_token = self.settings.get("github_oauth_token") if github_oauth_token: curl_args[1:1] = ["-u", github_oauth_token] markdown_html = subprocess.Popen(curl_args, stdout=subprocess.PIPE).communicate()[0].decode("utf-8") return markdown_html except subprocess.CalledProcessError: sublime.error_message( "cannot use github API to convert markdown. SSL is not included in your Python installation. And using curl didn't work either" ) return None
def parser_specific_convert(self, markdown_text): import subprocess binary = self.settings.get("multimarkdown_binary", "") if os.path.exists(binary): cmd = [binary] critic_mode = self.settings.get("strip_critic_marks", "accept") if critic_mode in ("accept", "reject"): cmd.append("-a" if critic_mode == "accept" else "-r") sublime.status_message("converting markdown with multimarkdown...") if sublime.platform() == "windows": startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen( cmd, startupinfo=startupinfo, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) else: p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) for line in markdown_text.split("\n"): p.stdin.write((line + "\n").encode("utf-8")) markdown_html = p.communicate()[0].decode("utf-8") if p.returncode: # Log info to console sublime.error_message("Could not convert file! See console for more info.") print(markdown_html) markdown_html = _CANNOT_CONVERT else: sublime.error_message("Cannot find multimarkdown binary!") markdown_html = _CANNOT_CONVERT return markdown_html
def SearchFor(view, text, searchurl): if not searchurl: # see if we have an extension match first, then use default settings = sublime.load_settings(__name__ + '.sublime-settings') filename, ext = os.path.splitext(view.file_name()) typesettings = settings.get('searchanywhere_type_searchengine', []) foundsetting = False for typesetting in typesettings: if typesetting['extension'] == ext: foundsetting = True searchurl = typesetting['searchurl'] if not foundsetting: if settings.has('searchanywhere_searchurl'): searchurl = settings.get('searchanywhere_searchurl') else: sublime.error_message(__name__ + ': No Search Engine selected') return else: # search url is provided by the caller pass url = searchurl.replace('{0}', text.replace(' ','%20')) webbrowser.open_new_tab(url)
def open_in_browser(cls, path, browser="default"): if browser == "default": if sys.platform == "darwin": # To open HTML files, Mac OS the open command uses the file # associated with .html. For many developers this is Sublime, # not the default browser. Getting the right value is # embarrassingly difficult. import shlex import subprocess env = {"VERSIONER_PERL_PREFER_32_BIT": "true"} raw = """perl -MMac::InternetConfig -le 'print +(GetICHelper "http")[1]'""" process = subprocess.Popen(shlex.split(raw), env=env, stdout=subprocess.PIPE) out, err = process.communicate() default_browser = out.strip().decode("utf-8") cmd = "open -a '%s' %s" % (default_browser, path) os.system(cmd) else: desktop.open(path) sublime.status_message("Markdown preview launched in default browser") else: cmd = '"%s" %s' % (browser, path) if sys.platform == "darwin": cmd = "open -a %s" % cmd elif sys.platform == "linux2": cmd += " &" elif sys.platform == "win32": cmd = 'start "" %s' % cmd result = os.system(cmd) if result != 0: sublime.error_message('cannot execute "%s" Please check your Markdown Preview settings' % browser) else: sublime.status_message("Markdown preview launched in %s" % browser)
def run(self, edit): selections = self.get_selections() CompilerCall = self.get_minifier() if CompilerCall is None: sublime.error_message('Please focus on the file you wish to minify.') else: threads = [] for sel in selections: selbody = self.view.substr(sel) thread = CompilerCall( sel, selbody, timeout=self.settings.get('timeout', 5), level=self.settings.get('optimization_level', 'WHITESPACE_ONLY'), rm_new_lines=self.settings.get('remove_new_lines', False)) threads.append(thread) thread.start() # Wait for threads for thread in threads: thread.join() selections.clear() self.handle_threads(edit, threads, selections, offset=0, i=0, dir=1)
def handle_cwd(self, new_dir): try: if new_dir[0] == "~": new_dir = os.getenv(self.home) + new_dir[1:] os.chdir(new_dir) except: sublime.error_message(new_dir + " does not exist")
def process_errors(self, lines, errlines): """ Process the error found """ view_id = self.view.id() PYLINTER_ERRORS[view_id] = {"visible": True} # if pylint raised any exceptions, propogate those to the user, for # instance, trying to disable a messaage id that does not exist if len(errlines) > 1: err = errlines[-2] if not err.startswith("No config file found"): sublime.error_message("Fatal pylint error:\n%s" % (errlines[-2])) for line in lines: mdic = re.match(P_PYLINT_ERROR, line) if mdic: m = mdic.groupdict() line_num = int(m['line']) - 1 if m['type'].lower() not in self.ignore: PYLINTER_ERRORS[view_id][line_num] = \ "%s%s: %s " % (m['type'], m['errno'], m['msg'].strip()) speak(PYLINTER_ERRORS[view_id][line_num]) if len(PYLINTER_ERRORS[view_id]) <= 1: speak("No errors found") PylinterCommand.show_errors(self.view)
def __init__(self, caption, initial_text, on_done, on_change, on_cancel, create_from, with_files, pick_first, case_sensitive, log_in_status_bar, log_template, browser_action={}, start_with_browser=False, no_browser_action=False, browser_index=None): self.user_on_done = on_done self.user_on_change = on_change self.user_on_cancel = on_cancel self.caption = caption self.initial_text = initial_text self.log_template = log_template self.browser_action = browser_action self.no_browser_action = no_browser_action self.browser_index = browser_index self.create_from = create_from if self.create_from: self.create_from = computer_friendly(self.create_from) if not os.path.isdir(self.create_from): if os.path.exists(self.create_from): sublime.error_message( "This path exists, but doesn't seem to be a directory. " " Please report this (see link in the console)") raise ValueError( "This path exists, but doesn't seem to be a directory. " "Here's the path {0}. Please report this bug here: " "https://github.com/math2001/FileManager/issues". format(self.create_from)) sublime.error_message( 'The path `create_from` should exists. {0!r} does not ' " exists.".format(self.create_from)) raise ValueError( 'The path create from does not exists ({0!r})'.format( self.create_from)) self.browser = StdClass('Browser') self.browser.path = self.create_from self.browser.items = [] self.with_files = with_files self.pick_first = pick_first self.case_sensitive = case_sensitive self.path_to_create_choosed_from_browsing = False self.window = sublime.active_window() self.view = self.window.active_view() self.log_in_status_bar = log_in_status_bar if start_with_browser: self.browsing_on_done() else: self.create_input()
def show_error(self, error): sublime.error_message(error)
def run(self, edit): # get view and location of first selection, which we expect to be just the cursor position view = self.view point = view.sel()[0].b print(point) # Only trigger within LaTeX # Note using score_selector rather than match_selector if not view.score_selector(point, "text.tex.latex"): return try: completions, prefix, post_snippet, new_point_a, new_point_b = get_ref_completions(view, point) except UnrecognizedRefFormatError: sublime.error_message("Not a recognized format for reference completion") return # filter! Note matching is "less fuzzy" than ST2. Room for improvement... completions = [c for c in completions if prefix in c] # Note we now generate refs on the fly. Less copying of vectors! Win! def on_done(i): print("latex_ref_completion called with index %d" % (i,)) # Allow user to cancel if i < 0: return ref = completions[i] + post_snippet # Replace ref expression with reference and possibly post_snippet # The "latex_tools_replace" command is defined in # latex_ref_cite_completions.py view.run_command( "latex_tools_replace", { "a": new_point_a, "b": new_point_b, "replacement": ref } ) # Unselect the replaced region and leave the caret at the end caret = view.sel()[0].b view.sel().subtract(view.sel()[0]) view.sel().add(sublime.Region(caret, caret)) completions_length = len(completions) if completions_length == 0: sublime.error_message("No label matches %s !" % (prefix,)) elif completions_length == 1: view.run_command( "latex_tools_replace", { "a": new_point_a, "b": new_point_b, "replacement": completions[0] + post_snippet } ) # Unselect the replaced region and leave the caret at the end caret = view.sel()[0].b view.sel().subtract(view.sel()[0]) view.sel().add(sublime.Region(caret, caret)) else: view.window().show_quick_panel(completions, on_done)
def run(self, command='blame', branch=None): view = self.window.active_view() if not view: return file_name = view.file_name() if not file_name: return dirpath = os.path.dirname(file_name) repo_relative_path = git(['git', 'ls-files', '--full-name', file_name], dirpath) upstream_url = remote_url('upstream', dirpath) origin_url = remote_url('origin', dirpath) if not origin_url: sublime.error_message('Could not determine origin URL.') return local_branch_name = git(['git', 'rev-parse', '--abbrev-ref', 'HEAD'], dirpath) remote_branch_name = None remote_base = None # Check if branch exists on upstream, use that if available. if upstream_url: try: git([ 'git', 'rev-parse', 'refs/remotes/upstream/%s' % (local_branch_name) ], dirpath) remote_branch_name = local_branch_name remote_base = upstream_url except subprocess.CalledProcessError: pass if not remote_branch_name: # Check if branch is available in origin. try: actual_origin_branch = git( ['git', 'rev-parse', '--abbrev-ref', '@{u}'], dirpath) assert actual_origin_branch.startswith('origin/') remote_branch_name = actual_origin_branch[7:] remote_base = origin_url except subprocess.CalledProcessError: pass if not remote_branch_name: # Fall back to master. remote_branch_name = 'master' if upstream_url: remote_base = upstream_url else: remote_base = origin_url if branch != None: # Let the caller override it. remote_branch_name = branch if upstream_url: remote_base = upstream_url else: remote_base = origin_url line = view.rowcol(view.sel()[0].begin())[0] + 1 to_open = '%s/%s/%s/%s#L%i' % ( remote_base, command, remote_branch_name, repo_relative_path, line) print('open %r' % (to_open, )) webbrowser.open(to_open)
def _handle_error(self, error: 'Dict[str, Any]') -> None: self.view.erase_status("lsp_workspace_symbols") reason = error.get("message", "none provided by server :(") msg = "command 'workspace/symbol' failed. Reason: {}".format(reason) sublime.error_message(msg)
def run(self): view = self.window.active_view() binding_info = view.settings().get('requester.binding_info', None) if binding_info is None: return file, original_request = binding_info if not file or not original_request: return try: request = parse_requests(view.substr(sublime.Region( 0, view.size())), n=1)[0] except Exception as e: sublime.error_message( 'Save Error: there are no valid requests in your response view: {}' .format(e)) if request.startswith('requests.'): request = request[len('requests.'):] if not os.path.isfile(file): sublime.error_message( 'Save Error: requester file\n"{}"\nno longer exists'.format( file)) return is_open = bool(self.window.find_open_file(file)) requester_view = self.window.open_file(file) def save_request(): """Wait on another thread for view to load on main thread, then save. """ for i in range(40): # don't wait more than 2s if requester_view.is_loading(): time.sleep(.05) else: break content = requester_view.substr( sublime.Region(0, requester_view.size())) try: start_index = content.index(original_request) except ValueError: sublime.error_message( 'Save Error: your original request was modified since you first sent it!' ) return # this is necessary for reasons due to undocumented behavior in ST API (probably a bug) # simply calling `requester_view.replace` corrupts `view`s settings requester_view.run_command( 'requester_replace_text', { 'text': request, 'start_index': start_index, 'end_index': start_index + len(original_request) }) requester_view.sel().clear() requester_view.sel().add(sublime.Region(start_index)) if not is_open: # hacky trick to make sure scroll works time.sleep(.2) else: time.sleep(.1) requester_view.show_at_center(start_index) set_save_info_on_view(view, request) sublime.set_timeout_async(save_request, 0)
filename = os.path.split(filepath)[1] return os.path.join(get_backup_path(filepath), timestamp_file(filename)) ########NEW FILE######## __FILENAME__ = win32helpers import os import re import sublime try: import _winreg except ImportError: if sublime.platform() == 'windows': sublime.error_message( 'There was an error importing the _winreg module required by the Automatic Backups plugin.' ) def _substenv(m): return os.environ.get(m.group(1), m.group(0)) def get_shell_folder(name): """Returns the shell folder with the given name, eg "AppData", "Personal", "Programs". Environment variables in values of type REG_EXPAND_SZ are expanded if possible.""" HKCU = _winreg.HKEY_CURRENT_USER USER_SHELL_FOLDERS = \ r'Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'
def prepare_request(request, env, ordering): """Parse and evaluate args and kwargs in request string under context of env. Also, prepare request string: if request is not prefixed with "{var_name}.", prefix request with "requests." Accepts a request string and returns a `Request` instance. Finally, ensure request can time out so it doesn't hang indefinitely. http://docs.python-requests.org/en/master/user/advanced/#timeouts """ settings = sublime.load_settings('Requester.sublime-settings') req = prepend_library(request) session = None if not req.startswith('requests.'): session = req.split('.')[0] index = req.index('(') method = req[:index].split('.')[1].strip().upper() env['__parse_args__'] = parse_args try: args, kwargs = eval('__parse_args__{}'.format(req[index:]), env) except Exception as e: sublime.error_message('PrepareRequest Error: {}\n{}'.format( e, truncate(req, 150))) return Request(req, method, None, [], {}, ordering, session, {}, error=str(e)) else: args = list(args) url_from_kwargs = True url = kwargs.get('url', None) if url is None: url_from_kwargs = False try: url = args[0] except Exception as e: sublime.error_message('PrepareRequest Error: {}\n{}'.format( e, truncate(req, 150))) return Request(req, method, url, args, kwargs, ordering, session, {}, error=str(e)) if 'explore' in kwargs: req, e_url = kwargs.pop('explore') req = replace_method(prepend_library(req), 'get') if not same_domain(prepend_scheme(e_url), prepend_scheme(url)): # if explore URL does't have same domain as URL, remove auth kwargs from req kwargs.pop('params', None) kwargs.pop('headers', None) kwargs.pop('cookies', None) kwargs.pop('auth', None) req = replace_url(req, e_url, replace_all=True) else: req = replace_url(req, e_url, replace_all=False) url = prepend_scheme(e_url) method = 'GET' else: url = prepend_scheme(url) if url_from_kwargs: kwargs['url'] = url else: args[0] = url error = None fmt = kwargs.pop('fmt', settings.get('fmt', None)) if fmt not in ('raw', 'indent', 'indent_sort'): error = 'invalid `fmt`, must be one of ("raw", "indent", "indent_sort")' sublime.error_message('PrepareRequest Error: {}\n{}'.format( error, truncate(req, 150))) name = kwargs.pop('name', None) # cache response to "chain" requests tabname = kwargs.pop('tabname', None) # custom response tab name if tabname and type(tabname) is not str: error = 'invalid `tabname`, must be a string' sublime.error_message('PrepareRequest Error: {}\n{}'.format( error, truncate(req, 150))) skwargs = {'fmt': fmt, 'name': name, 'tabname': tabname} if 'filename' in kwargs: skwargs['filename'] = str(kwargs.pop('filename')) if 'streamed' in kwargs: skwargs['streamed'] = str(kwargs.pop('streamed')) if 'chunked' in kwargs: skwargs['chunked'] = str(kwargs.pop('chunked')) if 'gql' in kwargs: skwargs['gql'] = kwargs.pop('gql') gqlargs = {'query': skwargs['gql']} if 'gqlv' in kwargs: gqlargs['variables'] = kwargs.pop('gqlv') if 'gqlo' in kwargs: gqlargs['operationName'] = kwargs.pop('gqlo') if method == 'GET': kwargs['params'] = gqlargs if method == 'POST': kwargs['json'] = gqlargs if 'timeout' not in kwargs: kwargs['timeout'] = settings.get('timeout', None) if 'allow_redirects' not in kwargs: kwargs['allow_redirects'] = settings.get('allow_redirects', True) return Request(req, method, url, args, kwargs, ordering, session, skwargs, error)
markdown_html = urllib2.urlopen(request).read().decode('utf-8') except urllib2.HTTPError, e: if e.code == 401: sublime.error_message( 'github API auth failed. Please check your OAuth token.' ) else: sublime.error_message( 'github API responded in an unfashion way :/') except urllib2.URLError: sublime.error_message( 'cannot use github API to convert markdown. SSL is not included in your Python installation' ) except: sublime.error_message( 'cannot use github API to convert markdown. Please check your settings.' ) else: sublime.status_message( 'converted markdown with github API successfully') else: # convert the markdown enabled_extras = set( settings.get('enabled_extensions', [ 'footnotes', 'toc', 'fenced-code-blocks', 'cuddled-lists' ])) if settings.get("enable_mathjax") is True or settings.get( "enable_highlight") is True: enabled_extras.add('code-friendly') markdown_html = markdown2.markdown(markdown, extras=list(enabled_extras))
def run(self, cmd="", file_regex="", path=""): # Try to handle killing if hasattr( self, 'proc' ) and self.proc: # if we are running, try to kill running process self.output("\n\n### Got request to terminate compilation ###") self.proc.kill() self.proc = None return else: # either it's the first time we run, or else we have no running processes self.proc = None view = self.window.active_view() self.file_name = getTeXRoot.get_tex_root(view) if not os.path.isfile(self.file_name): sublime.error_message(self.file_name + ": file not found.") return self.tex_base, self.tex_ext = os.path.splitext(self.file_name) tex_dir = os.path.dirname(self.file_name) # Extra paths self.path = path # Output panel: from exec.py if not hasattr(self, 'output_view'): self.output_view = self.window.get_output_panel("exec") # Dumb, but required for the moment for the output panel to be picked # up as the result buffer self.window.get_output_panel("exec") self.output_view.settings().set( "result_file_regex", "^([^:\n\r]*):([0-9]+):?([0-9]+)?:? (.*)$") # self.output_view.settings().set("result_line_regex", line_regex) self.output_view.settings().set("result_base_dir", tex_dir) self.window.run_command("show_panel", {"panel": "output.exec"}) # Get parameters from sublime-build file: self.make_cmd = cmd # I actually think self.file_name is it already self.engine = 'pdflatex' # Standard pdflatex for line in codecs.open(self.file_name, "r", "UTF-8", "ignore").readlines(): if not line.startswith('%'): break else: # We have a comment match; check for a TS-program match mroot = re.match( r"%\s*!TEX\s+(?:TS-)?program *= *(xelatex|lualatex|pdflatex)\s*$", line) if mroot: # Sanity checks if "texify" == self.make_cmd[0]: sublime.error_message( "Sorry, cannot select engine using a %!TEX program directive on MikTeX." ) return if not ("$pdflatex = '%E" in self.make_cmd[3]): sublime.error_message( "You are using a custom LaTeX.sublime-build file (in User maybe?). Cannot select engine using a %!TEX program directive." ) return self.engine = mroot.group(1) break if self.engine != 'pdflatex': # Since pdflatex is standard, we do not output a msg. for it. self.output("Using engine " + self.engine + "\n") self.make_cmd[3] = self.make_cmd[3].replace("%E", self.engine) self.output_view.settings().set("result_file_regex", file_regex) if view.is_dirty(): print("saving...") view.run_command('save') # call this on view, not self.window if self.tex_ext.upper() != ".TEX": sublime.error_message( "%s is not a TeX source file: cannot compile." % (os.path.basename(view.file_name()), )) return s = platform.system() if s == "Darwin": self.encoding = "UTF-8" elif s == "Windows": self.encoding = getOEMCP() elif s == "Linux": self.encoding = "UTF-8" else: sublime.error_message("Platform as yet unsupported. Sorry!") return print(self.make_cmd + [self.file_name]) os.chdir(tex_dir) CmdThread(self).start() print(threading.active_count())
def show_error_dialog(message): """Show an error message dialog.""" sublime.error_message(message)
def run(self, edit, target='browser'): region = sublime.Region(0, self.view.size()) contents = self.get_contents(region) markdown_html = self.convert_markdown(contents) full_html = u'<!DOCTYPE html>' full_html += '<html><head><meta charset="utf-8">' full_html += self.getCSS() full_html += self.getHighlight() full_html += self.getMathJax() full_html += '</head><body>' full_html += markdown_html full_html += '</body>' full_html += '</html>' if target in ['disk', 'browser']: # check if LiveReload ST2 extension installed and add its script to the resulting HTML livereload_installed = ('LiveReload' in os.listdir(sublime.packages_path())) # build the html if livereload_installed: full_html += '<script>document.write(\'<script src="http://\' + (location.host || \'localhost\').split(\':\')[0] + \':35729/livereload.js?snipver=1"></\' + \'script>\')</script>' # update output html file tmp_fullpath = getTempMarkdownPreviewPath(self.view) tmp_html = open(tmp_fullpath, 'w') tmp_html.write(full_html.encode('utf-8')) tmp_html.close() # now opens in browser if needed if target == 'browser': config_browser = settings.get('browser') if config_browser and config_browser != 'default': cmd = '"%s" %s' % (config_browser, tmp_fullpath) if sys.platform == 'darwin': cmd = "open -a %s" % cmd elif sys.platform == 'linux2': cmd += ' &' result = os.system(cmd) if result != 0: sublime.error_message( 'cannot execute "%s" Please check your Markdown Preview settings' % config_browser) else: sublime.status_message( 'Markdown preview launched in %s' % config_browser) else: desktop.open(tmp_fullpath) sublime.status_message( 'Markdown preview launched in default html viewer') elif target == 'sublime': # create a new buffer and paste the output HTML new_view = self.view.window().new_file() new_view.set_scratch(True) new_edit = new_view.begin_edit() new_view.insert(new_edit, 0, markdown_html) new_view.end_edit(new_edit) sublime.status_message('Markdown preview launched in sublime') elif target == 'clipboard': # clipboard copy the full HTML sublime.set_clipboard(full_html) sublime.status_message('Markdown export copied to clipboard')
def on_done(self, themename): if not themename: sublime.error_message("No theme name provided") else: settings.set("DefaultTheme", themename) sublime.save_settings("hugofy.sublime-settings")
def get_integer(self, input): try: number = int(input) self.insert({'number': number}) except: sublime.error_message('Must be an integer')
in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. """ try: import sublime import ctypes except: sublime.error_message("""\ Unfortunately ctypes can't be imported, so SublimeClang will not work. There is a work around for this to get it to work, \ please see http://www.github.com/quarnster/SublimeClang for more details. """) from clang import cindex import sublime_plugin from sublime import Region import sublime import os import re import threading import time import Queue from errormarkers import clear_error_marks, add_error_mark, show_error_marks, \ update_statusbar, erase_error_marks, set_clang_view
def _handle_curl_error(self, error): sublime.error_message( self.CURL_ERRORS.get(error, "%s: %s" % (self.ERR_UNKNOWN_CODE, error)))
def getComparableFiles(self): self.viewsList = [] self.viewsPaths = [] active = self.window.active_view() allViews = self.window.views() ratios = [] if config.merge_settings.get('intelligent_files_sort'): original = os.path.split(active.file_name()) for view in allViews: if view.file_name() != None and view.file_name( ) != active.file_name() and ( not config.merge_settings.get('same_syntax_only') or view.settings().get('syntax') == active.settings().get('syntax')): f = view.file_name() ratio = 0 if config.merge_settings.get('intelligent_files_sort'): ratio = difflib.SequenceMatcher( None, original[1], os.path.split(f)[1]).ratio() ratios.append({'ratio': ratio, 'file': f, 'dirname': ''}) ratiosLength = len(ratios) if ratiosLength > 0: ratios = sorted(ratios, key=self.cmp_to_key(self.sortFiles)) if config.merge_settings.get('compact_files_list'): for i in range(ratiosLength): for j in range(ratiosLength): if i != j: sp1 = os.path.split(ratios[i]['file']) sp2 = os.path.split(ratios[j]['file']) if sp1[1] == sp2[1]: ratios[i][ 'dirname'] = self.getFirstDifferentDir( sp1[0], sp2[0]) ratios[j][ 'dirname'] = self.getFirstDifferentDir( sp2[0], sp1[0]) for f in ratios: self.viewsPaths.append(f['file']) self.viewsList.append( self.prepareListItem(f['file'], f['dirname'])) sublime.set_timeout(lambda: self.window.show_quick_panel( self.viewsList, self.onListSelect), 0) #timeout for ST3 else: # if config.merge_settings.get('same_syntax_only'): # syntax = re.match('(.+)\.tmLanguage$', os.path.split(active.settings().get('syntax'))[1]) # if syntax != None: # sublime.error_message('There are no other open ' + syntax.group(1) + ' files to compare') # return sublime.error_message('There are no other open files to compare')
def on_cancel(self): sublime.error_message("No filename provided")
def convertLess2Css(self, lessc_command, dirs, file='', minimised=True, outputFile=''): out = '' # get the plugin settings settings = self.getSettings() # get the current file & its css variant # if no file was specified take the file name if the current view if file == "": less = self.view.file_name().encode("utf_8") else: less = file # if the file name doesn't end on .less, stop processing it if not less.endswith(".less"): return '' # check if an output file has been specified if outputFile != "": # if the outputfile doesn't end on .css make sure that it does by appending .css if not outputFile.endswith(".css"): css = outputFile + ".css" else: css = outputFile else: # when no output file is specified we take the name of the less file and substitute .less with .css if settings['min_name']: css = re.sub('\.less$', '.min.css', less) else: css = re.sub('\.less$', '.css', less) # Check if the CSS file should be written to the same folder as where the LESS file is if (dirs['same_dir']): # set the folder for the CSS file to the same folder as the LESS file dirs['css'] = os.path.dirname(less) elif (dirs['shadow_folders']): # replace less in the path with css, this will shadow the less folder structure dirs['css'] = re.sub('less', 'css', os.path.dirname(less)) # get the file name of the CSS file, including the extension sub_path = os.path.basename(css) # css file name # combine the folder for the CSS file with the file name, this will be our target css = os.path.join(dirs['css'], sub_path) # create directories # get the name of the folder where we need to save the CSS file output_dir = os.path.dirname(css) # if the folder doesn't exist, create it if not os.path.isdir(output_dir): os.makedirs(output_dir) # if no alternate compiler has been specified, pick the default one if not lessc_command: lessc_command = "lessc" # get the name of the platform (ie are we running on windows) platform_name = platform.system() # check if the compiler should create a minified CSS file if minimised: # create the command for calling the compiler cmd = [lessc_command, less, css, "-x", "--verbose"] # when running on Windows we need to add an additional parameter to the call if platform_name == 'Windows': cmd[3] = '-compress' else: # the call for non minified CSS is the same on all platforms cmd = [lessc_command, less, css, "--verbose"] print("[less2css] Converting " + less + " to " + css) # check if we're compiling with the default compiler if lessc_command == "lessc": # check if we're on Windows if platform.system() == 'Windows': # change command from lessc to lessc.cmd on Windows, # only lessc.cmd works but lessc doesn't cmd[0] = 'lessc.cmd' else: # if is not Windows, modify the PATH env = os.getenv('PATH') env = env + ':/usr/local/bin:/usr/local/sbin' os.environ['PATH'] = env # check for the existance of the less compiler, exit if it can't be located if subprocess.call(['which', lessc_command]) == 1: return sublime.error_message( 'less2css error: `lessc` is not available') #run compiler, catch an errors that might come up try: # not sure if node outputs on stderr or stdout so capture both p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) except OSError as err: # an error has occured, stop processing the file any further return sublime.error_message('less2css error: ' + str(err)) stdout, stderr = p.communicate() # create a regex to match all blank lines and control characters blank_line_re = re.compile('(^\s+$)|(\033\[[^m]*m)', re.M) # take the result text returned from node and convert it to UTF-8 out = stderr.decode("utf_8") # use the regex to replace all blank lines and control characters with an empty string out = blank_line_re.sub('', out) # if out is empty it means the LESS file was succesfuly compiled to CSS, else we will print the error if out == '': print('[less2css] Convert completed!') else: print('----[less2cc] Compile Error----') print(out) return out
def output_error_message(output, *args, **kwargs): # print('error', output, args, kwargs) sublime.error_message(output)
libs_path = os.path.join(pkg_path, 'libs') PPA_PATH.append(libs_path) versionlibs_path = os.path.join(pkg_path, 'libs', 'py' + PYMAMI) if os.path.exists(versionlibs_path): PPA_PATH.append(versionlibs_path) print('Included directory to sys.path :', PPA_PATH) [sys.path.insert(0, p) for p in PPA_PATH if p not in sys.path] try: import autopep8 import MergeUtils except: sublime.error_message('{0}: import error: {1}'.format( PLUGIN_NAME, sys.exc_info()[1])) raise class PythonPEP8Autoformat(object): def __init__(self): self.settings = sublime.load_settings(SETTINGS_FILE) def get_options(self): cmd_args = list() cmd_args.extend(['--aggressive'] * self.settings.get('aggressive', 0)) if self.settings.get('list-fixes', False): cmd_args.append('--list-fixes') if self.settings.get('ignore', False): cmd_args.append('--ignore={0}'.format(','.join([
def error_callback(self, string): string = str(string) self.reset_hide() self.just_error = True sublime.error_message('MavensMate: ' + string)
def run(self, direction="down", always_split=False, split_fraction=0.35, use_available=False, **kwargs): window = self.window direction = direction.strip().lower() if direction not in ('up', 'down', 'left', 'right'): raise ValueError("bad direction: {0}".format(direction)) if 'working_dir' in kwargs: kwargs['cwd'] = kwargs.pop('working_dir') if 'config_name' not in kwargs: kwargs['config_name'] = 'Default' Terminus, origami = import_companions() if Terminus is None: sublime.error_message("split-open terminal requires the " "Terminus plugin") return if origami is None: terminus_open(window, kwargs) _emit_no_origami_msg() else: cells = window.get_layout()['cells'] rows = window.get_layout()['rows'] cols = window.get_layout()['cols'] current_cell = cells[window.active_group()] # iaxis = {'left': 0, 'right': 0, 'up': 1, 'down': 1}[direction] # idir = {'left': 0, 'up': 1, 'right': 2, 'down': 3}[direction] adjacent_cells = origami.cells_adjacent_to_cell_in_direction( cells, current_cell, direction) lone_in_direction = not bool(adjacent_cells) if direction == 'down': extreme_group = [tup[3] for tup in cells].index(argmax(rows)) elif direction == 'up': extreme_group = [tup[1] for tup in cells].index(argmin(rows)) elif direction == 'left': extreme_group = [tup[0] for tup in cells].index(argmin(cols)) elif direction == 'right': extreme_group = [tup[2] for tup in cells].index(argmax(cols)) extreme_group_views = window.views_in_group(extreme_group) extreme_group_has_views = bool(extreme_group_views) extreme_group_has_terminal = any( view.settings().get('terminus_view', False) for view in extreme_group_views) # print("cells:", cells) # print("current_cell:", current_cell) # print("rows:", rows) # print("cols:", cols) # print("Lone in direction?", lone_in_direction) # print("Extreme Group", extreme_group) # print("extreme_group_has_views", extreme_group_has_views) # print("adjacent_cells", adjacent_cells) # this logic is becoming silly... available_view = None if use_available: groups_to_check = list(range(window.num_groups())) groups_to_check.pop(extreme_group) groups_to_check.insert(0, extreme_group) for group in groups_to_check: try: active_view = window.active_view_in_group(group) if view_is_available_terminal(active_view): available_view = active_view break except NotATerminal: pass if available_view is not None: window.focus_view(available_view) window.run_command("terminus_keypress", args={ "key": "u", "ctrl": True }) for hook in kwargs.pop('post_window_hooks', []): print("window running...", hook) window.run_command(*hook) for hook in kwargs.pop('post_view_hooks', []): print("view running...", hook) available_view.run_command(*hook) else: if always_split: do_split, start_from = True, extreme_group elif lone_in_direction and not extreme_group_has_views: do_split, start_from = True, extreme_group elif extreme_group_has_terminal: do_split, start_from = False, extreme_group elif not extreme_group_has_views: do_split, start_from = False, extreme_group else: do_split, start_from = True, extreme_group window.focus_group(start_from) if do_split: window.run_command("create_pane", args={ "direction": direction, "give_focus": True }) window.run_command("zoom_pane", args={"fraction": split_fraction}) terminus_open(window, kwargs)
def error_message(self, msg): sublime.error_message(msg)
def _finish(self, err=None): self._is_running = False for view in self.window.views(): view.erase_status('YetAnotherCodeSearch') if err: sublime.error_message(str(err))
from sys import exc_info from subprocess import PIPE, Popen, STDOUT from sublime import error_message, message_dialog, packages_path, run_command try: import sublime_helper selection = sublime_helper.selection substr = sublime_helper.substr PanelCommand = sublime_helper.command.PanelCommand SafeCommand = sublime_helper.command.SafeCommand pkg = sublime_helper.package(__file__) settings = pkg.settings except Exception, e: path = relpath(__file__, packages_path()) line = exc_info()[2].tb_lineno error_message("""python%s\n%s line %s:\n %s:\n%s""" % (python_version(), path, line, type(e), str(e))) def open_doc(): url = "www.postgresql.org/docs/9.2/static/libpq-pgpass.html" run_command("open_url", {"url": url}) if not pkg.user.settings.exists: pass #pkg.user.settings.open() #message_dialog("edit PostgreSQL connection settings") #open_doc()
def convertLess2Css(self, lessc_command, dirs, less_file=''): args = [] # get the current file & its css variant # if no file was specified take the file name if the current view if not less_file: less_file = self.file_name # if the current file name doesn't end on .less, stop processing it if not self.view.file_name().endswith(".less"): return '' css_file_name = self.output_file_name(less_file) # Check if the CSS file should be written to the same folder as # where the LESS file is css_dir = dirs['css'] if dirs['same_dir']: # set the folder for the CSS file to the same # folder as the LESS file css_dir = os.path.dirname(less_file) elif dirs['shadow_folders']: print( '[less2css] Using shadowed folders: outputting to {}'.format( dirs['css'] ) ) replacement = css_file_name.replace( dirs['less'], '' ) # Strip off the slash this can cause issue within windows file paths css_dir = os.path.join( dirs['css'], os.path.dirname(replacement.strip('/').strip('\\')) ) # get the file name of the CSS file, including the extension sub_path = os.path.basename(css_file_name) # css file name # combine the folder for the CSS file with the file name, this # will be our target css_file_name = os.path.join(css_dir, sub_path) # create directories # get the name of the folder where we need to save the CSS file output_dir = os.path.dirname(css_file_name) # if the folder doesn't exist, create it if not os.path.isdir(output_dir): os.makedirs(output_dir) # if no alternate compiler has been specified, pick the default one if (type(lessc_command) is not str) or (not lessc_command): lessc_command = 'lessc' else: print('[less2css] Using less compiler :: {}'.format(lessc_command)) # check if we're compiling with the default compiler if lessc_command == "lessc": if IS_WINDOWS: # change command from lessc to lessc.cmd on Windows, # only lessc.cmd works but lessc doesn't lessc_command = 'lessc.cmd' else: # if is not Windows, modify the PATH env = os.getenv('PATH') env = env + ':/usr/bin:/usr/local/bin:/usr/local/sbin' os.environ['PATH'] = env # check for the existance of the less compiler, # exit if it can't be located if subprocess.call(['which', lessc_command]) == 1: return sublime.error_message( 'less2css error: `lessc` is not available' ) # check if the compiler should create a minified CSS file _minifier = None if self.settings['minimised'] is True: _minifier = '--clean-css' elif type(self.settings.get('minimised')) is str: _minifier = self.settings.get('minimised', '') if _minifier: print('[less2css] Using minifier : '+_minifier) args.append(_minifier) if self.settings['create_css_source_maps']: args.append('--source-map') print('[less2css] Using css source maps') if self.settings['autoprefix']: args.append('--autoprefix') print('[less2css] add prefixes to {}'.format(css_file_name)) # you must opt in to disable this option if not self.settings['disable_verbose']: args.append('--verbose') print('[less2css] Using verbose mode') if self.settings['silent']: args.append('--silent') print('[less2css] Disabled warnings') print("[less2css] Converting " + less_file + " to " + css_file_name) if IS_WINDOWS: command = lessc_command + ' ' + ' '.join(args) + ' ' + less_file + ' ' + css_file_name else: command = list( itertools.chain.from_iterable( [[lessc_command], args, [less_file, css_file_name]] ) ) #run compiler, catch an errors that might come up try: # not sure if node outputs on stderr or stdout so capture both if IS_WINDOWS: # this startupinfo structure prevents a console window from popping up on Windows startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW p = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, startupinfo=startupinfo ) else: p = subprocess.Popen( command, stdout=subprocess.PIPE, stderr=subprocess.PIPE ) except OSError as err: # an error has occured, stop processing the file any further return sublime.error_message('less2css error: ' + str(err)) stdout, stderr = p.communicate() # create a regex to match all blank lines and control characters blank_line_re = re.compile('(^\s+$)|(\033\[[^m]*m)', re.M) # take the result text returned from node and convert it to UTF-8 out = stderr.decode("utf_8") # use the regex to replace all blank lines and control characters # with an empty string out = blank_line_re.sub('', out) # if out is empty it means the LESS file was succesfuly compiled to CSS, # else we will print the error if not out: print('[less2css] Convert completed!') else: print('----[less2cc] Compile Error----') print(out) return out
def _emit_no_origami_msg(): sublime.error_message("The Origami plugin must be installed to " "split-open a terminal window")
def em(*msgs, **kwargs): sublime.error_message(kwargs.get('sep', ' ').join([str(msg) for msg in msgs]))
def git_binary_path(self): """ Return the path to the available `git` binary. """ global git_path, error_message_displayed if not git_path: git_path_setting = self.savvy_settings.get("git_path") if isinstance(git_path_setting, dict): git_path = git_path_setting.get(sublime.platform()) if not git_path: git_path = git_path_setting.get('default') else: git_path = git_path_setting if not git_path: git_path = shutil.which("git") try: startupinfo = None if os.name == "nt": startupinfo = subprocess.STARTUPINFO() startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW stdout = subprocess.check_output( [git_path, "--version"], stderr=subprocess.PIPE, startupinfo=startupinfo).decode("utf-8") except Exception: stdout = "" git_path = None match = re.match(r"git version ([0-9]+)\.([0-9]+)\.([0-9]+)", stdout) if match: major = int(match.group(1)) minor = int(match.group(2)) patch = int(match.group(3)) if major < GIT_REQUIRE_MAJOR \ or (major == GIT_REQUIRE_MAJOR and minor < GIT_REQUIRE_MINOR) \ or (major == GIT_REQUIRE_MAJOR and minor == GIT_REQUIRE_MINOR and patch < GIT_REQUIRE_PATCH): msg = GIT_TOO_OLD_MSG.format(GIT_REQUIRE_MAJOR, GIT_REQUIRE_MINOR, GIT_REQUIRE_PATCH) git_path = None if not error_message_displayed: sublime.error_message(msg) error_message_displayed = True raise ValueError("Git binary too old.") if not git_path: msg = ( "Your Git binary cannot be found. If it is installed, add it " "to your PATH environment variable, or add a `git_path` setting " "in the GitSavvy settings.") if not error_message_displayed: sublime.error_message(msg) error_message_displayed = True raise ValueError("Git binary not found.") return git_path