ext-language_tools.js 61 KB

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