strip-spaces.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. module.exports = (function() {
  2. /**
  3. * Trim trailing spaces on each line.
  4. * @private
  5. * @param {String} string Spaceful string
  6. * @returns {String}
  7. */
  8. function trim(string) {
  9. return string.replace(/[ \t]+\n/g, '\n');
  10. }
  11. return {
  12. name: 'strip-spaces',
  13. syntax: ['css', 'less', 'sass', 'scss'],
  14. accepts: { boolean: [true] },
  15. /**
  16. * Processes tree node.
  17. * @param {node} node
  18. */
  19. process: function(node) {
  20. if (node.is('space')) {
  21. node.content = trim(node.content);
  22. } else if (node.is('stylesheet')) {
  23. var lastChild = node.last();
  24. if (lastChild.is('space')) {
  25. lastChild.content = trim(lastChild.content)
  26. .replace(/[ \t]+$/, '')
  27. .replace(/[\n]+/g, '\n');
  28. }
  29. }
  30. },
  31. detectDefault: true,
  32. /**
  33. * Detects the value of an option at the tree node.
  34. * This option is treated as `true` by default, but any trailing space would invalidate it.
  35. *
  36. * @param {node} node
  37. */
  38. detect: function(node) {
  39. if (node.is('space') &&
  40. node.content.match(/[ \t]\n/)) {
  41. return false;
  42. } else if (node.is('stylesheet')) {
  43. var lastChild = node.last();
  44. if (lastChild.is('space') &&
  45. lastChild.content !== '\n' &&
  46. lastChild.content.match(/^[ \n\t]+$/)) {
  47. return false;
  48. }
  49. }
  50. }
  51. };
  52. })();