Skip to content

Commit

Permalink
Add markdown table formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
marcelbuesing committed Oct 16, 2019
1 parent cf7dca3 commit b5711df
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 0 deletions.
10 changes: 10 additions & 0 deletions examples/formatting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ fn main() {
table.printstd();
println!("");

// Print
// | Title 1 | Title 2 |
// |-------------|------------|
// | Value 1 | Value 2 |
// | Value three | Value four |
println!("FORMAT_MARKDOWN :");
table.set_format(*format::consts::FORMAT_MARKDOWN);
table.printstd();
println!("");

// Custom format can be implemented using `prettytable::format::FormatBuilder`
// Example to print
// +-------------+------------+
Expand Down
19 changes: 19 additions & 0 deletions src/format.rs
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,9 @@ pub mod consts {
use super::{TableFormat, LineSeparator, FormatBuilder, LinePosition};

lazy_static! {

/// A line separator made of `-` and `|`
static ref MINUS_PIPE_SEP: LineSeparator = LineSeparator::new('-', '|', '|', '|');
/// A line separator made of `-` and `+`
static ref MINUS_PLUS_SEP: LineSeparator = LineSeparator::new('-', '+', '+', '+');
/// A line separator made of `=` and `+`
Expand Down Expand Up @@ -555,5 +558,21 @@ pub mod consts {
'┘'))
.padding(1, 1)
.build();

/// A markdown table
///
/// # Example
/// ```text
/// | Title 1 | Title 2 |
/// |-------------|------------|
/// | Value 1 | Value 2 |
/// | Value three | Value four |
/// ```
pub static ref FORMAT_MARKDOWN: TableFormat = FormatBuilder::new()
.padding(1, 1)
.borders('|')
.separator(LinePosition::Title, *MINUS_PIPE_SEP)
.column_separator('|')
.build();
}
}
22 changes: 22 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -975,6 +975,28 @@ mod tests {
assert_eq!(6, table.print(&mut StringWriter::new()).unwrap());
}

#[test]
fn test_markdown_format_with_title() {
let mut table = Table::new();
table.set_format(*format::consts::FORMAT_MARKDOWN);

table.set_titles(Row::new(vec![Cell::new("Title 1"), Cell::new("Title 2")]));
table.add_row(Row::new(vec![Cell::new("Value 1"), Cell::new("Value 2")]));
table.add_row(Row::new(vec![Cell::new("Value three"), Cell::new("Value four")]));

let out = "\
| Title 1 | Title 2 |
|-------------|------------|
| Value 1 | Value 2 |
| Value three | Value four |
";
println!("{}", out);
println!("____");
println!("{}", table.to_string().replace("\r\n","\n"));
assert_eq!(out, table.to_string().replace("\r\n","\n"));
assert_eq!(4, table.print(&mut StringWriter::new()).unwrap());
}

#[test]
fn test_horizontal_span() {
let mut table = Table::new();
Expand Down

0 comments on commit b5711df

Please sign in to comment.