Last active
December 3, 2024 10:40
-
-
Save RobTrew/354163dea706a3090eae to your computer and use it in GitHub Desktop.
Use js-beautify to reformat code in OS X 10.10 (Yosemite) Script Editor
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
// Ver 0.2 | |
// Restores syntax highlighting by recompiling | |
// either restoring cursor or placing it at first error found | |
// Assumes installation of node.js | |
// http://nodejs.org/download/ | |
// with npm at: | |
var pathNPM = '/usr/local/bin'; | |
// and js-beautify | |
// https://www.npmjs.com/package/js-beautify | |
// $ npm -g install js-beautify | |
function run() { | |
"use strict"; | |
var appSE = new Application("Script Editor"), | |
lstDoc = appSE.documents(), | |
oDoc = lstDoc.length ? lstDoc[0] : null; | |
if (!oDoc) return false; | |
var drafts = { // | |
getSelectedLineRange: function () { | |
// works, but let me know if you see a shorter route :-) | |
var rgxLFCR = /[\r\n]/, | |
dct, strFull, iFrom, iTo, lngLast, | |
varNoSeln = null; | |
if (oDoc) { | |
dct = oDoc.selection.characterRange(); | |
strFull = oDoc.text(); | |
if ((typeof strFull)[0] !== 's') return varNoSeln; | |
lngLast = strFull.length - 1; | |
iFrom = dct.x; | |
iTo = dct.y - 1; | |
if (iFrom < 0 || iTo < 0) return varNoSeln; | |
if ((iFrom < lngLast) || (iTo < lngLast)) { | |
while (iFrom--) { | |
if (strFull[iFrom].match(rgxLFCR)) break; | |
} | |
iFrom += 1; | |
while (iTo++ < lngLast) | |
if (strFull[iTo].match(rgxLFCR)) break; | |
return [iFrom, (iTo - iFrom)]; | |
} else return varNoSeln; | |
} | |
}, | |
setSelectedRange: function (iStart, iLength) { | |
if (oDoc) { | |
oDoc.selection = oDoc.text.characters.slice(iStart, iStart + iLength); | |
} | |
} | |
}; | |
var app = Application.currentApplication(), | |
lstSeln = drafts.getSelectedLineRange(); | |
app.includeStandardAdditions = true; | |
app.setTheClipboardTo( | |
oDoc.text().replace(/\r/g, '\n') | |
); | |
oDoc.text = app.doShellScript( | |
'export PATH=$PATH:' + pathNPM + | |
'; pbpaste | js-beautify -f - -t -j --good-stuff -p -n -w 80' | |
); | |
// Either restore selection or select first syntax error | |
if (appSE.compile(oDoc)) { | |
if (lstSeln) | |
drafts.setSelectedRange(lstSeln[0], lstSeln[1]); | |
} else appSE.checkSyntax(oDoc); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment