summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorPhilipp Gesang <phg@phi-gamma.net>2018-06-23 15:00:31 +0200
committerPhilipp Gesang <phg@phi-gamma.net>2018-06-26 13:57:26 +0200
commit918ea8eabd6a8ace037753d0cbe425a9143b52c6 (patch)
tree39c1634c530265cc9cf9f86d2725d4820f038b7e
parenta1439ba548dfdef1d8a8f1b27e6912d513eb5004 (diff)
downloadcaldr-918ea8eabd6a8ace037753d0cbe425a9143b52c6.tar.gz
cal: implement rfc2445 folding
-rwxr-xr-xcal.lua52
1 files changed, 44 insertions, 8 deletions
diff --git a/cal.lua b/cal.lua
index 9382524..1c6a453 100755
--- a/cal.lua
+++ b/cal.lua
@@ -8,8 +8,12 @@
local io = require "io"
local ioopen = io.open
+local math = require "math"
+local mathmin = math.min
+
local string = require "string"
local stringformat = string.format
+local stringsub = string.sub
local table = require "table"
local tableconcat = table.concat
@@ -37,7 +41,9 @@ local noiseln = mk_out ("stderr", 1, true)
local debugln = mk_out ("stderr", 2, true)
local fmt_calendar do
- local crlf = "\r\n"
+ local fold_rfc2445 = 75 --- B
+ local fold_wsp = " " --- could be tab as well
+ local crlf = "\r\n"
local fmt_line = function (ln)
local params = ""
@@ -62,15 +68,45 @@ local fmt_calendar do
return stringformat ("%s%s:%s", ln.name, params, ln.value)
end
- fmt_calendar = function (cal, newline, i, acc)
- if i == nil then return fmt_calendar (cal, newline, 1, { }) end
- if i > #cal then return tableconcat (acc, newline or crlf) end
+ local fold_line = function (line, len, newline)
+ local acc = { }
+ local pos = 1
+
+ while pos < #line do
+ local wsp = ""
+ local pos1
+ if pos == 1 then
+ pos1 = mathmin (#line, pos + len)
+ else
+ pos1 = mathmin (#line, pos + len - 1) --- account for leading whitespace
+ wsp = fold_wsp
+ end
+ acc [#acc + 1] = wsp .. stringsub (line, pos, pos1)
+ pos = pos1
+ end
+
+ return tableconcat (acc, newline)
+ end
+
+ fmt_calendar = function (cal, fold, newline, i, acc)
+ if i == nil then
+ return fmt_calendar (cal,
+ fold or fold_rfc2445,
+ newline or crlf,
+ 1, { })
+ end
+ if i > #cal then return tableconcat (acc, newline) end
- local cur = cal [i]
+ local cur = cal [i]
+ local line = fmt_line (cur)
+
+ if #line > fold then
+ line = fold_line (line, fold, newline)
+ end
- acc [#acc + 1] = fmt_line (cur)
+ acc [#acc + 1] = line
- return fmt_calendar (cal, newline, i + 1, acc)
+ return fmt_calendar (cal, fold, newline, i + 1, acc)
end
end
@@ -276,7 +312,7 @@ local main = function (argv)
local raw = loaddata (argv [1])
local cal = parse_calendar (raw)
- if cal ~= nil then println (fmt_calendar (cal, "\n")) end
+ if cal ~= nil then println (fmt_calendar (cal, nil, "\n")) end
return 0
end