atom / snippets

Atom snippets package
MIT License
205 stars 100 forks source link

Snippets with custom numbers #207

Closed azat-io closed 5 years ago

azat-io commented 8 years ago

How can I create a snippet which will transform something like this w100 to this width: 100px? It may be any number: w200, w48, etc.

"width": {
  "prefix": "w",
  "body": "width: ${1:${2:1}${3:px}}$0"
}
savetheclocktower commented 5 years ago

This isn’t really feasible for snippets because of how much more work it’d involve. Right now it only needs to compare the text before the cursor against a list of known prefixes. If the prefixes themselves could be dynamic, the snippets package would have to do far more work on each press of Tab, even presses that aren’t meant to invoke a snippet and end up inserting a literal tab character.

You could write a command that takes the content before the cursor and parses it in the way you want, inserting the result as a snippet. The only catch is that you’d probably want to assign it to a different key.

atom.commands.add('atom-text-editor', {
  'custom:width-hyper-snippet': (e) => {
    let snippet = atom.packages.activePackages.snippets.mainModule;
    let editor = atom.workspace.getActiveTextEditor();
    let word = editor.getWordUnderCursor();

    let matches = word.match(/^w(\d+)/)
    if (!matches) {
      e.abortKeyBinding();
      return;
    }

    let width = matches[1];

    snippet.insert("width: ${1:${2:" + width + "}px}")
  }
});