Hi everyone!

When the -s option is enabled (break at spaces), fold does not correctly handle the case in which the last character that should be on the folded line is a word's last character. In other words, the issue happens when the line's last character is a non-blank character, followed by a blank character. In that case, the whole last word, which would fit within the limit, is put on the next line.

To clarify, I'll make an example. Let's suppose that:
- the line width limit is set to 80 (default)
- the -s option is enabled

Let's take the following string, where the double quote characters simply mark the beginning and the end of the string and are not included in it.

"This line is exactly exactly exactly exactly exactly exactly exactly 80 chars!!!"

If you count the characters they are exactly 80, so it takes exactly a whole line. If you create an empty file and write only that line in it, fold correctly keeps the whole string in its line. However, if you add a space character and some other words, the word "chars!!!" gets folded to a new line.

I had a quick look at the source code on GitHub (master branch) and the error seems to lie in line 174 (`--logical_end`). I have not tested the program but if there are no "special characters" in the line (e.g. control characters like '\r' or '\b'), then the fold condition (`column > width`) is triggered when `column = width + 1` and `offset_out = column + 1`. Once `logical_end` is declared and initialized to `offset_out`, the following while loop decrements it as first thing. This means that the space character can never be in the current character (with index `offset_out`), only from the previous character to the beginning of the line, which folds the last word to the new line.

I also noticed that fold keeps the last space character at the end of the line when -s is enabled, instead of removing it. I don't know if this is the expected behavior, if it's not it might be worth to also fix this one.



Reply via email to