Published on

How to style markdown code blocks in VS Code


Here's a quick tip for everybody using VS Code for viewing markdown files with code blocks. It might be handy for all of you to use VS Code as a note-taking app.

The problem is that by default, in VS Code markdown edit mode (not the preview mode, that's an entirely different story), code blocks are not very clearly styled. They don't look much different than other types of text, and VS Code doesn't offer an easy way to achieve that. The main problem is that VS Code theming doesn't allow setting the background color for different types of parsed syntax. Ideally, I'd like to set background color code blocks so they'd be easily distinguishable from the rest of the text.

VS Code lack of code blocks styling

Fortunately, there's a Highlight extension, which allows you to set much more advanced styling (background color 🎉) by defining regex patterns and styling rules. Of course, ideally, I'd prefer to use theme tokens from the tmTheme parser, but it seems it's the best we can have 🤷.

So, first, of course, install the extension. Then to define to enable code blocks highlighting for a particular repo, create a settings file .vscode/settings.json.

  "highlight.regexes": {
    "([^`])(`[^`]+?`)": {
      "filterLanguageRegex": "markdown",
      "regexFlags": "g",
      "filterFileRegex": ".*\\.md",
      "decorations": [{}, {
        "backgroundColor": "rgba(0, 0, 0, 0.05)",
        "border": "1px dashed rgba(0, 0, 0, 0.1)",
        "borderRadius": "3px"
      }, {}]
    "(```.+?```)": {
      "regexFlags": "gs",
      "decorations": {
        "backgroundColor": "rgba(0, 0, 0, 0.05)",
        "isWholeLine": true,
      "filterLanguageRegex": "markdown",
      "filterFileRegex": ".*\\.md"

And now, after applying the settings (drums 🥁🥁🥁).

VS Code with code blocks styling

There's a little bit of regex trickery here around selecting single backticks ([^`])(`[^`]+?`) and triple backticks group (```.+?```). After that, there's only styling left. I'm using backgrounds and a bit of border color and radius in case of inline code blocks, but you can do a little bit more with this API.

Do you want to get updates about new content? Leave your email or use RSS Feed.