-
-
Notifications
You must be signed in to change notification settings - Fork 155
/
Copy pathstring.cr
64 lines (54 loc) · 1.36 KB
/
string.cr
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
class String
def uncolorize : String
self
.gsub(/[ \t]+$/m, "")
.gsub(/\e\[(\d+;?)*m/, "")
.rstrip
end
def last? : Char?
self[-1]?
end
def indent(spaces : Int32 = 2) : String
lines.join('\n') do |line|
line.empty? ? line : (" " * spaces) + line
end
end
def remove_trailing_whitespace : String
lines.join('\n', &.rstrip)
end
def shrink_to_minimum_leading_whitespace : String
# We start from the maximum number for indent size
indent_size =
Int32::MAX
# Iterate over all the lines and:
# - replace tabs with 2 spaces
# - update the indent size if it's smaller than the previous
lines =
self
.lines
.map do |line|
reader = Char::Reader.new(line)
size = 0
loop do
case reader.current_char
when '\t'
size += 2
when ' '
size += 1
else
break
end
reader.next_char
end
# For the indent size we ignore blank lines
if size < indent_size && !line.blank?
indent_size = size
end
(" " * size) + line[reader.pos..]?.to_s
end
# Remove the least number of indentation and recreate the string.
lines
.map(&.[indent_size..]?.to_s)
.join("\n")
end
end