1694f12f2e48f4b28754c37fd132c501.js 77 KB

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