ext-language_tools.js 75 KB

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