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