ext-language_tools.js 75 KB

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