1 -- filename : type-lam.lua
2 -- comment : Pretty printing of (extended) lambda calculus
3 -- author : Matthijs Kooijman, Universiteit Twente, NL
4 -- copyright: Matthijs Kooijman
7 local utf = unicode.utf8
9 local vis = buffers.newvisualizer("lam")
18 -- Symbols that should have a different representation
20 -- Note, the space we replace with is a Unicode non-breaking space
23 ['_'] = {repr = '\\_'},
24 ['->'] = {repr = '→'},
25 ['=>'] = {repr = '⇒'},
26 -- The default * sits very high above the baseline, \ast (u+2217) looks
28 ['*'] = {repr = '\\ast'},
29 ['~'] = {repr = '\\HDLine[width=.20 * \\the\\textwidth]'},
30 ['|'] = {repr = '\\char' .. utf.byte('|')},
31 -- Use ▶ from our roman font, since Iwona doesn't have the glyph
32 ['▶'] = {repr = '{\\rm{}▶}'},
35 -- Keywords that should be bold
43 ['DEFAULT'] = {small = true},
49 -- Store the last line for each indent level
50 local indentlines = {}
52 function array_concat(a1, a2)
54 for k,v in ipairs(a2) do
61 -- See if str starts with a symbol, and return the remaining string and that
62 -- symbol. If no symbol from the table is matched, just returns the first
63 -- character. We can do a lookup directly, since symbols can be different in
64 -- length, so we just loop over all symbols, trying them in turn.
65 local function take_symbol(str)
66 for symbol,props in pairs(symbols) do
67 -- Try to remove symbol from the start of str
68 symbol, newstr = utf.match(str, "^(" .. symbol .. ")(.*)")
70 -- Return this tokens repr, or just the token if it has no
72 res = props.repr or symbol
73 -- Enclose the token in {\style .. }
75 res = "{\\" .. props.style .. " " .. res .. "}"
80 -- No symbol found, just return the first character
81 return utf.match(str, "^(.)(.*)")
84 -- Take a single word from str, if posible. Returns the rest of the string and
86 local function take_word(str)
87 -- A word must always start with a-z (in particular, λ is not a valid
89 res, newstr = utf.match(str, "^([a-zA-Z][%a%d%+%-%,_]+)(.*)")
90 return res, newstr or str
93 -- Tries to match each of the patterns and returns the captures of the first
94 -- matching pattern (up to 5 captures are supported). Returns nil when nothing
96 local function match_mul(str, patterns)
97 for i, pat in ipairs(patterns) do
98 a, b, c, d, e = utf.match(str, pat)
106 -- Find any subscripts in the given word and typeset them
107 local function do_subscripts(word)
108 base, sub = match_mul(res, submatches)
110 word = base .. "\\low{" .. sub .. "}"
111 -- After a word has been used as a base, allow subscripts
112 -- without _, even for non-numbers.
113 if not bases[base] then
114 -- Register that we've added this base
116 -- Add a patterns for this base. First, the base with a single
117 -- letter or number subscript.
118 submatches[#submatches+1] = "^(" .. base .. ")([%a%d])$"
119 -- Seconde, the base with a longer prefix that includes at least
120 -- one of +-, (to catch things like ri+1, but not return).
121 submatches[#submatches+1] = "^(" .. base .. ")([%a%d]*[%-%+,]+[%a%d%-%+,]*)$"
127 -- Do proper aligning for subsequent lines. For example, in
130 -- We replace the spaces in the second line with a skip with the same with as
131 -- "foo ", to align the | with the =.
132 -- For this, we keep a table "indentlines", which contains all previous lines
133 -- with smaller indent levels that are still "in scope" (e.g., have not yet
134 -- been followed by a line with a smaller indent level). For example:
140 -- After the last line, the table will contain:
141 -- { 0 = "line1", 2 = " line4", 4 = " line5"}
142 -- In other words, line3 is no longer in scope since it is "hidden" by
143 -- line4, and line is no longer in scope since it is replaced by line4.
144 local function do_indent(line)
145 newind, rest = utf.match(line, '^(%s*)(.*)')
147 -- Loop all the previous lines
148 for indent, unused in pairs(indentlines) do
149 if indent > #newind then
150 -- Remove any lines with a larger indent
151 indentlines[indent] = nil
152 elseif indent < #newind and indent > prev then
153 -- Find the last line (e.g, with the highest indent) with an
154 -- indent smaller than the new indent. This is the line from which
155 -- we need to copy the indent.
160 -- Always store this line, possibly overwriting a previous line with the
162 indentlines[#newind] = line
165 -- If there is a previous line with a smaller indent, make sure we
166 -- align with it. We do this by taking a prefix from that previous
167 -- line just as long as our indent. This gives us a bunch of
168 -- whitespace, with a few non-whitespace characters. We find out the
169 -- width of this prefix, and put whitespace just as wide as that
170 -- prefix before the current line, instead of the whitespace
171 -- characters that were there.
172 -- Doing this is slightly risky, since the prefix might contain
173 -- unfinished markup (e.g., \foo{bar without the closing }). We might
174 -- need to solve this later.
175 copyind = utf.sub(indentlines[prev], 1, #newind)
176 setwidth = "\\setwidthof{" .. copyind .. "}\\to\\pretlamalignwidth"
177 hskip = "\\hskip\\pretlamalignwidth"
178 return "{" .. setwidth .. hskip .. "}" .. rest
180 -- No previous line? Just return the unmodified line then
185 -- Mark the begin of a block of lambda formatted buffers or expressions. This
186 -- means that, until you call end_of_block again, the subscript bases are
187 -- shared. For example, if you have \lam{y1} some text \lam{yn} within a
188 -- single block, the yn will properly get subscripted. Be sure to call
189 -- end_of_block again!
191 -- Blocks can be partially nested, meaning that the block
192 -- won't be closed until end_of_block was called exactly as often as
193 -- begin_of_block. However, subscripts from the inner block can still
194 -- influence subscripts in the outer block.
195 function vis.begin_of_block()
196 vis.begin_of_display()
197 in_block = in_block + 1
200 -- Ends the current block
201 function vis.end_of_block()
202 in_block = in_block - 1
205 function vis.begin_of_display()
206 if in_block == 0 then
207 -- Initially allow subscripts using _ or just appending a number (later,
208 -- we will add extra patterns here.
209 submatches = {"^(%a*)_([%a%d,]+)$", "^(%a+)(%d[%d,]+)$"}
210 -- This stores all the bases we've encountered so far (to prevent
211 -- duplicates). For each of them there will be a pattern in submatches
219 -- Make things work for inline typeing (e.g., \type{}) as well.
220 vis.begin_of_inline = vis.begin_of_display
221 vis.end_of_inline = vis.end_of_display
223 function vis.flush_line(str,nested)
224 buffers.flush_result(vis.do_line(str, false), nested)
227 function vis.do_line(str, no_indent)
229 if not no_indent then
230 -- Allow ignore of the indentation stuff when we're calling ourselves
231 -- for a partial line.
237 local text, rest = utf.match(str, "^%-%-(.-)%-%-(.*)")
239 table.insert(result, '\\strikethrough{')
240 -- Recursively call ourselves to handle spaces gracefully.
241 result = array_concat(result, vis.do_line(text, true))
242 table.insert(result, '}')
243 -- Eat the processed characters
245 elseif utf.match(str, "^%-%-") then
246 table.insert(result, '{\\italic{--')
247 -- Recursively call ourselves to handle spaces gracefully.
248 result = array_concat(result, vis.do_line(utf.sub(str, 3), true))
249 table.insert(result, '}}')
250 -- Done with this line
253 -- See if the next token is a word
254 word, str = take_word(str)
256 if keywords[res] then
257 -- Make all keywords bold
258 word = "{\\bold " .. word .. "}"
259 if keywords[res].small then
260 word = "\\small" .. word -- Curlies were added above
263 -- Process any subscripts in the word
264 word = do_subscripts(word)
266 table.insert(result, word)
268 -- The next token is not a word, it must be a symbol
269 symbol, str = take_symbol(str)
270 table.insert(result, symbol)
278 -- vim: set sw=4 sts=4 expandtab ai: