diff --git a/spec/System/TestCommon_spec.lua b/spec/System/TestCommon_spec.lua index 4ff1906d83..827f07cf86 100644 --- a/spec/System/TestCommon_spec.lua +++ b/spec/System/TestCommon_spec.lua @@ -93,4 +93,22 @@ describe("Common", function() common.classes.StupidClass = nil end) end) + it("WrapString wraps before the word that overflows the width", function() + -- Count visible characters so widths are character counts + local drawStringWidth = _G.DrawStringWidth + _G.DrawStringWidth = function(height, font, text) + return #StripEscapes(text) + end + finally(function() + _G.DrawStringWidth = drawStringWidth + end) + local function wrap(str, width) + return copyTable(main:WrapString(str, 16, width)) + end + + assert.are.same({ "aa bb", "cc dd" }, wrap("aa bb cc dd", 5)) + assert.are.same({ "abc", "de" }, wrap("abc de", 3)) + assert.are.same({ "^7abcd", "^xFF0000efgh", "ij" }, wrap("^7abcd ^xFF0000efgh ij", 4)) + assert.are.same({ "abcdefgh", "xy" }, wrap("abcdefgh xy", 3)) + end) end) \ No newline at end of file diff --git a/src/Modules/Main.lua b/src/Modules/Main.lua index 91e220c78b..7244391686 100644 --- a/src/Modules/Main.lua +++ b/src/Modules/Main.lua @@ -1811,24 +1811,20 @@ do local wrapTable = { } function main:WrapString(str, height, width) wipeTable(wrapTable) - local lineStart = 1 - local lastSpace, lastBreak + local lineStart, searchFrom = 1, 1 + local previousWordEnd while true do - local s, e = str:find("%s+", lastSpace) - if not s then - s = #str + 1 - e = #str + 1 + local spaceStart, spaceEnd = str:find("%s+", searchFrom) + local wordEnd = spaceStart and spaceStart - 1 or #str + if previousWordEnd and previousWordEnd >= lineStart and DrawStringWidth(height, "VAR", str:sub(lineStart, wordEnd)) > width then + t_insert(wrapTable, str:sub(lineStart, previousWordEnd)) + lineStart = searchFrom end - if s > #str then - t_insert(wrapTable, str:sub(lineStart, -1)) + if not spaceStart or spaceEnd == #str then + t_insert(wrapTable, str:sub(lineStart, wordEnd)) break end - lastBreak = s - 1 - lastSpace = e + 1 - if DrawStringWidth(height, "VAR", str:sub(lineStart, s - 1)) > width then - t_insert(wrapTable, str:sub(lineStart, lastBreak)) - lineStart = lastSpace - end + previousWordEnd, searchFrom = wordEnd, spaceEnd + 1 end return wrapTable end