space-between-declarations.js 3.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. var gonzales = require('gonzales-pe');
  2. module.exports = (function() {
  3. function getDeclarationEnd(node, i) {
  4. for (;i < node.length; i++) {
  5. if (!node.get(i + 1) || typeof node.get(i + 1) === 'string') {
  6. return 0;
  7. } else if (node.get(i + 1).is('space')) {
  8. if (node.get(i + 1).content.indexOf('\n') > -1) {
  9. if (node.get(i + 2) && node.get(i + 2).is('declaration')) {
  10. return i;
  11. } else {
  12. return 0;
  13. }
  14. } else if (node.get(i + 2) && node.get(i + 2).is('multilineComment')) {
  15. if (node.get(i + 3) && node.get(i + 3).is('declaration')) {
  16. return i + 2;
  17. } else if (node.get(i + 3) && node.get(i + 3).is('space')) {
  18. if (node.get(i + 4) && node.get(i + 4).is('declaration')) {
  19. return i + 2;
  20. } else {
  21. return 0;
  22. }
  23. } else {
  24. return 0;
  25. }
  26. } else if (node.get(i + 2) && node.get(i + 2).is('declaration')) {
  27. return i;
  28. }
  29. } else if (node.get(i + 1).is('declaration')) {
  30. return i;
  31. } else if (node.get(i + 1).is('multilineComment')) {
  32. if (node.get(i + 2) && node.get(i + 2).is('declaration')) {
  33. return i + 1;
  34. } else if (node.get(i + 2) && node.get(i + 2).is('space')) {
  35. if (node.get(i + 3) && node.get(i + 3).is('declaration')) {
  36. return i + 1;
  37. }
  38. } else {
  39. return 0;
  40. }
  41. } else {
  42. return 0;
  43. }
  44. }
  45. }
  46. return {
  47. name: 'space-between-declarations',
  48. runBefore: 'block-indent',
  49. syntax: ['css', 'less', 'scss'],
  50. accepts: {
  51. number: true,
  52. string: /^[ \t\n]*$/
  53. },
  54. /**
  55. * Processes tree node.
  56. *
  57. * @param {node} node
  58. */
  59. process: function(node) {
  60. var value = this.getValue('space-between-declarations');
  61. // TODO: Limit nodes to blocks, stylesheet, etc.
  62. // XXX: Hack for braces
  63. if (node.is('braces') || node.is('id')) return;
  64. for (var i = 0, l = node.length; i < l; i++) {
  65. if (!node.get(i) || !node.get(i).is('declarationDelimiter')) continue;
  66. // Grom user's point of view "declaration" includes semicolons
  67. // and comments placed on the same line.
  68. // So group those things together:
  69. var declarationEnd = getDeclarationEnd(node, i);
  70. if (!declarationEnd) {
  71. continue;
  72. } else {
  73. i = declarationEnd;
  74. }
  75. var nextNode = node.get(i + 1);
  76. if (nextNode.is('space')) {
  77. nextNode.content = value;
  78. } else {
  79. i++;
  80. l++;
  81. var space = gonzales.createNode({ type: 'space', content: value });
  82. node.insert(i, space);
  83. }
  84. }
  85. }
  86. };
  87. })();