ext-emmet.js 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330
  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/ext/emmet",["require","exports","module","ace/keyboard/hash_handler","ace/editor","ace/snippets","ace/range","ace/config","resources","resources","tabStops","resources","utils","actions"], function(require, exports, module) {
  933. "use strict";
  934. var HashHandler = require("../keyboard/hash_handler").HashHandler;
  935. var Editor = require("../editor").Editor;
  936. var snippetManager = require("../snippets").snippetManager;
  937. var Range = require("../range").Range;
  938. var config = require("../config");
  939. var emmet, emmetPath;
  940. function AceEmmetEditor() {}
  941. AceEmmetEditor.prototype = {
  942. setupContext: function(editor) {
  943. this.ace = editor;
  944. this.indentation = editor.session.getTabString();
  945. if (!emmet)
  946. emmet = window.emmet;
  947. var resources = emmet.resources || emmet.require("resources");
  948. resources.setVariable("indentation", this.indentation);
  949. this.$syntax = null;
  950. this.$syntax = this.getSyntax();
  951. },
  952. getSelectionRange: function() {
  953. var range = this.ace.getSelectionRange();
  954. var doc = this.ace.session.doc;
  955. return {
  956. start: doc.positionToIndex(range.start),
  957. end: doc.positionToIndex(range.end)
  958. };
  959. },
  960. createSelection: function(start, end) {
  961. var doc = this.ace.session.doc;
  962. this.ace.selection.setRange({
  963. start: doc.indexToPosition(start),
  964. end: doc.indexToPosition(end)
  965. });
  966. },
  967. getCurrentLineRange: function() {
  968. var ace = this.ace;
  969. var row = ace.getCursorPosition().row;
  970. var lineLength = ace.session.getLine(row).length;
  971. var index = ace.session.doc.positionToIndex({row: row, column: 0});
  972. return {
  973. start: index,
  974. end: index + lineLength
  975. };
  976. },
  977. getCaretPos: function(){
  978. var pos = this.ace.getCursorPosition();
  979. return this.ace.session.doc.positionToIndex(pos);
  980. },
  981. setCaretPos: function(index){
  982. var pos = this.ace.session.doc.indexToPosition(index);
  983. this.ace.selection.moveToPosition(pos);
  984. },
  985. getCurrentLine: function() {
  986. var row = this.ace.getCursorPosition().row;
  987. return this.ace.session.getLine(row);
  988. },
  989. replaceContent: function(value, start, end, noIndent) {
  990. if (end == null)
  991. end = start == null ? this.getContent().length : start;
  992. if (start == null)
  993. start = 0;
  994. var editor = this.ace;
  995. var doc = editor.session.doc;
  996. var range = Range.fromPoints(doc.indexToPosition(start), doc.indexToPosition(end));
  997. editor.session.remove(range);
  998. range.end = range.start;
  999. value = this.$updateTabstops(value);
  1000. snippetManager.insertSnippet(editor, value);
  1001. },
  1002. getContent: function(){
  1003. return this.ace.getValue();
  1004. },
  1005. getSyntax: function() {
  1006. if (this.$syntax)
  1007. return this.$syntax;
  1008. var syntax = this.ace.session.$modeId.split("/").pop();
  1009. if (syntax == "html" || syntax == "php") {
  1010. var cursor = this.ace.getCursorPosition();
  1011. var state = this.ace.session.getState(cursor.row);
  1012. if (typeof state != "string")
  1013. state = state[0];
  1014. if (state) {
  1015. state = state.split("-");
  1016. if (state.length > 1)
  1017. syntax = state[0];
  1018. else if (syntax == "php")
  1019. syntax = "html";
  1020. }
  1021. }
  1022. return syntax;
  1023. },
  1024. getProfileName: function() {
  1025. var resources = emmet.resources || emmet.require("resources");
  1026. switch (this.getSyntax()) {
  1027. case "css": return "css";
  1028. case "xml":
  1029. case "xsl":
  1030. return "xml";
  1031. case "html":
  1032. var profile = resources.getVariable("profile");
  1033. if (!profile)
  1034. profile = this.ace.session.getLines(0,2).join("").search(/<!DOCTYPE[^>]+XHTML/i) != -1 ? "xhtml": "html";
  1035. return profile;
  1036. default:
  1037. var mode = this.ace.session.$mode;
  1038. return mode.emmetConfig && mode.emmetConfig.profile || "xhtml";
  1039. }
  1040. },
  1041. prompt: function(title) {
  1042. return prompt(title); // eslint-disable-line no-alert
  1043. },
  1044. getSelection: function() {
  1045. return this.ace.session.getTextRange();
  1046. },
  1047. getFilePath: function() {
  1048. return "";
  1049. },
  1050. $updateTabstops: function(value) {
  1051. var base = 1000;
  1052. var zeroBase = 0;
  1053. var lastZero = null;
  1054. var ts = emmet.tabStops || emmet.require('tabStops');
  1055. var resources = emmet.resources || emmet.require("resources");
  1056. var settings = resources.getVocabulary("user");
  1057. var tabstopOptions = {
  1058. tabstop: function(data) {
  1059. var group = parseInt(data.group, 10);
  1060. var isZero = group === 0;
  1061. if (isZero)
  1062. group = ++zeroBase;
  1063. else
  1064. group += base;
  1065. var placeholder = data.placeholder;
  1066. if (placeholder) {
  1067. placeholder = ts.processText(placeholder, tabstopOptions);
  1068. }
  1069. var result = '${' + group + (placeholder ? ':' + placeholder : '') + '}';
  1070. if (isZero) {
  1071. lastZero = [data.start, result];
  1072. }
  1073. return result;
  1074. },
  1075. escape: function(ch) {
  1076. if (ch == '$') return '\\$';
  1077. if (ch == '\\') return '\\\\';
  1078. return ch;
  1079. }
  1080. };
  1081. value = ts.processText(value, tabstopOptions);
  1082. if (settings.variables['insert_final_tabstop'] && !/\$\{0\}$/.test(value)) {
  1083. value += '${0}';
  1084. } else if (lastZero) {
  1085. var common = emmet.utils ? emmet.utils.common : emmet.require('utils');
  1086. value = common.replaceSubstring(value, '${0}', lastZero[0], lastZero[1]);
  1087. }
  1088. return value;
  1089. }
  1090. };
  1091. var keymap = {
  1092. expand_abbreviation: {"mac": "ctrl+alt+e", "win": "alt+e"},
  1093. match_pair_outward: {"mac": "ctrl+d", "win": "ctrl+,"},
  1094. match_pair_inward: {"mac": "ctrl+j", "win": "ctrl+shift+0"},
  1095. matching_pair: {"mac": "ctrl+alt+j", "win": "alt+j"},
  1096. next_edit_point: "alt+right",
  1097. prev_edit_point: "alt+left",
  1098. toggle_comment: {"mac": "command+/", "win": "ctrl+/"},
  1099. split_join_tag: {"mac": "shift+command+'", "win": "shift+ctrl+`"},
  1100. remove_tag: {"mac": "command+'", "win": "shift+ctrl+;"},
  1101. evaluate_math_expression: {"mac": "shift+command+y", "win": "shift+ctrl+y"},
  1102. increment_number_by_1: "ctrl+up",
  1103. decrement_number_by_1: "ctrl+down",
  1104. increment_number_by_01: "alt+up",
  1105. decrement_number_by_01: "alt+down",
  1106. increment_number_by_10: {"mac": "alt+command+up", "win": "shift+alt+up"},
  1107. decrement_number_by_10: {"mac": "alt+command+down", "win": "shift+alt+down"},
  1108. select_next_item: {"mac": "shift+command+.", "win": "shift+ctrl+."},
  1109. select_previous_item: {"mac": "shift+command+,", "win": "shift+ctrl+,"},
  1110. reflect_css_value: {"mac": "shift+command+r", "win": "shift+ctrl+r"},
  1111. encode_decode_data_url: {"mac": "shift+ctrl+d", "win": "ctrl+'"},
  1112. expand_abbreviation_with_tab: "Tab",
  1113. wrap_with_abbreviation: {"mac": "shift+ctrl+a", "win": "shift+ctrl+a"}
  1114. };
  1115. var editorProxy = new AceEmmetEditor();
  1116. exports.commands = new HashHandler();
  1117. exports.runEmmetCommand = function runEmmetCommand(editor) {
  1118. if (this.action == "expand_abbreviation_with_tab") {
  1119. if (!editor.selection.isEmpty())
  1120. return false;
  1121. var pos = editor.selection.lead;
  1122. var token = editor.session.getTokenAt(pos.row, pos.column);
  1123. if (token && /\btag\b/.test(token.type))
  1124. return false;
  1125. }
  1126. try {
  1127. editorProxy.setupContext(editor);
  1128. var actions = emmet.actions || emmet.require("actions");
  1129. if (this.action == "wrap_with_abbreviation") {
  1130. return setTimeout(function() {
  1131. actions.run("wrap_with_abbreviation", editorProxy);
  1132. }, 0);
  1133. }
  1134. var result = actions.run(this.action, editorProxy);
  1135. } catch(e) {
  1136. if (!emmet) {
  1137. var loading = exports.load(runEmmetCommand.bind(this, editor));
  1138. if (this.action == "expand_abbreviation_with_tab")
  1139. return false;
  1140. return loading;
  1141. }
  1142. editor._signal("changeStatus", typeof e == "string" ? e : e.message);
  1143. config.warn(e);
  1144. result = false;
  1145. }
  1146. return result;
  1147. };
  1148. for (var command in keymap) {
  1149. exports.commands.addCommand({
  1150. name: "emmet:" + command,
  1151. action: command,
  1152. bindKey: keymap[command],
  1153. exec: exports.runEmmetCommand,
  1154. multiSelectAction: "forEach"
  1155. });
  1156. }
  1157. exports.updateCommands = function(editor, enabled) {
  1158. if (enabled) {
  1159. editor.keyBinding.addKeyboardHandler(exports.commands);
  1160. } else {
  1161. editor.keyBinding.removeKeyboardHandler(exports.commands);
  1162. }
  1163. };
  1164. exports.isSupportedMode = function(mode) {
  1165. if (!mode) return false;
  1166. if (mode.emmetConfig) return true;
  1167. var id = mode.$id || mode;
  1168. return /css|less|scss|sass|stylus|html|php|twig|ejs|handlebars/.test(id);
  1169. };
  1170. exports.isAvailable = function(editor, command) {
  1171. if (/(evaluate_math_expression|expand_abbreviation)$/.test(command))
  1172. return true;
  1173. var mode = editor.session.$mode;
  1174. var isSupported = exports.isSupportedMode(mode);
  1175. if (isSupported && mode.$modes) {
  1176. try {
  1177. editorProxy.setupContext(editor);
  1178. if (/js|php/.test(editorProxy.getSyntax()))
  1179. isSupported = false;
  1180. } catch(e) {}
  1181. }
  1182. return isSupported;
  1183. };
  1184. var onChangeMode = function(e, target) {
  1185. var editor = target;
  1186. if (!editor)
  1187. return;
  1188. var enabled = exports.isSupportedMode(editor.session.$mode);
  1189. if (e.enableEmmet === false)
  1190. enabled = false;
  1191. if (enabled)
  1192. exports.load();
  1193. exports.updateCommands(editor, enabled);
  1194. };
  1195. exports.load = function(cb) {
  1196. if (typeof emmetPath !== "string") {
  1197. config.warn("script for emmet-core is not loaded");
  1198. return false;
  1199. }
  1200. config.loadModule(emmetPath, function() {
  1201. emmetPath = null;
  1202. cb && cb();
  1203. });
  1204. return true;
  1205. };
  1206. exports.AceEmmetEditor = AceEmmetEditor;
  1207. config.defineOptions(Editor.prototype, "editor", {
  1208. enableEmmet: {
  1209. set: function(val) {
  1210. this[val ? "on" : "removeListener"]("changeMode", onChangeMode);
  1211. onChangeMode({enableEmmet: !!val}, this);
  1212. },
  1213. value: true
  1214. }
  1215. });
  1216. exports.setCore = function(e) {
  1217. if (typeof e == "string")
  1218. emmetPath = e;
  1219. else
  1220. emmet = e;
  1221. };
  1222. }); (function() {
  1223. ace.require(["ace/ext/emmet"], function(m) {
  1224. if (typeof module == "object" && typeof exports == "object" && module) {
  1225. module.exports = m;
  1226. }
  1227. });
  1228. })();