-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconvert_control_char.rb
121 lines (108 loc) · 2.76 KB
/
convert_control_char.rb
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
module Irclog
module Tag
BOLD = "<span class=\"bold\">"
U = "<span class=\"u\">"
COLOR = [
"white", "black", "darkblue", "darkgreen", "red", "darkred", "darkpurple", "orange",
"yellow", "green", "darkcyan", "cyan", "blue", "purple", "darkgray", "gray"
]
end
class ConvertControlChar
def initialize(text)
@text = text
@tags = Tags.new
end
def convert
ans = ""
i = 0
while i = @text.index(/\cB|\c_|\cO|\cC|\cV|\cR/)
ans << @text[0...i]
case @text[i]
when "\cC"
if @text[(i+1)..(i+5)] =~ /^(\d{1,2}),(\d{1,2})/
fg_index = $1.to_i % Tag::COLOR.length
bg_index = $2.to_i % Tag::COLOR.length
ans << @tags.color(fg_index, bg_index)
@text = @text[(i+2+$1.length+$2.length)..-1]
next
elsif @text[(i+1)..(i+2)] =~ /^(\d{1,2})/
fg_index = $1.to_i % Tag::COLOR.length
ans << @tags.color(fg_index)
@text = @text[(i+1+$1.length)..-1]
next
else
ans << @tags.reset_color
end
when "\cV", "\cR"
ans << @tags.reverse_color
when "\cB"
ans << @tags.toggle_bold
when "\c_"
ans << @tags.toggle_u
when "\cO"
ans << @tags.clear
end
@text = @text[(i+1)..-1]
end
ans << @text
return ans
end
end
class Tags
def initialize
@tags = []
@fg_index = 1
@bg_index = 0
end
def toggle_bold
if @tags.include?(Tag::BOLD)
return untag(Tag::BOLD)
else
return append(Tag::BOLD)
end
end
def toggle_u
if @tags.include?(Tag::U)
return untag(Tag::U)
else
return append(Tag::U)
end
end
def clear
tag_num = @tags.length
@tags = []
@fg_index = 1
@bg_index = 0
return "</span>" * tag_num
end
def color(fg_index, bg_index = nil)
@fg_index = fg_index
@bg_index = bg_index if bg_index
if @tags.include?(Tag::U)
ans = toggle_u
ans << append("<span class=\"#{Tag::COLOR[@fg_index]} bg#{Tag::COLOR[@bg_index]}\">")
ans << toggle_u
return ans
else
return append("<span class=\"#{Tag::COLOR[@fg_index]} bg#{Tag::COLOR[@bg_index]}\">")
end
end
def reset_color
return color(1, 0)
end
def reverse_color
return color(@bg_index, @fg_index)
end
private
def append(tag)
@tags << (tag)
return tag
end
def untag(tag)
tag_index = @tags.index(tag)
ans = "</span>" * (@tags.length - tag_index) + @tags[(tag_index + 1)..-1].join
@tags.delete_at(tag_index)
return ans
end
end
end