stb icon indicating copy to clipboard operation
stb copied to clipboard

stb_textedit: fix find_charpos for n == z to make cursor move correctly when pressing up

Open blackedout01 opened this issue 1 year ago • 0 comments

Previously, when the cursor was at the very end of the text in multiline mode (no trailing newline), pressing the up key did either nothing or set the character to the start of the same line.

This is because in this specific case (multiline mode, n == z) stb_textedit_find_charpos returned a strange find result with the found line being the next one (non existent) and the previous line being the actual line of the cursor. So when the following code searched for a character in the "previous" line it really searched in the current one. With preferred_x, nothing happened (it found the same cursor position), without preferred_x it searched for the character in the "current" line (where x is 0), so the character got set to the start of the line.

I think the whole n == z check can be removed if the layout row loop breaking condition is modified.

With this change in single line mode, stb_textedit_find_charpos returns the same result if two conditions are met:

  • r.num_chars == z (causing the layout row loop to break immediately)
  • r.x1 == r.x0 + sum(STB_TEXTEDIT_GETWIDTH(str, 0, i) for i in [0, n-1])

I assume both of these should be true.

With this change multiline mode, stb_textedit_find_charpos returns a very differnt result, but this is desired and more consistent with the result for the rest of the characters in the last row.

The upside of this change is that it fixes the issue and makes the code shorter, the downside is that the loop condition is a bit more complex and that the found line is scanned for the character position instead of just returning r.x1 (like previously in single line mode).

blackedout01 avatar Oct 03 '24 11:10 blackedout01