tpnote-lib 0.45.8

Minimalistic note-taking: save and edit your clipboard content as a note file
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
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
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
//! Extends the built-in Tera filters.
//! All custom filters check the type of their input variables at runtime and
//! throw an error if the type is other than specified.
use crate::config::FILENAME_DOTFILE_MARKER;
use crate::config::LIB_CFG;
use crate::config::Scheme;
use crate::config::TMPL_VAR_FM_;
use crate::filename::NotePath;
use crate::filename::NotePathBuf;
use crate::filename::NotePathStr;
#[cfg(feature = "lang-detection")]
use crate::lingua::get_lang;
use crate::markup_language::InputConverter;
use crate::markup_language::MarkupLanguage;
use crate::settings::SETTINGS;
use parse_hyperlinks::iterator::MarkupLink;
use parse_hyperlinks::parser::Link;
use sanitize_filename_reader_friendly::sanitize;
use std::borrow::Cow;
use std::collections::HashMap;
use std::hash::BuildHasher;
use std::path::Path;
use std::path::PathBuf;
use std::sync::LazyLock;
use tera::Map;
use tera::{Result as TeraResult, Tera, Value, try_get_value};

/// Filter parameter of the `trunc_filter()` limiting the maximum length of
/// template variables. The filter is usually used to in the note's front matter
/// as title. For example: the title should not be too long, because it will end
/// up as part of the filename when the note is saved to disk. Filenames of some
/// operating systems are limited to 255 bytes.
#[cfg(not(test))]
const TRUNC_LEN_MAX: usize = 200;
#[cfg(test)]
pub const TRUNC_LEN_MAX: usize = 10;

/// Tera object with custom functions registered.
pub static TERA: LazyLock<Tera> = LazyLock::new(|| {
    let mut tera = Tera::default();
    tera.register_filter("append", append_filter);
    tera.register_filter("file_copy_counter", file_copy_counter_filter);
    tera.register_filter("file_ext", file_ext_filter);
    tera.register_filter("file_name", file_name_filter);
    tera.register_filter("file_sort_tag", file_sort_tag_filter);
    tera.register_filter("file_stem", file_stem_filter);
    tera.register_filter("find_last_created_file", find_last_created_file);
    tera.register_filter("flatten_array", flatten_array_filter);
    tera.register_filter("get_lang", get_lang_filter);
    tera.register_filter("heading", heading_filter);
    tera.register_filter("html_heading", html_heading_filter);
    tera.register_filter("html_to_markup", html_to_markup_filter);
    tera.register_filter("incr_sort_tag", incr_sort_tag_filter);
    tera.register_filter("insert", insert_filter);
    tera.register_filter("insert", insert_filter);
    tera.register_filter("link_dest", link_dest_filter);
    tera.register_filter("link_text", link_text_filter);
    tera.register_filter("link_text_picky", link_text_picky_filter);
    tera.register_filter("link_title", link_title_filter);
    tera.register_filter("map_lang", map_lang_filter);
    tera.register_filter("markup_to_html", markup_to_html_filter);
    tera.register_filter("name", name_filter);
    tera.register_filter("prepend", prepend_filter);
    tera.register_filter("remove", remove_filter);
    tera.register_filter("replace_empty", replace_empty_filter);
    tera.register_filter("sanit", sanit_filter);
    tera.register_filter("to_html", to_html_filter);
    tera.register_filter("to_yaml", to_yaml_filter);
    tera.register_filter("trim_file_sort_tag", trim_file_sort_tag_filter);
    tera.register_filter("trunc", trunc_filter);
    tera
});

/// A filter converting any input `tera::Value` into a `tera::Value::String(s)`
/// with `s` being the YAML representation of the object. The input can be of
/// any type, the output type is always a `Value::String()`.
/// If the input type is `tera::Value::Object`, all top level keys starting with
/// `fm_` are localized (see `fm_var.localization`).
/// When the optional parameter `key='k'` is given, the input is regarded as
/// the corresponding value to this key.
/// The optional parameter `tab=n` indents the YAML values `n` characters to
/// the right of the first character of the key by inserting additional spaces
/// between the key and the value. When `tab=n` is given, it has precedence
/// over the default value, read from the configuration file variable
/// `tmpl.filter.to_yaml_tab`.
fn to_yaml_filter<S: BuildHasher>(
    val: &Value,
    args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let scheme = &LIB_CFG.read_recursive().scheme[SETTINGS.read_recursive().current_scheme];

    let val_yaml = if let Some(Value::String(k)) = args.get("key") {
        let mut m = tera::Map::new();
        let k = name(scheme, k);
        m.insert(k.to_owned(), val.to_owned());
        serde_yaml::to_string(&m).unwrap()
    } else {
        match &val {
            Value::Object(map) => {
                let mut m = Map::new();
                for (k, v) in map.into_iter() {
                    //
                    let new_k = name(scheme, k);
                    m.insert(new_k.to_owned(), v.to_owned());
                }
                let o = serde_json::Value::Object(m);
                serde_yaml::to_string(&o).unwrap()
            }
            &oo => serde_yaml::to_string(oo).unwrap(),
        }
    };

    // Translate the empty set, into an empty string and return it.
    if val_yaml.trim_end() == "{}" {
        return Ok(tera::Value::String("".to_string()));
    }

    // Formatting: adjust indent.
    let val_yaml: String = if let Some(tab) =
        args.get("tab").and_then(|v| v.as_u64()).or_else(|| {
            let n = scheme.tmpl.filter.to_yaml_tab;
            if n == 0 { None } else { Some(n) }
        }) {
        val_yaml
            .lines()
            .map(|l| {
                let mut insert_pos = 0;
                let mut inserts_n = 0;
                if let Some(colpos) = l.find(": ") {
                    if let Some(key_pos) = l.find(char::is_alphabetic) {
                        if key_pos < colpos
                            && l.find('\'').is_none_or(|p| p >= colpos)
                            && l.find("\"'").is_none_or(|p| p >= colpos)
                        {
                            insert_pos = colpos + ": ".len();
                            inserts_n = (tab as usize).saturating_sub(insert_pos);
                        }
                    }
                } else if l.starts_with("- ") {
                    inserts_n = tab as usize;
                };

                // Enlarge indent.
                let mut l = l.to_owned();
                let strut = " ".repeat(inserts_n);
                // If `insert>0`, we know that `colon_pos>0`.
                // `colon_pos+1` inserts between `: `.
                l.insert_str(insert_pos, &strut);
                l.push('\n');
                l
            })
            .collect::<String>()
    } else {
        val_yaml
    };

    let val_yaml = val_yaml.trim_end().to_owned();

    Ok(Value::String(val_yaml))
}

/// A filter that coverts a `tera::Value` tree into an HTML representation,
/// with following HTML tags:
/// * `Value::Object`: `<blockquote class="fm">` and `<div class="fm">`,
/// * `Value::Array`: `<ul class="fm">` and `<li class="fm">`,
/// * `Value::String`: no tag,
/// * Other non-string basic types: `<code class="fm">`.
///
/// The input can be of any type, the output type is `Value::String()`.
/// If the input type is `Value::Object`, all top level keys starting with
/// `fm_` are localized (see `fm_var.localization`).
/// Note: HTML templates escape HTML critical characters by default.
/// To use the `to_hmtl` filter in HTML templates, add a `safe` filter in last
/// position. This is no risk, as the `to_html` filter always escapes string
/// values automatically, regardless of the template type.
fn to_html_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    fn tag_to_html(val: Value, is_root: bool, output: &mut String) {
        match val {
            Value::Array(a) => {
                output.push_str("<ul class=\"fm\">");
                for i in a {
                    output.push_str("<li class=\"fm\">");
                    tag_to_html(i, false, output);
                    output.push_str("</li>");
                }
                output.push_str("</ul>");
            }

            Value::String(s) => output.push_str(&html_escape::encode_text(&s)),

            Value::Object(map) => {
                output.push_str("<blockquote class=\"fm\">");
                if is_root {
                    let scheme =
                        &LIB_CFG.read_recursive().scheme[SETTINGS.read_recursive().current_scheme];
                    for (k, v) in map {
                        output.push_str("<div class=\"fm\">");
                        output.push_str(name(scheme, &k));
                        output.push_str(": ");
                        tag_to_html(v, false, output);
                        output.push_str("</div>");
                    }
                } else {
                    for (k, v) in map {
                        output.push_str("<div class=\"fm\">");
                        output.push_str(&k);
                        output.push_str(": ");
                        tag_to_html(v, false, output);
                        output.push_str("</div>");
                    }
                }
                output.push_str("</blockquote>");
            }

            _ => {
                output.push_str("<code class=\"fm\">");
                output.push_str(&val.to_string());
                output.push_str("</code>");
            }
        };
    }

    let mut html = String::new();
    tag_to_html(value.to_owned(), true, &mut html);

    Ok(Value::String(html))
}

/// This filter translates `fm_*` header variable names into some human
/// language. Suppose we have:
/// ```rust, ignore
/// scheme.tmpl.variables.names_assertions = []
/// `[ "fm_lang", "Sprache", [], ],
/// ]
/// ```
/// Then, the expression `'fm_lang'|name` resolves into `Sprache`.
/// For variables not listed below, only the prefix `fm_` is stripped and
/// no translation occurs, e.g. `'fm_unknown'|name` becomes `unknown`.
/// The input type must be `Value::String` and the output type is
/// `Value::String`.
fn name_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("translate", "value", String, value);

    // This replaces the `fm`-name in the key by the localized name.
    let scheme = &LIB_CFG.read_recursive().scheme[SETTINGS.read_recursive().current_scheme];
    let output = name(scheme, &input);
    Ok(Value::String(output.to_string()))
}

/// Returns the localized header field name. For example: `fm_subtitle`
/// resolves into `Untertitel`. The configuration file variable
/// '`scheme.tmpl.variables.names_assertions`' contains the translation table.
pub(crate) fn name<'a>(scheme: &'a Scheme, input: &'a str) -> &'a str {
    let vars = &scheme.tmpl.fm_var.localization;
    vars.iter().find(|&l| l.0 == input).map_or_else(
        || input.strip_prefix(TMPL_VAR_FM_).unwrap_or(input),
        |l| &l.1,
    )
}

/// A filter that converts incoming HTML into some target markup language.
/// The parameter file `extension` indicates in what Markup
/// language the input is written. When no `extension` is given, the filler
/// does not convert, it just passes through.
/// This filter only converts, if the first line of the input stream starts with
/// the pattern `<html` or `<!DOCTYPE html`.
/// In any case, the output of the converter is trimmed at the end
/// (`trim_end()`).
fn html_to_markup_filter<S: BuildHasher>(
    value: &Value,
    #[allow(unused_variables)] args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    // Bring new methods into scope.
    use crate::html::HtmlStr;

    #[allow(unused_mut)]
    let mut buffer = try_get_value!("html_to_markup", "value", String, value);

    let default = if let Some(default_val) = args.get("default") {
        try_get_value!("markup_to_html", "default", String, default_val)
    } else {
        String::new()
    };

    let firstline = buffer
        .lines()
        .next()
        .map(|l| l.trim_start().to_ascii_lowercase());
    if firstline.is_some_and(|l| l.as_str().has_html_start_tag()) {
        let extension = if let Some(ext) = args.get("extension") {
            try_get_value!("markup_to_html", "extension", String, ext)
        } else {
            String::new()
        };

        let converter = InputConverter::build(&extension);
        buffer = match converter(buffer) {
            Ok(converted) if converted.is_empty() => default,
            Ok(converted) => converted,
            Err(e) => {
                log::info!("{}", e);
                default
            }
        };
    } else {
        buffer = default;
    }

    // Trim end without reallocation.
    buffer.truncate(buffer.trim_end().len());

    Ok(Value::String(buffer))
}

/// Takes the markup formatted input and renders it to HTML.
/// The parameter file `extension` indicates in what Markup
/// language the input is written.
/// When `extension` is not given or known, the renderer defaults to
/// `MarkupLanguage::Unknown`.
/// The input types must be `Value::String` and the output type is
/// `Value::String()`
fn markup_to_html_filter<S: BuildHasher>(
    value: &Value,
    args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("markup_to_html", "value", String, value);

    let markup_language = if let Some(ext) = args.get("extension") {
        let ext = try_get_value!("markup_to_html", "extension", String, ext);
        let ml = MarkupLanguage::from(ext.as_str());
        if ml.is_some() {
            ml
        } else {
            MarkupLanguage::Unkown
        }
    } else {
        MarkupLanguage::Unkown
    };

    // Render the markup language.
    let html_output = markup_language.render(&input);

    Ok(Value::String(html_output))
}

/// Adds a new filter to Tera templates:
/// `sanit` or `sanit()` sanitizes a string so that it can be used to
/// assemble filenames or paths. In addition, `sanit(alpha=true)` prepends
/// the `sort_tag.extra_separator` when the result starts with one of
/// `sort_tag.extra_chars`, usually a number. This way we guaranty that the filename
/// never starts with a number. We do not allow this, to be able to distinguish
/// reliably the sort tag from the filename. In addition to the above, the
/// filter checks if the string represents a "well-formed" filename. If it
/// is the case, and the filename starts with a dot, the file is prepended by
/// `sort_tag.extra_separator`.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn sanit_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("sanit", "value", String, value);

    // Check if this is a usual dotfile filename.
    let is_dotfile = input.starts_with(FILENAME_DOTFILE_MARKER)
        && PathBuf::from(&*input).has_wellformed_filename();

    // Sanitize string.
    let mut res = sanitize(&input);

    // If `FILNAME_DOTFILE_MARKER` was stripped, prepend one.
    if is_dotfile && !res.starts_with(FILENAME_DOTFILE_MARKER) {
        res.insert(0, FILENAME_DOTFILE_MARKER);
    }

    Ok(Value::String(res))
}

/// A Tera filter that searches for the first Markdown or ReStructuredText link
/// in the input stream and returns the link's name (link text).
/// If not found, it returns the empty string.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn link_text_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("link_text", "value", String, value);

    let hyperlink = FirstHyperlink::from(&input).unwrap_or_default();

    Ok(Value::String(hyperlink.text.to_string()))
}

/// A Tera filter that searches for the first Markdown or ReStructuredText link
/// in the input stream and returns the link's URL.
/// If not found, it returns the empty string.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn link_dest_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let p = try_get_value!("link_dest", "value", String, value);

    let hyperlink = FirstHyperlink::from(&p).unwrap_or_default();

    Ok(Value::String(hyperlink.dest.to_string()))
}

/// A Tera filter that searches for the first Markdown or ReStructuredText link
/// in the input stream and returns the link's text's name (link text).
/// Unlike the filter `link_dest`, it does not necessarily return the first
/// finding. For example, it skips autolinks, local links and links
/// with some URL in the link text.
/// If not found, it returns the empty string.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn link_text_picky_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let p = try_get_value!("link_text_picky", "value", String, value);

    let hyperlink = FirstHyperlink::from_picky(&p).unwrap_or_default();

    Ok(Value::String(hyperlink.text.to_string()))
}

/// A Tera filter that searches for the first Markdown or ReStructuredText link
/// in the input stream and returns the link's title.
/// If not found, it returns the empty string.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn link_title_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let p = try_get_value!("link_title", "value", String, value);

    let hyperlink = FirstHyperlink::from(&p).unwrap_or_default();

    Ok(Value::String(hyperlink.title.to_string()))
}

/// A Tera filter that searches for the first HTML heading
/// in the HTML input stream and returns the heading text.
/// If not found, it returns the empty string.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn html_heading_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let p = try_get_value!("html_heading", "value", String, value);

    let html_heading = FirstHtmlHeading::from(&p).unwrap_or_default();

    Ok(Value::String(html_heading.0.to_string()))
}

/// A Tera filter that truncates the input stream and returns the
/// max `TRUNC_LEN_MAX` bytes of valid UTF-8.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn trunc_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("trunc", "value", String, value);

    let mut short = "";
    for i in (0..TRUNC_LEN_MAX).rev() {
        if let Some(s) = input.get(..i) {
            short = s;
            break;
        }
    }
    Ok(Value::String(short.to_owned()))
}

/// A Tera filter that returns the first line or the first sentence of the input
/// stream.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn heading_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let p = try_get_value!("heading", "value", String, value);
    let p = p.trim_start();

    // Find the first heading, can finish with `. `, `.\n` or `.\r\n` on Windows.
    let mut index = p.len();

    if let Some(i) = p.find(". ") {
        if i < index {
            index = i;
        }
    }
    if let Some(i) = p.find(".\n") {
        if i < index {
            index = i;
        }
    }
    if let Some(i) = p.find(".\r\n") {
        if i < index {
            index = i;
        }
    }
    if let Some(i) = p.find('!') {
        if i < index {
            index = i;
        }
    }
    if let Some(i) = p.find('?') {
        if i < index {
            index = i;
        }
    }
    if let Some(i) = p.find("\n\n") {
        if i < index {
            index = i;
        }
    }
    if let Some(i) = p.find("\r\n\r\n") {
        if i < index {
            index = i;
        }
    }
    let content_heading = p[0..index].to_string();

    Ok(Value::String(content_heading))
}

/// A Tera filter that takes a path and extracts the tag of the filename.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn file_sort_tag_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let p = try_get_value!("file_sort_tag", "value", String, value);
    let p = PathBuf::from(p);
    let (tag, _, _, _, _) = p.disassemble();

    Ok(Value::String(tag.to_owned()))
}

/// A Tera filter that takes a path and extracts its last element.
/// This function trims the `sort_tag` if present.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn trim_file_sort_tag_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("trim_file_sort_tag", "value", String, value);
    let input = PathBuf::from(input);
    let (_, fname, _, _, _) = input.disassemble();

    Ok(Value::String(fname.to_owned()))
}

/// A Tera filter that takes a path and extracts its file stem,
/// in other words: the filename without `sort_tag`, `file_copy_counter`
/// and `extension`.
/// The input type must be `Value::String` and the output type is
/// `Value::String()`
fn file_stem_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("file_stem", "value", String, value);
    let input = PathBuf::from(input);
    let (_, _, stem, _, _) = input.disassemble();

    Ok(Value::String(stem.to_owned()))
}

/// A Tera filter that takes a path and extracts its copy counter,
/// or, to put it another way: the filename without `sort_tag`, `file_stem`
/// and `file_ext` (and their separators). If the filename contains a
/// `copy_counter=n`, the returned JSON value variant is `Value::Number(n)`.
/// If there is no copy counter in the input, the output is `Value::Number(0)`.
/// The input type must be `Value::String` and the output type is
/// `Value::Number()`
fn file_copy_counter_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("file_copy_counter", "value", String, value);
    let input = PathBuf::from(input);
    let (_, _, _, copy_counter, _) = input.disassemble();
    let copy_counter = copy_counter.unwrap_or(0);

    Ok(Value::from(copy_counter))
}

/// A Tera filter that takes a path and extracts its filename without
/// file extension. The filename may contain a sort-tag, a copy-counter and
/// separators. The input type must be `Value::String` and the output type is
/// `Value::String()`
fn file_name_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let p = try_get_value!("file_name", "value", String, value);

    let filename = Path::new(&p)
        .file_name()
        .unwrap_or_default()
        .to_str()
        .unwrap_or_default()
        .to_owned();

    Ok(Value::String(filename))
}

/// A Tera filter that replace the input string with the parameter `with`, but
/// only if the input stream is empty, e.g.:
///
/// * `Value::Null` or
/// * `Value::String("")`, or
/// * `Value::Array([])`, or
/// * the array contains only empty strings.
///
/// The parameter `with` can be any `Value` type.
fn replace_empty_filter<S: BuildHasher>(
    value: &Value,
    args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    // Detect the empty case. Exit early.
    match value {
        Value::Null => {}
        Value::String(s) if s.is_empty() => {}
        Value::Array(values) if values.is_empty() => {}
        Value::Array(values) => {
            if !values
                .iter()
                .map(|v| v.as_str())
                .all(|s| s.is_some_and(|s| s.is_empty()))
            {
                return Ok(value.to_owned());
            }
        }
        _ => return Ok(value.to_owned()),
    }

    if let Some(with) = args.get("with") {
        Ok(with.to_owned())
    } else {
        Ok(value.to_owned())
    }
}

/// A Tera filter that prepends the string parameter `with`, but only if the
/// input stream is not empty.
/// In addition, the flag `newline` inserts a newline character at end of the
/// result. In case the input stream is empty nothing is appended.
/// When called with the strings parameter `with_sort_tag`, the filter
/// prepends the sort-tag and all necessary sort-tag separator characters,
/// regardless whether the input stream in empty or not.
/// The input type, and the type of the parameter `with` and `with_sort_tag`
/// must be `Value::String`. The parameter `newline` must be a `Value::Bool` and
/// the output type is `Value::String()`.
fn prepend_filter<S: BuildHasher>(
    value: &Value,
    args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("prepend", "value", String, value);

    let mut res = input;

    if let Some(with) = args.get("with") {
        let with = try_get_value!("prepend", "with", String, with);
        let mut s = String::new();
        if !res.is_empty() {
            s.push_str(&with);
            s.push_str(&res);
            res = s;
        };
    } else if let Some(sort_tag) = args.get("with_sort_tag") {
        let sort_tag = try_get_value!("prepend", "with_sort_tag", String, sort_tag);
        res = PathBuf::from_disassembled(&sort_tag, &res, None, "")
            .to_str()
            .unwrap_or_default()
            .to_string();
    };

    if let Some(Value::Bool(newline)) = args.get("newline") {
        if *newline && !res.is_empty() {
            let mut s = String::new();
            s.push('\n');
            s.push_str(&res);
            res = s;
        }
    };

    Ok(Value::String(res))
}

/// A Tera filter that appends the string parameter `with`. In addition, the
/// flag `newline` inserts a newline character at end of the result. In
/// case the input stream is empty, nothing is appended.
/// The input type, and the type of the parameter `with` must be
/// `Value::String`. The parameter `newline` must be a `Value::Bool` and the
/// output type is `Value::String()`.
fn append_filter<S: BuildHasher>(
    value: &Value,
    args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("append", "value", String, value);

    if input.is_empty() {
        return Ok(Value::String("".to_string()));
    }

    let mut res = input.clone();
    if let Some(with) = args.get("with") {
        let with = try_get_value!("append", "with", String, with);
        res.push_str(&with);
    };

    if let Some(newline) = args.get("newline") {
        let newline = try_get_value!("newline", "newline", bool, newline);
        if newline && !res.is_empty() {
            res.push('\n');
        }
    };

    Ok(Value::String(res))
}

/// A Tera filter that takes a path and extracts its file extension.
/// The input type must be `Value::String()`, the output type is
/// `Value::String()`.
fn file_ext_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let p = try_get_value!("file_ext", "value", String, value);

    let ext = Path::new(&p)
        .extension()
        .unwrap_or_default()
        .to_str()
        .unwrap_or_default()
        .to_owned();

    Ok(Value::String(ext))
}

/// A Tera filter that takes a directory path and returns the alphabetically
/// last sort-tag of all Tp-Note documents in that directory.
/// The filter returns the empty string if none was found.
/// The input type must be `Value::String()`, the output type is
/// `Value::String()`.
fn find_last_created_file<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let p_str = try_get_value!("dir_last_created", "value", String, value);

    let p = Path::new(&p_str);
    let last = match p.find_last_created_file() {
        Some(filename) => Path::join(p, Path::new(&filename))
            .to_str()
            .unwrap()
            .to_string(),
        None => String::new(),
    };

    Ok(Value::String(last.to_string()))
}

/// Expects a path a filename in its input and returns an incremented sequential
/// sort-tag.
/// First, from the input's filename the sort-tag is extracted. Then, it
/// matches all digits from the end of the sort- tag, increments them
/// and replaces the matched digits with the result. If no numeric digits can be
/// matched, consider alphabetic letters as base 26 number system and try again.
/// Returns the default value if no match succeeds.
/// Note, that only sequential sort-tags are incremented, for others or, if the
/// input is empty, `default` is returned.
/// The path in the input allows to check if the resulting sort-tag exists
/// on disk already. If this is the case, a subcounter is appended to the
/// resulting sort-tag.
/// All input types are `Value::String`. The output type is `Value::String()`.
fn incr_sort_tag_filter<S: BuildHasher>(
    value: &Value,
    args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("incr_sort_tag", "value", String, value);

    let mut default = String::new();
    if let Some(d) = args.get("default") {
        default = try_get_value!("incr_sort_tag", "default", String, d);
    };

    let (input_dir, filename) = input.rsplit_once(['/', '\\']).unwrap_or(("", &input));
    let (input_sort_tag, _, is_sequential) = filename.split_sort_tag(false);

    if input_sort_tag.is_empty() || !is_sequential {
        return Ok(Value::String(default));
    }

    // Start analyzing the input.
    let (prefix, digits) = match input_sort_tag.rfind(|c: char| !c.is_ascii_digit()) {
        Some(idx) => (&input_sort_tag[..idx + 1], &input_sort_tag[idx + 1..]),
        None => ("", input_sort_tag),
    };

    // Search for digits
    let mut output_sort_tag = if !digits.is_empty() {
        // Return early if this number is too big.
        const DIGITS_MAX: usize = u32::MAX.ilog10() as usize; // 9
        if digits.len() > DIGITS_MAX {
            return Ok(Value::String(default));
        }

        // Convert string to n base 10.
        let mut n = match digits.parse::<u32>() {
            Ok(n) => n,
            _ => return Ok(Value::String(default)),
        };

        n += 1;

        let mut res = n.to_string();
        if res.len() < digits.len() {
            let padding = "0".repeat(digits.len() - res.len());
            res = format!("{}{}", padding, res);
        }

        // Assemble sort-tag.
        prefix.to_string() + &res
    } else {
        //
        // Search for letters as digits
        let (prefix, letters) = match input_sort_tag.rfind(|c: char| !c.is_ascii_lowercase()) {
            Some(idx) => (&input_sort_tag[..idx + 1], &input_sort_tag[idx + 1..]),
            None => ("", input_sort_tag),
        };

        if !letters.is_empty() {
            const LETTERS_BASE: u32 = 26;
            const LETTERS_MAX: usize = (u32::MAX.ilog2() / (LETTERS_BASE.ilog2() + 1)) as usize; // 6=31/(4+1)

            // Return early if this number is too big.
            if letters.len() > LETTERS_MAX {
                return Ok(Value::String(default));
            }

            // Interpret letters as base LETTERS_BASE and convert to int.
            let mut n = letters.chars().fold(0, |acc, c| {
                LETTERS_BASE * acc + (c as u8).saturating_sub(b'a') as u32
            });

            n += 1;

            // Convert back to letters base LETTERS_BASE.
            let mut res = String::new();
            while n > 0 {
                let c = char::from_u32('a' as u32 + n.rem_euclid(LETTERS_BASE)).unwrap_or_default();
                n = n.div_euclid(LETTERS_BASE);
                res = format!("{}{}", c, res);
            }
            if res.len() < letters.len() {
                let padding = "a".repeat(letters.len() - res.len());
                res = format!("{}{}", padding, res);
            }

            // Assemble sort-tag.
            prefix.to_string() + &res
        } else {
            default
        }
    };

    // Check for a free slot, branch if not free.
    let input_dir = Path::new(input_dir);
    if input_dir.has_file_with_sort_tag(&output_sort_tag).is_some() {
        output_sort_tag = input_sort_tag.to_string();
    }
    while input_dir.has_file_with_sort_tag(&output_sort_tag).is_some() {
        if output_sort_tag
            .chars()
            .last()
            .is_some_and(|c| c.is_ascii_digit())
        {
            output_sort_tag.push('a')
        } else {
            output_sort_tag.push('1')
        }
    }

    Ok(Value::String(output_sort_tag))
}

/// A Tera filter that takes a map of variables/values and removes a key/value
/// pair with the parameter `remove(key="<var-name>").
/// The input type must be `Value::Object()`, the parameter must be
/// `Value::String()` and the output type is `Value::Object()`.
fn remove_filter<S: BuildHasher>(
    value: &Value,
    args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let mut map = try_get_value!("remove", "value", tera::Map<String, tera::Value>, value);

    if let Some(outkey) = args.get("key") {
        let outkey = try_get_value!("remove", "key", String, outkey);
        let _ = map.remove(&outkey);
    };

    Ok(Value::Object(map))
}

/// A Tera filter that takes a map of key/values and inserts a key/value pair
/// with the parameters `insert(key="<var-name>", value=<var-value>). If the
/// variable exists in the map already, its value is replaced.
/// The input type must be `Value::Object()`, the `key` parameter must be a
/// `Value::String()` and the output type is `Value::Object()`.
fn insert_filter<S: BuildHasher>(
    value: &Value,
    args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let mut map = try_get_value!("insert", "value", tera::Map<String, tera::Value>, value);

    if let Some(inkey) = args.get("key") {
        let inkey = try_get_value!("insert", "key", String, inkey);
        let scheme = &LIB_CFG.read_recursive().scheme[SETTINGS.read_recursive().current_scheme];
        let inkey = name(scheme, &inkey);
        let inval = args
            .get("value")
            .map(|v| v.to_owned())
            .unwrap_or(tera::Value::Null);
        map.insert(inkey.to_string(), inval);
    };

    Ok(Value::Object(map))
}

/// A Tera filter telling in which natural language(s) the input text is
/// written. It returns an array of ISO 639-1 code representations listing the
/// detected languages. The input type must be a `Value::String`. The output
/// type is `Value::Array(<Vec<Value::String>>)`. If no language can be
/// reliably identified, the output is the empty array `Value::Array(vec![])`.
#[cfg(feature = "lang-detection")]
fn get_lang_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("get_lang", "value", String, value);

    let l = get_lang(&input).map_err(|e| tera::Error::from(e.to_string()))?;
    Ok(l.into())
}

#[cfg(not(feature = "lang-detection"))]
fn get_lang_filter<S: BuildHasher>(
    _value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    Ok(Value::String("".to_owned()))
}

/// A mapper that is usually used to convert ISO 639 codes to IETF language tags
/// by appending some region information, e.g.
/// `en` to `en-US` or `de` to `de-DE`. Configure the mapping with
/// `tmpl.filter.map_lang`:
///
/// `Fn: Array(<Vec<String>>) -> Value::Array(<Vec<String>>)`
///
/// The input and output type is `Value::Array(<Vec<String>>)`.
/// If the input `<String>` is a key in `tmpl.filter.map_lang`, it is replaced
/// with the corresponding value. If the input does not correspond to a key in
/// `tmpl.filter.map_lang`, it is passed through as such.
/// In case the optional parameter `default` (type `Value::String`) is given,
/// e.g. `map_lang(default="abc")`, then an empty input array is mapped to
/// `Value::Array(Vec::from("abc"))`.
fn map_lang_filter<S: BuildHasher>(
    value: &Value,
    args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let input = try_get_value!("map_lang", "value", Value, value);

    // Type check.
    if !input
        .as_array()
        .is_some_and(|a| a.iter().all(|s| s.is_string()))
    {
        return Err("input must be an array of strings".into());
    }

    // In `input` is empty return default.
    if input
        .as_array()
        .is_some_and(|a| a.is_empty() || a.iter().all(|v| v.as_str().is_some_and(|s| s.is_empty())))
    {
        return Ok(args
            .get("default")
            .map(|v| Value::Array(Vec::from([v.to_owned()])))
            .unwrap_or(input));
    }

    // Set up converter.
    let settings = SETTINGS.read_recursive();
    let convert = |v: Value| {
        if let (Value::String(s), Some(btm)) = (&v, &settings.map_lang_filter_btmap) {
            btm.get(s)
                .map(|new_v| Value::String(new_v.to_owned()))
                .unwrap_or(v)
        } else {
            v
        }
    };
    // Do conversion.
    let res = match input {
        Value::Array(a) => a.into_iter().map(convert).collect(),
        _ => input,
    };

    Ok(res)
}

/// The input must be of type `Value::Array(<Vec<a>>)`. If the array has
/// exactly one element, then the array is flattened to `<a>` otherwise the
/// input is passed through.
fn flatten_array_filter<S: BuildHasher>(
    value: &Value,
    _args: &HashMap<String, Value, S>,
) -> TeraResult<Value> {
    let val = try_get_value!("flatten_array", "value", Value, value);

    // Type check.
    if !value.is_array() {
        return Err("input must be of type array".into());
    }

    // In `input` is empty return default.
    match val {
        Value::Array(v) if v.len() == 1 => Ok(v[0].clone()),
        _ => Ok(val),
    }
}

#[derive(Debug, Eq, PartialEq, Default)]
/// Represents the first heading in an HTML document.
struct FirstHtmlHeading<'a>(Cow<'a, str>);

impl<'a> FirstHtmlHeading<'a> {
    /// Parse the HTML input `i` and return the first HTML heading found.
    fn from(html: &'a str) -> Option<Self> {
        /// A pattern to search for HTML heading tags.
        const HTML_HEADING_OPENING_TAG: &[&str; 6] = &["<h1", "<h2", "<h3", "<h4", "<h5", "<h6"];

        /// A pattern to search for HTML heading tags.
        const HTML_HEADING_CLOSING_TAG: &[&str; 6] =
            &["</h1>", "</h2>", "</h3>", "</h4>", "</h5>", "</h6>"];

        let mut i = 0;
        let mut heading_start = None;
        let mut heading_end = None;

        // Find opening tag.
        while let Some(mut tag_start) = html[i..].find('<') {
            if let Some(mut tag_end) = html[i + tag_start..].find('>') {
                tag_end += 1;
                // Move on if there is another opening bracket.
                if let Some(new_start) = html[i + tag_start + 1..i + tag_start + tag_end].rfind('<')
                {
                    tag_start += new_start + 1;
                    tag_end -= new_start + 1;
                }

                // Is this a tag listed in `HTML_HEADING_OPENING_TAGS`?
                heading_start = HTML_HEADING_OPENING_TAG
                    .iter()
                    .any(|&pat| html[i + tag_start..i + tag_start + tag_end].starts_with(pat))
                    // Store the index after the opening tag.
                    .then_some(i + tag_start + tag_end);

                if heading_start.is_some() {
                    break;
                } else {
                    i += tag_start + tag_end;
                }
            } else {
                break;
            }
        }

        // Search for the closing tag.

        // Find closing tag.
        if let Some(mut i) = heading_start {
            while let Some(mut tag_start) = html[i..].find('<') {
                if let Some(mut tag_end) = html[i + tag_start..].find('>') {
                    tag_end += 1;
                    // Move on if there is another opening bracket.
                    if let Some(new_start) =
                        html[i + tag_start + 1..i + tag_start + tag_end].rfind('<')
                    {
                        tag_start += new_start + 1;
                        tag_end -= new_start + 1;
                    }

                    // Is this a tag listed in `HTML_HEADING_OPENING_TAGS`?
                    heading_end = HTML_HEADING_CLOSING_TAG
                        .iter()
                        .any(|&pat| html[i + tag_start..i + tag_start + tag_end].starts_with(pat))
                        // Store the index before the closing tag.
                        .then_some(i + tag_start);

                    if heading_end.is_some() {
                        break;
                    } else {
                        i += tag_start + tag_end;
                    }
                } else {
                    break;
                }
            }
        }

        // Get Heading slice.
        let mut heading = "";
        if let (Some(heading_start), Some(heading_end)) = (heading_start, heading_end) {
            heading = &html[heading_start..heading_end];
        }
        if heading.is_empty() {
            return None;
        }

        // Remove HTML tags inside heading.
        let mut cleaned_heading = String::new();
        let mut inside_tag = false;
        for c in heading.chars() {
            if c == '<' {
                inside_tag = true;
            } else if c == '>' {
                inside_tag = false;
            } else if !inside_tag {
                cleaned_heading.push(c);
            }
        }
        if cleaned_heading.is_empty() {
            return None;
        }

        // Decode HTML entities.
        let output: Cow<str> = if cleaned_heading == heading {
            html_escape::decode_html_entities(heading)
        } else {
            Cow::Owned(html_escape::decode_html_entities(&cleaned_heading).into_owned())
        };

        // Pack the output into newtype.
        if output.is_empty() {
            None
        } else {
            Some(FirstHtmlHeading(output))
        }
    }
}

#[derive(Debug, Eq, PartialEq, Default)]
/// Represents a hyperlink.
struct FirstHyperlink<'a> {
    text: Cow<'a, str>,
    dest: Cow<'a, str>,
    title: Cow<'a, str>,
}

impl<'a> FirstHyperlink<'a> {
    /// Parse the first markup formatted hyperlink and stores the result in `Self`.
    fn from(i: &'a str) -> Option<Self> {
        let mut hlinks = MarkupLink::new(i, false);
        hlinks
            .find_map(|l| match l.1 {
                Link::Text2Dest(te, de, ti) => Some((te, de, ti)),
                _ => None,
            })
            .map(|(text, dest, title)| FirstHyperlink { text, dest, title })
    }

    /// Parse the first markup formatted hyperlink and stores the result in `Self`.
    /// If this first link is an autolink, return `None`.
    fn from_picky(i: &'a str) -> Option<Self> {
        let mut hlinks = MarkupLink::new(i, false);

        hlinks.find_map(|l| {
            match l.1 {
                // Is this an autolink? Skip.
                // Email autolink? Skip
                Link::Text2Dest(text, dest, _) if text == dest => None,
                Link::Text2Dest(_, dest, _) if dest.to_lowercase().starts_with("mailto:") => None,
                Link::Text2Dest(text, _, _) if text.to_lowercase().starts_with("https:") => None,
                Link::Text2Dest(text, _, _) if text.to_lowercase().starts_with("http:") => None,
                Link::Text2Dest(text, _, _) if text.to_lowercase().starts_with("tpnote:") => None,
                Link::Text2Dest(text, dest, title) => Some(FirstHyperlink { text, dest, title }),
                _ => None,
            }
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use parking_lot::RwLockWriteGuard;
    use serde_json::json;
    use std::collections::{BTreeMap, HashMap};
    use tera::to_value;

    #[test]
    fn test_to_yaml_filter() {
        // No key, the input is of type `Value::Object()`.
        let mut input = tera::Map::new();
        input.insert("number_type".to_string(), json!(123));

        let expected = "number_type:  123".to_string();

        let args = HashMap::new();
        assert_eq!(
            to_yaml_filter(&Value::Object(input), &args).unwrap(),
            Value::String(expected)
        );

        //
        // The key is `author`, the value is of type `Value::String()`.
        let input = "Getreu".to_string();

        let expected = "author:       Getreu".to_string();

        let mut args = HashMap::new();
        args.insert("key".to_string(), to_value("author").unwrap());
        assert_eq!(
            to_yaml_filter(&Value::String(input), &args).unwrap(),
            Value::String(expected)
        );

        //
        // The key is `my`, the value is of type `Value::Object()`.
        let mut input = tera::Map::new();
        input.insert(
            "author".to_string(),
            json!(["Getreu: Noname", "Jens: Noname"]),
        );

        let expected = "my:\n  author:\n  - 'Getreu: Noname'\n  - 'Jens: Noname'".to_string();

        let mut args = HashMap::new();
        args.insert("key".to_string(), to_value("my").unwrap());
        assert_eq!(
            to_yaml_filter(&Value::Object(input), &args).unwrap(),
            Value::String(expected)
        );

        //
        // The key is `my`, the value is of type `Value::Object()`.
        let mut input = tera::Map::new();
        input.insert("number_type".to_string(), json!(123));

        let expected = "my:\n  number_type: 123".to_string();

        let mut args = HashMap::new();
        args.insert("key".to_string(), to_value("my").unwrap());
        assert_eq!(
            to_yaml_filter(&Value::Object(input), &args).unwrap(),
            Value::String(expected)
        );

        //
        // The key is `my`, `tab` is 10, the value is of type `Value::Object()`.
        let mut input = tera::Map::new();
        input.insert("num".to_string(), json!(123));

        let expected = "my:\n  num:    123".to_string();

        let mut args = HashMap::new();
        args.insert("key".to_string(), to_value("my").unwrap());
        args.insert("tab".to_string(), to_value(10).unwrap());
        assert_eq!(
            to_yaml_filter(&Value::Object(input), &args).unwrap(),
            Value::String(expected)
        );

        //
        // Empty input.
        let input = tera::Map::new();

        let expected = "".to_string();

        let mut args = HashMap::new();
        args.insert("tab".to_string(), to_value(10).unwrap());
        assert_eq!(
            to_yaml_filter(&Value::Object(input), &args).unwrap(),
            Value::String(expected)
        );

        //
        // Empty input with key.
        let input = tera::Map::new();

        let expected = "my:       {}".to_string();

        let mut args = HashMap::new();
        args.insert("key".to_string(), to_value("my").unwrap());
        args.insert("tab".to_string(), to_value(10).unwrap());
        assert_eq!(
            to_yaml_filter(&Value::Object(input), &args).unwrap(),
            Value::String(expected)
        );

        //
        // Simple input string, no map.
        let input = json!("my str");
        let expected = "my str".to_string();
        let mut args = HashMap::new();
        args.insert("tab".to_string(), to_value(10).unwrap());
        assert_eq!(
            to_yaml_filter(&input, &args).unwrap(),
            Value::String(expected)
        );

        //
        // Simple input string, no map.
        let input = json!("my: str");
        let expected = "'my: str'".to_string();
        let mut args = HashMap::new();
        args.insert("tab".to_string(), to_value(10).unwrap());
        assert_eq!(
            to_yaml_filter(&input, &args).unwrap(),
            Value::String(expected)
        );

        //
        // Array.
        let input = json!(["Ford", "BMW", "Fiat"]);
        let expected = "    - Ford\n    - BMW\n    - Fiat".to_string();
        let mut args = HashMap::new();
        args.insert("tab".to_string(), to_value(4).unwrap());
        assert_eq!(
            to_yaml_filter(&input, &args).unwrap(),
            Value::String(expected)
        );

        //
        // Simple input number, no map.
        let input = json!(9876);
        let expected = "9876".to_string();
        let mut args = HashMap::new();
        args.insert("tab".to_string(), to_value(10).unwrap());
        assert_eq!(
            to_yaml_filter(&input, &args).unwrap(),
            Value::String(expected)
        );
    }

    #[test]
    fn test_to_html_filter() {
        //
        let input = json!(["Hello", "World", 123]);
        let expected = "<ul class=\"fm\"><li class=\"fm\">Hello</li>\
            <li class=\"fm\">World</li><li class=\"fm\">\
            <code class=\"fm\">123</code></li></ul>"
            .to_string();

        let args = HashMap::new();
        assert_eq!(
            to_html_filter(&input, &args).unwrap(),
            Value::String(expected)
        );

        //
        let input = json!({
            "title": "tmp: test",
            "subtitle": "Note",
            "author": [
                "Getreu: Noname",
                "Jens: Noname"
            ],
            "date": "2023-09-12T00:00:00.000Z",
            "my": {
                "num_type": 123,
                "str_type": {
                    "sub1": "foo",
                    "sub2": "bar"
                },
                "weiter": 3454
            },
            "other": "my \"new\" text",
            "filename_sync": false,
            "lang": "et-ET"
        });
        let expected = "<blockquote class=\"fm\">\
            <div class=\"fm\">author: <ul class=\"fm\">\
            <li class=\"fm\">Getreu: Noname</li>\
            <li class=\"fm\">Jens: Noname</li></ul></div>\
            <div class=\"fm\">date: 2023-09-12T00:00:00.000Z</div>\
            <div class=\"fm\">filename_sync: <code class=\"fm\">false</code></div>\
            <div class=\"fm\">lang: et-ET</div>\
            <div class=\"fm\">my: \
              <blockquote class=\"fm\">\
              <div class=\"fm\">num_type: <code class=\"fm\">123</code></div>\
              <div class=\"fm\">str_type: \
                <blockquote class=\"fm\"><div class=\"fm\">sub1: foo</div>\
                <div class=\"fm\">sub2: bar</div></blockquote></div>\
                <div class=\"fm\">weiter: <code class=\"fm\">3454</code></div>\
                </blockquote></div>\
            <div class=\"fm\">other: my \"new\" text</div>\
            <div class=\"fm\">subtitle: Note</div>\
            <div class=\"fm\">title: tmp: test</div>\
            </blockquote>"
            .to_string();

        let args = HashMap::new();
        assert_eq!(
            to_html_filter(&input, &args).unwrap(),
            Value::String(expected)
        );
    }

    #[test]
    fn test_name_filter() {
        //
        let result = name_filter(&to_value("fm_title").unwrap(), &HashMap::new());
        assert_eq!(result.unwrap(), to_value("title").unwrap());

        //
        let result = name_filter(&to_value("fm_unknown").unwrap(), &HashMap::new());
        assert_eq!(result.unwrap(), to_value("unknown").unwrap());
    }

    #[test]
    fn test_markup_to_html_filter() {
        //
        // Render verbatim text with the `parse-hyperlinks` crate to HTML.
        let input = json!("Hello World\n[link](<https://getreu.net>)");
        let expected = "<pre>Hello World\n\
            <a href=\"https://getreu.net\" title=\"\">\
            [link](&lt;https://getreu.net&gt;)</a></pre>"
            .to_string();

        let args = HashMap::new();
        assert_eq!(
            markup_to_html_filter(&input, &args).unwrap(),
            Value::String(expected)
        );

        // Render verbatim text with the `parse-hyperlinks` crate to HTML.
        let input = json!("Hello World\n[link](<https://getreu.net>)");
        let expected = "<pre>Hello World\n\
            <a href=\"https://getreu.net\" title=\"\">link</a></pre>"
            .to_string();
        let mut args = HashMap::new();
        // Select the "md" renderer.
        args.insert("extension".to_string(), to_value("txtnote").unwrap());

        assert_eq!(
            markup_to_html_filter(&input, &args).unwrap(),
            Value::String(expected)
        );

        //
        // Render Markdown to HTML.
        let input = json!("# Title\nHello World");
        let mut args = HashMap::new();
        // Select the "md" renderer.
        args.insert("extension".to_string(), to_value("md").unwrap());

        #[cfg(feature = "renderer")]
        let expected = "<h1>Title</h1>\n<p>Hello World</p>\n".to_string();
        #[cfg(not(feature = "renderer"))]
        let expected = "".to_string();

        assert_eq!(
            markup_to_html_filter(&input, &args).unwrap(),
            Value::String(expected)
        );
    }

    #[test]
    fn test_incr_sort_tag_filter() {
        let result = incr_sort_tag_filter(&to_value("dir/19-Note.md").unwrap(), &HashMap::new());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("20").unwrap());

        let result = incr_sort_tag_filter(&to_value("Note.md").unwrap(), &HashMap::new());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("").unwrap());

        let result = incr_sort_tag_filter(&to_value("29-Note.md").unwrap(), &HashMap::new());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("30").unwrap());

        let result = incr_sort_tag_filter(&to_value("02-Note.md").unwrap(), &HashMap::new());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("03").unwrap());

        let result = incr_sort_tag_filter(&to_value("cz-Note.md").unwrap(), &HashMap::new());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("da").unwrap());

        let result = incr_sort_tag_filter(&to_value("2cz-Note.md").unwrap(), &HashMap::new());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("2da").unwrap());

        // Too many letters, default string is ``.
        let result = incr_sort_tag_filter(&to_value("2acz-Note.md").unwrap(), &HashMap::new());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("").unwrap());

        // No input.
        let mut args = HashMap::new();
        args.insert("default".to_string(), to_value("my default.md").unwrap());
        let result = incr_sort_tag_filter(&to_value("-Note.md").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("my default.md").unwrap());

        // Too big.
        let mut args = HashMap::new();
        args.insert("default".to_string(), to_value("my default.md").unwrap());
        let result = incr_sort_tag_filter(&to_value("10000000000-Note.md").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("my default.md").unwrap());

        // Too many digits.
        let mut args = HashMap::new();
        args.insert("default".to_string(), to_value("my default.md").unwrap());
        let result = incr_sort_tag_filter(&to_value("013-Note.md").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("014").unwrap());

        // Too big.
        let mut args = HashMap::new();
        args.insert("default".to_string(), to_value("my default.md").unwrap());
        let result = incr_sort_tag_filter(&to_value("aaafbaz-Note.md").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("my default.md").unwrap());

        // Too many digits.
        let mut args = HashMap::new();
        args.insert("default".to_string(), to_value("my default.md").unwrap());
        let result = incr_sort_tag_filter(&to_value("aaf-Note.md").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("my default.md").unwrap());

        let mut args = HashMap::new();
        args.insert("default".to_string(), to_value("my default.md").unwrap());
        let result = incr_sort_tag_filter(&to_value("23-01-23-Note.md").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("23-01-24").unwrap());
    }

    #[test]
    fn test_sanit_filter() {
        let result = sanit_filter(
            &to_value(".# Strange filename? Yes.").unwrap(),
            &HashMap::new(),
        );
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("Strange filename_ Yes").unwrap());

        let result = sanit_filter(&to_value("Correct filename.pdf").unwrap(), &HashMap::new());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("Correct filename.pdf").unwrap());

        let result = sanit_filter(&to_value(".dotfilename").unwrap(), &HashMap::new());
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value(".dotfilename").unwrap());
    }

    #[test]
    fn test_remove_filter() {
        //
        let input = json!({"title": "my title", "subtitle": "my subtitle"});
        let mut args = HashMap::new();
        args.insert("key".to_string(), to_value("title").unwrap());
        let expected = json!({"subtitle": "my subtitle"});
        let result = remove_filter(&input, &args);
        //eprintln!("{:?}", result);
        assert_eq!(result.unwrap(), expected);

        //
        let input = json!({"title": "my title", "subtitle": "my subtitle"});
        let mut args = HashMap::new();
        args.insert("key".to_string(), to_value("nono").unwrap());
        let expected = json!({"title": "my title", "subtitle": "my subtitle"});
        let result = remove_filter(&input, &args);
        //eprintln!("{:?}", result);
        assert_eq!(result.unwrap(), expected);
    }

    #[test]
    fn test_insert_filter() {
        //
        let input = json!({"subtitle": "my subtitle"});
        let mut args = HashMap::new();
        args.insert("key".to_string(), to_value("fm_new").unwrap());
        args.insert("value".to_string(), to_value("my new").unwrap());
        let expected = json!({"new": "my new", "subtitle": "my subtitle"});
        let result = insert_filter(&input, &args);
        //eprintln!("{:?}", result);
        assert_eq!(result.unwrap(), expected);

        //
        let input = json!({"title": "my title", "subtitle": "my subtitle"});
        let mut args = HashMap::new();
        args.insert("key".to_string(), to_value("fm_title").unwrap());
        args.insert("value".to_string(), to_value("my replaced title").unwrap());
        let expected = json!({"title": "my replaced title", "subtitle": "my subtitle"});
        let result = insert_filter(&input, &args);
        //eprintln!("{:?}", result);
        assert_eq!(result.unwrap(), expected);

        //
        let input = json!({"title": "my title"});
        let mut args = HashMap::new();
        args.insert("key".to_string(), to_value("fm_new").unwrap());
        let expected = json!({"new": null, "title": "my title"});
        let result = insert_filter(&input, &args);
        //eprintln!("{:?}", result);
        assert_eq!(result.unwrap(), expected);
    }

    #[test]
    fn test_replace_emtpy_filter() {
        // Do not replace.
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value("new string").unwrap());
        let result = replace_empty_filter(&to_value("non empty string").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("non empty string").unwrap());

        // Replace.
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value("new string").unwrap());
        let result = replace_empty_filter(&to_value("").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("new string").unwrap());

        // Array input, not empty.
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value([1, 2, 3]).unwrap());
        let input = to_value([3, 4, 5]).unwrap();
        let output = replace_empty_filter(&input, &args).unwrap();
        assert_eq!(output, input);

        // Array input, empty.
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value([1, 2, 3]).unwrap());
        let input = Value::Array(vec![]);
        let output = replace_empty_filter(&input, &args).unwrap();
        assert_eq!(output, to_value([1, 2, 3]).unwrap());

        // Array input, not empty.
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value([1, 2, 3]).unwrap());
        let input = to_value(["", "not empty", ""]).unwrap();
        let output = replace_empty_filter(&input, &args).unwrap();
        assert_eq!(output, input);

        // Array input, empty.
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value([1, 2, 3]).unwrap());
        let input = to_value(["", "", ""]).unwrap();
        let output = replace_empty_filter(&input, &args).unwrap();
        assert_eq!(output, to_value([1, 2, 3]).unwrap());

        // Null input, not empty.
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value([1, 2, 3]).unwrap());
        let input = Value::Null;
        let output = replace_empty_filter(&input, &args).unwrap();
        assert_eq!(output, to_value([1, 2, 3]).unwrap());
    }

    #[test]
    fn test_prepend_filter() {
        // `with`
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value("-").unwrap());
        let result = prepend_filter(&to_value("1. My first chapter").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("-1. My first chapter").unwrap());

        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value("_").unwrap());
        let result = prepend_filter(&to_value("").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("").unwrap());

        // `with_sort_tag`
        let mut args = HashMap::new();
        args.insert("with_sort_tag".to_string(), to_value("20230809").unwrap());
        let result = prepend_filter(&to_value("1. My first chapter").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            to_value("20230809-1. My first chapter").unwrap()
        );

        let mut args = HashMap::new();
        args.insert("with_sort_tag".to_string(), to_value("20230809").unwrap());
        let result = prepend_filter(&to_value("1-My first chapter").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(
            result.unwrap(),
            to_value("20230809-'1-My first chapter").unwrap()
        );

        let mut args = HashMap::new();
        args.insert("with_sort_tag".to_string(), to_value("").unwrap());
        let result = prepend_filter(&to_value("1. My first chapter").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("1. My first chapter").unwrap());

        let mut args = HashMap::new();
        args.insert("with_sort_tag".to_string(), to_value("").unwrap());
        let result = prepend_filter(&to_value("1-My first chapter").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("'1-My first chapter").unwrap());

        let mut args = HashMap::new();
        args.insert("with_sort_tag".to_string(), to_value("20230809").unwrap());
        let result = prepend_filter(&to_value("").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("20230809-'").unwrap());

        let mut args = HashMap::new();
        args.insert("with_sort_tag".to_string(), to_value("").unwrap());
        let result = prepend_filter(&to_value("").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("'").unwrap());

        // `with`
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value("-").unwrap());
        args.insert("newline".to_string(), to_value(true).unwrap());
        let result = prepend_filter(&to_value("1. My first chapter").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("\n-1. My first chapter").unwrap());
    }

    #[test]
    fn test_append_filter() {
        // `with`
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value("-").unwrap());
        let result = append_filter(&to_value("1. My first chapter").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("1. My first chapter-").unwrap());

        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value("_").unwrap());
        let result = append_filter(&to_value("").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("").unwrap());

        // `with_sort_tag`
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value("-").unwrap());
        args.insert("newline".to_string(), to_value(true).unwrap());
        let result = append_filter(&to_value("1. My first chapter").unwrap(), &args);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), to_value("1. My first chapter-\n").unwrap());
    }

    #[test]
    fn test_link_text_link_dest_link_title_filter() {
        let args = HashMap::new();
        // Test Markdown link in clipboard.
        let input = r#"xxx[Jens Getreu's blog](https://blog.getreu.net "My blog")"#;
        let output_ln = link_text_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("Jens Getreu's blog", output_ln);
        let output_lta = link_dest_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("https://blog.getreu.net", output_lta);
        let output_lti = link_title_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("My blog", output_lti);

        // Test non-link string in clipboard.
        let input = "Tp-Note helps you to quickly get\
            started writing notes.";
        let output_ln = link_text_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("", output_ln);
        let output_lta = link_dest_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("", output_lta);
        let output_lti = link_title_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("", output_lti);
    }

    #[test]
    fn test_link_text_filter() {
        let args = HashMap::new();
        // Test Markdown link in clipboard.
        let input = r#"Some autolink: <tpnote:locallink.md>,
more autolinks: <tpnote:20>, <getreu@web.de>,
boring link text: [http://domain.com](http://getreu.net)
[Jens Getreu's blog](https://blog.getreu.net "My blog")
Some more text."#;

        let output = link_text_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!(output, "tpnote:locallink.md");

        // Test picky version also.

        let output = link_text_picky_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!(output, "Jens Getreu's blog");

        //
        let input = "[into\\_bytes](https://doc.rust-lang.org)";

        let output = link_text_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!(output, "into_bytes");

        // Test picky version also.

        let output = link_text_picky_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!(output, "into_bytes");
    }

    #[test]
    fn test_trunc_filter() {
        let args = HashMap::new();
        // Test Markdown link in clipboard.
        let input = "Jens Getreu's blog";
        let output = trunc_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("Jens Getr", output);
    }

    #[test]
    fn test_first_html_heading() {
        // Test case: No heading in the HTML
        let html = "<p>No heading here</p>";
        assert_eq!(FirstHtmlHeading::from(html), None);

        // Test case: H1 heading
        let html = "<h1>Heading 1</h1>";
        assert_eq!(
            FirstHtmlHeading::from(html),
            Some(FirstHtmlHeading(Cow::Borrowed("Heading 1")))
        );

        // Test case: Nested tags within a heading
        let html = "<h2>Heading <span>with</span> nested tags</h2>";
        assert_eq!(
            FirstHtmlHeading::from(html),
            Some(FirstHtmlHeading(Cow::Borrowed("Heading with nested tags")))
        );

        // Test case: HTML entities within a heading
        let html = "<h3>Heading with &lt;html entities&gt;</h3>";
        assert_eq!(
            FirstHtmlHeading::from(html),
            Some(FirstHtmlHeading(Cow::Borrowed(
                "Heading with <html entities>"
            )))
        );

        // Test case: Multiple headings in the HTML
        let html = "<h4>First Heading</h4><h5>Second Heading</h5>";
        assert_eq!(
            FirstHtmlHeading::from(html),
            Some(FirstHtmlHeading(Cow::Borrowed("First Heading")))
        );

        // Test case: Heading without a closing tag
        let html = "<h1>Heading without closing tag";
        assert_eq!(FirstHtmlHeading::from(html), None);

        // Test case: Empty heading
        let html = "<h6></h6>";
        assert_eq!(FirstHtmlHeading::from(html), None);

        // Test case: Heading with attributes
        let html = "<h1 class=\"title\">Heading with attributes</h1>";
        assert_eq!(
            FirstHtmlHeading::from(html),
            Some(FirstHtmlHeading(Cow::Borrowed("Heading with attributes")))
        );
    }

    #[test]
    fn test_heading_filter() {
        let args = HashMap::new();

        //
        // Test find first sentence.
        let input = "N.ote.\nIt helps. Get quickly\
            started writing notes.";
        let output = heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("N.ote", output);

        //
        // Test find first sentence (Windows)
        let input = "N.ote.\r\nIt helps. Get quickly\
            started writing notes.";
        let output = heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("N.ote", output);

        //
        // Test find heading
        let input = "N.ote\n\nIt helps. Get quickly\
            started writing notes.";
        let output = heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("N.ote", output);

        //
        // Test find heading (Windows)
        let input = "N.ote\r\n\r\nIt helps. Get quickly\
            started writing notes.";
        let output = heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("N.ote", output);

        //
        // Test trim whitespace
        let input = "\r\n\r\n  \tIt helps. Get quickly\
            started writing notes.";
        let output = heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("It helps", output);
    }

    #[test]
    fn test_html_heading_filter() {
        let args = HashMap::new();

        //
        // Test find first heading.
        let input = "Some text.<h1>Heading 1</h1>Get quickly\
            started writing notes.";
        let output = html_heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("Heading 1", output);

        //
        let input = "Some text.<h1 style=\"font-size:60px;\">\
            Heading 1</h1>Get quickly\
            started writing notes.";
        let output = html_heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("Heading 1", output);

        //
        let input = "Some text.<h2>Heading &amp;1</h2>Get quickly\
            started writing notes.";
        let output = html_heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("Heading &1", output);

        //
        let input = "Some text.<p>No Heading 1</p>Get quickly\
            started writing notes.";
        let output = html_heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("", output);

        //
        let input = "Some text.<h1>No Heading 1</p>Get quickly\
            started writing notes.";
        let output = html_heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("", output);

        //
        let input = "Some text.<p>No Heading 1</h1>Get quickly\
            started writing notes.";
        let output = html_heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("", output);

        //
        let input = "Some text.<p>No <h1>Heading 1</h1>Get quickly\
            started writing notes.";
        let output = html_heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("Heading 1", output);

        //
        let input = "Some text.<p>No <h1>Heading<br> 1</h1>Get quickly\
            started writing notes.";
        let output = html_heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("Heading 1", output);

        //
        let input = "<p>No <h1>Heading 1</h1> <h1>Heading 2</h1> text";
        let output = html_heading_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        // This string is shortened.
        assert_eq!("Heading 1", output);
    }

    #[test]
    fn test_file_filter() {
        let args = HashMap::new();
        //
        //
        // Test file stem.
        let input =
            "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My file.md";
        let output = file_stem_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("My file", output);

        let input =
            "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My dir/";
        let output = file_stem_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("My dir", output);
        //
        //
        // Test file tag.
        let input =
            "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My file.md";
        let output = file_sort_tag_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("20200908", output);

        let input =
            "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My dir/";
        let output = file_sort_tag_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("20200908", output);
        //
        //
        // Test file extension.
        let input =
            "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My file.md";
        let output = file_ext_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("md", output);

        let input = "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My file.pfd.md";
        let output = file_ext_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("md", output);

        let input =
            "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My dir/";
        let output = file_ext_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("", output);
        //
        //
        // Test copy counter filter.
        let input = "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My file(123).md";
        let output = file_copy_counter_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!(123, output);

        let input =
            "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My dir/";
        let output = file_ext_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("", output);
        //
        //
        // Test filename.
        let input = "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My file(123).md";
        let output = file_name_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("20200908-My file(123).md", output);

        let input =
            "/usr/local/WEB-SERVER-CONTENT/blog.getreu.net/projects/tp-note/20200908-My dir/";
        let output = file_ext_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("", output);
        //
        //
        // Test `prepend_dot`.
        let mut args = HashMap::new();
        args.insert("with".to_string(), to_value(".").unwrap());
        let input = "md";
        let output = prepend_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!(".md", output);

        let input = "";
        let output = prepend_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("", output);
    }

    #[test]
    fn test_map_lang_filter() {
        //
        // `Test `map_lang_filter()`
        use crate::settings::Settings;

        let mut map_lang_filter_btmap = BTreeMap::new();
        map_lang_filter_btmap.insert("de".to_string(), "de-DE".to_string());
        let mut settings = SETTINGS.write();
        *settings = Settings::default();
        settings.map_lang_filter_btmap = Some(map_lang_filter_btmap);

        // This locks `SETTINGS` for further write access in this scope.
        let _settings = RwLockWriteGuard::<'_, _>::downgrade(settings);

        let args = HashMap::new();
        let input = ["de"];
        let output = map_lang_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!(tera::to_value(["de-DE"]).unwrap(), output);

        let args = HashMap::new();
        let input = ["de", "fr"];
        let output = map_lang_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!(tera::to_value(["de-DE", "fr"]).unwrap(), output);

        let mut args = HashMap::new();
        args.insert("default".to_string(), to_value("test").unwrap());
        let input = Value::Null;
        let output = map_lang_filter(&input, &args).unwrap_or_default();
        assert_eq!(Value::Null, output);

        let mut args = HashMap::new();
        args.insert("default".to_string(), to_value("test").unwrap());
        let input = [""];
        let output = map_lang_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!(tera::to_value(["test"]).unwrap(), output);

        let args = HashMap::new();
        let input = "this is not an arry";
        let output = map_lang_filter(&to_value(input).unwrap(), &args);
        assert!(output.is_err());

        let args = HashMap::new();
        let input = [3, 5, 8];
        let output = map_lang_filter(&to_value(input).unwrap(), &args);
        assert!(output.is_err());

        drop(_settings);
    }

    #[test]
    fn test_flatten_array_filter() {
        // This is passed through.
        let args = HashMap::new();
        let input = ["de-DE", "fr", "et-ET"];
        let output = flatten_array_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("de-DE", output[0]);
        assert_eq!("fr", output[1]);
        assert_eq!("et-ET", output[2]);

        // This input is rejected.
        let args = HashMap::new();
        let input = "de-DE";
        let output = flatten_array_filter(&to_value(input).unwrap(), &args);
        assert!(output.is_err());

        // This is flattened.
        let args = HashMap::new();
        let input = ["de-DE"];
        let output = flatten_array_filter(&to_value(input).unwrap(), &args).unwrap_or_default();
        assert_eq!("de-DE", output);
    }

    #[test]
    fn test_parse_hyperlink() {
        use super::FirstHyperlink;
        // Stand alone Markdown link.
        let input = r#"abc[Homepage](https://blog.getreu.net "My blog")abc"#;
        let expected_output = FirstHyperlink {
            text: "Homepage".into(),
            dest: "https://blog.getreu.net".into(),
            title: "My blog".into(),
        };
        let output = FirstHyperlink::from(input);
        assert_eq!(expected_output, output.unwrap());

        // Markdown link reference.
        let input = r#"abc[Homepage][home]abc
                      [home]: https://blog.getreu.net "My blog""#;
        let expected_output = FirstHyperlink {
            text: "Homepage".into(),
            dest: "https://blog.getreu.net".into(),
            title: "My blog".into(),
        };
        let output = FirstHyperlink::from(input);
        assert_eq!(expected_output, output.unwrap());

        //
        // ReStructuredText link
        let input = "abc`Homepage <https://blog.getreu.net>`_\nabc";
        let expected_output = FirstHyperlink {
            text: "Homepage".into(),
            dest: "https://blog.getreu.net".into(),
            title: "".into(),
        };
        let output = FirstHyperlink::from(input);
        assert_eq!(expected_output, output.unwrap());

        //
        // ReStructuredText link ref
        let input = "abc `Homepage<home_>`_ abc\n.. _home: https://blog.getreu.net\nabc";
        let expected_output = FirstHyperlink {
            text: "Homepage".into(),
            dest: "https://blog.getreu.net".into(),
            title: "".into(),
        };
        let output = FirstHyperlink::from(input);
        assert_eq!(expected_output, output.unwrap());
    }
}