Python sublime.error_message() Examples

The following are 30 code examples of sublime.error_message(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module sublime , or try the search function .
Example #1
Source File: fuse.py    From Fuse.SublimePlugin with MIT License 6 votes vote down vote up
def on_done(self, file_name):
		try:
			log().info("Trying to create '" + self.full_path(file_name) +  "'")
			args = [getFusePathFromSettings(), "create", self.targetTemplate, file_name, self.targetFolder]
			try:
				proc = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
			except:
				gFuse.showFuseNotFound()
				return
			code = proc.wait()
			if code == 0:
				log().info("Succssfully created '" + self.full_path(file_name) +  "'")
				if self.targetTemplate != "app":
					self.window.open_file(self.full_path(file_name));
			else:
				out = "Could not create file:\n";
				out += self.full_path(file_name) + "\n";
				for line in proc.stdout.readlines():
					out += line.decode()
				error_message(out)
		except ValueError:
			pass 
Example #2
Source File: _generated_2018_02_11_at_20_21_24.py    From JavaScript-Completions with MIT License 6 votes vote down vote up
def exec_node(self, folder_path, node_command_args) :
      os.chdir(folder_path)
      from node.main import NodeJS
      node = NodeJS()
      animation_loader = AnimationLoader(["[=     ]", "[ =    ]", "[   =  ]", "[    = ]", "[     =]", "[    = ]", "[   =  ]", "[ =    ]"], 0.067, "Generating docs ")
      interval_animation = RepeatedTimer(animation_loader.sec, animation_loader.animate)
      result = node.execute("jsdoc", node_command_args, is_from_bin=True)
  
      if not result[0] :
        sublime.error_message(result[1])
  
      elif result[1].startswith("There are no input files to process") :
        sublime.error_message(result[1])
  
      animation_loader.on_complete()
      interval_animation.stop() 
Example #3
Source File: import_export.py    From Requester with MIT License 6 votes vote down vote up
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) 
Example #4
Source File: Hugofy.py    From Hugofy-sublime with MIT License 6 votes vote down vote up
def run(self,edit):
		setvars()
		server=settings.get("Server")
		startCmd = ["hugo", "server"]
		if server["THEME_FLAG"]:
			startCmd = startCmd + ["--theme={}".format(server["THEME"])]
		if server["DRAFTS_FLAG"]:
			startCmd = startCmd + ["--buildDrafts"]

		startCmd = startCmd + ["--watch", "--port={}".format(server["PORT"])] 

		try:
			out=subprocess.Popen(startCmd,stderr=subprocess.STDOUT,universal_newlines=True)
			sublime.status_message('Server Started: {}'.format(startCmd))
		except:
			sublime.error_message("Error starting server") 
Example #5
Source File: import_export.py    From Requester with MIT License 6 votes vote down vote up
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 
Example #6
Source File: commands.py    From sublime-text-virtualenv with MIT License 6 votes vote down vote up
def run(self, **kwargs):
        """Exec the command with virtualenv.

        If a virtualenv is active and valid update the build parameters
        as needed and call the built-in command.

        Else, if no virtualenv is active, do nothing and call the built-in
        command.

        Else, if the active virtualenv is invalid or corrupt display an error
        message and cancel execution.
        """
        try:
            venv = self.get_virtualenv(validate=True, **kwargs)
        except InvalidVirtualenv as error:
            sublime.error_message(str(error) + " Execution cancelled!")
        else:
            if venv:
                kwargs = self.update_exec_kwargs(venv, **kwargs)
                logger.info("Command executed with virtualenv \"{}\".".format(venv))
            super(VirtualenvExecCommand, self).run(**kwargs) 
Example #7
Source File: commands.py    From sublime-text-virtualenv with MIT License 6 votes vote down vote up
def add_directory(self, directory):
        """Add given directory to the list.

        If the path is not a directory show error dialog.
        """
        if not directory:
            return

        directory = os.path.expanduser(os.path.normpath(directory))
        if not os.path.isdir(directory):
            sublime.error_message("\"{}\" is not a directory.".format(directory))
            return

        directories = self.virtualenv_directories
        directories.append(directory)
        settings().set('virtualenv_directories', directories)
        settings.save() 
Example #8
Source File: test.py    From Requester with MIT License 6 votes vote down vote up
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] 
Example #9
Source File: request.py    From Requester with MIT License 6 votes vote down vote up
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))] 
Example #10
Source File: dired.py    From dired with MIT License 6 votes vote down vote up
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') 
Example #11
Source File: dired.py    From dired with MIT License 6 votes vote down vote up
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}) 
Example #12
Source File: GitConflictResolver.py    From sublime-GitConflictResolver with MIT License 6 votes vote down vote up
def run(self):
        # Reload settings
        settings.load()

        # Ensure git executable is available
        if not self.git_executable_available():
            sublime.error_message(msgs.get('git_executable_not_found'))
            return

        self.git_repo = self.determine_git_repo()
        if not self.git_repo:
            sublime.status_message(msgs.get('no_git_repo_found'))
            return

        conflict_files = self.get_conflict_files()
        if not conflict_files:
            sublime.status_message(msgs.get('no_conflict_files_found', self.git_repo))
            return

        self.show_quickpanel_selection(conflict_files) 
Example #13
Source File: sublime3dsmax.py    From sublime3dsmax with MIT License 6 votes vote down vote up
def run(self, edit):
        currentfile = self.view.file_name()
        if currentfile is None:
            sublime.error_message(constants.NOT_SAVED)
            return

        is_mxs = _is_maxscriptfile(currentfile)
        is_python = _is_pythonfile(currentfile)

        if is_mxs:
            cmd = 'fileIn @"{0}"\r\n'.format(currentfile)
            _send_cmd_to_max(cmd)
        elif is_python:
            cmd = 'python.executeFile @"{0}"\r\n'.format(currentfile)
            _send_cmd_to_max(cmd)
        else:
            sublime.error_message(constants.NO_SUPPORTED_FILE) 
Example #14
Source File: dired_file_operations.py    From SublimeFileBrowser with MIT License 6 votes vote down vote up
def on_done(self, value):
        value = value.strip()
        if not value:
            return False

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

        if self.which == 'directory':
            os.makedirs(fqn)
        else:
            with open(fqn, 'wb'):
                pass
        if self.refresh:  # user press enter
            emit_event(u'watch_view', self.view.id(), plugin=u'FileBrowserWFS')
            self.view.run_command('dired_refresh', {'goto': fqn})

        # user press ctrl+enter, no refresh
        return fqn 
Example #15
Source File: dired_file_operations.py    From SublimeFileBrowser with MIT License 6 votes vote down vote up
def run(self, edit):
        self.which = self.view.settings().get('which', '')
        if not self.which:
            return sublime.error_message('oops, does not work!')

        self.refresh = False
        value = self.view.substr(Region(0, self.view.size()))
        fqn = self.on_done(value)
        if not fqn:
            return sublime.status_message('oops, does not work!')

        sublime.active_window().run_command('hide_panel', {'cancel': True})

        dired_view = sublime.active_window().active_view()
        if dired_view.settings().has('dired_path'):
            self.refresh = True
        if self.which == 'directory':
            dired_view.settings().set('dired_path', fqn + os.sep)
        else:
            sublime.active_window().open_file(fqn)
        if self.refresh:
            emit_event(u'watch_view', dired_view.id(), plugin=u'FileBrowserWFS')
            dired_view.run_command('dired_refresh', {'goto': fqn}) 
Example #16
Source File: download.py    From Requester with MIT License 6 votes vote down vote up
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) 
Example #17
Source File: dired_file_operations.py    From SublimeFileBrowser with MIT License 6 votes vote down vote up
def run(self, edit):
        if not self.view.settings().has('rename'):
            # Shouldn't happen, but we want to cleanup when things go wrong.
            self.view.run_command('dired_refresh')
            return

        before = self.view.settings().get('rename')
        # We marked the set of files with a region.  Make sure the region still has the same
        # number of files.
        after  = self.get_after()

        if len(after) != len(before):
            return sublime.error_message('You cannot add or remove lines')

        if len(set(after)) != len(after):
            return self.report_conflicts(before, after)

        self.apply_renames(before, after)

        self.view.erase_regions('rename')
        self.view.settings().erase('rename')
        self.view.settings().set('dired_rename_mode', False)
        emit_event(u'watch_view', self.view.id(), plugin=u'FileBrowserWFS')
        self.view.run_command('dired_refresh', {'to_expand': self.re_expand_new_names()}) 
Example #18
Source File: fuse.py    From Fuse.SublimePlugin with MIT License 6 votes vote down vote up
def ensureDaemonIsRunning(self):
		if not self.interop.isConnected():
			try:
				path = getFusePathFromSettings()
				start_daemon = [path, "daemon", "-b"]
				log().info("Calling subprocess '%s'", str(start_daemon))
				if os.name == "nt":
					CREATE_NO_WINDOW = 0x08000000
					subprocess.check_output(start_daemon, creationflags=CREATE_NO_WINDOW, stderr=subprocess.STDOUT)
				else:
					subprocess.check_output(start_daemon, stderr=subprocess.STDOUT)
			except subprocess.CalledProcessError as e:
				log().error("Fuse returned exit status " + str(e.returncode) + ". Output was '" + e.output.decode("utf-8") + "'.")
				error_message("Error starting Fuse:\n\n" + e.output.decode("utf-8"))
				return
			except:
				log().error("Fuse not found: " + traceback.format_exc())
				gFuse.showFuseNotFound()
				return 
Example #19
Source File: hound.py    From SublimeHound with MIT License 6 votes vote down vote up
def run(self, edit):
        self.settings = sublime.load_settings(SETTINGS)
        self.hound_url = self.settings.get("hound_url").rstrip("/")
        self.github_base_url = self.settings.get("github_base_url")
        self.exclude_repos = set(self.settings.get("exclude_repos", []))
        self.custom_headers = self.settings.get("custom_headers", {})
        self.debug = self.settings.get("debug", False)
        if self.debug:
            logger.setLevel(logging.DEBUG)
            http.client.HTTPConnection.debuglevel = 1
        else:
            http.client.HTTPConnection.debuglevel = 0

        if self.hound_url == "" or self.github_base_url == "":
            self.settings.set("hound_url", self.hound_url)
            self.settings.set("github_base_url", self.github_base_url)
            sublime.save_settings(self.SETTINGS)  # save them so we have something to edit
            sublime.error_message("Please set your hound_url and github_base_url.")
            self.open_settings()
            return 
Example #20
Source File: common.py    From SublimeFileBrowser with MIT License 6 votes vote down vote up
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 "dired_select" command with other_group=True
    '''
    width = view.settings().get('dired_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\ndired_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 
Example #21
Source File: common.py    From SublimeOutline with MIT License 6 votes vote down vote up
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 
Example #22
Source File: Stylefmt.py    From sublime-stylefmt with ISC License 6 votes vote down vote up
def format(self, data):
		try:
			args = []
			if get_setting(self.view, 'config-basedir') is not None:
				args.extend(('--config-basedir', get_setting(self.view, 'config-basedir')))
			if get_setting(self.view, 'config') is not None:
				args.extend(('--config', get_setting(self.view, 'config')))
			if get_setting(self.view, 'ignore-path') is not None:
				args.extend(('--ignore-path', get_setting(self.view, 'ignore-path')))

			if 'file' in self.sublime_vars:
				args.extend(('--stdin-filename', self.sublime_vars['file']))
				return node_bridge(data, BIN_PATH, args)
			else:
				return node_bridge(data, BIN_PATH, args)

		except Exception as e:
			sublime.error_message('Stylefmt\n%s' % e)
			raise 
Example #23
Source File: tern.py    From PhaserSublimePackage with MIT License 6 votes vote down vote up
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 
Example #24
Source File: tern.py    From PhaserSublimePackage with MIT License 6 votes vote down vote up
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) 
Example #25
Source File: request_history.py    From Requester with MIT License 6 votes vote down vote up
def move_requester_file(view, old_path, new_path):
    if os.path.exists(new_path):
        sublime.error_message('Move Requester File Error: `{}` already exists'.format(new_path))
        return
    try:
        os.rename(old_path, new_path)
    except Exception:
        sublime.error_message("Move Requester File Error: you couldn't move file to `{}`\n\n\
Remember to create the destination folder first".format(new_path))
        return
    window = view.window()
    window.run_command('close_file')
    window.open_file(new_path)

    rh = load_history(as_dict=True)
    for k, v in rh.items():
        if v.get('file') == old_path:
            v['file'] = new_path

    config = sublime.load_settings('Requester.sublime-settings')
    history_file = config.get('history_file', None)
    write_json_file(rh, os.path.join(sublime.packages_path(), 'User', history_file)) 
Example #26
Source File: _generated_2018_02_11_at_20_21_24.py    From JavaScript-Completions with MIT License 5 votes vote down vote up
def run(self, **args):
      window = self.window
      contextual_keys = window.extract_variables()
      folder_path = contextual_keys.get("folder")
      if folder_path and os.path.isdir(folder_path) :
        jsdoc_json = os.path.join(folder_path, javascriptCompletions.get("jsdoc_conf_file"))
  
        if os.path.isfile(jsdoc_json) :
          thread = Util.create_and_start_thread(self.exec_node, "JSDocGenerating", [folder_path, ["-c",jsdoc_json]])
        else :
          sublime.error_message("ERROR: Can't load "+jsdoc_json+" file!\nConfiguration file REQUIRED!")
          return 
Example #27
Source File: python.py    From sublime_debugger with MIT License 5 votes vote down vote up
def start(self, log, configuration):
		if configuration.request == "attach":
			connect = configuration.get("connect")
			if connect:
				host = connect.get("host", "localhost")
				port = connect.get("port")

				return adapter.SocketTransport(log, host, port)

			port = configuration.get("port")
			if port:
				host = configuration.get("host", "localhost")

				return adapter.SocketTransport(log, host, port)

			if not configuration.get("listen") and not configuration.get("processId"):
				sublime.error_message("Warning: Check your debugger configuration.\n\n'attach' requires 'connect', 'listen' or 'processId'.\n\nIf they contain a $variable that variable may not have existed.""")

		install_path = adapter.vscode.install_path(self.type)

		python = configuration.get("pythonPath", "python")
		command = [
			python,
			f'{install_path}/extension/pythonFiles/lib/python/debugpy/adapter',
		]

		return adapter.StdioTransport(log, command) 
Example #28
Source File: python.py    From sublime_debugger with MIT License 5 votes vote down vote up
def configuration_resolve(self, configuration):
		if configuration.request == "launch":
			if not configuration.get("program"):
				sublime.error_message("Warning: Check your debugger configuration.\n\nField `program` in configuration is empty. If it contained a $variable that variable may not have existed.""")

		return configuration 
Example #29
Source File: fuse.py    From Fuse.SublimePlugin with MIT License 5 votes vote down vote up
def run(self, working_dir, build_target, run, paths=[]):
		log().info("Requested build: platform:'%s', build_target:'%s', working_dir:'%s'", str(sublime.platform()), build_target, working_dir)
		gFuse.ensureConnected()
		save_current_view()
		working_dir = working_dir or os.path.dirname(paths[0])
		gFuse.buildManager.build(build_target, run, working_dir, error_message) 
Example #30
Source File: fuse.py    From Fuse.SublimePlugin with MIT License 5 votes vote down vote up
def showFuseNotFound(self):
		error_message("Fuse could not be found.\n\nAttempted to run from: '"+getFusePathFromSettings()+"'\n\nPATH is: '" + os.environ['PATH'] + "'\n\nPlease verify your Fuse installation." + self.rebootMessage())