iced-markdown-editor 0.3.1

A Word-style WYSIWYG CommonMark editor widget for Iced
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
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
//! The public widget API.
//!
//! * [`EditorState`] owns the document, selection, history, paper, zoom,
//!   tab width, highlighter, image settings and style. Keep it in your
//!   application state.
//! * [`markdown_editor`] builds the widget from a `&EditorState`.
//! * The widget produces [`Action`]s. Pass them to
//!   [`EditorState::update`], which returns an [`Output`] with a [`Task`]
//!   and the [`Event`]s that happened.
//! * [`EditorState::execute`] runs a [`Command`] programmatically.
//!
//! * `edit`: keyboard, mouse and commands.
//! * `source`: Markdown source mode.
//! * `view`: the widget (page canvas, link bar, status bar).
//! * `toolbar`: the built-in toolbar.

mod edit;
mod source;
mod toolbar;
mod view;

pub use view::{MarkdownEditor, markdown_editor};

use crate::doc::{Block, BlockKind, ColumnAlign, Container, Document, Leaf, Pos, Selection, Style};
use crate::extension::{BlockRenderer, Frame, Rectangle, RenderRequest};
use crate::features::Features;
use crate::fonts::Fonts;
use crate::highlight::{self, COMMON_LANGUAGES, CodeHighlighter, HighlightRequest};
use crate::i18n::Language;
use crate::images::{
    self, ImageCache, ImageId, ImageLoader, ImageRejection, ImageSettings, ImageSource, PastedImage,
};
use crate::layout::{Layout, Lookups, compute as compute_layout};
use crate::markdown;
use crate::page::Paper;
use crate::style::EditorStyle;
use crate::zoom::ZoomSettings;
use iced::keyboard::{Key, Modifiers};
use iced::mouse::ScrollDelta;
use iced::widget::canvas;
use iced::{Color, Size, Subscription, Task};
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
// `std::time::Instant` panics in the browser; `web_time` is std on desktop.
use web_time::Instant;

pub(crate) const BLINK: Duration = Duration::from_millis(530);

/// Default number of spaces inserted by the Tab key.
pub const DEFAULT_TAB_WIDTH: usize = 4;

/// Editing mode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
    /// Formatted, Word-like editing.
    Wysiwyg,
    /// Raw Markdown text.
    Source,
}

/// A message produced by the widget. Opaque: forward it to
/// [`EditorState::update`]. Create one from a [`Command`] with
/// `Action::from(command)` to drive the editor from your own widgets.
#[derive(Debug, Clone)]
pub struct Action(pub(crate) Inner);

impl From<Command> for Action {
    fn from(command: Command) -> Self {
        Action(Inner::Command(command))
    }
}

#[derive(Debug, Clone)]
pub(crate) enum Inner {
    Key(Key, Modifiers, Option<String>),
    Modifiers(Modifiers),
    /// Press in document coordinates.
    Press {
        x: f32,
        y: f32,
        clicks: u8,
    },
    /// Drag in document coordinates.
    Drag {
        x: f32,
        y: f32,
    },
    PressOutside,
    Blink,
    /// Scroll by a distance in pixels.
    ScrollBy {
        dx: f32,
        dy: f32,
    },
    /// Scroll to an absolute offset (scrollbar drag).
    ScrollTo {
        x: Option<f32>,
        y: Option<f32>,
    },
    /// Ctrl/Cmd + wheel: zoom.
    Wheel(ScrollDelta),
    Command(Command),
    LinkUrl(String),
    LinkApply,
    LinkRemove,
    LinkCancel,
    Paste(Option<String>),
    /// A file dropped onto the window.
    FileDropped(PathBuf),
}

/// Operations that can be triggered programmatically.
#[derive(Debug, Clone, PartialEq)]
pub enum Command {
    Undo,
    Redo,
    ToggleBold,
    ToggleItalic,
    ToggleStrike,
    ToggleCode,
    /// Changes the paragraph(s) under the selection: block type, list,
    /// task list or block quote. Applying the current kind again reverts.
    SetBlock(BlockKind),
    /// Checks or unchecks the task list item(s) under the selection.
    ToggleChecked,
    /// Sets the language of the code block(s) under the selection.
    SetCodeLanguage(Option<String>),
    InsertRule,
    /// Inserts an empty table; `rows` includes the header row.
    InsertTable {
        rows: usize,
        columns: usize,
    },
    /// Inserts a row above or below the row at the caret.
    InsertRow {
        below: bool,
    },
    /// Inserts a column left or right of the column at the caret.
    InsertColumn {
        right: bool,
    },
    /// Deletes the table row at the caret.
    DeleteRow,
    /// Deletes the table column at the caret.
    DeleteColumn,
    /// Deletes the table at the caret.
    DeleteTable,
    /// Aligns the table column at the caret.
    SetColumnAlign(ColumnAlign),
    /// Opens the link bar for the selection (or word under the caret).
    EditLink,
    /// Inserts text at the caret, replacing the selection.
    InsertText(String),
    /// Same as the Tab key.
    Indent,
    /// Same as Shift+Tab.
    Outdent,
    SelectAll,
    Copy,
    Cut,
    /// Pastes an image (with the `images` feature, desktop) or text.
    Paste,
    /// Inserts an image from its encoded bytes, following the [`ImageSettings`].
    InsertImage {
        bytes: Vec<u8>,
        /// File name, used as description and in [`PastedImage::name`].
        name: Option<String>,
    },
    /// Like [`Command::InsertImage`] with the content of a file (desktop).
    InsertImageFile(PathBuf),
    /// Inserts `![alt](url)` for an image that already has a URL.
    InsertImageLink {
        url: String,
        alt: String,
    },
    /// Answer to [`Event::ImagePasted`]: the placeholder becomes `![alt](url)`.
    ResolveImage {
        id: ImageId,
        url: String,
        alt: String,
    },
    /// Answer to [`Event::ImagePasted`]: the placeholder is removed.
    CancelImage {
        id: ImageId,
    },
    /// Emits [`Event::ImageRequested`] (the toolbar's image button).
    RequestImage,
    SetMode(Mode),
    Focus,
    Blur,
    ZoomIn,
    ZoomOut,
    ResetZoom,
    /// Sets a zoom factor (1.0 = 100 %).
    SetZoom(f32),
    /// Zooms so the page width fits the widget.
    FitWidth,
    /// Zooms so a whole page fits the widget.
    FitPage,
}

/// Something that happened inside the editor.
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
    /// The document content changed. Call [`EditorState::markdown`] here,
    /// not in `view`.
    Changed,
    /// The caret or selection moved.
    SelectionChanged,
    ModeChanged(Mode),
    /// The zoom factor changed (1.0 = 100 %).
    ZoomChanged(f32),
    Focused,
    Blurred,
    /// A link was Ctrl/Cmd-clicked.
    LinkClicked(String),
    /// An image to store ([`ImageMode::Delegate`](crate::ImageMode::Delegate)).
    /// Answer with [`Command::ResolveImage`] or [`Command::CancelImage`].
    ImagePasted(PastedImage),
    /// An image was not accepted.
    ImageRejected {
        source: ImageSource,
        reason: ImageRejection,
    },
    /// The toolbar's image button was pressed. Show a file dialog.
    ImageRequested,
}

/// Result of [`EditorState::update`].
pub struct Output {
    /// Must be returned from your `update` (mapped to your message type).
    pub task: Task<Action>,
    /// Events produced by this update, in order.
    pub events: Vec<Event>,
}

/// Formatting at the caret, for building custom toolbars.
#[derive(Debug, Clone, PartialEq)]
pub struct Formatting {
    pub bold: bool,
    pub italic: bool,
    pub strike: bool,
    pub code: bool,
    pub link: Option<String>,
    /// Block type: `Paragraph`, `Heading`, `Code`, `Rule` or `Html`.
    pub block: BlockKind,
    /// Innermost list: `Some(true)` numbered, `Some(false)` bullets.
    pub list: Option<bool>,
    /// Task state of the innermost list item.
    pub task: Option<bool>,
    /// Number of nested lists at the caret.
    pub list_depth: usize,
    /// The caret is inside a block quote.
    pub quote: bool,
    /// Language of the code block at the caret, if any.
    pub code_language: Option<String>,
    /// The caret is inside a table.
    pub table: bool,
    /// Alignment of the table column at the caret.
    pub column_align: Option<ColumnAlign>,
}

pub(crate) struct Snapshot {
    pub doc: Document,
    pub sel: Selection,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum EditKind {
    None,
    Typing,
    Delete,
    Other,
}

/// The editor state. Keep one per editor in your application.
pub struct EditorState {
    pub(crate) doc: Document,
    pub(crate) sel: Selection,
    pub(crate) layout: RefCell<Layout>,
    pub(crate) cache: RefCell<canvas::Cache>,
    pub(crate) viewport: Cell<Size>,
    pub(crate) style: EditorStyle,
    pub(crate) paper: Paper,
    pub(crate) zoom: f32,
    pub(crate) zoom_settings: ZoomSettings,
    pub(crate) tab_width: usize,
    pub(crate) highlighter: Option<Arc<dyn CodeHighlighter>>,
    pub(crate) highlight_cache: RefCell<HashMap<u64, Arc<Vec<Color>>>>,
    pub(crate) features: Features,
    pub(crate) language: Language,
    pub(crate) renderers: Vec<Arc<dyn BlockRenderer>>,
    /// Language -> index in `renderers`.
    pub(crate) renderer_languages: HashMap<String, usize>,
    /// Measured sizes of rendered blocks.
    pub(crate) render_cache: RefCell<HashMap<u64, Option<Size>>>,
    pub(crate) image_settings: ImageSettings,
    pub(crate) image_base: Option<PathBuf>,
    pub(crate) image_loader: Option<ImageLoader>,
    pub(crate) image_cache: RefCell<ImageCache>,
    pub(crate) pending_images: HashMap<ImageId, Arc<[u8]>>,
    pub(crate) next_image_id: u64,
    /// Long `data:` URLs shortened in source mode.
    pub(crate) embedded: source::Embedded,
    pub(crate) mode: Mode,
    pub(crate) focused: bool,
    pub(crate) caret_on: bool,
    pub(crate) link_url: Option<String>,
    pub(crate) link_range: Option<(Pos, Pos)>,
    pub(crate) fonts: Fonts,
    pub(crate) pending: Option<Style>,
    pub(crate) goal_x: Option<f32>,
    pub(crate) undo: Vec<Snapshot>,
    pub(crate) redo: Vec<Snapshot>,
    pub(crate) last_edit: EditKind,
    pub(crate) modifiers: Modifiers,
    pub(crate) last_activity: Instant,
    pub(crate) scroll_x: f32,
    pub(crate) scroll_y: f32,
    pub(crate) revision: u64,
    pub(crate) dirty: bool,
    pub(crate) pending_events: Vec<Event>,
}

impl Default for EditorState {
    fn default() -> Self {
        Self::new()
    }
}

impl EditorState {
    /// An empty document.
    pub fn new() -> Self {
        Self::with_markdown("")
    }

    /// A document parsed from CommonMark (with the GFM extensions
    /// strikethrough, task lists and tables; see [`Self::features`]).
    pub fn with_markdown(markdown_text: &str) -> Self {
        let state = Self {
            doc: markdown::parse(markdown_text),
            sel: Selection::caret(Pos::new(0, 0)),
            layout: RefCell::new(Layout::default()),
            cache: RefCell::new(canvas::Cache::new()),
            viewport: Cell::new(Size::new(1000.0, 700.0)),
            style: EditorStyle::default(),
            paper: Paper::default(),
            zoom: 1.0,
            zoom_settings: ZoomSettings::default(),
            tab_width: DEFAULT_TAB_WIDTH,
            highlighter: None,
            highlight_cache: RefCell::new(HashMap::new()),
            features: Features::default(),
            language: Language::default(),
            renderers: Vec::new(),
            renderer_languages: HashMap::new(),
            render_cache: RefCell::new(HashMap::new()),
            image_settings: ImageSettings::default(),
            image_base: None,
            image_loader: None,
            image_cache: RefCell::new(ImageCache::default()),
            pending_images: HashMap::new(),
            next_image_id: 1,
            embedded: source::Embedded::default(),
            mode: Mode::Wysiwyg,
            focused: false,
            caret_on: true,
            link_url: None,
            link_range: None,
            fonts: Fonts::load(),
            pending: None,
            goal_x: None,
            undo: Vec::new(),
            redo: Vec::new(),
            last_edit: EditKind::None,
            modifiers: Modifiers::empty(),
            last_activity: Instant::now(),
            scroll_x: 0.0,
            scroll_y: 0.0,
            revision: 0,
            dirty: false,
            pending_events: Vec::new(),
        };
        state.relayout();
        state
    }

    /// Builder: sets the style.
    pub fn style(mut self, style: EditorStyle) -> Self {
        self.set_style(style);
        self
    }

    /// Builder: sets the paper.
    pub fn paper(mut self, paper: Paper) -> Self {
        self.set_paper(paper);
        self
    }

    /// Builder: sets the zoom settings.
    pub fn zoom_settings(mut self, settings: ZoomSettings) -> Self {
        self.set_zoom_settings(settings);
        self
    }

    /// Builder: sets the initial zoom.
    pub fn zoom(mut self, zoom: f32) -> Self {
        self.set_zoom(zoom);
        self
    }

    /// Builder: number of spaces the Tab key inserts (0 = Tab not handled).
    pub fn tab_width(mut self, spaces: usize) -> Self {
        self.set_tab_width(spaces);
        self
    }

    /// Builder: installs a code highlighting plugin.
    pub fn highlighter(mut self, highlighter: impl CodeHighlighter) -> Self {
        self.set_highlighter(Some(Arc::new(highlighter)));
        self
    }

    /// Builder: enables or disables optional Markdown features. The document
    /// is read again with the new features.
    pub fn features(mut self, features: Features) -> Self {
        self.set_features(features);
        self
    }

    /// Builder: sets the language of the toolbar, link bar and status bar.
    pub fn language(mut self, language: Language) -> Self {
        self.set_language(language);
        self
    }

    /// Builder: adds a renderer for fenced code blocks of some languages.
    /// Call it once per renderer; the first one listing a language wins.
    pub fn block_renderer(mut self, renderer: impl BlockRenderer) -> Self {
        let mut renderers = self.renderers.clone();
        renderers.push(Arc::new(renderer));
        self.set_block_renderers(renderers);
        self
    }

    /// Builder: what happens with pasted, dropped and inserted images.
    pub fn images(mut self, settings: ImageSettings) -> Self {
        self.set_image_settings(settings);
        self
    }

    /// Builder: folder for relative image URLs (desktop display).
    pub fn image_base(mut self, folder: impl Into<PathBuf>) -> Self {
        self.set_image_base(Some(folder.into()));
        self
    }

    /// Builder: loads image bytes for display by URL.
    pub fn image_loader(
        mut self,
        loader: impl Fn(&str) -> Option<Vec<u8>> + Send + Sync + 'static,
    ) -> Self {
        self.set_image_loader(Some(Arc::new(loader)));
        self
    }

    /// Builder: sets the mode.
    pub fn mode(mut self, mode: Mode) -> Self {
        self.set_mode(mode);
        self
    }

    // ----------------------------------------------------------------
    // Reading
    // ----------------------------------------------------------------

    /// The document as Markdown, without image placeholders and with full
    /// `data:` URLs. Builds the whole text: call it on changes, not in `view`.
    pub fn markdown(&self) -> String {
        match self.mode {
            Mode::Wysiwyg => markdown::serialize(&images::without_pending(&self.doc)),
            Mode::Source => self
                .embedded
                .expand(&source::text(&images::without_pending(&self.doc))),
        }
    }

    /// The document as plain text.
    pub fn plain_text(&self) -> String {
        self.doc.plain_text(self.doc.start(), self.doc.end())
    }

    /// The selected text, if any.
    pub fn selected_text(&self) -> Option<String> {
        let (a, b) = self.sel.range();
        (a != b).then(|| self.embedded.expand(&self.doc.plain_text(a, b)))
    }

    pub fn word_count(&self) -> usize {
        self.doc.word_count()
    }

    pub fn current_mode(&self) -> Mode {
        self.mode
    }

    pub fn current_style(&self) -> &EditorStyle {
        &self.style
    }

    pub fn current_paper(&self) -> &Paper {
        &self.paper
    }

    /// Current zoom factor (1.0 = 100 %).
    pub fn current_zoom(&self) -> f32 {
        self.zoom
    }

    pub fn current_zoom_settings(&self) -> &ZoomSettings {
        &self.zoom_settings
    }

    /// Spaces per Tab (0 = Tab not handled).
    pub fn current_tab_width(&self) -> usize {
        self.tab_width
    }

    pub fn current_image_settings(&self) -> &ImageSettings {
        &self.image_settings
    }

    /// Images handed to the application and not answered yet.
    pub fn pending_images(&self) -> usize {
        self.pending_images.len()
    }

    pub fn has_highlighter(&self) -> bool {
        self.highlighter.is_some()
    }

    pub fn current_features(&self) -> Features {
        self.features
    }

    pub fn current_language(&self) -> Language {
        self.language
    }

    /// Languages drawn by block renderers.
    pub fn rendered_languages(&self) -> Vec<String> {
        self.renderers
            .iter()
            .flat_map(|renderer| renderer.languages())
            .collect()
    }

    /// Languages offered for code blocks: from the highlighter (or a common
    /// list) and the block renderers.
    pub fn code_languages(&self) -> Vec<String> {
        let languages = self
            .highlighter
            .as_ref()
            .map(|highlighter| highlighter.languages())
            .unwrap_or_default();
        let mut languages: Vec<String> = if languages.is_empty() {
            COMMON_LANGUAGES
                .iter()
                .map(|name| name.to_string())
                .collect()
        } else {
            languages
        };
        for language in self.rendered_languages() {
            if !languages.contains(&language) {
                languages.push(language);
            }
        }
        languages
    }

    /// `(checked, total)` task list items.
    pub fn task_progress(&self) -> (usize, usize) {
        let mut seen = Vec::new();
        let mut checked = 0;
        for block in &self.doc.blocks {
            for container in &block.containers {
                if let Container::Item {
                    id,
                    task: Some(done),
                    ..
                } = container
                {
                    if !seen.contains(id) {
                        seen.push(*id);
                        if *done {
                            checked += 1;
                        }
                    }
                }
            }
        }
        (checked, seen.len())
    }

    /// Number of pages (1 in full-width mode).
    pub fn page_count(&self) -> usize {
        self.layout.borrow().pages.len().max(1)
    }

    /// Page (1-based) that contains the caret.
    pub fn current_page(&self) -> usize {
        self.layout.borrow().page_of(self.sel.head) + 1
    }

    pub fn is_focused(&self) -> bool {
        self.focused
    }

    /// `true` when the content changed since the last load or save.
    pub fn is_dirty(&self) -> bool {
        self.dirty
    }

    pub fn can_undo(&self) -> bool {
        !self.undo.is_empty()
    }

    pub fn can_redo(&self) -> bool {
        !self.redo.is_empty()
    }

    /// Formatting at the caret (or at the start of the selection).
    pub fn formatting(&self) -> Formatting {
        let (a, b) = self.sel.range();
        let style = if a == b {
            self.typing_style()
        } else {
            self.doc.blocks[a.block]
                .styles
                .get(a.offset)
                .cloned()
                .unwrap_or_default()
        };
        let block = &self.doc.blocks[self.sel.head.block];
        let leaf_kind = match block.leaf {
            Leaf::Paragraph | Leaf::Line | Leaf::Cell(_) => BlockKind::Paragraph,
            Leaf::Heading(level) => BlockKind::Heading(level),
            Leaf::Code => BlockKind::Code,
            Leaf::Html => BlockKind::Html,
            Leaf::Rule => BlockKind::Rule,
        };
        let item = block
            .containers
            .iter()
            .rev()
            .find(|c| matches!(c, Container::Item { .. }));
        Formatting {
            bold: style.bold,
            italic: style.italic,
            strike: style.strike,
            code: style.code,
            link: style.link.map(|link| link.url.clone()),
            block: leaf_kind,
            list: item.and_then(Container::list).map(|list| list.ordered),
            task: item.and_then(Container::task),
            list_depth: block
                .containers
                .iter()
                .filter(|c| c.list().is_some())
                .count(),
            quote: block.containers.iter().any(Container::is_quote),
            code_language: if block.leaf == Leaf::Code {
                block.language().map(str::to_string)
            } else {
                None
            },
            table: block.cell().is_some(),
            column_align: block.cell().map(|cell| cell.align),
        }
    }

    // ----------------------------------------------------------------
    // Writing
    // ----------------------------------------------------------------

    /// Replaces the whole document. Clears history, pending images and the
    /// dirty flag.
    pub fn set_markdown(&mut self, markdown_text: &str) {
        self.doc = match self.mode {
            Mode::Wysiwyg => markdown::parse_with(markdown_text, self.features),
            Mode::Source => source::document(&self.embedded.shorten(markdown_text)),
        };
        self.sel = Selection::caret(Pos::new(0, 0));
        self.undo.clear();
        self.redo.clear();
        self.pending_images.clear();
        self.reset_transient();
        self.dirty = false;
        self.revision += 1;
        self.scroll_x = 0.0;
        self.scroll_y = 0.0;
        self.relayout();
    }

    /// Clears the dirty flag (call after saving).
    pub fn mark_saved(&mut self) {
        self.dirty = false;
    }

    pub fn set_style(&mut self, style: EditorStyle) {
        self.style = style;
        self.relayout();
    }

    pub fn set_paper(&mut self, paper: Paper) {
        self.paper = paper;
        self.relayout();
        self.clamp_scroll();
    }

    pub fn set_zoom_settings(&mut self, settings: ZoomSettings) {
        self.zoom_settings = settings;
        self.zoom = self.zoom_settings.clamp(self.zoom);
        self.relayout();
        self.clamp_scroll();
    }

    /// Sets the zoom factor (1.0 = 100 %), also when zoom is disabled.
    pub fn set_zoom(&mut self, zoom: f32) {
        self.zoom = self.zoom_settings.clamp(zoom);
        self.relayout();
        self.clamp_scroll();
    }

    /// Spaces per Tab; `0` leaves Tab to the application.
    pub fn set_tab_width(&mut self, spaces: usize) {
        self.tab_width = spaces.min(16);
    }

    pub fn set_highlighter(&mut self, highlighter: Option<Arc<dyn CodeHighlighter>>) {
        self.highlighter = highlighter;
        self.highlight_cache.borrow_mut().clear();
        self.relayout();
    }

    /// Sets the language of the toolbar, link bar and status bar. The
    /// document is not changed.
    pub fn set_language(&mut self, language: Language) {
        self.language = language;
    }

    /// Enables or disables optional Markdown features. In WYSIWYG mode the
    /// document is read again, as if it had been loaded with the new
    /// features; the undo history starts again.
    pub fn set_features(&mut self, features: Features) {
        if features == self.features {
            return;
        }
        self.features = features;
        if self.mode == Mode::Wysiwyg {
            let text = markdown::serialize(&self.doc);
            self.doc = markdown::parse_with(&text, features);
            self.sel = Selection {
                anchor: self.doc.clamp(self.sel.anchor),
                head: self.doc.clamp(self.sel.head),
            };
            self.undo.clear();
            self.redo.clear();
            self.reset_transient();
        }
        self.relayout();
    }

    /// Replaces the block renderers. The first renderer listing a language
    /// draws it.
    pub fn set_block_renderers(&mut self, renderers: Vec<Arc<dyn BlockRenderer>>) {
        let mut languages = HashMap::new();
        for (index, renderer) in renderers.iter().enumerate() {
            for language in renderer.languages() {
                languages.entry(language).or_insert(index);
            }
        }
        self.renderers = renderers;
        self.renderer_languages = languages;
        self.render_cache.borrow_mut().clear();
        self.relayout();
    }

    pub fn set_image_settings(&mut self, settings: ImageSettings) {
        self.image_settings = settings;
    }

    pub fn set_image_base(&mut self, folder: Option<PathBuf>) {
        self.image_base = folder;
        self.reload_images();
    }

    pub fn set_image_loader(&mut self, loader: Option<ImageLoader>) {
        self.image_loader = loader;
        self.reload_images();
    }

    /// Forgets loaded images and loads them again.
    pub fn reload_images(&mut self) {
        self.image_cache.borrow_mut().clear();
        self.relayout();
    }

    /// Switches between WYSIWYG and source mode. The undo history starts
    /// again after a switch.
    pub fn set_mode(&mut self, mode: Mode) {
        if mode == self.mode {
            return;
        }
        self.doc = match mode {
            Mode::Source => {
                let text = markdown::serialize(&self.doc);
                let text = self.embedded.shorten(&text);
                source::document(&text)
            }
            Mode::Wysiwyg => {
                let text = self.embedded.expand(&source::text(&self.doc));
                markdown::parse_with(&text, self.features)
            }
        };
        self.mode = mode;
        self.sel = Selection::caret(Pos::new(0, 0));
        self.undo.clear();
        self.redo.clear();
        self.reset_transient();
        self.highlight_cache.borrow_mut().clear();
        self.scroll_x = 0.0;
        self.scroll_y = 0.0;
        self.relayout();
    }

    /// Runs a command and reports what happened.
    pub fn execute(&mut self, command: Command) -> Output {
        self.update(Action(Inner::Command(command)))
    }

    /// Handles an [`Action`] produced by the widget.
    pub fn update(&mut self, action: Action) -> Output {
        let revision = self.revision;
        let sel = self.sel;
        let mode = self.mode;
        let focused = self.focused;
        let zoom = self.zoom;

        let task = self.apply(action.0);

        // A rendered block shows its code while the caret is in it.
        if self.sel.head.block != sel.head.block
            && (self.renderer_for(sel.head.block).is_some()
                || self.renderer_for(self.sel.head.block).is_some())
        {
            self.relayout();
        }

        let mut events = std::mem::take(&mut self.pending_events);
        if self.focused != focused {
            events.push(if self.focused {
                Event::Focused
            } else {
                Event::Blurred
            });
        }
        if self.mode != mode {
            events.push(Event::ModeChanged(self.mode));
        }
        if (self.zoom - zoom).abs() > f32::EPSILON {
            events.push(Event::ZoomChanged(self.zoom));
        }
        if self.revision != revision {
            events.push(Event::Changed);
        }
        if self.sel != sel {
            events.push(Event::SelectionChanged);
        }

        Output { task, events }
    }

    /// Caret blinking and dropped image files:
    /// `state.subscription().map(Message::Editor)`.
    pub fn subscription(&self) -> Subscription<Action> {
        let blink = if self.focused {
            iced::time::every(BLINK).map(|_| Action(Inner::Blink))
        } else {
            Subscription::none()
        };
        let drops = if self.image_settings.enabled() && self.image_settings.drop {
            iced::event::listen_with(file_dropped)
        } else {
            Subscription::none()
        };
        Subscription::batch([blink, drops])
    }

    // ----------------------------------------------------------------
    // Internal helpers
    // ----------------------------------------------------------------

    pub(crate) fn expand_width(&self) -> usize {
        if self.tab_width == 0 {
            DEFAULT_TAB_WIDTH
        } else {
            self.tab_width
        }
    }

    pub(crate) fn new_image_id(&mut self) -> ImageId {
        let id = ImageId(self.next_image_id);
        self.next_image_id += 1;
        id
    }

    /// Highlight colours for a code block, from the plugin (cached).
    pub(crate) fn code_colors(&self, index: usize) -> Option<Arc<Vec<Color>>> {
        let highlighter = self.highlighter.as_ref()?;
        let block = self.doc.blocks.get(index)?;
        if block.leaf != Leaf::Code || block.chars.is_empty() {
            return None;
        }
        let language = block.language()?;
        let palette = &self.style.palette;

        let mut hasher = DefaultHasher::new();
        language.hash(&mut hasher);
        block.chars.hash(&mut hasher);
        for channel in [palette.code_background, palette.code] {
            channel.r.to_bits().hash(&mut hasher);
            channel.g.to_bits().hash(&mut hasher);
            channel.b.to_bits().hash(&mut hasher);
        }
        let key = hasher.finish();

        if let Some(colors) = self.highlight_cache.borrow().get(&key) {
            return Some(colors.clone());
        }

        let code: String = block.chars.iter().collect();
        let spans = highlighter.highlight(&HighlightRequest {
            language,
            code: &code,
            background: palette.code_background,
            dark: highlight::is_dark(palette.code_background),
        });

        let len = block.chars.len();
        let mut colors = vec![palette.code; len];
        for span in spans {
            let start = span.range.start.min(len);
            let end = span.range.end.min(len);
            for color in &mut colors[start..end.max(start)] {
                *color = span.color;
            }
        }

        let colors = Arc::new(colors);
        let mut cache = self.highlight_cache.borrow_mut();
        if cache.len() > 512 {
            cache.clear();
        }
        cache.insert(key, colors.clone());
        Some(colors)
    }

    /// The block renderer for block `index`, if it is a code block of one
    /// of its languages (WYSIWYG mode only).
    pub(crate) fn renderer_for(&self, index: usize) -> Option<&Arc<dyn BlockRenderer>> {
        if self.mode != Mode::Wysiwyg || self.renderers.is_empty() {
            return None;
        }
        let block = self.doc.blocks.get(index)?;
        if block.leaf != Leaf::Code {
            return None;
        }
        let renderer = *self.renderer_languages.get(block.language()?)?;
        self.renderers.get(renderer)
    }

    /// Size of block `index` drawn by its renderer (cached); `None` while
    /// the caret is in it or when the renderer declines.
    fn measure_block(&self, index: usize, width: f32, max_height: f32) -> Option<Size> {
        if index == self.sel.head.block {
            return None;
        }
        let renderer = self.renderer_for(index)?;
        let block = &self.doc.blocks[index];
        let code: String = block.chars.iter().collect();

        let mut hasher = DefaultHasher::new();
        Arc::as_ptr(renderer).cast::<()>().hash(&mut hasher);
        block.info.hash(&mut hasher);
        code.hash(&mut hasher);
        for value in [width, max_height, self.zoom] {
            value.to_bits().hash(&mut hasher);
        }
        let key = hasher.finish();
        if let Some(size) = self.render_cache.borrow().get(&key) {
            return *size;
        }

        let size = renderer.measure(&RenderRequest {
            language: block.language().unwrap_or(""),
            info: block.info.as_deref().unwrap_or(""),
            code: &code,
            width,
            max_height,
            zoom: self.zoom,
            style: &self.style,
        });
        let mut cache = self.render_cache.borrow_mut();
        if cache.len() > 512 {
            cache.clear();
        }
        cache.insert(key, size);
        size
    }

    /// Draws block `index` with its renderer; `available` is the room it
    /// was measured for.
    pub(crate) fn draw_block(
        &self,
        frame: &mut Frame,
        index: usize,
        bounds: Rectangle,
        available: Size,
    ) {
        let Some(renderer) = self.renderer_for(index) else {
            return;
        };
        let block = &self.doc.blocks[index];
        let code: String = block.chars.iter().collect();
        let request = RenderRequest {
            language: block.language().unwrap_or(""),
            info: block.info.as_deref().unwrap_or(""),
            code: &code,
            width: available.width,
            max_height: available.height,
            zoom: self.zoom,
            style: &self.style,
        };
        renderer.draw(frame, bounds, &request);
    }

    pub(crate) fn relayout(&self) {
        let cache = &self.image_cache;
        let base = self.image_base.as_deref();
        let loader = self.image_loader.as_ref();
        let lookup = |url: &str| cache.borrow_mut().get(url, base, loader);
        let custom = |index: usize, width: f32, max_height: f32| {
            self.measure_block(index, width, max_height)
        };
        let layout = compute_layout(
            &self.doc,
            &self.fonts,
            &self.style,
            &self.paper,
            self.viewport.get(),
            self.zoom,
            Lookups {
                images: &lookup,
                custom: &custom,
            },
        );
        *self.layout.borrow_mut() = layout;
        self.cache.borrow_mut().clear();
    }

    /// Called while drawing with the widget size.
    pub(crate) fn sync_viewport(&self, size: Size) {
        let current = self.viewport.get();
        if (current.width - size.width).abs() > 0.5 || (current.height - size.height).abs() > 0.5 {
            self.viewport.set(size);
            self.relayout();
        }
    }

    /// Largest scroll offsets for the current layout and widget size.
    pub(crate) fn max_scroll(&self) -> (f32, f32) {
        let layout = self.layout.borrow();
        let viewport = self.viewport.get();
        (
            (layout.width - viewport.width).max(0.0),
            (layout.height - viewport.height).max(0.0),
        )
    }

    /// Scroll offsets clamped to the content (used while drawing).
    pub(crate) fn clamped_scroll(&self) -> (f32, f32) {
        let (max_x, max_y) = self.max_scroll();
        (
            self.scroll_x.clamp(0.0, max_x),
            self.scroll_y.clamp(0.0, max_y),
        )
    }

    pub(crate) fn set_scroll(&mut self, x: f32, y: f32) {
        let (max_x, max_y) = self.max_scroll();
        let x = x.clamp(0.0, max_x);
        let y = y.clamp(0.0, max_y);
        if (x - self.scroll_x).abs() > 0.01 || (y - self.scroll_y).abs() > 0.01 {
            self.scroll_x = x;
            self.scroll_y = y;
            self.cache.borrow_mut().clear();
        }
    }

    pub(crate) fn clamp_scroll(&mut self) {
        let (x, y) = (self.scroll_x, self.scroll_y);
        self.set_scroll(x, y);
    }

    pub(crate) fn reset_transient(&mut self) {
        self.pending = None;
        self.goal_x = None;
        self.last_edit = EditKind::None;
        self.link_url = None;
        self.link_range = None;
    }

    pub(crate) fn touch(&mut self) {
        self.last_activity = Instant::now();
        self.caret_on = true;
    }

    pub(crate) fn typing_style(&self) -> Style {
        match &self.pending {
            Some(style) => style.clone(),
            None => self.doc.typing_style(self.sel.range().0),
        }
    }

    pub(crate) fn begin_edit(&mut self, kind: EditKind) {
        let coalesce =
            kind == self.last_edit && matches!(kind, EditKind::Typing | EditKind::Delete);
        if !coalesce {
            self.undo.push(Snapshot {
                doc: self.doc.clone(),
                sel: self.sel,
            });
            if self.undo.len() > 300 {
                self.undo.remove(0);
            }
        }
        self.redo.clear();
        self.last_edit = kind;
    }

    pub(crate) fn after_edit(&mut self) -> Task<Action> {
        self.dirty = true;
        self.revision += 1;
        self.goal_x = None;
        self.relayout();
        self.touch();
        self.scroll_to_caret()
    }

    /// Scrolls so that the caret is visible.
    pub(crate) fn scroll_to_caret(&mut self) -> Task<Action> {
        let caret = self.layout.borrow().caret(self.sel.head);
        let Some((x, y, height)) = caret else {
            return Task::none();
        };
        let viewport = self.viewport.get();
        let margin = 24.0;
        let (mut sx, mut sy) = (self.scroll_x, self.scroll_y);

        if y < sy + margin {
            sy = y - 2.0 * margin;
        } else if y + height > sy + viewport.height - margin {
            sy = y + height - viewport.height + 2.0 * margin;
        }
        if !self.paper.is_fill() {
            if x < sx + margin {
                sx = x - 4.0 * margin;
            } else if x > sx + viewport.width - margin {
                sx = x - viewport.width + 4.0 * margin;
            }
        }
        self.set_scroll(sx, sy);
        Task::none()
    }

    /// Changes the zoom and keeps the visible area roughly in place.
    pub(crate) fn zoom_to(&mut self, zoom: f32) -> Task<Action> {
        let zoom = self.zoom_settings.clamp(zoom);
        if (zoom - self.zoom).abs() < 1.0e-4 {
            return Task::none();
        }
        let ratio = zoom / self.zoom;
        let viewport = self.viewport.get();
        let center_x = self.scroll_x + viewport.width / 2.0;
        let center_y = self.scroll_y + viewport.height / 2.0;

        self.zoom = zoom;
        self.relayout();
        self.set_scroll(
            center_x * ratio - viewport.width / 2.0,
            center_y * ratio - viewport.height / 2.0,
        );
        Task::none()
    }

    pub(crate) fn block_len(&self, index: usize) -> usize {
        self.doc.blocks.get(index).map(Block::len).unwrap_or(0)
    }
}

/// Files dropped onto the window (images are filtered in the editor).
fn file_dropped(
    event: iced::Event,
    _status: iced::event::Status,
    _window: iced::window::Id,
) -> Option<Action> {
    match event {
        iced::Event::Window(iced::window::Event::FileDropped(path)) => {
            Some(Action(Inner::FileDropped(path)))
        }
        _ => None,
    }
}