20 Jan 2013



One of the toughest problems I faced when I built Notepad Classic was an issue where many functions like Go To & Find were always off a few characters. After a bit of experimenting I noticed a pattern, it was off by the number of characters equal to the line number (0 based).

i.e.: no issues on the first line (line index 0); Off by one on the second line (line index 1); Off by two on the third line (line index 2); Off by three on the forth line etc…


It turned out that the way the string functions count a line break (i.e. \r\n) as two characters, and rightly so – it is two characters a \r & a \n. However the TextBox functions like Select treat \r\n as a single character because that is what is displayed visually – a line break is one character visually. So there is a difference between the two scenarios and thus the “off by one x line count” error I found.


The solution I used is to compensate for it by working out the number of lines to the point (i.e. count all the line breaks before the point) and adjusting the results (adding +1 for each \r\n) as needed.

Sample application to show this problem and the solution can be found at: https://bitbucket.org/rmaclean/off-by-one-x-sample-code


Visitor's picture

Alternatively, keep your text data clean by removing \r when reading text in, and write \r\n line endings only when saving text to disk.
Robert MacLean's picture

The issues with this is what happens if you get data from another system which just uses \r? Now you have no way to figure out where the line breaks were.
Ulf T's picture

In that case you just replace \r with \n. You know if you have such case because there are no \n in the text in that case.

Add new comment