+
+-- Keywords that should be bold
+local keywords = {
+ ['case'] = {},
+ ['of'] = {},
+ ['let'] = {},
+ ['in'] = {},
+}
+
+-- See if str starts with a symbol, and return the remaining string and that
+-- symbol. If no symbol from the table is matched, just returns the first
+-- character. We can do a lookup directly, since symbols can be different in
+-- length, so we just loop over all symbols, trying them in turn.
+local function take_symbol(str)
+ for symbol,props in pairs(symbols) do
+ -- Try to remove symbol from the start of str
+ symbol, newstr = utf.match(str, "^(" .. symbol .. ")(.*)")
+ if symbol then
+ -- Return this tokens repr, or just the token if it has no
+ -- repr.
+ res = props.repr or symbol
+ -- Enclose the token in {\style .. }
+ if props.style then
+ res = "{\\" .. props.style .. " " .. res .. "}"
+ end
+ return res, newstr
+ end
+ end
+ -- No symbol found, just return the first character
+ return utf.match(str, "^(.)(.*)")
+end
+
+-- Take a single word from str, if posible. Returns the rest of the string and
+-- the word taken.
+local function take_word(str)
+ -- A word must always start with a-z (in particular, λ is not a valid
+ -- start of a word).
+ res, newstr = utf.match(str, "^([a-zA-Z][%a%d_]+)(.*)")
+ return res, newstr or str
+end
+
+-- Tries to match each of the patterns and returns the captures of the first
+-- matching pattern (up to 5 captures are supported). Returns nil when nothing
+-- matches.
+local function match_mul(str, patterns)
+ for i, pat in ipairs(patterns) do
+ a, b, c, d, e = utf.match(str, pat)
+ if a then
+ return a, b, c, d, e
+ end
+ end
+ return nil
+end
+
+-- Find any subscripts in the given word and typeset them
+local function do_subscripts(word)
+ base, sub = match_mul(res, submatches)
+ if sub then
+ word = base .. "\\low{" .. sub .. "}"
+ -- After a word has been used as a base, allow subscripts
+ -- without _, even for non-numbers.
+ if not bases[base] then
+ -- Register that we've added this base
+ bases[base] = true
+ -- Add a pattern for this base
+ submatches[#submatches+1] = "^(" .. base .. ")([%a%d,]+)$"
+ end
+ end
+ return word
+end
+
+function vis.begin_of_display()
+ -- Initially allow subscripts using _ or just appending a number (later,
+ -- we will add extra patterns here.
+ submatches = {"^(.*)_([%a%d,]+)$", "^(.*[^%d])(%d+)$"}
+ -- This stores all the bases we've encountered so far (to prevent
+ -- duplicates). For each of them there will be a pattern in submatches
+ -- above.
+ bases = {}
+end
+
+-- Make things work for inline typeing (e.g., \type{}) as well.
+vis.begin_of_inline = vis.begin_of_display
+vis.end_of_inline = vis.end_of_display
+
+function vis.flush_line(str,nested)