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
//! DisplayListFormatter is a module handling the formatting of a
//! `DisplayList` into a formatted string.
//!
//! Besides formatting into a string it also uses a `style::Stylesheet` to
//! provide additional styling like colors and emphasis to the text.

pub mod style;

use std::cmp;
use display_list::*;
use self::style::{Style, StyleClass, Stylesheet};

#[cfg(feature = "ansi_term")]
use stylesheets::color::AnsiTermStylesheet;
use stylesheets::no_color::NoColorStylesheet;

fn repeat_char(c: char, n: usize) -> String {
    let mut s = String::with_capacity(c.len_utf8());
    s.push(c);
    s.repeat(n)
}

/// DisplayListFormatter' constructor accepts a single argument which
/// allows the formatter to optionally apply colors and emphasis
/// using `ansi_term` crate.
///
/// Example:
///
/// ```
/// use annotate_snippets::formatter::DisplayListFormatter;
/// use annotate_snippets::display_list::{DisplayList, DisplayLine, DisplaySourceLine};
///
/// let dlf = DisplayListFormatter::new(false); // Don't use colors
///
/// let dl = DisplayList {
///     body: vec![
///         DisplayLine::Source {
///             lineno: Some(192),
///             inline_marks: vec![],
///             line: DisplaySourceLine::Content {
///                 text: "Example line of text".into(),
///                 range: (0, 21)
///             }
///         }
///     ]
/// };
/// assert_eq!(dlf.format(&dl), "192 | Example line of text");
/// ```
pub struct DisplayListFormatter {
    stylesheet: Box<Stylesheet>,
}

impl DisplayListFormatter {
    /// Constructor for the struct. The argument `color` selects
    /// the stylesheet depending on the user preferences and `ansi_term`
    /// crate availability.
    pub fn new(color: bool) -> Self {
        if color {
            Self {
                #[cfg(feature = "ansi_term")]
                stylesheet: Box::new(AnsiTermStylesheet {}),
                #[cfg(not(feature = "ansi_term"))]
                stylesheet: Box::new(NoColorStylesheet {}),
            }
        } else {
            Self {
                stylesheet: Box::new(NoColorStylesheet {}),
            }
        }
    }

    /// Formats a `DisplayList` into a String.
    pub fn format(&self, dl: &DisplayList) -> String {
        let lineno_width = dl.body.iter().fold(0, |max, line| match line {
            DisplayLine::Source {
                lineno: Some(lineno),
                ..
            } => cmp::max(lineno.to_string().len(), max),
            _ => max,
        });
        let inline_marks_width = dl.body.iter().fold(0, |max, line| match line {
            DisplayLine::Source { inline_marks, .. } => cmp::max(inline_marks.len(), max),
            _ => max,
        });

        dl.body
            .iter()
            .map(|line| self.format_line(line, lineno_width, inline_marks_width))
            .collect::<Vec<String>>()
            .join("\n")
    }

    fn format_annotation_type(&self, annotation_type: &DisplayAnnotationType) -> &'static str {
        match annotation_type {
            DisplayAnnotationType::Error => "error",
            DisplayAnnotationType::Warning => "warning",
            DisplayAnnotationType::Info => "info",
            DisplayAnnotationType::Note => "note",
            DisplayAnnotationType::Help => "help",
            DisplayAnnotationType::None => "",
        }
    }

    fn get_annotation_style(&self, annotation_type: &DisplayAnnotationType) -> Box<Style> {
        self.stylesheet.get_style(match annotation_type {
            DisplayAnnotationType::Error => StyleClass::Error,
            DisplayAnnotationType::Warning => StyleClass::Warning,
            DisplayAnnotationType::Info => StyleClass::Info,
            DisplayAnnotationType::Note => StyleClass::Note,
            DisplayAnnotationType::Help => StyleClass::Help,
            DisplayAnnotationType::None => StyleClass::None,
        })
    }

    fn format_label(&self, label: &[DisplayTextFragment]) -> String {
        let emphasis_style = self.stylesheet.get_style(StyleClass::Emphasis);
        label
            .iter()
            .map(|fragment| match fragment.style {
                DisplayTextStyle::Regular => fragment.content.clone(),
                DisplayTextStyle::Emphasis => emphasis_style.paint(&fragment.content),
            })
            .collect::<Vec<String>>()
            .join("")
    }

    fn format_annotation(
        &self,
        annotation: &Annotation,
        continuation: bool,
        in_source: bool,
    ) -> String {
        let color = self.get_annotation_style(&annotation.annotation_type);
        let formatted_type = if let Some(ref id) = annotation.id {
            format!(
                "{}[{}]",
                self.format_annotation_type(&annotation.annotation_type),
                id
            )
        } else {
            self.format_annotation_type(&annotation.annotation_type)
                .to_string()
        };
        let label = self.format_label(&annotation.label);

        let label_part = if label.is_empty() {
            "".to_string()
        } else if in_source {
            color.paint(&format!(": {}", self.format_label(&annotation.label)))
        } else {
            format!(": {}", self.format_label(&annotation.label))
        };
        if continuation {
            let indent = formatted_type.len() + 2;
            return format!("{}{}", repeat_char(' ', indent), label);
        }
        if !formatted_type.is_empty() {
            format!("{}{}", color.paint(&formatted_type), label_part)
        } else {
            label
        }
    }

    fn format_source_line(&self, line: &DisplaySourceLine) -> Option<String> {
        match line {
            DisplaySourceLine::Empty => None,
            DisplaySourceLine::Content { text, .. } => Some(format!(" {}", text)),
            DisplaySourceLine::Annotation {
                range,
                annotation,
                annotation_type,
                annotation_part,
            } => {
                let indent_char = match annotation_part {
                    DisplayAnnotationPart::Standalone => ' ',
                    DisplayAnnotationPart::LabelContinuation => ' ',
                    DisplayAnnotationPart::Consequitive => ' ',
                    DisplayAnnotationPart::MultilineStart => '_',
                    DisplayAnnotationPart::MultilineEnd => '_',
                };
                let mark = match annotation_type {
                    DisplayAnnotationType::Error => '^',
                    DisplayAnnotationType::Warning => '-',
                    DisplayAnnotationType::Info => '-',
                    DisplayAnnotationType::Note => '-',
                    DisplayAnnotationType::Help => '-',
                    DisplayAnnotationType::None => ' ',
                };
                let color = self.get_annotation_style(annotation_type);
                let indent_length = match annotation_part {
                    DisplayAnnotationPart::LabelContinuation => range.1,
                    DisplayAnnotationPart::Consequitive => range.1,
                    _ => range.0,
                };
                let indent = color.paint(&repeat_char(indent_char, indent_length + 1));
                let marks = color.paint(&repeat_char(mark, range.1 - indent_length));
                let annotation = self.format_annotation(
                    annotation,
                    annotation_part == &DisplayAnnotationPart::LabelContinuation,
                    true,
                );
                if annotation.is_empty() {
                    return Some(format!("{}{}", indent, marks));
                }
                Some(format!("{}{} {}", indent, marks, color.paint(&annotation)))
            }
        }
    }

    fn format_lineno(&self, lineno: Option<usize>, lineno_width: usize) -> String {
        match lineno {
            Some(n) => format!("{:>width$}", n, width = lineno_width),
            None => repeat_char(' ', lineno_width),
        }
    }

    fn format_raw_line(&self, line: &DisplayRawLine, lineno_width: usize) -> String {
        match line {
            DisplayRawLine::Origin {
                path,
                pos,
                header_type,
            } => {
                let header_sigil = match header_type {
                    DisplayHeaderType::Initial => "-->",
                    DisplayHeaderType::Continuation => ":::",
                };
                let lineno_color = self.stylesheet.get_style(StyleClass::LineNo);

                if let Some((col, row)) = pos {
                    format!(
                        "{}{} {}:{}:{}",
                        repeat_char(' ', lineno_width),
                        lineno_color.paint(header_sigil),
                        path,
                        col,
                        row
                    )
                } else {
                    format!(
                        "{}{} {}",
                        repeat_char(' ', lineno_width),
                        lineno_color.paint(header_sigil),
                        path
                    )
                }
            }
            DisplayRawLine::Annotation {
                annotation,
                source_aligned,
                continuation,
            } => {
                if *source_aligned {
                    if *continuation {
                        format!(
                            "{}{}",
                            repeat_char(' ', lineno_width + 3),
                            self.format_annotation(annotation, *continuation, false)
                        )
                    } else {
                        let lineno_color = self.stylesheet.get_style(StyleClass::LineNo);
                        format!(
                            "{} {} {}",
                            repeat_char(' ', lineno_width),
                            lineno_color.paint("="),
                            self.format_annotation(annotation, *continuation, false)
                        )
                    }
                } else {
                    self.format_annotation(annotation, *continuation, false)
                }
            }
        }
    }

    fn format_line(
        &self,
        dl: &DisplayLine,
        lineno_width: usize,
        inline_marks_width: usize,
    ) -> String {
        match dl {
            DisplayLine::Source {
                lineno,
                inline_marks,
                line,
            } => {
                let lineno = self.format_lineno(*lineno, lineno_width);
                let marks = self.format_inline_marks(inline_marks, inline_marks_width);
                let lf = self.format_source_line(line);
                let lineno_color = self.stylesheet.get_style(StyleClass::LineNo);

                let mut prefix = lineno_color.paint(&format!("{} |", lineno));

                match lf {
                    Some(lf) => {
                        if !marks.is_empty() {
                            prefix.push_str(&format!(" {}", marks));
                        }
                        format!("{}{}", prefix, lf)
                    }
                    None => {
                        if !marks.trim().is_empty() {
                            prefix.push_str(&format!(" {}", marks));
                        }
                        prefix
                    }
                }
            }
            DisplayLine::Fold { inline_marks } => {
                let marks = self.format_inline_marks(inline_marks, inline_marks_width);
                let indent = lineno_width;
                if marks.trim().is_empty() {
                    String::from("...")
                } else {
                    format!("...{}{}", repeat_char(' ', indent), marks)
                }
            }
            DisplayLine::Raw(line) => self.format_raw_line(line, lineno_width),
        }
    }

    fn format_inline_marks(
        &self,
        inline_marks: &[DisplayMark],
        inline_marks_width: usize,
    ) -> String {
        format!(
            "{}{}",
            " ".repeat(inline_marks_width - inline_marks.len()),
            inline_marks
                .iter()
                .map(|mark| {
                    let sigil = match mark.mark_type {
                        DisplayMarkType::AnnotationThrough => "|",
                        DisplayMarkType::AnnotationStart => "/",
                    };
                    let color = self.get_annotation_style(&mark.annotation_type);
                    color.paint(sigil)
                })
                .collect::<Vec<String>>()
                .join(""),
        )
    }
}