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