Skip to content

Instantly share code, notes, and snippets.

@brettstimmerman
Created June 13, 2013 22:38
Show Gist options
  • Select an option

  • Save brettstimmerman/5778013 to your computer and use it in GitHub Desktop.

Select an option

Save brettstimmerman/5778013 to your computer and use it in GitHub Desktop.

Revisions

  1. brettstimmerman created this gist Jun 13, 2013.
    51 changes: 51 additions & 0 deletions multilinejs.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,51 @@
    import sublime
    import sublime_plugin
    import re

    '''
    SublimeText 2 plugin to convert selections (or the entire document) to a
    JavaScript multiline string using the [].join('\n') idiom.
    Given a document like:
    line one
    line two
    It will create:
    var FIXME = [
    'line one',
    'line two'
    ].join('\n');
    Keybind this by adding something like the following to
    `Packages/User/Default (<platform>).sublime-keymap`
    { "keys": ["ctrl+shift+c"], "command": "multiline_js" }
    '''

    class MultilineJsCommand(sublime_plugin.TextCommand):
    def run(self, edit, **args):
    if self.view.sel()[0].empty():
    # no selections, so create a selection of the entire document
    self.view.sel().add(sublime.Region(0, self.view.size()))

    # wrap a string in single quotes
    def quote(str):
    return re.sub(r"(\s*)(.+)(\s*)", r" \1'\2'\3", str)

    for sel in self.view.sel():
    str = self.view.substr(sel)

    # capture leading spaces for use later when injecting the new text
    m = re.match(r"\s*", str)
    if m:
    lead = m.group()
    else:
    lead = ''

    fixed = '\n' + ',\n'.join(map(quote, str.splitlines())) + '\n'

    js = lead + 'var FIXME = [' + fixed + lead + '].join(\'\\n\');'

    self.view.replace(edit, sel, js)