Skip to content

Commit

Permalink
Allow separation of settings for html, css, js
Browse files Browse the repository at this point in the history
  • Loading branch information
HookyQR committed Dec 26, 2015
1 parent 92f7047 commit 9f29a30
Show file tree
Hide file tree
Showing 4 changed files with 292 additions and 245 deletions.
23 changes: 21 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,26 @@ This package includes hints when editing your `.jsbeautifyrc`. Only the first fi
"fileMatch": ["**/.jsbeautifyrc"],
"url": "http://json.schemastore.org/jsbeautifyrc"
}
]
```
]```


Also runs http and css beautify from the same package, as determined by the file extension. The schema indicates which beautifier each of the settings pertains to.


The `.jsbeautifyrc` config parser accepts sub elements of `html`, `js` and `css` so that different settings can be used for each of the beautifiers (like sublime allows). Note that this will cause the config file to be incorrectly structure for running `js-beautify` from the command line.

Settings are inherited from the base of the file. Thus:

```json
{
"indent_size": 4,
"indent_char": " ",
"css": {
"indent_size": 2
}
}```
Will result in the `indent_size` being set to 4 for Javascript and HTML, but set to 2 for css. All will get the same `intent_char` setting.

If the file is unsaved, or the type is undetermined, you'll be prompted for which beautifier to use.

Extra (permanent) file extension may be added under user or workspace settings.
Expand All @@ -25,6 +40,10 @@ Extra (permanent) file extension may be added under user or workspace settings.
Embedded version of js-beautify is v1.5.10.

## Changes:
### 0.0.6: 27 Dec 2015
* Added allowing sub elements in config. Fixes [Issue #3: Allow separation of settings for html, css and js options like sublime.](https://github.com/HookyQR/VSCodeBeautify/issues/3)


### 0.0.5: 24 Dec 2015
* Schema published at http://json.schemastore.org/jsbeautifyrc.
* Added README details for schema install for users of VSCode < v0.10.5
Expand Down
188 changes: 96 additions & 92 deletions extension.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,87 +13,82 @@ function findRecursive(dir, fileName) {
}
return result;
}

var dropWithRegEx = function(text, re) {
if (!re.global) //I'm not doing that for ever
return text;
var oText = "";
var match = re.exec(text);
var lastEnd = 0;
while (match) {
if (lastEnd < match.index)
oText += text.slice(lastEnd, match.index);
lastEnd = match.index + match[0].length;
match = re.exec(text);
}
if (lastEnd < text.length) oText += text.slice(lastEnd, text.length);
return oText;
};
var dropMultiLineComments = inText => dropWithRegEx(inText, /\/\*.*\*\//g);
var dropSingleLineComments = inText => dropWithRegEx(inText, /\/\/.*(?:[\r\n]|$)/g);
var dropComments = inText => dropSingleLineComments(dropMultiLineComments(inText));
var dropComments = inText => inText.replace(/(\/\*.*\*\/)|\/\/.*(?:[\r\n]|$)/g, "");

//register on activation
function activate(context) {
var doBeautify = function(active, doc, opts) {
var original = doc.getText();
var type = doc.isUntitled ? "" : doc.fileName.split('.')
.pop()
.toLowerCase();
var cfg = vscode.workspace.getConfiguration('beautify');
//if a type is set on the window, use that
//check if the file is in the users json schema set
var jsSchema = vscode.workspace.getConfiguration('json')
.schemas;
//get the whole file:
var range = new vscode.Range(new vscode.Position(0, 0), doc.positionAt(Infinity));
var result;
if (jsSchema) {
var matcher = [];
var extMatch = n => ({
pattern: n.startsWith("**/") ? n : ("**/" + n)
});
jsSchema.forEach(schema => {
if (typeof schema.fileMatch === 'string') {
matcher.push(extMatch(schema.fileMatch));
} else {
var t = schema.fileMatch.map(extMatch);
matcher = matcher.concat(t);
}
});
if (vscode.languages.match(matcher, doc)) {
//beautify as javascript
result = beautify.js(original, opts);
//get the whole file:
range = new vscode.Range(new vscode.Position(0, 0), doc.positionAt(Infinity));
//and make the change:
active.edit(editor => editor.replace(range, result));
return;
var mergeOpts = function(opts, type) {
var finOpts = {};
for (let a in opts) {
if (a !== 'js' && a !== 'html' && a !== 'css') {
finOpts[a] = opts[a];
}
}
if (cfg.HTMLfiles.indexOf(type) + 1) result = beautify.html(original, opts);
else if (cfg.CSSfiles.indexOf(type) + 1) result = beautify.css(original, opts);
else if (cfg.JSfiles.indexOf(type) + 1) result = beautify.js(original, opts);
else {
//Ask what they want to do:
vscode.window.showQuickPick([{
label: "JS",
description: "Does JavaScript and JSON"
}, {
label: "CSS"
}, {
label: "HTML"
}], {
matchOnDescription: true,
placeHolder: "Couldn't determine type to beautify, pleae choose."
})
.then(function(choice) {
if (!choice || !choice.label) return;
result = beautify[choice.label.toLowerCase()](original, opts);
active.edit(editor => editor.replace(range, result));
});
return;
//merge in the per type settings
if (type in opts) {
for (let b in opts[type]) {
if (b === 'allowed_file_extensions') continue;
finOpts[b] = opts[type][b];
}
}
return finOpts;
};
var getBeautifyType = function(doc) {
return Promise.resolve()
.then(() => {
var type = doc.isUntitled ? "" : doc.fileName.split('.')
.pop()
.toLowerCase();
var cfg = vscode.workspace.getConfiguration('beautify');
//if a type is set on the window, use that
//check if the file is in the users json schema set
var jsSchema = vscode.workspace.getConfiguration('json')
.schemas;
if (jsSchema) {
var matcher = [];
var extMatch = n => ({
pattern: n.startsWith("**/") ? n : ("**/" + n)
});
jsSchema.forEach(schema => {
if (typeof schema.fileMatch === 'string') {
matcher.push(extMatch(schema.fileMatch));
} else {
var t = schema.fileMatch.map(extMatch);
matcher = matcher.concat(t);
}
});
if (vscode.languages.match(matcher, doc)) {
return "js";
}
}
if (cfg.HTMLfiles.indexOf(type) + 1) return "html";
else if (cfg.CSSfiles.indexOf(type) + 1) return "css";
else if (cfg.JSfiles.indexOf(type) + 1) return "js";
else {
//Ask what they want to do:
return vscode.window.showQuickPick([{
label: "JS",
description: "Does JavaScript and JSON"
}, {
label: "CSS"
}, {
label: "HTML"
}], {
matchOnDescription: true,
placeHolder: "Couldn't determine type to beautify, pleae choose."
})
.then(function(choice) {
if (!choice || !choice.label) return;
return choice.label.toLowerCase();
});
}
});
};
var doBeautify = function(active, doc, type, opts) {
var original = doc.getText();
//get the whole file:
var range = new vscode.Range(new vscode.Position(0, 0), doc.positionAt(Infinity));
var result = beautify[type](original, opts);
//and make the change:
active.edit(editor => editor.replace(range, result));
};
Expand All @@ -108,24 +103,33 @@ function activate(context) {
var base = vscode.workspace.rootPath;

if (!doc.isUntitled) base = doc.fileName;
var beautFile;
if (base) beautFile = findRecursive(base, ".jsbeautifyrc");

//walk to find a .jsbeautifyrc
if (beautFile) fs.readFile(beautFile, function(ee, d) {
if (!d) d = "{}";
var opts = {};
try {
var unCommented = dropComments(d.toString());
opts = JSON.parse(unCommented);
} catch (e) {
//put a warning in here
vscode.window.showWarningMessage("Found a .jsbeautifyrc file, but it didn't parse correctly.");
opts = {}; //just use the default opts
}
doBeautify(active, doc, opts);
});
else doBeautify(active, doc, {});
//get the type of beautify to be done
getBeautifyType(doc)
.then(type => {
if (!type) return; //user skipped the selection
var beautFile;
if (base) beautFile = findRecursive(base, ".jsbeautifyrc");
//walk to find a .jsbeautifyrc
if (beautFile) fs.readFile(beautFile, function(ee, d) {
if (!d) d = "{}";
var opts = {};
try {
var unCommented = dropComments(d.toString());
console.log(unCommented);
opts = JSON.parse(unCommented);
opts = mergeOpts(opts, type);
console.log(opts);
} catch (e) {
console.log(e.message);
//put a warning in here
vscode.window.showWarningMessage("Found a .jsbeautifyrc file, but it didn't parse correctly.");
opts = {}; //just use the default opts
}
doBeautify(active, doc, type, opts);
});
else doBeautify(active, doc, type, {});
});
});
context.subscriptions.push(disposable);
}
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "beautify",
"displayName": "beautify",
"description": "Beautify code in place for VS Code",
"version": "0.0.5",
"version": "0.0.6",
"publisher": "HookyQR",
"engines": {
"vscode": "^0.10.1"
Expand Down
Loading

0 comments on commit 9f29a30

Please sign in to comment.