2

I want to create a snippet on Visual Studio Code 1.33.1 that create a C++ class using the file's name.
First, I want to set up the "include guard", the point is to use the file's name, replace every '.' by a '_' and set it all to uppercase (norm):
#ifndef FILE_CLASS_HPP //filename: File.class.hpp

The VSC documentation provides some variable for the file's name, and some Regex to change to all uppercase and replace a character by another.
Point is: I never managed to do both since I know nothing about Regex.

I tried to manually join the Regex but it never worked:
#ifndef ${TM_FILENAME/(.*)/${1:/upcase}/[\\.-]/_/g}

expected result:
#ifndef FILE_CLASS_HPP
actual result:
#ifndef ${TM_FILENAME/(.*)//upcase/[\.-]/_/g}

tblaudez
  • 145
  • 2
  • 10
  • Visual Studio [does not appear to support uppercasing via regex](https://stackoverflow.com/questions/2743836/is-it-possible-to-replace-to-uppercase-in-visual-studio). – Tim Biegeleisen May 03 '19 at 10:04
  • @TimBiegeleisen The post you linked dates from 2012. You can see in the examples of the [VSC Documentation](https://code.visualstudio.com/docs/editor/userdefinedsnippets#_transform-examples) that uppercasing using Regex is possible. – tblaudez May 03 '19 at 10:08
  • This is tough to do purely with regex. Do the `#ifndef` names have a fixed number of dots in them, or could there be an arbitrary number of dots? – Tim Biegeleisen May 03 '19 at 10:15
  • @TimBiegeleisen Unfortunately, the number of dots is arbitrary. It seems that there is a Regex to replace all occurrences of a character by another thought: `[\\.-]/_/g`. I just don't know how to combine it with the all uppercase Regex. – tblaudez May 03 '19 at 10:25
  • Yes, but the thing is, the regex you have in mind only works if you already have the string isolated and in hand, which is _not_ the case here. For uppercasing, you have the same problem. – Tim Biegeleisen May 03 '19 at 10:27

1 Answers1

5

This should work:

"Filename upcase": {
  "prefix": "_uc",
  "body": [
    "#ifndef ${TM_FILENAME/([^\\.]*)(\\.)*/${1:/upcase}${2:+_}/g}"
  ],
  "description": "Filename uppercase and underscore"
},

([^\\.]*)(\\.)*  group1: all characters before a period
                 group2: the following period

replace with uppercase all the group1's: ${1:/upcase}

replace all the group2s ''s with _'s

The ${2:+_} is a conditional replacement, so you only add a _ at the end of group1 uppercase if there is a following group2.

The g global flag is necessary in this case to catch all the occurrences of group1group2's, not just the first.

Mark
  • 143,421
  • 24
  • 428
  • 436