remove-indentation.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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 lineFeed = '\n'
  7. var space = ' '
  8. var exclamationMark = '!'
  9. // Remove the minimum indent from every line in `value`. Supports both tab,
  10. // spaced, and mixed indentation (as well as possible).
  11. function indentation(value, maximum) {
  12. var values = value.split(lineFeed)
  13. var position = values.length + 1
  14. var minIndent = Infinity
  15. var matrix = []
  16. var index
  17. var indentation
  18. var stops
  19. values.unshift(repeat(space, maximum) + exclamationMark)
  20. while (position--) {
  21. indentation = getIndent(values[position])
  22. matrix[position] = indentation.stops
  23. if (trim(values[position]).length === 0) {
  24. continue
  25. }
  26. if (indentation.indent) {
  27. if (indentation.indent > 0 && indentation.indent < minIndent) {
  28. minIndent = indentation.indent
  29. }
  30. } else {
  31. minIndent = Infinity
  32. break
  33. }
  34. }
  35. if (minIndent !== Infinity) {
  36. position = values.length
  37. while (position--) {
  38. stops = matrix[position]
  39. index = minIndent
  40. while (index && !(index in stops)) {
  41. index--
  42. }
  43. values[position] = values[position].slice(stops[index] + 1)
  44. }
  45. }
  46. values.shift()
  47. return values.join(lineFeed)
  48. }