v1.5.0
AtheraStudio Code
- (function () {
- "use strict";
-
- var A = window.Athera;
- var t = A.t;
-
- var COMMENT_NODE = /Comment(Block)?$/;
- var BRACKET_SKIP = /String|Comment|RegExp|Heredoc|Nowdoc|Text|Escape|Char|Url|Raw|Doctype|ParenthesizedContent/;
- var OPENERS = { "(": ")", "[": "]", "{": "}" };
- var CLOSERS = { ")": "(", "]": "[", "}": "{" };
- var MAX_BRACKET_SCAN = 400000;
- var MAX_DIAGNOSTICS = 20;
-
- function view() {
- return A.editor.view;
- }
-
- function parsed(state, timeout) {
- return CM.ensureSyntaxTree(state, state.doc.length, timeout || 4000);
- }
-
- function diffChange(from, oldText, newText) {
- var start = 0, endA = oldText.length, endB = newText.length;
- while (start < endA && start < endB && oldText.charCodeAt(start) === newText.charCodeAt(start)) start++;
- while (endA > start && endB > start && oldText.charCodeAt(endA - 1) === newText.charCodeAt(endB - 1)) { endA--; endB--; }
- return { from: from + start, to: from + endA, insert: newText.slice(start, endB) };
- }
-
- function scope(state) {
- var sel = state.selection.main;
- if (sel.empty) return { from: 0, to: state.doc.length };
- var a = state.doc.lineAt(sel.from), b = state.doc.lineAt(sel.to);
- var to = sel.to === b.from && b.number > a.number ? state.doc.lineAt(sel.to - 1).to : b.to;
- return { from: a.from, to: to };
- }
-
- function rewriteLines(transform) {
- var v = view(), state = v.state, r = scope(state);
- var oldText = state.sliceDoc(r.from, r.to);
- var newText = transform(oldText);
- if (newText === oldText) {
- A.ui.toast(t("tools.nothing_changed"), "info");
- return false;
- }
- v.dispatch({ changes: diffChange(r.from, oldText, newText), userEvent: "input.tools", scrollIntoView: true });
- v.focus();
- return true;
- }
-
- function rewriteSelection(transform) {
- var v = view(), state = v.state, changes = [];
- state.selection.ranges.forEach(function (range) {
- var from = range.from, to = range.to;
- if (range.empty) {
- var word = state.wordAt(range.head);
- if (!word) return;
- from = word.from;
- to = word.to;
- }
- var oldText = state.sliceDoc(from, to), newText = transform(oldText);
- if (newText !== oldText) changes.push(diffChange(from, oldText, newText));
- });
- if (!changes.length) {
- A.ui.toast(t("tools.nothing_changed"), "info");
- return false;
- }
- v.dispatch({ changes: changes, userEvent: "input.tools", scrollIntoView: true });
- v.focus();
- return true;
- }
-
- function splitLines(text) {
- var lines = text.split("\n"), trailing = lines.length > 1 && lines[lines.length - 1] === "";
- if (trailing) lines.pop();
- return { lines: lines, trailing: trailing };
- }
-
- function joinLines(parts) {
- return parts.lines.join("\n") + (parts.trailing ? "\n" : "");
- }
-
- function collectComments(state, from, to) {
- var tree = parsed(state);
- if (!tree) return null;
- var found = [];
- tree.iterate({
- from: from,
- to: to,
- enter: function (node) {
- if (!COMMENT_NODE.test(node.name)) return;
- if (node.from >= from && node.to <= to) found.push({ from: node.from, to: node.to });
- return false;
- }
- });
- found.sort(function (a, b) { return a.from - b.from; });
- var merged = [];
- found.forEach(function (c) {
- var last = merged[merged.length - 1];
- if (last && c.from <= last.to) last.to = Math.max(last.to, c.to);
- else merged.push({ from: c.from, to: c.to });
- });
- return merged;
- }
-
- function groupText(doc, group) {
- var offset = group.first.from, raw = doc.sliceString(offset, group.last.to), out = "", pos = 0;
- group.comments.forEach(function (c) {
- out += raw.slice(pos, c.from - offset);
- pos = c.to - offset;
- var rest = raw.slice(pos);
- if (/(^|[ \t\n(\[{])$/.test(out) && /^[ \t]/.test(rest)) pos += /^[ \t]*/.exec(rest)[0].length;
- else if (/[ \t]$/.test(out) && /^[)\]},;]/.test(rest)) out = out.replace(/[ \t]+$/, "");
- else if (/\w$/.test(out) && /^\w/.test(rest)) out += " ";
- });
- return out + raw.slice(pos);
- }
-
- function removeComments() {
- var v = view(), state = v.state, doc = state.doc;
- var ranges = state.selection.ranges.filter(function (r) { return !r.empty; });
- if (!ranges.length) ranges = [{ from: 0, to: doc.length }];
- var all = [];
- for (var i = 0; i < ranges.length; i++) {
- var list = collectComments(state, ranges[i].from, ranges[i].to);
- if (!list) {
- A.ui.toast(t("tools.parse_failed"), "warning");
- return 0;
- }
- all = all.concat(list);
- }
- all.sort(function (a, b) { return a.from - b.from; });
- if (!all.length) {
- A.ui.toast(t("tools.no_comments"), "info");
- return 0;
- }
- var groups = [];
- all.forEach(function (c) {
- var first = doc.lineAt(c.from), last = doc.lineAt(c.to);
- var g = groups[groups.length - 1];
- if (g && first.number <= g.last.number) {
- g.comments.push(c);
- if (last.number > g.last.number) g.last = last;
- } else {
- groups.push({ first: first, last: last, comments: [c] });
- }
- });
- var changes = groups.map(function (g) {
- var lines = groupText(doc, g).split("\n").map(function (line) { return line.replace(/[ \t]+$/, ""); }).filter(function (line) { return line !== ""; });
- var insert = lines.join("\n"), from = g.first.from, to = g.last.to;
- if (!insert) {
- if (to < doc.length) to += 1;
- else if (from > 0) from -= 1;
- }
- return { from: from, to: to, insert: insert };
- });
- v.dispatch({ changes: changes, userEvent: "delete.comments", scrollIntoView: true });
- v.focus();
- A.ui.toast(A.tn("tools.comments_removed", all.length), "success");
- return all.length;
- }
-
- function indentSize() {
- return Math.max(1, A.settings.get("tabSize") || 2);
- }
-
- var tools = (A.codetools = {
- removeComments: removeComments,
-
- trimTrailing: function () {
- return rewriteLines(function (text) { return text.replace(/[ \t]+$/gm, ""); });
- },
-
- removeEmptyLines: function () {
- return rewriteLines(function (text) {
- var p = splitLines(text);
- p.lines = p.lines.filter(function (line) { return line.trim() !== ""; });
- return joinLines(p);
- });
- },
-
- collapseEmptyLines: function () {
- return rewriteLines(function (text) { return text.replace(/(\n[ \t]*){3,}/g, "\n\n"); });
- },
-
- sortLines: function (descending) {
- return rewriteLines(function (text) {
- var p = splitLines(text);
- p.lines.sort(function (a, b) { return a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }); });
- if (descending) p.lines.reverse();
- return joinLines(p);
- });
- },
-
- uniqueLines: function () {
- return rewriteLines(function (text) {
- var p = splitLines(text), seen = {};
- p.lines = p.lines.filter(function (line) {
- if (Object.prototype.hasOwnProperty.call(seen, line)) return false;
- seen[line] = true;
- return true;
- });
- return joinLines(p);
- });
- },
-
- reverseLines: function () {
- return rewriteLines(function (text) {
- var p = splitLines(text);
- p.lines.reverse();
- return joinLines(p);
- });
- },
-
- joinLines: function () {
- return rewriteLines(function (text) {
- var parts = text.split("\n").map(function (line) { return line.trim(); }).filter(Boolean);
- return parts.join(" ");
- });
- },
-
- upperCase: function () {
- return rewriteSelection(function (text) { return text.toUpperCase(); });
- },
-
- lowerCase: function () {
- return rewriteSelection(function (text) { return text.toLowerCase(); });
- },
-
- tabsToSpaces: function () {
- var unit = " ".repeat(indentSize());
- return rewriteLines(function (text) {
- return text.replace(/^[ \t]*\t[ \t]*/gm, function (lead) { return lead.replace(/\t/g, unit); });
- });
- },
-
- spacesToTabs: function () {
- var size = indentSize(), re = new RegExp("^((?: {" + size + "})+)", "gm");
- return rewriteLines(function (text) {
- return text.replace(re, function (lead) { return "\t".repeat(lead.length / size); });
- });
- }
- });
-
- function bracketDiagnostics(state) {
- if (state.doc.length > MAX_BRACKET_SCAN) return [];
- var tree = CM.ensureSyntaxTree(state, state.doc.length, 300) || CM.syntaxTree(state);
- var text = state.doc.toString(), re = /[()\[\]{}]/g, stack = [], out = [], m;
- function skipped(index) {
- var slashes = 0;
- while (index - slashes - 1 >= 0 && text.charCodeAt(index - slashes - 1) === 92) slashes++;
- if (slashes % 2) return true;
- for (var n = tree.resolveInner(index, 1); n; n = n.parent) {
- if (BRACKET_SKIP.test(n.name)) return true;
- }
- return false;
- }
- function report(from, message) {
- if (out.length < MAX_DIAGNOSTICS) out.push({ from: from, to: from + 1, severity: "error", source: "syntax", message: message });
- }
- while ((m = re.exec(text))) {
- var ch = m[0], i = m.index;
- if (skipped(i)) continue;
- if (OPENERS[ch]) {
- stack.push({ ch: ch, pos: i });
- continue;
- }
- var depth = -1;
- for (var k = stack.length - 1; k >= 0; k--) {
- if (stack[k].ch === CLOSERS[ch]) { depth = k; break; }
- }
- if (depth < 0) {
- report(i, t("lint.bracket_unexpected", { char: ch }));
- continue;
- }
- if (depth === stack.length - 1) {
- stack.pop();
- continue;
- }
- var top = stack[stack.length - 1];
- report(top.pos, t("lint.bracket_mismatch", { open: top.ch, expected: OPENERS[top.ch], found: ch }));
- stack.length = depth;
- }
- stack.forEach(function (item) {
- report(item.pos, t("lint.bracket_unclosed", { char: item.ch }));
- });
- return out;
- }
-
- function stripJsonc(text) {
- var out = "", i = 0, n = text.length;
- while (i < n) {
- var c = text[i], next = text[i + 1];
- if (c === '"') {
- var j = i + 1;
- while (j < n && text[j] !== '"' && text[j] !== "\n") j += text[j] === "\\" ? 2 : 1;
- out += text.slice(i, j + 1);
- i = j + 1;
- } else if (c === "/" && next === "/") {
- while (i < n && text[i] !== "\n") { out += " "; i++; }
- } else if (c === "/" && next === "*") {
- var end = text.indexOf("*/", i + 2);
- end = end < 0 ? n : end + 2;
- while (i < end) { out += text[i] === "\n" ? "\n" : " "; i++; }
- } else {
- out += c;
- i++;
- }
- }
- return out.replace(/,(\s*[}\]])/g, " $1");
- }
-
- function jsonErrorPosition(error, doc) {
- var msg = String(error.message || error), m;
- if ((m = /at position (\d+)/.exec(msg))) return Math.min(Number(m[1]), doc.length);
- if ((m = /line (\d+) column (\d+)/.exec(msg))) {
- var line = doc.line(Math.max(1, Math.min(doc.lines, Number(m[1]))));
- return Math.min(line.from + Number(m[2]) - 1, line.to);
- }
- return 0;
- }
-
- function jsoncDiagnostics(state) {
- var doc = state.doc;
- if (!doc.toString().trim()) return [];
- try {
- JSON.parse(stripJsonc(doc.toString()));
- } catch (e) {
- if (!(e instanceof SyntaxError)) throw e;
- var pos = jsonErrorPosition(e, doc);
- return [{ from: pos, to: Math.min(pos + 1, doc.length), severity: "error", source: "json", message: String(e.message).split("\n")[0] }];
- }
- return [];
- }
-
- tools.bracketDiagnostics = bracketDiagnostics;
- tools.jsoncDiagnostics = jsoncDiagnostics;
- })();
-