Tyler Collier
Tyler Collier

Reputation: 11990

How can I wrap an arbitrary piece of text in an indented block in Sublime Text 3 using a keybinding?

Let's say I have:

doSomeAction()

and I want to wrap it in some arbitrary text, such that the original text is indented:

if myValue
  doSomeAction()
end

Ideally I'd like to highlight my line, press some keybinding, and have the original text indented, and my cursor on what becomes the first line, where I'd type the if myValue (or whatever).

I realize this depends on the programming language I'm in, mostly regarding what comes after the original line. In Ruby, I need end, in Javascript, I need }, and in Coffeescript, I need nothing :-) I figure if it's left blank, such that I can press tab to get to that spot, I can type what's needed myself.

Upvotes: 1

Views: 158

Answers (1)

sergioFC
sergioFC

Reputation: 6016

You can create a snippet for that purpose. Example:

<snippet>
<content><![CDATA[
${1:if condition}
    $SELECTION${3}
${2:end}
${4}
]]></content>
</snippet>

Imporant note: Stackoverflows shows this text with spaces but remember to use tabs for indentations in snippets: see Tyler edit and comments at the bottom of this answer.

As you can see it can have multipe parts starting with $ delimiting positions, you can navigate all parts using tab, this allows you easily change the content of the condition or to add extra content inside. You can easily change the structure, add or remove parts, content, change default values, etc.


RESULT:

Sublime wrap snippet


¿How to create the snippet?

Use menu Tools > new Snippet, then put the given file content in the new file. Save it inside sublime Packages/User with the (example) filename wrap.sublime-snippet. Usually Packages/User is the default folder showed, and usually Packages folder is opened via menu Preferences>Browse Packages.

¿How to add the key-binding?

Go to menu Preferences > Key Bindings-user and add your keybinding inside the global array, use a free key combination you like and save the file. If you dont have any other user key-bindings this file content should be something like this (remember to use the name you give to the snippet):

[
    { "keys": ["ctrl+alt+z"], "command": "insert_snippet", "args": {"name": "Packages/User/wrap.sublime-snippet"}}   
]

EDIT: Always use a tab for indentation in snippets as recommended by Sublime Text help:

When writing a snippet that contains indentation, always use tabs. The tabs will be transformed into spaces when the snippet is inserted if the option translateTabsToSpaces is set to true.

Upvotes: 4

Related Questions