### Foreground and Background Filter Examples Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/styling.md Examples showing how to convert colors to foreground or background using the respective filters. ```APIDOC ## Foreground and Background Filters ### Description These filters convert a color to either a foreground or background color, augmenting the CSS returned by the `css` filter. ### Method `foreground()` `background()` ### Request Example **Convert to Foreground**: ```css+jinja body { {{'.background'|css('background-color')|foreground}} } ``` **Convert to Background**: ```css+jinja body { {{'.foreground'|css('color')|background}} } ``` ``` -------------------------------- ### Install Linting Dependencies Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/about/contributing.md Install the required Python linting packages to validate code quality. ```bash pip install flake8 pip install flake8-docstrings pip install flake8-mutable pip install flake8-builtins pip install pep8-naming ``` -------------------------------- ### Saturation Filter Example Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/styling.md Shows how to adjust the saturation of a color, either desaturating or saturating it. ```APIDOC ## Saturation Filter ### Description Shifts the saturation either to right (saturate) or the left (desaturate). Saturation is relative to `1` where `1` means no change. Accepted values are floats that are greater than `0`. Ranges are clamped between `0` and `2`. ### Method `saturation(value)` ### Parameters - **value** (float) - Required - The saturation adjustment factor. `1` is no change. Clamped between `0` and `2`. ### Request Example **Desaturate**: ```css+jinja body { {{'.background'|css('background-color')|saturation(0.9)}} } ``` **Saturate**: ```css+jinja body { {{'.background'|css('background-color')|saturation(1.1)}} } ``` ``` -------------------------------- ### Sepia Filter Example Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/styling.md Shows how to apply a sepia tone filter to a color. ```APIDOC ## Sepia Filter ### Description Filters all colors to a sepia tone. ### Method `sepia()` ### Request Example ```css+jinja body { {{'.background'|css('background-color')|sepia}} } ``` ``` -------------------------------- ### Grayscale Filter Example Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/styling.md Demonstrates applying a grayscale filter to a color. ```APIDOC ## Grayscale Filter ### Description Filters all colors to a grayish tone. ### Method `grayscale()` ### Request Example ```css+jinja body { {{'.background'|css('background-color')|grayscale}} } ``` ``` -------------------------------- ### Contrast Filter Example Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/styling.md Illustrates how to increase or decrease the contrast of a color. ```APIDOC ## Contrast Filter ### Description Increases or decreases the contrast. Contrast is relative to `1` where `1` means no change. Accepted values are floats that are greater than `0`. Ranges are clamped between `0` and `2`. ### Method `contrast(value)` ### Parameters - **value** (float) - Required - The contrast adjustment factor. `1` is no change. Clamped between `0` and `2`. ### Request Example **Decrease contrast**: ```css+jinja body { {{'.background'|css('background-color')|contrast(0.9)}} } ``` **Increase contrast**: ```css+jinja body { {{'.background'|css('background-color')|contrast(1.1)}} } ``` ``` -------------------------------- ### Brightness Filter Example Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/styling.md Demonstrates how to use the brightness filter to make a popup's background darker or lighter. ```APIDOC ## Brightness Filter ### Description Shifts brightness either dark or lighter. Brightness is relative to `1` where `1` means no change. Accepted values are floats that are greater than `0`. Ranges are clamped between `0` and `2`. ### Method `brightness(value)` ### Parameters - **value** (float) - Required - The brightness adjustment factor. `1` is no change. Clamped between `0` and `2`. ### Request Example **Darken**: ```css+jinja .mdpopups div.myplugin { {{'.background'|css('background-color')|brightness(0.9)}} } ``` **Lighten**: ```css+jinja .mdpopups div.myplugin { {{'.background'|css('background-color')|brightness(1.1)}} } ``` ``` -------------------------------- ### Hue Filter Example Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/styling.md Shows how to shift the current hue of a color. ```APIDOC ## Hue Filter ### Description Shifts the current hue either to the left or right. The values are angular dimensions starting at the red primary at 0°, passing through the green primary at 120° and the blue primary at 240°, and then wrapping back to red at 360°. ### Method `hue(value)` ### Parameters - **value** (number) - Required - The hue shift value in degrees (0-360). ### Request Example ```css+jinja body { {{'.background'|css('background-color')|hue(45)}} } ``` ``` -------------------------------- ### Colorize Filter Example Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/styling.md Demonstrates how to apply a specific hue to a color using the colorize filter. ```APIDOC ## Colorize Filter ### Description Filters all colors to a shade of the specified hue. The values are angular dimensions starting at the red primary at 0°, passing through the green primary at 120° and the blue primary at 240°, and then wrapping back to red at 360°. ### Method `colorize(hue)` ### Parameters - **hue** (number) - Required - The hue value in degrees (0-360). ### Request Example ```css+jinja body { {{'.background'|css('background-color')|colorize(30)}} } ``` ``` -------------------------------- ### Invert Filter Example Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/styling.md Illustrates how to invert a color using the invert filter. ```APIDOC ## Invert Filter ### Description Inverts a color. ### Method `invert()` ### Request Example ```css+jinja body { {{'.background'|css('background-color')|invert}} } ``` ``` -------------------------------- ### Configure Markdown Extensions with Specific Settings Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Configure specific settings for markdown extensions by making the extension entry a dictionary. This example shows custom settings for 'smarty', 'magiclink', 'escapeall', and 'smartsymbols'. ```yaml --- markdown_extensions: - markdown.extensions.admonition - markdown.extensions.attr_list - markdown.extensions.def_list - markdown.extensions.nl2br - markdown.extensions.smarty: smart_quotes: false - pymdownx.betterem - pymdownx.magiclink: base_repo_url: https://github.com/facelessuser/sublime-markdown-popups repo_url_shortener: true - pymdownx.extrarawhtml - pymdownx.keys - pymdownx.escapeall: hardbreak: true nbsp: true - pymdownx.smartsymbols: ordinal_numbers: false ... ``` -------------------------------- ### Configure Default Markdown Extensions Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Specify an array of markdown extensions to be used. This example shows a common set of default extensions. ```yaml --- markdown_extensions: - markdown.extensions.admonition - markdown.extensions.attr_list - markdown.extensions.def_list - markdown.extensions.nl2br - pymdownx.betterem - pymdownx.magiclink - pymdownx.extrarawhtml ... ``` -------------------------------- ### Define Pygments CSS Classes Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/styling.md Examples of defining CSS rules for Pygments syntax classes and container backgrounds. ```css .highlight .w { color: #cccccc } /* Text.Whitespace */ ``` ```css .mdpopups .highlight { background-color: #f8f8f8; color: #4d4d4c } ``` ```css .mdpopups .highlight { background-color: #f8f8f8; color: #4d4d4c } .mdpopups .highlight .c { color: #8e908c; font-style: italic } /* Comment */ .mdpopups .highlight .err { color: #c82829 } /* Error */ .mdpopups .highlight .k { color: #8959a8; font-weight: bold } /* Keyword */ .mdpopups .highlight .l { color: #f5871f } /* Literal */ .mdpopups .highlight .n { color: #4d4d4c } /* Name */ .mdpopups .highlight .o { color: #3e999f } /* Operator */ .mdpopups .highlight .p { color: #4d4d4c } /* Punctuation */ .mdpopups .highlight .cm { color: #8e908c; font-style: italic } /* Comment.Multiline */ .mdpopups .highlight .cp { color: #8e908c; font-weight: bold } /* Comment.Preproc */ .mdpopups .highlight .c1 { color: #8e908c; font-style: italic } /* Comment.Single */ .mdpopups .highlight .cs { color: #8e908c; font-style: italic } /* Comment.Special */ .mdpopups .highlight .gd { color: #c82829 } /* Generic.Deleted */ .mdpopups .highlight .ge { font-style: italic } /* Generic.Emph */ .mdpopups .highlight .gh { color: #4d4d4c; font-weight: bold } /* Generic.Heading */ .mdpopups .highlight .gi { color: #718c00 } /* Generic.Inserted */ .mdpopups .highlight .gp { color: #8e908c; font-weight: bold } /* Generic.Prompt */ .mdpopups .highlight .gs { font-weight: bold } /* Generic.Strong */ .mdpopups .highlight .gu { color: #3e999f; font-weight: bold } /* Generic.Subheading */ .mdpopups .highlight .kc { color: #8959a8; font-weight: bold } /* Keyword.Constant */ .mdpopups .highlight .kd { color: #8959a8; font-weight: bold } /* Keyword.Declaration */ .mdpopups .highlight .kn { color: #8959a8; font-weight: bold } /* Keyword.Namespace */ .mdpopups .highlight .kp { color: #8959a8; font-weight: bold } /* Keyword.Pseudo */ .mdpopups .highlight .kr { color: #8959a8; font-weight: bold } /* Keyword.Reserved */ .mdpopups .highlight .kt { color: #eab700; font-weight: bold } /* Keyword.Type */ .mdpopups .highlight .ld { color: #718c00 } /* Literal.Date */ .mdpopups .highlight .m { color: #f5871f } /* Literal.Number */ .mdpopups .highlight .s { color: #718c00 } /* Literal.String */ .mdpopups .highlight .na { color: #4271ae } /* Name.Attribute */ .mdpopups .highlight .nb { color: #4271ae } /* Name.Builtin */ .mdpopups .highlight .nc { color: #c82829; font-weight: bold } /* Name.Class */ .mdpopups .highlight .no { color: #c82829 } /* Name.Constant */ .mdpopups .highlight .nd { color: #3e999f } /* Name.Decorator */ .mdpopups .highlight .ni { color: #4d4d4c } /* Name.Entity */ .mdpopups .highlight .ne { color: #c82829; font-weight: bold } /* Name.Exception */ .mdpopups .highlight .nf { color: #4271ae; font-weight: bold } /* Name.Function */ .mdpopups .highlight .nl { color: #4d4d4c } /* Name.Label */ .mdpopups .highlight .nn { color: #4d4d4c } /* Name.Namespace */ .mdpopups .highlight .nx { color: #4271ae } /* Name.Other */ .mdpopups .highlight .py { color: #4d4d4c } /* Name.Property */ .mdpopups .highlight .nt { color: #c82829 } /* Name.Tag */ .mdpopups .highlight .nv { color: #c82829 } /* Name.Variable */ .mdpopups .highlight .ow { color: #3e999f } /* Operator.Word */ .mdpopups .highlight .w { color: #4d4d4c } /* Text.Whitespace */ .mdpopups .highlight .mb { color: #f5871f } /* Literal.Number.Bin */ .mdpopups .highlight .mf { color: #f5871f } /* Literal.Number.Float */ .mdpopups .highlight .mh { color: #f5871f } /* Literal.Number.Hex */ .mdpopups .highlight .mi { color: #f5871f } /* Literal.Number.Integer */ .mdpopups .highlight .mo { color: #f5871f } /* Literal.Number.Oct */ .mdpopups .highlight .sb { color: #718c00 } /* Literal.String.Backtick */ ``` -------------------------------- ### Add MdPopups as Package Control Dependency Source: https://context7.com/facelessuser/sublime-markdown-popups/llms.txt Specify MdPopups as a dependency in your plugin's `dependencies.json` file for Package Control to manage installation. This ensures the library is available for your plugin. ```json { "*": { ">=3124": [ "mdpopups" ] } } ``` -------------------------------- ### Get Language From View API Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Allows a user to extract the equivalent language specifier for `mdpopups.syntax_highlight` from a Sublime Text view. ```APIDOC ## Get Language From View ### Description Allows a user to extract the equivalent language specifier for `mdpopups.syntax_highlight` from a view. If the language cannot be determined, `None` will be returned. ### Method `mdpopups.get_language_from_view` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **view** (sublime.View) - Required - Sublime text View object. ### Request Example ```python import mdpopups # Assuming 'view' is a valid sublime.View object language = mdpopups.get_language_from_view(view) if language: print(f"Detected language: {language}") else: print("Language could not be determined.") ``` ### Response #### Success Response (200) - **language** (str or None) - The detected language specifier for the view, or None if it cannot be determined. ``` -------------------------------- ### YAML Frontmatter with Key-Value Pairs Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Demonstrates a basic structure of YAML frontmatter using key-value pairs at the base level. ```yaml --- key1: value1 key2: value2 ... ``` -------------------------------- ### Run Linting Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/about/contributing.md Execute the flake8 linter on the current directory to check for style and syntax issues. ```bash flake8 . ``` -------------------------------- ### Basic YAML Frontmatter Structure Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Frontmatter for configuration must be enclosed between '---' markers at the beginning of the content. It uses YAML syntax for key-value pairs. ```yaml --- # yaml content --- ``` -------------------------------- ### Utility Functions for Plugin Management Source: https://context7.com/facelessuser/sublime-markdown-popups/llms.txt Access helper utilities for version checking, popup visibility, language detection, cache management, and phantom manipulation. ```python import mdpopups def utility_examples(view): """Demonstrate utility functions.""" # Get MdPopups version version = mdpopups.version() print(f"MdPopups version: {version}") # (5, 1, 2) # Check popup visibility if mdpopups.is_popup_visible(view): mdpopups.hide_popup(view) # Get language from current view's syntax language = mdpopups.get_language_from_view(view) print(f"Detected language: {language}") # e.g., "python" # Clear CSS cache (useful after scheme changes) mdpopups.clear_cache() # Convert tabs to spaces with proper tab stops code_with_tabs = "class\tName:\n\tdef\tmethod(self):" formatted = mdpopups.tabs2spaces(code_with_tabs, tab_size=4) print(formatted) # Output: # class Name: # def method(self): # Erase phantoms by key mdpopups.erase_phantoms(view, "my_plugin_hints") # Erase specific phantom by ID phantom_id = 12345 mdpopups.erase_phantom_by_id(view, phantom_id) # Query phantom location regions = mdpopups.query_phantom(view, phantom_id) # Returns: [Region(100, 100)] or [Region(-1, -1)] if not found # Query multiple phantoms phantom_ids = [123, 456, 789] all_regions = mdpopups.query_phantoms(view, phantom_ids) ``` -------------------------------- ### Tint Images for Themed Icons Source: https://context7.com/facelessuser/sublime-markdown-popups/llms.txt Apply color tints to PNG images or raw bytes to match the editor's color scheme. ```python import mdpopups def create_themed_icon(view): """Tint a PNG icon to match the color scheme.""" # Get foreground color from scheme style = mdpopups.scope2style(view, "entity.name.function") icon_color = style['color'] # Tint from a package resource path tinted_icon = mdpopups.tint( img="Packages/MyPlugin/icons/function.png", color=icon_color, opacity=255, height=16, width=16 ) # Tint from raw bytes with open("/path/to/icon.png", "rb") as f: icon_bytes = f.read() tinted_from_bytes = mdpopups.tint( img=icon_bytes, color="#FF5733", opacity=200 ) # Get raw tinted image bytes (for further processing) raw_tinted = mdpopups.tint_raw( img="Packages/MyPlugin/icons/symbol.png", color="#3357FF", opacity=255 ) # Use in popup content content = f""" ## Function Details {tinted_icon} `my_function()` This function does important things. """ return content ``` -------------------------------- ### mdpopups.color_box (Raw Bytes) Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Generates a color preview box image and returns the raw byte string of the image. ```APIDOC ## mdpopups.color_box (Raw Bytes) ### Description Generates a color preview box image and returns the raw byte string of the image. ### Parameters - **colors** ([str]) - Required - A list of color strings formatted as #RRGGBBAA. - **border** (str) - Required - The color for the color box border (#RRGGBB). - **border2** (str) - Optional - The optional secondary border color (#RRGGBB). - **height** (int) - Optional - Height of color box (Default: 32). - **width** (int) - Optional - Width of color box (Default: 32). - **border_size** (int) - Optional - Width of the color box border (Default: 1). - **check_size** (int) - Optional - Size of checkered box squares for transparent colors (Default: 4). - **max_colors** (int) - Optional - Max number of colors evaluated (Default: 5). - **alpha** (bool) - Optional - Create images with real alpha channel (Default: False). - **border_map** (int) - Optional - Mapping of which borders to show (Default: 0xF). ``` -------------------------------- ### Create HTML Sheets Source: https://context7.com/facelessuser/sublime-markdown-popups/llms.txt Render Markdown content into a new full-tab HTML sheet. Useful for documentation or complex reports. ```python import sublime import sublime_plugin import mdpopups class ShowDocumentationSheetCommand(sublime_plugin.WindowCommand): def run(self): content = """ # API Documentation ## Overview This document provides comprehensive API documentation. ## Functions ### `process_data(input, options=None)` Process the input data with optional configuration. ```python from mylib import process_data result = process_data( input="raw data", options={ "format": "json", "validate": True } ) print(result) # Output: {"status": "success", "data": [...]} ``` ### `validate_schema(data, schema)` Validate data against a JSON schema. ```python from mylib import validate_schema is_valid = validate_schema( data={"name": "test", "value": 42}, schema={"type": "object", "required": ["name"]} ) # Returns: True ``` --- *Generated documentation for MyPlugin v1.0* """ custom_css = """ .doc-sheet h1 { border-bottom: 1px solid var(--foreground); } .doc-sheet h2 { color: var(--bluish); margin-top: 1.5rem; } .doc-sheet code { background-color: color(var(--background) blend(white 95%)); } """ sheet = mdpopups.new_html_sheet( self.window, name="API Documentation", contents=content, md=True, css=custom_css, flags=0, group=-1, wrapper_class="doc-sheet" ) return sheet ``` -------------------------------- ### mdpopups.color_box (Base64) Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Generates a color preview box image encoded in base 64, formatted as an HTML img tag. ```APIDOC ## mdpopups.color_box (Base64) ### Description Generates a color preview box image encoded in base 64 and formatted to be inserted into Markdown or HTML code as an img tag. ### Parameters - **colors** ([str]) - Required - A list of color strings formatted as #RRGGBBAA. - **border** (str) - Required - The color for the color box border (#RRGGBB). - **border2** (str) - Optional - The optional secondary border color (#RRGGBB). - **height** (int) - Optional - Height of color box (Default: 32). - **width** (int) - Optional - Width of color box (Default: 32). - **border_size** (int) - Optional - Width of the color box border (Default: 1). - **check_size** (int) - Optional - Size of checkered box squares for transparent colors (Default: 4). - **max_colors** (int) - Optional - Max number of colors evaluated (Default: 5). - **alpha** (bool) - Optional - Create images with real alpha channel (Default: False). - **border_map** (int) - Optional - Mapping of which borders to show (Default: 0xF). ``` -------------------------------- ### Configure Frontmatter from Python Objects Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Use mdpopups.format_frontmatter to convert a Python dictionary into YAML frontmatter for Markdown content. ```py3 frontmatter = { "allow_code_wrap": false, "language_map": { "language": [["mapping_alias"], ["MyPackage/MySyntaxLanguage"]] }, "markdown_extensions": [ "markdown.extensions.admonition", "markdown.extensions.attr_list", "markdown.extensions.def_list", "markdown.extensions.nl2br", # Smart quotes always have corner cases that annoy me, so don't bother with them. {"markdown.extensions.smarty": {"smart_quotes": False}}, "pymdownx.betterem", { "pymdownx.magiclink": { "repo_url_shortener": True, "base_repo_url": "https://github.com/facelessuser/sublime-markdown-popups" } }, "pymdownx.extrarawhtml", "pymdownx.keys", {"pymdownx.escapeall": {"hardbreak": True, "nbsp": True}}, # Sublime doesn't support superscript, so no ordinal numbers {"pymdownx.smartsymbols": {"ordinal_numbers": False}} ] } content = mdpopups.format_frontmatter(frontmatter) + markdown_content ``` -------------------------------- ### Specify Custom User CSS File Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/settings.md Overrides the default CSS with a custom theme file. Provide a relative path to the CSS file, e.g., "Packages/User/my_custom_theme.css". User CSS is applied last. ```json "mdpopups.user_css": "Packages/User/mdpopups.css" ``` -------------------------------- ### Use Sublime Text Syntax Highlighter Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/settings.md Determines whether to use Pygments or Sublime Text's native highlighter for code. Set to true to use Sublime's highlighter. ```json "mdpopups.use_sublime_highlighter": true ``` -------------------------------- ### Enable Marko with GitHub Flavored Markdown Extensions Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Enable the CommonMark parser with GitHub Flavored Markdown extensions by listing 'gfm' under markdown_extensions. Note that table support is stripped for minihtml compatibility. ```yaml --- markdown_parser: marko markdown_extensions: - gfm --- ``` -------------------------------- ### Scope to Style Conversion Source: https://context7.com/facelessuser/sublime-markdown-popups/llms.txt Retrieve color scheme style information for specific scopes to build dynamic CSS for popups. ```python import mdpopups def get_scope_styling(view): """Get style information for various scopes.""" # Get style for a specific scope keyword_style = mdpopups.scope2style(view, "keyword.control") # Returns: {'color': '#FF5733', 'background': None, 'style': 'bold'} # Get style for string scope string_style = mdpopups.scope2style(view, "string.quoted") # Get explicit background (only if defined in scheme) comment_style = mdpopups.scope2style( view, "comment.line", selected=False, explicit_background=True ) # Build dynamic CSS based on scheme dynamic_css = f""" .keyword {{ color: {keyword_style['color']}; }} .string {{ color: {string_style['color']}; }} .comment {{ color: {comment_style['color']}; font-style: {comment_style['style'] if 'italic' in comment_style['style'] else 'normal'}; }} """ return dynamic_css ``` -------------------------------- ### Configure Custom Fences for Special Block Content Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Use the 'custom_fences' option to define custom fences for special block content like UML diagrams. Requires configuration via mdpopups.mdx.superfences. ```yaml --- custom_fences: - name: uml class: uml format: !!python/name:my_package.my_module.my_custom_format ... ``` -------------------------------- ### Enable Marko CommonMark Parser Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Specify 'marko' in the frontmatter to enable the CommonMark compliant Marko parser. Requires Python 3.13+ and Sublime Text 4201+. ```yaml --- markdown_parser: marko --- ``` -------------------------------- ### Syntax Highlighting for Popups Source: https://context7.com/facelessuser/sublime-markdown-popups/llms.txt Generate syntax-highlighted code blocks or inline snippets using the current color scheme. Supports custom language mappings for non-standard syntaxes. ```python import mdpopups def highlight_code_snippet(view, code, language): """Highlight code with the current color scheme.""" source_code = ''' class DataProcessor: def __init__(self, config): self.config = config self._cache = {} def process(self, data): """Process data according to configuration.""" if data in self._cache: return self._cache[data] result = self._transform(data) self._cache[data] = result return result def _transform(self, data): return data.upper() ''' # Highlight for block display highlighted_block = mdpopups.syntax_highlight( view, source_code, language="python", inline=False, allow_code_wrap=True ) # Highlight for inline display inline_code = "self.process(data)" highlighted_inline = mdpopups.syntax_highlight( view, inline_code, language="python", inline=True ) # Use custom language mapping for plugin-specific syntaxes custom_map = { "myconfig": [["myconfig", "cfg"], ["MyPlugin/MyConfigSyntax"]] } config_code = "setting = value" highlighted_config = mdpopups.syntax_highlight( view, config_code, language="myconfig", language_map=custom_map ) return highlighted_block, highlighted_inline ``` -------------------------------- ### Color Box Generation Source: https://context7.com/facelessuser/sublime-markdown-popups/llms.txt Create base64-encoded color preview images for use in popups. Supports single colors, palettes, transparency, and alpha channels. ```python import mdpopups def create_color_preview(): """Generate various color preview boxes.""" # Single color box single_color = mdpopups.color_box( colors=["#FF5733FF"], # RRGGBBAA format border="#000000", height=24, width=24, border_size=1 ) # Color palette with multiple colors palette = mdpopups.color_box( colors=[ "#FF5733FF", # Red-orange "#33FF57FF", # Green "#3357FFFF", # Blue "#FF33F5FF", # Pink "#F5FF33FF", # Yellow ], border="#333333", border2="#CCCCCC", # Double border for visibility height=32, width=150, border_size=2, max_colors=5 ) # Transparent color with checkered background transparent_color = mdpopups.color_box( colors=["#FF573380"], # 50% transparent border="#000000", height=32, width=32, check_size=4, # Checkerboard square size alpha=False # Simulate transparency with checkerboard ) # Color box with real alpha channel alpha_color = mdpopups.color_box( colors=["#3357FF80"], border="#000000", height=32, width=32, alpha=True, # Real alpha channel border_map=mdpopups.colorbox.TOP | mdpopups.colorbox.BOTTOM ) # Use in popup content popup_content = f""" ## Color Preview **Selected Color:** {single_color} **Palette:** {palette} **Transparent:** {transparent_color} """ return popup_content ``` -------------------------------- ### new_html_sheet Function Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Accepts Markdown and creates a Sublime HTML sheet, with options for syntax highlighting, CSS injection, and template variables. ```APIDOC ## new_html_sheet Function ### Description Accepts Markdown and creates a Sublime HTML sheet. By default, the built-in Sublime syntax highlighter will be used for code highlighting. ### Parameters #### Path Parameters - **window** (sublime.Window) - Required - A Sublime Text view object. - **name** (str) - Required - Name for the HTML sheet. - **contents** (str) - Required - Markdown/HTML content for the popup. - **md** (bool) - Optional - Defines whether the content is Markdown and needs to be converted. Default: True. - **css** (str) - Optional - Additional CSS that will be injected. Default: None. - **flags** (int) - Optional - Flags to pass down to the Sublime Text `new_html_sheet` call. Default: 0. - **group** (int) - Optional - Specify window group. Default: -1. - **wrapper_class** (str) - Optional - A string containing the class name you wish wrap your content in. A `div` will be created with the given class. Default: None. - **template_vars** (dict) - Optional - A dictionary containing template vars. These can be used in either the CSS or the HTML/Markdown content. These vars are found under the object `plugin`. Default: None. - **template_env_options** (dict) - Optional - A dictionary containing options for the Jinja2 template environment. This **only** applies to the **HTML/Markdown** content. Default: None. ### Notes - `new_html_sheet` is new in 3.6.0. This feature should be considered experimental. - Removed in 4.0: The parameters `nl2br` and `alow_code_wrap` are removed. If passed, they will be ignored. To disable `nl2br`, customize which extensions get loaded. To enable code wrapping, see [Enable Code Wrapping](#enable-code-wrapping). ``` -------------------------------- ### Scope to Style Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Guess the style applied to a Sublime Text scope and return it as a dictionary. ```APIDOC ## Scope to Style ### Description Guess the style applied to a Sublime Text scope and return it as a dictionary. This function attempts to accurately determine the color and style (bold, italic) associated with a given scope. ### Method `mdpopups.scope2style` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **view** (sublime.View) - Required - Sublime text View object to search the correct color scheme. - **scope** (string) - Required - The scope to search for. - **selected** (bool) - Optional - Whether this scope is in a selected state. Defaults to False. - **explicit_background** (bool) - Optional - Only return a background if one is explicitly defined in the color scheme. Defaults to False. ### Request Example ```python view = sublime.active_window().active_view() style = mdpopups.scope2style(view, 'source.python.syntax', selected=True) print(style) ``` ### Response #### Success Response (200) - **dict** (dict) - A dictionary containing 'color', 'background', and 'style' keys. 'color' and 'background' can be None if not found or explicitly not set. 'style' can be 'bold', 'italic', 'bold italic', or an empty string. #### Response Example ```json { "color": "#FFFFFF", "background": "#333333", "style": "bold italic" } ``` ``` -------------------------------- ### Configure Markdown Popups with Frontmatter Source: https://context7.com/facelessuser/sublime-markdown-popups/llms.txt Use YAML frontmatter within Markdown content or generate it programmatically with Python dictionaries to customize Markdown extensions and options for popups. ```python import mdpopups def create_configured_popup(view): """Create popup with custom Markdown configuration.""" # Method 1: YAML frontmatter in content content_with_frontmatter = """ --- allow_code_wrap: true markdown_parser: markdown markdown_extensions: - markdown.extensions.admonition - markdown.extensions.attr_list - markdown.extensions.def_list - markdown.extensions.nl2br - pymdownx.betterem - pymdownx.magiclink: repo_url_shortener: true base_repo_url: https://github.com/myorg/myrepo - pymdownx.keys - pymdownx.escapeall: hardbreak: true nbsp: true custom_fences: - name: mermaid class: mermaid format: !!python/name:mypackage.format_mermaid --- # Configured Content This content uses custom extensions. Press ++ctrl+s++ to save. Check issue #123 for details. """ # Method 2: Programmatic frontmatter generation config = { "allow_code_wrap": True, "language_map": { "mylang": [["mylang", "ml"], ["MyPackage/MySyntax"]] }, "markdown_extensions": [ "markdown.extensions.admonition", "markdown.extensions.attr_list", "markdown.extensions.def_list", "markdown.extensions.nl2br", {"markdown.extensions.smarty": {"smart_quotes": False}}, "pymdownx.betterem", { "pymdownx.magiclink": { "repo_url_shortener": True, "base_repo_url": "https://github.com/myorg/myrepo" } }, "pymdownx.keys", {"pymdownx.escapeall": {"hardbreak": True, "nbsp": True}}, ] } markdown_content = """ # Dynamic Configuration This popup was configured programmatically. """ # Generate frontmatter from dictionary content = mdpopups.format_frontmatter(config) + markdown_content mdpopups.show_popup(view, content, md=True) ``` -------------------------------- ### Tint Image to HTML Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Tints a PNG image and returns a base64 encoded HTML element. ```py3 mdpopups.tint ``` -------------------------------- ### Enable MdPopups Debug Mode Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/settings.md Turns on debug mode to output detailed information to the console. Set to 1 for errors, 2 for warnings and errors, or 3 for general info and warnings. ```json "mdpopups.debug": 1, ``` -------------------------------- ### Resolve Images Asynchronously in Popups Source: https://context7.com/facelessuser/sublime-markdown-popups/llms.txt Use mdpopups.resolve_images to download and embed remote images into popups without blocking the UI thread. ```python # First convert markdown to HTML html = mdpopups.md2html(view, markdown_content) def on_images_resolved(final_html): """Called when all images are downloaded and embedded.""" # Now show the popup with embedded images full_html = f'
{final_html}
' view.show_popup( full_html, max_width=800, max_height=600 ) # Resolve images asynchronously (non-blocking) resolver_handle = mdpopups.resolve_images( html, mdpopups.worker_thread_resolver, # Run downloads on worker thread on_images_resolved ) # Alternative resolvers: # mdpopups.blocking_resolver - Blocks until download complete # mdpopups.ui_thread_resolver - Runs on main UI thread ``` -------------------------------- ### Package Control Dependencies for mdpopups with typing Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Declare both 'mdpopups' and 'typing' as dependencies for Sublime Text build 3124 and later, ensuring Python 3.3 compatibility. ```json { "*": { ">=3124": [ "mdpopups", "typing" ] } } ``` -------------------------------- ### mdpopups.show_popup Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Creates and displays a new Markdown or HTML popup in a Sublime Text view. ```APIDOC ## mdpopups.show_popup ### Description Accepts Markdown and creates a Sublime popup. By default, the built-in Sublime syntax highlighter will be used for code highlighting. ### Parameters - **view** (sublime.View) - Required - A Sublime Text view object. - **content** (str) - Required - Markdown/HTML content for the popup. - **md** (bool) - Optional (Default: True) - Defines whether the content is Markdown and needs to be converted. - **css** (str) - Optional (Default: None) - Additional CSS that will be injected. - **flags** (int) - Optional (Default: 0) - Flags to pass down to the Sublime Text view.show_popup call. - **location** (int) - Optional (Default: -1) - Location to show popup in view. -1 means to show right under the first cursor. - **max_width** (int) - Optional (Default: 320) - Maximum width of the popup. - **max_height** (int) - Optional (Default: 240) - Maximum height of the popup. - **on_navigate** (def fn()) - Optional (Default: None) - Callback that receives one variable href. - **on_hide** (def fn()) - Optional (Default: None) - Callback for when the popup is hidden. - **wrapper_class** (str) - Optional (Default: None) - A string containing the class name you wish wrap your content in. - **template_vars** (dict) - Optional (Default: None) - A dictionary containing template vars. - **template_env_options** (dict) - Optional (Default: None) - A dictionary containing options for the Jinja2 template environment. ``` -------------------------------- ### mdpopups.version Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Retrieves the current version of the MdPopups library. ```APIDOC ## mdpopups.version ### Description Returns the version of the MdPopups library as a tuple of integers. ### Response - **tuple** (int,) - A tuple representing the major, minor, and patch version numbers. ``` -------------------------------- ### Syntax Highlight API Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Allows for syntax highlighting outside the Markdown environment by feeding code directly and specifying the language. ```APIDOC ## Syntax Highlight ### Description Allows for syntax highlighting outside the Markdown environment. You can just feed it code directly and give it the language of your choice, and you will be returned a block of HTML that has been syntax highlighted. By default, the built-in Sublime highlighter will be used for code highlighting. ### Method `mdpopups.syntax_highlight` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **view** (sublime.View) - Required - Sublime text View object. - **src** (str) - Required - The source code to be converted. No fence tokens are needed (` ``` `). - **language** (str) - Optional - Specifies the language to highlight as. Defaults to None. - **inline** (bool) - Optional - Will return the code formatted for inline display. Defaults to False. - **allow_code_wrap** (bool) - Optional - Do not convert all the spaces in code blocks to ` ` so that wrapping can occur. Defaults to False. - **language_map** (Dict) - Optional - Language map that can be passed in to add to the built-in language map. Mainly for Plugins to add plugin specific languages that are too specific to be added globally. Defaults to None. ### Request Example ```python import mdpopups # Assuming 'view' is a valid sublime.View object html_output = mdpopups.syntax_highlight(view, src='print("Hello, World!")', language='python') ``` ### Response #### Success Response (200) - **html_output** (str) - HTML string with syntax highlighted code. ``` -------------------------------- ### Convert Tabs to Spaces with mdpopups.tabs2spaces Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Uses intelligent tab stop detection to convert tabs to spaces, which is more accurate than simple fixed-width conversion. Useful for preparing text for syntax highlighting. ```pycon3 >>> import mdpopups >>> text = ''' ============================================================ T\tTp\tSp\tD\tDp\tS\tD7\tT ------------------------------------------------------------ A\tF#m\tBm\tE\tC#m\tD\tE7\tA A#\tGm\tCm\tF\tDm\tD#\tF7\tA# B♭\tGm\tCm\tF\tDm\tE♭m\tF7\tB♭ ''' >>> print(mdpopups.tabs2spaces(text, tab_size=8)) ============================================================ T Tp Sp D Dp S D7 T ------------------------------------------------------------ A F#m Bm E C#m D E7 A A# Gm Cm F Dm D# F7 A# B♭ Gm Cm F Dm E♭m F7 B ``` -------------------------------- ### Show Markdown Popup Tooltip Source: https://context7.com/facelessuser/sublime-markdown-popups/llms.txt Display a Markdown-formatted popup at a specific location in a Sublime Text view. Customize appearance with CSS, set dimensions, and define navigation callbacks. Ensure `md=True` for Markdown parsing. ```python import sublime import sublime_plugin import mdpopups class MyPluginHoverCommand(sublime_plugin.EventListener): def on_hover(self, view, point, hover_zone): if hover_zone != sublime.HOVER_TEXT: return content = """ ## Function Documentation This function performs **important operations**. ```python def my_function(arg1, arg2): return arg1 + arg2 ``` - Parameter `arg1`: The first value - Parameter `arg2`: The second value """ custom_css = """ .my-plugin-popup h2 { color: var(--bluish); } .my-plugin-popup code { background-color: var(--background); } """ mdpopups.show_popup( view, content, md=True, css=custom_css, flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY, location=point, max_width=600, max_height=400, on_navigate=self.on_navigate, on_hide=self.on_hide, wrapper_class="my-plugin-popup" ) def on_navigate(self, href): print(f"User clicked: {href}") def on_hide(self): print("Popup hidden") ``` -------------------------------- ### Style Elements with CSS Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Use wrapper classes to scope CSS styles to specific plugin content. ```css .mdpopups .myplugin-wrapper .myclass {} ``` ```css .myplugin-wrapper .myclass {} ``` -------------------------------- ### Retrieve Library Version Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Access the library version as a tuple of integers representing major, minor, and patch versions. ```py3 mdpopups.version ``` -------------------------------- ### Resolve Scope to Style Dictionary Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/api.md Guesses the style attributes for a given Sublime Text scope. ```py3 mdpopups.scope2style ``` ```py3 { # Colors will be None if not found, # though usually, even if the scope has no color # it will return the overall theme foreground. # # Background might be None if using `explicit_background` # as it only returns a background if that style specifically # defines a background. "color": "#RRGGBB", "background": "#RRGGBB", # Style will usually be either 'bold', 'italic'. # Multiple styles may be returned 'bold italic' or an empty string ''. "style": 'bold italic' } ``` -------------------------------- ### Map Custom Sublime Syntax Languages Source: https://github.com/facelessuser/sublime-markdown-popups/blob/master/docs/src/markdown/settings.md Maps personal Sublime syntax languages to be used with the native highlighter. Allows defining new entries or extending existing ones. ```json "mdpopups.sublime_user_lang_map": { "language": [["mapping_alias"], ["MyPackage/MySyntaxLanguage"]] } ``` ```json "mdpopups.sublime_user_lang_map": { "javascript": [["javascript", "js"], ["JavaScript/JavaScript", "JavaScriptNext - ES6 Syntax/JavaScriptNext"]] } ``` ```json "mdpopups.sublime_user_lang_map": { "javascript": [["javascript", "js"], ["scope:source.js"]] } ```