def _show_status(self, view: sublime.View) -> None:
        """Show message in the view status bar
        """

        view.set_status(
            'anaconda_doc', 'Anaconda: {}'.format(self.signature)
        )
Example #2
0
def last_block_in_region(
    view: sublime.View,
    begin: int,
    scope: str,
    end: Optional[int] = None,
    skip: int = SKIP_ANYTHING,
) -> Optional[Tuple[int, int]]:
    skipper = SKIPPERS.get(skip, do_skip_anything)
    stop = view.size() if end is None else end
    empty = True

    while (
        stop > begin and
        not view.match_selector(stop, scope) and
        skipper(view, stop)
    ):
        stop -= 1

    start = stop
    while start > begin and view.match_selector(start, scope):
        start -= 1
        empty = False

    if empty:
        return None
    return start + 1, stop + 1
    def prepare_data_tooltip(
            self, view: sublime.View, data: Dict[str, Any]) -> Any:
        """Prepare the returned data for tooltips
        """

        merge_doc = get_settings(view, 'merge_signatures_and_doc')
        if (data['success'] and 'No docstring' not
                in data['doc'] and data['doc'] != 'list\n'):
            try:
                i = data['doc'].split('<br>').index("")
            except ValueError:
                self.signature = data['doc']
                self.doc = ''
                if self._signature_excluded(self.signature):
                    return
                return self._show_popup(view)

            if merge_doc:
                self.doc = '<br>'.join(data['doc'].split('<br>')[i:]).replace(
                    "  ", "&nbsp;&nbsp;")

            self.signature = '<br>&nbsp;&nbsp;&nbsp;&nbsp;'.join(
                data['doc'].split('<br>')[0:i])
            if self.signature is not None and self.signature != "":
                if not self._signature_excluded(self.signature):
                    return self._show_popup(view)

        if view.is_popup_visible():
                view.hide_popup()
        view.erase_status('anaconda_doc')
Example #4
0
def is_scope(view: sublime.View, scope: str) -> bool:
    sel = view.sel()
    try:
        return view.match_selector(sel[0].begin(), scope)
    except IndexError:
        # If in doubt, let's return `False`.
        return False
Example #5
0
def _session_for_view_and_window(view: sublime.View, window: 'Optional[sublime.Window]') -> 'Optional[Session]':
    if not window:
        debug("no window for view", view.file_name())
        return None

    if view.size() > 1000000:
        printf("file is too big, ignoring!")
        return False

    config = config_for_scope(view)
    if not config:
        debug("config not available for view", view.file_name())
        return None

    window_config_states = window_configs(window)
    if config.name not in window_config_states:
        debug(config.name, "not available for view",
              view.file_name(), "in window", window.id())
        return None
    else:
        session = window_config_states[config.name]
        if session.state == ClientStates.READY:
            return session
        else:
            return None
    def on_modified(self, view: sublime.View) -> None:
        """Called after changes has been made to a view
        """

        if view.command_history(0)[0] in ("expand_tabs", "unexpand_tabs"):
            return

        if not is_python(view) or not get_settings(view, 'display_signatures'):
            return

        try:
            location = view.rowcol(view.sel()[0].begin())
            if view.substr(view.sel()[0].begin()) in ['(', ')']:
                location = (location[0], location[1] - 1)

            data = prepare_send_data(location, 'doc', 'jedi')
            use_tooltips = get_settings(
                view, 'enable_signatures_tooltip', True
            )
            st_version = int(sublime.version())
            if st_version >= 3070:
                data['html'] = use_tooltips

            currying = partial(self.prepare_data_status, view)
            if use_tooltips and st_version >= 3070:
                currying = partial(self.prepare_data_tooltip, view)
            Worker().execute(currying, **data)
        except Exception as error:
            logging.error(error)
Example #7
0
    def modified_buffer(self, view: sublime.View) -> str:
        """Guru needs this to use unsaved buffers instead of files
        """

        code = view.substr(sublime.Region(0, view.size()))
        return '\n'.join([
            view.file_name(), str(len(code.encode('utf8'))), code
        ])
Example #8
0
def show_enable_config(view: sublime.View, config: ClientConfig):
    syntax = str(view.settings().get("syntax", ""))
    message = "SublimeCodeIntel has found a language server for {}. Run \"Setup Language Server\" to start using it".format(
        extract_syntax_name(syntax)
    )
    window = view.window()
    if window:
        window.status_message(message)
Example #9
0
def notify_did_save(view: sublime.View):
    file_name = view.file_name()
    window = view.window()
    if window and file_name:
        if has_document_state(window, file_name):
            client = client_for_view(view)
            if client:
                params = {"textDocument": {"uri": filename_to_uri(file_name)}}
                client.send_notification(Notification.didSave(params))
        else:
            debug('document not tracked', file_name)
Example #10
0
def get_document_position(view: sublime.View, point) -> 'Optional[OrderedDict]':
    file_name = view.file_name()
    if file_name:
        if not point:
            point = view.sel()[0].begin()
        d = OrderedDict()  # type: OrderedDict[str, Any]
        d['textDocument'] = {"uri": filename_to_uri(file_name)}
        d['position'] = offset_to_point(view, point).to_lsp()
        return d
    else:
        return None
Example #11
0
def try_jump_to_def_aux(view: sublime.View, name: str) -> None:
    start_time = time.time()
    while view.is_loading():
        time.sleep(0.01)
        if time.time() - start_time > 1:
            return
    symbols = {strip_prefix(text): pos for (pos, text) in view.symbols()}
    if name in symbols:
        region = symbols[name]
        view.run_command(
            "simple_context_show_selection",
            {"regions": [(region.a, region.b)]},
        )
Example #12
0
def enclosing_block(
    view: sublime.View, point: int, scope: str, end: Optional[int] = None,
) -> Optional[Tuple[int, int]]:
    start = stop = point
    while start > 0 and view.match_selector(start, scope):
        start -= 1
    end_ = view.size() if end is None else end
    while stop < end_ and view.match_selector(stop, scope):
        stop += 1

    if start < stop:
        return start + 1, stop
    return None
Example #13
0
def update_diagnostics_regions(view: sublime.View, diagnostics: 'List[Diagnostic]', severity: int):
    region_name = "code_intel_" + format_severity(severity)
    if settings.show_diagnostics_phantoms and not view.is_dirty():
        regions = None
    else:
        regions = list(range_to_region(diagnostic.range, view) for diagnostic in diagnostics
                       if diagnostic.severity == severity)
    if regions:
        scope_name = diagnostic_severity_scopes[severity]
        view.add_regions(
            region_name, regions, scope_name, settings.diagnostics_gutter_marker,
            UNDERLINE_FLAGS if settings.diagnostics_highlight_style == "underline" else BOX_FLAGS)
    else:
        view.erase_regions(region_name)
Example #14
0
def left_enclosing_block(
    view: sublime.View, point: int, scope: str, end: Optional[int] = None,
) -> Optional[Tuple[int, int]]:
    """
    Like `enclosing_block`, but checks that `point` is the right-boundary of
    the eventual block. If not, signal an error with `None`.
    """

    if end is None:
        end = view.size()
    block = enclosing_block(view, point, scope, end=end)
    if block and not view.match_selector(point + 1, scope):
        return block
    return None
Example #15
0
    def on_query_completions(self, view: sublime.View, prefix: str, locations: List[Tuple[int]]) -> Tuple[List[Tuple[str]], int]:  # noqa
        """Sublime Text autocompletion event handler
        """

        if not is_python(view, autocomplete_ignore_repl=True):
            return

        if completion_is_disabled(view):
            return

        if not dot_completion(view):
            enable_dot_completion(view)

        global JUST_COMPLETED

        if self.ready_from_defer is True:
            completion_flags = 0

            if get_settings(view, 'suppress_word_completions', False):
                completion_flags = sublime.INHIBIT_WORD_COMPLETIONS

            if get_settings(view, 'suppress_explicit_completions', False):
                completion_flags |= sublime.INHIBIT_EXPLICIT_COMPLETIONS

            cpl = self.completions
            self.completions = []
            self.ready_from_defer = False
            JUST_COMPLETED = True

            return (cpl, completion_flags)

        location = view.rowcol(locations[0])
        data = prepare_send_data(location, 'autocomplete', 'jedi')

        Worker().execute(self._complete, **data)
Example #16
0
def is_at_word(view: sublime.View, event) -> bool:
    pos = get_position(view, event)
    point_classification = view.classify(pos)
    if point_classification & SUBLIME_WORD_MASK:
        return True
    else:
        return False
Example #17
0
    def _modified_buffer(self, view: sublime.View, code: str) -> str:
        """Guru needs this to use unsaved buffers instead of files
        """

        return '\n'.join([
            view.file_name(), str(len(code.encode('utf8'))), code
        ])
Example #18
0
def update_diagnostics_in_view(view: sublime.View, diagnostics: 'List[Diagnostic]'):
    if view and view.is_valid():
        update_diagnostics_phantoms(view, diagnostics)
        for severity in range(
                DiagnosticSeverity.Error,
                DiagnosticSeverity.Error + settings.show_diagnostics_severity_level):
            update_diagnostics_regions(view, diagnostics, severity)
Example #19
0
    def on_pre_close(self, view: sublime.View) -> None:
        """Called when the view is about to be closed
        """

        self._erase_marks(view)
        for severity in ['VIOLATIONS', 'WARNINGS', 'ERRORS']:
            ANACONDA[severity][view.id()] = {}
Example #20
0
def get_window_client_config(view: sublime.View) -> 'Optional[ClientConfig]':
    window = view.window()
    if window:
        configs_for_window = window_client_configs.get(window.id(), [])
        return get_scope_client_config(view, configs_for_window)
    else:
        return None
Example #21
0
def update_diagnostics_phantoms(view: sublime.View, diagnostics: 'List[Diagnostic]'):
    global phantom_sets_by_buffer

    buffer_id = view.buffer_id()
    if not settings.show_diagnostics_phantoms or view.is_dirty():
        phantoms = None
    else:
        phantoms = list(
            create_phantom(view, diagnostic) for diagnostic in diagnostics)
    if phantoms:
        phantom_set = phantom_sets_by_buffer.get(buffer_id)
        if not phantom_set:
            phantom_set = sublime.PhantomSet(view, "code_intel_diagnostics")
            phantom_sets_by_buffer[buffer_id] = phantom_set
        phantom_set.update(phantoms)
    else:
        phantom_sets_by_buffer.pop(buffer_id, None)
Example #22
0
def text_document_range_formatting(view: sublime.View,
                                   region: sublime.Region) -> Request:
    return Request("textDocument/rangeFormatting", {
        "textDocument": text_document_identifier(view),
        "options": formatting_options(view.settings()),
        "range": region_to_range(view, region).to_lsp()
    },
                   view,
                   progress=True)
Example #23
0
def get_url_region(view: sublime.View, css_prop: CSSProperty,
                   pos: int) -> sublime.Region:
    "Returns region of matched `url()` token from given value"
    for v in css_prop.value_tokens:
        m = re.match(r'url\([\'"]?(.+?)[\'"]?\)',
                     view.substr(v)) if v.contains(pos) else None
        if m:
            return sublime.Region(v.begin() + m.start(1), v.begin() + m.end(1))
    return None
Example #24
0
    def from_rpc(cls, view: sublime.View, diagnostic: Dict[str, object], /):
        """from rpc"""
        try:
            range_ = diagnostic["range"]
            start = view.text_point(range_["start"]["line"],
                                    range_["start"]["character"])
            end = view.text_point(range_["end"]["line"],
                                  range_["end"]["character"])

            severity = diagnostic["severity"]
            message = diagnostic["message"]
            region = sublime.Region(start, end)

        except Exception as err:
            raise ValueError(
                f"error loading diagnostic from rpc: {err}") from err

        return cls(region, severity, message, diagnostic)
Example #25
0
def point_diagnostics_by_config(view: sublime.View,
                                point: int) -> 'Dict[str, List[Diagnostic]]':
    diagnostics_by_config = {}
    if view.window():
        file_name = view.file_name()
        if file_name:
            window_diagnostics = windows.lookup(
                view.window())._diagnostics.get()
            file_diagnostics = window_diagnostics.get(file_name, {})
            for config_name, diagnostics in file_diagnostics.items():
                point_diagnostics = [
                    diagnostic for diagnostic in diagnostics
                    if range_to_region(diagnostic.range, view).contains(point)
                ]
                if point_diagnostics:
                    diagnostics_by_config[config_name] = point_diagnostics

    return diagnostics_by_config
Example #26
0
def update_diagnostics_regions(view: sublime.View,
                               diagnostics: 'List[Diagnostic]',
                               severity: int) -> None:
    region_name = "lsp_" + format_severity(severity)
    if settings.show_diagnostics_phantoms and not view.is_dirty():
        regions = None
    else:
        regions = list(
            range_to_region(diagnostic.range, view)
            for diagnostic in diagnostics if diagnostic.severity == severity)
    if regions:
        scope_name = diagnostic_severity_scopes[severity]
        view.add_regions(
            region_name, regions, scope_name,
            settings.diagnostics_gutter_marker, UNDERLINE_FLAGS if
            settings.diagnostics_highlight_style == "underline" else BOX_FLAGS)
    else:
        view.erase_regions(region_name)
Example #27
0
    def from_rpc(cls, view: sublime.View, change: Dict[str, object], /):
        """from rpc"""

        try:
            range_ = change["range"]
            new_text = change["newText"]

            start = view.text_point(range_["start"]["line"],
                                    range_["start"]["character"])
            end = view.text_point(range_["end"]["line"],
                                  range_["end"]["character"])

        except Exception as err:
            raise ValueError(f"error loading changes from rpc: {err}") from err

        region = sublime.Region(start, end)
        old_text = view.substr(region)
        return cls(region, old_text, new_text)
	def __init__(self, component: 'Component', view: sublime.View, location: int = -1, layout: int = sublime.LAYOUT_INLINE, on_close: Optional[Callable[[], None]] = None) -> None:
		super().__init__(component, view)
		self.on_close = on_close
		self.location = location
		self.layout = layout
		self.max_height = 500
		self.max_width = 1000
		self.render()
		view.show_popup(self.html,
                  location=location,
                  max_width=self.max_width,
                  max_height=self.max_height,
                  on_navigate=self.on_navigate,
                  flags=sublime.COOPERATE_WITH_AUTO_COMPLETE | sublime.HIDE_ON_MOUSE_MOVE_AWAY,
                  on_hide=self.on_hide)

		_renderables_add.append(self)
		self.is_hidden = False
Example #29
0
def update_diagnostics_in_view(view: sublime.View) -> None:
    if view and view.is_valid():
        file_diagnostics = get_view_diagnostics(view)
        for severity in range(
                DiagnosticSeverity.Error, DiagnosticSeverity.Error +
                settings.show_diagnostics_severity_level):
            update_diagnostics_regions(view, file_diagnostics, severity)

        update_diagnostics_phantoms(view, file_diagnostics)
Example #30
0
def client_for_view(view: sublime.View) -> 'Optional[Client]':
    window = view.window()
    if not window:
        debug("no window for view", view.file_name())
        return None

    config = config_for_scope(view)
    if not config:
        debug("config not available for view", view.file_name())
        return None

    clients = window_clients(window)
    if config.name not in clients:
        debug(config.name, "not available for view", view.file_name(),
              "in window", window.id())
        return None
    else:
        return clients[config.name]
Example #31
0
 def get_completions(self, view: sublime.View,
                     text: str) -> core.awaitable[None]:
     from ..debugger.debugger_interface import DebuggerInterface
     window = view.window()
     m = DebuggerInterface.for_window(window)
     if not m:
         return
     adapter = m.debugger.adapter
     if not adapter:
         return
     self.completions = yield from adapter.Completions(
         text,
         len(text) + 1, m.debugger.selected_frame)
     view.run_command("hide_auto_complete")
     view.run_command("auto_complete", {
         'disable_auto_insert': True,
         'next_completion_if_showing': False
     })
Example #32
0
def view_background_lightness(view: sublime.View) -> float:
	style = view.style()
	if "background" not in style:
		return 0

	color = style["background"].lstrip('#')
	rgb = tuple(int(color[i:i + 2], 16) / 255.0 for i in (0, 2, 4))
	lum = 0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]
	return lum
Example #33
0
    def on_text_command(self, view: sublime.View, cmd: str,
                        args: dict) -> None:
        if cmd == 'drag_select' and 'event' in args:
            view_drag_select.post(view)
            event = args['event']
            # left click
            if event['button'] != 1:
                return

            x = event['x']
            y = event['y']

            pt = view.window_to_text((x, y))
            on_gutter = _is_coord_on_gutter_or_empy_line(view, x, y)
            if not on_gutter:
                return
            self.line = view.rowcol(pt)[0]
            self.was_drag_select = True
    def add_to_view(self, view: sublime.View) -> None:
        for old_view in self.views:
            if old_view.view.id() == view.id():
                old_view.render()
                return

        self.views.append(
            SourceBreakpointView(self, view,
                                 lambda: self.breakpoints.edit(self).run()))
Example #35
0
 def on_load(self, view: sublime.View) -> None:
     file_name = view.file_name()
     if not file_name:
         return
     for fn in opening_files.keys():
         if fn == file_name or os.path.samefile(fn, file_name):
             # Remove it from the pending opening files, and resolve the promise.
             opening_files.pop(fn)[1](view)
             break
Example #36
0
def update_diagnostics_phantoms(view: sublime.View,
                                diagnostics: 'List[Diagnostic]'):
    global phantom_sets_by_buffer

    buffer_id = view.buffer_id()
    if not settings.show_diagnostics_phantoms or view.is_dirty():
        phantoms = None
    else:
        phantoms = list(
            create_phantom(view, diagnostic) for diagnostic in diagnostics)
    if phantoms:
        phantom_set = phantom_sets_by_buffer.get(buffer_id)
        if not phantom_set:
            phantom_set = sublime.PhantomSet(view, "lsp_diagnostics")
            phantom_sets_by_buffer[buffer_id] = phantom_set
        phantom_set.update(phantoms)
    else:
        phantom_sets_by_buffer.pop(buffer_id, None)
Example #37
0
def get_setting_show_open_button(view: sublime.View) -> str:
    from .functions import is_view_too_large

    return get_setting(
        # ...
        "show_open_button_fallback"
        if not view.is_loading() and is_view_too_large(view)
        else "show_open_button"
    )
Example #38
0
def read_image_size(view: sublime.View, src: str):
    "Reads image size of given file, if possible"
    if utils.is_url(src):
        abs_file = src
    elif view.file_name():
        abs_file = utils.locate_file(view.file_name(), src)

    if abs_file:
        file_name = os.path.basename(abs_file)
        name, ext = os.path.splitext(file_name)
        chunk = 2048 if ext.lower() in ('.svg', '.jpg', '.jpeg') else 100
        data = utils.read_file(abs_file, chunk)
        size = get_size(data)
        if size:
            dpi = get_dpi(src)
            return round(size[0] / dpi), round(size[1] / dpi)
    else:
        print('Unable to locate file for "%s" url' % src)
def view_last_typing_timestamp_val(
        view: sublime.View,
        timestamp_s: Optional[float] = None) -> Optional[float]:
    """
    @brief Set/Get the last timestamp (in sec) when "VZWC_char_regions" is updated

    @param view        The view
    @param timestamp_s The last timestamp (in sec)

    @return None if the set mode, otherwise the value
    """

    if timestamp_s is None:
        return view.settings().get("VZWC_last_update_timestamp",
                                   0)  # type: ignore

    view.settings().set("VZWC_last_update_timestamp", timestamp_s)
    return None
Example #40
0
 def __init__(self, view: sublime.View) -> None:
     self.view = view
     self._initialized = False
     self._signature_help_triggers = []  # type: List[str]
     self._signature_help_selector = view.settings().get(
         "auto_complete_selector", "") or ""  # type: str
     self._visible = False
     self._help = None  # type: Optional[SignatureHelp]
     self._renderer = ColorSchemeScopeRenderer(self.view)
Example #41
0
def from_pos(view: sublime.View, pt: int):
    "Returns Emmet syntax for given location in view"
    scopes = get_settings('syntax_scopes', {})
    if scopes:
        for name, sel in scopes.items():
            if view.match_selector(pt, sel):
                return name

    return None
Example #42
0
def get_activation_context(editor: sublime.View, pos: int) -> Config:
    """
    Detects and returns valid abbreviation activation context for given location
    in editor which can be used for abbreviation expanding.
    For example, in given HTML code:
    `<div title="Sample" style="">Hello world</div>`
    it’s not allowed to expand abbreviations inside `<div ...>` or `</div>`,
    yet it’s allowed inside `style` attribute and between tags.

    This method ensures that given `pos` is inside location allowed for expanding
    abbreviations and returns context data about it.

    Default implementation works for any editor since it uses own parsers for HTML
    and CSS but might be slow: if your editor supports low-level access to document
    parse tree or tokens, authors should override this method and provide alternative
    based on editor native features.
    """
    if editor.match_selector(pos, 'meta.attribute-with-value.style string'):
        # Inline CSS
        # TODO detect property value context
        return create_activation_context(
            editor, pos, {'name': CSSAbbreviationScope.Property}, True)

    syntax_name = syntax.from_pos(editor, pos)
    if syntax.is_css(syntax_name):
        ctx = get_css_context(editor, pos)
        if ctx:
            result = create_activation_context(editor, pos, ctx)
            if editor.match_selector(pos, 'meta.at-rule.media'):
                result.options['stylesheet.after'] = ''
            return result

        return None

    if syntax.is_html(syntax_name):
        ctx = get_html_context(editor, pos)
        if syntax.is_jsx(syntax_name) and ctx is None:
            # No luck with context for JSX: but we can still use it
            return create_activation_context(editor, pos)

        return create_activation_context(editor, pos,
                                         ctx) if ctx is not None else None

    return create_activation_context(editor, pos)
Example #43
0
    def complete_function_argument(self, view: sublime.View, prefix, pt):
        func_name = ""
        nest_level = 1
        # Look for the beginning of the current function call's arguments list,
        # while ignoring any nested function call or group.
        for i in range(pt - 1, pt - 32 * 1024, -1):
            ch = view.substr(i)
            # end of nested arguments list or group before caret
            if ch == ")" and not view.match_selector(i, "string, comment"):
                nest_level += 1
                continue
            # begin of maybe nested arguments list or group before caret
            if ch == "(" and not view.match_selector(i, "string, comment"):
                nest_level -= 1
                # Stop, if nesting level drops below start value as this indicates the
                # beginning of the arguments list the function name is of interest for.
                if nest_level <= 0:
                    func_name = view.substr(
                        view.expand_by_class(
                            i - 1,
                            sublime.CLASS_WORD_START | sublime.CLASS_WORD_END))
                    break

        if func_name == "var":
            return [
                sublime.CompletionItem(
                    trigger=symbol,
                    completion_format=sublime.COMPLETION_FORMAT_TEXT,
                    kind=sublime.KIND_VARIABLE,
                    details="var() argument") for symbol in set(
                        view.substr(symbol_region) for symbol_region in
                        view.find_by_selector("entity.other.custom-property"))
                if not prefix or symbol.startswith(prefix)
            ]

        args = self.func_args.get(func_name)
        if not args:
            return None

        completions = []
        details = f"{func_name}() argument"
        for arg in args:
            if isinstance(arg, list):
                completions.append(
                    sublime.CompletionItem(
                        trigger=arg[0],
                        completion=arg[1],
                        completion_format=sublime.COMPLETION_FORMAT_SNIPPET,
                        kind=KIND_CSS_FUNCTION,
                        details=details))
            else:
                completions.append(
                    sublime.CompletionItem(
                        trigger=arg,
                        completion_format=sublime.COMPLETION_FORMAT_TEXT,
                        kind=KIND_CSS_CONSTANT,
                        details=details))

        return completions
Example #44
0
    def on_load(self, view: sublime.View) -> None:
        """Called after load a file
        """

        if (check_linting(view, ONLY_CODE, code=self.lang.lower())
                and check_linting_behaviour(view, ['always', 'load-save'])):
            if self.lang in view.settings().get('syntax'):
                self.run_linter(view)
        else:
            self._erase_marks_if_no_linting(view)
Example #45
0
def expand_local_path(view: sublime.View, url: str) -> str:
    path_aliases = sublime.load_settings(SETTINGS_FILE).get('path_aliases')
    path, filename = os.path.split(url)  # split filename from path because variables should not be expanded within the filename
    window = view.window()
    variables = window.extract_variables() if window else {}
    for alias, replacement in path_aliases.items():
        if path.startswith(alias):
            replacement = sublime.expand_variables(replacement, variables)
            path = path.replace(alias, replacement, 1)
            break
    path = os.path.join(path, filename)  # join back together
    if os.path.isabs(path):
        return path
    else:
        file_name = view.file_name()
        if not file_name:
            return ''
        else:
            return os.path.abspath(os.path.join(os.path.dirname(file_name), path))
Example #46
0
 def match_view(self, view: sublime.View, scheme: str) -> bool:
     syntax = view.syntax()
     if not syntax:
         return False
     # Every part of a x.y.z scope seems to contribute 8.
     # An empty selector result in a score of 1.
     # A non-matching non-empty selector results in a score of 0.
     # We want to match at least one part of an x.y.z, and we don't want to match on empty selectors.
     return scheme in self.schemes and sublime.score_selector(
         syntax.scope, self.selector) >= 8
Example #47
0
 def __call__(self, view: sublime.View) -> bool:
     """Does this filter match the view? An empty filter matches any view."""
     if self.language:
         syntax = view.syntax()
         if not syntax or basescope2languageid(
                 syntax.scope) != self.language:
             return False
     if self.scheme:
         uri = view.settings().get("lsp_uri")
         if isinstance(
                 uri,
                 str) and urllib.parse.urlparse(uri).scheme != self.scheme:
             return False
     if self.pattern:
         if not globmatch(view.file_name() or "",
                          self.pattern,
                          flags=GLOBSTAR | BRACE):
             return False
     return True
Example #48
0
    def on_load(self, view: sublime.View) -> None:
        """Called after load a file
        """

        if (check_linting(view, ONLY_CODE, code=self.lang.lower()) and
                check_linting_behaviour(view, ['always', 'load-save'])):
            if self.lang in view.settings().get('syntax'):
                self.run_linter(view)
        else:
            self._erase_marks_if_no_linting(view)
Example #49
0
File: documents.py Project: nh2/LSP
def notify_did_save(view: sublime.View):
    file_name = view.file_name()
    if file_name:
        if file_name in document_states:
            client = client_for_view(view)
            if client:
                params = {"textDocument": {"uri": filename_to_uri(file_name)}}
                client.send_notification(Notification.didSave(params))
        else:
            debug('document not tracked', file_name)
Example #50
0
def notify_did_close(view: sublime.View):
    file_name = view.file_name()
    window = sublime.active_window()
    if window and file_name:
        if has_document_state(window, file_name):
            clear_document_state(window, file_name)
            client = client_for_closed_view(view)
            if client:
                params = {"textDocument": {"uri": filename_to_uri(file_name)}}
                client.send_notification(Notification.didClose(params))
Example #51
0
def notify_did_close(view: sublime.View):
    file_name = view.file_name()
    window = sublime.active_window()
    if window and file_name:
        if has_document_state(window, file_name):
            clear_document_state(window, file_name)
            client = client_for_closed_view(view)
            if client:
                params = {"textDocument": {"uri": filename_to_uri(file_name)}}
                client.send_notification(Notification.didClose(params))
Example #52
0
    def update(self, view: sublime.View):
        core.log_info("updating settings callback view")
        if self.settings_changed_callback:
            self.settings_changed_callback.dispose()
            self.settings_changed_callback = None

        plugin_settings = sublime.load_settings('debugger.sublime-settings')
        view_settings = view.settings()
        self.settings_changed_callback = SettingsChangedCallbabck(
            [plugin_settings, view_settings], self.on_changed)
def convert_from_data_url(view: sublime.View, region: sublime.Region, dest: str):
    src = view.substr(region)
    m = re.match(r'^data\:.+?;base64,(.+)', src)
    if m:
        base_dir = os.path.dirname(view.file_name())
        abs_dest = utils.create_path(base_dir, dest)
        file_url = os.path.relpath(abs_dest, base_dir).replace('\\', '/')

        dest_dir = os.path.dirname(abs_dest)
        if not os.path.exists(dest_dir):
            os.makedirs(dest_dir)

        with open(abs_dest, 'wb') as fd:
            fd.write(base64.urlsafe_b64decode(m.group(1)))

        view.run_command('convert_data_url_replace', {
            'region': [region.begin(), region.end()],
            'text': file_url
        })
Example #54
0
    def on_activated(self, view: sublime.View) -> None:
        """Called when a view gain the focus
        """

        if (check_linting(
                view, ONLY_CODE | LINTING_ENABLED, code=self.lang.lower()) and
                check_linting_behaviour(view, ['always'])):
            if self.lang in view.settings().get('syntax'):
                self.run_linter(view)
        else:
            self._erase_marks_if_no_linting(view)
Example #55
0
def initialize_on_open(view: sublime.View):
    window = view.window()

    if not window:
        return

    debug("initialize on open", window.id(), view.file_name())

    if window_configs(window):
        unload_old_clients(window)

    window_id = window.id()
    global didopen_after_initialize
    config = config_for_scope(view)
    if config:
        if config.enabled:
            if not is_ready_window_config(window, config.name):
                open_after_initialize_by_window.setdefault(window_id, []).append(view)
                start_window_client(view, window, config)
        else:
            debug(config.name, 'is not enabled')
Example #56
0
    def on_modified(self, view: sublime.View) -> None:
        """Called after changes has been made to a view.
        """

        if not is_python(view, autocomplete_ignore_repl=True):
            return

        global JUST_COMPLETED

        if (view.substr(view.sel()[0].begin() - 1) == '('
                and view.substr(view.sel()[0].begin()) == ')'):
            if JUST_COMPLETED:
                view.run_command('anaconda_complete_funcargs')

            JUST_COMPLETED = False
        elif view.substr(sublime.Region(
                view.sel()[0].begin() - 7, view.sel()[0].end())) == 'import ':
            self._run_auto_complete()
Example #57
0
def _client_for_view_and_window(view: sublime.View, window: 'Optional[sublime.Window]') -> 'Optional[Client]':
    session = _session_for_view_and_window(view, window)

    if session:
        if session.client:
            return session.client
        else:
            debug(session.config.name, "in state", session.state, " for view",
                  view.file_name())
            return None
    else:
        debug('no session found')
        return None
Example #58
0
def update_diagnostics_in_status_bar(view: sublime.View):
    errors = 0
    warnings = 0

    window = view.window()
    if window:
        diagnostics_by_file = get_window_diagnostics(window)

        if diagnostics_by_file:
            for file_path, source_diagnostics in diagnostics_by_file.items():

                if source_diagnostics:
                    for origin, diagnostics in source_diagnostics.items():
                        for diagnostic in diagnostics:

                            if diagnostic.severity == DiagnosticSeverity.Error:
                                errors += 1
                            if diagnostic.severity == DiagnosticSeverity.Warning:
                                warnings += 1

        count = 'E: {} W: {}'.format(errors, warnings)
        view.set_status('code_intel_errors_warning_count', count)
Example #59
0
    def on_post_save(self, view: sublime.View) -> None:
        """Called post file save event
        """

        if check_linting(
                view, NOT_SCRATCH | LINTING_ENABLED, code=self.lang.lower()):
            if self.lang in view.settings().get('syntax'):
                if get_settings(
                        view, "anaconda_linter_show_errors_on_save", False):
                    self.run_linter(view, self._show_errors_list)
                else:
                    self.run_linter(view)
        else:
            self._erase_marks_if_no_linting(view)
Example #60
0
    def on_selection_modified(self, view: sublime.View) -> None:
        """Called on selection modified
        """

        constraints = ONLY_CODE | NOT_SCRATCH | LINTING_ENABLED
        if (not check_linting(view, constraints, code=self.lang.lower()) or
                self.lang not in view.settings().get('syntax')):
            return

        last_selected_line = last_selected_lineno(view)

        if last_selected_line != self.last_selected_line:
            self.last_selected_line = last_selected_line
            update_statusbar(view)