Skip to main content

vtcode_tui/core_tui/session/
input.rs

1use super::{PLACEHOLDER_COLOR, Session, measure_text_width, ratatui_style_from_inline};
2use crate::config::constants::ui;
3use crate::ui::tui::types::InlineTextStyle;
4use crate::utils::file_utils::is_image_path;
5use anstyle::{Color as AnsiColorEnum, Effects};
6use ratatui::{
7    buffer::Buffer,
8    prelude::*,
9    widgets::{Block, Padding, Paragraph, Wrap},
10};
11use regex::Regex;
12use std::path::Path;
13use std::sync::LazyLock;
14use tui_shimmer::shimmer_spans_with_style_at_phase;
15use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
16
17use super::utils::line_truncation::truncate_line_with_ellipsis_if_overflow;
18
19struct InputRender {
20    text: Text<'static>,
21    cursor_x: u16,
22    cursor_y: u16,
23}
24
25#[derive(Default)]
26struct InputLineBuffer {
27    prefix: String,
28    text: String,
29    prefix_width: u16,
30    text_width: u16,
31    /// Character index in the original input where this buffer's text starts.
32    char_start: usize,
33}
34
35impl InputLineBuffer {
36    fn new(prefix: String, prefix_width: u16, char_start: usize) -> Self {
37        Self {
38            prefix,
39            text: String::new(),
40            prefix_width,
41            text_width: 0,
42            char_start,
43        }
44    }
45}
46
47/// Token type for syntax highlighting in the input field.
48#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49enum InputTokenKind {
50    Normal,
51    SlashCommand,
52    FileReference,
53    InlineCode,
54}
55
56/// A contiguous range of characters sharing the same token kind.
57struct InputToken {
58    kind: InputTokenKind,
59    /// Start char index (inclusive).
60    start: usize,
61    /// End char index (exclusive).
62    end: usize,
63}
64
65/// Tokenize input text into styled regions for syntax highlighting.
66fn tokenize_input(content: &str) -> Vec<InputToken> {
67    let chars: Vec<char> = content.chars().collect();
68    let len = chars.len();
69    if len == 0 {
70        return Vec::new();
71    }
72
73    // Assign a token kind to each character position.
74    let mut kinds = vec![InputTokenKind::Normal; len];
75
76    // 1. Slash commands: `/word` at the start or after whitespace.
77    //    Mark the leading `/` and subsequent non-whitespace chars.
78    {
79        let mut i = 0;
80        while i < len {
81            if chars[i] == '/'
82                && (i == 0 || chars[i - 1].is_whitespace())
83                && i + 1 < len
84                && chars[i + 1].is_alphanumeric()
85            {
86                let start = i;
87                i += 1;
88                while i < len && !chars[i].is_whitespace() {
89                    i += 1;
90                }
91                for kind in &mut kinds[start..i] {
92                    *kind = InputTokenKind::SlashCommand;
93                }
94                continue;
95            }
96            i += 1;
97        }
98    }
99
100    // 2. @file references: `@` at word boundary followed by non-whitespace.
101    {
102        let mut i = 0;
103        while i < len {
104            if chars[i] == '@'
105                && (i == 0 || chars[i - 1].is_whitespace())
106                && i + 1 < len
107                && !chars[i + 1].is_whitespace()
108            {
109                let start = i;
110                i += 1;
111                while i < len && !chars[i].is_whitespace() {
112                    i += 1;
113                }
114                for kind in &mut kinds[start..i] {
115                    *kind = InputTokenKind::FileReference;
116                }
117                continue;
118            }
119            i += 1;
120        }
121    }
122
123    // 3. Inline code: backtick-delimited spans (single or triple).
124    {
125        let mut i = 0;
126        while i < len {
127            if chars[i] == '`' {
128                let tick_start = i;
129                let mut tick_len = 0;
130                while i < len && chars[i] == '`' {
131                    tick_len += 1;
132                    i += 1;
133                }
134                // Find matching closing backticks.
135                let mut found = false;
136                let content_start = i;
137                while i <= len.saturating_sub(tick_len) {
138                    if chars[i] == '`' {
139                        let mut close_len = 0;
140                        while i < len && chars[i] == '`' {
141                            close_len += 1;
142                            i += 1;
143                        }
144                        if close_len == tick_len {
145                            for kind in &mut kinds[tick_start..i] {
146                                *kind = InputTokenKind::InlineCode;
147                            }
148                            found = true;
149                            break;
150                        }
151                    } else {
152                        i += 1;
153                    }
154                }
155                if !found {
156                    i = content_start;
157                }
158                continue;
159            }
160            i += 1;
161        }
162    }
163
164    // Coalesce adjacent chars with the same kind into tokens.
165    let mut tokens = Vec::new();
166    let mut cur_kind = kinds[0];
167    let mut cur_start = 0;
168    for (i, kind) in kinds.iter().enumerate().skip(1) {
169        if *kind != cur_kind {
170            tokens.push(InputToken {
171                kind: cur_kind,
172                start: cur_start,
173                end: i,
174            });
175            cur_kind = *kind;
176            cur_start = i;
177        }
178    }
179    tokens.push(InputToken {
180        kind: cur_kind,
181        start: cur_start,
182        end: len,
183    });
184    tokens
185}
186
187struct InputLayout {
188    buffers: Vec<InputLineBuffer>,
189    cursor_line_idx: usize,
190    cursor_column: u16,
191}
192
193const SHELL_MODE_BORDER_TITLE: &str = " ! Shell mode ";
194const SHELL_MODE_STATUS_HINT: &str = "Shell mode (!): direct command execution";
195
196impl Session {
197    pub(super) fn render_input(&mut self, frame: &mut Frame<'_>, area: Rect) {
198        if area.height == 0 {
199            self.set_input_area(None);
200            return;
201        }
202
203        let mut input_area = area;
204        let mut status_area = None;
205        if area.height > ui::INLINE_INPUT_STATUS_HEIGHT {
206            let block_height = area.height.saturating_sub(ui::INLINE_INPUT_STATUS_HEIGHT);
207            input_area.height = block_height.max(1);
208            status_area = Some(Rect::new(
209                area.x,
210                area.y + block_height,
211                area.width,
212                ui::INLINE_INPUT_STATUS_HEIGHT,
213            ));
214        }
215
216        let background_style = self.styles.input_background_style();
217        let shell_mode_title = self.shell_mode_border_title();
218        let mut block = if shell_mode_title.is_some() {
219            Block::bordered()
220        } else {
221            Block::new()
222        };
223        block = block
224            .style(background_style)
225            .padding(self.input_block_padding());
226        if let Some(title) = shell_mode_title {
227            block = block
228                .title(title)
229                .border_type(super::terminal_capabilities::get_border_type())
230                .border_style(self.styles.accent_style().add_modifier(Modifier::BOLD));
231        }
232        let inner = block.inner(input_area);
233        self.set_input_area(Some(inner));
234        let input_render = self.build_input_render(inner.width, inner.height);
235        let paragraph = Paragraph::new(input_render.text)
236            .style(background_style)
237            .wrap(Wrap { trim: false });
238        frame.render_widget(paragraph.block(block), input_area);
239        self.apply_input_selection_highlight(frame.buffer_mut(), inner);
240
241        if self.cursor_should_be_visible() && inner.width > 0 && inner.height > 0 {
242            let cursor_x = input_render
243                .cursor_x
244                .min(inner.width.saturating_sub(1))
245                .saturating_add(inner.x);
246            let cursor_y = input_render
247                .cursor_y
248                .min(inner.height.saturating_sub(1))
249                .saturating_add(inner.y);
250            if self.use_fake_cursor() {
251                render_fake_cursor(frame.buffer_mut(), cursor_x, cursor_y);
252            } else {
253                frame.set_cursor_position(Position::new(cursor_x, cursor_y));
254            }
255        }
256
257        if let Some(status_area) = status_area {
258            let status_line = self
259                .render_input_status_line(status_area.width)
260                .unwrap_or_default();
261            let status = Paragraph::new(status_line)
262                .style(self.styles.default_style())
263                .wrap(Wrap { trim: false });
264            frame.render_widget(status, status_area);
265        }
266    }
267
268    pub(crate) fn desired_input_lines(&self, inner_width: u16) -> u16 {
269        if inner_width == 0 {
270            return 1;
271        }
272
273        if self.input_compact_mode
274            && self.input_manager.cursor() == self.input_manager.content().len()
275            && self.input_compact_placeholder().is_some()
276        {
277            return 1;
278        }
279
280        if self.input_manager.content().is_empty() {
281            return 1;
282        }
283
284        let prompt_width = UnicodeWidthStr::width(self.prompt_prefix.as_str()) as u16;
285        let prompt_display_width = prompt_width.min(inner_width);
286        let layout = self.input_layout(inner_width, prompt_display_width);
287        let line_count = layout.buffers.len().max(1);
288        let capped = line_count.min(ui::INLINE_INPUT_MAX_LINES.max(1));
289        capped as u16
290    }
291
292    pub(crate) fn apply_input_height(&mut self, height: u16) {
293        let resolved = height.max(Self::input_block_height_for_lines(1));
294        if self.input_height != resolved {
295            self.input_height = resolved;
296            crate::ui::tui::session::render::recalculate_transcript_rows(self);
297        }
298    }
299
300    pub(crate) fn input_block_height_for_lines(lines: u16) -> u16 {
301        lines
302            .max(1)
303            .saturating_add(ui::INLINE_INPUT_PADDING_VERTICAL.saturating_mul(2))
304    }
305
306    fn input_layout(&self, width: u16, prompt_display_width: u16) -> InputLayout {
307        let indent_prefix = " ".repeat(prompt_display_width as usize);
308        let mut buffers = vec![InputLineBuffer::new(
309            self.prompt_prefix.clone(),
310            prompt_display_width,
311            0,
312        )];
313        let secure_prompt_active = self.secure_prompt_active();
314        let mut cursor_line_idx = 0usize;
315        let mut cursor_column = prompt_display_width;
316        let input_content = self.input_manager.content();
317        let cursor_pos = self.input_manager.cursor();
318        let mut cursor_set = cursor_pos == 0;
319        let mut char_idx: usize = 0;
320
321        for (idx, ch) in input_content.char_indices() {
322            if !cursor_set
323                && cursor_pos == idx
324                && let Some(current) = buffers.last()
325            {
326                cursor_line_idx = buffers.len() - 1;
327                cursor_column = current.prefix_width + current.text_width;
328                cursor_set = true;
329            }
330
331            if ch == '\n' {
332                let end = idx + ch.len_utf8();
333                char_idx += 1;
334                buffers.push(InputLineBuffer::new(
335                    indent_prefix.clone(),
336                    prompt_display_width,
337                    char_idx,
338                ));
339                if !cursor_set && cursor_pos == end {
340                    cursor_line_idx = buffers.len() - 1;
341                    cursor_column = prompt_display_width;
342                    cursor_set = true;
343                }
344                continue;
345            }
346
347            let display_ch = if secure_prompt_active { '•' } else { ch };
348            let char_width = UnicodeWidthChar::width(display_ch).unwrap_or(0) as u16;
349
350            if let Some(current) = buffers.last_mut() {
351                let capacity = width.saturating_sub(current.prefix_width);
352                if capacity > 0
353                    && current.text_width + char_width > capacity
354                    && !current.text.is_empty()
355                {
356                    buffers.push(InputLineBuffer::new(
357                        indent_prefix.clone(),
358                        prompt_display_width,
359                        char_idx,
360                    ));
361                }
362            }
363
364            if let Some(current) = buffers.last_mut() {
365                current.text.push(display_ch);
366                current.text_width = current.text_width.saturating_add(char_width);
367            }
368
369            char_idx += 1;
370
371            let end = idx + ch.len_utf8();
372            if !cursor_set
373                && cursor_pos == end
374                && let Some(current) = buffers.last()
375            {
376                cursor_line_idx = buffers.len() - 1;
377                cursor_column = current.prefix_width + current.text_width;
378                cursor_set = true;
379            }
380        }
381
382        if !cursor_set && let Some(current) = buffers.last() {
383            cursor_line_idx = buffers.len() - 1;
384            cursor_column = current.prefix_width + current.text_width;
385        }
386
387        InputLayout {
388            buffers,
389            cursor_line_idx,
390            cursor_column,
391        }
392    }
393
394    fn visible_input_window(&self, width: u16, height: u16) -> (InputLayout, usize, usize) {
395        let prompt_width = UnicodeWidthStr::width(self.prompt_prefix.as_str()) as u16;
396        let prompt_display_width = prompt_width.min(width);
397        let layout = self.input_layout(width, prompt_display_width);
398        let total_lines = layout.buffers.len();
399        let visible_limit = height.max(1).min(ui::INLINE_INPUT_MAX_LINES as u16) as usize;
400        let mut start = total_lines.saturating_sub(visible_limit);
401        if layout.cursor_line_idx < start {
402            start = layout.cursor_line_idx.saturating_sub(visible_limit - 1);
403        }
404        let end = (start + visible_limit).min(total_lines);
405        (layout, start, end)
406    }
407
408    fn build_input_render(&self, width: u16, height: u16) -> InputRender {
409        if width == 0 || height == 0 {
410            return InputRender {
411                text: Text::default(),
412                cursor_x: 0,
413                cursor_y: 0,
414            };
415        }
416
417        let max_visible_lines = height.max(1).min(ui::INLINE_INPUT_MAX_LINES as u16) as usize;
418
419        let mut prompt_style = self.prompt_style.clone();
420        if prompt_style.color.is_none() {
421            prompt_style.color = self.theme.primary.or(self.theme.foreground);
422        }
423        if self.suggested_prompt_state.active {
424            prompt_style.color = self
425                .theme
426                .tool_accent
427                .or(self.theme.secondary)
428                .or(self.theme.primary)
429                .or(self.theme.foreground);
430            prompt_style.effects |= Effects::BOLD;
431        }
432        let prompt_style = ratatui_style_from_inline(&prompt_style, self.theme.foreground);
433        let prompt_width = UnicodeWidthStr::width(self.prompt_prefix.as_str()) as u16;
434        let prompt_display_width = prompt_width.min(width);
435
436        let cursor_at_end = self.input_manager.cursor() == self.input_manager.content().len();
437        if self.input_compact_mode
438            && cursor_at_end
439            && let Some(placeholder) = self.input_compact_placeholder()
440        {
441            let placeholder_style = InlineTextStyle {
442                color: Some(AnsiColorEnum::Rgb(PLACEHOLDER_COLOR)),
443                bg_color: None,
444                effects: Effects::DIMMED,
445            };
446            let style = ratatui_style_from_inline(
447                &placeholder_style,
448                Some(AnsiColorEnum::Rgb(PLACEHOLDER_COLOR)),
449            );
450            let placeholder_width = UnicodeWidthStr::width(placeholder.as_str()) as u16;
451            return InputRender {
452                text: Text::from(vec![Line::from(vec![
453                    Span::styled(self.prompt_prefix.clone(), prompt_style),
454                    Span::styled(placeholder, style),
455                ])]),
456                cursor_x: prompt_display_width.saturating_add(placeholder_width),
457                cursor_y: 0,
458            };
459        }
460
461        if self.input_manager.content().is_empty() {
462            let mut spans = Vec::new();
463            spans.push(Span::styled(self.prompt_prefix.clone(), prompt_style));
464
465            if let Some(placeholder) = &self.placeholder {
466                let placeholder_style = self.placeholder_style.clone().unwrap_or(InlineTextStyle {
467                    color: Some(AnsiColorEnum::Rgb(PLACEHOLDER_COLOR)),
468                    bg_color: None,
469                    effects: Effects::ITALIC,
470                });
471                let style = ratatui_style_from_inline(
472                    &placeholder_style,
473                    Some(AnsiColorEnum::Rgb(PLACEHOLDER_COLOR)),
474                );
475                spans.push(Span::styled(placeholder.clone(), style));
476            }
477
478            return InputRender {
479                text: Text::from(vec![Line::from(spans)]),
480                cursor_x: prompt_display_width,
481                cursor_y: 0,
482            };
483        }
484
485        let accent_style =
486            ratatui_style_from_inline(&self.styles.accent_inline_style(), self.theme.foreground);
487        let slash_style = accent_style.fg(Color::Yellow).add_modifier(Modifier::BOLD);
488        let file_ref_style = accent_style
489            .fg(Color::Cyan)
490            .add_modifier(Modifier::UNDERLINED);
491        let code_style = accent_style.fg(Color::Green).add_modifier(Modifier::BOLD);
492
493        let (layout, start, end) = self.visible_input_window(width, max_visible_lines as u16);
494        let tokens = tokenize_input(self.input_manager.content());
495        let cursor_y = layout.cursor_line_idx.saturating_sub(start) as u16;
496
497        let mut lines = Vec::new();
498        for buffer in &layout.buffers[start..end] {
499            let mut spans = Vec::new();
500            spans.push(Span::styled(buffer.prefix.clone(), prompt_style));
501            if !buffer.text.is_empty() {
502                let buf_chars: Vec<char> = buffer.text.chars().collect();
503                let buf_len = buf_chars.len();
504                let buf_start = buffer.char_start;
505                let buf_end = buf_start + buf_len;
506
507                let mut pos = 0usize;
508                for token in &tokens {
509                    if token.end <= buf_start || token.start >= buf_end {
510                        continue;
511                    }
512                    let seg_start = token.start.max(buf_start).saturating_sub(buf_start);
513                    let seg_end = token.end.min(buf_end).saturating_sub(buf_start);
514                    if seg_start > pos {
515                        let text: String = buf_chars[pos..seg_start].iter().collect();
516                        spans.push(Span::styled(text, accent_style));
517                    }
518                    let text: String = buf_chars[seg_start..seg_end].iter().collect();
519                    let style = match token.kind {
520                        InputTokenKind::SlashCommand => slash_style,
521                        InputTokenKind::FileReference => file_ref_style,
522                        InputTokenKind::InlineCode => code_style,
523                        InputTokenKind::Normal => accent_style,
524                    };
525                    spans.push(Span::styled(text, style));
526                    pos = seg_end;
527                }
528                if pos < buf_len {
529                    let text: String = buf_chars[pos..].iter().collect();
530                    spans.push(Span::styled(text, accent_style));
531                }
532            }
533            lines.push(Line::from(spans));
534        }
535
536        if lines.is_empty() {
537            lines.push(Line::from(vec![Span::styled(
538                self.prompt_prefix.clone(),
539                prompt_style,
540            )]));
541        }
542
543        InputRender {
544            text: Text::from(lines),
545            cursor_x: layout.cursor_column,
546            cursor_y,
547        }
548    }
549
550    fn apply_input_selection_highlight(&self, buf: &mut Buffer, area: Rect) {
551        let Some((selection_start, selection_end)) = self.input_manager.selection_range() else {
552            return;
553        };
554        if area.width == 0 || area.height == 0 || selection_start == selection_end {
555            return;
556        }
557
558        let (layout, start, end) = self.visible_input_window(area.width, area.height);
559        let selection_start_char =
560            byte_index_to_char_index(self.input_manager.content(), selection_start);
561        let selection_end_char =
562            byte_index_to_char_index(self.input_manager.content(), selection_end);
563
564        for (row_offset, buffer) in layout.buffers[start..end].iter().enumerate() {
565            let line_char_start = buffer.char_start;
566            let line_char_end = buffer.char_start + buffer.text.chars().count();
567            let highlight_start = selection_start_char.max(line_char_start);
568            let highlight_end = selection_end_char.min(line_char_end);
569            if highlight_start >= highlight_end {
570                continue;
571            }
572
573            let local_start = highlight_start.saturating_sub(line_char_start);
574            let local_end = highlight_end.saturating_sub(line_char_start);
575            let start_x = area
576                .x
577                .saturating_add(buffer.prefix_width)
578                .saturating_add(display_width_for_char_range(&buffer.text, local_start));
579            let end_x = area
580                .x
581                .saturating_add(buffer.prefix_width)
582                .saturating_add(display_width_for_char_range(&buffer.text, local_end));
583            let y = area.y.saturating_add(row_offset as u16);
584
585            for x in start_x..end_x.min(area.x.saturating_add(area.width)) {
586                if let Some(cell) = buf.cell_mut((x, y)) {
587                    let mut style = cell.style();
588                    style = style.add_modifier(Modifier::REVERSED);
589                    cell.set_style(style);
590                    if cell.symbol().is_empty() {
591                        cell.set_symbol(" ");
592                    }
593                }
594            }
595        }
596    }
597
598    pub(crate) fn cursor_index_for_input_point(&self, column: u16, row: u16) -> Option<usize> {
599        let area = self.input_area?;
600        if row < area.y
601            || row >= area.y.saturating_add(area.height)
602            || column < area.x
603            || column >= area.x.saturating_add(area.width)
604        {
605            return None;
606        }
607
608        if self.input_compact_mode
609            && self.input_manager.cursor() == self.input_manager.content().len()
610            && self.input_compact_placeholder().is_some()
611        {
612            return Some(self.input_manager.content().len());
613        }
614
615        let relative_row = row.saturating_sub(area.y);
616        let relative_column = column.saturating_sub(area.x);
617        let (layout, start, end) = self.visible_input_window(area.width, area.height);
618        if start >= end {
619            return Some(0);
620        }
621
622        let line_index = (start + usize::from(relative_row)).min(end.saturating_sub(1));
623        let buffer = layout.buffers.get(line_index)?;
624        if relative_column <= buffer.prefix_width {
625            return Some(char_index_to_byte_index(
626                self.input_manager.content(),
627                buffer.char_start,
628            ));
629        }
630
631        let target_width = relative_column.saturating_sub(buffer.prefix_width);
632        let mut consumed_width = 0u16;
633        let mut char_offset = 0usize;
634        for ch in buffer.text.chars() {
635            let ch_width = UnicodeWidthChar::width(ch).unwrap_or(0) as u16;
636            let next_width = consumed_width.saturating_add(ch_width);
637            if target_width < next_width {
638                break;
639            }
640            consumed_width = next_width;
641            char_offset += 1;
642        }
643
644        let char_index = buffer.char_start.saturating_add(char_offset);
645        Some(char_index_to_byte_index(
646            self.input_manager.content(),
647            char_index,
648        ))
649    }
650
651    pub(super) fn input_compact_placeholder(&self) -> Option<String> {
652        let content = self.input_manager.content();
653        let trimmed = content.trim();
654        let attachment_count = self.input_manager.attachments().len();
655        if trimmed.is_empty() && attachment_count == 0 {
656            return None;
657        }
658
659        if let Some(label) = compact_image_label(trimmed) {
660            return Some(format!("[Image: {label}]"));
661        }
662
663        if attachment_count > 0 {
664            let label = if attachment_count == 1 {
665                "1 attachment".to_string()
666            } else {
667                format!("{attachment_count} attachments")
668            };
669            if trimmed.is_empty() {
670                return Some(format!("[Image: {label}]"));
671            }
672            if let Some(compact) = compact_image_placeholders(content) {
673                return Some(format!("[Image: {label}] {compact}"));
674            }
675            return Some(format!("[Image: {label}] {trimmed}"));
676        }
677
678        let line_count = content.split('\n').count();
679        if line_count >= ui::INLINE_PASTE_COLLAPSE_LINE_THRESHOLD {
680            let char_count = content.chars().count();
681            return Some(format!("[Pasted Content {char_count} chars]"));
682        }
683
684        if let Some(compact) = compact_image_placeholders(content) {
685            return Some(compact);
686        }
687
688        None
689    }
690
691    fn render_input_status_line(&self, width: u16) -> Option<Line<'static>> {
692        if width == 0 {
693            return None;
694        }
695
696        let mut left = self
697            .input_status_left
698            .as_ref()
699            .map(|value| value.trim().to_owned())
700            .filter(|value| !value.is_empty());
701        let right = self
702            .input_status_right
703            .as_ref()
704            .map(|value| value.trim().to_owned())
705            .filter(|value| !value.is_empty());
706
707        if let Some(shell_hint) = self.shell_mode_status_hint() {
708            left = Some(match left {
709                Some(existing) => format!("{existing} · {shell_hint}"),
710                None => shell_hint.to_string(),
711            });
712        }
713
714        let right = match (right, self.vim_state.status_label()) {
715            (Some(existing), Some(vim_label)) => Some(format!("{vim_label} · {existing}")),
716            (None, Some(vim_label)) => Some(vim_label.to_string()),
717            (existing, None) => existing,
718        };
719
720        // Build scroll indicator if enabled
721        let scroll_indicator = if ui::SCROLL_INDICATOR_ENABLED {
722            Some(self.build_scroll_indicator())
723        } else {
724            None
725        };
726
727        if left.is_none() && right.is_none() && scroll_indicator.is_none() {
728            return None;
729        }
730
731        let dim_style = self.styles.default_style().add_modifier(Modifier::DIM);
732        let mut spans = Vec::new();
733
734        // Add left content (git status or shimmered activity)
735        if let Some(left_value) = left.as_ref() {
736            if status_requires_shimmer(left_value)
737                && self.appearance.should_animate_progress_status()
738            {
739                spans.extend(shimmer_spans_with_style_at_phase(
740                    left_value,
741                    dim_style,
742                    self.shimmer_state.phase(),
743                ));
744            } else {
745                spans.extend(self.create_git_status_spans(left_value, dim_style));
746            }
747        }
748
749        // Build right side spans (scroll indicator + optional right content)
750        let mut right_spans: Vec<Span<'static>> = Vec::new();
751        if let Some(scroll) = &scroll_indicator {
752            right_spans.push(Span::styled(scroll.clone(), dim_style));
753        }
754        if let Some(right_value) = &right {
755            if !right_spans.is_empty() {
756                right_spans.push(Span::raw(" "));
757            }
758            right_spans.push(Span::styled(right_value.clone(), dim_style));
759        }
760
761        if !right_spans.is_empty() {
762            let left_width: u16 = spans.iter().map(|s| measure_text_width(&s.content)).sum();
763            let right_width: u16 = right_spans
764                .iter()
765                .map(|s| measure_text_width(&s.content))
766                .sum();
767            let padding = width.saturating_sub(left_width + right_width);
768
769            if padding > 0 {
770                spans.push(Span::raw(" ".repeat(padding as usize)));
771            } else if !spans.is_empty() {
772                spans.push(Span::raw(" "));
773            }
774            spans.extend(right_spans);
775        }
776
777        if spans.is_empty() {
778            return None;
779        }
780
781        let mut line = Line::from(spans);
782        // Apply ellipsis truncation to prevent status line from overflowing
783        line = truncate_line_with_ellipsis_if_overflow(line, usize::from(width));
784        Some(line)
785    }
786
787    pub(crate) fn input_uses_shell_prefix(&self) -> bool {
788        self.input_manager.content().trim_start().starts_with('!')
789    }
790
791    pub(crate) fn input_block_padding(&self) -> Padding {
792        if self.input_uses_shell_prefix() {
793            Padding::new(0, 0, 0, 0)
794        } else {
795            Padding::new(
796                ui::INLINE_INPUT_PADDING_HORIZONTAL,
797                ui::INLINE_INPUT_PADDING_HORIZONTAL,
798                ui::INLINE_INPUT_PADDING_VERTICAL,
799                ui::INLINE_INPUT_PADDING_VERTICAL,
800            )
801        }
802    }
803
804    pub(crate) fn shell_mode_border_title(&self) -> Option<&'static str> {
805        self.input_uses_shell_prefix()
806            .then_some(SHELL_MODE_BORDER_TITLE)
807    }
808
809    fn shell_mode_status_hint(&self) -> Option<&'static str> {
810        self.input_uses_shell_prefix()
811            .then_some(SHELL_MODE_STATUS_HINT)
812    }
813
814    /// Build scroll indicator string with percentage
815    fn build_scroll_indicator(&self) -> String {
816        let percent = self.scroll_manager.progress_percent();
817        format!("{} {:>3}%", ui::SCROLL_INDICATOR_FORMAT, percent)
818    }
819
820    #[allow(dead_code)]
821    fn create_git_status_spans(&self, text: &str, default_style: Style) -> Vec<Span<'static>> {
822        if let Some((branch_part, indicator_part)) = text.rsplit_once(" | ") {
823            let mut spans = Vec::new();
824            let branch_trim = branch_part.trim_end();
825            if !branch_trim.is_empty() {
826                spans.push(Span::styled(branch_trim.to_owned(), default_style));
827            }
828            spans.push(Span::raw(" "));
829
830            let indicator_trim = indicator_part.trim();
831            let indicator_style = if indicator_trim == ui::HEADER_GIT_DIRTY_SUFFIX {
832                Style::default().fg(Color::Red).add_modifier(Modifier::BOLD)
833            } else if indicator_trim == ui::HEADER_GIT_CLEAN_SUFFIX {
834                Style::default()
835                    .fg(Color::Green)
836                    .add_modifier(Modifier::BOLD)
837            } else {
838                self.styles.accent_style().add_modifier(Modifier::BOLD)
839            };
840
841            spans.push(Span::styled(indicator_trim.to_owned(), indicator_style));
842            spans
843        } else {
844            vec![Span::styled(text.to_owned(), default_style)]
845        }
846    }
847
848    fn cursor_should_be_visible(&self) -> bool {
849        let loading_state = self.is_running_activity() || self.has_status_spinner();
850        self.cursor_visible && (self.input_enabled || loading_state)
851    }
852
853    fn use_fake_cursor(&self) -> bool {
854        self.has_status_spinner()
855    }
856
857    fn secure_prompt_active(&self) -> bool {
858        self.modal_state()
859            .and_then(|modal| modal.secure_prompt.as_ref())
860            .is_some()
861    }
862
863    /// Build input render data for external widgets
864    pub fn build_input_widget_data(&self, width: u16, height: u16) -> InputWidgetData {
865        let input_render = self.build_input_render(width, height);
866        let background_style = self.styles.input_background_style();
867
868        InputWidgetData {
869            text: input_render.text,
870            cursor_x: input_render.cursor_x,
871            cursor_y: input_render.cursor_y,
872            cursor_should_be_visible: self.cursor_should_be_visible(),
873            use_fake_cursor: self.use_fake_cursor(),
874            background_style,
875            default_style: self.styles.default_style(),
876        }
877    }
878
879    /// Build input status line for external widgets
880    pub fn build_input_status_widget_data(&self, width: u16) -> Option<Vec<Span<'static>>> {
881        self.render_input_status_line(width).map(|line| line.spans)
882    }
883}
884
885fn compact_image_label(content: &str) -> Option<String> {
886    let trimmed = content.trim();
887    if trimmed.is_empty() {
888        return None;
889    }
890
891    let unquoted = trimmed
892        .strip_prefix('"')
893        .and_then(|value| value.strip_suffix('"'))
894        .or_else(|| {
895            trimmed
896                .strip_prefix('\'')
897                .and_then(|value| value.strip_suffix('\''))
898        })
899        .unwrap_or(trimmed);
900
901    if unquoted.starts_with("data:image/") {
902        return Some("inline image".to_string());
903    }
904
905    let windows_drive = unquoted.as_bytes().get(1).is_some_and(|ch| *ch == b':')
906        && unquoted
907            .as_bytes()
908            .get(2)
909            .is_some_and(|ch| *ch == b'\\' || *ch == b'/');
910    let starts_like_path = unquoted.starts_with('@')
911        || unquoted.starts_with("file://")
912        || unquoted.starts_with('/')
913        || unquoted.starts_with("./")
914        || unquoted.starts_with("../")
915        || unquoted.starts_with("~/")
916        || windows_drive;
917    if !starts_like_path {
918        return None;
919    }
920
921    let without_at = unquoted.strip_prefix('@').unwrap_or(unquoted);
922
923    // Skip npm scoped package patterns like @scope/package@version
924    if without_at.contains('/')
925        && !without_at.starts_with('.')
926        && !without_at.starts_with('/')
927        && !without_at.starts_with("~/")
928    {
929        // Check if this looks like @scope/package (npm package)
930        let parts: Vec<&str> = without_at.split('/').collect();
931        if parts.len() >= 2 && !parts[0].is_empty() {
932            // Reject if it looks like a package name (no extension on second component)
933            if !parts[parts.len() - 1].contains('.') {
934                return None;
935            }
936        }
937    }
938
939    let without_scheme = without_at.strip_prefix("file://").unwrap_or(without_at);
940    let path = Path::new(without_scheme);
941    if !is_image_path(path) {
942        return None;
943    }
944
945    let label = path
946        .file_name()
947        .and_then(|name| name.to_str())
948        .unwrap_or(without_scheme);
949    Some(label.to_string())
950}
951
952static IMAGE_PATH_INLINE_REGEX: LazyLock<Regex> = LazyLock::new(|| {
953    match Regex::new(
954        r#"(?ix)
955        (?:^|[\s\(\[\{<\"'`])
956        (
957            @?
958            (?:file://)?
959            (?:
960                ~/(?:[^\n/]+/)+
961              | /(?:[^\n/]+/)+
962              | [A-Za-z]:[\\/](?:[^\n\\\/]+[\\/])+
963            )
964            [^\n]*?
965            \.(?:png|jpe?g|gif|bmp|webp|tiff?|svg)
966        )"#,
967    ) {
968        Ok(regex) => regex,
969        Err(error) => panic!("Failed to compile inline image path regex: {error}"),
970    }
971});
972
973fn compact_image_placeholders(content: &str) -> Option<String> {
974    let mut matches = Vec::new();
975    for capture in IMAGE_PATH_INLINE_REGEX.captures_iter(content) {
976        let Some(path_match) = capture.get(1) else {
977            continue;
978        };
979        let raw = path_match.as_str();
980        let Some(label) = image_label_for_path(raw) else {
981            continue;
982        };
983        matches.push((path_match.start(), path_match.end(), label));
984    }
985
986    if matches.is_empty() {
987        return None;
988    }
989
990    let mut result = String::with_capacity(content.len());
991    let mut last_end = 0usize;
992    for (start, end, label) in matches {
993        if start < last_end {
994            continue;
995        }
996        result.push_str(&content[last_end..start]);
997        result.push_str(&format!("[Image: {label}]"));
998        last_end = end;
999    }
1000    if last_end < content.len() {
1001        result.push_str(&content[last_end..]);
1002    }
1003
1004    Some(result)
1005}
1006
1007fn image_label_for_path(raw: &str) -> Option<String> {
1008    let trimmed = raw.trim_matches(|ch: char| matches!(ch, '"' | '\'')).trim();
1009    if trimmed.is_empty() {
1010        return None;
1011    }
1012
1013    let without_at = trimmed.strip_prefix('@').unwrap_or(trimmed);
1014    let without_scheme = without_at.strip_prefix("file://").unwrap_or(without_at);
1015    let unescaped = unescape_whitespace(without_scheme);
1016    let path = Path::new(unescaped.as_str());
1017    if !is_image_path(path) {
1018        return None;
1019    }
1020
1021    let label = path
1022        .file_name()
1023        .and_then(|name| name.to_str())
1024        .unwrap_or(unescaped.as_str());
1025    Some(label.to_string())
1026}
1027
1028fn unescape_whitespace(token: &str) -> String {
1029    let mut result = String::with_capacity(token.len());
1030    let mut chars = token.chars().peekable();
1031    while let Some(ch) = chars.next() {
1032        if ch == '\\'
1033            && let Some(next) = chars.peek()
1034            && next.is_ascii_whitespace()
1035        {
1036            result.push(*next);
1037            chars.next();
1038            continue;
1039        }
1040        result.push(ch);
1041    }
1042    result
1043}
1044
1045fn is_spinner_frame(indicator: &str) -> bool {
1046    matches!(
1047        indicator,
1048        "⠋" | "⠙"
1049            | "⠹"
1050            | "⠸"
1051            | "⠼"
1052            | "⠴"
1053            | "⠦"
1054            | "⠧"
1055            | "⠇"
1056            | "⠏"
1057            | "-"
1058            | "\\"
1059            | "|"
1060            | "/"
1061            | "."
1062    )
1063}
1064
1065pub(crate) fn status_requires_shimmer(text: &str) -> bool {
1066    if text.contains("Running command:")
1067        || text.contains("Running tool:")
1068        || text.contains("Running:")
1069        || text.contains("Running ")
1070        || text.contains("Executing ")
1071        || text.contains("Ctrl+C")
1072        || text.contains("/stop to stop")
1073    {
1074        return true;
1075    }
1076    let Some((indicator, rest)) = text.split_once(' ') else {
1077        return false;
1078    };
1079    if indicator.chars().count() != 1 || rest.trim().is_empty() {
1080        return false;
1081    }
1082    is_spinner_frame(indicator)
1083}
1084
1085/// Data structure for input widget rendering
1086#[derive(Clone, Debug)]
1087pub struct InputWidgetData {
1088    pub text: Text<'static>,
1089    pub cursor_x: u16,
1090    pub cursor_y: u16,
1091    pub cursor_should_be_visible: bool,
1092    pub use_fake_cursor: bool,
1093    pub background_style: Style,
1094    pub default_style: Style,
1095}
1096
1097fn render_fake_cursor(buf: &mut Buffer, cursor_x: u16, cursor_y: u16) {
1098    if let Some(cell) = buf.cell_mut((cursor_x, cursor_y)) {
1099        let mut style = cell.style();
1100        style = style.add_modifier(Modifier::REVERSED);
1101        cell.set_style(style);
1102        if cell.symbol().is_empty() {
1103            cell.set_symbol(" ");
1104        }
1105    }
1106}
1107
1108fn char_index_to_byte_index(content: &str, char_index: usize) -> usize {
1109    if char_index == 0 {
1110        return 0;
1111    }
1112
1113    content
1114        .char_indices()
1115        .nth(char_index)
1116        .map(|(byte_index, _)| byte_index)
1117        .unwrap_or(content.len())
1118}
1119
1120fn byte_index_to_char_index(content: &str, byte_index: usize) -> usize {
1121    content[..byte_index.min(content.len())].chars().count()
1122}
1123
1124fn display_width_for_char_range(content: &str, char_count: usize) -> u16 {
1125    content
1126        .chars()
1127        .take(char_count)
1128        .map(|ch| UnicodeWidthChar::width(ch).unwrap_or(0) as u16)
1129        .fold(0_u16, u16::saturating_add)
1130}
1131
1132#[cfg(test)]
1133mod input_highlight_tests {
1134    use super::*;
1135
1136    fn kinds(input: &str) -> Vec<(InputTokenKind, String)> {
1137        tokenize_input(input)
1138            .into_iter()
1139            .map(|t| {
1140                let text: String = input.chars().skip(t.start).take(t.end - t.start).collect();
1141                (t.kind, text)
1142            })
1143            .collect()
1144    }
1145
1146    #[test]
1147    fn slash_command_at_start() {
1148        let tokens = kinds("/use skill-name");
1149        assert_eq!(tokens[0].0, InputTokenKind::SlashCommand);
1150        assert_eq!(tokens[0].1, "/use");
1151        assert_eq!(tokens[1].0, InputTokenKind::Normal);
1152    }
1153
1154    #[test]
1155    fn slash_command_with_following_text() {
1156        let tokens = kinds("/doctor hello");
1157        assert_eq!(tokens[0].0, InputTokenKind::SlashCommand);
1158        assert_eq!(tokens[0].1, "/doctor");
1159        assert_eq!(tokens[1].0, InputTokenKind::Normal);
1160    }
1161
1162    #[test]
1163    fn at_file_reference() {
1164        let tokens = kinds("check @src/main.rs please");
1165        assert_eq!(tokens[0].0, InputTokenKind::Normal);
1166        assert_eq!(tokens[1].0, InputTokenKind::FileReference);
1167        assert_eq!(tokens[1].1, "@src/main.rs");
1168        assert_eq!(tokens[2].0, InputTokenKind::Normal);
1169    }
1170
1171    #[test]
1172    fn inline_backtick_code() {
1173        let tokens = kinds("run `cargo test` now");
1174        assert_eq!(tokens[0].0, InputTokenKind::Normal);
1175        assert_eq!(tokens[1].0, InputTokenKind::InlineCode);
1176        assert_eq!(tokens[1].1, "`cargo test`");
1177        assert_eq!(tokens[2].0, InputTokenKind::Normal);
1178    }
1179
1180    #[test]
1181    fn no_false_slash_mid_word() {
1182        let tokens = kinds("path/to/file");
1183        assert_eq!(tokens.len(), 1);
1184        assert_eq!(tokens[0].0, InputTokenKind::Normal);
1185    }
1186
1187    #[test]
1188    fn empty_input() {
1189        assert!(tokenize_input("").is_empty());
1190    }
1191
1192    #[test]
1193    fn mixed_tokens() {
1194        let tokens = kinds("/use @file.rs `code`");
1195        assert_eq!(tokens[0].0, InputTokenKind::SlashCommand);
1196        assert_eq!(tokens[2].0, InputTokenKind::FileReference);
1197        assert_eq!(tokens[4].0, InputTokenKind::InlineCode);
1198    }
1199}