简体   繁体   中英

Add cursor position to Snippet in Sublime Text 3

This is my code for adding snippet in Sublime Text 3:

<snippet>
    <content><![CDATA[
document.write();
]]></content>
    <tabTrigger> dw </tabTrigger>
</snippet>

the question is how add a cursor position in this code? thanks.

Snippets in Sublime allow you to optionally specify fields (tab stops) that allow you to interactively fill in the snippet with extra information.

When the snippet expands you're able to Tab and Shift+Tab back and forth between the fields, and when you press Tab while in the last field, the snippet expansion is completed.

The status of this is indicated in the status bar in the current window, where you will see Sublime telling you what field you're in and how many there are, eg Field 1 of 2 .

Fields are specified with a $ followed by a number, with Sublime following through the fields in their numeric order ( $1 , then $2 , etc). For this reason it's important that you enter any literal $ in your snippet content as \\$ instead so that Sublime knows it's not a field.

With that said, the field $0 is special and indicates where the cursor should finally end up when snippet expansion is complete. If $0 does not appear anywhere within the snippet, Sublime acts as if it's the last thing in the snippet content.

That's what it's doing in your snippet example above, so when the snippet expands it leaves the cursor at the end of the snippet, just after the ; character.

A snippet such as the following will instead leave the cursor inside of the paranthesis so that you can enter what you want to insert into the document:

<snippet>
    <content><![CDATA[
document.write($0);
]]></content>
    <tabTrigger> dw </tabTrigger>
</snippet>

When specified like this, the snippet has no "real" fields (just the special "exit" field), so as soon as it expands, the cursor is inside of the parenthesis and snippet expansion is complete.

Depending on your use case, you can also achieve something similar with a snippet like this:

<snippet>
    <content><![CDATA[
document.write($1);$0
]]></content>
    <tabTrigger> dw </tabTrigger>
</snippet>

When you expand this snippet, the cursor is placed inside of the parenthesis as before, but now the status line will tell you Field 1 of 2 because there are two fields now (your explicit one and the "exit" at $0 ).

This allows you to type to fill out the value of the call to document.write and then press Tab to jump directly to the end of the line.

For more information on snippets, I recommend the Unofficial Documentation on Snippets .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM