| 7 | ) |
| 8 | |
| 9 | func Dedent(text string) string { |
| 10 | lines := strings.Split(text, "\n") |
| 11 | // Remove blank lines in the beginning and end |
| 12 | // and convert all tabs in the beginning of line to spaces |
| 13 | startLine := -1 |
| 14 | lastLine := 0 |
| 15 | for i, line := range lines { |
| 16 | firstNonWhite := strings.IndexFunc(line, func(r rune) bool { |
| 17 | return !stringutil.IsWhiteSpaceLike(r) |
| 18 | }) |
| 19 | if firstNonWhite > 0 { |
| 20 | line = strings.ReplaceAll(line[0:firstNonWhite], "\t", " ") + line[firstNonWhite:] |
| 21 | lines[i] = line |
| 22 | } |
| 23 | line = strings.TrimSpace(line) |
| 24 | if line != "" { |
| 25 | if startLine == -1 { |
| 26 | startLine = i |
| 27 | } |
| 28 | lastLine = i |
| 29 | } |
| 30 | } |
| 31 | lines = lines[startLine : lastLine+1] |
| 32 | mappedLines := make([]string, len(lines)) |
| 33 | for i, line := range lines { |
| 34 | if trimmed := strings.TrimSpace(line); trimmed == "" { |
| 35 | mappedLines[i] = "" |
| 36 | } else { |
| 37 | mappedLines[i] = line |
| 38 | } |
| 39 | } |
| 40 | indentation := stringutil.GuessIndentation(mappedLines) |
| 41 | if indentation > 0 { |
| 42 | for i := range lines { |
| 43 | if len(lines[i]) > indentation { |
| 44 | lines[i] = lines[i][indentation:] |
| 45 | } else { |
| 46 | lines[i] = "" |
| 47 | } |
| 48 | } |
| 49 | } |
| 50 | return strings.Join(lines, "\n") |
| 51 | } |