snippets.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952
  1. /* ***** BEGIN LICENSE BLOCK *****
  2. * Distributed under the BSD license:
  3. *
  4. * Copyright (c) 2010, Ajax.org B.V.
  5. * All rights reserved.
  6. *
  7. * Redistribution and use in source and binary forms, with or without
  8. * modification, are permitted provided that the following conditions are met:
  9. * * Redistributions of source code must retain the above copyright
  10. * notice, this list of conditions and the following disclaimer.
  11. * * Redistributions in binary form must reproduce the above copyright
  12. * notice, this list of conditions and the following disclaimer in the
  13. * documentation and/or other materials provided with the distribution.
  14. * * Neither the name of Ajax.org B.V. nor the
  15. * names of its contributors may be used to endorse or promote products
  16. * derived from this software without specific prior written permission.
  17. *
  18. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  19. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  20. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  21. * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
  22. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  23. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  24. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  25. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  26. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  27. * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  28. *
  29. * ***** END LICENSE BLOCK ***** */
  30. define(function(require, exports, module) {
  31. "use strict";
  32. var oop = require("./lib/oop");
  33. var EventEmitter = require("./lib/event_emitter").EventEmitter;
  34. var lang = require("./lib/lang");
  35. var Range = require("./range").Range;
  36. var Anchor = require("./anchor").Anchor;
  37. var HashHandler = require("./keyboard/hash_handler").HashHandler;
  38. var Tokenizer = require("./tokenizer").Tokenizer;
  39. var comparePoints = Range.comparePoints;
  40. var SnippetManager = function() {
  41. this.snippetMap = {};
  42. this.snippetNameMap = {};
  43. };
  44. (function() {
  45. oop.implement(this, EventEmitter);
  46. this.getTokenizer = function() {
  47. function TabstopToken(str, _, stack) {
  48. str = str.substr(1);
  49. if (/^\d+$/.test(str) && !stack.inFormatString)
  50. return [{tabstopId: parseInt(str, 10)}];
  51. return [{text: str}];
  52. }
  53. function escape(ch) {
  54. return "(?:[^\\\\" + ch + "]|\\\\.)";
  55. }
  56. SnippetManager.$tokenizer = new Tokenizer({
  57. start: [
  58. {regex: /:/, onMatch: function(val, state, stack) {
  59. if (stack.length && stack[0].expectIf) {
  60. stack[0].expectIf = false;
  61. stack[0].elseBranch = stack[0];
  62. return [stack[0]];
  63. }
  64. return ":";
  65. }},
  66. {regex: /\\./, onMatch: function(val, state, stack) {
  67. var ch = val[1];
  68. if (ch == "}" && stack.length) {
  69. val = ch;
  70. }else if ("`$\\".indexOf(ch) != -1) {
  71. val = ch;
  72. } else if (stack.inFormatString) {
  73. if (ch == "n")
  74. val = "\n";
  75. else if (ch == "t")
  76. val = "\n";
  77. else if ("ulULE".indexOf(ch) != -1) {
  78. val = {changeCase: ch, local: ch > "a"};
  79. }
  80. }
  81. return [val];
  82. }},
  83. {regex: /}/, onMatch: function(val, state, stack) {
  84. return [stack.length ? stack.shift() : val];
  85. }},
  86. {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken},
  87. {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) {
  88. var t = TabstopToken(str.substr(1), state, stack);
  89. stack.unshift(t[0]);
  90. return t;
  91. }, next: "snippetVar"},
  92. {regex: /\n/, token: "newline", merge: false}
  93. ],
  94. snippetVar: [
  95. {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) {
  96. stack[0].choices = val.slice(1, -1).split(",");
  97. }, next: "start"},
  98. {regex: "/(" + escape("/") + "+)/(?:(" + escape("/") + "*)/)(\\w*):?",
  99. onMatch: function(val, state, stack) {
  100. var ts = stack[0];
  101. ts.fmtString = val;
  102. val = this.splitRegex.exec(val);
  103. ts.guard = val[1];
  104. ts.fmt = val[2];
  105. ts.flag = val[3];
  106. return "";
  107. }, next: "start"},
  108. {regex: "`" + escape("`") + "*`", onMatch: function(val, state, stack) {
  109. stack[0].code = val.splice(1, -1);
  110. return "";
  111. }, next: "start"},
  112. {regex: "\\?", onMatch: function(val, state, stack) {
  113. if (stack[0])
  114. stack[0].expectIf = true;
  115. }, next: "start"},
  116. {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"}
  117. ],
  118. formatString: [
  119. {regex: "/(" + escape("/") + "+)/", token: "regex"},
  120. {regex: "", onMatch: function(val, state, stack) {
  121. stack.inFormatString = true;
  122. }, next: "start"}
  123. ]
  124. });
  125. SnippetManager.prototype.getTokenizer = function() {
  126. return SnippetManager.$tokenizer;
  127. };
  128. return SnippetManager.$tokenizer;
  129. };
  130. this.tokenizeTmSnippet = function(str, startState) {
  131. return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) {
  132. return x.value || x;
  133. });
  134. };
  135. this.$getDefaultValue = function(editor, name) {
  136. if (/^[A-Z]\d+$/.test(name)) {
  137. var i = name.substr(1);
  138. return (this.variables[name[0] + "__"] || {})[i];
  139. }
  140. if (/^\d+$/.test(name)) {
  141. return (this.variables.__ || {})[name];
  142. }
  143. name = name.replace(/^TM_/, "");
  144. if (!editor)
  145. return;
  146. var s = editor.session;
  147. switch(name) {
  148. case "CURRENT_WORD":
  149. var r = s.getWordRange();
  150. /* falls through */
  151. case "SELECTION":
  152. case "SELECTED_TEXT":
  153. return s.getTextRange(r);
  154. case "CURRENT_LINE":
  155. return s.getLine(editor.getCursorPosition().row);
  156. case "PREV_LINE": // not possible in textmate
  157. return s.getLine(editor.getCursorPosition().row - 1);
  158. case "LINE_INDEX":
  159. return editor.getCursorPosition().column;
  160. case "LINE_NUMBER":
  161. return editor.getCursorPosition().row + 1;
  162. case "SOFT_TABS":
  163. return s.getUseSoftTabs() ? "YES" : "NO";
  164. case "TAB_SIZE":
  165. return s.getTabSize();
  166. // default but can't fill :(
  167. case "FILENAME":
  168. case "FILEPATH":
  169. return "";
  170. case "FULLNAME":
  171. return "Ace";
  172. }
  173. };
  174. this.variables = {};
  175. this.getVariableValue = function(editor, varName) {
  176. if (this.variables.hasOwnProperty(varName))
  177. return this.variables[varName](editor, varName) || "";
  178. return this.$getDefaultValue(editor, varName) || "";
  179. };
  180. // returns string formatted according to http://manual.macromates.com/en/regular_expressions#replacement_string_syntax_format_strings
  181. this.tmStrFormat = function(str, ch, editor) {
  182. var flag = ch.flag || "";
  183. var re = ch.guard;
  184. re = new RegExp(re, flag.replace(/[^gi]/, ""));
  185. var fmtTokens = this.tokenizeTmSnippet(ch.fmt, "formatString");
  186. var _self = this;
  187. var formatted = str.replace(re, function() {
  188. _self.variables.__ = arguments;
  189. var fmtParts = _self.resolveVariables(fmtTokens, editor);
  190. var gChangeCase = "E";
  191. for (var i = 0; i < fmtParts.length; i++) {
  192. var ch = fmtParts[i];
  193. if (typeof ch == "object") {
  194. fmtParts[i] = "";
  195. if (ch.changeCase && ch.local) {
  196. var next = fmtParts[i + 1];
  197. if (next && typeof next == "string") {
  198. if (ch.changeCase == "u")
  199. fmtParts[i] = next[0].toUpperCase();
  200. else
  201. fmtParts[i] = next[0].toLowerCase();
  202. fmtParts[i + 1] = next.substr(1);
  203. }
  204. } else if (ch.changeCase) {
  205. gChangeCase = ch.changeCase;
  206. }
  207. } else if (gChangeCase == "U") {
  208. fmtParts[i] = ch.toUpperCase();
  209. } else if (gChangeCase == "L") {
  210. fmtParts[i] = ch.toLowerCase();
  211. }
  212. }
  213. return fmtParts.join("");
  214. });
  215. this.variables.__ = null;
  216. return formatted;
  217. };
  218. this.resolveVariables = function(snippet, editor) {
  219. var result = [];
  220. for (var i = 0; i < snippet.length; i++) {
  221. var ch = snippet[i];
  222. if (typeof ch == "string") {
  223. result.push(ch);
  224. } else if (typeof ch != "object") {
  225. continue;
  226. } else if (ch.skip) {
  227. gotoNext(ch);
  228. } else if (ch.processed < i) {
  229. continue;
  230. } else if (ch.text) {
  231. var value = this.getVariableValue(editor, ch.text);
  232. if (value && ch.fmtString)
  233. value = this.tmStrFormat(value, ch);
  234. ch.processed = i;
  235. if (ch.expectIf == null) {
  236. if (value) {
  237. result.push(value);
  238. gotoNext(ch);
  239. }
  240. } else {
  241. if (value) {
  242. ch.skip = ch.elseBranch;
  243. } else
  244. gotoNext(ch);
  245. }
  246. } else if (ch.tabstopId != null) {
  247. result.push(ch);
  248. } else if (ch.changeCase != null) {
  249. result.push(ch);
  250. }
  251. }
  252. function gotoNext(ch) {
  253. var i1 = snippet.indexOf(ch, i + 1);
  254. if (i1 != -1)
  255. i = i1;
  256. }
  257. return result;
  258. };
  259. this.insertSnippetForSelection = function(editor, snippetText) {
  260. var cursor = editor.getCursorPosition();
  261. var line = editor.session.getLine(cursor.row);
  262. var tabString = editor.session.getTabString();
  263. var indentString = line.match(/^\s*/)[0];
  264. if (cursor.column < indentString.length)
  265. indentString = indentString.slice(0, cursor.column);
  266. var tokens = this.tokenizeTmSnippet(snippetText);
  267. tokens = this.resolveVariables(tokens, editor);
  268. // indent
  269. tokens = tokens.map(function(x) {
  270. if (x == "\n")
  271. return x + indentString;
  272. if (typeof x == "string")
  273. return x.replace(/\t/g, tabString);
  274. return x;
  275. });
  276. // tabstop values
  277. var tabstops = [];
  278. tokens.forEach(function(p, i) {
  279. if (typeof p != "object")
  280. return;
  281. var id = p.tabstopId;
  282. var ts = tabstops[id];
  283. if (!ts) {
  284. ts = tabstops[id] = [];
  285. ts.index = id;
  286. ts.value = "";
  287. }
  288. if (ts.indexOf(p) !== -1)
  289. return;
  290. ts.push(p);
  291. var i1 = tokens.indexOf(p, i + 1);
  292. if (i1 === -1)
  293. return;
  294. var value = tokens.slice(i + 1, i1);
  295. var isNested = value.some(function(t) {return typeof t === "object"});
  296. if (isNested && !ts.value) {
  297. ts.value = value;
  298. } else if (value.length && (!ts.value || typeof ts.value !== "string")) {
  299. ts.value = value.join("");
  300. }
  301. });
  302. // expand tabstop values
  303. tabstops.forEach(function(ts) {ts.length = 0});
  304. var expanding = {};
  305. function copyValue(val) {
  306. var copy = [];
  307. for (var i = 0; i < val.length; i++) {
  308. var p = val[i];
  309. if (typeof p == "object") {
  310. if (expanding[p.tabstopId])
  311. continue;
  312. var j = val.lastIndexOf(p, i - 1);
  313. p = copy[j] || {tabstopId: p.tabstopId};
  314. }
  315. copy[i] = p;
  316. }
  317. return copy;
  318. }
  319. for (var i = 0; i < tokens.length; i++) {
  320. var p = tokens[i];
  321. if (typeof p != "object")
  322. continue;
  323. var id = p.tabstopId;
  324. var i1 = tokens.indexOf(p, i + 1);
  325. if (expanding[id]) {
  326. // if reached closing bracket clear expanding state
  327. if (expanding[id] === p)
  328. expanding[id] = null;
  329. // otherwise just ignore recursive tabstop
  330. continue;
  331. }
  332. var ts = tabstops[id];
  333. var arg = typeof ts.value == "string" ? [ts.value] : copyValue(ts.value);
  334. arg.unshift(i + 1, Math.max(0, i1 - i));
  335. arg.push(p);
  336. expanding[id] = p;
  337. tokens.splice.apply(tokens, arg);
  338. if (ts.indexOf(p) === -1)
  339. ts.push(p);
  340. }
  341. // convert to plain text
  342. var row = 0, column = 0;
  343. var text = "";
  344. tokens.forEach(function(t) {
  345. if (typeof t === "string") {
  346. if (t[0] === "\n"){
  347. column = t.length - 1;
  348. row ++;
  349. } else
  350. column += t.length;
  351. text += t;
  352. } else {
  353. if (!t.start)
  354. t.start = {row: row, column: column};
  355. else
  356. t.end = {row: row, column: column};
  357. }
  358. });
  359. var range = editor.getSelectionRange();
  360. var end = editor.session.replace(range, text);
  361. var tabstopManager = new TabstopManager(editor);
  362. var selectionId = editor.inVirtualSelectionMode && editor.selection.index;
  363. tabstopManager.addTabstops(tabstops, range.start, end, selectionId);
  364. };
  365. this.insertSnippet = function(editor, snippetText) {
  366. var self = this;
  367. if (editor.inVirtualSelectionMode)
  368. return self.insertSnippetForSelection(editor, snippetText);
  369. editor.forEachSelection(function() {
  370. self.insertSnippetForSelection(editor, snippetText);
  371. }, null, {keepOrder: true});
  372. if (editor.tabstopManager)
  373. editor.tabstopManager.tabNext();
  374. };
  375. this.$getScope = function(editor) {
  376. var scope = editor.session.$mode.$id || "";
  377. scope = scope.split("/").pop();
  378. if (scope === "html" || scope === "php") {
  379. // PHP is actually HTML
  380. if (scope === "php" && !editor.session.$mode.inlinePhp)
  381. scope = "html";
  382. var c = editor.getCursorPosition();
  383. var state = editor.session.getState(c.row);
  384. if (typeof state === "object") {
  385. state = state[0];
  386. }
  387. if (state.substring) {
  388. if (state.substring(0, 3) == "js-")
  389. scope = "javascript";
  390. else if (state.substring(0, 4) == "css-")
  391. scope = "css";
  392. else if (state.substring(0, 4) == "php-")
  393. scope = "php";
  394. }
  395. }
  396. return scope;
  397. };
  398. this.getActiveScopes = function(editor) {
  399. var scope = this.$getScope(editor);
  400. var scopes = [scope];
  401. var snippetMap = this.snippetMap;
  402. if (snippetMap[scope] && snippetMap[scope].includeScopes) {
  403. scopes.push.apply(scopes, snippetMap[scope].includeScopes);
  404. }
  405. scopes.push("_");
  406. return scopes;
  407. };
  408. this.expandWithTab = function(editor, options) {
  409. var self = this;
  410. var result = editor.forEachSelection(function() {
  411. return self.expandSnippetForSelection(editor, options);
  412. }, null, {keepOrder: true});
  413. if (result && editor.tabstopManager)
  414. editor.tabstopManager.tabNext();
  415. return result;
  416. };
  417. this.expandSnippetForSelection = function(editor, options) {
  418. var cursor = editor.getCursorPosition();
  419. var line = editor.session.getLine(cursor.row);
  420. var before = line.substring(0, cursor.column);
  421. var after = line.substr(cursor.column);
  422. var snippetMap = this.snippetMap;
  423. var snippet;
  424. this.getActiveScopes(editor).some(function(scope) {
  425. var snippets = snippetMap[scope];
  426. if (snippets)
  427. snippet = this.findMatchingSnippet(snippets, before, after);
  428. return !!snippet;
  429. }, this);
  430. if (!snippet)
  431. return false;
  432. if (options && options.dryRun)
  433. return true;
  434. editor.session.doc.removeInLine(cursor.row,
  435. cursor.column - snippet.replaceBefore.length,
  436. cursor.column + snippet.replaceAfter.length
  437. );
  438. this.variables.M__ = snippet.matchBefore;
  439. this.variables.T__ = snippet.matchAfter;
  440. this.insertSnippetForSelection(editor, snippet.content);
  441. this.variables.M__ = this.variables.T__ = null;
  442. return true;
  443. };
  444. this.findMatchingSnippet = function(snippetList, before, after) {
  445. for (var i = snippetList.length; i--;) {
  446. var s = snippetList[i];
  447. if (s.startRe && !s.startRe.test(before))
  448. continue;
  449. if (s.endRe && !s.endRe.test(after))
  450. continue;
  451. if (!s.startRe && !s.endRe)
  452. continue;
  453. s.matchBefore = s.startRe ? s.startRe.exec(before) : [""];
  454. s.matchAfter = s.endRe ? s.endRe.exec(after) : [""];
  455. s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : "";
  456. s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : "";
  457. return s;
  458. }
  459. };
  460. this.snippetMap = {};
  461. this.snippetNameMap = {};
  462. this.register = function(snippets, scope) {
  463. var snippetMap = this.snippetMap;
  464. var snippetNameMap = this.snippetNameMap;
  465. var self = this;
  466. if (!snippets)
  467. snippets = [];
  468. function wrapRegexp(src) {
  469. if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src))
  470. src = "(?:" + src + ")";
  471. return src || "";
  472. }
  473. function guardedRegexp(re, guard, opening) {
  474. re = wrapRegexp(re);
  475. guard = wrapRegexp(guard);
  476. if (opening) {
  477. re = guard + re;
  478. if (re && re[re.length - 1] != "$")
  479. re = re + "$";
  480. } else {
  481. re = re + guard;
  482. if (re && re[0] != "^")
  483. re = "^" + re;
  484. }
  485. return new RegExp(re);
  486. }
  487. function addSnippet(s) {
  488. if (!s.scope)
  489. s.scope = scope || "_";
  490. scope = s.scope;
  491. if (!snippetMap[scope]) {
  492. snippetMap[scope] = [];
  493. snippetNameMap[scope] = {};
  494. }
  495. var map = snippetNameMap[scope];
  496. if (s.name) {
  497. var old = map[s.name];
  498. if (old)
  499. self.unregister(old);
  500. map[s.name] = s;
  501. }
  502. snippetMap[scope].push(s);
  503. if (s.tabTrigger && !s.trigger) {
  504. if (!s.guard && /^\w/.test(s.tabTrigger))
  505. s.guard = "\\b";
  506. s.trigger = lang.escapeRegExp(s.tabTrigger);
  507. }
  508. if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard)
  509. return;
  510. s.startRe = guardedRegexp(s.trigger, s.guard, true);
  511. s.triggerRe = new RegExp(s.trigger, "", true);
  512. s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true);
  513. s.endTriggerRe = new RegExp(s.endTrigger, "", true);
  514. }
  515. if (snippets && snippets.content)
  516. addSnippet(snippets);
  517. else if (Array.isArray(snippets))
  518. snippets.forEach(addSnippet);
  519. this._signal("registerSnippets", {scope: scope});
  520. };
  521. this.unregister = function(snippets, scope) {
  522. var snippetMap = this.snippetMap;
  523. var snippetNameMap = this.snippetNameMap;
  524. function removeSnippet(s) {
  525. var nameMap = snippetNameMap[s.scope||scope];
  526. if (nameMap && nameMap[s.name]) {
  527. delete nameMap[s.name];
  528. var map = snippetMap[s.scope||scope];
  529. var i = map && map.indexOf(s);
  530. if (i >= 0)
  531. map.splice(i, 1);
  532. }
  533. }
  534. if (snippets.content)
  535. removeSnippet(snippets);
  536. else if (Array.isArray(snippets))
  537. snippets.forEach(removeSnippet);
  538. };
  539. this.parseSnippetFile = function(str) {
  540. str = str.replace(/\r/g, "");
  541. var list = [], snippet = {};
  542. var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;
  543. var m;
  544. while (m = re.exec(str)) {
  545. if (m[1]) {
  546. try {
  547. snippet = JSON.parse(m[1]);
  548. list.push(snippet);
  549. } catch (e) {}
  550. } if (m[4]) {
  551. snippet.content = m[4].replace(/^\t/gm, "");
  552. list.push(snippet);
  553. snippet = {};
  554. } else {
  555. var key = m[2], val = m[3];
  556. if (key == "regex") {
  557. var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g;
  558. snippet.guard = guardRe.exec(val)[1];
  559. snippet.trigger = guardRe.exec(val)[1];
  560. snippet.endTrigger = guardRe.exec(val)[1];
  561. snippet.endGuard = guardRe.exec(val)[1];
  562. } else if (key == "snippet") {
  563. snippet.tabTrigger = val.match(/^\S*/)[0];
  564. if (!snippet.name)
  565. snippet.name = val;
  566. } else {
  567. snippet[key] = val;
  568. }
  569. }
  570. }
  571. return list;
  572. };
  573. this.getSnippetByName = function(name, editor) {
  574. var snippetMap = this.snippetNameMap;
  575. var snippet;
  576. this.getActiveScopes(editor).some(function(scope) {
  577. var snippets = snippetMap[scope];
  578. if (snippets)
  579. snippet = snippets[name];
  580. return !!snippet;
  581. }, this);
  582. return snippet;
  583. };
  584. }).call(SnippetManager.prototype);
  585. var TabstopManager = function(editor) {
  586. if (editor.tabstopManager)
  587. return editor.tabstopManager;
  588. editor.tabstopManager = this;
  589. this.$onChange = this.onChange.bind(this);
  590. this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule;
  591. this.$onChangeSession = this.onChangeSession.bind(this);
  592. this.$onAfterExec = this.onAfterExec.bind(this);
  593. this.attach(editor);
  594. };
  595. (function() {
  596. this.attach = function(editor) {
  597. this.index = 0;
  598. this.ranges = [];
  599. this.tabstops = [];
  600. this.$openTabstops = null;
  601. this.selectedTabstop = null;
  602. this.editor = editor;
  603. this.editor.on("change", this.$onChange);
  604. this.editor.on("changeSelection", this.$onChangeSelection);
  605. this.editor.on("changeSession", this.$onChangeSession);
  606. this.editor.commands.on("afterExec", this.$onAfterExec);
  607. this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  608. };
  609. this.detach = function() {
  610. this.tabstops.forEach(this.removeTabstopMarkers, this);
  611. this.ranges = null;
  612. this.tabstops = null;
  613. this.selectedTabstop = null;
  614. this.editor.removeListener("change", this.$onChange);
  615. this.editor.removeListener("changeSelection", this.$onChangeSelection);
  616. this.editor.removeListener("changeSession", this.$onChangeSession);
  617. this.editor.commands.removeListener("afterExec", this.$onAfterExec);
  618. this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
  619. this.editor.tabstopManager = null;
  620. this.editor = null;
  621. };
  622. this.onChange = function(delta) {
  623. var changeRange = delta;
  624. var isRemove = delta.action[0] == "r";
  625. var start = delta.start;
  626. var end = delta.end;
  627. var startRow = start.row;
  628. var endRow = end.row;
  629. var lineDif = endRow - startRow;
  630. var colDiff = end.column - start.column;
  631. if (isRemove) {
  632. lineDif = -lineDif;
  633. colDiff = -colDiff;
  634. }
  635. if (!this.$inChange && isRemove) {
  636. var ts = this.selectedTabstop;
  637. var changedOutside = ts && !ts.some(function(r) {
  638. return comparePoints(r.start, start) <= 0 && comparePoints(r.end, end) >= 0;
  639. });
  640. if (changedOutside)
  641. return this.detach();
  642. }
  643. var ranges = this.ranges;
  644. for (var i = 0; i < ranges.length; i++) {
  645. var r = ranges[i];
  646. if (r.end.row < start.row)
  647. continue;
  648. if (isRemove && comparePoints(start, r.start) < 0 && comparePoints(end, r.end) > 0) {
  649. this.removeRange(r);
  650. i--;
  651. continue;
  652. }
  653. if (r.start.row == startRow && r.start.column > start.column)
  654. r.start.column += colDiff;
  655. if (r.end.row == startRow && r.end.column >= start.column)
  656. r.end.column += colDiff;
  657. if (r.start.row >= startRow)
  658. r.start.row += lineDif;
  659. if (r.end.row >= startRow)
  660. r.end.row += lineDif;
  661. if (comparePoints(r.start, r.end) > 0)
  662. this.removeRange(r);
  663. }
  664. if (!ranges.length)
  665. this.detach();
  666. };
  667. this.updateLinkedFields = function() {
  668. var ts = this.selectedTabstop;
  669. if (!ts || !ts.hasLinkedRanges)
  670. return;
  671. this.$inChange = true;
  672. var session = this.editor.session;
  673. var text = session.getTextRange(ts.firstNonLinked);
  674. for (var i = ts.length; i--;) {
  675. var range = ts[i];
  676. if (!range.linked)
  677. continue;
  678. var fmt = exports.snippetManager.tmStrFormat(text, range.original);
  679. session.replace(range, fmt);
  680. }
  681. this.$inChange = false;
  682. };
  683. this.onAfterExec = function(e) {
  684. if (e.command && !e.command.readOnly)
  685. this.updateLinkedFields();
  686. };
  687. this.onChangeSelection = function() {
  688. if (!this.editor)
  689. return;
  690. var lead = this.editor.selection.lead;
  691. var anchor = this.editor.selection.anchor;
  692. var isEmpty = this.editor.selection.isEmpty();
  693. for (var i = this.ranges.length; i--;) {
  694. if (this.ranges[i].linked)
  695. continue;
  696. var containsLead = this.ranges[i].contains(lead.row, lead.column);
  697. var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column);
  698. if (containsLead && containsAnchor)
  699. return;
  700. }
  701. this.detach();
  702. };
  703. this.onChangeSession = function() {
  704. this.detach();
  705. };
  706. this.tabNext = function(dir) {
  707. var max = this.tabstops.length;
  708. var index = this.index + (dir || 1);
  709. index = Math.min(Math.max(index, 1), max);
  710. if (index == max)
  711. index = 0;
  712. this.selectTabstop(index);
  713. if (index === 0)
  714. this.detach();
  715. };
  716. this.selectTabstop = function(index) {
  717. this.$openTabstops = null;
  718. var ts = this.tabstops[this.index];
  719. if (ts)
  720. this.addTabstopMarkers(ts);
  721. this.index = index;
  722. ts = this.tabstops[this.index];
  723. if (!ts || !ts.length)
  724. return;
  725. this.selectedTabstop = ts;
  726. if (!this.editor.inVirtualSelectionMode) {
  727. var sel = this.editor.multiSelect;
  728. sel.toSingleRange(ts.firstNonLinked.clone());
  729. for (var i = ts.length; i--;) {
  730. if (ts.hasLinkedRanges && ts[i].linked)
  731. continue;
  732. sel.addRange(ts[i].clone(), true);
  733. }
  734. // todo investigate why is this needed
  735. if (sel.ranges[0])
  736. sel.addRange(sel.ranges[0].clone());
  737. } else {
  738. this.editor.selection.setRange(ts.firstNonLinked);
  739. }
  740. this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
  741. };
  742. this.addTabstops = function(tabstops, start, end) {
  743. if (!this.$openTabstops)
  744. this.$openTabstops = [];
  745. // add final tabstop if missing
  746. if (!tabstops[0]) {
  747. var p = Range.fromPoints(end, end);
  748. moveRelative(p.start, start);
  749. moveRelative(p.end, start);
  750. tabstops[0] = [p];
  751. tabstops[0].index = 0;
  752. }
  753. var i = this.index;
  754. var arg = [i + 1, 0];
  755. var ranges = this.ranges;
  756. tabstops.forEach(function(ts, index) {
  757. var dest = this.$openTabstops[index] || ts;
  758. for (var i = ts.length; i--;) {
  759. var p = ts[i];
  760. var range = Range.fromPoints(p.start, p.end || p.start);
  761. movePoint(range.start, start);
  762. movePoint(range.end, start);
  763. range.original = p;
  764. range.tabstop = dest;
  765. ranges.push(range);
  766. if (dest != ts)
  767. dest.unshift(range);
  768. else
  769. dest[i] = range;
  770. if (p.fmtString) {
  771. range.linked = true;
  772. dest.hasLinkedRanges = true;
  773. } else if (!dest.firstNonLinked)
  774. dest.firstNonLinked = range;
  775. }
  776. if (!dest.firstNonLinked)
  777. dest.hasLinkedRanges = false;
  778. if (dest === ts) {
  779. arg.push(dest);
  780. this.$openTabstops[index] = dest;
  781. }
  782. this.addTabstopMarkers(dest);
  783. }, this);
  784. if (arg.length > 2) {
  785. // when adding new snippet inside existing one, make sure 0 tabstop is at the end
  786. if (this.tabstops.length)
  787. arg.push(arg.splice(2, 1)[0]);
  788. this.tabstops.splice.apply(this.tabstops, arg);
  789. }
  790. };
  791. this.addTabstopMarkers = function(ts) {
  792. var session = this.editor.session;
  793. ts.forEach(function(range) {
  794. if (!range.markerId)
  795. range.markerId = session.addMarker(range, "ace_snippet-marker", "text");
  796. });
  797. };
  798. this.removeTabstopMarkers = function(ts) {
  799. var session = this.editor.session;
  800. ts.forEach(function(range) {
  801. session.removeMarker(range.markerId);
  802. range.markerId = null;
  803. });
  804. };
  805. this.removeRange = function(range) {
  806. var i = range.tabstop.indexOf(range);
  807. range.tabstop.splice(i, 1);
  808. i = this.ranges.indexOf(range);
  809. this.ranges.splice(i, 1);
  810. this.editor.session.removeMarker(range.markerId);
  811. if (!range.tabstop.length) {
  812. i = this.tabstops.indexOf(range.tabstop);
  813. if (i != -1)
  814. this.tabstops.splice(i, 1);
  815. if (!this.tabstops.length)
  816. this.detach();
  817. }
  818. };
  819. this.keyboardHandler = new HashHandler();
  820. this.keyboardHandler.bindKeys({
  821. "Tab": function(ed) {
  822. if (exports.snippetManager && exports.snippetManager.expandWithTab(ed)) {
  823. return;
  824. }
  825. ed.tabstopManager.tabNext(1);
  826. },
  827. "Shift-Tab": function(ed) {
  828. ed.tabstopManager.tabNext(-1);
  829. },
  830. "Esc": function(ed) {
  831. ed.tabstopManager.detach();
  832. },
  833. "Return": function(ed) {
  834. //ed.tabstopManager.tabNext(1);
  835. return false;
  836. }
  837. });
  838. }).call(TabstopManager.prototype);
  839. var changeTracker = {};
  840. changeTracker.onChange = Anchor.prototype.onChange;
  841. changeTracker.setPosition = function(row, column) {
  842. this.pos.row = row;
  843. this.pos.column = column;
  844. };
  845. changeTracker.update = function(pos, delta, $insertRight) {
  846. this.$insertRight = $insertRight;
  847. this.pos = pos;
  848. this.onChange(delta);
  849. };
  850. var movePoint = function(point, diff) {
  851. if (point.row == 0)
  852. point.column += diff.column;
  853. point.row += diff.row;
  854. };
  855. var moveRelative = function(point, start) {
  856. if (point.row == start.row)
  857. point.column -= start.column;
  858. point.row -= start.row;
  859. };
  860. require("./lib/dom").importCssString("\
  861. .ace_snippet-marker {\
  862. -moz-box-sizing: border-box;\
  863. box-sizing: border-box;\
  864. background: rgba(194, 193, 208, 0.09);\
  865. border: 1px dotted rgba(211, 208, 235, 0.62);\
  866. position: absolute;\
  867. }");
  868. exports.snippetManager = new SnippetManager();
  869. var Editor = require("./editor").Editor;
  870. (function() {
  871. this.insertSnippet = function(content, options) {
  872. return exports.snippetManager.insertSnippet(this, content, options);
  873. };
  874. this.expandSnippet = function(options) {
  875. return exports.snippetManager.expandWithTab(this, options);
  876. };
  877. }).call(Editor.prototype);
  878. });