【问题标题】:VS Code snippets for files with specific extension具有特定扩展名的文件的 VS 代码片段
【发布时间】:2021-04-01 14:18:21
【问题描述】:

Visual Studio Code 允许创建 sn-ps,为各种语言语法分开。但是是否可以为创建的 sn-p 不仅指定语言,还指定特定文件的扩展名?

例如: 我想专门为c#.csproj 文件创建sn-p。该文件具有xml 语法,我可以将sn-p 创建为xml sn-p,但我不想在除xml 之外的其他xml 文件中看到此sn-p。

【问题讨论】:

    标签: visual-studio-code vscode-snippets


    【解决方案1】:

    对于 sn-ps,您使用 scope 参数:

    "FrontMatter": {
      "scope": "csharp",         // put your language identifier here
      "prefix": "frontmatter",
      "body": [
          "...",
      ]
    },
    

    如果该范围不够具体,请改用键绑定,这样可以提供更多的具体性。

    scope 不能接受像editorTextFocus && !editorReadonly && resourceExtname =~ /\\.csproj/ 这样的内容。

    ----------- 对于键绑定,您可以使用以下 -----------

    "when": "editorTextFocus && !editorReadonly && resourceExtname =~ /\\.csproj/ && editorLangId == csharp"

    when clause operator

    =~ 运算符允许在右侧使用正则表达式,因此您可以这样做

    resourceExtname =~ /\\.(html|css|scss) 限制为这三个扩展。在我看来,您确实必须在扩展程序本身之前专门添加 .,但这似乎很奇怪,但您似乎这样做了。

    name 引用 sn-p 的键绑定 - sn-p 本身在您的以下 sn-p 文件之一中定义:

    {
      "key": "alt+l",
      "command": "editor.action.insertSnippet",
      "args": {
        "name": "My groovy comment style"
      },
      "when": "editorTextFocus && !editorReadonly && resourceExtname =~ /\\.csproj/ && editorLangId == csharp"
    },
    

    或在键绑定中使用实际的 sn-p 正文:

    {
      "key": "alt+m",
      "command": "editor.action.insertSnippet",
      "when": "editorTextFocus && !editorReadonly && resourceExtname =~ /\\.csproj/ && editorLangId == csharp",
      "args": {
          "snippet": "${TM_SELECTED_TEXT/([a-z])([A-Z]+(?=[A-Z]))|([A-Z][a-z])/$1 ${2:/downcase}${3:/downcase}/g}"
      }
    },
    

    【讨论】:

    • 我也有同样的问题,就是需要特定文件扩展名的 sn-ps,但是我不确定在哪里放置与 sn-p 相关的“when”子句。你能详细说明一下吗?
    • 我尝试了同样的方法,但我收到了“不允许使用属性”的警告。
    猜你喜欢
    • 2020-06-06
    • 2011-02-14
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多