diff --git a/crates/nu-command/tests/commands/table.rs b/crates/nu-command/tests/commands/table.rs index 04473e1776..41bd1ec531 100644 --- a/crates/nu-command/tests/commands/table.rs +++ b/crates/nu-command/tests/commands/table.rs @@ -3119,3 +3119,33 @@ fn table_colors() { )); assert_eq!(actual.out, "╭───┬───╮│ a │ 1 ││ b │ 2 │╰───┴───╯"); } + +#[test] +fn table_index() { + let actual = nu!("[[ index var ]; [ abc 1 ] [ def 2 ] [ ghi 3 ]] | table --width=80"); + assert_eq!( + actual.out, + "╭─────┬─────╮\ + │ # │ var │\ + ├─────┼─────┤\ + │ abc │ 1 │\ + │ def │ 2 │\ + │ ghi │ 3 │\ + ╰─────┴─────╯" + ); +} + +#[test] +fn table_index_expand() { + let actual = nu!("[[ index var ]; [ abc 1 ] [ def 2 ] [ ghi 3 ]] | table --width=80 --expand"); + assert_eq!( + actual.out, + "╭─────┬─────╮\ + │ # │ var │\ + ├─────┼─────┤\ + │ abc │ 1 │\ + │ def │ 2 │\ + │ ghi │ 3 │\ + ╰─────┴─────╯" + ); +} diff --git a/crates/nu-table/src/types/general.rs b/crates/nu-table/src/types/general.rs index c2ac2a00e4..81d4906783 100644 --- a/crates/nu-table/src/types/general.rs +++ b/crates/nu-table/src/types/general.rs @@ -236,20 +236,25 @@ fn get_table_row_index(item: &Value, config: &Config, row: usize, offset: usize) fn collect_headers(headers: Vec, index: bool) -> Vec { // The header with the INDEX is removed from the table headers since // it is added to the natural table index - - if !index { - headers - .into_iter() - .filter(|header| header != INDEX_COLUMN_NAME) - .map(NuRecordsValue::new) - .collect() + let length = if index { + headers.len() + 1 } else { - let mut v = Vec::with_capacity(headers.len() + 1); + headers.len() + }; + + let mut v = Vec::with_capacity(length); + + if index { v.insert(0, NuRecordsValue::new("#".into())); - for text in headers { - v.push(NuRecordsValue::new(text)); + } + + for text in headers { + if text == INDEX_COLUMN_NAME { + continue; } - v + v.push(NuRecordsValue::new(text)); } + + v }