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
//! Collects `tp-note`'s configuration from a configuration file,
//! the command-line parameters. It also reads the clipboard.

extern crate clipboard;
use crate::MESSAGE_ALERT_WINDOW_TITLE;
use crate::VERSION;
use anyhow::anyhow;
use clipboard::ClipboardContext;
use clipboard::ClipboardProvider;
use lazy_static::lazy_static;
use msgbox::IconType;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;
use std::process;
use structopt::StructOpt;

/// Name of this executable (without ".exe" extension on Windows).
const CURRENT_EXE: &str = "tp-note";

/// File extension of `to-note` files.
const NOTE_EXTENSION: &str = "md";

/// Maximum length of a note's filename in bytes. If a filename-template produces
/// a longer string, it will be truncated.
#[cfg(not(test))]
pub const NOTE_FILENAME_LEN_MAX: usize = 250;
#[cfg(test)]
pub const NOTE_FILENAME_LEN_MAX: usize = 10;

/// Default filename-template to test, if the filename of an existing note file on
/// disk, corresponds to the note's meta data stored in its front matter. If
/// it is not the case, the note's filename will be renamed.
/// Can be modified through editing the configuration file.
/// Useful variables in this context are:
/// `{{ sort_tag | path }}`
/// `{{ title | path }}`, `{{ subtitle | path }}`, `{{ note_extension | path }}`,
/// All variables also exist in a `{{ <var>| path(alpha) }}` variant: in case
/// its value starts with a number, the string is prepended with `'`.
/// `{{ sort_tag | path }}` must be the first in line here, then followed by a
/// `{{ <var>| path(alpha) }}` variable.
/// Note, that in this filename-template, all variables must be filtered
/// by a `path` or `path(alpha=true)` filter.
const TMPL_SYNC_FILENAME: &str = "\
{{ sort_tag | path }}{% if sort_tag | path != '' %}-{% endif %}\
{{ title | path(alpha=true) }}{% if subtitle | path != '' %}--{% endif %}\
{{ subtitle | path  }}.{{ note_extension | path }}\
";

/// Default content-template used when the command-line argument <path> is a
/// directory. Can be changed through editing the configuration file.
/// The following variables are  defined:
/// `{{ dirname }}`, `{{ file_stem }}`, `{{ extension }}`, `{{ note-extension }}`
/// `{{ sort_tag }}`, `{{ username }}`, `{{ date }}`, `{{ lang }}`,
/// `{{ path }}`.
/// In addition all environment variables can be used, e.g.
/// `{{ get_env(name=\"LOGNAME\") }}`
/// When placed in YAML-front-matter, the filter `| json_encode` must be
/// appended to each variable.
const TMPL_NEW_CONTENT: &str = "\
---
title:      {{ dirname | json_encode }}
subtitle:   {{ 'Note' | json_encode }}
author:     {{ username | json_encode }}
date:       {{ now() | date(format='%Y-%m-%d') | json_encode }}
lang:       {{ get_env(name='LANG', default='') | json_encode }}
revision:   {{ '1.0' | json_encode }}
---


";

/// Default filename-template for a new note file on disk. It satisfies the
/// sync criteria for note-meta data in front-matter and filename.
/// Useful variables in this context are:
/// `{{ title| path }}`, `{{ subtitle| path }}`, `{{ note_extension| path }}`,
/// All variables also exist in a `{{ <var>| path(alpha) }}` variant: in case
/// its value starts with a number, the string is prepended with `'`.
/// The first non-numerical variable must be some `{{ <var>| path(alpha) }}`
/// variant.
/// Note, that in this filename-template, all variables must be filtered
/// by a `path` or `path(alpha=true)` filter.
const TMPL_NEW_FILENAME: &str = "\
{{ now() | date(format='%Y%m%d') }}-\
{{ title | path(alpha=true) }}{% if subtitle | path != '' %}--{% endif %}\
{{ subtitle | path  }}.{{ note_extension | path }}\
";

/// Default template used, when the clipboard contains a string.
/// The clipboards content is in `{{ clipboard }}`, its truncated version
/// in `{{ clipboard_heading }}`
/// When the clipboard conains a hyper-link in markdown format: [<link-name>](<link-url>),
/// its first part is stored in `{{ clipboard-linkname }}`, the second part in
/// `{{ clipboard-linkurl }}`. 
/// The following variables are defined:
/// `{{ dirname }}`, `{{ file_stem }}`, `{{ extension }}`, `{{ note-extension }}`
/// `{{ path }}`, `{{ sort_tag }}`, `{{ username }}`.
/// In addition all environment variables can be used, e.g.
/// `{{ get_env(name=\"LOGNAME\") }}`
/// When placed in YAML-front-matter, the filter `| json_encode` must be
/// appended to each variable.
const TMPL_CLIPBOARD_CONTENT: &str = "\
---
{% if clipboard_linkname !='' %}title:      {{ clipboard_linkname | json_encode }}
subtitle:   {{ 'URL' | json_encode }}
{% else %}title:      {{ clipboard_heading | json_encode }}
subtitle:   {{ 'Note' | json_encode }}
{% endif %}author:     {{ username | json_encode }}
date:       {{ now() | date(format='%Y-%m-%d') | json_encode }}
lang:       {{ get_env(name='LANG', default='') | json_encode }}
revision:   {{ '1.0' | json_encode }}
---

{{ clipboard }}

";

/// Default filename template used when the clipboard contains a string.
/// Useful variables in this context are:
/// `{{ title| path }}`, `{{ subtitle| path }}`, `{{ note_extension| path }}`,
/// `{{ year| path }}`, `{{ month| path }}`. `{{ day| path }}`.
/// All variables also exist in a `{{ <var>| path(alpha) }}` variant: in case
/// its value starts with a number, the string is prepended with `'`.
/// The first non-numerical variable must be some `{{ <var>| path(alpha) }}`
/// variant.
/// Note, that in this filename-template, all variables must be filtered
/// by a `path` or `path(alpha=true)` filter.
const TMPL_CLIPBOARD_FILENAME: &str = "\
{{ now() | date(format='%Y%m%d') }}-\
{{ title | path(alpha=true) }}{% if subtitle | path != '' %}--{% endif %}\
{{ subtitle | path  }}.{{ note_extension | path }}\
";

/// Default template used when the command-line <path> parameter points to
/// an existing non-`.md`-file. Can be modified through editing
/// the configuration file.
/// The following variables are  defined:
/// `{{ dirname }}`, `{{ file_stem }}`, `{{ extension }}`, `{{ note-extension }}`
/// `{{ sort_tag }}`, `{{ username }}`, `{{ lang }}`,
/// `{{ path }}`.
/// In addition all environment variables can be used, e.g.
/// `{{ get_env(name=\"LOGNAME\") }}`
/// When placed in YAML-front-matter, the filter `| json_encode` must be
/// appended to each variable.
const TMPL_ANNOTATE_CONTENT: &str = "\
---
title:      {{ sort_tag ~ file_stem | json_encode }}
subtitle:   {{ 'Note' | json_encode }}
author:     {{ username | json_encode }}
date:       {{ now() | date(format='%Y-%m-%d') | json_encode }}
lang:       {{ get_env(name='LANG', default='') | json_encode }}
revision:   {{ '1.0' | json_encode }}
---

[{{ sort_tag ~ file_stem ~ '.' ~ extension }}\
]({{ sort_tag ~ file_stem ~ '.' ~ extension }})

";

/// Filename of a new note, that annotates an existing file on disk given in
/// <path>.
/// Useful variables are:
/// `{{ title | path(alpha=true) }}`, `{{ subtitle | path }}`, `{{ note_extension | path }}`.
/// All variables also exist in a `{{ <var>| path(alpha) }}` variant: in case
/// its value starts with a number, the string is prepended with `'`.
/// The first non-numerical variable must be the `{{ <var>| path(alpha) }}`
/// variant.
/// Note, that in this filename-template, all variables must be filtered
/// by a `path` or `path(alpha=true)` filter.
const TMPL_ANNOTATE_FILENAME: &str = "\
{{ title | path(alpha=true) }}{% if subtitle | path != '' %}--{% endif %}\
{{ subtitle | path  }}.{{ note_extension | path }}\
";

/// Default command-line argument list when launching external editor.
/// The editor list is executed item by item until an editor is found.
/// Can be changed in config file.
#[cfg(target_family = "unix")]
const EDITOR_ARGS: &[&[&str]] = &[
    &[&"typora"],
    &[&"code", &"-w", &"-n"],
    &[&"atom", &"-w"],
    &[&"retext"],
    &[&"geany", &"-s", &"-i", &"-m"],
    &[&"gedit", &"-w"],
    &[&"mousepad"],
    &[&"leafpad"],
    &[&"nvim-qt", &"--nofork"],
    &[&"gvim", &"--nofork"],
    &[&"nano"],
    &[&"nvim"],
    &[&"vim"],
    &[&"vi"],
];
#[cfg(target_family = "windows")]
const EDITOR_ARGS: &[&[&str]] = &[
    &[&"C:\\Program Files\\Typora\\Typora.exe"],
    &[
        "C:\\Program Files\\Notepad++\\notepad++.exe",
        "-nosession",
        "-multiInst",
    ],
    &[&"C:\\Windows\\notepad.exe"],
];
// Some info about lauching programs on iOS:
//[dshell.pdf](https://www.stata.com/manuals13/dshell.pdf)
#[cfg(target_os = "ios")]
const EDITOR_ARGS: &[&[&str]] = &[&[&"/Applications/TextEdit.app/Contents/MacOS/TextEdit"]];

/// Default command-line argument list when launching external viewer
/// with `--view`. Can be changed in config file.
/// The viewer list is executed item by item until an editor is found.
#[cfg(target_family = "unix")]
const VIEWER_ARGS: &[&[&str]] = &[
    &[&"typora"],
    &[&"code", &"-w", &"-n"],
    &[&"atom", &"-w"],
    &[&"retext"],
    &[&"geany", &"-r", &"-s", &"-i", &"-m"],
    &[&"gedit", &"-w"],
    &[&"mousepad"],
    &[&"leafpad"],
    &[&"nvim-qt", &"--nofork", &"-R"],
    &[&"gvim", &"--nofork", &"-R"],
    &[&"nvim", &"-R"],
    &[&"nano"],
    &[&"nvim", &"-R"],
    &[&"vim", &"-R"],
    &[&"vi", &"-R"],
];
#[cfg(target_family = "windows")]
const VIEWER_ARGS: &[&[&str]] = &[
    &[&"C:\\Program Files\\Typora\\Typora.exe"],
    &[
        "C:\\Program Files\\Notepad++\\notepad++.exe",
        "-nosession",
        "-multiInst",
        "-ro",
    ],
    &[&"C:\\Windows\\notepad.exe"],
];
// Some info about lauching programs on iOS:
//[dshell.pdf](https://www.stata.com/manuals13/dshell.pdf)
#[cfg(target_os = "ios")]
const VIEWER_ARGS: &[&[&str]] = &[&[&"/Applications/TextEdit.app/Contents/MacOS/TextEdit"]];

/// By default clipboard support is enabled, can be disabled
/// in config file. A false value here will set ENABLE_EMPTY_CLIPBOARD to
/// false.
const ENABLE_READ_CLIPBOARD: bool = true;

/// Should the clipboard be emptied when tp-note closes?
/// Default value.
const ENABLE_EMPTY_CLIPBOARD: bool = true;

/// Limit the size of clipboard data `tp-note` accepts as input.
const CLIPBOARD_LEN_MAX: usize = 0x8000;

/// Defines the maximum length of the template variables `{{ clipboard_truncated }}` and `{{
/// clipboard_linkname }}` which are usually used to in the note's front matter as title.  The
/// title should not be too long, because it will end up as part of the file-name when the note is
/// saved to disk. Filenames of some operating systems are limited to 255 bytes.
#[cfg(not(test))]
const CLIPBOARD_TRUNCATED_LEN_MAX: usize = 200;
#[cfg(test)]
const CLIPBOARD_TRUNCATED_LEN_MAX: usize = 10;

#[derive(Debug, PartialEq, StructOpt)]
#[structopt(
    name = "Tp-Note",
    about = "Fast note taking with templates and filename synchronization."
)]
/// `tp-note` is a note-taking-tool and a template system, that consistently
/// synchronizes the note's meta-data with its filename. `tp-note` collects
/// various information about its environment and the clipboard and stores them
/// in variables. New notes are created by filling these variables in predefined
/// and customizable `Tera`-templates. In case `<path>` points to an existing
/// `tp-note`-file, the note's meta-data is analysed and, if necessary, its
/// filename is modified. For all other file types, `tp-note` creates a new note
/// that annotates the file `<path>` points to. If `<path>` is a directory (or,
/// when omitted the current working directory), a new note is created in that
/// directory. After creation, `tp-note` launches an external editor of your
/// choice. Although the note's structure follows `pandoc`-conventions, it is not
/// tied to any specific markup language.
pub struct Args {
    /// Batch made: does not launch editor or viewer
    #[structopt(long, short = "b")]
    pub batch: bool,
    /// Loads alternative configuration file
    #[structopt(long, short = "c")]
    pub config: Option<String>,
    /// Debug: shows templates and its variables
    #[structopt(long, short = "d")]
    pub debug: bool,
    /// Launches editor in read-only mode
    #[structopt(long, short = "v")]
    pub view: bool,
    /// <dir> as new note location or <file> to annotate
    #[structopt(name = "PATH", parse(from_os_str))]
    pub path: Option<PathBuf>,
    /// Prints version and exit
    #[structopt(long, short = "V")]
    pub version: bool,
}

lazy_static! {
/// Structure to hold the parsed command-line arguments.
pub static ref ARGS : Args = Args::from_args();
}

/// Configuration data, deserialized from the configuration-file.
#[derive(Debug, Serialize, Deserialize)]
pub struct Cfg {
    pub note_extension: String,
    pub tmpl_new_content: String,
    pub tmpl_new_filename: String,
    pub tmpl_clipboard_content: String,
    pub tmpl_clipboard_filename: String,
    pub tmpl_annotate_content: String,
    pub tmpl_annotate_filename: String,
    pub tmpl_sync_filename: String,
    pub editor_args: Vec<Vec<String>>,
    pub viewer_args: Vec<Vec<String>>,
    pub enable_read_clipboard: bool,
    pub enable_empty_clipboard: bool,
}

/// When no configuration-file is found, defaults are set here from built-in
/// constants. These defaults are then serialized into a newly created
/// configuration file on disk.
impl ::std::default::Default for Cfg {
    fn default() -> Self {
        Cfg {
            note_extension: NOTE_EXTENSION.to_string(),
            tmpl_new_content: TMPL_NEW_CONTENT.to_string(),
            tmpl_new_filename: TMPL_NEW_FILENAME.to_string(),
            tmpl_clipboard_content: TMPL_CLIPBOARD_CONTENT.to_string(),
            tmpl_clipboard_filename: TMPL_CLIPBOARD_FILENAME.to_string(),
            tmpl_annotate_content: TMPL_ANNOTATE_CONTENT.to_string(),
            tmpl_annotate_filename: TMPL_ANNOTATE_FILENAME.to_string(),
            tmpl_sync_filename: TMPL_SYNC_FILENAME.to_string(),
            editor_args: EDITOR_ARGS
                .iter()
                .map(|i| i.iter().map(|a| (*a).to_string()).collect())
                .collect(),
            viewer_args: VIEWER_ARGS
                .iter()
                .map(|i| i.iter().map(|a| (*a).to_string()).collect())
                .collect(),
            enable_read_clipboard: ENABLE_READ_CLIPBOARD,
            enable_empty_clipboard: ENABLE_EMPTY_CLIPBOARD,
        }
    }
}

lazy_static! {
    /// Reads and parses the configuration file "tp-note.toml". An alternative
    /// filename (optionally with absolute path) can be given on the command line
    /// with "--config".
    pub static ref CFG: Cfg =
        confy::load::<Cfg>(PathBuf::from(
            if let Some(c) = &ARGS.config {
                c
            } else {
                CURRENT_EXE
            })
            // strip extension, ".toml" is added by `confy.load()`
            .with_extension("")
            .to_str()
            .unwrap_or_default()
        ).unwrap_or_else(|e| {
            print_message(&format!("Application error: \
                unable to load/write config file: {}", e));
            process::exit(1)
        });
}

lazy_static! {
    /// Reads the clipboard and empties it.
    pub static ref CLIPBOARD: Clipboard = {
        if CFG.enable_read_clipboard {
            let ctx: Option<ClipboardContext> = ClipboardProvider::new().ok();
            if ctx.is_some() {
                let ctx = &mut ctx.unwrap(); // This is ok since `is_some()`
                let s = ctx.get_contents().ok();
                if let Some(s) = &s {
                    if s.len() > CLIPBOARD_LEN_MAX {
                        print_message(&format!(
                            "Warning: clipboard content ignored because its size \
                            exceeds {} bytes.", CLIPBOARD_LEN_MAX));
                        return Clipboard::default();
                    }
                };
                Clipboard::new(&s.unwrap_or_default())
            } else {
                Clipboard::default()
            }
        } else {
            Clipboard::default()
        }
    };

}

#[derive(Debug, PartialEq)]
/// Represents the clipboard content.
pub struct Clipboard {
    /// Raw content sting.
    pub content: String,
    /// Shortened content string (max CLIPBOARD_SHORT_LEN_MAX).
    pub content_truncated: String,
    /// First sentence (all characters until the first period)
    /// or all characters until the first empty line.
    /// If none is found take the whole `content_truncated`.
    pub content_heading: String,
    /// Namepart of the Markdown link. Empty if none.
    pub linkname: String,
    /// URL part of the Markdown link. Empty if none.
    pub linkurl: String,
}

impl Clipboard {
    pub fn new(content: &str) -> Self {
        let content: String = content.trim_start().to_string();

        // Limit the size of `clipboard_truncated`
        let mut content_truncated = String::new();
        for i in (0..CLIPBOARD_TRUNCATED_LEN_MAX).rev() {
            if let Some(s) = content.get(..i) {
                content_truncated = s.to_string();
                break;
            }
        }

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

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

        // parse clipboard
        let hyperlink = match Hyperlink::new(&content) {
            Ok(s) => Some(s),
            Err(e) => {
                if ARGS.debug {
                    eprintln!("Note: clipboard does not contain a markdown link: {}", e);
                }
                None
            }
        };

        let mut linkname = String::new();
        let mut linkurl = String::new();
        // if there is a hyperlink in clipboard?
        if let Some(hyperlink) = hyperlink {
            linkname = hyperlink.name.to_owned();
            linkurl = hyperlink.url.to_owned();
        };

        // Limit the size of `linkname`
        for i in (0..CLIPBOARD_TRUNCATED_LEN_MAX).rev() {
            if let Some(s) = linkname.get(..i) {
                linkname = s.to_string();
                break;
            }
        }

        Self {
            content,
            content_truncated,
            content_heading,
            linkname,
            linkurl,
        }
    }
}

impl ::std::default::Default for Clipboard {
    fn default() -> Self {
        Self {
            content: "".to_string(),
            content_truncated: "".to_string(),
            content_heading: "".to_string(),
            linkname: "".to_string(),
            linkurl: "".to_string(),
        }
    }
}

#[derive(Debug, PartialEq)]
/// Represents a hyperlink.
pub struct Hyperlink {
    pub name: String,
    pub url: String,
}

impl Hyperlink {
    /// Parse a markdown formatted hyperlink and stores the result in `Self`.
    pub fn new(input: &str) -> Result<Hyperlink, anyhow::Error> {
        // parse input_linkname
        let name_start = input
            .find('[')
            .ok_or_else(|| anyhow!(format!("no `[` in \"{}\"", input)))?
            + 1;

        let mut bracket_counter = 1;
        let name_end = input[name_start..]
            .find(|c: char| {
                if c == '[' {
                    bracket_counter += 1;
                } else if c == ']' {
                    bracket_counter -= 1;
                };
                bracket_counter == 0
            })
            .ok_or_else(|| anyhow!(format!("no closing`]` in \"{}\"", input)))?
            + name_start;

        // parse input_linkurl
        if input[name_end + 1..].chars().next().unwrap_or('x') != '(' {
            return Err(anyhow!(format!("no `](` in \"{}\"", input)));
        };
        let url_start = name_end + 2;
        let mut bracket_counter = 1;
        let url_end = input[url_start..]
            .find(|c: char| {
                if c == '(' {
                    bracket_counter += 1;
                } else if c == ')' {
                    bracket_counter -= 1;
                };
                bracket_counter == 0
            })
            .ok_or_else(|| anyhow!(format!("no closing `)` in \"{}\"", input)))?
            + url_start;

        Ok(Hyperlink {
            name: input[name_start..name_end].to_string(),
            url: input[url_start..url_end].to_string(),
        })
    }
}

/// Pops up a message box and prints `msg`.
pub fn print_message(msg: &str) {
    let title = format!(
        "{} (v{})",
        MESSAGE_ALERT_WINDOW_TITLE,
        VERSION.unwrap_or("unknown")
    );
    // Print the same message also to console in case
    // the window does not pop up due to missing
    // libraries.
    print_message_console(msg);
    // Popup window.
    msgbox::create(&title, msg, IconType::Info);
}

/// Prints `msg` on console.
pub fn print_message_console(msg: &str) {
    let title = format!(
        "{} (v{})",
        MESSAGE_ALERT_WINDOW_TITLE,
        VERSION.unwrap_or("unknown")
    );
    // Print the same message also to console in case
    // the window does not pop up due to missing
    // libraries.
    eprintln!("{}\n\n{}", title, msg);
}

#[cfg(test)]
mod tests {
    use super::Clipboard;
    use super::Hyperlink;

    #[test]
    fn test_clipboard() {
        // Test Markdown link in clipboard.
        let input = "[Jens Getreu's blog](https://blog.getreu.net)";
        let output = Clipboard::new(input);
        // This string is shortened.
        assert_eq!("Jens Getr", output.linkname);
        assert_eq!("https://blog.getreu.net", output.linkurl);
        assert_eq!(
            "[Jens Getreu's blog](https://blog.getreu.net)",
            output.content
        );

        //
        // Test non-link string in clipboard.
        let input = "Tp-Note helps you to quickly get\
            started writing notes.";
        let output = Clipboard::new(input);

        assert_eq!("", output.linkname);
        assert_eq!("", output.linkurl);
        assert_eq!(
            "Tp-Note helps you to quickly get\
            started writing notes.",
            output.content
        );
        // This string is shortened.
        assert_eq!("Tp-Note h", output.content_truncated);

        //
        // Test find heading.
        let input = "N.ote. It helps. Get quickly\
            started writing notes.";
        let output = Clipboard::new(input);

        assert_eq!("", output.linkname);
        assert_eq!("", output.linkurl);
        assert_eq!(
            "N.ote. It helps. Get quickly\
            started writing notes.",
            output.content
        );
        // This string is shortened.
        assert_eq!("N.ote", output.content_heading);

        //
        // Test find first sentence.
        let input = "N.ote.\nIt helps. Get quickly\
            started writing notes.";
        let output = Clipboard::new(input);
        // This string is shortened.
        assert_eq!("N.ote", output.content_heading);

        //
        // Test find first sentence (Windows)
        let input = "N.ote.\r\nIt helps. Get quickly\
            started writing notes.";
        let output = Clipboard::new(input);
        // This string is shortened.
        assert_eq!("N.ote", output.content_heading);

        //
        // Test find heading
        let input = "N.ote\n\nIt helps. Get quickly\
            started writing notes.";
        let output = Clipboard::new(input);
        // This string is shortened.
        assert_eq!("N.ote", output.content_heading);

        //
        // Test find heading (Windows)
        let input = "N.ote\r\n\r\nIt helps. Get quickly\
            started writing notes.";
        let output = Clipboard::new(input);
        // This string is shortened.
        assert_eq!("N.ote", output.content_heading);

        //
        // Test trim whitespace 
        let input = "\r\n\r\n  \tIt helps. Get quickly\
            started writing notes.";
        let output = Clipboard::new(input);
        // This string is shortened.
        assert_eq!("It helps.", output.content_heading);
    }

    #[test]
    fn test_parse_hyperlink() {
        // Regular link
        let input = "xxx[Homepage](https://blog.getreu.net)";
        let expected_output = Hyperlink {
            name: "Homepage".to_string(),
            url: "https://blog.getreu.net".to_string(),
        };
        let output = Hyperlink::new(input);
        assert_eq!(expected_output, output.unwrap());

        // URL with ()
        let input = "xxx[Homepage](https://blog.getreu.net/(main))";
        let expected_output = Hyperlink {
            name: "Homepage".to_string(),
            url: "https://blog.getreu.net/(main)".to_string(),
        };
        let output = Hyperlink::new(input);
        assert_eq!(expected_output, output.unwrap());

        //
        // link with () in name
        let input = "[Homepage (my first)](https://getreu.net)";
        let expected_output = Hyperlink {
            name: "Homepage (my first)".to_string(),
            url: "https://getreu.net".to_string(),
        };
        let output = Hyperlink::new(input);
        assert_eq!(expected_output, output.unwrap());

        //
        // link with [] in name
        let input = "[Homepage [my first]](https://getreu.net)";
        let expected_output = Hyperlink {
            name: "Homepage [my first]".to_string(),
            url: "https://getreu.net".to_string(),
        };
        let output = Hyperlink::new(input);
        assert_eq!(expected_output, output.unwrap());

        //
        // link with [ in name
        let input = "[Homepage [my first](https://getreu.net)";
        let output = Hyperlink::new(input);
        assert!(output.is_err());

        //
        // link with only []
        let input = "[Homepage (my first)]";
        let output = Hyperlink::new(input);
        assert!(output.is_err());
    }
}