Search code examples
sublimetext

Is there a way to create a keybind that writes text in Sublime Text?


I want to make it so that if I press ctrl+alt+t, Sublime Text will write a template like this for my comments:

# -----  -----

I know ctrl+/ makes/toggles comments, but I mean a keybind that will add this exact template.

An example

1

Another example

2

Thanks in advance.


Solution

  • You can do this with two features of Sublime: Snippets and Key Bindings. Use the Tools > Developer > New Snippet… command to create a snippet. Enter your template text in the snippet, like so:

    <snippet>
        <content><![CDATA[
    # ----- ${1:NAME} -----
    ]]></content>
        <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
        <!-- <tabTrigger>hello</tabTrigger> -->
        <!-- Optional: Set a scope to limit where the snippet will trigger -->
        <scope>source.python</scope>
    </snippet>
    

    Save the snippet in your User package. Then, create a key binding to trigger the snippet:

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

    Note that, using this approach, you will need multiple snippets depending on the scope. (E.g. JS files need slash comments.) One solution here is to set a scope (with "selector") on the key bindings.

    For more details and variations (file snippets vs inline, for example), see this discussion on the Sublime Forum.