You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1955 lines
66 KiB

12 months ago
  1. ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"], function(acequire, exports, module) {
  2. "use strict";
  3. var oop = acequire("./lib/oop");
  4. var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
  5. var lang = acequire("./lib/lang");
  6. var Range = acequire("./range").Range;
  7. var Anchor = acequire("./anchor").Anchor;
  8. var HashHandler = acequire("./keyboard/hash_handler").HashHandler;
  9. var Tokenizer = acequire("./tokenizer").Tokenizer;
  10. var comparePoints = Range.comparePoints;
  11. var SnippetManager = function() {
  12. this.snippetMap = {};
  13. this.snippetNameMap = {};
  14. };
  15. (function() {
  16. oop.implement(this, EventEmitter);
  17. this.getTokenizer = function() {
  18. function TabstopToken(str, _, stack) {
  19. str = str.substr(1);
  20. if (/^\d+$/.test(str) && !stack.inFormatString)
  21. return [{tabstopId: parseInt(str, 10)}];
  22. return [{text: str}];
  23. }
  24. function escape(ch) {
  25. return "(?:[^\\\\" + ch + "]|\\\\.)";
  26. }
  27. SnippetManager.$tokenizer = new Tokenizer({
  28. start: [
  29. {regex: /:/, onMatch: function(val, state, stack) {
  30. if (stack.length && stack[0].expectIf) {
  31. stack[0].expectIf = false;
  32. stack[0].elseBranch = stack[0];
  33. return [stack[0]];
  34. }
  35. return ":";
  36. }},
  37. {regex: /\\./, onMatch: function(val, state, stack) {
  38. var ch = val[1];
  39. if (ch == "}" && stack.length) {
  40. val = ch;
  41. }else if ("`$\\".indexOf(ch) != -1) {
  42. val = ch;
  43. } else if (stack.inFormatString) {
  44. if (ch == "n")
  45. val = "\n";
  46. else if (ch == "t")
  47. val = "\n";
  48. else if ("ulULE".indexOf(ch) != -1) {
  49. val = {changeCase: ch, local: ch > "a"};
  50. }
  51. }
  52. return [val];
  53. }},
  54. {regex: /}/, onMatch: function(val, state, stack) {
  55. return [stack.length ? stack.shift() : val];
  56. }},
  57. {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken},
  58. {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) {
  59. var t = TabstopToken(str.substr(1), state, stack);
  60. stack.unshift(t[0]);
  61. return t;
  62. }, next: "snippetVar"},
  63. {regex: /\n/, token: "newline", merge: false}
  64. ],
  65. snippetVar: [
  66. {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) {
  67. stack[0].choices = val.slice(1, -1).split(",");
  68. }, next: "start"},
  69. {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?",
  70. onMatch: function(val, state, stack) {
  71. var ts = stack[0];
  72. ts.fmtString = val;
  73. val = this.splitRegex.exec(val);
  74. ts.guard = val[1];
  75. ts.fmt = val[2];
  76. ts.flag = val[3];
  77. return "";
  78. }, next: "start"},
  79. {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) {
  80. stack[0].code = val.splice(1, -1);
  81. return "";
  82. }, next: "start"},
  83. {regex: "\\?", onMatch: function(val, state, stack) {
  84. if (stack[0])
  85. stack[0].expectIf = true;
  86. }, next: "start"},
  87. {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"}
  88. ],
  89. formatString: [
  90. {regex: "/(" + escape("/") + "+)/", token: "regex"},
  91. {regex: "", onMatch: function(val, state, stack) {
  92. stack.inFormatString = true;
  93. }, next: "start"}
  94. ]
  95. });
  96. SnippetManager.prototype.getTokenizer = function() {
  97. return SnippetManager.$tokenizer;
  98. };
  99. return SnippetManager.$tokenizer;
  100. };
  101. this.tokenizeTmSnippet = function(str, startState) {
  102. return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) {
  103. return x.value || x;
  104. });
  105. };
  106. this.$getDefaultValue = function(editor, name) {
  107. if (/^[A-Z]\d+$/.test(name)) {
  108. var i = name.substr(1);
  109. return (this.variables[name[0] + "__"] || {})[i];
  110. }
  111. if (/^\d+$/.test(name)) {
  112. return (this.variables.__ || {})[name];
  113. }
  114. name = name.replace(/^TM_/, "");
  115. if (!editor)
  116. return;
  117. var s = editor.session;
  118. switch(name) {
  119. case "CURRENT_WORD":
  120. var r = s.getWordRange();
  121. case "SELECTION":
  122. case "SELECTED_TEXT":
  123. return s.getTextRange(r);
  124. case "CURRENT_LINE":
  125. return s.getLine(editor.getCursorPosition().row);
  126. case "PREV_LINE": // not possible in textmate
  127. return s.getLine(editor.getCursorPosition().row - 1);
  128. case "LINE_INDEX":
  129. return editor.getCursorPosition().column;
  130. case "LINE_NUMBER":
  131. return editor.getCursorPosition().row + 1;
  132. case "SOFT_TABS":
  133. return s.getUseSoftTabs() ? "YES" : "NO";
  134. case "TAB_SIZE":
  135. return s.getTabSize();
  136. case "FILENAME":
  137. case "FILEPATH":
  138. return "";
  139. case "FULLNAME":
  140. return "Ace";
  141. }
  142. };
  143. this.variables = {};
  144. this.getVariableValue = function(editor, varName) {
  145. if (this.variables.hasOwnProperty(varName))
  146. return this.variables[varName](editor, varName) || "";
  147. return this.$getDefaultValue(editor, varName) || "";
  148. };
  149. this.tmStrFormat = function(str, ch, editor) {
  150. var flag = ch.flag || "";
  151. var re = ch.guard;
  152. re = new RegExp(re, flag.replace(/[^gi]/, ""));
  153. var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString");
  154. var _self = this;
  155. var formatted = str.replace(re, function() {
  156. _self.variables.__ = arguments;
  157. var fmtParts = _self.resolveVariables(fmtTokens, editor);
  158. var gChangeCase = "E";
  159. for (var i = 0; i < fmtParts.length; i++) {
  160. var ch = fmtParts[i];
  161. if (typeof ch == "object") {
  162. fmtParts[i] = "";
  163. if (ch.changeCase && ch.local) {
  164. var next = fmtParts[i + 1];
  165. if (next && typeof next == "string") {
  166. if (ch.changeCase == "u")
  167. fmtParts[i] = next[0].toUpperCase();
  168. else
  169. fmtParts[i] = next[0].toLowerCase();
  170. fmtParts[i + 1] = next.substr(1);
  171. }
  172. } else if (ch.changeCase) {
  173. gChangeCase = ch.changeCase;
  174. }
  175. } else if (gChangeCase == "U") {
  176. fmtParts[i] = ch.toUpperCase();
  177. } else if (gChangeCase == "L") {
  178. fmtParts[i] = ch.toLowerCase();
  179. }
  180. }
  181. return fmtParts.join("");
  182. });
  183. this.variables.__ = null;
  184. return formatted;
  185. };
  186. this.resolveVariables = function(snippet, editor) {
  187. var result = [];
  188. for (var i = 0; i < snippet.length; i++) {
  189. var ch = snippet[i];
  190. if (typeof ch == "string") {
  191. result.push(ch);
  192. } else if (typeof ch != "object") {
  193. continue;
  194. } else if (ch.skip) {
  195. gotoNext(ch);
  196. } else if (ch.processed < i) {
  197. continue;
  198. } else if (ch.text) {
  199. var value = this.getVariableValue(editor, ch.text);
  200. if (value && ch.fmtString)
  201. value = this.tmStrFormat(value, ch);
  202. ch.processed = i;
  203. if (ch.expectIf == null) {
  204. if (value) {
  205. result.push(value);
  206. gotoNext(ch);
  207. }
  208. } else {
  209. if (value) {
  210. ch.skip = ch.elseBranch;
  211. } else
  212. gotoNext(ch);
  213. }
  214. } else if (ch.tabstopId != null) {
  215. result.push(ch);
  216. } else if (ch.changeCase != null) {
  217. result.push(ch);
  218. }
  219. }
  220. function gotoNext(ch) {
  221. var i1 = snippet.indexOf(ch, i + 1);
  222. if (i1 != -1)
  223. i = i1;
  224. }
  225. return result;
  226. };
  227. this.insertSnippetForSelection = function(editor, snippetText) {
  228. var cursor = editor.getCursorPosition();
  229. var line = editor.session.getLine(cursor.row);
  230. var tabString = editor.session.getTabString();
  231. var indentString = line.match(/^\s*/)[0];
  232. if (cursor.column < indentString.length)
  233. indentString = indentString.slice(0, cursor.column);
  234. snippetText = snippetText.replace(/\r/g, "");
  235. var tokens = this.tokenizeTmSnippet(snippetText);
  236. tokens = this.resolveVariables(tokens, editor);
  237. tokens = tokens.map(function(x) {
  238. if (x == "\n")
  239. return x + indentString;
  240. if (typeof x == "string")
  241. return x.replace(/\t/g, tabString);
  242. return x;
  243. });
  244. var tabstops = [];
  245. tokens.forEach(function(p, i) {
  246. if (typeof p != "object")
  247. return;
  248. var id = p.tabstopId;
  249. var ts = tabstops[id];
  250. if (!ts) {
  251. ts = tabstops[id] = [];
  252. ts.index = id;
  253. ts.value = "";
  254. }
  255. if (ts.indexOf(p) !== -1)
  256. return;
  257. ts.push(p);
  258. var i1 = tokens.indexOf(p, i + 1);
  259. if (i1 === -1)
  260. return;
  261. var value = tokens.slice(i + 1, i1);
  262. var isNested = value.some(function(t) {return typeof t === "object";});
  263. if (isNested && !ts.value) {
  264. ts.value = value;
  265. } else if (value.length && (!ts.value || typeof ts.value !== "string")) {
  266. ts.value = value.join("");
  267. }
  268. });
  269. tabstops.forEach(function(ts) {ts.length = 0;});
  270. var expanding = {};
  271. function copyValue(val) {
  272. var copy = [];
  273. for (var i = 0; i < val.length; i++) {
  274. var p = val[i];
  275. if (typeof p == "object") {
  276. if (expanding[p.tabstopId])
  277. continue;
  278. var j = val.lastIndexOf(p, i - 1);
  279. p = copy[j] || {tabstopId: p.tabstopId};
  280. }
  281. copy[i] = p;
  282. }
  283. return copy;
  284. }
  285. for (var i = 0; i < tokens.length; i++) {
  286. var p = tokens[i];
  287. if (typeof p != "object")
  288. continue;
  289. var id = p.tabstopId;
  290. var i1 = tokens.indexOf(p, i + 1);
  291. if (expanding[id]) {
  292. if (expanding[id] === p)
  293. expanding[id] = null;
  294. continue;
  295. }
  296. var ts = tabstops[id];
  297. var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value);
  298. arg.unshift(i + 1, Math.max(0, i1 - i));
  299. arg.push(p);
  300. expanding[id] = p;
  301. tokens.splice.apply(tokens, arg);
  302. if (ts.indexOf(p) === -1)
  303. ts.push(p);
  304. }
  305. var row = 0, column = 0;
  306. var text = "";
  307. tokens.forEach(function(t) {
  308. if (typeof t === "string") {
  309. var lines = t.split("\n");
  310. if (lines.length > 1){
  311. column = lines[lines.length - 1].length;
  312. row += lines.length - 1;
  313. } else
  314. column += t.length;
  315. text += t;
  316. } else {
  317. if (!t.start)
  318. t.start = {row: row, column: column};
  319. else
  320. t.end = {row: row, column: column};
  321. }
  322. });
  323. var range = editor.getSelectionRange();
  324. var end = editor.session.replace(range, text);
  325. var tabstopManager = new TabstopManager(editor);
  326. var selectionId = editor.inVirtualSelectionMode && editor.selection.index;
  327. tabstopManager.addTabstops(tabstops, range.start, end, selectionId);
  328. };
  329. this.insertSnippet = function(editor, snippetText) {
  330. var self = this;
  331. if (editor.inVirtualSelectionMode)
  332. return self.insertSnippetForSelection(editor, snippetText);
  333. editor.forEachSelection(function() {
  334. self.insertSnippetForSelection(editor, snippetText);
  335. }, null, {keepOrder: true});
  336. if (editor.tabstopManager)
  337. editor.tabstopManager.tabNext();
  338. };
  339. this.$getScope = function(editor) {
  340. var scope = editor.session.$mode.$id || "";
  341. scope = scope.split("/").pop();
  342. if (scope === "html" || scope === "php") {
  343. if (scope === "php" && !editor.session.$mode.inlinePhp)
  344. scope = "html";
  345. var c = editor.getCursorPosition();
  346. var state = editor.session.getState(c.row);
  347. if (typeof state === "object") {
  348. state = state[0];
  349. }
  350. if (state.substring) {
  351. if (state.substring(0, 3) == "js-")
  352. scope = "javascript";
  353. else if (state.substring(0, 4) == "css-")
  354. scope = "css";
  355. else if (state.substring(0, 4) == "php-")
  356. scope = "php";
  357. }
  358. }
  359. return scope;
  360. };
  361. this.getActiveScopes = function(editor) {
  362. var scope = this.$getScope(editor);
  363. var scopes = [scope];
  364. var snippetMap = this.snippetMap;
  365. if (snippetMap[scope] && snippetMap[scope].includeScopes) {
  366. scopes.push.apply(scopes, snippetMap[scope].includeScopes);
  367. }
  368. scopes.push("_");
  369. return scopes;
  370. };
  371. this.expandWithTab = function(editor, options) {
  372. var self = this;
  373. var result = editor.forEachSelection(function() {
  374. return self.expandSnippetForSelection(editor, options);
  375. }, null, {keepOrder: true});
  376. if (result && editor.tabstopManager)
  377. editor.tabstopManager.tabNext();
  378. return result;
  379. };
  380. this.expandSnippetForSelection = function(editor, options) {
  381. var cursor = editor.getCursorPosition();
  382. var line = editor.session.getLine(cursor.row);
  383. var before = line.substring(0, cursor.column);
  384. var after = line.substr(cursor.column);
  385. var snippetMap = this.snippetMap;
  386. var snippet;
  387. this.getActiveScopes(editor).some(function(scope) {
  388. var snippets = snippetMap[scope];
  389. if (snippets)
  390. snippet = this.findMatchingSnippet(snippets, before, after);
  391. return !!snippet;
  392. }, this);
  393. if (!snippet)
  394. return false;
  395. if (options && options.dryRun)
  396. return true;
  397. editor.session.doc.removeInLine(cursor.row,
  398. cursor.column - snippet.replaceBefore.length,
  399. cursor.column + snippet.replaceAfter.length
  400. );
  401. this.variables.M__ = snippet.matchBefore;
  402. this.variables.T__ = snippet.matchAfter;
  403. this.insertSnippetForSelection(editor, snippet.content);
  404. this.variables.M__ = this.variables.T__ = null;
  405. return true;
  406. };
  407. this.findMatchingSnippet = function(snippetList, before, after) {
  408. for (var i = snippetList.length; i--;) {
  409. var s = snippetList[i];
  410. if (s.startRe && !s.startRe.test(before))
  411. continue;
  412. if (s.endRe && !s.endRe.test(after))
  413. continue;
  414. if (!s.startRe && !s.endRe)
  415. continue;
  416. s.matchBefore = s.startRe ? s.startRe.exec(before) : [""];
  417. s.matchAfter = s.endRe ? s.endRe.exec(after) : [""];
  418. s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : "";
  419. s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : "";
  420. return s;
  421. }
  422. };
  423. this.snippetMap = {};
  424. this.snippetNameMap = {};
  425. this.register = function(snippets, scope) {
  426. var snippetMap = this.snippetMap;
  427. var snippetNameMap = this.snippetNameMap;
  428. var self = this;
  429. if (!snippets)
  430. snippets = [];
  431. function wrapRegexp(src) {
  432. if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src))
  433. src = "(?:" + src + ")";
  434. return src || "";
  435. }
  436. function guardedRegexp(re, guard, opening) {
  437. re = wrapRegexp(re);
  438. guard = wrapRegexp(guard);
  439. if (opening) {
  440. re = guard + re;
  441. if (re && re[re.length - 1] != "$")
  442. re = re + "$";
  443. } else {
  444. re = re + guard;
  445. if (re && re[0] != "^")
  446. re = "^" + re;
  447. }
  448. return new RegExp(re);
  449. }
  450. function addSnippet(s) {
  451. if (!s.scope)
  452. s.scope = scope || "_";
  453. scope = s.scope;
  454. if (!snippetMap[scope]) {
  455. snippetMap[scope] = [];
  456. snippetNameMap[scope] = {};
  457. }
  458. var map = snippetNameMap[scope];
  459. if (s.name) {
  460. var old = map[s.name];
  461. if (old)
  462. self.unregister(old);
  463. map[s.name] = s;
  464. }
  465. snippetMap[scope].push(s);
  466. if (s.tabTrigger && !s.trigger) {
  467. if (!s.guard && /^\w/.test(s.tabTrigger))
  468. s.guard = "\\b";
  469. s.trigger = lang.escapeRegExp(s.tabTrigger);
  470. }
  471. if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard)
  472. return;
  473. s.startRe = guardedRegexp(s.trigger, s.guard, true);
  474. s.triggerRe = new RegExp(s.trigger, "", true);
  475. s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true);
  476. s.endTriggerRe = new RegExp(s.endTrigger, "", true);
  477. }
  478. if (snippets && snippets.content)
  479. addSnippet(snippets);
  480. else if (Array.isArray(snippets))
  481. snippets.forEach(addSnippet);
  482. this._signal("registerSnippets", {scope: scope});
  483. };
  484. this.unregister = function(snippets, scope) {
  485. var snippetMap = this.snippetMap;
  486. var snippetNameMap = this.snippetNameMap;
  487. function removeSnippet(s) {
  488. var nameMap = snippetNameMap[s.scope||scope];
  489. if (nameMap && nameMap[s.name]) {
  490. delete nameMap[s.name];
  491. var map = snippetMap[s.scope||scope];
  492. var i = map && map.indexOf(s);
  493. if (i >= 0)
  494. map.splice(i, 1);
  495. }
  496. }
  497. if (snippets.content)
  498. removeSnippet(snippets);
  499. else if (Array.isArray(snippets))
  500. snippets.forEach(removeSnippet);
  501. };
  502. this.parseSnippetFile = function(str) {
  503. str = str.replace(/\r/g, "");
  504. var list = [], snippet = {};
  505. var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;
  506. var m;
  507. while (m = re.exec(str)) {
  508. if (m[1]) {
  509. try {
  510. snippet = JSON.parse(m[1]);
  511. list.push(snippet);
  512. } catch (e) {}
  513. } if (m[4]) {
  514. snippet.content = m[4].replace(/^\t/gm, "");
  515. list.push(snippet);
  516. snippet = {};
  517. } else {
  518. var key = m[2], val = m[3];
  519. if (key == "regex") {
  520. var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g;
  521. snippet.guard = guardRe.exec(val)[1];
  522. snippet.trigger = guardRe.exec(val)[1];
  523. snippet.endTrigger = guardRe.exec(val)[1];
  524. snippet.endGuard = guardRe.exec(val)[1];
  525. } else if (key == "snippet") {
  526. snippet.tabTrigger = val.match(/^\S*/)[0];
  527. if (!snippet.name)
  528. snippet.name = val;
  529. } else {
  530. snippet[key] = val;
  531. }
  532. }
  533. }
  534. return list;
  535. };
  536. this.getSnippetByName = function(name, editor) {
  537. var snippetMap = this.snippetNameMap;
  538. var snippet;
  539. this.getActiveScopes(editor).some(function(scope) {
  540. var snippets = snippetMap[scope];
  541. if (snippets)
  542. snippet = snippets[name];
  543. return !!snippet;
  544. }, this);
  545. return snippet;
  546. };
  547. }).call(SnippetManager.prototype);
  548. var TabstopManager = function(editor) {
  549. if (editor.tabstopManager)
  550. return editor.tabstopManager;
  551. editor.tabstopManager = this;
  552. this.$onChange = this.onChange.bind(this);
  553. this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule;
  554. this.$onChangeSession = this.onChangeSession.bind(this);
  555. this.$onAfterExec = this.onAfterExec.bind(this);
  556. this.attach(editor);
  557. };
  558. (function() {
  559. this.attach = function(editor) {
  560. this.index = 0;
  561. this.ranges = [];
  562. this.tabstops = [];
  563. this.$openTabstops = null;
  564. this.selectedTabstop = null;
  565. this.editor = editor;
  566. this.editor.on("change", this.$onChange);
  567. this.editor.on("changeSelection", this.$onChangeSelection);
  568. this.editor.on("changeSession", this.$onChangeSession);
  569. this.editor.commands.on("afterExec", this.$onAfterExec);
  570. this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  571. };
  572. this.detach = function() {
  573. this.tabstops.forEach(this.removeTabstopMarkers, this);
  574. this.ranges = null;
  575. this.tabstops = null;
  576. this.selectedTabstop = null;
  577. this.editor.removeListener("change", this.$onChange);
  578. this.editor.removeListener("changeSelection", this.$onChangeSelection);
  579. this.editor.removeListener("changeSession", this.$onChangeSession);
  580. this.editor.commands.removeListener("afterExec", this.$onAfterExec);
  581. this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
  582. this.editor.tabstopManager = null;
  583. this.editor = null;
  584. };
  585. this.onChange = function(delta) {
  586. var changeRange = delta;
  587. var isRemove = delta.action[0] == "r";
  588. var start = delta.start;
  589. var end = delta.end;
  590. var startRow = start.row;
  591. var endRow = end.row;
  592. var lineDif = endRow - startRow;
  593. var colDiff = end.column - start.column;
  594. if (isRemove) {
  595. lineDif = -lineDif;
  596. colDiff = -colDiff;
  597. }
  598. if (!this.$inChange && isRemove) {
  599. var ts = this.selectedTabstop;
  600. var changedOutside = ts && !ts.some(function(r) {
  601. return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0;
  602. });
  603. if (changedOutside)
  604. return this.detach();
  605. }
  606. var ranges = this.ranges;
  607. for (var i = 0; i < ranges.length; i++) {
  608. var r = ranges[i];
  609. if (r.end.row < start.row)
  610. continue;
  611. if (isRemove && comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) {
  612. this.removeRange(r);
  613. i--;
  614. continue;
  615. }
  616. if (r.start.row == startRow && r.start.column > start.column)
  617. r.start.column += colDiff;
  618. if (r.end.row == startRow && r.end.column >= start.column)
  619. r.end.column += colDiff;
  620. if (r.start.row >= startRow)
  621. r.start.row += lineDif;
  622. if (r.end.row >= startRow)
  623. r.end.row += lineDif;
  624. if (comparePoints(r.start, r.end) > 0)
  625. this.removeRange(r);
  626. }
  627. if (!ranges.length)
  628. this.detach();
  629. };
  630. this.updateLinkedFields = function() {
  631. var ts = this.selectedTabstop;
  632. if (!ts || !ts.hasLinkedRanges)
  633. return;
  634. this.$inChange = true;
  635. var session = this.editor.session;
  636. var text = session.getTextRange(ts.firstNonLinked);
  637. for (var i = ts.length; i--;) {
  638. var range = ts[i];
  639. if (!range.linked)
  640. continue;
  641. var fmt = exports.snippetManager.tmStrFormat(text, range.original);
  642. session.replace(range, fmt);
  643. }
  644. this.$inChange = false;
  645. };
  646. this.onAfterExec = function(e) {
  647. if (e.command && !e.command.readOnly)
  648. this.updateLinkedFields();
  649. };
  650. this.onChangeSelection = function() {
  651. if (!this.editor)
  652. return;
  653. var lead = this.editor.selection.lead;
  654. var anchor = this.editor.selection.anchor;
  655. var isEmpty = this.editor.selection.isEmpty();
  656. for (var i = this.ranges.length; i--;) {
  657. if (this.ranges[i].linked)
  658. continue;
  659. var containsLead = this.ranges[i].contains(lead.row, lead.column);
  660. var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column);
  661. if (containsLead && containsAnchor)
  662. return;
  663. }
  664. this.detach();
  665. };
  666. this.onChangeSession = function() {
  667. this.detach();
  668. };
  669. this.tabNext = function(dir) {
  670. var max = this.tabstops.length;
  671. var index = this.index + (dir || 1);
  672. index = Math.min(Math.max(index, 1), max);
  673. if (index == max)
  674. index = 0;
  675. this.selectTabstop(index);
  676. if (index === 0)
  677. this.detach();
  678. };
  679. this.selectTabstop = function(index) {
  680. this.$openTabstops = null;
  681. var ts = this.tabstops[this.index];
  682. if (ts)
  683. this.addTabstopMarkers(ts);
  684. this.index = index;
  685. ts = this.tabstops[this.index];
  686. if (!ts || !ts.length)
  687. return;
  688. this.selectedTabstop = ts;
  689. if (!this.editor.inVirtualSelectionMode) {
  690. var sel = this.editor.multiSelect;
  691. sel.toSingleRange(ts.firstNonLinked.clone());
  692. for (var i = ts.length; i--;) {
  693. if (ts.hasLinkedRanges && ts[i].linked)
  694. continue;
  695. sel.addRange(ts[i].clone(), true);
  696. }
  697. if (sel.ranges[0])
  698. sel.addRange(sel.ranges[0].clone());
  699. } else {
  700. this.editor.selection.setRange(ts.firstNonLinked);
  701. }
  702. this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  703. };
  704. this.addTabstops = function(tabstops, start, end) {
  705. if (!this.$openTabstops)
  706. this.$openTabstops = [];
  707. if (!tabstops[0]) {
  708. var p = Range.fromPoints(end, end);
  709. moveRelative(p.start, start);
  710. moveRelative(p.end, start);
  711. tabstops[0] = [p];
  712. tabstops[0].index = 0;
  713. }
  714. var i = this.index;
  715. var arg = [i + 1, 0];
  716. var ranges = this.ranges;
  717. tabstops.forEach(function(ts, index) {
  718. var dest = this.$openTabstops[index] || ts;
  719. for (var i = ts.length; i--;) {
  720. var p = ts[i];
  721. var range = Range.fromPoints(p.start, p.end || p.start);
  722. movePoint(range.start, start);
  723. movePoint(range.end, start);
  724. range.original = p;
  725. range.tabstop = dest;
  726. ranges.push(range);
  727. if (dest != ts)
  728. dest.unshift(range);
  729. else
  730. dest[i] = range;
  731. if (p.fmtString) {
  732. range.linked = true;
  733. dest.hasLinkedRanges = true;
  734. } else if (!dest.firstNonLinked)
  735. dest.firstNonLinked = range;
  736. }
  737. if (!dest.firstNonLinked)
  738. dest.hasLinkedRanges = false;
  739. if (dest === ts) {
  740. arg.push(dest);
  741. this.$openTabstops[index] = dest;
  742. }
  743. this.addTabstopMarkers(dest);
  744. }, this);
  745. if (arg.length > 2) {
  746. if (this.tabstops.length)
  747. arg.push(arg.splice(2, 1)[0]);
  748. this.tabstops.splice.apply(this.tabstops, arg);
  749. }
  750. };
  751. this.addTabstopMarkers = function(ts) {
  752. var session = this.editor.session;
  753. ts.forEach(function(range) {
  754. if (!range.markerId)
  755. range.markerId = session.addMarker(range, "ace_snippet-marker", "text");
  756. });
  757. };
  758. this.removeTabstopMarkers = function(ts) {
  759. var session = this.editor.session;
  760. ts.forEach(function(range) {
  761. session.removeMarker(range.markerId);
  762. range.markerId = null;
  763. });
  764. };
  765. this.removeRange = function(range) {
  766. var i = range.tabstop.indexOf(range);
  767. range.tabstop.splice(i, 1);
  768. i = this.ranges.indexOf(range);
  769. this.ranges.splice(i, 1);
  770. this.editor.session.removeMarker(range.markerId);
  771. if (!range.tabstop.length) {
  772. i = this.tabstops.indexOf(range.tabstop);
  773. if (i != -1)
  774. this.tabstops.splice(i, 1);
  775. if (!this.tabstops.length)
  776. this.detach();
  777. }
  778. };
  779. this.keyboardHandler = new HashHandler();
  780. this.keyboardHandler.bindKeys({
  781. "Tab": function(ed) {
  782. if (exports.snippetManager && exports.snippetManager.expandWithTab(ed)) {
  783. return;
  784. }
  785. ed.tabstopManager.tabNext(1);
  786. },
  787. "Shift-Tab": function(ed) {
  788. ed.tabstopManager.tabNext(-1);
  789. },
  790. "Esc": function(ed) {
  791. ed.tabstopManager.detach();
  792. },
  793. "Return": function(ed) {
  794. return false;
  795. }
  796. });
  797. }).call(TabstopManager.prototype);
  798. var changeTracker = {};
  799. changeTracker.onChange = Anchor.prototype.onChange;
  800. changeTracker.setPosition = function(row, column) {
  801. this.pos.row = row;
  802. this.pos.column = column;
  803. };
  804. changeTracker.update = function(pos, delta, $insertRight) {
  805. this.$insertRight = $insertRight;
  806. this.pos = pos;
  807. this.onChange(delta);
  808. };
  809. var movePoint = function(point, diff) {
  810. if (point.row == 0)
  811. point.column += diff.column;
  812. point.row += diff.row;
  813. };
  814. var moveRelative = function(point, start) {
  815. if (point.row == start.row)
  816. point.column -= start.column;
  817. point.row -= start.row;
  818. };
  819. acequire("./lib/dom").importCssString("\
  820. .ace_snippet-marker {\
  821. -moz-box-sizing: border-box;\
  822. box-sizing: border-box;\
  823. background: rgba(194, 193, 208, 0.09);\
  824. border: 1px dotted rgba(211, 208, 235, 0.62);\
  825. position: absolute;\
  826. }");
  827. exports.snippetManager = new SnippetManager();
  828. var Editor = acequire("./editor").Editor;
  829. (function() {
  830. this.insertSnippet = function(content, options) {
  831. return exports.snippetManager.insertSnippet(this, content, options);
  832. };
  833. this.expandSnippet = function(options) {
  834. return exports.snippetManager.expandWithTab(this, options);
  835. };
  836. }).call(Editor.prototype);
  837. });
  838. ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"], function(acequire, exports, module) {
  839. "use strict";
  840. var Renderer = acequire("../virtual_renderer").VirtualRenderer;
  841. var Editor = acequire("../editor").Editor;
  842. var Range = acequire("../range").Range;
  843. var event = acequire("../lib/event");
  844. var lang = acequire("../lib/lang");
  845. var dom = acequire("../lib/dom");
  846. var $singleLineEditor = function(el) {
  847. var renderer = new Renderer(el);
  848. renderer.$maxLines = 4;
  849. var editor = new Editor(renderer);
  850. editor.setHighlightActiveLine(false);
  851. editor.setShowPrintMargin(false);
  852. editor.renderer.setShowGutter(false);
  853. editor.renderer.setHighlightGutterLine(false);
  854. editor.$mouseHandler.$focusWaitTimout = 0;
  855. editor.$highlightTagPending = true;
  856. return editor;
  857. };
  858. var AcePopup = function(parentNode) {
  859. var el = dom.createElement("div");
  860. var popup = new $singleLineEditor(el);
  861. if (parentNode)
  862. parentNode.appendChild(el);
  863. el.style.display = "none";
  864. popup.renderer.content.style.cursor = "default";
  865. popup.renderer.setStyle("ace_autocomplete");
  866. popup.setOption("displayIndentGuides", false);
  867. popup.setOption("dragDelay", 150);
  868. var noop = function(){};
  869. popup.focus = noop;
  870. popup.$isFocused = true;
  871. popup.renderer.$cursorLayer.restartTimer = noop;
  872. popup.renderer.$cursorLayer.element.style.opacity = 0;
  873. popup.renderer.$maxLines = 8;
  874. popup.renderer.$keepTextAreaAtCursor = false;
  875. popup.setHighlightActiveLine(false);
  876. popup.session.highlight("");
  877. popup.session.$searchHighlight.clazz = "ace_highlight-marker";
  878. popup.on("mousedown", function(e) {
  879. var pos = e.getDocumentPosition();
  880. popup.selection.moveToPosition(pos);
  881. selectionMarker.start.row = selectionMarker.end.row = pos.row;
  882. e.stop();
  883. });
  884. var lastMouseEvent;
  885. var hoverMarker = new Range(-1,0,-1,Infinity);
  886. var selectionMarker = new Range(-1,0,-1,Infinity);
  887. selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine");
  888. popup.setSelectOnHover = function(val) {
  889. if (!val) {
  890. hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine");
  891. } else if (hoverMarker.id) {
  892. popup.session.removeMarker(hoverMarker.id);
  893. hoverMarker.id = null;
  894. }
  895. };
  896. popup.setSelectOnHover(false);
  897. popup.on("mousemove", function(e) {
  898. if (!lastMouseEvent) {
  899. lastMouseEvent = e;
  900. return;
  901. }
  902. if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) {
  903. return;
  904. }
  905. lastMouseEvent = e;
  906. lastMouseEvent.scrollTop = popup.renderer.scrollTop;
  907. var row = lastMouseEvent.getDocumentPosition().row;
  908. if (hoverMarker.start.row != row) {
  909. if (!hoverMarker.id)
  910. popup.setRow(row);
  911. setHoverMarker(row);
  912. }
  913. });
  914. popup.renderer.on("beforeRender", function() {
  915. if (lastMouseEvent && hoverMarker.start.row != -1) {
  916. lastMouseEvent.$pos = null;
  917. var row = lastMouseEvent.getDocumentPosition().row;
  918. if (!hoverMarker.id)
  919. popup.setRow(row);
  920. setHoverMarker(row, true);
  921. }
  922. });
  923. popup.renderer.on("afterRender", function() {
  924. var row = popup.getRow();
  925. var t = popup.renderer.$textLayer;
  926. var selected = t.element.childNodes[row - t.config.firstRow];
  927. if (selected == t.selectedNode)
  928. return;
  929. if (t.selectedNode)
  930. dom.removeCssClass(t.selectedNode, "ace_selected");
  931. t.selectedNode = selected;
  932. if (selected)
  933. dom.addCssClass(selected, "ace_selected");
  934. });
  935. var hideHoverMarker = function() { setHoverMarker(-1); };
  936. var setHoverMarker = function(row, suppressRedraw) {
  937. if (row !== hoverMarker.start.row) {
  938. hoverMarker.start.row = hoverMarker.end.row = row;
  939. if (!suppressRedraw)
  940. popup.session._emit("changeBackMarker");
  941. popup._emit("changeHoverMarker");
  942. }
  943. };
  944. popup.getHoveredRow = function() {
  945. return hoverMarker.start.row;
  946. };
  947. event.addListener(popup.container, "mouseout", hideHoverMarker);
  948. popup.on("hide", hideHoverMarker);
  949. popup.on("changeSelection", hideHoverMarker);
  950. popup.session.doc.getLength = function() {
  951. return popup.data.length;
  952. };
  953. popup.session.doc.getLine = function(i) {
  954. var data = popup.data[i];
  955. if (typeof data == "string")
  956. return data;
  957. return (data && data.value) || "";
  958. };
  959. var bgTokenizer = popup.session.bgTokenizer;
  960. bgTokenizer.$tokenizeRow = function(row) {
  961. var data = popup.data[row];
  962. var tokens = [];
  963. if (!data)
  964. return tokens;
  965. if (typeof data == "string")
  966. data = {value: data};
  967. if (!data.caption)
  968. data.caption = data.value || data.name;
  969. var last = -1;
  970. var flag, c;
  971. for (var i = 0; i < data.caption.length; i++) {
  972. c = data.caption[i];
  973. flag = data.matchMask & (1 << i) ? 1 : 0;
  974. if (last !== flag) {
  975. tokens.push({type: data.className || "" + ( flag ? "completion-highlight" : ""), value: c});
  976. last = flag;
  977. } else {
  978. tokens[tokens.length - 1].value += c;
  979. }
  980. }
  981. if (data.meta) {
  982. var maxW = popup.renderer.$size.scrollerWidth / popup.renderer.layerConfig.characterWidth;
  983. var metaData = data.meta;
  984. if (metaData.length + data.caption.length > maxW - 2) {
  985. metaData = metaData.substr(0, maxW - data.caption.length - 3) + "\u2026";
  986. }
  987. tokens.push({type: "rightAlignedText", value: metaData});
  988. }
  989. return tokens;
  990. };
  991. bgTokenizer.$updateOnChange = noop;
  992. bgTokenizer.start = noop;
  993. popup.session.$computeWidth = function() {
  994. return this.screenWidth = 0;
  995. };
  996. popup.$blockScrolling = Infinity;
  997. popup.isOpen = false;
  998. popup.isTopdown = false;
  999. popup.autoSelect = true;
  1000. popup.data = [];
  1001. popup.setData = function(list) {
  1002. popup.setValue(lang.stringRepeat("\n", list.length), -1);
  1003. popup.data = list || [];
  1004. popup.setRow(0);
  1005. };
  1006. popup.getData = function(row) {
  1007. return popup.data[row];
  1008. };
  1009. popup.getRow = function() {
  1010. return selectionMarker.start.row;
  1011. };
  1012. popup.setRow = function(line) {
  1013. line = Math.max(this.autoSelect ? 0 : -1, Math.min(this.data.length, line));
  1014. if (selectionMarker.start.row != line) {
  1015. popup.selection.clearSelection();
  1016. selectionMarker.start.row = selectionMarker.end.row = line || 0;
  1017. popup.session._emit("changeBackMarker");
  1018. popup.moveCursorTo(line || 0, 0);
  1019. if (popup.isOpen)
  1020. popup._signal("select");
  1021. }
  1022. };
  1023. popup.on("changeSelection", function() {
  1024. if (popup.isOpen)
  1025. popup.setRow(popup.selection.lead.row);
  1026. popup.renderer.scrollCursorIntoView();
  1027. });
  1028. popup.hide = function() {
  1029. this.container.style.display = "none";
  1030. this._signal("hide");
  1031. popup.isOpen = false;
  1032. };
  1033. popup.show = function(pos, lineHeight, topdownOnly) {
  1034. var el = this.container;
  1035. var screenHeight = window.innerHeight;
  1036. var screenWidth = window.innerWidth;
  1037. var renderer = this.renderer;
  1038. var maxH = renderer.$maxLines * lineHeight * 1.4;
  1039. var top = pos.top + this.$borderSize;
  1040. var allowTopdown = top > screenHeight / 2 && !topdownOnly;
  1041. if (allowTopdown && top + lineHeight + maxH > screenHeight) {
  1042. renderer.$maxPixelHeight = top - 2 * this.$borderSize;
  1043. el.style.top = "";
  1044. el.style.bottom = screenHeight - top + "px";
  1045. popup.isTopdown = false;
  1046. } else {
  1047. top += lineHeight;
  1048. renderer.$maxPixelHeight = screenHeight - top - 0.2 * lineHeight;
  1049. el.style.top = top + "px";
  1050. el.style.bottom = "";
  1051. popup.isTopdown = true;
  1052. }
  1053. el.style.display = "";
  1054. this.renderer.$textLayer.checkForSizeChanges();
  1055. var left = pos.left;
  1056. if (left + el.offsetWidth > screenWidth)
  1057. left = screenWidth - el.offsetWidth;
  1058. el.style.left = left + "px";
  1059. this._signal("show");
  1060. lastMouseEvent = null;
  1061. popup.isOpen = true;
  1062. };
  1063. popup.getTextLeftOffset = function() {
  1064. return this.$borderSize + this.renderer.$padding + this.$imageSize;
  1065. };
  1066. popup.$imageSize = 0;
  1067. popup.$borderSize = 1;
  1068. return popup;
  1069. };
  1070. dom.importCssString("\
  1071. .ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\
  1072. background-color: #CAD6FA;\
  1073. z-index: 1;\
  1074. }\
  1075. .ace_editor.ace_autocomplete .ace_line-hover {\
  1076. border: 1px solid #abbffe;\
  1077. margin-top: -1px;\
  1078. background: rgba(233,233,253,0.4);\
  1079. }\
  1080. .ace_editor.ace_autocomplete .ace_line-hover {\
  1081. position: absolute;\
  1082. z-index: 2;\
  1083. }\
  1084. .ace_editor.ace_autocomplete .ace_scroller {\
  1085. background: none;\
  1086. border: none;\
  1087. box-shadow: none;\
  1088. }\
  1089. .ace_rightAlignedText {\
  1090. color: gray;\
  1091. display: inline-block;\
  1092. position: absolute;\
  1093. right: 4px;\
  1094. text-align: right;\
  1095. z-index: -1;\
  1096. }\
  1097. .ace_editor.ace_autocomplete .ace_completion-highlight{\
  1098. color: #000;\
  1099. text-shadow: 0 0 0.01em;\
  1100. }\
  1101. .ace_editor.ace_autocomplete {\
  1102. width: 280px;\
  1103. z-index: 200000;\
  1104. background: #fbfbfb;\
  1105. color: #444;\
  1106. border: 1px lightgray solid;\
  1107. position: fixed;\
  1108. box-shadow: 2px 3px 5px rgba(0,0,0,.2);\
  1109. line-height: 1.4;\
  1110. }");
  1111. exports.AcePopup = AcePopup;
  1112. });
  1113. ace.define("ace/autocomplete/util",["require","exports","module"], function(acequire, exports, module) {
  1114. "use strict";
  1115. exports.parForEach = function(array, fn, callback) {
  1116. var completed = 0;
  1117. var arLength = array.length;
  1118. if (arLength === 0)
  1119. callback();
  1120. for (var i = 0; i < arLength; i++) {
  1121. fn(array[i], function(result, err) {
  1122. completed++;
  1123. if (completed === arLength)
  1124. callback(result, err);
  1125. });
  1126. }
  1127. };
  1128. var ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\uFFFF]/;
  1129. exports.retrievePrecedingIdentifier = function(text, pos, regex) {
  1130. regex = regex || ID_REGEX;
  1131. var buf = [];
  1132. for (var i = pos-1; i >= 0; i--) {
  1133. if (regex.test(text[i]))
  1134. buf.push(text[i]);
  1135. else
  1136. break;
  1137. }
  1138. return buf.reverse().join("");
  1139. };
  1140. exports.retrieveFollowingIdentifier = function(text, pos, regex) {
  1141. regex = regex || ID_REGEX;
  1142. var buf = [];
  1143. for (var i = pos; i < text.length; i++) {
  1144. if (regex.test(text[i]))
  1145. buf.push(text[i]);
  1146. else
  1147. break;
  1148. }
  1149. return buf;
  1150. };
  1151. exports.getCompletionPrefix = function (editor) {
  1152. var pos = editor.getCursorPosition();
  1153. var line = editor.session.getLine(pos.row);
  1154. var prefix;
  1155. editor.completers.forEach(function(completer) {
  1156. if (completer.identifierRegexps) {
  1157. completer.identifierRegexps.forEach(function(identifierRegex) {
  1158. if (!prefix && identifierRegex)
  1159. prefix = this.retrievePrecedingIdentifier(line, pos.column, identifierRegex);
  1160. }.bind(this));
  1161. }
  1162. }.bind(this));
  1163. return prefix || this.retrievePrecedingIdentifier(line, pos.column);
  1164. };
  1165. });
  1166. ace.define("ace/autocomplete",["require","exports","module","ace/keyboard/hash_handler","ace/autocomplete/popup","ace/autocomplete/util","ace/lib/event","ace/lib/lang","ace/lib/dom","ace/snippets"], function(acequire, exports, module) {
  1167. "use strict";
  1168. var HashHandler = acequire("./keyboard/hash_handler").HashHandler;
  1169. var AcePopup = acequire("./autocomplete/popup").AcePopup;
  1170. var util = acequire("./autocomplete/util");
  1171. var event = acequire("./lib/event");
  1172. var lang = acequire("./lib/lang");
  1173. var dom = acequire("./lib/dom");
  1174. var snippetManager = acequire("./snippets").snippetManager;
  1175. var Autocomplete = function() {
  1176. this.autoInsert = false;
  1177. this.autoSelect = true;
  1178. this.exactMatch = false;
  1179. this.gatherCompletionsId = 0;
  1180. this.keyboardHandler = new HashHandler();
  1181. this.keyboardHandler.bindKeys(this.commands);
  1182. this.blurListener = this.blurListener.bind(this);
  1183. this.changeListener = this.changeListener.bind(this);
  1184. this.mousedownListener = this.mousedownListener.bind(this);
  1185. this.mousewheelListener = this.mousewheelListener.bind(this);
  1186. this.changeTimer = lang.delayedCall(function() {
  1187. this.updateCompletions(true);
  1188. }.bind(this));
  1189. this.tooltipTimer = lang.delayedCall(this.updateDocTooltip.bind(this), 50);
  1190. };
  1191. (function() {
  1192. this.$init = function() {
  1193. this.popup = new AcePopup(document.body || document.documentElement);
  1194. this.popup.on("click", function(e) {
  1195. this.insertMatch();
  1196. e.stop();
  1197. }.bind(this));
  1198. this.popup.focus = this.editor.focus.bind(this.editor);
  1199. this.popup.on("show", this.tooltipTimer.bind(null, null));
  1200. this.popup.on("select", this.tooltipTimer.bind(null, null));
  1201. this.popup.on("changeHoverMarker", this.tooltipTimer.bind(null, null));
  1202. return this.popup;
  1203. };
  1204. this.getPopup = function() {
  1205. return this.popup || this.$init();
  1206. };
  1207. this.openPopup = function(editor, prefix, keepPopupPosition) {
  1208. if (!this.popup)
  1209. this.$init();
  1210. this.popup.autoSelect = this.autoSelect;
  1211. this.popup.setData(this.completions.filtered);
  1212. editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  1213. var renderer = editor.renderer;
  1214. this.popup.setRow(this.autoSelect ? 0 : -1);
  1215. if (!keepPopupPosition) {
  1216. this.popup.setTheme(editor.getTheme());
  1217. this.popup.setFontSize(editor.getFontSize());
  1218. var lineHeight = renderer.layerConfig.lineHeight;
  1219. var pos = renderer.$cursorLayer.getPixelPosition(this.base, true);
  1220. pos.left -= this.popup.getTextLeftOffset();
  1221. var rect = editor.container.getBoundingClientRect();
  1222. pos.top += rect.top - renderer.layerConfig.offset;
  1223. pos.left += rect.left - editor.renderer.scrollLeft;
  1224. pos.left += renderer.gutterWidth;
  1225. this.popup.show(pos, lineHeight);
  1226. } else if (keepPopupPosition && !prefix) {
  1227. this.detach();
  1228. }
  1229. };
  1230. this.detach = function() {
  1231. this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
  1232. this.editor.off("changeSelection", this.changeListener);
  1233. this.editor.off("blur", this.blurListener);
  1234. this.editor.off("mousedown", this.mousedownListener);
  1235. this.editor.off("mousewheel", this.mousewheelListener);
  1236. this.changeTimer.cancel();
  1237. this.hideDocTooltip();
  1238. this.gatherCompletionsId += 1;
  1239. if (this.popup && this.popup.isOpen)
  1240. this.popup.hide();
  1241. if (this.base)
  1242. this.base.detach();
  1243. this.activated = false;
  1244. this.completions = this.base = null;
  1245. };
  1246. this.changeListener = function(e) {
  1247. var cursor = this.editor.selection.lead;
  1248. if (cursor.row != this.base.row || cursor.column < this.base.column) {
  1249. this.detach();
  1250. }
  1251. if (this.activated)
  1252. this.changeTimer.schedule();
  1253. else
  1254. this.detach();
  1255. };
  1256. this.blurListener = function(e) {
  1257. var el = document.activeElement;
  1258. var text = this.editor.textInput.getElement();
  1259. var fromTooltip = e.relatedTarget && this.tooltipNode && this.tooltipNode.contains(e.relatedTarget);
  1260. var container = this.popup && this.popup.container;
  1261. if (el != text && el.parentNode != container && !fromTooltip
  1262. && el != this.tooltipNode && e.relatedTarget != text
  1263. ) {
  1264. this.detach();
  1265. }
  1266. };
  1267. this.mousedownListener = function(e) {
  1268. this.detach();
  1269. };
  1270. this.mousewheelListener = function(e) {
  1271. this.detach();
  1272. };
  1273. this.goTo = function(where) {
  1274. var row = this.popup.getRow();
  1275. var max = this.popup.session.getLength() - 1;
  1276. switch(where) {
  1277. case "up": row = row <= 0 ? max : row - 1; break;
  1278. case "down": row = row >= max ? -1 : row + 1; break;
  1279. case "start": row = 0; break;
  1280. case "end": row = max; break;
  1281. }
  1282. this.popup.setRow(row);
  1283. };
  1284. this.insertMatch = function(data, options) {
  1285. if (!data)
  1286. data = this.popup.getData(this.popup.getRow());
  1287. if (!data)
  1288. return false;
  1289. if (data.completer && data.completer.insertMatch) {
  1290. data.completer.insertMatch(this.editor, data);
  1291. } else {
  1292. if (this.completions.filterText) {
  1293. var ranges = this.editor.selection.getAllRanges();
  1294. for (var i = 0, range; range = ranges[i]; i++) {
  1295. range.start.column -= this.completions.filterText.length;
  1296. this.editor.session.remove(range);
  1297. }
  1298. }
  1299. if (data.snippet)
  1300. snippetManager.insertSnippet(this.editor, data.snippet);
  1301. else
  1302. this.editor.execCommand("insertstring", data.value || data);
  1303. }
  1304. this.detach();
  1305. };
  1306. this.commands = {
  1307. "Up": function(editor) { editor.completer.goTo("up"); },
  1308. "Down": function(editor) { editor.completer.goTo("down"); },
  1309. "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); },
  1310. "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); },
  1311. "Esc": function(editor) { editor.completer.detach(); },
  1312. "Return": function(editor) { return editor.completer.insertMatch(); },
  1313. "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); },
  1314. "Tab": function(editor) {
  1315. var result = editor.completer.insertMatch();
  1316. if (!result && !editor.tabstopManager)
  1317. editor.completer.goTo("down");
  1318. else
  1319. return result;
  1320. },
  1321. "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); },
  1322. "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); }
  1323. };
  1324. this.gatherCompletions = function(editor, callback) {
  1325. var session = editor.getSession();
  1326. var pos = editor.getCursorPosition();
  1327. var prefix = util.getCompletionPrefix(editor);
  1328. this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length);
  1329. this.base.$insertRight = true;
  1330. var matches = [];
  1331. var total = editor.completers.length;
  1332. editor.completers.forEach(function(completer, i) {
  1333. completer.getCompletions(editor, session, pos, prefix, function(err, results) {
  1334. if (!err && results)
  1335. matches = matches.concat(results);
  1336. callback(null, {
  1337. prefix: util.getCompletionPrefix(editor),
  1338. matches: matches,
  1339. finished: (--total === 0)
  1340. });
  1341. });
  1342. });
  1343. return true;
  1344. };
  1345. this.showPopup = function(editor) {
  1346. if (this.editor)
  1347. this.detach();
  1348. this.activated = true;
  1349. this.editor = editor;
  1350. if (editor.completer != this) {
  1351. if (editor.completer)
  1352. editor.completer.detach();
  1353. editor.completer = this;
  1354. }
  1355. editor.on("changeSelection", this.changeListener);
  1356. editor.on("blur", this.blurListener);
  1357. editor.on("mousedown", this.mousedownListener);
  1358. editor.on("mousewheel", this.mousewheelListener);
  1359. this.updateCompletions();
  1360. };
  1361. this.updateCompletions = function(keepPopupPosition) {
  1362. if (keepPopupPosition && this.base && this.completions) {
  1363. var pos = this.editor.getCursorPosition();
  1364. var prefix = this.editor.session.getTextRange({start: this.base, end: pos});
  1365. if (prefix == this.completions.filterText)
  1366. return;
  1367. this.completions.setFilter(prefix);
  1368. if (!this.completions.filtered.length)
  1369. return this.detach();
  1370. if (this.completions.filtered.length == 1
  1371. && this.completions.filtered[0].value == prefix
  1372. && !this.completions.filtered[0].snippet)
  1373. return this.detach();
  1374. this.openPopup(this.editor, prefix, keepPopupPosition);
  1375. return;
  1376. }
  1377. var _id = this.gatherCompletionsId;
  1378. this.gatherCompletions(this.editor, function(err, results) {
  1379. var detachIfFinished = function() {
  1380. if (!results.finished) return;
  1381. return this.detach();
  1382. }.bind(this);
  1383. var prefix = results.prefix;
  1384. var matches = results && results.matches;
  1385. if (!matches || !matches.length)
  1386. return detachIfFinished();
  1387. if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId)
  1388. return;
  1389. this.completions = new FilteredList(matches);
  1390. if (this.exactMatch)
  1391. this.completions.exactMatch = true;
  1392. this.completions.setFilter(prefix);
  1393. var filtered = this.completions.filtered;
  1394. if (!filtered.length)
  1395. return detachIfFinished();
  1396. if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet)
  1397. return detachIfFinished();
  1398. if (this.autoInsert && filtered.length == 1 && results.finished)
  1399. return this.insertMatch(filtered[0]);
  1400. this.openPopup(this.editor, prefix, keepPopupPosition);
  1401. }.bind(this));
  1402. };
  1403. this.cancelContextMenu = function() {
  1404. this.editor.$mouseHandler.cancelContextMenu();
  1405. };
  1406. this.updateDocTooltip = function() {
  1407. var popup = this.popup;
  1408. var all = popup.data;
  1409. var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]);
  1410. var doc = null;
  1411. if (!selected || !this.editor || !this.popup.isOpen)
  1412. return this.hideDocTooltip();
  1413. this.editor.completers.some(function(completer) {
  1414. if (completer.getDocTooltip)
  1415. doc = completer.getDocTooltip(selected);
  1416. return doc;
  1417. });
  1418. if (!doc)
  1419. doc = selected;
  1420. if (typeof doc == "string")
  1421. doc = {docText: doc};
  1422. if (!doc || !(doc.docHTML || doc.docText))
  1423. return this.hideDocTooltip();
  1424. this.showDocTooltip(doc);
  1425. };
  1426. this.showDocTooltip = function(item) {
  1427. if (!this.tooltipNode) {
  1428. this.tooltipNode = dom.createElement("div");
  1429. this.tooltipNode.className = "ace_tooltip ace_doc-tooltip";
  1430. this.tooltipNode.style.margin = 0;
  1431. this.tooltipNode.style.pointerEvents = "auto";
  1432. this.tooltipNode.tabIndex = -1;
  1433. this.tooltipNode.onblur = this.blurListener.bind(this);
  1434. this.tooltipNode.onclick = this.onTooltipClick.bind(this);
  1435. }
  1436. var tooltipNode = this.tooltipNode;
  1437. if (item.docHTML) {
  1438. tooltipNode.innerHTML = item.docHTML;
  1439. } else if (item.docText) {
  1440. tooltipNode.textContent = item.docText;
  1441. }
  1442. if (!tooltipNode.parentNode)
  1443. document.body.appendChild(tooltipNode);
  1444. var popup = this.popup;
  1445. var rect = popup.container.getBoundingClientRect();
  1446. tooltipNode.style.top = popup.container.style.top;
  1447. tooltipNode.style.bottom = popup.container.style.bottom;
  1448. if (window.innerWidth - rect.right < 320) {
  1449. tooltipNode.style.right = window.innerWidth - rect.left + "px";
  1450. tooltipNode.style.left = "";
  1451. } else {
  1452. tooltipNode.style.left = (rect.right + 1) + "px";
  1453. tooltipNode.style.right = "";
  1454. }
  1455. tooltipNode.style.display = "block";
  1456. };
  1457. this.hideDocTooltip = function() {
  1458. this.tooltipTimer.cancel();
  1459. if (!this.tooltipNode) return;
  1460. var el = this.tooltipNode;
  1461. if (!this.editor.isFocused() && document.activeElement == el)
  1462. this.editor.focus();
  1463. this.tooltipNode = null;
  1464. if (el.parentNode)
  1465. el.parentNode.removeChild(el);
  1466. };
  1467. this.onTooltipClick = function(e) {
  1468. var a = e.target;
  1469. while (a && a != this.tooltipNode) {
  1470. if (a.nodeName == "A" && a.href) {
  1471. a.rel = "noreferrer";
  1472. a.target = "_blank";
  1473. break;
  1474. }
  1475. a = a.parentNode;
  1476. }
  1477. };
  1478. }).call(Autocomplete.prototype);
  1479. Autocomplete.startCommand = {
  1480. name: "startAutocomplete",
  1481. exec: function(editor) {
  1482. if (!editor.completer)
  1483. editor.completer = new Autocomplete();
  1484. editor.completer.autoInsert = false;
  1485. editor.completer.autoSelect = true;
  1486. editor.completer.showPopup(editor);
  1487. editor.completer.cancelContextMenu();
  1488. },
  1489. bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space"
  1490. };
  1491. var FilteredList = function(array, filterText) {
  1492. this.all = array;
  1493. this.filtered = array;
  1494. this.filterText = filterText || "";
  1495. this.exactMatch = false;
  1496. };
  1497. (function(){
  1498. this.setFilter = function(str) {
  1499. if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0)
  1500. var matches = this.filtered;
  1501. else
  1502. var matches = this.all;
  1503. this.filterText = str;
  1504. matches = this.filterCompletions(matches, this.filterText);
  1505. matches = matches.sort(function(a, b) {
  1506. return b.exactMatch - a.exactMatch || b.score - a.score;
  1507. });
  1508. var prev = null;
  1509. matches = matches.filter(function(item){
  1510. var caption = item.snippet || item.caption || item.value;
  1511. if (caption === prev) return false;
  1512. prev = caption;
  1513. return true;
  1514. });
  1515. this.filtered = matches;
  1516. };
  1517. this.filterCompletions = function(items, needle) {
  1518. var results = [];
  1519. var upper = needle.toUpperCase();
  1520. var lower = needle.toLowerCase();
  1521. loop: for (var i = 0, item; item = items[i]; i++) {
  1522. var caption = item.value || item.caption || item.snippet;
  1523. if (!caption) continue;
  1524. var lastIndex = -1;
  1525. var matchMask = 0;
  1526. var penalty = 0;
  1527. var index, distance;
  1528. if (this.exactMatch) {
  1529. if (needle !== caption.substr(0, needle.length))
  1530. continue loop;
  1531. }else{
  1532. for (var j = 0; j < needle.length; j++) {
  1533. var i1 = caption.indexOf(lower[j], lastIndex + 1);
  1534. var i2 = caption.indexOf(upper[j], lastIndex + 1);
  1535. index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2;
  1536. if (index < 0)
  1537. continue loop;
  1538. distance = index - lastIndex - 1;
  1539. if (distance > 0) {
  1540. if (lastIndex === -1)
  1541. penalty += 10;
  1542. penalty += distance;
  1543. }
  1544. matchMask = matchMask | (1 << index);
  1545. lastIndex = index;
  1546. }
  1547. }
  1548. item.matchMask = matchMask;
  1549. item.exactMatch = penalty ? 0 : 1;
  1550. item.score = (item.score || 0) - penalty;
  1551. results.push(item);
  1552. }
  1553. return results;
  1554. };
  1555. }).call(FilteredList.prototype);
  1556. exports.Autocomplete = Autocomplete;
  1557. exports.FilteredList = FilteredList;
  1558. });
  1559. ace.define("ace/autocomplete/text_completer",["require","exports","module","ace/range"], function(acequire, exports, module) {
  1560. var Range = acequire("../range").Range;
  1561. var splitRegex = /[^a-zA-Z_0-9\$\-\u00C0-\u1FFF\u2C00-\uD7FF\w]+/;
  1562. function getWordIndex(doc, pos) {
  1563. var textBefore = doc.getTextRange(Range.fromPoints({row: 0, column:0}, pos));
  1564. return textBefore.split(splitRegex).length - 1;
  1565. }
  1566. function wordDistance(doc, pos) {
  1567. var prefixPos = getWordIndex(doc, pos);
  1568. var words = doc.getValue().split(splitRegex);
  1569. var wordScores = Object.create(null);
  1570. var currentWord = words[prefixPos];
  1571. words.forEach(function(word, idx) {
  1572. if (!word || word === currentWord) return;
  1573. var distance = Math.abs(prefixPos - idx);
  1574. var score = words.length - distance;
  1575. if (wordScores[word]) {
  1576. wordScores[word] = Math.max(score, wordScores[word]);
  1577. } else {
  1578. wordScores[word] = score;
  1579. }
  1580. });
  1581. return wordScores;
  1582. }
  1583. exports.getCompletions = function(editor, session, pos, prefix, callback) {
  1584. var wordScore = wordDistance(session, pos, prefix);
  1585. var wordList = Object.keys(wordScore);
  1586. callback(null, wordList.map(function(word) {
  1587. return {
  1588. caption: word,
  1589. value: word,
  1590. score: wordScore[word],
  1591. meta: "local"
  1592. };
  1593. }));
  1594. };
  1595. });
  1596. ace.define("ace/ext/language_tools",["require","exports","module","ace/snippets","ace/autocomplete","ace/config","ace/lib/lang","ace/autocomplete/util","ace/autocomplete/text_completer","ace/editor","ace/config"], function(acequire, exports, module) {
  1597. "use strict";
  1598. var snippetManager = acequire("../snippets").snippetManager;
  1599. var Autocomplete = acequire("../autocomplete").Autocomplete;
  1600. var config = acequire("../config");
  1601. var lang = acequire("../lib/lang");
  1602. var util = acequire("../autocomplete/util");
  1603. var textCompleter = acequire("../autocomplete/text_completer");
  1604. var keyWordCompleter = {
  1605. getCompletions: function(editor, session, pos, prefix, callback) {
  1606. if (session.$mode.completer) {
  1607. return session.$mode.completer.getCompletions(editor, session, pos, prefix, callback);
  1608. }
  1609. var state = editor.session.getState(pos.row);
  1610. var completions = session.$mode.getCompletions(state, session, pos, prefix);
  1611. callback(null, completions);
  1612. }
  1613. };
  1614. var snippetCompleter = {
  1615. getCompletions: function(editor, session, pos, prefix, callback) {
  1616. var snippetMap = snippetManager.snippetMap;
  1617. var completions = [];
  1618. snippetManager.getActiveScopes(editor).forEach(function(scope) {
  1619. var snippets = snippetMap[scope] || [];
  1620. for (var i = snippets.length; i--;) {
  1621. var s = snippets[i];
  1622. var caption = s.name || s.tabTrigger;
  1623. if (!caption)
  1624. continue;
  1625. completions.push({
  1626. caption: caption,
  1627. snippet: s.content,
  1628. meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet",
  1629. type: "snippet"
  1630. });
  1631. }
  1632. }, this);
  1633. callback(null, completions);
  1634. },
  1635. getDocTooltip: function(item) {
  1636. if (item.type == "snippet" && !item.docHTML) {
  1637. item.docHTML = [
  1638. "<b>", lang.escapeHTML(item.caption), "</b>", "<hr></hr>",
  1639. lang.escapeHTML(item.snippet)
  1640. ].join("");
  1641. }
  1642. }
  1643. };
  1644. var completers = [snippetCompleter, textCompleter, keyWordCompleter];
  1645. exports.setCompleters = function(val) {
  1646. completers.length = 0;
  1647. if (val) completers.push.apply(completers, val);
  1648. };
  1649. exports.addCompleter = function(completer) {
  1650. completers.push(completer);
  1651. };
  1652. exports.textCompleter = textCompleter;
  1653. exports.keyWordCompleter = keyWordCompleter;
  1654. exports.snippetCompleter = snippetCompleter;
  1655. var expandSnippet = {
  1656. name: "expandSnippet",
  1657. exec: function(editor) {
  1658. return snippetManager.expandWithTab(editor);
  1659. },
  1660. bindKey: "Tab"
  1661. };
  1662. var onChangeMode = function(e, editor) {
  1663. loadSnippetsForMode(editor.session.$mode);
  1664. };
  1665. var loadSnippetsForMode = function(mode) {
  1666. var id = mode.$id;
  1667. if (!snippetManager.files)
  1668. snippetManager.files = {};
  1669. loadSnippetFile(id);
  1670. if (mode.modes)
  1671. mode.modes.forEach(loadSnippetsForMode);
  1672. };
  1673. var loadSnippetFile = function(id) {
  1674. if (!id || snippetManager.files[id])
  1675. return;
  1676. var snippetFilePath = id.replace("mode", "snippets");
  1677. snippetManager.files[id] = {};
  1678. config.loadModule(snippetFilePath, function(m) {
  1679. if (m) {
  1680. snippetManager.files[id] = m;
  1681. if (!m.snippets && m.snippetText)
  1682. m.snippets = snippetManager.parseSnippetFile(m.snippetText);
  1683. snippetManager.register(m.snippets || [], m.scope);
  1684. if (m.includeScopes) {
  1685. snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes;
  1686. m.includeScopes.forEach(function(x) {
  1687. loadSnippetFile("ace/mode/" + x);
  1688. });
  1689. }
  1690. }
  1691. });
  1692. };
  1693. var doLiveAutocomplete = function(e) {
  1694. var editor = e.editor;
  1695. var hasCompleter = editor.completer && editor.completer.activated;
  1696. if (e.command.name === "backspace") {
  1697. if (hasCompleter && !util.getCompletionPrefix(editor))
  1698. editor.completer.detach();
  1699. }
  1700. else if (e.command.name === "insertstring") {
  1701. var prefix = util.getCompletionPrefix(editor);
  1702. if (prefix && !hasCompleter) {
  1703. if (!editor.completer) {
  1704. editor.completer = new Autocomplete();
  1705. }
  1706. editor.completer.autoInsert = false;
  1707. editor.completer.showPopup(editor);
  1708. }
  1709. }
  1710. };
  1711. var Editor = acequire("../editor").Editor;
  1712. acequire("../config").defineOptions(Editor.prototype, "editor", {
  1713. enableBasicAutocompletion: {
  1714. set: function(val) {
  1715. if (val) {
  1716. if (!this.completers)
  1717. this.completers = Array.isArray(val)? val: completers;
  1718. this.commands.addCommand(Autocomplete.startCommand);
  1719. } else {
  1720. this.commands.removeCommand(Autocomplete.startCommand);
  1721. }
  1722. },
  1723. value: false
  1724. },
  1725. enableLiveAutocompletion: {
  1726. set: function(val) {
  1727. if (val) {
  1728. if (!this.completers)
  1729. this.completers = Array.isArray(val)? val: completers;
  1730. this.commands.on('afterExec', doLiveAutocomplete);
  1731. } else {
  1732. this.commands.removeListener('afterExec', doLiveAutocomplete);
  1733. }
  1734. },
  1735. value: false
  1736. },
  1737. enableSnippets: {
  1738. set: function(val) {
  1739. if (val) {
  1740. this.commands.addCommand(expandSnippet);
  1741. this.on("changeMode", onChangeMode);
  1742. onChangeMode(null, this);
  1743. } else {
  1744. this.commands.removeCommand(expandSnippet);
  1745. this.off("changeMode", onChangeMode);
  1746. }
  1747. },
  1748. value: false
  1749. }
  1750. });
  1751. });
  1752. (function() {
  1753. ace.acequire(["ace/ext/language_tools"], function() {});
  1754. })();