Created
June 13, 2013 22:38
-
-
Save brettstimmerman/5778013 to your computer and use it in GitHub Desktop.
A non-Python developer's attempt at a SublimeText 2 plugin.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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