Skip to content

Commit e80c5ce

Browse files
committed
ext: string
1 parent e646d16 commit e80c5ce

File tree

1 file changed

+53
-9
lines changed

1 file changed

+53
-9
lines changed

src/ext/string.cr

Lines changed: 53 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,16 +18,60 @@
1818
# -----------------------------------------------------------------------
1919

2020
class String
21-
def uncolorize: String
22-
end
21+
def uncolorize : String
22+
self
23+
.gsub(/[ \t]+$/m, "")
24+
.gsub(/\e\[(\d+;?)*m/, "")
25+
.rstrip
26+
end
2327

24-
def last? : Char?
25-
self[-1]?
26-
end
28+
def last? : Char?
29+
self[-1]?
30+
end
2731

28-
def indent(spaces: Int32 = 2) : String
29-
lines.join('\n') do |line|
30-
line.empty? ? line : ("" * spaces) + line
31-
end
32+
def indent(spaces : Int32 = 2) : String
33+
lines.join('\n') do |line|
34+
line.empty? ? line : (" " * spaces) + line
3235
end
36+
end
37+
38+
def remove_trailing_whitespace : String
39+
lines.join('\n', &.rstrip)
40+
end
41+
42+
def shrink_to_minimum_leading_whitespace : String
43+
indent_size =
44+
Int32::MAX
45+
46+
lines =
47+
self
48+
.lines
49+
.map do |line|
50+
reader = Char::Reader.new(line)
51+
size = 0
52+
53+
loop do
54+
case reader.current_char
55+
when '\t'
56+
size += 2
57+
when ' '
58+
size += 1
59+
else
60+
break
61+
end
62+
63+
reader.next_char
64+
end
65+
66+
if size < indent_size && !line.blank?
67+
indent_size = size
68+
end
69+
70+
(" " * size) + line[reader.pos..]?.to_s
71+
end
72+
73+
lines
74+
.map(&.[indent_size..]?.to_s)
75+
.join("\n")
76+
end
3377
end

0 commit comments

Comments
 (0)