Example #1
0
def should_handle_tab_key(syntax=None):
    view = active_view()
    scopes = settings.get('disabled_single_snippet_for_scopes', None)
    cur_scope = get_scope(view)

    if sublime.score_selector(cur_scope, 'source.css'):
        return True

    if not scopes or not sublime.score_selector(cur_scope, scopes):
        return True

    abbr = ctx.js().locals.pyExtractAbbreviation()
    if not re.match(r'^[\w\:%]+$', abbr):
        # it's a complex expression
        return True

    if re.match(r'^(lorem|lipsum)\d*$', abbr):
        # hardcoded Lorem Ipsum generator
        return True

    # detect inline CSS
    if syntax is None:
        syntax = ctx.js().locals.pyGetSyntax()

    if syntax == 'css':
        return True

    known_tags = settings.get('known_html_tags', '').split()
    if abbr in known_tags or ctx.js().locals.pyHasSnippet(abbr):
        return True

    return False
Example #2
0
def should_handle_tab_key():
    view = active_view()
    scopes = settings.get('disabled_single_snippet_for_scopes', None)
    cur_scope = view.syntax_name(view.sel()[0].begin())

    if sublime.score_selector(cur_scope, 'source.css'):
        return True

    if not scopes or not sublime.score_selector(cur_scope, scopes):
        return True

    abbr = ctx.js().locals.pyExtractAbbreviation()
    if not re.match(r'^\w+$', abbr):
        # it's a complex expression
        return True

    if re.match(r'^(lorem|lipsum)\d*$', abbr):
        # hardcoded Lorem Ipsum generator
        return True

    known_tags = settings.get('known_html_tags', '').split()
    if abbr in known_tags or ctx.js().locals.pyHasSnippet(abbr):
        return True

    return False
Example #3
0
def get_hayaku_options(self):
    settings = self.view.settings()
    options = {}
    match = {}
    # Autoguessing the options
    if settings.get("hayaku_CSS_syntax_autoguess"):
        autoguess = settings.get("hayaku_CSS_syntax_autoguess")
        offset = len(autoguess[0]) - len(autoguess[0].lstrip())
        autoguess = [s[offset:].rstrip() for s in autoguess]

        match = GUESS_REGEX.search('\n'.join(autoguess))

    # Helper to set an option got from multiple sources
    def get_setting(setting, fallback, match_group=False):
        if match_group and match:
            fallback = match.group(match_group)
        single_setting = False
        if settings.has("hayaku_" + setting):
            single_setting = settings.get("hayaku_" + setting, fallback)
        options[setting] = single_setting or fallback

    # Some hardcode for different scopes
    # (could this be defined better?)
    scope_name = self.view.scope_name(self.view.sel()[0].a)
    is_sass = sublime.score_selector(scope_name, 'source.sass') > 0
    is_stylus = sublime.score_selector(scope_name, 'source.stylus') > 0

    disable_braces = is_stylus or is_sass
    if is_stylus and match and match.group(2) and match.group(8):
        disable_braces = False

    disable_colons = is_stylus
    if match and match.group(4):
        disable_colons = False

    disable_semicolons = is_stylus or is_sass
    if is_stylus and match and match.group(6):
        disable_semicolons = False

    # Calling helper, getting all the needed options
    get_setting("CSS_whitespace_block_start_before", " ", 1)
    get_setting("CSS_whitespace_block_start_after", "\n\t", 3)
    get_setting("CSS_whitespace_block_end_before", "\n", 7)
    get_setting("CSS_whitespace_block_end_after", "", 9)
    get_setting("CSS_whitespace_after_colon", " ", 5)
    get_setting("CSS_newline_after_expand", False)
    get_setting("CSS_syntax_no_curly_braces", disable_braces)
    get_setting("CSS_syntax_no_colons", disable_colons)
    get_setting("CSS_syntax_no_semicolons", disable_semicolons)
    get_setting("CSS_prefixes_disable", False)
    get_setting("CSS_prefixes_align", not (is_stylus or is_sass))
    get_setting("CSS_prefixes_only", [])
    get_setting("CSS_prefixes_no_unprefixed", False)
    get_setting("CSS_disable_postexpand", False)
    get_setting("CSS_colors_case", "uppercase")  # or "lowercase" or "initial"
    get_setting("CSS_colors_length", "short")  # or "long"      or "initial"
    get_setting("CSS_clipboard_defaults", ["colors", "images"])

    return options
Example #4
0
def toggle_breakpoint(view):
    try:
        # Get selected point in view
        point = view.sel()[0]
        # Check if selected point uses breakpoint line scope
        if point.size() == 3 and sublime.score_selector(
                view.scope_name(point.a), 'xdebug.output.breakpoint.line'):
            # Find line number of breakpoint
            line = view.substr(view.line(point))
            pattern = re.compile(
                '^\\s*(?:(\\|\\+\\|)|(\\|-\\|))\\s*(?P<line_number>\\d+)\\s*(?:(--)(.*)|.*)'
            )
            match = pattern.match(line)
            # Check if it has found line number
            if match and match.group('line_number'):
                # Get all breakpoint filenames
                breakpoint_file = view.find_by_selector(
                    'xdebug.output.breakpoint.file')
                # Locate line with filename related to selected breakpoint
                file_line = None
                for entry in breakpoint_file:
                    # Stop searching if we have passed selected breakpoint
                    if entry > point:
                        break
                    file_line = view.substr(view.line(entry))
                # Do not continue without line containing filename
                if file_line is None:
                    return
                # Remove unnecessary text from line to get filename
                file_pattern = re.compile('^\\s*(=>)\\s*(?P<filename>.*)')
                file_match = file_pattern.match(file_line)
                # Check if it is a valid filename
                if file_match and file_match.group('filename'):
                    filename = file_match.group('filename')
                    line_number = match.group('line_number')
                    enabled = None
                    # Disable breakpoint
                    if sublime.score_selector(
                            view.scope_name(point.a), 'entity'
                    ) and S.BREAKPOINT[filename][line_number]['enabled']:
                        enabled = False
                    # Enable breakpoint
                    if sublime.score_selector(
                            view.scope_name(point.a), 'keyword'
                    ) and not S.BREAKPOINT[filename][line_number]['enabled']:
                        enabled = True
                    # Toggle breakpoint only if it has valid value
                    if enabled is None:
                        return
                    sublime.active_window().run_command(
                        'xdebug_breakpoint', {
                            "enabled": enabled,
                            "rows": [line_number],
                            "filename": filename
                        })
    except:
        pass
Example #5
0
 def extract_inline_latex_scope(view, point):
     """Like extract_scope(), but extracts the extent of meta.inline_latex.fortran."""
     ltxscope = "meta.inline_latex.fortran"
     istart = point
     iend = point
     while istart > 0 and sublime.score_selector(
             view.scope_name(istart - 1), ltxscope) > 0:
         istart = istart - 1
     while iend < view.size() and sublime.score_selector(
             view.scope_name(iend), ltxscope) > 0:
         iend = iend + 1
     r = sublime.Region(istart, iend)
     if r.size() > 1000:
         r = sublime.Region(point, point)
     return r
Example #6
0
def toggle_watch(view):
    # Do not try to toggle when no watch expressions defined
    if not S.WATCH:
        return
    try:
        # Get selected point in view
        point = view.sel()[0]
        # Check if selected point uses watch entry scope
        if point.size() == 3 and sublime.score_selector(
                view.scope_name(point.a), 'meta.xdebug.watch.line'):
            # Determine if watch entry is enabled or disabled
            line = view.substr(view.line(point))
            pattern = re.compile(
                '^(?:(?P<enabled>\\|\\+\\|)|(?P<disabled>\\|-\\|))\\.*')
            match = pattern.match(line)
            if match and (match.group('enabled') or match.group('disabled')):
                # Get all entries and determine index by line/point match
                watch = view.find_by_selector('meta.xdebug.watch.line')
                watch_entries = [
                    watch_entry for watch_region in watch
                    for watch_entry in view.split_by_newlines(watch_region)
                ]
                watch_index = 0
                for entry in watch_entries:
                    # Stop searching if we have passed selected expression
                    if entry > point:
                        break
                    # Only increment watch index when it contains expression
                    watch_line = view.substr(view.line(entry))
                    watch_match = pattern.match(watch_line)
                    if watch_match and (watch_match.group('enabled')
                                        or watch_match.group('disabled')):
                        watch_index += 1
                # Disable watch expression
                if sublime.score_selector(
                        view.scope_name(point.a),
                        'entity') and S.WATCH[watch_index]['enabled']:
                    S.WATCH[watch_index]['enabled'] = False
                # Enable watch expression
                if sublime.score_selector(
                        view.scope_name(point.a),
                        'keyword') and not S.WATCH[watch_index]['enabled']:
                    S.WATCH[watch_index]['enabled'] = True
                # Update watch view and save watch data to file
                sublime.active_window().run_command('xdebug_watch',
                                                    {'update': True})
    except:
        pass
Example #7
0
    def on_hover(self, view, point, hover_zone):
        if "Fortran" not in view.settings().get('syntax'):
            return
        if view.settings().get('fortran_disable_latex', False):
            return
        if hover_zone != sublime.HOVER_TEXT:
            return
        scope = view.scope_name(point)
        score = sublime.score_selector(scope, "meta.inline_latex.fortran")
        if score > 0:
            # We are hovering over some embedded latex
            region = InlineLatexHover.extract_inline_latex_scope(view, point)
            latex = view.substr(region)
            # bg, fg = 'ffffff', '222222'
            bg, fg = InlineLatexHover.get_colors(view)

            params = urllib.parse.urlencode({
                'cht': "tx",
                'chl': latex,
                'chf': 'bg,s,' + bg,
                'chco': fg
            })
            imgurl = "http://chart.googleapis.com/chart?" + params
            try:
                response = urllib.request.urlopen(imgurl)
                rawdata = response.read()
                imgdata = b64encode(rawdata).decode()
                html_str = '<img src="data:image/png;base64,%s" />' % imgdata
            except (urllib.error.HTTPError) as e:
                html_str = '<span class="error">%s<span/>' % str(e)
            view.show_popup(html_str, sublime.HIDE_ON_MOUSE_MOVE, point)
 def check_scope(self):
     scope = self.view.scope_name(self.view.sel()[0].a)
     allowed_scopes = ['source.js', 'source.coffee']
     score = 0
     for a in allowed_scopes:
         score = score + sublime.score_selector(scope, a)
     return score > 0
    def get_color(self, scope_key):
        """
        Simplified version of the guess_color function from MdPopups which simply return the foreground color or a scope
        """

        color = self.special_colors['foreground']['color']
        if scope_key in self.matched:
            color = self.matched[scope_key]["color"]
        else:
            best_match_bg = 0
            best_match_fg = 0
            best_match_style = 0
            best_match_sfg = 0
            best_match_fg_gradient = 0
            for key in self.colors:
                match = sublime.score_selector(scope_key, key)
                if (
                    not self.colors[key]['color_gradient'] and
                    self.colors[key]["color"] is not None and
                    match > best_match_fg
                ):
                    best_match_fg = match
                    color = self.colors[key]["color"]

            self.matched[scope_key] = {"color": color}

        return color
Example #10
0
 def on_modified(self, view):
     if sublime.score_selector(view.scope_name(view.sel()[0].b),
                               'source.php') == 0:
         return
     editor = PhpCoder().editor(view)
     doComplete = False
     line = editor.before()
     if len(line) == 0:
         return
     if re.match(r'.*[,\(]\s*$', line) or line[-1] == '$' or re.match(
             r'.*new [a-zA-Z0-9_]*$', line) or re.match(
                 r'(^|\s+)[a-zA-Z]+$', line):
         doComplete = True
     else:
         expr = editor.expr()
         if expr and expr['prefix'][:2] in ['::', '->']:
             doComplete = True
     if doComplete:
         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 #11
0
def show_context_output(view):
    """
    Show selected variable in an output panel when clicked in context window.

    Keyword arguments:
    view -- View reference which holds the context window.
    """
    # Check if there is a debug session and context data
    if S.SESSION and S.SESSION.connected and S.CONTEXT_DATA:
        try:
            # Get selected point in view
            point = view.sel()[0]
            # Check if selected point uses variable scope
            if point.size() == 0 and sublime.score_selector(view.scope_name(point.a), 'variable'):
                # Find variable in line which contains the point
                line = view.substr(view.line(point))
                pattern = re.compile('^\\s*(\\$.*?)\\s+\\=')
                match = pattern.match(line)
                if match:
                    # Get variable details from context data
                    variable_name = match.group(1)
                    variable = get_context_variable(S.CONTEXT_DATA, variable_name)
                    if variable:
                        # Convert details to text output
                        variables = H.new_dictionary()
                        variables[variable_name] = variable
                        data = generate_context_output(variables)
                        # Show context variables and children in output panel
                        window = sublime.active_window()
                        panel = window.get_output_panel('xdebug')
                        panel.run_command("xdebug_view_update", {'data' : data} )
                        panel.run_command('set_setting', {"setting": 'word_wrap', "value": True})
                        window.run_command('show_panel', {"panel": 'output.xdebug'})
        except:
            pass
Example #12
0
def erlang_goto_definition(window, symbol=None):
    if symbol is not None:
        return None

    view = window.active_view()
    point = view.sel()[0].begin()
    scope = view.scope_name(point)
    symbol = view.substr(view.word(point))

    scores = map(lambda s: sublime.score_selector(scope, s[1]), PREFIX_MAP)
    (maxscore, match) = max(zip(scores, PREFIX_MAP), key=lambda z: z[0])
    kind = match[0]

    if maxscore == 0:
        gotosym = symbol
    elif kind == 'Macro':
        gotosym = kind + ': ' + strip_before('?', symbol)
    elif kind == 'Record':
        gotosym = kind + ': ' + strip_before('#', symbol)
    elif kind == 'Function':
        return GotoExactDefinition(view).at_position(kind, point)
    elif kind == 'Type':
        return GotoExactDefinition(view).at_position(kind, point)
    else:
        gotosym = kind + ': ' + symbol
    return ('goto_definition', {'symbol': gotosym})
def find_matches(scope, founds):
    global _schemeEditor

    ret = []
    maxscore = 0

    # find the scope in the xml that matches the most
    for found in founds:
        foundstr = _schemeEditor.substr(found)
        pos = foundstr.find('<string>') + 8
        foundstr = foundstr[pos:-9]
        foundstrs = foundstr.split(',')
        fstrlen = 0
        for fstr in foundstrs:
            fstrlen = len(fstr)
            fstr = fstr.lstrip(' ')
            padleft = fstrlen - len(fstr)
            fstr = fstr.rstrip(' ')
            score = sublime.score_selector(scope, fstr)
            if score > 0:
                a = found.a + pos + padleft
                ret.append([score, sublime.Region(a, a + len(fstr))])
            pos += fstrlen + 1

    if len(ret) == 0:
        return None
    else:
        return ret
Example #14
0
    def run(self, edit, **kw):
        view = active_view()
        if settings.get('clear_fields_on_enter_key', False):
            view.run_command('clear_fields')

        snippet = '\n${0}'

        if len(view.sel()) > 1:
            return view.run_command('insert_snippet', {'contents': snippet})

        # let's see if we have to insert formatted linebreak
        caret_pos = view.sel()[0].begin()
        scope = view.syntax_name(caret_pos)
        if sublime.score_selector(
                scope, settings.get('formatted_linebreak_scopes', '')):
            snippet = '\n\t${0}\n'

        # Looks like ST2 has buggy scope matcher: sometimes it will call
        # this action even if context selector forbids that.
        # Thus, we have to manually filter it.
        elif 'source.' not in scope:
            # checking a special case: caret right after opening tag,
            # but not exactly between pairs
            if view.substr(sublime.Region(caret_pos - 1, caret_pos)) == '>':
                line_range = view.line(caret_pos)
                line = view.substr(
                    sublime.Region(line_range.begin(), caret_pos)) or ''
                m = re.search(
                    r'<(\w+\:?[\w\-]*)(?:\s+[\w\:\-]+\s*=\s*([\'"]).*?\1)*\s*>$',
                    line)
                if m and m.group(1).lower() not in settings.get(
                        'empty_elements', '').split():
                    snippet = '\n\t${0}'

        view.run_command('insert_snippet', {'contents': snippet})
Example #15
0
    def run(self, edit, **kw):
        view = active_view()
        if settings.get('clear_fields_on_enter_key', False):
            view.run_command('clear_fields')

        snippet = '\n${0}'

        if len(view.sel()) > 1:
            return view.run_command('insert_snippet', {'contents': snippet})

        # let's see if we have to insert formatted linebreak
        caret_pos = view.sel()[0].begin()
        scope = view.syntax_name(caret_pos)
        if sublime.score_selector(
                scope, settings.get('formatted_linebreak_scopes', '')) > 0:
            snippet = '\n\t${0}\n'
        else:
            # checking a special case: caret right after opening tag,
            # but not exactly between pairs
            if view.substr(sublime.Region(caret_pos - 1, caret_pos)) == '>':
                line_range = view.line(caret_pos)
                line = view.substr(
                    sublime.Region(line_range.begin(), caret_pos)) or ''
                if re.search(
                        r'<\w+\:?[\w\-]*(?:\s+[\w\:\-]+\s*=\s*([\'"]).*?\1)*\s*>$',
                        line) is not None:
                    snippet = '\n\t${0}'

        view.run_command('insert_snippet', {'contents': snippet})
Example #16
0
    def on_selection_modified(self):
        '''
        Show selected variable in an output panel when clicked
        '''
        if protocol and protocol.connected and self.context_data:
            data = ''
            point = self.view.sel()[0].a
            var_name = self.view.substr(self.view.word(point))
            if not var_name.startswith('$'):
                var_name = '$' + var_name
            is_variable = sublime.score_selector(self.view.scope_name(point), 'variable')

            if is_variable and var_name in self.context_data:
                kind = self.context_data[var_name]['type']
                if kind == 'array' or kind == 'object':
                    for key in sorted(self.context_data.keys()):
                        if key.startswith(var_name):
                            data += '{k} ({t}) = {d}\n'.format(k=key, t=self.context_data[key]['type'], d=self.context_data[key]['data'])
                else:
                    data += '{k} ({t}) = {d}\n'.format(k=var_name, t=kind, d=self.context_data[var_name]['data'])

            window = self.view.window()
            if window:
                output = window.get_output_panel('xdebug_inspect')
                edit = output.begin_edit()
                output.erase(edit, sublime.Region(0, output.size()))
                output.insert(edit, 0, data)
                output.end_edit(edit)
                window.run_command('show_panel', {"panel": 'output.xdebug_inspect'})
Example #17
0
    def is_applicable(cls, settings):
        this_syntax = settings.get("syntax")
        for syntax in sublime.list_syntaxes():
            for scope in uri_setting("active_scopes"):
                if syntax.path == this_syntax:
                    if sublime.score_selector(syntax.scope, scope):
                        return True

        return False
Example #18
0
    def run(self, edit):
        if sublime.score_selector(self.view.scope_name(self.view.sel()[0].b),
                                  'source.php') == 0:
            return
        if self.fromMouseEvent:
            old_sel = [r for r in self.view.sel()]
            self.view.run_command("drag_select",
                                  {'event': self.fromMouseEvent})
            new_sel = self.view.sel()[0]
        editor = PhpCoder().editor(self.view)
        offset = 0
        pos = editor.getPosition()
        while re.match(r'[a-zA-Z_][a-zA-Z0-9_]*',
                       editor.substr(pos + offset, pos + offset + 1)):
            offset += 1
        expr = editor.expr()

        if expr:
            expr['prefix'] += editor.substr(pos, pos + offset)
            if editor.substr(pos + offset, pos + offset + 1) == '(':
                expr['prefix'] += '()'
        else:
            wordRegion = self.view.word(self.view.sel()[0])
            expr = {'prefix': '', 'expr': self.view.substr(wordRegion)}
            if editor.substr(wordRegion.begin() - 1,
                             wordRegion.begin()) == '$':
                expr['expr'] = '$' + expr['expr']

        if expr['expr']:
            resolver = phpcoder.resolver.Resolver(editor)
            self.prefix = None
            if expr['prefix']:
                parsedPrefix = resolver.parseExpression('Dummy' +
                                                        expr['prefix'])
                if parsedPrefix and len(parsedPrefix) > 1:
                    self.prefix = parsedPrefix[1]['name']
            self.matches = []
            for r in resolver.resolve(expr['expr']):
                if self.prefix == None or \
                    ('properties' in r and self.prefix in r['properties']) or \
                    ('methods' in r and self.prefix in r['methods']):
                    self.matches.append(r)

            results = []
            for r in self.matches:
                results.append([
                    r['name'] + expr['prefix'],
                    r['path'],
                ])
            if len(results) == 1:
                self.panel_on_select(0)
            elif len(results) > 0:
                self.view.window().show_quick_panel(
                    results,
                    self.panel_on_select,
                    on_highlight=self.panel_on_highlight)
Example #19
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 #20
0
    def get_CSS_declarations(self):
        if not sublime.score_selector(
                self.view.scope_name(self.region.a),
                'source.css, source.less, source.sass, source.scss, source.stylus, source.postcss'
        ):
            return False

        return self.get_closest_value(
            self.view.substr(self.view.line(self.region)),
            self.view.line(self.region).begin(), r'([^;]+;?)',
            r'^\s*\/\*|^\W+$')
Example #21
0
def find_css_selector(view, start_pt):
    conds = [track_scope(CSS_SELECTOR)]

    if not sublime.score_selector(view.scope_name(start_pt), CSS_SELECTOR):
        # if not view.score_selector((start_pt), CSS_SELECTOR):
        conds.insert(0, track_scope(CSS_SELECTOR, False))

    selector = back_track(view, start_pt, *conds)[-1]

    if selector is not None:
        return view.substr(selector).strip()
Example #22
0
	def run(self, edit, **kw):
		view = active_view()
		if settings.get('clear_fields_on_enter_key', False):
			view.run_command('clear_fields')

		# let's see if we have to insert formatted linebreak
		scope = view.syntax_name(view.sel()[0].begin())
		if sublime.score_selector(scope, 'meta.scope.between-tag-pair.html, meta.scope.between-tag-pair.xml') > 0:
			view.run_command('insert_snippet', {'contents': '\n\t${0}\n'})
		else:
			view.run_command('insert_snippet', {'contents': '\n${0}'})
Example #23
0
def find_common_scopes(scopes, skip_syntax_suffix):
    """Find the (partial) scopes that are common for a list of scopes.

    Example of unique scopes for the following Python code (and test positions):

    def function():
    ^^^^^^^^^^^^^^
    [
      'source.python meta.function.python storage.type.function.python',
      'source.python meta.function.python',
      'source.python meta.function.python entity.name.function.python',
      'source.python meta.function.parameters.python punctuation.section.parameters.begin.python'
    ]

    The common scope for these, ignoring the base scope, will be 'meta.function'
    """

    # we will use the scopes from index 0 and test against the scopes from the further indexes
    # as any scopes that doesn't appear in this index aren't worth checking, they can't be common

    # skip the base scope i.e. `source.python`
    check_scopes = next(iter(scopes)).split()[1:]

    shared_scopes = ''
    # stop as soon as at least one shared scope was found
    # or when there are no partial scopes left to check
    while not shared_scopes and check_scopes:
        if not skip_syntax_suffix:
            for check_scope in check_scopes:
                # check that the scope matches when combined with the shared scopes that have
                # already been discovered, because order matters (a space in a scope selector
                # is an operator, meaning the next scope must appear somewhere to the right
                # of the one before), and some scopes may appear more than once
                compare_with = shared_scopes + check_scope
                if all(
                        sublime.score_selector(scope, compare_with) > 0
                        for scope in scopes):
                    shared_scopes += check_scope + ' '

        # if no matches were found
        if not shared_scopes:
            # split off the last partial scope from each scope to check
            # i.e. `meta.function.parameters` becomes `meta.function`
            # if the scope to check doesn't contain any sub-scopes i.e. `meta`,
            # then drop it from the list of scopes to check
            check_scopes = [
                '.'.join(check_scope.split('.')[0:-1])
                for check_scope in check_scopes if '.' in check_scope
            ]
            skip_syntax_suffix = False

    return shared_scopes.strip()
Example #24
0
  def run(self, edit):
    scope_name = self.view.scope_name(self.view.sel()[0].a)
    selectors = self.parse_theme(self.load_theme())
    best, bestScore = '', 0
    for selector in selectors:
      score = sublime.score_selector(scope_name, selector)
      if score > bestScore:
        bestScore = score
        best = selector

    str = "Selector: |%s| Scope: |%s| Score %d " % (best, scope_name, bestScore)
    print str
    sublime.status_message(str)
Example #25
0
 def on_query_completions(self, view, prefix, locations):
     if sublime.score_selector(view.scope_name(view.sel()[0].b),
                               'source.php') == 0:
         return
     editor = PhpCoder().editor(view)
     resolver = phpcoder.resolver.Resolver(editor)
     line = editor.before()
     if re.match(r'.*[,\(]\s*$', line):
         return self._completeParams(editor, resolver)
     if re.match(r'.*new [a-zA-Z0-9_]*$', line):
         return self._completeNew(view)
     if line[-1] == '$':
         return editor.findLocals()
     expr = editor.expr()
     if expr:
         return self._completeExpr(expr, editor, resolver)
     return []
Example #26
0
    def run(self, edit, point=None):
        # TODO: take a list of positions instead?
        if point is None:
            point = self.view.sel()[0].begin()

        # if the mouse cursor is hovering at |SOL#, take the sharp token as well
        check_tokens = self.view.extract_tokens_with_scopes(sublime.Region(point, point + 4))
        if len(check_tokens) > 1:
            token_to_show = check_tokens[0]
            if sublime.score_selector(check_tokens[1][1], 'constant.language.sharp') > 0:
                token_to_show = check_tokens[1]
            point = token_to_show[0].end()

        # we could get all the tokens, but we don't need anything after the mouse cursor to show the state, so this saves time
        # and makes it easier to get the parse_state for the token under the mouse cursor - it's the last token we parsed
        instructions = piano_tunes.parse_piano_tune(piano_tunes.get_tokens_from_regions(self.view, [sublime.Region(0, point)]))
        # get the last instruction from an iterator
        # https://stackoverflow.com/a/3169701/4473405
        # (seems less wasteful than making it a list to get the -1 index)
        parse_state = deque(piano_tunes.resolve_piano_tune_instructions(instructions), maxlen=1).pop()

        note_index = parse_state.instruction.value
        self.view.show_popup(
            f'''
            <body>
                <span>Note:</span>&nbsp;
                <span>{PianoMidi.notes_letters[note_index]}</span>
                <br />
                <span>Solfege:</span>&nbsp;
                <span>{PianoMidi.notes_solfege[note_index]}</span>
                <br />
                <span>Note Length:</span>&nbsp;
                <span>{parse_state.current_length}</span>
                <br />
                <span>Note Octave:</span>&nbsp;
                <span>{parse_state.current_octave}</span>
                <br />
                <a href="play"><span>Midi Note:</span>&nbsp;
                <span>{PianoMidi.note_to_midi_note(parse_state.current_octave, note_index)}</span></a>
                <br />
                <span>Time Elapsed:</span>&nbsp;
                <span>{parse_state.time_elapsed:.3f} ms</span>
            </body>
            ''', sublime.HIDE_ON_MOUSE_MOVE_AWAY, point,
            on_navigate=lambda _: self.play_note(parse_state)
        )
Example #27
0
def get_selector_style_map(view, selectors):
    styles = {}

    if int(sublime.version()) > 3153:
        for s in selectors:
            styles[s] = view.style_for_scope(s)
    else:
        color_scheme = get_color_scheme()
        top_scores = {}
        for s in selectors:
            for scope in color_scheme["scopes"]:
                score = sublime.score_selector(s, scope["scope"])
                top_score = top_scores.get(s, 0)
                if score > 0 and score >= top_score:
                    top_scores[s] = score
                    styles[s] = scope["style"]
    return styles
Example #28
0
def toggle_stack(view):
    try:
        # Get selected point in view
        point = view.sel()[0]
        # Check if selected point uses stack entry scope
        if point.size() > 3 and sublime.score_selector(view.scope_name(point.a), 'xdebug.output.stack.entry'):
            # Get fileuri and line number from selected line in view
            line = view.substr(view.line(point))
            pattern = re.compile('^(\[\d+\])\s*(?P<fileuri>.*)(\..*)(\s*:.*?(?P<lineno>\d+))\s*(\((.*?):.*\)|$)')
            match = pattern.match(line)
            # Show file when it's a valid fileuri
            if match and match.group('fileuri'):
                filename = get_real_path(match.group('fileuri'))
                lineno = 0
                if match.group('lineno'):
                    lineno = match.group('lineno')
                show_file(filename, lineno)
    except:
        pass
Example #29
0
    def at_point(self, point):
        scope = self.view.scope_name(point).strip()

        if scope in self.scope_style_cache:
            return self.scope_style_cache[scope]

        style = self.default_styles.copy()

        scored_styles = []
        for rule in self.json['rules']:
            if 'scope' in rule:
                score = score_selector(scope, rule['scope'])

                if 'foreground' in rule:
                    fg = rule['foreground']
                    color = fg
                    if fg in self.json_variables_dict:
                        color = self.json_variables_dict[fg]

                    rule.update({'foreground': color.lower()})

                if 'background' in rule:
                    bg = rule['background']
                    color = bg
                    if bg in self.json_variables_dict:
                        color = self.json_variables_dict[bg]

                    rule.update({'background': color.lower()})

                if 'font_style' in rule:
                    rule.update({'fontStyle': rule['font_style']})

                if score:
                    rule.update({'score': score})
                    scored_styles.append(rule)

        for s in sorted(scored_styles, key=lambda k: k['score']):
            style.update(s)

        self.scope_style_cache[scope] = style

        return style
    def at_point(self, point):
        scope = self.view.scope_name(point).strip()

        if scope in self.scope_style_cache:
            return self.scope_style_cache[scope]

        style = self.default_styles.copy()

        scored_styles = []
        for color_scheme_definition in self.plist['settings']:
            if 'scope' in color_scheme_definition:
                score = score_selector(scope, color_scheme_definition['scope'])
                if score:
                    color_scheme_definition.update({'score': score})
                    scored_styles.append(color_scheme_definition)

        for s in sorted(scored_styles, key=lambda k: k['score']):
            style.update(s['settings'])

        self.scope_style_cache[scope] = style

        return style