0

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.

1
  • Using variable names with all capitals is bad practice, it is reserved for constants, better to use prefix f or m_, I have edited the snippet
    – rioV8
    Commented Sep 24, 2021 at 16:06

1 Answer 1

1

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;}"
    ]
  }
2
  • Works like a charm! Just want to point out that after typing the first VARNM in capitals, temporarily, all of the other references to this appear as capitals, but then, hitting tab once more changes it to downcase.
    – Tryer
    Commented Sep 24, 2021 at 15:06
  • 1
    @Tryer probably they perform the transformations when the snippet ends, as long as the end result is what we want.
    – rioV8
    Commented Sep 24, 2021 at 15:09

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.