stylus.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // Stylus mode created by Dmitry Kiselyov http://git.io/AaRB
  4. (function(mod) {
  5. if (typeof exports == "object" && typeof module == "object") // CommonJS
  6. mod(require("../../lib/codemirror"));
  7. else if (typeof define == "function" && define.amd) // AMD
  8. define(["../../lib/codemirror"], mod);
  9. else // Plain browser env
  10. mod(CodeMirror);
  11. })(function(CodeMirror) {
  12. "use strict";
  13. CodeMirror.defineMode("stylus", function(config) {
  14. var indentUnit = config.indentUnit,
  15. tagKeywords = keySet(tagKeywords_),
  16. tagVariablesRegexp = /^(a|b|i|s|col|em)$/i,
  17. propertyKeywords = keySet(propertyKeywords_),
  18. nonStandardPropertyKeywords = keySet(nonStandardPropertyKeywords_),
  19. valueKeywords = keySet(valueKeywords_),
  20. colorKeywords = keySet(colorKeywords_),
  21. documentTypes = keySet(documentTypes_),
  22. documentTypesRegexp = wordRegexp(documentTypes_),
  23. mediaFeatures = keySet(mediaFeatures_),
  24. mediaTypes = keySet(mediaTypes_),
  25. fontProperties = keySet(fontProperties_),
  26. operatorsRegexp = /^\s*([.]{2,3}|&&|\|\||\*\*|[?!=:]?=|[-+*\/%<>]=?|\?:|\~)/,
  27. wordOperatorKeywordsRegexp = wordRegexp(wordOperatorKeywords_),
  28. blockKeywords = keySet(blockKeywords_),
  29. vendorPrefixesRegexp = new RegExp(/^\-(moz|ms|o|webkit)-/i),
  30. commonAtoms = keySet(commonAtoms_),
  31. firstWordMatch = "",
  32. states = {},
  33. ch,
  34. style,
  35. type,
  36. override;
  37. /**
  38. * Tokenizers
  39. */
  40. function tokenBase(stream, state) {
  41. firstWordMatch = stream.string.match(/(^[\w-]+\s*=\s*$)|(^\s*[\w-]+\s*=\s*[\w-])|(^\s*(\.|#|@|\$|\&|\[|\d|\+|::?|\{|\>|~|\/)?\s*[\w-]*([a-z0-9-]|\*|\/\*)(\(|,)?)/);
  42. state.context.line.firstWord = firstWordMatch ? firstWordMatch[0].replace(/^\s*/, "") : "";
  43. state.context.line.indent = stream.indentation();
  44. ch = stream.peek();
  45. // Line comment
  46. if (stream.match("//")) {
  47. stream.skipToEnd();
  48. return ["comment", "comment"];
  49. }
  50. // Block comment
  51. if (stream.match("/*")) {
  52. state.tokenize = tokenCComment;
  53. return tokenCComment(stream, state);
  54. }
  55. // String
  56. if (ch == "\"" || ch == "'") {
  57. stream.next();
  58. state.tokenize = tokenString(ch);
  59. return state.tokenize(stream, state);
  60. }
  61. // Def
  62. if (ch == "@") {
  63. stream.next();
  64. stream.eatWhile(/[\w\\-]/);
  65. return ["def", stream.current()];
  66. }
  67. // ID selector or Hex color
  68. if (ch == "#") {
  69. stream.next();
  70. // Hex color
  71. if (stream.match(/^[0-9a-f]{6}|[0-9a-f]{3}/i)) {
  72. return ["atom", "atom"];
  73. }
  74. // ID selector
  75. if (stream.match(/^[a-z][\w-]*/i)) {
  76. return ["builtin", "hash"];
  77. }
  78. }
  79. // Vendor prefixes
  80. if (stream.match(vendorPrefixesRegexp)) {
  81. return ["meta", "vendor-prefixes"];
  82. }
  83. // Numbers
  84. if (stream.match(/^-?[0-9]?\.?[0-9]/)) {
  85. stream.eatWhile(/[a-z%]/i);
  86. return ["number", "unit"];
  87. }
  88. // !important|optional
  89. if (ch == "!") {
  90. stream.next();
  91. return [stream.match(/^(important|optional)/i) ? "keyword": "operator", "important"];
  92. }
  93. // Class
  94. if (ch == "." && stream.match(/^\.[a-z][\w-]*/i)) {
  95. return ["qualifier", "qualifier"];
  96. }
  97. // url url-prefix domain regexp
  98. if (stream.match(documentTypesRegexp)) {
  99. if (stream.peek() == "(") state.tokenize = tokenParenthesized;
  100. return ["property", "word"];
  101. }
  102. // Mixins / Functions
  103. if (stream.match(/^[a-z][\w-]*\(/i)) {
  104. stream.backUp(1);
  105. return ["keyword", "mixin"];
  106. }
  107. // Block mixins
  108. if (stream.match(/^(\+|-)[a-z][\w-]*\(/i)) {
  109. stream.backUp(1);
  110. return ["keyword", "block-mixin"];
  111. }
  112. // Parent Reference BEM naming
  113. if (stream.string.match(/^\s*&/) && stream.match(/^[-_]+[a-z][\w-]*/)) {
  114. return ["qualifier", "qualifier"];
  115. }
  116. // / Root Reference & Parent Reference
  117. if (stream.match(/^(\/|&)(-|_|:|\.|#|[a-z])/)) {
  118. stream.backUp(1);
  119. return ["variable-3", "reference"];
  120. }
  121. if (stream.match(/^&{1}\s*$/)) {
  122. return ["variable-3", "reference"];
  123. }
  124. // Word operator
  125. if (stream.match(wordOperatorKeywordsRegexp)) {
  126. return ["operator", "operator"];
  127. }
  128. // Word
  129. if (stream.match(/^\$?[-_]*[a-z0-9]+[\w-]*/i)) {
  130. // Variable
  131. if (stream.match(/^(\.|\[)[\w-\'\"\]]+/i, false)) {
  132. if (!wordIsTag(stream.current())) {
  133. stream.match(/\./);
  134. return ["variable-2", "variable-name"];
  135. }
  136. }
  137. return ["variable-2", "word"];
  138. }
  139. // Operators
  140. if (stream.match(operatorsRegexp)) {
  141. return ["operator", stream.current()];
  142. }
  143. // Delimiters
  144. if (/[:;,{}\[\]\(\)]/.test(ch)) {
  145. stream.next();
  146. return [null, ch];
  147. }
  148. // Non-detected items
  149. stream.next();
  150. return [null, null];
  151. }
  152. /**
  153. * Token comment
  154. */
  155. function tokenCComment(stream, state) {
  156. var maybeEnd = false, ch;
  157. while ((ch = stream.next()) != null) {
  158. if (maybeEnd && ch == "/") {
  159. state.tokenize = null;
  160. break;
  161. }
  162. maybeEnd = (ch == "*");
  163. }
  164. return ["comment", "comment"];
  165. }
  166. /**
  167. * Token string
  168. */
  169. function tokenString(quote) {
  170. return function(stream, state) {
  171. var escaped = false, ch;
  172. while ((ch = stream.next()) != null) {
  173. if (ch == quote && !escaped) {
  174. if (quote == ")") stream.backUp(1);
  175. break;
  176. }
  177. escaped = !escaped && ch == "\\";
  178. }
  179. if (ch == quote || !escaped && quote != ")") state.tokenize = null;
  180. return ["string", "string"];
  181. };
  182. }
  183. /**
  184. * Token parenthesized
  185. */
  186. function tokenParenthesized(stream, state) {
  187. stream.next(); // Must be "("
  188. if (!stream.match(/\s*[\"\')]/, false))
  189. state.tokenize = tokenString(")");
  190. else
  191. state.tokenize = null;
  192. return [null, "("];
  193. }
  194. /**
  195. * Context management
  196. */
  197. function Context(type, indent, prev, line) {
  198. this.type = type;
  199. this.indent = indent;
  200. this.prev = prev;
  201. this.line = line || {firstWord: "", indent: 0};
  202. }
  203. function pushContext(state, stream, type, indent) {
  204. indent = indent >= 0 ? indent : indentUnit;
  205. state.context = new Context(type, stream.indentation() + indent, state.context);
  206. return type;
  207. }
  208. function popContext(state, currentIndent) {
  209. var contextIndent = state.context.indent - indentUnit;
  210. currentIndent = currentIndent || false;
  211. state.context = state.context.prev;
  212. if (currentIndent) state.context.indent = contextIndent;
  213. return state.context.type;
  214. }
  215. function pass(type, stream, state) {
  216. return states[state.context.type](type, stream, state);
  217. }
  218. function popAndPass(type, stream, state, n) {
  219. for (var i = n || 1; i > 0; i--)
  220. state.context = state.context.prev;
  221. return pass(type, stream, state);
  222. }
  223. /**
  224. * Parser
  225. */
  226. function wordIsTag(word) {
  227. return word.toLowerCase() in tagKeywords;
  228. }
  229. function wordIsProperty(word) {
  230. word = word.toLowerCase();
  231. return word in propertyKeywords || word in fontProperties;
  232. }
  233. function wordIsBlock(word) {
  234. return word.toLowerCase() in blockKeywords;
  235. }
  236. function wordIsVendorPrefix(word) {
  237. return word.toLowerCase().match(vendorPrefixesRegexp);
  238. }
  239. function wordAsValue(word) {
  240. var wordLC = word.toLowerCase();
  241. var override = "variable-2";
  242. if (wordIsTag(word)) override = "tag";
  243. else if (wordIsBlock(word)) override = "block-keyword";
  244. else if (wordIsProperty(word)) override = "property";
  245. else if (wordLC in valueKeywords || wordLC in commonAtoms) override = "atom";
  246. else if (wordLC == "return" || wordLC in colorKeywords) override = "keyword";
  247. // Font family
  248. else if (word.match(/^[A-Z]/)) override = "string";
  249. return override;
  250. }
  251. function typeIsBlock(type, stream) {
  252. return ((endOfLine(stream) && (type == "{" || type == "]" || type == "hash" || type == "qualifier")) || type == "block-mixin");
  253. }
  254. function typeIsInterpolation(type, stream) {
  255. return type == "{" && stream.match(/^\s*\$?[\w-]+/i, false);
  256. }
  257. function typeIsPseudo(type, stream) {
  258. return type == ":" && stream.match(/^[a-z-]+/, false);
  259. }
  260. function startOfLine(stream) {
  261. return stream.sol() || stream.string.match(new RegExp("^\\s*" + escapeRegExp(stream.current())));
  262. }
  263. function endOfLine(stream) {
  264. return stream.eol() || stream.match(/^\s*$/, false);
  265. }
  266. function firstWordOfLine(line) {
  267. var re = /^\s*[-_]*[a-z0-9]+[\w-]*/i;
  268. var result = typeof line == "string" ? line.match(re) : line.string.match(re);
  269. return result ? result[0].replace(/^\s*/, "") : "";
  270. }
  271. /**
  272. * Block
  273. */
  274. states.block = function(type, stream, state) {
  275. if ((type == "comment" && startOfLine(stream)) ||
  276. (type == "," && endOfLine(stream)) ||
  277. type == "mixin") {
  278. return pushContext(state, stream, "block", 0);
  279. }
  280. if (typeIsInterpolation(type, stream)) {
  281. return pushContext(state, stream, "interpolation");
  282. }
  283. if (endOfLine(stream) && type == "]") {
  284. if (!/^\s*(\.|#|:|\[|\*|&)/.test(stream.string) && !wordIsTag(firstWordOfLine(stream))) {
  285. return pushContext(state, stream, "block", 0);
  286. }
  287. }
  288. if (typeIsBlock(type, stream, state)) {
  289. return pushContext(state, stream, "block");
  290. }
  291. if (type == "}" && endOfLine(stream)) {
  292. return pushContext(state, stream, "block", 0);
  293. }
  294. if (type == "variable-name") {
  295. if (stream.string.match(/^\s?\$[\w-\.\[\]\'\"]+$/) || wordIsBlock(firstWordOfLine(stream))) {
  296. return pushContext(state, stream, "variableName");
  297. }
  298. else {
  299. return pushContext(state, stream, "variableName", 0);
  300. }
  301. }
  302. if (type == "=") {
  303. if (!endOfLine(stream) && !wordIsBlock(firstWordOfLine(stream))) {
  304. return pushContext(state, stream, "block", 0);
  305. }
  306. return pushContext(state, stream, "block");
  307. }
  308. if (type == "*") {
  309. if (endOfLine(stream) || stream.match(/\s*(,|\.|#|\[|:|{)/,false)) {
  310. override = "tag";
  311. return pushContext(state, stream, "block");
  312. }
  313. }
  314. if (typeIsPseudo(type, stream)) {
  315. return pushContext(state, stream, "pseudo");
  316. }
  317. if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) {
  318. return pushContext(state, stream, endOfLine(stream) ? "block" : "atBlock");
  319. }
  320. if (/@(-(moz|ms|o|webkit)-)?keyframes$/.test(type)) {
  321. return pushContext(state, stream, "keyframes");
  322. }
  323. if (/@extends?/.test(type)) {
  324. return pushContext(state, stream, "extend", 0);
  325. }
  326. if (type && type.charAt(0) == "@") {
  327. // Property Lookup
  328. if (stream.indentation() > 0 && wordIsProperty(stream.current().slice(1))) {
  329. override = "variable-2";
  330. return "block";
  331. }
  332. if (/(@import|@require|@charset)/.test(type)) {
  333. return pushContext(state, stream, "block", 0);
  334. }
  335. return pushContext(state, stream, "block");
  336. }
  337. if (type == "reference" && endOfLine(stream)) {
  338. return pushContext(state, stream, "block");
  339. }
  340. if (type == "(") {
  341. return pushContext(state, stream, "parens");
  342. }
  343. if (type == "vendor-prefixes") {
  344. return pushContext(state, stream, "vendorPrefixes");
  345. }
  346. if (type == "word") {
  347. var word = stream.current();
  348. override = wordAsValue(word);
  349. if (override == "property") {
  350. if (startOfLine(stream)) {
  351. return pushContext(state, stream, "block", 0);
  352. } else {
  353. override = "atom";
  354. return "block";
  355. }
  356. }
  357. if (override == "tag") {
  358. // tag is a css value
  359. if (/embed|menu|pre|progress|sub|table/.test(word)) {
  360. if (wordIsProperty(firstWordOfLine(stream))) {
  361. override = "atom";
  362. return "block";
  363. }
  364. }
  365. // tag is an attribute
  366. if (stream.string.match(new RegExp("\\[\\s*" + word + "|" + word +"\\s*\\]"))) {
  367. override = "atom";
  368. return "block";
  369. }
  370. // tag is a variable
  371. if (tagVariablesRegexp.test(word)) {
  372. if ((startOfLine(stream) && stream.string.match(/=/)) ||
  373. (!startOfLine(stream) &&
  374. !stream.string.match(/^(\s*\.|#|\&|\[|\/|>|\*)/) &&
  375. !wordIsTag(firstWordOfLine(stream)))) {
  376. override = "variable-2";
  377. if (wordIsBlock(firstWordOfLine(stream))) return "block";
  378. return pushContext(state, stream, "block", 0);
  379. }
  380. }
  381. if (endOfLine(stream)) return pushContext(state, stream, "block");
  382. }
  383. if (override == "block-keyword") {
  384. override = "keyword";
  385. // Postfix conditionals
  386. if (stream.current(/(if|unless)/) && !startOfLine(stream)) {
  387. return "block";
  388. }
  389. return pushContext(state, stream, "block");
  390. }
  391. if (word == "return") return pushContext(state, stream, "block", 0);
  392. // Placeholder selector
  393. if (override == "variable-2" && stream.string.match(/^\s?\$[\w-\.\[\]\'\"]+$/)) {
  394. return pushContext(state, stream, "block");
  395. }
  396. }
  397. return state.context.type;
  398. };
  399. /**
  400. * Parens
  401. */
  402. states.parens = function(type, stream, state) {
  403. if (type == "(") return pushContext(state, stream, "parens");
  404. if (type == ")") {
  405. if (state.context.prev.type == "parens") {
  406. return popContext(state);
  407. }
  408. if ((stream.string.match(/^[a-z][\w-]*\(/i) && endOfLine(stream)) ||
  409. wordIsBlock(firstWordOfLine(stream)) ||
  410. /(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(firstWordOfLine(stream)) ||
  411. (!stream.string.match(/^-?[a-z][\w-\.\[\]\'\"]*\s*=/) &&
  412. wordIsTag(firstWordOfLine(stream)))) {
  413. return pushContext(state, stream, "block");
  414. }
  415. if (stream.string.match(/^[\$-]?[a-z][\w-\.\[\]\'\"]*\s*=/) ||
  416. stream.string.match(/^\s*(\(|\)|[0-9])/) ||
  417. stream.string.match(/^\s+[a-z][\w-]*\(/i) ||
  418. stream.string.match(/^\s+[\$-]?[a-z]/i)) {
  419. return pushContext(state, stream, "block", 0);
  420. }
  421. if (endOfLine(stream)) return pushContext(state, stream, "block");
  422. else return pushContext(state, stream, "block", 0);
  423. }
  424. if (type && type.charAt(0) == "@" && wordIsProperty(stream.current().slice(1))) {
  425. override = "variable-2";
  426. }
  427. if (type == "word") {
  428. var word = stream.current();
  429. override = wordAsValue(word);
  430. if (override == "tag" && tagVariablesRegexp.test(word)) {
  431. override = "variable-2";
  432. }
  433. if (override == "property" || word == "to") override = "atom";
  434. }
  435. if (type == "variable-name") {
  436. return pushContext(state, stream, "variableName");
  437. }
  438. if (typeIsPseudo(type, stream)) {
  439. return pushContext(state, stream, "pseudo");
  440. }
  441. return state.context.type;
  442. };
  443. /**
  444. * Vendor prefixes
  445. */
  446. states.vendorPrefixes = function(type, stream, state) {
  447. if (type == "word") {
  448. override = "property";
  449. return pushContext(state, stream, "block", 0);
  450. }
  451. return popContext(state);
  452. };
  453. /**
  454. * Pseudo
  455. */
  456. states.pseudo = function(type, stream, state) {
  457. if (!wordIsProperty(firstWordOfLine(stream.string))) {
  458. stream.match(/^[a-z-]+/);
  459. override = "variable-3";
  460. if (endOfLine(stream)) return pushContext(state, stream, "block");
  461. return popContext(state);
  462. }
  463. return popAndPass(type, stream, state);
  464. };
  465. /**
  466. * atBlock
  467. */
  468. states.atBlock = function(type, stream, state) {
  469. if (type == "(") return pushContext(state, stream, "atBlock_parens");
  470. if (typeIsBlock(type, stream, state)) {
  471. return pushContext(state, stream, "block");
  472. }
  473. if (typeIsInterpolation(type, stream)) {
  474. return pushContext(state, stream, "interpolation");
  475. }
  476. if (type == "word") {
  477. var word = stream.current().toLowerCase();
  478. if (/^(only|not|and|or)$/.test(word))
  479. override = "keyword";
  480. else if (documentTypes.hasOwnProperty(word))
  481. override = "tag";
  482. else if (mediaTypes.hasOwnProperty(word))
  483. override = "attribute";
  484. else if (mediaFeatures.hasOwnProperty(word))
  485. override = "property";
  486. else if (nonStandardPropertyKeywords.hasOwnProperty(word))
  487. override = "string-2";
  488. else override = wordAsValue(stream.current());
  489. if (override == "tag" && endOfLine(stream)) {
  490. return pushContext(state, stream, "block");
  491. }
  492. }
  493. if (type == "operator" && /^(not|and|or)$/.test(stream.current())) {
  494. override = "keyword";
  495. }
  496. return state.context.type;
  497. };
  498. states.atBlock_parens = function(type, stream, state) {
  499. if (type == "{" || type == "}") return state.context.type;
  500. if (type == ")") {
  501. if (endOfLine(stream)) return pushContext(state, stream, "block");
  502. else return pushContext(state, stream, "atBlock");
  503. }
  504. if (type == "word") {
  505. var word = stream.current().toLowerCase();
  506. override = wordAsValue(word);
  507. if (/^(max|min)/.test(word)) override = "property";
  508. if (override == "tag") {
  509. tagVariablesRegexp.test(word) ? override = "variable-2" : override = "atom";
  510. }
  511. return state.context.type;
  512. }
  513. return states.atBlock(type, stream, state);
  514. };
  515. /**
  516. * Keyframes
  517. */
  518. states.keyframes = function(type, stream, state) {
  519. if (stream.indentation() == "0" && ((type == "}" && startOfLine(stream)) || type == "]" || type == "hash"
  520. || type == "qualifier" || wordIsTag(stream.current()))) {
  521. return popAndPass(type, stream, state);
  522. }
  523. if (type == "{") return pushContext(state, stream, "keyframes");
  524. if (type == "}") {
  525. if (startOfLine(stream)) return popContext(state, true);
  526. else return pushContext(state, stream, "keyframes");
  527. }
  528. if (type == "unit" && /^[0-9]+\%$/.test(stream.current())) {
  529. return pushContext(state, stream, "keyframes");
  530. }
  531. if (type == "word") {
  532. override = wordAsValue(stream.current());
  533. if (override == "block-keyword") {
  534. override = "keyword";
  535. return pushContext(state, stream, "keyframes");
  536. }
  537. }
  538. if (/@(font-face|media|supports|(-moz-)?document)/.test(type)) {
  539. return pushContext(state, stream, endOfLine(stream) ? "block" : "atBlock");
  540. }
  541. if (type == "mixin") {
  542. return pushContext(state, stream, "block", 0);
  543. }
  544. return state.context.type;
  545. };
  546. /**
  547. * Interpolation
  548. */
  549. states.interpolation = function(type, stream, state) {
  550. if (type == "{") popContext(state) && pushContext(state, stream, "block");
  551. if (type == "}") {
  552. if (stream.string.match(/^\s*(\.|#|:|\[|\*|&|>|~|\+|\/)/i) ||
  553. (stream.string.match(/^\s*[a-z]/i) && wordIsTag(firstWordOfLine(stream)))) {
  554. return pushContext(state, stream, "block");
  555. }
  556. if (!stream.string.match(/^(\{|\s*\&)/) ||
  557. stream.match(/\s*[\w-]/,false)) {
  558. return pushContext(state, stream, "block", 0);
  559. }
  560. return pushContext(state, stream, "block");
  561. }
  562. if (type == "variable-name") {
  563. return pushContext(state, stream, "variableName", 0);
  564. }
  565. if (type == "word") {
  566. override = wordAsValue(stream.current());
  567. if (override == "tag") override = "atom";
  568. }
  569. return state.context.type;
  570. };
  571. /**
  572. * Extend/s
  573. */
  574. states.extend = function(type, stream, state) {
  575. if (type == "[" || type == "=") return "extend";
  576. if (type == "]") return popContext(state);
  577. if (type == "word") {
  578. override = wordAsValue(stream.current());
  579. return "extend";
  580. }
  581. return popContext(state);
  582. };
  583. /**
  584. * Variable name
  585. */
  586. states.variableName = function(type, stream, state) {
  587. if (type == "string" || type == "[" || type == "]" || stream.current().match(/^(\.|\$)/)) {
  588. if (stream.current().match(/^\.[\w-]+/i)) override = "variable-2";
  589. return "variableName";
  590. }
  591. return popAndPass(type, stream, state);
  592. };
  593. return {
  594. startState: function(base) {
  595. return {
  596. tokenize: null,
  597. state: "block",
  598. context: new Context("block", base || 0, null)
  599. };
  600. },
  601. token: function(stream, state) {
  602. if (!state.tokenize && stream.eatSpace()) return null;
  603. style = (state.tokenize || tokenBase)(stream, state);
  604. if (style && typeof style == "object") {
  605. type = style[1];
  606. style = style[0];
  607. }
  608. override = style;
  609. state.state = states[state.state](type, stream, state);
  610. return override;
  611. },
  612. indent: function(state, textAfter, line) {
  613. var cx = state.context,
  614. ch = textAfter && textAfter.charAt(0),
  615. indent = cx.indent,
  616. lineFirstWord = firstWordOfLine(textAfter),
  617. lineIndent = line.length - line.replace(/^\s*/, "").length,
  618. prevLineFirstWord = state.context.prev ? state.context.prev.line.firstWord : "",
  619. prevLineIndent = state.context.prev ? state.context.prev.line.indent : lineIndent;
  620. if (cx.prev &&
  621. (ch == "}" && (cx.type == "block" || cx.type == "atBlock" || cx.type == "keyframes") ||
  622. ch == ")" && (cx.type == "parens" || cx.type == "atBlock_parens") ||
  623. ch == "{" && (cx.type == "at"))) {
  624. indent = cx.indent - indentUnit;
  625. cx = cx.prev;
  626. } else if (!(/(\})/.test(ch))) {
  627. if (/@|\$|\d/.test(ch) ||
  628. /^\{/.test(textAfter) ||
  629. /^\s*\/(\/|\*)/.test(textAfter) ||
  630. /^\s*\/\*/.test(prevLineFirstWord) ||
  631. /^\s*[\w-\.\[\]\'\"]+\s*(\?|:|\+)?=/i.test(textAfter) ||
  632. /^(\+|-)?[a-z][\w-]*\(/i.test(textAfter) ||
  633. /^return/.test(textAfter) ||
  634. wordIsBlock(lineFirstWord)) {
  635. indent = lineIndent;
  636. } else if (/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(ch) || wordIsTag(lineFirstWord)) {
  637. if (/\,\s*$/.test(prevLineFirstWord)) {
  638. indent = prevLineIndent;
  639. } else if (/^\s+/.test(line) && (/(\.|#|:|\[|\*|&|>|~|\+|\/)/.test(prevLineFirstWord) || wordIsTag(prevLineFirstWord))) {
  640. indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + indentUnit;
  641. } else {
  642. indent = lineIndent;
  643. }
  644. } else if (!/,\s*$/.test(line) && (wordIsVendorPrefix(lineFirstWord) || wordIsProperty(lineFirstWord))) {
  645. if (wordIsBlock(prevLineFirstWord)) {
  646. indent = lineIndent <= prevLineIndent ? prevLineIndent : prevLineIndent + indentUnit;
  647. } else if (/^\{/.test(prevLineFirstWord)) {
  648. indent = lineIndent <= prevLineIndent ? lineIndent : prevLineIndent + indentUnit;
  649. } else if (wordIsVendorPrefix(prevLineFirstWord) || wordIsProperty(prevLineFirstWord)) {
  650. indent = lineIndent >= prevLineIndent ? prevLineIndent : lineIndent;
  651. } else if (/^(\.|#|:|\[|\*|&|@|\+|\-|>|~|\/)/.test(prevLineFirstWord) ||
  652. /=\s*$/.test(prevLineFirstWord) ||
  653. wordIsTag(prevLineFirstWord) ||
  654. /^\$[\w-\.\[\]\'\"]/.test(prevLineFirstWord)) {
  655. indent = prevLineIndent + indentUnit;
  656. } else {
  657. indent = lineIndent;
  658. }
  659. }
  660. }
  661. return indent;
  662. },
  663. electricChars: "}",
  664. lineComment: "//",
  665. fold: "indent"
  666. };
  667. });
  668. // developer.mozilla.org/en-US/docs/Web/HTML/Element
  669. var tagKeywords_ = ["a","abbr","address","area","article","aside","audio", "b", "base","bdi", "bdo","bgsound","blockquote","body","br","button","canvas","caption","cite", "code","col","colgroup","data","datalist","dd","del","details","dfn","div", "dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1", "h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe", "img","input","ins","kbd","keygen","label","legend","li","link","main","map", "mark","marquee","menu","menuitem","meta","meter","nav","nobr","noframes", "noscript","object","ol","optgroup","option","output","p","param","pre", "progress","q","rp","rt","ruby","s","samp","script","section","select", "small","source","span","strong","style","sub","summary","sup","table","tbody","td","textarea","tfoot","th","thead","time","tr","track", "u","ul","var","video"];
  670. // github.com/codemirror/CodeMirror/blob/master/mode/css/css.js
  671. var documentTypes_ = ["domain", "regexp", "url", "url-prefix"];
  672. var mediaTypes_ = ["all","aural","braille","handheld","print","projection","screen","tty","tv","embossed"];
  673. var mediaFeatures_ = ["width","min-width","max-width","height","min-height","max-height","device-width","min-device-width","max-device-width","device-height","min-device-height","max-device-height","aspect-ratio","min-aspect-ratio","max-aspect-ratio","device-aspect-ratio","min-device-aspect-ratio","max-device-aspect-ratio","color","min-color","max-color","color-index","min-color-index","max-color-index","monochrome","min-monochrome","max-monochrome","resolution","min-resolution","max-resolution","scan","grid"];
  674. var propertyKeywords_ = ["align-content","align-items","align-self","alignment-adjust","alignment-baseline","anchor-point","animation","animation-delay","animation-direction","animation-duration","animation-fill-mode","animation-iteration-count","animation-name","animation-play-state","animation-timing-function","appearance","azimuth","backface-visibility","background","background-attachment","background-clip","background-color","background-image","background-origin","background-position","background-repeat","background-size","baseline-shift","binding","bleed","bookmark-label","bookmark-level","bookmark-state","bookmark-target","border","border-bottom","border-bottom-color","border-bottom-left-radius","border-bottom-right-radius","border-bottom-style","border-bottom-width","border-collapse","border-color","border-image","border-image-outset","border-image-repeat","border-image-slice","border-image-source","border-image-width","border-left","border-left-color","border-left-style","border-left-width","border-radius","border-right","border-right-color","border-right-style","border-right-width","border-spacing","border-style","border-top","border-top-color","border-top-left-radius","border-top-right-radius","border-top-style","border-top-width","border-width","bottom","box-decoration-break","box-shadow","box-sizing","break-after","break-before","break-inside","caption-side","clear","clip","color","color-profile","column-count","column-fill","column-gap","column-rule","column-rule-color","column-rule-style","column-rule-width","column-span","column-width","columns","content","counter-increment","counter-reset","crop","cue","cue-after","cue-before","cursor","direction","display","dominant-baseline","drop-initial-after-adjust","drop-initial-after-align","drop-initial-before-adjust","drop-initial-before-align","drop-initial-size","drop-initial-value","elevation","empty-cells","fit","fit-position","flex","flex-basis","flex-direction","flex-flow","flex-grow","flex-shrink","flex-wrap","float","float-offset","flow-from","flow-into","font","font-feature-settings","font-family","font-kerning","font-language-override","font-size","font-size-adjust","font-stretch","font-style","font-synthesis","font-variant","font-variant-alternates","font-variant-caps","font-variant-east-asian","font-variant-ligatures","font-variant-numeric","font-variant-position","font-weight","grid","grid-area","grid-auto-columns","grid-auto-flow","grid-auto-position","grid-auto-rows","grid-column","grid-column-end","grid-column-start","grid-row","grid-row-end","grid-row-start","grid-template","grid-template-areas","grid-template-columns","grid-template-rows","hanging-punctuation","height","hyphens","icon","image-orientation","image-rendering","image-resolution","inline-box-align","justify-content","left","letter-spacing","line-break","line-height","line-stacking","line-stacking-ruby","line-stacking-shift","line-stacking-strategy","list-style","list-style-image","list-style-position","list-style-type","margin","margin-bottom","margin-left","margin-right","margin-top","marker-offset","marks","marquee-direction","marquee-loop","marquee-play-count","marquee-speed","marquee-style","max-height","max-width","min-height","min-width","move-to","nav-down","nav-index","nav-left","nav-right","nav-up","object-fit","object-position","opacity","order","orphans","outline","outline-color","outline-offset","outline-style","outline-width","overflow","overflow-style","overflow-wrap","overflow-x","overflow-y","padding","padding-bottom","padding-left","padding-right","padding-top","page","page-break-after","page-break-before","page-break-inside","page-policy","pause","pause-after","pause-before","perspective","perspective-origin","pitch","pitch-range","play-during","position","presentation-level","punctuation-trim","quotes","region-break-after","region-break-before","region-break-inside","region-fragment","rendering-intent","resize","rest","rest-after","rest-before","richness","right","rotation","rotation-point","ruby-align","ruby-overhang","ruby-position","ruby-span","shape-image-threshold","shape-inside","shape-margin","shape-outside","size","speak","speak-as","speak-header","speak-numeral","speak-punctuation","speech-rate","stress","string-set","tab-size","table-layout","target","target-name","target-new","target-position","text-align","text-align-last","text-decoration","text-decoration-color","text-decoration-line","text-decoration-skip","text-decoration-style","text-emphasis","text-emphasis-color","text-emphasis-position","text-emphasis-style","text-height","text-indent","text-justify","text-outline","text-overflow","text-shadow","text-size-adjust","text-space-collapse","text-transform","text-underline-position","text-wrap","top","transform","transform-origin","transform-style","transition","transition-delay","transition-duration","transition-property","transition-timing-function","unicode-bidi","vertical-align","visibility","voice-balance","voice-duration","voice-family","voice-pitch","voice-range","voice-rate","voice-stress","voice-volume","volume","white-space","widows","width","word-break","word-spacing","word-wrap","z-index","clip-path","clip-rule","mask","enable-background","filter","flood-color","flood-opacity","lighting-color","stop-color","stop-opacity","pointer-events","color-interpolation","color-interpolation-filters","color-rendering","fill","fill-opacity","fill-rule","image-rendering","marker","marker-end","marker-mid","marker-start","shape-rendering","stroke","stroke-dasharray","stroke-dashoffset","stroke-linecap","stroke-linejoin","stroke-miterlimit","stroke-opacity","stroke-width","text-rendering","baseline-shift","dominant-baseline","glyph-orientation-horizontal","glyph-orientation-vertical","text-anchor","writing-mode","font-smoothing","osx-font-smoothing"];
  675. var nonStandardPropertyKeywords_ = ["scrollbar-arrow-color","scrollbar-base-color","scrollbar-dark-shadow-color","scrollbar-face-color","scrollbar-highlight-color","scrollbar-shadow-color","scrollbar-3d-light-color","scrollbar-track-color","shape-inside","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","zoom"];
  676. var fontProperties_ = ["font-family","src","unicode-range","font-variant","font-feature-settings","font-stretch","font-weight","font-style"];
  677. var colorKeywords_ = ["aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","grey","green","greenyellow","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen"];
  678. var valueKeywords_ = ["above","absolute","activeborder","additive","activecaption","afar","after-white-space","ahead","alias","all","all-scroll","alphabetic","alternate","always","amharic","amharic-abegede","antialiased","appworkspace","arabic-indic","armenian","asterisks","attr","auto","avoid","avoid-column","avoid-page","avoid-region","background","backwards","baseline","below","bidi-override","binary","bengali","blink","block","block-axis","bold","bolder","border","border-box","both","bottom","break","break-all","break-word","bullets","button","button-bevel","buttonface","buttonhighlight","buttonshadow","buttontext","calc","cambodian","capitalize","caps-lock-indicator","caption","captiontext","caret","cell","center","checkbox","circle","cjk-decimal","cjk-earthly-branch","cjk-heavenly-stem","cjk-ideographic","clear","clip","close-quote","col-resize","collapse","column","compact","condensed","contain","content","content-box","context-menu","continuous","copy","counter","counters","cover","crop","cross","crosshair","currentcolor","cursive","cyclic","dashed","decimal","decimal-leading-zero","default","default-button","destination-atop","destination-in","destination-out","destination-over","devanagari","disc","discard","disclosure-closed","disclosure-open","document","dot-dash","dot-dot-dash","dotted","double","down","e-resize","ease","ease-in","ease-in-out","ease-out","element","ellipse","ellipsis","embed","end","ethiopic","ethiopic-abegede","ethiopic-abegede-am-et","ethiopic-abegede-gez","ethiopic-abegede-ti-er","ethiopic-abegede-ti-et","ethiopic-halehame-aa-er","ethiopic-halehame-aa-et","ethiopic-halehame-am-et","ethiopic-halehame-gez","ethiopic-halehame-om-et","ethiopic-halehame-sid-et","ethiopic-halehame-so-et","ethiopic-halehame-ti-er","ethiopic-halehame-ti-et","ethiopic-halehame-tig","ethiopic-numeric","ew-resize","expanded","extends","extra-condensed","extra-expanded","fantasy","fast","fill","fixed","flat","flex","footnotes","forwards","from","geometricPrecision","georgian","graytext","groove","gujarati","gurmukhi","hand","hangul","hangul-consonant","hebrew","help","hidden","hide","higher","highlight","highlighttext","hiragana","hiragana-iroha","horizontal","hsl","hsla","icon","ignore","inactiveborder","inactivecaption","inactivecaptiontext","infinite","infobackground","infotext","inherit","initial","inline","inline-axis","inline-block","inline-flex","inline-table","inset","inside","intrinsic","invert","italic","japanese-formal","japanese-informal","justify","kannada","katakana","katakana-iroha","keep-all","khmer","korean-hangul-formal","korean-hanja-formal","korean-hanja-informal","landscape","lao","large","larger","left","level","lighter","line-through","linear","linear-gradient","lines","list-item","listbox","listitem","local","logical","loud","lower","lower-alpha","lower-armenian","lower-greek","lower-hexadecimal","lower-latin","lower-norwegian","lower-roman","lowercase","ltr","malayalam","match","matrix","matrix3d","media-controls-background","media-current-time-display","media-fullscreen-button","media-mute-button","media-play-button","media-return-to-realtime-button","media-rewind-button","media-seek-back-button","media-seek-forward-button","media-slider","media-sliderthumb","media-time-remaining-display","media-volume-slider","media-volume-slider-container","media-volume-sliderthumb","medium","menu","menulist","menulist-button","menulist-text","menulist-textfield","menutext","message-box","middle","min-intrinsic","mix","mongolian","monospace","move","multiple","myanmar","n-resize","narrower","ne-resize","nesw-resize","no-close-quote","no-drop","no-open-quote","no-repeat","none","normal","not-allowed","nowrap","ns-resize","numbers","numeric","nw-resize","nwse-resize","oblique","octal","open-quote","optimizeLegibility","optimizeSpeed","oriya","oromo","outset","outside","outside-shape","overlay","overline","padding","padding-box","painted","page","paused","persian","perspective","plus-darker","plus-lighter","pointer","polygon","portrait","pre","pre-line","pre-wrap","preserve-3d","progress","push-button","radial-gradient","radio","read-only","read-write","read-write-plaintext-only","rectangle","region","relative","repeat","repeating-linear-gradient","repeating-radial-gradient","repeat-x","repeat-y","reset","reverse","rgb","rgba","ridge","right","rotate","rotate3d","rotateX","rotateY","rotateZ","round","row-resize","rtl","run-in","running","s-resize","sans-serif","scale","scale3d","scaleX","scaleY","scaleZ","scroll","scrollbar","se-resize","searchfield","searchfield-cancel-button","searchfield-decoration","searchfield-results-button","searchfield-results-decoration","semi-condensed","semi-expanded","separate","serif","show","sidama","simp-chinese-formal","simp-chinese-informal","single","skew","skewX","skewY","skip-white-space","slide","slider-horizontal","slider-vertical","sliderthumb-horizontal","sliderthumb-vertical","slow","small","small-caps","small-caption","smaller","solid","somali","source-atop","source-in","source-out","source-over","space","spell-out","square","square-button","start","static","status-bar","stretch","stroke","sub","subpixel-antialiased","super","sw-resize","symbolic","symbols","table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row","table-row-group","tamil","telugu","text","text-bottom","text-top","textarea","textfield","thai","thick","thin","threeddarkshadow","threedface","threedhighlight","threedlightshadow","threedshadow","tibetan","tigre","tigrinya-er","tigrinya-er-abegede","tigrinya-et","tigrinya-et-abegede","to","top","trad-chinese-formal","trad-chinese-informal","translate","translate3d","translateX","translateY","translateZ","transparent","ultra-condensed","ultra-expanded","underline","up","upper-alpha","upper-armenian","upper-greek","upper-hexadecimal","upper-latin","upper-norwegian","upper-roman","uppercase","urdu","url","var","vertical","vertical-text","visible","visibleFill","visiblePainted","visibleStroke","visual","w-resize","wait","wave","wider","window","windowframe","windowtext","words","x-large","x-small","xor","xx-large","xx-small","bicubic","optimizespeed","grayscale","row","row-reverse","wrap","wrap-reverse","column-reverse","flex-start","flex-end","space-between","space-around"];
  679. var wordOperatorKeywords_ = ["in","and","or","not","is not","is a","is","isnt","defined","if unless"],
  680. blockKeywords_ = ["for","if","else","unless", "from", "to"],
  681. commonAtoms_ = ["null","true","false","href","title","type","not-allowed","readonly","disabled"],
  682. commonDef_ = ["@font-face", "@keyframes", "@media", "@viewport", "@page", "@host", "@supports", "@block", "@css"];
  683. var hintWords = tagKeywords_.concat(documentTypes_,mediaTypes_,mediaFeatures_,
  684. propertyKeywords_,nonStandardPropertyKeywords_,
  685. colorKeywords_,valueKeywords_,fontProperties_,
  686. wordOperatorKeywords_,blockKeywords_,
  687. commonAtoms_,commonDef_);
  688. function wordRegexp(words) {
  689. words = words.sort(function(a,b){return b > a;});
  690. return new RegExp("^((" + words.join(")|(") + "))\\b");
  691. }
  692. function keySet(array) {
  693. var keys = {};
  694. for (var i = 0; i < array.length; ++i) keys[array[i]] = true;
  695. return keys;
  696. }
  697. function escapeRegExp(text) {
  698. return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");
  699. }
  700. CodeMirror.registerHelper("hintWords", "stylus", hintWords);
  701. CodeMirror.defineMIME("text/x-styl", "stylus");
  702. });