如何在 VSCode 中编写继承自现有格式化程序的自定义格式化程序?

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

我有 HTML 代码和内容的 YAML 前端内容,我想同时格式化这两个部分。我创建了一个自定义语法并且突出显示效果很好。

如何为自定义文件类型注册一个新的格式化程序,它将继承 VSCode 中现有的格式化程序?

看起来像这样:

---
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}}

这是我当前的 jet.tmLanguage.json(上面的格式是 Go Jet HTML 模板文件,YAML 作为前端):

{
  "$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*$"
    },
  }
}

我有几个选项供您选择:(按努力程度从低到高的顺序)

  1. 您可以向 Microsoft VSCode Repository 提交 PR,看看他们是否可以添加适合该文件类型的格式。 (看看他们是否可以将其合并到 VSCode)

  2. 您可以安装一个VSCode插件来对您的文件应用自定义格式,它也提供了配置格式工具的教程,您可以安装它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. 另一种选择是切换到支持格式化 Jet HTML 模板的众多 IDE 之一,例如 JetBrains GoLand(可以推荐)。 (仅在您不依附于 VSCode 时才指出这一点)

  2. 通读 "Creating a Formatter Plugin" 文档并构建 VSCode 扩展。然后你可以为其他人发布这个扩展。