7bb1f8a6cab40d376b1269db23381f39b8aa0f46
[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 if not buffers                 then buffers                 = { } end
10 if not buffers.visualizers     then buffers.visualizers     = { } end
11 if not buffers.visualizers.lam then buffers.visualizers.lam = { } end
12
13 buffers.visualizers.lam.colors = {
14     "prettytwo",
15     "prettyone",
16     "prettythree",
17     "prettyfour"
18 }
19
20 buffers.visualizers.lam.tokens = {
21     [' '] = {repr = '\\obs '},
22     ['_'] = {repr = '\\_'},
23     ['->'] = {repr = '\\rightarrow'},
24     -- The default * sits very high above the baseline, \ast (u+2217) looks
25     -- better.
26     ['*'] = {repr = '\\ast'},
27     ['case'] = {style = 'bold'},
28     ['of'] = {style = 'bold'},
29     ['let'] = {style = 'bold'},
30     ['in'] = {style = 'bold'},
31 }
32
33 function buffers.visualizers.lam.flush_line(str,nested)
34     local result, state = { }, 0
35     local finish, change = buffers.finish_state, buffers.change_state
36     -- Set the colorscheme, which is used by finish_state and change_state
37     buffers.currentcolors = buffers.visualizers.lam.colors
38
39     while str ~= "" do
40         found = false
41         for tok,props in pairs(buffers.visualizers.lam.tokens) do
42             -- Try to remove tok from the start of str 
43             str, count = utf.gsub(str, "^" .. tok, "")
44             if count ~= 0 then
45                 -- Replace the token with the repr, or just itself
46                 result[#result+1] = props.repr or tok
47                 -- Enclose the token in {\style .. }
48                 if props.style then
49                     result[#result] = "{\\" .. props.style ..
50                                         " " .. result[#result] ..
51                                         "}"
52                 end
53                 -- We found a token, now start over
54                 found = true
55                 break
56             end
57         end
58         if not found then
59             result[#result+1] = utf.sub(str, 1, 1)
60             str = utf.sub(str, 2)
61         end
62     end
63     state = finish(state, result)
64     buffers.flush_result(result,nested)
65 end
66
67 -- vim: set sw=4 sts=4 expandtab ai: