具有特定扩展名的文件的 VS 代码片段

VS Code snippets for files with specific extension

Visual Studio 代码允许创建片段,针对各种语言语法进行分隔。但是是否可以不仅指定语言,还可以为创建的代码段指定特定文件的扩展名?

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

对于使用 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 引用片段的键绑定 - 片段本身在您的片段文件之一中定义如下:

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

或者在键绑定中使用实际的代码段正文:

{
  "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])/ ${2:/downcase}${3:/downcase}/g}"
  }
},