gilt 1.7.0

Fast, beautiful terminal formatting for Rust — styles, tables, trees, syntax highlighting, progress bars, markdown.
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
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
//! Console engine — the central orchestrator of gilt rendering output.
//!
//! The Console manages terminal capabilities, drives the rendering pipeline,
//! and handles output buffering, capture, and export.

use crate::color::ColorSystem;
use crate::color_env::{detect_color_env, ColorEnvOverride};
use crate::control::Control;
use crate::error::ConsoleError;
use crate::export_format::{
    FontEmbedding, HtmlExportOptions, SvgExportOptions, CONSOLE_HTML_FORMAT, CONSOLE_SVG_FORMAT,
};
use crate::pager::Pager;
use crate::segment::Segment;
use crate::style::Style;
use crate::style_interner::StyleInterner;
use crate::terminal_theme::{TerminalTheme, DEFAULT_TERMINAL_THEME, SVG_EXPORT_THEME};
use crate::text::{JustifyMethod, OverflowMethod, Text};
use crate::theme::{Theme, ThemeStack};
use std::borrow::Cow;
use std::fmt::Write as _;
use std::sync::{Arc, Mutex};

// ---------------------------------------------------------------------------
// Color-system auto-detection helper (P1 parity, finding #1)
// ---------------------------------------------------------------------------

/// Detect the color system from `COLORTERM` and `TERM` environment values,
/// following rich's detection order:
///
/// 1. `COLORTERM` contains `truecolor` or `24bit` → `TrueColor`
/// 2. `TERM` ends with `256color` → `EightBit`
/// 3. `TERM` is set (and not `dumb`) → `Standard`
/// 4. Otherwise → `TrueColor` (caller-level fallback; no-TTY callers use `None`)
///
/// This is a pure helper that takes string slices so it can be unit-tested
/// without mutating the process environment.
pub fn detect_color_system_from(colorterm: Option<&str>, term: Option<&str>) -> ColorSystem {
    // Step 1: COLORTERM truecolor / 24bit
    if let Some(ct) = colorterm {
        let ct_lower = ct.to_lowercase();
        if ct_lower.contains("truecolor") || ct_lower.contains("24bit") {
            return ColorSystem::TrueColor;
        }
    }
    // Step 2: TERM ends with 256color
    if let Some(t) = term {
        if t.ends_with("256color") {
            return ColorSystem::EightBit;
        }
        // Step 3: TERM is set and not dumb
        if !t.is_empty() && t != "dumb" {
            return ColorSystem::Standard;
        }
    }
    // Step 4: no meaningful terminal signal → fall back to TrueColor
    // (the caller decides whether to use None for no-TTY situations)
    ColorSystem::TrueColor
}

// ---------------------------------------------------------------------------
// Terminal detection helper
// ---------------------------------------------------------------------------

/// Detect whether stdout is connected to a terminal.
///
/// On native (non-wasm) targets this uses [`std::io::IsTerminal`] for an
/// accurate answer even when stdout is piped. On wasm targets — where
/// `IsTerminal` is not available — we fall back to checking that `TERM` is
/// set and not `"dumb"`.
fn detect_is_terminal() -> bool {
    #[cfg(not(target_arch = "wasm32"))]
    {
        use std::io::IsTerminal as _;
        std::io::stdout().is_terminal()
    }
    #[cfg(target_arch = "wasm32")]
    {
        matches!(
            std::env::var("TERM").as_deref(),
            Ok(t) if !t.is_empty() && t != "dumb"
        )
    }
}

// ---------------------------------------------------------------------------
// ConsoleDimensions
// ---------------------------------------------------------------------------

/// Terminal dimensions in columns and rows.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ConsoleDimensions {
    /// Number of columns.
    pub width: usize,
    /// Number of rows.
    pub height: usize,
}

// ---------------------------------------------------------------------------
// ConsoleOptions
// ---------------------------------------------------------------------------

/// Options that control how renderables produce segments.
#[derive(Debug, Clone)]
pub struct ConsoleOptions {
    /// Terminal dimensions used for layout.
    pub size: ConsoleDimensions,
    /// Whether to use legacy Windows console rendering.
    pub legacy_windows: bool,
    /// Minimum width in columns for renderable output.
    pub min_width: usize,
    /// Maximum width in columns for renderable output.
    pub max_width: usize,
    /// Whether the output target is an interactive terminal.
    pub is_terminal: bool,
    /// Character encoding (always `"utf-8"` in Rust; `Cow` avoids allocation
    /// per `options()` call while still letting tests set non-utf encodings
    /// for `ascii_only()` checks — finding #6).
    pub encoding: Cow<'static, str>,
    /// Maximum height in rows for renderable output.
    pub max_height: usize,
    /// Text justification override, if any.
    pub justify: Option<JustifyMethod>,
    /// Text overflow strategy override, if any.
    pub overflow: Option<OverflowMethod>,
    /// Whether to disable text wrapping.
    ///
    /// Tri-state (rich parity):
    /// - `None`        = inherit / wrap by default
    /// - `Some(false)` = force-wrap (explicit wrap)
    /// - `Some(true)`  = no-wrap (suppress wrapping)
    ///
    /// Only `Some(true)` suppresses wrapping; `None` and `Some(false)` both wrap.
    pub no_wrap: Option<bool>,
    /// Whether to enable syntax highlighting, if set.
    pub highlight: Option<bool>,
    /// Whether to enable markup parsing, if set.
    pub markup: Option<bool>,
    /// Explicit height constraint for renderables, if set.
    pub height: Option<usize>,
}

/// Builder for applying selective updates to `ConsoleOptions`.
#[derive(Debug, Clone, Default)]
pub struct ConsoleOptionsUpdates {
    /// New width in columns, if changing.
    pub width: Option<usize>,
    /// New minimum width, if changing.
    pub min_width: Option<usize>,
    /// New maximum width, if changing.
    pub max_width: Option<usize>,
    /// New justification override, if changing.
    pub justify: Option<Option<JustifyMethod>>,
    /// New overflow strategy override, if changing.
    pub overflow: Option<Option<OverflowMethod>>,
    /// New no-wrap flag, if changing.
    pub no_wrap: Option<bool>,
    /// New highlight flag, if changing.
    pub highlight: Option<Option<bool>>,
    /// New markup flag, if changing.
    pub markup: Option<Option<bool>>,
    /// New height constraint, if changing.
    pub height: Option<Option<usize>>,
    /// New maximum height, if changing.
    pub max_height: Option<usize>,
}

impl ConsoleOptions {
    /// Returns `true` if the encoding is NOT utf-based (i.e. ASCII-only output).
    pub fn ascii_only(&self) -> bool {
        !self.encoding.to_lowercase().starts_with("utf")
    }

    /// Clone this options set.
    pub fn copy(&self) -> Self {
        self.clone()
    }

    /// Return a new `ConsoleOptions` with the width replaced.
    ///
    /// `min_width` is clamped so it never exceeds the new width (finding #3).
    pub fn update_width(&self, width: usize) -> Self {
        let mut opts = self.clone();
        opts.size.width = width;
        opts.max_width = width;
        // P1 parity: min_width must not exceed the new width.
        opts.min_width = opts.min_width.min(width);
        opts
    }

    /// Return a new `ConsoleOptions` with the height replaced.
    pub fn update_height(&self, height: usize) -> Self {
        let mut opts = self.clone();
        opts.height = Some(height);
        opts
    }

    /// Return a new `ConsoleOptions` with both width and height replaced.
    pub fn update_dimensions(&self, width: usize, height: usize) -> Self {
        let mut opts = self.clone();
        opts.size = ConsoleDimensions { width, height };
        opts.max_width = width;
        opts.height = Some(height);
        opts
    }

    /// Return a new `ConsoleOptions` with height reset to `None`.
    pub fn reset_height(&self) -> Self {
        let mut opts = self.clone();
        opts.height = None;
        opts
    }

    /// Apply a set of optional field updates, returning a new `ConsoleOptions`.
    pub fn with_updates(&self, updates: &ConsoleOptionsUpdates) -> Self {
        let mut opts = self.clone();
        if let Some(w) = updates.width {
            opts.size.width = w;
            opts.max_width = w;
        }
        if let Some(min_w) = updates.min_width {
            opts.min_width = min_w;
        }
        if let Some(max_w) = updates.max_width {
            opts.max_width = max_w;
        }
        if let Some(ref j) = updates.justify {
            opts.justify = *j;
        }
        if let Some(ref o) = updates.overflow {
            opts.overflow = *o;
        }
        if let Some(nw) = updates.no_wrap {
            // `ConsoleOptionsUpdates.no_wrap` is `Option<bool>`; wrap it in
            // `Some` so it becomes the tri-state value on ConsoleOptions.
            opts.no_wrap = Some(nw);
        }
        if let Some(ref h) = updates.highlight {
            opts.highlight = *h;
        }
        if let Some(ref m) = updates.markup {
            opts.markup = *m;
        }
        if let Some(ref h) = updates.height {
            opts.height = *h;
        }
        if let Some(mh) = updates.max_height {
            opts.max_height = mh;
        }
        opts
    }
}

// ---------------------------------------------------------------------------
// Renderable trait
// ---------------------------------------------------------------------------

/// Trait for objects that can produce `Segment`s for console rendering.
pub trait Renderable {
    /// Produce segments for rendering on the given console with given options.
    fn gilt_console(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment>;
}

impl Renderable for Text {
    fn gilt_console(&self, _console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        let mut text = self.clone();
        if let Some(justify) = &options.justify {
            text.justify = Some(*justify);
        }
        if let Some(overflow) = &options.overflow {
            text.overflow = Some(*overflow);
        }
        if options.no_wrap == Some(true) || options.overflow == Some(OverflowMethod::Ignore) {
            text.render()
        } else {
            let tab_size = text.tab_size.unwrap_or(8);
            let lines = text.wrap(
                options.max_width,
                text.justify,
                text.overflow,
                tab_size,
                text.no_wrap.unwrap_or(false),
            );
            let mut segments = Vec::new();
            for line in lines.iter() {
                // Each line's render() already appends its `end` ("\n"),
                // so no extra Segment::line() is needed between lines.
                segments.extend(line.render());
            }
            segments
        }
    }
}

impl Renderable for str {
    fn gilt_console(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        let text = console.render_str(self, None, options.justify, options.overflow);
        text.gilt_console(console, options)
    }
}

impl Renderable for String {
    fn gilt_console(&self, console: &Console, options: &ConsoleOptions) -> Vec<Segment> {
        self.as_str().gilt_console(console, options)
    }
}

// ConsoleBuilder moved to console_builder.rs (v1.2 Phase 3 split).
#[path = "console_builder.rs"]
mod console_builder;
pub use console_builder::ConsoleBuilder;

// Capture-mode methods (begin_capture / end_capture / render_widget_to_text)
// moved to console_capture.rs in v1.3 Phase 4 — methods stay on Console via
// a separate impl block.
#[path = "console_capture.rs"]
mod console_capture;
pub use console_capture::{CaptureGuard, ScreenGuard};

// Render path (render/print/log/rule/line/inspect/print_json/print_error/
// print_exception/write_segments/buffer ops) moved to console_render.rs in
// v1.3 Phase 5 — same multi-impl-block pattern.
#[path = "console_render.rs"]
mod console_render;

// ---------------------------------------------------------------------------
// Console
// ---------------------------------------------------------------------------

/// The central orchestrator of gilt rendering output.
///
/// Console manages terminal capabilities, drives the rendering pipeline,
/// and handles output buffering, capture, and export.
pub struct Console {
    // Configuration
    color_system: Option<ColorSystem>,
    width_override: Option<usize>,
    height_override: Option<usize>,
    force_terminal: Option<bool>,
    #[allow(dead_code)] // Reserved for future tab expansion support
    tab_size: usize,
    record: bool,
    markup_enabled: bool,
    highlight_enabled: bool,
    #[allow(dead_code)] // Reserved for future soft-wrap rendering
    soft_wrap: bool,
    no_color: bool,
    quiet: bool,
    #[allow(dead_code)] // Reserved for future safe box-drawing fallback
    safe_box: bool,
    legacy_windows: bool,
    base_style: Option<Style>,
    /// When `true`, `Console::log` appends the caller's file:line to each log line.
    log_path: bool,

    // Theme
    theme_stack: ThemeStack,

    // Buffers
    buffer: Vec<Segment>,
    buffer_index: usize,
    record_buffer: Vec<Segment>,

    // State
    is_alt_screen: bool,
    capture_buffer: Option<Vec<Segment>>,
    /// Stack of nested live-display IDs.
    ///
    /// The top-of-stack ID is the currently-active Live; any preceding entries
    /// represent outer Live displays that have been suspended while a nested
    /// Live was started. Mirrors rich v14.1.0's `Console._live_stack` —
    /// allows Progress + Live + Status etc. to nest without each one
    /// clobbering the others' state.
    live_stack: Vec<usize>,

    /// Per-console style interner (foundation for L2 — see
    /// `.review/V0_11_DESIGN.md`). **Dormant in v0.11.0-alpha.1**: no
    /// caller currently interns or resolves through it. Wired in PR1b
    /// when `Segment::style` is converted from a field to a method.
    /// `Arc<Mutex<...>>` so the handle returned by `style_interner()` can
    /// be shared across threads (e.g. by a future Live integration) and
    /// to leave room for cross-Console resegmenting in PR3.
    style_interner: Arc<Mutex<StyleInterner>>,

    /// Optional output sink override. When `Some`, render output goes here
    /// instead of `std::io::stdout()`. Set via [`Console::with_writer`].
    /// Capture and record modes still take precedence.
    ///
    /// `+ Send + Sync` (not just `+ Send`) preserves `Console: Sync` so
    /// downstream code can wrap a Console in `Arc<…>` for cross-task
    /// sharing — same trait bounds Console had pre-v1.2.0.
    pub(crate) writer_override: Option<Box<dyn std::io::Write + Send + Sync>>,
}

impl Console {
    /// Create a Console with sensible defaults.
    ///
    /// Prefer [`Console::default()`] for the common one-line case — it
    /// calls this method. Reach for [`Console::builder`] only when you
    /// need explicit overrides (custom width, recording for export,
    /// forcing a specific color system).
    ///
    /// Defaults:
    /// - **Color**: TrueColor, auto-disabled by `NO_COLOR`,
    ///   auto-forced by `FORCE_COLOR` / `CLICOLOR`.
    /// - **Width**: auto-detected from terminal; falls back to 80.
    /// - **Markup**: enabled (`[bold]hi[/]`-style tags parsed by
    ///   [`print_text`](Self::print_text)).
    /// - **Recording**: off — enable via the builder for
    ///   [`export_html`](Self::export_html) / [`export_svg`](Self::export_svg).
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    ///
    /// let mut c = Console::default();           // recommended
    /// c.print_text("[bold green]ready[/]");
    /// ```
    pub fn new() -> Self {
        ConsoleBuilder::default().build()
    }

    /// Create a Console using the builder pattern. Use when you need
    /// explicit overrides on top of [`Console::default()`].
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    ///
    /// let console = Console::builder()
    ///     .width(120)
    ///     .record(true)       // for export_html / export_svg
    ///     .build();
    /// assert_eq!(console.width(), 120);
    /// ```
    pub fn builder() -> ConsoleBuilder {
        ConsoleBuilder::default()
    }

    /// Create a Console whose output goes to **stderr** with terminal state
    /// detected from `stderr` itself (not `stdout`).
    ///
    /// This is the correct console to use for diagnostic output, prompts, and
    /// error messages that should always be visible even when `stdout` is
    /// redirected to a file or pipe.
    ///
    /// Terminal detection uses [`std::io::IsTerminal`] on `stderr` on native
    /// targets; on wasm the `TERM` env-var fallback is used. When `stderr` is
    /// a tty the color system is auto-detected; when it is piped the console
    /// is plain (same policy as the stdout console).
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    ///
    /// let mut c = Console::stderr();
    /// c.print_text("[bold red]error:[/] something went wrong");
    /// ```
    pub fn stderr() -> Self {
        #[cfg(not(target_arch = "wasm32"))]
        let is_tty = {
            use std::io::IsTerminal as _;
            std::io::stderr().is_terminal()
        };
        #[cfg(target_arch = "wasm32")]
        let is_tty = matches!(
            std::env::var("TERM").as_deref(),
            Ok(t) if !t.is_empty() && t != "dumb"
        );

        ConsoleBuilder::default()
            .force_terminal(is_tty)
            .build()
            .with_writer(std::io::stderr())
    }

    /// Construct a `Console` from a fully-configured `ConsoleBuilder`.
    /// Called by `ConsoleBuilder::build`; lives here so `Console`'s
    /// private fields stay private to console.rs.
    pub(crate) fn from_builder(builder: ConsoleBuilder) -> Self {
        // Color system priority (highest first):
        //   1. color_system_override (explicit ColorSystem value)
        //   2. color_system (string, e.g. "truecolor")
        //   3. no_color(true) explicitly set by caller
        //   4. Environment vars (NO_COLOR, FORCE_COLOR, CLICOLOR_FORCE, CLICOLOR)
        //   5. Non-terminal output (piped/redirected) → no color
        //   6. Auto-detect from COLORTERM / TERM
        let has_explicit_cs = matches!(
            builder.color_system.as_deref(),
            Some("standard" | "256" | "truecolor" | "windows")
        );

        // A "color forced on" condition: force_terminal(true) is an explicit
        // signal that the caller wants terminal behaviour (ANSI output).
        let force_terminal_on = builder.force_terminal == Some(true);

        let color_system = if let Some(cs) = builder.color_system_override {
            Some(cs)
        } else if has_explicit_cs {
            match builder.color_system.as_deref() {
                Some("standard") => Some(ColorSystem::Standard),
                Some("256") => Some(ColorSystem::EightBit),
                Some("truecolor") => Some(ColorSystem::TrueColor),
                Some("windows") => Some(ColorSystem::Windows),
                _ => unreachable!(),
            }
        } else if builder.no_color_explicit && builder.no_color {
            None
        } else {
            match detect_color_env() {
                ColorEnvOverride::NoColor => None,
                // FORCE_COLOR / CLICOLOR_FORCE → keep color even when piped.
                ColorEnvOverride::ForceColor => Some(ColorSystem::EightBit),
                ColorEnvOverride::ForceColorTruecolor => Some(ColorSystem::TrueColor),
                ColorEnvOverride::None => {
                    if builder.no_color {
                        None
                    } else if !force_terminal_on && !detect_is_terminal() {
                        // Piped / redirected output: disable color unless the
                        // caller explicitly forced terminal mode.
                        None
                    } else {
                        // P1 parity: use env-based detection instead of hard TrueColor default.
                        let colorterm = std::env::var("COLORTERM").ok();
                        let term = std::env::var("TERM").ok();
                        Some(detect_color_system_from(
                            colorterm.as_deref(),
                            term.as_deref(),
                        ))
                    }
                }
            }
        };

        // Mirror the no_color flag: if color_system resolved to None due to
        // non-terminal detection, also set no_color so render_buffer skips SGR.
        let effective_no_color = builder.no_color || color_system.is_none();

        let theme = builder.theme.unwrap_or_else(|| Theme::new(None, true));
        let theme_stack = ThemeStack::new(theme);

        Console {
            color_system,
            width_override: builder.width,
            height_override: builder.height,
            force_terminal: builder.force_terminal,
            tab_size: builder.tab_size,
            record: builder.record,
            markup_enabled: builder.markup,
            highlight_enabled: builder.highlight,
            soft_wrap: builder.soft_wrap,
            no_color: effective_no_color,
            quiet: builder.quiet,
            safe_box: builder.safe_box,
            legacy_windows: false,
            base_style: None,
            log_path: builder.log_path,
            theme_stack,
            buffer: Vec::new(),
            buffer_index: 0,
            record_buffer: Vec::new(),
            is_alt_screen: false,
            capture_buffer: None,
            live_stack: Vec::new(),
            style_interner: Arc::new(Mutex::new(StyleInterner::new())),
            writer_override: None,
        }
    }

    /// Send all output to a custom writer instead of `std::io::stdout()`.
    /// Use for log-to-file, in-memory testing, or piping into a pre-existing
    /// sink (e.g. a network socket). Capture and record modes still take
    /// precedence over the override.
    ///
    /// ```
    /// # use gilt::console::Console;
    /// let buf: Vec<u8> = Vec::new();
    /// let mut console = Console::default().with_writer(buf);
    /// console.print_text("hello");
    /// // output is in console's writer, not on stdout
    /// ```
    pub fn with_writer<W: std::io::Write + Send + Sync + 'static>(mut self, writer: W) -> Self {
        self.writer_override = Some(Box::new(writer));
        self
    }

    // -- Properties ---------------------------------------------------------

    /// The current terminal width in columns.
    pub fn width(&self) -> usize {
        if let Some(w) = self.width_override {
            return w;
        }
        let (w, _) = Self::detect_terminal_size();
        w
    }

    /// The current terminal height in rows.
    pub fn height(&self) -> usize {
        if let Some(h) = self.height_override {
            return h;
        }
        let (_, h) = Self::detect_terminal_size();
        h
    }

    /// Current terminal dimensions.
    pub fn size(&self) -> ConsoleDimensions {
        ConsoleDimensions {
            width: self.width(),
            height: self.height(),
        }
    }

    /// Build the default `ConsoleOptions` for this console.
    pub fn options(&self) -> ConsoleOptions {
        let size = self.size();
        ConsoleOptions {
            size,
            legacy_windows: self.legacy_windows,
            min_width: 1,
            max_width: size.width,
            is_terminal: self.is_terminal(),
            encoding: Cow::Borrowed("utf-8"),
            max_height: size.height,
            justify: None,
            overflow: None,
            no_wrap: None,
            highlight: Some(self.highlight_enabled),
            markup: Some(self.markup_enabled),
            height: None,
        }
    }

    /// The current color system name, or `None` if colors are disabled.
    pub fn color_system_name(&self) -> Option<&str> {
        self.color_system.as_ref().map(|cs| match cs {
            ColorSystem::Standard => "standard",
            ColorSystem::EightBit => "256",
            ColorSystem::TrueColor => "truecolor",
            ColorSystem::Windows => "windows",
        })
    }

    /// The active `ColorSystem`, if any.
    pub fn color_system(&self) -> Option<ColorSystem> {
        self.color_system
    }

    /// The character encoding (always "utf-8" in Rust).
    pub fn encoding(&self) -> &str {
        "utf-8"
    }

    /// Whether the console is connected to a terminal.
    ///
    /// Resolution order:
    /// 1. Explicit `force_terminal` set on the builder
    /// 2. `TTY_COMPATIBLE=1`/`0` environment override
    /// 3. `std::io::IsTerminal` on stdout (native targets only)
    /// 4. `TERM` is set and not `"dumb"` (wasm / fallback)
    pub fn is_terminal(&self) -> bool {
        if let Some(forced) = self.force_terminal {
            return forced;
        }
        match crate::color::color_env::detect_tty_compatible() {
            crate::color::color_env::TtyOverride::ForceTty => return true,
            crate::color::color_env::TtyOverride::ForceNotTty => return false,
            crate::color::color_env::TtyOverride::None => {}
        }
        detect_is_terminal()
    }

    /// Whether the console should treat the user as interactive (prompts,
    /// progress bars with refresh, live updates, etc.).
    ///
    /// Resolution order:
    /// 1. `TTY_INTERACTIVE=1`/`0` environment override
    /// 2. Falls back to [`is_terminal`](Self::is_terminal)
    ///
    /// This is intentionally independent of TTY status so a user can pipe
    /// output to a file but still be prompted on stdin.
    pub fn is_interactive(&self) -> bool {
        match crate::color::color_env::detect_tty_interactive() {
            crate::color::color_env::TtyOverride::ForceTty => true,
            crate::color::color_env::TtyOverride::ForceNotTty => false,
            crate::color::color_env::TtyOverride::None => self.is_terminal(),
        }
    }

    /// Whether this is a "dumb" terminal with no styling support.
    pub fn is_dumb_terminal(&self) -> bool {
        match std::env::var("TERM") {
            Ok(term) => term == "dumb",
            Err(_) => false,
        }
    }

    // -- Terminal detection -------------------------------------------------

    /// Detect the terminal size.
    ///
    /// Resolution order (each dimension independently):
    /// 1. `COLUMNS` / `LINES` environment variables — these win, so tests, CI,
    ///    and explicit overrides remain deterministic.
    /// 2. The real terminal dimensions via an `ioctl`, when the `terminal-size`
    ///    feature is enabled (it is by default) on a non-wasm target and a
    ///    standard stream is connected to a terminal.
    /// 3. Fallback `80 x 25` (used when piped/redirected or on wasm).
    ///
    /// Most shells do not export `COLUMNS` to child processes, so before this
    /// the width was effectively pinned to `80`; the `ioctl` query fixes that
    /// for native builds while keeping wasm and `default-features = false`
    /// builds free of terminal syscalls.
    pub fn detect_terminal_size() -> (usize, usize) {
        let env_width = std::env::var("COLUMNS")
            .ok()
            .and_then(|v| v.parse::<usize>().ok());
        let env_height = std::env::var("LINES")
            .ok()
            .and_then(|v| v.parse::<usize>().ok());

        let (query_width, query_height) = query_terminal_size();

        let width = env_width.or(query_width).unwrap_or(80);
        let height = env_height.or(query_height).unwrap_or(25);
        (width, height)
    }

    // -- Theme / Style ------------------------------------------------------

    /// Look up a style by name from the theme stack, or parse it as a style definition.
    pub fn get_style(&self, name: &str) -> Result<Style, ConsoleError> {
        // First try the theme stack
        if let Some(style) = self.theme_stack.get(name) {
            return Ok(style.clone());
        }
        // Then try parsing as a style definition
        Style::parse_strict(name).map_err(|e| {
            ConsoleError::RenderError(format!("Failed to get style '{}': {}", name, e))
        })
    }

    /// Per-console style interner. **Dormant in v0.11.0-alpha.1** — no
    /// internal callers route through it yet. Exposed so `Segment` (PR1b)
    /// and the eventual L2 activation (PR3) can intern/resolve through
    /// the same id space as the parent `Console`.
    ///
    /// The returned handle is `Arc<Mutex<…>>` because a `Console::copy`
    /// (e.g. `begin_capture`) shares the id space with its origin.
    pub fn style_interner(&self) -> &Arc<Mutex<StyleInterner>> {
        &self.style_interner
    }

    /// Push a new theme onto the theme stack.
    pub fn push_theme(&mut self, theme: Theme) {
        self.theme_stack.push_theme(theme, true);
    }

    /// Pop the top theme from the theme stack.
    pub fn pop_theme(&mut self) {
        let _ = self.theme_stack.pop_theme();
    }

    // -- Control ------------------------------------------------------------

    /// Send a terminal control sequence.
    ///
    /// No-ops on dumb terminals (`TERM=dumb` or non-terminal output), because
    /// escape sequences would appear as raw text on those targets (parity with
    /// Python rich's dumb-terminal guard, finding #2).
    pub fn control(&mut self, ctrl: &Control) {
        if !self.quiet && !self.is_dumb_terminal() {
            self.write_segments(std::slice::from_ref(&ctrl.segment));
        }
    }

    /// Ring the terminal bell.
    pub fn bell(&mut self) {
        self.control(&Control::bell());
    }

    /// Clear the terminal screen.
    pub fn clear(&mut self) {
        self.control(&Control::clear());
    }

    /// Show or hide the cursor.
    pub fn show_cursor(&mut self, show: bool) {
        self.control(&Control::show_cursor(show));
    }

    /// Enable or disable the alternate screen buffer.
    ///
    /// Returns `true` if the operation was performed.
    pub fn set_alt_screen(&mut self, enable: bool) -> bool {
        if enable == self.is_alt_screen {
            return false;
        }
        self.is_alt_screen = enable;
        self.control(&Control::alt_screen(enable));
        true
    }

    /// Set the terminal window title.
    ///
    /// Returns `true` if the title was set (only works on terminals).
    pub fn set_window_title(&mut self, title: &str) -> bool {
        if !self.is_terminal() {
            return false;
        }
        self.control(&Control::title(title));
        true
    }

    // -- Synchronized Output ------------------------------------------------

    /// Begin synchronized output (DEC Mode 2026).
    ///
    /// The terminal buffers all subsequent output until
    /// [`end_synchronized`](Console::end_synchronized) is called, then paints
    /// atomically. This prevents flickering and tearing during rapid updates.
    pub fn begin_synchronized(&mut self) {
        self.control(&Control::begin_sync());
    }

    /// End synchronized output (DEC Mode 2026).
    ///
    /// The terminal flushes all buffered content and renders it at once.
    pub fn end_synchronized(&mut self) {
        self.control(&Control::end_sync());
    }

    /// Execute a closure with synchronized output wrapping.
    ///
    /// Emits the DEC Mode 2026 begin sequence, runs the closure, then emits
    /// the end sequence. If the closure panics the end sequence is still sent
    /// (panic-safe) via a RAII drop guard (finding #4).
    pub fn synchronized<F, R>(&mut self, f: F) -> R
    where
        F: FnOnce(&mut Console) -> R,
    {
        self.begin_synchronized();
        // RAII guard: writes the end-sync segment when dropped, whether the
        // closure returns normally or unwinds.
        struct SyncGuard {
            /// The DEC 2026 end-sync escape sequence to write on drop.
            segment: crate::segment::Segment,
            /// True once we have already emitted end-sync (normal path).
            done: bool,
        }
        impl Drop for SyncGuard {
            fn drop(&mut self) {
                // If `done` is false we are being dropped due to a panic — we
                // cannot access the Console here, so we write the escape
                // sequence directly to stderr as a best-effort recovery.
                if !self.done {
                    use std::io::Write as _;
                    let _ = std::io::stderr().write_all(self.segment.text.as_bytes());
                }
            }
        }
        let end_seg = crate::control::Control::end_sync().segment.clone();
        let mut guard = SyncGuard {
            segment: end_seg,
            done: false,
        };
        let result = f(self);
        // Normal path: emit end-sync through the Console and mark guard done.
        self.end_synchronized();
        guard.done = true;
        result
    }

    // -- Desktop notification (OSC 9) ---------------------------------------

    /// Send a desktop notification via OSC 9.
    ///
    /// If `title` is non-empty, the message is `"{title}: {body}"`;
    /// otherwise just `body` is used. No-ops on dumb terminals.
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    ///
    /// let mut c = Console::builder().force_terminal(true).no_color(true).build();
    /// c.notify("Build", "Done"); // no-op unless TERM != dumb
    /// ```
    pub fn notify(&mut self, title: &str, body: &str) {
        self.control(&Control::notify(title, body));
    }

    // -- Taskbar progress (OSC 9;4) -----------------------------------------

    /// Set the taskbar progress indicator via OSC 9;4 (ConEmu / Windows Terminal).
    ///
    /// `state` controls the indicator style and `percent` is clamped to 0–100.
    /// No-ops on dumb terminals.
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    /// use gilt::segment::TaskbarState;
    ///
    /// let mut c = Console::builder().force_terminal(true).no_color(true).build();
    /// c.set_taskbar_progress(TaskbarState::Normal, 50);
    /// ```
    pub fn set_taskbar_progress(&mut self, state: crate::segment::TaskbarState, percent: u8) {
        self.control(&Control::taskbar_progress(state, percent));
    }

    // -- Clipboard (OSC 52) -------------------------------------------------

    /// Copy text to the system clipboard via OSC 52 escape sequence.
    ///
    /// This works in terminals that support OSC 52 (kitty, iTerm2, WezTerm,
    /// etc.). The text is base64-encoded in the escape sequence.
    pub fn copy_to_clipboard(&mut self, text: &str) {
        self.control(&Control::set_clipboard(text));
    }

    /// Request clipboard contents via OSC 52.
    ///
    /// Most terminals require explicit opt-in for clipboard reading.
    /// The terminal will respond with an OSC 52 sequence containing the
    /// base64-encoded clipboard contents, which must be read from stdin.
    pub fn request_clipboard(&mut self) {
        self.control(&Control::request_clipboard());
    }

    // -- Pager --------------------------------------------------------------

    /// Pipe recorded output through an external pager.
    ///
    /// Captures the current recorded output via `export_text(true, false)` and
    /// pipes it through a [`Pager`]. If `pager_command` is `Some`, uses the
    /// specified command; otherwise uses the default pager (`less -r`).
    ///
    /// Pager errors are silently ignored.
    pub fn pager(&mut self, pager_command: Option<&str>) {
        let text = self.export_text(true, false);
        let pager = match pager_command {
            Some(cmd) => Pager::new().with_command(cmd),
            None => Pager::new(),
        };
        let _ = pager.show(&text);
    }

    // -- Screen helpers -----------------------------------------------------

    /// Enter alternate screen mode, optionally hiding the cursor.
    ///
    /// Call [`exit_screen`](Console::exit_screen) with the same `hide_cursor`
    /// value to restore the previous state.
    pub fn enter_screen(&mut self, hide_cursor: bool) {
        self.set_alt_screen(true);
        if hide_cursor {
            self.show_cursor(false);
        }
    }

    /// Exit alternate screen mode, restoring the cursor if it was hidden.
    ///
    /// Pass the same `hide_cursor` value that was used with
    /// [`enter_screen`](Console::enter_screen).
    pub fn exit_screen(&mut self, hide_cursor: bool) {
        if hide_cursor {
            self.show_cursor(true);
        }
        self.set_alt_screen(false);
    }

    /// Render a [`Renderable`] at an arbitrary `(x, y)` position in the active
    /// alternate screen.
    ///
    /// Moves the cursor to the absolute position (0-indexed), prints the
    /// renderable, then leaves the cursor at the position the renderable's
    /// last segment ended at. Designed for partial-update UIs (Layouts,
    /// dashboards) running inside `enter_screen`.
    ///
    /// Has no effect — and silently does nothing — when the console is not
    /// currently in alt-screen mode, since absolute positioning would
    /// scribble on the user's main scrollback otherwise.
    pub fn update_screen(&mut self, x: usize, y: usize, renderable: &dyn Renderable) {
        if !self.is_alt_screen {
            return;
        }
        let ctrl = crate::utils::control::Control::move_to(x as i32, y as i32);
        self.write_segments(&[ctrl.segment]);
        self.print(renderable);
    }

    /// Render a slice of [`Segment`] lines at successive rows starting from
    /// `(x, y)` in the active alternate screen.
    ///
    /// Each `Vec<Segment>` in `lines` is treated as one line — printed at
    /// `(x, y + i)` for the i-th entry. Useful when you've already produced
    /// per-line segments via `Console::render` and want to splat them into a
    /// known position without going through a full Renderable wrapper.
    ///
    /// Like [`update_screen`](Self::update_screen), no-ops when not in
    /// alt-screen mode.
    pub fn update_screen_lines(&mut self, x: usize, y: usize, lines: &[Vec<Segment>]) {
        if !self.is_alt_screen {
            return;
        }
        for (i, line) in lines.iter().enumerate() {
            let ctrl = crate::utils::control::Control::move_to(x as i32, (y + i) as i32);
            self.write_segments(&[ctrl.segment]);
            self.write_segments(line);
        }
    }

    // -- Live display ID ----------------------------------------------------

    /// Push a Live-display ID onto the stack, making it the active Live.
    ///
    /// Returns `true` if the ID was pushed (always true; the API returns a
    /// `bool` for parity with rich's `set_live` which returned `False` when
    /// nesting was disabled — gilt always allows nesting).
    pub fn push_live(&mut self, live_id: usize) -> bool {
        self.live_stack.push(live_id);
        true
    }

    /// Pop the top Live-display ID off the stack. Returns the popped ID, or
    /// `None` if the stack was empty.
    pub fn pop_live(&mut self) -> Option<usize> {
        self.live_stack.pop()
    }

    /// Return the currently-active Live-display ID (the top of the stack), or
    /// `None` when no Live is active.
    pub fn current_live(&self) -> Option<usize> {
        self.live_stack.last().copied()
    }

    /// Number of currently-nested Live displays. `0` means no Live is active.
    pub fn live_depth(&self) -> usize {
        self.live_stack.len()
    }

    // -- Backwards-compatible single-slot API -------------------------------

    /// Set the active Live-display ID. `Some(id)` pushes (or replaces top);
    /// `None` clears the entire stack.
    ///
    /// Provided for source compatibility with the pre-nesting API. New code
    /// should prefer [`push_live`](Self::push_live) / [`pop_live`](Self::pop_live).
    pub fn set_live(&mut self, live_id: Option<usize>) {
        match live_id {
            Some(id) => {
                if let Some(top) = self.live_stack.last_mut() {
                    *top = id;
                } else {
                    self.live_stack.push(id);
                }
            }
            None => self.live_stack.clear(),
        }
    }

    /// Clear all Live IDs. Equivalent to `set_live(None)`.
    pub fn clear_live(&mut self) {
        self.live_stack.clear();
    }

    // -- Export (record mode) -----------------------------------------------

    /// Export recorded output as plain or styled text.
    ///
    /// Only works if `record` was enabled when the Console was created.
    /// Pass `clear = true` to empty the record buffer after export.
    /// Pass `styles = true` to include ANSI escape codes in the output.
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    /// use gilt::text::Text;
    /// use gilt::style::Style;
    ///
    /// let mut console = Console::builder()
    ///     .width(80)
    ///     .no_color(true)
    ///     .record(true)
    ///     .markup(false)
    ///     .build();
    /// let text = Text::new("Export me", Style::null());
    /// console.print(&text);
    /// let exported = console.export_text(false, false);
    /// assert!(exported.contains("Export me"));
    /// ```
    pub fn export_text(&mut self, clear: bool, styles: bool) -> String {
        let buffer = self.record_buffer.clone();
        if clear {
            self.record_buffer.clear();
        }

        if styles {
            self.render_buffer(&buffer)
        } else {
            // Strip control segments and just concatenate text
            let mut output = String::new();
            for segment in &buffer {
                if !segment.is_control() {
                    output.push_str(&segment.text);
                }
            }
            output
        }
    }

    /// Export recorded output as an HTML document.
    ///
    /// Generates a complete HTML page with inline or class-based styles.
    /// Requires `record` mode to be enabled.
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    /// use gilt::text::Text;
    /// use gilt::style::Style;
    ///
    /// let mut console = Console::builder()
    ///     .width(80)
    ///     .record(true)
    ///     .markup(false)
    ///     .build();
    /// let text = Text::styled("Red text", "red");
    /// console.print(&text);
    /// let html = console.export_html(None, false, true);
    /// assert!(html.contains("<!DOCTYPE html>"));
    /// assert!(html.contains("Red text"));
    /// ```
    pub fn export_html(
        &mut self,
        theme: Option<&TerminalTheme>,
        clear: bool,
        inline_styles: bool,
    ) -> String {
        let theme = theme.unwrap_or(&DEFAULT_TERMINAL_THEME);
        // Finding #9: iterate by reference; only copy out when clear is needed.
        let buffer_ref: &[Segment];
        let taken: Vec<Segment>;
        if clear {
            taken = std::mem::take(&mut self.record_buffer);
            buffer_ref = &taken;
        } else {
            buffer_ref = &self.record_buffer;
        }

        // Finding #8: merge adjacent same-style segments before HTML iteration.
        let simplified = Segment::simplify(buffer_ref);

        let mut code = String::new();
        let mut stylesheet = String::new();
        let mut style_cache: Vec<(Style, String)> = Vec::new();

        for segment in &simplified {
            if segment.is_control() {
                continue;
            }
            let escaped = html_escape(&segment.text);

            if let Some(style) = segment.style() {
                // Finding #7: wrap the text in <a href> when the style has a link.
                let link_url = style.link().map(|s| s.to_string());

                if style.is_null() && link_url.is_none() {
                    code.push_str(&escaped);
                    continue;
                }

                let css = style.get_html_style(Some(theme));
                let inner: String;
                if css.is_empty() {
                    inner = escaped.into_owned();
                } else if inline_styles {
                    inner = format!("<span style=\"{}\">{}</span>", css, escaped);
                } else {
                    // Use class-based styles
                    let class_name =
                        find_or_insert_class(&mut style_cache, &mut stylesheet, style, &css);
                    inner = format!("<span class=\"{}\">{}</span>", class_name, escaped);
                }

                // Wrap in <a href> if there is a link (finding #7).
                if let Some(url) = link_url {
                    write!(code, "<a href=\"{}\">{}</a>", html_escape(&url), inner).unwrap();
                } else {
                    code.push_str(&inner);
                }
            } else {
                code.push_str(&escaped);
            }
        }

        let fg = theme.foreground_color.hex();
        let bg = theme.background_color.hex();

        CONSOLE_HTML_FORMAT
            .replace("{stylesheet}", &stylesheet)
            .replace("{foreground}", &fg)
            .replace("{background}", &bg)
            .replace("{code}", &code)
    }

    /// Export recorded output as HTML using a named palette from [`ThemeRegistry`].
    ///
    /// Convenience wrapper around [`export_html`](Self::export_html): looks up
    /// `theme_name` in `ThemeRegistry` and passes the result.  Equivalent to:
    ///
    /// ```rust,ignore
    /// let theme = ThemeRegistry::terminal_theme("dracula").unwrap();
    /// console.export_html(Some(theme), clear, inline_styles);
    /// ```
    ///
    /// Returns the same HTML as `export_html` with `theme = None` (the default
    /// terminal theme) when `theme_name` is not found.
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    /// use gilt::text::Text;
    /// use gilt::style::Style;
    ///
    /// let mut console = Console::builder()
    ///     .width(80)
    ///     .record(true)
    ///     .force_terminal(true)
    ///     .markup(false)
    ///     .build();
    /// let text = Text::styled("Dracula", "bold magenta");
    /// console.print(&text);
    /// let html = console.export_html_with_theme("dracula", false, true);
    /// assert!(html.contains("<!DOCTYPE html>"));
    /// // Background should come from the Dracula palette (#282a36)
    /// assert!(html.contains("#282a36") || html.contains("1a2a36") || html.len() > 100);
    /// ```
    pub fn export_html_with_theme(
        &mut self,
        theme_name: &str,
        clear: bool,
        inline_styles: bool,
    ) -> String {
        use crate::terminal_theme::ThemeRegistry;
        let theme = ThemeRegistry::terminal_theme(theme_name);
        self.export_html(theme, clear, inline_styles)
    }

    /// Export recorded output as an HTML document with full control via
    /// [`HtmlExportOptions`].
    ///
    /// This is the options-based API; [`export_html`](Self::export_html) and
    /// [`export_html_with_theme`](Self::export_html_with_theme) delegate to
    /// this method via the default theme.
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    /// use gilt::export_format::HtmlExportOptions;
    /// use gilt::text::Text;
    /// use gilt::style::Style;
    ///
    /// let mut console = Console::builder()
    ///     .width(80)
    ///     .record(true)
    ///     .markup(false)
    ///     .build();
    /// console.print(&Text::styled("hello", "bold green"));
    /// let opts = HtmlExportOptions::default()
    ///     .inline_styles(true)
    ///     .dark_mode(true)
    ///     .copy_button(true);
    /// let html = console.export_html_opts(None, &opts);
    /// assert!(html.contains("<!DOCTYPE html>"));
    /// assert!(html.contains("hello"));
    /// ```
    pub fn export_html_opts(
        &mut self,
        theme: Option<&TerminalTheme>,
        opts: &HtmlExportOptions,
    ) -> String {
        let theme = theme.unwrap_or(&DEFAULT_TERMINAL_THEME);

        // Optionally clear (same logic as export_html)
        let buffer_ref: &[Segment];
        let taken: Vec<Segment>;
        if opts.clear {
            taken = std::mem::take(&mut self.record_buffer);
            buffer_ref = &taken;
        } else {
            buffer_ref = &self.record_buffer;
        }

        let simplified = Segment::simplify(buffer_ref);

        let mut code = String::new();
        let mut stylesheet = String::new();
        let mut style_cache: Vec<(Style, String)> = Vec::new();

        for segment in &simplified {
            if segment.is_control() {
                continue;
            }
            let escaped = html_escape(&segment.text);

            if let Some(style) = segment.style() {
                let link_url = style.link().map(|s| s.to_string());

                if style.is_null() && link_url.is_none() {
                    code.push_str(&escaped);
                    continue;
                }

                let css = style.get_html_style(Some(theme));
                let inner: String;
                if css.is_empty() {
                    inner = escaped.into_owned();
                } else if opts.inline_styles {
                    inner = format!("<span style=\"{}\">{}</span>", css, escaped);
                } else {
                    let class_name =
                        find_or_insert_class(&mut style_cache, &mut stylesheet, style, &css);
                    inner = format!("<span class=\"{}\">{}</span>", class_name, escaped);
                }

                if let Some(url) = link_url {
                    write!(code, "<a href=\"{}\">{}</a>", html_escape(&url), inner).unwrap();
                } else {
                    code.push_str(&inner);
                }
            } else {
                code.push_str(&escaped);
            }
        }

        let fg = theme.foreground_color.hex();
        let bg = theme.background_color.hex();

        // Font-family override
        let font_family = opts
            .font_family
            .as_deref()
            .unwrap_or("Menlo,'DejaVu Sans Mono',consolas,'Courier New',monospace");

        // Build @font-face if font_url is provided
        let font_face = if let Some(ref url) = opts.font_url {
            format!(
                "@font-face {{ font-family: '{}'; src: url('{}'); }}\n",
                font_family, url
            )
        } else {
            String::new()
        };

        // Dark-mode CSS block
        let dark_css = if opts.dark_mode {
            format!(
                "\n@media (prefers-color-scheme: dark) {{\n  body {{ color: {}; background-color: {}; }}\n}}\n",
                bg, fg
            )
        } else {
            String::new()
        };

        // Full stylesheet
        let full_stylesheet = format!("{}{}{}", font_face, stylesheet, dark_css);

        // Copy-button HTML + JS
        let copy_snippet = if opts.copy_button {
            r#"<button id="gilt-copy-btn" onclick="(function(){var p=document.querySelector('pre');if(p){navigator.clipboard&&navigator.clipboard.writeText(p.innerText)||window.prompt('Copy:',p.innerText)}})()">Copy</button>
<script>document.getElementById('gilt-copy-btn').style.cssText='position:absolute;top:8px;right:8px;padding:2px 8px;cursor:pointer';</script>
"#
        } else {
            ""
        };

        // Choose template
        let template = opts.code_format.as_deref().unwrap_or(CONSOLE_HTML_FORMAT);

        // Inject copy button before </body>
        let html_base = template
            .replace("{stylesheet}", &full_stylesheet)
            .replace("{foreground}", &fg)
            .replace("{background}", &bg)
            .replace("{code}", &code);

        if opts.copy_button {
            html_base.replace("</body>", &format!("{}</body>", copy_snippet))
        } else {
            html_base
        }
    }

    /// Export recorded output as an SVG document.
    ///
    /// Generates a complete SVG image with terminal-style chrome (title bar,
    /// window controls) and styled text content. Requires `record` mode.
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    /// use gilt::text::Text;
    /// use gilt::style::Style;
    ///
    /// let mut console = Console::builder()
    ///     .width(40)
    ///     .record(true)
    ///     .no_color(true)
    ///     .markup(false)
    ///     .build();
    /// let text = Text::new("SVG test", Style::null());
    /// console.print(&text);
    /// let svg = console.export_svg("Test", None, false, None, 0.61);
    /// assert!(svg.contains("<svg"));
    /// assert!(svg.contains("SVG test"));
    /// ```
    pub fn export_svg(
        &mut self,
        title: &str,
        theme: Option<&TerminalTheme>,
        clear: bool,
        unique_id: Option<&str>,
        font_aspect_ratio: f64,
    ) -> String {
        let theme = theme.unwrap_or(&SVG_EXPORT_THEME);

        // Finding #9: avoid cloning the whole buffer.
        let buffer_ref: &[Segment];
        let taken: Vec<Segment>;
        if clear {
            taken = std::mem::take(&mut self.record_buffer);
            buffer_ref = &taken;
        } else {
            buffer_ref = &self.record_buffer;
        }

        // Finding #11: derive a unique id from FNV-1a hash of segment text + title
        // when the caller leaves unique_id as None.
        let derived_id: String;
        let unique_id: &str = if let Some(id) = unique_id {
            id
        } else {
            let mut hash: u64 = 14695981039346656037u64; // FNV-1a offset basis
            for seg in buffer_ref {
                for byte in seg.text.as_bytes() {
                    hash = hash.wrapping_mul(1099511628211) ^ (*byte as u64);
                }
            }
            for byte in title.as_bytes() {
                hash = hash.wrapping_mul(1099511628211) ^ (*byte as u64);
            }
            derived_id = format!("gilt-{:016x}", hash);
            &derived_id
        };

        // Finding #10: split multi-newline segments into per-line owned Segments.
        let text_lines: Vec<Vec<Segment>> = {
            let mut lines: Vec<Vec<Segment>> = Vec::new();
            let mut current: Vec<Segment> = Vec::new();
            for seg in buffer_ref {
                if seg.is_control() {
                    continue;
                }
                if seg.text.contains('\n') {
                    let parts: Vec<&str> = seg.text.split('\n').collect();
                    for (i, part) in parts.iter().enumerate() {
                        if !part.is_empty() {
                            // Create an owned sub-segment carrying the original style.
                            current.push(Segment::new(part, seg.style().cloned(), None));
                        }
                        if i + 1 < parts.len() {
                            lines.push(std::mem::take(&mut current));
                        }
                    }
                } else {
                    current.push(seg.clone());
                }
            }
            if !current.is_empty() {
                lines.push(current);
            }
            lines
        };

        let char_height = 20.0_f64;
        let line_height = char_height * 1.22;
        let char_width = char_height * font_aspect_ratio;
        let margin_top = 1.0;
        let margin_right = 1.0;
        let margin_bottom = 1.0;
        let margin_left = 1.0;
        let padding_top = 40.0;
        let padding_right = 8.0;
        let padding_bottom = 8.0;
        let padding_left = 8.0;

        let console_width = self.width() as f64;
        let line_count = text_lines.len().max(1) as f64;

        let terminal_width = (console_width * char_width + padding_left + padding_right).ceil();
        let terminal_height = (line_count * line_height + padding_top + padding_bottom).ceil();
        let svg_width = (terminal_width + margin_left + margin_right).ceil();
        let svg_height = (terminal_height + margin_top + margin_bottom).ceil();

        let terminal_x = margin_left;
        let terminal_y = margin_top;

        // Build the chrome (window decorations)
        let chrome = build_svg_chrome(terminal_width, terminal_height, theme, title, unique_id);

        // Build the text matrix (pass buffer_ref so build_svg_text doesn't need the split lines)
        let (matrix, backgrounds, styles, lines_defs) = build_svg_text(
            buffer_ref,
            theme,
            unique_id,
            char_width,
            line_height,
            padding_top,
            padding_left,
        );

        // Pre-format numeric values into a shared buffer to avoid per-replace allocations.
        let mut buf = String::with_capacity(16);
        macro_rules! fmt_buf {
            ($fmt:literal, $val:expr) => {{
                buf.clear();
                write!(buf, $fmt, $val).unwrap();
                &buf
            }};
        }

        // Apply replacements that use the shared buffer one at a time,
        // cloning the formatted value so `buf` can be reused.
        let mut svg = CONSOLE_SVG_FORMAT.replace("{unique_id}", unique_id);
        svg = svg.replace("{char_height}", fmt_buf!("{:.1}", char_height));
        svg = svg.replace("{line_height}", fmt_buf!("{:.1}", line_height));
        svg = svg.replace("{width}", fmt_buf!("{:.0}", svg_width));
        svg = svg.replace("{height}", fmt_buf!("{:.0}", svg_height));
        svg = svg.replace("{terminal_width}", fmt_buf!("{:.0}", terminal_width));
        svg = svg.replace("{terminal_height}", fmt_buf!("{:.0}", terminal_height));
        svg = svg.replace("{terminal_x}", fmt_buf!("{:.0}", terminal_x));
        svg = svg.replace("{terminal_y}", fmt_buf!("{:.0}", terminal_y));
        svg = svg.replace("{chrome}", &chrome);
        svg = svg.replace("{matrix}", &matrix);
        svg = svg.replace("{backgrounds}", &backgrounds);
        svg = svg.replace("{styles}", &styles);
        svg = svg.replace("{lines}", &lines_defs);
        svg
    }

    /// Export recorded output as an SVG document with full control via
    /// [`SvgExportOptions`].
    ///
    /// The key addition over [`export_svg`](Self::export_svg) is
    /// [`FontEmbedding::Base64`], which embeds raw font bytes as a base64
    /// `data:` URL so the SVG is completely self-contained offline.
    ///
    /// # Examples
    ///
    /// ```
    /// use gilt::console::Console;
    /// use gilt::export_format::{FontEmbedding, SvgExportOptions};
    /// use gilt::text::Text;
    /// use gilt::style::Style;
    ///
    /// let mut console = Console::builder()
    ///     .width(40)
    ///     .record(true)
    ///     .no_color(true)
    ///     .markup(false)
    ///     .build();
    /// console.print(&Text::new("SVG opts", Style::null()));
    ///
    /// // Embed a tiny fake font for offline use
    /// let opts = SvgExportOptions::default()
    ///     .title("Demo")
    ///     .font_embedding(FontEmbedding::Base64(b"FAKE_FONT".to_vec()));
    /// let svg = console.export_svg_opts(None, &opts);
    /// assert!(svg.contains("<svg"));
    /// assert!(svg.contains("data:font/"));
    /// ```
    pub fn export_svg_opts(
        &mut self,
        theme: Option<&TerminalTheme>,
        opts: &SvgExportOptions,
    ) -> String {
        use crate::utils::control::base64_encode;

        let theme = theme.unwrap_or(&SVG_EXPORT_THEME);

        let buffer_ref: &[Segment];
        let taken: Vec<Segment>;
        if opts.clear {
            taken = std::mem::take(&mut self.record_buffer);
            buffer_ref = &taken;
        } else {
            buffer_ref = &self.record_buffer;
        }

        // Derive unique_id
        let derived_id: String;
        let unique_id: &str = if let Some(ref id) = opts.unique_id {
            id.as_str()
        } else {
            let mut hash: u64 = 14695981039346656037u64;
            for seg in buffer_ref {
                for byte in seg.text.as_bytes() {
                    hash = hash.wrapping_mul(1099511628211) ^ (*byte as u64);
                }
            }
            for byte in opts.title.as_bytes() {
                hash = hash.wrapping_mul(1099511628211) ^ (*byte as u64);
            }
            derived_id = format!("gilt-{:016x}", hash);
            &derived_id
        };

        let text_lines: Vec<Vec<Segment>> = {
            let mut lines: Vec<Vec<Segment>> = Vec::new();
            let mut current: Vec<Segment> = Vec::new();
            for seg in buffer_ref {
                if seg.is_control() {
                    continue;
                }
                if seg.text.contains('\n') {
                    let parts: Vec<&str> = seg.text.split('\n').collect();
                    for (i, part) in parts.iter().enumerate() {
                        if !part.is_empty() {
                            current.push(Segment::new(part, seg.style().cloned(), None));
                        }
                        if i + 1 < parts.len() {
                            lines.push(std::mem::take(&mut current));
                        }
                    }
                } else {
                    current.push(seg.clone());
                }
            }
            if !current.is_empty() {
                lines.push(current);
            }
            lines
        };

        let char_height = 20.0_f64;
        let line_height = char_height * 1.22;
        let char_width = char_height * opts.font_aspect_ratio;
        let margin_top = 1.0;
        let margin_right = 1.0;
        let margin_bottom = 1.0;
        let margin_left = 1.0;
        let padding_top = 40.0;
        let padding_right = 8.0;
        let padding_bottom = 8.0;
        let padding_left = 8.0;

        let console_width = self.width() as f64;
        let line_count = text_lines.len().max(1) as f64;

        let terminal_width = (console_width * char_width + padding_left + padding_right).ceil();
        let terminal_height = (line_count * line_height + padding_top + padding_bottom).ceil();
        let svg_width = (terminal_width + margin_left + margin_right).ceil();
        let svg_height = (terminal_height + margin_top + margin_bottom).ceil();
        let terminal_x = margin_left;
        let terminal_y = margin_top;

        let chrome = build_svg_chrome(
            terminal_width,
            terminal_height,
            theme,
            &opts.title,
            unique_id,
        );

        let (matrix, backgrounds, styles, lines_defs) = build_svg_text(
            buffer_ref,
            theme,
            unique_id,
            char_width,
            line_height,
            padding_top,
            padding_left,
        );

        // Build base SVG from standard template
        let mut buf = String::with_capacity(16);
        macro_rules! fmt_buf {
            ($fmt:literal, $val:expr) => {{
                buf.clear();
                write!(buf, $fmt, $val).unwrap();
                &buf
            }};
        }

        let mut svg = CONSOLE_SVG_FORMAT.replace("{unique_id}", unique_id);
        svg = svg.replace("{char_height}", fmt_buf!("{:.1}", char_height));
        svg = svg.replace("{line_height}", fmt_buf!("{:.1}", line_height));
        svg = svg.replace("{width}", fmt_buf!("{:.0}", svg_width));
        svg = svg.replace("{height}", fmt_buf!("{:.0}", svg_height));
        svg = svg.replace("{terminal_width}", fmt_buf!("{:.0}", terminal_width));
        svg = svg.replace("{terminal_height}", fmt_buf!("{:.0}", terminal_height));
        svg = svg.replace("{terminal_x}", fmt_buf!("{:.0}", terminal_x));
        svg = svg.replace("{terminal_y}", fmt_buf!("{:.0}", terminal_y));
        svg = svg.replace("{chrome}", &chrome);
        svg = svg.replace("{matrix}", &matrix);
        svg = svg.replace("{backgrounds}", &backgrounds);
        svg = svg.replace("{styles}", &styles);
        svg = svg.replace("{lines}", &lines_defs);

        // Task 2: inject @font-face with base64 data: URL when FontEmbedding::Base64
        if let FontEmbedding::Base64(ref font_bytes) = opts.font_embedding {
            let encoded = base64_encode(font_bytes);
            let font_face = format!(
                "@font-face {{\n    font-family: \"Fira Code\";\n    src: url(\"data:font/woff2;base64,{}\") format(\"woff2\");\n    font-style: normal;\n    font-weight: 400;\n}}\n",
                encoded
            );
            // Replace the existing @font-face blocks (everything from the first
            // @font-face up to the first `.{unique_id}-matrix` class).
            // Simpler: just prepend the embedded rule inside the <style> tag.
            svg = svg.replacen("<style>", &format!("<style>\n{}", font_face), 1);
        }

        svg
    }
}

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

// Export helpers moved to console_export.rs (v1.2 Phase 2 split).
#[path = "console_export.rs"]
mod console_export;
use console_export::*;

// ---------------------------------------------------------------------------
// Terminal size query (feature-gated, native only)
// ---------------------------------------------------------------------------

/// Query the real terminal dimensions via `ioctl` (`terminal-size` feature,
/// native targets). Returns `(None, None)` when not connected to a terminal.
#[cfg(all(feature = "terminal-size", not(target_arch = "wasm32")))]
fn query_terminal_size() -> (Option<usize>, Option<usize>) {
    match terminal_size::terminal_size() {
        Some((terminal_size::Width(w), terminal_size::Height(h))) => {
            (Some(w as usize), Some(h as usize))
        }
        None => (None, None),
    }
}

/// Fallback when the `terminal-size` feature is off or on wasm: env vars and
/// the `80x25` default are the only sources (no terminal syscalls).
#[cfg(not(all(feature = "terminal-size", not(target_arch = "wasm32"))))]
fn query_terminal_size() -> (Option<usize>, Option<usize>) {
    (None, None)
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[path = "console_tests.rs"]
mod tests;