Python sublime 模块,error_message() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用sublime.error_message()

项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
def extract_path(cmd, delim=':'):
    """Return the user's PATH as a colon-delimited list."""
    from . import persist
    persist.debug('user shell:', cmd[0])

    out = run_shell_cmd(cmd).decode()
    path = out.split('__SUBL_PATH__', 2)

    if len(path) > 1:
        path = path[1]
        return ':'.join(path.strip().split(delim))
    else:
        persist.printf('Could not parse shell PATH output:\n' + (out if out else '<empty>'))
        sublime.error_message(
            'SublimeLinter could not determine your shell PATH. '
            'It is unlikely that any linters will work. '
            '\n\n'
            'Please see the troubleshooting guide for info on how to debug PATH problems.')
        return ''
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
def run_terminal(self, dir_, parameters):
        try:
            if not dir_:
                raise NotFoundError('The file open in the selected view has ' +
                    'not yet been saved')
            for k, v in enumerate(parameters):
                parameters[k] = v.replace('%CWD%', dir_)
            args = [TerminalSelector.get()]
            args.extend(parameters)
            encoding = locale.getpreferredencoding(do_setlocale=True)
            if sys.version_info >= (3,):
                cwd = dir_
            else:
                cwd = dir_.encode(encoding)
            subprocess.Popen(args, cwd=cwd)

        except (OSError) as exception:
            print(str(exception))
            sublime.error_message('Terminal: The terminal ' +
                TerminalSelector.get() + ' was not found')
        except (Exception) as exception:
            sublime.error_message('Terminal: ' + str(exception))
项目:PhaserSublimePackage    作者:PhaserEditor2D    | 项目源码 | 文件源码
def start_server(project):
  if not tern_command: return None
  if time.time() - project.last_failed < 30: return None
  env = None
  if platform.system() == "Darwin":
    env = os.environ.copy()
    env["PATH"] += ":/usr/local/bin"
  proc = subprocess.Popen(tern_command + tern_arguments, cwd=project.dir, env=env,
                          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT, shell=windows)
  output = ""

  while True:
    line = proc.stdout.readline().decode("utf-8")
    if not line:
      sublime.error_message("Failed to start server" + (output and ":\n" + output))
      project.last_failed = time.time()
      return None
    match = re.match("Listening on port (\\d+)", line)
    if match:
      project.proc = proc
      return int(match.group(1))
    else:
      output += line
项目:PhaserSublimePackage    作者:PhaserEditor2D    | 项目源码 | 文件源码
def run(self, edit, **args):
    data = run_command(self.view, {"type": "definition", "lineCharPositions": True})
    if data is None: return
    file = data.get("file", None)
    if file is not None:
      # Found an actual definition
      row, col = self.view.rowcol(self.view.sel()[0].b)
      cur_pos = self.view.file_name() + ":" + str(row + 1) + ":" + str(col + 1)
      jump_stack.append(cur_pos)
      if len(jump_stack) > 50: jump_stack.pop(0)
      real_file = (os.path.join(get_pfile(self.view).project.dir, file) +
        ":" + str(data["start"]["line"] + 1) + ":" + str(data["start"]["ch"] + 1))
      sublime.active_window().open_file(real_file, sublime.ENCODED_POSITION)
    else:
      url = data.get("url", None)
      if url is None:
        sublime.error_message("Could not find a definition")
      else:
        webbrowser.open(url)
项目:sublime_libsass    作者:blitzrk    | 项目源码 | 文件源码
def compile_deps(path, config):
    files, root = deps.get(path)
    config['root'] = root
    config['file'] = path

    autoload_frameworks(config)

    struct = config["output"]["structure"]
    if not struct or struct == "nested":
        return compile.nested(files, config)
    elif type(struct) is list and len(struct) is 2 and struct[0] == "nested":
        return compile.nested(files, config, struct[1])
    elif struct == "flat":
        return compile.flat(files, config)
    else:
        sublime.error_message(u"Unknown output structure: {0}".format(struct))
        return
项目:sublime_libsass    作者:blitzrk    | 项目源码 | 文件源码
def _compile(files, config, outfile_for):
    flags = to_flags(config['compile'])

    compiled = []
    for f in files:
        in_file  = os.path.join(config['root'], f)
        out_file = outfile_for(f)

        # Make sure output folder exists
        mkdir_p(os.path.dirname(out_file))

        command = [sass.path] + flags + [in_file, out_file]
        p = Popen(command, stdout=PIPE, stderr=PIPE, **_platform_opts)
        out, err = p.communicate()

        if err:
            print(u"Error: {0}".format(err))
            print(u"Command: {0}".format(" ".join(command)))
            sublime.error_message(u"Failed to compile {0}\n\nView error with Ctrl+`".format(f))
            return

        compiled.append(f)

    return compiled
项目:sublime_libsass    作者:blitzrk    | 项目源码 | 文件源码
def guess_root(file):
    '''
    For projects without .libsass.json configs, search for the most distant
    parent directory that still has a .sass or .scss file
    '''

    def is_sass(file):
        ext = os.path.splitext(file)[1]
        return ext in ['.sass', '.scss']

    for i, path in enumerate(subpaths(file)):
        (_, _, files) = next(os.walk(path))
        if not any([is_sass(f) for f in files]):
            break

    if not is_sass(file):
        sublime.error_message("Please save the file")

    assert is_sass(file)
    assert i > 0

    return subpaths(file)[i-1]
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
def _run(self, thread, count=0):
        """Evaluate environment in a separate thread and show an activity
        indicator. Inspect thread at regular intervals until it's finished, at
        which point `make_requests` can be invoked. Return if thread times out.
        """
        REFRESH_MULTIPLIER = 2
        activity = self.get_activity_indicator(count//REFRESH_MULTIPLIER, self.ACTIVITY_SPACES)
        if count > 0:  # don't distract user with RequesterEnv status if env can be evaluated quickly
            self.view.set_status('requester.activity', '{} {}'.format('RequesterEnv', activity))

        if thread.is_alive():
            timeout = self.config.get('timeout_env', None)
            if timeout is not None and count * self.REFRESH_MS/REFRESH_MULTIPLIER > timeout * 1000:
                sublime.error_message('Timeout Error: environment took too long to parse')
                self.view.set_status('requester.activity', '')
                return
            sublime.set_timeout(lambda: self._run(thread, count+1), self.REFRESH_MS/REFRESH_MULTIPLIER)

        else:
            requests = self.get_requests()
            self.view.set_status('requester.activity', '')
            self.make_requests(requests, self._env)
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
def get_env_dict_from_string(s):
        """What it sounds like.

        http://stackoverflow.com/questions/5362771/load-module-from-string-in-python
        """
        try:
            del sys.modules['requester.env']  # this avoids a subtle bug, DON'T REMOVE
        except KeyError:
            pass

        if not s:
            return {}

        env = imp.new_module('requester.env')
        try:
            exec(s, env.__dict__)
        except Exception as e:
            sublime.error_message('EnvBlock Error:\n{}'.format(e))
            return {}
        else:
            return dict(env.__dict__)
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
def run(self, edit, back):
        view = self.view
        if not view.settings().get('requester.response_view', False):
            return
        reqs = load_history(rev=False)
        index = view.settings().get('requester.request_history_index', len(reqs)-1)
        total = len(reqs)

        if back:
            index -= 1
        else:
            index += 1
        if index < 0 or index >= len(reqs):
            return

        try:
            params_dict = reqs[index][1]
        except IndexError as e:
            sublime.error_message('RequestHistory Error: {}'.format(e))
            return
        view.settings().set('requester.request_history_index', index)
        populate_staging_view(view, total-index-1, total, **params_dict)
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
def run_initial_request(self, req, filename):
        requests_method = getattr(requests, req.method.lower())
        try:
            res = requests_method(*req.args, stream=True, **req.kwargs)
        except Exception as e:
            sublime.error_message('Download Error: {}'.format(e))
            return

        response = Response(req, res, None)
        self.handle_response(response)
        self.handle_responses([response])
        self.persist_requests([response])  # persist initial request before starting download

        if res.status_code != 200:
            sublime.error_message(
                'Download Error: response status code is not 200\n\n{}'.format(truncate(res.text, 500))
            )
            if sublime.load_settings('Requester.sublime-settings').get('only_download_for_200', True):
                return
        self.download_file(res, filename)
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
def run(self, edit):
        curls = self.get_curls()
        requests = []
        for curl in curls:
            try:
                request = curl_to_request(curl)
            except Exception as e:
                sublime.error_message('Conversion Error: {}'.format(e))
                traceback.print_exc()
            else:
                requests.append(request)

        if not requests:
            return

        header = '# import from cURL'
        view = self.view.window().new_file()
        view.run_command('requester_replace_view_text',
                         {'text': header + '\n\n\n' + '\n\n\n'.join(requests) + '\n', 'point': 0})
        view.set_syntax_file('Packages/Requester/syntax/requester-source.sublime-syntax')
        view.set_name('requests')
        view.set_scratch(True)
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
def get_curls(self):
        """Parses curls from multiple selections. If nothing is highlighted,
        cursor's current line is taken as selection.
        """
        view = self.view
        curls = []
        for region in view.sel():
            if not region.empty():
                selection = view.substr(region)
            else:
                selection = view.substr(view.line(region))
            try:
                curls_ = self.parse_curls(selection)
            except Exception as e:
                sublime.error_message('Parse Error: {}'.format(e))
                traceback.print_exc()
            else:
                for curl in curls_:
                    curls.append(curl)
        return curls
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
def get_requests(self):
        """Parses only first highlighted selection.
        """
        view = self.view
        self._tests = []

        for region in view.sel():
            if not region.empty():
                selection = view.substr(region)
            try:
                self._tests = parse_tests(selection)
            except Exception as e:
                sublime.error_message('Parse Error: there may be unbalanced brackets in tests')
                print(e)
            break  # only parse first selection

        return [test.request for test in self._tests]
项目:Requester    作者:kylebebak    | 项目源码 | 文件源码
def get_requests(self):
        """Parses URL from first selection, and passes it in special `explore` arg
        to call to requests.
        """
        view = self.view
        if not view or not view.settings().get('requester.response_view', False):
            sublime.error_message('Explore Error: you can only explore URLs from response tabs')
            return []

        try:
            url = view.substr(view.sel()[0]).replace('"', '')
        except:
            return []
        if not url:
            return []
        self._explore_url = url

        try:
            request = self.get_replay_request()
        except:
            return []
        unclosed = request[:-1].strip()
        if unclosed[-1] == ',':
            unclosed = unclosed[:-1]
        return ["{}, explore=({}, {}))".format(unclosed, repr(request), repr(url))]
项目:docphp    作者:garveen    | 项目源码 | 文件源码
def plugin_loaded():
    global currentSettings, language, currentView
    currentSettings = sublime.load_settings(setting_file)
    language = currentSettings.get('language')
    currentView = sublime.active_window().active_view()

    docphpPath = getDocphpPath()
    if not os.path.isdir(docphpPath + 'language'):
        os.makedirs(docphpPath + 'language')

    if not callable(sublime_symbol.symbol_at_point) or not callable(sublime_symbol.navigate_to_symbol):
        sublime.error_message('Cannot find symbol_at_point from Default.sublime-package\n\nPlease restore the file which usually replaced by outdated localizations')

    from package_control import events

    if events.install(package_name) or not language:
        currentView.run_command('docphp_checkout_language', {"is_init": True, "set_fallback": True})
项目:docphp    作者:garveen    | 项目源码 | 文件源码
def languageExists(languageName=None, fallback=False):
    if not languageName:
        languageName = language
    if not language:
        currentView.run_command('docphp_checkout_language', {"is_init": True, "set_fallback": True})
        return False
    if languageName not in docphp_languages and not loadLanguage():
        if fallback:
            begin = 'The fallback'
        else:
            begin = 'The'
        print(getAllLanguages())
        show_name = getAllLanguages()[languageName]['name']
        sublime.error_message(begin + ' language "' + show_name +
                              '" has not yet installed.\nYou can use\n\n   DocPHP: checkout language\n\ncommand to checkout a language pack.')
        return False
    return True
项目:SublimeRemoteGDB    作者:summerwinter    | 项目源码 | 文件源码
def load_settings(self, project_dir):
        project_setting_file = RemoteGDBSettings.project_setting_file(project_dir)
        if not os.path.exists(project_setting_file):
            return False

        try:
            with open(project_setting_file) as data_file:
                json_str = ""
                for line in data_file.readlines():
                    line = line.strip()
                    if len(line) == 0:
                        continue
                    if line.startswith("//"):
                        continue
                    json_str += line
                    json_str += "\n"
                self.data = json.loads(json_str)
        except Exception as err:
            print(err)
            # sublime.error_message("some errors exist in project setting file!")
            return False

        return True
项目:sublime-phoenix-beagle    作者:noma4i    | 项目源码 | 文件源码
def run(self, index=None, **args):
        command = args.get('command')
        active_file_path = self.__active_file_path()
        active_folders = sublime.active_window().folders()
        if command == 'mlist':
            self.__beagle = Phoenix(active_file_path + 'beagle_migrations', self.__patterns(), active_folders)
            self.window.show_quick_panel(self.__beagle.descriptions(), self.__open_file)
        else:
            if not active_folders:
                active_folders = os.path.split(active_file_path)[0]
                sublime.error_message("SideBar is empty!")
            if active_file_path:
                if self.__patterns():
                    self.__beagle = Phoenix(active_file_path, self.__patterns(), active_folders)
                    self.window.show_quick_panel(self.__beagle.descriptions(), self.__open_file)
                else:
                    self.__status_msg("Patterns are not loaded!")
            else:
                self.__status_msg("No open files")
项目:Spandoc    作者:geniusupgrader    | 项目源码 | 文件源码
def get_transformation_list(self, settings, view):
        '''Generates a ranked list of available transformations.'''

        # score the transformations and rank them
        ranked = {}
        for label, setting in settings['transformations'].items():
            for scope in setting['scope']:
                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
        transformation_list = list(OrderedDict(sorted(
            ranked.items(), key=lambda t: t[1])).keys())
        transformation_list.reverse()
        return transformation_list
项目:Spandoc    作者:geniusupgrader    | 项目源码 | 文件源码
def load_folder_settings_file(folder_settings_file):

    try:
        folder_settings_file = open(folder_settings_file, "r")
    except IOError as e:
        sublime.error_message("Error: spandoc.json exists, but could not be read. Exception: " + str(e))
        folder_settings_file.close()
    else:
        settings_file_commented = folder_settings_file.read()
        folder_settings_file.close()
        # debug("settings_file_commented: " + str(settings_file_commented))

        try:
            settings_file = sublime.decode_value(settings_file_commented)
        except (KeyError, ValueError) as e:
            sublime.error_message("JSON Error: Cannot parse spandoc.json. See console for details. Exception: " + str(e))
            return None
        # debug("settings_file: " + str(settings_file))

    return settings_file
项目:SublimeOutline    作者:warmdev    | 项目源码 | 文件源码
def calc_width(view):
    '''
    return float width, which must be
        0.0 < width < 1.0 (other values acceptable, but cause unfriendly layout)
    used in show.show() and "outline_select" command with other_group=True
    '''
    width = view.settings().get('outline_width', 0.3)
    if isinstance(width, float):
        width -= width//1  # must be less than 1
    elif isinstance(width, int if ST3 else long):  # assume it is pixels
        wport = view.viewport_extent()[0]
        width = 1 - round((wport - width) / wport, 2)
        if width >= 1:
            width = 0.9
    else:
        sublime.error_message(u'FileBrowser:\n\noutline_width set to '
                              u'unacceptable type "%s", please change it.\n\n'
                              u'Fallback to default 0.3 for now.' % type(width))
        width = 0.3
    return width or 0.1  # avoid 0.0
项目:.sublime    作者:cxdongjack    | 项目源码 | 文件源码
def on_done(self, paths, relative_to_project, name):
        if relative_to_project or s.get('new_folders_relative_to_project_root', False):
            paths = SideBarProject().getDirectories()
            if paths:
                paths = [SideBarItem(paths[0], True)]
            if not paths:
                paths = SideBarSelection(paths).getSelectedDirectoriesOrDirnames()
        else:
            paths = SideBarSelection(paths).getSelectedDirectoriesOrDirnames()

        for item in paths:
            item = SideBarItem(item.join(name), True)
            if item.exists():
                sublime.error_message("Unable to create folder, folder or file exists.")
                self.run(paths, name)
                return
            else:
                item.create()
                if not item.exists():
                    sublime.error_message("Unable to create folder:\n\n"+item.path())
                    self.run(paths, name)
                    return
        SideBarProject().refresh();
项目:.sublime    作者:cxdongjack    | 项目源码 | 文件源码
def run(self, paths = [], application = "", extensions = "", args=[]):
        application_dir, application_name = os.path.split(application)

        if extensions == '*':
            extensions = '.*'
        if extensions == '':
            items = SideBarSelection(paths).getSelectedItems()
        else:
            items = SideBarSelection(paths).getSelectedFilesWithExtension(extensions)
        import subprocess
        try:
            for item in items:
                if sublime.platform() == 'osx':
                    subprocess.Popen(['open', '-a', application] + args + [item.name()], cwd=item.dirname())
                elif sublime.platform() == 'windows':
                    subprocess.Popen([application_name] + args + [escapeCMDWindows(item.path())], cwd=expandVars(application_dir), shell=True)
                else:
                    subprocess.Popen([application_name] + args + [escapeCMDWindows(item.name())], cwd=item.dirname())
        except:
            sublime.error_message('Unable to "Open With..", probably incorrect path to application.')
项目:.sublime    作者:cxdongjack    | 项目源码 | 文件源码
def run(self):
        old = self.old
        new = self.new
        key = self.key
        window_set_status(key, 'Duplicating…')

        item = SideBarItem(old, os.path.isdir(old))
        try:
            if not item.copy(new):
                window_set_status(key, '')
                if SideBarItem(new, os.path.isdir(new)).overwrite():
                    self.run()
                else:
                    SideBarDuplicateCommand(sublime_plugin.WindowCommand).run([old], new)
                return
        except:
            window_set_status(key, '')
            sublime.error_message("Unable to copy:\n\n"+old+"\n\nto\n\n"+new)
            SideBarDuplicateCommand(sublime_plugin.WindowCommand).run([old], new)
            return
        item = SideBarItem(new, os.path.isdir(new))
        if item.isFile():
            item.edit();
        SideBarProject().refresh();
        window_set_status(key, '')
项目:MarkdownLivePreview    作者:math2001    | 项目源码 | 文件源码
def get_base64_saver(loading, url):
    def callback(content):
        if isinstance(content, urllib.error.HTTPError):
            if content.getcode() == 404:
                loading[url] = 404
                return
        elif isinstance(content, urllib.error.URLError):
            if (content.reason.errno == 11001 and
                content.reason.strerror == 'getaddrinfo failed'):
                loading[url] = 404
                return
            return sublime.error_message('An unexpected error has occured: ' +
                                         str(content))
        loading[url] = to_base64(content=content)

    return callback
项目:EasyClangComplete    作者:niosus    | 项目源码 | 文件源码
def _get_apple_clang_version_str(cls, output_text):
        version_regex = re.compile("\d\.\d\.*\d*")
        match = version_regex.search(output_text)
        if match:
            version_str = match.group()
            # throw away the patch number
            osx_version = version_str[:3]
            try:
                # info from this table:
                # https://gist.github.com/yamaya/2924292
                version_str = OSX_CLANG_VERSION_DICT[osx_version]
            except Exception as e:
                sublime.error_message("Version '{}' of AppleClang is not "
                                      "supported yet. Please open an issue "
                                      "for it".format(osx_version))
                raise e
            log.warning("OSX version %s reported. Reducing it to %s.",
                        osx_version,
                        version_str)
            log.info("Found clang version %s", version_str)
            return version_str
        else:
            raise RuntimeError(" Couldn't find clang version in clang version "
                               "output.")
项目:EasyClangComplete    作者:niosus    | 项目源码 | 文件源码
def info(self, tooltip_request, settings):
        """Provide information about object in given location.

        Using the current translation unit it queries libclang for available
        information about cursor.

        Args:
            tooltip_request (tools.ActionRequest): A request for action
                from the plugin.
            settings: All plugin settings.

        Returns:
            (tools.ActionRequest, str): completion request along with the
                info details read from the translation unit.
        """
        # This is a dummy implementation that just shows an error to the user.
        sublime.error_message(DUMMY_INFO_MSG)
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def extract_path(cmd, delim=':'):
    """Return the user's PATH as a colon-delimited list."""
    from . import persist
    persist.debug('user shell:', cmd[0])

    out = run_shell_cmd(cmd).decode()
    path = out.split('__SUBL_PATH__', 2)

    if len(path) > 1:
        path = path[1]
        return ':'.join(path.strip().split(delim))
    else:
        persist.printf('Could not parse shell PATH output:\n' + (out if out else '<empty>'))
        sublime.error_message(
            'SublimeLinter could not determine your shell PATH. '
            'It is unlikely that any linters will work. '
            '\n\n'
            'Please see the troubleshooting guide for info on how to debug PATH problems.')
        return ''
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
def _wait_for_finish_and_notify_user(self, i=1, dir=-1):
        """ Displays animated Message as long as TSS is initing. Is recoursive function. """

        if self.get_initialisation_error_message():
            sublime.error_message('Typescript initializion error for : %s\n >>> %s\n ArcticTypescript is disabled until you restart sublime.'
                         % (self.project.tsconfigfile, self.get_initialisation_error_message()))
            set_plugin_temporarily_disabled()
            return

        if not self.is_initialized():
            (i, dir) = self._display_animated_init_message(i, dir)
            # recursive:
            sublime.set_timeout(lambda: self._wait_for_finish_and_notify_user(i, dir), 100)
        else:
            # starting finished ->
            MESSAGE.show('Typescript project intialized for file : %s' % self.project.tsconfigfile, True, with_panel=False)
            self.project.on_services_started()
项目:ElectricImp-Sublime    作者:electricimp    | 项目源码 | 文件源码
def entered_filename(self, filename):
        # Check if valid root specified for windows.
        if PLATFORM == "windows":
            if re.match(WIN_ROOT_REGEX, filename):
                root = filename[0:3]
                if not os.path.isdir(root):
                    sublime.error_message(root + " is not a valid root.")
                    self.clear()
                    return

        base, path = self.split_path(filename)
        file_path = generate_creation_path(self.settings, base, path, True)
        # Check for invalid alias specified.
        is_valid = (TOP_LEVEL_SPLIT_CHAR in filename and
                    not self.platform.is_absolute_path(base))
        if is_valid:
            if base == "":
                error_message = "Current file cannot be resolved."
            else:
                error_message = "'" + base + "' is an invalid alias."
            sublime.error_message(error_message)

        self.entered_file_action(file_path)
项目:ElectricImp-Sublime    作者:electricimp    | 项目源码 | 文件源码
def _delete_file(self, filepath):
        if not filepath:
            return
        elif not os.path.isfile(filepath):
            sublime.error_message("%s is not a file" % filepath)
            return

        if not sublime.ok_cancel_dialog("Delete this file?\n%s" % filepath):
            return

        vcs_tracking = (self.file_tracked_by_git(filepath) and
                        self.settings.get(VCS_MANAGEMENT_SETTING))

        self.close_view(filepath)

        if vcs_tracking:
            self._git_rm(filepath)
        else:
            self._execute_delete_file(filepath)

        self.refresh_sidebar()
项目:CMakeBuilder    作者:rwols    | 项目源码 | 文件源码
def run(self, index=None, name=None):
        if self.server.is_configuring:
            sublime.error_message("CMake is configuring, please wait.")
            return
        if not self.server.targets:
            sublime.error_message("No targets found! "
                                  "Did you configure the project?")
            return
        if name is not None:
            self._on_done(name)
        elif not index:
            self.items = [
                [t.name, t.type, t.directory] for t in self.server.targets]
            self.window.show_quick_panel(self.items, self._on_done)
        else:
            self._on_done(index)
项目:CMakeBuilder    作者:rwols    | 项目源码 | 文件源码
def _create_project(self):
        os.makedirs(self.project_dir, exist_ok=True)
        if not os.path.exists(self.project_dir):
            sublime.error_message("Could not create directory %s" % self.project_dir)
        os.makedirs(os.path.join(self.project_dir, "src"), exist_ok=True)
        with open(os.path.join(self.project_dir, "CMakeLists.txt"), "w") as f:
            f.write(CMAKELISTS_FILE.format(self.project_name, self.type))
        with open(os.path.join(self.project_dir, "src", "main." + self.suffix), "w") as f:
            if self.type == "C":
                f.write(CFILE)
            else:
                f.write(CXXFILE)
        with open(os.path.join(self.project_dir, "src", "CMakeLists.txt"), "w") as f:
            f.write(CMAKELISTS_SRC_FILE.format(self.suffix))
        project_file = os.path.join(self.project_dir, self.project_name + ".sublime-project")
        with open(project_file, "w") as f:
            f.write(PROJECTFILE)
        if sublime.ok_cancel_dialog('Select the file %s in "%s" in the upcoming prompt...' % (self.project_name + ".sublime-project", self.project_dir)):
            sublime.run_command("prompt_open_project_or_workspace")
项目:sublime-dired    作者:Twizzledrizzle    | 项目源码 | 文件源码
def _on_done(self, which, value):
        value = value.strip()
        if not value:
            return

        fqn = join(self.path, value)
        if exists(fqn):
            sublime.error_message('{} already exists'.format(fqn))
            return

        if which == 'directory':
            os.makedirs(fqn)
        else:
            open(fqn, 'wb')

        self.view.run_command('dired_refresh', {'goto': value})
项目:sublime-dired    作者:Twizzledrizzle    | 项目源码 | 文件源码
def _move(self, path):
        if path == self.path:
            return

        files = self.get_marked() or self.get_selected()

        if not isabs(path):
            path = join(self.path, path)
        if not isdir(path):
            sublime.error_message('Not a valid directory: {}'.format(path))
            return

        # Move all items into the target directory.  If the target directory was also selected,
        # ignore it.
        files = self.get_marked() or self.get_selected()
        path = normpath(path)
        for filename in files:
            fqn = normpath(join(self.path, filename))
            if fqn != path:
                shutil.move(fqn, path)
        self.view.run_command('dired_refresh')
项目:sublime-solium-gutter    作者:sey    | 项目源码 | 文件源码
def run_script_on_file(self, temp_file_path):
    try:
      node_path = PluginUtils.get_node_path()
      script_path = PLUGIN_FOLDER + "/scripts/run.js"
      file_path = self.view.file_name()
      cmd = [node_path, script_path, temp_file_path, file_path or "?"]
      output = SoliumGutterCommand.get_output(cmd)
      print(output)
      if output.find(OUTPUT_VALID) != -1:
        output = output.decode('utf-8');
        return output
      print(output)
      raise Exception(output)
    except:
      # Something bad happened.
      print("Unexpected error({0}): {1}".format(sys.exc_info()[0], sys.exc_info()[1]))

      # Usually, it's just node.js not being found. Try to alleviate the issue.
      msg = "Node.js was not found in the default path. Please specify the location."
      if not sublime.ok_cancel_dialog(msg):
        msg = "You won't be able to use this plugin without specifying the path to node.js."
        sublime.error_message(msg)
      else:
        PluginUtils.open_sublime_settings(self.view.window())
项目:sublime-PICO-8    作者:Neko250    | 项目源码 | 文件源码
def run(self, edit):
        def done(path):
            settings = sublime.load_settings("PICO-8.sublime-settings")
            settings.set("pico-8_path", path)
            sublime.save_settings("PICO-8.sublime-settings")
            return

        platform = sublime.platform()
        if platform == "linux":
            self.view.window().show_input_panel("PICO-8 Path", "/path/to/pico8", done, None, None)
        elif platform == "osx":
            self.view.window().show_input_panel("PICO-8 Path", "/path/to/PICO-8.app/Contents/MacOS/pico8", done, None, None)
        elif platform == "windows":
            self.view.window().show_input_panel("PICO-8 Path", "C:\\Program Files (x86)\\PICO-8\\pico8.exe", done, None, None)
        else:
            sublime.error_message("Error: could not resolve platform\n\n[\"linux\", \"osx\", \"windows\"]")
            return
项目:Codeforces-Sublime-Plugin    作者:karunk    | 项目源码 | 文件源码
def run(self):
        head, tail = os.path.split(self.window.active_view().file_name())
        CurrentWindowFileName = self.window.active_view().file_name().split('/')[-1].split('.')[0]
        CurrentWindowFileType = self.window.active_view().file_name().split('/')[-1].split('.')[-1]

        if os.path.isfile(CurrentWindowFileName) == False:
            sublime.error_message("You have not complied your solution! Build the executable using sublime text")
            return

        inputFile = CurrentWindowFileName+"_input.in"
        outputFile = CurrentWindowFileName+"_output.out"

        if os.path.isfile(inputFile) == False:
            print(os.path.isfile(inputFile), inputFile)
            sublime.error_message("Initialize the input first! Enter your custom testcases here")
            self.window.open_file(inputFile)
            return


        cmd = QuoteFunc(head + '/' + tail.split('.')[0])+"<"+QuoteFunc(head + '/' + inputFile)+">"+QuoteFunc(head + '/' + outputFile)
        command = Command(cmd)
        command.run(timeout = 3)
        self.window.open_file(outputFile)
项目:RemoteCpp    作者:ruibm    | 项目源码 | 文件源码
def show_file_input(view, title, on_done):
  file = STATE.file(view.file_name())
  if file == None:
    path = s_cwd()
    path = path + os.sep
  else:
    path = file.remote_path()
  def on_done_callback(new_file):
    log('The user has chosen: ' + new_file)
    cwd = s_cwd()
    if not new_file.startswith(cwd):
      sublime.error_message('File must be under CWD:\n\n' + cwd)
      return
    path = new_file[len(cwd) + 1:]
    file = File(cwd=cwd, path=path)
    on_done(file)
  view.window().show_input_panel(
      caption=title,
      initial_text=path,
      on_done=on_done_callback,
      on_change=None,
      on_cancel=None,
  )
项目:RemoteCpp    作者:ruibm    | 项目源码 | 文件源码
def _run_in_the_background(self, view, src_file, dst_file):
    try:
      ssh_cmd('mv "{src}" "{dst}"'.format(
          src=src_file.remote_path(),
          dst=dst_file.remote_path()))
    except:
      log_exception('Failed to mv remote files.')
      sublime.error_message(
          'Failed to move files remotely.\n\nSRC={src}\n\nDST={dst}'.format(
                src=src_file.remote_path(),
                dst=dst_file.remote_path()))
      return
    self._rm_local_file(src_file.local_path())
    self._rm_local_file(dst_file.local_path())
    Commands.open_file(self.view, dst_file.to_args())
    log(dir(self.view))
    view.close()
    STATE.update_list(cwd=s_cwd(view),
                      files_to_add=[dst_file],
                      files_to_rm=[src_file])
项目:ESLint-Formatter    作者:TheSavior    | 项目源码 | 文件源码
def run_script_on_file(self, data):
    try:
      dirname = os.path.dirname(data)
      node_path = PluginUtils.get_node_path()
      eslint_path = PluginUtils.get_eslint_path(dirname)

      if eslint_path == False:
        sublime.error_message('ESLint could not be found on your path')
        return;

      cmd = [node_path, eslint_path, '--fix', data]

      config_path = PluginUtils.get_pref("config_path")

      if os.path.isfile(config_path):
        # If config file path exists, use as is
        full_config_path = config_path
      else:
        # Find config gile relative to project path
        project_path = PluginUtils.project_path()
        full_config_path = os.path.join(project_path, config_path)

      if os.path.isfile(full_config_path):
        print("Using configuration from {0}".format(full_config_path))
        cmd.extend(["--config", full_config_path])

      if self.view.file_name():
          cdir = os.path.dirname(self.view.file_name())
      else:
          cdir = "/"

      output = PluginUtils.get_output(cmd, cdir, data)

      return output;

    except:
      # Something bad happened.
      msg = str(sys.exc_info()[1])
      print("Unexpected error({0}): {1}".format(sys.exc_info()[0], msg))
      sublime.error_message(msg)
项目:sublime-text-elixir-tests    作者:tarzan    | 项目源码 | 文件源码
def run(self, args):
    self.load_config()
    self.save_all()
    file = self.file_type(self.view.file_name())
    command = file.run_all_tests_command()
    if self.run_shell_command(command, file.get_project_root()):
      pass
    else:
      sublime.error_message("Only *.exs files supported!")
项目:sublime-text-elixir-tests    作者:tarzan    | 项目源码 | 文件源码
def file_name_input(self, file_name):
      full_path = os.path.join(self.selected_dir, file_name)

      if os.path.lexists(full_path):
          sublime.error_message('File already exists:\n%s' % full_path)
          return
      else:
          self.create_and_open_file(full_path)
项目:TerminalView    作者:Wramberg    | 项目源码 | 文件源码
def run(self,
            cmd="/bin/bash -l",
            title="Terminal",
            cwd=None,
            syntax=None,
            keep_open=False):
        """
        Open a new terminal view

        Args:
            cmd (str, optional): Shell to execute. Defaults to 'bash -l.
            title (str, optional): Terminal view title. Defaults to 'Terminal'.
            cwd (str, optional): The working dir to start out with. Defaults to
                                 either the currently open file, the currently
                                 open folder, $HOME, or "/", in that order of
                                 precedence. You may pass arbitrary snippet-like
                                 variables.
            syntax (str, optional): Syntax file to use in the view.
            keep_open (bool, optional): Keep view open after cmd exits.
        """
        if sublime.platform() not in ("linux", "osx"):
            sublime.error_message("TerminalView: Unsupported OS")
            return

        st_vars = self.window.extract_variables()
        if not cwd:
            cwd = "${file_path:${folder}}"
        cwd = sublime.expand_variables(cwd, st_vars)
        if not cwd:
            cwd = os.environ.get("HOME", None)
        if not cwd:
            # Last resort
            cwd = "/"

        args = {"cmd": cmd, "title": title, "cwd": cwd, "syntax": syntax, "keep_open": keep_open}
        self.window.new_file().run_command("terminal_view_activate", args=args)
项目:TerminalView    作者:Wramberg    | 项目源码 | 文件源码
def run(self, _, **kwargs):
        # Lookup the sublime buffer instance for this view the first time this
        # command is called
        if self._sub_buffer is None:
            self._sub_buffer = SublimeBufferManager.load_from_id(self.view.id())

        if type(kwargs["key"]) is not str:
            sublime.error_message("Terminal View: Got keypress with non-string key")
            return

        if "meta" in kwargs and kwargs["meta"]:
            sublime.error_message("Terminal View: Meta key is not supported yet")
            return

        if "meta" not in kwargs:
            kwargs["meta"] = False
        if "alt" not in kwargs:
            kwargs["alt"] = False
        if "ctrl" not in kwargs:
            kwargs["ctrl"] = False
        if "shift" not in kwargs:
            kwargs["shift"] = False

        # Lookup the sublime buffer instance for this view
        sublime_buffer = SublimeBufferManager.load_from_id(self.view.id())
        keypress_cb = sublime_buffer.keypress_callback()
        app_mode = sublime_buffer.terminal_emulator().application_mode_enabled()
        if keypress_cb:
            keypress_cb(kwargs["key"], kwargs["ctrl"], kwargs["alt"],
                        kwargs["shift"], kwargs["meta"], app_mode)
项目:sublime-commandbox    作者:Ortus-Solutions    | 项目源码 | 文件源码
def error_message(self, text):
        sublime.error_message("%s: %s" % (self.package_name, text))

    # Output view
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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)))
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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)
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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)