1use crate::buffer::LineBuffer;
4use crate::cursor::{MultiCursor, Position, Selection};
5use crate::history::HistoryStack;
6use crate::ime::ImeComposition;
7use crate::syntax::{Language, SyntaxHighlighter, TokenType};
8use strata_dom::{NodeBlueprint, Tag};
9
10#[derive(Debug, Clone)]
12pub struct CodeEditor {
13 buffer: LineBuffer,
14 cursors: MultiCursor,
15 history: HistoryStack,
16 highlighter: SyntaxHighlighter,
17 language: Language,
18 folded_lines: Vec<usize>,
19 ime: ImeComposition,
20 tab_size: usize,
21 wrap_column: Option<usize>,
22}
23
24impl CodeEditor {
25 pub fn new(content: &str, language: Language) -> Self {
27 let mut highlighter = SyntaxHighlighter::with_language(language);
28 highlighter.parse(content);
29 Self {
30 buffer: LineBuffer::from_str(content),
31 cursors: MultiCursor::new(),
32 history: HistoryStack::default(),
33 highlighter,
34 language,
35 folded_lines: Vec::new(),
36 ime: ImeComposition::new(),
37 tab_size: 4,
38 wrap_column: None,
39 }
40 }
41
42 pub fn highlighter(&self) -> &SyntaxHighlighter {
44 &self.highlighter
45 }
46
47 pub fn highlighter_mut(&mut self) -> &mut SyntaxHighlighter {
49 &mut self.highlighter
50 }
51
52 pub fn language(&self) -> Language {
54 self.language
55 }
56
57 pub fn set_language(&mut self, language: Language) {
59 self.language = language;
60 self.highlighter.set_language(language);
61 self.highlighter.parse(&self.buffer.to_string());
62 }
63
64 pub fn reparse(&mut self) {
66 self.highlighter.parse_incremental(&self.buffer.to_string());
67 }
68
69 pub fn buffer(&self) -> &LineBuffer {
71 &self.buffer
72 }
73
74 pub fn cursors(&self) -> &MultiCursor {
76 &self.cursors
77 }
78
79 pub fn cursors_mut(&mut self) -> &mut MultiCursor {
81 &mut self.cursors
82 }
83
84 pub fn ime(&self) -> &ImeComposition {
86 &self.ime
87 }
88
89 pub fn ime_mut(&mut self) -> &mut ImeComposition {
91 &mut self.ime
92 }
93
94 pub fn tab_size(&self) -> usize {
96 self.tab_size
97 }
98
99 pub fn set_tab_size(&mut self, size: usize) {
101 self.tab_size = size;
102 }
103
104 pub fn wrap_column(&self) -> Option<usize> {
106 self.wrap_column
107 }
108
109 pub fn set_wrap_column(&mut self, wrap: Option<usize>) {
111 self.wrap_column = wrap;
112 }
113
114 pub fn line_count(&self) -> usize {
116 self.buffer.line_count()
117 }
118
119 pub fn text(&self) -> String {
121 self.buffer.to_string()
122 }
123
124 pub fn set_text(&mut self, text: &str) {
126 self.buffer = LineBuffer::from_str(text);
127 self.cursors.set_single(Position::ZERO);
128 self.history = HistoryStack::default();
129 self.highlighter.parse(text);
130 }
131
132 pub fn insert_char(&mut self, ch: char) {
134 if ch == '\n' {
135 self.insert_newline();
136 } else {
137 self.insert_text(&ch.to_string());
138 }
139 }
140
141 pub fn insert_newline(&mut self) {
143 self.cursors.normalize();
144 let before_all = self.cursors.all().to_vec();
145 let descending = self.cursors.selections_descending();
146
147 let mut operations = Vec::with_capacity(descending.len() * 2);
148 let mut processed_carets: Vec<Position> = Vec::with_capacity(descending.len());
149
150 for sel in descending {
151 let (start, end) = sel.ordered_range();
152 if start != end {
153 let deleted = self
154 .buffer
155 .delete_range(start.line, start.col, end.line, end.col);
156 operations.push(crate::history::EditOperation::Delete {
157 start,
158 end,
159 text: deleted,
160 });
161 }
162
163 let indent_spaces = self
164 .highlighter
165 .compute_auto_indent(&self.buffer, start.line);
166 self.buffer.split_line(start.line, start.col);
167
168 let new_line = start.line + 1;
169 let indent_str = if indent_spaces > 0 {
170 let spaces = " ".repeat(indent_spaces);
171 self.buffer.insert_str(new_line, 0, &spaces);
172 spaces
173 } else {
174 String::new()
175 };
176
177 let inserted_text = format!("\n{indent_str}");
178 operations.push(crate::history::EditOperation::Insert {
179 pos: start,
180 text: inserted_text,
181 });
182
183 let lines_slice: Vec<&str> = vec!["", &indent_str];
184 let my_new_pos = Position::new(new_line, indent_spaces);
185
186 for caret in &mut processed_carets {
187 *caret = crate::cursor::shift_position_after_edit(*caret, start, end, &lines_slice);
188 }
189
190 processed_carets.push(my_new_pos);
191 }
192
193 let new_cursors: Vec<Selection> =
194 processed_carets.into_iter().map(Selection::point).collect();
195
196 self.cursors = MultiCursor::from_selections(new_cursors);
197
198 self.history
199 .push_transaction(crate::history::EditorTransaction::new(
200 operations,
201 before_all,
202 self.cursors.all().to_vec(),
203 ));
204
205 self.reparse();
206 }
207
208 pub fn insert_text(&mut self, text: &str) {
210 if text.is_empty() {
211 return;
212 }
213
214 self.cursors.normalize();
215 let before_all = self.cursors.all().to_vec();
216 let descending = self.cursors.selections_descending();
217
218 let mut operations = Vec::with_capacity(descending.len());
219 let mut processed_carets: Vec<Position> = Vec::with_capacity(descending.len());
220
221 let text_lines: Vec<&str> = text.split('\n').collect();
222
223 for sel in descending {
224 let (start, end) = sel.ordered_range();
225 if start != end {
226 let deleted = self
227 .buffer
228 .delete_range(start.line, start.col, end.line, end.col);
229 operations.push(crate::history::EditOperation::Delete {
230 start,
231 end,
232 text: deleted,
233 });
234 }
235
236 self.buffer.insert_str(start.line, start.col, text);
237 operations.push(crate::history::EditOperation::Insert {
238 pos: start,
239 text: text.to_string(),
240 });
241
242 let my_new_pos = if text_lines.len() == 1 {
243 Position::new(start.line, start.col + text_lines[0].len())
244 } else {
245 Position::new(
246 start.line + text_lines.len() - 1,
247 text_lines.last().map_or(0, |l| l.len()),
248 )
249 };
250
251 for caret in &mut processed_carets {
252 *caret = crate::cursor::shift_position_after_edit(*caret, start, end, &text_lines);
253 }
254
255 processed_carets.push(my_new_pos);
256 }
257
258 let new_cursors: Vec<Selection> =
259 processed_carets.into_iter().map(Selection::point).collect();
260
261 self.cursors = MultiCursor::from_selections(new_cursors);
262
263 self.history
264 .push_transaction(crate::history::EditorTransaction::new(
265 operations,
266 before_all,
267 self.cursors.all().to_vec(),
268 ));
269
270 self.reparse();
271 }
272
273 pub fn delete_backwards(&mut self) {
275 self.cursors.normalize();
276 let before_all = self.cursors.all().to_vec();
277 let descending = self.cursors.selections_descending();
278
279 let mut operations = Vec::with_capacity(descending.len());
280 let mut processed_carets: Vec<Position> = Vec::with_capacity(descending.len());
281
282 for sel in descending {
283 let (start, end) = sel.ordered_range();
284 if start != end {
285 let deleted = self
286 .buffer
287 .delete_range(start.line, start.col, end.line, end.col);
288 operations.push(crate::history::EditOperation::Delete {
289 start,
290 end,
291 text: deleted,
292 });
293
294 for caret in &mut processed_carets {
295 *caret = crate::cursor::shift_position_after_edit(*caret, start, end, &[""]);
296 }
297
298 processed_carets.push(start);
299 } else if start.col > 0 {
300 let del_start = Position::new(start.line, start.col - 1);
301 let deleted =
302 self.buffer
303 .delete_range(del_start.line, del_start.col, start.line, start.col);
304 operations.push(crate::history::EditOperation::Delete {
305 start: del_start,
306 end: start,
307 text: deleted,
308 });
309
310 for caret in &mut processed_carets {
311 *caret =
312 crate::cursor::shift_position_after_edit(*caret, del_start, start, &[""]);
313 }
314
315 processed_carets.push(del_start);
316 } else if start.line > 0 {
317 let prev_line = start.line - 1;
318 let prev_len = self.buffer.line_len(prev_line);
319 let del_start = Position::new(prev_line, prev_len);
320
321 self.buffer.join_line_with_next(prev_line);
322 operations.push(crate::history::EditOperation::Delete {
323 start: del_start,
324 end: Position::new(start.line, 0),
325 text: "\n".to_string(),
326 });
327
328 for caret in &mut processed_carets {
329 *caret = crate::cursor::shift_position_after_edit(
330 *caret,
331 del_start,
332 Position::new(start.line, 0),
333 &[""],
334 );
335 }
336
337 processed_carets.push(del_start);
338 } else {
339 processed_carets.push(start);
340 }
341 }
342
343 let new_cursors: Vec<Selection> =
344 processed_carets.into_iter().map(Selection::point).collect();
345
346 self.cursors = MultiCursor::from_selections(new_cursors);
347
348 if !operations.is_empty() {
349 self.history
350 .push_transaction(crate::history::EditorTransaction::new(
351 operations,
352 before_all,
353 self.cursors.all().to_vec(),
354 ));
355 }
356
357 self.reparse();
358 }
359
360 pub fn undo(&mut self) {
362 if let Some(restored) = self.history.undo(&mut self.buffer) {
363 self.cursors = MultiCursor::from_selections(restored);
364 self.reparse();
365 }
366 }
367
368 pub fn redo(&mut self) {
370 if let Some(restored) = self.history.redo(&mut self.buffer) {
371 self.cursors = MultiCursor::from_selections(restored);
372 self.reparse();
373 }
374 }
375
376 pub fn move_left(&mut self, select: bool) {
378 let before = self.cursors.all().to_vec();
379 let mut new_cursors = Vec::with_capacity(before.len());
380
381 for sel in &before {
382 let focus = sel.focus;
383 let new_focus = if focus.col > 0 {
384 Position::new(focus.line, focus.col - 1)
385 } else if focus.line > 0 {
386 let prev_line = focus.line - 1;
387 let prev_len = self.buffer.line_len(prev_line);
388 Position::new(prev_line, prev_len)
389 } else {
390 Position::ZERO
391 };
392
393 let anchor = if select { sel.anchor } else { new_focus };
394 new_cursors.push(Selection::range(anchor, new_focus));
395 }
396
397 self.cursors = MultiCursor::from_selections(new_cursors);
398 }
399
400 pub fn move_right(&mut self, select: bool) {
402 let before = self.cursors.all().to_vec();
403 let mut new_cursors = Vec::with_capacity(before.len());
404
405 for sel in &before {
406 let focus = sel.focus;
407 let cur_line_len = self.buffer.line_len(focus.line);
408
409 let new_focus = if focus.col < cur_line_len {
410 Position::new(focus.line, focus.col + 1)
411 } else if focus.line + 1 < self.buffer.line_count() {
412 Position::new(focus.line + 1, 0)
413 } else {
414 Position::new(focus.line, cur_line_len)
415 };
416
417 let anchor = if select { sel.anchor } else { new_focus };
418 new_cursors.push(Selection::range(anchor, new_focus));
419 }
420
421 self.cursors = MultiCursor::from_selections(new_cursors);
422 }
423
424 pub fn move_up(&mut self, select: bool) {
426 let before = self.cursors.all().to_vec();
427 let mut new_cursors = Vec::with_capacity(before.len());
428
429 for sel in &before {
430 let focus = sel.focus;
431 let new_focus = if focus.line > 0 {
432 let prev_line = focus.line - 1;
433 let prev_len = self.buffer.line_len(prev_line);
434 Position::new(prev_line, focus.col.min(prev_len))
435 } else {
436 Position::new(0, 0)
437 };
438
439 let anchor = if select { sel.anchor } else { new_focus };
440 new_cursors.push(Selection::range(anchor, new_focus));
441 }
442
443 self.cursors = MultiCursor::from_selections(new_cursors);
444 }
445
446 pub fn move_down(&mut self, select: bool) {
448 let before = self.cursors.all().to_vec();
449 let mut new_cursors = Vec::with_capacity(before.len());
450
451 for sel in &before {
452 let focus = sel.focus;
453 let new_focus = if focus.line + 1 < self.buffer.line_count() {
454 let next_line = focus.line + 1;
455 let next_len = self.buffer.line_len(next_line);
456 Position::new(next_line, focus.col.min(next_len))
457 } else {
458 let last_len = self.buffer.line_len(focus.line);
459 Position::new(focus.line, last_len)
460 };
461
462 let anchor = if select { sel.anchor } else { new_focus };
463 new_cursors.push(Selection::range(anchor, new_focus));
464 }
465
466 self.cursors = MultiCursor::from_selections(new_cursors);
467 }
468
469 pub fn move_to_line_start(&mut self, select: bool) {
471 let before = self.cursors.all().to_vec();
472 let mut new_cursors = Vec::with_capacity(before.len());
473
474 for sel in &before {
475 let new_focus = Position::new(sel.focus.line, 0);
476 let anchor = if select { sel.anchor } else { new_focus };
477 new_cursors.push(Selection::range(anchor, new_focus));
478 }
479
480 self.cursors = MultiCursor::from_selections(new_cursors);
481 }
482
483 pub fn move_to_line_end(&mut self, select: bool) {
485 let before = self.cursors.all().to_vec();
486 let mut new_cursors = Vec::with_capacity(before.len());
487
488 for sel in &before {
489 let line_len = self.buffer.line_len(sel.focus.line);
490 let new_focus = Position::new(sel.focus.line, line_len);
491 let anchor = if select { sel.anchor } else { new_focus };
492 new_cursors.push(Selection::range(anchor, new_focus));
493 }
494
495 self.cursors = MultiCursor::from_selections(new_cursors);
496 }
497
498 pub fn select_all(&mut self) {
500 let total_lines = self.buffer.line_count();
501 let last_line = total_lines.saturating_sub(1);
502 let last_col = self.buffer.line_len(last_line);
503 self.cursors.set_single(Position::ZERO);
504 self.cursors.all_mut()[0] =
505 Selection::range(Position::ZERO, Position::new(last_line, last_col));
506 }
507
508 pub fn toggle_fold(&mut self, line: usize) {
510 if let Some(pos) = self.folded_lines.iter().position(|&l| l == line) {
511 self.folded_lines.remove(pos);
512 } else {
513 self.folded_lines.push(line);
514 }
515 }
516
517 pub fn is_folded(&self, line: usize) -> bool {
519 self.folded_lines.contains(&line)
520 }
521
522 pub fn render(&self) -> NodeBlueprint {
524 self.render_blueprint("")
525 }
526
527 pub fn render_blueprint(&self, class_style: &str) -> NodeBlueprint {
529 if self.buffer.line_count() > 100 {
530 return self.render_virtualized(0.0, 800.0, 24.0, class_style);
531 }
532
533 let mut row_nodes = Vec::new();
534
535 let visible_lines = self.buffer.slice_lines(0, self.buffer.line_count());
536 let active_line = self.cursors.primary().focus.line;
537
538 for (l_idx, line_str) in visible_lines {
539 let is_active = l_idx == active_line;
540
541 let row_class = if is_active {
542 "flex items-center font-mono text-sm leading-6 bg-slate-800/40 hover:bg-slate-800/60"
543 } else {
544 "flex items-center font-mono text-sm leading-6 hover:bg-slate-800/30"
545 };
546
547 let visual_sublines = if let Some(cols) = self.wrap_column {
548 crate::soft_wrap::wrap_logical_line(line_str, l_idx, cols, true)
549 } else {
550 vec![crate::soft_wrap::VisualLine {
551 logical_line: l_idx,
552 visual_subline: 0,
553 text: line_str.to_string(),
554 char_start: 0,
555 char_end: line_str.chars().count(),
556 is_continuation: false,
557 }]
558 };
559
560 for vline in visual_sublines {
561 let gutter_text = if vline.is_continuation {
562 "↳".to_string()
563 } else {
564 (l_idx + 1).to_string()
565 };
566
567 let gutter_node = NodeBlueprint::element(
568 Tag::Span,
569 vec![
570 "w-12 text-right pr-4 select-none text-slate-500 font-mono text-xs"
571 .to_string(),
572 ],
573 Vec::new(),
574 vec![NodeBlueprint::text(gutter_text)],
575 );
576
577 let tokens = self.highlighter.highlight_line_ast(l_idx, &vline.text);
578 let mut line_token_nodes = Vec::new();
579
580 if tokens.is_empty() {
581 line_token_nodes.push(NodeBlueprint::text(vline.text));
582 } else {
583 let mut last_col = 0;
584 for token in tokens {
585 if token.start_col > last_col && token.start_col <= vline.text.len() {
586 line_token_nodes
587 .push(NodeBlueprint::text(&vline.text[last_col..token.start_col]));
588 }
589
590 let color_class = match token.token_type {
591 TokenType::Keyword => "text-purple-400 font-semibold",
592 TokenType::Type => "text-amber-400 font-medium",
593 TokenType::Function => "text-blue-400",
594 TokenType::String => "text-emerald-400",
595 TokenType::Number => "text-orange-400",
596 TokenType::Comment => "text-slate-500 italic",
597 TokenType::Operator => "text-rose-400",
598 TokenType::Punctuation => "text-slate-400",
599 TokenType::Tag => "text-cyan-400",
600 TokenType::Attribute => "text-sky-300",
601 TokenType::Identifier => "text-slate-200",
602 };
603
604 line_token_nodes.push(NodeBlueprint::element(
605 Tag::Span,
606 vec![color_class.to_string()],
607 Vec::new(),
608 vec![NodeBlueprint::text(token.text)],
609 ));
610 last_col = token.end_col.min(vline.text.len());
611 }
612 if last_col < vline.text.len() {
613 line_token_nodes.push(NodeBlueprint::text(&vline.text[last_col..]));
614 }
615 }
616
617 let code_node = NodeBlueprint::element(
618 Tag::Span,
619 vec!["flex-1 pl-2 whitespace-pre".to_string()],
620 Vec::new(),
621 line_token_nodes,
622 );
623
624 row_nodes.push(NodeBlueprint::element(
625 Tag::Div,
626 vec![row_class.to_string()],
627 Vec::new(),
628 vec![gutter_node, code_node],
629 ));
630 }
631 }
632
633 let container_class = format!(
634 "bg-slate-950 text-slate-200 border border-slate-800 rounded-lg p-4 font-mono overflow-x-auto {}",
635 class_style
636 );
637
638 NodeBlueprint::element(Tag::Div, vec![container_class], Vec::new(), row_nodes)
639 }
640
641 pub fn render_virtualized(
647 &self,
648 scroll_top: f32,
649 viewport_height: f32,
650 line_height: f32,
651 class_style: &str,
652 ) -> NodeBlueprint {
653 let total_lines = self.buffer.line_count();
654 let effective_lh = line_height.max(1.0);
655
656 let first_visible = (scroll_top / effective_lh).floor() as usize;
657 let visible_count = (viewport_height / effective_lh).ceil() as usize;
658
659 let start_line = first_visible.saturating_sub(2).min(total_lines);
661 let end_line = (first_visible + visible_count + 2).min(total_lines);
662
663 let top_spacer_height = start_line as f32 * effective_lh;
664 let bottom_spacer_height = (total_lines.saturating_sub(end_line)) as f32 * effective_lh;
665
666 let mut row_nodes = Vec::new();
667
668 if top_spacer_height > 0.0 {
670 row_nodes.push(NodeBlueprint::element(
671 Tag::Div,
672 vec![format!(
673 "h-[{:.1}px] w-full pointer-events-none",
674 top_spacer_height
675 )],
676 Vec::new(),
677 Vec::new(),
678 ));
679 }
680
681 let visible_lines = self
682 .buffer
683 .slice_lines(start_line, end_line.saturating_sub(start_line));
684 let active_line = self.cursors.primary().focus.line;
685
686 for (l_idx, line_str) in visible_lines {
687 let is_active = l_idx == active_line;
688
689 let row_class = if is_active {
690 "flex items-center font-mono text-sm leading-6 bg-slate-800/40 hover:bg-slate-800/60"
691 } else {
692 "flex items-center font-mono text-sm leading-6 hover:bg-slate-800/30"
693 };
694
695 let visual_sublines = if let Some(cols) = self.wrap_column {
696 crate::soft_wrap::wrap_logical_line(line_str, l_idx, cols, true)
697 } else {
698 vec![crate::soft_wrap::VisualLine {
699 logical_line: l_idx,
700 visual_subline: 0,
701 text: line_str.to_string(),
702 char_start: 0,
703 char_end: line_str.chars().count(),
704 is_continuation: false,
705 }]
706 };
707
708 for vline in visual_sublines {
709 let gutter_text = if vline.is_continuation {
710 "↳".to_string()
711 } else {
712 (l_idx + 1).to_string()
713 };
714
715 let gutter_class = if vline.is_continuation {
716 "w-12 text-right pr-4 select-none text-slate-600 font-mono text-xs"
717 } else {
718 "w-12 text-right pr-4 select-none text-slate-500 font-mono text-xs"
719 };
720
721 let gutter_node = NodeBlueprint::element(
722 Tag::Span,
723 vec![gutter_class.to_string()],
724 Vec::new(),
725 vec![NodeBlueprint::text(gutter_text)],
726 );
727
728 let tokens = self.highlighter.highlight_line_ast(l_idx, &vline.text);
730 let mut line_token_nodes = Vec::new();
731
732 if tokens.is_empty() {
733 line_token_nodes.push(NodeBlueprint::text(vline.text));
734 } else {
735 let mut last_col = 0;
736 for token in tokens {
737 if token.start_col > last_col && token.start_col <= vline.text.len() {
738 line_token_nodes
739 .push(NodeBlueprint::text(&vline.text[last_col..token.start_col]));
740 }
741
742 let color_class = match token.token_type {
743 TokenType::Keyword => "text-purple-400 font-semibold",
744 TokenType::Type => "text-amber-400 font-medium",
745 TokenType::Function => "text-blue-400",
746 TokenType::String => "text-emerald-400",
747 TokenType::Number => "text-orange-400",
748 TokenType::Comment => "text-slate-500 italic",
749 TokenType::Operator => "text-rose-400",
750 TokenType::Punctuation => "text-slate-400",
751 TokenType::Tag => "text-cyan-400",
752 TokenType::Attribute => "text-sky-300",
753 TokenType::Identifier => "text-slate-200",
754 };
755
756 line_token_nodes.push(NodeBlueprint::element(
757 Tag::Span,
758 vec![color_class.to_string()],
759 Vec::new(),
760 vec![NodeBlueprint::text(token.text)],
761 ));
762 last_col = token.end_col.min(vline.text.len());
763 }
764 if last_col < vline.text.len() {
765 line_token_nodes.push(NodeBlueprint::text(&vline.text[last_col..]));
766 }
767 }
768
769 let code_node = NodeBlueprint::element(
770 Tag::Span,
771 vec!["flex-1 pl-2 whitespace-pre".to_string()],
772 Vec::new(),
773 line_token_nodes,
774 );
775
776 row_nodes.push(NodeBlueprint::element(
777 Tag::Div,
778 vec![row_class.to_string()],
779 Vec::new(),
780 vec![gutter_node, code_node],
781 ));
782 }
783 }
784
785 if bottom_spacer_height > 0.0 {
787 row_nodes.push(NodeBlueprint::element(
788 Tag::Div,
789 vec![format!(
790 "h-[{:.1}px] w-full pointer-events-none",
791 bottom_spacer_height
792 )],
793 Vec::new(),
794 Vec::new(),
795 ));
796 }
797
798 let container_class = format!(
799 "bg-slate-950 text-slate-200 border border-slate-800 rounded-lg p-4 font-mono overflow-y-auto {}",
800 class_style
801 );
802
803 NodeBlueprint::element(Tag::Div, vec![container_class], Vec::new(), row_nodes)
804 }
805}