Repository navigation
Expand file tree
/
Copy pathprettify.lua
More file actions
65 lines (57 loc) · 1.67 KB
/
Copy pathprettify.lua
File metadata and controls
65 lines (57 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
-- Making Lua source code look pretty.
-- A simple scanner based prettifier, which scans comments for @{ref} and code
-- for known modules and functions.
-- A module reference to an example `test-fun.lua` would look like
-- `@{example:test-fun}`.
local List = require 'pl.List'
local lexer = require 'ldoc.lexer'
local globals = require 'ldoc.builtin.globals'
local tnext = lexer.skipws
local prettify = {}
local escaped_chars = {
['&'] = '&',
['<'] = '<',
['>'] = '>',
}
local escape_pat = '[&<>]'
local function escape(str)
return (str:gsub(escape_pat,escaped_chars))
end
local function span(t,val)
return ('<span class="%s">%s</span>'):format(t,val)
end
local spans = {keyword=true,number=true,string=true,comment=true,global=true}
function prettify.lua (fname, code, initial_lineno)
local res = List()
res:append '<pre>\n'
initial_lineno = initial_lineno or 0
local tok = lexer.lua(code,{},{})
local error_reporter = {
warning = function (self,msg)
io.stderr:write(fname..':'..tok:lineno()+initial_lineno..': '..msg,'\n')
end
}
local t,val = tok()
if not t then return nil,"empty file" end
while t do
val = escape(val)
if globals.functions[val] or globals.tables[val] then
t = 'global'
end
if spans[t] then
if t == 'comment' then -- may contain @{ref}
val = prettify.resolve_inline_references(val,error_reporter)
end
res:append(span(t,val))
else
res:append(val)
end
t,val = tok()
end
local last = res[#res]
if last:match '\n$' then
res[#res] = last:gsub('\n+','')
end
return res:join ()
end
return prettify