When creating a VSCode snippet, how can I transform a variable to title-case (like TitleCase)?

江枫思渺然 提交于 2021-02-04 17:49:07

问题


https://code.visualstudio.com/docs/editor/userdefinedsnippets#_placeholdertransform

My aim is to automatically set the class name within the context of the snippet being inserted. VSCode does not natively support class or method names, but it does support the file name.

My file names closely mimic the class name:

foo-bar.ts for class FooBar.

Here is my current code snippet wherein I can transform "foo-bar" to "Foo-bar" using the native "capitalize" grammar provided by VSCode. TM_FILENAME_BASE is a native variable which extracts the filename without the extension:

"My Snippet": {
    "scope": "typescript",
    "prefix": "snippet",
    "body": [
        "${1}() {",
        "\treturn this.get(${TM_FILENAME_BASE/(.*)/${1:/capitalize}/}.FIELD.${3});",
        "}",
        "",
        "$0"
    ],
    "description": "Creates a function wrapper for a model's attribute."
}

I'd like to transform "foo-bar" to "FooBar".


回答1:


Try this:

  "My Snippet": {
    "scope": "typescript",
    "prefix": "snippet",
    "body": [
      "${1}() {",

      // "\treturn this.get(${TM_FILENAME_BASE/([a-z]*)-*([a-z]*)/${1:/capitalize}${2:/capitalize}/g}.FIELD.${3});",

      "\treturn this.get(${TM_FILENAME_BASE/(.*)/${1:/pascalcase}/g}.FIELD.${3});",

      "}",
      "",
      "$0"
    ],
    "description": "Creates a function wrapper for a model's attribute."
  }

EDIT : In October, 2018 the \pascalcase transform was added to vscode - see commit, but not yet added to the documentation (as of the date of this edit). I have added the much simpler transform above which accomplishes the PascalCase transform.

Demo added, uses the clipboard after the first filename case (test-bed-snippets.xxx) just to make the various possibilities easy to demonstrate.

See also snippet transform to CamelCase




回答2:


Thought it might be useful to supplement Mark's excellent answer with another example.

In my case, I wanted to take a name - as selected text - and convert it to Swift code that would instantiate a new class passing in variables name and email address.

So for example I select John Smith as first name, last name and convert to:

let johnSmith = User(name: "John Smith", email: "john.smith@foorbar.com")

Code snippet for this would be as follows:

"User": {
        "prefix": "u",
        "body": [
            "\tlet ${TM_SELECTED_TEXT/([a-zA-Z]*) *([a-zA-Z]*)/${1:/downcase}$2/} = User(name: \"${TM_SELECTED_TEXT}\", email: \"${TM_SELECTED_TEXT/([a-zA-Z]*) *([a-zA-Z]*)/${1:/downcase}.${2:/downcase}/}@foobar.com\")\n",
        ],
        "description": "Create User with name and email"
    }


来源:https://stackoverflow.com/questions/52874954/when-creating-a-vscode-snippet-how-can-i-transform-a-variable-to-title-case-li

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!