summaryrefslogtreecommitdiff
path: root/rst_context.lua
blob: e6c20ee9304f0829520cf3538f8d3e1672bca9d0 (plain)
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
#!/usr/bin/env texlua
--------------------------------------------------------------------------------
--         FILE:  rst_context.lua
--        USAGE:  ./rst_context.lua 
--  DESCRIPTION:  
--      OPTIONS:  ---
-- REQUIREMENTS:  ---
--       AUTHOR:  Philipp Gesang (Phg), <megas.kapaneus@gmail.com>
--      VERSION:  1.0
--      CREATED:  31/08/10 19:35:15 CEST
--------------------------------------------------------------------------------
--


require "lpeg"
local C, Cb, Cc, Cg, Cmt, Cp, Cs, Ct, P, R, S, V, match = lpeg.C, lpeg.Cb, lpeg.Cc, lpeg.Cg, lpeg.Cmt, lpeg.Cp, lpeg.Cs, lpeg.Ct, lpeg.P, lpeg.R, lpeg.S, lpeg.V, lpeg.match

if not context then -- standard context lpeg stripper from l-string.lua
    local stripper = P{
        [1] = "stripper",
        stripper = V"space"^0 * C((V"space"^0 * V"nospace"^1)^0),
        space    = S(" \t\v\n"),
        nospace  = 1 - V"space",
    }
    function string.strip(str)
        return stripper:match(str) or ""
    end 
end


local rst_context = {}
rst_context.collected_references = {}
rst_context.collected_adornments = {}
rst_context.last_section_level   = 0
rst_context.anonymous_links      = 0
rst_context.context_references   = {}

-- So we can use crefs[n][2] to refer to the place where the reference was
-- created.
local function get_context_reference (str)
    local crefs = rst_context.context_references
    refstring = "__contextref__" .. tostring(#crefs + 1)
    crefs[#crefs + 1] = { refstring, str }
    return refstring
end

function rst_context.emphasis (str)
    return [[{\\em ]] .. str .. [[}]]
end

function rst_context.strong_emphasis (str)
    return [[{\\sc ]] .. str .. [[}]]
end

function rst_context.paragraph (str)
    return "\n" .. [[\\startparagraph]] .. "\n" .. str .. "\n".. [[\\stopparagraph]] .. "\n"
end

function rst_context.literal (str)
    str = str:gsub([[\]], [[\\]]) -- evade escaping of backslashes
    return [[\\type{]] .. str .. [[}]]
end


function rst_context.interpreted_text (...)
    local tab = { ... }
    --print (tab, #tab, tab[1], tab[2], tab[3])
    local role, str
    role = tab[1]:match("^:(.*):$") or tab[3]:match("^:(.*):$")
    str  = tab[2]

    if not role then -- implicit role
        role = "emphasis"
    end

    --print(role, str)

    return rst_context[role](str)
end

function rst_context.link_standalone (str)
    return "\n"
        .. [[\\goto{\\hyphenatedurl{]]
        .. str
        .. [[}}[url(]]
        .. str
        .. [=[)]]=]
end

function rst_context.reference (str)
    str = str:match("[^_]*")
    local link = rst_context.collected_references[str]
    if not link then -- TODO make warning instead
        return([[{\\sc UNDEFINED REFERENCE ]] .. str .. [[}.]])
    end
    return [[\\goto{]]
        .. str
        .. [[}[url(]]
        .. link
        .. [=[)]]=]
end

function rst_context.target (tab)
    --print("GOT ONE!")
    --local tab = { ... }
    local refs = rst_context.collected_references
    local target = tab[#tab] -- Ct + C could be clearer but who cares
    tab[#tab] = nil

    local function resolve_indirect (r)
        if r and r:match(".*_$") then -- pointing elsewhere
            return resolve_indirect (refs[r:match("(.*)_$")]) or "need another run!" -- TODO multiple runs && data collection
        end
        return r
    end

    local function create_anonymous ()
        rst_context.anonymous_links = rst_context.anonymous_links + 1
        return "__anon__" .. rst_context.anonymous_links
    end


    target = resolve_indirect (target)

    for i=1,#tab do
        local id = tab[i]:gsub("\\:",":") -- deescaping
        id = id ~= "" and id or create_anonymous ()
        refs[id] = refs[id] or target
    end
    return ""
end

function rst_context.escape (str)
    return str:gsub("\\(.)", "%1")
end

function rst_context.joinindented (tab)
    return table.concat (tab, "")
end

local sectionlevels = {
    [1] = "chapter",
    [2] = "section",
    [3] = "subsection",
    [4] = "subsubsection",
    [5] = "subsubsubsection",
}

local function get_line_pattern (chr)
    return P(chr)^1 * (-P(1))
end

function rst_context.section (...)  -- TODO general cleanup; move validity
    local tab = { ... }             -- checking to parser.
    local section, str = true, ""
    local adornchar 
    if #tab == 3 then -- TODO use unicode length with ConTeXt
        --print(">>"..tab[1].."<>"..tab[2].."<<")
        adornchar = tab[1]:sub(1,1)
        --  overline == underline && len(overline) = len(sectionstring)
        section = tab[1] == tab[3] and #tab[1] >= #tab[2] 
        -- if overline consists only of one char then keep truth value else
        -- false
        section = get_line_pattern(adornchar):match(tab[1]) ~= nil and section
        str = string.strip(tab[2])
    else -- no overline
        --print(">>"..tab[1].."<>"..tab[2].."<<")
        adornchar = tab[2]:sub(1,1)
        section = #tab[1] <= #tab[2]
        section = get_line_pattern(adornchar):match(tab[2]) ~= nil and section
        str = tab[1]
    end

    if section then -- determine level
        local level = rst_context.last_section_level
        local rca = rst_context.collected_adornments
        if rca[adornchar] then
            level = rca[adornchar]
        else
            level = level + 1
            rca[adornchar] = level
            rst_context.last_section_level = level
        end

        ref = get_context_reference (str)

        str = string.format("\n\\\\%s[%s]{%s}\n", sectionlevels[level], ref, str)
    end

    return section and str or ""
end

-- Prime time for the fancybreak module.
function rst_context.transition (str)
    return "\n\\hrule\n"
end

function rst_context.bullet_marker(str)
    return "marker"
end

do
    local space    = lpeg.S(" \t\v\n")
    local nospace  = 1 - space
    local stripper = space^0 * lpeg.C((space^0 * nospace^1)^0)
    function string.strip(str)
        return match(stripper,str) or ""
    end 
end

local enumeration_types = {
    ["*"] = "*", -- unordered bulleted
    ["+"] = "*",
    ["-"] = "*",
    ["•"] = "*",
    ["‣"] = "*",
    ["⁃"] = "*",

    ["#"] = "1", -- numbered lists and conversion
    ["A"] = "A",
    ["a"] = "a",
    ["I"] = "R",
    ["i"] = "r",
}

-- \setupitemize[left=(, right=), margin=4em, stopper=]

local stripme   = S"()."
local dontstrip = 1 - stripme
local itemstripper = stripme^0 * C(dontstrip^1) * stripme^0
local function parse_itemstring(str)
    local setup = [[\setupitemize[]]
    -- string.match is slightly faster than string.find
    if str:match("^%(") then
        setup = setup .. [[left=(,]]
    end
    if str:match("%)$") then
        setup = setup .. [[right=)]]
    end
    if str:match("%.$") then
        setup = setup .. [[stopper=.]]
    end
    setup = setup .. "]\n"

    str = itemstripper:match(str)
    return {setup = setup, str=str}
end

function rst_context.startitemize(str)
    local setup = ""
    str = string.strip(str)

    local listtype = enumeration_types[str] or parse_itemstring(str)

    if type(listtype) == "table" then
        print(type(listtype), listtype[2])
        setup = listtype.setup
        listtype = listtype.str
    end

    return setup .. [[
\\startitemize[]] .. listtype .. [[]
]] 
end

function rst_context.stopitemize(str)
    return str .. [[
\\stopitemize
]]
end

function rst_context.bullet_item (str)
    return [[

\\item ]] .. str .. [[

]]
end

--------------------------------------------------------------------------------
-- Definition lists 
--------------------------------------------------------------------------------
-- TODO define proper setups (probably bnf-like and some narrower for def-paragraphs)

function rst_context.deflist (str)
    return [[

\\startdefinitionlist
]] .. str .. [[

\\stopdefinitionlist
]]
end

function rst_context.deflist_item (str)
    return [[\\definitionitem{%]] .. str .. [[}]]
end

function rst_context.deflist_classifier (str)
    return [[\\definitionclassifier{]] .. str .. [[}]]
end

function rst_context.deflist_term (str)
    return [[
    
  \\definitionterm{]] .. str .. [[}]]
end

function rst_context.deflist_def (str)
    return [[
    
  \\definitiondef{%]] .. str .. [[}]]
end

return rst_context