From f49d6aac7fec91f865c0638e698f43db4bafa3ce Mon Sep 17 00:00:00 2001 From: David Medgyesy Date: Fri, 27 Nov 2026 11:55:51 +0100 Subject: [PATCH] Fix WrapString leaving lines wider than the limit The word that pushed a line over the width stayed on that line, and an overlong last line was never wrapped. The line now breaks before the overflowing word. --- spec/System/TestCommon_spec.lua | 18 ++++++++++++++++++ src/Modules/Main.lua | 24 ++++++++++-------------- 2 files changed, 28 insertions(+), 14 deletions(-) diff --git a/spec/System/TestCommon_spec.lua b/spec/System/TestCommon_spec.lua index 4ff1906d83c..827f07cf869 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 91e220c78b0..72443916863 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