pulldown-cmark-mdcat 2.12.0

Render pulldown-cmark events to TTY
Documentation
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
// Copyright 2020 Sebastian Wiesner <sebastian@swsnr.de>

// 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 anstyle::Style;
use std::borrow::Borrow;
use syntect::highlighting::HighlightState;
use syntect::parsing::ParseState;

/// Whether to add a margin.
#[derive(Debug, PartialEq, Eq, Copy, Clone)]
pub(super) enum MarginControl {
    /// Always add a margin.
    Margin,
    /// Always add no margin.
    NoMargin,
}

/// State attributes for inline text.
#[derive(Debug, PartialEq, Clone)]
pub struct InlineAttrs {
    /// The style to apply to this piece of inline text.
    pub(super) style: Style,
    /// The indent to add after a line break in inline text.
    pub(super) indent: u16,
    /// How many block quote levels deep we are (for rendering the `│` border).
    pub(super) quote_depth: u16,
    /// Override color for the block quote border, used by alerts.
    pub(super) border_style: Option<Style>,
}

impl Default for InlineAttrs {
    fn default() -> Self {
        InlineAttrs {
            style: Style::new(),
            indent: 0,
            quote_depth: 0,
            border_style: None,
        }
    }
}

impl<T> From<T> for InlineAttrs
where
    T: Borrow<StyledBlockAttrs>,
{
    fn from(attrs: T) -> Self {
        InlineAttrs {
            style: attrs.borrow().style,
            indent: attrs.borrow().indent,
            quote_depth: attrs.borrow().quote_depth,
            border_style: attrs.borrow().border_style,
        }
    }
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ListItemKind {
    Unordered,
    Ordered(u64),
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum ListItemState {
    /// The first line after the list bullet/
    StartItem,
    /// Text directly within a list item.
    ItemText,
    /// A list after a nested block.
    ItemBlock,
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum InlineState {
    /// Inline text.
    ///
    /// Regular inline text without any particular implications.
    InlineText,
    /// Inline text.
    ///
    /// Inline text block which may not be wrapped.
    InlineBlock,
    /// Inline link.
    ///
    /// This state suppresses link references being written when reading a link
    /// end event.
    InlineLink,
    /// A list item.
    ///
    /// This is a hybrid between inline and block state because it can contain nested blocks as well
    /// as immediate inline text.  We define it as inline state mostly for convenience: Since there
    /// are less block than inline elements in Markdown we need to duplicate less state transitions
    /// to deal with the peculiarities of list items.
    ///
    /// List item text carries the type of the current item as well as a "state" which we use for
    /// newline control when ending and starting list items.
    ListItem(ListItemKind, ListItemState),
    /// A definition list term (`<dt>`) or description (`<dd>`).
    ///
    /// Structurally the same hybrid inline/block situation as `ListItem`: term and description
    /// content can be direct inline text (tight) or nested blocks wrapped in `Paragraph` etc.
    /// (loose), so we reuse `ListItemState` for the same newline-control bookkeeping.
    Definition(DefinitionPart, ListItemState),
}

/// Which part of a definition list entry we're currently rendering.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum DefinitionPart {
    /// The term being defined (`<dt>`).
    Term,
    /// A description of the term (`<dd>`). A term may have more than one.
    Description,
}

/// State attributes for styled blocks.
#[derive(Debug, PartialEq, Clone)]
pub struct StyledBlockAttrs {
    /// Whether to write a margin before the beginning of a block inside this block.
    pub(super) margin_before: MarginControl,
    /// The indent to add after the block quote prefix on each line.
    pub(super) indent: u16,
    /// The general style to apply to children of this block, if possible.
    ///
    /// Note that not all nested blocks inherit style; code blocks for instance will always use
    /// their own dedicated style.
    pub(super) style: Style,
    /// How many block quote levels deep we are (for rendering the `│` border).
    pub(super) quote_depth: u16,
    /// Override color for the block quote border, used by alerts.
    pub(super) border_style: Option<Style>,
}

#[derive(Debug, Default, PartialEq, Clone)]
pub struct TableBlockAttrs {
    /// Indentation to apply to the table.
    pub(super) indent: u16,
    /// How many block quote levels deep we are (for rendering the `│` border).
    pub(super) quote_depth: u16,
    /// Override color for the block quote border, used by alerts.
    pub(super) border_style: Option<Style>,
}

impl TableBlockAttrs {
    pub(super) fn from_styled_block(attrs: &StyledBlockAttrs) -> Self {
        Self {
            indent: attrs.indent,
            quote_depth: attrs.quote_depth,
            border_style: attrs.border_style,
        }
    }

    pub(super) fn from_inline(attrs: &InlineAttrs) -> Self {
        Self {
            indent: attrs.indent,
            quote_depth: attrs.quote_depth,
            border_style: attrs.border_style,
        }
    }
}

impl StyledBlockAttrs {
    pub(super) fn without_margin_before(self) -> Self {
        StyledBlockAttrs {
            margin_before: MarginControl::NoMargin,
            ..self
        }
    }

    pub(super) fn with_margin_before(self) -> Self {
        StyledBlockAttrs {
            margin_before: MarginControl::Margin,
            ..self
        }
    }

    pub(super) fn block_quote(self) -> Self {
        StyledBlockAttrs {
            indent: self.indent,
            style: self.style.italic(),
            quote_depth: self.quote_depth + 1,
            ..self
        }
    }

    pub(super) fn alert(self, border_style: Style) -> Self {
        StyledBlockAttrs {
            indent: self.indent,
            style: self.style,
            quote_depth: self.quote_depth + 1,
            border_style: Some(border_style),
            ..self
        }
    }
}

impl Default for StyledBlockAttrs {
    fn default() -> Self {
        StyledBlockAttrs {
            margin_before: MarginControl::NoMargin,
            indent: 0,
            style: Style::new(),
            quote_depth: 0,
            border_style: None,
        }
    }
}

impl<T> From<T> for StyledBlockAttrs
where
    T: Borrow<InlineAttrs>,
{
    fn from(attrs: T) -> Self {
        StyledBlockAttrs {
            indent: attrs.borrow().indent,
            style: attrs.borrow().style,
            ..StyledBlockAttrs::default()
        }
    }
}

/// Attributes for highlighted blocks, that is, code blocks.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HighlightBlockAttrs {
    pub(super) parse_state: ParseState,
    pub(super) highlight_state: HighlightState,
    /// The indentation to apply to this code block.
    ///
    /// Code blocks in nested blocks such as quotes, lists, etc. gain an additional indent to align
    /// them in the surrounding block.
    pub(super) indent: u16,
}

#[derive(Debug, PartialEq)]
pub struct LiteralBlockAttrs {
    /// The indent for this block.
    pub(super) indent: u16,
    /// The outer style to include.
    pub(super) style: Style,
}

#[derive(Debug, PartialEq)]
pub struct HtmlBlockAttrs {
    /// The initial indent for this block.
    pub(super) initial_indent: u16,
    /// Indent for the remainder of this block.
    pub(super) indent: u16,
    /// The base style for this block.
    pub(super) style: Style,
}

#[derive(Debug, PartialEq)]
pub enum StackedState {
    /// Styled block.
    ///
    /// A block with attached style.
    StyledBlock(StyledBlockAttrs),
    /// A highlighted block of code.
    HighlightBlock(HighlightBlockAttrs),
    /// A literal block without highlighting.
    LiteralBlock(LiteralBlockAttrs),
    /// A block of HTML contents.
    HtmlBlock(HtmlBlockAttrs),
    /// A rendered inline image.
    ///
    /// We move to this state when we can render an image directly to the terminal, in order to
    /// suppress intermediate events, namely the image title.
    RenderedImage,
    /// A table block.
    TableBlock(TableBlockAttrs),
    /// A footnote definition block (collecting body text, not rendering).
    FootnoteDefinition,
    /// Some inline markup.
    Inline(InlineState, InlineAttrs),
}

impl From<StyledBlockAttrs> for StackedState {
    fn from(attrs: StyledBlockAttrs) -> Self {
        StackedState::StyledBlock(attrs)
    }
}

impl From<HighlightBlockAttrs> for StackedState {
    fn from(attrs: HighlightBlockAttrs) -> Self {
        StackedState::HighlightBlock(attrs)
    }
}

impl From<LiteralBlockAttrs> for StackedState {
    fn from(attrs: LiteralBlockAttrs) -> Self {
        StackedState::LiteralBlock(attrs)
    }
}

impl From<HtmlBlockAttrs> for StackedState {
    fn from(attrs: HtmlBlockAttrs) -> Self {
        StackedState::HtmlBlock(attrs)
    }
}

/// State attributes for top level.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TopLevelAttrs {
    pub(super) margin_before: MarginControl,
}

impl TopLevelAttrs {
    pub(super) fn margin_before() -> Self {
        TopLevelAttrs {
            margin_before: MarginControl::Margin,
        }
    }
}

impl Default for TopLevelAttrs {
    fn default() -> Self {
        TopLevelAttrs {
            margin_before: MarginControl::NoMargin,
        }
    }
}

const MAX_STATES: usize = 100;

#[derive(Debug, PartialEq)]
pub struct StateStack {
    /// The top level state this stack grows upon.
    top_level: TopLevelAttrs,
    /// The stack of states
    states: Vec<StackedState>,
}

impl StateStack {
    /// Stack onto the given top level state.
    fn new(top_level: TopLevelAttrs) -> Self {
        StateStack {
            top_level,
            states: Vec::with_capacity(20),
        }
    }

    /// Push a new stacked state.
    ///
    /// Panics if the amount of stacked states is exceeded.
    pub(crate) fn push(mut self, state: StackedState) -> StateStack {
        if MAX_STATES <= self.states.len() {
            panic!(
                "More than {MAX_STATES} levels of nesting reached.

Report an issue to https://github.com/BIRSAx2/mdcat/issues
including the document causing this panic.",
            )
        }
        self.states.push(state);
        self
    }

    /// Return a state by combining this stack with the current stacked state.
    pub(crate) fn current(self, state: StackedState) -> State {
        State::Stacked(self, state)
    }

    /// Pop a stacked state.
    ///
    /// Returns a stacked state with the last state on the stack and the rest of the stack if the
    /// stack is non-empty, or a toplevel state if the stack is empty.
    pub(crate) fn pop(self) -> State {
        let StateStack {
            mut states,
            top_level,
        } = self;
        match states.pop() {
            None => State::TopLevel(top_level),
            Some(state) => StateStack { top_level, states }.current(state),
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum State {
    /// At top level.
    TopLevel(TopLevelAttrs),
    /// A stacked state.
    Stacked(StateStack, StackedState),
}

impl State {
    pub(super) fn stack_onto(top_level: TopLevelAttrs) -> StateStack {
        StateStack::new(top_level)
    }

    pub(super) fn and_data<T>(self, data: T) -> StateAndData<T> {
        StateAndData(self, data)
    }
}

impl Default for State {
    fn default() -> Self {
        State::TopLevel(TopLevelAttrs::default())
    }
}

impl From<TopLevelAttrs> for State {
    fn from(attrs: TopLevelAttrs) -> Self {
        State::TopLevel(attrs)
    }
}

#[derive(Debug, PartialEq)]
pub struct StateAndData<T>(pub State, pub T);

impl<T> StateAndData<T> {
    pub fn ok<E>(self) -> Result<Self, E> {
        Ok(self)
    }
}