Skip to content

Instantly share code, notes, and snippets.

@brettstimmerman
Created June 13, 2013 22:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brettstimmerman/5778013 to your computer and use it in GitHub Desktop.
Save brettstimmerman/5778013 to your computer and use it in GitHub Desktop.
A non-Python developer's attempt at a SublimeText 2 plugin.
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment