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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
//! The editing surface.
//!
//! The document is the single source of truth. There is no `TextField` per
//! block: a selection is a pair of `Cursor`s into one `Doc`, which is what
//! makes Enter split, Backspace merge and Tab indent into list operations
//! rather than negotiations between separate widgets each owning a string.
//!
//! Everything about *what* an edit does lives in `markdown` — `edit` and
//! `select` — and is tested there without a window. This crate owns only what
//! needs one: a focus handle, key bindings, the platform input handler, and
//! turning a click into a position.
use gpui::{
App, Context, CursorStyle, ElementInputHandler, EventEmitter, FocusHandle, Focusable,
KeyContext, MouseButton, Render, Styled as _, Task, Window, canvas, div, prelude::*,
};
use markdown::{
Annotation, Block, BlockKind, BlockLayouts, Cursor, Doc, Form, Mark, Part, Selection, Splice,
Text, edit, edit::shortcut,
};
use motion::Painter;
use std::{ops::Range, time::Duration};
use theme::Theme;
use crate::{
comment::{Anchor, CommentId, Delta},
history::{EditKind, History},
layout::Layout,
link::{self, Choice},
slash::Slash,
text_size::{self, TextSize},
};
pub(crate) mod image;
mod input;
mod keys;
pub(crate) mod menu;
pub use keys::init;
use keys::{
Backspace, Copy, Cut, DecreaseTextSize, Delete, DeleteToHome, DeleteWordLeft, DeleteWordRight,
Dismiss, Down, DuplicateBlock, End, Home, IncreaseTextSize, Indent, KillLine, Left,
MoveBlockDown, MoveBlockUp, Outdent, Paste, Redo, RemoveBlock, ResetTextSize, Right, SelectAll,
SelectDown, SelectEnd, SelectHome, SelectLeft, SelectRight, SelectUp, SelectWordLeft,
SelectWordRight, SplitBlock, ToggleBold, ToggleCode, ToggleItalic, ToggleStrike, Undo, Up,
WordLeft, WordRight,
};
const CONTEXT: &str = "BezelEditor";
/// [`CONTEXT`], which every binding in [`keys`] is scoped to, plus the mark
/// that keeps `tab` for [`Editor::indent`].
fn key_context() -> KeyContext {
let mut context = KeyContext::default();
context.add(CONTEXT);
context.add(ui::focus::CLAIMS_TAB);
context
}
/// What the editor tells its host about.
///
/// An app holding comment threads has to hear that the document moved, or its
/// side of the pairing goes stale against anchors that did not. Split the way
/// [`ui::input::FieldEvent`] is, so a listener takes only the half it needs.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EditorEvent {
/// The document is different, and the anchors have been mapped through it.
Changed,
/// A click landed on a comment's range.
CommentActivated(CommentId),
}
/// Shown on the focused block while it is empty — the only discoverable place
/// to say that `/` does anything.
const PLACEHOLDER: &str = "Type / for commands";
/// Half the caret's blink period — `ui::TextField`'s, which is the 500ms on,
/// 500ms off macOS itself uses.
const BLINK: Duration = Duration::from_millis(500);
/// The handle's box. Wide enough to be hit without crowding the margin; how
/// far left of the text it sits is [`Layout::text_inset`](crate::Layout).
const HANDLE_SIZE: f32 = 18.0;
/// How far a drag on an image's edge handle can shrink it — matches
/// `markdown::render`'s `TABLE_MIN_COLUMN_WIDTH`, the same floor for the
/// other block content a drag can resize.
const MIN_IMAGE_WIDTH: f32 = 96.0;
/// Whether a selection is prose covering more than one line — two blocks, or
/// one line break inside a single block.
///
/// What a chord means about a selection is the editor's to decide; a [`Doc`]
/// has no opinion about it. A selection reaching into a table or a fence is not
/// prose and keeps the inline behaviour, because half a table has no lines to
/// make a fence out of.
fn fenceable(doc: &Doc, selection: Selection) -> bool {
let spans = doc.spans(selection);
let covered = |at: &Cursor, range: &Range<usize>| {
doc.blocks[at.block]
.text_at(at.part)
.and_then(|text| text.text.get(range.clone()))
};
spans.iter().all(|(at, _)| at.part == Part::Body)
&& (spans.len() > 1
|| spans
.iter()
.any(|(at, range)| covered(at, range).is_some_and(|text| text.contains('\n'))))
}
/// Give an empty document a block to hold a caret, and say whether one was
/// needed.
///
/// A [`Doc`] with no blocks is a legitimate document — it is what `parse("")`
/// returns — but it is not something that can be edited: nothing paints, so
/// there is no caret and no placeholder, and neither a click nor a hit test
/// has a target to find. An empty file would sit inert until something typed
/// a block into existence, which is the one thing you cannot do with no caret.
fn ensure_block(doc: &mut Doc) -> bool {
if !doc.blocks.is_empty() {
return false;
}
doc.blocks
.push(Block::new(BlockKind::Paragraph(Text::default())));
true
}
/// One of the two floating menus a block drops — the block it belongs to and
/// where it hangs. A `Popup` rather than an `Option` for the exit phase, and
/// for the press note: the card's `on_mouse_down_out` fires on the *press*, so
/// without one a trigger's click on the *release* reopens what it just shut.
pub(crate) type MenuPopup = ui::popover::Popup<(usize, gpui::Point<gpui::Pixels>)>;
pub struct Editor {
doc: Doc,
/// Collapsed for an ordinary caret, so there is one position here rather
/// than a caret and a range that can disagree.
selection: Selection,
focus_handle: FocusHandle,
/// The IME composition range within the caret's text, underlined while it
/// is being composed.
marked: Option<Range<usize>>,
/// Where each text landed last frame, so a click can be turned into a
/// caret. Only paint knows this, so the renderer fills it.
layouts: BlockLayouts,
history: History,
/// Which half of the blink the caret is in. Flipped by [`Self::start_blink`].
caret_on: bool,
/// The blink, alive only while the document holds focus.
blink: Option<Task<()>>,
/// Comment ranges, mapped through every edit and snapshotted with the
/// document. Here rather than in the app because an undo restores a whole
/// document and leaves no delta an app could map its own copy through.
anchors: Vec<Anchor>,
/// Marks the next typed character will carry — cmd-B at a collapsed caret,
/// which otherwise has no range to apply to and so would do nothing.
/// Cleared by any motion, because they belong to a spot and not to a mood.
stored: Vec<Mark>,
/// The open slash menu, if `/` started one.
slash: Option<Slash>,
/// The open paste menu, if a URL landed in a block of its own.
pasted: Option<link::Paste>,
/// The open prompt, if an image is waiting to be told where to look.
url_prompt: Option<image::Prompt>,
/// The block a file being dragged over the document would land after.
dropping: Option<usize>,
/// The block the pointer is over, which is the only one showing a handle.
hovered: Option<usize>,
/// A block being dragged by its handle, and where it would land.
lifted: Option<(usize, usize)>,
/// An image being dragged wider or narrower by its edge handle, and the
/// width it holds now — `None` being the natural one, exactly as the
/// document spells it. The document only learns the final width on
/// release, the same reason `lifted` waits for the drop; carrying the
/// document's own value here is what makes a press that never moved
/// read back as no change at all.
resizing: Option<(usize, Option<u32>)>,
/// The block menu the handle opened, and where to anchor it.
block_menu: MenuPopup,
/// The language menu a fence's header opened, and the block it belongs to.
language_menu: MenuPopup,
/// Set by a floating layer's press — the gutter handle, the URL prompt —
/// so the editor's own press does not undo what that press just did.
press_claimed: bool,
/// Where the editor's own box starts, so a position recorded in window
/// coordinates can be placed inside it, and how far it reaches — which is
/// how wide a resized image is allowed to be. Its own box rather than the
/// picture's: a picture already narrowed would otherwise be its own
/// ceiling, and no drag could ever widen it again.
origin: gpui::Point<gpui::Pixels>,
width: gpui::Pixels,
/// Whether the pointer is dragging out a selection.
dragging: bool,
/// Whether the pointer is over painted text, which is the only place the
/// editor claims an I-beam.
over_text: bool,
/// The host's scroll box, when it gave one, and whether the caret still
/// owes it a reveal.
scroll: Option<gpui::ScrollHandle>,
reveal: bool,
/// Where the gutter handle was placed this frame, so the frame after can
/// tell whether the block moved out from under it.
handle_at: Option<gpui::Point<gpui::Pixels>>,
/// The point vertical motion is trying to keep. Held across a run of
/// up/down so walking through a short line and out the other side returns
/// to the column you started in, and dropped by anything horizontal —
/// which is every other way the caret moves.
///
/// The *row* is held as well as the column because an offset at a soft
/// wrap belongs to two rows and answers with the first, so a caret that
/// derived its own row would step down into the same one forever.
goal: Option<gpui::Point<gpui::Pixels>>,
/// The size the app set this document in, in points, or `None` to follow
/// the app's own text size. Absolute rather than a factor over the ladder,
/// so moving the interface size leaves a document set to 16pt at 16pt.
///
/// What the chords move is the shared adjustment on top of this; the base
/// itself is the app's alone.
text_size: Option<f32>,
}
impl Editor {
pub fn new(source: &str, cx: &mut Context<Self>) -> Self {
let mut doc = markdown::parse(source);
ensure_block(&mut doc);
Self {
// Clamped, not defaulted: a document opening on a fence or a table
// has no body at block zero, and a caret claiming one resolves
// against nothing until something moves it.
selection: Selection::at(Cursor::default().clamp(&doc)),
doc,
focus_handle: cx.focus_handle(),
marked: None,
layouts: BlockLayouts::default(),
history: History::default(),
caret_on: true,
blink: None,
anchors: Vec::new(),
stored: Vec::new(),
slash: None,
pasted: None,
url_prompt: None,
dropping: None,
hovered: None,
lifted: None,
resizing: None,
block_menu: MenuPopup::default(),
language_menu: MenuPopup::default(),
press_claimed: false,
origin: gpui::Point::default(),
width: gpui::Pixels::ZERO,
dragging: false,
over_text: false,
scroll: None,
reveal: false,
goal: None,
handle_at: None,
text_size: None,
}
}
/// How many undo steps to keep. App-wide configuration would be a gpui
/// global alongside [`init`], not a `Theme` field — the theme is rebuilt on
/// every light/dark switch, which would quietly reset anything behavioural
/// parked in it.
pub fn with_undo_limit(mut self, limit: usize) -> Self {
self.history = History::with_limit(limit);
self
}
/// Open the document at a size of its own, in points — the app's settings
/// field for prose. Unset, it is set at the app's own text size.
///
/// The base, not the current size: `cmd-+` moves a shared adjustment over
/// this, and `cmd-0` clears that adjustment to come back here.
pub fn with_text_size(mut self, points: f32) -> Self {
self.text_size = Some(points);
self
}
/// The base the app set, if any. Add
/// [`text_size_adjustment`](crate::text_size_adjustment) for what is on
/// screen.
pub fn text_size(&self) -> Option<f32> {
self.text_size
}
/// The box the document scrolls in, so typing off the bottom follows the
/// caret down.
///
/// The host's rather than the editor's: a document goes in whatever pane
/// the app gives it, and the gutter handle, the drop indicator and the
/// menus are all placed absolutely against this editor's own origin — put
/// the scroll box here and every one of them would be offset twice.
pub fn with_scroll(mut self, handle: gpui::ScrollHandle) -> Self {
self.scroll = Some(handle);
self
}
/// Bring the caret back into view.
///
/// Read *after* paint, because a block that has only just appeared — the
/// one Enter made — has no position recorded until it has painted once,
/// which is exactly the case worth scrolling for.
/// Ask for another frame when the block the handle sits on has moved.
///
/// The handle is built from the records of the frame *before* this one —
/// the document fills them as it paints, which is after the editor has
/// finished building its tree — so a block that has just been indented, or
/// grown a line, leaves the handle behind. Reading the records back here,
/// once the document has painted, is what turns that into one late frame
/// instead of a handle stranded until the caret blink happens to draw
/// again.
fn settle_handle(&mut self, window: &Window, cx: &mut Context<Self>) {
let focused = self.focus_handle.is_focused(window);
let now = self
.handle_block(focused)
.and_then(|ix| self.handle_origin(ix, cx));
if now != self.handle_at {
// Not `notify`: this runs *during* the draw, and the dirty flag it
// sets is cleared when that draw finishes. Asking for the next
// frame is what survives it.
window.request_animation_frame();
}
}
fn reveal_caret(&mut self, cx: &mut Context<Self>) {
if !self.reveal {
return;
}
let Some(scroll) = self.scroll.clone() else {
self.reveal = false;
return;
};
// Left set when the caret has not painted: a block with no text at all
// never answers, and the next move is what gets it back.
let Some((at, line)) = self.layouts.position(self.selection.head) else {
return;
};
self.reveal = false;
let view = scroll.bounds();
let offset = scroll.offset();
let mut y = offset.y;
if at.y < view.top() {
y += view.top() - at.y;
} else if at.y + line > view.bottom() {
y -= at.y + line - view.bottom();
}
// `set_offset` clamps nothing, and past the ends the document would
// scroll away from the caret it was asked to show.
let y = y.clamp(-scroll.max_offset().y, gpui::px(0.0));
if y != offset.y {
scroll.set_offset(gpui::point(offset.x, y));
cx.notify();
}
}
pub fn doc(&self) -> &Doc {
&self.doc
}
pub fn selection(&self) -> Selection {
self.selection
}
/// Put the selection somewhere — what a thread in a sidebar does when it is
/// clicked, and what a caret restored with a document needs.
///
/// Clamped, because the caller's range came from somewhere the document may
/// have moved on from.
pub fn select(&mut self, selection: Selection, cx: &mut Context<Self>) {
self.selection = selection.clamp(&self.doc);
self.history.interrupt();
self.reveal = true;
self.caret_moved();
cx.notify();
}
/// Where the selection sits on screen, in window coordinates, so a host can
/// float a toolbar at it.
///
/// The head's row only — a selection spanning ten blocks wants its bubble
/// where the pointer left off, not centred over the whole span. `None` when
/// nothing is selected or the caret has not painted yet.
pub fn selection_bounds(&self) -> Option<gpui::Bounds<gpui::Pixels>> {
if self.selection.is_collapsed() {
return None;
}
let (point, line_height) = self.layouts.position(self.selection.head)?;
Some(gpui::Bounds::new(
point,
gpui::size(gpui::px(0.0), line_height),
))
}
/// The comment ranges, mapped up to date with the document.
///
/// A range that reads [`Anchor::detached`] lost the words it pointed at.
/// It is kept rather than dropped, because whether that means "outdated" or
/// "resolved" is the app's question.
pub fn anchors(&self) -> &[Anchor] {
&self.anchors
}
/// Hand over the whole list — the app keeps the threads, this keeps their
/// ranges. One entry point rather than add/remove/update, since the app is
/// already holding the list that decides all three.
pub fn set_anchors(&mut self, anchors: Vec<Anchor>, cx: &mut Context<Self>) {
self.anchors = anchors;
cx.notify();
}
/// The comment under a point in window coordinates — the space
/// [`Self::anchor_bounds`] answers in and the press handler resolves in.
///
/// The last match wins, so the newer of two overlapping ranges is the one a
/// click opens.
pub fn comment_at(&self, at: gpui::Point<gpui::Pixels>) -> Option<CommentId> {
let at = self.layouts.hit(at)?;
self.anchors
.iter()
.rfind(|anchor| {
let (start, end) = anchor.range.ordered();
!anchor.detached() && start <= at && at <= end
})
.map(|anchor| anchor.id)
}
/// Where to float a thread, mirroring [`Self::selection_bounds`].
pub fn anchor_bounds(&self, id: CommentId) -> Option<gpui::Bounds<gpui::Pixels>> {
let anchor = self.anchors.iter().find(|anchor| anchor.id == id)?;
let (point, line_height) = self.layouts.position(anchor.range.ordered().0)?;
Some(gpui::Bounds::new(
point,
gpui::size(gpui::px(0.0), line_height),
))
}
/// The ranges the renderer washes, clamped because a block can change kind
/// under an anchor and take its part with it.
fn annotations(&self) -> Vec<(Selection, Annotation)> {
self.anchors
.iter()
.filter(|anchor| !anchor.detached())
.map(|anchor| (anchor.range.clamp(&self.doc), anchor.state))
.collect()
}
/// The caret moved: drop the blink so the next render starts a fresh one.
/// Without the reset it would blink through your own typing, which reads as
/// a dropped keystroke.
fn caret_moved(&mut self) {
self.blink = None;
}
/// Blink the caret for as long as the document holds focus.
fn start_blink(&mut self, cx: &mut Context<Self>) {
self.caret_on = true;
self.blink = Some(cx.spawn(async move |editor, cx| {
loop {
cx.background_executor().timer(BLINK).await;
let flipped = editor.update(cx, |editor, cx| {
editor.caret_on = !editor.caret_on;
cx.notify();
});
if flipped.is_err() {
break;
}
}
}));
}
/// Where typing would land — the moving end of the selection.
fn cursor(&self) -> Cursor {
self.selection.head
}
/// Put the caret somewhere, collapsed.
fn place(&mut self, cursor: Cursor) {
self.selection = Selection::at(cursor.clamp(&self.doc));
}
/// Move the head, extending the selection or collapsing it — the one path
/// every motion key takes, so shift is a flag rather than a second handler.
fn moved(
&mut self,
extend: bool,
to: impl FnOnce(Cursor, &Doc) -> Cursor,
cx: &mut Context<Self>,
) {
let head = to(self.selection.head, &self.doc).clamp(&self.doc);
self.head_to(head, extend);
// Every horizontal motion drops the goal; the two vertical ones put it
// back after calling this.
self.goal = None;
cx.notify();
}
/// Delete from the caret to wherever `to` lands — every kill chord, sharing
/// the cursor functions the motion chords use so the two cannot disagree.
///
/// Nothing left to take within the block — the target crossed out of it, or
/// landed on the caret — is the block edge, and `forward` is which edge:
/// [`Self::delete_forward`] joins the next block, [`Self::delete_back`]
/// outdents or strips block syntax before it merges anything. The direction
/// has to be the chord's own, because a target that lands on the caret is
/// the same cursor whichever way it was reaching.
fn delete_to(
&mut self,
forward: bool,
to: impl FnOnce(Cursor, &Doc) -> Cursor,
cx: &mut Context<Self>,
) {
if !self.selection.is_collapsed() {
return self.delete_back(cx);
}
let at = self.cursor();
let target = to(at, &self.doc).clamp(&self.doc);
if target.block != at.block || target.part != at.part || target.offset == at.offset {
return if forward {
self.delete_forward(cx)
} else {
self.delete_back(cx)
};
}
let painter = Painter::of(cx);
self.edit(EditKind::Delete, cx, |this| {
let splice = this
.doc
.replace(Selection::new(target, at), Text::default());
this.selection = Selection::at(splice.caret.clamp(&this.doc));
this.track_slash("", painter);
vec![Delta::Spliced(splice)]
});
}
fn head_to(&mut self, head: Cursor, extend: bool) {
self.selection = if extend {
self.selection.extend_to(head)
} else {
Selection::at(head)
};
// A motion ends the undo group: typing a word, moving away and typing
// again must not undo as one step across two places. It also spends any
// stored mark and any open paste menu, both of which belonged to the
// spot the caret just left.
self.history.interrupt();
self.stored.clear();
self.pasted = None;
self.reveal = true;
self.caret_moved();
}
/// Every mutation goes through here, so none of them can forget to record
/// a step and none of them has to know how steps coalesce.
fn edit(
&mut self,
kind: EditKind,
cx: &mut Context<Self>,
edit: impl FnOnce(&mut Self) -> Vec<Delta>,
) {
// Any edit answers the paste menu by ignoring it — whatever it offered
// was about a block that no longer holds only the link.
self.pasted = None;
self.history
.record(kind, &self.doc, self.selection, &self.anchors);
// A list rather than one: Enter clears a selection *and* splits, and an
// anchor mapped through only half of that lands in the wrong place.
for delta in edit(self) {
for anchor in &mut self.anchors {
anchor.map(&delta);
}
}
// Deleting the last block is the other way to an empty document, and
// the caret belongs at the start of whatever replaces it.
if ensure_block(&mut self.doc) {
self.selection = Selection::at(Cursor::default());
}
self.history.landed(kind, self.selection);
// Typing moves the caret as surely as an arrow key does, and a split
// moves it onto a block that does not exist until this frame paints.
self.reveal = true;
self.caret_moved();
cx.emit(EditorEvent::Changed);
cx.notify();
}
/// Up and down, by one painted row.
///
/// Geometry rather than arithmetic on line numbers, so a wrapped paragraph,
/// a code block's lines and a table's rows are all the same case and none
/// needs counting — but geometry walked in document order rather than
/// hit-tested, which is [`markdown::BlockLayouts::step_row`]'s whole point.
/// Falls back to the block-wise motion off either end of the document, and
/// on the first frame, when nothing has painted to walk.
fn vertical(&mut self, down: bool, extend: bool, cx: &mut Context<Self>) {
// Up and down walk a menu while it is open, not the document.
let delta = if down { 1 } else { -1 };
if let Some(pasted) = &mut self.pasted {
pasted.step(delta);
return cx.notify();
}
if let Some(slash) = &mut self.slash {
slash.step(delta);
return cx.notify();
}
let head = self.selection.head;
let Some((at, _)) = self.layouts.position(head) else {
return self.moved(
extend,
|at, doc| if down { at.down(doc) } else { at.up(doc) },
cx,
);
};
let from = self.goal.unwrap_or(at);
match self.layouts.step_row(head, from, down) {
Some((to, row)) => {
self.head_to(to.clamp(&self.doc), extend);
self.goal = Some(gpui::point(from.x, row));
}
// Off the top is the start of the document and off the bottom is
// its end, which is what every native field does.
None => {
// Except where the end is a block a caret cannot carry on from,
// and going down means the paragraph after it — the one a click
// below the document asks for by the same rule.
if down
&& !extend
&& self.cursor().block + 1 == self.doc.blocks.len()
&& self.append_tail(cx)
{
return;
}
let to = if down {
head.down(&self.doc)
} else {
head.up(&self.doc)
};
self.head_to(to.clamp(&self.doc), extend);
self.goal = Some(from);
}
}
cx.notify();
}
/// The document as markdown — normalized, because that is the form that
/// survives being read back.
pub fn source(&self) -> String {
let mut doc = self.doc.clone();
doc.normalize();
markdown::serialize(&doc)
}
/// 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.
fn insert(&mut self, text: &str, cx: &mut Context<Self>) {
let painter = Painter::of(cx);
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.replace(this.selection, typed);
this.selection = Selection::at(splice.caret.clamp(&this.doc));
this.apply_shortcut();
this.apply_inline_rule();
this.track_slash(text, painter);
vec![Delta::Spliced(splice)]
});
}
/// 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.
fn track_slash(&mut self, typed: &str, painter: Painter) {
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
},
painter,
));
}
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);
}
}
/// 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,
kind: Option<BlockKind>,
cx: &mut Context<Self>,
) -> bool {
let Some(slash) = &self.slash else {
return false;
};
let (at, kind) = (slash.at, kind.or_else(|| slash.choice()));
self.slash = None;
let Some(kind) = kind else {
return false;
};
let caret = self.cursor();
self.edit(EditKind::Structure, cx, |this| {
this.doc
.edit_at(at, |text| text.remove(at.offset..caret.offset));
this.doc.set_kind(at.block, kind);
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,
})]
});
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.
fn apply_inline_rule(&mut self) {
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;
}
let Some(text) = self
.doc
.blocks
.get(at.block)
.and_then(|block| block.text_at(at.part))
else {
return;
};
let Some((open, inner, mark)) = edit::inline_rule(&text.text, at.offset) else {
return;
};
let width = open.len();
self.doc.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));
}
/// 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>) {
// 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.unfence(selection) {
this.selection = Selection::at(head.clamp(&this.doc));
return refenced(&this.doc, head);
}
if fenceable(&this.doc, selection) {
let head = this.doc.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.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 (```` ``` ````).
fn apply_shortcut(&mut self) {
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;
}
let Some(block) = self.doc.blocks.get(at.block) else {
return;
};
let Some(text) = block.text_at(Part::Body) else {
return;
};
// 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 Some((hit, len)) = shortcut(&text.text) else {
return;
};
if at.offset < len {
return;
}
// 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_at(at, |text| text.remove(0..len));
self.doc.set_kind(at.block, hit.apply(Text::default()));
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.history.interrupt();
}
fn backspace(&mut self, _: &Backspace, _: &mut Window, cx: &mut Context<Self>) {
self.delete_back(cx);
}
/// 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.
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
};
let painter = Painter::of(cx);
self.edit(kind, cx, |this| {
let before = this.doc.blocks.len();
let splice = if !this.selection.is_collapsed() {
this.doc.replace(this.selection, Text::default())
} else if at.offset > 0 {
this.doc
.replace(Selection::new(at.left(&this.doc), 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.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("", painter);
vec![Delta::Spliced(splice)]
});
}
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.
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.replace(range, Text::default());
this.selection = Selection::at(splice.caret.clamp(&this.doc));
vec![Delta::Spliced(splice)]
});
}
/// 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.
fn split_block(&mut self, _: &SplitBlock, window: &mut Window, cx: &mut Context<Self>) {
// A menu owns Enter while it is open, or picking a block would also
// split the one it is turning.
if let Some(choice) = self.pasted.as_ref().map(link::Paste::choice) {
return self.confirm_paste(choice, cx);
}
if self.confirm_slash(None, cx) {
return;
}
let at = self.cursor();
match at.part {
Part::Code => return self.insert("\n", cx),
// A cell is one line by definition; Enter has nowhere to put a
// break, so it does nothing rather than something surprising.
Part::Cell { .. } => 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 => {}
}
self.edit(EditKind::Structure, cx, |this| {
let mut deltas = Vec::new();
if !this.selection.is_collapsed() {
let splice = this.doc.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.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
});
}
fn indent(&mut self, _: &Indent, _: &mut Window, cx: &mut Context<Self>) {
self.edit(EditKind::Structure, cx, |this| {
this.doc.indent(this.cursor().block);
vec![]
});
}
fn outdent(&mut self, _: &Outdent, _: &mut Window, cx: &mut Context<Self>) {
self.edit(EditKind::Structure, cx, |this| {
this.doc.outdent(this.cursor().block);
vec![]
});
}
fn increase_text_size(&mut self, _: &IncreaseTextSize, _: &mut Window, cx: &mut Context<Self>) {
self.step_text_size(TextSize::of(cx).step, cx);
}
fn decrease_text_size(&mut self, _: &DecreaseTextSize, _: &mut Window, cx: &mut Context<Self>) {
self.step_text_size(-TextSize::of(cx).step, cx);
}
fn reset_text_size(&mut self, _: &ResetTextSize, _: &mut Window, cx: &mut Context<Self>) {
text_size::reset_text_size(cx);
}
/// 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.
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 = TextSize::of(cx).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.
fn dismiss(&mut self, _: &Dismiss, _: &mut Window, cx: &mut Context<Self>) {
if self.pasted.take().is_none() && self.slash.take().is_none() {
self.selection = Selection::at(self.selection.head);
}
cx.notify();
}
fn select_all(&mut self, _: &SelectAll, _: &mut Window, cx: &mut Context<Self>) {
self.selection = Selection::all(&self.doc);
self.history.interrupt();
cx.notify();
}
/// The selection as markdown — what a copy puts on the clipboard, and what
/// a paste elsewhere reads back.
fn selected_source(&self) -> Option<String> {
(!self.selection.is_collapsed()).then(|| {
let mut slice = self.doc.slice(self.selection);
slice.normalize();
markdown::serialize(&slice)
})
}
fn copy(&mut self, _: &Copy, _: &mut Window, cx: &mut Context<Self>) {
if let Some(source) = self.selected_source() {
cx.write_to_clipboard(gpui::ClipboardItem::new_string(source));
}
}
fn cut(&mut self, _: &Cut, _: &mut Window, cx: &mut Context<Self>) {
let Some(source) = self.selected_source() else {
return;
};
cx.write_to_clipboard(gpui::ClipboardItem::new_string(source));
self.edit(EditKind::Structure, cx, |this| {
let splice = this.doc.replace(this.selection, Text::default());
this.selection = Selection::at(splice.caret.clamp(&this.doc));
vec![Delta::Spliced(splice)]
});
}
/// Markdown in, at the caret. A lone paragraph goes in as inline text with
/// its marks; anything else arrives as blocks.
fn paste(&mut self, _: &Paste, _: &mut Window, cx: &mut Context<Self>) {
let Some(item) = cx.read_from_clipboard() else {
return;
};
// A screenshot before its text, because a clipboard carrying both is
// carrying a file name for the picture — which is not the picture.
for entry in item.entries() {
if let gpui::ClipboardEntry::Image(image) = entry
&& self.paste_image(image, cx)
{
return;
}
}
let Some(source) = item.text() else {
return;
};
let url = source.trim();
if markdown::is_url(url) {
return self.paste_url(url.to_string(), cx);
}
self.edit(EditKind::Structure, cx, |this| {
let removed = this.selection;
let before = this.doc.blocks.len();
let head = this.doc.splice(removed, markdown::parse(&source));
this.selection = Selection::at(head.clamp(&this.doc));
vec![Delta::Spliced(Splice {
removed,
caret: head,
blocks: this.doc.blocks.len() as isize - before as isize,
})]
});
}
/// A URL is never spliced in as a block. It links whatever is selected, or
/// lands as a link where the caret is — and only when the block it landed
/// in held nothing else does it also offer to become a card, which is the
/// one place a card would not eat a sentence.
fn paste_url(&mut self, url: String, cx: &mut Context<Self>) {
// The one paste people expect to *not* overwrite what they chose.
if !self.selection.is_collapsed() {
return self.toggle_mark(Mark::Link(url), cx);
}
// A card needs a block with nothing else in it; a chip needs a body or
// a cell to sit in. A fence holds its URL literally and offers neither.
let at = self.cursor();
let alone = at.part == Part::Body && self.caret_text().is_some_and(Text::is_empty);
self.edit(EditKind::Structure, cx, |this| {
let splice = this.doc.replace(this.selection, Text::link(&url));
this.selection = Selection::at(splice.caret.clamp(&this.doc));
vec![Delta::Spliced(splice)]
});
// A fence holds its URL literally and a caption cannot spell a mark, so
// neither has a richer form to offer.
if !matches!(at.part, Part::Code | Part::Caption) {
self.pasted = Some(link::Paste::open(at, url, alone));
cx.notify();
}
}
/// Answer the paste menu: leave the link, or turn its block into a card or
/// the picture it points at.
pub(super) fn confirm_paste(&mut self, choice: Choice, cx: &mut Context<Self>) {
let Some(pasted) = self.pasted.take() else {
return;
};
let ix = pasted.at.block;
let card = |url, form| BlockKind::Bookmark { url, form };
match choice {
Choice::Dismiss => cx.notify(),
// A chip with a line to itself is a block, which is what gives it
// room for a favicon; inside a sentence it is a mark over the text
// that is already there, and only the spelling changes.
Choice::Chip if pasted.alone => self.turn_into(ix, card(pasted.url, Form::Chip), cx),
Choice::Chip => self.edit(EditKind::Structure, cx, |this| {
let end = Cursor {
offset: pasted.at.offset + pasted.url.len(),
..pasted.at
};
let text = Text {
text: pasted.url.clone(),
marks: vec![markdown::MarkSpan {
range: 0..pasted.url.len(),
mark: Mark::Mention {
url: pasted.url,
form: markdown::Form::Chip,
},
}],
};
let splice = this.doc.replace(Selection::new(pasted.at, end), text);
this.selection = Selection::at(splice.caret.clamp(&this.doc));
vec![Delta::Spliced(splice)]
}),
Choice::Bookmark => self.turn_into(ix, card(pasted.url, Form::Auto), cx),
Choice::Embed => self.turn_into(ix, card(pasted.url, Form::Embed), cx),
Choice::Image => self.turn_into(
ix,
BlockKind::Image {
url: pasted.url,
alt: Text::default(),
width: None,
},
cx,
),
}
}
/// Give a block over to the link it holds — a card, or the picture it
/// points at.
///
/// One step, not two: turning the block and giving the caret somewhere to
/// go are one gesture, and undo has to agree.
fn turn_into(&mut self, ix: usize, kind: BlockKind, cx: &mut Context<Self>) {
self.edit(EditKind::Structure, cx, |this| {
// The URL is the block's whole text and the new block shows it
// already, so [`Doc::set_kind`] is given nothing to carry across —
// otherwise a picture prints its own URL as its caption.
let held = this.doc.blocks[ix]
.text_at(Part::Body)
.map_or(0, |text| text.text.len());
this.doc.edit_at(Cursor::new(ix, Part::Body, 0), |text| {
*text = Text::default()
});
this.doc.set_kind(ix, kind);
// A caret goes where the block admits one, and otherwise carries on
// in the block after it — a fresh one when it ends the document.
let part = this.doc.blocks[ix].parts().first().copied();
let at = match part {
Some(part) => Cursor::new(ix, part, 0),
None => {
if this.doc.blocks.len() <= ix + 1 {
this.doc
.blocks
.push(markdown::Block::new(BlockKind::Paragraph(Text::default())));
}
Cursor::new(ix + 1, Part::Body, 0)
}
};
this.selection = Selection::at(at.clamp(&this.doc));
vec![Delta::Spliced(Splice {
removed: Selection::new(
Cursor::new(ix, Part::Body, 0),
Cursor::new(ix, Part::Body, held),
),
caret: Cursor::new(ix, Part::Body, 0),
blocks: 0,
})]
});
}
fn undo(&mut self, _: &Undo, _: &mut Window, cx: &mut Context<Self>) {
if let Some(step) = self.history.undo(&self.doc, self.selection, &self.anchors) {
self.restore(step, cx);
}
}
fn redo(&mut self, _: &Redo, _: &mut Window, cx: &mut Context<Self>) {
if let Some(step) = self.history.redo(&self.doc, self.selection, &self.anchors) {
self.restore(step, cx);
}
}
/// Put a whole moment back — document, caret and anchors together.
///
/// The anchors come from the snapshot rather than from mapping, because a
/// step back is not an edit: there is no delta between here and a document
/// two hundred keystrokes ago.
fn restore(&mut self, step: crate::history::Step, cx: &mut Context<Self>) {
self.doc = step.doc;
self.selection = step.selection.clamp(&self.doc);
self.anchors = step.anchors;
cx.emit(EditorEvent::Changed);
cx.notify();
}
/// Move the caret's block, children and all, and follow it.
///
/// Public because a gutter handle and a menu row reach the same operation
/// as the key does — one vocabulary, not three paths into [`Doc`].
pub fn move_block(&mut self, ix: usize, delta: isize, cx: &mut Context<Self>) {
self.edit(EditKind::Structure, cx, |this| {
let caret = this.cursor();
let at = this.doc.subtree(ix);
let Some(to) = this.doc.move_block(ix, delta) else {
return vec![];
};
// The caret rides along, keeping its depth within the subtree
// that moved and its offset within its own text.
let block = to + caret.block.saturating_sub(ix);
this.selection = Selection::at(Cursor { block, ..caret }.clamp(&this.doc));
vec![Delta::Moved { at, to: Some(to) }]
});
}
pub fn duplicate_block(&mut self, ix: usize, cx: &mut Context<Self>) {
self.edit(EditKind::Structure, cx, |this| {
let span = this.doc.subtree(ix);
let Some(copy) = this.doc.duplicate(ix) else {
return vec![];
};
this.selection = Selection::at(Cursor::new(copy, Part::Body, 0).clamp(&this.doc));
vec![Delta::Opened {
at: copy,
count: span.len(),
}]
});
}
pub fn remove_block(&mut self, ix: usize, cx: &mut Context<Self>) {
self.edit(EditKind::Structure, cx, |this| {
let at = this.doc.subtree(ix);
this.doc.remove_block(ix);
this.selection =
Selection::at(Cursor::new(ix.saturating_sub(1), Part::Body, 0).clamp(&this.doc));
vec![Delta::Moved { at, to: None }]
});
}
/// Tag a fenced block with the language it holds, or `None` for plain.
pub fn set_language(&mut self, ix: usize, language: Option<String>, cx: &mut Context<Self>) {
self.edit(EditKind::Structure, cx, |this| {
this.doc.set_language(ix, language);
vec![]
});
}
/// Turn the caret's block into `kind` — what the slash menu and the block
/// menu both do.
pub fn set_block(&mut self, ix: usize, kind: BlockKind, cx: &mut Context<Self>) {
self.edit(EditKind::Structure, cx, |this| {
this.doc.set_kind(ix, kind);
this.selection = this.selection.clamp(&this.doc);
vec![]
});
}
/// The paragraph a document ending in a fence, a table, a rule or an image
/// has no other way to grow: a fence swallows Enter, a cell and a caption
/// have nowhere to put one, and a rule holds no caret at all. `false` when
/// the last block ends in a body, which can carry on by itself.
fn append_tail(&mut self, cx: &mut Context<Self>) -> bool {
let Some(last) = self.doc.blocks.len().checked_sub(1) else {
return false;
};
if self.doc.blocks[last].parts().last() == Some(&Part::Body) {
return false;
}
self.edit(EditKind::Structure, cx, |this| {
this.doc
.blocks
.push(markdown::Block::new(BlockKind::Paragraph(Text::default())));
let ix = this.doc.blocks.len() - 1;
this.selection = Selection::at(Cursor::new(ix, Part::Body, 0).clamp(&this.doc));
vec![]
});
true
}
/// A click past the end of the document. Without this the document has no
/// end: the click snaps back into the block above it, and what gets typed
/// lands inside the code the reader was trying to escape.
fn tail_click(&mut self, at: gpui::Point<gpui::Pixels>, cx: &mut Context<Self>) -> bool {
let Some(last) = self.doc.blocks.len().checked_sub(1) else {
return false;
};
let Some(bounds) = self.layouts.block_bounds(last) else {
return false;
};
at.y > bounds.origin.y + bounds.size.height && self.append_tail(cx)
}
/// The caret's text, for the input handler's offset arithmetic.
fn caret_text(&self) -> Option<&Text> {
let at = self.cursor();
self.doc.blocks.get(at.block)?.text_at(at.part)
}
}
impl EventEmitter<EditorEvent> for Editor {}
impl Focusable for Editor {
fn focus_handle(&self, _: &App) -> FocusHandle {
self.focus_handle.clone()
}
}
impl Render for Editor {
fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
let theme = Theme::of(cx).clone();
let layout = Layout::of(cx);
let focused = self.focus_handle.is_focused(window);
// The only place the blink starts: `caret_moved` drops the task, so the
// next render brings it back in phase, lit beat first.
if focused && ui::input::caret_blink(cx) {
if self.blink.is_none() {
self.start_blink(cx);
}
} else {
self.blink = None;
self.caret_on = true;
}
let selection = focused.then_some(self.selection);
// Typed text and IME reach an entity only through an input handler
// registered during *paint*, against the bounds it should be anchored
// to. There is no custom element here to do that from, so a zero-cost
// canvas over the document supplies the paint phase. Without this the
// key bindings still fire and nothing types.
let handle = self.focus_handle.clone();
let entity = cx.entity();
let input = canvas(
|_, _, _| (),
move |bounds, _, window, cx| {
// The gutter handle is placed from positions recorded in window
// coordinates, so the box they have to be measured against is
// taken here — the one place that knows it.
entity.update(cx, |this, _| {
this.origin = bounds.origin;
this.width = bounds.size.width;
});
window.handle_input(
&handle,
ElementInputHandler::new(bounds, entity.clone()),
cx,
);
},
)
.absolute()
.size_full();
// A tab stop, so the editor is reachable the same way every other
// control in the library is.
let handle = self.focus_handle.clone().tab_stop(true);
div()
// Stateful only so the pointer leaving can be heard: `on_hover` is
// what tells the gutter handle to stop pointing at a block the
// pointer left behind.
.id("bezel-editor")
// The mark is what keeps `tab`: without it traversal answers the
// key first and the caret never sees it.
.key_context(key_context())
.track_focus(&handle)
// Tracking focus does not take it. Without this, clicking into the
// document blurs the editor instead of putting a caret in it, and
// the caret vanishes on the first click.
.on_mouse_down(
MouseButton::Left,
cx.listener(|this, event: &gpui::MouseDownEvent, window, cx| {
// The handle's own listener runs first and claims the
// press; without the flag this would close the menu it
// just opened. `ui::popover::Popup` solves it the same way.
if std::mem::take(&mut this.press_claimed) {
return;
}
ui::popover::close_popup(this, cx, |this| &mut this.block_menu);
ui::popover::close_popup(this, cx, |this| &mut this.language_menu);
this.pasted = None;
this.focus_handle.clone().focus(window, cx);
if this.tail_click(event.position, cx) {
return;
}
let Some(hit) = this.layouts.hit(event.position) else {
return cx.notify();
};
this.selection = match event.click_count {
// Shift extends from wherever the anchor already is,
// which is what makes click-then-shift-click a range.
_ if event.modifiers.shift => this.selection.extend_to(hit),
1 => Selection::at(hit),
2 => Selection::new(hit.word_left(&this.doc), hit.word_right(&this.doc)),
_ => Selection::new(hit.home(), hit.end(&this.doc)),
}
.clamp(&this.doc);
this.dragging = event.click_count == 1 && !event.modifiers.shift;
this.history.interrupt();
this.caret_moved();
// Only the editor sees the press, so only the editor can
// say which thread it landed on.
if let Some(id) = this.comment_at(event.position) {
cx.emit(EditorEvent::CommentActivated(id));
}
cx.notify();
}),
)
// The drag has to be tracked from the container rather than from a
// payload: a text selection has nothing to carry, and gpui's drag
// payload is for things being dropped somewhere.
.on_hover(cx.listener(|this, hovered: &bool, _, cx| {
if !*hovered && this.hovered.take().is_some() {
cx.notify();
}
}))
.on_mouse_move(cx.listener(|this, event: &gpui::MouseMoveEvent, _, cx| {
// Ahead of every drag branch below, because the pointer's shape
// is about where it *is* rather than about what it is doing.
let over_text = this.layouts.over_text(event.position);
if over_text != this.over_text {
this.over_text = over_text;
cx.notify();
}
// A lifted block follows the pointer; otherwise the pointer
// only decides which block wears the handle.
if let Some((from, _)) = this.lifted.filter(|_| event.dragging()) {
if let Some(to) = this.layouts.block_at(event.position) {
this.lifted = Some((from, to));
cx.notify();
}
return;
}
// An image being resized follows the pointer the same way — the
// document holds nothing until the handle is released.
if let Some((ix, _)) = this.resizing.filter(|_| event.dragging()) {
if let Some(width) = this.dragged_width(ix, event.position.x) {
this.resizing = Some((ix, Some(width)));
cx.notify();
}
return;
}
if this.dragging && event.dragging() {
if let Some(hit) = this.layouts.hit(event.position) {
this.selection = this.selection.extend_to(hit).clamp(&this.doc);
cx.notify();
}
return;
}
let hovered = this.layouts.block_at(event.position);
if hovered != this.hovered {
this.hovered = hovered;
cx.notify();
}
}))
// Both, because a release can land anywhere on screen and only the
// first fires over the editor. A resize left running would leave
// its stand-in picture painted over the document for good.
.on_mouse_up_out(
MouseButton::Left,
cx.listener(|this, _: &gpui::MouseUpEvent, window, cx| {
this.dragging = false;
this.drop_resize(window, cx);
}),
)
.on_mouse_up(
MouseButton::Left,
cx.listener(|this, event: &gpui::MouseUpEvent, window, cx| {
this.dragging = false;
if this.drop_resize(window, cx) {
return;
}
let Some((from, to)) = this.lifted.take() else {
return;
};
if from == to {
// A press that never moved is a click, and a click on
// the handle is what opens the menu — unless that same
// press is what dismissed it, which the note taken on
// the way down is the only way to tell.
if !this.block_menu.take_press_was_open() {
this.block_menu.open((from, event.position));
}
return cx.notify();
}
this.edit(EditKind::Structure, cx, |this| {
// `move_block` steps one sibling at a time, so a drop
// several blocks away is that many steps. Bounded by
// the block count, which no drag can exceed.
let delta = if to > from { 1 } else { -1 };
let mut at = from;
// Each step is its own move, so each is its own delta —
// folding them into one would have to compose the
// hops, and they are already in order.
let mut deltas = Vec::new();
for _ in 0..this.doc.blocks.len() {
let span = this.doc.subtree(at);
let Some(next) = this.doc.move_block(at, delta) else {
break;
};
deltas.push(Delta::Moved {
at: span,
to: Some(next),
});
at = next;
if (delta > 0 && at >= to) || (delta < 0 && at <= to) {
break;
}
}
this.selection =
Selection::at(Cursor::new(at, Part::Body, 0).clamp(&this.doc));
deltas
});
}),
)
.on_action(cx.listener(Self::backspace))
.on_action(cx.listener(Self::delete))
.on_action(
cx.listener(|this, _: &KillLine, _, cx| this.delete_to(true, Cursor::end, cx)),
)
.on_action(cx.listener(|this, _: &DeleteWordLeft, _, cx| {
this.delete_to(false, Cursor::word_left, cx)
}))
.on_action(cx.listener(|this, _: &DeleteWordRight, _, cx| {
this.delete_to(true, Cursor::word_right, cx)
}))
.on_action(cx.listener(|this, _: &DeleteToHome, _, cx| {
this.delete_to(false, |at, _| at.home(), cx)
}))
.on_action(cx.listener(Self::split_block))
.on_action(cx.listener(Self::indent))
.on_action(cx.listener(Self::increase_text_size))
.on_action(cx.listener(Self::decrease_text_size))
.on_action(cx.listener(Self::reset_text_size))
.on_action(cx.listener(Self::outdent))
.on_action(cx.listener(Self::dismiss))
.on_action(cx.listener(Self::select_all))
.on_action(cx.listener(Self::copy))
.on_action(cx.listener(Self::cut))
.on_action(cx.listener(Self::paste))
.on_action(cx.listener(Self::undo))
.on_action(cx.listener(Self::redo))
.on_action(cx.listener(Self::confirm_url))
.on_action(cx.listener(Self::cancel_url))
// A file crossing the document lights the same indicator a lifted
// block does, so a drop from outside lands where it looks like it
// will.
.on_drag_move(cx.listener(
|this, event: &gpui::DragMoveEvent<gpui::ExternalPaths>, _, cx| {
let over = this.layouts.block_at(event.event.position);
if over != this.dropping {
this.dropping = over;
cx.notify();
}
},
))
.on_drop(
cx.listener(|this, paths: &gpui::ExternalPaths, window, cx| {
this.focus_handle.clone().focus(window, cx);
this.drop_paths(paths, cx);
}),
)
.on_action(cx.listener(|this, _: &ToggleBold, _, cx| this.toggle_mark(Mark::Bold, cx)))
.on_action(
cx.listener(|this, _: &ToggleItalic, _, cx| this.toggle_mark(Mark::Italic, cx)),
)
.on_action(
cx.listener(|this, _: &ToggleStrike, _, cx| this.toggle_mark(Mark::Strike, cx)),
)
.on_action(cx.listener(|this, _: &ToggleCode, _, cx| this.toggle_mark(Mark::Code, cx)))
.on_action(cx.listener(|this, _: &MoveBlockUp, _, cx| {
this.move_block(this.cursor().block, -1, cx)
}))
.on_action(cx.listener(|this, _: &MoveBlockDown, _, cx| {
this.move_block(this.cursor().block, 1, cx)
}))
.on_action(cx.listener(|this, _: &DuplicateBlock, _, cx| {
this.duplicate_block(this.cursor().block, cx)
}))
.on_action(cx.listener(|this, _: &RemoveBlock, _, cx| {
this.remove_block(this.cursor().block, cx)
}))
// Motion is one method with a `Cursor` function and an "extend"
// flag, so a shift variant cannot drift from the key it shadows.
.on_action(cx.listener(|this, _: &Left, _, cx| this.moved(false, Cursor::left, cx)))
.on_action(cx.listener(|this, _: &Right, _, cx| this.moved(false, Cursor::right, cx)))
.on_action(cx.listener(|this, _: &Up, _, cx| this.vertical(false, false, cx)))
.on_action(cx.listener(|this, _: &Down, _, cx| this.vertical(true, false, cx)))
.on_action(
cx.listener(|this, _: &Home, _, cx| this.moved(false, |at, _| at.home(), cx)),
)
.on_action(cx.listener(|this, _: &End, _, cx| this.moved(false, Cursor::end, cx)))
.on_action(
cx.listener(|this, _: &WordLeft, _, cx| this.moved(false, Cursor::word_left, cx)),
)
.on_action(
cx.listener(|this, _: &WordRight, _, cx| this.moved(false, Cursor::word_right, cx)),
)
.on_action(
cx.listener(|this, _: &SelectLeft, _, cx| this.moved(true, Cursor::left, cx)),
)
.on_action(
cx.listener(|this, _: &SelectRight, _, cx| this.moved(true, Cursor::right, cx)),
)
.on_action(cx.listener(|this, _: &SelectUp, _, cx| this.vertical(false, true, cx)))
.on_action(cx.listener(|this, _: &SelectDown, _, cx| this.vertical(true, true, cx)))
.on_action(
cx.listener(|this, _: &SelectHome, _, cx| this.moved(true, |at, _| at.home(), cx)),
)
.on_action(cx.listener(|this, _: &SelectEnd, _, cx| this.moved(true, Cursor::end, cx)))
.on_action(cx.listener(|this, _: &SelectWordLeft, _, cx| {
this.moved(true, Cursor::word_left, cx)
}))
.on_action(cx.listener(|this, _: &SelectWordRight, _, cx| {
this.moved(true, Cursor::word_right, cx)
}))
.w_full()
// Text under the pointer, so the pointer says so — and only there,
// or while a drag is still sweeping one out. The editor's box
// reaches over its gutter, the margin beside a short line, a rule,
// an image and a card, none of which a caret can be put into.
// Where it has nothing to say it stays quiet rather than
// overriding the page with an arrow of its own.
.when(self.over_text || self.dragging, |el| {
el.cursor(CursorStyle::IBeam)
})
// No focus ring. A ring says *widget*, and a document is not one —
// the caret already paints only while focused, so a box around the
// whole page is a second, louder signal for the same fact.
.relative()
.child(input)
// The document is inset by the gutter so the handle has somewhere
// to sit *inside* the editor. Outside it the handle is clipped by
// any scrolling ancestor, and a drag through it never reaches
// `on_mouse_move`, which fires only while this element is the one
// under the pointer.
.child(
div()
.w_full()
.pl(gpui::px(layout.text_inset))
.child(markdown::render_with(
&self.doc,
markdown::Editing {
selection,
caret_on: self.caret_on,
layouts: Some(&self.layouts),
annotations: &self.annotations(),
placeholder: focused.then(|| PLACEHOLDER.into()),
// A caret goes into the caption here, so it is always
// painted — an editor that could hide it would be
// hiding a place you can already be typing.
caption: markdown::Caption::Shown,
// The size is absolute, so the factor the ladder
// is already scaled by comes back out of it —
// otherwise the app's size and this one multiply.
typography: Some(markdown::Typography::of(cx).scaled(
text_size::resolve(self.text_size, cx) / theme::base_text_size(),
)),
},
window,
cx,
)),
)
// Last, so the layouts it reads are this frame's rather than the
// one before — children paint in order.
.child(
canvas(|_, _, _| (), {
let entity = cx.entity();
move |_, _, window, cx| {
entity.update(cx, |this, cx| {
this.reveal_caret(cx);
this.settle_handle(window, cx);
});
}
})
.absolute()
.size(gpui::px(0.0)),
)
.children(self.slash_menu(&theme, cx))
.children(self.paste_menu(&theme, cx))
.children(self.url_prompt(&theme, cx))
.children(self.image_target(cx))
.children(self.resize_preview())
.children(self.handle(focused, &theme, cx))
.children(self.resize_handle(&theme, cx))
.children(self.drop_indicator(&theme))
.children(self.language_chip(&theme, cx))
.children(self.block_menu(&theme, cx))
.children(self.language_menu(&theme, cx))
}
}