Require a word (including its subscript) to end in a number or letter.
[matthijs/master-project/report.git] / pret-lam.lua
1 -- filename : type-lam.lua
2 -- comment  : Pretty printing of (extended) lambda calculus
3 -- author   : Matthijs Kooijman, Universiteit Twente, NL
4 -- copyright: Matthijs Kooijman
5 -- license  : None
6
7 local utf = unicode.utf8
8
9 local vis = buffers.newvisualizer("lam")
10
11 local colors = {
12     "prettytwo",
13     "prettyone",
14     "prettythree",
15     "prettyfour"
16 }
17
18 -- Symbols that should have a different representation
19 local symbols = {
20     -- Note, the space we replace with is a Unicode non-breaking space
21     -- (U+00A0).
22     {symbol = ' ', repr = ' '},
23     {symbol = '_', repr = '\\_'},
24     {symbol = '->>', repr = '\\twoheadrightarrow'},
25     {symbol = '->', repr = '→'},
26     {symbol = '=>', repr = '⇒'},
27     -- The default * sits very high above the baseline, \ast (u+2217) looks
28     -- better.
29     {symbol = '*', repr = '\\ast'},
30     {symbol = '~', repr = '\\HDLine[width=.20 * \\the\\textwidth]'},
31     {symbol = '|', repr = '\\char' .. utf.byte('|')},
32     -- Use ▶ and ∧ from our roman font, since Iwona doesn't have the glyph
33     {symbol = '▶', repr = '{\\rm{}▶}'},
34     --{symbol = '∧', repr = '{$∧$}'},
35     {symbol = '∧', repr = '{\\rm{}∧}'},
36 }
37
38 -- Keywords that should be bold
39 local keywords = {
40     ['case'] = {},
41     ['of'] = {},
42     ['let'] = {},
43     ['letrec'] = {},
44     ['letnonrec'] = {},
45     ['in'] = {},
46     ['DEFAULT'] = {small = true},
47 }
48
49 local in_block = 0
50 local submatches = {}
51 local bases = {}
52 -- Store the last line for each indent level
53 local indentlines = {}
54
55 function array_concat(a1, a2)
56     local res = a1
57     for k,v in ipairs(a2) do
58         table.insert(res, v)
59     end
60     return res
61 end
62
63
64 -- See if str starts with a symbol, and return the remaining string and that
65 -- symbol. If no symbol from the table is matched, just returns the first
66 -- character.  We can do a lookup directly, since symbols can be different in
67 -- length, so we just loop over all symbols, trying them in turn.
68 local function take_symbol(str)
69     for i,props in ipairs(symbols) do
70         -- Try to remove symbol from the start of str 
71         symbol, newstr = utf.match(str, "^(" .. props.symbol .. ")(.*)")
72         if symbol then
73             -- Return this tokens repr, or just the token if it has no
74             -- repr.
75             res = props.repr or symbol
76             -- Enclose the token in {\style .. }
77             if props.style then
78                 res = "{\\" .. props.style ..  " " .. res ..  "}"
79             end
80             return res, newstr
81         end
82     end
83     -- No symbol found, just return the first character
84     return utf.match(str, "^(.)(.*)")
85 end
86
87 -- Take a single word from str, if posible. Returns the rest of the string and
88 -- the word taken.
89 local function take_word(str)
90         -- A word must always start with a-z (in particular, λ is not a valid
91         -- start of a word). A word must always end with a letter or a digit
92         res, newstr = utf.match(str, "^([a-zA-Z][%a%d%+%-%,_]*[%a%d]+)(.*)")
93         if not res then
94             -- The above does not catch single letter words
95             res, newstr = utf.match(str, "^([a-zA-Z])(.*)")
96         end
97         return res, newstr or str
98 end
99
100 -- Tries to match each of the patterns and returns the captures of the first
101 -- matching pattern (up to 5 captures are supported). Returns nil when nothing
102 -- matches.
103 local function match_mul(str, patterns)
104     for i, pat in ipairs(patterns) do
105         a, b, c, d, e = utf.match(str, pat)
106         if a then
107             return a, b, c, d, e
108         end
109     end
110     return nil
111 end
112
113 -- Find any subscripts in the given word and typeset them
114 local function do_subscripts(word)
115     base, sub = match_mul(res, submatches)
116     if sub then
117         word = base .. "\\low{" .. sub .. "}"
118         -- After a word has been used as a base, allow subscripts
119         -- without _, even for non-numbers.
120         if not bases[base] then
121             -- Register that we've added this base
122             bases[base] = true
123             -- Add a patterns for this base. First, the base with a single
124             -- letter or number subscript.
125             submatches[#submatches+1] = "^(" .. base .. ")([%a%d])$"
126             -- Seconde, the base with a longer prefix that includes at least
127             -- one of +-, (to catch things like ri+1, but not return).
128             submatches[#submatches+1] = "^(" .. base .. ")([%a%d]*[%-%+,]+[%a%d%-%+,]*)$"
129         end
130     end
131     return word
132 end
133
134 -- Do proper aligning for subsequent lines. For example, in 
135 --   foo = bar
136 --       | baz
137 -- We replace the spaces in the second line with a skip with the same with as
138 -- "foo ", to align the | with the =.
139 -- For this, we keep a table "indentlines", which contains all previous lines
140 -- with smaller indent levels that are still "in scope" (e.g., have not yet
141 -- been followed by a line with a smaller indent level). For example:
142 --   line1
143 --     line2
144 --       line3
145 --     line4
146 --       line5
147 -- After the last line, the table will contain:
148 --   { 0 = "line1", 2 = "  line4", 4 = "    line5"}
149 --   In other words, line3 is no longer in scope since it is "hidden" by
150 --   line4, and line is no longer in scope since it is replaced by line4.
151 local function do_indent(line)
152     newind, rest = utf.match(line, '^(%s*)(.*)')
153     prev = -1
154     -- Loop all the previous lines
155     for indent, unused in pairs(indentlines) do
156         if indent > #newind then
157             -- Remove any lines with a larger indent
158             indentlines[indent] = nil
159         elseif indent < #newind and indent > prev then
160             -- Find the last line (e.g, with the highest indent) with an
161             -- indent smaller than the new indent. This is the line from which
162             -- we need to copy the indent.
163             prev = indent
164         end
165     end
166     
167     -- Always store this line, possibly overwriting a previous line with the
168     -- same indent
169     indentlines[#newind] = line
170
171     if prev ~= -1 then
172         -- If there is a previous line with a smaller indent, make sure we
173         -- align with it. We do this by taking a prefix from that previous
174         -- line just as long as our indent. This gives us a bunch of
175         -- whitespace, with a few non-whitespace characters. We find out the
176         -- width of this prefix, and put whitespace just as wide as that
177         -- prefix before the current line, instead of the whitespace
178         -- characters that were there.
179         -- Doing this is slightly risky, since the prefix might contain
180         -- unfinished markup (e.g., \foo{bar without the closing }). We might
181         -- need to solve this later.
182         copyind = utf.sub(indentlines[prev], 1, #newind)
183         setwidth = "\\setwidthof{" .. copyind .. "}\\to\\pretlamalignwidth"
184         hskip = "\\hskip\\pretlamalignwidth"
185         return "{" .. setwidth .. hskip .. "}" .. rest
186     end
187         -- No previous line? Just return the unmodified line then
188         return line
189 end
190
191
192 -- Mark the begin of a block of lambda formatted buffers or expressions. This
193 -- means that, until you call end_of_block again, the subscript bases are
194 -- shared. For example, if you have \lam{y1} some text \lam{yn} within a
195 -- single block, the yn will properly get subscripted. Be sure to call
196 -- end_of_block again!
197 --
198 -- Blocks can be partially nested, meaning that the block
199 -- won't be closed until end_of_block was called exactly as often as
200 -- begin_of_block. However, subscripts from the inner block can still
201 -- influence subscripts in the outer block.
202 function vis.begin_of_block()
203     vis.begin_of_display()
204     in_block = in_block + 1
205 end
206
207 -- Ends the current block
208 function vis.end_of_block()
209     in_block = in_block - 1
210 end
211
212 function vis.begin_of_display()
213     if in_block == 0 then
214         -- Initially allow subscripts using _ or just appending a number (later,
215         -- we will add extra patterns here.
216         submatches = {"^(%a*)_([%a%d,]+)$", "^(%a+)(%d[%d,]*)$"}
217         -- This stores all the bases we've encountered so far (to prevent
218         -- duplicates). For each of them there will be a pattern in submatches
219         -- above.
220         bases = {}
221     end
222     indentlines = {}
223 end
224     
225
226 -- Make things work for inline typeing (e.g., \type{}) as well.
227 vis.begin_of_inline = vis.begin_of_display
228 vis.end_of_inline = vis.end_of_display
229
230 function vis.flush_line(str,nested)
231     buffers.flush_result(vis.do_line(str, false), nested)   
232 end
233
234 function vis.do_line(str, no_indent)
235     local result = {}
236     if not no_indent then
237         -- Allow ignore of the indentation stuff when we're calling ourselves
238         -- for a partial line.
239         str = do_indent(str)
240     end
241     while str ~= "" do
242         local found = false
243         local word, symbol
244         local text, rest = utf.match(str, "^%-%-(.-)%-%-(.*)")
245         if text then
246             table.insert(result, '\\strikethrough{')
247             -- Recursively call ourselves to handle spaces gracefully.
248             result = array_concat(result, vis.do_line(text, true))
249             table.insert(result, '}')
250             -- Eat the processed characters
251             str = rest
252         elseif utf.match(str, "^%-%-") then
253             table.insert(result, '{\\italic{--')
254             -- Recursively call ourselves to handle spaces gracefully.
255             result = array_concat(result, vis.do_line(utf.sub(str, 3), true))
256             table.insert(result, '}}')
257             -- Done with this line
258             str = ''
259         else
260             -- See if the next token is a word
261             word, str = take_word(str)
262             if word then
263                 if keywords[res] then
264                     -- Make all keywords bold
265                     word = "{\\bold " .. word ..  "}"
266                     if keywords[res].small then
267                         word = "\\small" .. word -- Curlies were added above
268                     end
269                 else
270                     -- Process any subscripts in the word
271                     word = do_subscripts(word)
272                 end
273                 table.insert(result, word)
274             else
275                 -- The next token is not a word, it must be a symbol
276                 symbol, str = take_symbol(str)
277                 table.insert(result, symbol)
278             end
279         end
280     end
281
282     return result
283 end
284
285 -- vim: set sw=4 sts=4 expandtab ai: