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