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
// Copyright © 2021 Alexandra Frydl
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.

use super::*;

/// A wrapper returned from [`indent()`] that displays its inner value with
/// custom indentation.
pub struct Indented<'a, T> {
  initial: &'a str,
  hanging: &'a str,
  value: T,
}

/// A formatter that automatically indents lines.
pub struct IndentedFormatter<'a, F> {
  f: F,
  initial: &'a str,
  hanging: &'a str,
  line: usize,
  start_of_line: bool,
}

/// Wraps the value so that it is displayed with the given initial and hanging
/// indentation.
pub fn indent<'a, T>(initial: &'a str, hanging: &'a str, value: T) -> Indented<'a, T> {
  Indented { initial, hanging, value }
}

impl<'a, F: Write + 'a> IndentedFormatter<'a, F> {
  /// Creates a new indented formatter with the given initial and hanging
  /// indentation.
  pub fn new(f: F, initial: &'a str, hanging: &'a str) -> Self {
    Self { f, initial, hanging, line: 1, start_of_line: true }
  }
}

impl<'a, T: Debug> Debug for Indented<'a, T> {
  fn fmt(&self, f: &mut Formatter) -> Result {
    let alt = f.alternate();
    let mut f = IndentedFormatter::new(f, self.initial, self.hanging);

    if alt {
      write!(f, "{:#?}", self.value)
    } else {
      write!(f, "{:?}", self.value)
    }
  }
}

impl<'a, T: Display> Display for Indented<'a, T> {
  fn fmt(&self, f: &mut Formatter) -> Result {
    let alt = f.alternate();
    let mut f = IndentedFormatter::new(f, self.initial, self.hanging);

    if alt {
      write!(f, "{:#}", self.value)
    } else {
      write!(f, "{}", self.value)
    }
  }
}

impl<'a, F: 'a + Write> Write for IndentedFormatter<'a, F> {
  fn write_str(&mut self, s: &str) -> Result {
    for c in s.chars() {
      // Mark new lines.

      if c == '\n' {
        self.f.write_char(c)?;
        self.start_of_line = true;
        self.line += 1;

        continue;
      }

      // Output indentation before each line.

      if self.start_of_line {
        if self.line == 1 {
          self.f.write_str(self.initial)?;
        } else {
          self.f.write_str(self.hanging)?;
        }

        self.start_of_line = false;
      }

      // Output the original character.

      self.f.write_char(c)?;
    }

    Ok(())
  }
}