tpnote-lib 0.44.1

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
//! Tp-Note's low level API, creating a memory representation of a
//! note file by inserting Tp-Note's
//! environment data in some templates. If the note exists on disk already,
//! the memory representation is established be reading the note file and
//! parsing its front matter.
//! NB: The high level API is in the module `tpnote_lib::workflow`.

use crate::config::TMPL_VAR_DOC;
use crate::content::Content;
use crate::context::Context;
use crate::context::HasSettings;
use crate::context::ReadyForContentTemplate;
use crate::context::ReadyForFilenameTemplate;
use crate::error::NoteError;
use crate::filename::NotePath;
use crate::filename::NotePathBuf;
use crate::filter::TERA;
use crate::front_matter::FrontMatter;
use crate::note_error_tera_template;
use crate::template::TemplateKind;
use std::default::Default;
use std::fs;
use std::path::{Path, PathBuf};
use std::str;
use tera::Tera;

/// This constant is used by Tera as template name for `tera::render_str()`.
/// Unfortunately it is private there, this is why we must redefine it here.
pub(crate) const ONE_OFF_TEMPLATE_NAME: &str = "__tera_one_off";

//#[derive(Debug, PartialEq)]
/// Represents a note.
/// 1. The `ContentString`'s header is deserialized into `FrontMatter`.
/// 2. `FrontMatter` is stored in `Context` with some environment data.
/// 3. `Context` data is filled in some filename template.
/// 4. The result is stored in `rendered_filename`.
pub struct Note<T: Content> {
    /// Captured environment of _Tp-Note_ that
    /// is used to fill in templates.
    pub context: Context<ReadyForFilenameTemplate>,
    /// The full text content of the note, including
    /// its front matter.
    pub content: T,
    /// This field equals to `PathBuf::new()` until `self.render_filename()`
    /// is called.
    pub rendered_filename: PathBuf,
}

impl<T: Content> Note<T> {
    /// Constructor creating a `Note` memory representation of some content
    /// that exists outside of Tp-Note provided by the `content` object. No file
    /// content is read from disk.
    ///
    /// In case of `TemplateKind::SyncFilename` the `content` is required to
    /// have a header with front matter.
    ///
    /// Contract: `template_kind` must be one of:
    /// * `TemplateKind::SyncFilename`,
    /// * `TemplateKind::None` or
    ///
    /// Panics otherwise. Use `Note::from_content_template()` in those cases.
    ///
    pub fn from_existing_content(
        context: Context<HasSettings>,
        content: T,
        template_kind: TemplateKind,
    ) -> Result<Note<T>, NoteError> {
        // Check contract.
        debug_assert!(match template_kind {
            TemplateKind::SyncFilename => true,

            TemplateKind::None => true,
            _ => panic!(
                "Contract violation: `template_kind=={:?}` is not acceptable here.",
                template_kind
            ),
        });

        // Deserialize the note's header read from disk.
        // Store the front matter in the context for later use in templates.
        let fm = FrontMatter::try_from(content.header())?;
        let context = context.insert_front_matter(&fm);

        // This data comes from outside. We need additional checks here.
        context.assert_precoditions()?;

        Ok(Note {
            context,
            content,
            rendered_filename: PathBuf::new(),
        })
    }

    /// Constructor that creates a new note by filling in the content
    /// template `template` with the data read from `context`.
    /// The result is an initialized `self.content`.
    ///
    /// Contract: `template_kind` should be NOT one of:
    /// * `TemplateKind::SyncFilename`,
    /// * `TemplateKind::None`
    ///
    /// Panics if this is the case.
    ///
    pub fn from_content_template(
        context: Context<ReadyForContentTemplate>,
        template_kind: TemplateKind,
    ) -> Result<Note<T>, NoteError> {
        // Add content to context.
        log::trace!(
            "Available substitution variables for the content template:\n{:#?}",
            *context
        );

        debug_assert!(match template_kind {
            TemplateKind::SyncFilename => panic!("`TemplateKind::SyncFilename` not allowed here"),

            TemplateKind::None => panic!("`TemplateKind::None` not allowed here"),
            _ => true,
        });

        // Render template
        let new_content: T = T::from_string(
            {
                let mut tera = Tera::default();
                tera.extend(&TERA)?;

                // Panics, if the content template does not exist (see contract).
                // Returns an error, when the rendition goes wrong.
                tera.render_str(&template_kind.get_content_template(), &context)
                    .map_err(|e| {
                        note_error_tera_template!(
                            e,
                            template_kind.get_content_template_name().to_string()
                        )
                    })?
            },
            TMPL_VAR_DOC.to_string(),
        );

        log::debug!(
            "Rendered content template:\n---\n{}\n---\n\n{}",
            new_content.header(),
            new_content.body()
        );

        // Deserialize the rendered template
        let fm = FrontMatter::try_from(new_content.header())?;

        let new_context = Context::from_context_path(&context).insert_front_matter(&fm);

        // Return new note.
        Ok(Note {
            context: new_context,
            content: new_content,
            rendered_filename: PathBuf::new(),
        })
    }

    /// Applies a Tera template to the notes context in order to generate a
    /// sanitized filename that is in sync with the note's meta data stored in
    /// its front matter.
    pub fn render_filename(&mut self, template_kind: TemplateKind) -> Result<(), NoteError> {
        log::trace!(
            "Available substitution variables for the filename template:\n{:#?}",
            *self.context
        );
        // Render template
        let mut file_path = self.context.get_dir_path().to_owned();
        let mut tera = Tera::default();
        tera.extend(&TERA)?;

        match tera.render_str(&template_kind.get_filename_template(), &self.context) {
            Ok(filename) => {
                file_path.push(filename.trim());
            }
            Err(e) => {
                return Err(note_error_tera_template!(
                    e,
                    template_kind.get_filename_template_name().to_string()
                ));
            }
        }

        file_path.shorten_filename();
        self.rendered_filename = file_path;
        Ok(())
    }

    /// Checks if `self.rendered_filename` is taken already.
    /// If yes, some copy counter is appended/incremented.
    /// Contract: `render_filename` must have been executed before.
    pub fn set_next_unused_rendered_filename(&mut self) -> Result<(), NoteError> {
        debug_assert_ne!(self.rendered_filename, PathBuf::new());

        self.rendered_filename.set_next_unused()?;
        Ok(())
    }

    /// Checks if `alt_path` is equal to `self.rendered_filename`
    /// without considering their copy counter.
    /// If they are similar, `self.rendered_filename` becomes `alt_path`.
    /// If they are different, then we continue incrementing the copy
    /// counter in `self.rendered_filename` until we find a free spot.
    /// (Same as in `set_next_unused_rendered_filename()`).
    /// Contract: `render_filename` must have been executed before.
    pub fn set_next_unused_rendered_filename_or(
        &mut self,
        alt_path: &Path,
    ) -> Result<(), NoteError> {
        debug_assert_ne!(self.rendered_filename, PathBuf::new());

        if self.rendered_filename.exclude_copy_counter_eq(alt_path) {
            self.rendered_filename = alt_path.to_path_buf();
        } else {
            self.rendered_filename.set_next_unused()?;
        }
        Ok(())
    }

    /// Writes the note to disk using the note's `content` and the note's
    /// `rendered_filename`.
    pub fn save(&self) -> Result<(), NoteError> {
        debug_assert_ne!(self.rendered_filename, PathBuf::new());

        log::trace!(
            "Writing the note's content to file: {:?}",
            self.rendered_filename
        );
        self.content.save_as(&self.rendered_filename)?;
        Ok(())
    }

    /// Rename the file `from_path` to `self.rendered_filename`.
    /// Silently fails is source and target are identical.
    /// Contract: `render_filename` must have been executed before.
    pub fn rename_file_from(&self, from_path: &Path) -> Result<(), NoteError> {
        debug_assert_ne!(self.rendered_filename, PathBuf::new());

        if !from_path.exclude_copy_counter_eq(&self.rendered_filename) {
            // Rename file
            fs::rename(from_path, &self.rendered_filename)?;
            log::trace!(
                "File renamed to {}",
                self.rendered_filename.to_str().unwrap_or_default()
            );
        }
        Ok(())
    }

    /// Write the note to disk and remove the file at the previous location.
    /// Similar to `rename_from()`, but the target is replaced by `self.content`.
    /// Silently fails is source and target are identical.
    /// Contract: `render_filename` must have been executed before.
    pub fn save_and_delete_from(&mut self, from_path: &Path) -> Result<(), NoteError> {
        debug_assert_ne!(self.rendered_filename, PathBuf::new());

        self.save()?;
        if from_path != self.rendered_filename {
            log::trace!("Deleting file: {:?}", from_path);
            fs::remove_file(from_path)?;
        }
        Ok(())
    }

    #[inline]
    /// Renders `self.content` to HTML by calling the appropriate markup
    /// renderer. The `html_tmpl` injects JavaScript code with the
    /// key `TMPL_HTML_VAR_VIEWER_DOC_JS`. This code is provided with
    /// `viewer_doc_js`.
    ///
    /// Contract:
    /// * `self.context` is in a valid `ReadyForFilenameTemplate` state.
    /// * `self.content.body_name == TMPL_VAR_DOC`. The HTML template expects
    ///   this name.
    /// * The `html_tmpl` template expects `content` to have a header with:
    ///   a `title:` field.
    ///
    pub fn render_content_to_html(
        &self,
        // HTML template for this rendition.
        tmpl: &str,
        // JavaScript for live update code injection.
        viewer_doc_js: &str,
    ) -> Result<String, NoteError> {
        //
        let html_context = self.context.clone();

        let html_context = html_context.insert_raw_content_and_css(&self.content, viewer_doc_js);

        log::trace!(
            "Available substitution variables for the HTML template:\
            \n{:#?}",
            html_context
        );

        let mut tera = Tera::default();
        tera.extend(&TERA)?;
        // Switch `autoescape_on()` only for HTML templates.
        tera.autoescape_on(vec![ONE_OFF_TEMPLATE_NAME]);
        let html = tera.render_str(tmpl, &html_context).map_err(|e| {
            note_error_tera_template!(e, "[html_tmpl] viewer/exporter_tmpl ".to_string())
        })?;

        Ok(html)
    }
}

#[cfg(test)]
mod tests {
    use super::Context;
    use super::FrontMatter;
    use crate::config::TMPL_VAR_FM_ALL;
    use serde_json::json;
    use std::path::Path;
    use tera::Value;

    #[test]
    fn test_deserialize() {
        let input = "# document start
        title:     The book
        subtitle:  you always wanted
        author:    It's me
        date:      2020-04-21
        lang:      en
        revision:  '1.0'
        sort_tag:  20200420-21_22
        file_ext:  md
        height:    1.23
        count:     2
        neg:       -1
        flag:      true
        numbers:
          - 1
          - 3
          - 5
        ";

        let mut expected = tera::Map::new();
        expected.insert("title".to_string(), Value::String("The book".to_string()));
        expected.insert(
            "subtitle".to_string(),
            Value::String("you always wanted".to_string()),
        );
        expected.insert("author".to_string(), Value::String("It\'s me".to_string()));
        expected.insert("date".to_string(), Value::String("2020-04-21".to_string()));
        expected.insert("lang".to_string(), Value::String("en".to_string()));
        expected.insert("revision".to_string(), Value::String("1.0".to_string()));
        expected.insert(
            "sort_tag".to_string(),
            Value::String("20200420-21_22".to_string()),
        );
        expected.insert("file_ext".to_string(), Value::String("md".to_string()));
        expected.insert("height".to_string(), json!(1.23)); // Number()
        expected.insert("count".to_string(), json!(2)); // Number()
        expected.insert("neg".to_string(), json!(-1)); // Number()
        expected.insert("flag".to_string(), json!(true)); // Bool()
        expected.insert("numbers".to_string(), json!([1, 3, 5])); // Array()

        let expected_front_matter = FrontMatter(expected);

        //panic!("{:?}", &expected_front_matter);
        assert_eq!(expected_front_matter, FrontMatter::try_from(input).unwrap());
    }

    #[test]
    fn test_register_front_matter() {
        let mut tmp = tera::Map::new();
        tmp.insert("file_ext".to_string(), Value::String("md".to_string())); // String
        tmp.insert("height".to_string(), json!(1.23)); // Number()
        tmp.insert("count".to_string(), json!(2)); // Number()
        tmp.insert("neg".to_string(), json!(-1)); // Number()
        tmp.insert("flag".to_string(), json!(true)); // Bool()
        tmp.insert("numbers".to_string(), json!([1, 3, 5])); // Array([Numbers()..])!
        let mut tmp2 = tera::Map::new();
        tmp2.insert("fm_file_ext".to_string(), Value::String("md".to_string())); // String
        tmp2.insert("fm_height".to_string(), json!(1.23)); // Number()
        tmp2.insert("fm_count".to_string(), json!(2)); // Number()
        tmp2.insert("fm_neg".to_string(), json!(-1)); // Number()
        tmp2.insert("fm_flag".to_string(), json!(true)); // Bool()
        tmp2.insert("fm_numbers".to_string(), json!([1, 3, 5])); // Array([Numbers()..])!

        let input1 = Context::from(Path::new("a/b/test.md")).unwrap();
        let input2 = FrontMatter(tmp);

        let mut expected = Context::from(Path::new("a/b/test.md")).unwrap();
        tmp2.remove("fm_numbers");
        tmp2.insert("fm_numbers".to_string(), json!([1, 3, 5])); // String()!
        let tmp2 = tera::Value::from(tmp2);
        expected.insert(TMPL_VAR_FM_ALL, &tmp2); // Map()
        let expected = expected.insert_front_matter(&FrontMatter::try_from("").unwrap());

        let result = input1.insert_front_matter(&input2);

        assert_eq!(result, expected);
    }

    #[test]
    fn test_from_existing_content1() {
        //
        // Example with `TemplateKind::SyncFilename`
        //
        use crate::content::Content;
        use crate::content::ContentString;
        use crate::context::Context;
        use crate::note::Note;
        use crate::template::TemplateKind;
        use std::env::temp_dir;
        use std::fs;
        // Prepare test: create existing note.
        let raw = r#"---
title: "My day"
subtitle: "Note"
---
Body text
"#;
        let notefile = temp_dir().join("20221031-hello.md");
        fs::write(&notefile, raw.as_bytes()).unwrap();
        let expected = temp_dir().join("20221031-My day--Note.md");
        let _ = fs::remove_file(&expected);
        // Start test.
        let context = Context::from(&notefile).unwrap();
        // Create note object.
        let content = <ContentString as Content>::open(&notefile).unwrap();
        // You can plug in your own type (must impl. `Content`).
        let mut n = Note::<ContentString>::from_existing_content(
            context,
            content,
            TemplateKind::SyncFilename,
        )
        .unwrap();

        let path = n.context.get_path().to_owned();
        n.render_filename(TemplateKind::SyncFilename).unwrap();
        n.set_next_unused_rendered_filename_or(&path).unwrap();
        assert_eq!(n.rendered_filename, expected);
        // Rename file on the disk.
        n.rename_file_from(&path).unwrap();
        assert!(n.rendered_filename.is_file());
    }

    #[test]
    fn test_from_existing_content2() {
        // Example with `TemplateKind::None`
        //
        //    This constructor is called, when `Note` is solely created for
        // HTML rendering and no templates will be applied.
        //
        use crate::config::LIB_CFG;
        use crate::config::TMPL_HTML_VAR_VIEWER_DOC_JS;
        use crate::content::Content;
        use crate::content::ContentString;
        use crate::context::Context;
        use crate::note::Note;
        use crate::template::TemplateKind;
        use std::env::temp_dir;
        use std::fs;
        // Prepare test: create existing note file.
        let raw = r#"---
title: "My day"
subtitle: "Note"
---
Body text
"#;
        let notefile = temp_dir().join("20221030-My day--Note.md");
        fs::write(&notefile, raw.as_bytes()).unwrap();
        // Start test
        // Only minimal context is needed, because no templates are applied later.
        let mut context = Context::from(&notefile).unwrap();
        // We do not inject any JavaScript.
        context.insert(TMPL_HTML_VAR_VIEWER_DOC_JS, &"".into());
        // Create note object.
        let content = <ContentString as Content>::open(&notefile).unwrap();
        // You can plug in your own type (must impl. `Content`).
        let n: Note<ContentString> =
            Note::<ContentString>::from_existing_content(context, content, TemplateKind::None)
                .unwrap();
        // Check the HTML rendition.
        let html = n
            .render_content_to_html(&LIB_CFG.read_recursive().tmpl_html.viewer, "")
            .unwrap();
        assert!(html.starts_with("<!DOCTYPE html>\n<html"))
    }

    #[test]
    fn test_from_content_template1() {
        // Example with `TemplateKind::New`
        //
        use crate::content::Content;
        use crate::content::ContentString;
        use crate::context::Context;
        use crate::note::Note;
        use crate::settings::Settings;
        use crate::settings::SETTINGS;
        use crate::template::TemplateKind;
        use parking_lot::RwLockWriteGuard;
        use std::env::temp_dir;
        use std::fs;

        // Prepare test.
        let mut settings = SETTINGS.write();
        *settings = Settings::default();
        // This locks `SETTINGS` for further write access in this scope.
        let _settings = RwLockWriteGuard::<'_, _>::downgrade(settings);
        // Create a directory for the new note.
        let notedir = temp_dir().join("123-my dir/");
        fs::create_dir_all(&notedir).unwrap();

        // Store the path in `context`.
        let context = Context::from(&notedir).unwrap();
        let html_clipboard =
            ContentString::from_string("".to_string(), "html_clipboard".to_string());
        let txt_clipboard = ContentString::from_string("".to_string(), "txt_clipboard".to_string());
        let stdin = ContentString::from_string("".to_string(), "stdin".to_string());
        let v = vec![&html_clipboard, &txt_clipboard, &stdin];
        let context = context
            .insert_front_matter_and_raw_text_from_existing_content(&v)
            .unwrap()
            .set_state_ready_for_content_template();

        // Create the `Note` object.
        // You can plug in your own type (must impl. `Content`).
        let mut n =
            Note::<ContentString>::from_content_template(context, TemplateKind::FromDir).unwrap();
        assert!(n.content.header().starts_with("title:        my dir"));
        assert_eq!(n.content.borrow_dependent().body, "\n\n");

        // Check the title and subtitle in the note's header.
        assert_eq!(
            n.context
                .get(TMPL_VAR_FM_ALL)
                .unwrap()
                .get("fm_title")
                .unwrap()
                .as_str(),
            Some("my dir")
        );
        assert_eq!(
            n.context
                .get(TMPL_VAR_FM_ALL)
                .unwrap()
                .get("fm_subtitle")
                .unwrap()
                .as_str(),
            Some("Note")
        );
        n.render_filename(TemplateKind::FromDir).unwrap();
        n.set_next_unused_rendered_filename().unwrap();
        n.save().unwrap();

        // Check the created new note file.
        assert!(n.rendered_filename.is_file());
        let raw_note = fs::read_to_string(n.rendered_filename).unwrap();
        #[cfg(not(target_family = "windows"))]
        assert!(raw_note.starts_with("\u{feff}---\ntitle:        my dir"));
        #[cfg(target_family = "windows")]
        assert!(raw_note.starts_with("\u{feff}---\r\ntitle:        my dir"));
    }

    #[test]
    fn test_from_content_template2() {
        // Example with `TemplateKind::FromClipboard`

        use crate::content::Content;
        use crate::content::ContentString;
        use crate::context::Context;
        use crate::note::Note;
        use crate::settings::Settings;
        use crate::settings::SETTINGS;
        use crate::template::TemplateKind;
        use parking_lot::RwLockWriteGuard;
        use std::env::temp_dir;
        use std::fs;

        // Prepare test.
        let mut settings = SETTINGS.write();
        *settings = Settings::default();
        // This locks `SETTINGS` for further write access in this scope.
        let _settings = RwLockWriteGuard::<'_, _>::downgrade(settings);
        // Directory for the new note.
        let notedir = temp_dir();

        // Store the path in `context`.
        let context = Context::from(&notedir).unwrap();
        let html_clipboard =
            ContentString::from_string("html_clp\n".to_string(), "html_clipboard".to_string());
        let txt_clipboard =
            ContentString::from_string("txt_clp\n".to_string(), "txt_clipboard".to_string());
        let stdin = ContentString::from_string("std\n".to_string(), "stdin".to_string());
        let v = vec![&html_clipboard, &txt_clipboard, &stdin];
        let context = context
            .insert_front_matter_and_raw_text_from_existing_content(&v)
            .unwrap();

        // This is the condition to choose: `TemplateKind::FromClipboard`:
        assert!(
            html_clipboard.header().is_empty()
                && txt_clipboard.header().is_empty()
                && stdin.header().is_empty()
        );
        assert!(
            !html_clipboard.body().is_empty()
                && !txt_clipboard.body().is_empty()
                && !stdin.body().is_empty()
        );

        let context = context.set_state_ready_for_content_template();

        // Create the `Note` object.
        // You can plug in your own type (must impl. `Content`).
        let mut n =
            Note::<ContentString>::from_content_template(context, TemplateKind::FromDir).unwrap();
        let expected_body = "\nstd\ntxt_clp\n\n";
        assert_eq!(n.content.body(), expected_body);
        // Check the title and subtitle in the note's header.
        assert_eq!(
            n.context
                .get(TMPL_VAR_FM_ALL)
                .unwrap()
                .get("fm_title")
                .unwrap()
                .as_str(),
            Some("std")
        );

        assert_eq!(
            n.context
                .get(TMPL_VAR_FM_ALL)
                .unwrap()
                .get("fm_subtitle")
                .unwrap()
                .as_str(),
            Some("Note")
        );
        n.render_filename(TemplateKind::FromDir).unwrap();
        n.set_next_unused_rendered_filename().unwrap();
        n.save().unwrap();

        // Check the new note file.
        // println!("{:?}", n.rendered_filename);
        assert!(n
            .rendered_filename
            .as_os_str()
            .to_str()
            .unwrap()
            .contains("std--Note"));
        assert!(n.rendered_filename.is_file());
        let raw_note = fs::read_to_string(&n.rendered_filename).unwrap();
        println!("{}", raw_note);
        #[cfg(not(target_family = "windows"))]
        assert!(raw_note.starts_with("\u{feff}---\ntitle:        std"));
        #[cfg(target_family = "windows")]
        assert!(raw_note.starts_with("\u{feff}---\r\ntitle:"));
    }

    #[test]
    fn test_from_content_template3() {
        // Example with `TemplateKind::FromClipboardYaml`

        use crate::content::Content;
        use crate::content::ContentString;
        use crate::context::Context;
        use crate::note::Note;
        use crate::settings::Settings;
        use crate::settings::SETTINGS;
        use crate::template::TemplateKind;
        use parking_lot::RwLockWriteGuard;
        use std::env::temp_dir;
        use std::fs;

        // Prepare test.
        let mut settings = SETTINGS.write();
        *settings = Settings::default();
        // This locks `SETTINGS` for further write access in this scope.
        let _settings = RwLockWriteGuard::<'_, _>::downgrade(settings);
        // Directory for the new note.
        let notedir = temp_dir().join("123-my dir/");

        // Run test.
        // Store the path in `context`.
        let context = Context::from(&notedir).unwrap();
        let html_clipboard = ContentString::from_string(
            "my HTML clipboard\n".to_string(),
            "html_clipboard".to_string(),
        );
        let txt_clipboard = ContentString::from_string(
            "my TXT clipboard\n".to_string(),
            "txt_clipboard".to_string(),
        );
        let stdin = ContentString::from_string(
            "---\nsubtitle: \"this overwrites\"\n---\nstdin body".to_string(),
            "stdin".to_string(),
        );
        let v = vec![&html_clipboard, &txt_clipboard, &stdin];

        let context = context
            .insert_front_matter_and_raw_text_from_existing_content(&v)
            .unwrap();
        // This is the condition to choose: `TemplateKind::FromClipboardYaml`:
        assert!(
            !html_clipboard.header().is_empty()
                || !txt_clipboard.header().is_empty()
                || !stdin.header().is_empty()
        );

        let context = context.set_state_ready_for_content_template();

        // Create the `Note` object.
        // You can plug in your own type (must impl. `Content`).
        let mut n =
            Note::<ContentString>::from_content_template(context, TemplateKind::FromDir).unwrap();
        let expected_body = "\nstdin body\nmy TXT clipboard\n\n";
        assert_eq!(n.content.body(), expected_body);
        // Check the title and subtitle in the note's header.
        assert_eq!(
            n.context
                .get(TMPL_VAR_FM_ALL)
                .unwrap()
                .get("fm_title")
                .unwrap()
                .as_str(),
            // Remember: in debug titles are very short. The code only works,
            // because the string is pure ASCII (not UTF-8).
            Some("stdin bod")
        );

        assert_eq!(
            n.context
                .get(TMPL_VAR_FM_ALL)
                .unwrap()
                .get("fm_subtitle")
                .unwrap()
                .as_str(),
            // Remember: in debug titles are very short. The code only works,
            // because the string is pure ASCII (not UTF-8).
            Some("this over")
        );
        n.render_filename(TemplateKind::FromDir).unwrap();
        n.set_next_unused_rendered_filename().unwrap();
        n.save().unwrap();

        // Check the new note file.
        //println!("rendered_filename == {:?}", n.rendered_filename);
        assert!(n
            .rendered_filename
            .as_os_str()
            .to_str()
            .unwrap()
            .contains("stdin bod--this over"));
        assert!(n.rendered_filename.is_file());
        let raw_note = fs::read_to_string(n.rendered_filename).unwrap();
        #[cfg(not(target_family = "windows"))]
        assert!(raw_note.starts_with("\u{feff}---\ntitle:        stdin bod"));
        #[cfg(target_family = "windows")]
        assert!(raw_note.starts_with("\u{feff}---\r\ntitle:        stdin bod"));
    }

    #[test]
    fn test_from_content_template4() {
        // Example with `TemplateKind::AnnotateFile`

        use crate::content::Content;
        use crate::content::ContentString;
        use crate::context::Context;
        use crate::note::Note;
        use crate::settings::Settings;
        use crate::settings::SETTINGS;
        use crate::template::TemplateKind;
        use parking_lot::RwLockWriteGuard;
        use std::env::temp_dir;
        use std::fs;

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

        // Create some non-Tp-Note-file.
        let raw = "This simulates a non tp-note file";
        let non_notefile = temp_dir().join("20221030-some.pdf");
        fs::write(&non_notefile, raw.as_bytes()).unwrap();
        let expected = temp_dir().join("20221030-some.pdf--Note.md");
        let _ = fs::remove_file(&expected);

        // Run the test.
        // Store the path in `context`.
        let context = Context::from(&non_notefile).unwrap();
        let html_clipboard = ContentString::from_string(
            "my HTML clipboard\n".to_string(),
            "html_clipboard".to_string(),
        );
        let txt_clipboard = ContentString::from_string(
            "my TXT clipboard\n".to_string(),
            "txt_clipboard".to_string(),
        );
        let stdin =
            ContentString::from_string_with_cr("my stdin\n".to_string(), "stdin".to_string());
        let v = vec![&html_clipboard, &txt_clipboard, &stdin];

        let context = context
            .insert_front_matter_and_raw_text_from_existing_content(&v)
            .unwrap()
            .set_state_ready_for_content_template();

        // Create the `Note` object.
        // You can plug in your own type (must impl. `Content`).
        let mut n =
            Note::<ContentString>::from_content_template(context, TemplateKind::AnnotateFile)
                .unwrap();
        let expected_body =
            "\n[20221030-some.pdf](<20221030-some.pdf>)\n____\n\nmy stdin\nmy TXT clipboard\n\n";
        assert_eq!(n.content.body(), expected_body);
        // Check the title and subtitle in the note's header.
        assert_eq!(
            n.context
                .get(TMPL_VAR_FM_ALL)
                .unwrap()
                .get("fm_title")
                .unwrap()
                .as_str(),
            Some("some.pdf")
        );
        assert_eq!(
            n.context
                .get(TMPL_VAR_FM_ALL)
                .unwrap()
                .get("fm_subtitle")
                .unwrap()
                .as_str(),
            Some("Note")
        );

        n.render_filename(TemplateKind::AnnotateFile).unwrap();
        n.set_next_unused_rendered_filename().unwrap();
        n.save().unwrap();

        // Check the new note file.
        assert_eq!(n.rendered_filename, expected);
        fs::remove_file(n.rendered_filename).unwrap();
    }

    #[test]
    fn test_from_existing_content5() {
        //
        // Example with `TemplateKind::FromTextFile`
        //
        use crate::content::Content;
        use crate::content::ContentString;
        use crate::context::Context;
        use crate::note::Note;
        use crate::template::TemplateKind;
        use std::env::temp_dir;
        use std::fs;

        // Prepare test: create existing note file without header.
        let raw = "Body text without header";
        let notefile = temp_dir().join("20221030-hello -- world.md");
        let _ = fs::write(&notefile, raw.as_bytes());
        let expected = temp_dir().join("20221030-hello--world.md");
        let _ = fs::remove_file(&expected);
        // Start test.
        let context = Context::from(&notefile).unwrap();
        // Create note object.
        let content = <ContentString as Content>::open(&notefile).unwrap();
        let context = context
            .insert_front_matter_and_raw_text_from_existing_content(&vec![&content])
            .unwrap()
            .set_state_ready_for_content_template();
        // You can plug in your own type (must impl. `Content`).
        let mut n = Note::<ContentString>::from_content_template(
            context.clone(),
            TemplateKind::FromTextFile,
        )
        .unwrap();
        assert!(!n.content.header().is_empty());
        assert_eq!(
            n.context
                .get(TMPL_VAR_FM_ALL)
                .unwrap()
                .get("fm_title")
                .unwrap()
                .as_str(),
            Some("hello ")
        );
        assert_eq!(
            n.context
                .get(TMPL_VAR_FM_ALL)
                .unwrap()
                .get("fm_subtitle")
                .unwrap()
                .as_str(),
            Some(" world")
        );
        assert_eq!(n.content.body().trim(), raw);
        n.render_filename(TemplateKind::FromTextFile).unwrap();
        n.set_next_unused_rendered_filename().unwrap();
        n.save_and_delete_from(context.get_path()).unwrap();

        // Check the new file with header
        assert_eq!(&n.rendered_filename, &expected);
        assert!(n.rendered_filename.is_file());
        let raw_note = fs::read_to_string(n.rendered_filename).unwrap();
        #[cfg(not(target_family = "windows"))]
        assert!(raw_note.starts_with("\u{feff}---\ntitle:        'hello '"));
        #[cfg(target_family = "windows")]
        assert!(raw_note.starts_with("\u{feff}---\r\ntitle:        'hello '"));
    }
}