From 544af1841ff27421aa241481566fa46edc7067e9 Mon Sep 17 00:00:00 2001 From: Izaya Date: Sun, 17 Jun 2018 15:17:59 +1000 Subject: [PATCH] import lib and test --- mdparse.lua | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++ mdptest.lua | 13 ++++++++++ 2 files changed, 88 insertions(+) create mode 100644 mdparse.lua create mode 100644 mdptest.lua diff --git a/mdparse.lua b/mdparse.lua new file mode 100644 index 0000000..be2bc9a --- /dev/null +++ b/mdparse.lua @@ -0,0 +1,75 @@ +local md = {} + +function md.parse(md) + local it = {} + it.l = {} + it[#it+1] = {["content"]="",["bold"]=false,["italic"]=false} + local lc,llc = "","" + local function newpart() + it[#it+1] = {["content"]=""} + end + newpart() + local lm = false + for c in md:gmatch(".") do + if c == "[" then + newpart() + elseif c == "(" and lc == "]" then + lm = true + it[#it].content = it[#it].content:sub(1,-2) + it[#it].address = "" + elseif c == ")" and lm then + lm = false + it.l[#it.l+1] = it[#it].address + it[#it].addrid = #it.l + newpart() + elseif c == "\n" and lc == "\n" then + newpart() + it[#it].content = "\n\n" + newpart() + else + if not lm then + it[#it].content = it[#it].content .. c + else + it[#it].address = it[#it].address .. c + end + end + llc = lc + lc = c + end + return it +end + +function md.reflow(text,len) + local words, lines, links = {}, {""}, {} + for k,v in ipairs(md.parse(text)) do + if v.content == "\n\n" then + words[#words+1] = {"\n\n"} + elseif not v.address then + for word in v.content:gmatch("%S+") do + words[#words+1] = {word} + end + else + words[#words+1] = {v.content,v.address} + end + end + for k,v in pairs(words) do + if v[2] then + if lines[#lines]:len()+v[1]:len()+2 > len then + lines[#lines+1] = "" + end + links[#links+1] = {#lines, lines[#lines]:len()+1, v[2]} + lines[#lines] = lines[#lines] .. "<"..v[1].."> " + elseif v[1] == "\n\n" then + lines[#lines+1] = "" + lines[#lines+1] = "" + else + if lines[#lines]:len()+v[1]:len() > len then + lines[#lines+1] = "" + end + lines[#lines] = lines[#lines] .. v[1].." " + end + end + return lines, links +end + +return md diff --git a/mdptest.lua b/mdptest.lua new file mode 100644 index 0000000..285534e --- /dev/null +++ b/mdptest.lua @@ -0,0 +1,13 @@ +local md = require "mdparse" +teststr = [[This is a test markdown string. It contains formatting including bold and italics, and [links](somewhere else) too. + +Here is a paragraph break, I suppose. + +Here's another. ]] + +lines, links = md.reflow(teststr, 40) +print("0\t"..("1234567890"):rep(4)) +for k,v in pairs(lines) do print(k,v) end + +print("\nLinks:") +for k,v in pairs(links) do print(k,v[1], v[2], v[3]) end