cstyle.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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 Behaviour = require("../behaviour").Behaviour;
  34. var TokenIterator = require("../../token_iterator").TokenIterator;
  35. var lang = require("../../lib/lang");
  36. var SAFE_INSERT_IN_TOKENS =
  37. ["text", "paren.rparen", "punctuation.operator"];
  38. var SAFE_INSERT_BEFORE_TOKENS =
  39. ["text", "paren.rparen", "punctuation.operator", "comment"];
  40. var context;
  41. var contextCache = {};
  42. var initContext = function(editor) {
  43. var id = -1;
  44. if (editor.multiSelect) {
  45. id = editor.selection.index;
  46. if (contextCache.rangeCount != editor.multiSelect.rangeCount)
  47. contextCache = {rangeCount: editor.multiSelect.rangeCount};
  48. }
  49. if (contextCache[id])
  50. return context = contextCache[id];
  51. context = contextCache[id] = {
  52. autoInsertedBrackets: 0,
  53. autoInsertedRow: -1,
  54. autoInsertedLineEnd: "",
  55. maybeInsertedBrackets: 0,
  56. maybeInsertedRow: -1,
  57. maybeInsertedLineStart: "",
  58. maybeInsertedLineEnd: ""
  59. };
  60. };
  61. var getWrapped = function(selection, selected, opening, closing) {
  62. var rowDiff = selection.end.row - selection.start.row;
  63. return {
  64. text: opening + selected + closing,
  65. selection: [
  66. 0,
  67. selection.start.column + 1,
  68. rowDiff,
  69. selection.end.column + (rowDiff ? 0 : 1)
  70. ]
  71. };
  72. };
  73. var CstyleBehaviour = function() {
  74. this.add("braces", "insertion", function(state, action, editor, session, text) {
  75. var cursor = editor.getCursorPosition();
  76. var line = session.doc.getLine(cursor.row);
  77. if (text == '{') {
  78. initContext(editor);
  79. var selection = editor.getSelectionRange();
  80. var selected = session.doc.getTextRange(selection);
  81. if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) {
  82. return getWrapped(selection, selected, '{', '}');
  83. } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
  84. if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) {
  85. CstyleBehaviour.recordAutoInsert(editor, session, "}");
  86. return {
  87. text: '{}',
  88. selection: [1, 1]
  89. };
  90. } else {
  91. CstyleBehaviour.recordMaybeInsert(editor, session, "{");
  92. return {
  93. text: '{',
  94. selection: [1, 1]
  95. };
  96. }
  97. }
  98. } else if (text == '}') {
  99. initContext(editor);
  100. var rightChar = line.substring(cursor.column, cursor.column + 1);
  101. if (rightChar == '}') {
  102. var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row});
  103. if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
  104. CstyleBehaviour.popAutoInsertedClosing();
  105. return {
  106. text: '',
  107. selection: [1, 1]
  108. };
  109. }
  110. }
  111. } else if (text == "\n" || text == "\r\n") {
  112. initContext(editor);
  113. var closing = "";
  114. if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) {
  115. closing = lang.stringRepeat("}", context.maybeInsertedBrackets);
  116. CstyleBehaviour.clearMaybeInsertedClosing();
  117. }
  118. var rightChar = line.substring(cursor.column, cursor.column + 1);
  119. if (rightChar === '}') {
  120. var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}');
  121. if (!openBracePos)
  122. return null;
  123. var next_indent = this.$getIndent(session.getLine(openBracePos.row));
  124. } else if (closing) {
  125. var next_indent = this.$getIndent(line);
  126. } else {
  127. CstyleBehaviour.clearMaybeInsertedClosing();
  128. return;
  129. }
  130. var indent = next_indent + session.getTabString();
  131. return {
  132. text: '\n' + indent + '\n' + next_indent + closing,
  133. selection: [1, indent.length, 1, indent.length]
  134. };
  135. } else {
  136. CstyleBehaviour.clearMaybeInsertedClosing();
  137. }
  138. });
  139. this.add("braces", "deletion", function(state, action, editor, session, range) {
  140. var selected = session.doc.getTextRange(range);
  141. if (!range.isMultiLine() && selected == '{') {
  142. initContext(editor);
  143. var line = session.doc.getLine(range.start.row);
  144. var rightChar = line.substring(range.end.column, range.end.column + 1);
  145. if (rightChar == '}') {
  146. range.end.column++;
  147. return range;
  148. } else {
  149. context.maybeInsertedBrackets--;
  150. }
  151. }
  152. });
  153. this.add("parens", "insertion", function(state, action, editor, session, text) {
  154. if (text == '(') {
  155. initContext(editor);
  156. var selection = editor.getSelectionRange();
  157. var selected = session.doc.getTextRange(selection);
  158. if (selected !== "" && editor.getWrapBehavioursEnabled()) {
  159. return getWrapped(selection, selected, '(', ')');
  160. } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
  161. CstyleBehaviour.recordAutoInsert(editor, session, ")");
  162. return {
  163. text: '()',
  164. selection: [1, 1]
  165. };
  166. }
  167. } else if (text == ')') {
  168. initContext(editor);
  169. var cursor = editor.getCursorPosition();
  170. var line = session.doc.getLine(cursor.row);
  171. var rightChar = line.substring(cursor.column, cursor.column + 1);
  172. if (rightChar == ')') {
  173. var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row});
  174. if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
  175. CstyleBehaviour.popAutoInsertedClosing();
  176. return {
  177. text: '',
  178. selection: [1, 1]
  179. };
  180. }
  181. }
  182. }
  183. });
  184. this.add("parens", "deletion", function(state, action, editor, session, range) {
  185. var selected = session.doc.getTextRange(range);
  186. if (!range.isMultiLine() && selected == '(') {
  187. initContext(editor);
  188. var line = session.doc.getLine(range.start.row);
  189. var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
  190. if (rightChar == ')') {
  191. range.end.column++;
  192. return range;
  193. }
  194. }
  195. });
  196. this.add("brackets", "insertion", function(state, action, editor, session, text) {
  197. if (text == '[') {
  198. initContext(editor);
  199. var selection = editor.getSelectionRange();
  200. var selected = session.doc.getTextRange(selection);
  201. if (selected !== "" && editor.getWrapBehavioursEnabled()) {
  202. return getWrapped(selection, selected, '[', ']');
  203. } else if (CstyleBehaviour.isSaneInsertion(editor, session)) {
  204. CstyleBehaviour.recordAutoInsert(editor, session, "]");
  205. return {
  206. text: '[]',
  207. selection: [1, 1]
  208. };
  209. }
  210. } else if (text == ']') {
  211. initContext(editor);
  212. var cursor = editor.getCursorPosition();
  213. var line = session.doc.getLine(cursor.row);
  214. var rightChar = line.substring(cursor.column, cursor.column + 1);
  215. if (rightChar == ']') {
  216. var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row});
  217. if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) {
  218. CstyleBehaviour.popAutoInsertedClosing();
  219. return {
  220. text: '',
  221. selection: [1, 1]
  222. };
  223. }
  224. }
  225. }
  226. });
  227. this.add("brackets", "deletion", function(state, action, editor, session, range) {
  228. var selected = session.doc.getTextRange(range);
  229. if (!range.isMultiLine() && selected == '[') {
  230. initContext(editor);
  231. var line = session.doc.getLine(range.start.row);
  232. var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
  233. if (rightChar == ']') {
  234. range.end.column++;
  235. return range;
  236. }
  237. }
  238. });
  239. this.add("string_dquotes", "insertion", function(state, action, editor, session, text) {
  240. if (text == '"' || text == "'") {
  241. initContext(editor);
  242. var quote = text;
  243. var selection = editor.getSelectionRange();
  244. var selected = session.doc.getTextRange(selection);
  245. if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) {
  246. return getWrapped(selection, selected, quote, quote);
  247. } else if (!selected) {
  248. var cursor = editor.getCursorPosition();
  249. var line = session.doc.getLine(cursor.row);
  250. var leftChar = line.substring(cursor.column-1, cursor.column);
  251. var rightChar = line.substring(cursor.column, cursor.column + 1);
  252. var token = session.getTokenAt(cursor.row, cursor.column);
  253. var rightToken = session.getTokenAt(cursor.row, cursor.column + 1);
  254. // We're escaped.
  255. if (leftChar == "\\" && token && /escape/.test(token.type))
  256. return null;
  257. var stringBefore = token && /string|escape/.test(token.type);
  258. var stringAfter = !rightToken || /string|escape/.test(rightToken.type);
  259. var pair;
  260. if (rightChar == quote) {
  261. pair = stringBefore !== stringAfter;
  262. } else {
  263. if (stringBefore && !stringAfter)
  264. return null; // wrap string with different quote
  265. if (stringBefore && stringAfter)
  266. return null; // do not pair quotes inside strings
  267. var wordRe = session.$mode.tokenRe;
  268. wordRe.lastIndex = 0;
  269. var isWordBefore = wordRe.test(leftChar);
  270. wordRe.lastIndex = 0;
  271. var isWordAfter = wordRe.test(leftChar);
  272. if (isWordBefore || isWordAfter)
  273. return null; // before or after alphanumeric
  274. if (rightChar && !/[\s;,.})\]\\]/.test(rightChar))
  275. return null; // there is rightChar and it isn't closing
  276. pair = true;
  277. }
  278. return {
  279. text: pair ? quote + quote : "",
  280. selection: [1,1]
  281. };
  282. }
  283. }
  284. });
  285. this.add("string_dquotes", "deletion", function(state, action, editor, session, range) {
  286. var selected = session.doc.getTextRange(range);
  287. if (!range.isMultiLine() && (selected == '"' || selected == "'")) {
  288. initContext(editor);
  289. var line = session.doc.getLine(range.start.row);
  290. var rightChar = line.substring(range.start.column + 1, range.start.column + 2);
  291. if (rightChar == selected) {
  292. range.end.column++;
  293. return range;
  294. }
  295. }
  296. });
  297. };
  298. CstyleBehaviour.isSaneInsertion = function(editor, session) {
  299. var cursor = editor.getCursorPosition();
  300. var iterator = new TokenIterator(session, cursor.row, cursor.column);
  301. // Don't insert in the middle of a keyword/identifier/lexical
  302. if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) {
  303. // Look ahead in case we're at the end of a token
  304. var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1);
  305. if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS))
  306. return false;
  307. }
  308. // Only insert in front of whitespace/comments
  309. iterator.stepForward();
  310. return iterator.getCurrentTokenRow() !== cursor.row ||
  311. this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS);
  312. };
  313. CstyleBehaviour.$matchTokenType = function(token, types) {
  314. return types.indexOf(token.type || token) > -1;
  315. };
  316. CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) {
  317. var cursor = editor.getCursorPosition();
  318. var line = session.doc.getLine(cursor.row);
  319. // Reset previous state if text or context changed too much
  320. if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0]))
  321. context.autoInsertedBrackets = 0;
  322. context.autoInsertedRow = cursor.row;
  323. context.autoInsertedLineEnd = bracket + line.substr(cursor.column);
  324. context.autoInsertedBrackets++;
  325. };
  326. CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) {
  327. var cursor = editor.getCursorPosition();
  328. var line = session.doc.getLine(cursor.row);
  329. if (!this.isMaybeInsertedClosing(cursor, line))
  330. context.maybeInsertedBrackets = 0;
  331. context.maybeInsertedRow = cursor.row;
  332. context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket;
  333. context.maybeInsertedLineEnd = line.substr(cursor.column);
  334. context.maybeInsertedBrackets++;
  335. };
  336. CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) {
  337. return context.autoInsertedBrackets > 0 &&
  338. cursor.row === context.autoInsertedRow &&
  339. bracket === context.autoInsertedLineEnd[0] &&
  340. line.substr(cursor.column) === context.autoInsertedLineEnd;
  341. };
  342. CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) {
  343. return context.maybeInsertedBrackets > 0 &&
  344. cursor.row === context.maybeInsertedRow &&
  345. line.substr(cursor.column) === context.maybeInsertedLineEnd &&
  346. line.substr(0, cursor.column) == context.maybeInsertedLineStart;
  347. };
  348. CstyleBehaviour.popAutoInsertedClosing = function() {
  349. context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1);
  350. context.autoInsertedBrackets--;
  351. };
  352. CstyleBehaviour.clearMaybeInsertedClosing = function() {
  353. if (context) {
  354. context.maybeInsertedBrackets = 0;
  355. context.maybeInsertedRow = -1;
  356. }
  357. };
  358. oop.inherits(CstyleBehaviour, Behaviour);
  359. exports.CstyleBehaviour = CstyleBehaviour;
  360. });