【问题标题】:VSCode Snippet syntax for duplicating snippet lines用于复制代码段行的 VSCode 代码段语法
【发布时间】:2021-11-23 11:58:44
【问题描述】:

假设我想为打字稿界面创建一个 VSCode sn-p,如下所示:

interface MyInterface{ 
  prop1: string; 
  prop2: string;
  prop3: string
}

现在我可以创建以下 sn-p:

"myinterface": {
  "prefix": "myinterface",
  "body": [
    "interface MyInterface{ ",
    "  prop1: string; ",
    "  prop2: string;",
    "  prop3: string",
    "}"
  ],
  "description": "not smart interface creator"
}

但如果我想在我的界面中添加prop4prop5prop6,该怎么办?无论如何有条件地扩展sn-p,以便通过点击Tab 会提示我向接口添加另一个prop 字段,格式为 ${1:propX}: ${2:string};

另一个用例是写出一个数组:

const myArray = [val1, val2, val3]

【问题讨论】:

    标签: visual-studio-code code-snippets vscode-snippets


    【解决方案1】:

    我认为没有任何方法可以直接做你想做的事。但是您可以使用下面的方法 2 非常接近。

    方法一

    "PS3": {
      "prefix": "ps3",
      "body": [
        "interface MyInterface{",  
        "${1/([^,]+)([,\\s]*|)/\t$1: string;${2:+\n}/g}",
        "}"
      ]
    },
    

    这类似于我在snippets with variable number of arguments 中使用的技术。这是上面的演示:

    但是您不能使用此方法选择和轻松编辑变量或类型。


    方法二

    这比较棘手,但会导致选择的键和类型更容易更改。你需要 2 个 sn-ps"

    "myinterface": {
      "prefix": "myinterface",
      "body": [
        "interface MyInterface{ ",
    
        // I jazzed it up by adding a choice transform
        "\t${1:propX}: ${0:${2|string,int,bool|}};",
        "}"
      ],
      "description": "sorta smart interface creator"
    },
    
    "addProps": {
      "prefix": "[int, bool, string]",  // note multiple prefixes
      "body": [
        "$TM_SELECTED_TEXT;",
        "${1:propX}: ${0:${2|string,int,bool|}}",
      ],
      "description": "add props to interface"
    },
    

    基本上,这使用第一个 sn-p 的结尾作为附加 key: type 对的前缀。演示:

    在切换到您选择的int/bool/string 选项卡后,再次移动到最后 - 这将自动选择您从int/bool/string 中选择的内容。

    现在您可以使用 Ctrl+Space 触发第二个 sn-p 的建议以插入一个键:一次键入对。请注意,第二个 sn-p 有三个前缀来匹配您的类型选择,在行尾重新插入您的选择并添加另一个键:type line below。

    【讨论】:

      猜你喜欢
      • 2019-12-11
      • 2019-11-04
      • 1970-01-01
      • 2020-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-01
      • 1970-01-01
      相关资源
      最近更新 更多