Harrison Cramer
Harrison Cramer

Reputation: 4496

How can you capitalize this word in VIM snippet?

EDIT — This is not possible with coc-snippets. It's possible with Ultisnips.

I've got the following vim snippet that I'm using (with coc-snippets) for React:

snippet STATE_HOOK "useState hook" b
const [${1:state}, set${1:`!v expand('%:t:r')`}] = useState($2)
endsnippet

This could be used to quickly create the following (incorrect) code:

const [color, setcolor] = useState("green");

The problem is that the setcolor needs to be camelcased, like this: setColor

How would one write this snippet so that the expanded input is capitalized?

Upvotes: 5

Views: 730

Answers (2)

Chcamiloam
Chcamiloam

Reputation: 594

I was testing some different things and you can use:

snippet STATE_HOOK "useState hook" b
const [$1, set${1/\w+/\u$0/g}] = useState("$2")
endsnippet 

How it works: Checking the documentation I found that you should overrite the text with the same text but capitalized, so \w+takes all the text (I think that '+' is unnecesary) and overrite it with \u$0 (is the same text but capitalized)

enter image description here

Upvotes: 4

romainl
romainl

Reputation: 196546

Strings like foo-bar or foo_bar are easy to turn into fooBar and fooBar is easy to turn into foo-bar or foo_bar because the two parts are easily identifiable, which gives you a structure to work with.

There is no such thing with usecolor. There is no separator and everything is of the same case so you can get quite a bunch of valid camel-cased names out of that string: usecOlor, uSeCoLor, etc.

You have three options:

  1. camel-case your filenames so that you don't have to perform any transformation,
  2. kebab-case or snake-case your filenames to make them easy to transform with a simple substitution,
  3. come up with extensive rules and find out how to transform random strings in a satisfactory and reproducible way.

I would go with number 1.

Upvotes: -1

Related Questions