24
24
// Find the longest leading margin common between the given lines.
25
25
func calculateMargin(lines []string) string {
28
for _, line := range lines {
29
indent := reLeadingWhitespace.FindString(line)
31
case len(indent) == len(line):
32
// The line is either empty or whitespace and will be ignored for
33
// the purposes of calculating the margin.
35
// This is the first line with an indent, so start from here.
38
case strings.HasPrefix(indent, margin):
39
// This line's indent is longer or equal to the margin. The
40
// current margin remains unalterered.
41
case strings.HasPrefix(margin, indent):
42
// This line's indent is compatible with the margin but shorter
43
// (strictly it could be equal, however that condition is handled
44
// earlier in this switch). The current indent becomes the margin.
47
// There is no common margin so stop scanning.
28
for _, line := range lines {
29
indent := reLeadingWhitespace.FindString(line)
31
case len(indent) == len(line):
32
// The line is either empty or whitespace and will be ignored for
33
// the purposes of calculating the margin.
35
// This is the first line with an indent, so start from here.
38
case strings.HasPrefix(indent, margin):
39
// This line's indent is longer or equal to the margin. The
40
// current margin remains unalterered.
41
case strings.HasPrefix(margin, indent):
42
// This line's indent is compatible with the margin but shorter
43
// (strictly it could be equal, however that condition is handled
44
// earlier in this switch). The current indent becomes the margin.
47
// There is no common margin so stop scanning.
54
54
// Remove a prefix from each line, if present.
55
55
func trimPrefix(lines []string, prefix string) {
57
for i, line := range lines {
58
if strings.HasPrefix(line, prefix) {
59
lines[i] = line[trim:]
57
for i, line := range lines {
58
if strings.HasPrefix(line, prefix) {
59
lines[i] = line[trim:]
64
64
func Dedent(text string) string {
65
lines := splitLines(text)
66
trimPrefix(lines, calculateMargin(lines))
67
return strings.Join(lines, "\n")
65
lines := splitLines(text)
66
trimPrefix(lines, calculateMargin(lines))
67
return strings.Join(lines, "\n")