1 -- filename : type-lam.lua
2 -- comment : Pretty printing of (extended) lambda calculus
3 -- author : Matthijs Kooijman, Universiteit Twente, NL
4 -- copyright: Matthijs Kooijman
7 local utf = unicode.utf8
9 local vis = buffers.newvisualizer("lam")
18 -- Symbols that should have a different representation
20 [' '] = {repr = '\\obs '},
21 ['_'] = {repr = '\\_'},
22 ['->'] = {repr = '\\rightarrow'},
23 -- The default * sits very high above the baseline, \ast (u+2217) looks
25 ['*'] = {repr = '\\ast'},
26 ['~'] = {repr = '\\HDLine[width=.20 * \\the\\textwidth]'},
27 ['|'] = {repr = '\\char' .. utf.byte('|')},
30 -- Keywords that should be bold
44 -- Store the last line for each indent level
45 local indentlines = {}
46 -- The amount of indent of the first line, which we will strip of all
47 -- subsequent lines. This allows the entire block to be indented as normal in
48 -- the tex source code.
51 -- See if str starts with a symbol, and return the remaining string and that
52 -- symbol. If no symbol from the table is matched, just returns the first
53 -- character. We can do a lookup directly, since symbols can be different in
54 -- length, so we just loop over all symbols, trying them in turn.
55 local function take_symbol(str)
56 for symbol,props in pairs(symbols) do
57 -- Try to remove symbol from the start of str
58 symbol, newstr = utf.match(str, "^(" .. symbol .. ")(.*)")
60 -- Return this tokens repr, or just the token if it has no
62 res = props.repr or symbol
63 -- Enclose the token in {\style .. }
65 res = "{\\" .. props.style .. " " .. res .. "}"
70 -- No symbol found, just return the first character
71 return utf.match(str, "^(.)(.*)")
74 -- Take a single word from str, if posible. Returns the rest of the string and
76 local function take_word(str)
77 -- A word must always start with a-z (in particular, λ is not a valid
79 res, newstr = utf.match(str, "^([a-zA-Z][%a%d%+%-%,_]+)(.*)")
80 return res, newstr or str
83 -- Tries to match each of the patterns and returns the captures of the first
84 -- matching pattern (up to 5 captures are supported). Returns nil when nothing
86 local function match_mul(str, patterns)
87 for i, pat in ipairs(patterns) do
88 a, b, c, d, e = utf.match(str, pat)
96 -- Find any subscripts in the given word and typeset them
97 local function do_subscripts(word)
98 base, sub = match_mul(res, submatches)
100 word = base .. "\\low{" .. sub .. "}"
101 -- After a word has been used as a base, allow subscripts
102 -- without _, even for non-numbers.
103 if not bases[base] then
104 -- Register that we've added this base
106 -- Add a patterns for this base. First, the base with a single
107 -- letter or number subscript.
108 submatches[#submatches+1] = "^(" .. base .. ")([%a%d])$"
109 -- Seconde, the base with a longer prefix that includes at least
110 -- one of +-, (to catch things like ri+1, but not return).
111 submatches[#submatches+1] = "^(" .. base .. ")([%a%d]*[%-%+%,]+[%a%d%-%+%,]*)$"
117 -- Do proper aligning for subsequent lines. For example, in
120 -- We replace the spaces in the second line with a skip with the same with as
121 -- "foo ", to align the | with the =.
122 -- For this, we keep a table "indentlines", which contains all previous lines
123 -- with smaller indent levels that are still "in scope" (e.g., have not yet
124 -- been followed by a line with a smaller indent level). For example:
130 -- After the last line, the table will contain:
131 -- { 0 = "line1", 2 = " line4", 4 = " line5"}
132 -- In other words, line3 is no longer in scope since it is "hidden" by
133 -- line4, and line is no longer in scope since it is replaced by line4.
134 local function do_indent(line)
135 newind, rest = utf.match(line, '^(%s*)(.*)')
137 -- Store the first line's indent
138 if not first_indent then
139 first_indent = utf.len(newind)
142 -- Strip the indent of the first line from this line's indent.
143 newind = utf.sub(newind, first_indent + 1)
144 -- Rebuild line, so we can still use it below
145 line = newind .. rest
148 -- Loop all the previous lines
149 for indent, unused in pairs(indentlines) do
150 if indent > #newind then
151 -- Remove any lines with a larger indent
152 indentlines[indent] = nil
153 elseif indent < #newind and indent > prev then
154 -- Find the last line (e.g, with the highest indent) with an
155 -- indent smaller than the new indent. This is the line from which
156 -- we need to copy the indent.
161 -- Always store this line, possibly overwriting a previous line with the
163 indentlines[#newind] = line
166 -- If there is a previous line with a smaller indent, make sure we
167 -- align with it. We do this by taking a prefix from that previous
168 -- line just as long as our indent. This gives us a bunch of
169 -- whitespace, with a few non-whitespace characters. We find out the
170 -- width of this prefix, and put whitespace just as wide as that
171 -- prefix before the current line, instead of the whitespace
172 -- characters that were there.
173 -- Doing this is slightly risky, since the prefix might contain
174 -- unfinished markup (e.g., \foo{bar without the closing }). We might
175 -- need to solve this later.
176 copyind = utf.sub(indentlines[prev], 1, #newind)
177 setwidth = "\\setwidthof{" .. copyind .. "}\\to\\pretlamalignwidth"
178 hskip = "\\hskip\\pretlamalignwidth"
179 return "{" .. setwidth .. hskip .. "}" .. rest
181 -- No previous line? Just return the unmodified line then
186 -- Mark the begin of a block of lambda formatted buffers or expressions. This
187 -- means that, until you call end_of_block again, the subscript bases are
188 -- shared. For example, if you have \lam{y1} some text \lam{yn} within a
189 -- single block, the yn will properly get subscripted. Be sure to call
190 -- end_of_block again!
192 -- Blocks can be partially nested, meaning that the block
193 -- won't be closed until end_of_block was called exactly as often as
194 -- begin_of_block. However, subscripts from the inner block can still
195 -- influence subscripts in the outer block.
196 function vis.begin_of_block()
197 vis.begin_of_display()
198 in_block = in_block + 1
201 -- Ends the current block
202 function vis.end_of_block()
203 in_block = in_block - 1
206 function vis.begin_of_display()
207 if in_block == 0 then
208 -- Initially allow subscripts using _ or just appending a number (later,
209 -- we will add extra patterns here.
210 submatches = {"^(%a*)_([%a%d,]+)$", "^(%a+)([%d,]+)$"}
211 -- This stores all the bases we've encountered so far (to prevent
212 -- duplicates). For each of them there will be a pattern in submatches
221 -- Make things work for inline typeing (e.g., \type{}) as well.
222 vis.begin_of_inline = vis.begin_of_display
223 vis.end_of_inline = vis.end_of_display
225 function vis.flush_line(str,nested)
226 local result, state = { }, 0
227 local finish, change = buffers.finish_state, buffers.change_state
229 -- Set the colorscheme, which is used by finish_state and change_state
230 buffers.currentcolors = colors
234 -- See if the next token is a word
235 word, str = take_word(str)
237 if keywords[res] then
238 -- Make all keywords bold
239 word = "{\\bold " .. word .. "}"
241 -- Process any subscripts in the word
242 word = do_subscripts(word)
245 -- The next token is not a word, it must be a symbol
246 symbol, str = take_symbol(str)
249 -- Append the resulting token
250 result[#result+1] = word or symbol
253 state = finish(state, result)
254 buffers.flush_result(result,nested)
257 -- vim: set sw=4 sts=4 expandtab ai: