Python sublime.Edit() Examples

The following are 30 code examples of sublime.Edit(). 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: references.py    From LSP with MIT License 6 votes vote down vote up
def run(self, edit: sublime.Edit, event: Optional[dict] = None) -> None:
        client = self.client_with_capability('referencesProvider')
        file_path = self.view.file_name()
        if client and file_path:
            pos = get_position(self.view, event)
            window = self.view.window()
            self.word_region = self.view.word(pos)
            self.word = self.view.substr(self.word_region)

            # use relative paths if file on the same root.
            base_dir = windows.lookup(window).get_project_path(file_path)
            if base_dir:
                if os.path.commonprefix([base_dir, file_path]):
                    self.base_dir = base_dir

            document_position = text_document_position_params(self.view, pos)
            document_position['context'] = {"includeDeclaration": False}
            request = Request.references(document_position)
            client.send_request(request, lambda response: self.handle_response(response, pos)) 
Example #2
Source File: update_image_size.py    From sublime-text-plugin with MIT License 6 votes vote down vote up
def update_image_size_css(view: sublime.View, edit: sublime.Edit, pos: int):
    "Updates image size in CSS context"
    section = emmet.css_section(utils.get_content(view), pos, True)
    # Store all properties in lookup table and find matching URL
    props = {}
    src = None
    context_prop = None

    if section:
        for p in section.properties:
            props[view.substr(p.name)] = p

            # If value matches caret location, find url(...) token for it
            if p.value.contains(pos):
                context_prop = p
                src = get_css_url(view, p, pos)

    if src:
        size = read_image_size(view, src)
        if size:
            patch_css_size(view, edit, props, size[0], size[1], context_prop)
        else:
            print('Unable to determine size of "%s": file is either unsupported or invalid' % src) 
Example #3
Source File: update_image_size.py    From sublime-text-plugin with MIT License 6 votes vote down vote up
def patch_css_size(view: sublime.View, edit: sublime.Edit, props: dict, width: int, height: int, context_prop: dict):
    width = '%dpx' % width
    height = '%dpx' % height
    width_prop = props.get('width')
    height_prop = props.get('height')

    if width_prop and height_prop:
        # We have both properties, patch them
        if width_prop.before < height_prop.before:
            view.replace(edit, height_prop.value, height)
            view.replace(edit, width_prop.value, width)
        else:
            view.replace(edit, width_prop.value, width)
            view.replace(edit, height_prop.value, height)
    elif width_prop or height_prop:
        # Use existing attribute and replace it with patched variations
        prop = width_prop or height_prop
        data = utils.patch_property(view, prop, width, 'width') + utils.patch_property(view, prop, height, 'height')
        view.replace(edit, sublime.Region(prop.before, prop.after), data)
    elif context_prop:
        # Append to source property
        data = utils.patch_property(view, context_prop, width, 'width') + utils.patch_property(view, context_prop, height, 'height')
        view.insert(edit, context_prop.after, data) 
Example #4
Source File: status.py    From GitSavvy with MIT License 6 votes vote down vote up
def run(self, edit, action=None):
        # type: (sublime.Edit, str) -> None
        window = self.view.window()
        if not window:
            return

        ids = get_selected_subjects(self.view, 'stashes')
        if not ids:
            return

        if action == "show":
            window.run_command("gs_stash_show", {"stash_ids": ids})
            return

        if len(ids) > 1:
            window.status_message("You can only {} one stash at a time.".format(action))
            return

        if action == "apply":
            window.run_command("gs_stash_apply", {"stash_id": ids[0]})
        elif action == "pop":
            window.run_command("gs_stash_pop", {"stash_id": ids[0]})
        elif action == "drop":
            window.run_command("gs_stash_drop", {"stash_id": ids[0]}) 
Example #5
Source File: hover.py    From LSP with MIT License 6 votes vote down vote up
def run(self, edit: sublime.Edit, point: Optional[int] = None) -> None:
        hover_point = point or self.view.sel()[0].begin()
        self._base_dir = windows.lookup(self.view.window()).get_project_path(self.view.file_name() or "")

        self._hover = None  # type: Optional[Any]
        self._actions_by_config = {}  # type: Dict[str, List[CodeActionOrCommand]]
        self._diagnostics_by_config = {}  # type: Dict[str, List[Diagnostic]]

        if self.is_likely_at_symbol(hover_point):
            self.request_symbol_hover(hover_point)

        self._diagnostics_by_config = filter_by_point(view_diagnostics(self.view),
                                                      Point(*self.view.rowcol(hover_point)))
        if self._diagnostics_by_config:
            self.request_code_actions(hover_point)
            self.request_show_hover(hover_point) 
Example #6
Source File: status.py    From GitSavvy with MIT License 6 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        window = self.view.window()
        if not window:
            return

        repo_path = self.repo_path
        non_cached_files = get_selected_files(
            self.view, repo_path, 'unstaged', 'untracked', 'merge-conflicts'
        )
        cached_files = get_selected_files(self.view, repo_path, 'staged')

        sublime.set_timeout_async(
            lambda: self.load_diff_windows(
                window,  # type: ignore  # https://github.com/python/mypy/issues/4297
                non_cached_files,
                cached_files
            )
        ) 
Example #7
Source File: status.py    From GitSavvy with MIT License 6 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        interface = get_interface(self.view)
        if not interface:
            return

        conflicts = interface.state['merge_conflicts']
        file_paths = get_selected_subjects(self.view, 'merge-conflicts')

        for fpath in file_paths:
            if self.is_base_version_deleted(fpath, conflicts):
                self.git("rm", "--", fpath)
            else:
                self.git("checkout", "--ours", "--", fpath)
                self.stage_file(fpath)

        interface.refresh_repo_status_and_render() 
Example #8
Source File: convert_data_url.py    From sublime-text-plugin with MIT License 6 votes vote down vote up
def convert_to_data_url(view: sublime.View, edit: sublime.Edit, region: sublime.Region):
    max_size = emmet.get_settings('max_data_url', 0)
    src = view.substr(region)
    abs_file = None

    if utils.is_url(src):
        abs_file = src
    elif view.file_name():
        abs_file = utils.locate_file(view.file_name(), src)
        if abs_file and max_size and os.path.getsize(abs_file) > max_size:
            print('Size of %s file is too large. Check "emmet_max_data_url" setting to increase this limit' % abs_file)
            return

    if abs_file:
        data = utils.read_file(abs_file)
        if data and (not max_size or len(data) <= max_size):
            ext = os.path.splitext(abs_file)[1]
            if ext in mime_types:
                new_src = 'data:%s;base64,%s' % (mime_types[ext], base64.urlsafe_b64encode(data).decode('utf8'))
                view.replace(edit, region, new_src) 
Example #9
Source File: status.py    From GitSavvy with MIT License 6 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        interface = get_interface(self.view)
        if not interface:
            return

        conflicts = interface.state['merge_conflicts']
        file_paths = get_selected_subjects(self.view, 'merge-conflicts')

        for fpath in file_paths:
            if self.is_commit_version_deleted(fpath, conflicts):
                self.git("rm", "--", fpath)
            else:
                self.git("checkout", "--theirs", "--", fpath)
                self.stage_file(fpath)

        interface.refresh_repo_status_and_render() 
Example #10
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        window = self.view.window()
        if not window:
            return

        repo_path = self.repo_path
        non_cached_files = get_selected_files(self.view, repo_path, 'unstaged', 'merge-conflicts')
        cached_files = get_selected_files(self.view, repo_path, 'staged')

        sublime.set_timeout_async(
            lambda: self.load_inline_diff_views(window, non_cached_files, cached_files)
        ) 
Example #11
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        interface = get_interface(self.view)
        if not interface:
            return

        self.add_all_tracked_files()
        interface.refresh_repo_status_and_render() 
Example #12
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        window, interface = self.view.window(), get_interface(self.view)
        if not (window and interface):
            return
        untracked_files = self.discard_untracked()
        unstaged_files = self.discard_unstaged()
        if untracked_files or unstaged_files:
            window.status_message("Successfully discarded changes.")
            interface.refresh_repo_status_and_render() 
Example #13
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        window, interface = self.view.window(), get_interface(self.view)
        if not (window and interface):
            return

        file_paths = get_selected_subjects(self.view, 'unstaged', 'untracked', 'merge-conflicts')
        if file_paths:
            self.stage_file(*file_paths, force=False)
            window.status_message("Staged files successfully.")
            interface.refresh_repo_status_and_render() 
Example #14
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        window, interface = self.view.window(), get_interface(self.view)
        if not (window and interface):
            return

        file_paths = get_selected_subjects(
            self.view, 'staged', 'unstaged', 'untracked', 'merge-conflicts'
        )
        if file_paths:
            window.run_command("gs_ignore_pattern", {"pre_filled": file_paths[0]}) 
Example #15
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        file_paths = get_selected_subjects(self.view, 'staged', 'unstaged', 'merge-conflicts')
        if file_paths:
            self.view.run_command("gs_github_open_file_on_remote", {"fpath": file_paths}) 
Example #16
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        window = self.view.window()
        if not window:
            return

        for fpath in get_selected_files(self.view, self.repo_path):
            window.open_file(fpath) 
Example #17
Source File: diff.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None

        def first_per_file(items):
            # type: (Iterator[JumpTo]) -> Iterator[JumpTo]
            seen = set()  # type: Set[str]
            for item in items:
                if item.filename not in seen:
                    seen.add(item.filename)
                    yield item

        word_diff_mode = bool(self.view.settings().get('git_savvy.diff_view.show_word_diff'))
        algo = (
            self.jump_position_to_file_for_word_diff_mode
            if word_diff_mode
            else self.jump_position_to_file
        )
        diff = SplittedDiff.from_view(self.view)
        jump_positions = list(first_per_file(filter_(
            algo(diff, s.begin())
            for s in self.view.sel()
        )))
        if not jump_positions:
            util.view.flash(self.view, "Not within a hunk")
        else:
            for jp in jump_positions:
                self.load_file_at_line(*jp) 
Example #18
Source File: diff.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit, amount):
        # type: (sublime.Edit, int) -> None
        settings = self.view.settings()
        current = settings.get('git_savvy.diff_view.context_lines')
        next = max(current + amount, 0)
        settings.set('git_savvy.diff_view.context_lines', next)

        # Getting a meaningful cursor after 'zooming' is the tricky part
        # here. We first extract all hunks under the cursors *verbatim*.
        diff = SplittedDiff.from_view(self.view)
        cur_hunks = [
            header.text + hunk.text
            for header, hunk in filter_(diff.head_and_hunk_for_pt(s.a) for s in self.view.sel())
        ]

        self.view.run_command("gs_diff_refresh")

        # Now, we fuzzy search the new view content for the old hunks.
        cursors = {
            region.a
            for region in (
                filter_(find_hunk_in_view(self.view, hunk) for hunk in cur_hunks)
            )
        }
        if cursors:
            set_and_show_cursor(self.view, cursors) 
Example #19
Source File: commit.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit, sync=True):
        # type: (sublime.Edit, bool) -> None
        if sync:
            self.run_impl()
        else:
            enqueue_on_worker(self.run_impl) 
Example #20
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        interface = get_interface(self.view)
        if not interface:
            return

        self.add_all_files()
        interface.refresh_repo_status_and_render() 
Example #21
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        interface = get_interface(self.view)
        if not interface:
            return

        self.unstage_all_files()
        interface.refresh_repo_status_and_render() 
Example #22
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        interface = get_interface(self.view)
        if not interface:
            return

        self.discard_all_unstaged()
        interface.refresh_repo_status_and_render() 
Example #23
Source File: panels.py    From LSP with MIT License 5 votes vote down vote up
def run(self, edit: sublime.Edit, characters: Optional[str] = "") -> None:
        # Clear folds
        self.view.unfold(sublime.Region(0, self.view.size()))

        with mutable(self.view):
            self.view.replace(edit, sublime.Region(0, self.view.size()), characters or "")

        # Clear the selection
        selection = self.view.sel()
        selection.clear() 
Example #24
Source File: status.py    From GitSavvy with MIT License 5 votes vote down vote up
def run(self, edit):
        # type: (sublime.Edit) -> None
        file_paths = get_selected_subjects(
            self.view, 'staged', 'unstaged', 'untracked', 'merge-conflicts'
        )
        if len(file_paths) > 1:
            sublime.error_message("You can only launch merge tool for a single file at a time.")
            return

        sublime.set_timeout_async(lambda: self.launch_tool_for_file(file_paths[0]), 0) 
Example #25
Source File: callers.py    From anaconda_go with GNU General Public License v3.0 5 votes vote down vote up
def run(self, edit: sublime.Edit) -> None:
        try:
            view = self.view
            scope = get_settings(view, 'anaconda_go_guru_scope')
            row, col = view.rowcol(view.sel()[0].begin())
            offset = view.text_point(row, col)
            code = view.substr(sublime.Region(0, view.size()))

            data = {
                'vid': view.id(),
                'scope': scope if scope is not None else get_scope(view, go.GOPATH),  # noqa
                'path': view.file_name(),
                'offset': offset,
                'modified_buffer': self._modified_buffer(view, code),
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED
                },
                'method': 'callers',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(
                    on_success=self._on_success,
                    on_failure=self._on_failure,
                    on_timeout=self._on_timeout
                ),
                **data
            )
        except Exception as err:
            print('anaconda_go: callers error')
            print(traceback.print_exc()) 
Example #26
Source File: callees.py    From anaconda_go with GNU General Public License v3.0 5 votes vote down vote up
def run(self, edit: sublime.Edit) -> None:
        try:
            view = self.view
            scope = get_settings(view, 'anaconda_go_guru_scope')
            row, col = view.rowcol(view.sel()[0].begin())
            offset = view.text_point(row, col)
            code = view.substr(sublime.Region(0, view.size()))

            data = {
                'vid': view.id(),
                'scope': scope if scope is not None else get_scope(view, go.GOPATH),  # noqa
                'path': view.file_name(),
                'offset': offset,
                'modified_buffer': self._modified_buffer(view, code),
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED
                },
                'method': 'callees',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(
                    on_success=self._on_success,
                    on_failure=self._on_failure,
                    on_timeout=self._on_timeout
                ),
                **data
            )
        except Exception as err:
            print('anaconda_go: callees error')
            print(traceback.print_exc()) 
Example #27
Source File: referrers.py    From anaconda_go with GNU General Public License v3.0 5 votes vote down vote up
def run(self, edit: sublime.Edit) -> None:
        try:
            view = self.view
            scope = get_settings(view, 'anaconda_go_guru_scope')
            row, col = view.rowcol(view.sel()[0].begin())
            offset = view.text_point(row, col)
            code = view.substr(sublime.Region(0, view.size()))

            data = {
                'vid': view.id(),
                'scope': scope if scope is not None else get_scope(view, go.GOPATH),  # noqa
                'path': view.file_name(),
                'offset': offset,
                'modified_buffer': self._modified_buffer(view, code),
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED
                },
                'method': 'referrers',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(
                    on_success=self._on_success,
                    on_failure=self._on_failure,
                    on_timeout=self._on_timeout
                ),
                **data
            )
        except:
            print('anaconda_go: referrers error')
            print(traceback.print_exc()) 
Example #28
Source File: callstack.py    From anaconda_go with GNU General Public License v3.0 5 votes vote down vote up
def run(self, edit: sublime.Edit) -> None:
        try:
            view = self.view
            scope = get_settings(view, 'anaconda_go_guru_scope')
            row, col = view.rowcol(view.sel()[0].begin())
            offset = view.text_point(row, col)
            code = view.substr(sublime.Region(0, view.size()))

            data = {
                'vid': view.id(),
                'scope': scope if scope is not None else get_scope(view, go.GOPATH),  # noqa
                'path': view.file_name(),
                'offset': offset,
                'modified_buffer': self._modified_buffer(view, code),
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED
                },
                'method': 'callstack',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(
                    on_success=self._on_success,
                    on_failure=self._on_failure,
                    on_timeout=self._on_timeout
                ),
                **data
            )
        except:
            print('anaconda_go: callers error')
            print(traceback.print_exc()) 
Example #29
Source File: impl.py    From anaconda_go with GNU General Public License v3.0 5 votes vote down vote up
def run(self, edit: sublime.Edit) -> None:

        if self.impl is not None:
            self.view.insert(edit, self.view.sel()[0].begin(), self.impl)
            self.impl = None
            return

        sublime.active_window().show_input_panel(
            "Struct Name:", "Receiver",
            partial(self._receiver_done, edit), None, None
        ) 
Example #30
Source File: impl.py    From anaconda_go with GNU General Public License v3.0 5 votes vote down vote up
def _exec(self, edit: sublime.Edit, receiver: str, iface: str) -> None:

        if iface is None or iface == '':
            return

        try:
            data = {
                'vid': self.view.id(),
                'receiver': receiver,
                'iface': iface,
                'go_env': {
                    'GOROOT': go.GOROOT,
                    'GOPATH': go.GOPATH,
                    'CGO_ENABLED': go.CGO_ENABLED
                },
                'method': 'impl',
                'handler': 'anaGonda'
            }
            Worker().execute(
                Callback(
                    on_success=self.update_buffer,
                    on_failure=self.on_failure,
                    on_timeout=self.on_timeout
                ),
                **data
            )
        except:
            print('anaconda_go error: {}'.format(traceback.format_exc()))