j-cli 12.9.76

A fast CLI tool for alias management, daily reports, and productivity
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
//! Markdown 渲染器
//!
//! 负责将文本渲染为 ratatui 的 Line/Widget。
//! 支持代码块围栏样式、表格、Markdown 语法高亮等高级渲染。

mod code_block;
mod inline;
mod line;
mod table;
mod visual_line;

use ratatui::{
    style::{Color, Modifier, Style},
    text::{Line, Span},
};

use super::theme::{EditorTheme, HighlightFn};
use super::wrap_engine::VisualLine;
use super::{search::SearchState, text_buffer::TextBuffer};
use crate::util::text::{char_width, display_width};

use code_block::CodeBlockCache;

/// Markdown 渲染器
pub struct MarkdownRenderer {
    theme: EditorTheme,
    /// 水平滚动偏移
    horizontal_scroll: usize,
    /// 代码块缓存
    code_block_cache: CodeBlockCache,
    /// 语法高亮函数
    highlight_fn: HighlightFn,
    /// 是否显示行号
    show_line_numbers: bool,
}

impl MarkdownRenderer {
    /// 创建新的渲染器
    pub fn new(theme: EditorTheme, highlight_fn: HighlightFn) -> Self {
        Self {
            theme,
            horizontal_scroll: 0,
            code_block_cache: CodeBlockCache::new(),
            highlight_fn,
            show_line_numbers: true,
        }
    }

    /// 使代码块缓存失效
    pub fn invalidate_cache(&mut self) {
        self.code_block_cache.invalidate();
    }

    /// 切换主题
    pub fn set_theme(&mut self, theme: EditorTheme) {
        self.theme = theme;
        self.invalidate_cache();
    }

    /// 设置是否显示行号
    pub fn set_show_line_numbers(&mut self, show: bool) {
        self.show_line_numbers = show;
    }

    /// 获取是否显示行号
    pub fn is_show_line_numbers(&self) -> bool {
        self.show_line_numbers
    }

    /// 生成行号字符串
    fn format_line_number(&self, line_idx: usize) -> String {
        if self.show_line_numbers {
            format!("{:4} ", line_idx + 1)
        } else {
            String::new()
        }
    }

    /// 生成续行行号字符串(空格或空)
    fn format_continuation_line_number(&self) -> String {
        if self.show_line_numbers {
            "     ".to_string()
        } else {
            String::new()
        }
    }

    /// 确保代码块缓存有效
    pub fn ensure_cache_valid(&mut self, lines: &[String]) {
        if !self.code_block_cache.valid || self.code_block_cache.line_count != lines.len() {
            self.code_block_cache.build(lines);
        }
    }

    // ========== 基础样式辅助方法 ==========

    /// 创建带背景色的 Style
    #[inline]
    pub fn style(&self, fg: Color) -> Style {
        Style::default().fg(fg).bg(self.theme.bg_primary)
    }

    /// 创建带输入区背景色的 Style
    #[inline]
    pub fn style_input(&self, fg: Color) -> Style {
        Style::default().fg(fg).bg(self.theme.bg_input)
    }

    /// 创建带背景色和加粗的 Style
    #[inline]
    pub fn style_bold(&self, fg: Color) -> Style {
        Style::default()
            .fg(fg)
            .bg(self.theme.bg_primary)
            .add_modifier(Modifier::BOLD)
    }

    /// 创建代码块背景色的 Style
    #[inline]
    pub fn style_code(&self, fg: Color) -> Style {
        Style::default().fg(fg).bg(self.theme.code_bg)
    }

    // ========== 视觉行渲染 ==========

    /// 渲染一个视觉行(Typora 风格)
    ///
    /// - 光标行:显示原始 Markdown 源码 + 光标
    /// - 非光标行:显示渲染后的 Markdown 效果(代码块围栏、表格、标题等)
    #[allow(clippy::too_many_arguments)]
    pub fn render_visual_line(
        &self,
        vl: &VisualLine,
        is_cursor_line: bool,
        cursor_col: Option<usize>,
        search: &SearchState,
        buffer: &TextBuffer,
        wrap_width: usize,
    ) -> Vec<Line<'static>> {
        let lines = buffer.lines();
        let logical_line = vl.logical_line;
        let Some(raw_line_content) = lines.get(logical_line) else {
            return vec![Line::default()];
        };
        // 将 tab 替换为空格,防止终端展开 tab 导致二次折行
        let line_content = Self::normalize_tabs(raw_line_content);
        // 视觉行文本同样需要标准化(tab → 空格)
        let vl_text = Self::normalize_tabs(&vl.text);

        let is_continuation = vl.start_col > 0;

        // 行号:续行显示空格,否则显示行号;若隐藏行号则为空
        let line_num_str = if !self.show_line_numbers {
            String::new()
        } else if is_continuation {
            "     ".to_string()
        } else {
            format!("{:>4} ", logical_line + 1)
        };
        let line_num_style = if is_cursor_line {
            Style::default()
                .fg(Color::Yellow)
                .bg(self.theme.bg_input)
                .add_modifier(Modifier::BOLD)
        } else {
            Style::default()
                .fg(Color::DarkGray)
                .bg(self.theme.bg_primary)
        };

        // ---- 光标行:显示源码 + 光标 ----
        // 代码块内的光标行使用 code_bg 背景以保持视觉一致性
        let code_block_max_width = if !Self::is_code_fence_line(&line_content)
            && self.is_line_in_complete_code_block(logical_line, lines)
        {
            self.find_code_block_range(logical_line, lines)
                .map(|(start, end)| self.calculate_code_block_max_width(start, end, lines))
        } else {
            None
        };

        if is_cursor_line {
            // 判断是否是逻辑行的最后一个视觉行
            let is_last_vl = vl.end_col >= line_content.chars().count();
            return vec![self.render_cursor_visual_line(
                vl_text,
                vl,
                &visual_line::CursorLineContext {
                    line_num_str: &line_num_str,
                    line_num_style,
                    cursor_col,
                    search,
                    code_block_max_width,
                    is_last_vl,
                },
            )];
        }

        // ---- 非光标行:Typora 风格渲染 ----
        // 续行(折行后的第二行及之后)无法独立渲染 Markdown,
        // 因为 Markdown 标记可能跨越折行边界,所以续行显示源码
        // 但代码块内的续行需要保持 code_bg 样式
        if is_continuation {
            let text = &vl_text;

            // 检查续行是否在代码块内(非围栏行)
            let in_code_block = !Self::is_code_fence_line(&line_content)
                && self.is_line_in_complete_code_block(logical_line, lines);

            if in_code_block {
                // 代码块续行:保持 code_bg 背景 + 边框
                let mut spans = vec![
                    Span::styled(
                        line_num_str,
                        Style::default()
                            .fg(Color::DarkGray)
                            .bg(self.theme.bg_primary),
                    ),
                    Span::styled("", self.style_code(self.theme.text_dim)),
                    Span::styled(" ", Style::default().bg(self.theme.code_bg)),
                ];
                // 续行用 code_bg 背景显示源码,不语法高亮(续行是折行片段)
                spans.push(Span::styled(
                    text.clone(),
                    Style::default()
                        .fg(self.theme.text_normal)
                        .bg(self.theme.code_bg),
                ));
                // 计算填充宽度以对齐右边框
                let max_width = self
                    .find_code_block_range(logical_line, lines)
                    .map(|(start, end)| self.calculate_code_block_max_width(start, end, lines))
                    .unwrap_or(0);
                let content_width = display_width(text);
                let fill_width = max_width.saturating_sub(content_width);
                spans.push(Span::styled(
                    " ".repeat(fill_width),
                    Style::default().bg(self.theme.code_bg),
                ));
                spans.push(Span::styled(" ", Style::default().bg(self.theme.code_bg)));
                spans.push(Span::styled("", self.style_code(self.theme.text_dim)));
                return vec![Line::from(spans)];
            }

            // 表格续行:保持表格边框样式
            if Self::is_table_row(&line_content) {
                let mut spans = vec![Span::styled(line_num_str, line_num_style)];
                spans.push(Span::styled(
                    text.clone(),
                    self.style(self.theme.text_normal),
                ));
                return vec![Line::from(spans)];
            }

            // 引用块续行:保持引用块样式
            let trimmed = line_content.trim_start();
            if trimmed.starts_with('>') {
                let mut level = 0;
                let mut rest = trimmed;
                while rest.starts_with('>') {
                    level += 1;
                    rest = rest[1..].trim_start();
                }
                let _ = rest; // 续行不需要 rest

                let bar: String = (0..level).map(|_| "").collect::<Vec<_>>().join("");
                let bar_style = Style::default()
                    .fg(self.theme.md_blockquote_bar)
                    .bg(self.theme.md_blockquote_bg)
                    .add_modifier(Modifier::BOLD);
                let text_style = Style::default()
                    .fg(self.theme.md_blockquote_text)
                    .bg(self.theme.md_blockquote_bg);

                let mut spans = vec![Span::styled(line_num_str, line_num_style)];
                spans.push(Span::styled(format!("{} ", bar), bar_style));
                spans.push(Span::styled(text.clone(), text_style));
                return vec![Line::from(spans)];
            }

            // 普通续行
            let mut spans = vec![Span::styled(line_num_str, line_num_style)];
            if search.is_searching() && search.match_count() > 0 {
                spans.extend(search.highlight_line(logical_line, text, &self.theme, vl.start_col));
            } else {
                spans.push(Span::styled(
                    text.clone(),
                    self.style(self.theme.text_normal),
                ));
            }
            return vec![Line::from(spans)];
        }

        // 非续行的非光标行:完整 Markdown 渲染
        // 截断到折行宽度,防止终端二次折行导致重复渲染
        let truncated = Self::truncate_to_display_width(&line_content, wrap_width);

        // 检查是否是代码块围栏行
        if Self::is_code_fence_line(&line_content) {
            if self.is_fence_line_paired(logical_line, lines) {
                return vec![self.render_code_fence_line(&line_content, logical_line, lines)];
            }
            // 不成对的围栏,渲染为普通文本
            let mut spans = vec![Span::styled(line_num_str, line_num_style)];
            if search.is_searching() && search.match_count() > 0 {
                spans.extend(search.highlight_line(logical_line, &truncated, &self.theme, 0));
            } else {
                spans.push(Span::styled(truncated, self.style(self.theme.text_normal)));
            }
            return vec![Line::from(spans)];
        }

        // 检查是否在完整的代码块内
        if self.is_line_in_complete_code_block(logical_line, lines) {
            return vec![self.render_code_block_line(&line_content, logical_line, lines)];
        }

        // 检查是否在表格内
        if let Some(table_ctx) = self.find_table_context(logical_line, lines) {
            return self.render_table_rows(
                &line_content,
                logical_line,
                &table_ctx,
                lines,
                wrap_width,
            );
        }

        // 其他行:搜索高亮优先,否则 Markdown 渲染(标题、列表、引用等)
        if search.is_searching() && search.match_count() > 0 {
            let mut spans = vec![Span::styled(line_num_str, line_num_style)];
            spans.extend(search.highlight_line(logical_line, &truncated, &self.theme, 0));
            vec![Line::from(spans)]
        } else {
            vec![self.render_single_line_with_number(&truncated, logical_line, wrap_width)]
        }
    }

    /// 将 tab 替换为空格(宽度为 1,与 char_width('\t') = 1 一致)
    ///
    /// 终端会将 tab 展开到下一个 tab stop(通常占 8 列),
    /// 但 char_width 计算时 tab = 1,导致显示宽度与计算宽度不一致,
    /// 引起终端二次折行和字符重复。替换为空格后两者保持一致。
    fn normalize_tabs(text: &str) -> String {
        text.replace('\t', " ")
    }

    /// 将文本截断到指定显示宽度(使用 unicode-width 精确计算)
    fn truncate_to_display_width(text: &str, max_width: usize) -> String {
        let mut result = String::new();
        let mut width = 0;
        for ch in text.chars() {
            let ch_width = char_width(ch);
            if width + ch_width > max_width {
                break;
            }
            result.push(ch);
            width += ch_width;
        }
        result
    }

    /// 在已渲染的 spans 上叠加光标样式(按字符索引定位)
    pub(super) fn overlay_cursor_on_spans(
        spans: Vec<Span<'static>>,
        cursor_char_idx: usize,
        cursor_style: Style,
    ) -> Vec<Span<'static>> {
        let mut result = Vec::with_capacity(spans.len() + 2);
        let mut chars_seen = 0;
        let mut placed = false;

        for span in spans {
            if placed {
                result.push(span);
                continue;
            }
            let span_chars: Vec<char> = span.content.chars().collect();
            let span_len = span_chars.len();
            let span_end = chars_seen + span_len;

            if cursor_char_idx >= span_end {
                result.push(span);
                chars_seen = span_end;
                continue;
            }

            let local = cursor_char_idx - chars_seen;
            if local > 0 {
                let before: String = span_chars[..local].iter().collect();
                result.push(Span::styled(before, span.style));
            }
            if local < span_len {
                result.push(Span::styled(span_chars[local].to_string(), cursor_style));
                if local + 1 < span_len {
                    let after: String = span_chars[local + 1..].iter().collect();
                    result.push(Span::styled(after, span.style));
                }
            }
            placed = true;
            chars_seen = span_end;
        }

        // 光标在所有 span 之后(行尾),追加一个空格光标块
        if !placed {
            result.push(Span::styled(" ", cursor_style));
        }

        result
    }
}