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