randombits
randombits

Reputation: 48460

Wrap a code block in HTML tags or other arbitrary code

I am not sure what the best way to word this question is. It is possibly why I am on StackOverflow because I cannot find a result on Google. Let me give it a try.

Assume I have the following HTML in my editor:

<li>One</li>
<li>Two</li>
<li>Three</li>

Is there a way to highlight all three of those lines, perhaps (on MacOS) using cmd+L and wrap them conveniently in <ul></ul> tags? Right now my process for doing this includes:

  1. writing out <ul></ul> above the HTML I want to wrap. Hit return for a line break between the two tags I want to embed content between.
  2. select the code block I want to embed between those tags using cmd+L
  3. on MacOS, hit option+Up Arrow Key to move it in between the tags.

This is kind of awkward. Is there a simpler keyboard shortcut to do this, not just for HTML but for any code? It would be great to be able to take code like this:

car.turnLeft()

and simply wrap it in a condition very quickly without following the 3 non-optimal steps above:

if (car.isHeadedWrongDirection()) {
    car.turnLeft()
}

The example above is forcefully contrived, but I think it makes the point for what I would like to accomplish in the editor.

Upvotes: 0

Views: 240

Answers (1)

Mark
Mark

Reputation: 181479

The general form for wrapping is to use $TM_SELECTED_TEXT within a snippet. Like

"if wrap": {
  "prefix": "*s",
  "body": [

      "if car.$1()) {",
      "\t${TM_SELECTED_TEXT}",
      "}"
  ],
  "description": "Wrap selection in if statement"
},

That snippet goes into one of your snippet files, see create a snippet.

Because the snippet trigger, here *s will negate your selection, you will need to trigger the snippet with a keybinding, in keybindings.json:

{
  "key": "alt+i",         // whatever keybinding you want
  "command": "editor.action.insertSnippet",
  "args": {

    "name": "if wrap"   // the name you gave your snippet
  },
  "when": "editorTextFocus"
},

Now select the text you want to wrap and trigger the keybinding alt+i.


There are other ways to avoid having to select the text first that you want to wrap or to not actually consume the text - if you wanted to add the if wrap below the text for example.

Upvotes: 1

Related Questions