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
use ratatui::{buffer::Buffer, layout::Rect, style::Modifier};
use super::state::InteractiveState;
use crate::styled_string::Span;
impl<'a> InteractiveState<'a> {
/// Render a span with optional action tracking
pub(super) fn render_span(&mut self, span: &Span<'a>, buf: &mut Buffer) {
self.render_span_with_modifier(span, Modifier::empty(), buf);
}
/// Render a span with additional style modifier
pub(super) fn render_span_with_modifier(
&mut self,
span: &Span<'a>,
modifier: Modifier,
buf: &mut Buffer,
) {
let mut style = self.style(span.style);
style = style.add_modifier(modifier);
// Underline clickable spans to make them discoverable
if span.action.is_some() {
style = style.add_modifier(Modifier::UNDERLINED);
}
let start_col = self.layout.pos.x;
let start_row = self.layout.pos.y;
// Determine if this span should be highlighted (by mouse or keyboard)
let should_highlight = if span.action.is_some() {
// Check mouse hover
let mouse_hover = self.viewport.cursor_pos.map_or_else(
|| false,
|cursor| {
cursor.y == self.layout.pos.y
&& cursor.x >= self.layout.pos.x
&& cursor.x < self.layout.pos.x + display_width(&span.text) as u16
},
);
// Check keyboard focus - this action is about to be pushed, so its index will be actions.len()
let keyboard_focus = match self.viewport.keyboard_cursor {
super::state::KeyboardCursor::Focused { action_index } => {
action_index == self.render_cache.actions.len()
}
_ => false,
};
mouse_hover || keyboard_focus
} else {
false
};
// If hovered or focused, invert colors
if should_highlight {
style = style.add_modifier(Modifier::REVERSED);
}
// Handle newlines in span text
for (line_idx, line) in span.text.split('\n').enumerate() {
if line_idx > 0 {
self.layout.pos.y += 1;
self.layout.pos.x = self.layout.indent;
// Draw blockquote markers on new line
self.draw_blockquote_markers(buf);
}
// Word wrap if line is too long
let mut remaining = line;
while !remaining.is_empty() {
// Calculate available width: columns from current to edge (exclusive)
// area.width is the total width, so valid columns are 0 to area.width-1
let available_width = self.layout.area.width.saturating_sub(self.layout.pos.x);
if available_width == 0 {
// No space left on this line, wrap to next
self.layout.pos.y += 1;
self.layout.pos.x = self.layout.indent;
// Draw blockquote markers on new line
self.draw_blockquote_markers(buf);
continue;
}
if display_width(remaining) <= available_width as usize {
// Fits on current line
self.write_text(
buf,
self.layout.pos.y,
self.layout.pos.x,
remaining,
self.layout.area,
style,
);
self.layout.pos.x += display_width(remaining) as u16;
break;
} else {
// Need to wrap - find best break point
let truncate_at = available_width as usize;
// First try to find a good break point (whitespace or after punctuation)
let wrap_pos = find_wrap_position(remaining, truncate_at);
if let Some(wrap_at) = wrap_pos {
let (chunk, rest) = remaining.split_at(wrap_at);
self.write_text(
buf,
self.layout.pos.y,
self.layout.pos.x,
chunk,
self.layout.area,
style,
);
self.layout.pos.y += 1;
self.layout.pos.x = self.layout.indent;
// Draw blockquote markers on new line
self.draw_blockquote_markers(buf);
remaining = rest.trim_start(); // Skip leading whitespace on next line
} else {
// No good break point within available width
// Look for the next break point beyond the available width
// This creates ragged right margins but avoids splitting words
if let Some(next_space) = remaining.find(char::is_whitespace) {
// Check if the word will fit on the current line
let word_width = display_width(&remaining[..next_space]);
if word_width <= available_width as usize {
// Word fits on current line, write it
let (chunk, rest) = remaining.split_at(next_space);
self.write_text(
buf,
self.layout.pos.y,
self.layout.pos.x,
chunk,
self.layout.area,
style,
);
self.layout.pos.y += 1;
self.layout.pos.x = self.layout.indent;
// Draw blockquote markers on new line
self.draw_blockquote_markers(buf);
remaining = rest.trim_start();
} else {
// Word doesn't fit, wrap to next line first
self.layout.pos.y += 1;
self.layout.pos.x = self.layout.indent;
// Draw blockquote markers on new line
self.draw_blockquote_markers(buf);
// Don't modify remaining, continue on next line and try again
}
} else {
// No whitespace at all in remaining text
// If it fits, write it; otherwise wrap first
if display_width(remaining) <= available_width as usize {
self.write_text(
buf,
self.layout.pos.y,
self.layout.pos.x,
remaining,
self.layout.area,
style,
);
self.layout.pos.x += display_width(remaining) as u16;
break;
} else {
// Doesn't fit, wrap to next line
self.layout.pos.y += 1;
self.layout.pos.x = self.layout.indent;
// Draw blockquote markers on new line
self.draw_blockquote_markers(buf);
// Continue to try writing on next line
}
}
}
}
}
}
// Track action if present
if let Some(action) = &span.action {
// Calculate width handling wrapping (pos.x might be less than start_col if we wrapped)
let width = if self.layout.pos.y > start_row {
// Multi-line span - use full width of first line as clickable area
self.layout.area.width.saturating_sub(start_col).max(1)
} else {
// Single line - use actual span width
self.layout.pos.x.saturating_sub(start_col).max(1)
};
let rect = Rect::new(
start_col,
start_row,
width,
(self.layout.pos.y - start_row + 1).max(1),
);
self.render_cache.actions.push((rect, action.clone()));
}
}
}
/// Calculate the display width of text, accounting for tabs rendered as 4 spaces
fn display_width(text: &str) -> usize {
text.chars().map(|ch| if ch == '\t' { 4 } else { 1 }).sum()
}
/// Find the best position to wrap text within a given width
/// Returns the position after which to break, or None if no good break point exists
fn find_wrap_position(text: &str, max_width: usize) -> Option<usize> {
if max_width == 0 || text.is_empty() {
return None;
}
// Find the byte position that corresponds to max_width display columns (accounting for tabs)
let mut display_cols = 0;
let mut search_end = 0;
for (idx, ch) in text.char_indices() {
let char_width = if ch == '\t' { 4 } else { 1 };
if display_cols + char_width > max_width {
break;
}
display_cols += char_width;
search_end = idx + ch.len_utf8();
}
if search_end == 0 {
return None;
}
let search_range = &text[..search_end];
// First priority: break at whitespace
if let Some(pos) = search_range.rfind(char::is_whitespace) {
// Avoid breaking if it would leave a very short word (< 3 display cols) on next line
// This prevents orphans like "a" or "is" at the start of a line
let remaining_width = display_width(&text[pos..]);
if pos > 0 && remaining_width > 3 {
return Some(pos);
}
// If the remaining part is short enough, it's ok to break here
if remaining_width <= max_width / 2 {
return Some(pos);
}
}
// Second priority: break after certain punctuation (., ,, ;, :, ), ])
// This helps with long sentences without spaces
for (i, ch) in search_range.char_indices().rev() {
if matches!(ch, '.' | ',' | ';' | ':' | ')' | ']' | '}') {
// Break after the punctuation
if i + 1 < search_range.len() {
return Some(i + 1);
}
}
}
// Third priority: break at word boundaries (after lowercase before uppercase)
// This helps with camelCase or PascalCase identifiers
for i in (1..search_range.len()).rev() {
let chars: Vec<char> = search_range.chars().collect();
if i < chars.len() - 1 {
let prev = chars[i - 1];
let curr = chars[i];
if prev.is_lowercase() && curr.is_uppercase() {
return Some(i);
}
}
}
None
}