sublimetext3sublimetextsublime-text-pluginsublimetext4

How to paste some text in Sublime?


I need to paste console.log() very often. I want to create a hotkey for this. And the cursor should be between brackets (usual pasting doesn't work so).
How to do this? It doesn't look like this can be configured in the settings. Maybe some plugin. I'd rather create a little script for this.


Solution

  • No plugins are needed; you just need to create a new snippet. Select Tools → Developer → New Snippet… and the following will appear:

    <snippet>
        <content><![CDATA[
    Hello, ${1:this} is a ${2:snippet}.
    ]]></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>
    

    First, replace the contents of the CDATA designator in the <content> tag with console.log($0). The $0 is a field designator. Snippets also support a number of built-in variables.

    Next, set a trigger sequence - something that when you type it and hit Tab, the snippet will be triggered. clog should work.

    Next, you can set a scope selector to refine the context in which the snippet can be triggered. If nothing is in this field, the snippet will be available everywhere. Assuming you're programming in JavaScript, use source.js here.

    Finally, we'll add a <description> field that will show up in the autocomplete popup. Otherwise, it'll just show clog as the description. Here, we'll use console.log().

    Here's what the final snippet will look like:

    <snippet>
        <content><![CDATA[
    console.log($0)
    ]]></content>
        <tabTrigger>clog</tabTrigger>
        <scope>source.js</scope>
        <description>console.log()</description>
    </snippet>
    

    Hit Save and the save dialog will come up in your Packages/User folder*. Save the snippet here (otherwise it may not work) as clog.sublime-snippet. Once saved, it is immediately activated. You can test it by switching to a JS file and typing clog and hitting Tab. console.log() should be entered at that position, with the cursor between the parentheses.


    * The exact path of the Packages directory depends on your operating system and whether or not you've upgraded your installation to Sublime Text 4 (Build 4000 and greater).