ttdl 6.2.2

TTDL - Terminal ToDo List manager
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
//! Markdown rendering for task subject text.
//!
//! Provides terminal-aware rendering of a CommonMark subset:
//! bold, italic, inline code, and links — with optional OSC 8 hyperlinks
//! and syntax highlighting of `+projects`, `@contexts`, and `tag:value` fields.

use std::io;
use std::sync::OnceLock;

use pulldown_cmark::{Event, Options, Parser, Tag, TagEnd};
use regex::Regex;
use termcolor::{ColorSpec, HyperlinkSpec, WriteColor};

use crate::fmt;

fn bare_url_re() -> &'static Regex {
    static RE: OnceLock<Regex> = OnceLock::new();
    RE.get_or_init(|| Regex::new(r"https?://\S+").unwrap())
}

/// Strips common trailing punctuation characters from a bare URL match.
///
/// Greedy `\S+` can absorb trailing `.`, `,`, `)`, etc. that belong to the
/// surrounding prose.  This helper peels them off so only the URL is linked.
/// Returns `(url, trailing)` where `trailing` is the stripped suffix.
fn trim_url_punctuation(url: &str) -> (&str, &str) {
    let trim_chars: &[char] = &['.', ',', ')', ']', '!', '?', ';', ':'];
    let trimmed = url.trim_end_matches(trim_chars);
    let trailing = &url[trimmed.len()..];
    (trimmed, trailing)
}

/// Returns the visible text that a terminal would display after markdown rendering.
/// Strips all formatting — used for width calculation and wrapping.
pub fn visible_text(input: &str) -> String {
    let parser = Parser::new_ext(input, Options::empty());
    let mut out = String::new();
    for event in parser {
        match event {
            Event::Text(t) => out.push_str(&t),
            Event::Code(t) => out.push_str(&t),
            Event::SoftBreak | Event::HardBreak => out.push(' '),
            _ => {}
        }
    }
    out
}

/// Merges bold/italic/underline from the markdown style stack into a base ColorSpec.
fn merge_md_style(base: &ColorSpec, bold: bool, italic: bool, underline: bool) -> ColorSpec {
    let mut spc = base.clone();
    if bold {
        spc.set_bold(true);
    }
    if italic {
        spc.set_italic(true);
    }
    if underline {
        spc.set_underline(true);
    }
    spc
}

/// Writes `text` with syntax highlighting (projects, contexts, tags, hashtags)
/// while preserving bold/italic/underline from the markdown stack.
fn write_text_with_syntax<W: WriteColor>(
    stdout: &mut W,
    text: &str,
    base: &ColorSpec,
    bold: bool,
    italic: bool,
    underline: bool,
    c: &fmt::Conf,
) -> io::Result<()> {
    let merged = merge_md_style(base, bold, italic, underline);
    if !c.syntax {
        write_text_with_urls(stdout, text, &merged, c)?;
        return Ok(());
    }
    let words = fmt::parse_subj(text);
    for word in words.iter() {
        let word_color = if fmt::is_project(word) {
            merge_md_style(&c.colors.project, bold, italic, underline)
        } else if fmt::is_hashtag(word) {
            merge_md_style(&c.colors.hashtag, bold, italic, underline)
        } else if fmt::is_context(word) {
            merge_md_style(&c.colors.context, bold, italic, underline)
        } else if fmt::is_tag(word) {
            merge_md_style(&c.colors.tag, bold, italic, underline)
        } else {
            merged.clone()
        };
        write_text_with_urls(stdout, word, &word_color, c)?;
    }
    Ok(())
}

/// Writes text, wrapping bare URLs in OSC 8 hyperlinks when running in a terminal.
/// Trailing punctuation is stripped from matched URLs and printed as plain text.
fn write_text_with_urls<W: WriteColor>(stdout: &mut W, text: &str, color: &ColorSpec, c: &fmt::Conf) -> io::Result<()> {
    if !c.atty || c.color_term == fmt::TermColorType::None {
        stdout.set_color(color)?;
        write!(stdout, "{text}")?;
        return Ok(());
    }

    let mut last = 0;
    for m in bare_url_re().find_iter(text) {
        if m.start() > last {
            stdout.set_color(color)?;
            write!(stdout, "{}", &text[last..m.start()])?;
        }
        let (url, trailing) = trim_url_punctuation(m.as_str());
        let mut url_color = color.clone();
        url_color.set_underline(true);
        stdout.set_hyperlink(&HyperlinkSpec::open(url.as_bytes()))?;
        stdout.set_color(&url_color)?;
        write!(stdout, "{url}")?;
        stdout.set_hyperlink(&HyperlinkSpec::close())?;
        if !trailing.is_empty() {
            stdout.set_color(color)?;
            write!(stdout, "{trailing}")?;
        }
        last = m.end();
    }
    if last < text.len() {
        stdout.set_color(color)?;
        write!(stdout, "{}", &text[last..])?;
    }
    Ok(())
}

/// Renders markdown-formatted text to the terminal with ANSI styling.
///
/// Supports bold, italic, inline code, links, and bare URLs.
/// When `c.syntax` is true, also highlights +projects, @contexts, #hashtags, and tags.
pub fn print_markdown<W: WriteColor>(stdout: &mut W, text: &str, base: &ColorSpec, c: &fmt::Conf) -> io::Result<()> {
    let parser = Parser::new_ext(text, Options::empty());
    let mut bold = false;
    let mut italic = false;
    let mut in_link = false;

    for event in parser {
        match event {
            Event::Start(Tag::Emphasis) => italic = true,
            Event::Start(Tag::Strong) => bold = true,
            Event::Start(Tag::Link { dest_url, .. }) => {
                in_link = true;
                if c.atty && c.color_term != fmt::TermColorType::None {
                    stdout.set_hyperlink(&HyperlinkSpec::open(dest_url.as_bytes()))?;
                }
            }
            Event::End(TagEnd::Emphasis) => italic = false,
            Event::End(TagEnd::Strong) => bold = false,
            Event::End(TagEnd::Link) => {
                if c.atty && c.color_term != fmt::TermColorType::None {
                    stdout.set_hyperlink(&HyperlinkSpec::close())?;
                }
                in_link = false;
            }
            Event::Code(t) => {
                let code_color = merge_md_style(&c.colors.code, bold, italic, in_link);
                stdout.set_color(&code_color)?;
                write!(stdout, "{t}")?;
            }
            Event::Text(t) => {
                if in_link {
                    // Inside a link — `in_link` maps to underline in merge_md_style
                    let merged = merge_md_style(base, bold, italic, true);
                    stdout.set_color(&merged)?;
                    write!(stdout, "{t}")?;
                } else {
                    write_text_with_syntax(stdout, &t, base, bold, italic, false, c)?;
                }
            }
            Event::SoftBreak | Event::HardBreak => {
                write!(stdout, " ")?;
            }
            _ => {} // Ignore block-level events
        }
    }

    Ok(())
}

/// Renders a range of markdown text by visible character count.
///
/// Skips the first `skip` visible characters, then renders up to `limit`
/// visible characters. Used for wrapped/cut lines: line 1 uses skip=0,
/// line 2 uses skip=len(line1), etc.
///
/// Note: when `skip` or `limit` bisects a bare URL, the halves are rendered
/// as plain text rather than hyperlinks.  This is a known limitation of the
/// character-offset slicing approach; the output is visually correct.
pub fn print_markdown_range<W: WriteColor>(
    stdout: &mut W,
    text: &str,
    skip: usize,
    limit: usize,
    base: &ColorSpec,
    c: &fmt::Conf,
) -> io::Result<()> {
    let parser = Parser::new_ext(text, Options::empty());
    let mut bold = false;
    let mut italic = false;
    let mut in_link = false;
    let mut link_url_str: Option<String> = None;
    let mut link_hyperlink_opened = false;
    let mut visible_pos = 0usize;
    let end = skip + limit;

    for event in parser {
        if visible_pos >= end {
            break;
        }
        match event {
            Event::Start(Tag::Emphasis) => italic = true,
            Event::Start(Tag::Strong) => bold = true,
            Event::Start(Tag::Link { dest_url, .. }) => {
                in_link = true;
                link_url_str = Some(dest_url.to_string());
                link_hyperlink_opened = false;
                // Open hyperlink eagerly when already in the visible range
                if visible_pos >= skip && c.atty && c.color_term != fmt::TermColorType::None {
                    stdout.set_hyperlink(&HyperlinkSpec::open(dest_url.as_bytes()))?;
                    link_hyperlink_opened = true;
                }
            }
            Event::End(TagEnd::Emphasis) => italic = false,
            Event::End(TagEnd::Strong) => bold = false,
            Event::End(TagEnd::Link) => {
                if link_hyperlink_opened && c.atty && c.color_term != fmt::TermColorType::None {
                    stdout.set_hyperlink(&HyperlinkSpec::close())?;
                }
                in_link = false;
                link_url_str = None;
                link_hyperlink_opened = false;
            }
            Event::Code(t) => {
                for ch in t.chars() {
                    if visible_pos >= end {
                        break;
                    }
                    if visible_pos >= skip {
                        let code_color = merge_md_style(&c.colors.code, bold, italic, in_link);
                        stdout.set_color(&code_color)?;
                        write!(stdout, "{ch}")?;
                    }
                    visible_pos += 1;
                }
            }
            Event::Text(t) => {
                // Compute the slice of text that falls in our range
                let text_start = visible_pos;
                let text_chars: Vec<char> = t.chars().collect();
                let text_end = text_start + text_chars.len();

                if text_end <= skip || text_start >= end {
                    // Entirely outside our range
                    visible_pos += text_chars.len();
                    continue;
                }

                let range_start = skip.saturating_sub(text_start);
                let range_end = if text_end > end { end - text_start } else { text_chars.len() };
                let slice: String = text_chars[range_start..range_end].iter().collect();

                if in_link {
                    // Lazy-open hyperlink when the link straddles the skip boundary
                    if !link_hyperlink_opened
                        && c.atty
                        && c.color_term != fmt::TermColorType::None
                        && let Some(ref url) = link_url_str
                    {
                        stdout.set_hyperlink(&HyperlinkSpec::open(url.as_bytes()))?;
                        link_hyperlink_opened = true;
                    }
                    let merged = merge_md_style(base, bold, italic, true);
                    stdout.set_color(&merged)?;
                    write!(stdout, "{slice}")?;
                } else {
                    write_text_with_syntax(stdout, &slice, base, bold, italic, false, c)?;
                }
                visible_pos += text_chars.len();
            }
            Event::SoftBreak | Event::HardBreak => {
                if visible_pos >= skip && visible_pos < end {
                    write!(stdout, " ")?;
                }
                visible_pos += 1;
            }
            _ => {}
        }
    }

    // Close any open hyperlink if we broke out of the loop mid-link
    if in_link && link_hyperlink_opened && c.atty && c.color_term != fmt::TermColorType::None {
        stdout.set_hyperlink(&HyperlinkSpec::close())?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use termcolor::{Buffer, ColorSpec};

    // ── visible_text ──────────────────────────────────────────────────────────

    #[test]
    fn visible_text_bold() {
        assert_eq!(visible_text("**bold**"), "bold");
    }

    #[test]
    fn visible_text_italic() {
        assert_eq!(visible_text("*italic*"), "italic");
    }

    #[test]
    fn visible_text_code() {
        assert_eq!(visible_text("`code`"), "code");
    }

    #[test]
    fn visible_text_link() {
        assert_eq!(visible_text("[label](https://example.com)"), "label");
    }

    #[test]
    fn visible_text_plain() {
        assert_eq!(visible_text("plain text"), "plain text");
    }

    #[test]
    fn visible_text_unmatched_star() {
        assert_eq!(visible_text("a * b"), "a * b");
    }

    #[test]
    fn visible_text_underscore_tag() {
        // CommonMark flanking rules: underscores within words don't trigger emphasis
        assert_eq!(visible_text("due_date:2024-01-01"), "due_date:2024-01-01");
    }

    #[test]
    fn visible_text_bold_italic() {
        assert_eq!(visible_text("***both***"), "both");
    }

    #[test]
    fn visible_text_mixed() {
        assert_eq!(visible_text("**bold** and *italic* and `code`"), "bold and italic and code");
    }

    #[test]
    fn visible_text_empty() {
        assert_eq!(visible_text(""), "");
    }

    #[test]
    fn visible_text_nested_formatting() {
        assert_eq!(visible_text("**bold *and italic***"), "bold and italic");
    }

    #[test]
    fn visible_text_soft_break() {
        // pulldown-cmark emits SoftBreak between lines; visible_text renders it as a space
        assert_eq!(visible_text("line one\nline two"), "line one line two");
    }

    #[test]
    fn visible_text_multiple_links() {
        assert_eq!(visible_text("[first](https://a.com) and [second](https://b.com)"), "first and second");
    }

    #[test]
    fn visible_text_bare_url() {
        // Bare URLs are plain text to the parser; they pass through unchanged
        assert_eq!(visible_text("see https://example.com for details"), "see https://example.com for details");
    }

    // ── merge_md_style ────────────────────────────────────────────────────────

    #[test]
    fn merge_md_style_bold() {
        let base = ColorSpec::new();
        let result = merge_md_style(&base, true, false, false);
        assert!(result.bold());
        assert!(!result.italic());
        assert!(!result.underline());
    }

    #[test]
    fn merge_md_style_italic() {
        let base = ColorSpec::new();
        let result = merge_md_style(&base, false, true, false);
        assert!(!result.bold());
        assert!(result.italic());
    }

    #[test]
    fn merge_md_style_underline() {
        let base = ColorSpec::new();
        let result = merge_md_style(&base, false, false, true);
        assert!(result.underline());
    }

    #[test]
    fn merge_md_style_all_flags() {
        let base = ColorSpec::new();
        let result = merge_md_style(&base, true, true, true);
        assert!(result.bold());
        assert!(result.italic());
        assert!(result.underline());
    }

    #[test]
    fn merge_md_style_preserves_base_color() {
        use termcolor::Color;
        let mut base = ColorSpec::new();
        base.set_fg(Some(Color::Red));
        let result = merge_md_style(&base, true, false, false);
        assert_eq!(result.fg(), Some(&Color::Red));
        assert!(result.bold());
    }

    // ── trim_url_punctuation ──────────────────────────────────────────────────

    #[test]
    fn trim_url_trailing_period() {
        let (url, trailing) = trim_url_punctuation("https://example.com.");
        assert_eq!(url, "https://example.com");
        assert_eq!(trailing, ".");
    }

    #[test]
    fn trim_url_trailing_paren_comma() {
        let (url, trailing) = trim_url_punctuation("https://example.com),");
        assert_eq!(url, "https://example.com");
        assert_eq!(trailing, "),");
    }

    #[test]
    fn trim_url_no_trailing_punctuation() {
        let (url, trailing) = trim_url_punctuation("https://example.com/path");
        assert_eq!(url, "https://example.com/path");
        assert_eq!(trailing, "");
    }

    #[test]
    fn trim_url_query_string() {
        let (url, trailing) = trim_url_punctuation("https://example.com/path?q=1");
        assert_eq!(url, "https://example.com/path?q=1");
        assert_eq!(trailing, "");
    }

    // ── print_markdown output tests ───────────────────────────────────────────

    fn make_conf() -> fmt::Conf {
        fmt::Conf { atty: false, ..Default::default() }
    }

    fn render_markdown(text: &str) -> String {
        let mut buf = Buffer::no_color();
        let base = ColorSpec::new();
        let c = make_conf();
        print_markdown(&mut buf, text, &base, &c).unwrap();
        String::from_utf8(buf.into_inner()).unwrap()
    }

    #[test]
    fn print_markdown_plain_text() {
        assert_eq!(render_markdown("hello world"), "hello world");
    }

    #[test]
    fn print_markdown_bold() {
        // Bold markers are consumed; visible text is the inner content
        assert_eq!(render_markdown("**bold**"), "bold");
    }

    #[test]
    fn print_markdown_italic() {
        assert_eq!(render_markdown("*italic*"), "italic");
    }

    #[test]
    fn print_markdown_code() {
        assert_eq!(render_markdown("`code`"), "code");
    }

    #[test]
    fn print_markdown_link() {
        // Link label is the visible text; dest_url is only in hyperlink escape
        assert_eq!(render_markdown("[label](https://example.com)"), "label");
    }

    #[test]
    fn print_markdown_mixed() {
        assert_eq!(render_markdown("**bold** and *italic*"), "bold and italic");
    }

    // ── print_markdown_range output tests ────────────────────────────────────

    fn render_range(text: &str, skip: usize, limit: usize) -> String {
        let mut buf = Buffer::no_color();
        let base = ColorSpec::new();
        let c = make_conf();
        print_markdown_range(&mut buf, text, skip, limit, &base, &c).unwrap();
        String::from_utf8(buf.into_inner()).unwrap()
    }

    #[test]
    fn print_markdown_range_full() {
        let text = "hello world";
        let full = render_markdown(text);
        let range = render_range(text, 0, full.chars().count());
        assert_eq!(full, range);
    }

    #[test]
    fn print_markdown_range_skip() {
        // Skip first 6 chars of "hello world" → "world"
        let result = render_range("hello world", 6, 5);
        assert_eq!(result, "world");
    }

    #[test]
    fn print_markdown_range_cut_through_formatted() {
        // "**bold** text" → visible "bold text"; take first 4 chars → "bold"
        let result = render_range("**bold** text", 0, 4);
        assert_eq!(result, "bold");
    }

    #[test]
    fn print_markdown_range_second_line() {
        // "bold text" visible; skip 4 → " text"
        let result = render_range("**bold** text", 4, 5);
        assert_eq!(result, " text");
    }
}