Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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".

like image 332
Omair Vaiyani Avatar asked Oct 18 '18 13:10

Omair Vaiyani


1 Answers

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.

pascalCase snippet demo

See also snippet transform to CamelCase

like image 120
Mark Avatar answered Nov 16 '22 01:11

Mark