Alexei Danchenkov
Alexei Danchenkov

Reputation: 2082

How to write a custom formatter in VSCode that inherits from existing formatters?

I have HTML code with YAML front matter for content and I would like to format both parts concurrently. I have created a custom syntax and highlighting works well.

How to register a new formatter for the custom file type, which would inherit from existing formatters in VSCode?

That would look like this:

---
title: "Title"
description: "Long and arduous description"
x:
  bodyclasses: home
---
{{extends "page.html"}}

{{block Body()}}
<article class="main">
  <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Voluptates, magni sapiente voluptas magnam omnis nisi aut amet! Facilis exercitationem voluptatem dolorem asperiores accusamus vitae, maiores veritatis, animi perspiciatis dolor commodi!</p>
</article>
{{end}}

Here is my current jet.tmLanguage.json (the format above is for Go Jet HTML template files with YAML as a front matter):

{
  "$schema": "https://raw.githubusercontent.com/martinring/tmlanguage/master/tmlanguage.json",
  "name": "HTML Template (Jet)",
  "scopeName": "text.html.jet",
  "fileTypes": [
    "jet"
  ],
  "patterns": [
    {
      "yaml.format.enable": true,
      "include": "#frontMatter"
    },
    {
      "html.format.enable": true,
      "include": "text.html.basic"
    }
  ],
  "repository": {
    "frontMatter": {
      "begin": "\\A-{3}\\s*$",
      "contentName": "meta.embedded.block.frontmatter",
      "patterns": [
        {
          "include": "source.yaml"
        }
      ],
      "end": "(^|\\G)-{3}|\\.{3}\\s*$"
    },
  }
}

Upvotes: 1

Views: 2107

Answers (1)

Noah
Noah

Reputation: 919

I have a few options for you: (in order of least to most effort)

  1. You can make a PR to the Microsoft VSCode Repository and see if they can add in a formatted for that file type. (see if they can merge this into VSCode)

  2. You can install a VSCode plugin to apply custom formatting to your files, it provides a tutorial to configure the format tool as well, you can install it here.

I don't run VSCode for Golang development, but I do see the Golang Plugin in the VSCode market and it says it formats tmpl files but doubt it would format the .jet file. An issue could be made with Golang community plugin to add support for that as well.

  1. Another option is to switch to one of the many IDEs like JetBrains GoLand (can recommend) that has support for formatting the Jet HTML Templates. (Only pointing this out if you are not attached to VSCode)

  2. Read through the "Creating a Formatter Plugin" documentation and build a VSCode Extention. Then you could publish this extension for others.

Upvotes: 1

Related Questions