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
use crate::line::FormattedLine;
use crate::area::Area;
use crate::text::FormattedText;
use crossterm::{Attribute, Color, ObjectStyle, StyledObject};
use minimad::{Compound, Line, LineStyle, MAX_HEADER_DEPTH, Text};
use std::fmt;

// The scrollbar style is defined by two styled chars, one
//  for the track, and one for the thumb.
// For the default styling only the fg color is defined
//  and the char is ▐ but everything can be changed
pub struct ScrollBarStyle {
    pub track: StyledObject<char>,
    pub thumb: StyledObject<char>,
}

impl ScrollBarStyle {
    pub fn new() -> ScrollBarStyle {
        let char = '▐';
        ScrollBarStyle {
            track: ObjectStyle::new().fg(Color::Rgb{r:35, g:35, b:35}).apply_to(char),
            thumb: ObjectStyle::new().fg(Color::Rgb{r:140, g:140, b:140}).apply_to(char),
        }
    }
    pub fn set_thumb_fg(&mut self, c: Color) {
        let os = ObjectStyle::new().fg(c);
        self.thumb = os.apply_to(self.thumb.content);
    }
    pub fn set_track_fg(&mut self, c: Color) {
        let os = ObjectStyle::new().fg(c);
        self.track = os.apply_to(self.track.content);
    }
}

/// A skin defining how a parsed mardkown appears on the terminal
/// (fg and bg colors, bold, italic, underline, etc.)
pub struct MadSkin {
    pub normal: ObjectStyle,
    pub bold: ObjectStyle,
    pub italic: ObjectStyle,
    pub code: ObjectStyle,
    pub headers: [ObjectStyle; MAX_HEADER_DEPTH],
    pub scrollbar: ScrollBarStyle,
}

// overwrite style of a with b
fn add_style(a: &mut ObjectStyle, b: &ObjectStyle) {
    a.fg_color = b.fg_color.or(a.fg_color);
    a.bg_color = b.bg_color.or(a.bg_color);
    a.attrs.extend(&b.attrs);
}

#[macro_export]
macro_rules! mad_fg {
    (
        $item:expr, $color:expr
    ) => {
        $item.fg_color = Some($color);
    }
}

#[macro_export]
macro_rules! mad_bg {
    (
        $item:expr, $color:expr
    ) => {
        $item.bg_color = Some($color);
    }
}

#[macro_export]
macro_rules! mad_colors {
    (
        $item:expr, $fg:expr, $bg:expr
    ) => {
        $item.fg_color = Some($fg);
        $item.bg_color = Some($bg);
    }
}

impl MadSkin {
    /// build a customizable skin.
    /// It's initialized with sensible monochrome settings.
    pub fn new() -> MadSkin {
        let mut skin = MadSkin {
            normal: ObjectStyle::new(),
            bold: ObjectStyle::new().fg(Color::White),
            italic: ObjectStyle::new(),
            code: ObjectStyle::new(),
            headers: Default::default(),
            scrollbar: ScrollBarStyle::new(),
        };
        skin.bold.add_attr(Attribute::Bold);
        skin.italic.add_attr(Attribute::Italic);
        skin.code.bg_color = Some(Color::Rgb {
            r: 40,
            g: 40,
            b: 40,
        });
        for h in &mut skin.headers {
            h.add_attr(Attribute::Underlined);
        }
        skin.headers[0].add_attr(Attribute::Bold);
        skin.headers[0].fg_color = Some(Color::Rgb{r:250, g:250, b:250});
        skin.headers[1].fg_color = Some(Color::Rgb{r:240, g:240, b:240});
        skin
    }
    pub fn set_headers_fg_color(&mut self, c: Color) {
        for h in &mut self.headers {
            h.fg_color = Some(c);
        }
    }
    pub fn set_headers_bg_color(&mut self, c: Color) {
        for h in &mut self.headers {
            h.bg_color = Some(c);
        }
    }
    fn line_object_style(&self, line_style: &LineStyle) -> &ObjectStyle {
        match line_style {
            LineStyle::Code => &self.code,
            LineStyle::Header(level) if *level <= MAX_HEADER_DEPTH as u8 => {
                &self.headers[*level as usize - 1]
            }
            _ => &self.normal,
        }
    }
    fn compound_object_style(
        &self,
        line_object_style: &ObjectStyle,
        compound: &Compound,
    ) -> ObjectStyle {
        let mut os = line_object_style.clone();
        if compound.italic {
            add_style(&mut os, &self.italic);
        }
        if compound.bold {
            add_style(&mut os, &self.bold);
        }
        if compound.code {
            add_style(&mut os, &self.code);
        }
        os
    }
    // return a formatted line
    // Don't use this function if `src` is expected to be several lines.
    pub fn line<'s, 'l>(&'s self, src: &'l str) -> FormattedLine<'s, 'l> {
        FormattedLine::new(self, src)
    }
    // return a formatted text.
    // Code blocs will be right justified
    pub fn text<'s, 'l>(&'s self, src: &'l str) -> FormattedText<'s, 'l> {
        let mut text = FormattedText::new(self, src);
        text.right_pad_code_blocks();
        text
    }
    // return a formatted text adjusted for a specific area width.
    // Lines will be wrapped to fit in the width of the area (with
    //  the space for the scrollbar)
    // Code blocs will be right justified.
    pub fn wrapped_text<'s, 'l>(&'s self, src: &'l str, area: &Area) -> FormattedText<'s, 'l> {
        let text = Text::from(src);
        let mut text = FormattedText{
            skin: self,
            text: hard_wrap_text(&text, (area.width) as usize),
        };
        text.right_pad_code_blocks();
        text
    }
    pub fn print_line(&self, src: &str) {
        print!("{}", FormattedLine::new(self, src));
    }
    pub fn print_line_ln(&self, src: &str) {
        println!("{}", FormattedLine::new(self, src));
    }
    pub fn print_text(&self, src: &str) {
        println!("{}", FormattedText::new(self, src));
    }
    pub fn fmt_line(&self, f: &mut fmt::Formatter, line: &Line) -> fmt::Result {
        let os = self.line_object_style(&line.style);
        if line.is_list_item() {
            write!(f, "• ")?;
        }
        for c in &line.compounds {
            let os = self.compound_object_style(os, c);
            write!(f, "{}", os.apply_to(c.as_str()))?;
        }
        Ok(())
    }
}

fn follow_up_line<'s>(line: &Line<'s>) -> Line<'s> {
    Line {
        style: match line.style {
            LineStyle::ListItem => LineStyle::Normal,
            _ => line.style,
        },
        compounds: Vec::new(),
    }
}

/// cut the passed line in several lines fitting the given width
fn hard_wrap_line<'s>(src_line: &Line<'s>, width: usize) -> Vec<Line<'s>> {
    assert!(width > 4);
    let mut lines = Vec::new();
    let max_cut_back = width / 5;
    let mut dst_line = Line {
        style: src_line.style,
        compounds: Vec::new(),
    };
    let mut ll = match src_line.style {
        LineStyle::ListItem => 2, // space of the puce
        _ => 0,
    };
    for sc in &src_line.compounds {
        let s = sc.as_str();
        let cl = s.chars().count();
        if ll + cl <= width {
            // we add the compound as is to the current line
            dst_line.compounds.push(sc.clone());
            ll += cl;
            continue;
        }
        if ll + 2 >= width {
            // we close the current line
            let new_dst_line = follow_up_line(&dst_line);
            lines.push(dst_line);
            dst_line = new_dst_line;
            ll = 0;
        }
        let mut c_start = 0;
        let mut last_space: Option<usize> = None;
        for (idx, char) in s.char_indices() {
            ll += 1;
            if char.is_whitespace() {
                last_space = Some(idx);
            }
            if ll == width {
                let mut cut = idx;
                if let Some(ls) = last_space {
                    if ls + max_cut_back >= idx {
                        cut = ls;
                    }
                }
                dst_line.compounds.push(sc.sub(c_start, cut));
                let new_dst_line = follow_up_line(&dst_line);
                lines.push(dst_line);
                dst_line = new_dst_line;
                c_start = cut;
                last_space = None;
                ll = idx - cut;
            }
        }
        if ll!=width {
            dst_line.compounds.push(sc.tail(c_start));
        }
    }
    lines.push(dst_line);
    lines
}
fn hard_wrap_text<'s>(text: &Text<'s>, width: usize) -> Text<'s> {
    assert!(width > 4);
    let mut lines = Vec::new();
    for src_line in &text.lines {
        for line in hard_wrap_line(src_line, width) {
            lines.push(line)
        }
    }
    Text {
        lines
    }
}

#[test]
pub fn hard_wrap() {
    // build a text and check it
    let src = "This is a *long* line which needs to be **broken**.\n\
        And the text goes on with a list:\n\
        * short item\n\
        * a *somewhat longer item* (with a part in **bold**)";
    println!("input text:\n{}", &src);
    let src_text =  Text::from(&src);
    assert_eq!(src_text.lines[0].char_length(), 45);
    assert_eq!(src_text.lines[1].char_length(), 33);
    assert_eq!(src_text.lines[2].char_length(), 10);
    assert_eq!(src_text.lines[3].char_length(), 44);

    // checking several wrapping widths
    let text = hard_wrap_text(&src_text, 100);
    assert_eq!(text.lines.len(), 4);
    let text = hard_wrap_text(&src_text, 30);
    assert_eq!(text.lines.len(), 7);
    let text = hard_wrap_text(&src_text, 12);
    assert_eq!(text.lines.len(), 12);
}