Let all lambda expressions in pret-trans share subscript detection.
[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 = '\\sim'},
27 }
28
29
30 -- Keywords that should be bold
31 local keywords = {
32     ['case'] = {},
33     ['of'] = {},
34     ['let'] = {},
35     ['in'] = {},
36 }
37
38 -- See if str starts with a symbol, and return the remaining string and that
39 -- symbol. If no symbol from the table is matched, just returns the first
40 -- character.  We can do a lookup directly, since symbols can be different in
41 -- length, so we just loop over all symbols, trying them in turn.
42 local function take_symbol(str)
43     for symbol,props in pairs(symbols) do
44         -- Try to remove symbol from the start of str 
45         symbol, newstr = utf.match(str, "^(" .. symbol .. ")(.*)")
46         if symbol then
47             -- Return this tokens repr, or just the token if it has no
48             -- repr.
49             res = props.repr or symbol
50             -- Enclose the token in {\style .. }
51             if props.style then
52                 res = "{\\" .. props.style ..  " " .. res ..  "}"
53             end
54             return res, newstr
55         end
56     end
57     -- No symbol found, just return the first character
58     return utf.match(str, "^(.)(.*)")
59 end
60
61 -- Take a single word from str, if posible. Returns the rest of the string and
62 -- the word taken.
63 local function take_word(str)
64         -- A word must always start with a-z (in particular, λ is not a valid
65         -- start of a word).
66         res, newstr = utf.match(str, "^([a-zA-Z][%a%d%+%-%,_]+)(.*)")
67         return res, newstr or str
68 end
69
70 -- Tries to match each of the patterns and returns the captures of the first
71 -- matching pattern (up to 5 captures are supported). Returns nil when nothing
72 -- matches.
73 local function match_mul(str, patterns)
74     for i, pat in ipairs(patterns) do
75         a, b, c, d, e = utf.match(str, pat)
76         if a then
77             return a, b, c, d, e
78         end
79     end
80     return nil
81 end
82
83 -- Find any subscripts in the given word and typeset them
84 local function do_subscripts(word)
85     base, sub = match_mul(res, submatches)
86     if sub then
87         word = base .. "\\low{" .. sub .. "}"
88         -- After a word has been used as a base, allow subscripts
89         -- without _, even for non-numbers.
90         if not bases[base] then
91             -- Register that we've added this base
92             bases[base] = true
93             -- Add a patterns for this base. First, the base with a single
94             -- letter or number subscript.
95             submatches[#submatches+1] = "^(" .. base .. ")([%a%d])$"
96             -- Seconde, the base with a longer prefix that includes at least
97             -- one of +-, (to catch things like ri+1, but not return).
98             submatches[#submatches+1] = "^(" .. base .. ")([%a%d]*[%-%+%,]+[%a%d%-%+%,]*)$"
99         end
100     end
101     return word
102 end
103
104 local in_block = 0
105
106 -- Mark the begin of a block of lambda formatted buffers or expressions. This
107 -- means that, until you call end_of_block again, the subscript bases are
108 -- shared. For example, if you have \lam{y1} some text \lam{yn} within a
109 -- single block, the yn will properly get subscripted. Be sure to call
110 -- end_of_block again!
111 --
112 -- Blocks can be partially nested, meaning that the block
113 -- won't be closed until end_of_block was called exactly as often as
114 -- begin_of_block. However, subscripts from the inner block can still
115 -- influence subscripts in the outer block.
116 function vis.begin_of_block()
117     vis.begin_of_display()
118     in_block = in_block + 1
119 end
120
121 -- Ends the current block
122 function vis.end_of_block()
123     in_block = in_block - 1
124 end
125
126 function vis.begin_of_display()
127     if in_block == 0 then
128         -- Initially allow subscripts using _ or just appending a number (later,
129         -- we will add extra patterns here.
130         submatches = {"^(%a*)_([%a%d,]+)$", "^(%a+)(%d+)$"}
131         -- This stores all the bases we've encountered so far (to prevent
132         -- duplicates). For each of them there will be a pattern in submatches
133         -- above.
134         bases = {}
135     end
136 end
137
138 -- Make things work for inline typeing (e.g., \type{}) as well.
139 vis.begin_of_inline = vis.begin_of_display
140 vis.end_of_inline = vis.end_of_display
141
142 function vis.flush_line(str,nested)
143     local result, state = { }, 0
144     local finish, change = buffers.finish_state, buffers.change_state
145     -- Set the colorscheme, which is used by finish_state and change_state
146     buffers.currentcolors = colors
147     while str ~= "" do
148         local found = false
149         local word, symbol
150         -- See if the next token is a word
151         word, str = take_word(str)
152         if word then
153             if keywords[res] then
154                 -- Make all keywords bold
155                 word = "{\\bold " .. word ..  "}"
156             else
157                 -- Process any subscripts in the word
158                 word = do_subscripts(word)
159             end
160         else
161             -- The next token is not a word, it must be a symbol
162             symbol, str = take_symbol(str)
163         end
164
165         -- Append the resulting token
166         result[#result+1] = word or symbol
167     end
168
169     state = finish(state, result)
170     buffers.flush_result(result,nested)
171 end
172
173 -- vim: set sw=4 sts=4 expandtab ai: