From b5ab9445882ece8bf0c384d7a9314753b9557bd7 Mon Sep 17 00:00:00 2001 From: Philipp Gesang Date: Tue, 14 Sep 2010 17:18:39 +0200 Subject: output formatting. includes paragraph reflowing --- rst_helpers.lua | 40 ++++++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) (limited to 'rst_helpers.lua') diff --git a/rst_helpers.lua b/rst_helpers.lua index b30370a..f7eb950 100644 --- a/rst_helpers.lua +++ b/rst_helpers.lua @@ -29,10 +29,10 @@ end --helpers.dbg_write = dbg_write local dbg_write = helpers.dbg_writef -local patterns = {} +helpers.patterns = {} do - local p = patterns + local p = helpers.patterns p.dash = P"-" p.equals = P"=" p.plus = P"+" @@ -701,5 +701,41 @@ do helpers.list.successor = suc end +helpers.string = {} + +do + -- This grammar inside the function is slightly faster than the same as an upvalue + -- with the value of “width” repeatedly given via lpeg.Carg(). This holds + -- for repeated calls as well. + local ulen = utf.len + function helpers.string.wrapat (str, width) + local linelength = 0 + local wrap = P{ + [1] = "wrapper", + + wrapper = Cs(V"nowhitespace"^0 * (Cs(V"wrapme") + V"other")^1), + whitespace = S" \t\v" + P"\n" / function() linelength = 0 end, + nowhitespace = 1 - V"whitespace", + ignore = P"\\type{" * (1 - P"}")^1 * P"}", + other = Cmt(V"whitespace"^1 * (V"ignore" + (1 - V"whitespace")^1), function(s,i,w) + linelength = linelength + ulen(w) + return true + end), + wrapme = Cmt(V"whitespace"^1 * (1 - V"whitespace" - V"ignore")^1, function(s,i,w) + local lw = ulen(w) + if linelength + lw > width then + linelength = lw + return true + end + return false + --end) / function (word) return "\n" .. match(V"whitespace"^1 * C((1 - V"whitespace")^1), word) end, + end) / function (word) return "\n" .. word:match("[^%s]+") end, + } + + local reflowed = wrap:match(str) + return reflowed + end +end + return helpers -- cgit v1.2.3