editor/editor.rs
1//! The editing surface.
2//!
3//! The document is the single source of truth. There is no `TextField` per
4//! block: a selection is a pair of `Cursor`s into one `Doc`, which is what
5//! makes Enter split, Backspace merge and Tab indent into list operations
6//! rather than negotiations between separate widgets each owning a string.
7//!
8//! Everything about *what* an edit does lives in `markdown` — `edit` and
9//! `select` — and is tested there without a window. This crate owns only what
10//! needs one: a focus handle, key bindings, the platform input handler, and
11//! turning a click into a position.
12
13use gpui::{
14 App, Context, CursorStyle, ElementInputHandler, Entity, EventEmitter, FocusHandle, Focusable,
15 KeyContext, MouseButton, Render, Styled as _, Task, Window, canvas, div, prelude::*,
16};
17use markdown::{
18 Affinity, Annotation, AppExt as _, Block, BlockKind, BlockLayouts, Cursor, Doc, Form, Mark,
19 Part, Selection, Splice, Text, edit, edit::shortcut,
20};
21use std::{ops::Range, time::Duration};
22use theme::Theme;
23
24use crate::{
25 anchor::{Anchor, AnchorId, Delta},
26 document::{Change, Document, DocumentEvent, Tracked},
27 history::{EditKind, Run},
28 link::{self, Choice},
29 slash::{Slash, SlashAction, SlashAt},
30 text_size,
31};
32
33mod anchors;
34mod blocks;
35mod caret;
36mod clipboard;
37pub(crate) mod image;
38mod input;
39pub mod keys;
40pub(crate) mod menu;
41pub(crate) mod mode;
42mod pointer;
43mod render;
44mod sizing;
45mod sync;
46mod table;
47mod typing;
48
49pub use keys::init;
50use keys::{
51 Backspace, Copy, Cut, DecreaseTextSize, Delete, DeleteToHome, DeleteWordLeft, DeleteWordRight,
52 Dismiss, DocumentEnd, DocumentStart, Down, DuplicateBlock, End, Home, IncreaseTextSize, Indent,
53 InsertParagraph, KillLine, Left, MoveBlockDown, MoveBlockUp, Outdent, Paste, Redo, RemoveBlock,
54 ResetTextSize, Right, SelectAll, SelectDocumentEnd, SelectDocumentStart, SelectDown, SelectEnd,
55 SelectHome, SelectLeft, SelectRight, SelectUp, SelectWordLeft, SelectWordRight, SoftBreak,
56 SplitBlock, ToggleBold, ToggleCode, ToggleHighlight, ToggleItalic, ToggleStrike, Undo, Up,
57 WordLeft, WordRight,
58};
59
60pub const CONTEXT: &str = "BezelEditor";
61
62/// The custom mark [`ToggleHighlight`] toggles. It does nothing until the app
63/// registers a mark under this name with [`markdown::AppExt::set_marks`].
64pub const HIGHLIGHT_MARK: &str = "highlight";
65
66/// [`CONTEXT`], which every binding in [`keys`] is scoped to, plus the mark
67/// that keeps `tab` for [`Editor::indent`].
68fn key_context() -> KeyContext {
69 let mut context = KeyContext::default();
70 context.add(CONTEXT);
71 context.add(ui::focus::CLAIMS_TAB);
72 context
73}
74
75/// What the editor tells its host about.
76///
77/// An app holding comment threads has to hear that the document moved, or its
78/// side of the pairing goes stale against anchors that did not. Split the way
79/// [`ui::input::FieldEvent`] is, so a listener takes only the half it needs.
80#[derive(Clone, Copy, Debug, PartialEq)]
81pub enum EditorEvent {
82 /// The document is different, and the anchors have been mapped through it.
83 Changed,
84 /// A click landed on an anchor's range.
85 AnchorActivated(AnchorId),
86 /// The pointer came over an anchor's painted text, or left it: `None`
87 /// over none, and when the pointer leaves the editor.
88 AnchorHovered(Option<AnchorId>),
89 /// The editor switched between the document and its source, which a host
90 /// lighting its own toggle has no other way to hear about — the switch can
91 /// come from an undo as well as from the button.
92 ModeChanged(Mode),
93}
94
95/// Which form the document is being edited in.
96///
97/// The trigger is the app's: a button, a menu row, a chord of its own. What is
98/// here is the switch it calls, because the caret, the undo history and the
99/// focus have to survive it, and only the editor owns all three.
100#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
101pub enum Mode {
102 /// The document as it reads.
103 #[default]
104 Blocks,
105 /// The markdown a save would write, in one editable text.
106 Source,
107}
108
109/// Which of the editor's own affordances are on.
110///
111/// All of them unless an app says otherwise: a document with nothing
112/// discoverable on it is the wrong default for a library. Turning one off is
113/// for an app that puts its own in the same place — a bar with its own block
114/// menu does not want the gutter handle's as well — rather than for trimming.
115#[derive(Clone, Copy, Debug, PartialEq, Eq)]
116pub struct Chrome {
117 /// The gutter handle, the menu it opens, and dragging a block by it.
118 pub handle: bool,
119 /// The `/` menu at an empty block.
120 pub slash: bool,
121 /// A fence's language label, and the picker it opens.
122 pub language: bool,
123 /// The menu a pasted URL drops — leave it, or make a card, a chip or the
124 /// picture it points at.
125 pub paste: bool,
126 /// The mention menus over the app's [`crate::MentionSource`]s. Off by
127 /// default.
128 pub mention: bool,
129}
130
131impl Default for Chrome {
132 fn default() -> Self {
133 Self {
134 handle: true,
135 slash: true,
136 language: true,
137 paste: true,
138 mention: false,
139 }
140 }
141}
142
143/// What a toolbar reads to light itself, in one call.
144///
145/// Every field is a question a bar asks on every frame, and each was a separate
146/// reach into the document before: which marks are lit, what the block is
147/// called, whether cmd-E would fence, and whether any of it applies at all.
148/// Taken together so a bar cannot answer half of them from one frame and half
149/// from the next.
150#[derive(Clone, Debug, PartialEq, Eq)]
151pub struct Formatting {
152 /// Which form the document is in. In [`Mode::Source`] the markup is already
153 /// spelled out, so [`Self::marks`] is empty and a bar has nothing to light.
154 pub mode: Mode,
155 /// The marks the selection carries throughout — and at a collapsed caret,
156 /// the ones the next character typed would carry, cmd-B before typing
157 /// included.
158 pub marks: Vec<Mark>,
159 /// What the caret's block is called in [`turns`], or `None` for a block the
160 /// menu does not offer.
161 pub block: Option<gpui::SharedString>,
162 /// The quote the caret's block sits in — see [`quotes`].
163 pub quote: Option<markdown::Quoted>,
164 /// Whether [`Mark::Code`] here makes a fence out of the selection rather
165 /// than an inline span — the one chord whose meaning changes with what is
166 /// selected, and the one a bar cannot work out for itself.
167 pub fenceable: bool,
168}
169
170/// Every block a block can be turned into, and what each is called — the
171/// vocabulary the slash menu and the block menu both offer, for an app building
172/// a menu of its own. Pair with [`Editor::set_block`], which is what both of
173/// bezel's own menus call.
174pub fn turns() -> Vec<(gpui::SharedString, BlockKind)> {
175 crate::slash::items()
176}
177
178/// Every quote a block can be put in, and what each is called. Pair with
179/// [`Editor::toggle_quote`].
180pub fn quotes() -> Vec<(gpui::SharedString, Option<markdown::QuoteKind>)> {
181 crate::slash::quotes()
182}
183
184/// Shown on the focused block while it is empty — the only discoverable place
185/// to say that `/` does anything.
186const PLACEHOLDER: &str = "Type / for commands";
187
188/// What tab inserts in the source, where there are no blocks to indent. Two
189/// spaces, which is what markdown's own nesting is written in.
190const INDENT: &str = " ";
191
192/// Half the caret's blink period — `ui::TextField`'s, which is the 500ms on,
193/// 500ms off macOS itself uses.
194const BLINK: Duration = Duration::from_millis(500);
195
196/// The handle's box. Wide enough to be hit without crowding the margin; how
197/// far left of the text it sits is [`Layout::text_inset`](crate::Layout).
198const HANDLE_SIZE: f32 = 18.0;
199
200/// How far a drag on an image's edge handle can shrink it — matches
201/// `markdown::render`'s `TABLE_MIN_COLUMN_WIDTH`, the same floor for the
202/// other block content a drag can resize.
203const MIN_IMAGE_WIDTH: f32 = 96.0;
204
205/// Whether a selection is prose covering more than one line — two blocks, or
206/// one line break inside a single block.
207///
208/// What a chord means about a selection is the editor's to decide; a [`Doc`]
209/// has no opinion about it. A selection reaching into a table or a fence is not
210/// prose and keeps the inline behaviour, because half a table has no lines to
211/// make a fence out of.
212fn fenceable(doc: &Doc, selection: Selection) -> bool {
213 let spans = doc.spans(selection);
214 let covered = |at: &Cursor, range: &Range<usize>| {
215 doc.blocks[at.block]
216 .text_at(at.part)
217 .and_then(|text| text.text.get(range.clone()))
218 };
219 spans.iter().all(|(at, _)| at.part == Part::Body)
220 && (spans.len() > 1
221 || spans
222 .iter()
223 .any(|(at, range)| covered(at, range).is_some_and(|text| text.contains('\n'))))
224}
225
226/// Give an empty document a block to hold a caret, and say whether one was
227/// needed.
228///
229/// A [`Doc`] with no blocks is a legitimate document — it is what `parse("")`
230/// returns — but it is not something that can be edited: nothing paints, so
231/// there is no caret and no placeholder, and neither a click nor a hit test
232/// has a target to find. An empty file would sit inert until something typed
233/// a block into existence, which is the one thing you cannot do with no caret.
234pub(crate) fn ensure_block(doc: &mut Doc) -> bool {
235 if !doc.blocks.is_empty() {
236 return false;
237 }
238 doc.blocks
239 .push(Block::new(BlockKind::Paragraph(Text::default())));
240 true
241}
242
243fn line_home(at: Cursor, doc: &Doc) -> Cursor {
244 let Some(text) = doc
245 .blocks
246 .get(at.block)
247 .and_then(|block| block.text_at(at.part))
248 else {
249 return at.home();
250 };
251 Cursor {
252 offset: ui::input::line_start(&text.text, at.offset.min(text.text.len())),
253 ..at
254 }
255}
256
257fn line_end(at: Cursor, doc: &Doc) -> Cursor {
258 let Some(text) = doc
259 .blocks
260 .get(at.block)
261 .and_then(|block| block.text_at(at.part))
262 else {
263 return at.end(doc);
264 };
265 Cursor {
266 offset: ui::input::line_end(&text.text, at.offset.min(text.text.len())),
267 ..at
268 }
269}
270
271/// The document a source view is edited as: one fence holding the markdown.
272///
273/// A fence rather than a paragraph because a fence is the block whose caret
274/// already behaves like a plain text editor's — Enter is a newline, nothing
275/// typed into it is markup, and its lines are laid out one per source line.
276fn source_doc(source: &str) -> Doc {
277 Doc {
278 blocks: vec![Block::new(BlockKind::Code {
279 language: Some(markdown::source::LANGUAGES[0].to_string()),
280 code: Text::plain(source),
281 height: None,
282 })],
283 }
284}
285
286/// A floating menu a block drops. A `Popup` rather than an `Option` for the
287/// exit phase, and for the press note: the card's `on_mouse_down_out` fires on
288/// the *press*, so without one a trigger's click on the *release* reopens what
289/// it just shut.
290pub(crate) type MenuPopup<T> = ui::popover::Popup<Dropped<T>>;
291
292/// What a dropped menu belongs to, where it hangs, and its live row.
293pub(crate) struct Dropped<T> {
294 pub of: T,
295 pub at: gpui::Point<gpui::Pixels>,
296 pub cursor: ui::menu::Cursor,
297}
298
299impl<T> Dropped<T> {
300 pub fn new(of: T, at: gpui::Point<gpui::Pixels>) -> Self {
301 Self {
302 of,
303 at,
304 cursor: ui::menu::Cursor::default(),
305 }
306 }
307}
308
309/// The row, column, or cell whose table menu is open.
310#[derive(Clone, Copy, PartialEq, Eq)]
311pub(crate) enum TableTarget {
312 Row(usize),
313 Column(usize),
314 Cell { row: usize, column: usize },
315}
316
317/// A table's row or column, as [`markdown::Part::Cell`] numbers them.
318#[derive(Clone, Copy, Debug, PartialEq, Eq)]
319pub(crate) enum Line {
320 Row(usize),
321 Column(usize),
322}
323
324/// Where a reveal leaves the caret's row in the scroll box.
325#[derive(Clone, Copy, Debug, PartialEq, Eq)]
326pub(crate) enum Reveal {
327 /// The least scroll that brings the row inside the box.
328 Nearest,
329 /// The row at the box's top edge, or as near it as the document's end
330 /// allows.
331 Top,
332}
333
334pub struct Editor {
335 document: Entity<Document>,
336 /// This editor's snapshot of the document, its form, its marks and its
337 /// anchors: what it edits, handed back to [`Self::document`] after each
338 /// change, and replaced whenever another editor changes the document.
339 doc: Tracked,
340 /// The source view's text and the [`Tracked::revision`] it was built at.
341 /// Read only in [`Mode::Source`].
342 source_view: Option<(u64, markdown::SourceText)>,
343 /// Highlighting the source view's text after an edit. Dropping it cancels.
344 source_spans: Option<Task<()>>,
345 marks: markdown::Marks,
346 /// Which of the editor's own affordances paint. The app's, so one document
347 /// can carry the lot and another none of it.
348 chrome: Chrome,
349 /// In [`Mode::Source`] `doc` is one fenced block holding the markdown, so
350 /// every operation below that is about *blocks* asks [`Editor::blocks`]
351 /// first.
352 mode: Mode,
353 /// Collapsed for an ordinary caret, so there is one position here rather
354 /// than a caret and a range that can disagree.
355 selection: Selection,
356 focus_handle: FocusHandle,
357 /// The IME composition range within the caret's text, underlined while it
358 /// is being composed.
359 marked: Option<Range<usize>>,
360 /// Where each text landed last frame, so a click can be turned into a
361 /// caret. Only paint knows this, so the renderer fills it.
362 layouts: BlockLayouts,
363 run: Run,
364 /// Which half of the blink the caret is in. Flipped by [`Self::start_blink`].
365 caret_on: bool,
366 /// The blink, alive only while the document holds focus.
367 blink: Option<Task<()>>,
368 anchors: Vec<Anchor>,
369 /// Ranges washed for one frame's worth of the app's say — find hits. Not
370 /// mapped through edits and not in the history: the app sets them again.
371 washes: Vec<(Selection, Annotation)>,
372 /// Marks the next typed character will carry — cmd-B at a collapsed caret,
373 /// which otherwise has no range to apply to and so would do nothing.
374 /// Cleared by any motion, because they belong to a spot and not to a mood.
375 stored: Vec<Mark>,
376 /// The open slash menu, if `/` started one.
377 slash: Option<Slash>,
378 mention: Option<crate::mention::MentionMenu>,
379 /// The open paste menu, if a URL landed in a block of its own.
380 pasted: Option<link::Paste>,
381 /// The open prompt, if an image is waiting to be told where to look.
382 url_prompt: Option<image::Prompt>,
383 /// The block a file being dragged over the document would land after.
384 dropping: Option<usize>,
385 /// The block the pointer is over, which is the only one showing a handle.
386 hovered: Option<usize>,
387 /// The table cell the pointer is over, whose row and column show handles.
388 hovered_cell: Option<(usize, Part)>,
389 /// A table row's or column's menu: the table, the line and where it hangs.
390 table_drag: Option<table::TableDrag>,
391 table_dragged: bool,
392 table_menu: MenuPopup<(usize, TableTarget)>,
393 /// The right-click menu on text, with its rows as they stood when it
394 /// opened.
395 text_menu: MenuPopup<Vec<ui::menu::Item>>,
396 /// The right-click menu on a picture.
397 image_menu: MenuPopup<image::ImageTarget>,
398 /// A block being dragged by its handle, and where it would land.
399 lifted: Option<(usize, usize)>,
400 /// An image being dragged wider or narrower by its edge handle, and the
401 /// width it holds now — `None` being the natural one, exactly as the
402 /// document spells it. The document only learns the final width on
403 /// release, the same reason `lifted` waits for the drop; carrying the
404 /// document's own value here is what makes a press that never moved
405 /// read back as no change at all.
406 resizing: Option<(usize, Option<u32>)>,
407 /// A painted block being dragged taller or shorter by its bottom handle.
408 sizing: Option<sizing::Sizing>,
409 /// The block menu the handle opened, over the block and its rows.
410 block_menu: MenuPopup<(usize, crate::slash::Rows)>,
411 /// The language menu a fence's header opened, over its block.
412 language_menu: MenuPopup<usize>,
413 /// Set by a floating layer's press — the gutter handle, the URL prompt —
414 /// so the editor's own press does not undo what that press just did.
415 press_claimed: bool,
416 /// Where the editor's own box starts, so a position recorded in window
417 /// coordinates can be placed inside it, and how far it reaches — which is
418 /// how wide a resized image is allowed to be. Its own box rather than the
419 /// picture's: a picture already narrowed would otherwise be its own
420 /// ceiling, and no drag could ever widen it again.
421 origin: gpui::Point<gpui::Pixels>,
422 width: gpui::Pixels,
423 /// The press being dragged out: what it selects by, and what it selected.
424 dragging: Option<(ui::input::Granularity, Range<Cursor>)>,
425 /// Whether the pointer is over painted text, which is the only place the
426 /// editor claims an I-beam.
427 over_text: bool,
428 /// The anchor whose text the pointer is over — see
429 /// [`EditorEvent::AnchorHovered`].
430 over_anchor: Option<AnchorId>,
431 /// The host's scroll box, when it gave one, and the reveal the caret still
432 /// owes it.
433 scroll: Option<gpui::ScrollHandle>,
434 reveal: Option<Reveal>,
435 /// Where a held drag last was, in window coordinates.
436 drag_at: Option<gpui::Point<gpui::Pixels>>,
437 /// Scrolls [`Self::scroll`] while a drag is held past its top or bottom.
438 edge_scroll: Option<Task<()>>,
439 /// Where the gutter handle was placed this frame, so the frame after can
440 /// tell whether the block moved out from under it.
441 handle_at: Option<gpui::Point<gpui::Pixels>>,
442 /// The column held across consecutive vertical moves.
443 goal: Option<gpui::Pixels>,
444 /// The size the app set this document in, in points, or `None` to follow
445 /// the app's own text size. Absolute rather than a factor over the ladder,
446 /// so moving the interface size leaves a document set to 16pt at 16pt.
447 ///
448 /// What the chords move is the shared adjustment on top of this; the base
449 /// itself is the app's alone.
450 text_size: Option<f32>,
451 /// The directory relative image paths resolve against.
452 base: Option<std::path::PathBuf>,
453 image_overlay: Option<markdown::ImageOverlay>,
454 image_overlay_corner: markdown::ImageOverlayCorner,
455 _document: gpui::Subscription,
456}
457
458impl Editor {
459 /// An editor on a document of its own.
460 pub fn new(source: &str, cx: &mut Context<Self>) -> Self {
461 let document = cx.new(|cx| Document::new(source, cx));
462 Self::for_document(document, cx)
463 }
464
465 /// An editor on `document`, beside any others already on it.
466 pub fn for_document(document: Entity<Document>, cx: &mut Context<Self>) -> Self {
467 let (doc, mode, marks, anchors) = {
468 let document = document.read(cx);
469 (
470 document.doc.clone(),
471 document.mode,
472 document.marks.clone(),
473 document.anchors.clone(),
474 )
475 };
476 let subscription = cx.subscribe(&document, |this, document, event: &DocumentEvent, cx| {
477 if event.by != Some(cx.entity_id()) {
478 this.take_document(&document, &event.change, cx);
479 }
480 });
481 Self {
482 document,
483 marks,
484 // Clamped, not defaulted: a document opening on a fence or a table
485 // has no body at block zero, and a caret claiming one resolves
486 // against nothing until something moves it.
487 selection: Selection::at(Cursor::default().clamp(&doc)),
488 doc,
489 mode,
490 anchors,
491 source_view: None,
492 source_spans: None,
493 chrome: Chrome::default(),
494 focus_handle: cx.focus_handle(),
495 marked: None,
496 layouts: BlockLayouts::default(),
497 run: Run::default(),
498 caret_on: true,
499 blink: None,
500 washes: Vec::new(),
501 stored: Vec::new(),
502 slash: None,
503 mention: None,
504 pasted: None,
505 url_prompt: None,
506 dropping: None,
507 hovered: None,
508 hovered_cell: None,
509 table_menu: Default::default(),
510 text_menu: Default::default(),
511 image_menu: Default::default(),
512 table_drag: None,
513 table_dragged: false,
514 lifted: None,
515 resizing: None,
516 sizing: None,
517 block_menu: MenuPopup::default(),
518 language_menu: MenuPopup::default(),
519 press_claimed: false,
520 origin: gpui::Point::default(),
521 width: gpui::Pixels::ZERO,
522 dragging: None,
523 over_text: false,
524 over_anchor: None,
525 scroll: None,
526 reveal: None,
527 drag_at: None,
528 edge_scroll: None,
529 goal: None,
530 handle_at: None,
531 text_size: None,
532 base: None,
533 image_overlay: None,
534 image_overlay_corner: markdown::ImageOverlayCorner::default(),
535 _document: subscription,
536 }
537 }
538
539 /// The document this editor is a view of.
540 pub fn document(&self) -> &Entity<Document> {
541 &self.document
542 }
543
544 /// Which of the editor's own affordances to paint. See [`Chrome`].
545 pub fn with_chrome(mut self, chrome: Chrome) -> Self {
546 self.chrome = chrome;
547 self
548 }
549
550 /// Adds an app-provided hover control to pictures in rich mode.
551 pub fn with_image_overlay(mut self, overlay: markdown::ImageOverlay) -> Self {
552 self.image_overlay = Some(overlay);
553 self
554 }
555
556 /// Replaces or removes the picture hover control.
557 pub fn set_image_overlay(
558 &mut self,
559 overlay: Option<markdown::ImageOverlay>,
560 cx: &mut Context<Self>,
561 ) {
562 self.image_overlay = overlay;
563 cx.notify();
564 }
565
566 /// Positions picture hover controls; bottom-right by default.
567 pub fn with_image_overlay_corner(mut self, corner: markdown::ImageOverlayCorner) -> Self {
568 self.image_overlay_corner = corner;
569 self
570 }
571
572 /// Repositions the picture hover control.
573 pub fn set_image_overlay_corner(
574 &mut self,
575 corner: markdown::ImageOverlayCorner,
576 cx: &mut Context<Self>,
577 ) {
578 self.image_overlay_corner = corner;
579 cx.notify();
580 }
581
582 /// What is painting now, for an app whose own bar mirrors it.
583 pub fn chrome(&self) -> Chrome {
584 self.chrome
585 }
586
587 /// Open the document at a size of its own, in points — the app's settings
588 /// field for prose. Unset, it is set at the app's own text size.
589 ///
590 /// The base, not the current size: `cmd-+` moves a shared adjustment over
591 /// this, and `cmd-0` clears that adjustment to come back here.
592 pub fn with_text_size(mut self, points: f32) -> Self {
593 self.text_size = Some(points);
594 self
595 }
596
597 /// Update the configured base size without changing the temporary zoom.
598 pub fn set_text_size(&mut self, points: f32, cx: &mut Context<Self>) {
599 if self.text_size != Some(points) {
600 self.text_size = Some(points);
601 cx.notify();
602 }
603 }
604
605 /// The base the app set, if any. Add
606 /// [`crate::AppExt::editor_text_size_adjustment`](crate::AppExt::editor_text_size_adjustment) for what is on
607 /// screen.
608 pub fn text_size(&self) -> Option<f32> {
609 self.text_size
610 }
611
612 /// Resolve relative image paths against `dir` — the document's own folder,
613 /// for a document that keeps its pictures beside it. The stored URL stays
614 /// as written.
615 pub fn with_base(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
616 self.base = Some(dir.into());
617 self
618 }
619
620 /// Change or clear the directory relative image paths resolve against.
621 pub fn set_base(&mut self, dir: Option<std::path::PathBuf>, cx: &mut Context<Self>) {
622 if self.base != dir {
623 self.base = dir;
624 cx.notify();
625 }
626 }
627
628 /// The directory relative image paths resolve against, if one is set.
629 pub fn base(&self) -> Option<&std::path::Path> {
630 self.base.as_deref()
631 }
632
633 /// The box the document scrolls in, so typing off the bottom follows the
634 /// caret down and a drag held past its top or bottom scrolls it.
635 ///
636 /// The host's rather than the editor's: a document goes in whatever pane
637 /// the app gives it, and the gutter handle, the drop indicator and the
638 /// menus are all placed absolutely against this editor's own origin — put
639 /// the scroll box here and every one of them would be offset twice.
640 pub fn with_scroll(mut self, handle: gpui::ScrollHandle) -> Self {
641 self.scroll = Some(handle);
642 self
643 }
644
645 pub fn doc(&self) -> &Doc {
646 &self.doc
647 }
648
649 pub fn selection(&self) -> Selection {
650 self.selection
651 }
652
653 /// Put the selection somewhere — what a thread in a sidebar does when it is
654 /// clicked, and what a caret restored with a document needs.
655 ///
656 /// Clamped, because the caller's range came from somewhere the document may
657 /// have moved on from.
658 pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
659 self.select_revealing(selection, Reveal::Nearest, cx);
660 }
661
662 /// [`Self::select`], scrolling the caret's row to the top of the scroll
663 /// box — what a jump to a heading wants, from either side of it.
664 pub fn select_to_top(&mut self, selection: Selection, cx: &mut Context<Self>) {
665 self.select_revealing(selection, Reveal::Top, cx);
666 }
667
668 fn select_revealing(&mut self, selection: Selection, reveal: Reveal, cx: &mut Context<Self>) {
669 self.selection = selection.clamp(&self.doc);
670 self.run.interrupt();
671 self.reveal = Some(reveal);
672 self.caret_moved();
673 cx.notify();
674 }
675
676 /// Where the selection sits on screen, in window coordinates, so a host can
677 /// float a toolbar at it.
678 ///
679 /// The head's row only — a selection spanning ten blocks wants its bubble
680 /// where the pointer left off, not centred over the whole span. `None` when
681 /// nothing is selected or the caret has not painted yet.
682 /// Where everything landed last frame — blocks, pictures, a fence's
683 /// language label, and the row rects of any range.
684 ///
685 /// Handed out whole rather than a method per question: an app placing
686 /// chrome of its own asks the geometry, and which question it needs is not
687 /// this crate's to guess. See [`markdown::BlockLayouts`].
688 pub fn layouts(&self) -> &BlockLayouts {
689 &self.layouts
690 }
691
692 pub fn selection_bounds(&self) -> Option<gpui::Bounds<gpui::Pixels>> {
693 // The head alone. A bar centred over the whole selection wants
694 // `layouts().rects(selection)`, which is every painted row of it.
695 if self.selection.is_collapsed() {
696 return None;
697 }
698 let (point, line_height) = self
699 .layouts
700 .position(self.selection.head, self.selection.affinity)?;
701 Some(gpui::Bounds::new(
702 point,
703 gpui::size(gpui::px(0.0), line_height),
704 ))
705 }
706}
707
708impl EventEmitter<EditorEvent> for Editor {}
709
710impl Focusable for Editor {
711 fn focus_handle(&self, _: &App) -> FocusHandle {
712 self.focus_handle.clone()
713 }
714}