2011-07-10 19:10:53 +02:00
|
|
|
-- 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}`.
|
|
|
|
require 'pl'
|
|
|
|
local lexer = require 'ldoc.lexer'
|
2011-07-11 15:40:44 +02:00
|
|
|
local tnext = lexer.skipws
|
2011-07-10 19:10:53 +02:00
|
|
|
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}
|
|
|
|
|
2011-07-11 15:40:44 +02:00
|
|
|
function prettify.lua (code)
|
2011-07-10 19:10:53 +02:00
|
|
|
local res = List()
|
|
|
|
res:append(header)
|
|
|
|
res:append '<pre>\n'
|
|
|
|
|
|
|
|
local tok = lexer.lua(code,{},{})
|
|
|
|
local t,val = tok()
|
2011-07-11 09:34:18 +02:00
|
|
|
if not t then return nil,"empty file" end
|
2011-07-10 19:10:53 +02:00
|
|
|
while t do
|
|
|
|
val = escape(val)
|
|
|
|
if spans[t] then
|
2011-07-11 15:40:44 +02:00
|
|
|
if t == 'comment' then -- may contain @{ref}
|
2011-07-12 14:14:55 +02:00
|
|
|
val = prettify.resolve_inline_references(val)
|
2011-07-11 15:40:44 +02:00
|
|
|
end
|
2011-07-10 19:10:53 +02:00
|
|
|
res:append(span(t,val))
|
|
|
|
else
|
|
|
|
res:append(val)
|
|
|
|
end
|
|
|
|
t,val = tok()
|
|
|
|
end
|
|
|
|
res:append(footer)
|
|
|
|
return res:join ()
|
|
|
|
end
|
|
|
|
|
|
|
|
return prettify
|
2011-07-11 15:40:44 +02:00
|
|
|
|