-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathhtml.rs
More file actions
1917 lines (1719 loc) · 66.4 KB
/
html.rs
File metadata and controls
1917 lines (1719 loc) · 66.4 KB
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
//! Helper functions dealing with HTML conversion.
use crate::clone_ext::CloneExt;
use crate::error::InputStreamError;
use crate::filename::{NotePath, NotePathStr};
use crate::{config::LocalLinkKind, error::NoteError};
use html_escape;
use parking_lot::RwLock;
use parse_hyperlinks::parser::Link;
use parse_hyperlinks_extras::iterator_html::HtmlLinkInlineImage;
use percent_encoding::percent_decode_str;
use std::path::MAIN_SEPARATOR_STR;
use std::{
borrow::Cow,
collections::HashSet,
path::{Component, Path, PathBuf},
sync::Arc,
};
pub(crate) const HTML_EXT: &str = ".html";
/// A local path can carry a format string at the end. This is the separator
/// character.
const FORMAT_SEPARATOR: char = '?';
/// If followed directly after FORMAT_SEPARATOR, it selects the sort-tag
/// for further matching.
const FORMAT_ONLY_SORT_TAG: char = '#';
/// If followed directly after FORMAT_SEPARATOR, it selects the whole filename
/// for further matching.
const FORMAT_COMPLETE_FILENAME: &str = "?";
/// A format string can be separated in a _from_ and _to_ part. This
/// optional separator is placed after `FORMAT_SEPARATOR` and separates
/// the _from_ and _to_ pattern.
const FORMAT_FROM_TO_SEPARATOR: char = ':';
/// If `rewrite_rel_path` and `dest` is relative, concatenate `docdir` and
/// `dest`, then strip `root_path` from the left before returning.
/// If not `rewrite_rel_path` and `dest` is relative, return `dest`.
/// If `rewrite_abs_path` and `dest` is absolute, concatenate and return
/// `root_path` and `dest`.
/// If not `rewrite_abs_path` and `dest` is absolute, return `dest`.
/// The `dest` portion of the output is always canonicalized.
/// Return the assembled path, when in `root_path`, or `None` otherwise.
/// Asserts in debug mode, that `doc_dir` is in `root_path`.
fn assemble_link(
root_path: &Path,
docdir: &Path,
dest: &Path,
rewrite_rel_paths: bool,
rewrite_abs_paths: bool,
) -> Option<PathBuf> {
///
/// Concatenate `path` and `append`.
/// The `append` portion of the output is if possible canonicalized.
/// In case of underflow of an absolute link, the returned path is empty.
fn append(path: &mut PathBuf, append: &Path) {
// Append `dest` to `link` and canonicalize.
for dir in append.components() {
match dir {
Component::ParentDir => {
if !path.pop() {
let path_is_relative = {
let mut c = path.components();
!(c.next() == Some(Component::RootDir)
|| c.next() == Some(Component::RootDir))
};
if path_is_relative {
path.push(Component::ParentDir.as_os_str());
} else {
path.clear();
break;
}
}
}
Component::Normal(c) => path.push(c),
_ => {}
}
}
}
// Under Windows `.is_relative()` does not detect `Component::RootDir`
let dest_is_relative = {
let mut c = dest.components();
!(c.next() == Some(Component::RootDir) || c.next() == Some(Component::RootDir))
};
// Check if the link points into `root_path`, reject otherwise
// (strip_prefix will not work).
debug_assert!(docdir.starts_with(root_path));
// Calculate the output.
let mut link = match (rewrite_rel_paths, rewrite_abs_paths, dest_is_relative) {
// *** Relative links.
// Result: "/" + docdir.strip(root_path) + dest
(true, false, true) => {
let link = PathBuf::from(Component::RootDir.as_os_str());
link.join(docdir.strip_prefix(root_path).ok()?)
}
// Result: docdir + dest
(true, true, true) => docdir.to_path_buf(),
// Result: dest
(false, _, true) => PathBuf::new(),
// *** Absolute links.
// Result: "/" + dest
(_, false, false) => PathBuf::from(Component::RootDir.as_os_str()),
// Result: "/" + root_path
(_, true, false) => root_path.to_path_buf(),
};
append(&mut link, dest);
if link.as_os_str().is_empty() {
None
} else {
Some(link)
}
}
trait Hyperlink {
/// A helper function, that first HTML escape decodes all strings of the
/// link. Then it percent decodes the link destination (and the
/// link text in case of an autolink).
fn decode_ampersand_and_percent(&mut self);
/// True if the value is a local link.
#[allow(clippy::ptr_arg)]
fn is_local_fn(value: &Cow<str>) -> bool;
/// * `Link::Text2Dest`: strips a possible scheme in local `dest`.
/// * `Link::Image2Dest`: strip local scheme in `dest`.
/// * `Link::Image`: strip local scheme in `src`.
///
/// No action if not local.
fn strip_local_scheme(&mut self);
/// Helper function that strips a possible scheme in `input`.
fn strip_scheme_fn(input: &mut Cow<str>);
/// True if the link is:
/// * `Link::Text2Dest` and the link text equals the link destination, or
/// * `Link::Image` and the links `alt` equals the link source.
///
/// WARNING: place this test after `decode_html_escape_and_percent()`
/// and before: `rebase_local_link`, `expand_shorthand_link`,
/// `rewrite_autolink` and `apply_format_attribute`.
fn is_autolink(&self) -> bool;
/// A method that converts the relative URLs (local links) in `self`.
/// If successful, it returns `Ok(Some(URL))`, otherwise
/// `Err(NoteError::InvalidLocalLink)`.
/// If `self` contains an absolute URL, no conversion is performed and the
/// return value is `Ok(())`.
///
/// Conversion details:
/// The base path for this conversion (usually where the HTML file resides),
/// is `docdir`. If not `rewrite_rel_links`, relative local links are not
/// converted. Furthermore, all local links starting with `/` are prepended
/// with `root_path`. All absolute URLs always remain untouched.
///
/// Algorithm:
/// 1. If `rewrite_abs_links==true` and `link` starts with `/`, concatenate
/// and return `root_path` and `dest`.
/// 2. If `rewrite_abs_links==false` and `dest` does not start wit `/`,
/// return `dest`.
/// 3. If `rewrite_ext==true` and the link points to a known Tp-Note file
/// extension, then `.html` is appended to the converted link.
///
/// Remark: The _anchor's text property_ is never changed. However, there
/// is one exception: when the text contains a URL starting with `http:` or
/// `https:`, only the file stem is kept. Example, the anchor text property:
/// `<a ...>http:dir/my file.md</a>` is rewritten into `<a ...>my file</a>`.
///
/// Contracts:
/// 1. `link` may have a scheme.
/// 2. `link` is `Link::Text2Dest` or `Link::Image`
/// 3. `root_path` and `docdir` are absolute paths to directories.
/// 4. `root_path` is never empty `""`. It can be `"/"`.
fn rebase_local_link(
&mut self,
root_path: &Path,
docdir: &Path,
rewrite_rel_paths: bool,
rewrite_abs_paths: bool,
) -> Result<(), NoteError>;
/// If `dest` in `Link::Text2Dest` contains only a sort
/// tag as filename, expand the latter to a full filename.
/// Otherwise, no action.
/// This method accesses the filesystem. Therefore sometimes `prepend_path`
/// is needed as parameter and prepended.
fn expand_shorthand_link(&mut self, prepend_path: Option<&Path>) -> Result<(), NoteError>;
/// This removes a possible scheme in `text`.
/// Call this method only when you sure that this
/// is an autolink by testing with `is_autolink()`.
fn rewrite_autolink(&mut self);
/// A formatting attribute is a format string starting with `?` followed
/// by one or two patterns. It is appended to `dest` or `src`.
/// Processing details:
/// 1. Extract some a possible formatting attribute string in `dest`
/// (`Link::Text2Dest`) or `src` (`Link::Image`) after `?`.
/// 2. Extract the _path_ before `?` in `dest` or `src`.
/// 3. Apply the formatting to _path_.
/// 4. Store the result by overwriting `text` or `alt`.
fn apply_format_attribute(&mut self);
/// If the link destination `dest` is a local path, return it.
/// Otherwise return `None`.
/// Acts on `Link:Text2Dest` and `Link::Imgage2Dest` only.
fn get_local_link_dest_path(&self) -> Option<&Path>;
/// If `dest` or `src` is a local path, return it.
/// Otherwise return `None`.
/// Acts an `Link:Image` and `Link::Image2Dest` only.
fn get_local_link_src_path(&self) -> Option<&Path>;
/// If the extension of a local path in `dest` is some Tp-Note
/// extension, append `.html` to the path. Otherwise silently return.
/// Acts on `Link:Text2Dest` only.
fn append_html_ext(&mut self);
/// Renders `Link::Text2Dest`, `Link::Image2Dest` and `Link::Image`
/// to HTML. Some characters in `dest` or `src` might be HTML
/// escape encoded. This does not percent encode at all, because
/// we know, that the result will be inserted later in a UTF-8 template.
fn to_html(&self) -> String;
}
impl Hyperlink for Link<'_> {
#[inline]
fn decode_ampersand_and_percent(&mut self) {
// HTML escape decode value.
fn dec_amp(val: &mut Cow<str>) {
let decoded_text = html_escape::decode_html_entities(val);
if matches!(&decoded_text, Cow::Owned(..)) {
// Does nothing, but satisfying the borrow checker. Does not `clone()`.
let decoded_text = Cow::Owned(decoded_text.into_owned());
// Store result.
let _ = std::mem::replace(val, decoded_text);
}
}
// HTML escape decode and percent decode value.
fn dec_amp_percent(val: &mut Cow<str>) {
dec_amp(val);
let decoded_dest = percent_decode_str(val.as_ref()).decode_utf8().unwrap();
if matches!(&decoded_dest, Cow::Owned(..)) {
// Does nothing, but satisfying the borrow checker. Does not `clone()`.
let decoded_dest = Cow::Owned(decoded_dest.into_owned());
// Store result.
let _ = std::mem::replace(val, decoded_dest);
}
}
match self {
Link::Text2Dest(text1, dest, title) => {
dec_amp(text1);
dec_amp_percent(dest);
dec_amp(title);
}
Link::Image(alt, src) => {
dec_amp(alt);
dec_amp_percent(src);
}
Link::Image2Dest(text1, alt, src, text2, dest, title) => {
dec_amp(text1);
dec_amp(alt);
dec_amp_percent(src);
dec_amp(text2);
dec_amp_percent(dest);
dec_amp(title);
}
_ => unimplemented!(),
};
}
//
fn is_local_fn(dest: &Cow<str>) -> bool {
!((dest.contains("://") && !dest.contains(":///"))
|| dest.starts_with("mailto:")
|| dest.starts_with("tel:"))
}
//
fn strip_local_scheme(&mut self) {
fn strip(dest: &mut Cow<str>) {
if <Link<'_> as Hyperlink>::is_local_fn(dest) {
<Link<'_> as Hyperlink>::strip_scheme_fn(dest);
}
}
match self {
Link::Text2Dest(_, dest, _title) => strip(dest),
Link::Image2Dest(_, _, src, _, dest, _) => {
strip(src);
strip(dest);
}
Link::Image(_, src) => strip(src),
_ => {}
};
}
//
fn strip_scheme_fn(inout: &mut Cow<str>) {
let output = inout
.trim_start_matches("https://")
.trim_start_matches("https:")
.trim_start_matches("http://")
.trim_start_matches("http:")
.trim_start_matches("tpnote:")
.trim_start_matches("mailto:")
.trim_start_matches("tel:");
if output != inout.as_ref() {
let _ = std::mem::replace(inout, Cow::Owned(output.to_string()));
}
}
//
fn is_autolink(&self) -> bool {
let (text, dest) = match self {
Link::Text2Dest(text, dest, _title) => (text, dest),
Link::Image(alt, source) => (alt, source),
// `Link::Image2Dest` is never an autolink.
_ => return false,
};
text == dest
}
//
fn rebase_local_link(
&mut self,
root_path: &Path,
docdir: &Path,
rewrite_rel_paths: bool,
rewrite_abs_paths: bool,
) -> Result<(), NoteError> {
let do_rebase = |path: &mut Cow<str>| -> Result<(), NoteError> {
if <Link as Hyperlink>::is_local_fn(path) {
let dest_out = assemble_link(
root_path,
docdir,
Path::new(path.as_ref()),
rewrite_rel_paths,
rewrite_abs_paths,
)
.ok_or(NoteError::InvalidLocalPath {
path: path.as_ref().to_string(),
})?;
// Store result.
let new_dest = Cow::Owned(dest_out.to_str().unwrap_or_default().to_string());
let _ = std::mem::replace(path, new_dest);
}
Ok(())
};
match self {
Link::Text2Dest(_, dest, _) => do_rebase(dest),
Link::Image2Dest(_, _, src, _, dest, _) => do_rebase(src).and_then(|_| do_rebase(dest)),
Link::Image(_, src) => do_rebase(src),
_ => unimplemented!(),
}
}
//
fn expand_shorthand_link(&mut self, prepend_path: Option<&Path>) -> Result<(), NoteError> {
let shorthand_link = match self {
Link::Text2Dest(_, dest, _) => dest,
Link::Image2Dest(_, _, _, _, dest, _) => dest,
_ => return Ok(()),
};
if !<Link as Hyperlink>::is_local_fn(shorthand_link) {
return Ok(());
}
let (shorthand_str, shorthand_format) = match shorthand_link.split_once(FORMAT_SEPARATOR) {
Some((path, fmt)) => (path, Some(fmt)),
None => (shorthand_link.as_ref(), None),
};
let shorthand_path = Path::new(shorthand_str);
if let Some(sort_tag) = shorthand_str.is_valid_sort_tag() {
let full_shorthand_path = if let Some(root_path) = prepend_path {
// Concatenate `root_path` and `shorthand_path`.
let shorthand_path = shorthand_path
.strip_prefix(MAIN_SEPARATOR_STR)
.unwrap_or(shorthand_path);
Cow::Owned(root_path.join(shorthand_path))
} else {
Cow::Borrowed(shorthand_path)
};
// Search for the file.
let found = full_shorthand_path
.parent()
.and_then(|dir| dir.find_file_with_sort_tag(sort_tag));
if let Some(path) = found {
// We prepended `root_path` before, we can safely strip it
// and unwrap.
let found_link = path
.strip_prefix(prepend_path.unwrap_or(Path::new("")))
.unwrap();
// Prepend `/`.
let mut found_link = Path::new(MAIN_SEPARATOR_STR)
.join(found_link)
.to_str()
.unwrap_or_default()
.to_string();
if let Some(fmt) = shorthand_format {
found_link.push(FORMAT_SEPARATOR);
found_link.push_str(fmt);
}
// Store result.
let _ = std::mem::replace(shorthand_link, Cow::Owned(found_link));
} else {
return Err(NoteError::CanNotExpandShorthandLink {
path: full_shorthand_path.to_string_lossy().into_owned(),
});
}
}
Ok(())
}
//
fn rewrite_autolink(&mut self) {
let text = match self {
Link::Text2Dest(text, _, _) => text,
Link::Image(alt, _) => alt,
_ => return,
};
<Link as Hyperlink>::strip_scheme_fn(text);
}
//
fn apply_format_attribute(&mut self) {
// Is this an absolute URL?
let (text, dest) = match self {
Link::Text2Dest(text, dest, _) => (text, dest),
Link::Image(alt, source) => (alt, source),
_ => return,
};
if !<Link as Hyperlink>::is_local_fn(dest) {
return;
}
// We assume, that `dest` had been expanded already, so we can extract
// the full filename here.
// If ever it ends with a format string we apply it. Otherwise we quit
// the method and do nothing.
let (path, format) = match dest.split_once(FORMAT_SEPARATOR) {
Some(s) => s,
None => return,
};
let mut short_text = Path::new(path)
.file_name()
.unwrap_or_default()
.to_str()
.unwrap_or_default();
// Select what to match:
let format = if format.starts_with(FORMAT_COMPLETE_FILENAME) {
// Keep complete filename.
format
.strip_prefix(FORMAT_COMPLETE_FILENAME)
.unwrap_or(format)
} else if format.starts_with(FORMAT_ONLY_SORT_TAG) {
// Keep only format-tag.
short_text = Path::new(path).disassemble().0;
format.strip_prefix(FORMAT_ONLY_SORT_TAG).unwrap_or(format)
} else {
// Keep only stem.
short_text = Path::new(path).disassemble().2;
format
};
match format.split_once(FORMAT_FROM_TO_SEPARATOR) {
// No `:`
None => {
if !format.is_empty()
&& let Some(idx) = short_text.find(format) {
short_text = &short_text[..idx];
};
}
// Some `:`
Some((from, to)) => {
if !from.is_empty()
&& let Some(idx) = short_text.find(from) {
short_text = &short_text[(idx + from.len())..];
};
if !to.is_empty()
&& let Some(idx) = short_text.find(to) {
short_text = &short_text[..idx];
};
}
}
// Store the result.
let _ = std::mem::replace(text, Cow::Owned(short_text.to_string()));
let _ = std::mem::replace(dest, Cow::Owned(path.to_string()));
}
//
fn get_local_link_dest_path(&self) -> Option<&Path> {
let dest = match self {
Link::Text2Dest(_, dest, _) => dest,
Link::Image2Dest(_, _, _, _, dest, _) => dest,
_ => return None,
};
if <Link as Hyperlink>::is_local_fn(dest) {
// Strip URL fragment.
match (dest.rfind('#'), dest.rfind(['/', '\\'])) {
(Some(n), sep) if sep.is_some_and(|sep| n > sep) || sep.is_none() => {
Some(Path::new(&dest.as_ref()[..n]))
}
_ => Some(Path::new(dest.as_ref())),
}
} else {
None
}
}
//
fn get_local_link_src_path(&self) -> Option<&Path> {
let src = match self {
Link::Image2Dest(_, _, src, _, _, _) => src,
Link::Image(_, src) => src,
_ => return None,
};
if <Link as Hyperlink>::is_local_fn(src) {
Some(Path::new(src.as_ref()))
} else {
None
}
}
//
fn append_html_ext(&mut self) {
let dest = match self {
Link::Text2Dest(_, dest, _) => dest,
Link::Image2Dest(_, _, _, _, dest, _) => dest,
_ => return,
};
if <Link as Hyperlink>::is_local_fn(dest) {
let path = dest.as_ref();
if path.has_tpnote_ext() {
let mut newpath = path.to_string();
newpath.push_str(HTML_EXT);
let _ = std::mem::replace(dest, Cow::Owned(newpath));
}
}
}
//
fn to_html(&self) -> String {
// HTML escape encode double quoted attributes
fn enc_amp(val: Cow<str>) -> Cow<str> {
let s = html_escape::encode_double_quoted_attribute(val.as_ref());
if s == val {
val
} else {
// No cloning happens here, because we own `s` already.
Cow::Owned(s.into_owned())
}
}
// Replace Windows backslash, then HTML escape encode.
fn repl_backspace_enc_amp(val: Cow<str>) -> Cow<str> {
let val = if val.as_ref().contains('\\') {
Cow::Owned(val.to_string().replace('\\', "/"))
} else {
val
};
let s = html_escape::encode_double_quoted_attribute(val.as_ref());
if s == val {
val
} else {
// No cloning happens here, because we own `s` already.
Cow::Owned(s.into_owned())
}
}
match self {
Link::Text2Dest(text, dest, title) => {
// Format title.
let title_html = if !title.is_empty() {
format!(" title=\"{}\"", enc_amp(title.shallow_clone()))
} else {
"".to_string()
};
format!(
"<a href=\"{}\"{}>{}</a>",
repl_backspace_enc_amp(dest.shallow_clone()),
title_html,
text
)
}
Link::Image2Dest(text1, alt, src, text2, dest, title) => {
// Format title.
let title_html = if !title.is_empty() {
format!(" title=\"{}\"", enc_amp(title.shallow_clone()))
} else {
"".to_string()
};
format!(
"<a href=\"{}\"{}>{}<img src=\"{}\" alt=\"{}\">{}</a>",
repl_backspace_enc_amp(dest.shallow_clone()),
title_html,
text1,
repl_backspace_enc_amp(src.shallow_clone()),
enc_amp(alt.shallow_clone()),
text2
)
}
Link::Image(alt, src) => {
format!(
"<img src=\"{}\" alt=\"{}\">",
repl_backspace_enc_amp(src.shallow_clone()),
enc_amp(alt.shallow_clone())
)
}
_ => unimplemented!(),
}
}
}
#[inline]
/// A helper function that scans the input HTML document in `html_input` for
/// HTML hyperlinks. When it finds a relative URL (local link), it analyzes it's
/// path. Depending on the `local_link_kind` configuration, relative local
/// links are converted into absolute local links and eventually rebased.
///
/// In order to achieve this, the user must respect the following convention
/// concerning absolute local links in Tp-Note documents:
/// 1. When a document contains a local link with an absolute path (absolute
/// local link), the base of this path is considered to be the directory
/// where the marker file ‘.tpnote.toml’ resides (or ‘/’ in non exists). The
/// marker file directory is `root_path`.
/// 2. Furthermore, the parameter `docdir` contains the absolute path of the
/// directory of the currently processed HTML document. The user guarantees
/// that `docdir` is the base for all relative local links in the document.
/// Note: `docdir` must always start with `root_path`.
///
/// If `LocalLinkKind::Off`, relative local links are not converted.
/// If `LocalLinkKind::Short`, relative local links are converted into an
/// absolute local links with `root_path` as base directory.
/// If `LocalLinkKind::Long`, in addition to the above, the resulting absolute
/// local link is prepended with `root_path`.
///
/// If `rewrite_ext` is true and a local link points to a known
/// Tp-Note file extension, then `.html` is appended to the converted link.
///
/// Remark: The link's text property is never changed. However, there is
/// one exception: when the link's text contains a string similar to URLs,
/// starting with `http:` or `tpnote:`. In this case, the string is interpreted
/// as URL and only the stem of the filename is displayed, e.g.
/// `<a ...>http:dir/my file.md</a>` is replaced with `<a ...>my file</a>`.
///
/// Finally, before a converted local link is reinserted in the output HTML, a
/// copy of that link is kept in `allowed_local_links` for further bookkeeping.
///
/// NB: All absolute URLs (starting with a domain) always remain untouched.
///
/// NB2: It is guaranteed, that the resulting HTML document contains only local
/// links to other documents within `root_path`. Deviant links displayed as
/// `INVALID LOCAL LINK` and URL is discarded.
pub fn rewrite_links(
html_input: String,
root_path: &Path,
docdir: &Path,
local_link_kind: LocalLinkKind,
rewrite_ext: bool,
allowed_local_links: Arc<RwLock<HashSet<PathBuf>>>,
) -> String {
let (rewrite_rel_paths, rewrite_abs_paths) = match local_link_kind {
LocalLinkKind::Off => (false, false),
LocalLinkKind::Short => (true, false),
LocalLinkKind::Long => (true, true),
};
// Search for hyperlinks and inline images in the HTML rendition
// of this note.
let mut rest = &*html_input;
let mut html_out = String::new();
for ((skipped, _consumed, remaining), mut link) in HtmlLinkInlineImage::new(&html_input) {
html_out.push_str(skipped);
rest = remaining;
// Check if `text` = `dest`.
let mut link_is_autolink = link.is_autolink();
// Percent decode link destination.
link.decode_ampersand_and_percent();
// Check again if `text` = `dest`.
link_is_autolink = link_is_autolink || link.is_autolink();
link.strip_local_scheme();
// Rewrite the local link.
match link
.rebase_local_link(root_path, docdir, rewrite_rel_paths, rewrite_abs_paths)
.and_then(|_| {
link.expand_shorthand_link(
(matches!(local_link_kind, LocalLinkKind::Short)).then_some(root_path),
)
}) {
Ok(()) => {}
Err(e) => {
let e = e.to_string();
let e = html_escape::encode_text(&e);
html_out.push_str(&format!("<i>{}</i>", e));
continue;
}
};
if link_is_autolink {
link.rewrite_autolink();
}
link.apply_format_attribute();
if let Some(dest_path) = link.get_local_link_dest_path() {
allowed_local_links.write().insert(dest_path.to_path_buf());
};
if let Some(src_path) = link.get_local_link_src_path() {
allowed_local_links.write().insert(src_path.to_path_buf());
};
if rewrite_ext {
link.append_html_ext();
}
html_out.push_str(&link.to_html());
}
// Add the last `remaining`.
html_out.push_str(rest);
log::trace!(
"Viewer: referenced allowed local files: {}",
allowed_local_links
.read_recursive()
.iter()
.map(|p| {
let mut s = "\n '".to_string();
s.push_str(&p.display().to_string());
s
})
.collect::<String>()
);
html_out
// The `RwLockWriteGuard` is released here.
}
/// This trait deals with tagged HTML `&str` data.
pub trait HtmlStr {
/// Lowercase pattern to check if this is a Doctype tag.
const TAG_DOCTYPE_PAT: &'static str = "<!doctype";
/// Lowercase pattern to check if this Doctype is HTML.
const TAG_DOCTYPE_HTML_PAT: &'static str = "<!doctype html";
/// Doctype HTML tag. This is inserted by
/// `<HtmlString>.prepend_html_start_tag()`
const TAG_DOCTYPE_HTML: &'static str = "<!DOCTYPE html>";
/// Pattern to check if f this is an HTML start tag.
const START_TAG_HTML_PAT: &'static str = "<html";
/// HTML end tag.
const END_TAG_HTML: &'static str = "</html>";
/// We consider `self` empty, when it equals to `<!DOCTYPE html...>` or
/// when it is empty.
fn is_empty_html(&self) -> bool;
/// We consider `html` empty, when it equals to `<!DOCTYPE html...>` or
/// when it is empty.
/// This is identical to `is_empty_html()`, but does not pull in
/// additional trait bounds.
fn is_empty_html2(html: &str) -> bool {
html.is_empty_html()
}
/// True if stream starts with `<!DOCTYPE html...>`.
fn has_html_start_tag(&self) -> bool;
/// True if `html` starts with `<!DOCTYPE html...>`.
/// This is identical to `has_html_start_tag()`, but does not pull in
/// additional trait bounds.
fn has_html_start_tag2(html: &str) -> bool {
html.has_html_start_tag()
}
/// Some heuristics to guess if the input stream contains HTML.
/// Current implementation:
/// True if:
///
/// * The stream starts with `<!DOCTYPE html ...>`, or
/// * the stream starts with `<html ...>`
///
/// This function does not check if the recognized HTML is valid.
fn is_html_unchecked(&self) -> bool;
}
impl HtmlStr for str {
fn is_empty_html(&self) -> bool {
if self.is_empty() {
return true;
}
let html = self
.trim_start()
.lines()
.next()
.map(|l| l.to_ascii_lowercase())
.unwrap_or_default();
html.as_str().starts_with(Self::TAG_DOCTYPE_HTML_PAT)
// The next closing bracket must be in last position.
&& html.find('>').unwrap_or_default() == html.len()-1
}
fn has_html_start_tag(&self) -> bool {
let html = self
.trim_start()
.lines()
.next()
.map(|l| l.to_ascii_lowercase());
html.as_ref()
.is_some_and(|l| l.starts_with(Self::TAG_DOCTYPE_HTML_PAT))
}
fn is_html_unchecked(&self) -> bool {
let html = self
.trim_start()
.lines()
.next()
.map(|l| l.to_ascii_lowercase());
html.as_ref().is_some_and(|l| {
(l.starts_with(Self::TAG_DOCTYPE_HTML_PAT)
&& l[Self::TAG_DOCTYPE_HTML_PAT.len()..].contains('>'))
|| (l.starts_with(Self::START_TAG_HTML_PAT)
&& l[Self::START_TAG_HTML_PAT.len()..].contains('>'))
})
}
}
/// This trait deals with tagged HTML `String` data.
pub trait HtmlString: Sized {
/// If the input does not start with `<!DOCTYPE html`
/// (or lowercase variants), then insert `<!DOCTYPE html>`.
/// Returns `InputStreamError::NonHtmlDoctype` if there is another Doctype
/// already.
fn prepend_html_start_tag(self) -> Result<Self, InputStreamError>;
}
impl HtmlString for String {
fn prepend_html_start_tag(self) -> Result<Self, InputStreamError> {
// Bring `HtmlStr` methods into scope.
use crate::html::HtmlStr;
let html2 = self
.trim_start()
.lines()
.next()
.map(|l| l.to_ascii_lowercase())
.unwrap_or_default();
if html2.starts_with(<str as HtmlStr>::TAG_DOCTYPE_HTML_PAT) {
// Has a start tag already.
Ok(self)
} else if !html2.starts_with(<str as HtmlStr>::TAG_DOCTYPE_PAT) {
// Insert HTML Doctype tag.
let mut html = self;
html.insert_str(0, <str as HtmlStr>::TAG_DOCTYPE_HTML);
Ok(html)
} else {
// There is a Doctype other than HTML.
Err(InputStreamError::NonHtmlDoctype {
html: self.chars().take(25).collect::<String>(),
})
}
}
}
#[cfg(test)]
mod tests {
use crate::error::InputStreamError;
use crate::error::NoteError;
use crate::html::Hyperlink;
use crate::html::assemble_link;
use crate::html::rewrite_links;
use parking_lot::RwLock;
use parse_hyperlinks::parser::Link;
use parse_hyperlinks_extras::parser::parse_html::take_link;
use std::borrow::Cow;
use std::{
collections::HashSet,
path::{Path, PathBuf},
sync::Arc,
};
#[test]
fn test_assemble_link() {
// `rewrite_rel_links=true`
let output = assemble_link(
Path::new("/my"),
Path::new("/my/doc/path"),
Path::new("../local/link to/note.md"),
true,
false,
)
.unwrap();
assert_eq!(output, Path::new("/doc/local/link to/note.md"));
// `rewrite_rel_links=false`
let output = assemble_link(
Path::new("/my"),
Path::new("/my/doc/path"),
Path::new("../local/link to/note.md"),
false,
false,
)
.unwrap();
assert_eq!(output, Path::new("../local/link to/note.md"));
// Absolute `dest`.
let output = assemble_link(
Path::new("/my"),
Path::new("/my/doc/path"),
Path::new("/test/../abs/local/link to/note.md"),
false,
false,
)
.unwrap();
assert_eq!(output, Path::new("/abs/local/link to/note.md"));
// Underflow.
let output = assemble_link(
Path::new("/my"),
Path::new("/my/doc/path"),
Path::new("/../local/link to/note.md"),
false,
false,
);
assert_eq!(output, None);
// Absolute `dest`, `rewrite_abs_links=true`.
let output = assemble_link(
Path::new("/my"),
Path::new("/my/doc/path"),
Path::new("/abs/local/link to/note.md"),
false,
true,
)
.unwrap();
assert_eq!(output, Path::new("/my/abs/local/link to/note.md"));
// Absolute `dest`, `rewrite_abs_links=false`.
let output = assemble_link(
Path::new("/my"),
Path::new("/my/doc/path"),
Path::new("/test/../abs/local/link to/note.md"),
false,
false,
)
.unwrap();
assert_eq!(output, Path::new("/abs/local/link to/note.md"));
// Absolute `dest`, `rewrite` both.
let output = assemble_link(
Path::new("/my"),
Path::new("/my/doc/path"),
Path::new("abs/local/link to/note.md"),
true,
true,
)
.unwrap();
assert_eq!(output, Path::new("/my/doc/path/abs/local/link to/note.md"));
}
#[test]
fn test_decode_html_escape_and_percent() {
//
let mut input = Link::Text2Dest(Cow::from("text"), Cow::from("dest"), Cow::from("title"));
let expected = Link::Text2Dest(Cow::from("text"), Cow::from("dest"), Cow::from("title"));
input.decode_ampersand_and_percent();
let output = input;
assert_eq!(output, expected);
//