diff options
author | Norbert Preining <norbert@preining.info> | 2021-09-20 03:02:23 +0000 |
---|---|---|
committer | Norbert Preining <norbert@preining.info> | 2021-09-20 03:02:23 +0000 |
commit | c9fcf97bc045a9d020980c33b6c7c1ee5aedef99 (patch) | |
tree | bf74a43623e081cad4b72a752730aeff86b7c5cf /macros/luatex/generic/penlight/pl/url.lua | |
parent | 996c9b239bde82dc3ef3e5b69cd525e87fdb61a8 (diff) |
CTAN sync 202109200302
Diffstat (limited to 'macros/luatex/generic/penlight/pl/url.lua')
-rw-r--r-- | macros/luatex/generic/penlight/pl/url.lua | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/macros/luatex/generic/penlight/pl/url.lua b/macros/luatex/generic/penlight/pl/url.lua new file mode 100644 index 0000000000..8c7cfeb7aa --- /dev/null +++ b/macros/luatex/generic/penlight/pl/url.lua @@ -0,0 +1,51 @@ +--- Python-style URL quoting library. +-- +-- @module pl.url + +local url = {} + +local function quote_char(c) + return string.format("%%%02X", string.byte(c)) +end + +--- Quote the url, replacing special characters using the '%xx' escape. +-- @string s the string +-- @bool quote_plus Also escape slashes and replace spaces by plus signs. +-- @return The quoted string, or if `s` wasn't a string, just plain unaltered `s`. +function url.quote(s, quote_plus) + if type(s) ~= "string" then + return s + end + + s = s:gsub("\n", "\r\n") + s = s:gsub("([^A-Za-z0-9 %-_%./])", quote_char) + if quote_plus then + s = s:gsub(" ", "+") + s = s:gsub("/", quote_char) + else + s = s:gsub(" ", "%%20") + end + + return s +end + +local function unquote_char(h) + return string.char(tonumber(h, 16)) +end + +--- Unquote the url, replacing '%xx' escapes and plus signs. +-- @string s the string +-- @return The unquoted string, or if `s` wasn't a string, just plain unaltered `s`. +function url.unquote(s) + if type(s) ~= "string" then + return s + end + + s = s:gsub("+", " ") + s = s:gsub("%%(%x%x)", unquote_char) + s = s:gsub("\r\n", "\n") + + return s +end + +return url |