AlreadyPro
AlreadyPro

Reputation: 3

Replace VS Code Snippet Variable

I want to replace ${TM_FILENAME_BASE} with ${TM_DIRECTORY} if ${TM_FILENAME_BASE} is init

I tried this snippet. It works for all files not named init, otherwise the output is -- Name: $TM_DIRECTORY

{
    "filename": {
        "prefix": "filename",
        "body": [
            "${LINE_COMMENT} Name: ${TM_FILENAME_BASE/^init$/$TM_DIRECTORY/}"
        ]
    },
}

Upvotes: 0

Views: 32

Answers (1)

Mark
Mark

Reputation: 182251

You can't use a snippet variable in a transform. So your use of $TM_DIRECTORY will not be resolved to its actual value. See Snippet Grammar.

If the file is NOT named init, there is no match in

${TM_FILENAME_BASE/^init$/$TM_DIRECTORY/}

and so there is no transform and so ${TM_FILENAME_BASE} is inserted un-transformed.


The closest you are going to get with a pure snippet would be something like:

"filename": {
  "prefix": "filename",
  "body": [
      // "${LINE_COMMENT} Name: ${TM_FILENAME_BASE/^init$/$TM_DIRECTORY/}"
      "${LINE_COMMENT} Name: ${1:$TM_FILENAME_BASE}${2:$TM_DIRECTORY}"
  ]
}

Both options, the filenameBase and the directory would appear. First, the filenameBase would be selected - if you don't want it hit delete and tab past the directory. If you do want the filenameBase only, tab and delete the now-selected directory.


You can do what you want to do with an extension but it is more complicated. Let me know if you want to see it.

Upvotes: 0

Related Questions