Python sublime.run_command() Examples

The following are 29 code examples of sublime.run_command(). 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: temp_directory_test_case.py    From UnitTesting with MIT License 6 votes vote down vote up
def setUpClass(cls):
        """Create a temp directory for testing."""
        cls._temp_dir = tempfile.mkdtemp()
        nwindows = len(sublime.windows())
        original_window_id = sublime.active_window().id()
        sublime.run_command("new_window")

        yield lambda: len(sublime.windows()) > nwindows

        yield lambda: sublime.active_window().id() != original_window_id

        cls.window = sublime.active_window()

        project_data = dict(folders=[dict(follow_symlinks=True, path=cls._temp_dir)])
        cls.window.set_project_data(project_data)

        def condition():
            for d in cls.window.folders():
                # on Windows, `cls._temp_dir` is lowered cased,
                # `os.path.normcase` is needed for comparison.
                if cls._temp_dir == os.path.normcase(d):
                    return True

        yield condition 
Example #2
Source File: test_project.py    From JavaScriptEnhancements with MIT License 6 votes vote down vote up
def test_project(self):
    start_time = time.time()

    while not plugin_ready():
      if time.time() - start_time <= timeout:
        yield 200
      else:
        raise TimeoutError("plugin is not ready in " + str(timeout) + " seconds")

    self.window.run_command("javascript_enhancements_create_new_project")
    yield 1000
    self.window.run_command("insert", {"characters": "empty"})
    yield 1000
    self.window.run_command("keypress", {"key": "enter"})
    yield 1000
    self.window.run_command("insert", {"characters": "javascript_enhancements_project_test"})
    yield 1000
    self.window.run_command("keypress", {"key": "enter"})
    self.window.run_command("keypress", {"key": "enter"})
    yield 1000
    self.assertDictEqual(project_settings, util.get_project_settings()) 
Example #3
Source File: open_found_files.py    From SublimeScraps with MIT License 6 votes vote down vote up
def run(self, edit, new_window=False):
        # Collect all found filenames
        positions = self.view.find_by_selector("entity.name.filename.find-in-files")
        if len(positions) > 0:
            # Set up the window to open the files in
            if new_window:
                sublime.run_command("new_window")
                window = sublime.active_window()
            else:
                window = self.view.window()

            # Open each file in the new window
            for position in positions:
                window.run_command('open_file', {'file': self.view.substr (position)})
        else:
            self.view.window().status_message("No find results") 
Example #4
Source File: fuse.py    From Fuse.SublimePlugin with MIT License 6 votes vote down vote up
def plugin_loaded():
	log().info("Loading plugin")
	log().info("Sublime version '" + sublime.version() + "'")
	log().info("Fuse plugin version '" + VERSION + "'")
	global gFuse
	gFuse = Fuse()
	fix_osx_path()

	s = sublime.load_settings("Preferences.sublime-settings")
	if getSetting("fuse_open_files_in_same_window"):
		s.set("open_files_in_new_window", False)
	else:
		s.set("open_files_in_new_window", True)

	if getSetting("fuse_show_user_guide_on_start", True):
		sublime.active_window().run_command("open_file", {"file":"${packages}/Fuse/UserGuide.txt"})
		setSetting("fuse_show_user_guide_on_start", False)
	log().info("Plugin loaded successfully") 
Example #5
Source File: package.py    From UnitTesting with MIT License 6 votes vote down vote up
def run(self, package=None, **kwargs):
        if not package:
            self.prompt_package(lambda x: self.run(x, **kwargs))
            return

        package, pattern = self.input_parser(package)

        if sys.version_info >= (3, 8) and self.package_python_version(package) == "3.3":
            print("run unit_testing in python 3.3")
            kwargs["package"] = package
            sublime.set_timeout(lambda: sublime.run_command(self.fallback33, kwargs))
            return

        if pattern is not None:
            # kwargs have the highest precedence when evaluating the settings,
            # so we sure don't want to pass `None` down
            kwargs['pattern'] = pattern

        settings = self.load_unittesting_settings(package, kwargs)
        stream = self.load_stream(package, settings)

        if settings["async"]:
            threading.Thread(target=lambda: self.unit_testing(stream, package, settings)).start()
        else:
            self.unit_testing(stream, package, settings) 
Example #6
Source File: support.py    From ColorHelper with MIT License 5 votes vote down vote up
def run(self):
        """Show the changelog in a new view."""
        try:
            import mdpopups
            has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3124)
        except Exception:
            has_phantom_support = False

        text = sublime.load_resource('Packages/ColorHelper/CHANGES.md')
        view = self.window.new_file()
        view.set_name('ColorHelper - Changelog')
        view.settings().set('gutter', False)
        view.settings().set('word_wrap', False)
        if has_phantom_support:
            mdpopups.add_phantom(
                view,
                'changelog',
                sublime.Region(0),
                text,
                sublime.LAYOUT_INLINE,
                wrapper_class="color-helper",
                css=CSS,
                on_navigate=self.on_navigate
            )
        else:
            view.run_command('insert', {"characters": text})
        view.set_read_only(True)
        view.set_scratch(True) 
Example #7
Source File: open_image.py    From Graphvizer with GNU General Public License v2.0 5 votes vote down vote up
def open_image_window(self):
		image_filepath = get_image_filepath(self.st_settings, self.window.active_view())
		if os.path.isfile(image_filepath):
			sublime.run_command("new_window")
			image_window = sublime.active_window()
			image_window.open_file(image_filepath)
			image_window.set_menu_visible(False)
			image_window.set_tabs_visible(False)
			image_window.set_minimap_visible(False)
			image_window.set_status_bar_visible(False)
		else:
			sublime.message_dialog("Image has not been rendered!") 
Example #8
Source File: test_project.py    From JavaScriptEnhancements with MIT License 5 votes vote down vote up
def tearDown(self):
    global project_path
    sublime.active_window().run_command("close")
    sublime.active_window().run_command("close")
    if os.path.isdir(project_path):
      shutil.rmtree(project_path) 
Example #9
Source File: test_project.py    From JavaScriptEnhancements with MIT License 5 votes vote down vote up
def setUp(self):
    sublime.run_command('new_window')
    self.view = sublime.active_window().new_file()
    self.window = self.view.window()
    if os.path.isdir(project_path):
      shutil.rmtree(project_path) 
Example #10
Source File: temp_directory_test_case.py    From UnitTesting with MIT License 5 votes vote down vote up
def tearDownClass(cls):
        # need at least one window in order to keep sublime running
        if len(sublime.windows()) > 1:
            cls.window.run_command('close_window')

            def remove_temp_dir():
                try:
                    shutil.rmtree(cls._temp_dir)
                except Exception:
                    print("Cannot remove {}".format(cls._temp_dir))

            sublime.set_timeout(remove_temp_dir, 1000) 
Example #11
Source File: quick_panel.py    From GitSavvy with MIT License 5 votes vote down vote up
def get_arguments(self, selected_action):
        """Prepares `run_command` arguments:
          - (required) Command name is 1st argument
          - (optional) args is 2nd (and next) arguments
          - (optional) kwargs are simply keyword arguments
        """
        args, kwargs = super().get_arguments(selected_action)
        return ((selected_action[0], ) + args), kwargs 
Example #12
Source File: quick_panel.py    From GitSavvy with MIT License 5 votes vote down vote up
def get_callable(self, selected_action):
        if hasattr(self, 'window'):
            return self.window.run_command
        elif hasattr(self, 'view'):
            return self.view.run_command
        else:
            return sublime.run_command 
Example #13
Source File: init.py    From GitSavvy with MIT License 5 votes vote down vote up
def open_folder(self):
        # taken from
        # https://github.com/rosshemsley/iOpener/blob/a35117a201290b63b53ba6372dbf8bbfc68f28b9/i_opener.py#L203-L205
        sublime.run_command("new_window")
        project_data = dict(folders=[dict(follow_symlinks=True, path=self.suggested_git_root)])
        sublime.active_window().set_project_data(project_data) 
Example #14
Source File: init.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self):
        if self.savvy_settings.get("disable_git_init_prompt"):
            return

        active_view_id = self.window.active_view().id()
        if active_view_id not in views_with_offer_made and sublime.ok_cancel_dialog(NO_REPO_MESSAGE):
            self.window.run_command("gs_init")
        else:
            views_with_offer_made.add(active_view_id) 
Example #15
Source File: MarkdownLivePreview.py    From MarkdownLivePreview with MIT License 5 votes vote down vote up
def _update_preview(self, markdown_view):
        # if the buffer id is 0, that means that the markdown_view has been closed
        # This check is needed since a this function is used as a callback for when images
        # are loaded from the internet (ie. it could finish loading *after* the user
        # closes the markdown_view)
        if time.time() - self.last_update < DELAY / 1000:
            return

        if markdown_view.buffer_id() == 0:
            return

        self.last_update = time.time()

        total_region = sublime.Region(0, markdown_view.size())
        markdown = markdown_view.substr(total_region)

        preview_view = markdown_view.window().active_view_in_group(1)
        viewport_width = preview_view.viewport_extent()[0]

        basepath = os.path.dirname(markdown_view.file_name())
        html = markdown2html(
            markdown,
            basepath,
            partial(self._update_preview, markdown_view),
            resources,
            viewport_width,
        )

        self.phantom_sets[markdown_view.id()].update(
            [
                sublime.Phantom(
                    sublime.Region(0),
                    html,
                    sublime.LAYOUT_BLOCK,
                    lambda href: sublime.run_command("open_url", {"url": href}),
                )
            ]
        ) 
Example #16
Source File: scheduler.py    From UnitTesting with MIT License 5 votes vote down vote up
def try_running_scheduler():
    while not UnitTestingRunSchedulerCommand.ready:
        sublime.set_timeout(
            lambda: sublime.run_command("unit_testing_run_scheduler"), 1)

        time.sleep(1) 
Example #17
Source File: support.py    From ColorHelper with MIT License 5 votes vote down vote up
def run(self, page):
        """Open page."""

        try:
            import mdpopups
            has_phantom_support = (mdpopups.version() >= (1, 10, 0)) and (int(sublime.version()) >= 3124)
        except Exception:
            has_phantom_support = False

        if not has_phantom_support:
            sublime.run_command('open_file', {"file": page})
        else:
            text = sublime.load_resource(page.replace('${packages}', 'Packages'))
            view = self.window.new_file()
            view.set_name('ColorHelper - Quick Start')
            view.settings().set('gutter', False)
            view.settings().set('word_wrap', False)
            if has_phantom_support:
                mdpopups.add_phantom(
                    view,
                    'quickstart',
                    sublime.Region(0),
                    text,
                    sublime.LAYOUT_INLINE,
                    css=CSS,
                    wrapper_class="color-helper",
                    on_navigate=self.on_navigate
                )
            else:
                view.run_command('insert', {"characters": text})
            view.set_read_only(True)
            view.set_scratch(True) 
Example #18
Source File: support.py    From ColorHelper with MIT License 5 votes vote down vote up
def on_navigate(self, href):
        """Handle links."""

        if href.startswith('sub://Packages'):
            sublime.run_command('open_file', {"file": self.re_pkgs.sub('${packages}', href[6:])})
        else:
            webbrowser.open_new_tab(href) 
Example #19
Source File: color_helper_util.py    From ColorHelper with MIT License 5 votes vote down vote up
def color_picker_available():
    """Check if color picker is available."""

    s = sublime.load_settings('color_helper_share.sublime-settings')
    s.set('color_pick_return', None)
    sublime.run_command('color_pick_api_is_available', {'settings': 'color_helper_share.sublime-settings'})
    return s.get('color_pick_return', None) 
Example #20
Source File: sublimefunctions.py    From FileManager with MIT License 5 votes vote down vote up
def close_view(view_to_close, dont_prompt_save=False):
    if dont_prompt_save:
        view_to_close.set_scratch(True)
    if isST3():
        view_to_close.close()
        return
    window = view_to_close.window()
    window.focus_view(view_to_close)
    window.run_command("close") 
Example #21
Source File: sublimefunctions.py    From FileManager with MIT License 5 votes vote down vote up
def refresh_sidebar(settings=None, window=None):
    if window is None:
        window = active_window()
    if settings is None:
        settings = window.active_view().settings()
    if settings.get("explicitly_refresh_sidebar") is True:
        window.run_command("refresh_folder_list") 
Example #22
Source File: create_from_selection.py    From FileManager with MIT License 5 votes vote down vote up
def run(self, edit, event):
        base_path, input_path = self.get_path(event)
        abspath = computer_friendly(os.path.join(base_path, input_path))
        sublime.run_command(
            "fm_creater", {"abspath": abspath, "input_path": input_path}
        ) 
Example #23
Source File: fuse.py    From Fuse.SublimePlugin with MIT License 5 votes vote down vote up
def run(self, edit, type = "Local"):
		sublime.run_command("fuse_preview", {"type": type, "paths": [self.view.file_name()]}); 
Example #24
Source File: fuse.py    From Fuse.SublimePlugin with MIT License 5 votes vote down vote up
def save_current_view():
	window = sublime.active_window()
	if window:
		view = window.active_view()
		if (view and view.is_dirty()):
			view.run_command("save") 
Example #25
Source File: scheduler.py    From UnitTesting with MIT License 5 votes vote down vote up
def run(self):
        if self.syntax_test:
            sublime.run_command("unit_testing_syntax", {
                "package": self.package,
                "output": self.output
            })
        elif self.syntax_compatibility:
            sublime.run_command("unit_testing_syntax_compatibility", {
                "package": self.package,
                "output": self.output
            })
        elif self.color_scheme_test:
            sublime.run_command("unit_testing_color_scheme", {
                "package": self.package,
                "output": self.output
            })
        elif self.coverage:
            sublime.run_command("unit_testing_coverage", {
                "package": self.package,
                "output": self.output
            })
        else:
            sublime.run_command("unit_testing", {
                "package": self.package,
                "output": self.output
            }) 
Example #26
Source File: fuse.py    From Fuse.SublimePlugin with MIT License 5 votes vote down vote up
def responseAutoComplete(self, view, res):
		self.lastResponse = res
		view.run_command("auto_complete",
		{
            "disable_auto_insert": True,
            "api_completions_only": False,
            "next_completion_if_showing": False,
            "auto_complete_commit_on_tab": True,
        }) 
Example #27
Source File: MarkdownLivePreview.py    From MarkdownLivePreview with MIT License 4 votes vote down vote up
def run(self, edit):

        """ If the file is saved exists on disk, we close it, and reopen it in a new
        window. Otherwise, we copy the content, erase it all (to close the file without
        a dialog) and re-insert it into a new view into a new window """

        original_view = self.view
        original_window_id = original_view.window().id()
        file_name = original_view.file_name()

        syntax_file = original_view.settings().get("syntax")

        if file_name:
            original_view.close()
        else:
            # the file isn't saved, we need to restore the content manually
            total_region = sublime.Region(0, original_view.size())
            content = original_view.substr(total_region)
            original_view.erase(edit, total_region)
            original_view.close()
            # FIXME: save the document to a temporary file, so that if we crash,
            #        the user doesn't lose what he wrote

        sublime.run_command("new_window")
        preview_window = sublime.active_window()

        preview_window.run_command(
            "set_layout",
            {
                "cols": [0.0, 0.5, 1.0],
                "rows": [0.0, 1.0],
                "cells": [[0, 0, 1, 1], [1, 0, 2, 1]],
            },
        )

        preview_window.focus_group(1)
        preview_view = preview_window.new_file()
        preview_view.set_scratch(True)
        preview_view.settings().set(PREVIEW_VIEW_INFOS, {})
        preview_view.set_name("Preview")
        # FIXME: hide number lines on preview

        preview_window.focus_group(0)
        if file_name:
            markdown_view = preview_window.open_file(file_name)
        else:
            markdown_view = preview_window.new_file()
            markdown_view.run_command("mdlp_insert", {"point": 0, "string": content})
            markdown_view.set_scratch(True)

        markdown_view.set_syntax_file(syntax_file)
        markdown_view.settings().set(
            MARKDOWN_VIEW_INFOS, {"original_window_id": original_window_id,},
        ) 
Example #28
Source File: MarkdownLivePreview.py    From MarkdownLivePreview with MIT License 4 votes vote down vote up
def on_close(self, markdown_view):
        """ Use the information saved to restore the markdown_view as an original_view
        """
        infos = markdown_view.settings().get(MARKDOWN_VIEW_INFOS)
        if not infos:
            return

        assert (
            markdown_view.id() == self.markdown_view.id()
        ), "pre_close view.id() != close view.id()"

        del self.phantom_sets[markdown_view.id()]

        self.preview_window.run_command("close_window")

        # find the window with the right id
        original_window = next(
            window
            for window in sublime.windows()
            if window.id() == infos["original_window_id"]
        )
        if self.file_name:
            original_window.open_file(self.file_name)
        else:
            assert markdown_view.is_scratch(), (
                "markdown view of an unsaved file should " "be a scratch"
            )
            # note here that this is called original_view, because it's what semantically
            # makes sense, but this original_view.id() will be different than the one
            # that we closed first to reopen in the preview window
            # shouldn't cause any trouble though
            original_view = original_window.new_file()
            original_view.run_command(
                "mdlp_insert", {"point": 0, "string": self.content}
            )

            original_view.set_syntax_file(markdown_view.settings().get("syntax"))

    # here, views are NOT treated independently, which is theoretically wrong
    # but in practice, you can only edit one markdown file at a time, so it doesn't really
    # matter.
    # @min_time_between_call(.5) 
Example #29
Source File: sublimefunctions.py    From FileManager with MIT License 4 votes vote down vote up
def transform_aliases(window, string):
    """Transform aliases using the settings and the default variables
    It's recursive, so you can use aliases *in* your aliases' values
    """

    vars = window.extract_variables()
    vars.update(get_settings().get("aliases"))

    def has_unescaped_dollar(string):
        start = 0
        while True:
            index = string.find("$", start)
            if index < 0:
                return False
            elif string[index - 1] == "\\":
                start = index + 1
            else:
                return True

    string = string.replace("$$", "\\$")

    inifinite_loop_counter = 0
    while has_unescaped_dollar(string):
        inifinite_loop_counter += 1
        if inifinite_loop_counter > 100:
            sublime.error_message(
                "Infinite loop: you better check your "
                "aliases, they're calling each other "
                "over and over again."
            )
            if get_settings().get("open_help_on_alias_infinite_loop", True) is True:

                sublime.run_command(
                    "open_url",
                    {
                        "url": "https://github.com/math2001/ "
                        "FileManager/wiki/Aliases "
                        "#watch-out-for-infinite-loops"
                    },
                )
            return string
        string = sublime.expand_variables(string, vars)

    return string