Home > other >  Modify the first letter of an argument in a user snippet in VSCode
Modify the first letter of an argument in a user snippet in VSCode

Time:09-24

I am using the prefix prop to generate:

private $1 $2;
public void set$2($1 $2) {
    this.$2 = $2;
}
public $1 get$2() {
    return $2;
}

This is my snippet:

"Add a property" : {
    "prefix": "prop",
    "body": [
        "private $1 $2;",
        "public $1 get$2() {",
        "\treturn $2;",
        "}",
        "public void set$2($1 $2) {",
        "\tthis.$2 = $2;",
        "}"
    ],
    "description": "Add a property to class"
}

Output:

private int age;
public int getage() {
    return age;
}
public void setage(int age) {
    this.age = age;
}

Expected output:

private int age;
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}

What do I change in my snippet to achieve this output?

CodePudding user response:

I'm not on my normal computer, but try this:

"Add a property" : {
"prefix": "prop",
"body": [
    "private $1 $2;",
    "public $1 get${2:/capitalize/g}() {",
    "\treturn $2;",
    "}",
    "public void set${2:/capitalize/g}($1 $2) {",
    "\tthis.$2 = $2;",
    "}"
    ],
    "description": "Add a property to class"
}

CodePudding user response:

Try this:

"Add a property" : {
  "prefix": "prop",
  "body": [
    "private $1 $2;",
    "public $1 get${2/(.)/${1:/capitalize}/}() {",
    "\treturn $2;",
    "}",
    "public void set${2/(.)/${1:/capitalize}/}($1 $2) {",
    "\tthis.$2 = $2;",
    "}"
  ],
  "description": "Add a property to class"
}

This part ${2/(.)/${1:/capitalize}/} will transform the 2nd tabstop. It captures only the first character (.) of that word (age in your case) in capture group 1 and then ${1:/capitalize} will capitalize whatever is in capture group 1.

Have a look at snippet variable transforms.

  • Related