def hover_content(self, point, response): contents = ["No description available."] if isinstance(response, dict): # Flow returns None sometimes # See: https://github.com/flowtype/flow-language-server/issues/51 response_content = response.get('contents') if response_content: if isinstance(response_content, list): contents = response_content else: contents = [response_content] formatted = [] for item in contents: value = "" language = None if isinstance(item, str): value = item else: value = item.get("value") language = item.get("language") if language: formatted.append("```{}\n{}\n```\n".format(language, value)) else: formatted.append(value) return mdpopups.md2html(self.view, "\n".join(formatted))
def _build_html(self, view, docstring): """Convert python docstring to text ready to show in popup. :param view: sublime text view object :param docstring: python docstring as a string """ # highlight signature signature, docstring = self._prepare_signature(docstring) if signature: content = '```python\n{0}\n```\n'.format(signature) else: content = '' # merge the rest of the docstring beginning with 3rd line # skip leading and tailing empty lines content += html.escape(docstring, quote=False) # preserve empty lines content = content.replace('\n\n', '\n\u00A0\n') # preserve whitespace content = content.replace(' ', '\u00A0\u00A0') # convert markdown to html content = mdpopups.md2html(view, content) # TODO: move to GoogleStyleTooltip # highlight headlines ( Google Python Style Guide ) keywords = ( 'Args:', 'Arguments:', 'Attributes:', 'Example:', 'Examples:', 'Note:', 'Raises:', 'Returns:', 'Yields:') for keyword in keywords: content = content.replace( keyword + '<br />', '<h6>' + keyword + '</h6>') return content
def get_info(self, pt): """Get scope related info.""" scope = self.get_scope(pt) if self.rowcol_info or self.points_info or self.highlight_extent: self.get_extents(pt) if (self.appearance_info or self.selector_info) and scheme_matcher is not None: try: match = scheme_matcher.guess_color(scope) color = match.fg bgcolor = match.bg color_sim = match.fg_simulated bgcolor_sim = match.bg_simulated style = match.style bg_selector = match.bg_selector color_selector = match.fg_selector style_selectors = match.style_selectors color_gradient = match.color_gradient color_gradient_selector = match.color_gradient_selector # if match.color_gradient is not None: # color = self.view.style_for_scope(scope)["foreground"] # color_sim = color if self.appearance_info: self.get_appearance(color, color_sim, bgcolor, bgcolor_sim, style, color_gradient) if self.selector_info: self.get_selectors(color_selector, bg_selector, style_selectors, color_gradient_selector) except Exception: log("Evaluating theme failed! Ignoring theme related info.") debug(str(traceback.format_exc())) error("Evaluating theme failed!") self.scheme_info = False if self.file_path_info and scheme_matcher: self.get_scheme_syntax() # Divider self.next_index() self.scope_bfr.append("------") if self.show_popup: self.scope_bfr_tool.append( mdpopups.md2html( self.view, self.popup_template, template_vars=self.template_vars, template_env_options={ "trim_blocks": True, "lstrip_blocks": True } ) )
def run(self): import mdpopups text = sublime.load_resource('Packages/Material Theme/CHANGELOG.md') view = self.window.new_file() view.set_name('Material Theme Changelog') view.settings().set('gutter', False) html = '<div class="mt-config-changes">%s</div>' % mdpopups.md2html(view, text) mdpopups.add_phantom(view, 'changelog', sublime.Region(0), html, sublime.LAYOUT_INLINE, css=STYLES) view.set_read_only(True) view.set_scratch(True)
def preview(self, text): """Preview.""" style = self.get_html_style() try: colors = evaluate_contrast(text) html = mdpopups.md2html(self.view, DEF_RATIO.format(style)) if len(colors) >= 3: lum2 = colors[1].luminance() lum3 = colors[2].luminance() if len(colors) > 3: luma = colors[3].luminance() lumb = colors[4].luminance() mn = min(luma, lumb) mx = max(luma, lumb) min_max = "<ul><li><strong>min</strong>: {}</li><li><strong>max</strong>: {}</li></ul>".format( mn, mx ) else: min_max = "" html = ( "<p><strong>Fg</strong>: {}</p>" "<p><strong>Bg</strong>: {}</p>" "<p><strong>Relative Luminance (fg)</strong>: {}</p>{}" "<p><strong>Relative Luminance (bg)</strong>: {}</p>" ).format( colors[2].to_string(**util.DEFAULT), colors[1].to_string(**util.DEFAULT), lum3, min_max, lum2 ) html += "<p><strong>Contrast ratio</strong>: {}</p>".format(colors[1].contrast_ratio(colors[2])) html += CONTRAST_DEMO.format( colors[2].to_string(**util.COMMA), colors[1].to_string(**util.COMMA) ) return sublime.Html(style + html) except Exception: return sublime.Html(mdpopups.md2html(self.view, DEF_RATIO.format(style)))
def run(self): import mdpopups text = sublime.load_resource('Packages/Boxy Theme/CHANGELOG.md') view = self.window.new_file() view.set_name('Boxy Theme Changelog') view.settings().set('gutter', False) html = '<div class="boxy-changelog">%s</div>' % mdpopups.md2html(view, text) mdpopups.add_phantom(view, 'changelog', sublime.Region(0), html, sublime.LAYOUT_INLINE, css=STYLES, on_navigate=self.on_navigate) view.set_read_only(True) view.set_scratch(True)
def preview(self, text): """Preview.""" style = self.get_html_style() try: color = self.color_mod_class(text.strip()) if color is not None: srgb = Color(color).convert("srgb") preview_border = self.default_border message = "" if not srgb.in_gamut(): srgb.fit("srgb") message = '<br><em style="font-size: 0.9em;">* preview out of gamut</em>' preview = srgb.to_string(**util.HEX_NA) preview_alpha = srgb.to_string(**util.HEX) preview_border = self.default_border height = self.height * 3 width = self.width * 3 check_size = self.check_size(height, scale=8) html = PREVIEW_IMG.format( mdpopups.color_box( [ preview, preview_alpha ], preview_border, border_size=1, height=height, width=width, check_size=check_size ), message, color.to_string(**util.DEFAULT) ) if html: return sublime.Html(style + html) else: return sublime.Html(mdpopups.md2html(self.view, DEF_COLORMOD.format(style))) except Exception: return sublime.Html(mdpopups.md2html(self.view, DEF_COLORMOD.format(style)))
def preview(desc, value): items = [ 'allman', 'gnu', 'horstmann', 'k_and_r', 'lisp', 'pico', 'ratliff', 'whitesmiths' ] if value not in items: return None v = sublime.active_window().active_view() lsl_code_block = ResourcePath('{}/{}.lsl'.format( RESPATH_STYLES, value) # TODO: f'{RESPATH_STYLES}/{value}.lsl' ).read_text() lsl_code_block = '```lsl\n{}\n```'.format(lsl_code_block) # TODO: lsl_code_block = f'```lsl\n{lsl_code_block}\n```' return sublime.Html(mdpopups.md2html(v, lsl_code_block))
def run(self): """Show the changelog in a new view.""" import mdpopups text = sublime.load_resource('Packages/Material Theme/CHANGELOG.md') view = self.window.new_file() view.set_name('Material Theme - Changelog') view.settings().set('gutter', False) html = '<div class="mt-config-changes">%s</div>' % mdpopups.md2html( view, text) mdpopups.add_phantom(view, 'changelog', sublime.Region(0), html, sublime.LAYOUT_INLINE, css=CSS) view.set_read_only(True) view.set_scratch(True)
def generate_content(self, view): total_region = sublime.Region(0, view.size()) fm, content = frontmatter.get_frontmatter(view.substr(total_region)) MD_FM.update(fm) content = "{}\n\n{}".format( mdpopups.format_frontmatter(MD_FM), self.render_checkboxes(content), ) html_content = mdpopups.md2html(view, content).replace("<br>", "<br/>") file_name = view.file_name() basepath = os.path.dirname(file_name) if file_name else None html_content = imageparser( html_content, basepath, partial(self._update_preview, view), resources, ) return html_content
def run(self, resource_path='README.md', resource_title='README'): try: w = self.window v = w.active_view() import mdpopups md_preview = mdpopups.md2html( view=v, markup=sublime.load_resource('Packages/{}/{}'.format( PKG_NAME, resource_path)), # TODO: markup=sublime.load_resource(f'Packages/{PKG_NAME}/{resource_path}'), template_vars=None, template_env_options=None) preview_sheet = w.new_html_sheet( name='{}: {}'.format(PKG_NAME, resource_title), # TODO: name=f'{PKG_NAME}: {resource_title}', contents=md_preview, cmd='open_url', args=None, flags=0, group=-1) except Exception as e: print('{}: Exception: {}'.format(PKG_NAME, e))
def run(self): try: w = self.window v = w.active_view() if not v.settings().get('syntax').startswith('Packages/Markdown/'): return import mdpopups md_preview = mdpopups.md2html( view=v, markup=v.substr(sublime.Region(0, v.size())), template_vars=None, template_env_options=None ) p = os.path.join(sublime.packages_path(), 'User', 'Print Preview.cache', 'index.html') os.makedirs(p[:p.rindex(os.path.sep)], exist_ok=True) with open(p, mode='w', newline='\n') as f: f.write(md_preview) # TODO: remove pathlib from dependencies.json for py3.8 import pathlib w.run_command('open_url', { 'url': pathlib.Path(p).as_uri() }) except Exception as e: # TODO: update for py3.8 print('Print: Exception: {}'.format(e))
def minihtml(view: sublime.View, content: Union[MarkedString, MarkupContent, List[MarkedString]], allowed_formats: int) -> str: """ Formats provided input content into markup accepted by minihtml. Content can be in one of those formats: - string: treated as plain text - MarkedString: string or { language: string; value: string } - MarkedString[] - MarkupContent: { kind: MarkupKind, value: string } We can't distinguish between plain text string and a MarkedString in a string form so FORMAT_STRING and FORMAT_MARKED_STRING can't both be specified at the same time. :param view :param content :param allowed_formats: Bitwise flag specifying which formats to parse. :returns: Formatted string """ if allowed_formats == 0: raise ValueError("Must specify at least one format") parse_string = bool(allowed_formats & FORMAT_STRING) parse_marked_string = bool(allowed_formats & FORMAT_MARKED_STRING) parse_markup_content = bool(allowed_formats & FORMAT_MARKUP_CONTENT) if parse_string and parse_marked_string: raise ValueError( "Not allowed to specify FORMAT_STRING and FORMAT_MARKED_STRING at the same time" ) is_plain_text = True result = '' if (parse_string or parse_marked_string) and isinstance(content, str): # plain text string or MarkedString is_plain_text = parse_string result = content if parse_marked_string and isinstance(content, list): # MarkedString[] formatted = [] for item in content: value = "" language = None if isinstance(item, str): value = item else: value = item.get("value") or "" language = item.get("language") if language: formatted.append("```{}\n{}\n```\n".format(language, value)) else: formatted.append(value) is_plain_text = False result = "\n".join(formatted) if (parse_marked_string or parse_markup_content) and isinstance( content, dict): # MarkupContent or MarkedString (dict) language = content.get("language") kind = content.get("kind") value = content.get("value") or "" if parse_markup_content and kind: # MarkupContent is_plain_text = kind != "markdown" result = value if parse_marked_string and language: # MarkedString (dict) is_plain_text = False result = "```{}\n{}\n```\n".format(language, value) if is_plain_text: return "<p>{}</p>".format(text2html(result)) if result else '' else: frontmatter = { "allow_code_wrap": True, "markdown_extensions": [ { "pymdownx.escapeall": { "hardbreak": True, "nbsp": False } }, { "pymdownx.magiclink": { # links are displayed without the initial ftp://, http://, https://, or ftps://. "hide_protocol": True, # GitHub, Bitbucket, and GitLab commit, pull, and issue links are are rendered in a shorthand # syntax. "repo_url_shortener": True } } ] } # Workaround CommonMark deficiency: two spaces followed by a newline should result in a new paragraph. result = re.sub('(\\S) \n', '\\1\n\n', result) return mdpopups.md2html( view, mdpopups.format_frontmatter(frontmatter) + result)
def run(self, v): """Run ScopeHunter and display in the approriate way.""" self.view = v self.window = self.view.window() view = self.window.create_output_panel('scopehunter.results', unlisted=True) self.scope_bfr = [] self.scope_bfr_tool = [] self.clips = [] self.status = "" self.popup_template = sublime.load_resource('Packages/ScopeHunter/popup.j2') self.scheme_file = None self.syntax_file = None self.show_statusbar = bool(sh_settings.get("show_statusbar", False)) self.show_panel = bool(sh_settings.get("show_panel", False)) if TOOLTIP_SUPPORT: self.show_popup = bool(sh_settings.get("show_popup", False)) else: self.show_popup = False self.clipboard = bool(sh_settings.get("clipboard", False)) self.multiselect = bool(sh_settings.get("multiselect", False)) self.console_log = bool(sh_settings.get("console_log", False)) self.highlight_extent = bool(sh_settings.get("highlight_extent", False)) self.highlight_scope = sh_settings.get("highlight_scope", 'invalid') self.highlight_style = sh_settings.get("highlight_style", 'outline') self.highlight_max_size = int(sh_settings.get("highlight_max_size", 100)) self.rowcol_info = bool(sh_settings.get("extent_line_char", False)) self.points_info = bool(sh_settings.get("extent_points", False)) self.appearance_info = bool(sh_settings.get("styling", False)) self.show_simulated = bool(sh_settings.get("show_simulated_alpha_colors", False)) self.file_path_info = bool(sh_settings.get("file_paths", False)) self.selector_info = bool(sh_settings.get("selectors", False)) self.scheme_info = self.appearance_info or self.selector_info self.first = True self.extents = [] # Get scope info for each selection wanted self.index = -1 if len(self.view.sel()): if self.multiselect: count = 0 for sel in self.view.sel(): if count > 0 and self.show_popup: self.scope_bfr_tool.append('\n---\n') self.init_template_vars() self.get_info(sel.b) count += 1 else: self.init_template_vars() self.get_info(self.view.sel()[0].b) # Copy scopes to clipboard if self.clipboard: sublime.set_clipboard('\n'.join(self.clips)) # Display in status bar if self.show_statusbar: sublime.status_message(self.status) # Show panel if self.show_panel: ScopeHunterEditCommand.bfr = '\n'.join(self.scope_bfr) ScopeHunterEditCommand.pt = 0 view.run_command('scope_hunter_edit') ScopeHunterEditCommand.clear() self.window.run_command("show_panel", {"panel": "output.scopehunter.results"}) if self.console_log: print('\n'.join(["Scope Hunter"] + self.scope_bfr)) if self.highlight_extent: style = extent_style(self.highlight_style) if style == 'underline': self.extents = underline(self.extents) self.view.add_regions( 'scope_hunter', self.extents, self.highlight_scope, '', style ) if self.show_popup: if self.scheme_info or self.rowcol_info or self.points_info or self.file_path_info: tail = mdpopups.md2html(self.view, COPY_ALL) else: tail = mdpopups.md2html(self.view, RELOAD) mdpopups.show_popup( self.view, ''.join(self.scope_bfr_tool) + tail, md=False, css=ADD_CSS, wrapper_class=('scope-hunter'), max_width=1000, on_navigate=self.on_navigate, )
def run( self, edit, color='#ffffff', allowed_colors=util.ALL, use_hex_argb=None, compress_hex=False, hsl=False, hirespick=None, colornames=False, on_done=None, on_cancel=None ): """Run command.""" self.on_done = on_done self.on_cancel = on_cancel self.use_hex_argb = use_hex_argb self.compress_hex = compress_hex self.allowed_colors = allowed_colors self.hex_map = sublime.load_settings('color_helper.sublime-settings').get('use_hex_color_picker', True) rgba = util.RGBA(color) self.set_sizes() self.hsl = hsl self.color = rgba.get_rgba() self.alpha = util.fmt_float(float(int(self.color[-2:], 16)) / 255.0, 3) try: self.web_color = csscolors.hex2name(rgba.get_rgb()) except Exception: self.web_color = None text = [] if colornames: text.append('[cancel](%s){: .color-helper .small} ' % self.color) text.append('\n\n## CSS Color Names\n\n') self.get_css_color_names(text) elif hirespick: text.append('[cancel](%s){: .color-helper .small} ' % self.color) text.append('\n\n## %s\n\n' % hirespick) self.get_hires_color_channel(text, hirespick) else: text.append('[cancel](cancel){: .color-helper .small} ') text.append('[CSS color names](colornames){: .color-helper .small} ') text.append('[enter new color](edit){: .color-helper .small}\n\n') if self.hex_map: self.get_color_map_hex(text) else: self.get_color_map_square(text) self.get_current_color(text) text.append('\n\n---\n\n') if hsl: self.get_channel(text, 'H', -15, 15, 'hue') self.get_channel(text, 'S', 0.975, 1.025, 'saturation') self.get_channel(text, 'L', 0.975, 1.025, 'luminance') else: self.get_channel(text, 'R', 0.975, 1.025, 'red') self.get_channel(text, 'G', 0.975, 1.025, 'green') self.get_channel(text, 'B', 0.975, 1.025, 'blue') self.get_channel(text, 'A', 0.975, 1.025, 'alpha') text.append( '[switch to %s](%s){: .color-helper .small}\n' % ( 'rgb' if self.hsl else 'hsl', 'rgb' if self.hsl else 'hsl' ) ) text.append('\n\n---\n\n') self.get_color_info(text) md = mdpopups.md2html(self.view, ''.join(text)) mdpopups.show_popup( self.view, '<div class="color-helper content">%s</div>' % md, css=util.ADD_CSS, max_width=600, max_height=(500 if hirespick or colornames else 725), on_navigate=self.handle_href )
def markdown(self, content: str) -> str: return mdpopups.md2html(self._view, content)
def run(self, v): """Run ScopeHunter and display in the approriate way.""" self.view = v self.window = self.view.window() view = self.window.create_output_panel('scopehunter.results', unlisted=True) self.scope_bfr = [] self.scope_bfr_tool = [] self.clips = [] self.status = "" self.popup_template = sublime.load_resource('Packages/ScopeHunter/popup.j2') self.scheme_file = None self.syntax_file = None self.show_statusbar = bool(sh_settings.get("show_statusbar", False)) self.show_panel = bool(sh_settings.get("show_panel", False)) if TOOLTIP_SUPPORT: self.show_popup = bool(sh_settings.get("show_popup", False)) else: self.show_popup = False self.clipboard = bool(sh_settings.get("clipboard", False)) self.multiselect = bool(sh_settings.get("multiselect", False)) self.console_log = bool(sh_settings.get("console_log", False)) self.highlight_extent = bool(sh_settings.get("highlight_extent", False)) self.highlight_scope = sh_settings.get("highlight_scope", 'invalid') self.highlight_style = sh_settings.get("highlight_style", 'outline') self.highlight_max_size = int(sh_settings.get("highlight_max_size", 100)) self.rowcol_info = bool(sh_settings.get("extent_line_char", False)) self.points_info = bool(sh_settings.get("extent_points", False)) self.appearance_info = bool(sh_settings.get("styling", False)) self.show_simulated = bool(sh_settings.get("show_simulated_alpha_colors", False)) self.file_path_info = bool(sh_settings.get("file_paths", False)) self.selector_info = bool(sh_settings.get("selectors", False)) self.scheme_info = self.appearance_info or self.selector_info self.first = True self.extents = [] # Get scope info for each selection wanted self.index = -1 if len(self.view.sel()): if self.multiselect: count = 0 for sel in self.view.sel(): if count > 0 and self.show_popup: self.scope_bfr_tool.append('\n---\n') self.init_template_vars() self.get_info(sel.b) count += 1 else: self.init_template_vars() self.get_info(self.view.sel()[0].b) # Copy scopes to clipboard if self.clipboard: sublime.set_clipboard('\n'.join(self.clips)) # Display in status bar if self.show_statusbar: sublime.status_message(self.status) # Show panel if self.show_panel: ScopeHunterEditCommand.bfr = '\n'.join(self.scope_bfr) ScopeHunterEditCommand.pt = 0 view.run_command('scope_hunter_edit') ScopeHunterEditCommand.clear() self.window.run_command("show_panel", {"panel": "output.scopehunter.results"}) if self.console_log: print('\n'.join(["Scope Hunter"] + self.scope_bfr)) if self.highlight_extent: style = extent_style(self.highlight_style) if style == 'underline': self.extents = underline(self.extents) self.view.add_regions( 'scope_hunter', self.extents, self.highlight_scope, '', style ) if self.show_popup: if self.scheme_info or self.rowcol_info or self.points_info or self.file_path_info: tail = mdpopups.md2html(self.view, COPY_ALL % ('' if GOOD_CSS_SUPPORT else '.scope-hunter ')) else: tail = '' mdpopups.show_popup( self.view, ''.join(self.scope_bfr_tool) + tail, md=False, css=ADD_CSS, wrapper_class=('scope-hunter' if GOOD_CSS_SUPPORT else 'scope-hunter content'), max_width=1000, on_navigate=self.on_navigate, )