beautify-css.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /*jshint curly:true, eqeqeq:true, laxbreak:true, noempty:false */
  2. /*
  3. The MIT License (MIT)
  4. Copyright (c) 2007-2013 Einar Lielmanis and contributors.
  5. Permission is hereby granted, free of charge, to any person
  6. obtaining a copy of this software and associated documentation files
  7. (the "Software"), to deal in the Software without restriction,
  8. including without limitation the rights to use, copy, modify, merge,
  9. publish, distribute, sublicense, and/or sell copies of the Software,
  10. and to permit persons to whom the Software is furnished to do so,
  11. subject to the following conditions:
  12. The above copyright notice and this permission notice shall be
  13. included in all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  15. EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  16. MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  17. NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  18. BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  19. ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  21. SOFTWARE.
  22. CSS Beautifier
  23. ---------------
  24. Written by Harutyun Amirjanyan, (amirjanyan@gmail.com)
  25. Based on code initially developed by: Einar Lielmanis, <einar@jsbeautifier.org>
  26. http://jsbeautifier.org/
  27. Usage:
  28. css_beautify(source_text);
  29. css_beautify(source_text, options);
  30. The options are (default in brackets):
  31. indent_size (4) — indentation size,
  32. indent_char (space) — character to indent with,
  33. selector_separator_newline (true) - separate selectors with newline or
  34. not (e.g. "a,\nbr" or "a, br")
  35. end_with_newline (false) - end with a newline
  36. newline_between_rules (true) - add a new line after every css rule
  37. e.g
  38. css_beautify(css_source_text, {
  39. 'indent_size': 1,
  40. 'indent_char': '\t',
  41. 'selector_separator': ' ',
  42. 'end_with_newline': false,
  43. 'newline_between_rules': true
  44. });
  45. */
  46. // http://www.w3.org/TR/CSS21/syndata.html#tokenization
  47. // http://www.w3.org/TR/css3-syntax/
  48. (function() {
  49. function css_beautify(source_text, options) {
  50. options = options || {};
  51. source_text = source_text || '';
  52. // HACK: newline parsing inconsistent. This brute force normalizes the input.
  53. source_text = source_text.replace(/\r\n|[\r\u2028\u2029]/g, '\n')
  54. var indentSize = options.indent_size || 4;
  55. var indentCharacter = options.indent_char || ' ';
  56. var selectorSeparatorNewline = (options.selector_separator_newline === undefined) ? true : options.selector_separator_newline;
  57. var end_with_newline = (options.end_with_newline === undefined) ? false : options.end_with_newline;
  58. var newline_between_rules = (options.newline_between_rules === undefined) ? true : options.newline_between_rules;
  59. var eol = options.eol ? options.eol : '\n';
  60. // compatibility
  61. if (typeof indentSize === "string") {
  62. indentSize = parseInt(indentSize, 10);
  63. }
  64. if(options.indent_with_tabs){
  65. indentCharacter = '\t';
  66. indentSize = 1;
  67. }
  68. eol = eol.replace(/\\r/, '\r').replace(/\\n/, '\n')
  69. // tokenizer
  70. var whiteRe = /^\s+$/;
  71. var wordRe = /[\w$\-_]/;
  72. var pos = -1,
  73. ch;
  74. var parenLevel = 0;
  75. function next() {
  76. ch = source_text.charAt(++pos);
  77. return ch || '';
  78. }
  79. function peek(skipWhitespace) {
  80. var result = '';
  81. var prev_pos = pos;
  82. if (skipWhitespace) {
  83. eatWhitespace();
  84. }
  85. result = source_text.charAt(pos + 1) || '';
  86. pos = prev_pos - 1;
  87. next();
  88. return result;
  89. }
  90. function eatString(endChars) {
  91. var start = pos;
  92. while (next()) {
  93. if (ch === "\\") {
  94. next();
  95. } else if (endChars.indexOf(ch) !== -1) {
  96. break;
  97. } else if (ch === "\n") {
  98. break;
  99. }
  100. }
  101. return source_text.substring(start, pos + 1);
  102. }
  103. function peekString(endChar) {
  104. var prev_pos = pos;
  105. var str = eatString(endChar);
  106. pos = prev_pos - 1;
  107. next();
  108. return str;
  109. }
  110. function eatWhitespace() {
  111. var result = '';
  112. while (whiteRe.test(peek())) {
  113. next();
  114. result += ch;
  115. }
  116. return result;
  117. }
  118. function skipWhitespace() {
  119. var result = '';
  120. if (ch && whiteRe.test(ch)) {
  121. result = ch;
  122. }
  123. while (whiteRe.test(next())) {
  124. result += ch;
  125. }
  126. return result;
  127. }
  128. function eatComment(singleLine) {
  129. var start = pos;
  130. singleLine = peek() === "/";
  131. next();
  132. while (next()) {
  133. if (!singleLine && ch === "*" && peek() === "/") {
  134. next();
  135. break;
  136. } else if (singleLine && ch === "\n") {
  137. return source_text.substring(start, pos);
  138. }
  139. }
  140. return source_text.substring(start, pos) + ch;
  141. }
  142. function lookBack(str) {
  143. return source_text.substring(pos - str.length, pos).toLowerCase() ===
  144. str;
  145. }
  146. // Nested pseudo-class if we are insideRule
  147. // and the next special character found opens
  148. // a new block
  149. function foundNestedPseudoClass() {
  150. var openParen = 0;
  151. for (var i = pos + 1; i < source_text.length; i++) {
  152. var ch = source_text.charAt(i);
  153. if (ch === "{") {
  154. return true;
  155. } else if (ch === '(') {
  156. // pseudoclasses can contain ()
  157. openParen += 1;
  158. } else if (ch === ')') {
  159. if (openParen == 0) {
  160. return false;
  161. }
  162. openParen -= 1;
  163. } else if (ch === ";" || ch === "}") {
  164. return false;
  165. }
  166. }
  167. return false;
  168. }
  169. // printer
  170. var basebaseIndentString = source_text.match(/^[\t ]*/)[0];
  171. var singleIndent = new Array(indentSize + 1).join(indentCharacter);
  172. var indentLevel = 0;
  173. var nestedLevel = 0;
  174. function indent() {
  175. indentLevel++;
  176. basebaseIndentString += singleIndent;
  177. }
  178. function outdent() {
  179. indentLevel--;
  180. basebaseIndentString = basebaseIndentString.slice(0, -indentSize);
  181. }
  182. var print = {};
  183. print["{"] = function(ch) {
  184. print.singleSpace();
  185. output.push(ch);
  186. print.newLine();
  187. };
  188. print["}"] = function(ch) {
  189. print.newLine();
  190. output.push(ch);
  191. print.newLine();
  192. };
  193. print._lastCharWhitespace = function() {
  194. return whiteRe.test(output[output.length - 1]);
  195. };
  196. print.newLine = function(keepWhitespace) {
  197. if (output.length) {
  198. if (!keepWhitespace && output[output.length - 1] !== '\n') {
  199. print.trim();
  200. }
  201. output.push('\n');
  202. if (basebaseIndentString) {
  203. output.push(basebaseIndentString);
  204. }
  205. }
  206. };
  207. print.singleSpace = function() {
  208. if (output.length && !print._lastCharWhitespace()) {
  209. output.push(' ');
  210. }
  211. };
  212. print.preserveSingleSpace = function() {
  213. if (isAfterSpace) {
  214. print.singleSpace();
  215. }
  216. };
  217. print.trim = function() {
  218. while (print._lastCharWhitespace()) {
  219. output.pop();
  220. }
  221. };
  222. var output = [];
  223. /*_____________________--------------------_____________________*/
  224. var insideRule = false;
  225. var insidePropertyValue = false;
  226. var enteringConditionalGroup = false;
  227. var top_ch = '';
  228. var last_top_ch = '';
  229. while (true) {
  230. var whitespace = skipWhitespace();
  231. var isAfterSpace = whitespace !== '';
  232. var isAfterNewline = whitespace.indexOf('\n') !== -1;
  233. last_top_ch = top_ch;
  234. top_ch = ch;
  235. if (!ch) {
  236. break;
  237. } else if (ch === '/' && peek() === '*') { /* css comment */
  238. var header = indentLevel === 0;
  239. if (isAfterNewline || header) {
  240. print.newLine();
  241. }
  242. output.push(eatComment());
  243. print.newLine();
  244. if (header) {
  245. print.newLine(true);
  246. }
  247. } else if (ch === '/' && peek() === '/') { // single line comment
  248. if (!isAfterNewline && last_top_ch !== '{' ) {
  249. print.trim();
  250. }
  251. print.singleSpace();
  252. output.push(eatComment());
  253. print.newLine();
  254. } else if (ch === '@') {
  255. print.preserveSingleSpace();
  256. output.push(ch);
  257. // strip trailing space, if present, for hash property checks
  258. var variableOrRule = peekString(": ,;{}()[]/='\"");
  259. if (variableOrRule.match(/[ :]$/)) {
  260. // we have a variable or pseudo-class, add it and insert one space before continuing
  261. next();
  262. variableOrRule = eatString(": ").replace(/\s$/, '');
  263. output.push(variableOrRule);
  264. print.singleSpace();
  265. }
  266. variableOrRule = variableOrRule.replace(/\s$/, '')
  267. // might be a nesting at-rule
  268. if (variableOrRule in css_beautify.NESTED_AT_RULE) {
  269. nestedLevel += 1;
  270. if (variableOrRule in css_beautify.CONDITIONAL_GROUP_RULE) {
  271. enteringConditionalGroup = true;
  272. }
  273. }
  274. } else if (ch === '#' && peek() === '{') {
  275. print.preserveSingleSpace();
  276. output.push(eatString('}'));
  277. } else if (ch === '{') {
  278. if (peek(true) === '}') {
  279. eatWhitespace();
  280. next();
  281. print.singleSpace();
  282. output.push("{}");
  283. print.newLine();
  284. if (newline_between_rules && indentLevel === 0) {
  285. print.newLine(true);
  286. }
  287. } else {
  288. indent();
  289. print["{"](ch);
  290. // when entering conditional groups, only rulesets are allowed
  291. if (enteringConditionalGroup) {
  292. enteringConditionalGroup = false;
  293. insideRule = (indentLevel > nestedLevel);
  294. } else {
  295. // otherwise, declarations are also allowed
  296. insideRule = (indentLevel >= nestedLevel);
  297. }
  298. }
  299. } else if (ch === '}') {
  300. outdent();
  301. print["}"](ch);
  302. insideRule = false;
  303. insidePropertyValue = false;
  304. if (nestedLevel) {
  305. nestedLevel--;
  306. }
  307. if (newline_between_rules && indentLevel === 0) {
  308. print.newLine(true);
  309. }
  310. } else if (ch === ":") {
  311. eatWhitespace();
  312. if ((insideRule || enteringConditionalGroup) &&
  313. !(lookBack("&") || foundNestedPseudoClass())) {
  314. // 'property: value' delimiter
  315. // which could be in a conditional group query
  316. insidePropertyValue = true;
  317. output.push(':');
  318. print.singleSpace();
  319. } else {
  320. // sass/less parent reference don't use a space
  321. // sass nested pseudo-class don't use a space
  322. if (peek() === ":") {
  323. // pseudo-element
  324. next();
  325. output.push("::");
  326. } else {
  327. // pseudo-class
  328. output.push(':');
  329. }
  330. }
  331. } else if (ch === '"' || ch === '\'') {
  332. print.preserveSingleSpace();
  333. output.push(eatString(ch));
  334. } else if (ch === ';') {
  335. insidePropertyValue = false;
  336. output.push(ch);
  337. print.newLine();
  338. } else if (ch === '(') { // may be a url
  339. if (lookBack("url")) {
  340. output.push(ch);
  341. eatWhitespace();
  342. if (next()) {
  343. if (ch !== ')' && ch !== '"' && ch !== '\'') {
  344. output.push(eatString(')'));
  345. } else {
  346. pos--;
  347. }
  348. }
  349. } else {
  350. parenLevel++;
  351. print.preserveSingleSpace();
  352. output.push(ch);
  353. eatWhitespace();
  354. }
  355. } else if (ch === ')') {
  356. output.push(ch);
  357. parenLevel--;
  358. } else if (ch === ',') {
  359. output.push(ch);
  360. eatWhitespace();
  361. if (selectorSeparatorNewline && !insidePropertyValue && parenLevel < 1) {
  362. print.newLine();
  363. } else {
  364. print.singleSpace();
  365. }
  366. } else if (ch === ']') {
  367. output.push(ch);
  368. } else if (ch === '[') {
  369. print.preserveSingleSpace();
  370. output.push(ch);
  371. } else if (ch === '=') { // no whitespace before or after
  372. eatWhitespace()
  373. ch = '=';
  374. output.push(ch);
  375. } else {
  376. print.preserveSingleSpace();
  377. output.push(ch);
  378. }
  379. }
  380. var sweetCode = '';
  381. if (basebaseIndentString) {
  382. sweetCode += basebaseIndentString;
  383. }
  384. sweetCode += output.join('').replace(/[\r\n\t ]+$/, '');
  385. // establish end_with_newline
  386. if (end_with_newline) {
  387. sweetCode += '\n';
  388. }
  389. if (eol != '\n') {
  390. sweetCode = sweetCode.replace(/[\n]/g, eol);
  391. }
  392. return sweetCode;
  393. }
  394. // https://developer.mozilla.org/en-US/docs/Web/CSS/At-rule
  395. css_beautify.NESTED_AT_RULE = {
  396. "@page": true,
  397. "@font-face": true,
  398. "@keyframes": true,
  399. // also in CONDITIONAL_GROUP_RULE below
  400. "@media": true,
  401. "@supports": true,
  402. "@document": true
  403. };
  404. css_beautify.CONDITIONAL_GROUP_RULE = {
  405. "@media": true,
  406. "@supports": true,
  407. "@document": true
  408. };
  409. /*global define */
  410. if (typeof define === "function" && define.amd) {
  411. // Add support for AMD ( https://github.com/amdjs/amdjs-api/wiki/AMD#defineamd-property- )
  412. define([], function() {
  413. return {
  414. css_beautify: css_beautify
  415. };
  416. });
  417. } else if (typeof exports !== "undefined") {
  418. // Add support for CommonJS. Just put this file somewhere on your require.paths
  419. // and you will be able to `var html_beautify = require("beautify").html_beautify`.
  420. exports.css_beautify = css_beautify;
  421. } else if (typeof window !== "undefined") {
  422. // If we're running a web page and don't have either of the above, add our one global
  423. window.css_beautify = css_beautify;
  424. } else if (typeof global !== "undefined") {
  425. // If we don't even have window, try global.
  426. global.css_beautify = css_beautify;
  427. }
  428. }());