forked from max-heller/mdbook-pandoc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlib.rs
1499 lines (1386 loc) · 51.1 KB
/
lib.rs
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
use std::{
collections::HashMap,
fs::{self, File},
};
use anyhow::{anyhow, Context as _};
use mdbook::config::HtmlConfig;
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
mod book;
use book::Book;
mod latex;
mod pandoc;
mod preprocess;
use preprocess::Preprocessor;
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct Config {
#[serde(rename = "profile")]
pub profiles: HashMap<String, pandoc::Profile>,
#[serde(default = "defaults::enabled")]
pub keep_preprocessed: bool,
pub hosted_html: Option<String>,
/// Code block related configuration.
#[serde(default = "Default::default")]
pub code: CodeConfig,
}
/// Configuration for tweaking how code blocks are rendered.
#[derive(Debug, Default, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
struct CodeConfig {
pub show_hidden_lines: bool,
}
mod defaults {
pub fn enabled() -> bool {
true
}
}
/// A [`mdbook`] backend supporting many output formats by relying on [`pandoc`](https://pandoc.org).
#[derive(Default)]
pub struct Renderer {
logfile: Option<File>,
}
impl Renderer {
pub fn new() -> Self {
Self { logfile: None }
}
const NAME: &'static str = "pandoc";
const CONFIG_KEY: &'static str = "output.pandoc";
}
impl mdbook::Renderer for Renderer {
fn name(&self) -> &str {
Self::NAME
}
fn render(&self, ctx: &mdbook::renderer::RenderContext) -> anyhow::Result<()> {
// If we're compiled against mdbook version I.J.K, require ^I.J
// This allows using a version of mdbook with an earlier patch version as a server
static MDBOOK_VERSION_REQ: Lazy<semver::VersionReq> = Lazy::new(|| {
let compiled_mdbook_version = semver::Version::parse(mdbook::MDBOOK_VERSION).unwrap();
semver::VersionReq {
comparators: vec![semver::Comparator {
op: semver::Op::Caret,
major: compiled_mdbook_version.major,
minor: Some(compiled_mdbook_version.minor),
patch: None,
pre: Default::default(),
}],
}
});
let mdbook_server_version = semver::Version::parse(&ctx.version).unwrap();
if !MDBOOK_VERSION_REQ.matches(&mdbook_server_version) {
log::warn!(
"{} is semver-incompatible with mdbook {} (requires {})",
env!("CARGO_PKG_NAME"),
mdbook_server_version,
*MDBOOK_VERSION_REQ,
);
}
let pandoc_version = pandoc::check_compatibility()?;
let cfg: Config = ctx
.config
.get_deserialized_opt(Self::CONFIG_KEY)
.with_context(|| format!("Unable to deserialize {}", Self::CONFIG_KEY))?
.ok_or(anyhow!("No {} table found", Self::CONFIG_KEY))?;
let html_cfg: Option<HtmlConfig> = ctx
.config
.get_deserialized_opt("output.html")
.unwrap_or_default();
let book = Book::new(ctx)?;
for (name, profile) in cfg.profiles {
let ctx = pandoc::RenderContext {
book: &book,
mdbook_cfg: &ctx.config,
pandoc: pandoc::Context::new(pandoc_version),
destination: book.destination.join(name),
output: profile.output_format(),
columns: profile.columns,
cur_list_depth: 0,
max_list_depth: 0,
code: &cfg.code,
html: html_cfg.as_ref(),
};
// Preprocess book
let mut preprocessor = Preprocessor::new(ctx)?;
if let Some(uri) = cfg.hosted_html.as_deref() {
preprocessor.hosted_html(uri);
}
if let Some(redirects) = html_cfg.as_ref().map(|cfg| &cfg.redirect) {
if !redirects.is_empty() {
log::info!("Processing redirects in [output.html.redirect]");
let redirects = redirects
.iter()
.map(|(src, dst)| (src.as_str(), dst.as_str()));
// In tests, sort redirect map to ensure stable log output
#[cfg(test)]
let redirects = redirects
.collect::<std::collections::BTreeMap<_, _>>()
.into_iter();
preprocessor.add_redirects(redirects);
}
}
let mut preprocessed = preprocessor.preprocess();
// Initialize renderer
let mut renderer = pandoc::Renderer::new();
// Add preprocessed book chapters to renderer
renderer.current_dir(&book.root);
for input in &mut preprocessed {
renderer.input(input?);
}
if preprocessed.unresolved_links() {
log::warn!(
"Unable to resolve one or more relative links within the book, \
consider setting the `hosted-html` option in `[output.pandoc]`"
);
}
if let Some(logfile) = &self.logfile {
renderer.stderr(logfile.try_clone()?);
}
// Render final output
renderer.render(profile, preprocessed.render_context())?;
if !cfg.keep_preprocessed {
fs::remove_dir_all(preprocessed.output_dir())?;
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use std::{
env,
fmt::{self, Write},
fs,
io::{self, Read, Seek},
path::{Path, PathBuf},
str::FromStr,
};
use mdbook::{BookItem, Renderer as _};
use normpath::PathExt;
use once_cell::sync::Lazy;
use regex::Regex;
use tempfile::{tempfile, TempDir};
use toml::toml;
use super::*;
pub struct MDBook {
book: mdbook::MDBook,
_root: Option<TempDir>,
_logger: tracing::subscriber::DefaultGuard,
logfile: File,
}
#[derive(Clone, Copy)]
pub struct Options {
max_log_level: tracing::level_filters::LevelFilter,
}
#[derive(Clone)]
pub struct Chapter {
chapter: mdbook::book::Chapter,
}
impl Default for Options {
fn default() -> Self {
Self {
max_log_level: tracing::Level::INFO.into(),
}
}
}
impl Options {
pub fn init(self) -> MDBook {
// Initialize a book directory
let root = TempDir::new().unwrap();
let mut book = mdbook::book::BookBuilder::new(root.path()).build().unwrap();
// Clear out the stub files
let src = book.source_dir();
fs::remove_file(src.join("SUMMARY.md")).unwrap();
for item in book.book.sections.drain(..) {
match item {
BookItem::Chapter(chap) => {
if let Some(path) = chap.source_path {
fs::remove_file(src.join(path)).unwrap();
}
}
BookItem::Separator | BookItem::PartTitle(_) => {}
}
}
MDBook::new(book, Some(root), self)
}
pub fn load(self, path: impl Into<PathBuf>) -> MDBook {
MDBook::new(mdbook::MDBook::load(path).unwrap(), None, self)
}
pub fn max_log_level(
mut self,
max_level: impl Into<tracing::level_filters::LevelFilter>,
) -> Self {
self.max_log_level = max_level.into();
self
}
}
impl MDBook {
pub fn init() -> Self {
Options::default().init()
}
pub fn load(path: impl Into<PathBuf>) -> Self {
Options::default().load(path)
}
pub fn options() -> Options {
Options::default()
}
fn new(mut book: mdbook::MDBook, tempdir: Option<TempDir>, options: Options) -> Self {
// Initialize logger to captures `log` output and redirect it to a tempfile
let logfile = tempfile().unwrap();
let _logger = tracing::subscriber::set_default(
tracing_subscriber::fmt()
.with_max_level(options.max_log_level)
.compact()
.without_time()
.with_writer({
let logfile = logfile.try_clone().unwrap();
move || logfile.try_clone().unwrap()
})
.finish(),
);
{
let logger = tracing_log::LogTracer::new();
let _ = log::set_boxed_logger(Box::new(logger));
log::set_max_level(log::LevelFilter::Trace);
}
// Configure renderer to only preprocess
book.config
.set(Renderer::CONFIG_KEY, Config::markdown())
.unwrap();
Self {
book,
_root: tempdir,
_logger,
logfile,
}
}
pub fn mdbook_config(mut self, config: mdbook::Config) -> Self {
self.book.config = config;
self
}
pub fn config(mut self, config: Config) -> Self {
self.book.config.set(Renderer::CONFIG_KEY, config).unwrap();
self
}
pub fn toml_config(self, toml: toml::map::Map<String, toml::Value>) -> Self {
self.config(toml.try_into().expect("invalid config"))
}
pub fn chapter(mut self, Chapter { mut chapter }: Chapter) -> Self {
use mdbook::book::SectionNumber;
let number = (self.book.book.sections.iter())
.filter(
|item| matches!(item, BookItem::Chapter(chapter) if chapter.number.is_some()),
)
.count();
chapter.number = Some(SectionNumber(vec![number as u32]));
let mut chapters = vec![&mut chapter];
while let Some(chapter) = chapters.pop() {
let number = &chapter.number;
for (idx, chapter) in chapter
.sub_items
.iter_mut()
.filter_map(|item| match item {
BookItem::Chapter(chapter) => Some(chapter),
_ => None,
})
.enumerate()
{
if let Some(number) = number {
let mut number = number.clone();
number.push(idx as u32 + 1);
chapter.number = Some(number);
}
chapters.push(chapter);
}
if let Some(path) = &chapter.path {
let path = self.book.source_dir().join(path);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
File::create(path).unwrap();
}
}
self.book.book.push_item(BookItem::Chapter(chapter));
self
}
pub fn part(mut self, name: impl Into<String>) -> Self {
self.book.book.push_item(BookItem::PartTitle(name.into()));
self
}
pub fn file_in_root(self, path: impl AsRef<Path>, contents: &str) -> Self {
let path = self.book.root.join(path);
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).unwrap();
}
fs::write(path, contents).unwrap();
self
}
pub fn build(mut self) -> BuildOutput {
let mut renderer = Renderer::new();
renderer.logfile = Some(self.logfile.try_clone().unwrap());
let res = self.book.execute_build_process(&renderer);
self.logfile.seek(io::SeekFrom::Start(0)).unwrap();
let mut logs = String::new();
self.logfile.read_to_string(&mut logs).unwrap();
if let Err(err) = res {
writeln!(&mut logs, "{err:#}").unwrap()
}
let root = self.book.root.normalize().unwrap().into_path_buf();
let re = Regex::new(&format!(
r"(?P<root>{})|(?P<line>line\s+\d+)|(?P<page>page\s+\d+)",
root.display()
))
.unwrap();
let logs = re.replace_all(&logs, |caps: ®ex::Captures| {
(caps.name("root").map(|_| "$ROOT"))
.or_else(|| caps.name("line").map(|_| "$LINE"))
.or_else(|| caps.name("page").map(|_| "$PAGE"))
.unwrap()
});
BuildOutput {
logs: logs.into(),
dir: self.book.build_dir_for(renderer.name()),
_root: self._root,
}
}
}
impl Chapter {
pub fn new(
name: impl Into<String>,
content: impl Into<String>,
path: impl Into<PathBuf>,
) -> Self {
let path = path.into();
Self {
chapter: mdbook::book::Chapter {
name: name.into(),
content: content.into(),
path: Some(path.clone()),
source_path: Some(path),
..Default::default()
},
}
}
/// Adds `chapter` as a child of `self` in the hierarchy.
pub fn child(mut self, mut chapter: Self) -> Self {
chapter.chapter.parent_names.push(self.chapter.name.clone());
self.chapter
.sub_items
.push(BookItem::Chapter(chapter.chapter));
self
}
}
fn visualize_directory(
dir: impl AsRef<Path>,
mut writer: impl fmt::Write,
) -> anyhow::Result<()> {
fn visualize_directory(
root: &Path,
dir: &Path,
writer: &mut dyn fmt::Write,
) -> anyhow::Result<()> {
let mut entries = fs::read_dir(dir)
.with_context(|| format!("Unable to read directory: {}", dir.display()))?
.collect::<Result<Vec<_>, _>>()?;
entries.sort_by_key(|entry| entry.path());
for entry in entries {
let path = entry.path();
match entry.file_type()? {
ty if ty.is_dir() => visualize_directory(root, path.as_ref(), writer)?,
ty if ty.is_file() => {
writeln!(writer, "├─ {}", path.strip_prefix(root).unwrap().display())?;
match fs::read_to_string(path) {
Ok(contents) => {
for line in contents.lines() {
writeln!(writer, "│ {line}")?;
}
}
Err(err) if err.kind() == io::ErrorKind::InvalidData => {
writeln!(writer, "│ <INVALID UTF8>")?;
}
Err(err) => return Err(err.into()),
}
}
_ => {}
}
}
Ok(())
}
visualize_directory(dir.as_ref(), dir.as_ref(), &mut writer)
}
pub struct BuildOutput {
logs: String,
dir: PathBuf,
_root: Option<TempDir>,
}
impl fmt::Display for BuildOutput {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if !self.logs.is_empty() {
writeln!(f, "├─ log output")?;
for line in self.logs.lines() {
writeln!(f, "│ {line}")?;
}
}
visualize_directory(&self.dir, f).expect("`visualize_directory` should succeed");
Ok(())
}
}
impl Config {
fn latex() -> Self {
toml! {
[profile.latex]
output-file = "output.tex"
standalone = false
[profile.latex.variables]
documentclass = "report"
}
.try_into()
.unwrap()
}
fn pdf() -> Self {
toml! {
keep-preprocessed = false
[profile.pdf]
output-file = "book.pdf"
to = "latex"
pdf-engine = "lualatex"
[profile.pdf.variables]
documentclass = "report"
mainfont = "Noto Serif"
sansfont = "Noto Sans"
monofont = "Noto Sans Mono"
mainfontfallback = [
"NotoColorEmoji:mode=harf",
"NotoSansMath:",
"NotoSerifCJKSC:",
]
monofontfallback = [
"NotoColorEmoji:mode=harf",
"NotoSansMath:",
"NotoSansMonoCJKSC:",
]
geometry = ["margin=1.25in"]
}
.try_into()
.unwrap()
}
fn markdown() -> Self {
toml! {
keep-preprocessed = false
[profile.markdown]
output-file = "book.md"
standalone = false
}
.try_into()
.unwrap()
}
fn pandoc() -> Self {
toml! {
keep-preprocessed = false
[profile.markdown]
output-file = "pandoc-ir"
to = "native"
standalone = false
}
.try_into()
.unwrap()
}
}
#[test]
fn basic() {
let book = MDBook::init()
.chapter(Chapter::new(
"Getting Started",
"# Getting Started",
"getting-started.md",
))
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/markdown/book.md
├─ markdown/book.md
│ # Getting Started
"###);
}
#[test]
fn broken_links() {
let book = MDBook::init()
.chapter(Chapter::new(
"Getting Started",
"[broken link](foobarbaz)",
"getting-started.md",
))
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ WARN mdbook_pandoc::preprocess: Unable to normalize link 'foobarbaz' in chapter 'Getting Started': Unable to normalize path: $ROOT/src/foobarbaz: No such file or directory (os error 2)
│ WARN mdbook_pandoc: Unable to resolve one or more relative links within the book, consider setting the `hosted-html` option in `[output.pandoc]`
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/markdown/book.md
├─ markdown/book.md
│ [broken link](foobarbaz)
"###);
}
#[test]
fn strikethrough() {
let book = MDBook::init()
.chapter(Chapter::new("", "~test1~ ~~test2~~", "chapter.md"))
.config(Config::latex())
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/latex/output.tex
├─ latex/output.tex
│ \st{test1} \st{test2}
├─ latex/src/chapter.md
│ ~~test1~~ ~~test2~~
"###);
}
#[test]
fn task_lists() {
let book = MDBook::init()
.chapter(Chapter::new(
"",
"- [x] Complete task\n- [ ] Incomplete task",
"chapter.md",
))
.config(Config::latex())
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/latex/output.tex
├─ latex/output.tex
│ \begin{itemize}
│ \tightlist
│ \item[$\boxtimes$]
│ Complete task
│ \item[$\square$]
│ Incomplete task
│ \end{itemize}
├─ latex/src/chapter.md
│ * [x] Complete task
│ * [ ] Incomplete task
"###);
}
#[test]
fn heading_attributes() {
let book = MDBook::init()
.chapter(Chapter::new(
"",
"# Heading { #custom-heading }\n[heading](#custom-heading)",
"chapter.md",
))
.config(Config::latex())
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/latex/output.tex
├─ latex/output.tex
│ \chapter{Heading}\label{custom-heading}
│
│ \hyperref[custom-heading]{heading}
├─ latex/src/chapter.md
│ # Heading { #custom-heading }
│
│ [heading](#custom-heading)
"###);
}
#[test]
fn footnotes() {
let book = MDBook::init()
.chapter(Chapter::new(
"",
"
This is an example of a footnote[^note].
[^note]: This text is the contents of the footnote, which will be rendered
towards the bottom.
",
"chapter.md",
))
.config(Config::latex())
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/latex/output.tex
├─ latex/output.tex
│ This is an example of a footnote\footnote{This text is the contents of
│ the footnote, which will be rendered towards the bottom.}.
├─ latex/src/chapter.md
│ This is an example of a footnote[^note].
│
│ [^note]: This text is the contents of the footnote, which will be rendered
│ towards the bottom.
"###);
}
#[test]
fn tables() {
let book = MDBook::init()
.chapter(Chapter::new(
"",
"
| Header1 | Header2 |
|---------|---------|
| abc | def |
",
"chapter.md",
))
.config(Config::latex())
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/latex/output.tex
├─ latex/output.tex
│ \begin{longtable}[]{@{}ll@{}}
│ \toprule\noalign{}
│ Header1 & Header2 \\
│ \midrule\noalign{}
│ \endhead
│ \bottomrule\noalign{}
│ \endlastfoot
│ abc & def \\
│ \end{longtable}
├─ latex/src/chapter.md
│ |Header1|Header2|
│ |-------|-------|
│ |abc|def|
"###);
}
#[test]
fn wide_table() {
let book = MDBook::init()
.chapter(Chapter::new(
"",
"
| Header1 | Header2 |
| ------- | :--------------------------------------------------------------- |
| abc | long long long long long long long long long long long long long |
",
"chapter.md",
))
.config(Config::latex())
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/latex/output.tex
├─ latex/output.tex
│ \begin{longtable}[]{@{}
│ >{\raggedright\arraybackslash}p{(\columnwidth - 2\tabcolsep) * \real{0.0986}}
│ >{\raggedright\arraybackslash}p{(\columnwidth - 2\tabcolsep) * \real{0.9014}}@{}}
│ \toprule\noalign{}
│ \begin{minipage}[b]{\linewidth}\raggedright
│ Header1
│ \end{minipage} & \begin{minipage}[b]{\linewidth}\raggedright
│ Header2
│ \end{minipage} \\
│ \midrule\noalign{}
│ \endhead
│ \bottomrule\noalign{}
│ \endlastfoot
│ abc & long long long long long long long long long long long long
│ long \\
│ \end{longtable}
├─ latex/src/chapter.md
│ <!-- mdbook-pandoc::table: 7|64 -->
│ |Header1|Header2|
│ |-------|:------|
│ |abc|long long long long long long long long long long long long long|
"###);
}
#[test]
fn parts() {
let book = MDBook::init()
.chapter(Chapter::new("", "# One", "one.md"))
.part("part two")
.chapter(Chapter::new("", "# Two", "two.md"))
.config(Config::latex())
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/latex/output.tex
├─ latex/output.tex
│ \phantomsection\label{book__latex__src__onemd}
│ \chapter{One}\label{book__latex__src__onemd__one}
│
│ \phantomsection\label{book__latex__src__part-1-part-twomd}
│ \part{part two}
│
│ \phantomsection\label{book__latex__src__twomd}
│ \chapter{Two}\label{book__latex__src__twomd__two}
├─ latex/src/one.md
│ # One
├─ latex/src/part-1-part-two.md
│ `\part{part two}`{=latex}
├─ latex/src/two.md
│ # Two
"###);
}
#[test]
fn inter_chapter_links() {
let book = MDBook::init()
.chapter(Chapter::new("One", "[Two](../two/two.md)", "one/one.md"))
.chapter(Chapter::new("Two", "[One](../one/one.md)", "two/two.md"))
.config(Config::latex())
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/latex/output.tex
├─ latex/output.tex
│ \phantomsection\label{book__latex__src__one__onemd}
│ \hyperref[book__latex__src__two__twomd]{Two}
│
│ \phantomsection\label{book__latex__src__two__twomd}
│ \hyperref[book__latex__src__one__onemd]{One}
├─ latex/src/one/one.md
│ [Two](book/latex/src/two/two.md)
├─ latex/src/two/two.md
│ [One](book/latex/src/one/one.md)
"###);
}
#[test]
fn nested_chapters() {
let book = MDBook::init()
.chapter(Chapter::new("One", "# One", "one.md").child(Chapter::new(
"One.One",
"# Top\n## Another",
"onepointone.md",
)))
.chapter(Chapter::new("Two", "# Two", "two.md"))
.config(Config::latex())
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/latex/output.tex
├─ latex/output.tex
│ \phantomsection\label{book__latex__src__onemd}
│ \chapter{One}\label{book__latex__src__onemd__one}
│
│ \phantomsection\label{book__latex__src__onepointonemd}
│ \section{Top}\label{book__latex__src__onepointonemd__top}
│
│ \subsection*{Another}\label{book__latex__src__onepointonemd__another}
│
│ \phantomsection\label{book__latex__src__twomd}
│ \chapter{Two}\label{book__latex__src__twomd__two}
├─ latex/src/one.md
│ # One
├─ latex/src/onepointone.md
│ ## Top
│
│ ### Another { .unnumbered .unlisted }
├─ latex/src/two.md
│ # Two
"###);
}
#[test]
fn font_awesome_icons() {
let book = MDBook::init()
.config(Config::latex())
.chapter(Chapter::new(
"",
r#"
<i class="fa fa-print"></i>
<i class="fa fa-print"/>
<i class = "fa fa-print"/>
"#,
"chapter.md",
))
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/latex/output.tex
├─ latex/output.tex
│ \faicon{print} \faicon{print} \faicon{print}
├─ latex/src/chapter.md
│ `\faicon{print}`{=latex}
│ `\faicon{print}`{=latex}
│ `\faicon{print}`{=latex}
"###);
let book = MDBook::init()
.chapter(Chapter::new(
"",
r#"<i class="fa fa-print"/>"#,
"chapter.md",
))
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/markdown/book.md
├─ markdown/book.md
│ ```{=html}
│ <i class="fa fa-print"/>
│ ```
"###);
}
#[test]
fn code_block_with_hidden_lines() {
let content = r#"
```rust
# fn main() {
# // another hidden line
println!("Hello, world!");
# }
```
"#;
let book = MDBook::init()
.config(Config::markdown())
.chapter(Chapter::new("", content, "chapter.md"))
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/markdown/book.md
├─ markdown/book.md
│ ``` rust
│ println!("Hello, world!");
│ ```
"###);
let book = MDBook::init()
.config(Config {
code: CodeConfig {
show_hidden_lines: true,
},
..Config::markdown()
})
.chapter(Chapter::new("", content, "chapter.md"))
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/markdown/book.md
├─ markdown/book.md
│ ``` rust
│ # fn main() {
│ # // another hidden line
│ println!("Hello, world!");
│ # }
│ ```
"###);
}
#[test]
fn non_rust_code_block_with_hidden_lines() {
let content = r#"
```python
~hidden()
nothidden():
~ hidden()
~hidden()
nothidden()
```
"#;
let cfg = r#"
[output.html.code.hidelines]
python = "~"
"#;
let book = MDBook::init()
.mdbook_config(cfg.parse().unwrap())
.config(Config::markdown())
.chapter(Chapter::new("", content, "chapter.md"))
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/markdown/book.md
├─ markdown/book.md
│ ``` python
│ nothidden():
│ nothidden()
│ ```
"###);
let book = MDBook::init()
.config(Config {
code: CodeConfig {
show_hidden_lines: true,
},
..Config::markdown()
})
.chapter(Chapter::new("", content, "chapter.md"))
.build();
insta::assert_snapshot!(book, @r###"
├─ log output
│ INFO mdbook::book: Running the pandoc backend
│ INFO mdbook_pandoc::pandoc::renderer: Wrote output to book/markdown/book.md
├─ markdown/book.md
│ ``` python