rusty-rich 0.3.0

Rich text and beautiful formatting in the terminal — a Rust port of Python's Rich library
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
//! Text style — equivalent to Rich's `style.py`.
//!
//! A [`Style`] combines foreground/background color with 13 text attributes
//! (bold, dim, italic, underline, blink, reverse, strike, underline2, frame,
//! encircle, overline, blink2, conceal), plus optional link and metadata.
//!
//! # Quick Example
//!
//! ```rust
//! use rusty_rich::{Style, Color};
//!
//! let style = Style::new()
//!     .color(Color::parse("cyan").unwrap())
//!     .bgcolor(Color::parse("#1E1E2E").unwrap())
//!     .bold(true)
//!     .italic(true);
//!
//! // Parse from a string
//! let parsed = Style::from_str("bold red on blue");
//! ```
//!
//! # Style Combination
//!
//! Styles combine left-to-right via [`Style::combine`] with a 3-state attribute
//! cascade: explicit `true` wins over inherit, explicit `false` resets, and
//! unset falls through to the parent.
//!
//! # StyleStack
//!
//! [`StyleStack`] tracks nested style inheritance for markup parsing. Push
//! a style when entering a tag, pop when leaving.

use std::fmt;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicU32, Ordering};

use crate::color::{Color, ColorType, EIGHT_BIT_PALETTE, STANDARD_COLOR_NAMES, STANDARD_PALETTE};

static NEXT_ID: AtomicU32 = AtomicU32::new(0);

// ---------------------------------------------------------------------------
// Style attributes — bit flags
// ---------------------------------------------------------------------------

/// Bit flags for text attributes.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Attributes(u32);

impl Attributes {
    /// Bit flag for bold text.
    pub const BOLD: u32 = 1 << 0;
    /// Bit flag for dim/dark text.
    pub const DIM: u32 = 1 << 1;
    /// Bit flag for italic text.
    pub const ITALIC: u32 = 1 << 2;
    /// Bit flag for underlined text.
    pub const UNDERLINE: u32 = 1 << 3;
    /// Bit flag for blinking text.
    pub const BLINK: u32 = 1 << 4;
    /// Bit flag for reverse-video text.
    pub const REVERSE: u32 = 1 << 5;
    /// Bit flag for strikethrough text.
    pub const STRIKE: u32 = 1 << 6;
    /// Bit flag for double underline.
    pub const UNDERLINE2: u32 = 1 << 7;
    /// Bit flag for framed text.
    pub const FRAME: u32 = 1 << 8;
    /// Bit flag for encircled text.
    pub const ENCIRCLE: u32 = 1 << 9;
    /// Bit flag for overlined text.
    pub const OVERLINE: u32 = 1 << 10;
    /// Bit flag for rapid blink.
    pub const BLINK2: u32 = 1 << 11;
    /// Bit flag for concealed/hidden text.
    pub const CONCEAL: u32 = 1 << 12;

    /// Create an empty set of attributes (no flags set).
    pub const fn empty() -> Self {
        Self(0)
    }

    /// Set or clear a specific attribute bit.
    pub fn set(&mut self, bit: u32, value: bool) {
        if value {
            self.0 |= bit;
        } else {
            self.0 &= !bit;
        }
    }

    /// Check whether a specific attribute bit is set.
    pub fn get(&self, bit: u32) -> bool {
        self.0 & bit != 0
    }

    /// Return the raw bitmask value.
    pub const fn bits(&self) -> u32 {
        self.0
    }
}

/// All 13 style attribute bits in order (for iteration).
pub const STYLE_BITS: &[u32] = &[
    Attributes::BOLD, Attributes::DIM, Attributes::ITALIC,
    Attributes::UNDERLINE, Attributes::BLINK, Attributes::REVERSE,
    Attributes::STRIKE, Attributes::UNDERLINE2, Attributes::FRAME,
    Attributes::ENCIRCLE, Attributes::OVERLINE, Attributes::BLINK2,
    Attributes::CONCEAL,
];

/// All 13 style attribute (name, bit) pairs for iteration.
pub const STYLE_ATTRIBUTES: &[(&str, u32)] = &[
    ("bold", Attributes::BOLD),
    ("dim", Attributes::DIM),
    ("italic", Attributes::ITALIC),
    ("underline", Attributes::UNDERLINE),
    ("blink", Attributes::BLINK),
    ("reverse", Attributes::REVERSE),
    ("strike", Attributes::STRIKE),
    ("underline2", Attributes::UNDERLINE2),
    ("frame", Attributes::FRAME),
    ("encircle", Attributes::ENCIRCLE),
    ("overline", Attributes::OVERLINE),
    ("blink2", Attributes::BLINK2),
    ("conceal", Attributes::CONCEAL),
];

impl fmt::Display for Attributes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut parts: Vec<&str> = Vec::new();
        if self.get(Self::BOLD) { parts.push("bold"); }
        if self.get(Self::DIM) { parts.push("dim"); }
        if self.get(Self::ITALIC) { parts.push("italic"); }
        if self.get(Self::UNDERLINE) { parts.push("underline"); }
        if self.get(Self::BLINK) { parts.push("blink"); }
        if self.get(Self::REVERSE) { parts.push("reverse"); }
        if self.get(Self::CONCEAL) { parts.push("conceal"); }
        if self.get(Self::STRIKE) { parts.push("strike"); }
        if self.get(Self::OVERLINE) { parts.push("overline"); }
        if parts.is_empty() {
            write!(f, "none")
        } else {
            write!(f, "{}", parts.join(" "))
        }
    }
}

// ---------------------------------------------------------------------------
// Style
// ---------------------------------------------------------------------------

/// A terminal style.
///
/// Supports foreground color, background color, attributes, and an optional
/// hyperlink. Attributes use a three-state system: set to `true`, set to
/// `false`, or not set (`None`).
#[derive(Debug, Clone)]
pub struct Style {
    pub(crate) color: Option<Color>,
    pub(crate) bgcolor: Option<Color>,
    pub(crate) attributes: Attributes,
    /// Which attribute bits have been explicitly set (vs inherited).
    pub(crate) set_attributes: u32,
    pub(crate) link: Option<String>,
    pub(crate) link_id: u32,
    pub(crate) is_null: bool,
    /// Arbitrary metadata attached to this style.
    pub(crate) meta: Option<Vec<u8>>,
}

impl Style {
    // -- constructors -------------------------------------------------------

    /// Create a null (empty) style.
    pub fn null() -> Self {
        Self {
            color: None,
            bgcolor: None,
            attributes: Attributes::empty(),
            set_attributes: 0,
            link: None,
            link_id: 0,
            is_null: true,
            meta: None,
        }
    }

    /// Create a new style with optional settings.
    pub fn new() -> Self {
        Self {
            color: None,
            bgcolor: None,
            attributes: Attributes::empty(),
            set_attributes: 0,
            link: None,
            link_id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
            is_null: false,
            meta: None,
        }
    }

    /// Builder: set foreground color.
    pub fn color(mut self, color: impl Into<Option<Color>>) -> Self {
        self.color = color.into();
        self
    }

    /// Builder: set background color.
    pub fn bgcolor(mut self, bgcolor: impl Into<Option<Color>>) -> Self {
        self.bgcolor = bgcolor.into();
        self
    }

    /// Builder: set bold.
    pub fn bold(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::BOLD;
        self.attributes.set(Attributes::BOLD, value);
        self
    }

    /// Builder: set dim.
    pub fn dim(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::DIM;
        self.attributes.set(Attributes::DIM, value);
        self
    }

    /// Builder: set italic.
    pub fn italic(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::ITALIC;
        self.attributes.set(Attributes::ITALIC, value);
        self
    }

    /// Builder: set underline.
    pub fn underline(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::UNDERLINE;
        self.attributes.set(Attributes::UNDERLINE, value);
        self
    }

    /// Builder: set blink.
    pub fn blink(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::BLINK;
        self.attributes.set(Attributes::BLINK, value);
        self
    }

    /// Builder: set reverse.
    pub fn reverse(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::REVERSE;
        self.attributes.set(Attributes::REVERSE, value);
        self
    }

    /// Builder: set strikethrough.
    pub fn strike(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::STRIKE;
        self.attributes.set(Attributes::STRIKE, value);
        self
    }

    /// Builder: set blink2 (rapid blink).
    pub fn blink2(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::BLINK2;
        self.attributes.set(Attributes::BLINK2, value);
        self
    }

    /// Builder: set conceal.
    pub fn conceal(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::CONCEAL;
        self.attributes.set(Attributes::CONCEAL, value);
        self
    }

    /// Builder: set double underline.
    pub fn underline2(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::UNDERLINE2;
        self.attributes.set(Attributes::UNDERLINE2, value);
        self
    }

    /// Builder: set frame.
    pub fn frame(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::FRAME;
        self.attributes.set(Attributes::FRAME, value);
        self
    }

    /// Builder: set encircle.
    pub fn encircle(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::ENCIRCLE;
        self.attributes.set(Attributes::ENCIRCLE, value);
        self
    }

    /// Builder: set overline.
    pub fn overline(mut self, value: bool) -> Self {
        self.set_attributes |= Attributes::OVERLINE;
        self.attributes.set(Attributes::OVERLINE, value);
        self
    }

    /// Return a copy with foreground and background colors stripped.
    pub fn without_color(&self) -> Self {
        let mut s = self.clone();
        s.color = None;
        s.bgcolor = None;
        s
    }

    /// Return a style with the background color set to the foreground color,
    /// useful for background-only rendering.
    pub fn background_style(&self) -> Self {
        let mut s = Self::new();
        s.bgcolor = self.color.clone();
        s
    }

    /// Returns true if the background is not set (transparent).
    pub fn transparent_background(&self) -> bool {
        self.bgcolor.is_none()
    }

    /// Builder: set link.
    pub fn link(mut self, url: impl Into<String>) -> Self {
        self.link = Some(url.into());
        self.link_id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
        self
    }

    /// Builder: set style from a string (e.g. "bold red on blue").
    pub fn from_str(definition: &str) -> Self {
        let mut style = Self::new();
        for part in definition.split_whitespace() {
            match part {
                "bold" | "b" => { style.set_attributes |= Attributes::BOLD; style.attributes.set(Attributes::BOLD, true); }
                "dim" | "d" => { style.set_attributes |= Attributes::DIM; style.attributes.set(Attributes::DIM, true); }
                "italic" | "i" => { style.set_attributes |= Attributes::ITALIC; style.attributes.set(Attributes::ITALIC, true); }
                "underline" | "u" => { style.set_attributes |= Attributes::UNDERLINE; style.attributes.set(Attributes::UNDERLINE, true); }
                "blink" => { style.set_attributes |= Attributes::BLINK; style.attributes.set(Attributes::BLINK, true); }
                "reverse" | "r" => { style.set_attributes |= Attributes::REVERSE; style.attributes.set(Attributes::REVERSE, true); }
                "strike" | "s" => { style.set_attributes |= Attributes::STRIKE; style.attributes.set(Attributes::STRIKE, true); }
                "not bold" | "!bold" | "nobold" => { style.set_attributes |= Attributes::BOLD; style.attributes.set(Attributes::BOLD, false); }
                "not italic" | "!italic" | "noitalic" => { style.set_attributes |= Attributes::ITALIC; style.attributes.set(Attributes::ITALIC, false); }
                "not underline" | "!underline" | "nounderline" => { style.set_attributes |= Attributes::UNDERLINE; style.attributes.set(Attributes::UNDERLINE, false); }
                "none" | "default" => {}
                "on" => { /* "on <color>" handled below */ }
                part if part.starts_with("on ") => {
                    if let Ok(c) = Color::parse(&part[3..]) {
                        style.bgcolor = Some(c);
                    }
                }
                part if part.starts_with("link=") => {
                    style.link = Some(part[5..].to_string());
                }
                part => {
                    // Try as color name
                    if let Ok(c) = Color::parse(part) {
                        if style.bgcolor.is_some() && style.color.is_none() {
                            // We already saw "on" — don't overwrite fg
                        } else {
                            style.color = Some(c);
                        }
                    }
                }
            }
        }
        style
    }

    // -- queries ------------------------------------------------------------

    /// Returns `true` if this is a null (empty) style.
    pub fn is_null(&self) -> bool {
        self.is_null
    }

    /// Returns `true` if this style has no colors, attributes, or link set.
    pub fn is_plain(&self) -> bool {
        self.color.is_none()
            && self.bgcolor.is_none()
            && self.set_attributes == 0
            && self.link.is_none()
    }

    /// Check if the bold attribute is explicitly set to `true`.
    pub fn get_bold(&self) -> Option<bool> {
        if self.set_attributes & Attributes::BOLD != 0 {
            Some(self.attributes.get(Attributes::BOLD))
        } else {
            None
        }
    }

    /// Check if the italic attribute is explicitly set to `true`.
    pub fn get_italic(&self) -> Option<bool> {
        if self.set_attributes & Attributes::ITALIC != 0 {
            Some(self.attributes.get(Attributes::ITALIC))
        } else {
            None
        }
    }

    /// Merge two styles: `self` is the base, `other` overrides.
    pub fn combine(&self, other: &Style) -> Style {
        if other.is_null {
            return self.clone();
        }
        if self.is_null {
            return other.clone();
        }

        let mut combined = self.clone();
        if other.color.is_some() {
            combined.color = other.color.clone();
        }
        if other.bgcolor.is_some() {
            combined.bgcolor = other.bgcolor.clone();
        }
        // Attributes: other's set bits override self (3-state cascade)
        for &bit in STYLE_BITS {
            if other.set_attributes & bit != 0 {
                combined.set_attributes |= bit;
                combined.attributes.set(bit, other.attributes.get(bit));
            }
        }
        if other.link.is_some() {
            combined.link = other.link.clone();
            combined.link_id = other.link_id;
        }
        if other.meta.is_some() {
            combined.meta = other.meta.clone();
        }
        combined.is_null = false;
        combined
    }

    /// Render this style as ANSI SGR escape sequences.
    pub fn to_ansi(&self) -> String {
        if self.is_null {
            return String::new();
        }
        let mut codes: Vec<String> = Vec::new();

        // Foreground color
        if let Some(ref c) = self.color {
            match c.color_type {
                crate::color::ColorType::Default => codes.push("39".into()),
                crate::color::ColorType::Standard => {
                    if let Some(n) = c.number {
                        if n < 8 {
                            codes.push((30 + n).to_string());
                        } else {
                            codes.push((82 + n).to_string()); // 90-97 for bright
                        }
                    }
                }
                crate::color::ColorType::EightBit => {
                    if let Some(n) = c.number {
                        codes.push(format!("38;5;{n}"));
                    }
                }
                crate::color::ColorType::TrueColor => {
                    if let Some((r, g, b)) = c.triplet {
                        codes.push(format!("38;2;{r};{g};{b}"));
                    }
                }
            }
        }

        // Background color
        if let Some(ref c) = self.bgcolor {
            match c.color_type {
                crate::color::ColorType::Default => codes.push("49".into()),
                crate::color::ColorType::Standard => {
                    if let Some(n) = c.number {
                        if n < 8 {
                            codes.push((40 + n).to_string());
                        } else {
                            codes.push((92 + n).to_string()); // 100-107
                        }
                    }
                }
                crate::color::ColorType::EightBit => {
                    if let Some(n) = c.number {
                        codes.push(format!("48;5;{n}"));
                    }
                }
                crate::color::ColorType::TrueColor => {
                    if let Some((r, g, b)) = c.triplet {
                        codes.push(format!("48;2;{r};{g};{b}"));
                    }
                }
            }
        }

        // Attributes
        if self.set_attributes & Attributes::BOLD != 0 {
            codes.push(if self.attributes.get(Attributes::BOLD) { "1" } else { "22" }.into());
        }
        if self.set_attributes & Attributes::DIM != 0 {
            codes.push(if self.attributes.get(Attributes::DIM) { "2" } else { "22" }.into());
        }
        if self.set_attributes & Attributes::ITALIC != 0 {
            codes.push(if self.attributes.get(Attributes::ITALIC) { "3" } else { "23" }.into());
        }
        if self.set_attributes & Attributes::UNDERLINE != 0 {
            codes.push(if self.attributes.get(Attributes::UNDERLINE) { "4" } else { "24" }.into());
        }
        if self.set_attributes & Attributes::BLINK != 0 {
            codes.push(if self.attributes.get(Attributes::BLINK) { "5" } else { "25" }.into());
        }
        if self.set_attributes & Attributes::REVERSE != 0 {
            codes.push(if self.attributes.get(Attributes::REVERSE) { "7" } else { "27" }.into());
        }
        if self.set_attributes & Attributes::CONCEAL != 0 {
            codes.push(if self.attributes.get(Attributes::CONCEAL) { "8" } else { "28" }.into());
        }
        if self.set_attributes & Attributes::STRIKE != 0 {
            codes.push(if self.attributes.get(Attributes::STRIKE) { "9" } else { "29" }.into());
        }
        if self.set_attributes & Attributes::CONCEAL != 0 {
            codes.push(if self.attributes.get(Attributes::CONCEAL) { "8" } else { "28" }.into());
        }
        if self.set_attributes & Attributes::UNDERLINE2 != 0 {
            codes.push(if self.attributes.get(Attributes::UNDERLINE2) { "21" } else { "24" }.into());
        }
        if self.set_attributes & Attributes::BLINK2 != 0 {
            codes.push(if self.attributes.get(Attributes::BLINK2) { "6" } else { "25" }.into());
        }
        if self.set_attributes & Attributes::FRAME != 0 {
            codes.push(if self.attributes.get(Attributes::FRAME) { "51" } else { "54" }.into());
        }
        if self.set_attributes & Attributes::ENCIRCLE != 0 {
            codes.push(if self.attributes.get(Attributes::ENCIRCLE) { "52" } else { "54" }.into());
        }
        if self.set_attributes & Attributes::OVERLINE != 0 {
            codes.push(if self.attributes.get(Attributes::OVERLINE) { "53" } else { "55" }.into());
        }

        if codes.is_empty() {
            String::new()
        } else {
            format!("\x1b[{}m", codes.join(";"))
        }
    }

    /// Return the ANSI reset sequence needed to turn off this style.
    pub fn reset_ansi(&self) -> &'static str {
        "\x1b[0m"
    }

    // -- chaining --------------------------------------------------------------

    /// Create a chain-of-styles fallback. When `self` has a value set, use it;
    /// otherwise fall through to `other`.
    pub fn chain(&self, other: &Style) -> Style {
        let mut result = Style::new();
        result.color = self.color.clone().or_else(|| other.color.clone());
        result.bgcolor = self.bgcolor.clone().or_else(|| other.bgcolor.clone());
        result.link = self.link.clone().or_else(|| other.link.clone());
        result.meta = self.meta.clone().or_else(|| other.meta.clone());
        for &bit in STYLE_BITS {
            if self.set_attributes & bit != 0 {
                result.set_attributes |= bit;
                result.attributes.set(bit, self.attributes.get(bit));
            } else if other.set_attributes & bit != 0 {
                result.set_attributes |= bit;
                result.attributes.set(bit, other.attributes.get(bit));
            }
        }
        result
    }

    // -- copy / clear ----------------------------------------------------------

    /// Explicit clone (delegates to Clone, named for Python parity).
    pub fn copy(&self) -> Style {
        self.clone()
    }

    /// Clear the meta field and link field, returning self for chaining.
    pub fn clear_meta_and_links(&mut self) -> &mut Self {
        self.meta = None;
        self.link = None;
        self
    }

    // -- constructors ----------------------------------------------------------

    /// Create a style with just a foreground color set.
    pub fn from_color(color: Color) -> Self {
        Self::new().color(color)
    }

    /// Create a style with metadata.
    pub fn from_meta(meta: Vec<u8>) -> Self {
        let mut s = Self::new();
        s.meta = Some(meta);
        s
    }

    // -- html export -----------------------------------------------------------

    /// Generate CSS style string for HTML export.
    pub fn get_html_style(&self, _theme: Option<&crate::export::ExportTheme>) -> String {
        if self.is_null {
            return String::new();
        }
        let mut parts: Vec<String> = Vec::new();

        if let Some(ref c) = self.color {
            let hex = color_to_css_hex(c);
            if !hex.is_empty() {
                parts.push(format!("color: {}", hex));
            }
        }
        if let Some(ref c) = self.bgcolor {
            let hex = color_to_css_hex(c);
            if !hex.is_empty() {
                parts.push(format!("background-color: {}", hex));
            }
        }
        if self.set_attributes & Attributes::BOLD != 0 && self.attributes.get(Attributes::BOLD) {
            parts.push("font-weight: bold".into());
        }
        if self.set_attributes & Attributes::ITALIC != 0 && self.attributes.get(Attributes::ITALIC) {
            parts.push("font-style: italic".into());
        }

        // text-decoration: combine underline and strike
        let mut decor: Vec<&str> = Vec::new();
        if self.set_attributes & Attributes::UNDERLINE != 0
            && self.attributes.get(Attributes::UNDERLINE)
        {
            decor.push("underline");
        }
        if self.set_attributes & Attributes::UNDERLINE2 != 0
            && self.attributes.get(Attributes::UNDERLINE2)
        {
            decor.push("underline");
        }
        if self.set_attributes & Attributes::STRIKE != 0
            && self.attributes.get(Attributes::STRIKE)
        {
            decor.push("line-through");
        }
        if !decor.is_empty() {
            parts.push(format!("text-decoration: {}", decor.join(" ")));
        }

        if parts.is_empty() {
            String::new()
        } else {
            parts.join("; ")
        }
    }

    // -- normalize -------------------------------------------------------------

    /// Return a "normalized" style: remove negative (explicitly false) attributes
    /// that just reset inherited ones. Only keep explicitly true attributes and
    /// colors.
    pub fn normalize(&self) -> Style {
        let mut s = Style::new();
        s.color = self.color.clone();
        s.bgcolor = self.bgcolor.clone();
        s.link = self.link.clone();
        s.link_id = self.link_id;
        s.meta = self.meta.clone();
        for &bit in STYLE_BITS {
            if self.set_attributes & bit != 0 && self.attributes.get(bit) {
                s.set_attributes |= bit;
                s.attributes.set(bit, true);
            }
        }
        s
    }

    // -- utility ---------------------------------------------------------------

    /// Return the "first" significant color name for display purposes
    /// (fg color name, or bg color name, or None).
    pub fn pick_first(&self) -> Option<&'static str> {
        if let Some(ref c) = self.color {
            if let Some(name) = color_to_name(c) {
                return Some(name);
            }
        }
        if let Some(ref c) = self.bgcolor {
            if let Some(name) = color_to_name(c) {
                return Some(name);
            }
        }
        None
    }

    /// Render `text` wrapped in this style's ANSI codes.
    pub fn render(&self, text: &str) -> String {
        format!("{}{}{}", self.to_ansi(), text, self.reset_ansi())
    }

    /// Render a test/demo string. If text is None, use "Lorem ipsum".
    pub fn test(&self, text: Option<&str>) -> String {
        let t = text.unwrap_or("Lorem ipsum");
        self.render(t)
    }

    /// Update or clear the link, returning self for chaining.
    pub fn update_link(&mut self, url: Option<String>) -> &mut Self {
        self.link = url;
        if self.link.is_some() {
            self.link_id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
        }
        self
    }

    // -- accessors -------------------------------------------------------------

    /// Get a reference to metadata.
    pub fn meta(&self) -> Option<&Vec<u8>> {
        self.meta.as_ref()
    }

    /// Get a mutable reference to metadata.
    pub fn meta_mut(&mut self) -> Option<&mut Vec<u8>> {
        self.meta.as_mut()
    }

    /// Set metadata, returning self for chaining.
    pub fn set_meta(&mut self, meta: Option<Vec<u8>>) -> &mut Self {
        self.meta = meta;
        self
    }

    /// Get the link ID.
    pub fn link_id(&self) -> u32 {
        self.link_id
    }

    /// Alias for `bgcolor()` (Python rich has both `.on()` and `.bgcolor()`).
    pub fn on(self, color: impl Into<Option<Color>>) -> Self {
        self.bgcolor(color)
    }

    /// Get a reference to the foreground color.
    pub fn color_ref(&self) -> Option<&Color> {
        self.color.as_ref()
    }

    /// Get a reference to the background color.
    pub fn bgcolor_ref(&self) -> Option<&Color> {
        self.bgcolor.as_ref()
    }
}

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

impl PartialEq for Style {
    fn eq(&self, other: &Self) -> bool {
        self.color == other.color
            && self.bgcolor == other.bgcolor
            && self.attributes == other.attributes
            && self.set_attributes == other.set_attributes
            && self.link == other.link
    }
}

impl Eq for Style {}

impl Hash for Style {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.color.hash(state);
        self.bgcolor.hash(state);
        self.attributes.hash(state);
        self.set_attributes.hash(state);
        self.link.hash(state);
    }
}

impl fmt::Display for Style {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.is_null {
            return write!(f, "null");
        }
        let mut parts: Vec<String> = Vec::new();
        if let Some(ref c) = self.color {
            parts.push(c.to_string());
        }
        if let Some(ref c) = self.bgcolor {
            parts.push(format!("on {}", c));
        }
        let attrs = self.attributes.to_string();
        if attrs != "none" {
            parts.push(attrs);
        }
        if parts.is_empty() {
            write!(f, "none")
        } else {
            write!(f, "{}", parts.join(" "))
        }
    }
}

/// Convenience type alias.
pub type StyleType = Style;

// -- helper functions for html export and color name lookup ------------------

/// Convert a `Color` to a CSS hex string `#rrggbb`.
fn color_to_css_hex(c: &Color) -> String {
    match c.color_type {
        ColorType::Default => String::new(),
        ColorType::Standard => {
            if let Some(n) = c.number {
                let (r, g, b) = STANDARD_PALETTE[n as usize];
                format!("#{:02x}{:02x}{:02x}", r, g, b)
            } else {
                String::new()
            }
        }
        ColorType::EightBit => {
            if let Some(n) = c.number {
                let [r, g, b] = EIGHT_BIT_PALETTE[n as usize];
                format!("#{:02x}{:02x}{:02x}", r, g, b)
            } else {
                String::new()
            }
        }
        ColorType::TrueColor => {
            if let Some((r, g, b)) = c.triplet {
                format!("#{:02x}{:02x}{:02x}", r, g, b)
            } else {
                String::new()
            }
        }
    }
}

/// Return the static color name for a Standard color, or `None` otherwise.
fn color_to_name(c: &Color) -> Option<&'static str> {
    match c.color_type {
        ColorType::Standard => {
            if let Some(n) = c.number {
                Some(STANDARD_COLOR_NAMES[n as usize])
            } else {
                None
            }
        }
        _ => None,
    }
}

// ---------------------------------------------------------------------------
// StyleStack — a stack of styles (for nested markup)
// ---------------------------------------------------------------------------

/// A stack of styles, used when rendering nested markup.
#[derive(Debug, Clone)]
pub struct StyleStack {
    stack: Vec<Style>,
    default_style: Style,
}

impl StyleStack {
    /// Create a new style stack with a given default style.
    pub fn new(default_style: Style) -> Self {
        Self {
            stack: Vec::new(),
            default_style,
        }
    }

    /// Get the current (combined) style.
    pub fn current(&self) -> Style {
        let mut combined = self.default_style.clone();
        for s in &self.stack {
            combined = combined.combine(s);
        }
        combined
    }

    /// Push a style onto the stack.
    pub fn push(&mut self, style: Style) {
        self.stack.push(style);
    }

    /// Pop the top style.
    pub fn pop(&mut self) -> Option<Style> {
        self.stack.pop()
    }

    /// Get the depth.
    pub fn len(&self) -> usize {
        self.stack.len()
    }

    /// Returns `true` if the stack is empty (no pushed styles).
    pub fn is_empty(&self) -> bool {
        self.stack.is_empty()
    }
}

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

    #[test]
    fn test_style_parse() {
        let s = Style::from_str("bold red");
        assert_eq!(s.get_bold(), Some(true));
        assert!(s.color.is_some());
    }

    #[test]
    fn test_style_combine() {
        let base = Style::from_str("red");
        let over = Style::from_str("bold");
        let combined = base.combine(&over);
        assert_eq!(combined.get_bold(), Some(true));
        assert!(combined.color.is_some());
    }

    #[test]
    fn test_ansi_output() {
        let s = Style::new().color(Color::parse("red").unwrap()).bold(true);
        let ansi = s.to_ansi();
        assert!(ansi.contains("31")); // red foreground
        assert!(ansi.contains("1"));  // bold
    }

    #[test]
    fn test_chain() {
        let a = Style::new().bold(true);
        let b = Style::new().color(Color::parse("red").unwrap()).italic(true);
        let chained = a.chain(&b);
        assert_eq!(chained.get_bold(), Some(true));
        assert!(chained.attributes.get(Attributes::ITALIC));
        assert!(chained.set_attributes & Attributes::ITALIC != 0);
        assert!(chained.color.is_some());
    }

    #[test]
    fn test_chain_precedence() {
        let a = Style::new().bold(true).color(Color::parse("red").unwrap());
        let b = Style::new().bold(false).color(Color::parse("blue").unwrap());
        let chained = a.chain(&b);
        // a sets bold(true) and color(red); b sets bold(false) and color(blue)
        // chain: self's values take priority
        assert_eq!(chained.get_bold(), Some(true));
        let c = chained.color.as_ref().unwrap();
        let name = color_to_name(c);
        assert_eq!(name, Some("red"));
    }

    #[test]
    fn test_copy() {
        let s = Style::new().bold(true).color(Color::parse("red").unwrap());
        let c = s.copy();
        assert_eq!(s, c);
    }

    #[test]
    fn test_clear_meta_and_links() {
        let mut s = Style::new().link("https://example.com");
        s.meta = Some(vec![1, 2, 3]);
        s.clear_meta_and_links();
        assert!(s.link.is_none());
        assert!(s.meta.is_none());
    }

    #[test]
    fn test_from_color() {
        let s = Style::from_color(Color::parse("red").unwrap());
        assert!(s.color.is_some());
        assert!(s.bgcolor.is_none());
    }

    #[test]
    fn test_from_meta() {
        let s = Style::from_meta(vec![10, 20, 30]);
        assert_eq!(s.meta(), Some(&vec![10, 20, 30]));
    }

    #[test]
    fn test_get_html_style() {
        let s = Style::new()
            .color(Color::parse("red").unwrap())
            .bold(true)
            .italic(true);
        let css = s.get_html_style(None);
        assert!(css.contains("color:"));
        assert!(css.contains("font-weight: bold"));
        assert!(css.contains("font-style: italic"));
    }

    #[test]
    fn test_get_html_style_underline_strike() {
        let s = Style::new()
            .color(Color::parse("red").unwrap())
            .underline(true)
            .strike(true);
        let css = s.get_html_style(None);
        assert!(css.contains("text-decoration:"));
        assert!(css.contains("underline"));
        assert!(css.contains("line-through"));
    }

    #[test]
    fn test_get_html_style_null() {
        let s = Style::null();
        let css = s.get_html_style(None);
        assert!(css.is_empty());
    }

    #[test]
    fn test_normalize() {
        let s = Style::new().bold(true).italic(false);
        let n = s.normalize();
        assert_eq!(n.get_bold(), Some(true));
        // italic was set to false, so normalize should remove it
        assert!(n.set_attributes & Attributes::ITALIC == 0);
    }

    #[test]
    fn test_pick_first() {
        let s = Style::new().color(Color::parse("red").unwrap());
        assert_eq!(s.pick_first(), Some("red"));
    }

    #[test]
    fn test_pick_first_fallback() {
        let s = Style::new().bgcolor(Color::parse("blue").unwrap());
        assert_eq!(s.pick_first(), Some("blue"));
    }

    #[test]
    fn test_pick_first_none() {
        let s = Style::new();
        assert_eq!(s.pick_first(), None);
    }

    #[test]
    fn test_render() {
        let s = Style::new().bold(true).color(Color::parse("red").unwrap());
        let rendered = s.render("hello");
        assert!(rendered.starts_with("\x1b["));
        assert!(rendered.contains("hello"));
        assert!(rendered.ends_with("\x1b[0m"));
    }

    #[test]
    fn test_test_with_text() {
        let s = Style::new().bold(true);
        let out = s.test(Some("custom"));
        assert!(out.contains("custom"));
    }

    #[test]
    fn test_test_default() {
        let s = Style::new().bold(true);
        let out = s.test(None);
        assert!(out.contains("Lorem ipsum"));
    }

    #[test]
    fn test_update_link() {
        let mut s = Style::new();
        s.update_link(Some("https://example.com".into()));
        assert!(s.link.is_some());
        let first_id = s.link_id;
        s.update_link(None);
        assert!(s.link.is_none());
        assert_eq!(s.link_id, first_id);
    }

    #[test]
    fn test_link_id() {
        let s = Style::new().link("https://example.com");
        assert!(s.link_id() > 0);
    }

    #[test]
    fn test_meta_methods() {
        let mut s = Style::new();
        s.set_meta(Some(vec![1, 2, 3]));
        assert_eq!(s.meta(), Some(&vec![1, 2, 3]));
        if let Some(m) = s.meta_mut() {
            m.push(4);
        }
        assert_eq!(s.meta(), Some(&vec![1, 2, 3, 4]));
    }

    #[test]
    fn test_on() {
        let s = Style::new().on(Color::parse("red").unwrap());
        assert!(s.bgcolor.is_some());
        let b = Color::parse("red").unwrap();
        assert_eq!(s.bgcolor.unwrap(), b);
    }

    #[test]
    fn test_references() {
        let s = Style::new()
            .color(Color::parse("red").unwrap())
            .bgcolor(Color::parse("blue").unwrap());
        assert!(s.color_ref().is_some());
        assert!(s.bgcolor_ref().is_some());
    }

    #[test]
    fn test_color_to_css_hex() {
        let c = Color::parse("red").unwrap();
        let hex = color_to_css_hex(&c);
        assert_eq!(hex, "#800000"); // standard red
    }

    #[test]
    fn test_color_to_css_hex_truecolor() {
        let c = Color::from_rgb(255, 0, 128);
        let hex = color_to_css_hex(&c);
        assert_eq!(hex, "#ff0080");
    }

    #[test]
    fn test_static_attributes() {
        assert!(!STYLE_ATTRIBUTES.is_empty());
        let names: Vec<&str> = STYLE_ATTRIBUTES.iter().map(|(n, _)| *n).collect();
        assert!(names.contains(&"bold"));
        assert!(names.contains(&"italic"));
        assert!(names.contains(&"underline"));
        assert!(!names.contains(&"notexist"));
    }
}