mdsee-render 0.1.0

ANSI / plain renderer for mdsee
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
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
//! mdsee-render(design.md §5)。
//!
//! Layout TreeからANSI / plain textを生成する。

mod highlight;
mod style;
mod theme;

use std::io;

use thiserror::Error;

use mdsee_layout::{LayoutBlock, LayoutDocument, LayoutLine, LayoutSpan, SemanticStyle};
use mdsee_terminal::ColorLevel;

#[cfg(feature = "syntax")]
pub use highlight::syntect_backend::SyntectHighlighter;
pub use highlight::{HighlightedLine, HighlightedSpan, NoHighlight, SyntaxHighlighter};
pub use theme::{select_auto_theme, AlertTheme, TextStyle, Theme};

/// ANSI reset sequence。
const RESET: &str = "\x1b[0m";

/// Render error(§66)。
#[derive(Debug, Error)]
pub enum RenderError {
    #[error("failed to write output")]
    Write(#[from] io::Error),
}

/// Render options。
///
/// `color_level` が `None` の場合はplain text renderingになる(§71)。
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenderOptions {
    pub color_level: ColorLevel,
    /// 行頭の左margin(§22)。layoutのmarginと同じ値を渡す。
    pub margin: u16,
    /// OSC 8 hyperlinkを出すか(§33)。`false` なら `text <URL>` へfallbackする。
    pub osc8: bool,
    /// Theme(§61, S2-9)。
    pub theme: Theme,
}

impl Default for RenderOptions {
    fn default() -> Self {
        Self {
            color_level: ColorLevel::None,
            margin: 2,
            osc8: false,
            theme: Theme::dark(),
        }
    }
}

/// LayoutDocumentをtargetへ書き出す(§100 基本pipeline)。
///
/// blockの間に空行を1つ挟む。空行には余白を出さない。
pub fn render(
    document: &LayoutDocument,
    target: &mut dyn io::Write,
    options: &RenderOptions,
) -> Result<(), RenderError> {
    let mut output = String::new();
    for (index, block) in document.blocks.iter().enumerate() {
        if index > 0 {
            output.push('\n');
        }
        match block {
            LayoutBlock::Text(text_block) => {
                for line in &text_block.lines {
                    write_text_line(&mut output, line, options);
                }
            }
            LayoutBlock::Code(code) => write_code_block(&mut output, code, options),
            LayoutBlock::Rule(rule) => write_rule_line(&mut output, rule.width, options),
            LayoutBlock::Table(table) => {
                for line in &table.lines {
                    write_text_line(&mut output, line, options);
                }
            }
        }
    }
    target.write_all(output.as_bytes())?;
    Ok(())
}

fn write_text_line(output: &mut String, line: &LayoutLine, options: &RenderOptions) {
    if line.spans.iter().all(|span| span.content.is_empty()) {
        output.push('\n');
        return;
    }
    push_margin(output, options.margin);
    match options.color_level {
        ColorLevel::None => {
            for (position, span) in line.spans.iter().enumerate() {
                push_span_plain(output, span, fallback_url(span, line, position));
            }
        }
        level => {
            for (position, span) in line.spans.iter().enumerate() {
                let sequence = style::sgr_sequence(&options.theme.spec(span.style), level);
                if !sequence.is_empty() {
                    output.push_str(&sequence);
                }
                match (&span.link, options.osc8) {
                    // §33: OSC 8 hyperlink
                    (Some(link), true) => {
                        output.push_str(&osc8_open(&link.url));
                        output.push_str(&span.content);
                        output.push_str(OSC8_CLOSE);
                    }
                    _ => {
                        push_span_plain(output, span, fallback_url(span, line, position));
                    }
                }
                if !sequence.is_empty() {
                    output.push_str(RESET);
                }
            }
        }
    }
    output.push('\n');
}

/// span本文を書き出し、fallback URLがあれば末尾空白の直前に置く。
///
/// `docs ` なら `docs <URL> ` とすることで、
/// `docs  <URL>`(空白の二重化)を防ぐ。
fn push_span_plain(output: &mut String, span: &LayoutSpan, fallback_url: Option<&str>) {
    let trimmed = span.content.trim_end_matches(' ');
    let trailing = &span.content[trimmed.len()..];
    output.push_str(trimmed);
    if let Some(url) = fallback_url {
        output.push_str(&format!(" <{url}>"));
    }
    output.push_str(trailing);
}

/// plain fallback用のURL(§33)。
///
/// 同一URLのspanが行内に複数ある場合は、最後の出現箇所にのみ付ける。
fn fallback_url<'a>(
    span: &'a LayoutSpan,
    line: &'a LayoutLine,
    position: usize,
) -> Option<&'a str> {
    let url = span.link.as_ref().map(|l| l.url.as_str())?;
    let is_last_occurrence = !line
        .spans
        .iter()
        .skip(position + 1)
        .any(|other| other.link.as_ref().map(|l| l.url.as_str()) == Some(url));
    is_last_occurrence.then_some(url)
}

/// OSC 8 開始sequence(§33): `ESC ] 8 ; ; URL ST`
fn osc8_open(url: &str) -> String {
    format!("\x1b]8;;{url}\x1b\\")
}

/// OSC 8 終了sequence(§33): `ESC ] 8 ; ; ST`
const OSC8_CLOSE: &str = "\x1b]8;;\x1b\\";

/// 水平罫線(§11 HorizontalRule)。styleは§19の `Border`。
fn write_rule_line(output: &mut String, width: usize, options: &RenderOptions) {
    push_margin(output, options.margin);
    let content: String = std::iter::repeat_n('', width).collect();
    match options.color_level {
        ColorLevel::None => output.push_str(&content),
        level => {
            let sequence = style::sgr_sequence(&options.theme.spec(SemanticStyle::Border), level);
            if sequence.is_empty() {
                output.push_str(&content);
            } else {
                output.push_str(&sequence);
                output.push_str(&content);
                output.push_str(RESET);
            }
        }
    }
    output.push('\n');
}

/// コードblock(§28)。`╭─ 言語 ─` 枠で囲み、中身はhighlightして出す。
///
/// 本文は折り返さない(S3-1)。色が無効な場合はhighlightも行わない。
fn write_code_block(output: &mut String, code: &mdsee_layout::CodeLayout, options: &RenderOptions) {
    use unicode_width::UnicodeWidthStr;

    // 上枠: ╭─ rust ─────(言語がなければ ╭────)
    push_margin(output, options.margin);
    match options.color_level {
        ColorLevel::None => match &code.language {
            Some(language) => {
                let prefix = format!("╭─ {language} ");
                let fill = code.width.saturating_sub(prefix.width() + 1);
                output.push_str(&prefix);
                output.push_str(&"".repeat(fill));
                output.push('');
            }
            None => {
                output.push('');
                output.push_str(&"".repeat(code.width.saturating_sub(1)));
            }
        },
        level => {
            let border = style::sgr_sequence(&options.theme.spec(SemanticStyle::Border), level);
            output.push_str(&border);
            match &code.language {
                Some(language) => {
                    let label_width = UnicodeWidthStr::width(language.as_str());
                    // "╭─ " + label + " " + "─" * (width - 3 - label - 1)
                    let fill = code.width.saturating_sub(3 + label_width + 1).max(1);
                    output.push_str("╭─ ");
                    output.push_str(RESET);
                    let label =
                        style::sgr_sequence(&options.theme.spec(SemanticStyle::Muted), level);
                    output.push_str(&label);
                    output.push_str(language);
                    output.push_str(RESET);
                    output.push_str(&border);
                    output.push(' ');
                    output.push_str(&"".repeat(fill));
                    output.push_str(RESET);
                }
                None => {
                    output.push('');
                    output.push_str(&"".repeat(code.width.saturating_sub(1)));
                    output.push_str(RESET);
                }
            }
        }
    }
    output.push('\n');

    // 本文行: │ + highlight済みspan
    let highlighted = highlight_code(code, options);
    for (index, line) in code.lines.iter().enumerate() {
        push_margin(output, options.margin);
        match options.color_level {
            ColorLevel::None => {
                if line.is_empty() {
                    output.push('');
                } else {
                    output.push_str("");
                    output.push_str(line);
                }
            }
            level => {
                let border = style::sgr_sequence(&options.theme.spec(SemanticStyle::Border), level);
                output.push_str(&border);
                output.push('');
                output.push_str(RESET);
                if line.is_empty() {
                    output.push('\n');
                    continue;
                }
                output.push(' ');
                match highlighted.as_ref().and_then(|lines| lines.get(index)) {
                    Some(hl) if !hl.spans.is_empty() => {
                        for span in &hl.spans {
                            let sequence = style::sgr_sequence(
                                &style::StyleSpec {
                                    fg: Some(span.fg),
                                    bold: span.bold,
                                    italic: span.italic,
                                    underline: span.underline,
                                    strike: false,
                                },
                                level,
                            );
                            if sequence.is_empty() {
                                output.push_str(&span.text);
                            } else {
                                output.push_str(&sequence);
                                output.push_str(&span.text);
                                output.push_str(RESET);
                            }
                        }
                    }
                    _ => {
                        let sequence =
                            style::sgr_sequence(&options.theme.spec(SemanticStyle::Code), level);
                        if sequence.is_empty() {
                            output.push_str(line);
                        } else {
                            output.push_str(&sequence);
                            output.push_str(line);
                            output.push_str(RESET);
                        }
                    }
                }
            }
        }
        output.push('\n');
    }

    // 下枠: ╰────
    push_margin(output, options.margin);
    match options.color_level {
        ColorLevel::None => {
            output.push('');
            output.push_str(&"".repeat(code.width.saturating_sub(1)));
        }
        level => {
            let border = style::sgr_sequence(&options.theme.spec(SemanticStyle::Border), level);
            output.push_str(&border);
            output.push('');
            output.push_str(&"".repeat(code.width.saturating_sub(1)));
            output.push_str(RESET);
        }
    }
    output.push('\n');
}

/// code blockのhighlight。色無効またはfeature構成によりhighlightできない
/// 場合は `None`(§29: rendererはtrait越しにのみ使う)。
fn highlight_code(
    code: &mdsee_layout::CodeLayout,
    options: &RenderOptions,
) -> Option<Vec<HighlightedLine>> {
    if options.color_level == ColorLevel::None {
        return None;
    }
    #[cfg(feature = "syntax")]
    {
        let highlighter: &dyn SyntaxHighlighter =
            &SyntectHighlighter::new(options.theme.syntax_theme.clone());
        let mut source = code.lines.join("\n");
        if !source.is_empty() {
            source.push('\n');
        }
        let lines = highlighter.highlight(&source, code.language.as_deref());
        Some(lines)
    }
    #[cfg(not(feature = "syntax"))]
    {
        let highlighter: &dyn SyntaxHighlighter = &NoHighlight;
        let lines = highlighter.highlight(&code.lines.join("\n"), code.language.as_deref());
        Some(lines)
    }
}

fn push_margin(output: &mut String, margin: u16) {
    for _ in 0..margin {
        output.push(' ');
    }
}

#[cfg(test)]
mod tests {
    use mdsee_layout::{LayoutLine, LayoutSpan, LinkTarget, RuleLayout, SemanticStyle, TextBlock};

    use super::*;

    fn span(content: &str, style: SemanticStyle) -> LayoutSpan {
        LayoutSpan {
            content: content.to_string(),
            style,
            link: None,
        }
    }

    fn document_with(lines: Vec<LayoutLine>) -> LayoutDocument {
        LayoutDocument {
            blocks: vec![LayoutBlock::Text(TextBlock { lines })],
        }
    }

    fn render_to(document: &LayoutDocument, options: &RenderOptions) -> String {
        let mut buffer: Vec<u8> = Vec::new();
        render(document, &mut buffer, options).unwrap();
        String::from_utf8(buffer).unwrap()
    }

    #[test]
    fn plain_rendering_has_no_escape_sequences() {
        let document = document_with(vec![LayoutLine {
            spans: vec![
                span("hello ", SemanticStyle::Body),
                span("world", SemanticStyle::Strong),
            ],
        }]);
        let output = render_to(&document, &RenderOptions::default());
        assert_eq!(output, "  hello world\n");
        assert!(!output.contains('\x1b'));
    }

    #[test]
    fn truecolor_rendering_emits_ansi() {
        let document = document_with(vec![LayoutLine {
            spans: vec![span("hi", SemanticStyle::InlineCode)],
        }]);
        let options = RenderOptions {
            color_level: ColorLevel::TrueColor,
            margin: 0,
            osc8: false,
            theme: Theme::dark(),
        };
        let output = render_to(&document, &options);
        assert_eq!(output, "\x1b[38;2;79;193;233mhi\x1b[0m\n");
    }

    #[test]
    fn blocks_are_separated_by_blank_line() {
        let document = LayoutDocument {
            blocks: vec![
                LayoutBlock::Text(TextBlock {
                    lines: vec![LayoutLine {
                        spans: vec![span("one", SemanticStyle::Body)],
                    }],
                }),
                LayoutBlock::Text(TextBlock {
                    lines: vec![LayoutLine {
                        spans: vec![span("two", SemanticStyle::Body)],
                    }],
                }),
            ],
        };
        let output = render_to(&document, &RenderOptions::default());
        assert_eq!(output, "  one\n\n  two\n");
    }

    #[test]
    fn blank_line_has_no_trailing_margin() {
        let document = document_with(vec![
            LayoutLine {
                spans: vec![span("a", SemanticStyle::Body)],
            },
            LayoutLine { spans: vec![] },
            LayoutLine {
                spans: vec![span("b", SemanticStyle::Body)],
            },
        ]);
        let output = render_to(&document, &RenderOptions::default());
        assert_eq!(output, "  a\n\n  b\n");
    }

    #[test]
    fn code_block_renders_frame_and_highlighted_lines() {
        let document = LayoutDocument {
            blocks: vec![LayoutBlock::Code(mdsee_layout::CodeLayout {
                language: Some("rust".to_string()),
                lines: vec!["fn main() {}".to_string()],
                width: 20,
            })],
        };
        let options = RenderOptions {
            color_level: ColorLevel::Ansi256,
            margin: 0,
            osc8: false,
            theme: Theme::dark(),
        };
        let output = render_to(&document, &options);
        let lines: Vec<&str> = output.lines().collect();
        assert_eq!(lines.len(), 3);
        // 上枠は ╭─ rust ─…。言語label付き
        assert!(lines[0].starts_with("\x1b[38;5;"));
        assert!(lines[0].contains(''));
        assert!(lines[0].contains("rust"));
        // 本文行は │ prefixを持ち、highlight色(syntect由来)で分割される。
        // escapeを除去すると元のコード行に戻る
        let stripped = strip_sgr(lines[1]);
        assert_eq!(stripped, "│ fn main() {}");
        // 下枠
        assert!(lines[2].contains(''));
        assert_eq!(
            lines[2],
            format!(
                "\x1b[38;5;{}m╰{}\x1b[0m",
                style::rgb_to_256(style::Rgb(48, 54, 61)),
                "".repeat(18)
            )
        );
    }

    /// SGR sequence(\x1b[...m)を除去する。test専用の簡易版。
    fn strip_sgr(input: &str) -> String {
        let mut out = String::new();
        let mut chars = input.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '\x1b' && chars.peek() == Some(&'[') {
                for c in chars.by_ref() {
                    if c == 'm' {
                        break;
                    }
                }
            } else {
                out.push(c);
            }
        }
        out
    }

    #[test]
    fn plain_code_block_renders_frame_without_ansi() {
        let document = LayoutDocument {
            blocks: vec![LayoutBlock::Code(mdsee_layout::CodeLayout {
                language: Some("sh".to_string()),
                lines: vec!["ls -la".to_string(), String::new()],
                width: 12,
            })],
        };
        let output = render_to(&document, &RenderOptions::default());
        assert_eq!(output, "  ╭─ sh ──────\n  │ ls -la\n\n  ╰───────────\n");
        assert!(!output.contains('\x1b'));
    }

    #[test]
    fn no_language_code_block_has_plain_frame() {
        let document = LayoutDocument {
            blocks: vec![LayoutBlock::Code(mdsee_layout::CodeLayout {
                language: None,
                lines: vec!["x".to_string()],
                width: 6,
            })],
        };
        let output = render_to(&document, &RenderOptions::default());
        assert_eq!(output, "  ╭─────\n  │ x\n  ╰─────\n");
    }

    // ---- Sprint 2(S2-4, S2-3) ----

    fn link_span(content: &str, url: &str) -> LayoutSpan {
        LayoutSpan {
            content: content.to_string(),
            style: SemanticStyle::Link,
            link: Some(LinkTarget {
                url: url.to_string(),
            }),
        }
    }

    #[test]
    fn osc8_wraps_link_text() {
        // §33: ESC ] 8 ; ; URL ST text ESC ] 8 ; ; ST
        let document = document_with(vec![LayoutLine {
            spans: vec![link_span("site", "https://example.com")],
        }]);
        let options = RenderOptions {
            color_level: ColorLevel::TrueColor,
            margin: 0,
            osc8: true,
            theme: Theme::dark(),
        };
        let output = render_to(&document, &options);
        assert_eq!(
            output,
            "\x1b[4;38;2;88;166;255m\x1b]8;;https://example.com\x1b\\site\x1b]8;;\x1b\\\x1b[0m\n"
        );
    }

    #[test]
    fn plain_fallback_appends_url_in_angle_brackets() {
        // §33: plain fallbackは `text <URL>`
        let document = document_with(vec![LayoutLine {
            spans: vec![
                span("see ", SemanticStyle::Body),
                link_span("docs", "https://example.com/docs"),
            ],
        }]);
        let output = render_to(&document, &RenderOptions::default());
        assert_eq!(output, "  see docs <https://example.com/docs>\n");
    }

    #[test]
    fn plain_fallback_keeps_trailing_space_after_url() {
        // link spanの末尾空白はURLの後に置く(空白の二重化を防ぐ)
        let document = document_with(vec![LayoutLine {
            spans: vec![
                span("see ", SemanticStyle::Body),
                link_span("docs ", "https://example.com"),
                span("here", SemanticStyle::Body),
            ],
        }]);
        let output = render_to(&document, &RenderOptions::default());
        assert_eq!(output, "  see docs <https://example.com> here\n");
    }

    #[test]
    fn same_url_repeated_in_line_prints_fallback_once() {
        let document = document_with(vec![LayoutLine {
            spans: vec![
                link_span("a", "https://x"),
                span(" ", SemanticStyle::Body),
                link_span("b", "https://x"),
            ],
        }]);
        let output = render_to(&document, &RenderOptions::default());
        assert_eq!(output, "  a b <https://x>\n");
    }

    #[test]
    fn different_urls_each_get_fallback() {
        let document = document_with(vec![LayoutLine {
            spans: vec![
                link_span("a", "https://x"),
                span(" ", SemanticStyle::Body),
                link_span("b", "https://y"),
            ],
        }]);
        let output = render_to(&document, &RenderOptions::default());
        assert_eq!(output, "  a <https://x> b <https://y>\n");
    }

    #[test]
    fn rule_block_renders_full_width_line_with_border_style() {
        let document = LayoutDocument {
            blocks: vec![LayoutBlock::Rule(RuleLayout { width: 5 })],
        };
        let options = RenderOptions {
            color_level: ColorLevel::TrueColor,
            margin: 0,
            osc8: false,
            theme: Theme::dark(),
        };
        let output = render_to(&document, &options);
        assert_eq!(output, "\x1b[38;2;48;54;61m─────\x1b[0m\n");
    }
}