Skip to content

Commit 2673e3c

Browse files
Fixing so that newline string wraps after too long words
- Fixing bug that made newline not be respected in case wrapLongWords is false and the first word on a line was too long - Adding test cases for above, and for the same condition with wrapOn
1 parent eb1d77c commit 2673e3c

File tree

2 files changed

+21
-3
lines changed

2 files changed

+21
-3
lines changed

src/main/java/org/apache/commons/text/WordUtils.java

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -845,9 +845,10 @@ public static String wrap(final String str,
845845
if(wrapLongWords && nextForcedWrap < nextNewlineStr && nextForcedWrap < nextWrapOn) {
846846
// We need to wrap the line due to a long word
847847
lineEnd = nextLineStart = nextForcedWrap;
848-
} else if(nextNewlineStr <= nextForcedWrap) {
848+
} else if(nextNewlineStr <= nextForcedWrap || (nextNewlineStr > nextForcedWrap && nextNewlineStr <= nextWrapOn)) {
849849
// There is a newLineStr before the length limit of the line,
850-
// so we wrap just after that.
850+
// or after the length limit and before the next wrapOn,
851+
// so we wrap just after that newline string.
851852
// This preserves trailing instances of wrapOn.
852853
nextLineStart = !newlineStrMatcher.hitEnd() ? newlineStrMatcher.end() : inputLineLength;
853854
lineEnd = nextLineStart;

src/test/java/org/apache/commons/text/WordUtilsTest.java

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -446,7 +446,24 @@ private static Stream<Arguments> provideDataForTypicalUseCasesLengthArgument() {
446446
Arguments.of(
447447
"Strip leading, keep trailing",
448448
"word1 word2 word3", 7,
449-
"word1 " + systemNewLine + "word2 " + systemNewLine + "word3")
449+
"word1 " + systemNewLine + "word2 " + systemNewLine + "word3"),
450+
451+
Arguments.of(
452+
"Long word, followed by wrap",
453+
"LongForALine Line 2 and Line 3", 12,
454+
"LongForALine" + systemNewLine + "Line 2 and" + systemNewLine + "Line 3"),
455+
Arguments.of(
456+
"Long word, followed by newline",
457+
"LongForALine" + systemNewLine + "Line 2 and Line 3", 12,
458+
"LongForALine" + systemNewLine + "Line 2 and" + systemNewLine + "Line 3"),
459+
Arguments.of(
460+
"Too long word, followed by wrap",
461+
"TooLongForALine Line 2 and Line 3", 10,
462+
"TooLongForALine" + systemNewLine + "Line 2 and" + systemNewLine + "Line 3"),
463+
Arguments.of(
464+
"Too long word, followed by newline",
465+
"TooLongForALine" + systemNewLine + "Line 2 and Line 3", 10,
466+
"TooLongForALine" + systemNewLine + "Line 2 and" + systemNewLine + "Line 3")
450467
);
451468
}
452469

0 commit comments

Comments
 (0)