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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
|
local objects = {
enabled = true,
min_length = 7,
max_length = 64,
url = "./?id=%s",
}
local rules = {
{ pattern = "#(%d+)", url = "https://bugs.example.com/?bug=%s" },
}
local chunks = {}
local function url_encode(s)
return (string.gsub(s, "[^%w._~-]", function(c)
return string.format("%%%02X", string.byte(c))
end))
end
local function make_link(url_template, capture, display)
local encoded = url_encode(capture)
local href = string.gsub(url_template, "%%s", function() return encoded end)
return '<a href="' .. href .. '">' .. display .. '</a>'
end
local function collect(text)
local cands = {}
for pri, rule in ipairs(rules) do
pcall(function()
local init = 1
while init <= #text do
local s, e, cap = string.find(text, rule.pattern, init)
if not s then break end
if cap == nil then
cap = string.sub(text, s, e)
end
cands[#cands + 1] = {
s = s, e = e, pri = pri,
link = make_link(rule.url, cap, string.sub(text, s, e)),
}
init = (e >= s) and e + 1 or s + 1
end
end)
end
if objects.enabled then
local objpri = #rules + 1
local init = 1
while init <= #text do
local s, e, run = string.find(text, "%f[%w](%x+)%f[%W]", init)
if not s then break end
if #run >= objects.min_length and #run <= objects.max_length then
cands[#cands + 1] = {
s = s, e = e, pri = objpri,
link = make_link(objects.url, run, run),
}
end
init = e + 1
end
end
return cands
end
function filter_open(...)
chunks = {}
end
function filter_write(str)
chunks[#chunks + 1] = str
end
function filter_close()
local text = table.concat(chunks)
local cands = collect(text)
table.sort(cands, function(a, b)
if a.s ~= b.s then
return a.s < b.s
end
return a.pri < b.pri
end)
local out = {}
local i = 1
for _, c in ipairs(cands) do
if c.s >= i then
out[#out + 1] = string.sub(text, i, c.s - 1)
out[#out + 1] = c.link
i = c.e + 1
end
end
out[#out + 1] = string.sub(text, i)
html(table.concat(out))
return 0
end
|