From efd4a8a88371df065212e80c4a1264140b433693 Mon Sep 17 00:00:00 2001 From: "Kartik K. Agaram" Date: Tue, 19 Jul 2022 16:49:08 -0700 Subject: keep text from overflowing right margin I've been sloppy about this so far, and outside of tests I can't find any examples where it matters, but it matters in a potential fork where I'm rendering multiple columns of text. It's unfortunate that my tests have this level of brittleness. What I'd really like to assert in many of these changed lines is that the text stays inside the margins and that more text would overflow margins. --- text.lua | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) (limited to 'text.lua') diff --git a/text.lua b/text.lua index e28a9dc..fdf2418 100644 --- a/text.lua +++ b/text.lua @@ -807,21 +807,23 @@ function Text.nearest_cursor_pos(line, x, left) assert(false) end -function Text.nearest_pos_less_than(line, x) -- x DOES NOT include left margin +-- return the nearest index of line (in utf8 code points) which lies entirely +-- within x pixels of the left margin +function Text.nearest_pos_less_than(line, x) +--? print('-- nearest_pos_less_than', line, x) if x == 0 then return 1 end local len = utf8.len(line) - local max_x = Text.x(line, len+1) + local max_x = Text.x_after(line, len) if x > max_x then return len+1 end local left, right = 1, len+1 ---? print('--') while true do local curr = math.floor((left+right)/2) - local currxmin = Text.x(line, curr+1) - local currxmax = Text.x(line, curr+2) + local currxmin = Text.x_after(line, curr+1) + local currxmax = Text.x_after(line, curr+2) --? print(x, left, right, curr, currxmin, currxmax) if currxmin <= x and x < currxmax then return curr @@ -838,6 +840,14 @@ function Text.nearest_pos_less_than(line, x) -- x DOES NOT include left margin assert(false) end +function Text.x_after(s, pos) + local offset = Text.offset(s, math.min(pos+1, #s+1)) + local s_before = s:sub(1, offset-1) +--? print('^'..s_before..'$') + local text_before = App.newText(love.graphics.getFont(), s_before) + return App.width(text_before) +end + function Text.x(s, pos) local offset = Text.offset(s, pos) local s_before = s:sub(1, offset-1) -- cgit 1.4.1-2-gfad0