def style_all(self, view, file_name): if file_name: if file_name.split('.')[-1] == FILE_EXTENSION: self.tag_phantoms = sublime.PhantomSet(view, 'todo-tags') view.erase_phantoms('todo-tags') self.style_tags(view.find_all(r'\[.*?\]')) self.due_phantoms = sublime.PhantomSet(view, 'todo-due') view.erase_phantoms('todo-due') self.style_due_today(view) self.current_phantoms = sublime.PhantomSet(view, 'todo-current') view.erase_phantoms('todo-current') self.style_current(view)
def show(view, marker, as_phantom=False): "Displays Emmet abbreviation as a preview for given view" content = None buffer_id = view.buffer_id() try: content = format_snippet(marker.preview()) except Exception as e: content = '<div class="error">%s</div>' % format_snippet(str(e)) if content: if as_phantom: if buffer_id not in phantom_sets_by_buffer: phantom_set = sublime.PhantomSet(view, 'emmet') phantom_sets_by_buffer[buffer_id] = phantom_set else: phantom_set = phantom_sets_by_buffer[buffer_id] r = sublime.Region(marker.region.end(), marker.region.end()) phantoms = [ sublime.Phantom(r, phantom_content(content), sublime.LAYOUT_INLINE) ] phantom_set.update(phantoms) elif not view.is_popup_visible() or previews_by_buffer.get( buffer_id, None) != marker.abbreviation: previews_by_buffer[buffer_id] = marker.abbreviation view.show_popup(popup_content(content), sublime.COOPERATE_WITH_AUTO_COMPLETE, marker.region.begin(), 400, 300)
def update_phantoms(patch, self): """Create our own phantoms.""" for file, errs in self.errs_by_file.items(): view = self.window.find_open_file(file) if view: buffer_id = view.buffer_id() if buffer_id not in self.phantom_sets_by_buffer: phantom_set = sublime.PhantomSet(view, "exec") self.phantom_sets_by_buffer[buffer_id] = phantom_set else: phantom_set = self.phantom_sets_by_buffer[buffer_id] # use the rulers as an approximate maximum width rulers = view.settings().get("rulers", []) width = int((rulers[0] or 80) * 1.25) phantoms = [] for line, column, text in errs: if not text: continue # break the text up into shorter lines to make reading easier lines = textwrap.wrap(text, width) lines = [html.escape(l, quote=False) for l in lines] text = "<br>".join(lines) phantoms.append( generate_phantom(self, view, line, column, text)) phantom_set.update(phantoms)
def show_html(md_view, preview): global windows_phantom_set html = markdown2html(get_view_content(md_view), os.path.dirname(md_view.file_name()), md_view.settings().get('color_scheme')) phantom_set = windows_phantom_set.setdefault( preview.window().id(), sublime.PhantomSet(preview, 'markdown_live_preview')) phantom_set.update([ sublime.Phantom( sublime.Region(0), html, sublime.LAYOUT_BLOCK, lambda href: sublime.run_command('open_url', {'url': href})) ]) # lambda href: sublime.run_command('open_url', {'url': href}) # get the "ratio" of the markdown view's position. # 0 < y < 1 y = md_view.text_to_layout( md_view.sel()[0].begin())[1] / md_view.layout_extent()[1] # set the vector (position) for the preview vector = [0, y * preview.layout_extent()[1]] # remove half of the viewport_extent.y to center it on the screen (verticaly) vector[1] -= preview.viewport_extent()[1] / 2 # make sure the minimum is 0 vector[1] = 0 if vector[1] < 0 else vector[1] # the hide the first line vector[1] += preview.line_height() preview.set_viewport_position(vector, animate=False)
def __init__(self, symbol, current_position, matches, commonprefix): self.name = "Toks: " + symbol sublime.active_window().destroy_output_panel(self.name) self.op = sublime.active_window().create_output_panel(self.name) sublime.active_window().run_command("show_panel", {"panel": "output." + self.name}) contents = "<b><a href=$hide style=\"text-decoration: none\">" + chr( 0x00D7) + "</a> " + symbol + "</b>" if isinstance(current_position, str): contents += " (<a href=" + os.path.join( commonprefix, current_position) + ">" + current_position + "</a>)" else: contents += " (<a href=$back>" + "unsaved view" + "</a>)" self.pre_lookup_view = current_position contents += "<ul>" for match in matches: contents += "<li><a href=" + os.path.join( commonprefix, match[0]) + ">" + match[0] + "</a> " + html.escape( match[1], quote=False) + " " + match[2] + "</li>" contents += "</ul>" self.phantom = sublime.Phantom(self.op.sel()[0], '<body>' + contents + '</body>', sublime.LAYOUT_INLINE, on_navigate=self.on_phantom_navigate) self.phantomset = sublime.PhantomSet(self.op, "toks") self.phantomset.update([self.phantom])
def __init__(self, view): self.view = view self.phantom_set = sublime.PhantomSet(view, 'plain_tasks_remain_time') self.view.settings().add_on_change('plain_tasks_remain_time_phantoms', self.check_setting) self.phantoms = self.view.settings().get( 'plain_tasks_remain_time_phantoms', [])
def on_modified(self, view): if 'text.git-commit-message' not in view.scope_name(0): return first_line = view.line(0) text = view.substr(first_line) html = text.replace(' ', ' ') with open(os.path.join(__file__, '..', 'emojis.json')) as fp: for alias, base64 in json.load(fp).items(): html = html.replace( ':{}:'.format(alias), '<img src="data:image/png;base64,{0}" height="{1}" width="{1}"/>' .format(base64, view.line_height() - 2)) length = len(EMOJI_ALIASES.sub(' ', text)) color = 'var(--' + ('greenish' if length <= 50 else 'redish') html += ' <span style="color: {}"> → {}</span>'.format(color, length) view_id = view.id() ps = phantom_sets.get(view_id) or sublime.PhantomSet( view, 'commit-msg-preview') phantom_sets[view_id] = ps ps.update([sublime.Phantom(first_line, html, sublime.LAYOUT_BLOCK)])
def display_images(self): view = self.window.active_view() phantom_set = self.phantom_sets.get( view.id(), sublime.PhantomSet(view, "scitzen")) def phantom_for(image_desc) -> sublime.Phantom: region = sublime.Region(image_desc["start"], image_desc["end"]) img = image_desc["file"] html_format = ''' <img src="file://{}" style="width: {}; height: {};"> ''' sizings = self.good_size(view, img) if not sizings: return (width, height) = sizings html_img = html_format.format(img, width, height) return sublime.Phantom(region, html_img, sublime.LAYOUT_BLOCK) # view.add_phantom("scitzen", region, html_img, sublime.LAYOUT_BLOCK) image_file_map = self.load_image_file_map() view.erase_phantoms("scitzen") file_name = view.file_name() # for desc in image_file_map[file_name]: # phantom_for(desc) phantoms = list( filter(lambda x: not not x, map(phantom_for, image_file_map[file_name]))) phantom_set.update(phantoms) self.phantom_sets[view.id()] = phantom_set
def update_phantoms(self, view): # Display phantoms for embeds self.phantom_set = sublime.PhantomSet(view) phantoms = [] for region in view.find_by_selector( 'meta.brackets markup.underline.link.embed'): link = view.substr(region) note_name = note_name_from_link(link) note_path = path_to_note(view, note_name) extension = file_extension(note_name) if extension == None: lines = open(note_path, 'r').readlines() note_content = ''.join( ['<p>' + line + '</p>' for line in lines]) phantom_content = NOTE_EMBED_TEMPLATE.format(note_content) phantom = sublime.Phantom(region, phantom_content, sublime.LAYOUT_BLOCK) phantoms.append(phantom) elif is_image_extension(extension): log('embed jpg') note_content = IMAGE_EMBED_TEMPLATE.format(note_path) phantom = sublime.Phantom(region, note_content, sublime.LAYOUT_BLOCK) phantoms.append(phantom) self.phantom_set.update(phantoms)
def show_phantoms(self, view): """Show phantoms for compilation errors. Args: view (sublime.View): current view """ view.erase_phantoms(PopupErrorVis._TAG) if view.buffer_id() not in self.phantom_sets: phantom_set = sublime.PhantomSet(view, PopupErrorVis._TAG) self.phantom_sets[view.buffer_id()] = phantom_set else: phantom_set = self.phantom_sets[view.buffer_id()] phantoms = [] current_error_dict = self.err_regions[view.buffer_id()] for err in current_error_dict: errors_dict = current_error_dict[err] errors_html = PhantomErrorVis._as_html(errors_dict) pt = view.text_point(err - 1, 1) phantoms.append( sublime.Phantom(sublime.Region(pt, view.line(pt).b), errors_html, sublime.LAYOUT_BELOW, on_navigate=self._on_phantom_navigate)) phantom_set.update(phantoms)
def __init__(self, view): """Initialize view event listener object.""" # Need this "hack" to allow reloading of the module, # because `super` tries to use the old reference (I think?). # See also https://lists.gt.net/python/python/139992 sublime_plugin.ViewEventListener.__init__(self, view) filepath = view.file_name() l.debug("initializing SettingsListener for %r", view.file_name()) if filepath and filepath.endswith(".sublime-settings"): filename = os.path.basename(filepath) self.known_settings = KnownSettings(filename) self.known_settings.add_on_loaded(self.do_linting) elif filepath and filepath.endswith(".sublime-project"): self.known_settings = KnownSettings("Preferences.sublime-settings") self.known_settings.add_on_loaded(self.do_linting) else: self.known_settings = None l.error("Not a Sublime Text Settings or Project file: %r", filepath) self.phantom_set = sublime.PhantomSet(self.view, "sublime-settings-edit") if self._is_base_settings_view(): self.build_phantoms()
def handle_response(self, response) -> None: phantoms = [] for val in response: color = val['color'] red = color['red'] * 255 green = color['green'] * 255 blue = color['blue'] * 255 alpha = color['alpha'] content = """ <div style='padding: 0.4em; margin-top: 0.1em; border: 1px solid color(var(--foreground) alpha(0.25)); background-color: rgba({}, {}, {}, {})'> </div>""".format(red, green, blue, alpha) range = Range.from_lsp(val['range']) region = range_to_region(range, self.view) phantoms.append(sublime.Phantom(region, content, sublime.LAYOUT_INLINE)) if phantoms: if not self.color_phantom_set: self.color_phantom_set = sublime.PhantomSet(self.view, "lsp_color") self.color_phantom_set.update(phantoms) else: self.color_phantom_set = None
def update_phantoms(self, view, phantoms): if not self.loaded: return thmname = get_settings(view, 'anaconda_linter_phantoms_theme', 'phantom') tplname = get_settings(view, 'anaconda_linter_phantoms_template', 'default') thm = self.themes.get(thmname, self.themes['phantom']) tpl = self.templates.get(tplname, self.templates['default']) vid = view.id() if vid not in self.phantomsets: self.phantomsets[vid] = sublime.PhantomSet(view, 'Anaconda') sublime_phantoms = [] for item in phantoms: region = view.full_line(view.text_point(item['line'], 0)) context = {'css': thm} context.update(item) content = tpl.safe_substitute(context) sublime_phantoms.append( sublime.Phantom(region, content, sublime.LAYOUT_BLOCK)) self.phantomsets[vid].update(sublime_phantoms)
def handle_decorations(session: Session, params: Union[Dict[str, Any], str]) -> None: phantom_key = "metals_decoraction" field_name = "_lsp_metals_decorations" clear_phantoms = False uri = None if isinstance(params, str): uri = session.config.map_client_path_to_server_uri(params) clear_phantoms = True elif isinstance(params, dict): uri = params.get('uri') if not uri: return session_buffer = session.get_session_buffer_for_uri_async(uri) if not session_buffer: return session_view = next(iter(session_buffer.session_views), None) if session_view: phantoms = [] try: phantom_set = getattr(session_buffer, field_name) except AttributeError: phantom_set = sublime.PhantomSet(session_view.view, phantom_key) setattr(session_buffer, field_name, phantom_set) if not clear_phantoms: phantoms = decorations_to_phantom(params.get('options', []), session_view.view) phantom_set.update(phantoms)
def display_previews(view, previews, pt=-1, current_index=0): global phantom_sets_by_buffer buffer_id = view.buffer_id() if ( buffer_id in phantom_sets_by_buffer and pt != phantom_sets_by_buffer[buffer_id][1] ): return preview_html, preview_regions = generate_previews(previews, current_index) on_navigate = get_on_navigate(view, previews, current_index, pt) view.add_regions( "cfml_method_preview", merge_regions(preview_regions), "source", flags=sublime.DRAW_NO_FILL, ) phantom_set = sublime.PhantomSet(view, "cfml_method_preview") phantom_sets_by_buffer[buffer_id] = (phantom_set, pt) phantom = sublime.Phantom( view.line(pt), preview_html, sublime.LAYOUT_BLOCK, on_navigate ) phantom_set.update([phantom])
def update_regions(view, phantom_set): # Only for python syntax if view.settings().get('syntax').find('ython') == -1: return # Find block indicators blocks = view.find_all(r'^[[:blank:]]*#[[:blank:]]*%%') phantoms = [] for block in blocks: # Get previous line block = view.line(block) block = sublime.Region(block.begin() - 1, block.begin() - 1) block = view.line(block) # Create phantom phantoms.append( sublime.Phantom( block, ('<body id="py_blocks">' + stylesheet + '<div class="horz">' + ' ' * 79 + '</div></body>'), sublime.LAYOUT_BLOCK)) v_id = view.buffer_id() phantom_set[v_id] = sublime.PhantomSet(view, 'py_blocks') phantom_set[v_id].update(phantoms)
def update_phantoms(self): stylesheet = """ <style> div.lt-error { padding: 0.4rem 0 0.4rem 0.7rem; margin: 0.2rem 0; border-radius: 2px; } div.lt-error span.message { padding-right: 0.7rem; } div.lt-error a { text-decoration: inherit; padding: 0.35rem 0.7rem 0.45rem 0.8rem; position: relative; bottom: 0.05rem; border-radius: 0 2px 2px 0; font-weight: bold; } html.dark div.lt-error a { background-color: #00000018; } html.light div.lt-error a { background-color: #ffffff18; } </style> """ for file, errs in self.errs_by_file.items(): view = self.window.find_open_file(file) if view: buffer_id = view.buffer_id() if buffer_id not in self.phantom_sets_by_buffer: phantom_set = sublime.PhantomSet(view, "lt_exec") self.phantom_sets_by_buffer[buffer_id] = phantom_set else: phantom_set = self.phantom_sets_by_buffer[buffer_id] phantoms = [] for line, column, text, error_class in errs: pt = view.text_point(line - 1, column - 1) html_text = html.escape(text, quote=False) phantom_content = """ <body id="inline-error"> {stylesheet} <div class="lt-error {error_class}"> <span class="message">{html_text}</span> <a href="hide">{cancel_char}</a> </div> </body> """.format(cancel_char=chr(0x00D7), **locals()) phantoms.append(sublime.Phantom( sublime.Region(pt, view.line(pt).b), phantom_content, sublime.LAYOUT_BELOW, on_navigate=self.on_phantom_navigate)) phantom_set.update(phantoms)
def __init__(self, view): self.view = view self.phantom_set = sublime.PhantomSet(view) self.timeout_scheduled = False self.last_modified = 0 self.prepared = {l[0]: ToolRunner.prepare(view, l[0]) for l in LINTERS}
def update_phantoms(self): stylesheet = ''' <style> div.error { padding: 0.4rem 0 0.4rem 0.7rem; margin: 0.2rem 0; border-radius: 2px; } div.error span.message { padding-right: 0.7rem; } div.error a { text-decoration: inherit; padding: 0.35rem 0.7rem 0.45rem 0.8rem; position: relative; bottom: 0.05rem; border-radius: 0 2px 2px 0; font-weight: bold; } html.dark div.error a { background-color: #00000018; } html.light div.error a { background-color: #ffffff18; } </style> ''' for file, errs in self.errs_by_file.items(): view = self.window.find_open_file(file) if view: buffer_id = view.buffer_id() if buffer_id not in self.phantom_sets_by_buffer: phantom_set = sublime.PhantomSet(view, "exec") self.phantom_sets_by_buffer[buffer_id] = phantom_set else: phantom_set = self.phantom_sets_by_buffer[buffer_id] phantoms = [] for line, column, text in errs: pt = view.text_point(line - 1, column - 1) phantoms.append( sublime.Phantom( sublime.Region(pt, view.line(pt).b), ('<body id=inline-error>' + stylesheet + '<div class="error">' + '<span class="message">' + html.escape(text, quote=False) + '</span>' + '<a href=hide>' + chr(0x00D7) + '</a></div>' + '</body>'), sublime.LAYOUT_BELOW, on_navigate=self.on_phantom_navigate)) phantom_set.update(phantoms)
def reclaim_view(self): for window in sublime.windows(): for view in window.views(): if view.name() == self.name: self.view = view self.phantom_set = sublime.PhantomSet( self.view, self.phantom_set_key) self.update() return
def run(self, edit): view = self.view self.currents = [] self.edit = edit self.phantomSet = sublime.PhantomSet(view, "phantomSet") self.buildRegions() self.buildPhantoms()
def apply_phantom(self, view: sublime.View, diagnostic: Diagnostic) -> None: phantom_set = sublime.PhantomSet(view, "lsp_diagnostics") phantom = self.create_phantom(view, diagnostic) phantom_set.update([phantom]) view.show_at_center(phantom.region) self._last_phantom_set = phantom_set has_phantom = view.settings().get('lsp_diagnostic_phantom') if not has_phantom: view.settings().set('lsp_diagnostic_phantom', True)
def initWindow(self, window): if not window.id() in self.data: self.data[window.id()] = {} xref_data = self.data[window.id()] window.destroy_output_panel("chromium_x_refs") xref_data['panel'] = window.create_output_panel( "chromium_x_refs", False) xref_data['phantom_set'] = sublime.PhantomSet( xref_data['panel'], "phantoms")
def on_activated(self, view): self.get_settings() self.view = view self.has_been_modified = False self.delay_update = False self.phantom_set = sublime.PhantomSet(view) # highlight dodgy characters when the file is opened self.highlight(view)
def run(self, edit, language, description, code): self.phantom_set = sublime.PhantomSet(self.view) # set syntax first as we will need the comment string utils.set_syntax(self.view, language) self.insert_description(self.view, edit, description) code = "\n\n" + code self.view.insert(edit, 0, code)
def on_load_async(self, markdown_view): infos = markdown_view.settings().get(MARKDOWN_VIEW_INFOS) if not infos: return preview_view = markdown_view.window().active_view_in_group(1) self.phantom_sets[markdown_view.id()] = sublime.PhantomSet( preview_view) self._update_preview(markdown_view)
def _draw_phantoms(view, errs, mode, phantom_sets, show_phantoms): buffer_id = view.buffer_id() if buffer_id not in phantom_sets: phantom_set = sublime.PhantomSet(view, PHANTOMS_MARKER) phantom_sets[buffer_id] = phantom_set else: phantom_set = phantom_sets[buffer_id] formatter = formatters.TB_MODES[mode] phantoms = build_phantoms(view, errs, formatter) if show_phantoms else [] phantom_set.update(phantoms)
def update_phantoms(view, stderr, region): view_id = view.id() view.erase_phantoms(str(view_id)) if view_id in PHANTOM_SETS: PHANTOM_SETS.pop(view_id) if not stderr or not "Unexpected" in stderr or not "SyntaxError" in stderr: return if not view_id in PHANTOM_SETS: PHANTOM_SETS[view_id] = sublime.PhantomSet(view, str(view_id)) # Extract line and column digits = re.compile(r"\d+|$").findall(stderr) line = int(digits[0]) - 1 column = int(digits[1]) - 1 if region: line += view.rowcol(region.begin())[0] # Format error message # [error] stdin: SyntaxError: Unexpected token (23:5) # [error] stdin: SyntaxError: Unexpected token (23:5) pattern = ".*SyntaxError: " stderr = re.compile(pattern).sub("", stderr) pattern = "\\[.*" stderr = re.compile(pattern).sub("", stderr) def erase_phantom(self): view.erase_phantoms(str(view_id)) phantoms = [] point = view.text_point(line, column) region = sublime.Region(point, view.line(point).b) phantoms.append( sublime.Phantom( region, ("<body id=inline-error>" + PHANTOM_STYLE + '<div class="error-arrow"></div><div class="error">' + '<span class="message">' + html.escape(stderr, quote=False) + "</span>" + "<a href=hide>" + chr(0x00D7) + "</a></div>" + "</body>"), sublime.LAYOUT_BELOW, on_navigate=erase_phantom, )) PHANTOM_SETS[view_id].update(phantoms) # Scroll to the syntax error point if sublime.load_settings(SETTINGS_FILENAME).get("scroll_to_error_point"): view.sel().clear() view.sel().add(sublime.Region(point)) view.show_at_center(point)
def mark(self, view: sublime.View): "Marks tracker in given view" scope = emmet.get_settings('marker_scope', 'region.accent') mark_opt = sublime.DRAW_SOLID_UNDERLINE | sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE view.erase_regions(ABBR_REGION_ID) view.add_regions(ABBR_REGION_ID, [self.region], scope, '', mark_opt) if self.forced: phantoms = [sublime.Phantom(self.region, forced_indicator('⋮>'), sublime.LAYOUT_INLINE)] if not self.forced_indicator: self.forced_indicator = sublime.PhantomSet(view, ABBR_REGION_ID) self.forced_indicator.update(phantoms)
def open_view(self, window, **kwargs): if not self.view: self.view = window.new_file() self.view.set_scratch(True) self.view.set_read_only(True) self.view.set_name(self.name) self.phantom_set = sublime.PhantomSet(self.view, self.phantom_set_key) self.update(**kwargs) window.focus_view(self.view) return self.view