Home > Blockchain >  VSCode - custom snippet to create multiple different lines from selected C declaration
VSCode - custom snippet to create multiple different lines from selected C declaration

Time:09-25

I have a line:

int INTVAR;

I would like to highlight this line, and run a snippet which automatically creates the following set of three lines in place of the single line above.

int INTVAR;
int intvar() {return INTVAR;}
void intvar(int val){INTVAR = val;}

That is, a function that it a getter/setter for the variable should automatically be generated. The variable name will always be in full capital letters. The getter/setter name should be the same except that they will always be in lower case.

int could also be a double, char, etc.

ETA:

What I have tried/know so far: Instead of highlighting the line, the following appears more straightforward where I just type the declaration once and the getters/setters are automatically added.

"int var set get":{
    "prefix": "intsetget",
    "body":[
        "int ${1:VARNM};",
        "int ${1:/downcase}(){return ${1};}",
        "void ${1:/downcase}(int val){${1} = val;}"
    ]
}

This almost gets the job done, except that the downcase for setter and getter name does not work.

CodePudding user response:

The following snippet will also handle the different types:

  "var set get":{
    "prefix": "varsetget",
    "body":[
        "${1:int} ${2:VARNM};",
        "$1 ${2/(.*)/${1:/downcase}/}(){return $2;}",
        "void ${2/(.*)/${1:/downcase}/}($1 val){$2 = val;}"
    ]
  }

I think it can be done with selected text but you have to insert the snippet with a key binding, otherwise there is no selected text for the snippet to use. But It might be easier to copy the var name and use the full snippet.

Edit

Better is to use different variable name convention (ALL CAPS usually means a constant).

To support fMyVar, f_myVar, mMyVar and m_myVar member names you can use

  "var set get f m_":{
    "prefix": "varsetgetfm",
    "body":[
        "${1:int} ${2:VARNM};",
        "$1 ${2/^(?:f|m)_?([A-Za-z])(.*)|([A-Z].*)$/${1:/downcase}$2${3:/downcase}/}(){return $2;}",
        "void ${2/^(?:f|m)_?([A-Za-z])(.*)|([A-Z].*)$/${1:/downcase}$2${3:/downcase}/}($1 val){$2 = val;}"
    ]
  }
  • Related