remove-indentation.js 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. 'use strict';
  2. var trim = require('trim');
  3. var repeat = require('repeat-string');
  4. var getIndent = require('./get-indentation');
  5. module.exports = indentation;
  6. var C_SPACE = ' ';
  7. var C_NEWLINE = '\n';
  8. var C_TAB = '\t';
  9. /* Remove the minimum indent from every line in `value`.
  10. * Supports both tab, spaced, and mixed indentation (as
  11. * well as possible). */
  12. function indentation(value, maximum) {
  13. var values = value.split(C_NEWLINE);
  14. var position = values.length + 1;
  15. var minIndent = Infinity;
  16. var matrix = [];
  17. var index;
  18. var indentation;
  19. var stops;
  20. var padding;
  21. values.unshift(repeat(C_SPACE, maximum) + '!');
  22. while (position--) {
  23. indentation = getIndent(values[position]);
  24. matrix[position] = indentation.stops;
  25. if (trim(values[position]).length === 0) {
  26. continue;
  27. }
  28. if (indentation.indent) {
  29. if (indentation.indent > 0 && indentation.indent < minIndent) {
  30. minIndent = indentation.indent;
  31. }
  32. } else {
  33. minIndent = Infinity;
  34. break;
  35. }
  36. }
  37. if (minIndent !== Infinity) {
  38. position = values.length;
  39. while (position--) {
  40. stops = matrix[position];
  41. index = minIndent;
  42. while (index && !(index in stops)) {
  43. index--;
  44. }
  45. if (
  46. trim(values[position]).length !== 0 &&
  47. minIndent &&
  48. index !== minIndent
  49. ) {
  50. padding = C_TAB;
  51. } else {
  52. padding = '';
  53. }
  54. values[position] = padding + values[position].slice(
  55. index in stops ? stops[index] + 1 : 0
  56. );
  57. }
  58. }
  59. values.shift();
  60. return values.join(C_NEWLINE);
  61. }