ext-language_tools.js 76 KB

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