-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlines.go
More file actions
67 lines (62 loc) · 1.67 KB
/
lines.go
File metadata and controls
67 lines (62 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package strings
import (
"strings"
"unicode"
)
// TrimShiftLines will trim each line in s (separated by newlines) as follows:
//
// If the line is only whitespace, it will become an empty line.
//
// Whitespace at the end of each line will be removed.
//
// Each line that has content will be examined for whitespace in front of the content, and the smallest
// length of white space found in all the lines will then be removed from the front of every line, provided.
// that whitespace is found at the front of every line.
// Note that tabs will not be converted to spaces. The whitespace characters must match.
// The effect will be to shift all the lines to the left so that the line closest to the left
// will now be flush with the left, and all other lines will be shifted left the same amount.
func TrimShiftLines(s string) string {
lines := strings.Split(s, "\n")
var prefix string
var noMatch bool
// Pass one, making obvious fixes
for i, line := range lines {
if IsWhitespace(line) {
lines[i] = ""
continue
}
line = TrimRightSpace(line)
lines[i] = line
// Find first non-whitespace rune
start := 0
var r rune
for start, r = range line {
if !unicode.IsSpace(r) {
break
}
}
if !noMatch {
if prefix == "" {
prefix = line[:start]
} else if len(prefix) <= start {
if prefix != line[:len(prefix)] {
noMatch = true
}
} else {
if prefix[:start] != line[:start] {
noMatch = true
} else {
// new prefix
prefix = line[:start]
}
}
}
}
if !noMatch {
// Strip prefix from all lines
for i, line := range lines {
lines[i] = strings.TrimPrefix(line, prefix)
}
}
return strings.Join(lines, "\n")
}