-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext.lua
More file actions
100 lines (86 loc) · 2.59 KB
/
text.lua
File metadata and controls
100 lines (86 loc) · 2.59 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
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
local JSON = require("mw/external/JSON")
local p = {}
local priv = {}
function p.jsonDecode(raw_json_text)
local lua_value = JSON:decode(raw_json_text)
return lua_value
end
function p.jsonEncode(lua_value)
local raw_json_text = JSON:encode(lua_value)
return raw_json_text
end
function p.jsonPrettyEncode(lua_value)
local raw_json_text = JSON:encode_pretty(lua_value)
return raw_json_text
end
-- Note! This is not aware of unicode
-- https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#mw.text.split
function p.split(text, pattern, plain)
local ret = {}
local s, l = 1, string.len( text )
while s do
local e, n = string.find( text, pattern, s, plain )
if not e then
ret[#ret+1] = string.sub ( text, s )
s = nil
elseif n < e then
-- Empty separator!
ret[#ret+1] = string.sub ( text, s, e )
if e < l then
s = e + 1
else
s = nil
end
else
ret[#ret+1] = e > s and string.sub( text, s, e - 1 ) or ''
s = n + 1
end
end
return ret
end
--
-- .nowiki
-- https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#mw.text.nowiki
--
-- Wiki characters to escape
priv.entities = {
['"'] = """,
["&"] = "&",
["'"] = "'",
["<"] = "<",
["="] = "=",
[">"] = ">",
["["] = "[",
["]"] = "]",
["{"] = "{",
["|"] = "|",
["}"] = "}",
}
local function escapeChar(c)
return priv.entities[c] or c
end
function p.nowiki(str)
if type(str) ~= "string" then return "" end
-- Main wiki characters
str = str:gsub('[\"&\'<=>%[%]{|}]', escapeChar)
-- `://` will have the colon escaped
str = str:gsub(":(//)", ":%1")
-- `__` will have one underscore escaped
str = str:gsub("(__)", "__")
-- Escape first ---- at start of string or after newline
str = str:gsub("(^%-%-%-%-)", "-%-%-%-")
str = str:gsub("(\n)(%-%-%-%-)", function(nl, dashes)
return nl .. "-" .. dashes:sub(2)
end)
-- Blank lines will have one of the associated newline or carriage return characters escaped
str = str:gsub("(\r?\n)(\r?\n)", function(a, b)
return a .. (b == "\r\n" and " " or (b == "\n" and " " or " "))
end)
-- Lists: The following characters at the start of the string or immediately after a newline: `#`, `*`, `:`, `;`, space, tab (`\t`)
str = ("\n"..str):gsub("(\n)([ \t#%*;:])", function(nl, c)
return nl .. "&#" .. string.byte(c) .. ";"
end)
str = str:gsub("^\n", "") -- remove extra \n added above
return str
end
return p