atom / snippets

Atom snippets package
MIT License
205 stars 100 forks source link

Allow $SELECTION$ variable to create a snippet that surrounds code #200

Closed vjpr closed 5 years ago

vjpr commented 8 years ago

Similar to IntelliJ's Live Template Surround feature.

E.g. Template:

// ---
$SELECTION$
// ---

Select the following text and type keyboard shortcut...

test

Output

// ---
test
// ---
sygint commented 8 years ago

I like this one, but how could you have this feature and replace the text by typing?

dcbishop commented 7 years ago

Vim's UltiSnips plugin has this, it's quite handy.

In Vim you select the text, type (which removes the text, but Vim stores the last removed text in a register) then when you tab complete the snippet it pastes it in with the removed text. There's a VimCasts video.

Alternatively you could abuse undo to back off the changes to before the snippet was typed, then insert the snippet text on either side of the selection.

Or just have a popup snippet pallet menu that activates on a keypress.

mateusvahl commented 6 years ago

Hi all, I could not find a way of create a $SELECTION$, it seems that once snippets is loaded, a cache is created, so we cannot read from atom.clipboard.read();

The only approach right now is to create a template like:

'.source.js':
  'my-template':
    'prefix': 'tmplt'
    'body': '''
        // ---
          ${0}
        // ---
    '''

And paste your content manually

segevfiner commented 6 years ago

This will be $TM_SELECTED_TEXT in the TextMate snippet syntax which Atom uses. It's probably best to implement this using that name.

savetheclocktower commented 6 years ago

Since Atom snippets don't have a built-in way of being triggered by hotkey (instead of typing its name and hitting Tab), this isn't an intuitive feature. I'd like to solve that underlying limitation before adding features like this.

But it's pretty easy to write a command like this. Example:

// WRAP IN HTML TAG
atom.commands.add('atom-text-editor', {
  'custom:wrap-in-html-tag': () => {
    let snippet = atom.packages.activePackages.snippets.mainModule;
    let editor = atom.workspace.getActiveTextEditor();
    let selection = editor.getLastSelection();

    snippet.insert('<${1:div}>' + selection.getText() + '</${1:div}>');
  }
});

Put that into your init script, then map custom:wrap-in-html-tag to the keystroke of your choice in your keymap file.

If you have a bunch of snippets like this, of course, it's rather tedious to turn them all into commands, but perhaps this will satisfy some people as a workaround for now.

savetheclocktower commented 5 years ago

Several issues are open asking for variable support; I’m anointing #41 as the canonical feature request and closing the others as dupes.