diff options
author | Pierre-Henri Symoneaux <pierre-henri.symoneaux@nokia.com> | 2017-05-29 22:10:07 +0200 |
---|---|---|
committer | Pierre-Henri Symoneaux <pierre-henri.symoneaux@nokia.com> | 2017-05-29 22:10:07 +0200 |
commit | 0b633eb06f99a24f54070fe460068b2fa5ce1e13 (patch) | |
tree | dbc9095bb2ec623bee04382c74f356c327810a0b | |
parent | c771c45b69de6b1c432e070cf6ac4d58c885488c (diff) |
Applied rustfmt on code
-rw-r--r-- | examples/basic.rs | 59 | ||||
-rw-r--r-- | examples/csv.rs | 3 | ||||
-rw-r--r-- | examples/formatting.rs | 173 | ||||
-rw-r--r-- | examples/multiline.rs | 27 | ||||
-rw-r--r-- | examples/slices.rs | 39 | ||||
-rw-r--r-- | examples/style.rs | 61 | ||||
-rw-r--r-- | examples/tictactoe.rs | 178 | ||||
-rw-r--r-- | src/cell.rs | 659 | ||||
-rw-r--r-- | src/format.rs | 514 | ||||
-rw-r--r-- | src/lib.rs | 1484 | ||||
-rw-r--r-- | src/main.rs | 91 | ||||
-rw-r--r-- | src/row.rs | 444 | ||||
-rw-r--r-- | src/utils.rs | 245 |
13 files changed, 2050 insertions, 1927 deletions
diff --git a/examples/basic.rs b/examples/basic.rs index 111328f..4ca5d39 100644 --- a/examples/basic.rs +++ b/examples/basic.rs @@ -1,8 +1,9 @@ -#[macro_use] extern crate prettytable;
-use prettytable::Table;
-use prettytable::row::Row;
-use prettytable::cell::Cell;
-
+#[macro_use] +extern crate prettytable; +use prettytable::Table; +use prettytable::row::Row; +use prettytable::cell::Cell; + /*
Following main function will print :
+---------+------+---------+
@@ -20,30 +21,24 @@ use prettytable::cell::Cell; +---------+------+---------+
| foobar2 | bar2 | new_foo |
+---------+------+---------+
-*/
-fn main() {
- let mut table = Table::new();
- table.add_row(row!["ABC", "DEFG", "HIJKLMN"]);
- table.add_row(row!["foobar", "bar", "foo"]);
- table.add_row(Row::new(vec![
- Cell::new("foobar2"),
- Cell::new("bar2"),
- Cell::new("foo2")])
- );
- table.printstd();
- println!("Modified : ");
- table.set_element("new_foo", 2, 1).unwrap();
- table.printstd();
-
- // The same table can be built the following way :
- let _table = table!(["ABC", "DEFG", "HIJKLMN"],
- ["foobar", "bar", "foo"],
- ["foobar2", "bar2", "foo2"]
- );
-
- // Or directly print it like this
- let _table = ptable!(["ABC", "DEFG", "HIJKLMN"],
- ["foobar", "bar", "foo"],
- ["foobar2", "bar2", "foo2"]
- );
-}
+*/ +fn main() { + let mut table = Table::new(); + table.add_row(row!["ABC", "DEFG", "HIJKLMN"]); + table.add_row(row!["foobar", "bar", "foo"]); + table.add_row(Row::new(vec![Cell::new("foobar2"), Cell::new("bar2"), Cell::new("foo2")])); + table.printstd(); + println!("Modified : "); + table.set_element("new_foo", 2, 1).unwrap(); + table.printstd(); + + // The same table can be built the following way : + let _table = table!(["ABC", "DEFG", "HIJKLMN"], + ["foobar", "bar", "foo"], + ["foobar2", "bar2", "foo2"]); + + // Or directly print it like this + let _table = ptable!(["ABC", "DEFG", "HIJKLMN"], + ["foobar", "bar", "foo"], + ["foobar2", "bar2", "foo2"]); +} diff --git a/examples/csv.rs b/examples/csv.rs index 68958ef..dd104af 100644 --- a/examples/csv.rs +++ b/examples/csv.rs @@ -20,7 +20,8 @@ fn main() { let table = Table::from_csv_string("ABC,DEFG,HIJKLMN\n\ foobar,bar,foo\n\ - foobar2,bar2,foo2").unwrap(); + foobar2,bar2,foo2") + .unwrap(); table.printstd(); println!(""); diff --git a/examples/formatting.rs b/examples/formatting.rs index d994796..a3cbc51 100644 --- a/examples/formatting.rs +++ b/examples/formatting.rs @@ -1,87 +1,86 @@ -#[macro_use] extern crate prettytable;
-use prettytable::format;
-
-fn main() {
- let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]);
- table.set_titles(row!["Title 1", "Title 2"]);
-
- // Print
- // +-------------+------------+
- // | Title 1 | Title 2 |
- // +-------------+------------+
- // | Value 1 | Value 2 |
- // | Value three | Value four |
- // +-------------+------------+
- println!("FORMAT_NO_LINESEP_WITH_TITLE :");
- table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE);
- table.printstd();
- println!("");
-
- // Print
- // -------------------------
- // Title 1 Title 2
- // =========================
- // Value 1 Value 2
- // -------------------------
- // Value three Value four
- // -------------------------
- println!("FORMAT_NO_COLSEP :");
- table.set_format(*format::consts::FORMAT_NO_COLSEP);
- table.printstd();
- println!("");
-
- // Print
- // +-------------------------+
- // | Title 1 Title 2 |
- // +=========================+
- // | Value 1 Value 2 |
- // | Value three Value four |
- // +-------------------------+
- println!("FORMAT_BORDERS_ONLY :");
- table.set_format(*format::consts::FORMAT_BORDERS_ONLY);
- table.printstd();
- println!("");
-
- // Custom format can be implemented using `prettytable::format::FormatBuilder`
- // Example to print
- // +-------------+------------+
- // | Title 1 | Title 2 |
- // | Value 1 | Value 2 |
- // | Value three | Value four |
- // +-------------+------------+
- println!("Custom :");
- table.set_format(
- format::FormatBuilder::new()
- .column_separator('|')
- .borders('|')
- .separators(
- &[format::LinePosition::Top, format::LinePosition::Bottom],
- format::LineSeparator::new('-', '+', '+', '+')
- )
- .padding(1, 1)
- .build()
- );
- table.printstd();
-
- // Customized format with unicode
- // Example to print
- // ┌─────────────┬────────────┐
- // | Title 1 | Title 2 |
- // ├─────────────┼────────────┤
- // | Value 1 | Value 2 |
- // ├─────────────┼────────────┤
- // | Value three | Value four |
- // └─────────────┴────────────┘
- println!("With unicode:");
- table.set_format(
- format::FormatBuilder::new()
- .column_separator('|')
- .borders('|')
- .separators( &[format::LinePosition::Top], format::LineSeparator::new('─', '┬', '┌', '┐'))
- .separators( &[format::LinePosition::Intern], format::LineSeparator::new('─', '┼', '├', '┤'))
- .separators( &[format::LinePosition::Bottom], format::LineSeparator::new('─', '┴', '└', '┘'))
- .padding(1, 1)
- .build()
- );
- table.printstd();
-}
+#[macro_use] +extern crate prettytable; +use prettytable::format; + +fn main() { + let mut table = table!(["Value 1", "Value 2"], ["Value three", "Value four"]); + table.set_titles(row!["Title 1", "Title 2"]); + + // Print + // +-------------+------------+ + // | Title 1 | Title 2 | + // +-------------+------------+ + // | Value 1 | Value 2 | + // | Value three | Value four | + // +-------------+------------+ + println!("FORMAT_NO_LINESEP_WITH_TITLE :"); + table.set_format(*format::consts::FORMAT_NO_LINESEP_WITH_TITLE); + table.printstd(); + println!(""); + + // Print + // ------------------------- + // Title 1 Title 2 + // ========================= + // Value 1 Value 2 + // ------------------------- + // Value three Value four + // ------------------------- + println!("FORMAT_NO_COLSEP :"); + table.set_format(*format::consts::FORMAT_NO_COLSEP); + table.printstd(); + println!(""); + + // Print + // +-------------------------+ + // | Title 1 Title 2 | + // +=========================+ + // | Value 1 Value 2 | + // | Value three Value four | + // +-------------------------+ + println!("FORMAT_BORDERS_ONLY :"); + table.set_format(*format::consts::FORMAT_BORDERS_ONLY); + table.printstd(); + println!(""); + + // Custom format can be implemented using `prettytable::format::FormatBuilder` + // Example to print + // +-------------+------------+ + // | Title 1 | Title 2 | + // | Value 1 | Value 2 | + // | Value three | Value four | + // +-------------+------------+ + println!("Custom :"); + table.set_format(format::FormatBuilder::new() + .column_separator('|') + .borders('|') + .separators(&[format::LinePosition::Top, + format::LinePosition::Bottom], + format::LineSeparator::new('-', '+', '+', '+')) + .padding(1, 1) + .build()); + table.printstd(); + + // Customized format with unicode + // Example to print + // ┌─────────────┬────────────┐ + // | Title 1 | Title 2 | + // ├─────────────┼────────────┤ + // | Value 1 | Value 2 | + // ├─────────────┼────────────┤ + // | Value three | Value four | + // └─────────────┴────────────┘ + println!("With unicode:"); + table.set_format(format::FormatBuilder::new() + .column_separator('|') + .borders('|') + .separators(&[format::LinePosition::Top], + format::LineSeparator::new('─', '┬', '┌', '┐')) + .separators(&[format::LinePosition::Intern], + format::LineSeparator::new('─', '┼', '├', '┤')) + .separators(&[format::LinePosition::Bottom], + format::LineSeparator::new('─', '┴', '└', '┘')) + .padding(1, 1) + .build()); + table.printstd(); +} diff --git a/examples/multiline.rs b/examples/multiline.rs index 3015fe6..e633531 100644 --- a/examples/multiline.rs +++ b/examples/multiline.rs @@ -1,5 +1,6 @@ -#[macro_use] extern crate prettytable;
-
+#[macro_use] +extern crate prettytable; + /*
Following main function will print :
+-------------------------+------------------------------+
@@ -17,15 +18,13 @@ | | | foobar2 | bar2 | foo2 | |
| | +---------+------+---------+ |
+-------------------------+------------------------------+
-*/
-fn main() {
- let table1 = table!(["ABC", "DEFG", "HIJKLMN"],
- ["foobar", "bar", "foo"],
- ["foobar2", "bar2", "foo2"]
- );
- let table2 = table!(["Title 1", "Title 2"],
- ["This is\na multiline\ncell", "foo"],
- ["Yo dawg ;) You can even\nprint tables\ninto tables", table1]
- );
- table2.printstd();
-}
+*/ +fn main() { + let table1 = table!(["ABC", "DEFG", "HIJKLMN"], + ["foobar", "bar", "foo"], + ["foobar2", "bar2", "foo2"]); + let table2 = table!(["Title 1", "Title 2"], + ["This is\na multiline\ncell", "foo"], + ["Yo dawg ;) You can even\nprint tables\ninto tables", table1]); + table2.printstd(); +} diff --git a/examples/slices.rs b/examples/slices.rs index 1bef3a3..38e07ee 100644 --- a/examples/slices.rs +++ b/examples/slices.rs @@ -1,15 +1,16 @@ -#[macro_use] extern crate prettytable;
-
-use prettytable::Slice;
-
-fn main() {
- let mut table = table![[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]];
- table.set_titles(row!["t1", "t2", "t3"]);
-
- let slice = table.slice(..);
- let slice = slice.slice(2..);
- let slice = slice.slice(..3);
-
+#[macro_use] +extern crate prettytable; + +use prettytable::Slice; + +fn main() { + let mut table = table![[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4], [5, 5, 5]]; + table.set_titles(row!["t1", "t2", "t3"]); + + let slice = table.slice(..); + let slice = slice.slice(2..); + let slice = slice.slice(..3); + /*
Will print
+----+----+----+
@@ -21,10 +22,10 @@ fn main() { +----+----+----+
| 4 | 4 | 4 |
+----+----+----+
- */
- slice.printstd();
-
- // This is equivalent to
- let slice = table.slice(2..5);
- slice.printstd();
-}
+ */ + slice.printstd(); + + // This is equivalent to + let slice = table.slice(2..5); + slice.printstd(); +} diff --git a/examples/style.rs b/examples/style.rs index 8191372..843061f 100644 --- a/examples/style.rs +++ b/examples/style.rs @@ -1,19 +1,20 @@ -#[macro_use] extern crate prettytable;
-extern crate term;
-use prettytable::Table;
-use prettytable::row::Row;
-use prettytable::cell::Cell;
-
-use term::{Attr, color};
-
-#[allow(dead_code)]
-fn main() {
- let _ = table!();
- let mut table = Table::new();
- // Add style to a cell
- table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]);
- // Add style to a full row
- table.add_row(row![FY => "styled", "bar", "foo"]);
+#[macro_use] +extern crate prettytable; +extern crate term; +use prettytable::Table; +use prettytable::row::Row; +use prettytable::cell::Cell; + +use term::{Attr, color}; + +#[allow(dead_code)] +fn main() { + let _ = table!(); + let mut table = Table::new(); + // Add style to a cell + table.add_row(row![FrByb->"ABC", "DEFG", "HIJKLMN"]); + // Add style to a full row + table.add_row(row![FY => "styled", "bar", "foo"]); table.add_row(Row::new(vec![
Cell::new("foobar2"),
// Create a cell with a red foreground color
@@ -22,17 +23,17 @@ fn main() { Cell::new("foo2").style_spec("FrByb"),
// Using the cell! macro
cell!(Fr->"red")])
- );
-
- table.printstd();
-
- // Print a table with some styles on it :
- // FrBybl means : Foregound red, Background yellow, bold, left align
- ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]);
-
- // You can also apply style to full rows :
- let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]);
- // Set a title line, with all text centered in the cell
- table.set_titles(row![c => "Title 1", "Title 2"]);
- table.printstd();
-}
+ ); + + table.printstd(); + + // Print a table with some styles on it : + // FrBybl means : Foregound red, Background yellow, bold, left align + ptable!([FrBybl->"A", "B", FrBybr->"C"], [123, 234, 345, 456], [Fg => 1, 2, 3]); + + // You can also apply style to full rows : + let mut table = table!([Frb => "A", "B", "C"], [1, 2, 3, 4], ["A\nBCCZZZ\nDDD", 2, table]); + // Set a title line, with all text centered in the cell + table.set_titles(row![c => "Title 1", "Title 2"]); + table.printstd(); +} diff --git a/examples/tictactoe.rs b/examples/tictactoe.rs index 3d25057..49444eb 100644 --- a/examples/tictactoe.rs +++ b/examples/tictactoe.rs @@ -1,90 +1,98 @@ -#[macro_use]extern crate prettytable;
-use prettytable::Table;
-
-use std::io;
-use std::io::Write;
-use std::str::FromStr;
-
-const CROSS: &'static str = "X";
-const EMPTY: &'static str = " ";
-const ROUND: &'static str = "O";
-
-fn main() {
- let mut table = table![[EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY], [EMPTY, EMPTY, EMPTY]];
- table.printstd();
- let stdin = io::stdin();
- let mut stdout = io::stdout();
- let mut current = CROSS;
- loop {
- let mut line = String::new();
- print!("{} plays > ", current);
- stdout.flush().unwrap();
- stdin.read_line(&mut line).expect("Cannot read input");
+#[macro_use] +extern crate prettytable; +use prettytable::Table; + +use std::io; +use std::io::Write; +use std::str::FromStr; + +const CROSS: &'static str = "X"; +const EMPTY: &'static str = " "; +const ROUND: &'static str = "O"; + +fn main() { + let mut table = table![[EMPTY, EMPTY, EMPTY], + [EMPTY, EMPTY, EMPTY], + [EMPTY, EMPTY, EMPTY]]; + table.printstd(); + let stdin = io::stdin(); + let mut stdout = io::stdout(); + let mut current = CROSS; + loop { + let mut line = String::new(); + print!("{} plays > ", current); + stdout.flush().unwrap(); + stdin.read_line(&mut line).expect("Cannot read input"); let i = match usize::from_str(line.trim()) {
Ok(i) => i,
- _ => {
- println!("Bad input");
- continue;
+ _ => { + println!("Bad input"); + continue; }
- };
- if i < 1 || i > 9 {
- println!("Bad input, should be between 1 and 9");
- continue;
- }
- let x = (i-1)%3;
- let y = (i-1)/3;
- {
- let mut row = table.get_mut_row(y).unwrap();
- if row.get_cell(x).unwrap().to_string() != EMPTY {
- println!("There's already someone there");
- continue;
- }
- row.set_cell(cell!(current), x).unwrap();
- }
- table.printstd();
- if check(&table) {
- return
- }
- if current == CROSS {
- current = ROUND;
- } else {
- current = CROSS;
- }
- }
-}
-
-fn get(table: &Table, x: usize, y: usize) -> String {
+ }; + if i < 1 || i > 9 { + println!("Bad input, should be between 1 and 9"); + continue; + } + let x = (i - 1) % 3; + let y = (i - 1) / 3; + { + let mut row = table.get_mut_row(y).unwrap(); + if row.get_cell(x).unwrap().to_string() != EMPTY { + println!("There's already someone there"); + continue; + } + row.set_cell(cell!(current), x).unwrap(); + } + table.printstd(); + if check(&table) { + return; + } + if current == CROSS { + current = ROUND; + } else { + current = CROSS; + } + } +} + +fn get(table: &Table, x: usize, y: usize) -> String { match table.get_row(y) {
- Some(ref r) => match r.get_cell(x){
- Some(ref c) => c.to_string(),
- _ => EMPTY.to_string()
- },
- _ => EMPTY.to_string()
- }
-}
-
-fn is(table: &Table, s : &str, x: usize, y: usize) -> bool {
- get(table, x, y).as_str() == s
-}
-
-fn check(table: &Table) -> bool {
- let mut full = true;
- for y in 0..3 {
- for x in 0..3 {
- if is(table, EMPTY, x, y) {
- full = false;
- continue;
- }
- let current = get(table, x, y);
- let c = current.as_str();
- if is(table, c, x+1, y) && is(table, c, x+2, y) || is(table, c, x+1, y+1) && is(table, c, x+2, y+2) || x >= 2 && is(table, c, x-1, y+1) && is(table, c, x-2, y+2) || is(table, c, x, y+1) && is(table, c, x, y+2) {
- println!("Game is over. {} is the winner", current);
- return true;
- }
+ Some(ref r) => { + match r.get_cell(x) {
+ Some(ref c) => c.to_string(),
+ _ => EMPTY.to_string(),
+ } }
- }
- if full {
- println!("Game is over. It's a draw");
- }
- return full;
-}
+ _ => EMPTY.to_string(),
+ } +} + +fn is(table: &Table, s: &str, x: usize, y: usize) -> bool { + get(table, x, y).as_str() == s +} + +fn check(table: &Table) -> bool { + let mut full = true; + for y in 0..3 { + for x in 0..3 { + if is(table, EMPTY, x, y) { + full = false; + continue; + } + let current = get(table, x, y); + let c = current.as_str(); + if is(table, c, x + 1, y) && is(table, c, x + 2, y) || + is(table, c, x + 1, y + 1) && is(table, c, x + 2, y + 2) || + x >= 2 && is(table, c, x - 1, y + 1) && is(table, c, x - 2, y + 2) || + is(table, c, x, y + 1) && is(table, c, x, y + 2) { + println!("Game is over. {} is the winner", current); + return true; + } + } + } + if full { + println!("Game is over. It's a draw"); + } + return full; +} diff --git a/src/cell.rs b/src/cell.rs index 40a1141..18aadd0 100644 --- a/src/cell.rs +++ b/src/cell.rs @@ -1,114 +1,114 @@ -//! This module contains definition of table/row cells stuff
-
-use std::io::{Write, Error};
-use std::string::ToString;
-use unicode_width::UnicodeWidthStr;
-use term::{Attr, Terminal, color};
-use super::format::Alignment;
-use super::utils::print_align;
-
-/// Represent a table cell containing a string.
-///
-/// Once created, a cell's content cannot be modified.
-/// The cell would have to be replaced by another one
-#[derive(Clone, Debug)]
-pub struct Cell {
- content: Vec<String>,
- width: usize,
- align: Alignment,
- style: Vec<Attr>
-}
-
-impl Cell {
- /// Create a new `Cell` initialized with content from `string`.
- /// Text alignment in cell is configurable with the `align` argument
- pub fn new_align(string: &str, align: Alignment) -> Cell {
- let content: Vec<String> = string.lines().map(|ref x| x.to_string()).collect();
- let mut width = 0;
- for cont in &content {
- let l = UnicodeWidthStr::width(&cont[..]);
- if l > width {
- width = l;
- }
- }
- Cell {
- content: content,
- width: width,
- align: align,
- style: Vec::new()
- }
- }
-
- /// Create a new `Cell` initialized with content from `string`.
- /// By default, content is align to `LEFT`
- pub fn new(string: &str) -> Cell {
- Cell::new_align(string, Alignment::LEFT)
- }
-
- /// Set text alignment in the cell
- pub fn align(&mut self, align: Alignment) {
- self.align = align;
- }
-
- /// Add a style attribute to the cell
- pub fn style(&mut self, attr: Attr) {
- self.style.push(attr);
- }
-
- /// Add a style attribute to the cell. Can be chained
- pub fn with_style(mut self, attr: Attr) -> Cell {
- self.style(attr);
- self
- }
-
- /// Remove all style attributes and reset alignment to default (LEFT)
- pub fn reset_style(&mut self) {
- self.style.clear();
- self.align(Alignment::LEFT);
- }
-
- /// Set the cell's style by applying the given specifier string
- ///
- /// # Style spec syntax
- ///
- /// The syntax for the style specifier looks like this :
- /// **FrBybl** which means **F**oreground **r**ed **B**ackground **y**ellow **b**old **l**eft
- ///
- /// ### List of supported specifiers :
- ///
- /// * **F** : **F**oreground (must be followed by a color specifier)
- /// * **B** : **B**ackground (must be followed by a color specifier)
- /// * **b** : **b**old
- /// * **i** : **i**talic
- /// * **u** : **u**nderline
- /// * **c** : Align **c**enter
- /// * **l** : Align **l**eft
- /// * **r** : Align **r**ight
- /// * **d** : **d**efault style
- ///
- /// ### List of color specifiers :
- ///
- /// * **r** : Red
- /// * **b** : Blue
- /// * **g** : Green
- /// * **y** : Yellow
- /// * **c** : Cyan
- /// * **m** : Magenta
- /// * **w** : White
- /// * **d** : Black
- ///
- /// And capital letters are for **bright** colors.
- /// Eg :
- ///
- /// * **R** : Bright Red
- /// * **B** : Bright Blue
- /// * ... and so on ...
- pub fn style_spec(mut self, spec: &str) -> Cell {
- self.reset_style();
- let mut foreground = false;
- let mut background = false;
- for c in spec.chars() {
- if foreground || background {
+//! This module contains definition of table/row cells stuff + +use std::io::{Write, Error}; +use std::string::ToString; +use unicode_width::UnicodeWidthStr; +use term::{Attr, Terminal, color}; +use super::format::Alignment; +use super::utils::print_align; + +/// Represent a table cell containing a string. +/// +/// Once created, a cell's content cannot be modified. +/// The cell would have to be replaced by another one +#[derive(Clone, Debug)] +pub struct Cell { + content: Vec<String>, + width: usize, + align: Alignment, + style: Vec<Attr>, +} + +impl Cell { + /// Create a new `Cell` initialized with content from `string`. + /// Text alignment in cell is configurable with the `align` argument + pub fn new_align(string: &str, align: Alignment) -> Cell { + let content: Vec<String> = string.lines().map(|ref x| x.to_string()).collect(); + let mut width = 0; + for cont in &content { + let l = UnicodeWidthStr::width(&cont[..]); + if l > width { + width = l; + } + } + Cell { + content: content, + width: width, + align: align, + style: Vec::new(), + } + } + + /// Create a new `Cell` initialized with content from `string`. + /// By default, content is align to `LEFT` + pub fn new(string: &str) -> Cell { + Cell::new_align(string, Alignment::LEFT) + } + + /// Set text alignment in the cell + pub fn align(&mut self, align: Alignment) { + self.align = align; + } + + /// Add a style attribute to the cell + pub fn style(&mut self, attr: Attr) { + self.style.push(attr); + } + + /// Add a style attribute to the cell. Can be chained + pub fn with_style(mut self, attr: Attr) -> Cell { + self.style(attr); + self + } + + /// Remove all style attributes and reset alignment to default (LEFT) + pub fn reset_style(&mut self) { + self.style.clear(); + self.align(Alignment::LEFT); + } + + /// Set the cell's style by applying the given specifier string + /// + /// # Style spec syntax + /// + /// The syntax for the style specifier looks like this : + /// **FrBybl** which means **F**oreground **r**ed **B**ackground **y**ellow **b**old **l**eft + /// + /// ### List of supported specifiers : + /// + /// * **F** : **F**oreground (must be followed by a color specifier) + /// * **B** : **B**ackground (must be followed by a color specifier) + /// * **b** : **b**old + /// * **i** : **i**talic + /// * **u** : **u**nderline + /// * **c** : Align **c**enter + /// * **l** : Align **l**eft + /// * **r** : Align **r**ight + /// * **d** : **d**efault style + /// + /// ### List of color specifiers : + /// + /// * **r** : Red + /// * **b** : Blue + /// * **g** : Green + /// * **y** : Yellow + /// * **c** : Cyan + /// * **m** : Magenta + /// * **w** : White + /// * **d** : Black + /// + /// And capital letters are for **bright** colors. + /// Eg : + /// + /// * **R** : Bright Red + /// * **B** : Bright Blue + /// * ... and so on ... + pub fn style_spec(mut self, spec: &str) -> Cell { + self.reset_style(); + let mut foreground = false; + let mut background = false; + for c in spec.chars() { + if foreground || background { let color = match c {
'r' => color::RED,
'R' => color::BRIGHT_RED,
@@ -126,18 +126,21 @@ impl Cell { 'W' => color::BRIGHT_WHITE,
'd' => color::BLACK,
'D' => color::BRIGHT_BLACK,
- _ => { // Silently ignore unknown tags
- foreground = false;
- background = false;
- continue;
- }
- };
- if foreground { self.style(Attr::ForegroundColor(color)); }
- else if background { self.style(Attr::BackgroundColor(color)); }
- foreground = false;
- background = false;
- }
- else {
+ _ => { + // Silently ignore unknown tags + foreground = false; + background = false; + continue; + }
+ }; + if foreground { + self.style(Attr::ForegroundColor(color)); + } else if background { + self.style(Attr::BackgroundColor(color)); + } + foreground = false; + background = false; + } else { match c {
'F' => foreground = true,
'B' => background = true,
@@ -147,209 +150,225 @@ impl Cell { 'c' => self.align(Alignment::CENTER),
'l' => self.align(Alignment::LEFT),
'r' => self.align(Alignment::RIGHT),
- 'd' => {/* Default : do nothing */}
- _ => {/* Silently ignore unknown tags */}
- }
- }
- }
- return self;
- }
-
- /// Return the height of the cell
- pub fn get_height(&self) -> usize {
- self.content.len()
- }
-
- /// Return the width of the cell
- pub fn get_width(&self) -> usize {
- self.width
- }
-
- /// Return a copy of the full string contained in the cell
- pub fn get_content(&self) -> String {
- self.content.join("\n")
- }
-
- /// Print a partial cell to `out`. Since the cell may be multi-lined,
- /// `idx` is the line index to print. `col_width` is the column width used to
- /// fill the cells with blanks so it fits in the table.
- /// If `ìdx` is higher than this cell's height, it will print empty content
- pub fn print<T: Write+?Sized>(&self, out: &mut T, idx: usize, col_width: usize, skip_right_fill: bool) -> Result<(), Error> {
- let c = self.content.get(idx).map(|s| s.as_ref()).unwrap_or("");
- print_align(out, self.align, c, ' ', col_width, skip_right_fill)
- }
-
- /// Apply style then call `print` to print the cell into a terminal
- pub fn print_term<T: Terminal+?Sized>(&self, out: &mut T, idx: usize, col_width: usize, skip_right_fill: bool) -> Result<(), Error> {
- for a in &self.style {
+ 'd' => { /* Default : do nothing */ }
+ _ => { /* Silently ignore unknown tags */ }
+ } + } + } + return self; + } + + /// Return the height of the cell + pub fn get_height(&self) -> usize { + self.content.len() + } + + /// Return the width of the cell + pub fn get_width(&self) -> usize { + self.width + } + + /// Return a copy of the full string contained in the cell + pub fn get_content(&self) -> String { + self.content.join("\n") + } + + /// Print a partial cell to `out`. Since the cell may be multi-lined, + /// `idx` is the line index to print. `col_width` is the column width used to + /// fill the cells with blanks so it fits in the table. + /// If `ìdx` is higher than this cell's height, it will print empty content + pub fn print<T: Write + ?Sized>(&self, + out: &mut T, + idx: usize, + col_width: usize, + skip_right_fill: bool) + -> Result<(), Error> { + let c = self.content.get(idx).map(|s| s.as_ref()).unwrap_or(""); + |