bezel-editor 0.2.14

A Notion-style block editor for gpui — the editing surface over the markdown document model
Documentation
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
//! Typing, deletion, block splits, indent and text size.

use super::*;
use crate::AppExt as _;

impl Editor {
    /// Replace whatever is selected with `text`, applying a markdown prefix if
    /// one completes.
    ///
    /// Typing, backspace, delete and IME all land here, so none of them has to
    /// ask whether a selection was empty.
    pub(super) fn insert(&mut self, text: &str, cx: &mut Context<Self>) {
        let items = crate::slash::installed(cx);
        let trigger = crate::mention::Installed::source(cx, text);
        self.edit(EditKind::Insert, cx, |this| {
            let mut typed = Text::plain(text);
            // A stored mark applies to what is typed next and to nothing else,
            // so it is spent here.
            for mark in this.stored.drain(..) {
                typed.marks.push(markdown::MarkSpan {
                    range: 0..typed.text.len(),
                    mark,
                });
            }
            let splice = this.doc.edit().replace(this.selection, typed);
            this.selection = Selection::at(splice.caret.clamp(&this.doc));
            let shortcut = this.apply_shortcut();
            let promoted = this.promote_quote_marker();
            let inline = this.apply_inline_rule();
            this.track_slash(text, items);
            this.track_mention(trigger);
            std::iter::once(Delta::Spliced(splice))
                .chain(shortcut)
                .chain(promoted)
                .chain(inline)
                .collect()
        });
    }

    /// Open the menu on a typed `/`, and keep its query in step afterwards.
    ///
    /// The query is the text between the `/` and the caret, so there is no
    /// second field and no focus to hand over — typing filters because typing
    /// is what it already was.
    pub(super) fn track_slash(&mut self, typed: &str, items: Vec<crate::SlashItem>) {
        if !self.chrome.slash {
            return;
        }
        let at = self.cursor();
        let text = self
            .doc
            .blocks
            .get(at.block)
            .and_then(|block| block.text_at(at.part))
            .map(|text| text.text.clone())
            .unwrap_or_default();

        if self.slash.is_none() {
            // Only a `/` that starts a word — a URL's slashes are not commands.
            let opened = at.offset.checked_sub(1).filter(|_| typed == "/");
            let starts_word = opened.is_none_or(|slash| {
                text[..slash]
                    .chars()
                    .next_back()
                    .is_none_or(char::is_whitespace)
            });
            // Only in a body: a fence holds its slash literally, and a caption
            // belongs to a block that is already what it is.
            if let Some(slash) = opened.filter(|_| starts_word && at.part == Part::Body) {
                self.slash = Some(Slash::open(
                    Cursor {
                        offset: slash,
                        ..at
                    },
                    items,
                ));
            }
            return;
        }

        // Anything that leaves the run — a space, a click away, backspacing
        // onto the slash — closes it.
        let Some(query) = self.slash.as_ref().and_then(|slash| slash.query(at, &text)) else {
            self.slash = None;
            return;
        };
        if let Some(slash) = &mut self.slash {
            slash.refilter(&query);
        }
    }

    /// Open the mention menu on `typed`, a trigger just typed, when it starts
    /// a word, and keep its query in step afterwards — [`Self::track_slash`]'s
    /// rules.
    pub(super) fn track_mention(&mut self, typed: Option<(char, crate::MentionSource)>) {
        if !self.chrome.mention {
            return;
        }
        let at = self.cursor();
        let text = self
            .doc
            .blocks
            .get(at.block)
            .and_then(|block| block.text_at(at.part))
            .map(|text| text.text.clone())
            .unwrap_or_default();
        let Some(menu) = &mut self.mention else {
            let opened = typed.and_then(|typed| {
                let sign = at.offset.checked_sub(typed.0.len_utf8())?;
                let starts_word = text[..sign]
                    .chars()
                    .next_back()
                    .is_none_or(char::is_whitespace);
                (starts_word && at.part == Part::Body).then_some((sign, typed))
            });
            if let Some((sign, source)) = opened {
                self.mention = Some(crate::mention::MentionMenu::open(
                    Cursor { offset: sign, ..at },
                    source,
                ));
            }
            return;
        };
        let start = menu.at.offset + menu.trigger.len_utf8();
        let query = (at.block == menu.at.block && at.part == menu.at.part && at.offset >= start)
            .then(|| text.get(start..at.offset))
            .flatten()
            .filter(|query| !query.contains(char::is_whitespace));
        match query {
            Some(query) => menu.set_query(query.to_owned()),
            None => self.mention = None,
        }
    }

    /// Replace the trigger and query with a chip linking the row at `ix`, or the live
    /// one, and a space after it.
    pub(super) fn confirm_mention(&mut self, ix: Option<usize>, cx: &mut Context<Self>) -> bool {
        let Some(menu) = self.mention.take() else {
            return false;
        };
        let Some(row) = menu.row(ix).cloned() else {
            cx.notify();
            return true;
        };
        let (at, caret) = (menu.at, self.cursor());
        let chip = Text {
            text: format!("{} ", row.url),
            marks: vec![markdown::MarkSpan {
                range: 0..row.url.len(),
                mark: markdown::Mark::Mention {
                    url: row.url.clone(),
                    form: markdown::Form::Chip,
                },
            }],
        };
        self.edit(EditKind::Insert, cx, |this| {
            let splice = this.doc.edit().replace(Selection::new(at, caret), chip);
            this.selection = Selection::at(splice.caret.clamp(&this.doc));
            vec![Delta::Spliced(splice)]
        });
        true
    }

    /// Take the highlighted block, replacing the `/query` that summoned it.
    /// Take `kind`, or the highlighted row when the caller names none — Enter
    /// and a click are the same operation with a different source.
    pub(super) fn confirm_slash(
        &mut self,
        path: Option<Vec<usize>>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> bool {
        let Some(slash) = &mut self.slash else {
            return false;
        };
        if path.is_none() && slash.on_group() {
            slash.descend();
            cx.notify();
            return true;
        }
        let Some(path) = path.or_else(|| slash.cursor.path()) else {
            return false;
        };
        let (at, action) = (slash.at, slash.action_at(&path));
        self.slash = None;
        let Some(action) = action else {
            return false;
        };
        let caret = self.cursor();
        self.edit(EditKind::Structure, cx, |this| {
            this.doc
                .edit()
                .edit_at(at, |text| text.remove(at.offset..caret.offset));
            match &action {
                SlashAction::Block(kind) => this.doc.edit().set_kind(at.block, kind.clone()),
                SlashAction::Quote(alert) => this.doc.edit().toggle_quote(at.block, *alert),
                SlashAction::Run(_) => {}
            }
            this.selection =
                Selection::at(Cursor::new(at.block, Part::Body, at.offset).clamp(&this.doc));
            vec![Delta::Spliced(Splice {
                removed: Selection::new(at, caret),
                caret: at,
                blocks: 0,
            })]
        });
        if let SlashAction::Run(run) = action {
            // After this update ends: the app edits this editor.
            let editor = cx.entity().downgrade();
            window.defer(cx, move |window, cx| {
                run(
                    SlashAt {
                        editor,
                        block: at.block,
                    },
                    window,
                    cx,
                )
            });
        }
        true
    }

    /// Collapse `**bold**` into a mark when its closing delimiter is typed.
    ///
    /// Runs after the insertion, on the text as it now stands, so a paste and a
    /// keystroke reach it the same way.
    pub(super) fn apply_inline_rule(&mut self) -> Vec<Delta> {
        let at = self.cursor();
        // Code is literal to its closing fence, and a caption holds no mark a
        // `![...]` could spell.
        if matches!(at.part, Part::Code | Part::Caption) {
            return Vec::new();
        }
        let Some(text) = self
            .doc
            .blocks
            .get(at.block)
            .and_then(|block| block.text_at(at.part))
        else {
            return Vec::new();
        };
        let Some((open, inner, mark)) = edit::inline_rule(&text.text, at.offset) else {
            return Vec::new();
        };
        let width = open.len();
        let (opening, closing) = (open.clone(), inner.end..at.offset);
        self.doc.edit().edit_at(at, |text| {
            // The closing delimiter first — taking the opening one would move
            // every offset after it.
            text.remove(inner.end..at.offset);
            text.remove(open);
            text.toggle(inner.start - width..inner.end - width, mark);
        });
        self.selection =
            Selection::at(Cursor::new(at.block, at.part, at.offset - 2 * width).clamp(&self.doc));
        // In the order the two removals went. The opening delimiter is ahead of
        // the closing one, so taking that one first left its offsets standing.
        vec![Self::taken(at, closing), Self::taken(at, opening)]
    }

    /// Add `mark` over the selection, or take it away if the whole selection
    /// already carries it. Public because a toolbar reaches the same operation
    /// the key does.
    pub fn toggle_mark(&mut self, mark: Mark, cx: &mut Context<Self>) {
        // Nothing in the source is a mark: the markup is already spelled out,
        // and cmd-B over `**bold**` would fence what it reads.
        if !self.blocks() {
            return;
        }
        // A caret inside a fence is enough to leave one, so this is the mark
        // that does not wait for a range: nothing typed into code is markup,
        // which leaves a stored mark there nothing to mean.
        let leaving_code = matches!(mark, Mark::Code) && self.cursor().part == Part::Code;
        // With nothing selected there is no range to mark, so the mark waits
        // for the next character — ProseMirror's stored marks, and the only way
        // cmd-B before typing can mean anything.
        if self.selection.is_collapsed() && !leaving_code {
            match self.stored.iter().position(|stored| *stored == mark) {
                Some(ix) => drop(self.stored.remove(ix)),
                None => self.stored.push(mark),
            }
            return cx.notify();
        }
        let selection = self.selection;
        self.edit(EditKind::Structure, cx, |this| {
            // Code over more than one line is a fence, which is the only shape
            // markdown has for it, and the same key is the way back out.
            let before = this.doc.blocks.len();
            // Fencing and unfencing rebuild the blocks the selection covered,
            // so what sat inside it has no position left to keep.
            let refenced = |doc: &Doc, head: Cursor| {
                vec![Delta::Spliced(Splice {
                    removed: selection,
                    caret: head,
                    blocks: doc.blocks.len() as isize - before as isize,
                })]
            };
            if matches!(mark, Mark::Code) {
                if let Some(head) = this.doc.edit().unfence(selection) {
                    this.selection = Selection::at(head.clamp(&this.doc));
                    return refenced(&this.doc, head);
                }
                if fenceable(&this.doc, selection) {
                    let head = this.doc.edit().fence(selection);
                    this.selection = Selection::at(head.clamp(&this.doc));
                    return refenced(&this.doc, head);
                }
            }
            // A mark is paint over text that does not move.
            this.doc.edit().toggle_mark(selection, mark);
            vec![]
        });
    }

    /// Turn a typed prefix into the block it spells — `## ` into a heading.
    ///
    /// Runs after every insertion rather than only on space, because the
    /// vocabulary includes prefixes that end in one (`- [ ] `) and prefixes
    /// that do not (```` ``` ````).
    pub(super) fn apply_shortcut(&mut self) -> Option<Delta> {
        let at = self.cursor();
        // A prefix is block syntax; inside a code fence or a table cell it is
        // the literal text the author typed.
        if at.part != Part::Body {
            return None;
        }
        // Only a paragraph turns: in a heading or list item the prefix is
        // text. `> ` quotes any block not already in a quote.
        let block = self.doc.blocks.get(at.block)?;
        let text = block.text_at(Part::Body)?;
        // Only from the very start of a block, and only up to the caret: a
        // `- ` typed in the middle of a sentence is a hyphen.
        let (hit, len) = shortcut(&text.text)?;
        let turns = match hit {
            markdown::Shortcut::Quote => block.quote.is_none(),
            _ => matches!(block.kind, BlockKind::Paragraph(_)),
        };
        if !turns || at.offset < len {
            return None;
        }
        // Strip the prefix, then turn the block — the same two steps the slash
        // menu takes, so a `## ` and a menu pick land in one place.
        self.doc.edit().edit_at(at, |text| text.remove(0..len));
        self.doc.edit().apply(at.block, hit);
        self.selection =
            Selection::at(Cursor::new(at.block, Part::Body, at.offset - len).clamp(&self.doc));
        // The transformation is its own step: undo after typing `## Title`
        // should give back the heading, not the paragraph before the hashes.
        self.run.interrupt();
        Some(Self::taken(at, 0..len))
    }

    /// Promote a quote whose block opens with a GFM alert marker into the
    /// alert the parser would have produced from the same markdown.
    ///
    /// The marker line goes the way a block shortcut's prefix does, so what was
    /// written under it stays as the alert's body.
    pub(super) fn promote_quote_marker(&mut self) -> Option<Delta> {
        let at = self.cursor();
        if at.part != Part::Body {
            return None;
        }
        let block = self.doc.blocks.get(at.block)?;
        if block.quote.is_none_or(|quote| quote.alert.is_some()) {
            return None;
        }
        let text = &block.text_at(Part::Body)?.text;
        let first = text.split('\n').next().unwrap_or_default();
        let kind = Self::quote_marker(first)?;
        // The marker line, and the break after it where a body follows.
        let len = first.len() + usize::from(text.len() > first.len());
        self.doc.edit().edit_at(at, |text| text.remove(0..len));
        self.doc.edit().set_alert(at.block, Some(kind));
        self.selection = Selection::at(
            Cursor::new(at.block, Part::Body, at.offset.saturating_sub(len)).clamp(&self.doc),
        );
        self.run.interrupt();
        Some(Self::taken(at, 0..len))
    }

    /// The delta for `range` taken out of the text `at` is in — what an anchor
    /// sitting in that text has to move through.
    pub(super) fn taken(at: Cursor, range: Range<usize>) -> Delta {
        let start = Cursor::new(at.block, at.part, range.start);
        Delta::Spliced(Splice {
            removed: Selection::new(start, Cursor::new(at.block, at.part, range.end)),
            caret: start,
            blocks: 0,
        })
    }

    pub(super) fn backspace(&mut self, _: &Backspace, _: &mut Window, cx: &mut Context<Self>) {
        self.delete_back(cx);
    }

    pub(super) fn quote_marker(text: &str) -> Option<markdown::QuoteKind> {
        [
            markdown::QuoteKind::Note,
            markdown::QuoteKind::Tip,
            markdown::QuoteKind::Important,
            markdown::QuoteKind::Warning,
            markdown::QuoteKind::Caution,
        ]
        .into_iter()
        .find(|kind| text.eq_ignore_ascii_case(kind.marker()))
    }

    /// Delete backwards: the selection if there is one, otherwise the character
    /// before the caret, otherwise whatever the start of a block means.
    ///
    /// The kill chords land here too when they have nothing left to take within
    /// the block, so reaching out of one is decided in a single place.
    pub(super) fn delete_back(&mut self, cx: &mut Context<Self>) {
        let at = self.cursor();
        // Reaching out of a block is structural; taking a character is not.
        let kind = if self.selection.is_collapsed() && at.offset == 0 {
            EditKind::Structure
        } else {
            EditKind::Delete
        };
        self.edit(kind, cx, |this| {
            let before = this.doc.blocks.len();
            let splice = if !this.selection.is_collapsed() {
                this.doc.edit().replace(this.selection, Text::default())
            } else if at.offset > 0 {
                let from = at.left(&this.doc);
                this.doc
                    .edit()
                    .replace(Selection::new(from, at), Text::default())
            } else {
                // `merge_back` outdents, unmarkers, unfences or merges —
                // whichever the block's state calls for — and says where the
                // caret landed.
                match this.doc.edit().merge_back(at) {
                    // The seam between where the caret was and where it landed
                    // is exactly what the merge closed up.
                    Some(head) => Splice {
                        removed: Selection::new(head, at),
                        caret: head,
                        blocks: this.doc.blocks.len() as isize - before as isize,
                    },
                    None => return vec![],
                }
            };
            let head = splice.caret;
            this.selection = Selection::at(head.clamp(&this.doc));
            // Deleting narrows the query too, and backspacing onto the slash
            // itself is what closes the menu.
            this.track_slash("", Vec::new());
            this.track_mention(None);
            vec![Delta::Spliced(splice)]
        });
    }

    pub(super) fn delete(&mut self, _: &Delete, _: &mut Window, cx: &mut Context<Self>) {
        self.delete_forward(cx);
    }

    /// Delete forwards, joining the next block when the caret is at the end of
    /// this one — which is what a kill to the end of a line does there too.
    pub(super) fn delete_forward(&mut self, cx: &mut Context<Self>) {
        self.edit(EditKind::Delete, cx, |this| {
            let at = this.cursor();
            let range = if this.selection.is_collapsed() {
                Selection::new(at, at.right(&this.doc))
            } else {
                this.selection
            };
            let splice = this.doc.edit().replace(range, Text::default());
            this.selection = Selection::at(splice.caret.clamp(&this.doc));
            vec![Delta::Spliced(splice)]
        });
    }

    /// Whether an open menu answered Enter itself.
    ///
    /// Every Enter chord asks first, or picking a block would also edit the one
    /// it is turning — and a chord the menu never sees leaves it open over a
    /// query the caret has walked away from.
    pub(super) fn menu_took_enter(&mut self, window: &mut Window, cx: &mut Context<Self>) -> bool {
        if let Some(pasted) = &self.pasted {
            if let Some(choice) = pasted.choice(None) {
                self.confirm_paste(choice, cx);
            }
            return true;
        }
        if self.dropdown_enter(window, cx) {
            return true;
        }
        if self.mention.is_some() {
            return self.confirm_mention(None, cx);
        }
        self.confirm_slash(None, window, cx)
    }

    /// Enter. In a body it splits the block; in a code fence it is a newline,
    /// which is the whole reason a fence is worth typing into.
    pub(super) fn split_block(
        &mut self,
        _: &SplitBlock,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if self.menu_took_enter(window, cx) {
            return;
        }
        let at = self.cursor();
        match at.part {
            Part::Code => return self.insert("\n", cx),
            // A cell is one line by definition: Enter goes down a row.
            Part::Cell { .. } => {
                self.cell_down(cx);
                return;
            }
            // An image with nothing to show yet is missing one thing, so Enter
            // asks for it rather than carrying on past a blank.
            Part::Caption
                if matches!(
                    self.doc.blocks.get(at.block).map(|block| &block.kind),
                    Some(BlockKind::Image { url, .. }) if url.is_empty()
                ) =>
            {
                return self.prompt_for_url(at.block, window, cx);
            }
            // A caption is one line too, but the block it belongs to is the
            // end of something — so Enter carries on underneath the picture,
            // which is [`Doc::split`]'s answer for a block with no body.
            Part::Caption | Part::Body => {}
        }
        // Enter in an empty block steps out of whatever holds it.
        let empty = self.selection.is_collapsed()
            && at.part == Part::Body
            && self
                .doc
                .blocks
                .get(at.block)
                .and_then(|block| block.text_at(Part::Body))
                .is_some_and(Text::is_empty);
        self.edit(EditKind::Structure, cx, |this| {
            if empty && this.doc.edit().peel(at.block) {
                this.selection = Selection::at(at.clamp(&this.doc));
                return vec![];
            }
            let mut deltas = Vec::new();
            if !this.selection.is_collapsed() {
                let splice = this.doc.edit().replace(this.selection, Text::default());
                this.selection = Selection::at(splice.caret.clamp(&this.doc));
                deltas.push(Delta::Spliced(splice));
            }
            let at = this.cursor();
            let new = this.doc.edit().split(at.block, at.offset);
            this.selection = Selection::at(Cursor::new(new, Part::Body, 0).clamp(&this.doc));
            // What followed the caret moved into a block of its own, which
            // everything below it now sits under.
            deltas.push(Delta::Spliced(Splice {
                removed: Selection::at(at),
                caret: Cursor::new(new, Part::Body, 0),
                blocks: 1,
            }));
            deltas
        });
    }

    /// Shift+Enter. In prose it keeps the caret in the block and inserts a
    /// literal newline; the places markdown itself keeps to one line still do.
    pub(super) fn soft_break(
        &mut self,
        _: &SoftBreak,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if self.menu_took_enter(window, cx) {
            return;
        }
        match self.cursor().part {
            Part::Body | Part::Code => self.insert("\n", cx),
            Part::Caption | Part::Cell { .. } => {}
        }
    }

    /// Ctrl+Enter. Open a plain paragraph after the current block's whole
    /// subtree and leave the current block's text untouched.
    pub(super) fn insert_paragraph(
        &mut self,
        _: &InsertParagraph,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if self.menu_took_enter(window, cx) {
            return;
        }
        if !self.blocks() {
            return;
        }
        self.edit(EditKind::Structure, cx, |this| {
            let at = this.cursor().block;
            let insert_at = this.doc.subtree(at).end;
            let indent = this.doc.blocks.get(at).map_or(0, |block| block.indent);
            this.doc.edit().blocks.insert(
                insert_at,
                Block::at(BlockKind::Paragraph(Text::default()), indent),
            );
            this.doc.edit().repair();
            this.selection = Selection::at(Cursor::new(insert_at, Part::Body, 0).clamp(&this.doc));
            vec![Delta::Opened {
                at: insert_at,
                count: 1,
            }]
        });
    }

    pub(super) fn indent(&mut self, _: &Indent, _: &mut Window, cx: &mut Context<Self>) {
        // In the source there is one block to indent and indenting it would be
        // invisible, so tab is what it is in any text editor: two spaces.
        if !self.blocks() {
            return self.insert(INDENT, cx);
        }
        if self.step_cell(true, cx) {
            return;
        }
        self.edit(EditKind::Structure, cx, |this| {
            let block = this.cursor().block;
            this.doc.edit().indent(block);
            vec![]
        });
    }

    pub(super) fn outdent(&mut self, _: &Outdent, _: &mut Window, cx: &mut Context<Self>) {
        if !self.blocks() {
            return self.unindent(cx);
        }
        if self.step_cell(false, cx) {
            return;
        }
        self.edit(EditKind::Structure, cx, |this| {
            let block = this.cursor().block;
            this.doc.edit().outdent(block);
            vec![]
        });
    }

    pub(super) fn increase_text_size(
        &mut self,
        _: &IncreaseTextSize,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.step_text_size(cx.editor_text_size().step, cx);
    }

    pub(super) fn decrease_text_size(
        &mut self,
        _: &DecreaseTextSize,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.step_text_size(-cx.editor_text_size().step, cx);
    }

    pub(super) fn reset_text_size(
        &mut self,
        _: &ResetTextSize,
        _: &mut Window,
        cx: &mut Context<Self>,
    ) {
        cx.reset_editor_text_size();
    }

    /// Sizing is not an edit: it changes nothing about the document, so it
    /// leaves no undo step and no anchor moves.
    ///
    /// The step is taken against *this* document's size and stored back as the
    /// shared adjustment, so a press at the end of the range banks up nothing
    /// to work back through on the way down.
    pub(super) fn step_text_size(&mut self, by: f32, cx: &mut Context<Self>) {
        let base = self.text_size.unwrap_or_else(theme::base_text_size);
        let next = cx
            .editor_text_size()
            .clamp(text_size::resolve(self.text_size, cx) + by);
        text_size::set_adjustment(next - base, cx);
    }

    /// Escape closes an open menu, and otherwise collapses a selection — the
    /// things there are to back out of, innermost first.
    pub(super) fn dismiss(&mut self, _: &Dismiss, _: &mut Window, cx: &mut Context<Self>) {
        if self.table_drag.take().is_some() {
            self.table_dragged = true;
            cx.notify();
            return;
        }
        if self.pasted.take().is_none()
            && self.slash.take().is_none()
            && self.mention.take().is_none()
            && !self.dropdown_dismiss(cx)
        {
            self.selection = Selection::at(self.selection.head);
        }
        cx.notify();
    }
}