title: Standards describing how navigation is handled in non-monospace text?
body: <p>For a recent project I've been working on a simple word processor, and because I need fine-grained control have had to implement a lot of the <a href="https://harfbuzz.github.io/what-is-harfbuzz.html" rel="nofollow noreferrer">text shaping</a> myself. Most of this is fairly straight-forward and described in detail places like <a href="https://www.w3.org/International/articles/typography/linebreak.en" rel="nofollow noreferrer">here</a> and <a href="https://en.wikipedia.org/wiki/Line_wrap_and_word_wrap" rel="nofollow noreferrer">here</a>.</p>
  <p>It's less obvious how to handle pressing down or up on the keyboard when dealing with non-monospaced text split across many lines. In monospaced text the algorithm is simple: move the text caret down one line and the same number of characters to the right that it was. But what about variable-width fonts? I've tried an algorithm like this (in pseudocode):</p>
  <pre><code>; Return text offset into next line after navigating down
  function moveCaretDown():
    Move text caret to start of next line
    targetPixelOffset := previous pixel offset of caret in line above
    textOffsetIntoLine := 0
    pixelOffsetIntoLine := 0
    prevDelta := Infinity
  
    for each char in text of new line:
      delta = abs(pixelOffsetIntoLine - targetPixelOffset)
  
      ; We are now further from the desired cursor offset than before, this must
      ; be closest slot to the caret's previous horizontal offset in this line.
      if (delta &gt; prevDelta):
        return textOffsetIntoLine - 1
  
      prevDelta = delta
      pixelOffsetIntoLine += measureWidth(char)
      currentOffset++
  
    ; Else return the offset of the last character in the line
    return length of newline - 1
  </code></pre>
  <p>But I've found its behavior differs from text inputs in major web browsers and/or text editors (I can come up with some specific examples if needed). Is there some standard algorithm for this used by GUI toolkits or text shaping libraries? I was surprised I couldn't find a W3C standard on it, for example, considering this is behavior needed in every web browser.</p>
  <p><sub>* Inserting line breaks into a string at the correct places, handling ragged or fully-justified text, etc.</sub></p>