1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864
//! The purpose of term-table is to make it easy for CLI apps to display data in a table format //!# Example //! Here is an example of how to create a simple table //!``` //!let mut table = term_table::Table::new(); //!table.max_column_width = 40; //! //!table.style = term_table::TableStyle::extended(); //!table.add_row(term_table::row::Row::new(vec![ //! term_table::table_cell::TableCell::new_with_alignment("This is some centered text", 2, term_table::table_cell::Alignment::Center) //!])); //!table.add_row(term_table::row::Row::new(vec![ //! term_table::table_cell::TableCell::new("This is left aligned text"), //! term_table::table_cell::TableCell::new_with_alignment("This is right aligned text", 1, term_table::table_cell::Alignment::Right) //!])); //! table.add_row(term_table::row::Row::new(vec![ //! term_table::table_cell::TableCell::new("This is left aligned text"), //! term_table::table_cell::TableCell::new_with_alignment("This is right aligned text", 1, term_table::table_cell::Alignment::Right) //!])); //!table.add_row(term_table::row::Row::new(vec![ //! term_table::table_cell::TableCell::new_with_col_span("This is some really really really really really really really really really that is going to wrap to the next line", 2), //!])); //!println!("{}", table.render()); //!``` //! //!### This is the result //! //!<pre> //! ╔═════════════════════════════════════════════════════════════════════════════════╗ //! ║ This is some centered text ║ //! ╠════════════════════════════════════════╦════════════════════════════════════════╣ //! ║ This is left aligned text ║ This is right aligned text ║ //! ╠════════════════════════════════════════╬════════════════════════════════════════╣ //! ║ This is left aligned text ║ This is right aligned text ║ //! ╠════════════════════════════════════════╩════════════════════════════════════════╣ //! ║ This is some really really really really really really really really really tha ║ //! ║ t is going to wrap to the next line ║ //! ╚═════════════════════════════════════════════════════════════════════════════════╝ //!</pre> #[macro_use] extern crate lazy_static; extern crate wcwidth; extern crate regex; pub mod table_cell; pub mod row; use row::Row; use std::cmp::{max, min}; use std::collections::HashMap; /// Represents the vertical postion of a row #[derive(Eq, PartialEq, Copy, Clone)] pub enum RowPosition { First, Mid, Last, } /// A set of characters which make up a table style /// ///# Example /// ///``` /// term_table::TableStyle { /// top_left_corner: '╔', /// top_right_corner: '╗', /// bottom_left_corner: '╚', /// bottom_right_corner: '╝', /// outer_left_vertical: '╠', /// outer_right_vertical: '╣', /// outer_bottom_horizontal: '╩', /// outer_top_horizontal: '╦', /// intersection: '╬', /// vertical: '║', /// horizontal: '═', /// }; ///``` pub struct TableStyle { pub top_left_corner: char, pub top_right_corner: char, pub bottom_left_corner: char, pub bottom_right_corner: char, pub outer_left_vertical: char, pub outer_right_vertical: char, pub outer_bottom_horizontal: char, pub outer_top_horizontal: char, pub intersection: char, pub vertical: char, pub horizontal: char, } impl TableStyle { /// Basic terminal table style /// ///# Example /// ///<pre> /// +---------------------------------------------------------------------------------+ /// | This is some centered text | /// +----------------------------------------+----------------------------------------+ /// | This is left aligned text | This is right aligned text | /// +----------------------------------------+----------------------------------------+ /// | This is left aligned text | This is right aligned text | /// +----------------------------------------+----------------------------------------+ /// | This is some really really really really really really really really really tha | /// | t is going to wrap to the next line | /// +---------------------------------------------------------------------------------+ ///</pre> pub fn simple() -> TableStyle { return TableStyle { top_left_corner: '+', top_right_corner: '+', bottom_left_corner: '+', bottom_right_corner: '+', outer_left_vertical: '+', outer_right_vertical: '+', outer_bottom_horizontal: '+', outer_top_horizontal: '+', intersection: '+', vertical: '|', horizontal: '-', }; } /// Table style using extended character set /// ///# Example /// ///<pre> /// ╔═════════════════════════════════════════════════════════════════════════════════╗ /// ║ This is some centered text ║ /// ╠════════════════════════════════════════╦════════════════════════════════════════╣ /// ║ This is left aligned text ║ This is right aligned text ║ /// ╠════════════════════════════════════════╬════════════════════════════════════════╣ /// ║ This is left aligned text ║ This is right aligned text ║ /// ╠════════════════════════════════════════╩════════════════════════════════════════╣ /// ║ This is some really really really really really really really really really tha ║ /// ║ t is going to wrap to the next line ║ /// ╚═════════════════════════════════════════════════════════════════════════════════╝ ///</pre> pub fn extended() -> TableStyle { return TableStyle { top_left_corner: '╔', top_right_corner: '╗', bottom_left_corner: '╚', bottom_right_corner: '╝', outer_left_vertical: '╠', outer_right_vertical: '╣', outer_bottom_horizontal: '╩', outer_top_horizontal: '╦', intersection: '╬', vertical: '║', horizontal: '═', }; } /// <pre> /// ┌─────────────────────────────────────────────────────────────────────────────────┐ /// │ This is some centered text │ /// ├────────────────────────────────────────┬────────────────────────────────────────┤ /// │ This is left aligned text │ This is right aligned text │ /// ├────────────────────────────────────────┼────────────────────────────────────────┤ /// │ This is left aligned text │ This is right aligned text │ /// ├────────────────────────────────────────┴────────────────────────────────────────┤ /// │ This is some really really really really really really really really really tha │ /// │ t is going to wrap to the next line │ /// └─────────────────────────────────────────────────────────────────────────────────┘ /// </pre> pub fn thin() -> TableStyle { return TableStyle { top_left_corner: '┌', top_right_corner: '┐', bottom_left_corner: '└', bottom_right_corner: '┘', outer_left_vertical: '├', outer_right_vertical: '┤', outer_bottom_horizontal: '┴', outer_top_horizontal: '┬', intersection: '┼', vertical: '│', horizontal: '─', }; } /// <pre> /// ╭─────────────────────────────────────────────────────────────────────────────────╮ /// │ This is some centered text │ /// ├────────────────────────────────────────┬────────────────────────────────────────┤ /// │ This is left aligned text │ This is right aligned text │ /// ├────────────────────────────────────────┼────────────────────────────────────────┤ /// │ This is left aligned text │ This is right aligned text │ /// ├────────────────────────────────────────┴────────────────────────────────────────┤ /// │ This is some really really really really really really really really really tha │ /// │ t is going to wrap to the next line │ /// ╰─────────────────────────────────────────────────────────────────────────────────╯ /// </pre> pub fn rounded() -> TableStyle { return TableStyle { top_left_corner: '╭', top_right_corner: '╮', bottom_left_corner: '╰', bottom_right_corner: '╯', outer_left_vertical: '├', outer_right_vertical: '┤', outer_bottom_horizontal: '┴', outer_top_horizontal: '┬', intersection: '┼', vertical: '│', horizontal: '─', }; } /// <pre> /// ╔─────────────────────────────────────────────────────────────────────────────────╗ /// │ This is some centered text │ /// ╠────────────────────────────────────────╦────────────────────────────────────────╣ /// │ This is left aligned text │ This is right aligned text │ /// ╠────────────────────────────────────────┼────────────────────────────────────────╣ /// │ This is left aligned text │ This is right aligned text │ /// ╠────────────────────────────────────────╩────────────────────────────────────────╣ /// │ This is some really really really really really really really really really tha │ /// │ t is going to wrap to the next line │ /// ╚─────────────────────────────────────────────────────────────────────────────────╝ /// </pre> pub fn elegant() -> TableStyle { return TableStyle { top_left_corner: '╔', top_right_corner: '╗', bottom_left_corner: '╚', bottom_right_corner: '╝', outer_left_vertical: '╠', outer_right_vertical: '╣', outer_bottom_horizontal: '╩', outer_top_horizontal: '╦', intersection: '┼', vertical: '│', horizontal: '─', }; } /// Table style comprised of null characters /// ///# Example /// ///<pre> /// This is some centered text /// /// This is left aligned text This is right aligned text /// /// This is left aligned text This is right aligned text /// /// This is some really really really really really really really really really tha /// t is going to wrap to the next line ///</pre> pub fn blank() -> TableStyle { return TableStyle { top_left_corner: '\0', top_right_corner: '\0', bottom_left_corner: '\0', bottom_right_corner: '\0', outer_left_vertical: '\0', outer_right_vertical: '\0', outer_bottom_horizontal: '\0', outer_top_horizontal: '\0', intersection: '\0', vertical: '\0', horizontal: '\0', }; } /// Returns the start character of a table style based on the /// vertical position of the row fn start_for_position(&self, pos: RowPosition) -> char { match pos { RowPosition::First => self.top_left_corner, RowPosition::Mid => self.outer_left_vertical, RowPosition::Last => self.bottom_left_corner, } } /// Returns the end character of a table style based on the /// vertical position of the row fn end_for_position(&self, pos: RowPosition) -> char { match pos { RowPosition::First => self.top_right_corner, RowPosition::Mid => self.outer_right_vertical, RowPosition::Last => self.bottom_right_corner, } } /// Returns the intersect character of a table style based on the /// vertical position of the row fn intersect_for_position(&self, pos: RowPosition) -> char { match pos { RowPosition::First => self.outer_top_horizontal, RowPosition::Mid => self.intersection, RowPosition::Last => self.outer_bottom_horizontal, } } /// Merges two intersecting characters based on the vertical position of a row. /// This is used to hanlde cases where one cell has a larger `col_span` value than the other fn merge_intersection_for_position(&self, top: char, bottom: char, pos: RowPosition) -> char { if (top == self.horizontal || top == self.outer_bottom_horizontal) && bottom == self.intersection { return self.outer_top_horizontal; } else if (top == self.intersection || top == self.outer_top_horizontal) && bottom == self.horizontal { return self.outer_bottom_horizontal; } else if top == self.outer_bottom_horizontal && bottom == self.horizontal { return self.horizontal; } else { return self.intersect_for_position(pos); } } } /// A set of rows containing data pub struct Table<'data> { pub rows: Vec<Row<'data>>, pub style: TableStyle, /// The maximum width of all columns. Overriden by values in column_widths. Defults to `std::usize::max` pub max_column_width: usize, /// The maxium widths of specific columns. Override max_column pub max_column_widths: HashMap<usize, usize>, } impl<'data> Table<'data> { pub fn new() -> Table<'data> { return Table { rows: Vec::new(), style: TableStyle::extended(), max_column_width: std::usize::MAX, max_column_widths: HashMap::new(), }; } /// Set the max width of a paticular column pub fn set_max_column_width(&mut self, column_index: usize, width: usize) { self.max_column_widths.insert(column_index, width); } /// Set the max widths of specific columns pub fn set_max_column_widths(&mut self, index_width_pairs: Vec<(usize, usize)>) { for pair in index_width_pairs { self.max_column_widths.insert(pair.0, pair.1); } } /// Simply adds a row to the rows Vec pub fn add_row(&mut self, row: Row<'data>) { self.rows.push(row); } /// Does all of the calculations to reformat the row based on it's current /// state and returns the result as a `String` pub fn render(&self) -> String { let mut print_buffer = String::new(); let max_widths = self.calculate_max_column_widths(); let mut previous_separator = None; if !self.rows.is_empty() { for i in 0..self.rows.len() { let mut row_pos = if i == 0 { RowPosition::First }else{ RowPosition::Mid }; let separator = self.rows[i].gen_separator( &max_widths, &self.style, row_pos, previous_separator.clone(), ); Table::buffer_line(&mut print_buffer, &separator); Table::buffer_line( &mut print_buffer, &self.rows[i].format(&max_widths, &self.style), ); previous_separator = Some(separator.clone()); } let separator = self.rows.last().unwrap().gen_separator( &max_widths, &self.style, RowPosition::Last, None, ); Table::buffer_line(&mut print_buffer, &separator); } return print_buffer; } /// Calculates the maximum width for each column. /// If a cell has a column span greater than 1, then the width /// of it's contents are divided by the column span, otherwise the cell /// would use more space than it needed. fn calculate_max_column_widths(&self) -> Vec<usize> { let mut num_columns = 0; for row in &self.rows { num_columns = max(row.num_columns(), num_columns); } let mut max_widths: Vec<usize> = vec![0; num_columns]; let mut min_widths: Vec<usize> = vec![0; num_columns]; for row in &self.rows { let column_widths = row.split_column_widths(); for i in 0..column_widths.len() { min_widths[i] = max(min_widths[i], column_widths[i].1); let mut max_width = *self.max_column_widths .get(&i) .unwrap_or(&self.max_column_width); max_width = max(min_widths[i] as usize, max_width); max_widths[i] = min(max_width, max(max_widths[i], column_widths[i].0 as usize)); } } return max_widths; } /// Helper method for adding a line to a string buffer fn buffer_line(buffer: &mut String, line: &str) { buffer.push_str(format!("{}\n", line).as_str()); } } impl<'data> Default for Table<'data>{ fn default()->Self{ return Table::new(); } } impl<'data> ToString for Table<'data>{ fn to_string(&self)->String{ return self.render(); } } #[cfg(test)] mod test { use Table; use TableStyle; use table_cell::{Alignment, TableCell}; use row::Row; #[test] fn simple_table_style() { let mut table = Table::new(); table.max_column_width = 40; table.style = TableStyle::simple(); table.add_row(Row::new(vec![ TableCell::new_with_alignment("This is some centered text", 2, Alignment::Center), ])); table.add_row(Row::new(vec![ TableCell::new("This is left aligned text"), TableCell::new_with_alignment("This is right aligned text", 1, Alignment::Right), ])); table.add_row(Row::new(vec![ TableCell::new("This is left aligned text"), TableCell::new_with_alignment("This is right aligned text", 1, Alignment::Right), ])); table.add_row(Row::new(vec![ TableCell::new_with_col_span("This is some really really really really really really really really really that is going to wrap to the next line", 2), ])); let expected = "+---------------------------------------------------------------------------------+ | This is some centered text | +----------------------------------------+----------------------------------------+ | This is left aligned text | This is right aligned text | +----------------------------------------+----------------------------------------+ | This is left aligned text | This is right aligned text | +----------------------------------------+----------------------------------------+ | This is some really really really really really really really really really tha | | t is going to wrap to the next line | +---------------------------------------------------------------------------------+ "; println!("{}", table.render()); assert_eq!(expected, table.render()); } #[test] fn extended_table_style() { let mut table = Table::new(); table.max_column_width = 40; table.set_max_column_widths(vec![(0, 1), (1, 1)]); table.style = TableStyle::extended(); table.add_row(Row::new(vec![ TableCell::new_with_alignment("This is some centered text", 2, Alignment::Center), ])); table.add_row(Row::new(vec![ TableCell::new("This is left aligned text"), TableCell::new_with_alignment("This is right aligned text", 1, Alignment::Right), ])); table.add_row(Row::new(vec![ TableCell::new("This is left aligned text"), TableCell::new_with_alignment("This is right aligned text", 1, Alignment::Right), ])); table.add_row(Row::new(vec![ TableCell::new_with_col_span("This is some really really really really really really really really really that is going to wrap to the next line\n1\n2", 2), ])); let expected = "╔═══════╗ ║ This ║ ║ is so ║ ║ me ce ║ ║ ntere ║ ║ d tex ║ ║ t ║ ╠═══╦═══╣ ║ T ║ T ║ ║ h ║ h ║ ║ i ║ i ║ ║ s ║ s ║ ║ ║ ║ ║ i ║ i ║ ║ s ║ s ║ ║ ║ ║ ║ l ║ r ║ ║ e ║ i ║ ║ f ║ g ║ ║ t ║ h ║ ║ ║ t ║ ║ a ║ ║ ║ l ║ a ║ ║ i ║ l ║ ║ g ║ i ║ ║ n ║ g ║ ║ e ║ n ║ ║ d ║ e ║ ║ ║ d ║ ║ t ║ ║ ║ e ║ t ║ ║ x ║ e ║ ║ t ║ x ║ ║ ║ t ║ ╠═══╬═══╣ ║ T ║ T ║ ║ h ║ h ║ ║ i ║ i ║ ║ s ║ s ║ ║ ║ ║ ║ i ║ i ║ ║ s ║ s ║ ║ ║ ║ ║ l ║ r ║ ║ e ║ i ║ ║ f ║ g ║ ║ t ║ h ║ ║ ║ t ║ ║ a ║ ║ ║ l ║ a ║ ║ i ║ l ║ ║ g ║ i ║ ║ n ║ g ║ ║ e ║ n ║ ║ d ║ e ║ ║ ║ d ║ ║ t ║ ║ ║ e ║ t ║ ║ x ║ e ║ ║ t ║ x ║ ║ ║ t ║ ╠═══╩═══╣ ║ This ║ ║ is so ║ ║ me re ║ ║ ally ║ ║ reall ║ ║ y rea ║ ║ lly r ║ ║ eally ║ ║ real ║ ║ ly re ║ ║ ally ║ ║ reall ║ ║ y rea ║ ║ lly r ║ ║ eally ║ ║ that ║ ║ is g ║ ║ oing ║ ║ to wr ║ ║ ap to ║ ║ the ║ ║ next ║ ║ line ║ ║ 1 ║ ║ 2 ║ ╚═══════╝ "; println!("{}", table.render()); assert_eq!(expected, table.render()); } #[test] fn blank_table_style() { let mut table = Table::new(); table.max_column_width = 40; table.style = TableStyle::blank(); table.add_row(Row::new(vec![ TableCell::new_with_alignment("This is some centered text", 2, Alignment::Center), ])); table.add_row(Row::new(vec![ TableCell::new("This is left aligned text"), TableCell::new_with_alignment("This is right aligned text", 1, Alignment::Right), ])); table.add_row(Row::new(vec![ TableCell::new("This is left aligned text"), TableCell::new_with_alignment("This is right aligned text", 1, Alignment::Right), ])); table.add_row(Row::new(vec![ TableCell::new_with_col_span("This is some really really really really really really really really really that is going to wrap to the next line", 2), ])); let expected = "