【问题标题】:How to write a custom formatter in VSCode that inherits from existing formatters?如何在 VSCode 中编写继承自现有格式化程序的自定义格式化程序?
【发布时间】:2022-01-10 20:22:20
【问题描述】:

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

如何为自定义文件类型注册一个新的格式化程序,它将继承自 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(上面的格式是用于以 YAML 为前端的 Go Jet HTML 模板文件):

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

【问题讨论】:

  • 也许简单的解决方案可能是最好的解决方案......为什么不把 yaml 作为第一个(评论)元素
  • @Akxe 我更新了帖子以包含我当前的设置,我相信它就是这样做的。但是,我正在尝试从 HTML 和 YAML 为两个不同的部分继承格式化程序,我希望这两个部分能够被继承。语法突出显示似乎有效。
  • 我不熟悉它是如何工作的,但我知道有许多多格式化程序可以在 JS/TS 中使用 /*yaml*/`... yaml config ...` 之类的注释来格式化模板字符串

标签: html visual-studio-code yaml formatter


【解决方案1】:

我有几个选项供您选择:(按从小到大的顺序)

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

  2. 您可以安装一个 VSCode 插件来对您的文件应用自定义格式,它还提供了配置格式工具的教程,您可以安装它here

我没有为 Golang 开发运行 VSCode,但我确实看到了 Golang Plugin in the VSCode market,它说它格式化了 tmpl 文件,但怀疑它会格式化 .jet 文件。 Golang community plugin 也可以添加对此的支持。

  1. 另一种选择是切换到支持格式化 Jet HTML 模板的众多 IDE 之一,例如 JetBrains GoLand(可以推荐)。 (仅在您未附加到 VSCode 时才指出这一点)

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-03
    • 1970-01-01
    • 1970-01-01
    • 2012-12-09
    • 2018-02-15
    • 1970-01-01
    • 2017-10-12
    相关资源
    最近更新 更多