You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
896 B

4 years ago
  1. var splitRE = /\r?\n/g
  2. var emptyRE = /^\s*$/
  3. var needFixRE = /^(\r?\n)*[\t\s]/
  4. module.exports = function deindent (str) {
  5. if (!needFixRE.test(str)) {
  6. return str
  7. }
  8. var lines = str.split(splitRE)
  9. var min = Infinity
  10. var type, cur, c
  11. for (var i = 0; i < lines.length; i++) {
  12. var line = lines[i]
  13. if (!emptyRE.test(line)) {
  14. if (!type) {
  15. c = line.charAt(0)
  16. if (c === ' ' || c === '\t') {
  17. type = c
  18. cur = count(line, type)
  19. if (cur < min) {
  20. min = cur
  21. }
  22. } else {
  23. return str
  24. }
  25. } else {
  26. cur = count(line, type)
  27. if (cur < min) {
  28. min = cur
  29. }
  30. }
  31. }
  32. }
  33. return lines.map(function (line) {
  34. return line.slice(min)
  35. }).join('\n')
  36. }
  37. function count (line, type) {
  38. var i = 0
  39. while (line.charAt(i) === type) {
  40. i++
  41. }
  42. return i
  43. }