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