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
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
/*!

This crate provides a library for displaying tabular data in, for instance, a command
line app.

# Usage

Colonnade is [on crates.io](https://crates.io/crates/colonnade) and can be
used by adding `colonnade` to your dependencies in your project's `Cargo.toml`.

```toml
[dependencies]
colonnade = "0"
```

# Example

```rust
extern crate colonnade;
use colonnade::{Alignment, Colonnade};

#[allow(unused_must_use)]
fn main() {
    // text to put in tabular form
    let text = vec![
        vec![
            "Colonnade lets you format text in columns.",
            "As you can see, it supports text alignment, viewport width, and column widths.",
            "It doesn't yet support color codes or other formatting, though that may come.",
        ],
        vec!["", "Two or more rows of columns makes a table.", ""],
    ];

    // 3 columns of text in an 80-character viewport
    let mut colonnade = Colonnade::new(3, 80).unwrap();

    // configure the table a bit
    colonnade.left_margin_all(4);
    colonnade.left_margin(0, 8); // the first column should have a left margin 8 spaces wide
    colonnade.fixed_width_all(15);
    colonnade.clear_limits(1); // the central column has no fixed size limits
    colonnade.alignment(0, Alignment::Right);
    colonnade.alignment(1, Alignment::Center);
    colonnade.alignment(2, Alignment::Left);
    colonnade.spaces_between_rows(1); // add a blank link between rows

    // now print out the table
    for line in colonnade.tabulate(&text).unwrap() {
        println!("{}", line);
    }
}
```
which produces
```plain
         Colonnade lets     As you can see, it supports text     It doesn't yet
        you format text      alignment, viewport width, and      support color
            in columns.              column widths.              codes or other
                                                                 formatting,
                                                                 though that may
                                                                 come.

                           Two or more rows of columns makes
                                        a table.
```
If Colonnade doesn't have enough space in a column to fit the text, it will attempt to
wrap it, splitting on whitespace. If this is not possible because a word in the text is
so long it does not fit in the column, it will fit as much as it can, splitting mid-word
and marking the split with a hyphen (unless the column is only one character wide).

To control the layout you can specify minimum and maximum column widths and column priorities.
If the columns differ in priority, lower priority, higher priority number, columns will
get wrapped first.
*/
use std::fmt;
use std::iter;

/// All the things that can go wrong when laying out tabular data.
#[derive(Debug)]
pub enum ColonnadeError {
    /// The data to display is inconsistent with the spec.
    /// The tuple values are the index of the data row, its length, and the expected length.
    InconsistentColumns(usize, usize, usize), // row, row length, spec length
    /// The column index provided is outside the columns available.
    OutOfBounds,
    /// The column count parameter given to the constructor was 0.
    InsufficientColumns,
    /// The minimum space required by the columns is greater than the viewport.
    InsufficientSpace,
    /// The minimum and maximum width of a column conflict. The stored parameter is the column index.
    MinGreaterThanMax(usize), // column
}

impl std::fmt::Display for ColonnadeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}

impl std::error::Error for ColonnadeError {}

/// Alignments one can apply to columns of text.
#[derive(Debug, Clone)]
pub enum Alignment {
    /// Left justification -- the default alignment
    Left,
    /// Right justification
    Right,
    /// Centering
    Center,
}

#[derive(Debug, Clone)]
struct ColumnSpec {
    alignment: Alignment,
    left_margin: usize,
    width: usize,
    priority: usize,
    min_width: Option<usize>,
    max_width: Option<usize>,
}

impl ColumnSpec {
    fn default() -> ColumnSpec {
        ColumnSpec {
            alignment: Alignment::Left,
            left_margin: 1,
            width: 0, // claimed width
            priority: usize::max_value(),
            min_width: None,
            max_width: None,
        }
    }
    fn effective_width(&self) -> usize {
        let w = if self.max_width.unwrap_or(self.width) < self.width {
            self.max_width.unwrap()
        } else {
            self.width
        };
        if self.min_width.unwrap_or(w) > w {
            self.min_width.unwrap()
        } else {
            w
        }
    }
    fn is_shrinkable(&self) -> bool {
        self.min_width.unwrap_or(0) < self.width
    }
    // shrink as close to width as possible
    fn shrink(&mut self, width: usize) {
        self.width = if self.min_width.unwrap_or(width) > width {
            self.min_width.unwrap()
        } else {
            width
        }
    }
    // attempt to shrink by decrease amount
    // returns whether there was any shrinkage
    fn shrink_by(&mut self, decrease: usize) -> bool {
        if self.is_shrinkable() {
            // you can't shrink all the way to 0
            let decrease = if decrease >= self.width {
                1
            } else {
                self.width - decrease
            };
            let before = self.width;
            self.shrink(decrease);
            before != self.width
        } else {
            false
        }
    }
    fn is_expandable(&self) -> bool {
        self.max_width.unwrap_or(usize::max_value()) > self.width
    }
    // expands column as much as possible to fit width and as much as necessary to match min_width
    fn expand(&mut self, width: usize) -> bool {
        if width <= self.width {
            return false;
        }
        let change = if self.max_width.unwrap_or(width) < width {
            self.max_width.unwrap()
        } else if self.min_width.unwrap_or(width) > width {
            self.min_width.unwrap()
        } else {
            width
        };
        let changed = self.width != change;
        if changed {
            self.width = change
        }
        changed
    }
    fn expand_by(&mut self, increase: usize) -> bool {
        self.expand(self.width + increase)
    }
    fn outer_width(&self) -> usize {
        self.left_margin + self.effective_width()
    }
}

/// A struct holding formatting information. This is the object which tabulates data.
#[derive(Debug, Clone)]
pub struct Colonnade {
    colonnade: Vec<ColumnSpec>,
    width: usize,
    spaces_between_rows: usize,
    adjusted: bool,
}

// find the longest sequence of non-whitespace characters in a string
fn longest_word(s: &str) -> usize {
    s.split_whitespace()
        .fold(0, |acc, v| if v.len() > acc { v.len() } else { acc })
}

impl Colonnade {
    /// Construct a `Colonnade` with default values: left alignment, no column size
    /// constraints, no blank lines between rows, 1 space margin between columns.
    ///
    /// # Arguments
    ///
    /// * `columns` - The number of columns of data to expect
    /// * `width` - Viewport size in characters
    ///
    /// # Errors
    ///
    /// * `ColonnadeError::InsufficientSpace` - the viewport isn't wide enough for the columns and their margins
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// let colonnade = Colonnade::new(4, 100);
    /// ```
    pub fn new(columns: usize, width: usize) -> Result<Colonnade, ColonnadeError> {
        if columns == 0 {
            return Err(ColonnadeError::InsufficientColumns);
        }
        let mut colonnade: Vec<ColumnSpec> =
            iter::repeat(ColumnSpec::default()).take(columns).collect();
        colonnade[0].left_margin = 0;
        let spec = Colonnade {
            colonnade,
            width,
            spaces_between_rows: 0,
            adjusted: false,
        };
        if !spec.sufficient_space() {
            return Err(ColonnadeError::InsufficientSpace);
        }
        Ok(spec)
    }
    // the absolute minimal space that might fit this table assuming some data in every column
    fn minimal_width(&self) -> usize {
        self.colonnade
            .iter()
            .fold(0, |acc, v| acc + v.left_margin + v.min_width.unwrap_or(1)) // assume each column requires at least one character
    }
    fn sufficient_space(&self) -> bool {
        self.minimal_width() <= self.width
    }
    // the amount of space required to display the data given the current column specs
    fn required_width(&self) -> usize {
        self.colonnade
            .iter()
            .fold(0, |acc, v| acc + v.outer_width())
    }
    fn len(&self) -> usize {
        self.colonnade.len()
    }
    // determine the characters required to represent s after whitespace normalization
    fn width_after_normalization(s: &str) -> usize {
        let mut l = 0;
        for w in s.trim().split_whitespace() {
            if l != 0 {
                l += 1;
            }
            l += w.len();
        }
        l
    }
    // returns priorites sorted lowest to highest
    fn priorities(&self) -> Vec<usize> {
        let mut v = self
            .colonnade
            .iter()
            .map(|c| c.priority)
            .collect::<Vec<_>>();
        v.sort_unstable();
        v.dedup();
        v.reverse();
        v
    }
    /// Construct a `Colonnade` with default values: left alignment, no column size
    /// constraints, no blank lines between rows, 1 space margin between columns.
    ///
    /// # Arguments
    ///
    /// * `table` - The data to display.
    ///
    /// # Errors
    ///
    /// Any errors of [`lay_out`](#method.lay_out). If the data has already been laid out, this method will throw no errors.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// let data = vec![vec!["some", "words", "for", "example"]];
    /// let lines = colonnade.tabulate(&data)?;
    /// # Ok(()) }
    /// ```
    pub fn tabulate(&mut self, table: &Vec<Vec<&str>>) -> Result<Vec<String>, ColonnadeError> {
        if !self.adjusted {
            match self.lay_out(table) {
                Err(e) => return Err(e),
                Ok(()) => (),
            }
        }
        let mut buffer = vec![];
        for (i, row) in table.iter().enumerate() {
            self.add_row(&mut buffer, row, i == table.len() - 1);
        }
        Ok(buffer)
    }
    // take one row of untabulated pieces of text and turn it into one or more lines of tabulated text
    fn add_row(&self, buffer: &mut Vec<String>, row: &Vec<&str>, last_row: bool) {
        let mut words: Vec<Vec<&str>> = row
            .iter()
            .map(|w| w.trim().split_whitespace().collect())
            .collect();
        if words.iter().all(|sentence| sentence.is_empty()) {
            // blank line
            buffer.push(String::new());
            if !last_row {
                for _ in 0..self.spaces_between_rows {
                    buffer.push(String::new());
                }
            }
            return;
        }
        while !words.iter().all(|sentence| sentence.is_empty()) {
            let mut line = String::new();
            for (i, c) in self.colonnade.iter().enumerate() {
                for _ in 0..c.left_margin {
                    line += " "
                }
                if words[i].is_empty() {
                    // we've used this one up, but there are still words to deal with in other sentences
                    for _ in 0..c.width {
                        line += " "
                    }
                } else {
                    let mut l = 0;
                    let mut phrase = String::new();
                    let mut first = true;
                    while !words[i].is_empty() {
                        let w = words[i].remove(0);
                        if first {
                            if w.len() == c.width {
                                // word fills column
                                phrase += w;
                                break;
                            } else if w.len() > c.width {
                                // word overflows column and we must split it
                                if c.width > 1 {
                                    phrase += &w[0..(c.width - 1)];
                                    words[i].insert(0, &w[(c.width - 1)..w.len()]);
                                    phrase += "-";
                                } else {
                                    phrase += &w[0..1];
                                    words[i].insert(0, &w[1..w.len()]);
                                }
                                break;
                            }
                        }
                        // try to tack on a new word
                        let new_length = l + w.len() + if first { 0 } else { 1 };
                        if new_length > c.width {
                            words[i].insert(0, w);
                            break;
                        } else {
                            if first {
                                first = false;
                            } else {
                                phrase += " ";
                            }
                            phrase += w;
                            l = new_length;
                        }
                    }
                    // pad phrase out propery in its cell
                    if phrase.len() < c.width {
                        let surplus = c.width - phrase.len();
                        match c.alignment {
                            Alignment::Left => {
                                line += &phrase;
                                for _ in 0..surplus {
                                    line += " "
                                }
                            }
                            Alignment::Center => {
                                let left_bit = surplus / 2;
                                for _ in 0..left_bit {
                                    line += " "
                                }
                                line += &phrase;
                                for _ in 0..(surplus - left_bit) {
                                    line += " "
                                }
                            }
                            Alignment::Right => {
                                for _ in 0..surplus {
                                    line += " "
                                }
                                line += &phrase;
                            }
                        }
                    } else {
                        line += &phrase;
                    }
                }
            }
            buffer.push(line);
        }
        if !last_row {
            for _ in 0..self.spaces_between_rows {
                buffer.push(String::new());
            }
        }
    }
    /// Determine column widths given data.
    ///
    /// Normally you do not need to call this method because it is called when you [`tabulate`](#method.tabulate)
    /// the first batch of data. However, this initial layout will then be used for every subsequent batch
    /// of data regardless of its size. If you want to re-flow the table to better fit the new data, you acn
    /// call `layout`.
    ///
    /// # Arguments
    ///
    /// * `table` - The data to display.
    ///
    /// # Errors
    ///
    /// * `ColonnadeError::InconsistentColumns` - The number of columns in some row of `table` does not match the spec.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// let data = vec![vec!["some", "words", "for", "example"]];
    /// let lines = colonnade.tabulate(&data)?;
    /// // ... later
    /// let data = vec![vec!["a very different, wider", "set of", "words that won't fit comfortably in the old layout"]];
    /// // reflow table
    /// colonnade.lay_out(&data)?;
    /// let lines = colonnade.tabulate(&data)?;
    /// # Ok(()) }
    /// ```
    pub fn lay_out(&mut self, table: &Vec<Vec<&str>>) -> Result<(), ColonnadeError> {
        // validate table
        for i in 0..table.len() {
            let row = &table[i];
            if row.len() != self.len() {
                return Err(ColonnadeError::InconsistentColumns(
                    i,
                    row.len(),
                    self.len(),
                ));
            }
        }
        // first try to do it all without splitting
        for i in 0..table.len() {
            for c in 0..self.len() {
                let m = Colonnade::width_after_normalization(&table[i][c]);
                if m >= self.colonnade[c].width {
                    // = to force initial expansion to min width
                    self.colonnade[c].expand(m);
                }
            }
        }
        if self.required_width() <= self.width {
            self.adjusted = true;
            return Ok(());
        }
        let mut modified_columns: Vec<usize> = Vec::with_capacity(self.len());
        // try shrinking columns to their longest word by order of priority
        for p in self.priorities() {
            for c in 0..self.len() {
                if self.colonnade[c].priority == p && self.colonnade[c].is_shrinkable() {
                    modified_columns.push(c);
                    self.colonnade[c].shrink(0);
                    for r in 0..table.len() {
                        let m = longest_word(&table[r][c]);
                        if m > self.colonnade[c].width {
                            self.colonnade[c].expand(m);
                        }
                    }
                }
            }
            if self.required_width() <= self.width {
                break;
            }
        }
        if self.required_width() > self.width {
            // forcibly truncate long columns
            let mut truncatable_columns = self.colonnade.iter().enumerate().collect::<Vec<_>>();
            truncatable_columns.retain(|(_, c)| c.is_shrinkable());
            let truncatable_columns: Vec<usize> =
                truncatable_columns.iter().map(|(i, _)| *i).collect();
            let mut priorities: Vec<usize> = truncatable_columns
                .iter()
                .map(|&i| self.colonnade[i].priority)
                .collect();
            priorities.sort_unstable();
            priorities.dedup();
            priorities.reverse();
            'outer: for p in priorities {
                let mut shrinkables: Vec<&usize> = truncatable_columns
                    .iter()
                    .filter(|&&i| self.colonnade[i].priority == p)
                    .collect();
                loop {
                    let excess = self.required_width() - self.width;
                    if excess == 0 {
                        break 'outer;
                    }
                    if excess <= shrinkables.len() {
                        shrinkables.retain(|&&i| self.colonnade[i].shrink_by(1));
                    } else {
                        let share = excess / shrinkables.len();
                        shrinkables.retain(|&&i| self.colonnade[i].shrink_by(share));
                    }
                    if shrinkables.is_empty() {
                        break;
                    }
                }
            }
            if self.required_width() > self.width {
                return Err(ColonnadeError::InsufficientSpace);
            }
        } else if self.required_width() < self.width {
            // try to give back surplus space
            modified_columns.retain(|&i| self.colonnade[i].is_expandable());
            if !modified_columns.is_empty() {
                while self.required_width() < self.width {
                    // find highest priority among modified columns
                    if let Some(priority) = modified_columns
                        .iter()
                        .map(|&i| self.colonnade[i].priority)
                        .min()
                    {
                        // there are still some modified columns we haven't restored any space to
                        let mut winners: Vec<&usize> = modified_columns
                            .iter()
                            .filter(|&&i| self.colonnade[i].priority == priority)
                            .collect();
                        let surplus = self.width - self.required_width();
                        if surplus <= winners.len() {
                            // give one column back to as many of the winners as possible and call it a day
                            // we will necessarily break out of the loop after this
                            for &&i in winners.iter().take(surplus) {
                                self.colonnade[i].width += 1;
                            }
                        } else {
                            // give a share back to each winner
                            loop {
                                let surplus = self.width - self.required_width();
                                if surplus == 0 {
                                    break;
                                }
                                winners.retain(|&&i| self.colonnade[i].is_expandable());
                                if winners.is_empty() {
                                    break;
                                }
                                if surplus <= winners.len() {
                                    for &&i in winners.iter().take(surplus) {
                                        self.colonnade[i].width += 1;
                                    }
                                    break;
                                }
                                let mut changed = false;
                                let share = surplus / winners.len();
                                for &&i in winners.iter() {
                                    let change = self.colonnade[i].expand_by(share);
                                    changed = changed || change;
                                }
                                if !changed {
                                    break;
                                }
                            }
                            modified_columns.retain(|&i| self.colonnade[i].priority != priority);
                        }
                    } else {
                        break;
                    }
                }
            }
        }
        self.adjusted = true;
        Ok(())
    }
    /// Specify a number of blank lines to insert between table rows.
    ///
    /// # Arguments
    ///
    /// * `n` - A number of spaces.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // we want rows to be separated by a single blank line
    /// colonnade.spaces_between_rows(1);
    /// # Ok(()) }
    /// ```
    pub fn spaces_between_rows(&mut self, n: usize) {
        self.spaces_between_rows = n;
    }
    /// Assign the same priority to all columns. By default, all columns have the lowest priority.
    ///
    /// Priority determines the order in which columns give up space when the viewport lacks sufficient
    /// space to display all columns without wrapping. Lower priority columns give up space first.
    ///
    /// # Arguments
    ///
    /// * `priority` - The common priority. Lower numbers confer higher priority; 0 is the highest priority.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // assign all columns the highest priority
    /// colonnade.priority_all(0);
    /// // now demote the last column
    /// colonnade.priority(3, 1);
    /// # Ok(()) }
    /// ```
    pub fn priority_all(&mut self, priority: usize) {
        for i in 0..self.len() {
            self.colonnade[i].priority = priority;
        }
    }
    /// Assign a particular priority to a particular column.
    ///
    /// Priority determines the order in which columns give up space when the viewport lacks sufficient
    /// space to display all columns without wrapping. Lower priority columns give up space first.
    ///
    /// # Arguments
    ///
    /// * `index` - Which column to which you wish to assign priority.
    /// * `priority` - The column's priority. Lower numbers confer higher priority; 0 is the highest priority.
    ///
    /// # Error
    ///
    /// * `ColonnadeError::OutOfBounds` - The index is beyond the bounds of the spec.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // assign all columns the highest priority
    /// colonnade.priority_all(0);
    /// // now demote the last column
    /// colonnade.priority(3, 1)?;
    /// # Ok(()) }
    /// ```
    pub fn priority(&mut self, index: usize, priority: usize) -> Result<(), ColonnadeError> {
        if index < self.len() {
            self.colonnade[index].priority = priority;
            Ok(())
        } else {
            Err(ColonnadeError::OutOfBounds)
        }
    }
    /// Assign the same maximum width to all columns. By default columns have no maximum width.
    ///
    /// # Arguments
    ///
    /// * `max_width` - The common maximum width.
    ///
    /// # Errors
    ///
    /// * `ColonnadeError::MinGreaterThanMax` - Assigning a maximum width in conflict with some assigned minimum width.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // assign all columns a maximum width of 20
    /// colonnade.max_width_all(20)?;
    /// // at most we will now use only 83 of the characters provided by the viewport (until we mess with margins)
    /// # Ok(()) }
    /// ```
    pub fn max_width_all(&mut self, max_width: usize) -> Result<(), ColonnadeError> {
        for i in 0..self.len() {
            if self.colonnade[i].min_width.unwrap_or(0) > max_width {
                return Err(ColonnadeError::MinGreaterThanMax(i));
            }
            self.colonnade[i].max_width = Some(max_width);
        }
        Ok(())
    }
    /// Assign the same maximum width to all columns. By default columns have no maximum width.
    ///
    /// # Arguments
    ///
    /// * `max_width` - The common maximum width.
    ///
    /// # Errors
    ///
    /// * `ColonnadeError::MinGreaterThanMax` - Assigning a maximum width in conflict with some assigned minimum width.
    /// * `ColonnadeError::OutOfBounds` - Attemping to assign a maximum width to a column that does not exist.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // assign the first column a maximum width of 20
    /// colonnade.max_width(0, 20)?;
    /// # Ok(()) }
    /// ```
    pub fn max_width(&mut self, index: usize, max_width: usize) -> Result<(), ColonnadeError> {
        if index < self.len() {
            if self.colonnade[index].min_width.unwrap_or(max_width) > max_width {
                Err(ColonnadeError::MinGreaterThanMax(index))
            } else {
                self.colonnade[index].max_width = Some(max_width);
                Ok(())
            }
        } else {
            if self.colonnade[index].min_width.unwrap_or(0) > max_width {
                return Err(ColonnadeError::MinGreaterThanMax(index));
            }
            Err(ColonnadeError::OutOfBounds)
        }
    }
    /// Assign the same minimum width to all columns. By default columns have no minimum width.
    ///
    /// # Arguments
    ///
    /// * `min_width` - The common minimum width.
    ///
    /// # Errors
    ///
    /// * `ColonnadeError::MinGreaterThanMax` - Assigning a maximum width in conflict with some assigned minimum width.
    /// * `ColonnadeError::InsufficientSpace` - Assigning this minimum width means the columns require more space than the viewport provides.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // assign all columns a minimum width of 20
    /// colonnade.min_width_all(20)?;
    /// // we will now use at least 83 of the characters provided by the viewport (until we mess with margins)
    /// # Ok(()) }
    /// ```
    pub fn min_width_all(&mut self, min_width: usize) -> Result<(), ColonnadeError> {
        for i in 0..self.len() {
            if self.colonnade[i].max_width.unwrap_or(min_width) < min_width {
                return Err(ColonnadeError::MinGreaterThanMax(i));
            }
            self.colonnade[i].width = min_width;
            self.colonnade[i].min_width = Some(min_width);
        }
        if !self.sufficient_space() {
            Err(ColonnadeError::InsufficientSpace)
        } else {
            Ok(())
        }
    }
    /// Assign a particular minimum width to a particular column. By default columns have no minimum width.
    ///
    /// # Arguments
    ///
    /// * `index` - The column to which we wish to assign a minimum width.
    /// * `min_width` - The common minimum width.
    ///
    /// # Errors
    ///
    /// * `ColonnadeError::MinGreaterThanMax` - Assigning a maximum width in conflict with some assigned minimum width.
    /// * `ColonnadeError::InsufficientSpace` - Assigning this minimum width means the columns require more space than the viewport provides.
    /// * `ColonnadeError::OutOfBounds` - The index is outside the columns in the spec.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // assign the first column a minimum width of 20
    /// colonnade.min_width(0, 20)?;
    /// # Ok(()) }
    /// ```
    pub fn min_width(&mut self, index: usize, min_width: usize) -> Result<(), ColonnadeError> {
        if index < self.len() {
            if self.colonnade[index].max_width.unwrap_or(min_width) < min_width {
                return Err(ColonnadeError::MinGreaterThanMax(index));
            }
            self.colonnade[index].width = min_width;
            self.colonnade[index].min_width = Some(min_width);
            if !self.sufficient_space() {
                Err(ColonnadeError::InsufficientSpace)
            } else {
                Ok(())
            }
        } else {
            Err(ColonnadeError::OutOfBounds)
        }
    }
    /// Assign the same maximum and minimum width to all columns. By default columns have neither a maximum nor a minimum width.
    ///
    /// # Arguments
    ///
    /// * `width` - The common width.
    ///
    /// # Errors
    ///
    /// This method is a convenience method which assigns all columns the same maximum and minimum width. Therefore
    /// the errors thrown are those thrown by [`max_width_all`](#method.max_width_all) and [`min_width_all`](#method.min_width_all).
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // assign all columns a width of 20
    /// colonnade.fixed_width_all(20)?;
    /// // we will now use at exactly 83 of the characters provided by the viewport (until we mess with margins)
    /// # Ok(()) }
    /// ```
    pub fn fixed_width_all(&mut self, width: usize) -> Result<(), ColonnadeError> {
        for i in 0..self.len() {
            self.colonnade[i].min_width = None;
            self.colonnade[i].max_width = None;
        }
        match self.min_width_all(width) {
            Err(e) => return Err(e),
            Ok(_) => (),
        }
        match self.max_width_all(width) {
            Err(e) => return Err(e),
            Ok(_) => (),
        }
        Ok(())
    }
    /// Assign a particular maximum and minimum width to a particular column. By default columns have neither a maximum nor a minimum width.
    ///
    /// # Arguments
    ///
    /// * `index` - The column to configure.
    /// * `width` - The common width.
    ///
    /// # Errors
    ///
    /// This method is a convenience method which assigns the column in question the same maximum and minimum width. Therefore
    /// the errors thrown are those thrown by [`max_width`](#method.max_width) and [`min_width`](#method.min_width).
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // assign the first column a width of 20
    /// colonnade.fixed_width(0, 20)?;
    /// # Ok(()) }
    /// ```
    pub fn fixed_width(&mut self, index: usize, min_width: usize) -> Result<(), ColonnadeError> {
        self.colonnade[index].min_width = None;
        self.colonnade[index].max_width = None;
        match self.min_width(index, min_width) {
            Err(e) => return Err(e),
            Ok(_) => (),
        }
        match self.max_width(index, min_width) {
            Err(e) => return Err(e),
            Ok(_) => (),
        }
        Ok(())
    }
    /// Remove any maximum or minimum column widths.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // assign all columns a width of 20
    /// colonnade.fixed_width_all(20)?;
    /// // later ...
    /// colonnade.clear_limits_all();
    /// # Ok(()) }
    /// ```
    pub fn clear_limits_all(&mut self) {
        for i in 0..self.len() {
            self.colonnade[i].max_width = None;
            self.colonnade[i].min_width = None;
        }
    }
    /// Remove maximum or minimum column widths from a particular column.
    ///
    /// # Errors
    ///
    /// * `ColonnadeError::OutOfBounds` - The column specified does not exist in the spec.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::Colonnade;
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // initially assign all columns a width of 20
    /// colonnade.fixed_width_all(20);
    /// // but we want the first column to be flexible
    /// colonnade.clear_limits(0)?;
    /// # Ok(()) }
    /// ```
    pub fn clear_limits(&mut self, index: usize) -> Result<(), ColonnadeError> {
        if index < self.len() {
            self.colonnade[index].max_width = None;
            self.colonnade[index].min_width = None;
            Ok(())
        } else {
            Err(ColonnadeError::OutOfBounds)
        }
    }
    /// Assign all columns the same alignment. The default alignment is left.
    ///
    /// # Arguments
    ///
    /// * `alignment` - The desired alignment.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::{Alignment,Colonnade};
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // all columns should be right-aligned (they're numeric)
    /// colonnade.alignment_all(Alignment::Right);
    /// # Ok(()) }
    /// ```
    pub fn alignment_all(&mut self, alignment: Alignment) {
        for i in 0..self.len() {
            self.colonnade[i].alignment = alignment.clone();
        }
    }
    /// Assign a particular column a particular alignment. The default alignment is left.
    ///
    /// # Arguments
    ///
    /// * `index` - The column to modify.
    /// * `alignment` - The desired alignment.
    ///
    /// # Errors
    ///
    /// * `ColonnadeError::OutOfBounds` - The column specified does not exist in the spec.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::{Alignment,Colonnade};
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // the first column should be right-aligned (it's numeric)
    /// colonnade.alignment(0, Alignment::Right)?;
    /// # Ok(()) }
    /// ```
    pub fn alignment(&mut self, index: usize, alignment: Alignment) -> Result<(), ColonnadeError> {
        if index < self.len() {
            self.colonnade[index].alignment = alignment;
            Ok(())
        } else {
            Err(ColonnadeError::OutOfBounds)
        }
    }
    /// Assign all columns the same left margin. The left margin is a number of blank spaces
    /// before the content of the column. By default the first column has a left margin of 0
    /// and the other columns have a left margin of 1.
    ///
    /// # Arguments
    ///
    /// * `left_margin` - The width in blank spaces of the desired margin.
    ///
    /// # Errors
    ///
    /// * `ColonnadeError::InsufficientSpace` - This margin will require more space than is available in the viewport.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::{Alignment,Colonnade};
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // all columns should be preceded by 2 blank spaces
    /// colonnade.left_margin_all(2)?;
    /// # Ok(()) }
    /// ```
    pub fn left_margin_all(&mut self, left_margin: usize) -> Result<(), ColonnadeError> {
        for i in 0..self.len() {
            self.colonnade[i].left_margin = left_margin;
        }
        if !self.sufficient_space() {
            Err(ColonnadeError::InsufficientSpace)
        } else {
            Ok(())
        }
    }
    /// Assign a particular column a particular left margin. The left margin is a number of blank spaces
    /// before the content of the column. By default the first column has a left margin of 0
    /// and the other columns have a left margin of 1.
    ///
    /// # Arguments
    ///
    /// * `index` - The column to configure.
    /// * `left_margin` - The width in blank spaces of the desired margin.
    ///
    /// # Errors
    ///
    /// * `ColonnadeError::InsufficientSpace` - This margin will require more space than is available in the viewport.
    /// * `ColonnadeError::OutOfBounds` - The column specified does not exist in the spec.
    ///
    /// # Example
    ///
    /// ```rust
    /// # extern crate colonnade;
    /// # use colonnade::{Alignment,Colonnade};
    /// # use std::error::Error;
    /// # fn demo() -> Result<(), Box<dyn Error>> {
    /// let mut colonnade = Colonnade::new(4, 100)?;
    /// // the first column should be preceded by 2 blank spaces
    /// colonnade.left_margin(0, 2)?;
    /// # Ok(()) }
    /// ```
    pub fn left_margin(&mut self, index: usize, left_margin: usize) -> Result<(), ColonnadeError> {
        if index < self.len() {
            self.colonnade[index].left_margin = left_margin;
            if !self.sufficient_space() {
                Err(ColonnadeError::InsufficientSpace)
            } else {
                Ok(())
            }
        } else {
            Err(ColonnadeError::OutOfBounds)
        }
    }
}