1#!/usr/bin/env lua
2
3--[[
4
5i got this script from https://github.com/mpeterv/markdown
6all other functionality aside from this script and luafilesystem (lfs.so) is all my stuff.
7- with love myu be you
8
9]]
10
11----------------------------------------------------------------------
12-- Utility functions
13----------------------------------------------------------------------
14
15local unpack = table.unpack or unpack
16
17-- Returns the result of mapping the values in table t through the function f
18local function map(t, f)
19 local out = {}
20 for k,v in pairs(t) do out[k] = f(v,k) end
21 return out
22end
23
24-- Functional style if statement. (NOTE: no short circuit evaluation)
25local function iff(t, a, b) if t then return a else return b end end
26
27-- Splits the text into an array of separate lines.
28local function split(text, sep)
29 sep = sep or "\n"
30 local lines = {}
31 local pos = 1
32 while true do
33 local b,e = text:find(sep, pos)
34 if not b then table.insert(lines, text:sub(pos)) break end
35 table.insert(lines, text:sub(pos, b-1))
36 pos = e + 1
37 end
38 return lines
39end
40
41-- Converts tabs to spaces
42local function detab(text)
43 local tab_width = 4
44 local function rep(match)
45 local spaces = -match:len()
46 while spaces<1 do spaces = spaces + tab_width end
47 return match .. string.rep(" ", spaces)
48 end
49 text = text:gsub("([^\n]-)\t", rep)
50 return text
51end
52
53-- Applies string.find for every pattern in the list and returns the first match
54local function find_first(s, patterns, index)
55 local res = {}
56 for _,p in ipairs(patterns) do
57 local match = {s:find(p, index)}
58 if #match>0 and (#res==0 or match[1] < res[1]) then res = match end
59 end
60 return unpack(res)
61end
62
63-- If a replacement array is specified, the range [start, stop] in the array is replaced
64-- with the replacement array and the resulting array is returned. Without a replacement
65-- array the section of the array between start and stop is returned.
66local function splice(array, start, stop, replacement)
67 if replacement then
68 local n = stop - start + 1
69 while n > 0 do
70 table.remove(array, start)
71 n = n - 1
72 end
73 for _,v in ipairs(replacement) do
74 table.insert(array, start, v)
75 end
76 return array
77 else
78 local res = {}
79 for i = start,stop do
80 table.insert(res, array[i])
81 end
82 return res
83 end
84end
85
86-- Outdents the text one step.
87local function outdent(text)
88 text = "\n" .. text
89 text = text:gsub("\n ? ? ?", "\n")
90 text = text:sub(2)
91 return text
92end
93
94-- Indents the text one step.
95local function indent(text)
96 text = text:gsub("\n", "\n ")
97 return text
98end
99
100-- Does a simple tokenization of html data. Returns the data as a list of tokens.
101-- Each token is a table with a type field (which is either "tag" or "text") and
102-- a text field (which contains the original token data).
103local function tokenize_html(html)
104 local tokens = {}
105 local pos = 1
106 while true do
107 local start = find_first(html, {"<!%-%-", "<[a-z/!$]", "<%?"}, pos)
108 if not start then
109 table.insert(tokens, {type="text", text=html:sub(pos)})
110 break
111 end
112 if start ~= pos then table.insert(tokens, {type="text", text = html:sub(pos, start-1)}) end
113
114 local _, stop
115 if html:match("^<!%-%-", start) then
116 _,stop = html:find("%-%->", start)
117 elseif html:match("^<%?", start) then
118 _,stop = html:find("?>", start)
119 else
120 _,stop = html:find("%b<>", start)
121 end
122 if not stop then
123 -- error("Could not match html tag " .. html:sub(start,start+30))
124 table.insert(tokens, {type="text", text=html:sub(start, start)})
125 pos = start + 1
126 else
127 table.insert(tokens, {type="tag", text=html:sub(start, stop)})
128 pos = stop + 1
129 end
130 end
131 return tokens
132end
133
134----------------------------------------------------------------------
135-- Hash
136----------------------------------------------------------------------
137
138-- This is used to "hash" data into alphanumeric strings that are unique
139-- in the document. (Note that this is not cryptographic hash, the hash
140-- function is not one-way.) The hash procedure is used to protect parts
141-- of the document from further processing.
142
143local HASH = {
144 -- Has the hash been inited.
145 inited = false,
146
147 -- The unique string prepended to all hash values. This is to ensure
148 -- that hash values do not accidently coincide with an actual existing
149 -- string in the document.
150 identifier = "",
151
152 -- Counter that counts up for each new hash instance.
153 counter = 0,
154
155 -- Hash table.
156 table = {}
157}
158
159-- Inits hashing. Creates a hash_identifier that doesn't occur anywhere
160-- in the text.
161local function init_hash(text)
162 HASH.inited = true
163 HASH.identifier = ""
164 HASH.counter = 0
165 HASH.table = {}
166
167 local s = "HASH"
168 local counter = 0
169 local id
170 while true do
171 id = s .. counter
172 if not text:find(id, 1, true) then break end
173 counter = counter + 1
174 end
175 HASH.identifier = id
176end
177
178-- Returns the hashed value for s.
179local function hash(s)
180 assert(HASH.inited)
181 if not HASH.table[s] then
182 HASH.counter = HASH.counter + 1
183 local id = HASH.identifier .. HASH.counter .. "X"
184 HASH.table[s] = id
185 end
186 return HASH.table[s]
187end
188
189----------------------------------------------------------------------
190-- Protection
191----------------------------------------------------------------------
192
193-- The protection module is used to "protect" parts of a document
194-- so that they are not modified by subsequent processing steps.
195-- Protected parts are saved in a table for later unprotection
196
197-- Protection data
198local PD = {
199 -- Saved blocks that have been converted
200 blocks = {},
201
202 -- Block level tags that will be protected
203 tags = {"p", "div", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote",
204 "pre", "table", "dl", "ol", "ul", "script", "noscript", "form", "fieldset",
205 "iframe", "math", "ins", "del"}
206}
207
208-- Pattern for matching a block tag that begins and ends in the leftmost
209-- column and may contain indented subtags, i.e.
210-- <div>
211-- A nested block.
212-- <div>
213-- Nested data.
214-- </div>
215-- </div>
216local function block_pattern(tag)
217 return "\n<" .. tag .. ".-\n</" .. tag .. ">[ \t]*\n"
218end
219
220-- Pattern for matching a block tag that begins and ends with a newline
221local function line_pattern(tag)
222 return "\n<" .. tag .. ".-</" .. tag .. ">[ \t]*\n"
223end
224
225-- Protects the range of characters from start to stop in the text and
226-- returns the protected string.
227local function protect_range(text, start, stop)
228 local s = text:sub(start, stop)
229 local h = hash(s)
230 PD.blocks[h] = s
231 text = text:sub(1,start) .. h .. text:sub(stop)
232 return text
233end
234
235-- Protect every part of the text that matches any of the patterns. The first
236-- matching pattern is protected first, etc.
237local function protect_matches(text, patterns)
238 while true do
239 local start, stop = find_first(text, patterns)
240 if not start then break end
241 text = protect_range(text, start, stop)
242 end
243 return text
244end
245
246-- Protects blocklevel tags in the specified text
247local function protect(text)
248 -- First protect potentially nested block tags
249 text = protect_matches(text, map(PD.tags, block_pattern))
250 -- Then protect block tags at the line level.
251 text = protect_matches(text, map(PD.tags, line_pattern))
252 -- Protect <hr> and comment tags
253 text = protect_matches(text, {"\n<hr[^>]->[ \t]*\n"})
254 text = protect_matches(text, {"\n<!%-%-.-%-%->[ \t]*\n"})
255 return text
256end
257
258-- Returns true if the string s is a hash resulting from protection
259local function is_protected(s)
260 return PD.blocks[s]
261end
262
263-- Unprotects the specified text by expanding all the nonces
264local function unprotect(text)
265 for k,v in pairs(PD.blocks) do
266 v = v:gsub("%%", "%%%%")
267 text = text:gsub(k, v)
268 end
269 return text
270end
271
272
273----------------------------------------------------------------------
274-- Block transform
275----------------------------------------------------------------------
276
277-- The block transform functions transform the text on the block level.
278-- They work with the text as an array of lines rather than as individual
279-- characters.
280
281-- Returns true if the line is a ruler of (char) characters.
282-- The line must contain at least three char characters and contain only spaces and
283-- char characters.
284local function is_ruler_of(line, char)
285 if not line:match("^[ %" .. char .. "]*$") then return false end
286 if not line:match("%" .. char .. ".*%" .. char .. ".*%" .. char) then return false end
287 return true
288end
289
290-- Identifies the block level formatting present in the line
291local function classify(line)
292 local info = {line = line, text = line}
293
294 if line:match("^ ") then
295 info.type = "indented"
296 info.outdented = line:sub(5)
297 return info
298 end
299
300 for _,c in ipairs({'*', '-', '_', '='}) do
301 if is_ruler_of(line, c) then
302 info.type = "ruler"
303 info.ruler_char = c
304 return info
305 end
306 end
307
308 if line == "" then
309 info.type = "blank"
310 return info
311 end
312
313 if line:match("^(#+)[ \t]*(.-)[ \t]*#*[ \t]*$") then
314 local m1, m2 = line:match("^(#+)[ \t]*(.-)[ \t]*#*[ \t]*$")
315 info.type = "header"
316 info.level = m1:len()
317 info.text = m2
318 return info
319 end
320
321 if line:match("^ ? ? ?(%d+)%.[ \t]+(.+)") then
322 local number, text = line:match("^ ? ? ?(%d+)%.[ \t]+(.+)")
323 info.type = "list_item"
324 info.list_type = "numeric"
325 info.number = 0 + number
326 info.text = text
327 return info
328 end
329
330 if line:match("^ ? ? ?([%*%+%-])[ \t]+(.+)") then
331 local bullet, text = line:match("^ ? ? ?([%*%+%-])[ \t]+(.+)")
332 info.type = "list_item"
333 info.list_type = "bullet"
334 info.bullet = bullet
335 info.text= text
336 return info
337 end
338
339 if line:match("^>[ \t]?(.*)") then
340 info.type = "blockquote"
341 info.text = line:match("^>[ \t]?(.*)")
342 return info
343 end
344
345 if is_protected(line) then
346 info.type = "raw"
347 info.html = unprotect(line)
348 return info
349 end
350
351 info.type = "normal"
352 return info
353end
354
355-- Find headers constisting of a normal line followed by a ruler and converts them to
356-- header entries.
357local function headers(array)
358 local i = 1
359 while i <= #array - 1 do
360 if array[i].type == "normal" and array[i+1].type == "ruler" and
361 (array[i+1].ruler_char == "-" or array[i+1].ruler_char == "=") then
362 local info = {line = array[i].line}
363 info.text = info.line
364 info.type = "header"
365 info.level = iff(array[i+1].ruler_char == "=", 1, 2)
366 table.remove(array, i+1)
367 array[i] = info
368 end
369 i = i + 1
370 end
371 return array
372end
373
374-- Forward declarations
375local block_transform, span_transform, encode_code
376
377-- Convert lines to html code
378local function blocks_to_html(lines, no_paragraphs)
379 local out = {}
380 local i = 1
381 while i <= #lines do
382 local line = lines[i]
383 if line.type == "ruler" then
384 table.insert(out, "<hr/>")
385 elseif line.type == "raw" then
386 table.insert(out, line.html)
387 elseif line.type == "normal" then
388 local s = line.line
389
390 while i+1 <= #lines and lines[i+1].type == "normal" do
391 i = i + 1
392 s = s .. "\n" .. lines[i].line
393 end
394
395 if no_paragraphs then
396 table.insert(out, span_transform(s))
397 else
398 table.insert(out, "<p>" .. span_transform(s) .. "</p>")
399 end
400 elseif line.type == "header" then
401 local s = "<h" .. line.level .. ">" .. span_transform(line.text) .. "</h" .. line.level .. ">"
402 table.insert(out, s)
403 else
404 table.insert(out, line.line)
405 end
406 i = i + 1
407 end
408 return out
409end
410
411-- Find list blocks and convert them to protected data blocks
412local function lists(array, sublist)
413 local function process_list(arr)
414 local function any_blanks(arr)
415 for i = 1, #arr do
416 if arr[i].type == "blank" then return true end
417 end
418 return false
419 end
420
421 local function split_list_items(arr)
422 local acc = {arr[1]}
423 local res = {}
424 for i=2,#arr do
425 if arr[i].type == "list_item" then
426 table.insert(res, acc)
427 acc = {arr[i]}
428 else
429 table.insert(acc, arr[i])
430 end
431 end
432 table.insert(res, acc)
433 return res
434 end
435
436 local function process_list_item(lines, block)
437 while lines[#lines].type == "blank" do
438 table.remove(lines)
439 end
440
441 local itemtext = lines[1].text
442 for i=2,#lines do
443 itemtext = itemtext .. "\n" .. outdent(lines[i].line)
444 end
445 if block then
446 itemtext = block_transform(itemtext, true)
447 if not itemtext:find("<pre>") then itemtext = indent(itemtext) end
448 return " <li>" .. itemtext .. "</li>"
449 else
450 local lines = split(itemtext)
451 lines = map(lines, classify)
452 lines = lists(lines, true)
453 lines = blocks_to_html(lines, true)
454 itemtext = table.concat(lines, "\n")
455 if not itemtext:find("<pre>") then itemtext = indent(itemtext) end
456 return " <li>" .. itemtext .. "</li>"
457 end
458 end
459
460 local block_list = any_blanks(arr)
461 local items = split_list_items(arr)
462 local out = ""
463 for _, item in ipairs(items) do
464 out = out .. process_list_item(item, block_list) .. "\n"
465 end
466 if arr[1].list_type == "numeric" then
467 return "<ol>\n" .. out .. "</ol>"
468 else
469 return "<ul>\n" .. out .. "</ul>"
470 end
471 end
472
473 -- Finds the range of lines composing the first list in the array. A list
474 -- starts with (^ list_item) or (blank list_item) and ends with
475 -- (blank* $) or (blank normal).
476 --
477 -- A sublist can start with just (list_item) does not need a blank...
478 local function find_list(array, sublist)
479 local function find_list_start(array, sublist)
480 if array[1].type == "list_item" then return 1 end
481 if sublist then
482 for i = 1,#array do
483 if array[i].type == "list_item" then return i end
484 end
485 else
486 for i = 1, #array-1 do
487 if array[i].type == "blank" and array[i+1].type == "list_item" then
488 return i+1
489 end
490 end
491 end
492 return nil
493 end
494 local function find_list_end(array, start)
495 local pos = #array
496 for i = start, #array-1 do
497 if array[i].type == "blank" and array[i+1].type ~= "list_item"
498 and array[i+1].type ~= "indented" and array[i+1].type ~= "blank" then
499 pos = i-1
500 break
501 end
502 end
503 while pos > start and array[pos].type == "blank" do
504 pos = pos - 1
505 end
506 return pos
507 end
508
509 local start = find_list_start(array, sublist)
510 if not start then return nil end
511 return start, find_list_end(array, start)
512 end
513
514 while true do
515 local start, stop = find_list(array, sublist)
516 if not start then break end
517 local text = process_list(splice(array, start, stop))
518 local info = {
519 line = text,
520 type = "raw",
521 html = text
522 }
523 array = splice(array, start, stop, {info})
524 end
525
526 -- Convert any remaining list items to normal
527 for _,line in ipairs(array) do
528 if line.type == "list_item" then line.type = "normal" end
529 end
530
531 return array
532end
533
534-- Find and convert blockquote markers.
535local function blockquotes(lines)
536 local function find_blockquote(lines)
537 local start
538 for i,line in ipairs(lines) do
539 if line.type == "blockquote" then
540 start = i
541 break
542 end
543 end
544 if not start then return nil end
545
546 local stop = #lines
547 for i = start+1, #lines do
548 if lines[i].type == "blank" or lines[i].type == "blockquote" then
549 elseif lines[i].type == "normal" then
550 if lines[i-1].type == "blank" then stop = i-1 break end
551 else
552 stop = i-1 break
553 end
554 end
555 while lines[stop].type == "blank" do stop = stop - 1 end
556 return start, stop
557 end
558
559 local function process_blockquote(lines)
560 local raw = lines[1].text
561 for i = 2,#lines do
562 raw = raw .. "\n" .. lines[i].text
563 end
564 local bt = block_transform(raw)
565 if not bt:find("<pre>") then bt = indent(bt) end
566 return "<blockquote>\n " .. bt ..
567 "\n</blockquote>"
568 end
569
570 while true do
571 local start, stop = find_blockquote(lines)
572 if not start then break end
573 local text = process_blockquote(splice(lines, start, stop))
574 local info = {
575 line = text,
576 type = "raw",
577 html = text
578 }
579 lines = splice(lines, start, stop, {info})
580 end
581 return lines
582end
583
584-- Find and convert codeblocks.
585local function codeblocks(lines)
586 local function find_codeblock(lines)
587 local start
588 for i,line in ipairs(lines) do
589 if line.type == "indented" then start = i break end
590 end
591 if not start then return nil end
592
593 local stop = #lines
594 for i = start+1, #lines do
595 if lines[i].type ~= "indented" and lines[i].type ~= "blank" then
596 stop = i-1
597 break
598 end
599 end
600 while lines[stop].type == "blank" do stop = stop - 1 end
601 return start, stop
602 end
603
604 local function process_codeblock(lines)
605 local raw = detab(encode_code(outdent(lines[1].line)))
606 for i = 2,#lines do
607 raw = raw .. "\n" .. detab(encode_code(outdent(lines[i].line)))
608 end
609 return "<pre><code>" .. raw .. "\n</code></pre>"
610 end
611
612 while true do
613 local start, stop = find_codeblock(lines)
614 if not start then break end
615 local text = process_codeblock(splice(lines, start, stop))
616 local info = {
617 line = text,
618 type = "raw",
619 html = text
620 }
621 lines = splice(lines, start, stop, {info})
622 end
623 return lines
624end
625
626-- Perform all the block level transforms
627function block_transform(text, sublist)
628 local lines = split(text)
629 lines = map(lines, classify)
630 lines = headers(lines)
631 lines = lists(lines, sublist)
632 lines = codeblocks(lines)
633 lines = blockquotes(lines)
634 lines = blocks_to_html(lines)
635 local text = table.concat(lines, "\n")
636 return text
637end
638
639----------------------------------------------------------------------
640-- Span transform
641----------------------------------------------------------------------
642
643-- Functions for transforming the text at the span level.
644
645-- These characters may need to be escaped because they have a special
646-- meaning in markdown.
647local escape_chars = "'\\`*_{}[]()>#+-.!'"
648local escape_table = {}
649
650local function init_escape_table()
651 escape_table = {}
652 for i = 1,#escape_chars do
653 local c = escape_chars:sub(i,i)
654 escape_table[c] = hash(c)
655 end
656end
657
658-- Adds a new escape to the escape table.
659local function add_escape(text)
660 if not escape_table[text] then
661 escape_table[text] = hash(text)
662 end
663 return escape_table[text]
664end
665
666-- Encode backspace-escaped characters in the markdown source.
667local function encode_backslash_escapes(t)
668 for i=1,escape_chars:len() do
669 local c = escape_chars:sub(i,i)
670 t = t:gsub("\\%" .. c, escape_table[c])
671 end
672 return t
673end
674
675-- Escape characters that should not be disturbed by markdown.
676local function escape_special_chars(text)
677 local tokens = tokenize_html(text)
678
679 local out = ""
680 for _, token in ipairs(tokens) do
681 local t = token.text
682 if token.type == "tag" then
683 -- In tags, encode * and _ so they don't conflict with their use in markdown.
684 t = t:gsub("%*", escape_table["*"])
685 t = t:gsub("%_", escape_table["_"])
686 else
687 t = encode_backslash_escapes(t)
688 end
689 out = out .. t
690 end
691 return out
692end
693
694-- Unescape characters that have been encoded.
695local function unescape_special_chars(t)
696 local tin = t
697 for k,v in pairs(escape_table) do
698 local mu = k:gsub("%%", "%%%%")
699 t = t:gsub(v,mu)
700 end
701 if t ~= tin then t = unescape_special_chars(t) end
702 return t
703end
704
705-- Encode/escape certain characters inside Markdown code runs.
706-- The point is that in code, these characters are literals,
707-- and lose their special Markdown meanings.
708function encode_code(s)
709 s = s:gsub("%&", "&")
710 s = s:gsub("<", "<")
711 s = s:gsub(">", ">")
712 for k,v in pairs(escape_table) do
713 s = s:gsub("%"..k, v)
714 end
715 return s
716end
717
718-- Handle backtick blocks.
719local function code_spans(s)
720 s = s:gsub("\\\\", escape_table["\\"])
721 s = s:gsub("\\`", escape_table["`"])
722
723 local pos = 1
724 while true do
725 local start, stop = s:find("`+", pos)
726 if not start then return s end
727 local count = stop - start + 1
728 -- Find a matching numbert of backticks
729 local estart, estop = s:find(string.rep("`", count), stop+1)
730 local brstart = s:find("\n", stop+1)
731 if estart and (not brstart or estart < brstart) then
732 local code = s:sub(stop+1, estart-1)
733 code = code:gsub("^[ \t]+", "")
734 code = code:gsub("[ \t]+$", "")
735 code = code:gsub(escape_table["\\"], escape_table["\\"] .. escape_table["\\"])
736 code = code:gsub(escape_table["`"], escape_table["\\"] .. escape_table["`"])
737 code = "<code>" .. encode_code(code) .. "</code>"
738 code = add_escape(code)
739 s = s:sub(1, start-1) .. code .. s:sub(estop+1)
740 pos = start + code:len()
741 else
742 pos = stop + 1
743 end
744 end
745 return s
746end
747
748-- Encode alt text... enodes &, and ".
749local function encode_alt(s)
750 if not s then return s end
751 s = s:gsub('&', '&')
752 s = s:gsub('"', '"')
753 s = s:gsub('<', '<')
754 return s
755end
756
757-- Forward declaration for link_db as returned by strip_link_definitions.
758local link_database
759
760-- Handle image references
761local function images(text)
762 local function reference_link(alt, id)
763 alt = encode_alt(alt:match("%b[]"):sub(2,-2))
764 id = id:match("%[(.*)%]"):lower()
765 if id == "" then id = text:lower() end
766 link_database[id] = link_database[id] or {}
767 if not link_database[id].url then return nil end
768 local url = link_database[id].url or id
769 url = encode_alt(url)
770 local title = encode_alt(link_database[id].title)
771 if title then title = " title=\"" .. title .. "\"" else title = "" end
772 return add_escape ('<img src="' .. url .. '" alt="' .. alt .. '"' .. title .. "/>")
773 end
774
775 local function inline_link(alt, link)
776 alt = encode_alt(alt:match("%b[]"):sub(2,-2))
777 local url, title = link:match("%(<?(.-)>?[ \t]*['\"](.+)['\"]")
778 url = url or link:match("%(<?(.-)>?%)")
779 url = encode_alt(url)
780 title = encode_alt(title)
781 if title then
782 return add_escape('<img src="' .. url .. '" alt="' .. alt .. '" title="' .. title .. '"/>')
783 else
784 return add_escape('<img src="' .. url .. '" alt="' .. alt .. '"/>')
785 end
786 end
787
788 text = text:gsub("!(%b[])[ \t]*\n?[ \t]*(%b[])", reference_link)
789 text = text:gsub("!(%b[])(%b())", inline_link)
790 return text
791end
792
793-- Handle anchor references
794local function anchors(text)
795 local function reference_link(text, id)
796 text = text:match("%b[]"):sub(2,-2)
797 id = id:match("%b[]"):sub(2,-2):lower()
798 if id == "" then id = text:lower() end
799 link_database[id] = link_database[id] or {}
800 if not link_database[id].url then return nil end
801 local url = link_database[id].url or id
802 url = encode_alt(url)
803 local title = encode_alt(link_database[id].title)
804 if title then title = " title=\"" .. title .. "\"" else title = "" end
805 return add_escape("<a href=\"" .. url .. "\"" .. title .. ">") .. text .. add_escape("</a>")
806 end
807
808 local function inline_link(text, link)
809 text = text:match("%b[]"):sub(2,-2)
810 local url, title = link:match("%(<?(.-)>?[ \t]*['\"](.+)['\"]")
811 title = encode_alt(title)
812 url = url or link:match("%(<?(.-)>?%)") or ""
813 url = encode_alt(url)
814 if title then
815 return add_escape("<a href=\"" .. url .. "\" title=\"" .. title .. "\">") .. text .. "</a>"
816 else
817 return add_escape("<a href=\"" .. url .. "\">") .. text .. add_escape("</a>")
818 end
819 end
820
821 text = text:gsub("(%b[])[ \t]*\n?[ \t]*(%b[])", reference_link)
822 text = text:gsub("(%b[])(%b())", inline_link)
823 return text
824end
825
826-- Handle auto links, i.e. <http://www.google.com/>.
827local function auto_links(text)
828 local function link(s)
829 return add_escape("<a href=\"" .. s .. "\">") .. s .. "</a>"
830 end
831 -- Encode chars as a mix of dec and hex entitites to (perhaps) fool
832 -- spambots.
833 local function encode_email_address(s)
834 -- Use a deterministic encoding to make unit testing possible.
835 -- Code 45% hex, 45% dec, 10% plain.
836 local hex = {code = function(c) return "&#x" .. string.format("%x", c:byte()) .. ";" end, count = 1, rate = 0.45}
837 local dec = {code = function(c) return "&#" .. c:byte() .. ";" end, count = 0, rate = 0.45}
838 local plain = {code = function(c) return c end, count = 0, rate = 0.1}
839 local codes = {hex, dec, plain}
840 local function swap(t,k1,k2) local temp = t[k2] t[k2] = t[k1] t[k1] = temp end
841
842 local out = ""
843 for i = 1,s:len() do
844 for _,code in ipairs(codes) do code.count = code.count + code.rate end
845 if codes[1].count < codes[2].count then swap(codes,1,2) end
846 if codes[2].count < codes[3].count then swap(codes,2,3) end
847 if codes[1].count < codes[2].count then swap(codes,1,2) end
848
849 local code = codes[1]
850 local c = s:sub(i,i)
851 -- Force encoding of "@" to make email address more invisible.
852 if c == "@" and code == plain then code = codes[2] end
853 out = out .. code.code(c)
854 code.count = code.count - 1
855 end
856 return out
857 end
858 local function mail(s)
859 s = unescape_special_chars(s)
860 local address = encode_email_address("mailto:" .. s)
861 local text = encode_email_address(s)
862 return add_escape("<a href=\"" .. address .. "\">") .. text .. "</a>"
863 end
864 -- links
865 text = text:gsub("<(https?:[^'\">%s]+)>", link)
866 text = text:gsub("<(ftp:[^'\">%s]+)>", link)
867
868 -- mail
869 text = text:gsub("<mailto:([^'\">%s]+)>", mail)
870 text = text:gsub("<([-.%w]+%@[-.%w]+)>", mail)
871 return text
872end
873
874-- Encode free standing amps (&) and angles (<)... note that this does not
875-- encode free >.
876local function amps_and_angles(s)
877 -- encode amps not part of &..; expression
878 local pos = 1
879 while true do
880 local amp = s:find("&", pos)
881 if not amp then break end
882 local semi = s:find(";", amp+1)
883 local stop = s:find("[ \t\n&]", amp+1)
884 if not semi or (stop and stop < semi) or (semi - amp) > 15 then
885 s = s:sub(1,amp-1) .. "&" .. s:sub(amp+1)
886 pos = amp+1
887 else
888 pos = amp+1
889 end
890 end
891
892 -- encode naked <'s
893 s = s:gsub("<([^a-zA-Z/?$!])", "<%1")
894 s = s:gsub("<$", "<")
895
896 -- what about >, nothing done in the original markdown source to handle them
897 return s
898end
899
900-- Handles emphasis markers (* and _) in the text.
901local function emphasis(text)
902 for _, s in ipairs {"%*%*", "%_%_"} do
903 text = text:gsub(s .. "([^%s][%*%_]?)" .. s, "<strong>%1</strong>")
904 text = text:gsub(s .. "([^%s][^<>]-[^%s][%*%_]?)" .. s, "<strong>%1</strong>")
905 end
906 for _, s in ipairs {"%*", "%_"} do
907 text = text:gsub(s .. "([^%s_])" .. s, "<em>%1</em>")
908 text = text:gsub(s .. "(<strong>[^%s_]</strong>)" .. s, "<em>%1</em>")
909 text = text:gsub(s .. "([^%s_][^<>_]-[^%s_])" .. s, "<em>%1</em>")
910 text = text:gsub(s .. "([^<>_]-<strong>[^<>_]-</strong>[^<>_]-)" .. s, "<em>%1</em>")
911 end
912 return text
913end
914
915-- Handles line break markers in the text.
916local function line_breaks(text)
917 return text:gsub(" +\n", " <br/>\n")
918end
919
920-- Perform all span level transforms.
921function span_transform(text)
922 text = code_spans(text)
923 text = escape_special_chars(text)
924 text = images(text)
925 text = anchors(text)
926 text = auto_links(text)
927 text = amps_and_angles(text)
928 text = emphasis(text)
929 text = line_breaks(text)
930 return text
931end
932
933----------------------------------------------------------------------
934-- Markdown
935----------------------------------------------------------------------
936
937-- Cleanup the text by normalizing some possible variations to make further
938-- processing easier.
939local function cleanup(text)
940 -- Standardize line endings
941 text = text:gsub("\r\n", "\n") -- DOS to UNIX
942 text = text:gsub("\r", "\n") -- Mac to UNIX
943
944 -- Convert all tabs to spaces
945 text = detab(text)
946
947 -- Strip lines with only spaces and tabs
948 while true do
949 local subs
950 text, subs = text:gsub("\n[ \t]+\n", "\n\n")
951 if subs == 0 then break end
952 end
953
954 return "\n" .. text .. "\n"
955end
956
957-- Strips link definitions from the text and stores the data in a lookup table.
958local function strip_link_definitions(text)
959 local linkdb = {}
960
961 local function link_def(id, url, title)
962 id = id:match("%[(.+)%]"):lower()
963 linkdb[id] = linkdb[id] or {}
964 linkdb[id].url = url or linkdb[id].url
965 linkdb[id].title = title or linkdb[id].title
966 return ""
967 end
968
969 local def_no_title = "\n ? ? ?(%b[]):[ \t]*\n?[ \t]*<?([^%s>]+)>?[ \t]*"
970 local def_title1 = def_no_title .. "[ \t]+\n?[ \t]*[\"'(]([^\n]+)[\"')][ \t]*"
971 local def_title2 = def_no_title .. "[ \t]*\n[ \t]*[\"'(]([^\n]+)[\"')][ \t]*"
972 local def_title3 = def_no_title .. "[ \t]*\n?[ \t]+[\"'(]([^\n]+)[\"')][ \t]*"
973
974 text = text:gsub(def_title1, link_def)
975 text = text:gsub(def_title2, link_def)
976 text = text:gsub(def_title3, link_def)
977 text = text:gsub(def_no_title, link_def)
978 return text, linkdb
979end
980
981-- Main markdown processing function
982local function markdown(text)
983 init_hash(text)
984 init_escape_table()
985
986 text = cleanup(text)
987 text = protect(text)
988 text, link_database = strip_link_definitions(text)
989 text = block_transform(text)
990 text = unescape_special_chars(text)
991 return text
992end
993
994----------------------------------------------------------------------
995-- End of module
996----------------------------------------------------------------------
997
998-- For compatibility, set markdown function as a global
999_G.markdown = markdown
1000
1001-- Class for parsing command-line options
1002local OptionParser = {}
1003OptionParser.__index = OptionParser
1004
1005-- Creates a new option parser
1006function OptionParser:new()
1007 local o = {short = {}, long = {}}
1008 setmetatable(o, self)
1009 return o
1010end
1011
1012-- Calls f() whenever a flag with specified short and long name is encountered
1013function OptionParser:flag(short, long, f)
1014 local info = {type = "flag", f = f}
1015 if short then self.short[short] = info end
1016 if long then self.long[long] = info end
1017end
1018
1019-- Calls f(param) whenever a parameter flag with specified short and long name is encountered
1020function OptionParser:param(short, long, f)
1021 local info = {type = "param", f = f}
1022 if short then self.short[short] = info end
1023 if long then self.long[long] = info end
1024end
1025
1026-- Calls f(v) for each non-flag argument
1027function OptionParser:arg(f)
1028 self.arg = f
1029end
1030
1031-- Runs the option parser for the specified set of arguments. Returns true if all arguments
1032-- where successfully parsed and false otherwise.
1033function OptionParser:run(args)
1034 local pos = 1
1035 while pos <= #args do
1036 local arg = args[pos]
1037 if arg == "--" then
1038 for i=pos+1,#args do
1039 if self.arg then self.arg(args[i]) end
1040 return true
1041 end
1042 end
1043 if arg:match("^%-%-") then
1044 local info = self.long[arg:sub(3)]
1045 if not info then print("Unknown flag: " .. arg) return false end
1046 if info.type == "flag" then
1047 info.f()
1048 pos = pos + 1
1049 else
1050 local param = args[pos+1]
1051 if not param then print("No parameter for flag: " .. arg) return false end
1052 info.f(param)
1053 pos = pos+2
1054 end
1055 elseif arg:match("^%-") then
1056 for i=2,arg:len() do
1057 local c = arg:sub(i,i)
1058 local info = self.short[c]
1059 if not info then print("Unknown flag: -" .. c) return false end
1060 if info.type == "flag" then
1061 info.f()
1062 else
1063 if i == arg:len() then
1064 local param = args[pos+1]
1065 if not param then print("No parameter for flag: -" .. c) return false end
1066 info.f(param)
1067 pos = pos + 1
1068 else
1069 local param = arg:sub(i+1)
1070 info.f(param)
1071 end
1072 break
1073 end
1074 end
1075 pos = pos + 1
1076 else
1077 if self.arg then self.arg(arg) end
1078 pos = pos + 1
1079 end
1080 end
1081 return true
1082end
1083
1084local function read_file(path, descr)
1085 local file = io.open(path) or error("Could not open " .. descr .. " file: " .. path)
1086 local contents = file:read("*a") or error("Could not read " .. descr .. " from " .. path)
1087 file:close()
1088 return contents
1089end
1090
1091-- Handles the case when markdown is run from the command line
1092local function run_command_line(arg)
1093 -- Generate output for input s given options
1094 local function run(s, options)
1095 s = markdown(s)
1096 if not options.wrap_header then return s end
1097 local header
1098 if options.header then
1099 header = read_file(options.header, "header")
1100 else
1101 header = [[
1102<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
1103<html>
1104<head>
1105 <meta http-equiv="content-type" content="text/html; charset=CHARSET" />
1106 <title>TITLE</title>
1107 <link rel="stylesheet" type="text/css" href="STYLESHEET" />
1108</head>
1109<body>
1110]]
1111 local title = options.title or s:match("<h1>(.-)</h1>") or s:match("<h2>(.-)</h2>") or
1112 s:match("<h3>(.-)</h3>") or "Untitled"
1113 header = header:gsub("TITLE", title)
1114 if options.inline_style then
1115 local style = read_file(options.stylesheet, "style sheet")
1116 header = header:gsub('<link rel="stylesheet" type="text/css" href="STYLESHEET" />',
1117 "<style type=\"text/css\"><!--\n" .. style .. "\n--></style>")
1118 else
1119 header = header:gsub("STYLESHEET", options.stylesheet)
1120 end
1121 header = header:gsub("CHARSET", options.charset)
1122 end
1123 local footer = "</body></html>"
1124 if options.footer then
1125 footer = read_file(options.footer, "footer")
1126 end
1127 return header .. s .. footer
1128 end
1129
1130 -- Generate output path name from input path name given options.
1131 local function outpath(path, options)
1132 if options.append then return path .. ".html" end
1133 local m = path:match("^(.+%.html)[^/\\]+$") if m then return m end
1134 m = path:match("^(.+%.)[^/\\]*$") if m and path ~= m .. "html" then return m .. "html" end
1135 return path .. ".html"
1136 end
1137
1138 -- Default commandline options
1139 local options = {
1140 wrap_header = true,
1141 header = nil,
1142 footer = nil,
1143 charset = "utf-8",
1144 title = nil,
1145 stylesheet = "default.css",
1146 inline_style = false
1147 }
1148 local help = [[
1149Usage: markdown.lua [OPTION] [FILE]
1150Runs the markdown text markup to HTML converter on each file specified on the
1151command line. If no files are specified, runs on standard input.
1152
1153No header:
1154 -n, --no-wrap Don't wrap the output in <html>... tags.
1155Custom header:
1156 -e, --header FILE Use content of FILE for header.
1157 -f, --footer FILE Use content of FILE for footer.
1158Generated header:
1159 -c, --charset SET Specifies charset (default utf-8).
1160 -i, --title TITLE Specifies title (default from first <h1> tag).
1161 -s, --style STYLE Specifies style sheet file (default default.css).
1162 -l, --inline-style Include the style sheet file inline in the header.
1163Generated files:
1164 -a, --append Append .html extension (instead of replacing).
1165Other options:
1166 -h, --help Print this help text.
1167 -t, --test Run the unit tests.
1168]]
1169
1170 local run_stdin = true
1171 local op = OptionParser:new()
1172 op:flag("n", "no-wrap", function () options.wrap_header = false end)
1173 op:param("e", "header", function (x) options.header = x end)
1174 op:param("f", "footer", function (x) options.footer = x end)
1175 op:param("c", "charset", function (x) options.charset = x end)
1176 op:param("i", "title", function(x) options.title = x end)
1177 op:param("s", "style", function(x) options.stylesheet = x end)
1178 op:flag("l", "inline-style", function() options.inline_style = true end)
1179 op:flag("a", "append", function() options.append = true end)
1180 op:flag("t", "test", function()
1181 local n = arg[0]:gsub("markdown%.lua", "markdown-tests.lua")
1182 local f = io.open(n)
1183 if f then
1184 f:close()
1185 package.loaded.markdown = markdown
1186 dofile(n)
1187 else
1188 error("Cannot find markdown-tests.lua")
1189 end
1190 run_stdin = false
1191 end)
1192 op:flag("h", "help", function() print(help) run_stdin = false end)
1193 op:arg(function(path)
1194 local s = read_file(path, "input")
1195 s = run(s, options)
1196 local file = io.open(outpath(path, options), "w") or error("Could not open output file: " .. outpath(path, options))
1197 file:write(s)
1198 file:close()
1199 run_stdin = false
1200 end
1201 )
1202
1203 if not op:run(arg) then
1204 print(help)
1205 run_stdin = false
1206 end
1207
1208 if run_stdin then
1209 local s = io.read("*a")
1210 s = run(s, options)
1211 io.write(s)
1212 end
1213end
1214
1215-- If we are being run from the command-line, act accordingly
1216if arg and arg[0]:find("markdown%.lua$") then
1217 run_command_line(arg)
1218else
1219 return markdown
1220end