1use std::ops::{Range, RangeInclusive};
10use std::rc::Rc;
11use std::time::{Duration, Instant};
12
13use gpui::{
14 App, Bounds, ClipboardItem, ContentMask, Context, CursorStyle, ElementInputHandler,
15 EntityInputHandler, EventEmitter, FocusHandle, Focusable, HighlightStyle, KeyBinding,
16 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, Pixels, Point, Render,
17 ScrollStrategy, ScrollWheelEvent, ShapedLine, SharedString, TextRun, UTF16Selection,
18 UnderlineStyle, UniformListScrollHandle, Window, canvas, div, fill, font, point, prelude::*,
19 px, size, uniform_list,
20};
21
22use super::code_buffer::{BufferPos, BufferSelection, CodeBuffer};
23use crate::motion::continuous_at;
24use crate::theme::{MONO_FONT_FAMILY, Theme, alpha};
25
26mod keys {
27 gpui::actions!(
28 m3_code_editor,
29 [
30 Backspace,
31 Delete,
32 DeleteWordLeft,
33 DeleteWordRight,
34 Left,
35 Right,
36 Up,
37 Down,
38 SelectLeft,
39 SelectRight,
40 SelectUp,
41 SelectDown,
42 WordLeft,
43 WordRight,
44 SelectWordLeft,
45 SelectWordRight,
46 Home,
47 End,
48 SelectHome,
49 SelectEnd,
50 DocStart,
51 DocEnd,
52 SelectDocStart,
53 SelectDocEnd,
54 PageUp,
55 PageDown,
56 SelectPageUp,
57 SelectPageDown,
58 SelectAll,
59 Copy,
60 Cut,
61 Paste,
62 Undo,
63 Redo,
64 Newline,
65 Indent,
66 Outdent,
67 Save,
68 Cancel
69 ]
70 );
71}
72use keys::*;
73
74const KEY_CONTEXT: &str = "M3CodeEditor";
75const TEXT_PAD: f32 = 8.;
77
78pub fn bind_code_editor_keys(cx: &mut App) {
80 cx.bind_keys(code_editor_bindings());
81}
82
83pub(crate) fn code_editor_bindings() -> Vec<KeyBinding> {
84 let ctx = Some(KEY_CONTEXT);
85 #[cfg(target_os = "macos")]
87 let word = "alt";
88 #[cfg(not(target_os = "macos"))]
89 let word = "ctrl";
90 let w = |key: &str| format!("{word}-{key}");
91 vec![
92 KeyBinding::new("backspace", Backspace, ctx),
93 KeyBinding::new("shift-backspace", Backspace, ctx),
94 KeyBinding::new("delete", Delete, ctx),
95 KeyBinding::new(&w("backspace"), DeleteWordLeft, ctx),
96 KeyBinding::new(&w("delete"), DeleteWordRight, ctx),
97 KeyBinding::new("left", Left, ctx),
98 KeyBinding::new("right", Right, ctx),
99 KeyBinding::new("up", Up, ctx),
100 KeyBinding::new("down", Down, ctx),
101 KeyBinding::new("shift-left", SelectLeft, ctx),
102 KeyBinding::new("shift-right", SelectRight, ctx),
103 KeyBinding::new("shift-up", SelectUp, ctx),
104 KeyBinding::new("shift-down", SelectDown, ctx),
105 KeyBinding::new(&w("left"), WordLeft, ctx),
106 KeyBinding::new(&w("right"), WordRight, ctx),
107 KeyBinding::new(&w("shift-left"), SelectWordLeft, ctx),
108 KeyBinding::new(&w("shift-right"), SelectWordRight, ctx),
109 KeyBinding::new("home", Home, ctx),
110 KeyBinding::new("end", End, ctx),
111 KeyBinding::new("shift-home", SelectHome, ctx),
112 KeyBinding::new("shift-end", SelectEnd, ctx),
113 KeyBinding::new("secondary-home", DocStart, ctx),
114 KeyBinding::new("secondary-end", DocEnd, ctx),
115 KeyBinding::new("secondary-up", DocStart, ctx),
116 KeyBinding::new("secondary-down", DocEnd, ctx),
117 KeyBinding::new("secondary-shift-home", SelectDocStart, ctx),
118 KeyBinding::new("secondary-shift-end", SelectDocEnd, ctx),
119 KeyBinding::new("pageup", PageUp, ctx),
120 KeyBinding::new("pagedown", PageDown, ctx),
121 KeyBinding::new("shift-pageup", SelectPageUp, ctx),
122 KeyBinding::new("shift-pagedown", SelectPageDown, ctx),
123 KeyBinding::new("secondary-a", SelectAll, ctx),
124 KeyBinding::new("secondary-c", Copy, ctx),
125 KeyBinding::new("secondary-x", Cut, ctx),
126 KeyBinding::new("secondary-v", Paste, ctx),
127 KeyBinding::new("secondary-z", Undo, ctx),
128 KeyBinding::new("secondary-shift-z", Redo, ctx),
129 KeyBinding::new("secondary-y", Redo, ctx),
130 KeyBinding::new("enter", Newline, ctx),
131 KeyBinding::new("shift-enter", Newline, ctx),
132 KeyBinding::new("tab", Indent, ctx),
133 KeyBinding::new("shift-tab", Outdent, ctx),
134 KeyBinding::new("secondary-s", Save, ctx),
135 KeyBinding::new("escape", Cancel, ctx),
136 ]
137}
138
139pub type LineHighlights = Vec<(Range<usize>, HighlightStyle)>;
141
142pub trait LineHighlighter: 'static {
151 fn highlight_line(&mut self, buffer: &CodeBuffer, line: usize, cx: &App) -> LineHighlights;
153
154 fn invalidate(&mut self, from_line: usize) {
156 let _ = from_line;
157 }
158}
159
160impl<F> LineHighlighter for F
161where
162 F: FnMut(usize, &str) -> LineHighlights + 'static,
163{
164 fn highlight_line(&mut self, buffer: &CodeBuffer, line: usize, _: &App) -> LineHighlights {
165 self(line, buffer.line(line))
166 }
167}
168
169#[derive(Clone, Debug, PartialEq, Eq)]
171pub enum CodeEditorEvent {
172 Changed,
175 Save,
177 SelectionChanged,
179 Cancelled,
181}
182
183#[derive(Clone, Debug, PartialEq, Eq)]
185pub struct CodeSelection {
186 pub path: Option<SharedString>,
187 pub lines: RangeInclusive<usize>,
189 pub text: String,
191}
192
193impl CodeSelection {
194 pub fn label(&self) -> String {
196 let path: &str = self.path.as_ref().map_or("untitled", |p| p.as_ref());
197 if self.lines.start() == self.lines.end() {
198 format!("{path}:{}", self.lines.start())
199 } else {
200 format!("{path}:{}-{}", self.lines.start(), self.lines.end())
201 }
202 }
203}
204
205pub struct CodeEditor {
222 focus_handle: FocusHandle,
223 buffer: CodeBuffer,
224 path: Option<SharedString>,
225 highlighter: Option<Box<dyn LineHighlighter>>,
226 highlights: Vec<Option<Rc<LineHighlights>>>,
227 scroll: UniformListScrollHandle,
228 scroll_x: Pixels,
229 reveal_x: bool,
230 font_size: Pixels,
231 line_numbers: bool,
232 read_only: bool,
233 rows: Vec<(usize, ShapedLine)>,
235 viewport: Option<Bounds<Pixels>>,
236 char_width: Pixels,
237 marked: Option<Range<BufferPos>>,
238 selecting: bool,
239 last_input: Instant,
240}
241
242impl EventEmitter<CodeEditorEvent> for CodeEditor {}
243
244impl Focusable for CodeEditor {
245 fn focus_handle(&self, _: &App) -> FocusHandle {
246 self.focus_handle.clone()
247 }
248}
249
250impl CodeEditor {
251 pub fn new(cx: &mut Context<Self>) -> Self {
252 Self {
253 focus_handle: cx.focus_handle(),
254 buffer: CodeBuffer::new(""),
255 path: None,
256 highlighter: None,
257 highlights: Vec::new(),
258 scroll: UniformListScrollHandle::new(),
259 scroll_x: px(0.),
260 reveal_x: false,
261 font_size: px(13.),
262 line_numbers: true,
263 read_only: false,
264 rows: Vec::new(),
265 viewport: None,
266 char_width: px(7.),
267 marked: None,
268 selecting: false,
269 last_input: Instant::now(),
270 }
271 }
272
273 pub fn with_text(mut self, text: &str) -> Self {
275 self.buffer.set_text(text);
276 self
277 }
278
279 pub fn path(mut self, path: impl Into<SharedString>) -> Self {
281 self.path = Some(path.into());
282 self
283 }
284
285 pub fn font_size(mut self, size: Pixels) -> Self {
287 self.font_size = size;
288 self
289 }
290
291 pub fn line_numbers(mut self, show: bool) -> Self {
293 self.line_numbers = show;
294 self
295 }
296
297 pub fn read_only(mut self, read_only: bool) -> Self {
299 self.read_only = read_only;
300 self
301 }
302
303 pub fn tab_size(mut self, size: usize) -> Self {
305 self.buffer.tab_size = size.max(1);
306 self
307 }
308
309 pub fn hard_tabs(mut self, hard: bool) -> Self {
311 self.buffer.hard_tabs = hard;
312 self
313 }
314
315 pub fn auto_pair(mut self, on: bool) -> Self {
317 self.buffer.auto_pair = on;
318 self
319 }
320
321 pub fn highlighter(mut self, highlighter: impl LineHighlighter) -> Self {
322 self.highlighter = Some(Box::new(highlighter));
323 self
324 }
325
326 pub fn text(&self) -> String {
328 self.buffer.text()
329 }
330
331 pub fn buffer(&self) -> &CodeBuffer {
332 &self.buffer
333 }
334
335 pub fn set_text(&mut self, text: &str, cx: &mut Context<Self>) {
337 self.buffer.set_text(text);
338 self.scroll_x = px(0.);
339 self.scroll.scroll_to_item(0, ScrollStrategy::Top);
340 self.after_edit(cx);
341 }
342
343 pub fn set_path(&mut self, path: Option<SharedString>, cx: &mut Context<Self>) {
344 self.path = path;
345 cx.notify();
346 }
347
348 pub fn file_path(&self) -> Option<&SharedString> {
349 self.path.as_ref()
350 }
351
352 pub fn set_highlighter(
354 &mut self,
355 highlighter: Option<Box<dyn LineHighlighter>>,
356 cx: &mut Context<Self>,
357 ) {
358 self.highlighter = highlighter;
359 self.highlights.clear();
360 cx.notify();
361 }
362
363 pub fn refresh_highlights(&mut self, cx: &mut Context<Self>) {
365 if let Some(h) = self.highlighter.as_mut() {
366 h.invalidate(0);
367 }
368 self.highlights.clear();
369 cx.notify();
370 }
371
372 pub fn set_read_only(&mut self, read_only: bool, cx: &mut Context<Self>) {
373 self.read_only = read_only;
374 cx.notify();
375 }
376
377 pub fn is_dirty(&self) -> bool {
379 self.buffer.is_dirty()
380 }
381
382 pub fn mark_saved(&mut self, cx: &mut Context<Self>) {
383 self.buffer.mark_saved();
384 cx.notify();
385 }
386
387 pub fn selection_context(&self) -> CodeSelection {
389 let sel = self.buffer.selection();
390 let lines = sel.lines();
391 CodeSelection {
392 path: self.path.clone(),
393 lines: lines.start + 1..=lines.end.max(lines.start + 1),
394 text: self.buffer.selected_text(),
395 }
396 }
397
398 pub fn selection(&self) -> BufferSelection {
399 self.buffer.selection()
400 }
401
402 pub fn go_to(&mut self, line: usize, col: usize, cx: &mut Context<Self>) {
404 self.motion(cx, |b| b.set_cursor(BufferPos::new(line, col), false));
405 self.scroll
406 .scroll_to_item(self.buffer.cursor().line, ScrollStrategy::Center);
407 }
408
409 pub fn select(&mut self, selection: BufferSelection, cx: &mut Context<Self>) {
411 self.motion(cx, |b| b.set_selection(selection));
412 }
413
414 pub fn focus(&self, window: &mut Window) {
415 window.focus(&self.focus_handle);
416 }
417
418 pub fn is_focused(&self, window: &Window) -> bool {
419 self.focus_handle.is_focused(window)
420 }
421
422 pub fn undo(&mut self, cx: &mut Context<Self>) {
423 self.edit(cx, |b| {
424 b.undo();
425 });
426 }
427
428 pub fn redo(&mut self, cx: &mut Context<Self>) {
429 self.edit(cx, |b| {
430 b.redo();
431 });
432 }
433
434 fn line_height(&self) -> Pixels {
437 (self.font_size * 1.5).round()
438 }
439
440 fn reveal(&mut self) {
441 self.scroll
442 .scroll_to_item(self.buffer.cursor().line, ScrollStrategy::Top);
443 self.reveal_x = true;
444 }
445
446 fn motion(&mut self, cx: &mut Context<Self>, f: impl FnOnce(&mut CodeBuffer)) {
448 let before = self.buffer.selection();
449 f(&mut self.buffer);
450 self.marked = None;
451 self.last_input = Instant::now();
452 self.reveal();
453 if self.buffer.selection() != before {
454 cx.emit(CodeEditorEvent::SelectionChanged);
455 }
456 cx.notify();
457 }
458
459 fn edit(&mut self, cx: &mut Context<Self>, f: impl FnOnce(&mut CodeBuffer)) {
462 if self.read_only {
463 return;
464 }
465 if self.last_input.elapsed() > Duration::from_secs(1) {
466 self.buffer.break_undo_group();
467 }
468 let before = self.buffer.selection();
469 f(&mut self.buffer);
470 self.last_input = Instant::now();
471 self.reveal();
472 self.after_edit(cx);
473 if self.buffer.selection() != before {
474 cx.emit(CodeEditorEvent::SelectionChanged);
475 }
476 }
477
478 fn after_edit(&mut self, cx: &mut Context<Self>) {
479 if let Some(from) = self.buffer.take_edited_from() {
480 self.highlights.truncate(from);
481 if let Some(h) = self.highlighter.as_mut() {
482 h.invalidate(from);
483 }
484 cx.emit(CodeEditorEvent::Changed);
485 }
486 cx.notify();
487 }
488
489 fn page_lines(&self) -> isize {
490 let height = self.viewport.map_or(px(400.), |b| b.size.height);
491 ((height / self.line_height()).floor() as isize - 1).max(1)
492 }
493
494 fn gutter_width(&self) -> Pixels {
495 if !self.line_numbers {
496 return px(0.);
497 }
498 let digits = self.buffer.line_count().to_string().len().max(2);
499 self.char_width * digits as f32 + px(28.)
500 }
501
502 fn pos_for_point(&self, position: Point<Pixels>) -> BufferPos {
504 let Some(viewport) = self.viewport else {
505 return BufferPos::default();
506 };
507 let lh = self.line_height();
508 let offset = self.scroll.0.borrow().base_handle.offset();
509 let y = position.y - viewport.top() - offset.y;
510 if y < px(0.) {
511 return BufferPos::default();
512 }
513 let line = (y / lh).floor() as usize;
514 if line >= self.buffer.line_count() {
515 let last = self.buffer.line_count() - 1;
516 return BufferPos::new(last, self.buffer.line(last).len());
517 }
518 let x = position.x - viewport.left() - self.gutter_width() - px(TEXT_PAD) + self.scroll_x;
519 let col = match self.rows.iter().find(|(l, _)| *l == line) {
520 Some((_, shaped)) => shaped.closest_index_for_x(x.max(px(0.))),
521 None => {
522 let chars = (x / self.char_width).round().max(0.) as usize;
523 let text = self.buffer.line(line);
524 text.char_indices()
525 .nth(chars)
526 .map_or(text.len(), |(i, _)| i)
527 }
528 };
529 self.buffer.clip(BufferPos::new(line, col))
530 }
531
532 fn highlights_for(&mut self, line: usize, cx: &App) -> Option<Rc<LineHighlights>> {
533 let highlighter = self.highlighter.as_mut()?;
534 if self.highlights.len() < self.buffer.line_count() {
535 self.highlights.resize(self.buffer.line_count(), None);
536 }
537 if let Some(Some(cached)) = self.highlights.get(line) {
538 return Some(cached.clone());
539 }
540 let computed = Rc::new(highlighter.highlight_line(&self.buffer, line, cx));
541 if let Some(slot) = self.highlights.get_mut(line) {
542 *slot = Some(computed.clone());
543 }
544 Some(computed)
545 }
546
547 fn backspace(&mut self, _: &Backspace, _: &mut Window, cx: &mut Context<Self>) {
550 self.edit(cx, CodeBuffer::backspace);
551 }
552 fn delete(&mut self, _: &Delete, _: &mut Window, cx: &mut Context<Self>) {
553 self.edit(cx, CodeBuffer::delete);
554 }
555 fn delete_word_left(&mut self, _: &DeleteWordLeft, _: &mut Window, cx: &mut Context<Self>) {
556 self.edit(cx, CodeBuffer::delete_word_left);
557 }
558 fn delete_word_right(&mut self, _: &DeleteWordRight, _: &mut Window, cx: &mut Context<Self>) {
559 self.edit(cx, CodeBuffer::delete_word_right);
560 }
561 fn left(&mut self, _: &Left, _: &mut Window, cx: &mut Context<Self>) {
562 self.motion(cx, |b| b.move_left(false));
563 }
564 fn right(&mut self, _: &Right, _: &mut Window, cx: &mut Context<Self>) {
565 self.motion(cx, |b| b.move_right(false));
566 }
567 fn up(&mut self, _: &Up, _: &mut Window, cx: &mut Context<Self>) {
568 self.motion(cx, |b| b.move_vertically(-1, false));
569 }
570 fn down(&mut self, _: &Down, _: &mut Window, cx: &mut Context<Self>) {
571 self.motion(cx, |b| b.move_vertically(1, false));
572 }
573 fn select_left(&mut self, _: &SelectLeft, _: &mut Window, cx: &mut Context<Self>) {
574 self.motion(cx, |b| b.move_left(true));
575 }
576 fn select_right(&mut self, _: &SelectRight, _: &mut Window, cx: &mut Context<Self>) {
577 self.motion(cx, |b| b.move_right(true));
578 }
579 fn select_up(&mut self, _: &SelectUp, _: &mut Window, cx: &mut Context<Self>) {
580 self.motion(cx, |b| b.move_vertically(-1, true));
581 }
582 fn select_down(&mut self, _: &SelectDown, _: &mut Window, cx: &mut Context<Self>) {
583 self.motion(cx, |b| b.move_vertically(1, true));
584 }
585 fn word_left(&mut self, _: &WordLeft, _: &mut Window, cx: &mut Context<Self>) {
586 self.motion(cx, |b| b.move_word_left(false));
587 }
588 fn word_right(&mut self, _: &WordRight, _: &mut Window, cx: &mut Context<Self>) {
589 self.motion(cx, |b| b.move_word_right(false));
590 }
591 fn select_word_left(&mut self, _: &SelectWordLeft, _: &mut Window, cx: &mut Context<Self>) {
592 self.motion(cx, |b| b.move_word_left(true));
593 }
594 fn select_word_right(&mut self, _: &SelectWordRight, _: &mut Window, cx: &mut Context<Self>) {
595 self.motion(cx, |b| b.move_word_right(true));
596 }
597 fn home(&mut self, _: &Home, _: &mut Window, cx: &mut Context<Self>) {
598 self.motion(cx, |b| b.move_home(false));
599 }
600 fn end(&mut self, _: &End, _: &mut Window, cx: &mut Context<Self>) {
601 self.motion(cx, |b| b.move_end(false));
602 }
603 fn select_home(&mut self, _: &SelectHome, _: &mut Window, cx: &mut Context<Self>) {
604 self.motion(cx, |b| b.move_home(true));
605 }
606 fn select_end(&mut self, _: &SelectEnd, _: &mut Window, cx: &mut Context<Self>) {
607 self.motion(cx, |b| b.move_end(true));
608 }
609 fn doc_start(&mut self, _: &DocStart, _: &mut Window, cx: &mut Context<Self>) {
610 self.motion(cx, |b| b.move_to_start(false));
611 }
612 fn doc_end(&mut self, _: &DocEnd, _: &mut Window, cx: &mut Context<Self>) {
613 self.motion(cx, |b| b.move_to_end(false));
614 }
615 fn select_doc_start(&mut self, _: &SelectDocStart, _: &mut Window, cx: &mut Context<Self>) {
616 self.motion(cx, |b| b.move_to_start(true));
617 }
618 fn select_doc_end(&mut self, _: &SelectDocEnd, _: &mut Window, cx: &mut Context<Self>) {
619 self.motion(cx, |b| b.move_to_end(true));
620 }
621 fn page_up(&mut self, _: &PageUp, _: &mut Window, cx: &mut Context<Self>) {
622 let n = self.page_lines();
623 self.motion(cx, |b| b.move_vertically(-n, false));
624 }
625 fn page_down(&mut self, _: &PageDown, _: &mut Window, cx: &mut Context<Self>) {
626 let n = self.page_lines();
627 self.motion(cx, |b| b.move_vertically(n, false));
628 }
629 fn select_page_up(&mut self, _: &SelectPageUp, _: &mut Window, cx: &mut Context<Self>) {
630 let n = self.page_lines();
631 self.motion(cx, |b| b.move_vertically(-n, true));
632 }
633 fn select_page_down(&mut self, _: &SelectPageDown, _: &mut Window, cx: &mut Context<Self>) {
634 let n = self.page_lines();
635 self.motion(cx, |b| b.move_vertically(n, true));
636 }
637 fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
638 self.motion(cx, CodeBuffer::select_all);
639 }
640
641 fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
643 let text = if self.buffer.selection().is_empty() {
644 format!("{}\n", self.buffer.line(self.buffer.cursor().line))
645 } else {
646 self.buffer.selected_text()
647 };
648 cx.write_to_clipboard(ClipboardItem::new_string(text));
649 }
650
651 fn cut(&mut self, _: &Cut, window: &mut Window, cx: &mut Context<Self>) {
653 if self.read_only {
654 return self.copy(&Copy, window, cx);
655 }
656 if self.buffer.selection().is_empty() {
657 let line = self.buffer.cursor().line;
658 self.buffer.select_line(line);
659 }
660 cx.write_to_clipboard(ClipboardItem::new_string(self.buffer.selected_text()));
661 self.edit(cx, |b| b.insert(""));
662 }
663
664 fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
665 let Some(text) = cx.read_from_clipboard().and_then(|item| item.text()) else {
666 return;
667 };
668 self.edit(cx, |b| b.insert(&text));
669 }
670
671 fn undo_action(&mut self, _: &Undo, _: &mut Window, cx: &mut Context<Self>) {
672 self.undo(cx);
673 }
674 fn redo_action(&mut self, _: &Redo, _: &mut Window, cx: &mut Context<Self>) {
675 self.redo(cx);
676 }
677 fn newline(&mut self, _: &Newline, _: &mut Window, cx: &mut Context<Self>) {
678 self.edit(cx, CodeBuffer::newline);
679 }
680 fn indent(&mut self, _: &Indent, _: &mut Window, cx: &mut Context<Self>) {
681 self.edit(cx, CodeBuffer::indent);
682 }
683 fn outdent(&mut self, _: &Outdent, _: &mut Window, cx: &mut Context<Self>) {
684 self.edit(cx, CodeBuffer::outdent);
685 }
686 fn save(&mut self, _: &Save, _: &mut Window, cx: &mut Context<Self>) {
687 cx.emit(CodeEditorEvent::Save);
688 }
689 fn cancel(&mut self, _: &Cancel, _: &mut Window, cx: &mut Context<Self>) {
690 if self.buffer.selection().is_empty() {
691 cx.emit(CodeEditorEvent::Cancelled);
692 } else {
693 let head = self.buffer.cursor();
694 self.motion(cx, |b| b.set_cursor(head, false));
695 }
696 }
697
698 fn on_mouse_down(
701 &mut self,
702 event: &MouseDownEvent,
703 window: &mut Window,
704 cx: &mut Context<Self>,
705 ) {
706 window.focus(&self.focus_handle);
707 let pos = self.pos_for_point(event.position);
708 self.selecting = true;
709 match event.click_count {
710 2 => self.motion(cx, |b| b.select_word_at(pos)),
711 n if n >= 3 => self.motion(cx, |b| b.select_line(pos.line)),
712 _ => {
713 let shift = event.modifiers.shift;
714 self.motion(cx, |b| b.set_cursor(pos, shift));
715 }
716 }
717 }
718
719 fn on_mouse_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
720 if !self.selecting || event.pressed_button != Some(MouseButton::Left) {
721 return;
722 }
723 let pos = self.pos_for_point(event.position);
724 if pos != self.buffer.cursor() {
725 self.motion(cx, |b| b.set_cursor(pos, true));
726 }
727 }
728
729 fn on_mouse_up(&mut self, _: &MouseUpEvent, _: &mut Window, _: &mut Context<Self>) {
730 self.selecting = false;
731 }
732
733 fn on_scroll_wheel(
734 &mut self,
735 event: &ScrollWheelEvent,
736 _: &mut Window,
737 cx: &mut Context<Self>,
738 ) {
739 let delta = event.delta.pixel_delta(self.line_height());
740 if delta.y != px(0.) && self.scroll.is_scrollable() {
742 cx.stop_propagation();
743 }
744 let dx = delta.x;
745 if dx == px(0.) {
746 return;
747 }
748 cx.stop_propagation();
749 let max = self.max_scroll_x();
750 let next = (self.scroll_x - dx).clamp(px(0.), max);
751 if next != self.scroll_x {
752 self.scroll_x = next;
753 cx.notify();
754 }
755 }
756
757 fn text_width(&self) -> Pixels {
758 self.viewport.map_or(px(0.), |b| b.size.width) - self.gutter_width() - px(TEXT_PAD * 2.)
759 }
760
761 fn max_scroll_x(&self) -> Pixels {
762 let content = self.char_width * (self.buffer.longest_line_len() + 2) as f32;
763 (content - self.text_width()).max(px(0.))
764 }
765
766 fn reveal_caret_x(&mut self) {
769 if !std::mem::take(&mut self.reveal_x) || self.viewport.is_none() {
770 return;
771 }
772 let head = self.buffer.cursor();
773 let chars = self.buffer.line(head.line)[..head.col].chars().count();
774 let x = self.char_width * chars as f32;
775 let width = self.text_width();
776 let margin = self.char_width * 4.;
777 if x < self.scroll_x + margin {
778 self.scroll_x = (x - margin).max(px(0.));
779 } else if x > self.scroll_x + width - margin {
780 self.scroll_x = x - width + margin;
781 }
782 self.scroll_x = self.scroll_x.clamp(px(0.), self.max_scroll_x());
783 }
784
785 fn render_rows(
788 &mut self,
789 range: Range<usize>,
790 window: &mut Window,
791 cx: &mut Context<Self>,
792 ) -> Vec<gpui::AnyElement> {
793 let s = *Theme::of(cx);
794 let lh = self.line_height();
795 let gutter = self.gutter_width();
796 let sel = self.buffer.selection();
797 let sel_range = sel.range();
798 let focused = self.focus_handle.is_focused(window);
799 let since = self.last_input.elapsed().as_secs_f32();
800 let caret_on = focused && (since < 0.5 || ((since / 0.53) as u32).is_multiple_of(2));
801 let scroll_x = self.scroll_x;
802 let base = TextRun {
803 len: 0,
804 font: font(MONO_FONT_FAMILY),
805 color: s.on_surface,
806 background_color: None,
807 underline: None,
808 strikethrough: None,
809 };
810 let selection_color = alpha(s.primary, if focused { 0.28 } else { 0.16 });
811 self.rows.retain(|(line, _)| range.contains(line));
812 let mut out = Vec::with_capacity(range.len());
813 for ix in range {
814 let highlights = self.highlights_for(ix, cx);
815 let text = self.buffer.line(ix);
816 let display: SharedString = if text.contains('\t') {
818 text.replace('\t', " ").into()
819 } else {
820 SharedString::from(text.to_owned())
821 };
822 let marked = self.marked.as_ref().and_then(|m| {
823 (m.start.line <= ix && ix <= m.end.line).then(|| {
824 let start = if m.start.line == ix { m.start.col } else { 0 };
825 let end = if m.end.line == ix {
826 m.end.col
827 } else {
828 text.len()
829 };
830 start..end
831 })
832 });
833 let runs = line_runs(
834 &display,
835 &base,
836 highlights.as_deref().map_or(&[][..], |h| &h[..]),
837 marked,
838 );
839 let shaped = window
840 .text_system()
841 .shape_line(display, self.font_size, &runs, None);
842 let selected = (!sel.is_empty()
843 && sel_range.start.line <= ix
844 && ix <= sel_range.end.line)
845 .then(|| {
846 let start = if sel_range.start.line == ix {
847 shaped.x_for_index(sel_range.start.col)
848 } else {
849 px(0.)
850 };
851 let end = if sel_range.end.line == ix {
852 shaped.x_for_index(sel_range.end.col)
853 } else {
854 shaped.width + self.char_width * 0.6
856 };
857 (start, end)
858 });
859 let caret = (caret_on && sel.head.line == ix).then(|| shaped.x_for_index(sel.head.col));
860 let current = sel.head.line == ix;
861 self.rows.retain(|(line, _)| *line != ix);
862 self.rows.push((ix, shaped.clone()));
863 let primary = s.primary;
864 let paint = canvas(
865 |_, _, _| {},
866 move |bounds, _, window, cx| {
867 let origin = point(bounds.left() + px(TEXT_PAD) - scroll_x, bounds.top());
868 window.with_content_mask(Some(ContentMask { bounds }), |window| {
869 if let Some((a, b)) = selected {
870 window.paint_quad(fill(
871 Bounds::from_corners(
872 point(origin.x + a, bounds.top()),
873 point(origin.x + b, bounds.bottom()),
874 ),
875 selection_color,
876 ));
877 }
878 shaped.paint(origin, lh, window, cx).ok();
879 if let Some(x) = caret {
880 window.paint_quad(fill(
881 Bounds::new(
882 point(origin.x + x - px(1.), bounds.top()),
883 size(px(2.), lh),
884 ),
885 primary,
886 ));
887 }
888 });
889 },
890 )
891 .flex_1()
892 .h_full();
893 let mut row = div()
894 .id(("code-line", ix))
895 .flex()
896 .w_full()
897 .h(lh)
898 .when(current && sel.is_empty(), |d| {
899 d.bg(alpha(s.on_surface, 0.045))
900 });
901 if self.line_numbers {
902 row = row.child(
903 div()
904 .flex_none()
905 .w(gutter)
906 .h_full()
907 .flex()
908 .items_center()
909 .justify_end()
910 .pr(px(12.))
911 .text_size(self.font_size * 0.92)
912 .text_color(if current {
913 s.on_surface_variant
914 } else {
915 alpha(s.outline, 0.8)
916 })
917 .child(SharedString::from((ix + 1).to_string())),
918 );
919 }
920 out.push(row.child(paint).into_any_element());
921 }
922 out
923 }
924}
925
926pub(crate) fn line_runs(
929 text: &str,
930 base: &TextRun,
931 highlights: &[(Range<usize>, HighlightStyle)],
932 marked: Option<Range<usize>>,
933) -> Vec<TextRun> {
934 let len = text.len();
935 let snap = |mut i: usize| {
936 i = i.min(len);
937 while !text.is_char_boundary(i) {
938 i -= 1;
939 }
940 i
941 };
942 let mut cuts = vec![0, len];
943 for (range, _) in highlights {
944 cuts.push(snap(range.start));
945 cuts.push(snap(range.end));
946 }
947 if let Some(m) = &marked {
948 cuts.push(snap(m.start));
949 cuts.push(snap(m.end));
950 }
951 cuts.sort_unstable();
952 cuts.dedup();
953 let mut runs: Vec<TextRun> = Vec::with_capacity(cuts.len());
954 for pair in cuts.windows(2) {
955 let (start, end) = (pair[0], pair[1]);
956 if start == end {
957 continue;
958 }
959 let mut run = TextRun {
960 len: end - start,
961 ..base.clone()
962 };
963 for (range, style) in highlights {
964 if snap(range.start) <= start && end <= snap(range.end) {
965 apply_highlight(&mut run, style);
966 }
967 }
968 if let Some(m) = &marked
969 && snap(m.start) <= start
970 && end <= snap(m.end)
971 {
972 run.underline = Some(UnderlineStyle {
973 color: Some(run.color),
974 thickness: px(1.),
975 wavy: false,
976 });
977 }
978 if let Some(prev) = runs.last_mut()
980 && prev.font == run.font
981 && prev.color == run.color
982 && prev.background_color == run.background_color
983 && prev.underline == run.underline
984 && prev.strikethrough == run.strikethrough
985 {
986 prev.len += run.len;
987 continue;
988 }
989 runs.push(run);
990 }
991 if runs.is_empty() {
992 runs.push(TextRun {
993 len: 0,
994 ..base.clone()
995 });
996 }
997 runs
998}
999
1000fn apply_highlight(run: &mut TextRun, style: &HighlightStyle) {
1001 if let Some(color) = style.color {
1002 run.color = color;
1003 }
1004 if let Some(fade) = style.fade_out {
1005 run.color.a *= 1. - fade.clamp(0., 1.);
1006 }
1007 if let Some(weight) = style.font_weight {
1008 run.font.weight = weight;
1009 }
1010 if let Some(font_style) = style.font_style {
1011 run.font.style = font_style;
1012 }
1013 if let Some(bg) = style.background_color {
1014 run.background_color = Some(bg);
1015 }
1016 if let Some(underline) = style.underline {
1017 run.underline = Some(underline);
1018 }
1019 if let Some(strike) = style.strikethrough {
1020 run.strikethrough = Some(strike);
1021 }
1022}
1023
1024impl EntityInputHandler for CodeEditor {
1025 fn text_for_range(
1026 &mut self,
1027 range_utf16: Range<usize>,
1028 actual_range: &mut Option<Range<usize>>,
1029 _: &mut Window,
1030 _: &mut Context<Self>,
1031 ) -> Option<String> {
1032 let start = self.buffer.pos_of_utf16(range_utf16.start);
1033 let end = self.buffer.pos_of_utf16(range_utf16.end);
1034 actual_range.replace(self.buffer.utf16_of(start)..self.buffer.utf16_of(end));
1035 Some(self.buffer.text_in(start..end))
1036 }
1037
1038 fn selected_text_range(
1039 &mut self,
1040 _: bool,
1041 _: &mut Window,
1042 _: &mut Context<Self>,
1043 ) -> Option<UTF16Selection> {
1044 let sel = self.buffer.selection();
1045 let r = sel.range();
1046 Some(UTF16Selection {
1047 range: self.buffer.utf16_of(r.start)..self.buffer.utf16_of(r.end),
1048 reversed: sel.reversed(),
1049 })
1050 }
1051
1052 fn marked_text_range(&self, _: &mut Window, _: &mut Context<Self>) -> Option<Range<usize>> {
1053 self.marked
1054 .as_ref()
1055 .map(|m| self.buffer.utf16_of(m.start)..self.buffer.utf16_of(m.end))
1056 }
1057
1058 fn unmark_text(&mut self, _: &mut Window, _: &mut Context<Self>) {
1059 self.marked = None;
1060 }
1061
1062 fn replace_text_in_range(
1063 &mut self,
1064 range_utf16: Option<Range<usize>>,
1065 text: &str,
1066 _: &mut Window,
1067 cx: &mut Context<Self>,
1068 ) {
1069 let range = range_utf16
1070 .map(|r| self.buffer.pos_of_utf16(r.start)..self.buffer.pos_of_utf16(r.end))
1071 .or(self.marked.take());
1072 self.marked = None;
1073 match range {
1074 Some(range) => self.edit(cx, |b| b.replace(range, text)),
1075 None => self.edit(cx, |b| b.type_text(text)),
1077 }
1078 }
1079
1080 fn replace_and_mark_text_in_range(
1081 &mut self,
1082 range_utf16: Option<Range<usize>>,
1083 text: &str,
1084 new_selected_range_utf16: Option<Range<usize>>,
1085 _: &mut Window,
1086 cx: &mut Context<Self>,
1087 ) {
1088 if self.read_only {
1089 return;
1090 }
1091 let range = range_utf16
1092 .map(|r| self.buffer.pos_of_utf16(r.start)..self.buffer.pos_of_utf16(r.end))
1093 .or(self.marked.clone())
1094 .unwrap_or_else(|| self.buffer.selection().range());
1095 let start = range.start;
1096 self.edit(cx, |b| b.replace(range, text));
1097 let start_utf16 = self.buffer.utf16_of(start);
1098 let end = self
1099 .buffer
1100 .pos_of_utf16(start_utf16 + text.encode_utf16().count());
1101 self.marked = (!text.is_empty()).then_some(start..end);
1102 if let Some(sel) = new_selected_range_utf16 {
1103 let a = self.buffer.pos_of_utf16(start_utf16 + sel.start);
1104 let b = self.buffer.pos_of_utf16(start_utf16 + sel.end);
1105 self.buffer
1106 .set_selection(BufferSelection { anchor: a, head: b });
1107 }
1108 cx.notify();
1109 }
1110
1111 fn bounds_for_range(
1112 &mut self,
1113 range_utf16: Range<usize>,
1114 bounds: Bounds<Pixels>,
1115 _: &mut Window,
1116 _: &mut Context<Self>,
1117 ) -> Option<Bounds<Pixels>> {
1118 let pos = self.buffer.pos_of_utf16(range_utf16.start);
1119 let lh = self.line_height();
1120 let offset = self.scroll.0.borrow().base_handle.offset();
1121 let x = match self.rows.iter().find(|(l, _)| *l == pos.line) {
1122 Some((_, shaped)) => shaped.x_for_index(pos.col),
1123 None => self.char_width * self.buffer.line(pos.line)[..pos.col].chars().count() as f32,
1124 };
1125 let origin = point(
1126 bounds.left() + self.gutter_width() + px(TEXT_PAD) - self.scroll_x + x,
1127 bounds.top() + offset.y + lh * pos.line as f32,
1128 );
1129 Some(Bounds::new(origin, size(px(2.), lh)))
1130 }
1131
1132 fn character_index_for_point(
1133 &mut self,
1134 point: Point<Pixels>,
1135 _: &mut Window,
1136 _: &mut Context<Self>,
1137 ) -> Option<usize> {
1138 let pos = self.pos_for_point(point);
1139 Some(self.buffer.utf16_of(pos))
1140 }
1141}
1142
1143impl Render for CodeEditor {
1144 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1145 let s = *Theme::of(cx);
1146 let mono = font(MONO_FONT_FAMILY);
1147 let font_id = window.text_system().resolve_font(&mono);
1148 if let Ok(advance) = window.text_system().advance(font_id, self.font_size, 'm') {
1149 self.char_width = advance.width;
1150 }
1151 if self.focus_handle.is_focused(window) {
1152 continuous_at(4., window, cx);
1153 }
1154 self.reveal_caret_x();
1155 let entity = cx.entity();
1156 let focus = self.focus_handle.clone();
1157 let mut list = uniform_list(
1158 ("m3-code-lines", cx.entity_id().as_u64()),
1159 self.buffer.line_count(),
1160 cx.processor(|this, range, window, cx| this.render_rows(range, window, cx)),
1161 )
1162 .track_scroll(self.scroll.clone())
1163 .size_full();
1164 list.style().restrict_scroll_to_axis = Some(true);
1166 div()
1167 .id(("m3-code-editor", cx.entity_id().as_u64()))
1168 .key_context(KEY_CONTEXT)
1169 .track_focus(&self.focus_handle)
1170 .cursor(CursorStyle::IBeam)
1171 .relative()
1172 .size_full()
1173 .overflow_hidden()
1174 .font_family(MONO_FONT_FAMILY)
1175 .text_size(self.font_size)
1176 .text_color(s.on_surface)
1177 .on_action(cx.listener(Self::backspace))
1178 .on_action(cx.listener(Self::delete))
1179 .on_action(cx.listener(Self::delete_word_left))
1180 .on_action(cx.listener(Self::delete_word_right))
1181 .on_action(cx.listener(Self::left))
1182 .on_action(cx.listener(Self::right))
1183 .on_action(cx.listener(Self::up))
1184 .on_action(cx.listener(Self::down))
1185 .on_action(cx.listener(Self::select_left))
1186 .on_action(cx.listener(Self::select_right))
1187 .on_action(cx.listener(Self::select_up))
1188 .on_action(cx.listener(Self::select_down))
1189 .on_action(cx.listener(Self::word_left))
1190 .on_action(cx.listener(Self::word_right))
1191 .on_action(cx.listener(Self::select_word_left))
1192 .on_action(cx.listener(Self::select_word_right))
1193 .on_action(cx.listener(Self::home))
1194 .on_action(cx.listener(Self::end))
1195 .on_action(cx.listener(Self::select_home))
1196 .on_action(cx.listener(Self::select_end))
1197 .on_action(cx.listener(Self::doc_start))
1198 .on_action(cx.listener(Self::doc_end))
1199 .on_action(cx.listener(Self::select_doc_start))
1200 .on_action(cx.listener(Self::select_doc_end))
1201 .on_action(cx.listener(Self::page_up))
1202 .on_action(cx.listener(Self::page_down))
1203 .on_action(cx.listener(Self::select_page_up))
1204 .on_action(cx.listener(Self::select_page_down))
1205 .on_action(cx.listener(Self::select_all))
1206 .on_action(cx.listener(Self::copy))
1207 .on_action(cx.listener(Self::cut))
1208 .on_action(cx.listener(Self::paste))
1209 .on_action(cx.listener(Self::undo_action))
1210 .on_action(cx.listener(Self::redo_action))
1211 .on_action(cx.listener(Self::newline))
1212 .on_action(cx.listener(Self::indent))
1213 .on_action(cx.listener(Self::outdent))
1214 .on_action(cx.listener(Self::save))
1215 .on_action(cx.listener(Self::cancel))
1216 .on_mouse_down(MouseButton::Left, cx.listener(Self::on_mouse_down))
1217 .on_mouse_move(cx.listener(Self::on_mouse_move))
1218 .on_mouse_up(MouseButton::Left, cx.listener(Self::on_mouse_up))
1219 .on_mouse_up_out(MouseButton::Left, cx.listener(Self::on_mouse_up))
1220 .on_scroll_wheel(cx.listener(Self::on_scroll_wheel))
1221 .child(list)
1222 .child(
1223 canvas(
1224 |_, _, _| {},
1225 move |bounds, _, window, cx| {
1226 entity.update(cx, |editor, _| editor.viewport = Some(bounds));
1227 window.handle_input(&focus, ElementInputHandler::new(bounds, entity), cx);
1228 },
1229 )
1230 .absolute()
1231 .top_0()
1232 .left_0()
1233 .size_full(),
1234 )
1235 }
1236}
1237
1238#[cfg(test)]
1239mod tests {
1240 use super::*;
1241 use gpui::{FontWeight, Hsla};
1242
1243 fn base() -> TextRun {
1244 TextRun {
1245 len: 0,
1246 font: font("Mono"),
1247 color: Hsla::default(),
1248 background_color: None,
1249 underline: None,
1250 strikethrough: None,
1251 }
1252 }
1253
1254 #[test]
1255 fn runs_cover_the_line_and_layer_highlights() {
1256 let red = gpui::red();
1257 let bold = HighlightStyle {
1258 font_weight: Some(FontWeight::BOLD),
1259 ..Default::default()
1260 };
1261 let color = HighlightStyle {
1262 color: Some(red),
1263 ..Default::default()
1264 };
1265 let runs = line_runs("let x = 1;", &base(), &[(0..3, color), (0..5, bold)], None);
1266 let lens: Vec<_> = runs.iter().map(|r| r.len).collect();
1267 assert_eq!(lens, vec![3, 2, 5]);
1268 assert_eq!(runs[0].color, red);
1269 assert_eq!(runs[0].font.weight, FontWeight::BOLD);
1270 assert_eq!(runs[1].font.weight, FontWeight::BOLD);
1271 assert_eq!(runs[2].font.weight, base().font.weight);
1272 }
1273
1274 #[test]
1275 fn runs_snap_to_char_boundaries_and_merge_equal_neighbours() {
1276 let style = HighlightStyle {
1277 color: Some(gpui::red()),
1278 ..Default::default()
1279 };
1280 let runs = line_runs("añb", &base(), &[(0..2, style), (40..50, style)], None);
1282 assert_eq!(runs.iter().map(|r| r.len).sum::<usize>(), 4);
1283 assert_eq!(runs.len(), 2);
1284 assert_eq!(runs[0].len, 1);
1285 let plain = line_runs("abc", &base(), &[], None);
1286 assert_eq!(plain.len(), 1);
1287 assert_eq!(plain[0].len, 3);
1288 }
1289
1290 #[test]
1291 fn marked_text_is_underlined() {
1292 let runs = line_runs("abcd", &base(), &[], Some(1..3));
1293 assert_eq!(runs.len(), 3);
1294 assert!(runs[1].underline.is_some());
1295 assert!(runs[0].underline.is_none());
1296 }
1297
1298 #[test]
1299 fn selection_label_cites_lines() {
1300 let one = CodeSelection {
1301 path: Some("src/a.rs".into()),
1302 lines: 3..=3,
1303 text: String::new(),
1304 };
1305 assert_eq!(one.label(), "src/a.rs:3");
1306 let many = CodeSelection {
1307 path: None,
1308 lines: 3..=9,
1309 text: "x".into(),
1310 };
1311 assert_eq!(many.label(), "untitled:3-9");
1312 }
1313}