Aleksandrs
Aleksandrs

Reputation: 1509

Visual studio code user snippets capitalize not working properly

I wrote such code

"State": {
    "prefix": "state",
    "body": [
        "const [$1, set${1:/capitalize}] = useState($2);"
    ],
    "description": "Adds state"
},

I expect that the result will be (if I enter test in $1) like this:

const [test, setTest] = useState($2);

But I get such result:

const [/capitalize, set/capitalize] = useState();

In official docs I found such rule: '${' int ':' '/upcase' | '/downcase' | '/capitalize' '}'.

Could you please tell what I am doing wrong?

Upvotes: 0

Views: 800

Answers (2)

Mark
Mark

Reputation: 180705

Lets look at why your version ${1:/capitalize} doesn't work:

Here is a portion of the snippet grammar you cited from https://code.visualstudio.com/docs/editor/userdefinedsnippets

tabstop     ::= '$' int
                | '${' int '}'
                | '${' int  transform '}'

 -snip-

transform   ::= '/' regex '/' (format | text)+ '/' options

format      ::= '$' int | '${' int '}'
                | '${' int ':' '/upcase' | '/downcase' | '/capitalize' '}'

So initially it looks like ${1:/capitalize} is correct, just looking at the last line of the grammar above it seems

${' int ':' '/capitalize'

is a valid option. But you have to track through the grammar to use it properly. The format syntax can only be used in a transform. We see this in:

transform ::= '/' regex '/' (format | text)+ '/' options

So right there your version does not include a transform. You do not have the necessary regex preceder. So those '/upcase' | '/downcase' | '/capitalize' options can only be used as part of a transform with a regex (although you can have an empty regex but that doesn't help you and you still need to have the regex entry point anyhow).

Here is the general form of a transform:

${someInt/regex captures here/do something with the captures here, like ${1:/capitalize} /}

Note that the first $someInt is a tabstop - it could be $1 for example, but the second $1 (with the capitalize) is NOT a tabstop but a reference to the first capture group from the preceding regex. So a transform can only transform something that has been captured by a regex.

The grammar requires that the format option be part of a transform, and a transform requires a regex and $n's in the format part refer to capture groups and not tabstop variables.

I hope this all makes sense.

Upvotes: 3

stud3nt
stud3nt

Reputation: 2143

You can use below snippet for the requested output:

const [$1, set${1/(.*)/${1:/capitalize}/}] = useState($2);

Output will be (in case I enter $1 as test):

const [test, setTest] = useState();

Upvotes: 2

Related Questions