Source file quill_tui.ml
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
open Mosaic
open Quill
type mode = Normal | Editing
type completion = {
prefix : string;
cursor_byte : int;
replace_start_byte : int;
items : string list;
selected : int;
}
type model = {
session : Session.t;
kernel : Kernel.t;
event_queue : Kernel.event Queue.t;
path : string;
focus : int;
mode : mode;
dirty : bool;
footer_msg : footer_msg option;
last_mtime : float;
reload_acc : float;
confirm_quit : bool;
show_help : bool;
clock : float;
viewport_width : int;
viewport_height : int;
edit_cursor : int;
edit_cursor_override : int option;
edit_selection : (int * int) option;
completion_popup_open : bool;
completion : completion option;
}
type msg =
| Focus_next
| Focus_prev
| Execute_focused
| Execute_and_advance
| Execute_all
| Interrupt
| Insert_code_below
| Insert_text_below
| Delete_focused
| Toggle_cell_kind
| Move_up
| Move_down
| Clear_focused
| Clear_all
| Save
| Quit
| Tick of float
| Dismiss_message
| Toggle_help
| Resize of int * int
| Enter_edit
| Exit_edit
| Edit_source of string
| Submit_edit of string
| Edit_cursor_changed of int * (int * int) option
| Trigger_completion
| Next_completion
| Prev_completion
| Accept_completion
| Dismiss_completion
| Deferred_focus_editor
let chrome_bg = Ansi.Color.of_rgb 24 24 30
let accent = Ansi.Color.of_rgb 218 165 80
let accent_dim = Ansi.Color.of_rgb 140 110 60
let border_focused = Ansi.Color.of_rgb 120 120 140
let border_unfocused = Ansi.Color.of_rgb 50 50 58
let label_fg = Ansi.Color.of_rgb 100 100 115
let hint_fg = Ansi.Color.of_rgb 80 80 92
let output_fg = Ansi.Color.of_rgb 170 175 185
let output_dim_fg = Ansi.Color.of_rgb 120 125 135
let warning_fg = Ansi.Color.of_rgb 210 180 100
let error_fg = Ansi.Color.of_rgb 210 100 100
let error_bg = Ansi.Color.of_rgb 50 30 30
let info_fg = Ansi.Color.of_rgb 150 160 175
let overlay_bg = Ansi.Color.of_rgb 12 12 16
let cell_bg_focused = Ansi.Color.of_rgb 30 30 38
let reload_interval = 1.0
let template = "# Untitled\n\n```ocaml\n\n```\n"
let scroll_box_id = "notebook-scroll"
let textarea_id = "cell-editor"
let help_scroll_id = "footer-help-scroll"
let lp n = Toffee.Style.Length_percentage.length (Float.of_int n)
let padding_lrtb ~l ~r ~t ~b =
Toffee.Geometry.Rect.make ~left:(lp l) ~right:(lp r) ~top:(lp t)
~bottom:(lp b)
let read_file path =
let ic = open_in path in
Fun.protect
~finally:(fun () -> close_in ic)
(fun () -> really_input_string ic (in_channel_length ic))
let write_file path content =
let oc = open_out path in
Fun.protect
~finally:(fun () -> close_out oc)
(fun () -> output_string oc content)
let get_mtime path =
try (Unix.stat path).Unix.st_mtime with Unix.Unix_error _ -> 0.
let drain_events event_queue session =
let rec loop session =
match Queue.pop event_queue with
| Kernel.Output { cell_id; output } ->
loop (Session.apply_output cell_id output session)
| Kernel.Finished { cell_id; success } ->
loop (Session.finish_execution cell_id ~success session)
| Kernel.Status_changed _ -> loop session
| exception Queue.Empty -> session
in
loop session
let focused_cell m = Doc.nth m.focus (Session.doc m.session)
let cell_count m = Doc.length (Session.doc m.session)
let char_eq c u = Uchar.equal u (Uchar.of_char c)
let m kind text =
{ m with footer_msg = Some { kind; text; created_at = m.clock } }
let m = { m with footer_msg = None }
let clear_confirm_message m =
match m.footer_msg with
| Some { kind = Confirm; _ } -> clear_footer_message m
| _ -> m
let clamp lo hi x = if x < lo then lo else if x > hi then hi else x
let lowercase_codepoint i =
if i >= Char.code 'A' && i <= Char.code 'Z' then i + 32 else i
let starts_with ~prefix s =
let lp = String.length prefix and ls = String.length s in
lp <= ls && String.sub s 0 lp = prefix
let is_ident_start = function
| 'a' .. 'z' | 'A' .. 'Z' | '_' -> true
| _ -> false
let is_ident_char = function
| 'a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '_' | '\'' -> true
| _ -> false
let unique_sorted strings =
let sorted = List.sort String.compare strings in
let rec dedup acc = function
| a :: (b :: _ as tl) when String.equal a b -> dedup acc tl
| x :: tl -> dedup (x :: acc) tl
| [] -> List.rev acc
in
dedup [] sorted
let collect_identifiers s =
let tbl = Hashtbl.create 64 in
let n = String.length s in
let i = ref 0 in
while !i < n do
if is_ident_start s.[!i] then begin
let j = ref (!i + 1) in
while !j < n && is_ident_char s.[!j] do
incr j
done;
let token = String.sub s !i (!j - !i) in
if String.length token >= 2 then Hashtbl.replace tbl token ();
i := !j
end
else incr i
done;
Hashtbl.fold (fun key () acc -> key :: acc) tbl []
let ocaml_keywords =
[
"and";
"as";
"begin";
"class";
"done";
"else";
"end";
"exception";
"external";
"false";
"for";
"fun";
"function";
"if";
"in";
"include";
"let";
"match";
"module";
"mutable";
"of";
"open";
"rec";
"sig";
"struct";
"then";
"true";
"try";
"type";
"val";
"when";
"with";
]
let take_first n xs =
let rec loop acc n xs =
if n <= 0 then List.rev acc
else
match xs with [] -> List.rev acc | x :: tl -> loop (x :: acc) (n - 1) tl
in
loop [] n xs
let utf8_codepoint_offsets s =
let len = String.length s in
let rec prev_start i =
if i <= 0 then 0
else if Char.code s.[i] land 0xC0 = 0x80 then prev_start (i - 1)
else i
in
let rec loop acc i =
if i <= 0 then Array.of_list (0 :: acc)
else
let j = prev_start (i - 1) in
loop (i :: acc) j
in
loop [] len
let grapheme_byte_offsets s = utf8_codepoint_offsets s
let grapheme_count s =
let offsets = grapheme_byte_offsets s in
Array.length offsets - 1
let cursor_byte_of code cursor =
let offsets = grapheme_byte_offsets code in
let max_cursor = Array.length offsets - 1 in
let cursor = clamp 0 max_cursor cursor in
(cursor, offsets.(cursor))
let cursor_of_byte code byte =
let offsets = grapheme_byte_offsets code in
let byte = clamp 0 (String.length code) byte in
let rec loop i =
if i >= Array.length offsets then Array.length offsets - 1
else if offsets.(i) >= byte then i
else loop (i + 1)
in
loop 0
let find_prefix_at_cursor code ~cursor ~selection =
match selection with
| Some _ -> None
| None ->
let cursor, cursor_byte = cursor_byte_of code cursor in
let len = String.length code in
let at_ident_end =
cursor_byte = len || not (is_ident_char code.[cursor_byte])
in
if not at_ident_end then None
else
let i = ref (cursor_byte - 1) in
while
!i >= 0 && (is_ident_char code.[!i] || Char.equal code.[!i] '.')
do
decr i
done;
let start = !i + 1 in
let token =
if cursor_byte > start then String.sub code start (cursor_byte - start)
else ""
in
let replace_start_byte, prefix =
match String.rindex_opt token '.' with
| Some dot ->
( start + dot + 1,
String.sub token (dot + 1) (String.length token - dot - 1) )
| None -> (start, token)
in
Some (cursor, cursor_byte, replace_start_byte, prefix)
let selected_completion_item c =
match c.items with
| [] -> None
| items ->
let len = List.length items in
Some (List.nth items (c.selected mod len))
let index_of item items =
let rec loop i = function
| [] -> None
| x :: _ when String.equal x item -> Some i
| _ :: tl -> loop (i + 1) tl
in
loop 0 items
let cycle_completion c delta =
let len = List.length c.items in
if len = 0 then c
else { c with selected = (c.selected + delta + len) mod len }
let kind =
match kind with
| Info -> Some 3.
| Warning -> Some 5.
| Error | Confirm -> None
let m =
match m.footer_msg with
| Some ({ kind; created_at; _ } as ) -> (
match footer_message_timeout kind with
| Some timeout when m.clock -. created_at >= timeout ->
{ m with footer_msg = None }
| _ -> { m with footer_msg = Some footer_msg })
| None -> m
let is_navigation_msg msg =
match msg with
| Focus_next | Focus_prev | Move_up | Move_down -> true
| _ -> false
let should_clear_error_msg msg =
if is_navigation_msg msg then false
else
match msg with
| Tick _ | Dismiss_message | Toggle_help | Edit_cursor_changed _ -> false
| _ -> true
let current_code_cell m =
match focused_cell m with
| Some (Cell.Code { id; source; _ }) -> Some (id, source)
| _ -> None
let build_completion ?(force = false) m code ~cursor ~selection =
match find_prefix_at_cursor code ~cursor ~selection with
| None -> None
| Some (_, cursor_byte, replace_start_byte, prefix) -> (
if (not force) && String.length prefix = 0 then None
else
let kernel_items =
try
List.map
(fun (c : Kernel.completion_item) -> c.label)
(m.kernel.complete ~code ~pos:cursor_byte)
with _ -> []
in
let items =
unique_sorted
(kernel_items @ collect_identifiers code @ ocaml_keywords)
|> List.filter (fun item ->
(String.length prefix = 0 || starts_with ~prefix item)
&& not (String.equal item prefix))
|> take_first 200
in
match items with
| [] -> None
| _ ->
Some
{ prefix; cursor_byte; replace_start_byte; items; selected = 0 })
let preserve_selection prev next =
match (prev, next) with
| Some prev, Some next -> (
match selected_completion_item prev with
| Some item -> (
match index_of item next.items with
| Some idx -> Some { next with selected = idx }
| None -> Some next)
| None -> Some next)
| _, x -> x
let recompute_completion m =
match current_code_cell m with
| None -> { m with completion = None; completion_popup_open = false }
| Some (_, source) ->
let force = m.completion_popup_open in
let next =
build_completion ~force m source ~cursor:m.edit_cursor
~selection:m.edit_selection
in
{ m with completion = preserve_selection m.completion next }
let ghost_text m =
match m.completion with
| None -> None
| Some c when String.length c.prefix = 0 -> None
| Some c -> (
match selected_completion_item c with
| None -> None
| Some item when starts_with ~prefix:c.prefix item ->
let suffix =
String.sub item (String.length c.prefix)
(String.length item - String.length c.prefix)
in
if String.length suffix = 0 then None else Some suffix
| Some _ -> None)
let replace_range_at_byte s ~start_byte ~end_byte text =
let len = String.length s in
let start_byte = clamp 0 len start_byte in
let end_byte = clamp start_byte len end_byte in
String.sub s 0 start_byte ^ text ^ String.sub s end_byte (len - end_byte)
let apply_completion m c choice =
match current_code_cell m with
| None -> m
| Some (cell_id, source) ->
let code =
replace_range_at_byte source ~start_byte:c.replace_start_byte
~end_byte:c.cursor_byte choice
in
let cursor =
cursor_of_byte code (c.replace_start_byte + String.length choice)
in
let session = Session.update_source cell_id code m.session in
{
m with
session;
dirty = true;
edit_cursor = cursor;
edit_cursor_override = Some cursor;
edit_selection = None;
completion_popup_open = false;
completion = None;
}
|> recompute_completion
let cursor_line code cursor =
let _, cursor_byte = cursor_byte_of code cursor in
let line = ref 0 in
for i = 0 to cursor_byte - 1 do
if code.[i] = '\n' then incr line
done;
!line
let active_line_colors code cursor =
let line = cursor_line code cursor in
[
( line,
{
Line_number.gutter = Ansi.Color.of_rgb 48 48 68;
content = Some (Ansi.Color.of_rgb 32 32 48);
} );
]
let highlight_source source =
try
Tree_sitter_ocaml.highlight_ocaml source
|> Syntax_theme.apply Syntax_theme.default ~content:source
with _ -> []
let editor_on_key m ev =
let data = Event.Key.data ev in
if data.event_type = Release then None
else
let md = data.modifier in
match data.key with
| Escape when m.completion_popup_open ->
Event.Key.prevent_default ev;
Some Dismiss_completion
| Enter
when m.completion_popup_open
&& not (md.ctrl || md.alt || md.super || md.shift) ->
Event.Key.prevent_default ev;
Some Accept_completion
| Tab when m.completion_popup_open && md.shift ->
Event.Key.prevent_default ev;
Some Prev_completion
| Tab when m.completion_popup_open ->
Event.Key.prevent_default ev;
Some Accept_completion
| Tab when Option.is_none m.edit_selection ->
Event.Key.prevent_default ev;
Some Trigger_completion
| Char c
when m.completion_popup_open && md.ctrl
&& lowercase_codepoint (Uchar.to_int c) = Char.code 'n' ->
Event.Key.prevent_default ev;
Some Next_completion
| Char c
when m.completion_popup_open && md.ctrl
&& lowercase_codepoint (Uchar.to_int c) = Char.code 'p' ->
Event.Key.prevent_default ev;
Some Prev_completion
| Char c when md.ctrl && Uchar.to_int c = Char.code ' ' ->
Event.Key.prevent_default ev;
Some Trigger_completion
| Line_feed when not (md.ctrl || md.alt || md.super) ->
Event.Key.prevent_default ev;
Some Execute_and_advance
| _ -> None
let init ~create_kernel ~path () =
let event_queue = Queue.create () in
let on_event ev = Queue.push ev event_queue in
let kernel = create_kernel ~on_event in
let md =
if Sys.file_exists path then read_file path
else (
write_file path template;
template)
in
let doc = Quill_markdown.of_string md in
let session = Session.create doc in
let last_mtime = get_mtime path in
let n = Doc.length doc in
let focus = if n > 0 then n - 1 else 0 in
let is_code_cell =
match Doc.nth focus doc with Some (Cell.Code _) -> true | _ -> false
in
let edit_cursor =
match Doc.nth focus doc with
| Some (Cell.Code { source; _ }) -> grapheme_count source
| _ -> 0
in
let initial_mode = if is_code_cell then Editing else Normal in
let title_cmd =
Cmd.set_title (Printf.sprintf "Quill - %s" (Filename.basename path))
in
let initial_cmd =
if is_code_cell then Cmd.batch [ title_cmd; Cmd.focus textarea_id ]
else title_cmd
in
( {
session;
kernel;
event_queue;
path;
focus;
mode = initial_mode;
dirty = false;
footer_msg = None;
last_mtime;
reload_acc = 0.;
confirm_quit = false;
show_help = false;
clock = 0.;
viewport_width = 120;
viewport_height = 32;
edit_cursor;
edit_cursor_override = (if is_code_cell then Some edit_cursor else None);
edit_selection = None;
completion_popup_open = false;
completion = None;
},
initial_cmd )
let check_reload m =
let mtime = get_mtime m.path in
if mtime > m.last_mtime then
let md = read_file m.path in
let doc = Quill_markdown.of_string md in
let session = Session.reload doc m.session in
let n = Doc.length (Session.doc session) in
let focus = if n > 0 then min m.focus (n - 1) else 0 in
{
m with
session;
focus;
last_mtime = mtime;
dirty = false;
completion_popup_open = false;
completion = None;
edit_cursor_override = None;
edit_selection = None;
}
else m
let execute_cell m id source =
let session = Session.checkpoint m.session in
let session = Session.clear_outputs id session in
let session = Session.mark_running id session in
m.kernel.execute ~cell_id:id ~code:source;
let session = drain_events m.event_queue session in
clear_footer_message { m with session; dirty = true }
let execute_all_cells m =
let session = Session.clear_all_outputs m.session in
let session = ref session in
List.iter
(fun cell ->
match cell with
| Cell.Code { id; source; _ } ->
session := Session.mark_running id !session;
m.kernel.execute ~cell_id:id ~code:source;
session := drain_events m.event_queue !session
| Cell.Text _ -> ())
(Doc.cells (Session.doc !session));
clear_footer_message { m with session = !session; dirty = true }
(** Execute the focused cell, then create a new empty cell below and enter edit
mode on it. This gives the REPL-like "type, run, type more" flow. *)
let execute_and_advance m =
match focused_cell m with
| Some (Cell.Code { id; source; _ }) ->
let m = execute_cell m id source in
let pos = m.focus + 1 in
let cell = Cell.code "" in
let session = Session.insert_cell ~pos cell m.session in
let n = Doc.length (Session.doc session) in
let focus = min pos (n - 1) in
let m =
{
m with
session;
focus;
mode = Editing;
edit_cursor = 0;
edit_cursor_override = Some 0;
edit_selection = None;
completion_popup_open = false;
completion = None;
}
in
(m, Cmd.perform (fun dispatch -> dispatch Deferred_focus_editor))
| Some (Cell.Text _) ->
let n = cell_count m in
let pos = m.focus + 1 in
if pos < n then
let source =
match Doc.nth pos (Session.doc m.session) with
| Some (Cell.Code { source; _ } | Cell.Text { source; _ }) -> source
| None -> ""
in
let edit_cursor = grapheme_count source in
let m =
{
m with
focus = pos;
mode = Editing;
edit_cursor;
edit_cursor_override = Some edit_cursor;
edit_selection = None;
completion_popup_open = false;
completion = None;
}
in
(m, Cmd.perform (fun dispatch -> dispatch Deferred_focus_editor))
else
let cell = Cell.code "" in
let session = Session.insert_cell ~pos cell m.session in
let n = Doc.length (Session.doc session) in
let focus = min pos (n - 1) in
let m =
{
m with
session;
focus;
dirty = true;
mode = Editing;
edit_cursor = 0;
edit_cursor_override = Some 0;
edit_selection = None;
completion_popup_open = false;
completion = None;
}
in
(m, Cmd.perform (fun dispatch -> dispatch Deferred_focus_editor))
| None -> (with_footer_message m Warning "No cell to advance from", Cmd.none)
let tick_model m dt =
let session = drain_events m.event_queue m.session in
let m = { m with session; clock = m.clock +. dt } in
expire_footer_message m
let update_toggle_help m =
let show_help = not m.show_help in
let cmd =
if show_help then Cmd.focus help_scroll_id
else
match m.mode with
| Editing -> Cmd.focus textarea_id
| Normal -> Cmd.focus scroll_box_id
in
({ m with show_help }, cmd)
let update_save m =
let session = Session.checkpoint m.session in
let m = { m with session } in
let doc = Session.doc m.session in
let content = Quill_markdown.to_string_with_outputs doc in
write_file m.path content;
let last_mtime = get_mtime m.path in
( with_footer_message { m with dirty = false; last_mtime } Info "Saved",
Cmd.none )
let update_quit m =
if m.dirty && not m.confirm_quit then
( with_footer_message
{ m with confirm_quit = true }
Confirm "Unsaved changes. Press q again to quit, s to save.",
Cmd.none )
else (
m.kernel.shutdown ();
(m, Cmd.quit))
let update_editing msg m =
match msg with
| Deferred_focus_editor -> (m, Cmd.focus textarea_id)
| Toggle_help -> update_toggle_help m
| Dismiss_message ->
({ m with confirm_quit = false; footer_msg = None }, Cmd.none)
| Resize (width, height) ->
({ m with viewport_width = width; viewport_height = height }, Cmd.none)
| Exit_edit ->
let session = Session.checkpoint m.session in
( {
m with
mode = Normal;
session;
edit_cursor_override = None;
completion_popup_open = false;
completion = None;
edit_selection = None;
},
Cmd.focus scroll_box_id )
| Edit_source source -> (
match focused_cell m with
| Some cell ->
let cell_id = Cell.id cell in
let session = Session.update_source cell_id source m.session in
let m = { m with session; dirty = true } in
let m =
if Option.is_some m.edit_selection then
{ m with completion_popup_open = false }
else m
in
(recompute_completion m, Cmd.none)
| None -> (m, Cmd.none))
| Edit_cursor_changed (cursor, selection) ->
let m =
{
m with
edit_cursor = cursor;
edit_cursor_override = None;
edit_selection = selection;
completion_popup_open =
(match selection with
| Some _ -> false
| None -> m.completion_popup_open);
}
in
(recompute_completion m, Cmd.none)
| Trigger_completion ->
if Option.is_some m.edit_selection then
( with_footer_message m Warning
"Dismiss selection before triggering completion.",
Cmd.none )
else
let m = recompute_completion { m with completion_popup_open = true } in
(m, Cmd.none)
| Next_completion -> (
match m.completion with
| None -> (m, Cmd.none)
| Some c ->
( {
m with
completion = Some (cycle_completion c 1);
completion_popup_open = true;
},
Cmd.none ))
| Prev_completion -> (
match m.completion with
| None -> (m, Cmd.none)
| Some c ->
( {
m with
completion = Some (cycle_completion c (-1));
completion_popup_open = true;
},
Cmd.none ))
| Accept_completion -> (
match m.completion with
| None -> (m, Cmd.none)
| Some c -> (
match selected_completion_item c with
| None ->
( { m with completion_popup_open = false } |> recompute_completion,
Cmd.none )
| Some choice -> (apply_completion m c choice, Cmd.none)))
| Dismiss_completion ->
( { m with completion_popup_open = false } |> recompute_completion,
Cmd.none )
| Submit_edit _ ->
execute_and_advance m
| Execute_focused -> (
match focused_cell m with
| Some (Cell.Code { id; source; _ }) ->
let m = execute_cell m id source in
(m, Cmd.none)
| _ -> (m, Cmd.none))
| Execute_and_advance -> execute_and_advance m
| Save -> update_save m
| Quit ->
let session = Session.checkpoint m.session in
update_quit
{
m with
session;
mode = Normal;
completion_popup_open = false;
completion = None;
edit_cursor_override = None;
edit_selection = None;
}
| Interrupt ->
m.kernel.interrupt ();
(m, Cmd.none)
| Tick dt ->
let m = tick_model m dt in
({ m with reload_acc = m.reload_acc +. dt }, Cmd.none)
| _ -> (m, Cmd.none)
let update_normal msg m =
match msg with
| Toggle_help -> update_toggle_help m
| Dismiss_message ->
({ m with confirm_quit = false; footer_msg = None }, Cmd.none)
| Resize (width, height) ->
({ m with viewport_width = width; viewport_height = height }, Cmd.none)
| Focus_next ->
let n = cell_count m in
let focus = if n > 0 then min (m.focus + 1) (n - 1) else 0 in
({ m with focus }, Cmd.none)
| Focus_prev -> ({ m with focus = max (m.focus - 1) 0 }, Cmd.none)
| Execute_focused -> (
match focused_cell m with
| Some (Cell.Code { id; source; _ }) ->
(execute_cell m id source, Cmd.none)
| Some (Cell.Text _) ->
(with_footer_message m Error "Cannot execute a text cell", Cmd.none)
| None -> (with_footer_message m Warning "No cell to execute", Cmd.none))
| Execute_and_advance -> execute_and_advance m
| Execute_all -> (execute_all_cells m, Cmd.none)
| Interrupt ->
m.kernel.interrupt ();
(m, Cmd.none)
| Insert_code_below ->
let pos = m.focus + 1 in
let cell = Cell.code "" in
let session = Session.insert_cell ~pos cell m.session in
let n = Doc.length (Session.doc session) in
let focus = min pos (n - 1) in
let m =
{
m with
session;
focus;
dirty = true;
mode = Editing;
edit_cursor = 0;
edit_cursor_override = Some 0;
edit_selection = None;
completion_popup_open = false;
completion = None;
}
in
(m, Cmd.focus textarea_id)
| Insert_text_below ->
let pos = m.focus + 1 in
let cell = Cell.text "" in
let session = Session.insert_cell ~pos cell m.session in
let n = Doc.length (Session.doc session) in
({ m with session; focus = min pos (n - 1); dirty = true }, Cmd.none)
| Delete_focused -> (
match focused_cell m with
| Some cell ->
let session = Session.remove_cell (Cell.id cell) m.session in
let n = Doc.length (Session.doc session) in
let focus = if n > 0 then min m.focus (n - 1) else 0 in
({ m with session; focus; dirty = true }, Cmd.none)
| None -> (m, Cmd.none))
| Toggle_cell_kind -> (
match focused_cell m with
| Some cell ->
let cell_id = Cell.id cell in
let kind =
match cell with Cell.Code _ -> `Text | Cell.Text _ -> `Code
in
let session = Session.set_cell_kind cell_id kind m.session in
({ m with session; dirty = true }, Cmd.none)
| None -> (m, Cmd.none))
| Move_up -> (
match focused_cell m with
| Some cell when m.focus > 0 ->
let cell_id = Cell.id cell in
let pos = m.focus - 1 in
let session = Session.move_cell cell_id ~pos m.session in
({ m with session; focus = pos; dirty = true }, Cmd.none)
| _ -> (m, Cmd.none))
| Move_down -> (
match focused_cell m with
| Some cell when m.focus < cell_count m - 1 ->
let cell_id = Cell.id cell in
let pos = m.focus + 1 in
let session = Session.move_cell cell_id ~pos m.session in
({ m with session; focus = pos; dirty = true }, Cmd.none)
| _ -> (m, Cmd.none))
| Clear_focused -> (
match focused_cell m with
| Some cell ->
let session = Session.clear_outputs (Cell.id cell) m.session in
({ m with session; dirty = true }, Cmd.none)
| None -> (m, Cmd.none))
| Clear_all ->
let session = Session.clear_all_outputs m.session in
({ m with session; dirty = true }, Cmd.none)
| Save -> update_save m
| Quit -> update_quit m
| Tick dt ->
let m = tick_model m dt in
let reload_acc = m.reload_acc +. dt in
if reload_acc >= reload_interval then
let m = check_reload { m with reload_acc = 0. } in
(m, Cmd.none)
else ({ m with reload_acc }, Cmd.none)
| Enter_edit -> (
match focused_cell m with
| Some (Cell.Code { source; _ } | Cell.Text { source; _ }) ->
let edit_cursor = grapheme_count source in
let m =
{
m with
mode = Editing;
edit_cursor;
edit_cursor_override = Some edit_cursor;
edit_selection = None;
completion_popup_open = false;
completion = None;
}
in
(recompute_completion m, Cmd.focus textarea_id)
| None -> (m, Cmd.none))
| _ -> (m, Cmd.none)
let update msg m =
let m =
if should_clear_error_msg msg then
match m.footer_msg with
| Some { kind = Error; _ } -> clear_footer_message m
| _ -> m
else m
in
let m =
match msg with
| Quit | Tick _ | Toggle_help | Resize _ -> m
| _ -> clear_confirm_message { m with confirm_quit = false }
in
match m.mode with
| Editing -> update_editing msg m
| Normal -> update_normal msg m
let running_count m =
List.fold_left
(fun acc cell ->
match cell with
| Cell.Code { id; _ } ->
if Session.cell_status id m.session = Session.Running then acc + 1
else acc
| _ -> acc)
0
(Doc.cells (Session.doc m.session))
let has_running m = running_count m > 0
let m =
let n = cell_count m in
let left =
box ~flex_direction:Row ~gap:(gap 1) ~align_items:Center
[
text ~style:(Ansi.Style.make ~fg:label_fg ~italic:true ()) "quill";
text
~style:(Ansi.Style.make ~fg:Ansi.Color.white ~bold:true ())
(Filename.basename m.path);
]
in
let center =
let rc = running_count m in
if rc > 0 then
box ~flex_direction:Row ~gap:(gap 1) ~align_items:Center
[
spinner ~frame_set:Spinner.dots ~color:accent ();
text
~style:(Ansi.Style.make ~fg:accent ())
(Printf.sprintf "%d running" rc);
]
else
text
~style:(Ansi.Style.make ~fg:label_fg ())
(Printf.sprintf "%d cells" n)
in
let right =
if m.dirty then
text ~style:(Ansi.Style.make ~fg:accent ~bold:true ()) "\xe2\x97\x8f"
else empty
in
box ~background:chrome_bg ~flex_direction:Row ~justify_content:Space_between
~align_items:Center
~size:{ width = pct 100; height = auto }
~padding:(padding_lrtb ~l:2 ~r:2 ~t:0 ~b:0)
[ left; center; right ]
let view_error_bar msg =
box ~background:error_bg ~border:true ~border_sides:[ `Left ]
~border_style:Border.heavy ~border_color:error_fg
~size:{ width = pct 100; height = auto }
~padding:(padding_lrtb ~l:1 ~r:1 ~t:0 ~b:0)
[ text ~style:(Ansi.Style.make ~fg:error_fg ()) msg ]
let trim_trailing_newlines s =
let len = String.length s in
let i = ref (len - 1) in
while !i >= 0 && (s.[!i] = '\n' || s.[!i] = '\r') do
decr i
done;
if !i = len - 1 then s else String.sub s 0 (!i + 1)
let view_output output =
match output with
| Cell.Stdout s ->
text ~style:(Ansi.Style.make ~fg:output_fg ()) (trim_trailing_newlines s)
| Cell.Stderr s ->
text
~style:(Ansi.Style.make ~fg:warning_fg ~italic:true ())
("\xe2\x96\xb6 " ^ trim_trailing_newlines s)
| Cell.Error s -> view_error_bar s
| Cell.Display { mime; data } ->
if String.starts_with ~prefix:"text/" mime then
text ~style:(Ansi.Style.make ~fg:output_fg ()) data
else
text
~style:(Ansi.Style.make ~fg:output_dim_fg ~italic:true ())
(Printf.sprintf "[%s \xc2\xb7 %d bytes]" mime (String.length data))
let completion_panel ~is_editing m =
if not (is_editing && m.mode = Editing && m.completion_popup_open) then empty
else
match m.completion with
| None ->
box ~border:true ~border_color:border_unfocused ~padding:(padding 1)
[
text
~style:(Ansi.Style.make ~fg:hint_fg ())
"No suggestions at cursor.";
]
| Some c ->
box ~border:true ~border_color:border_unfocused ~padding:(padding 1)
~flex_direction:Column ~gap:(gap 0)
[
text
~style:(Ansi.Style.make ~bold:true ~fg:accent ())
(Printf.sprintf "Completions (%d)" (List.length c.items));
box ~flex_direction:Column ~gap:(gap 0)
(take_first 8 c.items
|> List.mapi (fun i item ->
let selected = i = c.selected in
let prefix = if selected then "> " else " " in
text
~style:
(if selected then
Ansi.Style.make ~fg:Ansi.Color.black
~bg:Ansi.Color.yellow ~bold:true ()
else Ansi.Style.make ~fg:Ansi.Color.white ())
(prefix ^ item)));
]
let view_code_cell m ~index ~is_focused ~is_editing ~status source outputs =
let border_color = if is_focused then border_focused else border_unfocused in
let num = index + 1 in
let title =
if is_editing then Printf.sprintf " %d \xe2\x9c\x8e " num
else
let status_indicator =
match status with
| Session.Running -> " \xe2\x80\xa6"
| Session.Queued -> " \xe2\x97\x8b"
| Session.Idle -> if outputs <> [] then " \xe2\x9c\x93" else ""
in
Printf.sprintf " %d%s " num status_indicator
in
let source_view =
if is_editing then
let highlights = highlight_source source in
let ghost_text = ghost_text m in
box
~padding:(padding_lrtb ~l:1 ~r:1 ~t:0 ~b:0)
~size:{ width = pct 100; height = auto }
[
line_number ~flex_grow:1.
~line_colors:(active_line_colors source m.edit_cursor)
(textarea ~id:textarea_id ~value:source
?cursor:m.edit_cursor_override ~spans:highlights ?ghost_text
~ghost_text_color:(Ansi.Color.grayscale ~level:10)
~text_color:output_fg ~background_color:cell_bg_focused
~focused_text_color:output_fg
~focused_background_color:cell_bg_focused ~cursor_style:`Line
~cursor_color:accent ~wrap:`None
~size:{ width = pct 100; height = auto }
~on_key:(fun ev -> editor_on_key m ev)
~on_input:(fun s -> Some (Edit_source s))
~on_submit:(fun s -> Some (Submit_edit s))
~on_cursor:(fun ~cursor ~selection ->
Some (Edit_cursor_changed (cursor, selection)))
());
]
else
let highlights = highlight_source source in
box
~padding:(padding_lrtb ~l:1 ~r:1 ~t:0 ~b:0)
~size:{ width = pct 100; height = auto }
[ code ~spans:highlights source ]
in
let status_row =
match status with
| Session.Running ->
box ~flex_direction:Row ~gap:(gap 1) ~align_items:Center
~padding:(padding_lrtb ~l:1 ~r:1 ~t:0 ~b:0)
~size:{ width = pct 100; height = auto }
[
spinner ~frame_set:Spinner.dots ~color:accent ();
text
~style:(Ansi.Style.make ~fg:accent_dim ~italic:true ())
"evaluating";
]
| _ -> empty
in
let output_section =
if outputs = [] then empty
else
box ~flex_direction:Column ~border:true ~border_sides:[ `Top ]
~border_style:Border.single ~border_color:border_unfocused
~size:{ width = pct 100; height = auto }
~padding:(padding_lrtb ~l:1 ~r:1 ~t:0 ~b:0)
(List.map view_output outputs)
in
box ~flex_direction:Column ~border:true ~border_color
~border_style:Border.rounded ~title ~title_alignment:`Left
?background:(if is_focused then Some cell_bg_focused else None)
~size:{ width = pct 100; height = auto }
[ source_view; completion_panel ~is_editing m; status_row; output_section ]
let view_text_cell ~is_focused ~is_editing m source =
if is_editing then
box ~background:cell_bg_focused ~border:true ~border_color:border_focused
~border_style:Border.rounded ~title:" text \xe2\x9c\x8e "
~title_alignment:`Left
~size:{ width = pct 100; height = auto }
[
box
~padding:(padding_lrtb ~l:1 ~r:1 ~t:0 ~b:0)
~size:{ width = pct 100; height = auto }
[
textarea ~id:textarea_id ~value:source
?cursor:m.edit_cursor_override ~text_color:output_fg
~background_color:cell_bg_focused ~focused_text_color:output_fg
~focused_background_color:cell_bg_focused ~cursor_style:`Line
~cursor_color:accent ~wrap:`Word
~size:{ width = pct 100; height = auto }
~on_key:(fun ev ->
let data = Event.Key.data ev in
if data.event_type = Release then None
else
match data.key with
| Line_feed
when not
(data.modifier.ctrl || data.modifier.alt
|| data.modifier.super) ->
Event.Key.prevent_default ev;
Some Execute_and_advance
| _ -> None)
~on_input:(fun s -> Some (Edit_source s))
~on_submit:(fun _s -> Some Execute_and_advance)
~on_cursor:(fun ~cursor ~selection ->
Some (Edit_cursor_changed (cursor, selection)))
();
];
]
else
box
?background:(if is_focused then Some cell_bg_focused else None)
~size:{ width = pct 100; height = auto }
~padding:(padding_lrtb ~l:2 ~r:2 ~t:0 ~b:0)
[ markdown source ]
let view_cell ~index ~focus ~mode m cell =
let is_focused = index = focus in
match cell with
| Cell.Code { id; source; outputs; _ } ->
let status = Session.cell_status id m.session in
let is_editing = is_focused && mode = Editing in
view_code_cell m ~index ~is_focused ~is_editing ~status source outputs
| Cell.Text { source; _ } ->
let is_editing = is_focused && mode = Editing in
view_text_cell ~is_focused ~is_editing m source
let view_cells m =
let cells = Doc.cells (Session.doc m.session) in
if cells = [] then
[
box ~flex_direction:Column ~align_items:Center ~justify_content:Center
~flex_grow:1.
~size:{ width = pct 100; height = pct 100 }
[
text
~style:(Ansi.Style.make ~fg:label_fg ~italic:true ())
"empty notebook";
box
~size:{ width = auto; height = auto }
~padding:(padding_lrtb ~l:0 ~r:0 ~t:1 ~b:0)
[
text
~style:(Ansi.Style.make ~fg:hint_fg ())
"press a to add a code cell, or t for text";
];
];
]
else
List.mapi
(fun index cell -> view_cell ~index ~focus:m.focus ~mode:m.mode m cell)
cells
let m =
if m.viewport_width >= 120 then Wide
else if m.viewport_width >= 80 then Medium
else if m.viewport_width >= 60 then Compact
else Tiny
let rec take n xs =
if n <= 0 then []
else match xs with [] -> [] | x :: tl -> x :: take (n - 1) tl
let focused_kind_label m =
match focused_cell m with
| Some (Cell.Code _) -> "code"
| Some (Cell.Text _) -> "text"
| None -> "none"
let m =
match m.mode with Normal -> "NORMAL" | Editing -> "EDIT"
let m =
let rc = running_count m in
if rc > 0 then Printf.sprintf "running %d" rc else "idle"
let m =
if m.confirm_quit then
[
{ key = "q"; label = "Confirm" };
{ key = "s"; label = "Save" };
{ key = "Esc"; label = "Cancel" };
]
else
match m.mode with
| Editing ->
[
{ key = "Shift-Enter"; label = "Run" };
{ key = "Tab"; label = "Complete" };
{ key = "Esc"; label = "Exit" };
{ key = "?"; label = "Help" };
]
| Normal ->
[
{ key = "Enter"; label = "Edit" };
{ key = "x"; label = "Run" };
{ key = "j/k"; label = "Navigate" };
{ key = "?"; label = "Help" };
]
let tier =
match tier with Wide -> 4 | Medium -> 3 | Compact -> 2 | Tiny -> 1
let tier label =
match (tier, label) with
| Medium, "Interrupt" -> "Stop"
| Medium, "Navigate" -> "Nav"
| Medium, "Confirm Quit" -> "Confirm"
| Medium, "To Code" -> "ToCode"
| Compact, "Save" -> "Save"
| Compact, "Interrupt" -> "Stop"
| Compact, "Navigate" -> "Nav"
| Compact, "Confirm Quit" -> "Confirm"
| Compact, "To Code" -> "Code"
| Compact, "+Code" -> "+C"
| Compact, "+Text" -> "+T"
| Compact, "Help" -> "?"
| _ -> label
let truncate_text max_len s =
if String.length s <= max_len then s
else String.sub s 0 (max 0 (max_len - 1)) ^ "\xe2\x80\xa6"
let tier m =
match m.footer_msg with
| None -> None
| Some { kind; text = msg; _ } ->
let fg, prefix =
match kind with
| Info -> (info_fg, "INFO")
| Warning -> (warning_fg, "WARN")
| Error -> (error_fg, "ERROR")
| Confirm -> (warning_fg, "CONFIRM")
in
let max_len =
match tier with Wide -> 32 | Medium -> 22 | Compact -> 14 | Tiny -> 8
in
Some (fg, Printf.sprintf "%s:%s" prefix (truncate_text max_len msg))
let tier m =
let total = cell_count m in
let focus =
if total = 0 then "cell 0/0"
else Printf.sprintf "cell %d/%d" (m.focus + 1) total
in
let kernel = footer_kernel_label m in
let dirty = if m.dirty then "modified" else "saved" in
match tier with
| Wide ->
Printf.sprintf "%s %s %s %s" focus (focused_kind_label m) dirty kernel
| Medium -> Printf.sprintf "%s %s %s" focus (focused_kind_label m) kernel
| Compact -> Printf.sprintf "%s %s" focus kernel
| Tiny -> ""
let tier m =
let key_style = Ansi.Style.make ~fg:label_fg ~bold:true () in
let desc_style = Ansi.Style.make ~fg:hint_fg () in
let actions =
if tier = Tiny then [ { key = "?"; label = "Help" } ]
else take (footer_action_limit tier) (footer_actions m)
in
let view_action action =
let label = footer_action_label tier action.label in
box ~flex_direction:Row ~gap:(gap 0) ~align_items:Center
~size:{ width = auto; height = auto }
[
text ~style:key_style (Printf.sprintf "[%s]" action.key);
text ~style:desc_style (Printf.sprintf " %s" label);
]
in
box ~flex_direction:Row ~gap:(gap 1) ~align_items:Center
~size:{ width = auto; height = auto }
(List.map view_action actions)
let m =
let tier = footer_width_tier m in
let mode_style =
Ansi.Style.make
~fg:(match m.mode with Editing -> accent | Normal -> label_fg)
~bold:true ()
in
let desc_style = Ansi.Style.make ~fg:hint_fg () in
let status_text = footer_status_text tier m in
let status_node =
if status_text = "" then empty
else text ~style:desc_style (Printf.sprintf " %s" status_text)
in
let message_node =
match footer_message_view tier m with
| Some (fg, msg) ->
text ~style:(Ansi.Style.make ~fg ~bold:true ()) (" | " ^ msg)
| None -> empty
in
let left =
box ~flex_direction:Row ~gap:(gap 0) ~align_items:Center
~size:{ width = auto; height = auto }
[
text ~style:mode_style (Printf.sprintf "[%s]" (footer_mode_label m));
status_node;
message_node;
]
in
let right = view_footer_actions tier m in
box ~background:chrome_bg ~flex_direction:Row ~justify_content:Space_between
~align_items:Center
~size:{ width = pct 100; height = auto }
~padding:(padding_lrtb ~l:2 ~r:2 ~t:0 ~b:0)
[ left; right ]
let m =
if not m.show_help then empty
else
let section_title title =
text ~style:(Ansi.Style.make ~fg:accent ~bold:true ()) title
in
let item key desc =
box ~flex_direction:Row ~gap:(gap 1) ~align_items:Center
~size:{ width = pct 100; height = auto }
[
text
~style:(Ansi.Style.make ~fg:label_fg ~bold:true ())
(Printf.sprintf "[%s]" key);
text ~style:(Ansi.Style.make ~fg:hint_fg ()) desc;
]
in
let panel_width = if m.viewport_width < 80 then pct 96 else pct 82 in
let panel_height = if m.viewport_height < 24 then pct 86 else pct 72 in
box ~position:Absolute ~inset:(inset 0) ~z_index:20 ~background:overlay_bg
~justify_content:Center ~align_items:Center
~size:{ width = pct 100; height = pct 100 }
[
box ~border:true ~border_style:Border.rounded
~border_color:border_focused ~background:chrome_bg
~flex_direction:Column ~gap:(gap 1)
~size:{ width = panel_width; height = panel_height }
~padding:(padding_lrtb ~l:1 ~r:1 ~t:0 ~b:1)
[
box ~flex_direction:Row ~justify_content:Space_between
~align_items:Center
~size:{ width = pct 100; height = auto }
[
text
~style:(Ansi.Style.make ~fg:Ansi.Color.white ~bold:true ())
"Keybindings";
text ~style:(Ansi.Style.make ~fg:hint_fg ()) "Esc or ? to close";
];
scroll_box ~id:help_scroll_id ~scroll_y:true ~scroll_x:false
~flex_grow:1.
~size:{ width = pct 100; height = auto }
~padding:(padding_lrtb ~l:1 ~r:1 ~t:0 ~b:0)
~flex_direction:Column ~gap:(gap 1)
[
box ~flex_direction:Column ~gap:(gap 1)
[
section_title "Normal mode";
item "Enter" "Enter edit mode";
item "x" "Execute focused cell";
item "j / k" "Focus next / previous cell";
item "J / K" "Move cell down / up";
item "a / t" "Insert code / text cell below";
item "d" "Delete focused cell";
item "m" "Toggle cell kind (code/text)";
item "c" "Clear focused cell outputs";
item "s" "Save notebook";
item "q" "Quit";
];
box ~flex_direction:Column ~gap:(gap 1)
[
section_title "Edit mode";
item "Shift-Enter" "Execute and advance (REPL flow)";
item "Ctrl-Enter" "Execute and advance (REPL flow)";
item "Esc" "Exit to normal mode";
item "Tab" "Trigger / accept completion";
item "Shift-Tab" "Previous completion";
item "Ctrl-Space" "Open completion popup";
item "Ctrl-N / Ctrl-P" "Next / previous completion";
item "Ctrl-S" "Save notebook";
];
box ~flex_direction:Column ~gap:(gap 1)
[
section_title "Global";
item "Ctrl-A" "Execute all cells";
item "Ctrl-C" "Interrupt execution";
item "Ctrl-L" "Clear all outputs";
item "?" "Toggle this help panel";
];
];
];
]
let view m =
box ~flex_direction:Column
~size:{ width = pct 100; height = pct 100 }
[
view_header m;
scroll_box ~id:scroll_box_id ~scroll_y:true ~scroll_x:false ~flex_grow:1.
~autofocus:true
~size:{ width = pct 100; height = auto }
~flex_direction:Column ~gap:(gap 1)
~padding:(padding_lrtb ~l:1 ~r:1 ~t:1 ~b:1)
(view_cells m);
view_footer m;
view_footer_help_overlay m;
]
let subscriptions model =
Sub.batch
[
Sub.on_tick (fun ~dt -> Tick dt);
Sub.on_resize (fun ~width ~height -> Resize (width, height));
Sub.on_key_all (fun ev ->
let data = Event.Key.data ev in
if model.show_help then
match data.key with
| Escape -> Some Toggle_help
| Char c when char_eq '?' c -> Some Toggle_help
| _ -> None
else
match model.mode with
| Editing -> (
if data.modifier.ctrl then
match data.key with
| Char c when char_eq 'a' c -> Some Execute_all
| Char c when char_eq 's' c -> Some Save
| Char c when char_eq 'c' c -> Some Interrupt
| Char c when char_eq 'l' c -> Some Clear_all
| _ -> None
else
match data.key with
| Char c when char_eq '?' c -> Some Toggle_help
| _ -> None)
| Normal -> (
if data.modifier.ctrl then
match data.key with
| Char c when char_eq 'a' c -> Some Execute_all
| Char c when char_eq 's' c -> Some Save
| Char c when char_eq 'c' c -> Some Interrupt
| Char c when char_eq 'l' c -> Some Clear_all
| _ -> None
else
match data.key with
| Char c when char_eq 'j' c -> Some Focus_next
| Char c when char_eq 'k' c -> Some Focus_prev
| Char c when char_eq 'J' c -> Some Move_down
| Char c when char_eq 'K' c -> Some Move_up
| Char c when char_eq 'x' c -> Some Execute_focused
| Char c when char_eq 'a' c -> Some Insert_code_below
| Char c when char_eq 't' c -> Some Insert_text_below
| Char c when char_eq 'd' c -> Some Delete_focused
| Char c when char_eq 'm' c -> Some Toggle_cell_kind
| Char c when char_eq 'c' c -> Some Clear_focused
| Char c when char_eq 's' c -> Some Save
| Char c when char_eq 'q' c -> Some Quit
| Char c when char_eq '?' c -> Some Toggle_help
| Down -> Some Focus_next
| Up -> Some Focus_prev
| Enter ->
Some Enter_edit
| Escape -> Some Dismiss_message
| _ -> None));
Sub.on_key (fun ev ->
match model.mode with
| Editing when not model.show_help -> (
match (Event.Key.data ev).key with
| Escape when not model.completion_popup_open -> Some Exit_edit
| _ -> None)
| Editing | Normal -> None);
]
let run ~create_kernel path =
let init () = init ~create_kernel ~path () in
run { init; update; view; subscriptions }