summaryrefslogtreecommitdiff
path: root/src/libsystemd-terminal/term-page.c
blob: cbd80067347a536eadfc3c84f7d81530ebc39f39 (plain)
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
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/

/***
  This file is part of systemd.

  Copyright (C) 2014 David Herrmann <dh.herrmann@gmail.com>

  systemd is free software; you can redistribute it and/or modify it
  under the terms of the GNU Lesser General Public License as published by
  the Free Software Foundation; either version 2.1 of the License, or
  (at your option) any later version.

  systemd is distributed in the hope that it will be useful, but
  WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  Lesser General Public License for more details.

  You should have received a copy of the GNU Lesser General Public License
  along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/

/*
 * Terminal Page/Line/Cell/Char Handling
 * This file implements page handling of a terminal. It is split into pages,
 * lines, cells and characters. Each object is independent of the next upper
 * object.
 *
 * The Terminal layer keeps each line of a terminal separate and dynamically
 * allocated. This allows us to move lines from main-screen to history-buffers
 * very fast. Same is true for scrolling, top/bottom borders and other buffer
 * operations.
 *
 * While lines are dynamically allocated, cells are not. This would be a waste
 * of memory and causes heavy fragmentation. Furthermore, cells are moved much
 * less frequently than lines so the performance-penalty is pretty small.
 * However, to support combining-characters, we have to initialize and cleanup
 * cells properly and cannot just release the underlying memory. Therefore,
 * cells are treated as proper objects despite being allocated in arrays.
 *
 * Each cell has a set of attributes and a stored character. This is usually a
 * single Unicode character stored as 32bit UCS-4 char. However, we need to
 * support Unicode combining-characters, therefore this gets more complicated.
 * Characters themselves are represented by a "term_char_t" object. It
 * should be treated as a normal integer and passed by value. The
 * surrounding struct is just to hide the internals. A term-char can contain a
 * base character together with up to 2 combining-chars in a single integer.
 * Only if you need more combining-chars (very unlikely!) a term-char is a
 * pointer to an allocated storage. This requires you to always free term-char
 * objects once no longer used (even though this is a no-op most of the time).
 * Furthermore, term-char objects are not ref-counted so you must duplicate them
 * in case you want to store it somewhere and retain a copy yourself. By
 * convention, all functions that take a term-char object will not duplicate
 * it but implicitly take ownership of the passed value. It's up to the caller
 * to duplicate it beforehand, in case it wants to retain a copy.
 *
 * If it turns out, that more than 2 comb-chars become common in specific
 * languages, we can try to optimize this. One idea is to ref-count allocated
 * characters and store them in a hash-table (like gnome's libvte3 does). This
 * way we will never have two allocated chars for the same content. Or we can
 * simply put two uint64_t into a "term_char_t". This will slow down operations
 * on systems that don't need that many comb-chars, but avoid the dynamic
 * allocations on others.
 * Anyhow, until we have proper benchmarks, we will keep the current code. It
 * seems to compete very well with other solutions so far.
 *
 * The page-layer is a one-dimensional array of lines. Considering that each
 * line is a one-dimensional array of cells, the page layer provides the
 * two-dimensional cell-page required for terminals. The page itself only
 * operates on lines. All cell-related operations are forwarded to the correct
 * line.
 * A page does not contain any cursor tracking. It only provides the raw
 * operations to shuffle lines and modify the page.
 */

#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include "macro.h"
#include "term-internal.h"
#include "util.h"

/* maximum UCS-4 character */
#define CHAR_UCS4_MAX (0x10ffff)
/* mask for valid UCS-4 characters (21bit) */
#define CHAR_UCS4_MASK (0x1fffff)
/* UCS-4 replacement character */
#define CHAR_UCS4_REPLACEMENT (0xfffd)

/* real storage behind "term_char_t" in case it's not packed */
typedef struct term_character {
        uint8_t n;
        uint32_t codepoints[];
} term_character;

/*
 * char_pack() takes 3 UCS-4 values and packs them into a term_char_t object.
 * Note that UCS-4 chars only take 21 bits, so we still have the LSB as marker.
 * We set it to 1 so others can distinguish it from pointers.
 */
static inline term_char_t char_pack(uint32_t v1, uint32_t v2, uint32_t v3) {
        uint64_t packed, u1, u2, u3;

        u1 = v1;
        u2 = v2;
        u3 = v3;

        packed = 0x01;
        packed |= (u1 & (uint64_t)CHAR_UCS4_MASK) << 43;
        packed |= (u2 & (uint64_t)CHAR_UCS4_MASK) << 22;
        packed |= (u3 & (uint64_t)CHAR_UCS4_MASK) <<  1;

        return TERM_CHAR_INIT(packed);
}

#define char_pack1(_v1) char_pack2((_v1), CHAR_UCS4_MAX + 1)
#define char_pack2(_v1, _v2) char_pack3((_v1), (_v2), CHAR_UCS4_MAX + 1)
#define char_pack3(_v1, _v2, _v3) char_pack((_v1), (_v2), (_v3))

/*
 * char_unpack() is the inverse of char_pack(). It extracts the 3 stored UCS-4
 * characters and returns them. Note that this does not validate the passed
 * term_char_t. That's the responsibility of the caller.
 * This returns the number of characters actually packed. This obviously is a
 * number between 0 and 3 (inclusive).
 */
static inline uint8_t char_unpack(term_char_t packed, uint32_t *out_v1, uint32_t *out_v2, uint32_t *out_v3) {
        uint32_t v1, v2, v3;

        v1 = (packed._value >> 43) & (uint64_t)CHAR_UCS4_MASK;
        v2 = (packed._value >> 22) & (uint64_t)CHAR_UCS4_MASK;
        v3 = (packed._value >>  1) & (uint64_t)CHAR_UCS4_MASK;

        if (out_v1)
                *out_v1 = v1;
        if (out_v2)
                *out_v2 = v2;
        if (out_v3)
                *out_v3 = v3;

        return (v1 > CHAR_UCS4_MAX) ? 0 :
              ((v2 > CHAR_UCS4_MAX) ? 1 :
              ((v3 > CHAR_UCS4_MAX) ? 2 :
                                      3));
}

/* cast a term_char_t to a term_character* */
static inline term_character *char_to_ptr(term_char_t ch) {
        return (term_character*)(unsigned long)ch._value;
}

/* cast a term_character* to a term_char_t */
static inline term_char_t char_from_ptr(term_character *c) {
        return TERM_CHAR_INIT((unsigned long)c);
}

/*
 * char_alloc() allocates a properly aligned term_character object and returns
 * a pointer to it. NULL is returned on allocation errors. The object will have
 * enough room for @n following UCS-4 chars.
 * Note that we allocate (n+1) characters and set the last one to 0 in case
 * anyone prints this string for debugging.
 */
static term_character *char_alloc(uint8_t n) {
        term_character *c;
        int r;

        r = posix_memalign((void**)&c,
                           MAX(sizeof(void*), (size_t)2),
                           sizeof(*c) + sizeof(*c->codepoints) * (n + 1));
        if (r)
                return NULL;

        c->n = n;
        c->codepoints[n] = 0;

        return c;
}

/*
 * char_free() frees the memory allocated via char_alloc(). It is safe to call
 * this on any term_char_t, only allocated characters are freed.
 */
static inline void char_free(term_char_t ch) {
        if (term_char_is_allocated(ch))
                free(char_to_ptr(ch));
}

/*
 * This appends @append_ucs4 to the existing character @base and returns
 * it as a new character. In case that's not possible, @base is returned. The
 * caller can use term_char_same() to test whether the returned character was
 * freshly allocated or not.
 */
static term_char_t char_build(term_char_t base, uint32_t append_ucs4) {
        /* soft-limit for combining-chars; hard-limit is currently 255 */
        const size_t climit = 64;
        term_character *c;
        uint32_t buf[3], *t;
        uint8_t n;

        /* ignore invalid UCS-4 */
        if (append_ucs4 > CHAR_UCS4_MAX)
                return base;

        if (term_char_is_null(base)) {
                return char_pack1(append_ucs4);
        } else if (!term_char_is_allocated(base)) {
                /* unpack and try extending the packed character */
                n = char_unpack(base, &buf[0], &buf[1], &buf[2]);

                switch (n) {
                case 0:
                        return char_pack1(append_ucs4);
                case 1:
                        if (climit < 2)
                                return base;

                        return char_pack2(buf[0], append_ucs4);
                case 2:
                        if (climit < 3)
                                return base;

                        return char_pack3(buf[0], buf[1], append_ucs4);
                default:
                        /* fallthrough */
                        break;
                }

                /* already fully packed, we need to allocate a new one */
                t = buf;
        } else {
                /* already an allocated type, we need to allocate a new one */
                c = char_to_ptr(base);
                t = c->codepoints;
                n = c->n;
        }

        /* bail out if soft-limit is reached */
        if (n >= climit)
                return base;

        /* allocate new char */
        c = char_alloc(n + 1);
        if (!c)
                return base;

        memcpy(c->codepoints, t, sizeof(*t) * n);
        c->codepoints[n] = append_ucs4;

        return char_from_ptr(c);
}

/**
 * term_char_set() - Reset character to a single UCS-4 character
 * @previous: term-char to reset
 * @append_ucs4: UCS-4 char to set
 *
 * This frees all resources in @previous and re-initializes it to @append_ucs4.
 * The new char is returned.
 *
 * Usually, this is used like this:
 *   obj->ch = term_char_set(obj->ch, ucs4);
 *
 * Returns: The previous character reset to @append_ucs4.
 */
term_char_t term_char_set(term_char_t previous, uint32_t append_ucs4) {
        char_free(previous);
        return char_build(TERM_CHAR_NULL, append_ucs4);
}

/**
 * term_char_merge() - Merge UCS-4 char at the end of an existing char
 * @base: existing term-char
 * @append_ucs4: UCS-4 character to append
 *
 * This appends @append_ucs4 to @base and returns the result. @base is
 * invalidated by this function and must no longer be used. The returned value
 * replaces the old one.
 *
 * Usually, this is used like this:
 *   obj->ch = term_char_merge(obj->ch, ucs4);
 *
 * Returns: The new merged character.
 */
term_char_t term_char_merge(term_char_t base, uint32_t append_ucs4) {
        term_char_t ch;

        ch = char_build(base, append_ucs4);
        if (!term_char_same(ch, base))
                term_char_free(base);

        return ch;
}

/**
 * term_char_dup() - Duplicate character
 * @ch: character to duplicate
 *
 * This duplicates a term-character. In case the character is not allocated,
 * nothing is done. Otherwise, the underlying memory is copied and returned. You
 * need to call term_char_free() on the returned character to release it again.
 * On allocation errors, a replacement character is returned. Therefore, the
 * caller can safely assume that this function always succeeds.
 *
 * Returns: The duplicated term-character.
 */
term_char_t term_char_dup(term_char_t ch) {
        term_character *c, *newc;

        if (!term_char_is_allocated(ch))
                return ch;

        c = char_to_ptr(ch);
        newc = char_alloc(c->n);
        if (!newc)
                return char_pack1(CHAR_UCS4_REPLACEMENT);

        memcpy(newc->codepoints, c->codepoints, sizeof(*c->codepoints) * c->n);
        return char_from_ptr(newc);
}

/**
 * term_char_dup_append() - Duplicate tsm-char with UCS-4 character appended
 * @base: existing term-char
 * @append_ucs4: UCS-4 character to append
 *
 * This is similar to term_char_merge(), but it returns a separately allocated
 * character. That is, @base will stay valid after this returns and is not
 * touched. In case the append-operation fails, @base is duplicated and
 * returned. That is, the returned char is always independent of @base.
 *
 * Returns: Newly allocated character with @append_ucs4 appended to @base.
 */
term_char_t term_char_dup_append(term_char_t base, uint32_t append_ucs4) {
        term_char_t ch;

        ch = char_build(base, append_ucs4);
        if (term_char_same(ch, base))
                ch = term_char_dup(base);

        return ch;
}

/**
 * term_char_resolve() - Retrieve the UCS-4 string for a term-char
 * @ch: character to resolve
 * @s: storage for size of string or NULL
 * @b: storage for string or NULL
 *
 * This takes a term-character and returns the UCS-4 string associated with it.
 * In case @ch is not allocated, the string is stored in @b (in case @b is NULL
 * static storage is used). Otherwise, a pointer to the allocated storage is
 * returned.
 *
 * The returned string is only valid as long as @ch and @b are valid. The string
 * is zero-terminated and can safely be printed via long-character printf().
 * The length of the string excluding the zero-character is returned in @s.
 *
 * This never returns NULL. Even if the size is 0, this points to a buffer of at
 * least a zero-terminator.
 *
 * Returns: The UCS-4 string-representation of @ch, and its size in @s.
 */
const uint32_t *term_char_resolve(term_char_t ch, size_t *s, term_charbuf_t *b) {
        static term_charbuf_t static_b;
        term_character *c;
        uint32_t *cache;
        size_t len;

        if (b)
                cache = b->buf;
        else
                cache = static_b.buf;

        if (term_char_is_null(ch)) {
                len = 0;
                cache[0] = 0;
        } else if (term_char_is_allocated(ch)) {
                c = char_to_ptr(ch);
                len = c->n;
                cache = c->codepoints;
        } else {
                len = char_unpack(ch, &cache[0], &cache[1], &cache[2]);
                cache[len] = 0;
        }

        if (s)
                *s = len;

        return cache;
}

/**
 * term_char_lookup_width() - Lookup cell-width of a character
 * @ch: character to return cell-width for
 *
 * This is an equivalent of wcwidth() for term_char_t. It can deal directly
 * with UCS-4 and combining-characters and avoids the mess that is wchar_t and
 * locale handling.
 *
 * Returns: 0 for unprintable characters, >0 for everything else.
 */
unsigned int term_char_lookup_width(term_char_t ch) {
        term_charbuf_t b;
        const uint32_t *str;
        unsigned int max;
        size_t i, len;
        int r;

        max = 0;
        str = term_char_resolve(ch, &len, &b);

        for (i = 0; i < len; ++i) {
                /*
                 * Oh god, C99 locale handling strikes again: wcwidth() expects
                 * wchar_t, but there is no way for us to know the
                 * internal encoding of wchar_t. Moreover, it is nearly
                 * impossible to convert UCS-4 into wchar_t (except for iconv,
                 * which is way too much overhead).
                 * Therefore, we use our own copy of wcwidth(). Lets just hope
                 * that glibc will one day export it's internal UCS-4 and UTF-8
                 * helpers for direct use.
                 */
                assert_cc(sizeof(wchar_t) >= 4);
                r = mk_wcwidth((wchar_t)str[i]);
                if (r > 0 && (unsigned int)r > max)
                        max = r;
        }

        return max;
}

/**
 * term_cell_init() - Initialize a new cell
 * @cell: cell to initialize
 * @ch: character to set on the cell or TERM_CHAR_NULL
 * @cwidth: character width of @ch
 * @attr: attributes to set on the cell or NULL
 * @age: age to set on the cell or TERM_AGE_NULL
 *
 * This initializes a new cell. The backing-memory of the cell must be allocated
 * by the caller beforehand. The caller is responsible to destroy the cell via
 * term_cell_destroy() before freeing the backing-memory.
 *
 * It is safe (and supported!) to use:
 *   zero(*c);
 * instead of:
 *   term_cell_init(c, TERM_CHAR_NULL, NULL, TERM_AGE_NULL);
 *
 * Note that this call takes ownership of @ch. If you want to use it yourself
 * after this call, you need to duplicate it before calling this.
 */
static void term_cell_init(term_cell *cell, term_char_t ch, unsigned int cwidth, const term_attr *attr, term_age_t age) {
        assert(cell);

        cell->ch = ch;
        cell->cwidth = cwidth;
        cell->age = age;

        if (attr)
                memcpy(&cell->attr, attr, sizeof(*attr));
        else
                zero(cell->attr);
}

/**
 * term_cell_destroy() - Destroy previously initialized cell
 * @cell: cell to destroy or NULL
 *
 * This releases all resources associated with a cell. The backing memory is
 * kept as-is. It's the responsibility of the caller to manage it.
 *
 * You must not call any other cell operations on this cell after this call
 * returns. You must re-initialize the cell via term_cell_init() before you can
 * use it again.
 *
 * If @cell is NULL, this is a no-op.
 */
static void term_cell_destroy(term_cell *cell) {
        if (!cell)
                return;

        term_char_free(cell->ch);
}

/**
 * term_cell_set() - Change contents of a cell
 * @cell: cell to modify
 * @ch: character to set on the cell or cell->ch
 * @cwidth: character width of @ch or cell->cwidth
 * @attr: attributes to set on the cell or NULL
 * @age: age to set on the cell or cell->age
 *
 * This changes the contents of a cell. It can be used to change the character,
 * attributes and age. To keep the current character, pass cell->ch as @ch. To
 * reset the current attributes, pass NULL. To keep the current age, pass
 * cell->age.
 *
 * This call takes ownership of @ch. You need to duplicate it first, in case you
 * want to use it for your own purposes after this call.
 *
 * The cell must have been initialized properly before calling this. See
 * term_cell_init().
 */
static void term_cell_set(term_cell *cell, term_char_t ch, unsigned int cwidth, const term_attr *attr, term_age_t age) {
        assert(cell);

        if (!term_char_same(ch, cell->ch)) {
                term_char_free(cell->ch);
                cell->ch = ch;
        }

        cell->cwidth = cwidth;
        cell->age = age;

        if (attr)
                memcpy(&cell->attr, attr, sizeof(*attr));
        else
                zero(cell->attr);
}

/**
 * term_cell_append() - Append a combining-char to a cell
 * @cell: cell to modify
 * @ucs4: UCS-4 character to append to the cell
 * @age: new age to set on the cell or cell->age
 *
 * This appends a combining-character to a cell. No validation of the UCS-4
 * character is done, so this can be used to append any character. Additionally,
 * this can update the age of the cell.
 *
 * The cell must have been initialized properly before calling this. See
 * term_cell_init().
 */
static void term_cell_append(term_cell *cell, uint32_t ucs4, term_age_t age) {
        assert(cell);

        cell->ch = term_char_merge(cell->ch, ucs4);
        cell->age = age;
}

/**
 * term_cell_init_n() - Initialize an array of cells
 * @cells: pointer to an array of cells to initialize
 * @n: number of cells
 * @attr: attributes to set on all cells or NULL
 * @age: age to set on all cells
 *
 * This is the same as term_cell_init() but initializes an array of cells.
 * Furthermore, this always sets the character to TERM_CHAR_NULL.
 * If you want to set a specific characters on all cells, you need to hard-code
 * this loop and duplicate the character for each cell.
 */
static void term_cell_init_n(term_cell *cells, unsigned int n, const term_attr *attr, term_age_t age) {
        for ( ; n > 0; --n, ++cells)
                term_cell_init(cells, TERM_CHAR_NULL, 0, attr, age);
}

/**
 * term_cell_destroy_n() - Destroy an array of cells
 * @cells: pointer to an array of cells to destroy
 * @n: number of cells
 *
 * This is the same as term_cell_destroy() but destroys an array of cells.
 */
static void term_cell_destroy_n(term_cell *cells, unsigned int n) {
        for ( ; n > 0; --n, ++cells)
                term_cell_destroy(cells);
}

/**
 * term_cell_clear_n() - Clear contents of an array of cells
 * @cells: pointer to an array of cells to modify
 * @n: number of cells
 * @attr: attributes to set on all cells or NULL
 * @age: age to set on all cells
 *
 * This is the same as term_cell_set() but operates on an array of cells. Note
 * that all characters are always set to TERM_CHAR_NULL, unlike term_cell_set()
 * which takes the character as argument.
 * If you want to set a specific characters on all cells, you need to hard-code
 * this loop and duplicate the character for each cell.
 */
static void term_cell_clear_n(term_cell *cells, unsigned int n, const term_attr *attr, term_age_t age) {
        for ( ; n > 0; --n, ++cells)
                term_cell_set(cells, TERM_CHAR_NULL, 0, attr, age);
}

/**
 * term_line_new() - Allocate a new line
 * @out: place to store pointer to new line
 *
 * This allocates and initialized a new line. The line is unlinked and
 * independent of any page. It can be used for any purpose. The initial
 * cell-count is set to 0.
 *
 * The line has to be freed via term_line_free() once it's no longer needed.
 *
 * Returns: 0 on success, negative error code on failure.
 */
int term_line_new(term_line **out) {
        _term_line_free_ term_line *line = NULL;

        assert_return(out, -EINVAL);

        line = new0(term_line, 1);
        if (!line)
                return -ENOMEM;

        *out = line;
        line = NULL;
        return 0;
}

/**
 * term_line_free() - Free a line
 * @line: line to free or NULL
 *
 * This frees a line that was previously allocated via term_line_free(). All its
 * cells are released, too.
 *
 * If @line is NULL, this is a no-op.
 */
term_line *term_line_free(term_line *line) {
        if (!line)
                return NULL;

        term_cell_destroy_n(line->cells, line->n_cells);
        free(line->cells);
        free(line);

        return NULL;
}

/**
 * term_line_reserve() - Pre-allocate cells for a line
 * @line: line to pre-allocate cells for
 * @width: numbers of cells the line shall have pre-allocated
 * @attr: attribute for all allocated cells or NULL
 * @age: current age for all modifications
 * @protect_width: width to protect from erasure
 *
 * This pre-allocates cells for this line. Please note that @width is the number
 * of cells the line is guaranteed to have allocated after this call returns.
 * It's not the number of cells that are added, neither is it the new width of
 * the line.
 *
 * This function never frees memory. That is, reducing the line-width will
 * always succeed, same is true for increasing the width to a previously set
 * width.
 *
 * @attr and @age are used to initialize new cells. Additionally, any
 * existing cell outside of the protected area specified by @protect_width are
 * cleared and reset with @attr and @age.
 *
 * Returns: 0 on success, negative error code on failure.
 */
int term_line_reserve(term_line *line, unsigned int width, const term_attr *attr, term_age_t age, unsigned int protect_width) {
        unsigned int min_width;
        term_cell *t;

        assert_return(line, -EINVAL);

        /* reset existing cells if required */
        min_width = MIN(line->n_cells, width);
        if (min_width > protect_width)
                term_cell_clear_n(line->cells + protect_width,
                                  min_width - protect_width,
                                  attr,
                                  age);

        /* allocate new cells if required */

        if (width > line->n_cells) {
                t = realloc_multiply(line->cells, sizeof(*t), width);
                if (!t)
                        return -ENOMEM;

                if (!attr && !age)
                        memzero(t + line->n_cells,
                                sizeof(*t) * (width - line->n_cells));
                else
                        term_cell_init_n(t + line->n_cells,
                                         width - line->n_cells,
                                         attr,
                                         age);

                line->cells = t;
                line->n_cells = width;
        }

        line->fill = MIN(line->fill, protect_width);

        return 0;
}

/**
 * term_line_set_width() - Change width of a line
 * @line: line to modify
 * @width: new width
 *
 * This changes the actual width of a line. It is the caller's responsibility
 * to use term_line_reserve() to make sure enough space is allocated. If @width
 * is greater than the allocated size, it is cropped.
 *
 * This does not modify any cells. Use term_line_reserve() or term_line_erase()
 * to clear any newly added cells.
 *
 * NOTE: The fill state is cropped at line->width. Therefore, if you increase
 *       the line-width afterwards, but there is a multi-cell character at the
 *       end of the line that got cropped, then the fill-state will _not_ be
 *       adjusted.
 *       This means, the fill-state always includes the cells up to the start
 *       of the right-most character, but it might or might not cover it until
 *       its end. This should be totally fine, though. You should never access
 *       multi-cell tails directly, anyway.
 */
void term_line_set_width(term_line *line, unsigned int width) {
        assert(line);

        if (width > line->n_cells)
                width = line->n_cells;

        line->width = width;
        line->fill = MIN(line->fill, width);
}

/**
 * line_insert() - Insert characters and move existing cells to the right
 * @from: position to insert cells at
 * @num: number of cells to insert
 * @head_char: character that is set on the first cell
 * @head_cwidth: character-length of @head_char
 * @attr: attribute for all inserted cells or NULL
 * @age: current age for all modifications
 *
 * The INSERT operation (or writes with INSERT_MODE) writes data at a specific
 * position on a line and shifts the existing cells to the right. Cells that are
 * moved beyond the right hand border are discarded.
 *
 * This helper contains the actual INSERT implementation which is independent of
 * the data written. It works on cells, not on characters. The first cell is set
 * to @head_char, all others are reset to TERM_CHAR_NULL. See each caller for a
 * more detailed description.
 */
static inline void line_insert(term_line *line, unsigned int from, unsigned int num, term_char_t head_char, unsigned int head_cwidth, const term_attr *attr, term_age_t age) {
        unsigned int i, rem, move;

        if (from >= line->width)
                return;
        if (from + num < from || from + num > line->width)
                num = line->width - from;
        if (!num)
                return;

        move = line->width - from - num;
        rem = MIN(num, move);

        if (rem > 0) {
                /*
                 * Make room for @num cells; shift cells to the right if
                 * required. @rem is the number of remaining cells that we will
                 * knock off on the right and overwrite during the right shift.
                 *
                 * For INSERT_MODE, @num/@rem are usually 1 or 2, @move is 50%
                 * of the line on average. Therefore, the actual move is quite
                 * heavy and we can safely invalidate cells manually instead of
                 * the whole line.
                 * However, for INSERT operations, any parameters are
                 * possible. But we cannot place any assumption on its usage
                 * across applications, so we just handle it the same as
                 * INSERT_MODE and do per-cell invalidation.
                 */

                /* destroy cells that are knocked off on the right */
                term_cell_destroy_n(line->cells + line->width - rem, rem);

                /* move remaining bulk of cells */
                memmove(line->cells + from + num,
                        line->cells + from,
                        sizeof(*line->cells) * move);

                /* invalidate cells */
                for (i = 0; i < move; ++i)
                        line->cells[from + num + i].age = age;

                /* initialize fresh head-cell */
                term_cell_init(line->cells + from,
                               head_char,
                               head_cwidth,
                               attr,
                               age);

                /* initialize fresh tail-cells */
                term_cell_init_n(line->cells + from + 1,
                                 num - 1,
                                 attr,
                                 age);

                /* adjust fill-state */
                DISABLE_WARNING_SHADOW;
                line->fill = MIN(line->width,
                                 MAX(line->fill + num,
                                     from + num));
                REENABLE_WARNING;
        } else {
                /* modify head-cell */
                term_cell_set(line->cells + from,
                              head_char,
                              head_cwidth,
                              attr,
                              age);

                /* reset tail-cells */
                term_cell_clear_n(line->cells + from + 1,
                                  num - 1,
                                  attr,
                                  age);

                /* adjust fill-state */
                line->fill = line->width;
        }
}

/**
 * term_line_write() - Write to a single, specific cell
 * @line: line to write to
 * @pos_x: x-position of cell in @line to write to
 * @ch: character to write to the cell
 * @cwidth: character width of @ch
 * @attr: attributes to set on the cell or NULL
 * @age: current age for all modifications
 * @insert_mode: true if INSERT-MODE is enabled
 *
 * This writes to a specific cell in a line. The cell is addressed by its
 * X-position @pos_x. If that cell does not exist, this is a no-op.
 *
 * @ch and @attr are set on this cell.
 *
 * If @insert_mode is true, this inserts the character instead of overwriting
 * existing data (existing data is now moved to the right before writing).
 *
 * This function is the low-level handler of normal writes to a terminal.
 */
void term_line_write(term_line *line, unsigned int pos_x, term_char_t ch, unsigned int cwidth, const term_attr *attr, term_age_t age, bool insert_mode) {
        unsigned int len;

        assert(line);

        if (pos_x >= line->width)
                return;

        len = MAX(1U, cwidth);
        if (pos_x + len < pos_x || pos_x + len > line->width)
                len = line->width - pos_x;
        if (!len)
                return;

        if (insert_mode) {
                /* Use line_insert() to insert the character-head and fill
                 * the remains with NULLs. */
                line_insert(line, pos_x, len, ch, cwidth, attr, age);
        } else {
                /* modify head-cell */
                term_cell_set(line->cells + pos_x, ch, cwidth, attr, age);

                /* reset tail-cells */
                term_cell_clear_n(line->cells + pos_x + 1,
                                  len - 1,
                                  attr,
                                  age);

                /* adjust fill-state */
                DISABLE_WARNING_SHADOW;
                line->fill = MIN(line->width,
                                 MAX(line->fill,
                                     pos_x + len));
                REENABLE_WARNING;
        }
}

/**
 * term_line_insert() - Insert empty cells
 * @line: line to insert empty cells into
 * @from: x-position where to insert cells
 * @num: number of cells to insert
 * @attr: attributes to set on the cells or NULL
 * @age: current age for all modifications
 *
 * This inserts @num empty cells at position @from in line @line. All existing
 * cells to the right are shifted to make room for the new cells. Cells that get
 * pushed beyond the right hand border are discarded.
 */
void term_line_insert(term_line *line, unsigned int from, unsigned int num, const term_attr *attr, term_age_t age) {
        /* use line_insert() to insert @num empty cells */
        return line_insert(line, from, num, TERM_CHAR_NULL, 0, attr, age);
}

/**
 * term_line_delete() - Delete cells from line
 * @line: line to delete cells from
 * @from: position to delete cells at
 * @num: number of cells to delete
 * @attr: attributes to set on any new cells
 * @age: current age for all modifications
 *
 * Delete cells from a line. All cells to the right of the deleted cells are
 * shifted to the left to fill the empty space. New cells appearing on the right
 * hand border are cleared and initialized with @attr.
 */
void term_line_delete(term_line *line, unsigned int from, unsigned int num, const term_attr *attr, term_age_t age) {
        unsigned int rem, move, i;

        assert(line);

        if (from >= line->width)
                return;
        if (from + num < from || from + num > line->width)
                num = line->width - from;
        if (!num)
                return;

        /* destroy and move as many upfront as possible */
        move = line->width - from - num;
        rem = MIN(num, move);
        if (rem > 0) {
                /* destroy to be removed cells */
                term_cell_destroy_n(line->cells + from, rem);

                /* move tail upfront */
                memmove(line->cells + from,
                        line->cells + from + num,
                        sizeof(*line->cells) * move);

                /* invalidate copied cells */
                for (i = 0; i < move; ++i)
                        line->cells[from + i].age = age;

                /* initialize tail that was moved away */
                term_cell_init_n(line->cells + line->width - rem,
                                 rem,
                                 attr,
                                 age);

                /* reset remaining cells in case the move was too small */
                if (num > move)
                        term_cell_clear_n(line->cells + from + move,
                                          num - move,
                                          attr,
                                          age);
        } else {
                /* reset cells */
                term_cell_clear_n(line->cells + from,
                                  num,
                                  attr,
                                  age);
        }

        /* adjust fill-state */
        if (from + num < line->fill)
                line->fill -= num;
        else if (from < line->fill)
                line->fill = from;
}

/**
 * term_line_append_combchar() - Append combining char to existing cell
 * @line: line to modify
 * @pos_x: position of cell to append combining char to
 * @ucs4: combining character to append
 * @age: current age for all modifications
 *
 * Unicode allows trailing combining characters, which belong to the
 * char in front of them. The caller is responsible of detecting
 * combining characters and calling term_line_append_combchar() instead of
 * term_line_write(). This simply appends the char to the correct cell then.
 * If the cell is not in the visible area, this call is skipped.
 *
 * Note that control-sequences are not 100% compatible with combining
 * characters as they require delayed parsing. However, we must handle
 * control-sequences immediately. Therefore, there might be trailing
 * combining chars that should be discarded by the parser.
 * However, to prevent programming errors, we're also being pedantic
 * here and discard weirdly placed combining chars. This prevents
 * situations were invalid content is parsed into the terminal and you
 * might end up with cells containing only combining chars.
 *
 * Long story short: To get combining-characters working with old-fashioned
 * terminal-emulation, we parse them exclusively for direct cell-writes. Other
 * combining-characters are usually simply discarded and ignored.
 */
void term_line_append_combchar(term_line *line, unsigned int pos_x, uint32_t ucs4, term_age_t age) {
        assert(line);

        if (pos_x >= line->width)
                return;

        /* Unused cell? Skip appending any combining chars then. */
        if (term_char_is_null(line->cells[pos_x].ch))
                return;

        term_cell_append(line->cells + pos_x, ucs4, age);
}

/**
 * term_line_erase() - Erase parts of a line
 * @line: line to modify
 * @from: position to start the erase
 * @num: number of cells to erase
 * @attr: attributes to initialize erased cells with
 * @age: current age for all modifications
 * @keep_protected: true if protected cells should be kept
 *
 * This is the standard erase operation. It clears all cells in the targeted
 * area and re-initializes them. Cells to the right are not shifted left, you
 * must use DELETE to achieve that. Cells outside the visible area are skipped.
 *
 * If @keep_protected is true, protected cells will not be erased.
 */
void term_line_erase(term_line *line, unsigned int from, unsigned int num, const term_attr *attr, term_age_t age, bool keep_protected) {
        term_cell *cell;
        unsigned int i, last_protected;

        assert(line);

        if (from >= line->width)
                return;
        if (from + num < from || from + num > line->width)
                num = line->width - from;
        if (!num)
                return;

        last_protected = 0;
        for (i = 0; i < num; ++i) {
                cell = line->cells + from + i;
                if (keep_protected && cell->attr.protect) {
                        /* only count protected-cells inside the fill-region */
                        if (from + i < line->fill)
                                last_protected = from + i;

                        continue;
                }

                term_cell_set(cell, TERM_CHAR_NULL, 0, attr, age);
        }

        /* Adjust fill-state. This is a bit tricks, we can only adjust it in
         * case the erase-region starts inside the fill-region and ends at the
         * tail or beyond the fill-region. Otherwise, the current fill-state
         * stays as it was.
         * Furthermore, we must account for protected cells. The loop above
         * ensures that protected-cells are only accounted for if they're
         * inside the fill-region. */
        if (from < line->fill && from + num >= line->fill)
                line->fill = MAX(from, last_protected);
}

/**
 * term_line_reset() - Reset a line
 * @line: line to reset
 * @attr: attributes to initialize all cells with
 * @age: current age for all modifications
 *
 * This resets all visible cells of a line and sets their attributes and ages
 * to @attr and @age. This is equivalent to erasing a whole line via
 * term_line_erase().
 */
void term_line_reset(term_line *line, const term_attr *attr, term_age_t age) {
        assert(line);

        return term_line_erase(line, 0, line->width, attr, age, 0);
}

/**
 * term_line_link() - Link line in front of a list
 * @line: line to link
 * @first: member pointing to first entry
 * @last: member pointing to last entry
 *
 * This links a line into a list of lines. The line is inserted at the front and
 * must not be linked, yet. See the TERM_LINE_LINK() macro for an easier usage of
 * this.
 */
void term_line_link(term_line *line, term_line **first, term_line **last) {
        assert(line);
        assert(first);
        assert(last);
        assert(!line->lines_prev);
        assert(!line->lines_next);

        line->lines_prev = NULL;
        line->lines_next = *first;
        if (*first)
                (*first)->lines_prev = line;
        else
                *last = line;
        *first = line;
}

/**
 * term_line_link_tail() - Link line at tail of a list
 * @line: line to link
 * @first: member pointing to first entry
 * @last: member pointing to last entry
 *
 * Same as term_line_link() but links the line at the tail.
 */
void term_line_link_tail(term_line *line, term_line **first, term_line **last) {
        assert(line);
        assert(first);
        assert(last);
        assert(!line->lines_prev);
        assert(!line->lines_next);

        line->lines_next = NULL;
        line->lines_prev = *last;
        if (*last)
                (*last)->lines_next = line;
        else
                *first = line;
        *last = line;
}

/**
 * term_line_unlink() - Unlink line from a list
 * @line: line to unlink
 * @first: member pointing to first entry
 * @last: member pointing to last entry
 *
 * This unlinks a previously linked line. See TERM_LINE_UNLINK() for an easier to
 * use macro.
 */
void term_line_unlink(term_line *line, term_line **first, term_line **last) {
        assert(line);
        assert(first);
        assert(last);

        if (line->lines_prev)
                line->lines_prev->lines_next = line->lines_next;
        else
                *first = line->lines_next;
        if (line->lines_next)
                line->lines_next->lines_prev = line->lines_prev;
        else
                *last = line->lines_prev;

        line->lines_prev = NULL;
        line->lines_next = NULL;
}

/**
 * term_page_new() - Allocate new page
 * @out: storage for pointer to new page
 *
 * Allocate a new page. The initial dimensions are 0/0.
 *
 * Returns: 0 on success, negative error code on failure.
 */
int term_page_new(term_page **out) {
        _term_page_free_ term_page *page = NULL;

        assert_return(out, -EINVAL);

        page = new0(term_page, 1);
        if (!page)
                return -ENOMEM;

        *out = page;
        page = NULL;
        return 0;
}

/**
 * term_page_free() - Free page
 * @page: page to free or NULL
 *
 * Free a previously allocated page and all associated data. If @page is NULL,
 * this is a no-op.
 *
 * Returns: NULL
 */
term_page *term_page_free(term_page *page) {
        unsigned int i;

        if (!page)
                return NULL;

        for (i = 0; i < page->n_lines; ++i)
                term_line_free(page->lines[i]);

        free(page->line_cache);
        free(page->lines);
        free(page);

        return NULL;
}

/**
 * term_page_get_cell() - Return pointer to requested cell
 * @page: page to operate on
 * @x: x-position of cell
 * @y: y-position of cell
 *
 * This returns a pointer to the cell at position @x/@y. You're free to modify
 * this cell as much as you like. However, once you call any other function on
 * the page, you must drop the pointer to the cell.
 *
 * Returns: Pointer to the cell or NULL if out of the visible area.
 */
term_cell *term_page_get_cell(term_page *page, unsigned int x, unsigned int y) {
        assert_return(page, NULL);

        if (x >= page->width)
                return NULL;
        if (y >= page->height)
                return NULL;

        return &page->lines[y]->cells[x];
}

/**
 * page_scroll_up() - Scroll up
 * @page: page to operate on
 * @new_width: width to use for any new line moved into the visible area
 * @num: number of lines to scroll up
 * @attr: attributes to set on new lines
 * @age: age to use for all modifications
 * @history: history to use for old lines or NULL
 *
 * This scrolls the scroll-region by @num lines. New lines are cleared and reset
 * with the given attributes. Old lines are moved into the history if non-NULL.
 * If a new line is allocated, moved from the history buffer or moved from
 * outside the visible region into the visible region, this call makes sure it
 * has at least @width cells allocated. If a possible memory-allocation fails,
 * the previous line is reused. This has the side effect, that it will not be
 * linked into the history buffer.
 *
 * If the scroll-region is empty, this is a no-op.
 */
static void page_scroll_up(term_page *page, unsigned int new_width, unsigned int num, const term_attr *attr, term_age_t age, term_history *history) {
        term_line *line, **cache;
        unsigned int i;
        int r;

        assert(page);

        if (num > page->scroll_num)
                num = page->scroll_num;
        if (num < 1)
                return;

        /* Better safe than sorry: avoid under-allocating lines, even when
         * resizing. */
        new_width = MAX(new_width, page->width);

        cache = page->line_cache;

        /* Try moving lines into history and allocate new lines for each moved
         * line. In case allocation fails, or if we have no history, reuse the
         * line.
         * We keep the lines in the line-cache so we can safely move the
         * remaining lines around. */
        for (i = 0; i < num; ++i) {
                line = page->lines[page->scroll_idx + i];

                r = -EAGAIN;
                if (history) {
                        r = term_line_new(&cache[i]);
                        if (r >= 0) {
                                r = term_line_reserve(cache[i],
                                                      new_width,
                                                      attr,
                                                      age,
                                                      0);
                                if (r < 0)
                                        term_line_free(cache[i]);
                                else
                                        term_line_set_width(cache[i], page->width);
                        }
                }

                if (r >= 0) {
                        term_history_push(history, line);
                } else {
                        cache[i] = line;
                        term_line_reset(line, attr, age);
                }
        }

        if (num < page->scroll_num) {
                memmove(page->lines + page->scroll_idx,
                        page->lines + page->scroll_idx + num,
                        sizeof(*page->lines) * (page->scroll_num - num));

                /* update age of moved lines */
                for (i = 0; i < page->scroll_num - num; ++i)
                        page->lines[page->scroll_idx + i]->age = age;
        }

        /* copy remaining lines from cache; age is already updated */
        memcpy(page->lines + page->scroll_idx + page->scroll_num - num,
               cache,
               sizeof(*cache) * num);

        /* update fill */
        page->scroll_fill -= MIN(page->scroll_fill, num);
}

/**
 * page_scroll_down() - Scroll down
 * @page: page to operate on
 * @new_width: width to use for any new line moved into the visible area
 * @num: number of lines to scroll down
 * @attr: attributes to set on new lines
 * @age: age to use for all modifications
 * @history: history to use for new lines or NULL
 *
 * This scrolls the scroll-region by @num lines. New lines are retrieved from
 * the history or cleared if the history is empty or NULL.
 *
 * Usually, scroll-down implies that new lines are cleared. Therefore, you're
 * highly encouraged to set @history to NULL. However, if you resize a terminal,
 * you might want to include history-lines in the new area. In that case, you
 * should set @history to non-NULL.
 *
 * If a new line is allocated, moved from the history buffer or moved from
 * outside the visible region into the visible region, this call makes sure it
 * has at least @width cells allocated. If a possible memory-allocation fails,
 * the previous line is reused. This will have the side-effect that lines from
 * the history will not get visible on-screen but kept in history.
 *
 * If the scroll-region is empty, this is a no-op.
 */
static void page_scroll_down(term_page *page, unsigned int new_width, unsigned int num, const term_attr *attr, term_age_t age, term_history *history) {
        term_line *line, **cache, *t;
        unsigned int i, last_idx;

        assert(page);

        if (num > page->scroll_num)
                num = page->scroll_num;
        if (num < 1)
                return;

        /* Better safe than sorry: avoid under-allocating lines, even when
         * resizing. */
        new_width = MAX(new_width, page->width);

        cache = page->line_cache;
        last_idx = page->scroll_idx + page->scroll_num - 1;

        /* Try pulling out lines from history; if history is empty or if no
         * history is given, we reuse the to-be-removed lines. Otherwise, those
         * lines are released. */
        for (i = 0; i < num; ++i) {
                line = page->lines[last_idx - i];

                t = NULL;
                if (history)
                        t = term_history_pop(history, new_width, attr, age);

                if (t) {
                        cache[num - 1 - i] = t;
                        term_line_free(line);
                } else {
                        cache[num - 1 - i] = line;
                        term_line_reset(line, attr, age);
                }
        }

        if (num < page->scroll_num) {
                memmove(page->lines + page->scroll_idx + num,
                        page->lines + page->scroll_idx,
                        sizeof(*page->lines) * (page->scroll_num - num));

                /* update age of moved lines */
                for (i = 0; i < page->scroll_num - num; ++i)
                        page->lines[page->scroll_idx + num + i]->age = age;
        }

        /* copy remaining lines from cache; age is already updated */
        memcpy(page->lines + page->scroll_idx,
               cache,
               sizeof(*cache) * num);

        /* update fill; but only if there's already content in it */
        if (page->scroll_fill > 0)
                page->scroll_fill = MIN(page->scroll_num,
                                        page->scroll_fill + num);
}

/**
 * page_reserve() - Reserve page area
 * @page: page to modify
 * @cols: required columns (width)
 * @rows: required rows (height)
 * @attr: attributes for newly allocated cells
 * @age: age to set on any modified cells
 *
 * This allocates the required amount of lines and cells to guarantee that the
 * page has at least the demanded dimensions of @cols x @rows. Note that this
 * never shrinks the page-memory. We keep cells allocated for performance
 * reasons.
 *
 * Additionally to allocating lines, this also clears any newly added cells so
 * you can safely change the size afterwards without clearing new cells.
 *
 * Note that you must be careful what operations you call on the page between
 * page_reserve() and updating page->width/height. Any newly allocated line (or
 * shifted line) might not meet your new width/height expectations.
 *
 * Returns: 0 on success, negative error code on failure.
 */
int term_page_reserve(term_page *page, unsigned int cols, unsigned int rows, const term_attr *attr, term_age_t age) {
        _term_line_free_ term_line *line = NULL;
        unsigned int i, min_lines;
        term_line **t;
        int r;

        assert_return(page, -EINVAL);

        /*
         * First make sure the first MIN(page->n_lines, rows) lines have at
         * least the required width of @cols. This does not modify any visible
         * cells in the existing @page->width x @page->height area, therefore,
         * we can safely bail out afterwards in case anything else fails.
         * Note that lines in between page->height and page->n_lines might be
         * shorter than page->width. Hence, we need to resize them all, but we
         * can skip some of them for better performance.
         */
        min_lines = MIN(page->n_lines, rows);
        for (i = 0; i < min_lines; ++i) {
                /* lines below page->height have at least page->width cells */
                if (cols < page->width && i < page->height)
                        continue;

                r = term_line_reserve(page->lines[i],
                                      cols,
                                      attr,
                                      age,
                                      (i < page->height) ? page->width : 0);
                if (r < 0)
                        return r;
        }

        /*
         * We now know the first @min_lines lines have at least width @cols and
         * are prepared for resizing. We now only have to allocate any
         * additional lines below @min_lines in case @rows is greater than
         * page->n_lines.
         */
        if (rows > page->n_lines) {
                t = realloc_multiply(page->lines, sizeof(*t), rows);
                if (!t)
                        return -ENOMEM;
                page->lines = t;

                t = realloc_multiply(page->line_cache, sizeof(*t), rows);
                if (!t)
                        return -ENOMEM;
                page->line_cache = t;

                while (page->n_lines < rows) {
                        r = term_line_new(&line);
                        if (r < 0)
                                return r;

                        r = term_line_reserve(line, cols, attr, age, 0);
                        if (r < 0)
                                return r;

                        page->lines[page->n_lines++] = line;
                        line = NULL;
                }
        }

        return 0;
}

/**
 * term_page_resize() - Resize page
 * @page: page to modify
 * @cols: number of columns (width)
 * @rows: number of rows (height)
 * @attr: attributes for newly allocated cells
 * @age: age to set on any modified cells
 * @history: history buffer to use for new/old lines or NULL
 *
 * This changes the visible dimensions of a page. You must have called
 * term_page_reserve() beforehand, otherwise, this will fail.
 *
 * Returns: 0 on success, negative error code on failure.
 */
void term_page_resize(term_page *page, unsigned int cols, unsigned int rows, const term_attr *attr, term_age_t age, term_history *history) {
        unsigned int i, num, empty, max, old_height;
        term_line *line;

        assert(page);
        assert(page->n_lines >= rows);

        old_height = page->height;

        if (rows < old_height) {
                /*
                 * If we decrease the terminal-height, we emulate a scroll-up.
                 * This way, existing data from the scroll-area is moved into
                 * the history, making space at the bottom to reduce the screen
                 * height. In case the scroll-fill indicates empty lines, we
                 * reduce the amount of scrolled lines.
                 * Once scrolled, we have to move the lower margin from below
                 * the scroll area up so it is preserved.
                 */

                /* move lines to history if scroll region is filled */
                num = old_height - rows;
                empty = page->scroll_num - page->scroll_fill;
                if (num > empty)
                        page_scroll_up(page,
                                       cols,
                                       num - empty,
                                       attr,
                                       age,
                                       history);

                /* move lower margin up; drop its lines if not enough space */
                num = LESS_BY(old_height, page->scroll_idx + page->scroll_num);
                max = LESS_BY(rows, page->scroll_idx);
                num = MIN(num, max);
                if (num > 0) {
                        unsigned int top, bottom;

                        top = rows - num;
                        bottom = page->scroll_idx + page->scroll_num;

                        /* might overlap; must run topdown, not bottomup */
                        for (i = 0; i < num; ++i) {
                                line = page->lines[top + i];
                                page->lines[top + i] = page->lines[bottom + i];
                                page->lines[bottom + i] = line;
                        }
                }

                /* update vertical extents */
                page->height = rows;
                page->scroll_idx = MIN(page->scroll_idx, rows);
                page->scroll_num -= MIN(page->scroll_num, old_height - rows);
                /* fill is already up-to-date or 0 due to scroll-up */
        } else if (rows > old_height) {
                /*
                 * If we increase the terminal-height, we emulate a scroll-down
                 * and fetch new lines from the history.
                 * New lines are always accounted to the scroll-region. Thus we
                 * have to preserve the lower margin first, by moving it down.
                 */

                /* move lower margin down */
                num = LESS_BY(old_height, page->scroll_idx + page->scroll_num);
                if (num > 0) {
                        unsigned int top, bottom;

                        top = page->scroll_idx + page->scroll_num;
                        bottom = top + (rows - old_height);

                        /* might overlap; must run bottomup, not topdown */
                        for (i = num; i-- > 0; ) {
                                line = page->lines[top + i];
                                page->lines[top + i] = page->lines[bottom + i];
                                page->lines[bottom + i] = line;
                        }
                }

                /* update vertical extents */
                page->height = rows;
                page->scroll_num = MIN(LESS_BY(rows, page->scroll_idx),
                                       page->scroll_num + (rows - old_height));

                /* check how many lines can be received from history */
                if (history)
                        num = term_history_peek(history,
                                                rows - old_height,
                                                cols,
                                                attr,
                                                age);
                else
                        num = 0;

                /* retrieve new lines from history if available */
                if (num > 0)
                        page_scroll_down(page,
                                         cols,
                                         num,
                                         attr,
                                         age,
                                         history);
        }

        /* set horizontal extents */
        page->width = cols;
        for (i = 0; i < page->height; ++i)
                term_line_set_width(page->lines[i], cols);
}

/**
 * term_page_write() - Write to a single cell
 * @page: page to operate on
 * @pos_x: x-position of cell to write to
 * @pos_y: y-position of cell to write to
 * @ch: character to write
 * @cwidth: character-width of @ch
 * @attr: attributes to set on the cell or NULL
 * @age: age to use for all modifications
 * @insert_mode: true if INSERT-MODE is enabled
 *
 * This writes a character to a specific cell. If the cell is beyond bounds,
 * this is a no-op. @attr and @age are used to update the cell. @flags can be
 * used to alter the behavior of this function.
 *
 * This is a wrapper around term_line_write().
 *
 * This call does not wrap around lines. That is, this only operates on a single
 * line.
 */
void term_page_write(term_page *page, unsigned int pos_x, unsigned int pos_y, term_char_t ch, unsigned int cwidth, const term_attr *attr, term_age_t age, bool insert_mode) {
        assert(page);

        if (pos_y >= page->height)
                return;

        term_line_write(page->lines[pos_y], pos_x, ch, cwidth, attr, age, insert_mode);
}

/**
 * term_page_insert_cells() - Insert cells into a line
 * @page: page to operate on
 * @from_x: x-position where to insert new cells
 * @from_y: y-position where to insert new cells
 * @num: number of cells to insert
 * @attr: attributes to set on new cells or NULL
 * @age: age to use for all modifications
 *
 * This inserts new cells into a given line. This is a wrapper around
 * term_line_insert().
 *
 * This call does not wrap around lines. That is, this only operates on a single
 * line.
 */
void term_page_insert_cells(term_page *page, unsigned int from_x, unsigned int from_y, unsigned int num, const term_attr *attr, term_age_t age) {
        assert(page);

        if (from_y >= page->height)
                return;

        term_line_insert(page->lines[from_y], from_x, num, attr, age);
}

/**
 * term_page_delete_cells() - Delete cells from a line
 * @page: page to operate on
 * @from_x: x-position where to delete cells
 * @from_y: y-position where to delete cells
 * @num: number of cells to delete
 * @attr: attributes to set on new cells or NULL
 * @age: age to use for all modifications
 *
 * This deletes cells from a given line. This is a wrapper around
 * term_line_delete().
 *
 * This call does not wrap around lines. That is, this only operates on a single
 * line.
 */
void term_page_delete_cells(term_page *page, unsigned int from_x, unsigned int from_y, unsigned int num, const term_attr *attr, term_age_t age) {
        assert(page);

        if (from_y >= page->height)
                return;

        term_line_delete(page->lines[from_y], from_x, num, attr, age);
}

/**
 * term_page_append_combchar() - Append combining-character to a cell
 * @page: page to operate on
 * @pos_x: x-position of target cell
 * @pos_y: y-position of target cell
 * @ucs4: combining character to append
 * @age: age to use for all modifications
 *
 * This appends a combining-character to a specific cell. This is a wrapper
 * around term_line_append_combchar().
 */
void term_page_append_combchar(term_page *page, unsigned int pos_x, unsigned int pos_y, uint32_t ucs4, term_age_t age) {
        assert(page);

        if (pos_y >= page->height)
                return;

        term_line_append_combchar(page->lines[pos_y], pos_x, ucs4, age);
}

/**
 * term_page_erase() - Erase parts of a page
 * @page: page to operate on
 * @from_x: x-position where to start erasure (inclusive)
 * @from_y: y-position where to start erasure (inclusive)
 * @to_x: x-position where to stop erasure (inclusive)
 * @to_y: y-position where to stop erasure (inclusive)
 * @attr: attributes to set on cells
 * @age: age to use for all modifications
 * @keep_protected: true if protected cells should be kept
 *
 * This erases all cells starting at @from_x/@from_y up to @to_x/@to_y. Note
 * that this wraps around line-boundaries so lines between @from_y and @to_y
 * are cleared entirely.
 *
 * Lines outside the visible area are left untouched.
 */
void term_page_erase(term_page *page, unsigned int from_x, unsigned int from_y, unsigned int to_x, unsigned int to_y, const term_attr *attr, term_age_t age, bool keep_protected) {
        unsigned int i, from, to;

        assert(page);

        for (i = from_y; i <= to_y && i < page->height; ++i) {
                from = 0;
                to = page->width;

                if (i == from_y)
                        from = from_x;
                if (i == to_y)
                        to = to_x;

                term_line_erase(page->lines[i],
                                from,
                                LESS_BY(to, from),
                                attr,
                                age,
                                keep_protected);
        }
}

/**
 * term_page_reset() - Reset page
 * @page: page to modify
 * @attr: attributes to set on cells
 * @age: age to use for all modifications
 *
 * This erases the whole visible page. See term_page_erase().
 */
void term_page_reset(term_page *page, const term_attr *attr, term_age_t age) {
        assert(page);

        return term_page_erase(page,
                               0, 0,
                               page->width - 1, page->height - 1,
                               attr,
                               age,
                               0);
}

/**
 * term_page_set_scroll_region() - Set scroll region
 * @page: page to operate on
 * @idx: start-index of scroll region
 * @num: number of lines in scroll region
 *
 * This sets the scroll region of a page. Whenever an operation needs to scroll
 * lines, it scrolls them inside of that region. Lines outside the region are
 * left untouched. In case a scroll-operation is targeted outside of this
 * region, it will implicitly get a scroll-region of only one line (i.e., no
 * scroll region at all).
 *
 * Note that the scroll-region is clipped to the current page-extents. Growing
 * or shrinking the page always accounts new/old lines to the scroll region and
 * moves top/bottom margins accordingly so they're preserved.
 */
void term_page_set_scroll_region(term_page *page, unsigned int idx, unsigned int num) {
        assert(page);

        if (page->height < 1) {
                page->scroll_idx = 0;
                page->scroll_num = 0;
        } else {
                page->scroll_idx = MIN(idx, page->height - 1);
                page->scroll_num = MIN(num, page->height - page->scroll_idx);
        }
}

/**
 * term_page_scroll_up() - Scroll up
 * @page: page to operate on
 * @num: number of lines to scroll up
 * @attr: attributes to set on new lines
 * @age: age to use for all modifications
 * @history: history to use for old lines or NULL
 *
 * This scrolls the scroll-region by @num lines. New lines are cleared and reset
 * with the given attributes. Old lines are moved into the history if non-NULL.
 *
 * If the scroll-region is empty, this is a no-op.
 */
void term_page_scroll_up(term_page *page, unsigned int num, const term_attr *attr, term_age_t age, term_history *history) {
        page_scroll_up(page, page->width, num, attr, age, history);
}

/**
 * term_page_scroll_down() - Scroll down
 * @page: page to operate on
 * @num: number of lines to scroll down
 * @attr: attributes to set on new lines
 * @age: age to use for all modifications
 * @history: history to use for new lines or NULL
 *
 * This scrolls the scroll-region by @num lines. New lines are retrieved from
 * the history or cleared if the history is empty or NULL.
 *
 * Usually, scroll-down implies that new lines are cleared. Therefore, you're
 * highly encouraged to set @history to NULL. However, if you resize a terminal,
 * you might want to include history-lines in the new area. In that case, you
 * should set @history to non-NULL.
 *
 * If the scroll-region is empty, this is a no-op.
 */
void term_page_scroll_down(term_page *page, unsigned int num, const term_attr *attr, term_age_t age, term_history *history) {
        page_scroll_down(page, page->width, num, attr, age, history);
}

/**
 * term_page_insert_lines() - Insert new lines
 * @page: page to operate on
 * @pos_y: y-position where to insert new lines
 * @num: number of lines to insert
 * @attr: attributes to set on new lines
 * @age: age to use for all modifications
 *
 * This inserts @num new lines at position @pos_y. If @pos_y is beyond
 * boundaries or @num is 0, this is a no-op.
 * All lines below @pos_y are moved down to make space for the new lines. Lines
 * on the bottom are dropped. Note that this only moves lines above or inside
 * the scroll-region. If @pos_y is below the scroll-region, a scroll-region of
 * one line is implied (which means the line is simply cleared).
 */
void term_page_insert_lines(term_page *page, unsigned int pos_y, unsigned int num, const term_attr *attr, term_age_t age) {
        unsigned int scroll_idx, scroll_num;

        assert(page);

        if (pos_y >= page->height)
                return;
        if (num >= page->height)
                num = page->height;

        /* remember scroll-region */
        scroll_idx = page->scroll_idx;
        scroll_num = page->scroll_num;

        /* set scroll-region temporarily so we can reuse scroll_down() */
        {
                page->scroll_idx = pos_y;
                if (pos_y >= scroll_idx + scroll_num)
                        page->scroll_num = 1;
                else if (pos_y >= scroll_idx)
                        page->scroll_num -= pos_y - scroll_idx;
                else
                        page->scroll_num += scroll_idx - pos_y;

                term_page_scroll_down(page, num, attr, age, NULL);
        }

        /* reset scroll-region */
        page->scroll_idx = scroll_idx;
        page->scroll_num = scroll_num;
}

/**
 * term_page_delete_lines() - Delete lines
 * @page: page to operate on
 * @pos_y: y-position where to delete lines
 * @num: number of lines to delete
 * @attr: attributes to set on new lines
 * @age: age to use for all modifications
 *
 * This deletes @num lines at position @pos_y. If @pos_y is beyond boundaries or
 * @num is 0, this is a no-op.
 * All lines below @pos_y are moved up into the newly made space. New lines
 * on the bottom are clear. Note that this only moves lines above or inside
 * the scroll-region. If @pos_y is below the scroll-region, a scroll-region of
 * one line is implied (which means the line is simply cleared).
 */
void term_page_delete_lines(term_page *page, unsigned int pos_y, unsigned int num, const term_attr *attr, term_age_t age) {
        unsigned int scroll_idx, scroll_num;

        assert(page);

        if (pos_y >= page->height)
                return;
        if (num >= page->height)
                num = page->height;

        /* remember scroll-region */
        scroll_idx = page->scroll_idx;
        scroll_num = page->scroll_num;

        /* set scroll-region temporarily so we can reuse scroll_up() */
        {
                page->scroll_idx = pos_y;
                if (pos_y >= scroll_idx + scroll_num)
                        page->scroll_num = 1;
                else if (pos_y > scroll_idx)
                        page->scroll_num -= pos_y - scroll_idx;
                else
                        page->scroll_num += scroll_idx - pos_y;

                term_page_scroll_up(page, num, attr, age, NULL);
        }

        /* reset scroll-region */
        page->scroll_idx = scroll_idx;
        page->scroll_num = scroll_num;
}

/**
 * term_history_new() - Create new history object
 * @out: storage for pointer to new history
 *
 * Create a new history object. Histories are used to store scrollback-lines
 * from VTE pages. You're highly recommended to set a history-limit on
 * history->max_lines and trim it via term_history_trim(), otherwise history
 * allocations are unlimited.
 *
 * Returns: 0 on success, negative error code on failure.
 */
int term_history_new(term_history **out) {
        _term_history_free_ term_history *history = NULL;

        assert_return(out, -EINVAL);

        history = new0(term_history, 1);
        if (!history)
                return -ENOMEM;

        history->max_lines = 4096;

        *out = history;
        history = NULL;
        return 0;
}

/**
 * term_history_free() - Free history
 * @history: history to free
 *
 * Clear and free history. You must not access the object afterwards.
 *
 * Returns: NULL
 */
term_history *term_history_free(term_history *history) {
        if (!history)
                return NULL;

        term_history_clear(history);
        free(history);
        return NULL;
}

/**
 * term_history_clear() - Clear history
 * @history: history to clear
 *
 * Remove all linked lines from a history and reset it to its initial state.
 */
void term_history_clear(term_history *history) {
        return term_history_trim(history, 0);
}

/**
 * term_history_trim() - Trim history
 * @history: history to trim
 * @max: maximum number of lines to be left in history
 *
 * This removes lines from the history until it is smaller than @max. Lines are
 * removed from the top.
 */
void term_history_trim(term_history *history, unsigned int max) {
        term_line *line;

        if (!history)
                return;

        while (history->n_lines > max && (line = history->lines_first)) {
                TERM_LINE_UNLINK(line, history);
                term_line_free(line);
                --history->n_lines;
        }
}

/**
 * term_history_push() - Push line into history
 * @history: history to work on
 * @line: line to push into history
 *
 * This pushes a line into the given history. It is linked at the tail. In case
 * the history is limited, the top-most line might be freed.
 */
void term_history_push(term_history *history, term_line *line) {
        assert(history);
        assert(line);

        TERM_LINE_LINK_TAIL(line, history);
        if (history->max_lines > 0 && history->n_lines >= history->max_lines) {
                line = history->lines_first;
                TERM_LINE_UNLINK(line, history);
                term_line_free(line);
        } else {
                ++history->n_lines;
        }
}

/**
 * term_history_pop() - Retrieve last line from history
 * @history: history to work on
 * @new_width: width to reserve and set on the line
 * @attr: attributes to use for cell reservation
 * @age: age to use for cell reservation
 *
 * This unlinks the last linked line of the history and returns it. This also
 * makes sure the line has the given width pre-allocated (see
 * term_line_reserve()). If the pre-allocation fails, this returns NULL, so it
 * is treated like there's no line in history left. This simplifies
 * history-handling on the caller's side in case of allocation errors. No need
 * to throw lines away just because the reservation failed. We can keep them in
 * history safely, and make them available as scrollback.
 *
 * Returns: Line from history or NULL
 */
term_line *term_history_pop(term_history *history, unsigned int new_width, const term_attr *attr, term_age_t age) {
        term_line *line;
        int r;

        assert_return(history, NULL);

        line = history->lines_last;
        if (!line)
                return NULL;

        r = term_line_reserve(line, new_width, attr, age, line->width);
        if (r < 0)
                return NULL;

        term_line_set_width(line, new_width);
        TERM_LINE_UNLINK(line, history);
        --history->n_lines;

        return line;
}

/**
 * term_history_peek() - Return number of available history-lines
 * @history: history to work on
 * @max: maximum number of lines to look at
 * @reserve_width: width to reserve on the line
 * @attr: attributes to use for cell reservation
 * @age: age to use for cell reservation
 *
 * This returns the number of available lines in the history given as @history.
 * It returns at most @max. For each line that is looked at, the line is
 * verified to have at least @reserve_width cells. Valid cells are preserved,
 * new cells are initialized with @attr and @age. In case an allocation fails,
 * we bail out and return the number of lines that are valid so far.
 *
 * Usually, this function should be used before running a loop on
 * term_history_pop(). This function guarantees that term_history_pop() (with
 * the same arguments) will succeed at least the returned number of times.
 *
 * Returns: Number of valid lines that can be received via term_history_pop().
 */
unsigned int term_history_peek(term_history *history, unsigned int max, unsigned int reserve_width, const term_attr *attr, term_age_t age) {
        unsigned int num;
        term_line *line;
        int r;

        assert(history);

        num = 0;
        line = history->lines_last;

        while (num < max && line) {
                r = term_line_reserve(line, reserve_width, attr, age, line->width);
                if (r < 0)
                        break;

                ++num;
                line = line->lines_prev;
        }

        return num;
}