Fix todo's in the introduction chapter.
[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     [' '] = {repr = ' '},
23     ['_'] = {repr = '\\_'},
24     ['->'] = {repr = '→'},
25     ['=>'] = {repr = '⇒'},
26     -- The default * sits very high above the baseline, \ast (u+2217) looks
27     -- better.
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{}▶}'},
33 }
34
35 -- Keywords that should be bold
36 local keywords = {
37     ['case'] = {},
38     ['of'] = {},
39     ['let'] = {},
40     ['letrec'] = {},
41     ['letnonrec'] = {},
42     ['in'] = {},
43     ['DEFAULT'] = {small = true},
44 }
45
46 local in_block = 0
47 local submatches = {}
48 local bases = {}
49 -- Store the last line for each indent level
50 local indentlines = {}
51
52 -- See if str starts with a symbol, and return the remaining string and that
53 -- symbol. If no symbol from the table is matched, just returns the first
54 -- character.  We can do a lookup directly, since symbols can be different in
55 -- length, so we just loop over all symbols, trying them in turn.
56 local function take_symbol(str)
57     for symbol,props in pairs(symbols) do
58         -- Try to remove symbol from the start of str 
59         symbol, newstr = utf.match(str, "^(" .. symbol .. ")(.*)")
60         if symbol then
61             -- Return this tokens repr, or just the token if it has no
62             -- repr.
63             res = props.repr or symbol
64             -- Enclose the token in {\style .. }
65             if props.style then
66                 res = "{\\" .. props.style ..  " " .. res ..  "}"
67             end
68             return res, newstr
69         end
70     end
71     -- No symbol found, just return the first character
72     return utf.match(str, "^(.)(.*)")
73 end
74
75 -- Take a single word from str, if posible. Returns the rest of the string and
76 -- the word taken.
77 local function take_word(str)
78         -- A word must always start with a-z (in particular, λ is not a valid
79         -- start of a word).
80         res, newstr = utf.match(str, "^([a-zA-Z][%a%d%+%-%,_]+)(.*)")
81         return res, newstr or str
82 end
83
84 -- Tries to match each of the patterns and returns the captures of the first
85 -- matching pattern (up to 5 captures are supported). Returns nil when nothing
86 -- matches.
87 local function match_mul(str, patterns)
88     for i, pat in ipairs(patterns) do
89         a, b, c, d, e = utf.match(str, pat)
90         if a then
91             return a, b, c, d, e
92         end
93     end
94     return nil
95 end
96
97 -- Find any subscripts in the given word and typeset them
98 local function do_subscripts(word)
99     base, sub = match_mul(res, submatches)
100     if sub then
101         word = base .. "\\low{" .. sub .. "}"
102         -- After a word has been used as a base, allow subscripts
103         -- without _, even for non-numbers.
104         if not bases[base] then
105             -- Register that we've added this base
106             bases[base] = true
107             -- Add a patterns for this base. First, the base with a single
108             -- letter or number subscript.
109             submatches[#submatches+1] = "^(" .. base .. ")([%a%d])$"
110             -- Seconde, the base with a longer prefix that includes at least
111             -- one of +-, (to catch things like ri+1, but not return).
112             submatches[#submatches+1] = "^(" .. base .. ")([%a%d]*[%-%+,]+[%a%d%-%+,]*)$"
113         end
114     end
115     return word
116 end
117
118 -- Do proper aligning for subsequent lines. For example, in 
119 --   foo = bar
120 --       | baz
121 -- We replace the spaces in the second line with a skip with the same with as
122 -- "foo ", to align the | with the =.
123 -- For this, we keep a table "indentlines", which contains all previous lines
124 -- with smaller indent levels that are still "in scope" (e.g., have not yet
125 -- been followed by a line with a smaller indent level). For example:
126 --   line1
127 --     line2
128 --       line3
129 --     line4
130 --       line5
131 -- After the last line, the table will contain:
132 --   { 0 = "line1", 2 = "  line4", 4 = "    line5"}
133 --   In other words, line3 is no longer in scope since it is "hidden" by
134 --   line4, and line is no longer in scope since it is replaced by line4.
135 local function do_indent(line)
136     newind, rest = utf.match(line, '^(%s*)(.*)')
137     prev = -1
138     -- Loop all the previous lines
139     for indent, unused in pairs(indentlines) do
140         if indent > #newind then
141             -- Remove any lines with a larger indent
142             indentlines[indent] = nil
143         elseif indent < #newind and indent > prev then
144             -- Find the last line (e.g, with the highest indent) with an
145             -- indent smaller than the new indent. This is the line from which
146             -- we need to copy the indent.
147             prev = indent
148         end
149     end
150     
151     -- Always store this line, possibly overwriting a previous line with the
152     -- same indent
153     indentlines[#newind] = line
154
155     if prev ~= -1 then
156         -- If there is a previous line with a smaller indent, make sure we
157         -- align with it. We do this by taking a prefix from that previous
158         -- line just as long as our indent. This gives us a bunch of
159         -- whitespace, with a few non-whitespace characters. We find out the
160         -- width of this prefix, and put whitespace just as wide as that
161         -- prefix before the current line, instead of the whitespace
162         -- characters that were there.
163         -- Doing this is slightly risky, since the prefix might contain
164         -- unfinished markup (e.g., \foo{bar without the closing }). We might
165         -- need to solve this later.
166         copyind = utf.sub(indentlines[prev], 1, #newind)
167         setwidth = "\\setwidthof{" .. copyind .. "}\\to\\pretlamalignwidth"
168         hskip = "\\hskip\\pretlamalignwidth"
169         return "{" .. setwidth .. hskip .. "}" .. rest
170     end
171         -- No previous line? Just return the unmodified line then
172         return line
173 end
174
175
176 -- Mark the begin of a block of lambda formatted buffers or expressions. This
177 -- means that, until you call end_of_block again, the subscript bases are
178 -- shared. For example, if you have \lam{y1} some text \lam{yn} within a
179 -- single block, the yn will properly get subscripted. Be sure to call
180 -- end_of_block again!
181 --
182 -- Blocks can be partially nested, meaning that the block
183 -- won't be closed until end_of_block was called exactly as often as
184 -- begin_of_block. However, subscripts from the inner block can still
185 -- influence subscripts in the outer block.
186 function vis.begin_of_block()
187     vis.begin_of_display()
188     in_block = in_block + 1
189 end
190
191 -- Ends the current block
192 function vis.end_of_block()
193     in_block = in_block - 1
194 end
195
196 function vis.begin_of_display()
197     if in_block == 0 then
198         -- Initially allow subscripts using _ or just appending a number (later,
199         -- we will add extra patterns here.
200         submatches = {"^(%a*)_([%a%d,]+)$", "^(%a+)(%d[%d,]+)$"}
201         -- This stores all the bases we've encountered so far (to prevent
202         -- duplicates). For each of them there will be a pattern in submatches
203         -- above.
204         bases = {}
205     end
206     indentlines = {}
207 end
208     
209
210 -- Make things work for inline typeing (e.g., \type{}) as well.
211 vis.begin_of_inline = vis.begin_of_display
212 vis.end_of_inline = vis.end_of_display
213
214 function vis.flush_line(str,nested)
215     local result, state = { }, 0
216     local finish, change = buffers.finish_state, buffers.change_state
217     str = do_indent(str)
218     -- Set the colorscheme, which is used by finish_state and change_state
219     buffers.currentcolors = colors
220     while str ~= "" do
221         local found = false
222         local word, symbol
223         -- See if the next token is a word
224         word, str = take_word(str)
225         if word then
226             if keywords[res] then
227                 -- Make all keywords bold
228                 word = "{\\bold " .. word ..  "}"
229                 if keywords[res].small then
230                     word = "\\small" .. word -- Curlies were added above
231                 end
232             else
233                 -- Process any subscripts in the word
234                 word = do_subscripts(word)
235             end
236         else
237             -- The next token is not a word, it must be a symbol
238             symbol, str = take_symbol(str)
239         end
240
241         -- Append the resulting token
242         result[#result+1] = word or symbol
243     end
244     
245     state = finish(state, result)
246     buffers.flush_result(result,nested)
247 end
248
249 -- vim: set sw=4 sts=4 expandtab ai: