-- RTF in and out, as runs of text in one format each: { text, family,
-- size (points), color (0xRRGGBB), bold, italic, underline, strike },
-- the shape c8.text's runs() gives and append() takes. Character
-- formatting only: paragraphs (alignment, indents, lists), tables and
-- pictures are read as their text, and not written.
local M = {}
-- Windows-1252's 0x80-0x9f; the rest of the upper half is Latin-1
local cp1252 = {
[0x80] = 0x20ac, [0x82] = 0x201a, [0x83] = 0x0192, [0x84] = 0x201e,
[0x85] = 0x2026, [0x86] = 0x2020, [0x87] = 0x2021, [0x88] = 0x02c6,
[0x89] = 0x2030, [0x8a] = 0x0160, [0x8b] = 0x2039, [0x8c] = 0x0152,
[0x8e] = 0x017d, [0x91] = 0x2018, [0x92] = 0x2019, [0x93] = 0x201c,
[0x94] = 0x201d, [0x95] = 0x2022, [0x96] = 0x2013, [0x97] = 0x2014,
[0x98] = 0x02dc, [0x99] = 0x2122, [0x9a] = 0x0161, [0x9b] = 0x203a,
[0x9c] = 0x0153, [0x9e] = 0x017e, [0x9f] = 0x0178,
}
local from_cp1252 = {}
for byte, code in pairs(cp1252) do
from_cp1252[code] = byte
end
-- Text in Windows-1252 (or Latin-1) as UTF-8, for plain files that
-- aren't UTF-8
function M.decode_1252(s)
return (s:gsub("[\128-\255]", function(ch)
local b = ch:byte()
return utf8.char(cp1252[b] or b)
end))
end
-- Groups whose text isn't the document's
local skip = {
stylesheet = true, info = true, pict = true, header = true,
headerl = true, headerr = true, headerf = true, footer = true,
footerl = true, footerr = true, footerf = true, footnote = true,
object = true, listtable = true, listoverridetable = true,
rsidtbl = true, revtbl = true, xmlnstbl = true, themedata = true,
colorschememapping = true, latentstyles = true, datastore = true,
pgdsctbl = true, fldinst = true, bkmkstart = true, bkmkend = true,
nonshppict = true, shppict = true, generator = true, mmathPr = true,
filetbl = true, private = true,
}
-- Control words that stand for a character
local symbols = {
par = "\n", line = "\n", sect = "\n", page = "\n", row = "\n",
tab = "\t", cell = "\t", emdash = "\u{2014}", endash = "\u{2013}",
bullet = "\u{2022}", lquote = "\u{2018}", rquote = "\u{2019}",
ldblquote = "\u{201c}", rdblquote = "\u{201d}", emspace = "\u{2003}",
enspace = "\u{2002}", qmspace = "\u{2005}",
}
local underlines = {
ul = true, uld = true, uldash = true, uldashd = true, uldashdd = true,
uldb = true, ulhwave = true, ulldash = true, ulth = true, ulthd = true,
ulthdash = true, ulthdashd = true, ulthdashdd = true, ulthldash = true,
ululdbwave = true, ulw = true, ulwave = true,
}
local function copy(t)
local c = {}
for k, v in pairs(t) do
c[k] = v
end
return c
end
-- Reads an RTF document. Returns the runs, or nil and why
function M.read(data)
if not data:match("^%s*{\\rtf") then
return nil, "This isn't an RTF document."
end
local fonts, colors = {}, {}
local default_font = 0
local runs = {}
local out = {} -- the current run's pieces
local cur -- the format they're in
-- The state a group starts with is a copy of its parent's
local st = { b = false, i = false, ul = false, strike = false, fs = 24,
f = nil, cf = 0, uc = 1, dest = nil }
local stack = {}
local pending_skip = 0 -- characters left to skip after a \u
local high -- a high surrogate waiting for its low one
-- Font table entries are read a piece at a time
local font_no, font_name
local function same(a, b)
return a.family == b.family and a.size == b.size and
a.color == b.color and a.bold == b.bold and a.italic == b.italic
and a.underline == b.underline and a.strike == b.strike
end
local function flush()
if cur and #out > 0 then
local text = table.concat(out)
local last = runs[#runs]
if last and same(last, cur) then
last.text = last.text .. text
else
local run = copy(cur)
run.text = text
runs[#runs + 1] = run
end
end
out = {}
end
local function emit(s)
if st.dest == "fonttbl" then
font_name = (font_name or "") .. s
return
elseif st.dest == "colortbl" then
return
elseif st.dest then
return
end
local f = st.f or default_font
local fmt = {
family = fonts[f], size = st.fs / 2,
color = colors[st.cf], bold = st.b or nil,
italic = st.i or nil, underline = st.ul or nil,
strike = st.strike or nil,
}
if not cur or not same(cur, fmt) then
flush()
cur = fmt
end
out[#out + 1] = s
end
local function emit_code(code)
if code >= 0xd800 and code <= 0xdbff then
high = code
return
end
if code >= 0xdc00 and code <= 0xdfff then
if not high then
return
end
code = 0x10000 + (high - 0xd800) * 0x400 + (code - 0xdc00)
end
high = nil
emit(utf8.char(code))
end
-- A byte as it comes, or from \'hh: in the document's code page
local function emit_byte(b)
if pending_skip > 0 then
pending_skip = pending_skip - 1
return
end
if b < 0x80 then
emit(string.char(b))
else
emit_code(cp1252[b] or b)
end
end
-- The colour table: \red \green \blue, each entry ended by ';'
local red, green, blue
local function word(name, param)
local on = param == nil or param ~= 0
if name == "u" then
local code = param or 0
if code < 0 then
code = code + 65536
end
if not st.dest then
emit_code(code)
end
pending_skip = st.uc
return
end
pending_skip = 0
if name == "uc" then
st.uc = param or 1
elseif name == "fonttbl" or name == "colortbl" then
st.dest = name
elseif skip[name] then
st.dest = "skip"
elseif st.dest == "fonttbl" and name == "f" then
font_no = param or 0
font_name = nil
elseif st.dest == "colortbl" then
if name == "red" then
red = param
elseif name == "green" then
green = param
elseif name == "blue" then
blue = param
end
elseif name == "deff" then
default_font = param or 0
elseif name == "b" then
st.b = on
elseif name == "i" then
st.i = on
elseif underlines[name] then
st.ul = on
elseif name == "ulnone" then
st.ul = false
elseif name == "strike" or name == "striked" then
st.strike = on
elseif name == "fs" then
st.fs = param or 24
elseif name == "f" then
st.f = param
elseif name == "cf" then
st.cf = param or 0
elseif name == "plain" then
st.b, st.i, st.ul, st.strike = false, false, false, false
st.fs, st.f, st.cf = 24, nil, 0
elseif symbols[name] then
emit(symbols[name])
end
end
local color_index = 0
local i, n = 1, #data
local star = false -- \* seen: the group is skipped unless known
while i <= n do
local c = data:byte(i)
if c == 0x7b then -- {
stack[#stack + 1] = copy(st)
i = i + 1
star = false
elseif c == 0x7d then -- }
if st.dest == "fonttbl" and font_name and font_no then
fonts[font_no] = font_name:gsub(";%s*$", "")
font_name = nil
end
st = table.remove(stack) or st
pending_skip = 0
i = i + 1
elseif c == 0x5c then -- \
local nxt = data:sub(i + 1, i + 1)
if nxt:match("%a") then
local name, num, sp, e = data:match(
"^(%a+)(%-?%d*)( ?)()", i + 1)
local param = num ~= "" and tonumber(num) or nil
i = e
if star and not (name == "fonttbl" or name == "colortbl") then
-- An optional destination: known ones are in skip,
-- the rest are skipped too
st.dest = "skip"
else
word(name, param)
end
star = false
elseif nxt == "'" then
local hex = data:sub(i + 2, i + 3)
i = i + 4
emit_byte(tonumber(hex, 16) or 0x3f)
elseif nxt == "*" then
star = true
i = i + 2
elseif nxt == "~" then
emit("\u{a0}")
i = i + 2
elseif nxt == "_" then
emit("\u{2011}")
i = i + 2
elseif nxt == "-" or nxt == ":" or nxt == "|" then
i = i + 2
elseif nxt == "\n" or nxt == "\r" then
emit("\n")
i = i + 2
else
-- \\ \{ \} and anything else stands for itself
if pending_skip > 0 then
pending_skip = pending_skip - 1
else
emit(nxt)
end
i = i + 2
end
elseif c == 0x0d or c == 0x0a then
i = i + 1
else
-- Plain text up to the next special character
local e = data:find("[{}\\\r\n]", i) or n + 1
if st.dest == "colortbl" then
for _ in data:sub(i, e - 1):gmatch(";") do
if red or green or blue then
colors[color_index] = (red or 0) * 0x10000 +
(green or 0) * 0x100 + (blue or 0)
end
color_index = color_index + 1
red, green, blue = nil, nil, nil
end
elseif pending_skip > 0 or data:sub(i, e - 1):find("[\128-\255]") then
for k = i, e - 1 do
emit_byte(data:byte(k))
end
else
emit(data:sub(i, e - 1))
end
i = e
end
end
flush()
-- A document ends its last paragraph with \par: not a line of its own
local last = runs[#runs]
if last and last.text:sub(-1) == "\n" then
last.text = last.text:sub(1, -2)
if last.text == "" then
runs[#runs] = nil
end
end
return runs
end
local function escape(text)
local out = {}
for _, code in utf8.codes(text) do
if code == 0x5c then
out[#out + 1] = "\\\\"
elseif code == 0x7b then
out[#out + 1] = "\\{"
elseif code == 0x7d then
out[#out + 1] = "\\}"
elseif code == 0x0a then
out[#out + 1] = "\\par\n"
elseif code == 0x09 then
out[#out + 1] = "\\tab "
elseif code >= 0x20 and code < 0x80 then
out[#out + 1] = string.char(code)
elseif code < 0x20 then
-- other controls are dropped
elseif code <= 0xff and code >= 0xa0 or from_cp1252[code] then
-- In the code page, for readers that don't know \u
out[#out + 1] = string.format("\\'%02x",
from_cp1252[code] or code)
else
-- \u takes a signed 16-bit number, so pairs above the BMP;
-- each is followed by a ? for readers that don't know it
local units = { code }
if code > 0xffff then
local v = code - 0x10000
units = { 0xd800 + (v >> 10), 0xdc00 + (v & 0x3ff) }
end
for _, u in ipairs(units) do
out[#out + 1] = string.format("\\u%d?",
u >= 0x8000 and u - 0x10000 or u)
end
end
end
return table.concat(out)
end
-- Writes runs as an RTF document. family_default and size_default are
-- what a run without them is in
function M.write(runs, family_default, size_default)
local fonts, font_no = { family_default }, { [family_default] = 0 }
local colors, color_no = {}, {}
for _, r in ipairs(runs) do
local f = r.family or family_default
if not font_no[f] then
fonts[#fonts + 1] = f
font_no[f] = #fonts - 1
end
if r.color and not color_no[r.color] then
colors[#colors + 1] = r.color
color_no[r.color] = #colors
end
end
local out = { "{\\rtf1\\ansi\\ansicpg1252\\deff0{\\fonttbl" }
for i, f in ipairs(fonts) do
out[#out + 1] = string.format("{\\f%d\\fnil %s;}", i - 1,
escape(f))
end
out[#out + 1] = "}\n{\\colortbl ;"
for _, c in ipairs(colors) do
out[#out + 1] = string.format("\\red%d\\green%d\\blue%d;",
(c >> 16) & 0xff, (c >> 8) & 0xff, c & 0xff)
end
out[#out + 1] = "}\n\\uc1\\pard "
-- Only what changes from one run to the next is written
local now = { family = family_default, size = nil, color = nil,
bold = false, italic = false, underline = false, strike = false }
local function flag(name, word, on)
on = on and true or false
if now[name] ~= on then
out[#out + 1] = on and ("\\" .. word) or
(word == "ul" and "\\ulnone" or ("\\" .. word .. "0"))
now[name] = on
return true
end
end
local first = true
for _, r in ipairs(runs) do
local changed = false
local f = r.family or family_default
if first or now.family ~= f then
out[#out + 1] = "\\f" .. font_no[f]
now.family = f
changed = true
end
local size = r.size and r.size > 0 and r.size or size_default
if first or now.size ~= size then
out[#out + 1] = "\\fs" .. math.floor(size * 2 + 0.5)
now.size = size
changed = true
end
if first or now.color ~= r.color then
out[#out + 1] = "\\cf" .. (r.color and color_no[r.color] or 0)
now.color = r.color
changed = true
end
changed = flag("bold", "b", r.bold) or changed
changed = flag("italic", "i", r.italic) or changed
changed = flag("underline", "ul", r.underline) or changed
changed = flag("strike", "strike", r.strike) or changed
if changed then
out[#out + 1] = " "
end
out[#out + 1] = escape(r.text)
first = false
end
out[#out + 1] = "\\par\n}\n"
return table.concat(out)
end
return M