I am trying to create a snippet that surrounds the selected text with try..except
block. This is what I have in keybindings.json file:
{
"key": "ctrl+p'",
"command": "editor.action.insertSnippet",
"when": "editorHasSelection",
"args": {
"snippet": "try:rnt${TM_SELECTED_TEXT}rnexcept BaseException as ex:"
}
}
This works for most part except that if I select the entire line of indented code, it inserts try at the beginning of the line. I want it to behave like Command+/
which adds #
right before where the text starts.
How do I make my snippet behave like that?
2
Answers
You have to insert a possible whitespace in front of each line and remove the whitespace on the middle line:
Dang, it took a while but here is something pretty simple that I think works.
First, make this snippet (in some snippets file):
and then this keybinding (in your
keybindings.json
):That middle line of the snippet:
"${TM_SELECTED_TEXT/^(.*?)$(\r?\n)?/t$1$2/gm}"
will actually run once for each line of your selection, because the match is from
^
to the end of the same line and because of the globalg
flag. So it’ll keep running as long as it finds matches in your entire selection.@rioV8’s snippet works for me (for single lines only it seems) but it could be simplified a bit. I upvoted it.
Note that 3 parts of the snippet are identical:
${TM_SELECTED_TEXT/^([ \t]*).*$/$1/}
So to simplify that resulting value (the whitespace before the selected text) can be stored in a value and reused. See this:
Now you can just use
$1
in any other place you want that same value.See there are two
$1
‘s not part of a transform, liketry:rn$1t
: that$1
will be your computed whitespace from${1:${TM_SELECTED_TEXT/^([ \t]*).*$/$1/}}
Also, this part:
${TM_SELECTED_TEXT/^[ \t]*(.*)$/$1/}
can be simplified towhich matches the leading white space before the text and replaces that white space with nothing.
Result:
This is just a little cleaner and less prone to typos. You just have to do one tab or escape at the end to finish.