summaryrefslogtreecommitdiff
path: root/xmake/core/base/cli.lua
diff options
context:
space:
mode:
authorOpportunity <[email protected]>2020-01-16 00:35:46 +0800
committerOpportunity <[email protected]>2020-01-16 00:35:46 +0800
commitd72f0495c5a8b860e7abed729f0d874542653066 (patch)
tree634eab84b3f7188ee278d202fa09299cb97e3a8b /xmake/core/base/cli.lua
parentb18e975c2791c308499371173da11cbfa5297650 (diff)
show
Diffstat (limited to 'xmake/core/base/cli.lua')
-rw-r--r--xmake/core/base/cli.lua72
1 files changed, 72 insertions, 0 deletions
diff --git a/xmake/core/base/cli.lua b/xmake/core/base/cli.lua
index 310335fd4..9ce43500b 100644
--- a/xmake/core/base/cli.lua
+++ b/xmake/core/base/cli.lua
@@ -117,6 +117,78 @@ function cli.parsev(argv, flags)
return parsed
end
+-- @see https://unicode.org/reports/tr14/
+function cli._lastwbr(str, width, wordbreak)
+
+ -- check
+ assert(#str >= width)
+
+ if wordbreak == "breakall" then
+ -- To prevent overflow, word may be broken at any character
+ return width
+ else
+
+ if str:sub(width + 1, width + 1):find("[%s]") then
+ -- exact break
+ return width
+ end
+
+ local range = str:sub(1, width)
+ local poss = range:reverse():find("[%s-]")
+ if poss then
+ return #range - poss + 1
+ end
+
+ -- not found in range, try afterwards
+ poss = str:find("[%s-]", width + 1)
+ if poss then
+ return poss
+ end
+
+ -- not found in all str
+ return #str
+ end
+end
+
+-- break lines
+function cli.wordwrap(str, width, opt)
+
+ opt = opt or {}
+
+ -- split to lines
+ if type(str) == 'table' then
+ str = table.concat(str, '\n')
+ end
+ local lines = tostring(str):split('\n', {plain = true, strict = true})
+
+ local result = {}
+ -- handle lines
+ for _, v in ipairs(lines) do
+
+ -- remove tailing spaces, include '\r', which will be produced by `('l1\r\nl2'):split(...)`
+ v = v:rtrim()
+ while #v > width do
+
+ -- find word break chance
+ local wbr = cli._lastwbr(v, width, opt.wordbreak)
+
+ -- break line
+ local line = v:sub(1, wbr):rtrim()
+ table.insert(result, line)
+ v = v:sub(wbr + 1):ltrim()
+
+ -- prevent empty line
+ if #v == 0 then v = nil end
+ end
+
+ -- put remaining parts
+ table.insert(result, v)
+ end
+
+ -- ok
+ return result
+end
+
cli._segment = segment
-- return module
return cli