WebOrbiton
v1.5.0

AtheraStudio Code

338 lines · 11.4 KB
  1. (function () {
  2. "use strict";
  3. ​
  4. var A = window.Athera;
  5. var t = A.t;
  6. ​
  7. var COMMENT_NODE = /Comment(Block)?$/;
  8. var BRACKET_SKIP = /String|Comment|RegExp|Heredoc|Nowdoc|Text|Escape|Char|Url|Raw|Doctype|ParenthesizedContent/;
  9. var OPENERS = { "(": ")", "[": "]", "{": "}" };
  10. var CLOSERS = { ")": "(", "]": "[", "}": "{" };
  11. var MAX_BRACKET_SCAN = 400000;
  12. var MAX_DIAGNOSTICS = 20;
  13. ​
  14. function view() {
  15. return A.editor.view;
  16. }
  17. ​
  18. function parsed(state, timeout) {
  19. return CM.ensureSyntaxTree(state, state.doc.length, timeout || 4000);
  20. }
  21. ​
  22. function diffChange(from, oldText, newText) {
  23. var start = 0, endA = oldText.length, endB = newText.length;
  24. while (start < endA && start < endB && oldText.charCodeAt(start) === newText.charCodeAt(start)) start++;
  25. while (endA > start && endB > start && oldText.charCodeAt(endA - 1) === newText.charCodeAt(endB - 1)) { endA--; endB--; }
  26. return { from: from + start, to: from + endA, insert: newText.slice(start, endB) };
  27. }
  28. ​
  29. function scope(state) {
  30. var sel = state.selection.main;
  31. if (sel.empty) return { from: 0, to: state.doc.length };
  32. var a = state.doc.lineAt(sel.from), b = state.doc.lineAt(sel.to);
  33. var to = sel.to === b.from && b.number > a.number ? state.doc.lineAt(sel.to - 1).to : b.to;
  34. return { from: a.from, to: to };
  35. }
  36. ​
  37. function rewriteLines(transform) {
  38. var v = view(), state = v.state, r = scope(state);
  39. var oldText = state.sliceDoc(r.from, r.to);
  40. var newText = transform(oldText);
  41. if (newText === oldText) {
  42. A.ui.toast(t("tools.nothing_changed"), "info");
  43. return false;
  44. }
  45. v.dispatch({ changes: diffChange(r.from, oldText, newText), userEvent: "input.tools", scrollIntoView: true });
  46. v.focus();
  47. return true;
  48. }
  49. ​
  50. function rewriteSelection(transform) {
  51. var v = view(), state = v.state, changes = [];
  52. state.selection.ranges.forEach(function (range) {
  53. var from = range.from, to = range.to;
  54. if (range.empty) {
  55. var word = state.wordAt(range.head);
  56. if (!word) return;
  57. from = word.from;
  58. to = word.to;
  59. }
  60. var oldText = state.sliceDoc(from, to), newText = transform(oldText);
  61. if (newText !== oldText) changes.push(diffChange(from, oldText, newText));
  62. });
  63. if (!changes.length) {
  64. A.ui.toast(t("tools.nothing_changed"), "info");
  65. return false;
  66. }
  67. v.dispatch({ changes: changes, userEvent: "input.tools", scrollIntoView: true });
  68. v.focus();
  69. return true;
  70. }
  71. ​
  72. function splitLines(text) {
  73. var lines = text.split("\n"), trailing = lines.length > 1 && lines[lines.length - 1] === "";
  74. if (trailing) lines.pop();
  75. return { lines: lines, trailing: trailing };
  76. }
  77. ​
  78. function joinLines(parts) {
  79. return parts.lines.join("\n") + (parts.trailing ? "\n" : "");
  80. }
  81. ​
  82. function collectComments(state, from, to) {
  83. var tree = parsed(state);
  84. if (!tree) return null;
  85. var found = [];
  86. tree.iterate({
  87. from: from,
  88. to: to,
  89. enter: function (node) {
  90. if (!COMMENT_NODE.test(node.name)) return;
  91. if (node.from >= from && node.to <= to) found.push({ from: node.from, to: node.to });
  92. return false;
  93. }
  94. });
  95. found.sort(function (a, b) { return a.from - b.from; });
  96. var merged = [];
  97. found.forEach(function (c) {
  98. var last = merged[merged.length - 1];
  99. if (last && c.from <= last.to) last.to = Math.max(last.to, c.to);
  100. else merged.push({ from: c.from, to: c.to });
  101. });
  102. return merged;
  103. }
  104. ​
  105. function groupText(doc, group) {
  106. var offset = group.first.from, raw = doc.sliceString(offset, group.last.to), out = "", pos = 0;
  107. group.comments.forEach(function (c) {
  108. out += raw.slice(pos, c.from - offset);
  109. pos = c.to - offset;
  110. var rest = raw.slice(pos);
  111. if (/(^|[ \t\n(\[{])$/.test(out) && /^[ \t]/.test(rest)) pos += /^[ \t]*/.exec(rest)[0].length;
  112. else if (/[ \t]$/.test(out) && /^[)\]},;]/.test(rest)) out = out.replace(/[ \t]+$/, "");
  113. else if (/\w$/.test(out) && /^\w/.test(rest)) out += " ";
  114. });
  115. return out + raw.slice(pos);
  116. }
  117. ​
  118. function removeComments() {
  119. var v = view(), state = v.state, doc = state.doc;
  120. var ranges = state.selection.ranges.filter(function (r) { return !r.empty; });
  121. if (!ranges.length) ranges = [{ from: 0, to: doc.length }];
  122. var all = [];
  123. for (var i = 0; i < ranges.length; i++) {
  124. var list = collectComments(state, ranges[i].from, ranges[i].to);
  125. if (!list) {
  126. A.ui.toast(t("tools.parse_failed"), "warning");
  127. return 0;
  128. }
  129. all = all.concat(list);
  130. }
  131. all.sort(function (a, b) { return a.from - b.from; });
  132. if (!all.length) {
  133. A.ui.toast(t("tools.no_comments"), "info");
  134. return 0;
  135. }
  136. var groups = [];
  137. all.forEach(function (c) {
  138. var first = doc.lineAt(c.from), last = doc.lineAt(c.to);
  139. var g = groups[groups.length - 1];
  140. if (g && first.number <= g.last.number) {
  141. g.comments.push(c);
  142. if (last.number > g.last.number) g.last = last;
  143. } else {
  144. groups.push({ first: first, last: last, comments: [c] });
  145. }
  146. });
  147. var changes = groups.map(function (g) {
  148. var lines = groupText(doc, g).split("\n").map(function (line) { return line.replace(/[ \t]+$/, ""); }).filter(function (line) { return line !== ""; });
  149. var insert = lines.join("\n"), from = g.first.from, to = g.last.to;
  150. if (!insert) {
  151. if (to < doc.length) to += 1;
  152. else if (from > 0) from -= 1;
  153. }
  154. return { from: from, to: to, insert: insert };
  155. });
  156. v.dispatch({ changes: changes, userEvent: "delete.comments", scrollIntoView: true });
  157. v.focus();
  158. A.ui.toast(A.tn("tools.comments_removed", all.length), "success");
  159. return all.length;
  160. }
  161. ​
  162. function indentSize() {
  163. return Math.max(1, A.settings.get("tabSize") || 2);
  164. }
  165. ​
  166. var tools = (A.codetools = {
  167. removeComments: removeComments,
  168. ​
  169. trimTrailing: function () {
  170. return rewriteLines(function (text) { return text.replace(/[ \t]+$/gm, ""); });
  171. },
  172. ​
  173. removeEmptyLines: function () {
  174. return rewriteLines(function (text) {
  175. var p = splitLines(text);
  176. p.lines = p.lines.filter(function (line) { return line.trim() !== ""; });
  177. return joinLines(p);
  178. });
  179. },
  180. ​
  181. collapseEmptyLines: function () {
  182. return rewriteLines(function (text) { return text.replace(/(\n[ \t]*){3,}/g, "\n\n"); });
  183. },
  184. ​
  185. sortLines: function (descending) {
  186. return rewriteLines(function (text) {
  187. var p = splitLines(text);
  188. p.lines.sort(function (a, b) { return a.localeCompare(b, undefined, { numeric: true, sensitivity: "base" }); });
  189. if (descending) p.lines.reverse();
  190. return joinLines(p);
  191. });
  192. },
  193. ​
  194. uniqueLines: function () {
  195. return rewriteLines(function (text) {
  196. var p = splitLines(text), seen = {};
  197. p.lines = p.lines.filter(function (line) {
  198. if (Object.prototype.hasOwnProperty.call(seen, line)) return false;
  199. seen[line] = true;
  200. return true;
  201. });
  202. return joinLines(p);
  203. });
  204. },
  205. ​
  206. reverseLines: function () {
  207. return rewriteLines(function (text) {
  208. var p = splitLines(text);
  209. p.lines.reverse();
  210. return joinLines(p);
  211. });
  212. },
  213. ​
  214. joinLines: function () {
  215. return rewriteLines(function (text) {
  216. var parts = text.split("\n").map(function (line) { return line.trim(); }).filter(Boolean);
  217. return parts.join(" ");
  218. });
  219. },
  220. ​
  221. upperCase: function () {
  222. return rewriteSelection(function (text) { return text.toUpperCase(); });
  223. },
  224. ​
  225. lowerCase: function () {
  226. return rewriteSelection(function (text) { return text.toLowerCase(); });
  227. },
  228. ​
  229. tabsToSpaces: function () {
  230. var unit = " ".repeat(indentSize());
  231. return rewriteLines(function (text) {
  232. return text.replace(/^[ \t]*\t[ \t]*/gm, function (lead) { return lead.replace(/\t/g, unit); });
  233. });
  234. },
  235. ​
  236. spacesToTabs: function () {
  237. var size = indentSize(), re = new RegExp("^((?: {" + size + "})+)", "gm");
  238. return rewriteLines(function (text) {
  239. return text.replace(re, function (lead) { return "\t".repeat(lead.length / size); });
  240. });
  241. }
  242. });
  243. ​
  244. function bracketDiagnostics(state) {
  245. if (state.doc.length > MAX_BRACKET_SCAN) return [];
  246. var tree = CM.ensureSyntaxTree(state, state.doc.length, 300) || CM.syntaxTree(state);
  247. var text = state.doc.toString(), re = /[()\[\]{}]/g, stack = [], out = [], m;
  248. function skipped(index) {
  249. var slashes = 0;
  250. while (index - slashes - 1 >= 0 && text.charCodeAt(index - slashes - 1) === 92) slashes++;
  251. if (slashes % 2) return true;
  252. for (var n = tree.resolveInner(index, 1); n; n = n.parent) {
  253. if (BRACKET_SKIP.test(n.name)) return true;
  254. }
  255. return false;
  256. }
  257. function report(from, message) {
  258. if (out.length < MAX_DIAGNOSTICS) out.push({ from: from, to: from + 1, severity: "error", source: "syntax", message: message });
  259. }
  260. while ((m = re.exec(text))) {
  261. var ch = m[0], i = m.index;
  262. if (skipped(i)) continue;
  263. if (OPENERS[ch]) {
  264. stack.push({ ch: ch, pos: i });
  265. continue;
  266. }
  267. var depth = -1;
  268. for (var k = stack.length - 1; k >= 0; k--) {
  269. if (stack[k].ch === CLOSERS[ch]) { depth = k; break; }
  270. }
  271. if (depth < 0) {
  272. report(i, t("lint.bracket_unexpected", { char: ch }));
  273. continue;
  274. }
  275. if (depth === stack.length - 1) {
  276. stack.pop();
  277. continue;
  278. }
  279. var top = stack[stack.length - 1];
  280. report(top.pos, t("lint.bracket_mismatch", { open: top.ch, expected: OPENERS[top.ch], found: ch }));
  281. stack.length = depth;
  282. }
  283. stack.forEach(function (item) {
  284. report(item.pos, t("lint.bracket_unclosed", { char: item.ch }));
  285. });
  286. return out;
  287. }
  288. ​
  289. function stripJsonc(text) {
  290. var out = "", i = 0, n = text.length;
  291. while (i < n) {
  292. var c = text[i], next = text[i + 1];
  293. if (c === '"') {
  294. var j = i + 1;
  295. while (j < n && text[j] !== '"' && text[j] !== "\n") j += text[j] === "\\" ? 2 : 1;
  296. out += text.slice(i, j + 1);
  297. i = j + 1;
  298. } else if (c === "/" && next === "/") {
  299. while (i < n && text[i] !== "\n") { out += " "; i++; }
  300. } else if (c === "/" && next === "*") {
  301. var end = text.indexOf("*/", i + 2);
  302. end = end < 0 ? n : end + 2;
  303. while (i < end) { out += text[i] === "\n" ? "\n" : " "; i++; }
  304. } else {
  305. out += c;
  306. i++;
  307. }
  308. }
  309. return out.replace(/,(\s*[}\]])/g, " $1");
  310. }
  311. ​
  312. function jsonErrorPosition(error, doc) {
  313. var msg = String(error.message || error), m;
  314. if ((m = /at position (\d+)/.exec(msg))) return Math.min(Number(m[1]), doc.length);
  315. if ((m = /line (\d+) column (\d+)/.exec(msg))) {
  316. var line = doc.line(Math.max(1, Math.min(doc.lines, Number(m[1]))));
  317. return Math.min(line.from + Number(m[2]) - 1, line.to);
  318. }
  319. return 0;
  320. }
  321. ​
  322. function jsoncDiagnostics(state) {
  323. var doc = state.doc;
  324. if (!doc.toString().trim()) return [];
  325. try {
  326. JSON.parse(stripJsonc(doc.toString()));
  327. } catch (e) {
  328. if (!(e instanceof SyntaxError)) throw e;
  329. var pos = jsonErrorPosition(e, doc);
  330. return [{ from: pos, to: Math.min(pos + 1, doc.length), severity: "error", source: "json", message: String(e.message).split("\n")[0] }];
  331. }
  332. return [];
  333. }
  334. ​
  335. tools.bracketDiagnostics = bracketDiagnostics;
  336. tools.jsoncDiagnostics = jsoncDiagnostics;
  337. })();
  338. ​