Sublime Forum

Customised code for wrapping selection

#1

Hi, I’m new to programming so I hope you can give me an easy to understand answer. So, here’s what I want to do: I want to select a piece of code, press a key combination (say, ctrl+shift+c) and I want the selection to be wrapped with <span class=code> and </span>. I know that you can wrap the selection with generic tags with ctrl+shift+w but I was wondering if I could create a custom key binding to do what I want to do without having to type “span class=code”. Thank you.

Edit: Sorry, I meant alt+shift+w, not ctrl+shift+w

0 Likes

#2

This is a job for snippets and the insert_snippet command in particular. The key binding that you’re talking about is this one (ctrl+shif+w closes the current window, unless you happen to have remapped it):

{ "keys": ["alt+shift+w"], "command": "insert_snippet", "args": { "name": "Packages/XML/Snippets/long-tag.sublime-snippet" } },

The short version of the answer to your question is that you can use the same command and use the contents argument rather than the name argument to inline the snippet content that you want. Thus your key would look something like this:

{
    "keys": ["ctrl+shift+c"],
    "command": "insert_snippet",
    "args": {
        "contents": "<span class=\"code\">${0:$SELECTION}</span>"
    },
},

If you want the key to only work inside of HTML files, add this to the binding after the args (make sure that there is a comma after the args as above):

    "context": [
        { "key": "selector", "operator": "equal", "operand": "text.html" },
    ]

For a longer version of the answer that explains how all of this works and what it’s doing, see this SO question as well as the unofficial documentation on snippets.

1 Like

#3

@OdatNurd, Can you please let me know create how to create an insert_snipppet please ? I am not sure how to implement it , because when I click on the Tools->Developer->New Snippet the file template that is presented to me , does not look a bit similar to what you have here.

Can you please let me know ? (still better - create a video :slight_smile: )

Thank you in advance

With Regards
Gagan

0 Likes

#4

@OdatNurd Thanks… I had not seen your SO answer, and it works for me now.

Thanks
Gagan

0 Likes