ext-language_tools.js 74 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129
  1. define("ace/snippets",["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(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 RangeList = require("./range_list").RangeList;
  8. var HashHandler = require("./keyboard/hash_handler").HashHandler;
  9. var Tokenizer = require("./tokenizer").Tokenizer;
  10. var clipboard = 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.tabTrigger && !s.trigger) {
  576. if (!s.guard && /^\w/.test(s.tabTrigger))
  577. s.guard = "\\b";
  578. s.trigger = lang.escapeRegExp(s.tabTrigger);
  579. }
  580. if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard)
  581. return;
  582. s.startRe = guardedRegexp(s.trigger, s.guard, true);
  583. s.triggerRe = new RegExp(s.trigger);
  584. s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true);
  585. s.endTriggerRe = new RegExp(s.endTrigger);
  586. }
  587. if (snippets && snippets.content)
  588. addSnippet(snippets);
  589. else if (Array.isArray(snippets))
  590. snippets.forEach(addSnippet);
  591. this._signal("registerSnippets", {scope: scope});
  592. };
  593. this.unregister = function(snippets, scope) {
  594. var snippetMap = this.snippetMap;
  595. var snippetNameMap = this.snippetNameMap;
  596. function removeSnippet(s) {
  597. var nameMap = snippetNameMap[s.scope||scope];
  598. if (nameMap && nameMap[s.name]) {
  599. delete nameMap[s.name];
  600. var map = snippetMap[s.scope||scope];
  601. var i = map && map.indexOf(s);
  602. if (i >= 0)
  603. map.splice(i, 1);
  604. }
  605. }
  606. if (snippets.content)
  607. removeSnippet(snippets);
  608. else if (Array.isArray(snippets))
  609. snippets.forEach(removeSnippet);
  610. };
  611. this.parseSnippetFile = function(str) {
  612. str = str.replace(/\r/g, "");
  613. var list = [], snippet = {};
  614. var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;
  615. var m;
  616. while (m = re.exec(str)) {
  617. if (m[1]) {
  618. try {
  619. snippet = JSON.parse(m[1]);
  620. list.push(snippet);
  621. } catch (e) {}
  622. } if (m[4]) {
  623. snippet.content = m[4].replace(/^\t/gm, "");
  624. list.push(snippet);
  625. snippet = {};
  626. } else {
  627. var key = m[2], val = m[3];
  628. if (key == "regex") {
  629. var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g;
  630. snippet.guard = guardRe.exec(val)[1];
  631. snippet.trigger = guardRe.exec(val)[1];
  632. snippet.endTrigger = guardRe.exec(val)[1];
  633. snippet.endGuard = guardRe.exec(val)[1];
  634. } else if (key == "snippet") {
  635. snippet.tabTrigger = val.match(/^\S*/)[0];
  636. if (!snippet.name)
  637. snippet.name = val;
  638. } else {
  639. snippet[key] = val;
  640. }
  641. }
  642. }
  643. return list;
  644. };
  645. this.getSnippetByName = function(name, editor) {
  646. var snippetMap = this.snippetNameMap;
  647. var snippet;
  648. this.getActiveScopes(editor).some(function(scope) {
  649. var snippets = snippetMap[scope];
  650. if (snippets)
  651. snippet = snippets[name];
  652. return !!snippet;
  653. }, this);
  654. return snippet;
  655. };
  656. }).call(SnippetManager.prototype);
  657. var TabstopManager = function(editor) {
  658. if (editor.tabstopManager)
  659. return editor.tabstopManager;
  660. editor.tabstopManager = this;
  661. this.$onChange = this.onChange.bind(this);
  662. this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule;
  663. this.$onChangeSession = this.onChangeSession.bind(this);
  664. this.$onAfterExec = this.onAfterExec.bind(this);
  665. this.attach(editor);
  666. };
  667. (function() {
  668. this.attach = function(editor) {
  669. this.index = 0;
  670. this.ranges = [];
  671. this.tabstops = [];
  672. this.$openTabstops = null;
  673. this.selectedTabstop = null;
  674. this.editor = editor;
  675. this.editor.on("change", this.$onChange);
  676. this.editor.on("changeSelection", this.$onChangeSelection);
  677. this.editor.on("changeSession", this.$onChangeSession);
  678. this.editor.commands.on("afterExec", this.$onAfterExec);
  679. this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  680. };
  681. this.detach = function() {
  682. this.tabstops.forEach(this.removeTabstopMarkers, this);
  683. this.ranges = null;
  684. this.tabstops = null;
  685. this.selectedTabstop = null;
  686. this.editor.removeListener("change", this.$onChange);
  687. this.editor.removeListener("changeSelection", this.$onChangeSelection);
  688. this.editor.removeListener("changeSession", this.$onChangeSession);
  689. this.editor.commands.removeListener("afterExec", this.$onAfterExec);
  690. this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
  691. this.editor.tabstopManager = null;
  692. this.editor = null;
  693. };
  694. this.onChange = function(delta) {
  695. var isRemove = delta.action[0] == "r";
  696. var selectedTabstop = this.selectedTabstop || {};
  697. var parents = selectedTabstop.parents || {};
  698. var tabstops = (this.tabstops || []).slice();
  699. for (var i = 0; i < tabstops.length; i++) {
  700. var ts = tabstops[i];
  701. var active = ts == selectedTabstop || parents[ts.index];
  702. ts.rangeList.$bias = active ? 0 : 1;
  703. if (delta.action == "remove" && ts !== selectedTabstop) {
  704. var parentActive = ts.parents && ts.parents[selectedTabstop.index];
  705. var startIndex = ts.rangeList.pointIndex(delta.start, parentActive);
  706. startIndex = startIndex < 0 ? -startIndex - 1 : startIndex + 1;
  707. var endIndex = ts.rangeList.pointIndex(delta.end, parentActive);
  708. endIndex = endIndex < 0 ? -endIndex - 1 : endIndex - 1;
  709. var toRemove = ts.rangeList.ranges.slice(startIndex, endIndex);
  710. for (var j = 0; j < toRemove.length; j++)
  711. this.removeRange(toRemove[j]);
  712. }
  713. ts.rangeList.$onChange(delta);
  714. }
  715. var session = this.editor.session;
  716. if (!this.$inChange && isRemove && session.getLength() == 1 && !session.getValue())
  717. this.detach();
  718. };
  719. this.updateLinkedFields = function() {
  720. var ts = this.selectedTabstop;
  721. if (!ts || !ts.hasLinkedRanges || !ts.firstNonLinked)
  722. return;
  723. this.$inChange = true;
  724. var session = this.editor.session;
  725. var text = session.getTextRange(ts.firstNonLinked);
  726. for (var i = 0; i < ts.length; i++) {
  727. var range = ts[i];
  728. if (!range.linked)
  729. continue;
  730. var original = range.original;
  731. var fmt = exports.snippetManager.tmStrFormat(text, original, this.editor);
  732. session.replace(range, fmt);
  733. }
  734. this.$inChange = false;
  735. };
  736. this.onAfterExec = function(e) {
  737. if (e.command && !e.command.readOnly)
  738. this.updateLinkedFields();
  739. };
  740. this.onChangeSelection = function() {
  741. if (!this.editor)
  742. return;
  743. var lead = this.editor.selection.lead;
  744. var anchor = this.editor.selection.anchor;
  745. var isEmpty = this.editor.selection.isEmpty();
  746. for (var i = 0; i < this.ranges.length; i++) {
  747. if (this.ranges[i].linked)
  748. continue;
  749. var containsLead = this.ranges[i].contains(lead.row, lead.column);
  750. var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column);
  751. if (containsLead && containsAnchor)
  752. return;
  753. }
  754. this.detach();
  755. };
  756. this.onChangeSession = function() {
  757. this.detach();
  758. };
  759. this.tabNext = function(dir) {
  760. var max = this.tabstops.length;
  761. var index = this.index + (dir || 1);
  762. index = Math.min(Math.max(index, 1), max);
  763. if (index == max)
  764. index = 0;
  765. this.selectTabstop(index);
  766. if (index === 0)
  767. this.detach();
  768. };
  769. this.selectTabstop = function(index) {
  770. this.$openTabstops = null;
  771. var ts = this.tabstops[this.index];
  772. if (ts)
  773. this.addTabstopMarkers(ts);
  774. this.index = index;
  775. ts = this.tabstops[this.index];
  776. if (!ts || !ts.length)
  777. return;
  778. this.selectedTabstop = ts;
  779. var range = ts.firstNonLinked || ts;
  780. if (!this.editor.inVirtualSelectionMode) {
  781. var sel = this.editor.multiSelect;
  782. sel.toSingleRange(range.clone());
  783. for (var i = 0; i < ts.length; i++) {
  784. if (ts.hasLinkedRanges && ts[i].linked)
  785. continue;
  786. sel.addRange(ts[i].clone(), true);
  787. }
  788. if (sel.ranges[0])
  789. sel.addRange(sel.ranges[0].clone());
  790. } else {
  791. this.editor.selection.setRange(range);
  792. }
  793. this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  794. if (this.selectedTabstop && this.selectedTabstop.choices)
  795. this.editor.execCommand("startAutocomplete", {matches: this.selectedTabstop.choices});
  796. };
  797. this.addTabstops = function(tabstops, start, end) {
  798. var useLink = this.useLink || !this.editor.getOption("enableMultiselect");
  799. if (!this.$openTabstops)
  800. this.$openTabstops = [];
  801. if (!tabstops[0]) {
  802. var p = Range.fromPoints(end, end);
  803. moveRelative(p.start, start);
  804. moveRelative(p.end, start);
  805. tabstops[0] = [p];
  806. tabstops[0].index = 0;
  807. }
  808. var i = this.index;
  809. var arg = [i + 1, 0];
  810. var ranges = this.ranges;
  811. tabstops.forEach(function(ts, index) {
  812. var dest = this.$openTabstops[index] || ts;
  813. for (var i = 0; i < ts.length; i++) {
  814. var p = ts[i];
  815. var range = Range.fromPoints(p.start, p.end || p.start);
  816. movePoint(range.start, start);
  817. movePoint(range.end, start);
  818. range.original = p;
  819. range.tabstop = dest;
  820. ranges.push(range);
  821. if (dest != ts)
  822. dest.unshift(range);
  823. else
  824. dest[i] = range;
  825. if (p.fmtString || (dest.firstNonLinked && useLink)) {
  826. range.linked = true;
  827. dest.hasLinkedRanges = true;
  828. } else if (!dest.firstNonLinked)
  829. dest.firstNonLinked = range;
  830. }
  831. if (!dest.firstNonLinked)
  832. dest.hasLinkedRanges = false;
  833. if (dest === ts) {
  834. arg.push(dest);
  835. this.$openTabstops[index] = dest;
  836. }
  837. this.addTabstopMarkers(dest);
  838. dest.rangeList = dest.rangeList || new RangeList();
  839. dest.rangeList.$bias = 0;
  840. dest.rangeList.addList(dest);
  841. }, this);
  842. if (arg.length > 2) {
  843. if (this.tabstops.length)
  844. arg.push(arg.splice(2, 1)[0]);
  845. this.tabstops.splice.apply(this.tabstops, arg);
  846. }
  847. };
  848. this.addTabstopMarkers = function(ts) {
  849. var session = this.editor.session;
  850. ts.forEach(function(range) {
  851. if (!range.markerId)
  852. range.markerId = session.addMarker(range, "ace_snippet-marker", "text");
  853. });
  854. };
  855. this.removeTabstopMarkers = function(ts) {
  856. var session = this.editor.session;
  857. ts.forEach(function(range) {
  858. session.removeMarker(range.markerId);
  859. range.markerId = null;
  860. });
  861. };
  862. this.removeRange = function(range) {
  863. var i = range.tabstop.indexOf(range);
  864. if (i != -1) range.tabstop.splice(i, 1);
  865. i = this.ranges.indexOf(range);
  866. if (i != -1) this.ranges.splice(i, 1);
  867. i = range.tabstop.rangeList.ranges.indexOf(range);
  868. if (i != -1) range.tabstop.splice(i, 1);
  869. this.editor.session.removeMarker(range.markerId);
  870. if (!range.tabstop.length) {
  871. i = this.tabstops.indexOf(range.tabstop);
  872. if (i != -1)
  873. this.tabstops.splice(i, 1);
  874. if (!this.tabstops.length)
  875. this.detach();
  876. }
  877. };
  878. this.keyboardHandler = new HashHandler();
  879. this.keyboardHandler.bindKeys({
  880. "Tab": function(editor) {
  881. if (exports.snippetManager && exports.snippetManager.expandWithTab(editor))
  882. return;
  883. editor.tabstopManager.tabNext(1);
  884. editor.renderer.scrollCursorIntoView();
  885. },
  886. "Shift-Tab": function(editor) {
  887. editor.tabstopManager.tabNext(-1);
  888. editor.renderer.scrollCursorIntoView();
  889. },
  890. "Esc": function(editor) {
  891. editor.tabstopManager.detach();
  892. }
  893. });
  894. }).call(TabstopManager.prototype);
  895. var movePoint = function(point, diff) {
  896. if (point.row == 0)
  897. point.column += diff.column;
  898. point.row += diff.row;
  899. };
  900. var moveRelative = function(point, start) {
  901. if (point.row == start.row)
  902. point.column -= start.column;
  903. point.row -= start.row;
  904. };
  905. require("./lib/dom").importCssString("\
  906. .ace_snippet-marker {\
  907. -moz-box-sizing: border-box;\
  908. box-sizing: border-box;\
  909. background: rgba(194, 193, 208, 0.09);\
  910. border: 1px dotted rgba(211, 208, 235, 0.62);\
  911. position: absolute;\
  912. }");
  913. exports.snippetManager = new SnippetManager();
  914. var Editor = require("./editor").Editor;
  915. (function() {
  916. this.insertSnippet = function(content, options) {
  917. return exports.snippetManager.insertSnippet(this, content, options);
  918. };
  919. this.expandSnippet = function(options) {
  920. return exports.snippetManager.expandWithTab(this, options);
  921. };
  922. }).call(Editor.prototype);
  923. });
  924. define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"], function(require, exports, module) {
  925. "use strict";
  926. var Renderer = require("../virtual_renderer").VirtualRenderer;
  927. var Editor = require("../editor").Editor;
  928. var Range = require("../range").Range;
  929. var event = require("../lib/event");
  930. var lang = require("../lib/lang");
  931. var dom = require("../lib/dom");
  932. var $singleLineEditor = function(el) {
  933. var renderer = new Renderer(el);
  934. renderer.$maxLines = 4;
  935. var editor = new Editor(renderer);
  936. editor.setHighlightActiveLine(false);
  937. editor.setShowPrintMargin(false);
  938. editor.renderer.setShowGutter(false);
  939. editor.renderer.setHighlightGutterLine(false);
  940. editor.$mouseHandler.$focusTimeout = 0;
  941. editor.$highlightTagPending = true;
  942. return editor;
  943. };
  944. var AcePopup = function(parentNode) {
  945. var el = dom.createElement("div");
  946. var popup = new $singleLineEditor(el);
  947. if (parentNode)
  948. parentNode.appendChild(el);
  949. el.style.display = "none";
  950. popup.renderer.content.style.cursor = "default";
  951. popup.renderer.setStyle("ace_autocomplete");
  952. popup.setOption("displayIndentGuides", false);
  953. popup.setOption("dragDelay", 150);
  954. var noop = function(){};
  955. popup.focus = noop;
  956. popup.$isFocused = true;
  957. popup.renderer.$cursorLayer.restartTimer = noop;
  958. popup.renderer.$cursorLayer.element.style.opacity = 0;
  959. popup.renderer.$maxLines = 8;
  960. popup.renderer.$keepTextAreaAtCursor = false;
  961. popup.setHighlightActiveLine(false);
  962. popup.session.highlight("");
  963. popup.session.$searchHighlight.clazz = "ace_highlight-marker";
  964. popup.on("mousedown", function(e) {
  965. var pos = e.getDocumentPosition();
  966. popup.selection.moveToPosition(pos);
  967. selectionMarker.start.row = selectionMarker.end.row = pos.row;
  968. e.stop();
  969. });
  970. var lastMouseEvent;
  971. var hoverMarker = new Range(-1,0,-1,Infinity);
  972. var selectionMarker = new Range(-1,0,-1,Infinity);
  973. selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine");
  974. popup.setSelectOnHover = function(val) {
  975. if (!val) {
  976. hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine");
  977. } else if (hoverMarker.id) {
  978. popup.session.removeMarker(hoverMarker.id);
  979. hoverMarker.id = null;
  980. }
  981. };
  982. popup.setSelectOnHover(false);
  983. popup.on("mousemove", function(e) {
  984. if (!lastMouseEvent) {
  985. lastMouseEvent = e;
  986. return;
  987. }
  988. if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) {
  989. return;
  990. }
  991. lastMouseEvent = e;
  992. lastMouseEvent.scrollTop = popup.renderer.scrollTop;
  993. var row = lastMouseEvent.getDocumentPosition().row;
  994. if (hoverMarker.start.row != row) {
  995. if (!hoverMarker.id)
  996. popup.setRow(row);
  997. setHoverMarker(row);
  998. }
  999. });
  1000. popup.renderer.on("beforeRender", function() {
  1001. if (lastMouseEvent && hoverMarker.start.row != -1) {
  1002. lastMouseEvent.$pos = null;
  1003. var row = lastMouseEvent.getDocumentPosition().row;
  1004. if (!hoverMarker.id)
  1005. popup.setRow(row);
  1006. setHoverMarker(row, true);
  1007. }
  1008. });
  1009. popup.renderer.on("afterRender", function() {
  1010. var row = popup.getRow();
  1011. var t = popup.renderer.$textLayer;
  1012. var selected = t.element.childNodes[row - t.config.firstRow];
  1013. if (selected !== t.selectedNode && t.selectedNode)
  1014. dom.removeCssClass(t.selectedNode, "ace_selected");
  1015. t.selectedNode = selected;
  1016. if (selected)
  1017. dom.addCssClass(selected, "ace_selected");
  1018. });
  1019. var hideHoverMarker = function() { setHoverMarker(-1); };
  1020. var setHoverMarker = function(row, suppressRedraw) {
  1021. if (row !== hoverMarker.start.row) {
  1022. hoverMarker.start.row = hoverMarker.end.row = row;
  1023. if (!suppressRedraw)
  1024. popup.session._emit("changeBackMarker");
  1025. popup._emit("changeHoverMarker");
  1026. }
  1027. };
  1028. popup.getHoveredRow = function() {
  1029. return hoverMarker.start.row;
  1030. };
  1031. event.addListener(popup.container, "mouseout", hideHoverMarker);
  1032. popup.on("hide", hideHoverMarker);
  1033. popup.on("changeSelection", hideHoverMarker);
  1034. popup.session.doc.getLength = function() {
  1035. return popup.data.length;
  1036. };
  1037. popup.session.doc.getLine = function(i) {
  1038. var data = popup.data[i];
  1039. if (typeof data == "string")
  1040. return data;
  1041. return (data && data.value) || "";
  1042. };
  1043. var bgTokenizer = popup.session.bgTokenizer;
  1044. bgTokenizer.$tokenizeRow = function(row) {
  1045. var data = popup.data[row];
  1046. var tokens = [];
  1047. if (!data)
  1048. return tokens;
  1049. if (typeof data == "string")
  1050. data = {value: data};
  1051. var caption = data.caption || data.value || data.name;
  1052. function addToken(value, className) {
  1053. value && tokens.push({
  1054. type: (data.className || "") + (className || ""),
  1055. value: value
  1056. });
  1057. }
  1058. var lower = caption.toLowerCase();
  1059. var filterText = (popup.filterText || "").toLowerCase();
  1060. var lastIndex = 0;
  1061. var lastI = 0;
  1062. for (var i = 0; i <= filterText.length; i++) {
  1063. if (i != lastI && (data.matchMask & (1 << i) || i == filterText.length)) {
  1064. var sub = filterText.slice(lastI, i);
  1065. lastI = i;
  1066. var index = lower.indexOf(sub, lastIndex);
  1067. if (index == -1) continue;
  1068. addToken(caption.slice(lastIndex, index), "");
  1069. lastIndex = index + sub.length;
  1070. addToken(caption.slice(index, lastIndex), "completion-highlight");
  1071. }
  1072. }
  1073. addToken(caption.slice(lastIndex, caption.length), "");
  1074. if (data.meta)
  1075. tokens.push({type: "completion-meta", value: data.meta});
  1076. if (data.message)
  1077. tokens.push({type: "completion-message", value: data.message});
  1078. return tokens;
  1079. };
  1080. bgTokenizer.$updateOnChange = noop;
  1081. bgTokenizer.start = noop;
  1082. popup.session.$computeWidth = function() {
  1083. return this.screenWidth = 0;
  1084. };
  1085. popup.isOpen = false;
  1086. popup.isTopdown = false;
  1087. popup.autoSelect = true;
  1088. popup.filterText = "";
  1089. popup.data = [];
  1090. popup.setData = function(list, filterText) {
  1091. popup.filterText = filterText || "";
  1092. popup.setValue(lang.stringRepeat("\n", list.length), -1);
  1093. popup.data = list || [];
  1094. popup.setRow(0);
  1095. };
  1096. popup.getData = function(row) {
  1097. return popup.data[row];
  1098. };
  1099. popup.getRow = function() {
  1100. return selectionMarker.start.row;
  1101. };
  1102. popup.setRow = function(line) {
  1103. line = Math.max(this.autoSelect ? 0 : -1, Math.min(this.data.length, line));
  1104. if (selectionMarker.start.row != line) {
  1105. popup.selection.clearSelection();
  1106. selectionMarker.start.row = selectionMarker.end.row = line || 0;
  1107. popup.session._emit("changeBackMarker");
  1108. popup.moveCursorTo(line || 0, 0);
  1109. if (popup.isOpen)
  1110. popup._signal("select");
  1111. }
  1112. };
  1113. popup.on("changeSelection", function() {
  1114. if (popup.isOpen)
  1115. popup.setRow(popup.selection.lead.row);
  1116. popup.renderer.scrollCursorIntoView();
  1117. });
  1118. popup.hide = function() {
  1119. this.container.style.display = "none";
  1120. this._signal("hide");
  1121. popup.isOpen = false;
  1122. };
  1123. popup.show = function(pos, lineHeight, topdownOnly) {
  1124. var el = this.container;
  1125. var screenHeight = window.innerHeight;
  1126. var screenWidth = window.innerWidth;
  1127. var renderer = this.renderer;
  1128. var maxH = renderer.$maxLines * lineHeight * 1.4;
  1129. var top = pos.top + this.$borderSize;
  1130. var allowTopdown = top > screenHeight / 2 && !topdownOnly;
  1131. if (allowTopdown && top + lineHeight + maxH > screenHeight) {
  1132. renderer.$maxPixelHeight = top - 2 * this.$borderSize;
  1133. el.style.top = "";
  1134. el.style.bottom = screenHeight - top + "px";
  1135. popup.isTopdown = false;
  1136. } else {
  1137. top += lineHeight;
  1138. renderer.$maxPixelHeight = screenHeight - top - 0.2 * lineHeight;
  1139. el.style.top = top + "px";
  1140. el.style.bottom = "";
  1141. popup.isTopdown = true;
  1142. }
  1143. el.style.display = "";
  1144. var left = pos.left;
  1145. if (left + el.offsetWidth > screenWidth)
  1146. left = screenWidth - el.offsetWidth;
  1147. el.style.left = left + "px";
  1148. this._signal("show");
  1149. lastMouseEvent = null;
  1150. popup.isOpen = true;
  1151. };
  1152. popup.goTo = function(where) {
  1153. var row = this.getRow();
  1154. var max = this.session.getLength() - 1;
  1155. switch(where) {
  1156. case "up": row = row <= 0 ? max : row - 1; break;
  1157. case "down": row = row >= max ? -1 : row + 1; break;
  1158. case "start": row = 0; break;
  1159. case "end": row = max; break;
  1160. }
  1161. this.setRow(row);
  1162. };
  1163. popup.getTextLeftOffset = function() {
  1164. return this.$borderSize + this.renderer.$padding + this.$imageSize;
  1165. };
  1166. popup.$imageSize = 0;
  1167. popup.$borderSize = 1;
  1168. return popup;
  1169. };
  1170. dom.importCssString("\
  1171. .ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\
  1172. background-color: #CAD6FA;\
  1173. z-index: 1;\
  1174. }\
  1175. .ace_dark.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\
  1176. background-color: #3a674e;\
  1177. }\
  1178. .ace_editor.ace_autocomplete .ace_line-hover {\
  1179. border: 1px solid #abbffe;\
  1180. margin-top: -1px;\
  1181. background: rgba(233,233,253,0.4);\
  1182. position: absolute;\
  1183. z-index: 2;\
  1184. }\
  1185. .ace_dark.ace_editor.ace_autocomplete .ace_line-hover {\
  1186. border: 1px solid rgba(109, 150, 13, 0.8);\
  1187. background: rgba(58, 103, 78, 0.62);\
  1188. }\
  1189. .ace_completion-meta {\
  1190. opacity: 0.5;\
  1191. margin: 0.9em;\
  1192. }\
  1193. .ace_completion-message {\
  1194. color: blue;\
  1195. }\
  1196. .ace_editor.ace_autocomplete .ace_completion-highlight{\
  1197. color: #2d69c7;\
  1198. }\
  1199. .ace_dark.ace_editor.ace_autocomplete .ace_completion-highlight{\
  1200. color: #93ca12;\
  1201. }\
  1202. .ace_editor.ace_autocomplete {\
  1203. width: 300px;\
  1204. z-index: 200000;\
  1205. border: 1px lightgray solid;\
  1206. position: fixed;\
  1207. box-shadow: 2px 3px 5px rgba(0,0,0,.2);\
  1208. line-height: 1.4;\
  1209. background: #fefefe;\
  1210. color: #111;\
  1211. }\
  1212. .ace_dark.ace_editor.ace_autocomplete {\
  1213. border: 1px #484747 solid;\
  1214. box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.51);\
  1215. line-height: 1.4;\
  1216. background: #25282c;\
  1217. color: #c1c1c1;\
  1218. }", "autocompletion.css");
  1219. exports.AcePopup = AcePopup;
  1220. exports.$singleLineEditor = $singleLineEditor;
  1221. });
  1222. define("ace/autocomplete/util",["require","exports","module"], function(require, exports, module) {
  1223. "use strict";
  1224. exports.parForEach = function(array, fn, callback) {
  1225. var completed = 0;
  1226. var arLength = array.length;
  1227. if (arLength === 0)
  1228. callback();
  1229. for (var i = 0; i < arLength; i++) {
  1230. fn(array[i], function(result, err) {
  1231. completed++;
  1232. if (completed === arLength)
  1233. callback(result, err);
  1234. });
  1235. }
  1236. };
  1237. var ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\u2000\u2070-\uFFFF]/;
  1238. exports.retrievePrecedingIdentifier = function(text, pos, regex) {
  1239. regex = regex || ID_REGEX;
  1240. var buf = [];
  1241. for (var i = pos-1; i >= 0; i--) {
  1242. if (regex.test(text[i]))
  1243. buf.push(text[i]);
  1244. else
  1245. break;
  1246. }
  1247. return buf.reverse().join("");
  1248. };
  1249. exports.retrieveFollowingIdentifier = function(text, pos, regex) {
  1250. regex = regex || ID_REGEX;
  1251. var buf = [];
  1252. for (var i = pos; i < text.length; i++) {
  1253. if (regex.test(text[i]))
  1254. buf.push(text[i]);
  1255. else
  1256. break;
  1257. }
  1258. return buf;
  1259. };
  1260. exports.getCompletionPrefix = function (editor) {
  1261. var pos = editor.getCursorPosition();
  1262. var line = editor.session.getLine(pos.row);
  1263. var prefix;
  1264. editor.completers.forEach(function(completer) {
  1265. if (completer.identifierRegexps) {
  1266. completer.identifierRegexps.forEach(function(identifierRegex) {
  1267. if (!prefix && identifierRegex)
  1268. prefix = this.retrievePrecedingIdentifier(line, pos.column, identifierRegex);
  1269. }.bind(this));
  1270. }
  1271. }.bind(this));
  1272. return prefix || this.retrievePrecedingIdentifier(line, pos.column);
  1273. };
  1274. });
  1275. define("ace/autocomplete",["require","exports","module","ace/keyboard/hash_handler","ace/autocomplete/popup","ace/autocomplete/util","ace/lib/lang","ace/lib/dom","ace/snippets","ace/config"], function(require, exports, module) {
  1276. "use strict";
  1277. var HashHandler = require("./keyboard/hash_handler").HashHandler;
  1278. var AcePopup = require("./autocomplete/popup").AcePopup;
  1279. var util = require("./autocomplete/util");
  1280. var lang = require("./lib/lang");
  1281. var dom = require("./lib/dom");
  1282. var snippetManager = require("./snippets").snippetManager;
  1283. var config = require("./config");
  1284. var Autocomplete = function() {
  1285. this.autoInsert = false;
  1286. this.autoSelect = true;
  1287. this.exactMatch = false;
  1288. this.gatherCompletionsId = 0;
  1289. this.keyboardHandler = new HashHandler();
  1290. this.keyboardHandler.bindKeys(this.commands);
  1291. this.blurListener = this.blurListener.bind(this);
  1292. this.changeListener = this.changeListener.bind(this);
  1293. this.mousedownListener = this.mousedownListener.bind(this);
  1294. this.mousewheelListener = this.mousewheelListener.bind(this);
  1295. this.changeTimer = lang.delayedCall(function() {
  1296. this.updateCompletions(true);
  1297. }.bind(this));
  1298. this.tooltipTimer = lang.delayedCall(this.updateDocTooltip.bind(this), 50);
  1299. };
  1300. (function() {
  1301. this.$init = function() {
  1302. this.popup = new AcePopup(document.body || document.documentElement);
  1303. this.popup.on("click", function(e) {
  1304. this.insertMatch();
  1305. e.stop();
  1306. }.bind(this));
  1307. this.popup.focus = this.editor.focus.bind(this.editor);
  1308. this.popup.on("show", this.tooltipTimer.bind(null, null));
  1309. this.popup.on("select", this.tooltipTimer.bind(null, null));
  1310. this.popup.on("changeHoverMarker", this.tooltipTimer.bind(null, null));
  1311. return this.popup;
  1312. };
  1313. this.getPopup = function() {
  1314. return this.popup || this.$init();
  1315. };
  1316. this.openPopup = function(editor, prefix, keepPopupPosition) {
  1317. if (!this.popup)
  1318. this.$init();
  1319. this.popup.autoSelect = this.autoSelect;
  1320. this.popup.setData(this.completions.filtered, this.completions.filterText);
  1321. editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  1322. var renderer = editor.renderer;
  1323. this.popup.setRow(this.autoSelect ? 0 : -1);
  1324. if (!keepPopupPosition) {
  1325. this.popup.setTheme(editor.getTheme());
  1326. this.popup.setFontSize(editor.getFontSize());
  1327. var lineHeight = renderer.layerConfig.lineHeight;
  1328. var pos = renderer.$cursorLayer.getPixelPosition(this.base, true);
  1329. pos.left -= this.popup.getTextLeftOffset();
  1330. var rect = editor.container.getBoundingClientRect();
  1331. pos.top += rect.top - renderer.layerConfig.offset;
  1332. pos.left += rect.left - editor.renderer.scrollLeft;
  1333. pos.left += renderer.gutterWidth;
  1334. this.popup.show(pos, lineHeight);
  1335. } else if (keepPopupPosition && !prefix) {
  1336. this.detach();
  1337. }
  1338. };
  1339. this.detach = function() {
  1340. this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
  1341. this.editor.off("changeSelection", this.changeListener);
  1342. this.editor.off("blur", this.blurListener);
  1343. this.editor.off("mousedown", this.mousedownListener);
  1344. this.editor.off("mousewheel", this.mousewheelListener);
  1345. this.changeTimer.cancel();
  1346. this.hideDocTooltip();
  1347. this.gatherCompletionsId += 1;
  1348. if (this.popup && this.popup.isOpen)
  1349. this.popup.hide();
  1350. if (this.base)
  1351. this.base.detach();
  1352. this.activated = false;
  1353. this.completions = this.base = null;
  1354. };
  1355. this.changeListener = function(e) {
  1356. var cursor = this.editor.selection.lead;
  1357. if (cursor.row != this.base.row || cursor.column < this.base.column) {
  1358. this.detach();
  1359. }
  1360. if (this.activated)
  1361. this.changeTimer.schedule();
  1362. else
  1363. this.detach();
  1364. };
  1365. this.blurListener = function(e) {
  1366. var el = document.activeElement;
  1367. var text = this.editor.textInput.getElement();
  1368. var fromTooltip = e.relatedTarget && this.tooltipNode && this.tooltipNode.contains(e.relatedTarget);
  1369. var container = this.popup && this.popup.container;
  1370. if (el != text && el.parentNode != container && !fromTooltip
  1371. && el != this.tooltipNode && e.relatedTarget != text
  1372. ) {
  1373. this.detach();
  1374. }
  1375. };
  1376. this.mousedownListener = function(e) {
  1377. this.detach();
  1378. };
  1379. this.mousewheelListener = function(e) {
  1380. this.detach();
  1381. };
  1382. this.goTo = function(where) {
  1383. this.popup.goTo(where);
  1384. };
  1385. this.insertMatch = function(data, options) {
  1386. if (!data)
  1387. data = this.popup.getData(this.popup.getRow());
  1388. if (!data)
  1389. return false;
  1390. if (data.completer && data.completer.insertMatch) {
  1391. data.completer.insertMatch(this.editor, data);
  1392. } else {
  1393. if (this.completions.filterText) {
  1394. var ranges = this.editor.selection.getAllRanges();
  1395. for (var i = 0, range; range = ranges[i]; i++) {
  1396. range.start.column -= this.completions.filterText.length;
  1397. this.editor.session.remove(range);
  1398. }
  1399. }
  1400. if (data.snippet)
  1401. snippetManager.insertSnippet(this.editor, data.snippet);
  1402. else
  1403. this.editor.execCommand("insertstring", data.value || data);
  1404. }
  1405. this.detach();
  1406. };
  1407. this.commands = {
  1408. "Up": function(editor) { editor.completer.goTo("up"); },
  1409. "Down": function(editor) { editor.completer.goTo("down"); },
  1410. "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); },
  1411. "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); },
  1412. "Esc": function(editor) { editor.completer.detach(); },
  1413. "Return": function(editor) { return editor.completer.insertMatch(); },
  1414. "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); },
  1415. "Tab": function(editor) {
  1416. var result = editor.completer.insertMatch();
  1417. if (!result && !editor.tabstopManager)
  1418. editor.completer.goTo("down");
  1419. else
  1420. return result;
  1421. },
  1422. "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); },
  1423. "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); }
  1424. };
  1425. this.gatherCompletions = function(editor, callback) {
  1426. var session = editor.getSession();
  1427. var pos = editor.getCursorPosition();
  1428. var prefix = util.getCompletionPrefix(editor);
  1429. this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length);
  1430. this.base.$insertRight = true;
  1431. var matches = [];
  1432. var total = editor.completers.length;
  1433. editor.completers.forEach(function(completer, i) {
  1434. completer.getCompletions(editor, session, pos, prefix, function(err, results) {
  1435. if (!err && results)
  1436. matches = matches.concat(results);
  1437. callback(null, {
  1438. prefix: util.getCompletionPrefix(editor),
  1439. matches: matches,
  1440. finished: (--total === 0)
  1441. });
  1442. });
  1443. });
  1444. return true;
  1445. };
  1446. this.showPopup = function(editor, options) {
  1447. if (this.editor)
  1448. this.detach();
  1449. this.activated = true;
  1450. this.editor = editor;
  1451. if (editor.completer != this) {
  1452. if (editor.completer)
  1453. editor.completer.detach();
  1454. editor.completer = this;
  1455. }
  1456. editor.on("changeSelection", this.changeListener);
  1457. editor.on("blur", this.blurListener);
  1458. editor.on("mousedown", this.mousedownListener);
  1459. editor.on("mousewheel", this.mousewheelListener);
  1460. this.updateCompletions(false, options);
  1461. };
  1462. this.updateCompletions = function(keepPopupPosition, options) {
  1463. if (keepPopupPosition && this.base && this.completions) {
  1464. var pos = this.editor.getCursorPosition();
  1465. var prefix = this.editor.session.getTextRange({start: this.base, end: pos});
  1466. if (prefix == this.completions.filterText)
  1467. return;
  1468. this.completions.setFilter(prefix);
  1469. if (!this.completions.filtered.length)
  1470. return this.detach();
  1471. if (this.completions.filtered.length == 1
  1472. && this.completions.filtered[0].value == prefix
  1473. && !this.completions.filtered[0].snippet)
  1474. return this.detach();
  1475. this.openPopup(this.editor, prefix, keepPopupPosition);
  1476. return;
  1477. }
  1478. if (options && options.matches) {
  1479. var pos = this.editor.getSelectionRange().start;
  1480. this.base = this.editor.session.doc.createAnchor(pos.row, pos.column);
  1481. this.base.$insertRight = true;
  1482. this.completions = new FilteredList(options.matches);
  1483. return this.openPopup(this.editor, "", keepPopupPosition);
  1484. }
  1485. var _id = this.gatherCompletionsId;
  1486. this.gatherCompletions(this.editor, function(err, results) {
  1487. var detachIfFinished = function() {
  1488. if (!results.finished) return;
  1489. return this.detach();
  1490. }.bind(this);
  1491. var prefix = results.prefix;
  1492. var matches = results && results.matches;
  1493. if (!matches || !matches.length)
  1494. return detachIfFinished();
  1495. if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId)
  1496. return;
  1497. this.completions = new FilteredList(matches);
  1498. if (this.exactMatch)
  1499. this.completions.exactMatch = true;
  1500. this.completions.setFilter(prefix);
  1501. var filtered = this.completions.filtered;
  1502. if (!filtered.length)
  1503. return detachIfFinished();
  1504. if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet)
  1505. return detachIfFinished();
  1506. if (this.autoInsert && filtered.length == 1 && results.finished)
  1507. return this.insertMatch(filtered[0]);
  1508. this.openPopup(this.editor, prefix, keepPopupPosition);
  1509. }.bind(this));
  1510. };
  1511. this.cancelContextMenu = function() {
  1512. this.editor.$mouseHandler.cancelContextMenu();
  1513. };
  1514. this.updateDocTooltip = function() {
  1515. var popup = this.popup;
  1516. var all = popup.data;
  1517. var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]);
  1518. var doc = null;
  1519. if (!selected || !this.editor || !this.popup.isOpen)
  1520. return this.hideDocTooltip();
  1521. this.editor.completers.some(function(completer) {
  1522. if (completer.getDocTooltip)
  1523. doc = completer.getDocTooltip(selected);
  1524. return doc;
  1525. });
  1526. if (!doc && typeof selected != "string")
  1527. doc = selected;
  1528. if (typeof doc == "string")
  1529. doc = {docText: doc};
  1530. if (!doc || !(doc.docHTML || doc.docText))
  1531. return this.hideDocTooltip();
  1532. this.showDocTooltip(doc);
  1533. };
  1534. this.showDocTooltip = function(item) {
  1535. if (!this.tooltipNode) {
  1536. this.tooltipNode = dom.createElement("div");
  1537. this.tooltipNode.className = "ace_tooltip ace_doc-tooltip";
  1538. this.tooltipNode.style.margin = 0;
  1539. this.tooltipNode.style.pointerEvents = "auto";
  1540. this.tooltipNode.tabIndex = -1;
  1541. this.tooltipNode.onblur = this.blurListener.bind(this);
  1542. this.tooltipNode.onclick = this.onTooltipClick.bind(this);
  1543. }
  1544. var tooltipNode = this.tooltipNode;
  1545. if (item.docHTML) {
  1546. tooltipNode.innerHTML = item.docHTML;
  1547. } else if (item.docText) {
  1548. tooltipNode.textContent = item.docText;
  1549. }
  1550. if (!tooltipNode.parentNode)
  1551. document.body.appendChild(tooltipNode);
  1552. var popup = this.popup;
  1553. var rect = popup.container.getBoundingClientRect();
  1554. tooltipNode.style.top = popup.container.style.top;
  1555. tooltipNode.style.bottom = popup.container.style.bottom;
  1556. tooltipNode.style.display = "block";
  1557. if (window.innerWidth - rect.right < 320) {
  1558. if (rect.left < 320) {
  1559. if(popup.isTopdown) {
  1560. tooltipNode.style.top = rect.bottom + "px";
  1561. tooltipNode.style.left = rect.left + "px";
  1562. tooltipNode.style.right = "";
  1563. tooltipNode.style.bottom = "";
  1564. } else {
  1565. tooltipNode.style.top = popup.container.offsetTop - tooltipNode.offsetHeight + "px";
  1566. tooltipNode.style.left = rect.left + "px";
  1567. tooltipNode.style.right = "";
  1568. tooltipNode.style.bottom = "";
  1569. }
  1570. } else {
  1571. tooltipNode.style.right = window.innerWidth - rect.left + "px";
  1572. tooltipNode.style.left = "";
  1573. }
  1574. } else {
  1575. tooltipNode.style.left = (rect.right + 1) + "px";
  1576. tooltipNode.style.right = "";
  1577. }
  1578. };
  1579. this.hideDocTooltip = function() {
  1580. this.tooltipTimer.cancel();
  1581. if (!this.tooltipNode) return;
  1582. var el = this.tooltipNode;
  1583. if (!this.editor.isFocused() && document.activeElement == el)
  1584. this.editor.focus();
  1585. this.tooltipNode = null;
  1586. if (el.parentNode)
  1587. el.parentNode.removeChild(el);
  1588. };
  1589. this.onTooltipClick = function(e) {
  1590. var a = e.target;
  1591. while (a && a != this.tooltipNode) {
  1592. if (a.nodeName == "A" && a.href) {
  1593. a.rel = "noreferrer";
  1594. a.target = "_blank";
  1595. break;
  1596. }
  1597. a = a.parentNode;
  1598. }
  1599. };
  1600. this.destroy = function() {
  1601. this.detach();
  1602. if (this.popup) {
  1603. this.popup.destroy();
  1604. var el = this.popup.container;
  1605. if (el && el.parentNode)
  1606. el.parentNode.removeChild(el);
  1607. }
  1608. if (this.editor && this.editor.completer == this)
  1609. this.editor.completer == null;
  1610. this.popup = null;
  1611. };
  1612. }).call(Autocomplete.prototype);
  1613. Autocomplete.for = function(editor) {
  1614. if (editor.completer) {
  1615. return editor.completer;
  1616. }
  1617. if (config.get("sharedPopups")) {
  1618. if (!Autocomplete.$shared)
  1619. Autocomplete.$sharedInstance = new Autocomplete();
  1620. editor.completer = Autocomplete.$sharedInstance;
  1621. } else {
  1622. editor.completer = new Autocomplete();
  1623. editor.once("destroy", function(e, editor) {
  1624. editor.completer.destroy();
  1625. });
  1626. }
  1627. return editor.completer;
  1628. };
  1629. Autocomplete.startCommand = {
  1630. name: "startAutocomplete",
  1631. exec: function(editor, options) {
  1632. var completer = Autocomplete.for(editor);
  1633. completer.autoInsert = false;
  1634. completer.autoSelect = true;
  1635. completer.showPopup(editor, options);
  1636. completer.cancelContextMenu();
  1637. },
  1638. bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space"
  1639. };
  1640. var FilteredList = function(array, filterText) {
  1641. this.all = array;
  1642. this.filtered = array;
  1643. this.filterText = filterText || "";
  1644. this.exactMatch = false;
  1645. };
  1646. (function(){
  1647. this.setFilter = function(str) {
  1648. if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0)
  1649. var matches = this.filtered;
  1650. else
  1651. var matches = this.all;
  1652. this.filterText = str;
  1653. matches = this.filterCompletions(matches, this.filterText);
  1654. matches = matches.sort(function(a, b) {
  1655. return b.exactMatch - a.exactMatch || b.$score - a.$score
  1656. || (a.caption || a.value).localeCompare(b.caption || b.value);
  1657. });
  1658. var prev = null;
  1659. matches = matches.filter(function(item){
  1660. var caption = item.snippet || item.caption || item.value;
  1661. if (caption === prev) return false;
  1662. prev = caption;
  1663. return true;
  1664. });
  1665. this.filtered = matches;
  1666. };
  1667. this.filterCompletions = function(items, needle) {
  1668. var results = [];
  1669. var upper = needle.toUpperCase();
  1670. var lower = needle.toLowerCase();
  1671. loop: for (var i = 0, item; item = items[i]; i++) {
  1672. var caption = item.caption || item.value || item.snippet;
  1673. if (!caption) continue;
  1674. var lastIndex = -1;
  1675. var matchMask = 0;
  1676. var penalty = 0;
  1677. var index, distance;
  1678. if (this.exactMatch) {
  1679. if (needle !== caption.substr(0, needle.length))
  1680. continue loop;
  1681. } else {
  1682. var fullMatchIndex = caption.toLowerCase().indexOf(lower);
  1683. if (fullMatchIndex > -1) {
  1684. penalty = fullMatchIndex;
  1685. } else {
  1686. for (var j = 0; j < needle.length; j++) {
  1687. var i1 = caption.indexOf(lower[j], lastIndex + 1);
  1688. var i2 = caption.indexOf(upper[j], lastIndex + 1);
  1689. index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2;
  1690. if (index < 0)
  1691. continue loop;
  1692. distance = index - lastIndex - 1;
  1693. if (distance > 0) {
  1694. if (lastIndex === -1)
  1695. penalty += 10;
  1696. penalty += distance;
  1697. matchMask = matchMask | (1 << j);
  1698. }
  1699. lastIndex = index;
  1700. }
  1701. }
  1702. }
  1703. item.matchMask = matchMask;
  1704. item.exactMatch = penalty ? 0 : 1;
  1705. item.$score = (item.score || 0) - penalty;
  1706. results.push(item);
  1707. }
  1708. return results;
  1709. };
  1710. }).call(FilteredList.prototype);
  1711. exports.Autocomplete = Autocomplete;
  1712. exports.FilteredList = FilteredList;
  1713. });
  1714. define("ace/autocomplete/text_completer",["require","exports","module","ace/range"], function(require, exports, module) {
  1715. var Range = require("../range").Range;
  1716. var splitRegex = /[^a-zA-Z_0-9\$\-\u00C0-\u1FFF\u2C00-\uD7FF\w]+/;
  1717. function getWordIndex(doc, pos) {
  1718. var textBefore = doc.getTextRange(Range.fromPoints({row: 0, column:0}, pos));
  1719. return textBefore.split(splitRegex).length - 1;
  1720. }
  1721. function wordDistance(doc, pos) {
  1722. var prefixPos = getWordIndex(doc, pos);
  1723. var words = doc.getValue().split(splitRegex);
  1724. var wordScores = Object.create(null);
  1725. var currentWord = words[prefixPos];
  1726. words.forEach(function(word, idx) {
  1727. if (!word || word === currentWord) return;
  1728. var distance = Math.abs(prefixPos - idx);
  1729. var score = words.length - distance;
  1730. if (wordScores[word]) {
  1731. wordScores[word] = Math.max(score, wordScores[word]);
  1732. } else {
  1733. wordScores[word] = score;
  1734. }
  1735. });
  1736. return wordScores;
  1737. }
  1738. exports.getCompletions = function(editor, session, pos, prefix, callback) {
  1739. var wordScore = wordDistance(session, pos);
  1740. var wordList = Object.keys(wordScore);
  1741. callback(null, wordList.map(function(word) {
  1742. return {
  1743. caption: word,
  1744. value: word,
  1745. score: wordScore[word],
  1746. meta: "local"
  1747. };
  1748. }));
  1749. };
  1750. });
  1751. define("ace/ext/language_tools",["require","exports","module","ace/snippets","ace/autocomplete","ace/config","ace/lib/lang","ace/autocomplete/util","ace/autocomplete/text_completer","ace/editor","ace/config"], function(require, exports, module) {
  1752. "use strict";
  1753. var snippetManager = require("../snippets").snippetManager;
  1754. var Autocomplete = require("../autocomplete").Autocomplete;
  1755. var config = require("../config");
  1756. var lang = require("../lib/lang");
  1757. var util = require("../autocomplete/util");
  1758. var textCompleter = require("../autocomplete/text_completer");
  1759. var keyWordCompleter = {
  1760. getCompletions: function(editor, session, pos, prefix, callback) {
  1761. if (session.$mode.completer) {
  1762. return session.$mode.completer.getCompletions(editor, session, pos, prefix, callback);
  1763. }
  1764. var state = editor.session.getState(pos.row);
  1765. var completions = session.$mode.getCompletions(state, session, pos, prefix);
  1766. callback(null, completions);
  1767. }
  1768. };
  1769. var snippetCompleter = {
  1770. getCompletions: function(editor, session, pos, prefix, callback) {
  1771. var scopes = [];
  1772. var token = session.getTokenAt(pos.row, pos.column);
  1773. if (token && token.type.match(/(tag-name|tag-open|tag-whitespace|attribute-name|attribute-value)\.xml$/))
  1774. scopes.push('html-tag');
  1775. else
  1776. scopes = snippetManager.getActiveScopes(editor);
  1777. var snippetMap = snippetManager.snippetMap;
  1778. var completions = [];
  1779. scopes.forEach(function(scope) {
  1780. var snippets = snippetMap[scope] || [];
  1781. for (var i = snippets.length; i--;) {
  1782. var s = snippets[i];
  1783. var caption = s.name || s.tabTrigger;
  1784. if (!caption)
  1785. continue;
  1786. completions.push({
  1787. caption: caption,
  1788. snippet: s.content,
  1789. meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet",
  1790. type: "snippet"
  1791. });
  1792. }
  1793. }, this);
  1794. callback(null, completions);
  1795. },
  1796. getDocTooltip: function(item) {
  1797. if (item.type == "snippet" && !item.docHTML) {
  1798. item.docHTML = [
  1799. "<b>", lang.escapeHTML(item.caption), "</b>", "<hr></hr>",
  1800. lang.escapeHTML(item.snippet)
  1801. ].join("");
  1802. }
  1803. }
  1804. };
  1805. var completers = [snippetCompleter, textCompleter, keyWordCompleter];
  1806. exports.setCompleters = function(val) {
  1807. completers.length = 0;
  1808. if (val) completers.push.apply(completers, val);
  1809. };
  1810. exports.addCompleter = function(completer) {
  1811. completers.push(completer);
  1812. };
  1813. exports.textCompleter = textCompleter;
  1814. exports.keyWordCompleter = keyWordCompleter;
  1815. exports.snippetCompleter = snippetCompleter;
  1816. var expandSnippet = {
  1817. name: "expandSnippet",
  1818. exec: function(editor) {
  1819. return snippetManager.expandWithTab(editor);
  1820. },
  1821. bindKey: "Tab"
  1822. };
  1823. var onChangeMode = function(e, editor) {
  1824. loadSnippetsForMode(editor.session.$mode);
  1825. };
  1826. var loadSnippetsForMode = function(mode) {
  1827. var id = mode.$id;
  1828. if (!snippetManager.files)
  1829. snippetManager.files = {};
  1830. loadSnippetFile(id);
  1831. if (mode.modes)
  1832. mode.modes.forEach(loadSnippetsForMode);
  1833. };
  1834. var loadSnippetFile = function(id) {
  1835. if (!id || snippetManager.files[id])
  1836. return;
  1837. var snippetFilePath = id.replace("mode", "snippets");
  1838. snippetManager.files[id] = {};
  1839. config.loadModule(snippetFilePath, function(m) {
  1840. if (m) {
  1841. snippetManager.files[id] = m;
  1842. if (!m.snippets && m.snippetText)
  1843. m.snippets = snippetManager.parseSnippetFile(m.snippetText);
  1844. snippetManager.register(m.snippets || [], m.scope);
  1845. if (m.includeScopes) {
  1846. snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes;
  1847. m.includeScopes.forEach(function(x) {
  1848. loadSnippetFile("ace/mode/" + x);
  1849. });
  1850. }
  1851. }
  1852. });
  1853. };
  1854. var doLiveAutocomplete = function(e) {
  1855. var editor = e.editor;
  1856. var hasCompleter = editor.completer && editor.completer.activated;
  1857. if (e.command.name === "backspace") {
  1858. if (hasCompleter && !util.getCompletionPrefix(editor))
  1859. editor.completer.detach();
  1860. }
  1861. else if (e.command.name === "insertstring") {
  1862. var prefix = util.getCompletionPrefix(editor);
  1863. if (prefix && !hasCompleter) {
  1864. var completer = Autocomplete.for(editor);
  1865. completer.autoInsert = false;
  1866. completer.showPopup(editor);
  1867. }
  1868. }
  1869. };
  1870. var Editor = require("../editor").Editor;
  1871. require("../config").defineOptions(Editor.prototype, "editor", {
  1872. enableBasicAutocompletion: {
  1873. set: function(val) {
  1874. if (val) {
  1875. if (!this.completers)
  1876. this.completers = Array.isArray(val)? val: completers;
  1877. this.commands.addCommand(Autocomplete.startCommand);
  1878. } else {
  1879. this.commands.removeCommand(Autocomplete.startCommand);
  1880. }
  1881. },
  1882. value: false
  1883. },
  1884. enableLiveAutocompletion: {
  1885. set: function(val) {
  1886. if (val) {
  1887. if (!this.completers)
  1888. this.completers = Array.isArray(val)? val: completers;
  1889. this.commands.on('afterExec', doLiveAutocomplete);
  1890. } else {
  1891. this.commands.removeListener('afterExec', doLiveAutocomplete);
  1892. }
  1893. },
  1894. value: false
  1895. },
  1896. enableSnippets: {
  1897. set: function(val) {
  1898. if (val) {
  1899. this.commands.addCommand(expandSnippet);
  1900. this.on("changeMode", onChangeMode);
  1901. onChangeMode(null, this);
  1902. } else {
  1903. this.commands.removeCommand(expandSnippet);
  1904. this.off("changeMode", onChangeMode);
  1905. }
  1906. },
  1907. value: false
  1908. }
  1909. });
  1910. });
  1911. (function() {
  1912. window.require(["ace/ext/language_tools"], function(m) {
  1913. if (typeof module == "object" && typeof exports == "object" && module) {
  1914. module.exports = m;
  1915. }
  1916. });
  1917. })();