From 061fb216cb08a2f3755ca411fd14f0b28730afd0 Mon Sep 17 00:00:00 2001 From: MeGaurav4 Date: Fri, 24 Jul 2026 22:26:50 +0530 Subject: [PATCH] feat: implement `-b` / `--number-nonblank` for `cat -b` compatibility Adds a `-b` / `--number-nonblank` flag that numbers only non-blank lines. Blank lines (those containing only the line terminator) are printed without a number and don't advance the counter, matching `cat -b` behaviour. - `-b` implies `--style=numbers` (same as `-n`), but only counts non-blank lines - `-b` takes precedence over `-n`: both `-bn` and `-nb` behave like `-b` - `-bp` disables numbering (plain mode wins) - Works with files, stdin, and piped output (like `-n`) Closes #3856. --- CHANGELOG.md | 1 + doc/long-help.txt | 10 ++++++ doc/short-help.txt | 2 ++ src/bin/bat/app.rs | 40 +++++++++++++++++++++++- src/bin/bat/clap_app.rs | 18 +++++++++++ src/config.rs | 4 +++ src/controller.rs | 19 +++++++++--- src/decorations.rs | 8 +++++ src/printer.rs | 9 +++++- tests/integration_tests.rs | 63 ++++++++++++++++++++++++++++++++++++++ 10 files changed, 168 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e2fc216..f9ffec2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ ## Features +- Add `-b` / `--number-nonblank` flag to only number non-blank lines, for `cat -b` compatibility. Closes #3856, see #3857 (@MeGaurav4) - Add a `--sanitize=` flag for safe display of untrusted input. It implies `--strip-ansi` at the same value and additionally substitutes terminal-active control bytes (cursor moves, charset switches, beep, etc.) and Unicode bidi / zero-width formatting characters with the Unicode replacement character (U+FFFD). Mitigates Trojan-Source-style spoofing (CVE-2021-42574). See #3729 (@curious-rabbit) - Map justfile, Justfile, .justfile, and *.justfile to Makefile syntax highlighting, see #3623 (@zachvalenta) - Preserve `--diff` change markers and snip separators when `--plain` is set. Closes #3630, see #3643 (@mvanhorn) diff --git a/doc/long-help.txt b/doc/long-help.txt index 5b549e07..b4b07107 100644 --- a/doc/long-help.txt +++ b/doc/long-help.txt @@ -83,6 +83,16 @@ Options: -n, --number Only show line numbers, no other decorations. This is an alias for '--style=numbers' + -b, --number-nonblank + Only show line numbers for non-blank lines, no other decorations. This is an alias for + '--style=numbers'. Non-blank lines are lines that contain any character before the line + ending, including spaces and tabs. When used together with --number (-n), + --number-nonblank (-b) takes precedence. + + Example: + printf 'alpha\n\nbeta\n' | bat -b + numbers 'alpha' and 'beta', but skips the empty line. + --color Specify when to use colored output. The automatic mode only enables colors if an interactive terminal is detected - colors are automatically disabled if the output goes to diff --git a/doc/short-help.txt b/doc/short-help.txt index e08bb604..ae433a8f 100644 --- a/doc/short-help.txt +++ b/doc/short-help.txt @@ -33,6 +33,8 @@ Options: Truncate all lines longer than screen width. Alias for '--wrap=never'. -n, --number Show line numbers (alias for '--style=numbers'). + -b, --number-nonblank + Show line numbers for non-blank lines only (alias for '--style=numbers'). --color When to use colors (*auto*, never, always). --italic-text diff --git a/src/bin/bat/app.rs b/src/bin/bat/app.rs index cc37075c..7b738c35 100644 --- a/src/bin/bat/app.rs +++ b/src/bin/bat/app.rs @@ -59,6 +59,10 @@ pub struct App { /// (not from config file or environment variables). /// This is used to honor the flag when piping output, similar to `cat -n`. number_from_cli: bool, + /// True if -b / --number-nonblank was passed on the command line + /// (not from config file or environment variables). + /// This is used to honor the flag when piping output, similar to `cat -b`. + number_nonblank_from_cli: bool, } impl App { @@ -99,6 +103,29 @@ impl App { false }); + // Check if the -b / --number-nonblank option was passed on the command line + // (before merging with config file and environment variables). + // This is needed to honor the -b flag when piping output, similar to `cat -b`. + // The same combined-flag logic applies as for -n above. + let number_nonblank_from_cli = wild::args_os().any(|arg| { + let arg_str = arg.to_string_lossy(); + if arg_str == "-b" || arg_str == "--number-nonblank" { + return true; + } + // Handle combined short flags + if arg_str.starts_with('-') && !arg_str.starts_with("--") && arg_str.len() > 2 { + let chars: Vec = arg_str.chars().skip(1).collect(); + let b_pos = chars.iter().position(|&c| c == 'b'); + let p_pos = chars.iter().position(|&c| c == 'p'); + if let Some(b) = b_pos { + if p_pos.is_none() || b > p_pos.unwrap() { + return true; + } + } + } + false + }); + let matches = Self::matches(interactive_output)?; if matches.get_flag("help") { @@ -139,6 +166,7 @@ impl App { matches, interactive_output, number_from_cli, + number_nonblank_from_cli, }) } @@ -454,7 +482,8 @@ impl App { .map(|s| s.as_str()) == Some("always") || self.matches.get_flag("force-colorization") - || self.number_from_cli), + || self.number_from_cli + || self.number_nonblank_from_cli), tab_width: self .matches .get_one::("tabs") @@ -495,6 +524,8 @@ impl App { ), quiet_empty: self.matches.get_flag("quiet-empty"), unbuffered: self.matches.get_flag("unbuffered"), + number_nonblank: self.matches.get_flag("number-nonblank") + || self.number_nonblank_from_cli, theme: theme(self.theme_options()).to_string(), visible_lines: match self.matches.try_contains_id("diff").unwrap_or_default() && self.matches.get_flag("diff") @@ -613,6 +644,13 @@ impl App { ]))); } + // Only line numbers for non-blank lines if `--number-nonblank`. + if self.matches.get_flag("number-nonblank") || self.number_nonblank_from_cli { + return Some(StyleComponents(HashSet::from([ + StyleComponent::LineNumbers, + ]))); + } + // Plain if `--plain` is specified at least once. if self.matches.get_count("plain") > 0 { let mut components = HashSet::from([StyleComponent::Plain]); diff --git a/src/bin/bat/clap_app.rs b/src/bin/bat/clap_app.rs index decd0364..7f76f51b 100644 --- a/src/bin/bat/clap_app.rs +++ b/src/bin/bat/clap_app.rs @@ -97,6 +97,7 @@ pub fn build_app(interactive_output: bool) -> Command { Arg::new("plain") .overrides_with("plain") .overrides_with("number") + .overrides_with("number-nonblank") .short('p') .long("plain") .action(ArgAction::Count) @@ -277,6 +278,23 @@ pub fn build_app(interactive_output: bool) -> Command { '--style=numbers'", ), ) + .arg( + Arg::new("number-nonblank") + .long("number-nonblank") + .overrides_with("number-nonblank") + .short('b') + .action(ArgAction::SetTrue) + .help("Show line numbers for non-blank lines only (alias for '--style=numbers').") + .long_help( + "Only show line numbers for non-blank lines, no other decorations. This is an \ + alias for '--style=numbers'. Non-blank lines are lines that contain any \ + character before the line ending, including spaces and tabs. When used \ + together with --number (-n), --number-nonblank (-b) takes precedence.\n\n\ + Example:\n \ + printf 'alpha\\n\\nbeta\\n' | bat -b\n \ + numbers 'alpha' and 'beta', but skips the empty line.", + ), + ) .arg( Arg::new("color") .long("color") diff --git a/src/config.rs b/src/config.rs index 121097d9..9f78244e 100644 --- a/src/config.rs +++ b/src/config.rs @@ -119,6 +119,10 @@ pub struct Config<'a> { /// Whether or not to use unbuffered input reading for streaming use cases pub unbuffered: bool, + + /// Only number non-blank lines (like `cat -b`). Has no effect if `style_components` doesn't + /// include `LineNumbers`. + pub number_nonblank: bool, } #[cfg(all(feature = "minimal-application", feature = "paging"))] diff --git a/src/controller.rs b/src/controller.rs index 8f64e8c5..d9ed4b79 100644 --- a/src/controller.rs +++ b/src/controller.rs @@ -276,10 +276,21 @@ impl Controller<'_> { } if !reached_eof { if reader.read_line(&mut current_line_buffer)? { - // Fill the buffer - buffered_lines - .push_back((mem::take(&mut current_line_buffer), current_line_number)); - current_line_number += 1; + // Fill the buffer. In number-nonblank mode, don't advance the + // line counter for empty lines (content-free lines that contain + // only the line terminator). + if self.config.number_nonblank + && current_line_buffer + .iter() + .all(|&b| b == b'\r' || b == b'\n') + { + buffered_lines + .push_back((mem::take(&mut current_line_buffer), current_line_number)); + } else { + buffered_lines + .push_back((mem::take(&mut current_line_buffer), current_line_number)); + current_line_number += 1; + } } else { // No more data to read reached_eof = true; diff --git a/src/decorations.rs b/src/decorations.rs index 5b7846c3..cb0e5eaa 100644 --- a/src/decorations.rs +++ b/src/decorations.rs @@ -45,6 +45,14 @@ impl Decoration for LineNumberDecoration { continuation: bool, _printer: &InteractivePrinter, ) -> DecorationText { + if line_number == 0 { + // Blank line in number-nonblank mode: show empty space instead of a number. + return DecorationText { + text: self.color.paint(" ".repeat(self.width())).to_string(), + width: self.width(), + }; + } + if continuation { if line_number >= self.cached_wrap_invalid_at { let new_width = self.cached_wrap.width + 1; diff --git a/src/printer.rs b/src/printer.rs index 42405902..93a79e5f 100644 --- a/src/printer.rs +++ b/src/printer.rs @@ -738,10 +738,17 @@ impl Printer for InteractivePrinter<'_> { // Line decorations. if self.panel_width > 0 { + let display_line_number = + if self.config.number_nonblank && line.trim_end_matches(['\r', '\n']).is_empty() { + 0 + } else { + line_number + }; + let decorations = self .decorations .iter() - .map(|d| d.generate(line_number, false, self)); + .map(|d| d.generate(display_line_number, false, self)); for deco in decorations { write!(handle, "{} ", deco.text)?; diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index 33de3fbf..2a100ef2 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -213,6 +213,69 @@ fn numbers_honored_from_cli_when_preceeded_by_plain_in_loop_through_mode() { .stdout(" 1 line 1\n 2 line 2\n 3 line 3\n 4 line 4\n 5 line 5\n 6 line 6\n 7 line 7\n 8 line 8\n 9 line 9\n 10 line 10\n"); } +#[test] +fn number_nonblank_style() { + bat() + .arg("empty_lines.txt") + .arg("-b") + .arg("--decorations=always") + .assert() + .success() + .stdout(" 1 line 1\n \n \n \n 2 line 5\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n 3 line 20\n 4 line 21\n \n \n 5 line 24\n \n 6 line 26\n \n \n \n 7 line 30\n"); +} + +#[test] +fn number_nonblank_from_cli_in_loop_through_mode() { + bat() + .arg("empty_lines.txt") + .arg("-b") + .assert() + .success() + .stdout(" 1 line 1\n \n \n \n 2 line 5\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n 3 line 20\n 4 line 21\n \n \n 5 line 24\n \n 6 line 26\n \n \n \n 7 line 30\n"); +} + +#[test] +fn number_nonblank_takes_precedence_over_number() { + // -bn should behave like -b + bat() + .arg("empty_lines.txt") + .arg("-bn") + .arg("--decorations=always") + .assert() + .success() + .stdout(" 1 line 1\n \n \n \n 2 line 5\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n 3 line 20\n 4 line 21\n \n \n 5 line 24\n \n 6 line 26\n \n \n \n 7 line 30\n"); + + // -nb should also behave like -b + bat() + .arg("empty_lines.txt") + .arg("-nb") + .arg("--decorations=always") + .assert() + .success() + .stdout(" 1 line 1\n \n \n \n 2 line 5\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n 3 line 20\n 4 line 21\n \n \n 5 line 24\n \n 6 line 26\n \n \n \n 7 line 30\n"); +} + +#[test] +fn number_nonblank_ignored_when_followed_by_plain() { + bat() + .arg("empty_lines.txt") + .arg("-bp") + .arg("--decorations=auto") + .assert() + .success() + .stdout("line 1\n\n\n\nline 5\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nline 20\nline 21\n\n\nline 24\n\nline 26\n\n\n\nline 30\n"); +} + +#[test] +fn piped_output_with_number_nonblank_flag() { + bat() + .arg("-b") + .write_stdin("hello\n\nworld\n") + .assert() + .success() + .stdout(" 1 hello\n \n 2 world\n"); +} + #[test] fn line_range_2_3() { bat()