emmet.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  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 HashHandler = require("ace/keyboard/hash_handler").HashHandler;
  33. var Editor = require("ace/editor").Editor;
  34. var snippetManager = require("ace/snippets").snippetManager;
  35. var Range = require("ace/range").Range;
  36. var emmet;
  37. Editor.prototype.indexToPosition = function(index) {
  38. return this.session.doc.indexToPosition(index);
  39. };
  40. Editor.prototype.positionToIndex = function(pos) {
  41. return this.session.doc.positionToIndex(pos);
  42. };
  43. /**
  44. * Implementation of {@link IEmmetEditor} interface for Ace
  45. */
  46. function AceEmmetEditor() {}
  47. AceEmmetEditor.prototype = {
  48. setupContext: function(editor) {
  49. this.ace = editor;
  50. this.indentation = editor.session.getTabString();
  51. if (!emmet)
  52. emmet = window.emmet;
  53. emmet.require("resources").setVariable("indentation", this.indentation);
  54. this.$syntax = null;
  55. this.$syntax = this.getSyntax();
  56. },
  57. /**
  58. * Returns character indexes of selected text: object with <code>start</code>
  59. * and <code>end</code> properties. If there's no selection, should return
  60. * object with <code>start</code> and <code>end</code> properties referring
  61. * to current caret position
  62. * @return {Object}
  63. * @example
  64. * var selection = editor.getSelectionRange();
  65. * alert(selection.start + ', ' + selection.end);
  66. */
  67. getSelectionRange: function() {
  68. // TODO should start be caret position instead?
  69. var range = this.ace.getSelectionRange();
  70. return {
  71. start: this.ace.positionToIndex(range.start),
  72. end: this.ace.positionToIndex(range.end)
  73. };
  74. },
  75. /**
  76. * Creates selection from <code>start</code> to <code>end</code> character
  77. * indexes. If <code>end</code> is ommited, this method should place caret
  78. * and <code>start</code> index
  79. * @param {Number} start
  80. * @param {Number} [end]
  81. * @example
  82. * editor.createSelection(10, 40);
  83. *
  84. * //move caret to 15th character
  85. * editor.createSelection(15);
  86. */
  87. createSelection: function(start, end) {
  88. this.ace.selection.setRange({
  89. start: this.ace.indexToPosition(start),
  90. end: this.ace.indexToPosition(end)
  91. });
  92. },
  93. /**
  94. * Returns current line's start and end indexes as object with <code>start</code>
  95. * and <code>end</code> properties
  96. * @return {Object}
  97. * @example
  98. * var range = editor.getCurrentLineRange();
  99. * alert(range.start + ', ' + range.end);
  100. */
  101. getCurrentLineRange: function() {
  102. var row = this.ace.getCursorPosition().row;
  103. var lineLength = this.ace.session.getLine(row).length;
  104. var index = this.ace.positionToIndex({row: row, column: 0});
  105. return {
  106. start: index,
  107. end: index + lineLength
  108. };
  109. },
  110. /**
  111. * Returns current caret position
  112. * @return {Number|null}
  113. */
  114. getCaretPos: function(){
  115. var pos = this.ace.getCursorPosition();
  116. return this.ace.positionToIndex(pos);
  117. },
  118. /**
  119. * Set new caret position
  120. * @param {Number} index Caret position
  121. */
  122. setCaretPos: function(index){
  123. var pos = this.ace.indexToPosition(index);
  124. this.ace.clearSelection();
  125. this.ace.selection.moveCursorToPosition(pos);
  126. },
  127. /**
  128. * Returns content of current line
  129. * @return {String}
  130. */
  131. getCurrentLine: function() {
  132. var row = this.ace.getCursorPosition().row;
  133. return this.ace.session.getLine(row);
  134. },
  135. /**
  136. * Replace editor's content or it's part (from <code>start</code> to
  137. * <code>end</code> index). If <code>value</code> contains
  138. * <code>caret_placeholder</code>, the editor will put caret into
  139. * this position. If you skip <code>start</code> and <code>end</code>
  140. * arguments, the whole target's content will be replaced with
  141. * <code>value</code>.
  142. *
  143. * If you pass <code>start</code> argument only,
  144. * the <code>value</code> will be placed at <code>start</code> string
  145. * index of current content.
  146. *
  147. * If you pass <code>start</code> and <code>end</code> arguments,
  148. * the corresponding substring of current target's content will be
  149. * replaced with <code>value</code>.
  150. * @param {String} value Content you want to paste
  151. * @param {Number} [start] Start index of editor's content
  152. * @param {Number} [end] End index of editor's content
  153. * @param {Boolean} [noIndent] Do not auto indent <code>value</code>
  154. */
  155. replaceContent: function(value, start, end, noIndent) {
  156. if (end == null)
  157. end = start == null ? this.getContent().length : start;
  158. if (start == null)
  159. start = 0;
  160. var editor = this.ace;
  161. var range = Range.fromPoints(editor.indexToPosition(start), editor.indexToPosition(end));
  162. editor.session.remove(range);
  163. range.end = range.start;
  164. //editor.selection.setRange(range);
  165. value = this.$updateTabstops(value);
  166. snippetManager.insertSnippet(editor, value)
  167. },
  168. /**
  169. * Returns editor's content
  170. * @return {String}
  171. */
  172. getContent: function(){
  173. return this.ace.getValue();
  174. },
  175. /**
  176. * Returns current editor's syntax mode
  177. * @return {String}
  178. */
  179. getSyntax: function() {
  180. if (this.$syntax)
  181. return this.$syntax;
  182. var syntax = this.ace.session.$modeId.split("/").pop();
  183. if (syntax == "html" || syntax == "php") {
  184. var cursor = this.ace.getCursorPosition();
  185. var state = this.ace.session.getState(cursor.row);
  186. if (typeof state != "string")
  187. state = state[0];
  188. if (state) {
  189. state = state.split("-");
  190. if (state.length > 1)
  191. syntax = state[0];
  192. else if (syntax == "php")
  193. syntax = "html";
  194. }
  195. }
  196. return syntax;
  197. },
  198. /**
  199. * Returns current output profile name (@see emmet#setupProfile)
  200. * @return {String}
  201. */
  202. getProfileName: function() {
  203. switch(this.getSyntax()) {
  204. case "css": return "css";
  205. case "xml":
  206. case "xsl":
  207. return "xml";
  208. case "html":
  209. var profile = emmet.require("resources").getVariable("profile");
  210. // no forced profile, guess from content html or xhtml?
  211. if (!profile)
  212. profile = this.ace.session.getLines(0,2).join("").search(/<!DOCTYPE[^>]+XHTML/i) != -1 ? "xhtml": "html";
  213. return profile;
  214. }
  215. return "xhtml";
  216. },
  217. /**
  218. * Ask user to enter something
  219. * @param {String} title Dialog title
  220. * @return {String} Entered data
  221. * @since 0.65
  222. */
  223. prompt: function(title) {
  224. return prompt(title);
  225. },
  226. /**
  227. * Returns current selection
  228. * @return {String}
  229. * @since 0.65
  230. */
  231. getSelection: function() {
  232. return this.ace.session.getTextRange();
  233. },
  234. /**
  235. * Returns current editor's file path
  236. * @return {String}
  237. * @since 0.65
  238. */
  239. getFilePath: function() {
  240. return "";
  241. },
  242. // update tabstops: make sure all caret placeholders are unique
  243. // by default, abbreviation parser generates all unlinked (un-mirrored)
  244. // tabstops as ${0}, so we have upgrade all caret tabstops with unique
  245. // positions but make sure that all other tabstops are not linked accidentally
  246. // based on https://github.com/sergeche/emmet-sublime/blob/master/editor.js#L119-L171
  247. $updateTabstops: function(value) {
  248. var base = 1000;
  249. var zeroBase = 0;
  250. var lastZero = null;
  251. var range = emmet.require('range');
  252. var ts = emmet.require('tabStops');
  253. var settings = emmet.require('resources').getVocabulary("user");
  254. var tabstopOptions = {
  255. tabstop: function(data) {
  256. var group = parseInt(data.group, 10);
  257. var isZero = group === 0;
  258. if (isZero)
  259. group = ++zeroBase;
  260. else
  261. group += base;
  262. var placeholder = data.placeholder;
  263. if (placeholder) {
  264. // recursively update nested tabstops
  265. placeholder = ts.processText(placeholder, tabstopOptions);
  266. }
  267. var result = '${' + group + (placeholder ? ':' + placeholder : '') + '}';
  268. if (isZero) {
  269. lastZero = range.create(data.start, result);
  270. }
  271. return result
  272. },
  273. escape: function(ch) {
  274. if (ch == '$') return '\\$';
  275. if (ch == '\\') return '\\\\';
  276. return ch;
  277. }
  278. };
  279. value = ts.processText(value, tabstopOptions);
  280. if (settings.variables['insert_final_tabstop'] && !/\$\{0\}$/.test(value)) {
  281. value += '${0}';
  282. } else if (lastZero) {
  283. value = emmet.require('utils').replaceSubstring(value, '${0}', lastZero);
  284. }
  285. return value;
  286. }
  287. };
  288. var keymap = {
  289. expand_abbreviation: {"mac": "ctrl+alt+e", "win": "alt+e"},
  290. match_pair_outward: {"mac": "ctrl+d", "win": "ctrl+,"},
  291. match_pair_inward: {"mac": "ctrl+j", "win": "ctrl+shift+0"},
  292. matching_pair: {"mac": "ctrl+alt+j", "win": "alt+j"},
  293. next_edit_point: "alt+right",
  294. prev_edit_point: "alt+left",
  295. toggle_comment: {"mac": "command+/", "win": "ctrl+/"},
  296. split_join_tag: {"mac": "shift+command+'", "win": "shift+ctrl+`"},
  297. remove_tag: {"mac": "command+'", "win": "shift+ctrl+;"},
  298. evaluate_math_expression: {"mac": "shift+command+y", "win": "shift+ctrl+y"},
  299. increment_number_by_1: "ctrl+up",
  300. decrement_number_by_1: "ctrl+down",
  301. increment_number_by_01: "alt+up",
  302. decrement_number_by_01: "alt+down",
  303. increment_number_by_10: {"mac": "alt+command+up", "win": "shift+alt+up"},
  304. decrement_number_by_10: {"mac": "alt+command+down", "win": "shift+alt+down"},
  305. select_next_item: {"mac": "shift+command+.", "win": "shift+ctrl+."},
  306. select_previous_item: {"mac": "shift+command+,", "win": "shift+ctrl+,"},
  307. reflect_css_value: {"mac": "shift+command+r", "win": "shift+ctrl+r"},
  308. encode_decode_data_url: {"mac": "shift+ctrl+d", "win": "ctrl+'"},
  309. // update_image_size: {"mac": "shift+ctrl+i", "win": "ctrl+u"},
  310. // expand_as_you_type: "ctrl+alt+enter",
  311. // wrap_as_you_type: {"mac": "shift+ctrl+g", "win": "shift+ctrl+g"},
  312. expand_abbreviation_with_tab: "Tab",
  313. wrap_with_abbreviation: {"mac": "shift+ctrl+a", "win": "shift+ctrl+a"}
  314. };
  315. var editorProxy = new AceEmmetEditor();
  316. exports.commands = new HashHandler();
  317. exports.runEmmetCommand = function(editor) {
  318. editorProxy.setupContext(editor);
  319. if (editorProxy.getSyntax() == "php")
  320. return false;
  321. var actions = emmet.require("actions");
  322. if (this.action == "expand_abbreviation_with_tab") {
  323. if (!editor.selection.isEmpty())
  324. return false;
  325. }
  326. if (this.action == "wrap_with_abbreviation") {
  327. // without setTimeout prompt doesn't work on firefox
  328. return setTimeout(function() {
  329. actions.run("wrap_with_abbreviation", editorProxy);
  330. }, 0);
  331. }
  332. try {
  333. var result = actions.run(this.action, editorProxy);
  334. } catch(e) {
  335. editor._signal("changeStatus", typeof e == "string" ? e : e.message);
  336. console.log(e);
  337. }
  338. return result;
  339. };
  340. for (var command in keymap) {
  341. exports.commands.addCommand({
  342. name: "emmet:" + command,
  343. action: command,
  344. bindKey: keymap[command],
  345. exec: exports.runEmmetCommand,
  346. multiSelectAction: "forEach"
  347. });
  348. }
  349. var onChangeMode = function(e, target) {
  350. var editor = target;
  351. if (!editor)
  352. return;
  353. var modeId = editor.session.$modeId;
  354. var enabled = modeId && /css|less|scss|sass|stylus|html|php/.test(modeId);
  355. if (e.enableEmmet === false)
  356. enabled = false;
  357. if (enabled)
  358. editor.keyBinding.addKeyboardHandler(exports.commands);
  359. else
  360. editor.keyBinding.removeKeyboardHandler(exports.commands);
  361. };
  362. exports.AceEmmetEditor = AceEmmetEditor;
  363. require("ace/config").defineOptions(Editor.prototype, "editor", {
  364. enableEmmet: {
  365. set: function(val) {
  366. this[val ? "on" : "removeListener"]("changeMode", onChangeMode);
  367. onChangeMode({enableEmmet: !!val}, this);
  368. },
  369. value: true
  370. }
  371. });
  372. exports.setCore = function(e) {emmet = e;};
  373. });