From 756d30416db1ea31b907ec40a337427d77d28e7a Mon Sep 17 00:00:00 2001 From: rxi Date: Sat, 10 Jan 2015 20:26:19 +0000 Subject: [PATCH] Added lume.wordwrap(); updated README.md and tests --- README.md | 9 +++++++++ lume.lua | 26 ++++++++++++++++++++++++++ test/test_lume.lua | 10 ++++++++++ 3 files changed, 45 insertions(+) diff --git a/README.md b/README.md index 06c3ada..b8035e1 100644 --- a/README.md +++ b/README.md @@ -316,6 +316,15 @@ instead of whitespace. lume.trim(" Hello ") -- Returns "Hello" ``` +### lume.wordwrap(str [, limit]) +Returns `str` wrapped to `limit` number of characters per line, by default +`limit` is `72`. `limit` can also be a function which when passed a string, +returns `true` if it is too long for a single line. +```lua +-- Returns "Hello world\nThis is a\nshort string" +lume.wordwrap("Hello world. This is a short string", 14) +``` + ### lume.format(str [, vars]) Returns a formatted string. The values of keys in the table `vars` can be inserted into the string by using the form `"{key}"` in `str`; numerical keys diff --git a/lume.lua b/lume.lua index 14b478c..f9a52b4 100644 --- a/lume.lua +++ b/lume.lua @@ -480,6 +480,32 @@ function lume.trim(str, chars) end +function lume.wordwrap(str, limit) + limit = limit or 72 + local check + if type(limit) == "number" then + check = function(str) return #str >= limit end + else + check = limit + end + local rtn = {} + for j, line in ipairs(lume.split(str, "\n")) do + local str + for i, word in ipairs(lume.split(line)) do + local s = (str and (str .. " ") or "") .. word + if check(s) then + rtn[#rtn + 1] = str + str = word + else + str = s + end + end + rtn[#rtn + 1] = str + end + return table.concat(rtn, "\n") +end + + function lume.format(str, vars) if not vars then return str end local f = function(x) diff --git a/test/test_lume.lua b/test/test_lume.lua index ddaf11c..805351e 100644 --- a/test/test_lume.lua +++ b/test/test_lume.lua @@ -431,6 +431,16 @@ tests["lume.trim"] = function() testeq( lume.trim("^.hello world]^", "^.]"), "hello world" ) end +-- lume.wordwrap +tests["lume.wordwrap"] = function() + local str = "A small string with some words and then some more words" + local b = "A small string with\nsome words and then\nsome more words" + local fn = function(str) return #str >= 20 end + testeq( lume.wordwrap(str), str ) + testeq( lume.wordwrap(str, 20), b ) + testeq( lume.wordwrap(str, fn), b ) +end + -- lume.format tests["lume.format"] = function() local str = lume.format("a {a} in a {b}", {a = "mouse", b = "house"})