ext-emmet.js 42 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","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 Anchor = require("./anchor").Anchor;
  8. var HashHandler = require("./keyboard/hash_handler").HashHandler;
  9. var Tokenizer = require("./tokenizer").Tokenizer;
  10. var comparePoints = Range.comparePoints;
  11. var SnippetManager = function() {
  12. this.snippetMap = {};
  13. this.snippetNameMap = {};
  14. };
  15. (function() {
  16. oop.implement(this, EventEmitter);
  17. this.getTokenizer = function() {
  18. function TabstopToken(str, _, stack) {
  19. str = str.substr(1);
  20. if (/^\d+$/.test(str) && !stack.inFormatString)
  21. return [{tabstopId: parseInt(str, 10)}];
  22. return [{text: str}];
  23. }
  24. function escape(ch) {
  25. return "(?:[^\\\\" + ch + "]|\\\\.)";
  26. }
  27. SnippetManager.$tokenizer = new Tokenizer({
  28. start: [
  29. {regex: /:/, onMatch: function(val, state, stack) {
  30. if (stack.length && stack[0].expectIf) {
  31. stack[0].expectIf = false;
  32. stack[0].elseBranch = stack[0];
  33. return [stack[0]];
  34. }
  35. return ":";
  36. }},
  37. {regex: /\\./, onMatch: function(val, state, stack) {
  38. var ch = val[1];
  39. if (ch == "}" && stack.length) {
  40. val = ch;
  41. }else if ("`$\\".indexOf(ch) != -1) {
  42. val = ch;
  43. } else if (stack.inFormatString) {
  44. if (ch == "n")
  45. val = "\n";
  46. else if (ch == "t")
  47. val = "\n";
  48. else if ("ulULE".indexOf(ch) != -1) {
  49. val = {changeCase: ch, local: ch > "a"};
  50. }
  51. }
  52. return [val];
  53. }},
  54. {regex: /}/, onMatch: function(val, state, stack) {
  55. return [stack.length ? stack.shift() : val];
  56. }},
  57. {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken},
  58. {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) {
  59. var t = TabstopToken(str.substr(1), state, stack);
  60. stack.unshift(t[0]);
  61. return t;
  62. }, next: "snippetVar"},
  63. {regex: /\n/, token: "newline", merge: false}
  64. ],
  65. snippetVar: [
  66. {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) {
  67. stack[0].choices = val.slice(1, -1).split(",");
  68. }, next: "start"},
  69. {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?",
  70. onMatch: function(val, state, stack) {
  71. var ts = stack[0];
  72. ts.fmtString = val;
  73. val = this.splitRegex.exec(val);
  74. ts.guard = val[1];
  75. ts.fmt = val[2];
  76. ts.flag = val[3];
  77. return "";
  78. }, next: "start"},
  79. {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) {
  80. stack[0].code = val.splice(1, -1);
  81. return "";
  82. }, next: "start"},
  83. {regex: "\\?", onMatch: function(val, state, stack) {
  84. if (stack[0])
  85. stack[0].expectIf = true;
  86. }, next: "start"},
  87. {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"}
  88. ],
  89. formatString: [
  90. {regex: "/(" + escape("/") + "+)/", token: "regex"},
  91. {regex: "", onMatch: function(val, state, stack) {
  92. stack.inFormatString = true;
  93. }, next: "start"}
  94. ]
  95. });
  96. SnippetManager.prototype.getTokenizer = function() {
  97. return SnippetManager.$tokenizer;
  98. };
  99. return SnippetManager.$tokenizer;
  100. };
  101. this.tokenizeTmSnippet = function(str, startState) {
  102. return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) {
  103. return x.value || x;
  104. });
  105. };
  106. this.$getDefaultValue = function(editor, name) {
  107. if (/^[A-Z]\d+$/.test(name)) {
  108. var i = name.substr(1);
  109. return (this.variables[name[0] + "__"] || {})[i];
  110. }
  111. if (/^\d+$/.test(name)) {
  112. return (this.variables.__ || {})[name];
  113. }
  114. name = name.replace(/^TM_/, "");
  115. if (!editor)
  116. return;
  117. var s = editor.session;
  118. switch(name) {
  119. case "CURRENT_WORD":
  120. var r = s.getWordRange();
  121. case "SELECTION":
  122. case "SELECTED_TEXT":
  123. return s.getTextRange(r);
  124. case "CURRENT_LINE":
  125. return s.getLine(editor.getCursorPosition().row);
  126. case "PREV_LINE": // not possible in textmate
  127. return s.getLine(editor.getCursorPosition().row - 1);
  128. case "LINE_INDEX":
  129. return editor.getCursorPosition().column;
  130. case "LINE_NUMBER":
  131. return editor.getCursorPosition().row + 1;
  132. case "SOFT_TABS":
  133. return s.getUseSoftTabs() ? "YES" : "NO";
  134. case "TAB_SIZE":
  135. return s.getTabSize();
  136. case "FILENAME":
  137. case "FILEPATH":
  138. return "";
  139. case "FULLNAME":
  140. return "Ace";
  141. }
  142. };
  143. this.variables = {};
  144. this.getVariableValue = function(editor, varName) {
  145. if (this.variables.hasOwnProperty(varName))
  146. return this.variables[varName](editor, varName) || "";
  147. return this.$getDefaultValue(editor, varName) || "";
  148. };
  149. this.tmStrFormat = function(str, ch, editor) {
  150. var flag = ch.flag || "";
  151. var re = ch.guard;
  152. re = new RegExp(re, flag.replace(/[^gi]/, ""));
  153. var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString");
  154. var _self = this;
  155. var formatted = str.replace(re, function() {
  156. _self.variables.__ = arguments;
  157. var fmtParts = _self.resolveVariables(fmtTokens, editor);
  158. var gChangeCase = "E";
  159. for (var i = 0; i < fmtParts.length; i++) {
  160. var ch = fmtParts[i];
  161. if (typeof ch == "object") {
  162. fmtParts[i] = "";
  163. if (ch.changeCase && ch.local) {
  164. var next = fmtParts[i + 1];
  165. if (next && typeof next == "string") {
  166. if (ch.changeCase == "u")
  167. fmtParts[i] = next[0].toUpperCase();
  168. else
  169. fmtParts[i] = next[0].toLowerCase();
  170. fmtParts[i + 1] = next.substr(1);
  171. }
  172. } else if (ch.changeCase) {
  173. gChangeCase = ch.changeCase;
  174. }
  175. } else if (gChangeCase == "U") {
  176. fmtParts[i] = ch.toUpperCase();
  177. } else if (gChangeCase == "L") {
  178. fmtParts[i] = ch.toLowerCase();
  179. }
  180. }
  181. return fmtParts.join("");
  182. });
  183. this.variables.__ = null;
  184. return formatted;
  185. };
  186. this.resolveVariables = function(snippet, editor) {
  187. var result = [];
  188. for (var i = 0; i < snippet.length; i++) {
  189. var ch = snippet[i];
  190. if (typeof ch == "string") {
  191. result.push(ch);
  192. } else if (typeof ch != "object") {
  193. continue;
  194. } else if (ch.skip) {
  195. gotoNext(ch);
  196. } else if (ch.processed < i) {
  197. continue;
  198. } else if (ch.text) {
  199. var value = this.getVariableValue(editor, ch.text);
  200. if (value && ch.fmtString)
  201. value = this.tmStrFormat(value, ch);
  202. ch.processed = i;
  203. if (ch.expectIf == null) {
  204. if (value) {
  205. result.push(value);
  206. gotoNext(ch);
  207. }
  208. } else {
  209. if (value) {
  210. ch.skip = ch.elseBranch;
  211. } else
  212. gotoNext(ch);
  213. }
  214. } else if (ch.tabstopId != null) {
  215. result.push(ch);
  216. } else if (ch.changeCase != null) {
  217. result.push(ch);
  218. }
  219. }
  220. function gotoNext(ch) {
  221. var i1 = snippet.indexOf(ch, i + 1);
  222. if (i1 != -1)
  223. i = i1;
  224. }
  225. return result;
  226. };
  227. this.insertSnippetForSelection = function(editor, snippetText) {
  228. var cursor = editor.getCursorPosition();
  229. var line = editor.session.getLine(cursor.row);
  230. var tabString = editor.session.getTabString();
  231. var indentString = line.match(/^\s*/)[0];
  232. if (cursor.column < indentString.length)
  233. indentString = indentString.slice(0, cursor.column);
  234. snippetText = snippetText.replace(/\r/g, "");
  235. var tokens = this.tokenizeTmSnippet(snippetText);
  236. tokens = this.resolveVariables(tokens, editor);
  237. tokens = tokens.map(function(x) {
  238. if (x == "\n")
  239. return x + indentString;
  240. if (typeof x == "string")
  241. return x.replace(/\t/g, tabString);
  242. return x;
  243. });
  244. var tabstops = [];
  245. tokens.forEach(function(p, i) {
  246. if (typeof p != "object")
  247. return;
  248. var id = p.tabstopId;
  249. var ts = tabstops[id];
  250. if (!ts) {
  251. ts = tabstops[id] = [];
  252. ts.index = id;
  253. ts.value = "";
  254. }
  255. if (ts.indexOf(p) !== -1)
  256. return;
  257. ts.push(p);
  258. var i1 = tokens.indexOf(p, i + 1);
  259. if (i1 === -1)
  260. return;
  261. var value = tokens.slice(i + 1, i1);
  262. var isNested = value.some(function(t) {return typeof t === "object"});
  263. if (isNested && !ts.value) {
  264. ts.value = value;
  265. } else if (value.length && (!ts.value || typeof ts.value !== "string")) {
  266. ts.value = value.join("");
  267. }
  268. });
  269. tabstops.forEach(function(ts) {ts.length = 0});
  270. var expanding = {};
  271. function copyValue(val) {
  272. var copy = [];
  273. for (var i = 0; i < val.length; i++) {
  274. var p = val[i];
  275. if (typeof p == "object") {
  276. if (expanding[p.tabstopId])
  277. continue;
  278. var j = val.lastIndexOf(p, i - 1);
  279. p = copy[j] || {tabstopId: p.tabstopId};
  280. }
  281. copy[i] = p;
  282. }
  283. return copy;
  284. }
  285. for (var i = 0; i < tokens.length; i++) {
  286. var p = tokens[i];
  287. if (typeof p != "object")
  288. continue;
  289. var id = p.tabstopId;
  290. var i1 = tokens.indexOf(p, i + 1);
  291. if (expanding[id]) {
  292. if (expanding[id] === p)
  293. expanding[id] = null;
  294. continue;
  295. }
  296. var ts = tabstops[id];
  297. var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value);
  298. arg.unshift(i + 1, Math.max(0, i1 - i));
  299. arg.push(p);
  300. expanding[id] = p;
  301. tokens.splice.apply(tokens, arg);
  302. if (ts.indexOf(p) === -1)
  303. ts.push(p);
  304. }
  305. var row = 0, column = 0;
  306. var text = "";
  307. tokens.forEach(function(t) {
  308. if (typeof t === "string") {
  309. var lines = t.split("\n");
  310. if (lines.length > 1){
  311. column = lines[lines.length - 1].length;
  312. row += lines.length - 1;
  313. } else
  314. column += t.length;
  315. text += t;
  316. } else {
  317. if (!t.start)
  318. t.start = {row: row, column: column};
  319. else
  320. t.end = {row: row, column: column};
  321. }
  322. });
  323. var range = editor.getSelectionRange();
  324. var end = editor.session.replace(range, text);
  325. var tabstopManager = new TabstopManager(editor);
  326. var selectionId = editor.inVirtualSelectionMode && editor.selection.index;
  327. tabstopManager.addTabstops(tabstops, range.start, end, selectionId);
  328. };
  329. this.insertSnippet = function(editor, snippetText) {
  330. var self = this;
  331. if (editor.inVirtualSelectionMode)
  332. return self.insertSnippetForSelection(editor, snippetText);
  333. editor.forEachSelection(function() {
  334. self.insertSnippetForSelection(editor, snippetText);
  335. }, null, {keepOrder: true});
  336. if (editor.tabstopManager)
  337. editor.tabstopManager.tabNext();
  338. };
  339. this.$getScope = function(editor) {
  340. var scope = editor.session.$mode.$id || "";
  341. scope = scope.split("/").pop();
  342. if (scope === "html" || scope === "php") {
  343. if (scope === "php" && !editor.session.$mode.inlinePhp)
  344. scope = "html";
  345. var c = editor.getCursorPosition();
  346. var state = editor.session.getState(c.row);
  347. if (typeof state === "object") {
  348. state = state[0];
  349. }
  350. if (state.substring) {
  351. if (state.substring(0, 3) == "js-")
  352. scope = "javascript";
  353. else if (state.substring(0, 4) == "css-")
  354. scope = "css";
  355. else if (state.substring(0, 4) == "php-")
  356. scope = "php";
  357. }
  358. }
  359. return scope;
  360. };
  361. this.getActiveScopes = function(editor) {
  362. var scope = this.$getScope(editor);
  363. var scopes = [scope];
  364. var snippetMap = this.snippetMap;
  365. if (snippetMap[scope] && snippetMap[scope].includeScopes) {
  366. scopes.push.apply(scopes, snippetMap[scope].includeScopes);
  367. }
  368. scopes.push("_");
  369. return scopes;
  370. };
  371. this.expandWithTab = function(editor, options) {
  372. var self = this;
  373. var result = editor.forEachSelection(function() {
  374. return self.expandSnippetForSelection(editor, options);
  375. }, null, {keepOrder: true});
  376. if (result && editor.tabstopManager)
  377. editor.tabstopManager.tabNext();
  378. return result;
  379. };
  380. this.expandSnippetForSelection = function(editor, options) {
  381. var cursor = editor.getCursorPosition();
  382. var line = editor.session.getLine(cursor.row);
  383. var before = line.substring(0, cursor.column);
  384. var after = line.substr(cursor.column);
  385. var snippetMap = this.snippetMap;
  386. var snippet;
  387. this.getActiveScopes(editor).some(function(scope) {
  388. var snippets = snippetMap[scope];
  389. if (snippets)
  390. snippet = this.findMatchingSnippet(snippets, before, after);
  391. return !!snippet;
  392. }, this);
  393. if (!snippet)
  394. return false;
  395. if (options && options.dryRun)
  396. return true;
  397. editor.session.doc.removeInLine(cursor.row,
  398. cursor.column - snippet.replaceBefore.length,
  399. cursor.column + snippet.replaceAfter.length
  400. );
  401. this.variables.M__ = snippet.matchBefore;
  402. this.variables.T__ = snippet.matchAfter;
  403. this.insertSnippetForSelection(editor, snippet.content);
  404. this.variables.M__ = this.variables.T__ = null;
  405. return true;
  406. };
  407. this.findMatchingSnippet = function(snippetList, before, after) {
  408. for (var i = snippetList.length; i--;) {
  409. var s = snippetList[i];
  410. if (s.startRe && !s.startRe.test(before))
  411. continue;
  412. if (s.endRe && !s.endRe.test(after))
  413. continue;
  414. if (!s.startRe && !s.endRe)
  415. continue;
  416. s.matchBefore = s.startRe ? s.startRe.exec(before) : [""];
  417. s.matchAfter = s.endRe ? s.endRe.exec(after) : [""];
  418. s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : "";
  419. s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : "";
  420. return s;
  421. }
  422. };
  423. this.snippetMap = {};
  424. this.snippetNameMap = {};
  425. this.register = function(snippets, scope) {
  426. var snippetMap = this.snippetMap;
  427. var snippetNameMap = this.snippetNameMap;
  428. var self = this;
  429. if (!snippets)
  430. snippets = [];
  431. function wrapRegexp(src) {
  432. if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src))
  433. src = "(?:" + src + ")";
  434. return src || "";
  435. }
  436. function guardedRegexp(re, guard, opening) {
  437. re = wrapRegexp(re);
  438. guard = wrapRegexp(guard);
  439. if (opening) {
  440. re = guard + re;
  441. if (re && re[re.length - 1] != "$")
  442. re = re + "$";
  443. } else {
  444. re = re + guard;
  445. if (re && re[0] != "^")
  446. re = "^" + re;
  447. }
  448. return new RegExp(re);
  449. }
  450. function addSnippet(s) {
  451. if (!s.scope)
  452. s.scope = scope || "_";
  453. scope = s.scope;
  454. if (!snippetMap[scope]) {
  455. snippetMap[scope] = [];
  456. snippetNameMap[scope] = {};
  457. }
  458. var map = snippetNameMap[scope];
  459. if (s.name) {
  460. var old = map[s.name];
  461. if (old)
  462. self.unregister(old);
  463. map[s.name] = s;
  464. }
  465. snippetMap[scope].push(s);
  466. if (s.tabTrigger && !s.trigger) {
  467. if (!s.guard && /^\w/.test(s.tabTrigger))
  468. s.guard = "\\b";
  469. s.trigger = lang.escapeRegExp(s.tabTrigger);
  470. }
  471. if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard)
  472. return;
  473. s.startRe = guardedRegexp(s.trigger, s.guard, true);
  474. s.triggerRe = new RegExp(s.trigger, "", true);
  475. s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true);
  476. s.endTriggerRe = new RegExp(s.endTrigger, "", true);
  477. }
  478. if (snippets && snippets.content)
  479. addSnippet(snippets);
  480. else if (Array.isArray(snippets))
  481. snippets.forEach(addSnippet);
  482. this._signal("registerSnippets", {scope: scope});
  483. };
  484. this.unregister = function(snippets, scope) {
  485. var snippetMap = this.snippetMap;
  486. var snippetNameMap = this.snippetNameMap;
  487. function removeSnippet(s) {
  488. var nameMap = snippetNameMap[s.scope||scope];
  489. if (nameMap && nameMap[s.name]) {
  490. delete nameMap[s.name];
  491. var map = snippetMap[s.scope||scope];
  492. var i = map && map.indexOf(s);
  493. if (i >= 0)
  494. map.splice(i, 1);
  495. }
  496. }
  497. if (snippets.content)
  498. removeSnippet(snippets);
  499. else if (Array.isArray(snippets))
  500. snippets.forEach(removeSnippet);
  501. };
  502. this.parseSnippetFile = function(str) {
  503. str = str.replace(/\r/g, "");
  504. var list = [], snippet = {};
  505. var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;
  506. var m;
  507. while (m = re.exec(str)) {
  508. if (m[1]) {
  509. try {
  510. snippet = JSON.parse(m[1]);
  511. list.push(snippet);
  512. } catch (e) {}
  513. } if (m[4]) {
  514. snippet.content = m[4].replace(/^\t/gm, "");
  515. list.push(snippet);
  516. snippet = {};
  517. } else {
  518. var key = m[2], val = m[3];
  519. if (key == "regex") {
  520. var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g;
  521. snippet.guard = guardRe.exec(val)[1];
  522. snippet.trigger = guardRe.exec(val)[1];
  523. snippet.endTrigger = guardRe.exec(val)[1];
  524. snippet.endGuard = guardRe.exec(val)[1];
  525. } else if (key == "snippet") {
  526. snippet.tabTrigger = val.match(/^\S*/)[0];
  527. if (!snippet.name)
  528. snippet.name = val;
  529. } else {
  530. snippet[key] = val;
  531. }
  532. }
  533. }
  534. return list;
  535. };
  536. this.getSnippetByName = function(name, editor) {
  537. var snippetMap = this.snippetNameMap;
  538. var snippet;
  539. this.getActiveScopes(editor).some(function(scope) {
  540. var snippets = snippetMap[scope];
  541. if (snippets)
  542. snippet = snippets[name];
  543. return !!snippet;
  544. }, this);
  545. return snippet;
  546. };
  547. }).call(SnippetManager.prototype);
  548. var TabstopManager = function(editor) {
  549. if (editor.tabstopManager)
  550. return editor.tabstopManager;
  551. editor.tabstopManager = this;
  552. this.$onChange = this.onChange.bind(this);
  553. this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule;
  554. this.$onChangeSession = this.onChangeSession.bind(this);
  555. this.$onAfterExec = this.onAfterExec.bind(this);
  556. this.attach(editor);
  557. };
  558. (function() {
  559. this.attach = function(editor) {
  560. this.index = 0;
  561. this.ranges = [];
  562. this.tabstops = [];
  563. this.$openTabstops = null;
  564. this.selectedTabstop = null;
  565. this.editor = editor;
  566. this.editor.on("change", this.$onChange);
  567. this.editor.on("changeSelection", this.$onChangeSelection);
  568. this.editor.on("changeSession", this.$onChangeSession);
  569. this.editor.commands.on("afterExec", this.$onAfterExec);
  570. this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  571. };
  572. this.detach = function() {
  573. this.tabstops.forEach(this.removeTabstopMarkers, this);
  574. this.ranges = null;
  575. this.tabstops = null;
  576. this.selectedTabstop = null;
  577. this.editor.removeListener("change", this.$onChange);
  578. this.editor.removeListener("changeSelection", this.$onChangeSelection);
  579. this.editor.removeListener("changeSession", this.$onChangeSession);
  580. this.editor.commands.removeListener("afterExec", this.$onAfterExec);
  581. this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
  582. this.editor.tabstopManager = null;
  583. this.editor = null;
  584. };
  585. this.onChange = function(delta) {
  586. var changeRange = delta;
  587. var isRemove = delta.action[0] == "r";
  588. var start = delta.start;
  589. var end = delta.end;
  590. var startRow = start.row;
  591. var endRow = end.row;
  592. var lineDif = endRow - startRow;
  593. var colDiff = end.column - start.column;
  594. if (isRemove) {
  595. lineDif = -lineDif;
  596. colDiff = -colDiff;
  597. }
  598. if (!this.$inChange && isRemove) {
  599. var ts = this.selectedTabstop;
  600. var changedOutside = ts && !ts.some(function(r) {
  601. return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0;
  602. });
  603. if (changedOutside)
  604. return this.detach();
  605. }
  606. var ranges = this.ranges;
  607. for (var i = 0; i < ranges.length; i++) {
  608. var r = ranges[i];
  609. if (r.end.row < start.row)
  610. continue;
  611. if (isRemove && comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) {
  612. this.removeRange(r);
  613. i--;
  614. continue;
  615. }
  616. if (r.start.row == startRow && r.start.column > start.column)
  617. r.start.column += colDiff;
  618. if (r.end.row == startRow && r.end.column >= start.column)
  619. r.end.column += colDiff;
  620. if (r.start.row >= startRow)
  621. r.start.row += lineDif;
  622. if (r.end.row >= startRow)
  623. r.end.row += lineDif;
  624. if (comparePoints(r.start, r.end) > 0)
  625. this.removeRange(r);
  626. }
  627. if (!ranges.length)
  628. this.detach();
  629. };
  630. this.updateLinkedFields = function() {
  631. var ts = this.selectedTabstop;
  632. if (!ts || !ts.hasLinkedRanges)
  633. return;
  634. this.$inChange = true;
  635. var session = this.editor.session;
  636. var text = session.getTextRange(ts.firstNonLinked);
  637. for (var i = ts.length; i--;) {
  638. var range = ts[i];
  639. if (!range.linked)
  640. continue;
  641. var fmt = exports.snippetManager.tmStrFormat(text, range.original);
  642. session.replace(range, fmt);
  643. }
  644. this.$inChange = false;
  645. };
  646. this.onAfterExec = function(e) {
  647. if (e.command && !e.command.readOnly)
  648. this.updateLinkedFields();
  649. };
  650. this.onChangeSelection = function() {
  651. if (!this.editor)
  652. return;
  653. var lead = this.editor.selection.lead;
  654. var anchor = this.editor.selection.anchor;
  655. var isEmpty = this.editor.selection.isEmpty();
  656. for (var i = this.ranges.length; i--;) {
  657. if (this.ranges[i].linked)
  658. continue;
  659. var containsLead = this.ranges[i].contains(lead.row, lead.column);
  660. var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column);
  661. if (containsLead && containsAnchor)
  662. return;
  663. }
  664. this.detach();
  665. };
  666. this.onChangeSession = function() {
  667. this.detach();
  668. };
  669. this.tabNext = function(dir) {
  670. var max = this.tabstops.length;
  671. var index = this.index + (dir || 1);
  672. index = Math.min(Math.max(index, 1), max);
  673. if (index == max)
  674. index = 0;
  675. this.selectTabstop(index);
  676. if (index === 0)
  677. this.detach();
  678. };
  679. this.selectTabstop = function(index) {
  680. this.$openTabstops = null;
  681. var ts = this.tabstops[this.index];
  682. if (ts)
  683. this.addTabstopMarkers(ts);
  684. this.index = index;
  685. ts = this.tabstops[this.index];
  686. if (!ts || !ts.length)
  687. return;
  688. this.selectedTabstop = ts;
  689. if (!this.editor.inVirtualSelectionMode) {
  690. var sel = this.editor.multiSelect;
  691. sel.toSingleRange(ts.firstNonLinked.clone());
  692. for (var i = ts.length; i--;) {
  693. if (ts.hasLinkedRanges && ts[i].linked)
  694. continue;
  695. sel.addRange(ts[i].clone(), true);
  696. }
  697. if (sel.ranges[0])
  698. sel.addRange(sel.ranges[0].clone());
  699. } else {
  700. this.editor.selection.setRange(ts.firstNonLinked);
  701. }
  702. this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  703. };
  704. this.addTabstops = function(tabstops, start, end) {
  705. if (!this.$openTabstops)
  706. this.$openTabstops = [];
  707. if (!tabstops[0]) {
  708. var p = Range.fromPoints(end, end);
  709. moveRelative(p.start, start);
  710. moveRelative(p.end, start);
  711. tabstops[0] = [p];
  712. tabstops[0].index = 0;
  713. }
  714. var i = this.index;
  715. var arg = [i + 1, 0];
  716. var ranges = this.ranges;
  717. tabstops.forEach(function(ts, index) {
  718. var dest = this.$openTabstops[index] || ts;
  719. for (var i = ts.length; i--;) {
  720. var p = ts[i];
  721. var range = Range.fromPoints(p.start, p.end || p.start);
  722. movePoint(range.start, start);
  723. movePoint(range.end, start);
  724. range.original = p;
  725. range.tabstop = dest;
  726. ranges.push(range);
  727. if (dest != ts)
  728. dest.unshift(range);
  729. else
  730. dest[i] = range;
  731. if (p.fmtString) {
  732. range.linked = true;
  733. dest.hasLinkedRanges = true;
  734. } else if (!dest.firstNonLinked)
  735. dest.firstNonLinked = range;
  736. }
  737. if (!dest.firstNonLinked)
  738. dest.hasLinkedRanges = false;
  739. if (dest === ts) {
  740. arg.push(dest);
  741. this.$openTabstops[index] = dest;
  742. }
  743. this.addTabstopMarkers(dest);
  744. }, this);
  745. if (arg.length > 2) {
  746. if (this.tabstops.length)
  747. arg.push(arg.splice(2, 1)[0]);
  748. this.tabstops.splice.apply(this.tabstops, arg);
  749. }
  750. };
  751. this.addTabstopMarkers = function(ts) {
  752. var session = this.editor.session;
  753. ts.forEach(function(range) {
  754. if (!range.markerId)
  755. range.markerId = session.addMarker(range, "ace_snippet-marker", "text");
  756. });
  757. };
  758. this.removeTabstopMarkers = function(ts) {
  759. var session = this.editor.session;
  760. ts.forEach(function(range) {
  761. session.removeMarker(range.markerId);
  762. range.markerId = null;
  763. });
  764. };
  765. this.removeRange = function(range) {
  766. var i = range.tabstop.indexOf(range);
  767. range.tabstop.splice(i, 1);
  768. i = this.ranges.indexOf(range);
  769. this.ranges.splice(i, 1);
  770. this.editor.session.removeMarker(range.markerId);
  771. if (!range.tabstop.length) {
  772. i = this.tabstops.indexOf(range.tabstop);
  773. if (i != -1)
  774. this.tabstops.splice(i, 1);
  775. if (!this.tabstops.length)
  776. this.detach();
  777. }
  778. };
  779. this.keyboardHandler = new HashHandler();
  780. this.keyboardHandler.bindKeys({
  781. "Tab": function(ed) {
  782. if (exports.snippetManager && exports.snippetManager.expandWithTab(ed)) {
  783. return;
  784. }
  785. ed.tabstopManager.tabNext(1);
  786. },
  787. "Shift-Tab": function(ed) {
  788. ed.tabstopManager.tabNext(-1);
  789. },
  790. "Esc": function(ed) {
  791. ed.tabstopManager.detach();
  792. },
  793. "Return": function(ed) {
  794. return false;
  795. }
  796. });
  797. }).call(TabstopManager.prototype);
  798. var changeTracker = {};
  799. changeTracker.onChange = Anchor.prototype.onChange;
  800. changeTracker.setPosition = function(row, column) {
  801. this.pos.row = row;
  802. this.pos.column = column;
  803. };
  804. changeTracker.update = function(pos, delta, $insertRight) {
  805. this.$insertRight = $insertRight;
  806. this.pos = pos;
  807. this.onChange(delta);
  808. };
  809. var movePoint = function(point, diff) {
  810. if (point.row == 0)
  811. point.column += diff.column;
  812. point.row += diff.row;
  813. };
  814. var moveRelative = function(point, start) {
  815. if (point.row == start.row)
  816. point.column -= start.column;
  817. point.row -= start.row;
  818. };
  819. require("./lib/dom").importCssString("\
  820. .ace_snippet-marker {\
  821. -moz-box-sizing: border-box;\
  822. box-sizing: border-box;\
  823. background: rgba(194, 193, 208, 0.09);\
  824. border: 1px dotted rgba(211, 208, 235, 0.62);\
  825. position: absolute;\
  826. }");
  827. exports.snippetManager = new SnippetManager();
  828. var Editor = require("./editor").Editor;
  829. (function() {
  830. this.insertSnippet = function(content, options) {
  831. return exports.snippetManager.insertSnippet(this, content, options);
  832. };
  833. this.expandSnippet = function(options) {
  834. return exports.snippetManager.expandWithTab(this, options);
  835. };
  836. }).call(Editor.prototype);
  837. });
  838. ace.define("ace/ext/emmet",["require","exports","module","ace/keyboard/hash_handler","ace/editor","ace/snippets","ace/range","resources","resources","tabStops","resources","utils","actions","ace/config","ace/config"], function(require, exports, module) {
  839. "use strict";
  840. var HashHandler = require("ace/keyboard/hash_handler").HashHandler;
  841. var Editor = require("ace/editor").Editor;
  842. var snippetManager = require("ace/snippets").snippetManager;
  843. var Range = require("ace/range").Range;
  844. var emmet, emmetPath;
  845. function AceEmmetEditor() {}
  846. AceEmmetEditor.prototype = {
  847. setupContext: function(editor) {
  848. this.ace = editor;
  849. this.indentation = editor.session.getTabString();
  850. if (!emmet)
  851. emmet = window.emmet;
  852. var resources = emmet.resources || emmet.require("resources");
  853. resources.setVariable("indentation", this.indentation);
  854. this.$syntax = null;
  855. this.$syntax = this.getSyntax();
  856. },
  857. getSelectionRange: function() {
  858. var range = this.ace.getSelectionRange();
  859. var doc = this.ace.session.doc;
  860. return {
  861. start: doc.positionToIndex(range.start),
  862. end: doc.positionToIndex(range.end)
  863. };
  864. },
  865. createSelection: function(start, end) {
  866. var doc = this.ace.session.doc;
  867. this.ace.selection.setRange({
  868. start: doc.indexToPosition(start),
  869. end: doc.indexToPosition(end)
  870. });
  871. },
  872. getCurrentLineRange: function() {
  873. var ace = this.ace;
  874. var row = ace.getCursorPosition().row;
  875. var lineLength = ace.session.getLine(row).length;
  876. var index = ace.session.doc.positionToIndex({row: row, column: 0});
  877. return {
  878. start: index,
  879. end: index + lineLength
  880. };
  881. },
  882. getCaretPos: function(){
  883. var pos = this.ace.getCursorPosition();
  884. return this.ace.session.doc.positionToIndex(pos);
  885. },
  886. setCaretPos: function(index){
  887. var pos = this.ace.session.doc.indexToPosition(index);
  888. this.ace.selection.moveToPosition(pos);
  889. },
  890. getCurrentLine: function() {
  891. var row = this.ace.getCursorPosition().row;
  892. return this.ace.session.getLine(row);
  893. },
  894. replaceContent: function(value, start, end, noIndent) {
  895. if (end == null)
  896. end = start == null ? this.getContent().length : start;
  897. if (start == null)
  898. start = 0;
  899. var editor = this.ace;
  900. var doc = editor.session.doc;
  901. var range = Range.fromPoints(doc.indexToPosition(start), doc.indexToPosition(end));
  902. editor.session.remove(range);
  903. range.end = range.start;
  904. value = this.$updateTabstops(value);
  905. snippetManager.insertSnippet(editor, value);
  906. },
  907. getContent: function(){
  908. return this.ace.getValue();
  909. },
  910. getSyntax: function() {
  911. if (this.$syntax)
  912. return this.$syntax;
  913. var syntax = this.ace.session.$modeId.split("/").pop();
  914. if (syntax == "html" || syntax == "php") {
  915. var cursor = this.ace.getCursorPosition();
  916. var state = this.ace.session.getState(cursor.row);
  917. if (typeof state != "string")
  918. state = state[0];
  919. if (state) {
  920. state = state.split("-");
  921. if (state.length > 1)
  922. syntax = state[0];
  923. else if (syntax == "php")
  924. syntax = "html";
  925. }
  926. }
  927. return syntax;
  928. },
  929. getProfileName: function() {
  930. var resources = emmet.resources || emmet.require("resources");
  931. switch (this.getSyntax()) {
  932. case "css": return "css";
  933. case "xml":
  934. case "xsl":
  935. return "xml";
  936. case "html":
  937. var profile = resources.getVariable("profile");
  938. if (!profile)
  939. profile = this.ace.session.getLines(0,2).join("").search(/<!DOCTYPE[^>]+XHTML/i) != -1 ? "xhtml": "html";
  940. return profile;
  941. default:
  942. var mode = this.ace.session.$mode;
  943. return mode.emmetConfig && mode.emmetConfig.profile || "xhtml";
  944. }
  945. },
  946. prompt: function(title) {
  947. return prompt(title);
  948. },
  949. getSelection: function() {
  950. return this.ace.session.getTextRange();
  951. },
  952. getFilePath: function() {
  953. return "";
  954. },
  955. $updateTabstops: function(value) {
  956. var base = 1000;
  957. var zeroBase = 0;
  958. var lastZero = null;
  959. var ts = emmet.tabStops || emmet.require('tabStops');
  960. var resources = emmet.resources || emmet.require("resources");
  961. var settings = resources.getVocabulary("user");
  962. var tabstopOptions = {
  963. tabstop: function(data) {
  964. var group = parseInt(data.group, 10);
  965. var isZero = group === 0;
  966. if (isZero)
  967. group = ++zeroBase;
  968. else
  969. group += base;
  970. var placeholder = data.placeholder;
  971. if (placeholder) {
  972. placeholder = ts.processText(placeholder, tabstopOptions);
  973. }
  974. var result = '${' + group + (placeholder ? ':' + placeholder : '') + '}';
  975. if (isZero) {
  976. lastZero = [data.start, result];
  977. }
  978. return result;
  979. },
  980. escape: function(ch) {
  981. if (ch == '$') return '\\$';
  982. if (ch == '\\') return '\\\\';
  983. return ch;
  984. }
  985. };
  986. value = ts.processText(value, tabstopOptions);
  987. if (settings.variables['insert_final_tabstop'] && !/\$\{0\}$/.test(value)) {
  988. value += '${0}';
  989. } else if (lastZero) {
  990. var common = emmet.utils ? emmet.utils.common : emmet.require('utils');
  991. value = common.replaceSubstring(value, '${0}', lastZero[0], lastZero[1]);
  992. }
  993. return value;
  994. }
  995. };
  996. var keymap = {
  997. expand_abbreviation: {"mac": "ctrl+alt+e", "win": "alt+e"},
  998. match_pair_outward: {"mac": "ctrl+d", "win": "ctrl+,"},
  999. match_pair_inward: {"mac": "ctrl+j", "win": "ctrl+shift+0"},
  1000. matching_pair: {"mac": "ctrl+alt+j", "win": "alt+j"},
  1001. next_edit_point: "alt+right",
  1002. prev_edit_point: "alt+left",
  1003. toggle_comment: {"mac": "command+/", "win": "ctrl+/"},
  1004. split_join_tag: {"mac": "shift+command+'", "win": "shift+ctrl+`"},
  1005. remove_tag: {"mac": "command+'", "win": "shift+ctrl+;"},
  1006. evaluate_math_expression: {"mac": "shift+command+y", "win": "shift+ctrl+y"},
  1007. increment_number_by_1: "ctrl+up",
  1008. decrement_number_by_1: "ctrl+down",
  1009. increment_number_by_01: "alt+up",
  1010. decrement_number_by_01: "alt+down",
  1011. increment_number_by_10: {"mac": "alt+command+up", "win": "shift+alt+up"},
  1012. decrement_number_by_10: {"mac": "alt+command+down", "win": "shift+alt+down"},
  1013. select_next_item: {"mac": "shift+command+.", "win": "shift+ctrl+."},
  1014. select_previous_item: {"mac": "shift+command+,", "win": "shift+ctrl+,"},
  1015. reflect_css_value: {"mac": "shift+command+r", "win": "shift+ctrl+r"},
  1016. encode_decode_data_url: {"mac": "shift+ctrl+d", "win": "ctrl+'"},
  1017. expand_abbreviation_with_tab: "Tab",
  1018. wrap_with_abbreviation: {"mac": "shift+ctrl+a", "win": "shift+ctrl+a"}
  1019. };
  1020. var editorProxy = new AceEmmetEditor();
  1021. exports.commands = new HashHandler();
  1022. exports.runEmmetCommand = function runEmmetCommand(editor) {
  1023. try {
  1024. editorProxy.setupContext(editor);
  1025. var actions = emmet.actions || emmet.require("actions");
  1026. if (this.action == "expand_abbreviation_with_tab") {
  1027. if (!editor.selection.isEmpty())
  1028. return false;
  1029. var pos = editor.selection.lead;
  1030. var token = editor.session.getTokenAt(pos.row, pos.column);
  1031. if (token && /\btag\b/.test(token.type))
  1032. return false;
  1033. }
  1034. if (this.action == "wrap_with_abbreviation") {
  1035. return setTimeout(function() {
  1036. actions.run("wrap_with_abbreviation", editorProxy);
  1037. }, 0);
  1038. }
  1039. var result = actions.run(this.action, editorProxy);
  1040. } catch(e) {
  1041. if (!emmet) {
  1042. load(runEmmetCommand.bind(this, editor));
  1043. return true;
  1044. }
  1045. editor._signal("changeStatus", typeof e == "string" ? e : e.message);
  1046. console.log(e);
  1047. result = false;
  1048. }
  1049. return result;
  1050. };
  1051. for (var command in keymap) {
  1052. exports.commands.addCommand({
  1053. name: "emmet:" + command,
  1054. action: command,
  1055. bindKey: keymap[command],
  1056. exec: exports.runEmmetCommand,
  1057. multiSelectAction: "forEach"
  1058. });
  1059. }
  1060. exports.updateCommands = function(editor, enabled) {
  1061. if (enabled) {
  1062. editor.keyBinding.addKeyboardHandler(exports.commands);
  1063. } else {
  1064. editor.keyBinding.removeKeyboardHandler(exports.commands);
  1065. }
  1066. };
  1067. exports.isSupportedMode = function(mode) {
  1068. if (!mode) return false;
  1069. if (mode.emmetConfig) return true;
  1070. var id = mode.$id || mode;
  1071. return /css|less|scss|sass|stylus|html|php|twig|ejs|handlebars/.test(id);
  1072. };
  1073. exports.isAvailable = function(editor, command) {
  1074. if (/(evaluate_math_expression|expand_abbreviation)$/.test(command))
  1075. return true;
  1076. var mode = editor.session.$mode;
  1077. var isSupported = exports.isSupportedMode(mode);
  1078. if (isSupported && mode.$modes) {
  1079. try {
  1080. editorProxy.setupContext(editor);
  1081. if (/js|php/.test(editorProxy.getSyntax()))
  1082. isSupported = false;
  1083. } catch(e) {}
  1084. }
  1085. return isSupported;
  1086. }
  1087. var onChangeMode = function(e, target) {
  1088. var editor = target;
  1089. if (!editor)
  1090. return;
  1091. var enabled = exports.isSupportedMode(editor.session.$mode);
  1092. if (e.enableEmmet === false)
  1093. enabled = false;
  1094. if (enabled)
  1095. load();
  1096. exports.updateCommands(editor, enabled);
  1097. };
  1098. var load = function(cb) {
  1099. if (typeof emmetPath == "string") {
  1100. require("ace/config").loadModule(emmetPath, function() {
  1101. emmetPath = null;
  1102. cb && cb();
  1103. });
  1104. }
  1105. };
  1106. exports.AceEmmetEditor = AceEmmetEditor;
  1107. require("ace/config").defineOptions(Editor.prototype, "editor", {
  1108. enableEmmet: {
  1109. set: function(val) {
  1110. this[val ? "on" : "removeListener"]("changeMode", onChangeMode);
  1111. onChangeMode({enableEmmet: !!val}, this);
  1112. },
  1113. value: true
  1114. }
  1115. });
  1116. exports.setCore = function(e) {
  1117. if (typeof e == "string")
  1118. emmetPath = e;
  1119. else
  1120. emmet = e;
  1121. };
  1122. });
  1123. (function() {
  1124. ace.require(["ace/ext/emmet"], function() {});
  1125. })();