Skip to content Skip to sidebar Skip to footer

Vs Code: How To Make A Python Snippet That After String Or Expression Hitting Tab Will Transform It

is it possible to make a python snippet that transforms code like i explain in my example? 'Hello world'.print - hit tab transforms it into print('Hello world') it will be nice if

Solution 1:

I don't think this is possible to match exactly what you need. What about something like:

"Print": {
    "prefix": ".print",
    "body": [
        "print(${TM_CURRENT_LINE/(.*)\\..+$/$1/})$0"
    ],
    "description": "Print"
}

If I write a.print and hit ENTER this will be the output:

aprint(a)

If I write "a".print this will be the output:

"a"print("a")

You should then remove the first part. This is based on what I know, doing some searches didn't result in a better solution so far.

This will have some problems if you use it on a line which consist of others statements because it'll take TM_CURRENT_LINE. See Variables.

Solution 2:

NEWER ANSWER:

Try the HyperSnips extension. It lets you use a regex as the snippet prefix so that you can capture exactly what you want preceding the .print.

See https://stackoverflow.com/a/62562886/836330 for more info on setting up the extension. then in your python.hsnips file create this snippet:

snippet `(("[^"]+")|(\b\w+))\.print`"expand to print()" A
print(``rv = m[2] ? m[2] : m[3]``)
endsnippet

The regex (("[^"]+")|(\b\w+))\.print matches both"Hello World".printand a.print with "" in capture group 2 and \b\w+ in capture group 3.

Then those capture groups m[2] and m[3] are inserted into the print() output depending on which capture group has content.

With the A flag, the input is automatically converted once the .print typing is completed.

hyperSnips demo



OLDER ANSWER:

Here is a macro that I think does what you want. Using the multi-command macro extension, put this into your settings.json:

"multiCommand.commands": [
    
    {
      "command": "multiCommand.printVariable",
      "interval": 150,

      "sequence": [
        "cursorHomeSelect",
        "editor.action.clipboardCutAction",
        {
          "command": "editor.action.insertSnippet",
          "args": {
            "snippet": "print($CLIPBOARD)"
          }
        }
      ]
    }
  ]

and a keybinding into keybindings.json to trigger the above macro:

{"key":"alt+p","command":"multiCommand.printVariable","when":"editorFocus"},

Now see the demo:

demo gif of macro print var

Put the cursor at the end of the variable (only thing on line) and trigger with your keybinding.

Post a Comment for "Vs Code: How To Make A Python Snippet That After String Or Expression Hitting Tab Will Transform It"