Home > other >  Extending VSCode Markdown syntax highlighting to match nested Javascript code
Extending VSCode Markdown syntax highlighting to match nested Javascript code

Time:12-29

I am trying to extend VSCode's Markdown syntax highlighter in order to highlight some nested Javascript wrapped in a custom syntax. For example, the following Markdown file

# Example

@@$ var value = 10;

The result is @@{value}.

would be converted to

# Example

The result is 10.

I would like the following to be highlighted as Javascript in VSCode, as if they were wrapped in a fenced code block:

  • The contents of a line starting with @@$.

  • The contents wrapped between @@{ and }.

I tried modifying markdown.tmLanguage.json to add these:

"fenced_code_block_majsdown2": {
    "begin": "(^|\\G)(@@$)",
    "name": "markup.fenced_code.block.markdown",
    "end": "(^|\\G)(\\r\\n|\\r|\\n)\\s*$",
    "patterns": [{ "include": "source.js" }]
},
"fenced_code_block_majsdown": {
    "begin": "(^|\\G)(@@{)",
    "name": "markup.fenced_code.block.markdown",
    "end": "(^|\\G)(})\\s*$",
    "patterns": [{ "include": "source.js" }]
},

The code gets highlighted properly, but it seems that the "end" bit is ignored and I don't understand why -- starting from either a @@$ or @@{, the entire document is highlighted as Javascript. I've tried several combinations of regexes, and tried removing the initial part ((^|\\G)), but I couldn't figure out why the highlighter is so greedy.

How can I achieve my desired goal?

CodePudding user response:

I ended up solving the problem this way:

{
    "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
    "name": "Majsdown",
    "patterns": [
        {
            "include": "#majsdown_inject_expression"
        },
        {
            "include": "#majsdown_execute_statement"
        },
        {
            "include": "text.html.markdown"
        }
    ],
    "repository": {
        "majsdown_inject_expression": {
            "begin": "(.*?)(@@\\{)",
            "name": "test",
            "end": "(\\})",
            "beginCaptures": {
                "2": {
                    "name": "keyword.control.majsdown"
                }
            },
            "endCaptures": {
                "1": {
                    "name": "keyword.control.majsdown"
                }
            },
            "patterns": [
                {
                    "include": "source.js"
                }
            ]
        },
        "majsdown_execute_statement": {
            "begin": "(.*?)(@@\\$)",
            "name": "test",
            "end": "(\\r\\n|\\r|\\n)",
            "beginCaptures": {
                "2": {
                    "name": "keyword.control.majsdown"
                }
            },
            "patterns": [
                {
                    "include": "source.js"
                }
            ]
        }
    },
    "scopeName": "source.majsdown"
}
  • Related