libzettels 0.4.1

A library intended as a backend for applications which implement Niklas Luhmann's system of a 'Zettelkasten'.
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
//Copyright (c) 2020-2022 Stefan Thesing
//
//This file is part of libzettels.
//
//libzettels is free software: you can redistribute it and/or modify
//it under the terms of the GNU General Public License as published by
//the Free Software Foundation, either version 3 of the License, or
//(at your option) any later version.
//
//libzettels is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License
//along with Zettels. If not, see http://www.gnu.org/licenses/.

//use std::io::{BufRead, BufReader};
//use std::fmt::Write as FmtWrite; 
use std::path::{Path, PathBuf};
use std::collections::{BTreeMap, HashSet};
use std::fs;
use std::fs::File; 
use std::time::{SystemTime};

// From parent module
use backstage::configuration::Config;
use backstage::error::Error;
use backstage::indexing;
use backstage::querying::{self};
use backstage::querying::sequences::SequenceStart;
use backstage::zettel::Zettel;

/// The heart of a Zettelkasten is the data representing the interrelations 
/// between the zettels. All that information is bundled in the 
/// [`Index`](struct.Index.html). See its [Fields](struct.Index.html#fields)  
/// for details.
///
/// A YAML-representation of an example
/// Index might look like this:
/// ```yaml
/// ---    
/// files:
///     file1.md:
///         title: File 1
///         followups: [file2.md]
///         keywords: [example, first]
///         links: [subdir/file3.md]
///     file2.md:
///         title: File 2
///         followups: [subdir/file3.md]
///         keywords: [example, second]
///         links: []
///     subdir/file3.md:
///         title: File 3
///         followups: []
///         keywords: [example, third]
///         links: [file1.md]
/// timestamp:
///     secs_since_epoch: 1543078763
///     nanos_since_epoch: 449322318
/// ```
///
/// The Index provides the functionality necessary to query the Zettelkasten.
/// For that, it offers a
///
/// - Basic API, as well as an
/// - Extended API
/// 
/// Please refer to the 
/// [API Introduction](index.html#api-levels) for info on which to use.
///
/// # Basic API
/// ## Handling the Index itself
/// - [`new`](struct.Index.html#method.new)
/// - [`load`](struct.Index.html#method.load)  
/// - [`update`](struct.Index.html#method.update)
/// - [`save`](struct.Index.html#method.save)
///
/// ## Working with Zettels
/// - [`get_zettel`](struct.Index.html#method.get_zettel)|
///
/// ## Inspect Sequences
/// - [`sequences`](struct.Index.html#method.sequences)
/// - [`zettels_of_sequence`](struct.Index.html#method.zettels_of_sequence)
/// - [`sequence_tree`](struct.Index.html#method.sequence_tree)
/// - [`sequence_tree_whole`](struct.Index.html#method.sequence_tree_whole)
/// - [`parents_of_zettel`](struct.Index.html#method.parents_of_zettel)
///
/// ## Inspect Links
/// - [`inspect_links`](struct.Index.html#method.inspect_links)
/// - [`inspect_incoming_links`](struct.Index.html#method.inspect_incoming_links)
///
/// ## Search
/// - [`search_keywords`](struct.Index.html#method.search_keywords)
/// - [`search_title`](struct.Index.html#method.search_title) 
/// - [`combi_search`](struct.Index.html#method.combi_search) 
///
/// ## Listing
/// - [`get_keywords`](struct.Index.html#method.get_keywords)
/// - [`count_keywords`](struct.Index.html#method.count_keywords)
///
/// # Extended API
/// All functions of the Basic API plus the following:
///
/// ## Handling the Index itself
///
/// - [`empty`](struct.Index.html#method.empty)
/// - [`from_yaml`](struct.Index.html#method.from_yaml)
/// - [`from_file`](struct.Index.html#method.from_file)
/// - [`update_timestamp`](struct.Index.html#method.update_timestamp)
/// ## Working with Zettels
/// - [`add_zettel`](struct.Index.html#method.add_zettel)
/// - [`remove_zettel`](struct.Index.html#method.remove_zettel)
/// - [`get_mut_zettel`](struct.Index.html#method.get_mut_zettel)

///
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct Index {
    /// A key-value-store containing indexed data about the zettels.
    /// - The keys are paths to the respective zettel file (relative to the
    ///   root directory of the Zettelkasten).
    /// - The values are [`Zettel`s](struct.Zettel.html)
    pub files: BTreeMap<PathBuf, Zettel>,
    /// A timestamp that shows when the index was last updated.
    pub timestamp: SystemTime, 
}

impl Index {
    // ----------------------------------------------------------------------
    // Basic API
    // ----------------------------------------------------------------------
    
    /// Creates a new [`Index`](struct.Index.html) with data contained in
    /// [`Config`](struct.Config.html). The actual fields used are:
    /// - `rootdir`: path to the root directory containing the zettel files.
    /// - `indexingmethod`: the [`IndexingMethod`](enum.IndexingMethod.html) 
    ///   used.
    /// - `ignorefile`: path to the gitignore-compatible file telling the 
    ///   program which files in the root directory to ignore.
    ///
    /// **Note:** This really creates a *new* Index. All files in the root 
    /// directory are parsed. If you just want to load (and maybe update) an 
    /// existing index, use `Index::load` and `update` respectively.
    /// # Example
    /// ```rust, no_run
    /// # use std::path::Path;
    /// # use libzettels::{Config, Index};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::new(&cfg)?;
    /// # Ok(())
    /// # }
    /// ```
    /// **Note:**
    /// - If one of the files is non-text (e.g. an image) it is not added
    ///   to the index. An `info` about this is issued to logging.
    /// - If one of the files does not contain YAML-metadata, it is added to the 
    ///   index with the `title` "untitled" and empty `followups` and `keywords`. 
    ///   The markdown links (if any) are still parsed and `links` is populated 
    ///   as usual.
    /// # Errors
    /// - [`Error::BadLink`](enum.Error.html#variant.BadLink) if one of the 
    ///   files in the root directory  
    ///   links to a target that doesn't exist (both via `followups` and via
    ///   markdown link).
    /// - [`Error::IgnoreFile`](enum.Error.html#variant.IgnoreFile) for problems
    ///   applying an existing ignore file. (A missing ignore file is no problem).
    /// - [`Error::Io`](enum.Error.html#variant.Io) wrapping several kinds of 
    ///   `std::io:Error`, e.g. problems executing grep or ripgrep, problems with 
    ///   the files etc.
    /// - [`Error::NormalizePath`](enum.Error.html#variant.NormalizePath) if one of 
    ///   the files or a link in `followups` or `links`can not be expressed 
    ///   relative to the root directory
    /// - [`Error::Yaml`](enum.Error.html#variant.Yaml) when deserializing a
    ///   Zettel from YAML failed for one of the files (but only if it contains
    ///   any YAML, at all).
    pub fn new(cfg: &Config) -> Result<Index, Error> {
        indexing::create_index(&cfg.indexingmethod,
                               &cfg.rootdir,
                               &cfg.ignorefile)                  //error::Error
    }
    
    /// Loads an existing [`Index`](struct.Index.html) from the file  
    /// specified in the `indexfile` field of [`Config`](struct.Config.html).
    ///
    /// **Note**: This only loads the information contained in the index file.
    /// Changes in the zettel files since last update of the index are not 
    /// represented in the index (i.e. since 
    /// [`Index::new()`](struct.Index.html#method.load) or 
    /// [`index.update()`](struct.Index.html#method.update) were called).
    /// # Example
    /// ```rust, no_run
    /// # use std::path::Path;
    /// # use libzettels::{Index, Config, Error};
    /// # fn foo() -> Result<(), Error>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// # Ok(())
    /// # }
    /// ```
    /// # Errors
    /// - [`Error::Io`](enum.Error.html#variant.Io) for problems reading the
    ///   index file specified in `Config`'s field `indexfile`.
    /// - [`Error::Yaml`](enum.Error.html#variant.Yaml) when deserializing from
    ///   YAML failed.
    pub fn load(cfg: &Config) -> Result<Index, Error> {
        Index::from_file(&cfg.indexfile)
    }
    
    /// Updates an existing index using the info contained in the 
    /// [`Config`](struct.Config.html) passed as an argument. Only files 
    /// modified after the index' timestamp are inspected.
    /// 
    /// The actual `Config` fields used are:
    /// - `cfg.rootdir`
    /// - `cfg.ignorefile`
    /// - `cfg.indexingmethod`
    ///
    /// # Example
    /// ```rust, no_run
    /// # use std::path::Path;
    /// # use libzettels::{Index, Config, Error};
    /// # fn foo() -> Result<(), Error>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let mut index = Index::load(&cfg)?;
    /// index.update(&cfg)?;
    /// # Ok(())
    /// # }
    /// ```
    /// **Note:**
    /// - If one of the files is non-text (e.g. an image) it is not added
    ///   to the index. An `info` about this is issued to logging.
    /// - If one of the files does not contain YAML-metadata, it is added to the 
    ///   index with the `title` "untitled" and empty `followups` and `keywords`. 
    ///   The markdown links (if any) are still parsed and `links` is populated 
    ///   as usual.
    /// # Errors
    /// - [`Error::BadLink`](enum.Error.html#variant.BadLink) if one of the files 
    ///   links to a target that doesn't exist (both via `followups` and via
    ///   markdown link).
    /// - [`Error::IgnoreFile`](enum.Error.html#variant.IgnoreFile) for problems
    ///   applying an existing ignore file. (A missing ignore file is no problem).
    /// - [`Error::Io`](enum.Error.html#variant.Io) wrapping several kinds of 
    ///   `std::io:Error`, e.g. problems executing grep or ripgrep, problems with 
    ///   the files etc.
    /// - [`Error::NormalizePath`](enum.Error.html#variant.NormalizePath) if one of 
    ///   the files or a link in `followups` or `links`can not be expressed 
    ///   relative to the root directory
    /// - [`Error::Yaml`](enum.Error.html#variant.Yaml) when deserializing a
    ///   Zettel from YAML failed for one of the files (but only if it contains
    ///   any YAML, at all).
    pub fn update(&mut self, cfg: &Config) -> Result<(), Error> {
        indexing::update_index(self,
                               &cfg.indexingmethod, 
                               &cfg.rootdir,
                               &cfg.ignorefile)                  //error::Error
    }

    /// Write a YAML-representation to the file specified in the `Config` field
    /// `indexfile`.
    /// # Example
    /// ```rust, no_run
    /// # use std::path::Path;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// index.save(&cfg)
    ///     .expect("Failed to save index to file.");
    /// # Ok(())
    /// # }
    /// ```
    /// # Errors
    /// - [`Error::Io`](enum.Error.html#variant.Io) for problems with the 
    ///   specified indexfile.
    /// - [`Error::Yaml`](enum.Error.html#variant.Yaml) for problems 
    ///   serializing to YAML.
    pub fn save(&self, cfg: &Config) -> Result<(), Error> {
        self.to_file(&cfg.indexfile)
    }
  
    /// Returns a reference to the [Zettel](struct.Zettel.html) found at `key`. 
    /// Returns `None` if said key is not present.
    /// The `key` is a path to the file relative to root directory. 
    ///
    /// Internally, this function calls the method
    /// [`get`](https://doc.rust-lang.org/nightly/alloc/collections/btree_map/struct.BTreeMap.html#method.get) 
    ///  of [`std::collections::BTreeMap`](https://doc.rust-lang.org/nightly/alloc/collections/btree/map/struct.BTreeMap.html). 
    /// See documentation there for details.
    /// # Example
    /// ```rust, no_run
    /// # use std::path::Path;
    /// # use libzettels::{Index, Zettel, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let z1 = index.get_zettel(Path::new("file1.md"));
    /// assert!(z1.is_some());
    /// let z1 = z1.unwrap();
    /// assert_eq!(z1.title, "File 1");
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_zettel<P: AsRef<Path>>(&self, key: P) -> Option<&Zettel> {
        self.files.get(key.as_ref())
    }
    
    /// Returns a list of all the sequences the Zettels specified by `scope` is
    /// a part of.
    /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::HashSet;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let mut scope = HashSet::new();
    /// scope.insert(PathBuf::from("file1.md"));
    /// let sequences = index.sequences(&scope, &cfg.sequencestart);
    /// # Ok(())
    /// # }
    /// ```
    pub fn sequences(&self,
                              scope: &HashSet<PathBuf>,
                              cfg_sequence_start: &SequenceStart)
                              -> HashSet<PathBuf> {
        querying::sequences::sequences(&self, scope, cfg_sequence_start)
    }
    
    /// Using the Zettel specified by `key` as an identifier for a sequence, this 
    /// function returns a list of all the zettels that belong to that sequence.
    /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::HashSet;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let seq_zettels = index.zettels_of_sequence(PathBuf::from("file1.md"));
    /// # Ok(())
    /// # }
    /// ```
    pub fn zettels_of_sequence<P: AsRef<Path>>(&self, key: P)
                                                   -> HashSet<PathBuf> {
        querying::sequences::zettels_of_sequence(&self, key)
    }
    
    /// Returns a list of zettels that are part of all sequences of which the 
    /// zettels specified by `scope` are also a part of.
    /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::HashSet;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let mut scope = HashSet::new();
    /// scope.insert(PathBuf::from("file1.md"));
    /// let sequence_tree = index.sequence_tree(&scope);
    /// assert!(sequence_tree.contains(&PathBuf::from("file1.md")));
    /// assert!(sequence_tree.contains(&PathBuf::from("file2.md")));
    /// assert!(sequence_tree.contains(&PathBuf::from("file3.md")));
    /// assert!(sequence_tree.contains(&PathBuf::from("subdir/file4.md")));
    /// # Ok(())
    /// # }
    /// ```
    pub fn sequence_tree(&self, scope: &HashSet<PathBuf>) -> HashSet<PathBuf> {
        querying::sequences::sequence_tree(&self, &scope)
    }
    
    /// Returns a list of zettels that are part of all sequences of which the 
    /// zettels specified by `scope` are also a part of, as well as related 
    /// sequences.
    /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::HashSet;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let mut scope = HashSet::new();
    /// scope.insert(PathBuf::from("file1.md"));
    /// let sequence_tree = index.sequence_tree_whole(&scope);
    /// assert!(sequence_tree.contains(&PathBuf::from("file1.md")));
    /// assert!(sequence_tree.contains(&PathBuf::from("file2.md")));
    /// assert!(sequence_tree.contains(&PathBuf::from("file3.md")));
    /// assert!(sequence_tree.contains(&PathBuf::from("subdir/file4.md")));
    /// assert!(sequence_tree.contains(&PathBuf::from("subdir/file5.md")));
    /// # Ok(())
    /// # }
    /// ```
    pub fn sequence_tree_whole(&self, scope: &HashSet<PathBuf>)
                                        -> HashSet<PathBuf> {
        querying::sequences::sequence_tree_whole(&self, scope)
    }
    
    /// Returns the paths to all zettels in the index that list the zettel
    /// specified by `key` as their followups.
    /// # Note
    /// In Luhmann's Zettelkasten system, a Zettel can not be a followup of 
    /// more than one other Zettel. A user might approach this differently,
    /// however, so this returns a list (a HashSet, to be exact).
    /// # Example
    /// ```rust, no_run
    /// # use std::path::Path;
    /// # use libzettels::{Index, Zettel, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let parents = index.parents_of_zettel("file2.md");
    /// for parent in parents {
    ///     println!("{:?}", parent);
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn parents_of_zettel<P: AsRef<Path>>(&self, key: P) 
                                -> HashSet<PathBuf> {
        let scope = vec![key.as_ref().to_path_buf()];
        querying::sequences::parents_of_scope(&self, scope)
    }
    
    /// Collects the outgoing links of a list of zettels specified by
    /// `linkers`.
    /// Returns a `HashSet`.
    /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::HashSet;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// 
    /// // We want the links of one Zettel: file1.md
    /// let mut linkers = HashSet::new();
    /// linkers.insert(PathBuf::from("file1.md"));
    /// let links = index.inspect_links(&linkers);
    /// # Ok(())
    /// # }
    /// ```
    pub fn inspect_links(&self, scope: &HashSet<PathBuf>) 
                                                    -> HashSet<PathBuf> {
        let mut links = HashSet::new();
        for linker in scope {
            let z = &self.get_zettel(linker);
            if z.is_some() {
                for link in &z.unwrap().links {
                    links.insert(link.to_path_buf());
                }
            }
        }
        links
    }
    
    // wrapper for `querying::inspect_incoming`, unit tests are there.
    /// Returns a list of zettels that link to the zettels specified by
    /// `zettels`. If `all` is set to true, only zettels are returned that
    /// link to *all* specified zettels.
    /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::HashSet;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// 
    /// // We want zettels linking to two Zettels: file2.md and file3.md
    /// let mut targets = HashSet::new();
    /// targets.insert(PathBuf::from("file2.md"));
    /// targets.insert(PathBuf::from("file3.md"));
    ///
    /// // What links to either of them?
    /// let incoming = index.inspect_incoming_links(&targets, false);
    /// assert_eq!(incoming.len(), 3);
    /// assert!(incoming.contains(&PathBuf::from("file1.md")));
    /// assert!(incoming.contains(&PathBuf::from("file2.md")));
    /// assert!(incoming.contains(&PathBuf::from("onlies/markdown-only.md")));
    ///
    /// // What links to both of them?
    /// let incoming = index.inspect_incoming_links(&targets, true);
    /// assert_eq!(incoming.len(), 1);
    /// assert!(incoming.contains(&PathBuf::from("file1.md")));
    /// # Ok(())
    /// # }
    /// ```
    pub fn inspect_incoming_links(&self, scope: &HashSet<PathBuf>, all: bool)
                -> HashSet<PathBuf> {
        querying::inspect_incoming(&self, &scope, all)
    }
        
    // wrapper for `querying::search_index_for_keywords`
    /// Takes a vector of Strings, containing keywords to be searched for.
    /// Returns a list of zettels that have one or – if `all` is true – all
    /// of these keywords.
    /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::HashSet;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let searched_keywords = vec!["first".to_string()];
    /// let matching_zettels = index.search_keywords(searched_keywords,
    ///                                              false);
    /// assert_eq!(matching_zettels.len(), 1);
    /// assert!(matching_zettels.contains(&PathBuf::from("file1.md")));
    /// # Ok(())
    /// # }
    /// ```
    pub fn search_keywords(&self, searched_keywords: Vec<String>,
              all: bool) -> HashSet<PathBuf> {
        querying::search_index_for_keywords(&self, searched_keywords, all)
    }
    
    //wrapper for `querying::search_index_for_title`
    /// Searches the index for zettels whose title matches `search_term` 
    /// (exactly if `exact` is true). 
    /// Returns a list of matching zettels.
        /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::HashSet;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let matching_zettels = index.search_title("File 1", false);
    /// assert_eq!(matching_zettels.len(), 1);
    /// assert!(matching_zettels.contains(&PathBuf::from("file1.md")));
    /// # Ok(())
    /// # }
    /// ```
    pub fn search_title<T: AsRef<str>>(&self, 
                                       search_term: T,
                                       exact: bool) 
                                       -> HashSet<PathBuf> {
        querying::search_index_for_title(&self, search_term, exact)
    }
    
    //wrapper for `querying::combi_search`
    /// Combines searches for keywords and title. 
    /// If `exact` is true, the title must match `search_term` exactly.
    /// If `all` is true, only zettels are returned that match all search
    /// criteria.
    /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::HashSet;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let searched_keywords = vec!["first".to_string()];
    /// let matching_zettels = index.combi_search(searched_keywords, 
    ///                                              true,
    ///                                              "File",
    ///                                              false);
    /// assert_eq!(matching_zettels.len(), 1);
    /// assert!(matching_zettels.contains(&PathBuf::from("file1.md")));
    /// # Ok(())
    /// # }
    /// ```
    pub fn combi_search<T: AsRef<str>>(&self, 
                                       searched_keywords: Vec<String>,
                                       all: bool, 
                                       search_term: T,
                                       exact: bool) 
                                       -> HashSet<PathBuf> {
        querying::combi_search(&self, searched_keywords, all, 
                               search_term, exact)
    }
    
    //wrapper for `querying::get_keywords`
    /// Lists all keywords present in the zettels.
    /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::HashSet;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<dyn std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let all_keywords = index.get_keywords();
    /// assert!(all_keywords.contains("test"));
    /// assert!(all_keywords.contains("example"));
    /// # Ok(())
    /// # }
    /// ```    
    pub fn get_keywords(&self) -> HashSet<String> {
        querying::get_keywords(&self)
    }
    
    //wrapper for `querying::count_keywords`
    /// Lists all keywords present in the zettels along with how often
    /// they occur in the whole zettelkasen.
    /// # Example
    /// ```rust
    /// # use std::path::{Path, PathBuf};
    /// # use std::collections::BTreeMap;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<dyn std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// let keyword_count = index.count_keywords();
    /// assert_eq!(Some(&5), keyword_count.get("example"));
    /// assert_eq!(Some(&1), keyword_count.get("test"));
    /// # Ok(())
    /// # }
    /// ```    
    pub fn count_keywords(&self) -> BTreeMap<String, u32> {
        querying::count_keywords(&self)
    }
    
    
    // ----------------------------------------------------------------------
    // Extended API
    // ----------------------------------------------------------------------
    
    /// ## Extended API
    /// Creates a new Index with an empty file list and the current system
    /// time as timestamp.
    /// # Example - And a very elabourated one, at that.
    /// ```rust
    /// # use libzettels::Index;
    /// let index = Index::empty();
    /// ```
    pub fn empty() -> Index {
        Index {
            files: BTreeMap::new(),
            timestamp: SystemTime::now(),
        }
    }
    
    /// ## Extended API
    /// Creates a new Index by deserializing it from a YAML-string. Returns
    /// an error if something went wrong with deserializing it.
    /// # Example
    /// ```rust
    /// # use libzettels::{Index};
    /// # fn foo() -> Result<Index, Box<std::error::Error>>  {
    /// let yaml = "---    
    /// files:
    ///   file1.md:
    ///     title: File 1
    ///     followups: [subdir/file2.md]
    ///     keywords: [example]
    ///     links: []
    ///   subdir/file2.md:
    ///     title: File 2
    ///     followups: []
    ///     keywords: [example, second]
    ///     links: [file1.md]
    /// timestamp:
    ///     secs_since_epoch: 1543078763
    ///     nanos_since_epoch: 449322318";
    /// let index = Index::from_yaml(yaml)?;
    /// # Ok(index)
    /// # }    
    /// ```
    /// # Errors
    /// - [`Error::Yaml`](enum.Error.html#variant.Yaml) when deserializing from
    ///   YAML failed.
    pub fn from_yaml<T: AsRef<str>>(yaml: T) -> Result<Index, Error> {
        let index: Index = serde_yaml::from_str(yaml.as_ref())?; // serde_yaml::Error
        Ok(index)
    }
    
    /// ## Extended API
    /// Loads an existing Index by deserializing it from a YAML-file. Returns
    /// an error if something went wrong with reading the file or deserializing
    /// it.
    /// ```rust, no_run
    /// # use libzettels::{Index};
    /// # use std::path::Path;
    /// # fn foo() -> Result<Index, Box<std::error::Error>>  {
    /// let file = Path::new("examples/index.yaml");
    /// let index = Index::from_file(file)?;
    /// # Ok(index)
    /// # }     
    /// ```
    /// # Errors
    /// - [`Error::Io`](enum.Error.html#variant.Io) for problems reading the
    ///   file.
    /// - [`Error::Yaml`](enum.Error.html#variant.Yaml) when deserializing from
    ///   YAML failed.
    pub fn from_file<P: AsRef<Path>>(indexfile: P) -> Result<Index, Error> {
        let indexfile = indexfile.as_ref();
        debug!("Loading index from file: {:?}", indexfile);
        let yaml = fs::read_to_string(indexfile)?;          //io::Error
        Index::from_yaml(yaml)                             //error::Error::Yaml
    }
    
    /// ## Extended API
    /// Overwrites the timestamp with the current system time.
    /// # Example
    /// ```rust, no_run
    /// # use libzettels::{Config, Index};
    /// # use std::path::Path;
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let mut index = Index::new(&cfg)?;
    /// index.update_timestamp();
    /// # Ok(())
    /// # }
    /// ```
    pub fn update_timestamp(&mut self) {
        self.timestamp = SystemTime::now();
    }
    
    /// ## Extended API
    /// Write a YAML-representation of the index to file.
    /// # Example
    /// ```rust
    /// # use std::path::Path;
    /// # use libzettels::{Index, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let index = Index::load(&cfg)?;
    /// index.to_file(Path::new("examples/index.yaml"))?;
    /// # Ok(())
    /// # }
    /// ```
    /// # Errors
    /// - [`Error::Io`](enum.Error.html#variant.Io) for problems with the 
    ///   specified file.
    /// - [`Error::Yaml`](enum.Error.html#variant.Yaml) for problems 
    ///   serializing to YAML.
    pub fn to_file<P: AsRef<Path>>(&self, indexfile: P) -> Result<(), Error> {
        use std::io::Write; 
        let indexfile = indexfile.as_ref();
        debug!("Writing index to file {:?}", indexfile);
        let s = serde_yaml::to_string(self)?;
        let mut file = File::create(indexfile)?;
        writeln!(file, "{}", s)?;
        Ok(())
    }
    
    /// ## Extended API
    /// Adds a Zettel to the index with the path to the file relative to root 
    /// directory as `key`. Internally,
    /// [`insert`](https://doc.rust-lang.org/nightly/alloc/collections/btree_map/struct.BTreeMap.html#method.insert)
    ///  of [`std::collections::BTreeMap`](https://doc.rust-lang.org/nightly/alloc/collections/btree/map/struct.BTreeMap.html)
    /// is called. See documentation there for details. That method's return 
    /// value is disregarded, however.
    /// ```rust, no_run
    /// # use libzettels::{Config, Index, Zettel};
    /// # use std::path::Path;
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let mut index = Index::new(&cfg)?;
    /// let file = Path::new("test-zettel.md"); //relative to the root directory
    /// let zettel = Zettel::new("Empty Zettel for Testing");
    /// index.add_zettel(file, zettel);
    /// # Ok(())
    /// # }
    /// ```
    pub fn add_zettel<P: AsRef<Path>>(&mut self, key: P, zettel: Zettel) {
        self.files.insert(key.as_ref().to_path_buf(), zettel);
    }
    
    /// ## Extended API
    /// Removes a Zettel from the index. The `key` is the path to the 
    /// corresponding file, relative to the root directory. 
    /// 
    /// Returns the old Zettel found at the key or `None` if it was not present
    /// in the first place. Please note that the return value doesn't need to
    /// be checked for success. The entry for `key` is guaranteed to be gone,
    /// regardless of the return value.
    ///
    /// Internally,
    /// [`remove`](https://doc.rust-lang.org/nightly/alloc/collections/btree_map/struct.BTreeMap.html#method.remove)
    ///  of [`std::collections::BTreeMap`](https://doc.rust-lang.org/nightly/alloc/collections/btree/map/struct.BTreeMap.html)
    /// is called. See documentation there for details.
    /// # Example 1
    /// In most cases, you'll just disregard the return value.
    /// ```rust, no_run
    /// # use libzettels::{Config, Index, Zettel};
    /// # use std::path::Path;
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let mut index = Index::new(&cfg)?;
    /// let file = Path::new("test-zettel.md"); //relative to root directory
    /// let zettel = Zettel::new("Empty Zettel for Testing");
    /// index.add_zettel(file, zettel);
    /// index.remove_zettel(file);
    /// // or, if you want to be very tidy:
    /// let _ = index.remove_zettel(file);
    /// # Ok(())
    /// # }
    /// ```
    /// # Example 2
    /// If you want to do something with the old Zettel:
    /// ```rust, no_run
    /// # use libzettels::{Config, Index, Zettel};
    /// # use std::path::Path;
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// // snip
    /// # let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// # let mut index = Index::new(&cfg)?;
    /// # let file = Path::new("test-zettel.md"); //relative to root directory
    /// let zettel = Zettel::new("Empty Zettel for Testing");
    /// // We clone here so we have something to compare.
    /// index.add_zettel(file, zettel.clone());  
    /// let removed = index.remove_zettel(file);
    /// assert_eq!(removed, Some(zettel));
    /// # Ok(())
    /// # }
    /// ```
    pub fn remove_zettel<P: AsRef<Path>>(&mut self, key: P) -> Option<Zettel> {
        self.files.remove(key.as_ref())
    }
    
    /// ## Extended API
    /// Returns a mutable reference to the [Zettel](struct.Zettel.html) found 
    /// at `key`. 
    /// Returns `None` of said key is not present.
    /// The `key` is the path to the corresponding file relative to root 
    /// directory. 
    /// 
    /// **Note:** Editing this only changes the entry in the index, not the 
    /// file itself. Changes might be overwritten when the index us updated
    /// next. This method is intended for developers of frontends who want to
    /// present the metadata and the document body to their users, separately. 
    /// If you use this, take care to write changes back to the file.
    ///
    /// Internally, this function calls the method
    /// [`get_mut`](https://doc.rust-lang.org/nightly/alloc/collections/btree_map/struct.BTreeMap.html#method.get_mut) 
    ///  of [`std::collections::BTreeMap`](https://doc.rust-lang.org/nightly/alloc/collections/btree/map/struct.BTreeMap.html). 
    /// See documentation there for details.
    /// # Example
    /// ```rust, no_run
    /// # use std::path::Path;
    /// # use libzettels::{Index, Zettel, Config};
    /// # fn foo() -> Result<(), Box<std::error::Error>>  {
    /// let cfg = Config::from_file(Path::new("examples/zettels-examples.cfg.yaml"))?;
    /// let mut index = Index::load(&cfg)?;
    /// // Use an inner scope so z goes out of scope automatically.
    /// {
    ///     let z = index.get_mut_zettel(Path::new("file1.md"));
    ///     assert!(z.is_some());
    ///     let z = z.unwrap();
    ///     z.title = String::from("Changed Title 1");
    /// }
    /// // Let's get it again from index to see if the changes are there.
    /// let z = index.get_zettel(Path::new("file1.md")).unwrap();
    /// assert_eq!(z.title, "Changed Title 1");
    /// # Ok(())
    /// # }
    /// ```
    pub fn get_mut_zettel<P: AsRef<Path>>(&mut self, key: P) -> Option<&mut Zettel> {
        self.files.get_mut(key.as_ref())
    }

}

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

#[cfg(test)]
mod tests {
    use super::*;
    use IndexingMethod;
    use std::io::Write;
    
    extern crate tempfile;
    use self::tempfile::tempdir;
    use examples::*;
    const YAML: &str = "---    
files:
  file1.md:
    title: File 1
    followups: [subdir/file2.md]
    keywords: [example]
    links: []
  subdir/file2.md:
    title: File 2
    followups: []
    keywords: [example, second]
    links: [file1.md]
timestamp:
    secs_since_epoch: 1543078763
    nanos_since_epoch: 449322318";
    
    // ----------------------------------------------------------------------
    // with valid data
    // ----------------------------------------------------------------------
    
    #[test]
    fn test_index_new() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_config(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let cfg_file = config_dir.join("libzettels.cfg.yaml");
        let mut cfg = Config::from_file(cfg_file)
            .expect("Failed to read config from file.");
        
        // With default grep
        let index = Index::new(&cfg);
        cfg.indexingmethod = IndexingMethod::Grep;
        assert!(index.is_ok());
        let index_grep = index.unwrap();
        
        // with ripgrep
        cfg.indexingmethod = IndexingMethod::RipGrep;
        let index = Index::new(&cfg);
        assert!(index.is_ok());
        let index_rg = index.unwrap();
        
        // with native
        cfg.indexingmethod = IndexingMethod::Native;
        let index = Index::new(&cfg);
        assert!(index.is_ok());
        let index_native = index.unwrap();
        
        // All three indexes should be identical, except for the timestamp
        assert_eq!(index_grep.files, index_rg.files);
        assert_eq!(index_grep.files, index_native.files);
    }
    
    #[test]
    fn test_index_load() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let cfg_file = config_dir.join("libzettels.cfg.yaml");
        let cfg = Config::from_file(cfg_file)
            .expect("Failed to read config from file.");
        
        let index = Index::load(&cfg);
        assert!(index.is_ok());
    }
    
    #[test]
    fn test_index_update() {
        use std::io::Write;
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let cfg_file = config_dir.join("libzettels.cfg.yaml");
        let cfg = Config::from_file(cfg_file)
            .expect("Failed to read config from file.");
        
        let mut index = Index::load(&cfg)
            .expect("Failed to read index from file.");
            
        let mut file6 = std::fs::File::create(&cfg.rootdir.join("file6.md"))
            .expect("Failed to create file6.md");
        writeln!(file6, "{}", FILE6)
            .expect("Failed to write to file"); //see below
        
        assert!(index.update(&cfg).is_ok());
        assert!(index.files.contains_key(std::path::Path::new("file6.md")));
    }

    const FILE6: &str ="---
    title:  'File 6'
    keywords: [example6]
    followups: [file1.md]
    lang: de
    ...

    # Bla bla

    Lorem ipsum

    [//]: # (Links)
    ";
    
    #[test]
    fn test_index_empty() {
        let i1 = Index {
            files: BTreeMap::new(),
            timestamp: SystemTime::now(),
        };
        let i2 = Index::empty();
        assert!(i2.files.is_empty());
        assert_eq!(i2.files, i1.files);
        // has i1 been created before i2?
        assert!(i1.timestamp < i2.timestamp);
    }

    #[test]
    fn test_index_from_yaml() {
        let index = Index::from_yaml(YAML);
        assert!(index.is_ok());
    }
    
    #[test]
    fn test_index_from_file() {
        let tmp_dir = tempdir().expect("Failed setting up temp directory.");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let file_path = dir.join("examples/config/index.yaml");
        
        let index = Index::from_file(&file_path);
        assert!(index.is_ok());
    }
        
    #[test]
    fn test_index_add_zettel() {
        let mut index = Index {
            files: BTreeMap::new(),
            timestamp: SystemTime::now(),
        };
        let zettel = Zettel::new("Test Zettel");
        let zettel_copy = zettel.clone();
        index.add_zettel(&PathBuf::from("test_zettel.md"), zettel);
        assert_eq!(index.files.len(), 1);
        assert_eq!(index.files.get(&PathBuf::from("test_zettel.md")).unwrap(), 
                   &zettel_copy);
    }
    
    #[test]
    fn test_index_get_zettel() {
        let mut index = Index {
            files: BTreeMap::new(),
            timestamp: SystemTime::now(),
        };
        let zettel = Zettel::new("Test Zettel");
        let zettel_copy = zettel.clone();
        index.files.insert(PathBuf::from("test_zettel.md"), zettel);
        assert_eq!(index.get_zettel(PathBuf::from("test_zettel.md")).unwrap(), 
                   &zettel_copy);
    }
    
    #[test]
    fn test_index_save() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let cfg_file = config_dir.join("libzettels.cfg.yaml");
        let cfg = Config::from_file(cfg_file)
            .expect("Failed to read config from file.");
        
        let index = Index::load(&cfg)
            .expect("Failed to read index from file.");
        assert!(index.save(&cfg).is_ok());
    }
    
    #[test]
    fn test_index_remove_zettel() {
        let mut index = Index {
            files: BTreeMap::new(),
            timestamp: SystemTime::now(),
        };
        let zettel = Zettel::new("Test Zettel");
        let key = PathBuf::from("test_zettel.md");
        index.files.insert(key.clone(), zettel);
        assert_eq!(index.files.len(), 1);
        index.remove_zettel(key);
        assert!(index.files.is_empty());
    }
    
    #[test]
    fn test_index_update_timestamp() {
        let mut index = Index {
            files: BTreeMap::new(),
            timestamp: SystemTime::now(),
        };
        let t1 = index.timestamp;
        index.update_timestamp();
        // timestamp later than t1?
        assert!(t1 < index.timestamp);
    }
    
    #[test]
    fn test_index_get_mut_zettel() {
        let mut index = Index {
            files: BTreeMap::new(),
            timestamp: SystemTime::now(),
        };
        let zettel = Zettel::new("Test Zettel");
        let key = PathBuf::from("test_zettel.md");
        index.files.insert(key.clone(), zettel);
        // Use an inner scope so z goes out of scope automatically.
        {
            let z = index.get_mut_zettel(&key);
            assert!(z.is_some());
            let z = z.unwrap();
            z.title = String::from("Changed Title 1");
        }
        // Let's get it again from index to see if the changes are there.
        let z = index.get_zettel(&key).unwrap();
        assert_eq!(z.title, "Changed Title 1");
    }
    
    #[test]
    fn test_index_to_file() {
        // Setup
        let tmp_dir = tempdir().expect("Failed to create temp dir.");
        let indexfile = tmp_dir.path().join("index.yaml");
        // Create an empty index
        let mut index = Index::empty();
        // Add two Zettels
        let z1 = Zettel::new("Zettel 1");
        let z2 = Zettel::new("Zettel 2");
        index.add_zettel(Path::new("foo"), z1);
        index.add_zettel(Path::new("bar"), z2);
        
        // write the index to file
        assert!(index.to_file(indexfile).is_ok());
    }
    
    // -----------------------------------------------------------------------
    // invalid data aka error handling
    // -----------------------------------------------------------------------
    
    #[test]
    fn test_index_new_no_rootdir() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_config(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let _rootdir = dir.join("Zettelkasten/");
        let indexfile = config_dir.join("index.yaml");
        let _cfg_file = config_dir.join("libzettels.cfg.yaml");
        
        let cfg = Config::new(dir.join("foo"), //Non existing rootdir
                              indexfile);
        let index = Index::new(&cfg);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Io(inner) => {
                match inner.kind() {
                    std::io::ErrorKind::NotFound => {
                        assert!(inner.to_string().contains("No such file or \
                        directory"));
                    },
                    _ => panic!("Expected a NotFound error, got: {:#?}", inner)
                }
            },
            _ => panic!("Expected a Io error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_load_non_existing_file() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_config(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let rootdir = dir.join("Zettelkasten/");
        let _cfg_file = config_dir.join("libzettels.cfg.yaml");
        
        let indexfile = config_dir.join("foo"); //doesn't exist
        
        let cfg = Config::new(rootdir,
                              indexfile);
        
        let index = Index::load(&cfg);
        assert!(index.is_err());
        let e = index.unwrap_err();
            match e {
            Error::Io(inner) => {
                match inner.kind() {
                    std::io::ErrorKind::NotFound => {
                        assert!(inner.to_string().contains("No such file or \
                        directory"));
                    },
                    _ => panic!("Expected a NotFound error, got: {:#?}", inner)
                }
            },
            _ => panic!("Expected a Io error, got: {:#?}", e),
        }
    }

    #[test]
    fn test_index_load_missing_field() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_config(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let rootdir = dir.join("Zettelkasten/");
        let indexfile = config_dir.join("index.yaml");
        let _cfg_file = config_dir.join("libzettels.cfg.yaml");
        
        let cfg = Config::new(rootdir, indexfile.to_path_buf());

        let mut f = std::fs::File::create(&indexfile)
            .expect("Failed to create index file");
        
        let erronous_index = "---    
    file:
        file1.md:
            title: File 1
            followups: [file2.md]
            keywords: [example, first]
            links: [subdir/file3.md]
    timestamp:
        secs_since_epoch: 1543078763
        nanos_since_epoch: 449322318";
        writeln!(f, "{}", erronous_index).expect("Failed to write to file");
        
        let index = Index::load(&cfg);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("missing field `files`"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }

    #[test]
    fn test_index_load_duplicate_field() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_config(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let rootdir = dir.join("Zettelkasten/");
        let indexfile = config_dir.join("index.yaml");
        let _cfg_file = config_dir.join("libzettels.cfg.yaml");
        
        let cfg = Config::new(rootdir, indexfile.to_path_buf());

        let mut f = std::fs::File::create(&indexfile)
            .expect("Failed to create index file");
        
        let erronous_index = "---
    files:
        file1.md:
            title: File 1
            followups: [file2.md]
            keywords: [example, first]
            links: [subdir/file3.md]
    files: foo
    timestamp:
        secs_since_epoch: 1543078763
        nanos_since_epoch: 449322318";
        write!(f, "{}", erronous_index).expect("Failed to write to file");
        
        let index = Index::load(&cfg);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("duplicate field `files`"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }

    #[test]
    fn test_index_load_invalid_type() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_config(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let rootdir = dir.join("Zettelkasten/");
        let indexfile = config_dir.join("index.yaml");
        let _cfg_file = config_dir.join("libzettels.cfg.yaml");
        
        let cfg = Config::new(rootdir, indexfile.to_path_buf());

        let mut f = std::fs::File::create(&indexfile)
            .expect("Failed to create index file");
        
        let erronous_index = "---
    files: foo
    timestamp:
        secs_since_epoch: 1543078763
        nanos_since_epoch: 449322318";
        write!(f, "{}", erronous_index).expect("Failed to write to file");
        
        let index = Index::load(&cfg);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("invalid type"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }
        
    #[test]
    fn test_index_load_unknown_field() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_config(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let rootdir = dir.join("Zettelkasten/");
        let indexfile = config_dir.join("index.yaml");
        let _cfg_file = config_dir.join("libzettels.cfg.yaml");
        
        let cfg = Config::new(rootdir, indexfile.to_path_buf());

        let mut f = std::fs::File::create(&indexfile)
            .expect("Failed to create index file");
        
        let erronous_index = "---
    files:
        file1.md:
            title: File 1
            followups: [file2.md]
            keywords: [example, first]
            links: [subdir/file3.md]
    timestamp:
        secs_since_epoc: 1543078763
        nanos_since_epoch: 449322318";
        write!(f, "{}", erronous_index).expect("Failed to write to file");
        
        let index = Index::load(&cfg);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("unknown field"));
                assert!(message.contains("expected `secs_since_epoch`"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }

    #[test]
    fn test_index_load_invalid_value() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_config(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let rootdir = dir.join("Zettelkasten/");
        let indexfile = config_dir.join("index.yaml");
        let _cfg_file = config_dir.join("libzettels.cfg.yaml");
        
        let cfg = Config::new(rootdir, indexfile.to_path_buf());

        let mut f = std::fs::File::create(&indexfile)
            .expect("Failed to create index file");
        
        let erronous_index = "---
    files:
        file1.md:
            title: File 1
            followups: [file2.md]
            keywords: [example, first]
            links: [subdir/file3.md]
    timestamp:
        secs_since_epoch: 1543078763
        nanos_since_epoch: 44932231800000000";
        write!(f, "{}", erronous_index).expect("Failed to write to file");
        
        let index = Index::load(&cfg);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("invalid value"));
                assert!(message.contains("expected u32"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_update_bad_yaml() {
        use std::io::Write;
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let cfg_file = config_dir.join("libzettels.cfg.yaml");
        let cfg = Config::from_file(cfg_file)
            .expect("Failed to read config from file.");
        
        let mut index = Index::load(&cfg)
            .expect("Failed to read index from file.");
            
        let mut file6 = std::fs::File::create(&cfg.rootdir.join("file6.md"))
            .expect("Failed to create file6.md");
        
        let erroneous_file = "---
    title:  'File 6'
    title: Foo
    ";
        writeln!(file6, "{}", erroneous_file)
            .expect("Failed to write to file"); //see below
        
        let result = index.update(&cfg);
        assert!(result.is_err());
        let e = result.unwrap_err();
        
        match e {
            Error::BadHeader(_, inner) => {
                let message = inner.to_string();
                assert!(message.contains("duplicate field"));
            },
            _ => panic!("Expected a BadHeader error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_update_one_file_only_grep() {
        use std::io::Write;
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let cfg_file = config_dir.join("libzettels.cfg.yaml");
        let cfg = Config::from_file(cfg_file)
            .expect("Failed to read config from file.");
        
        let mut index = Index::load(&cfg)
            .expect("Failed to read index from file.");
            
        let mut file7 = std::fs::File::create(&cfg.rootdir.join("file7.md"))
            .expect("Failed to create file7.md");
        writeln!(file7, "{}", FILE7)
            .expect("Failed to write to file"); //see below
        
        let r = index.update(&cfg);
        assert!(r.is_ok());
        assert!(index.files.contains_key(std::path::Path::new("file7.md")));
    }
    
    #[test]
    fn test_index_update_one_file_only_ripgrep() {
        use std::io::Write;
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let cfg_file = config_dir.join("libzettels.cfg.yaml");
        let mut cfg = Config::from_file(cfg_file)
            .expect("Failed to read config from file.");
        cfg.indexingmethod = IndexingMethod::RipGrep;
        
        let mut index = Index::load(&cfg)
            .expect("Failed to read index from file.");
            
        let mut file7 = std::fs::File::create(&cfg.rootdir.join("file7.md"))
            .expect("Failed to create file7.md");
        writeln!(file7, "{}", FILE7)
            .expect("Failed to write to file"); //see below
        
        let r = index.update(&cfg);
        assert!(r.is_ok());
        assert!(index.files.contains_key(std::path::Path::new("file7.md")));
    }
    
    #[test]
    fn test_index_update_one_file_only_native() {
        use std::io::Write;
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let cfg_file = config_dir.join("libzettels.cfg.yaml");
        let mut cfg = Config::from_file(cfg_file)
            .expect("Failed to read config from file.");
        cfg.indexingmethod = IndexingMethod::Native;
        
        let mut index = Index::load(&cfg)
            .expect("Failed to read index from file.");
            
        let mut file7 = std::fs::File::create(&cfg.rootdir.join("file7.md"))
            .expect("Failed to create file7.md");
        writeln!(file7, "{}", FILE7)
            .expect("Failed to write to file"); //see below
        
        let r = index.update(&cfg);
        assert!(r.is_ok());
        assert!(index.files.contains_key(std::path::Path::new("file7.md")));
    }

    const FILE7: &str ="---
    title:  'File 7'
    keywords: [example7]
    followups: [file1.md]
    lang: de
    ...

    # Bla bla

    Lorem [ipsum](file2.md)

    [//]: # (Links)
    ";
    
    #[test]
    fn test_index_get_zettel_none() {
        use std::collections::BTreeMap;
        use std::time::SystemTime;
        use std::path::PathBuf;
        let index = Index {
            files: BTreeMap::new(),
            timestamp: SystemTime::now(),
        };
        let nz = index.get_zettel(PathBuf::from("non_existing_zettel.md"));
        assert!(nz.is_none());
    }
    
    #[test]
    fn test_index_save_non_existing_file() {
        let tmp_dir = tempdir().expect("Failed to create temp directory");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config");
        let cfg_file = config_dir.join("libzettels.cfg.yaml");
        let mut cfg = Config::from_file(cfg_file)
            .expect("Failed to read config from file.");
        
        let index = Index::load(&cfg)
            .expect("Failed to read index from file.");
        // change the indexfile
        cfg.indexfile = config_dir.join("nonexisting_dir/foo"); //doesn't exist
        
        let result = index.save(&cfg);
        assert!(result.is_err());
        let e = result.unwrap_err();
        match e {
            Error::Io(inner) => {
                match inner.kind() {
                    std::io::ErrorKind::NotFound => {
                        assert!(inner.to_string().contains("No such file or directory"));
                    },
                    _ => panic!("Expected a NotFound error, got: {:#?}", inner)
                }
            },
            _ => panic!("Expected a Io error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_from_yaml_unkown_field() {
        let yaml = "---
        files:
            file1.md:
                title: File 1
                followups: [file2.md]
                keywords: [example, first]
                links: [subdir/file3.md]
        timestamp:
            secs_since_epoc: 1543078763
            nanos_since_epoch: 449322318";
        
        let index = Index::from_yaml(yaml);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("unknown field"));
                assert!(message.contains("expected `secs_since_epoch`"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }

    #[test]
    fn test_index_from_yaml_missing_field() {
        let yaml = "---
        fies:
            file1.md:
                title: File 1
                followups: [file2.md]
                keywords: [example, first]
                links: [subdir/file3.md]
        timestamp:
            secs_since_epoch: 1543078763
            nanos_since_epoch: 449322318";
        
        let index = Index::from_yaml(yaml);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("missing field `files`"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }

    #[test]
    fn test_index_from_yaml_duplicate_field() {
        let yaml = "---
        files:
            file1.md:
                title: File 1
                followups: [file2.md]
                keywords: [example, first]
                links: [subdir/file3.md]
        timestamp:
            secs_since_epoch: 1543078763
            nanos_since_epoch: 449322318
        timestamp:
            secs_since_epoch: 1543078763
            nanos_since_epoch: 449322318";
        
        let index = Index::from_yaml(yaml);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("duplicate field `timestamp`"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }

    #[test]
    fn test_index_from_yaml_invalid_type() {
        let yaml = "---
        files: foo
        timestamp:
            secs_since_epoch: 1543078763
            nanos_since_epoch: 449322318";
        
        let index = Index::from_yaml(yaml);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("invalid type"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_from_file_non_existing_file() {
        let tmp_dir = tempdir().expect("Failed setting up temp directory.");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config/");
        let indexfile = config_dir.join("foo"); //doesn't exist
        
        let index = Index::from_file(indexfile);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Io(inner) => {
                match inner.kind() {
                    std::io::ErrorKind::NotFound => {
                        assert!(inner.to_string().contains("No such file or \
                                                            directory"));
                    },
                    _ => panic!("Expected a NotFound error, got: {:#?}", inner)
                }
            },
            _ => panic!("Expected a Io error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_from_file_missing_field() {
        let tmp_dir = tempdir().expect("Failed setting up temp directory.");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config/");
        let indexfile = config_dir.join("index.yaml");

        let mut f = std::fs::File::create(&indexfile)
            .expect("Failed to create index file");
        
        let erronous_index = "---    
        file:
            file1.md:
                title: File 1
                followups: [file2.md]
                keywords: [example, first]
                links: [subdir/file3.md]
        timestamp:
            secs_since_epoch: 1543078763
            nanos_since_epoch: 449322318";
        writeln!(f, "{}", erronous_index).expect("Failed to write to file");
        
        let index = Index::from_file(indexfile);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("missing field `files`"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_from_file_duplicate_field() {
        let tmp_dir = tempdir().expect("Failed setting up temp directory.");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config/");
        let indexfile = config_dir.join("index.yaml");

        let mut f = std::fs::File::create(&indexfile)
            .expect("Failed to create index file");
            
        let erronous_index = "---
        files:
            file1.md:
                title: File 1
                followups: [file2.md]
                keywords: [example, first]
                links: [subdir/file3.md]
        files: foo
        timestamp:
            secs_since_epoch: 1543078763
            nanos_since_epoch: 449322318";
            write!(f, "{}", erronous_index).expect("Failed to write to file");
        
        let index = Index::from_file(indexfile);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("duplicate field `files`"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_from_file_invalid_type() {
        let tmp_dir = tempdir().expect("Failed setting up temp directory.");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config/");
        let indexfile = config_dir.join("index.yaml");

        let mut f = std::fs::File::create(&indexfile)
            .expect("Failed to create index file");
        
        let erronous_index = "---
        files: foo
        timestamp:
            secs_since_epoch: 1543078763
            nanos_since_epoch: 449322318";
        write!(f, "{}", erronous_index).expect("Failed to write to file");
        
        let index = Index::from_file(indexfile);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("invalid type"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_from_file_unknown_field() {
        let tmp_dir = tempdir().expect("Failed setting up temp directory.");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config/");
        let indexfile = config_dir.join("index.yaml");

        let mut f = std::fs::File::create(&indexfile)
            .expect("Failed to create index file");
        
        let erronous_index = "---
        files:
            file1.md:
                title: File 1
                followups: [file2.md]
                keywords: [example, first]
                links: [subdir/file3.md]
        timestamp:
            secs_since_epoc: 1543078763
            nanos_since_epoch: 449322318";
        write!(f, "{}", erronous_index).expect("Failed to write to file");
        
        let index = Index::from_file(indexfile);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("unknown field"));
                assert!(message.contains("expected `secs_since_epoch`"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }

    #[test]
    fn test_index_from_file_invalid_value() {
        let tmp_dir = tempdir().expect("Failed setting up temp directory.");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config/");
        let indexfile = config_dir.join("index.yaml");

        let mut f = std::fs::File::create(&indexfile)
            .expect("Failed to create index file");
        
        let erronous_index = "---
        files:
            file1.md:
                title: File 1
                followups: [file2.md]
                keywords: [example, first]
                links: [subdir/file3.md]
        timestamp:
            secs_since_epoch: 1543078763
            nanos_since_epoch: 44932231800000000";
        write!(f, "{}", erronous_index).expect("Failed to write to file");
        
        let index = Index::from_file(indexfile);
        assert!(index.is_err());
        let e = index.unwrap_err();
        match e {
            Error::Yaml(inner) => {
                let message = inner.to_string();
                assert!(message.contains("invalid value"));
                assert!(message.contains("expected u32"));
            },
            _ => panic!("Expected a Yaml error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_to_file_non_existing_path() {
        let tmp_dir = tempdir().expect("Failed setting up temp directory.");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir).expect("Failed to generate examples");
        let config_dir = dir.join("examples/config/");
        let indexfile = config_dir.join("nonexisting_dir/foo"); //doesn't exist
        let index = Index::empty();
        let result = index.to_file(indexfile);
        assert!(result.is_err());
        let e = result.unwrap_err();
        match e {
            Error::Io(inner) => {
                match inner.kind() {
                    std::io::ErrorKind::NotFound => {
                        assert!(inner.to_string().contains("No such file or directory"));
                    },
                    _ => panic!("Expected a NotFound error, got: {:#?}", inner)
                }
            },
            _ => panic!("Expected a Io error, got: {:#?}", e),
        }
    }
    
    #[test]
    fn test_index_remove_zettel_not_contained() {
        let mut index = Index {
            files: std::collections::BTreeMap::new(),
            timestamp: std::time::SystemTime::now(),
        };
        let key = std::path::PathBuf::from("non_existing_zettel.md");
        let rz = index.remove_zettel(key);
        assert!(rz.is_none());
    }
    
    #[test]
    fn test_index_get_mut_zettel_none() {
        use std::collections::BTreeMap;
        use std::time::SystemTime;
        use std::path::PathBuf;
        let mut index = Index {
            files: BTreeMap::new(),
            timestamp: SystemTime::now(),
        };
        let nz = index.get_mut_zettel(PathBuf::from("non_existing_zettel.md"));
        assert!(nz.is_none());
    }
    
    fn sequence_test_index() -> Index {
        let mut index = Index::empty();
        let mut f1 = Zettel::new("File 1");
        let mut f2 = Zettel::new("File 2");
        let mut f3 = Zettel::new("File 3");
        let mut f4 = Zettel::new("File 4");
        let f5 = Zettel::new("File 5");
        let mut f6 = Zettel::new("File 6");
        let mut f7 = Zettel::new("File 7");
        
        f1.add_keyword("example");
        f3.add_keyword("foo");
        f4.add_keyword("bar");
        f7.add_keyword("baz");
        
        f1.add_followup("file2.md");
        f2.add_followup("file3.md");
        f2.add_followup("file4.md");
        f3.add_followup("file5.md");
        f4.add_followup("file5.md"); // double parentage for this test
        f4.add_followup("file6.md");
        f6.add_followup("file7.md");
        
        index.add_zettel("file1.md", f1);
        index.add_zettel("file2.md", f2);
        index.add_zettel("file3.md", f3);
        index.add_zettel("file4.md", f4);
        index.add_zettel("file5.md", f5);
        index.add_zettel("file6.md", f6);
        index.add_zettel("file7.md", f7);
        index
    }
    
    #[test]
    fn test_sequence_tree() {
        let index = sequence_test_index();
        let mut scope = HashSet::new();
        scope.insert(PathBuf::from("file4.md"));
        scope.insert(PathBuf::from("file6.md"));
        
        let stn = querying::sequences::sequence_tree(&index, &scope);
        assert_eq!(stn.len(), 6);
        assert!(stn.contains(&PathBuf::from("file1.md")));
        assert!(stn.contains(&PathBuf::from("file2.md")));
        assert!(stn.contains(&PathBuf::from("file4.md")));
        assert!(stn.contains(&PathBuf::from("file5.md")));
        assert!(stn.contains(&PathBuf::from("file6.md")));
        assert!(stn.contains(&PathBuf::from("file7.md")));
    }
    
    #[test]
    fn test_inspect_links() {
        let tmp_dir = tempdir().expect("Failed setting up temp directory.");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir)
                .expect("Failed to generate examples");
        let file_path = dir.join("examples/config/index.yaml");
        let index = Index::from_file(&file_path)
                .expect("Failed to load index.");
        
        // We want the links of one Zettel: file1.md
        let mut linkers = HashSet::new();
        linkers.insert(PathBuf::from("file1.md"));
        let links = index.inspect_links(&linkers);
        
        assert_eq!(links.len(), 2);
        assert!(links.contains(&PathBuf::from("file2.md")));
        assert!(links.contains(&PathBuf::from("file3.md")));
    }
    
    #[test]
    fn test_sequence_tree_whole() {
        let tmp_dir = tempdir().expect("Failed setting up temp directory.");
        let dir = tmp_dir.path();
        generate_examples_with_index(dir)
                .expect("Failed to generate examples");
        let file_path = dir.join("examples/config/index.yaml");
        let index = Index::from_file(&file_path)
                .expect("Failed to load index.");
        
        let mut scope = HashSet::new();
        scope.insert(PathBuf::from("file1.md"));
        let sequence_tree = index.sequence_tree_whole(&scope);
        assert_eq!(sequence_tree.len(), 5);
        assert!(sequence_tree.contains(&PathBuf::from("file1.md")));
        assert!(sequence_tree.contains(&PathBuf::from("file2.md")));
        assert!(sequence_tree.contains(&PathBuf::from("file3.md")));
        assert!(sequence_tree.contains(&PathBuf::from("subdir/file4.md")));
        assert!(sequence_tree.contains(&PathBuf::from("subdir/file5.md")));
    }
}