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