Skip to content

Commit 0a1c996

Browse files
og-orcasylvestre
authored andcommitted
fmt: balance the lines instead of leaving the last word alone
Allow a line to fall short of the goal by up to twice the stretch, and make the penalty for a lone sentence-final word big enough to win over the cost of a short line at narrow widths (stretch 1).
1 parent f88b235 commit 0a1c996

2 files changed

Lines changed: 37 additions & 2 deletions

File tree

‎src/uu/fmt/src/linebreak.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -232,7 +232,7 @@ fn find_kp_breakpoints<'a, T: Clone + Iterator<Item = &'a WordInfo<'a>>>(
232232
let minlength = if args.opts.goal <= 10 {
233233
1
234234
} else {
235-
args.opts.goal.max(stretch + 1) - stretch
235+
args.opts.goal.saturating_sub(2 * stretch).max(1)
236236
};
237237
let mut new_linebreaks = vec![];
238238
// the first word was written before this, so work out here whether the
@@ -410,7 +410,7 @@ const DR_MULT: f32 = 600.0;
410410
// DL_MULT is penalty multiplier for short words at end of line
411411
const DL_MULT: f32 = 10.0;
412412
// Penalize breaks that leave the first word on the next line as the sentence-final word.
413-
const ORPHAN_BREAK_PENALTY: i64 = 250_000_000;
413+
const ORPHAN_BREAK_PENALTY: i64 = 4_000_000_000;
414414

415415
fn is_word_sentence_final(current: &WordInfo, next: Option<&WordInfo>) -> bool {
416416
match next {

‎tests/by-util/test_fmt.rs‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -808,3 +808,38 @@ fn test_fmt_tagged_one_line_paragraph_indent() {
808808
.stdout_only(expected);
809809
}
810810
}
811+
812+
#[test]
813+
fn test_fmt_balances_lines_before_a_lone_last_word() {
814+
for (width, input, expected) in [
815+
(
816+
"20",
817+
"The quick brown fox jumps over the lazy dog.\n",
818+
"The quick brown\nfox jumps over the\nlazy dog.\n",
819+
),
820+
(
821+
"15",
822+
"one two three four five six seven\n",
823+
"one two three\nfour five\nsix seven\n",
824+
),
825+
("10", "aaa bbb ccc ddd eee\n", "aaa\nbbb ccc\nddd eee\n"),
826+
// already balanced, must stay as is
827+
("8", "aa bb cc dd ee\n", "aa bb cc\ndd ee\n"),
828+
(
829+
"10",
830+
"aaa bbb ccc ddd eee fff\n",
831+
"aaa bbb\nccc ddd\neee fff\n",
832+
),
833+
(
834+
"25",
835+
"The quick brown fox jumps over the lazy dog.\n",
836+
"The quick brown fox jumps\nover the lazy dog.\n",
837+
),
838+
] {
839+
new_ucmd!()
840+
.args(&["-w", width])
841+
.pipe_in(input)
842+
.succeeds()
843+
.stdout_only(expected);
844+
}
845+
}

0 commit comments

Comments
 (0)