From fc5666c693df9f0ab7a835db680b5bfbe2dffe92 Mon Sep 17 00:00:00 2001 From: Eugene Triguba Date: Sat, 12 Jul 2025 12:02:55 -0400 Subject: Fix word wrapping to next line when the word is longer than the buffer --- doc/justify.1 | 3 -- src/word.c | 12 +++++- tests/justify.bats | 19 +++++---- tests/test_word.c | 117 +++++++++++++++++++++++++++++++++++++++-------------- 4 files changed, 105 insertions(+), 46 deletions(-) diff --git a/doc/justify.1 b/doc/justify.1 index ccff202..e37f180 100644 --- a/doc/justify.1 +++ b/doc/justify.1 @@ -44,9 +44,6 @@ An error occurred (e.g., read error). .SH NOTES Before appending a word to the current line, the program ensures there is enough space for the word (and a space if not the first word). If not enough space remains, the current line is flushed (justified) and a new line is started. -.SH LIMITATIONS -The current implementation does not fully wrap or split words that are longer than the specified line width. Overlong words may be truncated or marked, rather than wrapped across lines. - .SH AUTHOR Eugene Triguba diff --git a/src/word.c b/src/word.c index 87643d6..e46aedd 100644 --- a/src/word.c +++ b/src/word.c @@ -16,11 +16,19 @@ int read_word(FILE *fp, char *word, size_t length) { while (!isspace(ch) && ch != EOF) { if (position >= length - 1) { // Note: -1 to ensure we have space for the null terminator + // // Once we hit the end of our available space, we stop reading, - // even if we didn't read the whole word. + // even if we didn't read the whole word. However, we need to + // ensure we put back the character we just read so that it is + // retrieved next time we call read_word. + int result = ungetc(ch, fp); + if (result == EOF) { + return READ_WORD_ERR_READ; + } break; } - word[position++] = ch; + word[position] = ch; + position++; ch = getc(fp); } if (length >= 0) { diff --git a/tests/justify.bats b/tests/justify.bats index a581c94..73db029 100644 --- a/tests/justify.bats +++ b/tests/justify.bats @@ -57,16 +57,15 @@ EOF assert_output "Hello world" } -# TODO: Handle this case properly -# @test "word longer than buffer is wrapped" { -# run "${JUSTIFY_BIN}" -w 60 <