rs-rich-ext 0.0.13

Extensions for the `rich` Rust port: diagnostics, structured data, clap and tracing integration, diffs, workflow renderables and a plugin registry
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
//! The extension registry: where plugins are hosted.
//!
//! A caller builds a registry, adds plugins, then installs it onto a
//! [`Console`]. Registration is **explicit** by default: a plugin is added by
//! [`ExtensionRegistry::add_plugin`], or, when the caller asks for them, every
//! plugin linked in with `rich_plugin_api::export_plugin!`
//! ([`ExtensionRegistry::add_linked_plugins`]) and runtime plugins loaded from
//! a path ([`crate::plugin_loading`]). Plugins implement the contract in
//! [`rich_plugin_api`], which depends only on core; this module is the host.
//! See docs/PLUGINS.md and docs/design/plugin-loading.md.

use std::collections::BTreeMap;
use std::panic::{catch_unwind, AssertUnwindSafe};
use std::sync::Arc;

use rich::console::ConsoleOptions;
use rich::r#box::Box as BoxStyle;
use rich::segment::Segment;
#[cfg(feature = "syntax")]
use rich::SyntectHighlighter;
use rich::{
    CodeHighlighter, CodeHighlighting, Console, ConsoleCodeHighlighting, FenceRenderer,
    Highlighter, Text, Theme,
};
use rich_plugin_api::{
    is_valid_name, Capability, ComponentFactory, CustomAction, HighlighterFactory, Plugin,
    PluginComponent, PluginError, PluginMetadata, PluginRegistrar, SourceRenderer, TextTransform,
    PLUGIN_API_VERSION,
};

use crate::transform::Pipeline;

/// A factory that produces a fresh highlighter each time it installs. The
/// highlighter is `Send` so the [`Console`] it installs onto stays `Send`.
type LocalHighlighterFactory = Box<dyn Fn() -> Box<dyn Highlighter + Send>>;

/// The id under which [`ExtensionRegistry::register_highlighter`] records
/// highlighters added without a plugin.
const DIRECT: &str = "(direct)";

/// A plugin a registry accepted, and what it registered.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RegisteredPlugin {
    pub metadata: PluginMetadata,
    pub capabilities: Vec<Capability>,
}

/// A collection of extensions to install onto a [`Console`].
#[derive(Default)]
pub struct ExtensionRegistry {
    /// Each factory with the plugin id that registered it, or [`DIRECT`].
    highlighters: Vec<(String, LocalHighlighterFactory)>,
    code_highlighters: BTreeMap<String, (String, Arc<dyn CodeHighlighter>)>,
    themes: BTreeMap<String, (String, Theme)>,
    box_styles: BTreeMap<String, (String, BoxStyle)>,
    renderers: BTreeMap<String, (String, Arc<dyn SourceRenderer>)>,
    fence_renderers: BTreeMap<String, (String, Arc<dyn FenceRenderer>)>,
    transforms: BTreeMap<String, (String, Arc<dyn TextTransform>)>,
    actions: BTreeMap<String, (String, Arc<dyn CustomAction>)>,
    components: BTreeMap<String, (String, ComponentFactory)>,
    plugins: Vec<RegisteredPlugin>,
    /// The code highlighter chosen as every console's default, and its theme.
    default_code_highlighter: Option<(String, Option<String>)>,
}

/// Why a code highlighter or theme could not be chosen.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HighlighterChoiceError {
    /// No registered code highlighter has this name.
    UnknownHighlighter {
        name: String,
        available: Vec<String>,
    },
    /// The highlighter has no theme of this name.
    UnknownTheme { highlighter: String, theme: String },
}

impl std::fmt::Display for HighlighterChoiceError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            HighlighterChoiceError::UnknownHighlighter { name, available } => write!(
                f,
                "unknown code highlighter {name:?}; available: {}",
                available.join(", ")
            ),
            HighlighterChoiceError::UnknownTheme { highlighter, theme } => write!(
                f,
                "the {highlighter} code highlighter has no theme {theme:?}"
            ),
        }
    }
}

impl std::error::Error for HighlighterChoiceError {}

impl ExtensionRegistry {
    /// An empty registry.
    pub fn new() -> Self {
        ExtensionRegistry::default()
    }

    /// A registry pre-loaded with this crate's defaults: the [`BuiltinPlugin`].
    pub fn with_defaults() -> Self {
        let mut registry = ExtensionRegistry::new();
        registry
            .add_plugin(&BuiltinPlugin)
            .expect("the built-in plugin registers cleanly");
        registry
    }

    /// [`with_defaults`](Self::with_defaults), then every plugin linked in with
    /// `rich_plugin_api::export_plugin!` ([`add_linked_plugins`](Self::add_linked_plugins)).
    pub fn with_linked_plugins() -> Result<Self, PluginError> {
        let mut registry = ExtensionRegistry::with_defaults();
        registry.add_linked_plugins()?;
        Ok(registry)
    }

    /// Add every plugin linked into this binary with
    /// `rich_plugin_api::export_plugin!`, sorted by plugin id so the order
    /// never depends on the linker. Returns their ids, in that order.
    ///
    /// Two linked plugins with the same id are an error
    /// ([`PluginError::DuplicatePlugin`]) and nothing is added; so is a linked
    /// plugin whose metadata panics. Otherwise each is added with
    /// [`add_plugin`](Self::add_plugin), and the first refusal is returned
    /// (the plugins before it stay added).
    pub fn add_linked_plugins(&mut self) -> Result<Vec<String>, PluginError> {
        let plugins: Vec<Box<dyn Plugin>> = rich_plugin_api::linked_plugins()
            .map(|linked| linked.plugin())
            .collect();
        self.add_plugin_set(plugins)
    }

    /// Add `plugins` as [`add_linked_plugins`](Self::add_linked_plugins) adds
    /// the linked ones: sorted by id, with a duplicate id refused before any
    /// is added.
    pub fn add_plugin_set(
        &mut self,
        plugins: impl IntoIterator<Item = Box<dyn Plugin>>,
    ) -> Result<Vec<String>, PluginError> {
        let mut keyed = Vec::new();
        for plugin in plugins {
            let metadata =
                catch_unwind(AssertUnwindSafe(|| plugin.metadata())).map_err(|panic| {
                    PluginError::Failed {
                        plugin: "(unknown)".to_string(),
                        message: format!("metadata panicked: {}", panic_message(&*panic)),
                    }
                })?;
            keyed.push((metadata.id, plugin));
        }
        keyed.sort_by(|a, b| a.0.cmp(&b.0));
        if let Some(pair) = keyed.windows(2).find(|pair| pair[0].0 == pair[1].0) {
            return Err(PluginError::DuplicatePlugin {
                id: pair[0].0.clone(),
            });
        }
        let mut added = Vec::with_capacity(keyed.len());
        for (id, plugin) in keyed {
            self.add_plugin(plugin.as_ref())?;
            added.push(id);
        }
        Ok(added)
    }

    /// Register a highlighter factory directly, without a plugin. The factory
    /// is invoked at [`install`] time so a registry can be installed onto
    /// multiple consoles.
    ///
    /// [`install`]: ExtensionRegistry::install
    pub fn register_highlighter<F>(&mut self, factory: F) -> &mut Self
    where
        F: Fn() -> Box<dyn Highlighter + Send> + 'static,
    {
        self.highlighters
            .push((DIRECT.to_string(), Box::new(factory)));
        self
    }

    /// Register a code highlighter directly, without a plugin, under `name`
    /// (lowercase letters, digits, `-`, `_` and `.`). Refused when the name is
    /// invalid or already taken.
    pub fn register_code_highlighter(
        &mut self,
        name: &str,
        highlighter: Arc<dyn CodeHighlighter>,
    ) -> Result<(), PluginError> {
        if !is_valid_name(name) {
            return Err(PluginError::InvalidName {
                plugin: DIRECT.to_string(),
                name: name.to_string(),
            });
        }
        let capability = Capability::CodeHighlighter(name.to_string());
        if let Some(existing) = self.provider(&capability) {
            return Err(PluginError::Conflict {
                capability,
                existing: existing.to_string(),
                plugin: DIRECT.to_string(),
            });
        }
        self.code_highlighters
            .insert(name.to_string(), (DIRECT.to_string(), highlighter));
        Ok(())
    }

    /// Add a plugin and everything it registers.
    ///
    /// Refused, with nothing kept, when the plugin was built for another
    /// [`PLUGIN_API_VERSION`], its id is invalid or already registered, a name
    /// it uses is invalid, it registers a capability another plugin already
    /// provides under the same name, or its own `register` fails.
    pub fn add_plugin(&mut self, plugin: &dyn Plugin) -> Result<(), PluginError> {
        // A plugin that panics is refused like one that fails: a third-party
        // bug must not take the host down.
        let metadata = catch_unwind(AssertUnwindSafe(|| plugin.metadata())).map_err(|panic| {
            PluginError::Failed {
                plugin: "(unknown)".to_string(),
                message: format!("metadata panicked: {}", panic_message(&*panic)),
            }
        })?;
        let id = metadata.id.clone();
        if !is_valid_name(&id) {
            return Err(PluginError::InvalidName {
                plugin: id.clone(),
                name: id,
            });
        }
        if metadata.api_version != PLUGIN_API_VERSION {
            return Err(PluginError::IncompatibleApi {
                plugin: id,
                built_for: metadata.api_version,
                host: PLUGIN_API_VERSION,
            });
        }
        if self.plugins.iter().any(|p| p.metadata.id == id) {
            return Err(PluginError::DuplicatePlugin { id });
        }

        let mut staged = Staged::default();
        match catch_unwind(AssertUnwindSafe(|| plugin.register(&mut staged))) {
            Ok(result) => result.map_err(|error| PluginError::Failed {
                plugin: id.clone(),
                message: error.to_string(),
            })?,
            Err(panic) => {
                return Err(PluginError::Failed {
                    plugin: id,
                    message: format!("register panicked: {}", panic_message(&*panic)),
                })
            }
        }
        if let Some(name) = staged.invalid_names.into_iter().next() {
            return Err(PluginError::InvalidName { plugin: id, name });
        }
        // Conflicts with other plugins, then within this one.
        let mut seen = Vec::new();
        for capability in &staged.capabilities {
            if let Some(existing) = self.provider(capability) {
                return Err(PluginError::Conflict {
                    capability: capability.clone(),
                    existing: existing.to_string(),
                    plugin: id,
                });
            }
            if *capability != Capability::Highlighter && seen.contains(&capability) {
                return Err(PluginError::Conflict {
                    capability: capability.clone(),
                    existing: id.clone(),
                    plugin: id,
                });
            }
            seen.push(capability);
        }

        for factory in staged.highlighters {
            self.highlighters
                .push((id.clone(), Box::new(move || factory())));
        }
        for (name, value) in staged.code_highlighters {
            self.code_highlighters.insert(name, (id.clone(), value));
        }
        for (name, value) in staged.themes {
            self.themes.insert(name, (id.clone(), value));
        }
        for (name, value) in staged.box_styles {
            self.box_styles.insert(name, (id.clone(), value));
        }
        for (name, value) in staged.renderers {
            self.renderers.insert(name, (id.clone(), value));
        }
        for (language, value) in staged.fence_renderers {
            self.fence_renderers.insert(language, (id.clone(), value));
        }
        for (name, value) in staged.transforms {
            self.transforms.insert(name, (id.clone(), value));
        }
        for (name, value) in staged.actions {
            self.actions.insert(name, (id.clone(), value));
        }
        for (name, value) in staged.components {
            self.components.insert(name, (id.clone(), value));
        }
        self.plugins.push(RegisteredPlugin {
            metadata,
            capabilities: staged.capabilities,
        });
        Ok(())
    }

    /// The plugin that provides a named capability, if any.
    fn provider(&self, capability: &Capability) -> Option<&str> {
        match capability {
            Capability::CodeHighlighter(name) => self.code_highlighters.get(name).map(|e| &e.0),
            Capability::Theme(name) => self.themes.get(name).map(|e| &e.0),
            Capability::BoxStyle(name) => self.box_styles.get(name).map(|e| &e.0),
            Capability::Renderer(name) => self.renderers.get(name).map(|e| &e.0),
            Capability::FenceRenderer(language) => self.fence_renderers.get(language).map(|e| &e.0),
            Capability::Transform(name) => self.transforms.get(name).map(|e| &e.0),
            Capability::Action(name) => self.actions.get(name).map(|e| &e.0),
            Capability::Component(name) => self.components.get(name).map(|e| &e.0),
            _ => None,
        }
        .map(String::as_str)
    }

    /// The plugins added, in the order they were added.
    pub fn plugins(&self) -> &[RegisteredPlugin] {
        &self.plugins
    }

    /// A code highlighter by name.
    pub fn code_highlighter(&self, name: &str) -> Option<Arc<dyn CodeHighlighter>> {
        self.code_highlighters.get(name).map(|e| e.1.clone())
    }

    /// Every code highlighter name, sorted.
    pub fn code_highlighter_names(&self) -> Vec<&str> {
        self.code_highlighters.keys().map(String::as_str).collect()
    }

    /// A theme by name.
    pub fn theme(&self, name: &str) -> Option<&Theme> {
        self.themes.get(name).map(|e| &e.1)
    }

    /// Every theme name, sorted: what a theme picker offers.
    pub fn theme_names(&self) -> Vec<&str> {
        self.themes.keys().map(String::as_str).collect()
    }

    /// A box style by name.
    pub fn box_style(&self, name: &str) -> Option<BoxStyle> {
        self.box_styles.get(name).map(|e| e.1)
    }

    /// A source renderer by name.
    pub fn renderer(&self, name: &str) -> Option<Arc<dyn SourceRenderer>> {
        self.renderers.get(name).map(|e| e.1.clone())
    }

    /// Make the code highlighter `name` (and `theme`, one of its themes; `None`
    /// is its default) the default for every console this registry is
    /// installed onto: `Syntax`, Markdown code, source views and diffs without
    /// a highlighter of their own use it.
    pub fn set_default_code_highlighter(
        &mut self,
        name: &str,
        theme: Option<&str>,
    ) -> Result<(), HighlighterChoiceError> {
        let highlighter = self.code_highlighter(name).ok_or_else(|| {
            HighlighterChoiceError::UnknownHighlighter {
                name: name.to_string(),
                available: self
                    .code_highlighter_names()
                    .into_iter()
                    .map(str::to_string)
                    .collect(),
            }
        })?;
        if let Some(theme) = theme {
            if !highlighter.themes().iter().any(|t| t == theme) {
                return Err(HighlighterChoiceError::UnknownTheme {
                    highlighter: name.to_string(),
                    theme: theme.to_string(),
                });
            }
        }
        self.default_code_highlighter = Some((name.to_string(), theme.map(str::to_string)));
        Ok(())
    }

    /// The default code highlighter's name, if one was chosen.
    pub fn default_code_highlighter(&self) -> Option<&str> {
        self.default_code_highlighter
            .as_ref()
            .map(|(name, _)| name.as_str())
    }

    /// The chosen default, ready for a console.
    pub fn code_highlighting(&self) -> Option<CodeHighlighting> {
        let (name, theme) = self.default_code_highlighter.as_ref()?;
        Some(CodeHighlighting {
            highlighter: self.code_highlighter(name)?,
            theme: theme.clone(),
        })
    }

    /// The fence renderer registered for `language`.
    pub fn fence_renderer(&self, language: &str) -> Option<Arc<dyn FenceRenderer>> {
        self.fence_renderers.get(language).map(|e| e.1.clone())
    }

    /// A text transform by name.
    pub fn transform(&self, name: &str) -> Option<Arc<dyn TextTransform>> {
        self.transforms.get(name).map(|e| e.1.clone())
    }

    /// Every custom action for interactive views, by name (sorted), with
    /// the plugin that registered it.
    pub fn actions(&self) -> Vec<(&str, &str, Arc<dyn CustomAction>)> {
        self.actions
            .iter()
            .map(|(name, (plugin, action))| (name.as_str(), plugin.as_str(), action.clone()))
            .collect()
    }

    /// The factory of the interactive component registered as `name`
    /// (`PluginRegistrar::component`). `rs-rich-interact`'s `PluginView`
    /// mounts one beside the built-in components.
    pub fn component(&self, name: &str) -> Option<ComponentFactory> {
        self.components.get(name).map(|e| e.1.clone())
    }

    /// A fresh instance of the component registered as `name`. `None` when
    /// no plugin registered one, or its factory panicked: a third-party bug
    /// must not take the host down.
    pub fn create_component(&self, name: &str) -> Option<Box<dyn PluginComponent>> {
        let factory = self.component(name)?;
        catch_unwind(AssertUnwindSafe(|| factory())).ok()
    }

    /// Every interactive component's name (sorted), with the plugin that
    /// registered it.
    pub fn component_names(&self) -> Vec<(&str, &str)> {
        self.components
            .iter()
            .map(|(name, (plugin, _))| (name.as_str(), plugin.as_str()))
            .collect()
    }

    /// Every text transform name, sorted.
    pub fn transform_names(&self) -> Vec<&str> {
        self.transforms.keys().map(String::as_str).collect()
    }

    /// A pipeline of the named text transforms, in the order given. Fails on
    /// the first name no plugin registered, with that name.
    pub fn text_pipeline<'n>(
        &self,
        names: impl IntoIterator<Item = &'n str>,
    ) -> Result<Pipeline<Text>, String> {
        let mut pipeline = Pipeline::new();
        for name in names {
            let transform = self.transform(name).ok_or_else(|| name.to_string())?;
            pipeline.push(name, Box::new(transform));
        }
        Ok(pipeline)
    }

    /// Register a text transform directly, without a plugin. Its provider is
    /// reported as `"(direct)"`.
    pub fn register_transform(
        &mut self,
        name: &str,
        transform: Arc<dyn TextTransform>,
    ) -> Result<(), PluginError> {
        if !is_valid_name(name) {
            return Err(PluginError::InvalidName {
                plugin: DIRECT.to_string(),
                name: name.to_string(),
            });
        }
        let capability = Capability::Transform(name.to_string());
        if let Some(existing) = self.provider(&capability) {
            return Err(PluginError::Conflict {
                capability,
                existing: existing.to_string(),
                plugin: DIRECT.to_string(),
            });
        }
        self.transforms
            .insert(name.to_string(), (DIRECT.to_string(), transform));
        Ok(())
    }

    /// One [`FenceRenderer`] that routes each fence to the renderer registered
    /// for its language, for [`rich::markdown::Markdown::fence_renderer`]. `None` when no
    /// plugin registered one, so a caller can leave Markdown untouched.
    pub fn fences(&self) -> Option<Arc<dyn FenceRenderer>> {
        if self.fence_renderers.is_empty() {
            return None;
        }
        let routes = self
            .fence_renderers
            .iter()
            .map(|(language, (_, renderer))| (language.clone(), renderer.clone()))
            .collect();
        Some(Arc::new(FenceRoutes(routes)))
    }

    /// The plugin id that provided a capability, or `"(direct)"` for one
    /// registered without a plugin. Highlighters are unnamed, so for
    /// [`Capability::Highlighter`] this is the first one registered.
    pub fn provided_by(&self, capability: &Capability) -> Option<&str> {
        match capability {
            Capability::Highlighter => self.highlighters.first().map(|(id, _)| id.as_str()),
            other => self.provider(other),
        }
    }

    /// Install every registered highlighter onto `console`, and the default
    /// code highlighter if one was chosen.
    pub fn install(&self, console: &mut Console) {
        for (_, factory) in &self.highlighters {
            console.add_highlighter(factory());
        }
        if let Some(highlighting) = self.code_highlighting() {
            console.set_code_highlighting(Some(highlighting));
        }
    }
}

/// Collects one plugin's registrations until they are checked.
#[derive(Default)]
struct Staged {
    capabilities: Vec<Capability>,
    invalid_names: Vec<String>,
    highlighters: Vec<HighlighterFactory>,
    code_highlighters: Vec<(String, Arc<dyn CodeHighlighter>)>,
    themes: Vec<(String, Theme)>,
    box_styles: Vec<(String, BoxStyle)>,
    renderers: Vec<(String, Arc<dyn SourceRenderer>)>,
    fence_renderers: Vec<(String, Arc<dyn FenceRenderer>)>,
    transforms: Vec<(String, Arc<dyn TextTransform>)>,
    actions: Vec<(String, Arc<dyn CustomAction>)>,
    components: Vec<(String, ComponentFactory)>,
}

/// Routes fences by language; see [`ExtensionRegistry::fences`].
struct FenceRoutes(BTreeMap<String, Arc<dyn FenceRenderer>>);

impl FenceRenderer for FenceRoutes {
    fn render_fence(
        &self,
        language: &str,
        code: &str,
        console: &Console,
        options: &ConsoleOptions,
    ) -> Option<Vec<Segment>> {
        self.0
            .get(language)?
            .render_fence(language, code, console, options)
    }
}

impl Staged {
    fn check(&mut self, name: &str) {
        if !is_valid_name(name) {
            self.invalid_names.push(name.to_string());
        }
    }
}

impl PluginRegistrar for Staged {
    fn highlighter(&mut self, factory: HighlighterFactory) {
        self.capabilities.push(Capability::Highlighter);
        self.highlighters.push(factory);
    }

    fn code_highlighter(&mut self, name: &str, highlighter: Arc<dyn CodeHighlighter>) {
        self.check(name);
        self.capabilities
            .push(Capability::CodeHighlighter(name.to_string()));
        self.code_highlighters.push((name.to_string(), highlighter));
    }

    fn theme(&mut self, name: &str, theme: Theme) {
        self.check(name);
        self.capabilities.push(Capability::Theme(name.to_string()));
        self.themes.push((name.to_string(), theme));
    }

    fn box_style(&mut self, name: &str, style: BoxStyle) {
        self.check(name);
        self.capabilities
            .push(Capability::BoxStyle(name.to_string()));
        self.box_styles.push((name.to_string(), style));
    }

    fn renderer(&mut self, name: &str, renderer: Arc<dyn SourceRenderer>) {
        self.check(name);
        self.capabilities
            .push(Capability::Renderer(name.to_string()));
        self.renderers.push((name.to_string(), renderer));
    }

    fn fence_renderer(&mut self, language: &str, renderer: Arc<dyn FenceRenderer>) {
        self.check(language);
        self.capabilities
            .push(Capability::FenceRenderer(language.to_string()));
        self.fence_renderers.push((language.to_string(), renderer));
    }

    fn transform(&mut self, name: &str, transform: Arc<dyn TextTransform>) {
        self.check(name);
        self.capabilities
            .push(Capability::Transform(name.to_string()));
        self.transforms.push((name.to_string(), transform));
    }

    fn action(&mut self, name: &str, action: Arc<dyn CustomAction>) {
        self.check(name);
        self.capabilities.push(Capability::Action(name.to_string()));
        self.actions.push((name.to_string(), action));
    }

    fn component(&mut self, name: &str, factory: ComponentFactory) {
        self.check(name);
        self.capabilities
            .push(Capability::Component(name.to_string()));
        self.components.push((name.to_string(), factory));
    }
}

/// This crate's defaults as a plugin: the number highlighter, and the default
/// code highlighter registered as `"syntect"`.
pub struct BuiltinPlugin;

impl Plugin for BuiltinPlugin {
    fn metadata(&self) -> PluginMetadata {
        PluginMetadata::new("rich-ext", "rich-ext built-ins", env!("CARGO_PKG_VERSION"))
            .description(if cfg!(feature = "syntax") {
                "number highlighting and the syntect code highlighter"
            } else {
                "number highlighting"
            })
    }

    fn register(&self, registrar: &mut dyn PluginRegistrar) -> Result<(), PluginError> {
        registrar.highlighter(Box::new(|| {
            Box::new(crate::highlighter::NumberHighlighter::new())
        }));
        #[cfg(feature = "syntax")]
        registrar.code_highlighter("syntect", SyntectHighlighter::shared());
        Ok(())
    }
}

/// Convenience: install this crate's default extensions onto a console.
pub fn install_defaults(console: &mut Console) {
    ExtensionRegistry::with_defaults().install(console);
}

/// The text of a caught panic, for the error that refuses the plugin.
fn panic_message(panic: &(dyn std::any::Any + Send)) -> String {
    if let Some(message) = panic.downcast_ref::<&str>() {
        (*message).to_string()
    } else if let Some(message) = panic.downcast_ref::<String>() {
        message.clone()
    } else {
        "a panic with no message".to_string()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use rich::ColorSystem;

    #[test]
    fn number_highlighter_installs_and_styles_digits() {
        let mut console = Console::builder()
            .force_terminal(true)
            .color_system(Some(ColorSystem::Truecolor))
            .build();
        install_defaults(&mut console);
        // "42" should be wrapped in bold cyan (1;36); surrounding text plain.
        let out = console.render_str_to_string("n=42");
        assert!(out.contains("\x1b[1;36m42\x1b[0m"), "got: {out:?}");
    }

    #[test]
    fn defaults_come_from_the_builtin_plugin() {
        let registry = ExtensionRegistry::with_defaults();
        assert_eq!(registry.plugins().len(), 1);
        assert_eq!(registry.plugins()[0].metadata.id, "rich-ext");
        #[cfg(feature = "syntax")]
        {
            assert_eq!(registry.code_highlighter_names(), ["syntect"]);
            assert_eq!(
                registry.provided_by(&Capability::CodeHighlighter("syntect".into())),
                Some("rich-ext")
            );
        }
        // Without `syntax` there is no syntect to register.
        #[cfg(not(feature = "syntax"))]
        assert!(registry.code_highlighter_names().is_empty());
    }

    /// A plugin that registers whatever it is given.
    struct Test {
        id: &'static str,
        api: u32,
        themes: Vec<&'static str>,
        fail: bool,
    }

    impl Plugin for Test {
        fn metadata(&self) -> PluginMetadata {
            let mut meta = PluginMetadata::new(self.id, self.id, "0.0.0");
            meta.api_version = self.api;
            meta
        }
        fn register(&self, registrar: &mut dyn PluginRegistrar) -> Result<(), PluginError> {
            for name in &self.themes {
                registrar.theme(name, Theme::new());
            }
            if self.fail {
                return Err(PluginError::Other("broken".into()));
            }
            Ok(())
        }
    }

    #[test]
    fn a_panicking_plugin_is_refused_and_leaves_the_registry_unchanged() {
        struct Panics {
            in_metadata: bool,
        }
        impl Plugin for Panics {
            fn metadata(&self) -> PluginMetadata {
                if self.in_metadata {
                    panic!("no metadata");
                }
                PluginMetadata::new("panics", "Panics", "0.0.0")
            }
            fn register(&self, registrar: &mut dyn PluginRegistrar) -> Result<(), PluginError> {
                registrar.theme("half", Theme::new());
                panic!("register blew up");
            }
        }
        let mut registry = ExtensionRegistry::with_defaults();
        for in_metadata in [false, true] {
            let error = registry.add_plugin(&Panics { in_metadata }).unwrap_err();
            assert!(matches!(error, PluginError::Failed { .. }), "{error:?}");
            let expected = if in_metadata {
                "no metadata"
            } else {
                "register blew up"
            };
            assert!(error.to_string().contains(expected), "{error}");
        }
        assert_eq!(registry.plugins().len(), 1);
        assert_eq!(
            registry.provided_by(&Capability::Theme("half".into())),
            None
        );
    }

    #[test]
    fn provided_by_highlighter_names_who_registered_it() {
        assert_eq!(
            ExtensionRegistry::new().provided_by(&Capability::Highlighter),
            None
        );
        assert_eq!(
            ExtensionRegistry::with_defaults().provided_by(&Capability::Highlighter),
            Some("rich-ext")
        );
        let mut direct = ExtensionRegistry::new();
        direct.register_highlighter(|| Box::new(rich::highlighter::ReprHighlighter::new()));
        assert_eq!(direct.provided_by(&Capability::Highlighter), Some(DIRECT));
    }

    fn plugin(id: &'static str, themes: &[&'static str]) -> Test {
        Test {
            id,
            api: PLUGIN_API_VERSION,
            themes: themes.to_vec(),
            fail: false,
        }
    }

    #[test]
    fn plugins_register_and_are_listed_in_order() {
        let mut registry = ExtensionRegistry::new();
        registry.add_plugin(&plugin("a", &["dark"])).unwrap();
        registry.add_plugin(&plugin("b", &["light"])).unwrap();
        let ids: Vec<_> = registry
            .plugins()
            .iter()
            .map(|p| p.metadata.id.as_str())
            .collect();
        assert_eq!(ids, ["a", "b"]);
        assert!(registry.theme("dark").is_some() && registry.theme("light").is_some());
        assert_eq!(registry.theme_names(), ["dark", "light"]);
    }

    /// Fences reach Markdown through `fences()`, routed by language, and two
    /// plugins cannot claim the same language.
    #[test]
    fn fence_renderers_route_by_language_and_conflict_by_language() {
        struct Tag(&'static str);
        impl FenceRenderer for Tag {
            fn render_fence(
                &self,
                _language: &str,
                _code: &str,
                _console: &Console,
                _options: &ConsoleOptions,
            ) -> Option<Vec<Segment>> {
                Some(vec![Segment::new(self.0, None), Segment::line()])
            }
        }
        struct Fences(&'static str, &'static str);
        impl Plugin for Fences {
            fn metadata(&self) -> PluginMetadata {
                PluginMetadata::new(self.0, self.0, "0.0.0")
            }
            fn register(&self, registrar: &mut dyn PluginRegistrar) -> Result<(), PluginError> {
                registrar.fence_renderer(self.1, Arc::new(Tag(self.1)));
                Ok(())
            }
        }

        let mut registry = ExtensionRegistry::with_defaults();
        assert!(registry.fences().is_none());
        registry.add_plugin(&Fences("diagrams", "mermaid")).unwrap();
        registry.add_plugin(&Fences("charts", "vega")).unwrap();
        let conflict = registry
            .add_plugin(&Fences("other", "mermaid"))
            .unwrap_err();
        assert!(
            matches!(conflict, PluginError::Conflict { .. }),
            "{conflict}"
        );
        assert_eq!(
            registry.provided_by(&Capability::FenceRenderer("mermaid".into())),
            Some("diagrams")
        );

        #[cfg(feature = "markdown")]
        {
            let md = rich::markdown::Markdown::new(
                "```mermaid\nx\n```\n\n```vega\ny\n```\n\n```rust\nz\n```",
            )
            .fence_renderer(registry.fences().unwrap());
            let console = Console::builder().width(30).color_system(None).build();
            let out = console.render_to_string(&md);
            assert!(out.contains("mermaid") && out.contains("vega"), "{out}");
            assert!(out.contains('z'), "the rust fence is still code: {out}");
        }
    }

    /// A chosen default reaches consoles on install; unknown names and themes
    /// are refused with what is available.
    #[cfg(feature = "syntax")]
    #[test]
    fn a_default_code_highlighter_is_chosen_by_name_and_installed() {
        let mut registry = ExtensionRegistry::with_defaults();
        assert!(registry.code_highlighting().is_none());
        let error = registry
            .set_default_code_highlighter("nope", None)
            .unwrap_err();
        assert_eq!(
            error.to_string(),
            "unknown code highlighter \"nope\"; available: syntect"
        );
        assert!(matches!(
            registry.set_default_code_highlighter("syntect", Some("no-theme")),
            Err(HighlighterChoiceError::UnknownTheme { .. })
        ));
        registry
            .set_default_code_highlighter("syntect", Some("ansi_dark"))
            .unwrap();
        assert_eq!(registry.default_code_highlighter(), Some("syntect"));

        let mut console = Console::builder()
            .width(30)
            .force_terminal(true)
            .color_system(Some(ColorSystem::Truecolor))
            .build();
        registry.install(&mut console);
        assert_eq!(
            console.code_highlighting().and_then(|h| h.theme.as_deref()),
            Some("ansi_dark")
        );
        // Code now renders in upstream's ANSI colours, with no RGB.
        let out = console.render_to_string(&rich::Syntax::new("def f(): pass", "python"));
        assert!(out.contains("\x1b[94mdef"), "{out:?}");
        assert!(!out.contains("38;2;"), "{out:?}");
    }

    #[cfg(feature = "syntax")]
    #[test]
    fn code_highlighters_register_directly() {
        let mut registry = ExtensionRegistry::with_defaults();
        registry
            .register_code_highlighter("mine", SyntectHighlighter::shared())
            .unwrap();
        assert_eq!(registry.code_highlighter_names(), ["mine", "syntect"]);
        assert_eq!(
            registry.provided_by(&Capability::CodeHighlighter("mine".into())),
            Some("(direct)")
        );
        assert!(matches!(
            registry.register_code_highlighter("syntect", SyntectHighlighter::shared()),
            Err(PluginError::Conflict { .. })
        ));
        assert!(matches!(
            registry.register_code_highlighter("Bad Name", SyntectHighlighter::shared()),
            Err(PluginError::InvalidName { .. })
        ));
    }

    #[test]
    fn plugins_contribute_text_transforms() {
        struct Shout;
        impl TextTransform for Shout {
            fn transform(&self, text: Text) -> Result<Text, PluginError> {
                Ok(Text::new(text.plain().to_uppercase()))
            }
        }
        struct Transforms;
        impl Plugin for Transforms {
            fn metadata(&self) -> PluginMetadata {
                PluginMetadata::new("transforms", "Transforms", "1.0.0")
            }
            fn register(&self, registrar: &mut dyn PluginRegistrar) -> Result<(), PluginError> {
                registrar.transform("shout", Arc::new(Shout));
                Ok(())
            }
        }

        let mut registry = ExtensionRegistry::new();
        registry.add_plugin(&Transforms).unwrap();
        registry
            .register_transform(
                "keep",
                Arc::new(crate::transform::KeepLines::new("a").unwrap()),
            )
            .unwrap();
        assert_eq!(registry.transform_names(), ["keep", "shout"]);
        assert_eq!(
            registry.plugins()[0].capabilities,
            [Capability::Transform("shout".into())]
        );
        assert_eq!(
            registry.provided_by(&Capability::Transform("keep".into())),
            Some("(direct)")
        );

        let pipeline = registry.text_pipeline(["keep", "shout"]).unwrap();
        assert_eq!(pipeline.names(), ["keep", "shout"]);
        let text = pipeline.apply(Text::new("abc\nxyz\n")).unwrap();
        assert_eq!(text.plain(), "ABC\n");
        assert_eq!(
            registry.text_pipeline(["shout", "nope"]).unwrap_err(),
            "nope"
        );
        assert!(matches!(
            registry.register_transform("shout", Arc::new(Shout)),
            Err(PluginError::Conflict { .. })
        ));
    }

    #[test]
    fn an_incompatible_api_version_is_refused_with_both_versions() {
        let mut registry = ExtensionRegistry::new();
        let mut old = plugin("old", &["x"]);
        old.api = PLUGIN_API_VERSION + 1;
        let error = registry.add_plugin(&old).unwrap_err();
        assert_eq!(
            error,
            PluginError::IncompatibleApi {
                plugin: "old".into(),
                built_for: PLUGIN_API_VERSION + 1,
                host: PLUGIN_API_VERSION,
            }
        );
        assert!(registry.plugins().is_empty() && registry.theme("x").is_none());
    }

    #[test]
    fn duplicate_ids_and_conflicting_names_are_refused_and_nothing_is_kept() {
        let mut registry = ExtensionRegistry::new();
        registry.add_plugin(&plugin("a", &["dark"])).unwrap();
        assert_eq!(
            registry.add_plugin(&plugin("a", &["other"])).unwrap_err(),
            PluginError::DuplicatePlugin { id: "a".into() }
        );
        let error = registry
            .add_plugin(&plugin("b", &["fresh", "dark"]))
            .unwrap_err();
        assert_eq!(
            error,
            PluginError::Conflict {
                capability: Capability::Theme("dark".into()),
                existing: "a".into(),
                plugin: "b".into(),
            }
        );
        // `fresh` was staged before the conflict and must not have been kept.
        assert!(registry.theme("fresh").is_none());
        assert_eq!(registry.plugins().len(), 1);
        // The same name twice inside one plugin is a conflict too.
        assert!(matches!(
            registry.add_plugin(&plugin("c", &["twice", "twice"])),
            Err(PluginError::Conflict { .. })
        ));
    }

    #[test]
    fn invalid_names_and_failed_registration_are_refused() {
        let mut registry = ExtensionRegistry::new();
        assert!(matches!(
            registry.add_plugin(&plugin("Bad Id", &[])),
            Err(PluginError::InvalidName { .. })
        ));
        assert!(matches!(
            registry.add_plugin(&plugin("ok", &["\u{1b}]0;x"])),
            Err(PluginError::InvalidName { .. })
        ));
        let mut broken = plugin("broken", &["kept-not"]);
        broken.fail = true;
        let error = registry.add_plugin(&broken).unwrap_err();
        assert_eq!(
            error,
            PluginError::Failed {
                plugin: "broken".into(),
                message: "broken".into(),
            }
        );
        assert!(registry.theme("kept-not").is_none() && registry.plugins().is_empty());
    }

    #[test]
    fn plugins_register_actions_for_interactive_views() {
        struct Reveal;
        impl CustomAction for Reveal {
            fn label(&self) -> String {
                "Reveal in file manager".into()
            }
            fn key(&self) -> Option<String> {
                Some("ctrl+r".into())
            }
            fn applies(&self, kind: &str, _: &str) -> bool {
                kind == "file"
            }
        }
        struct Actions;
        impl Plugin for Actions {
            fn metadata(&self) -> PluginMetadata {
                PluginMetadata::new("actions", "Actions", "0.0.0")
            }
            fn register(&self, registrar: &mut dyn PluginRegistrar) -> Result<(), PluginError> {
                registrar.action("reveal", Arc::new(Reveal));
                Ok(())
            }
        }
        let mut registry = ExtensionRegistry::new();
        registry.add_plugin(&Actions).unwrap();
        let actions = registry.actions();
        assert_eq!(actions.len(), 1);
        let (name, plugin, action) = &actions[0];
        assert_eq!((*name, *plugin), ("reveal", "actions"));
        assert!(action.applies("file", "a.txt") && !action.applies("row", "x"));
        assert_eq!(action.run("file", "a.txt"), Ok(None));
        assert_eq!(
            registry.plugins()[0].capabilities,
            [Capability::Action("reveal".into())]
        );
        // A second plugin may not take the name.
        struct Again;
        impl Plugin for Again {
            fn metadata(&self) -> PluginMetadata {
                PluginMetadata::new("again", "Again", "0.0.0")
            }
            fn register(&self, registrar: &mut dyn PluginRegistrar) -> Result<(), PluginError> {
                registrar.action("reveal", Arc::new(Reveal));
                Ok(())
            }
        }
        assert!(matches!(
            registry.add_plugin(&Again),
            Err(PluginError::Conflict { .. })
        ));
    }

    #[test]
    fn plugins_register_components_by_name() {
        use rich_plugin_api::component::{
            ComponentContext, ComponentEvent, ComponentFlow, ComponentView,
        };
        struct Blank;
        impl PluginComponent for Blank {
            fn handle(&mut self, _: &ComponentEvent, _: &ComponentContext<'_>) -> ComponentFlow {
                ComponentFlow::Ignored
            }
            fn render(&self, _: &ComponentContext<'_>) -> ComponentView {
                ComponentView::default()
            }
        }
        struct Views;
        impl Plugin for Views {
            fn metadata(&self) -> PluginMetadata {
                PluginMetadata::new("views", "Views", "0.0.0")
            }
            fn register(&self, registrar: &mut dyn PluginRegistrar) -> Result<(), PluginError> {
                registrar.component("blank", Arc::new(|| Box::new(Blank)));
                registrar.component("broken", Arc::new(|| panic!("no")));
                Ok(())
            }
        }
        let mut registry = ExtensionRegistry::new();
        registry.add_plugin(&Views).unwrap();
        assert_eq!(
            registry.component_names(),
            [("blank", "views"), ("broken", "views")]
        );
        assert_eq!(
            registry.provided_by(&Capability::Component("blank".into())),
            Some("views")
        );
        assert!(registry.create_component("blank").is_some());
        // A factory that panics mounts nothing; an unknown name neither.
        assert!(registry.create_component("broken").is_none());
        assert!(
            registry.create_component("nope").is_none() && registry.component("nope").is_none()
        );
        // The name is taken for every other plugin.
        struct Again;
        impl Plugin for Again {
            fn metadata(&self) -> PluginMetadata {
                PluginMetadata::new("again", "Again", "0.0.0")
            }
            fn register(&self, registrar: &mut dyn PluginRegistrar) -> Result<(), PluginError> {
                registrar.component("blank", Arc::new(|| Box::new(Blank)));
                Ok(())
            }
        }
        assert!(matches!(
            registry.add_plugin(&Again),
            Err(PluginError::Conflict { .. })
        ));
    }
}