-
-
Notifications
You must be signed in to change notification settings - Fork 982
/
Copy pathoutput_format.R
793 lines (682 loc) · 27.6 KB
/
output_format.R
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
#' Define an R Markdown output format
#'
#' Define an R Markdown output format based on a combination of
#' knitr and pandoc options.
#' @param knitr Knitr options for an output format (see
#' \code{\link{knitr_options}})
#' @param pandoc Pandoc options for an output format (see
#' \code{\link{pandoc_options}})
#' @param keep_md Keep the markdown file generated by knitting. Note that
#' if this is \code{TRUE} then \code{clean_supporting} will always be
#' \code{FALSE}.
#' @param clean_supporting Cleanup any supporting files after conversion see
#' \code{\link{render_supporting_files}}
#' @param df_print Method to be used for printing data frames. Valid values
#' include "default", "kable", "tibble", and "paged". The "default" method uses
#' \code{print.data.frame}. The "kable" method uses the
#' \code{\link[knitr:kable]{knitr::kable}} function. The "tibble" method uses
#' the \pkg{tibble} package to print a summary of the data frame. The "paged"
#' method creates a paginated HTML table (note that this method is only valid
#' for formats that produce HTML). In addition
#' to the named methods you can also pass an arbitrary function to be used
#' for printing data frames. You can disable the \code{df_print} behavior entirely
#' by setting the option \code{rmarkdown.df_print} to \code{FALSE}.
#' @param pre_knit An optional function that runs before knitting which
#' receives the \code{input} (input filename passed to \code{render}) and
#' \code{...} (for future expansion) arguments.
#' @param post_knit An optional function that runs after knitting which
#' receives the \code{metadata}, \code{input_file}, \code{runtime}, and \code{...}
#' (for future expansion) arguments. This function can return additional
#' arguments to pass to pandoc and can call \code{knitr::knit_meta_add}
#' to add additional dependencies based on the contents of the input_file or on other
#' assets side by side with it that may be used to produce html with dependencies
#' during subsequent processing.
#' @param pre_processor An optional pre-processor function that receives the
#' \code{metadata}, \code{input_file}, \code{runtime}, \code{knit_meta},
#' \code{files_dir}, and \code{output_dir} and can return additional arguments
#' to pass to pandoc.
#' @param intermediates_generator An optional function that receives the
#' original \code{input_file}, its \code{encoding}, and the intermediates
#' directory (i.e. the \code{intermediates_dir} argument to
#' \code{\link{render}}). The function should generate and return the names of
#' any intermediate files required to render the \code{input_file}.
#' @param post_processor An optional post-processor function that receives the
#' \code{metadata}, \code{input_file}, \code{output_file}, \code{clean},
#' and \code{verbose} parameters, and can return an alternative
#' \code{output_file}.
#' @param on_exit A function to call when \code{rmarkdown::render()} finishes
#' execution (as registered with a \code{\link{on.exit}} handler).
#' @param base_format An optional format to extend.
#' @return An R Markdown output format definition that can be passed to
#' \code{\link{render}}.
#' @seealso \link{render}, \link{knitr_options}, \link{pandoc_options}
#' @examples
#' \dontrun{
#' output_format(knitr = knitr_options(opts_chunk = list(dev = 'png')),
#' pandoc = pandoc_options(to = "html"))
#' }
#' @export
output_format <- function(knitr,
pandoc,
keep_md = FALSE,
clean_supporting = TRUE,
df_print = NULL,
pre_knit = NULL,
post_knit = NULL,
pre_processor = NULL,
intermediates_generator = NULL,
post_processor = NULL,
on_exit = NULL,
base_format = NULL) {
format <- list(
knitr = knitr,
pandoc = pandoc,
keep_md = keep_md,
clean_supporting = clean_supporting && !keep_md,
df_print = df_print,
pre_knit = pre_knit,
post_knit = post_knit,
pre_processor = pre_processor,
intermediates_generator = intermediates_generator,
post_processor = post_processor,
on_exit = on_exit
)
class(format) <- "rmarkdown_output_format"
# if a base format was supplied, merge it with the format we just created
if (!is.null(base_format))
merge_output_formats(base_format, format)
else
format
}
# merges two scalar values; picks the overlay if non-NULL and then the base
merge_scalar <- function(base,
overlay) {
if (is.null(base) && is.null(overlay))
NULL
else if (is.null(overlay))
base
else
overlay
}
# merges two functions: if both are non-NULL, produces a new function that
# invokes each and then uses the supplied operation to combine their outputs
merge_function_outputs <- function(base,
overlay,
op) {
if (!is.null(base) && !is.null(overlay)) {
function(...) {
op(base(...), overlay(...))
}
} else {
merge_scalar(base, overlay)
}
}
# merges two post-processors; if both are non-NULL, produces a new function that
# calls the overlay post-processor and then the base post-processor.
merge_post_processors <- function(base,
overlay) {
if (!is.null(base) && !is.null(overlay)) {
function(metadata, input_file, output_file, ...) {
# record original output file
original_output_file <- output_file
# call overlay post processor
output_file <- overlay(metadata, input_file, output_file, ...)
# also call base post processor on original file if requested
if (!is.null(attr(output_file, "post_process_original")))
base(metadata, input_file, original_output_file, ...)
# call base post processor
base(metadata, input_file, output_file, ...)
}
}
else {
merge_scalar(base, overlay)
}
}
# merges two output formats
merge_output_formats <- function(base,
overlay) {
structure(list(
knitr = merge_lists(base$knitr, overlay$knitr),
pandoc = merge_pandoc_options(base$pandoc, overlay$pandoc),
keep_md =
merge_scalar(base$keep_md, overlay$keep_md),
clean_supporting =
merge_scalar(base$clean_supporting, overlay$clean_supporting),
df_print =
merge_scalar(base$df_print, overlay$df_print),
pre_knit =
merge_function_outputs(base$pre_knit, overlay$pre_knit, c),
post_knit =
merge_function_outputs(base$post_knit, overlay$post_knit, c),
pre_processor =
merge_function_outputs(base$pre_processor, overlay$pre_processor, c),
intermediates_generator =
merge_function_outputs(base$intermediates_generator,
overlay$intermediates_generator, c),
post_processor =
merge_post_processors(base$post_processor, overlay$post_processor),
on_exit =
merge_on_exit(base$on_exit, overlay$on_exit)
), class = "rmarkdown_output_format")
}
merge_on_exit <- function(base,
overlay) {
function() {
if (is.function(base)) base()
if (is.function(overlay)) overlay()
}
}
merge_pandoc_options <- function(base,
overlay) {
res <- merge_lists(base, overlay, recursive = FALSE)
res$args <- c(base$args, overlay$args)
res
}
#' Knitr options for an output format
#'
#' Define the knitr options for an R Markdown output format.
#' @param opts_knit List of package level knitr options (see
#' \code{\link[knitr:opts_knit]{opts_knit}})
#' @param opts_chunk List of chunk level knitr options (see
#' \code{\link[knitr:opts_chunk]{opts_chunk}})
#' @param knit_hooks List of hooks for R code chunks, inline R code, and output
#' (see \code{\link[knitr:knit_hooks]{knit_hooks}})
#' @param opts_hooks List of hooks for code chunk options
#' (see \code{\link[knitr:opts_hooks]{opts_hooks}})
#' @param opts_template List of templates for chunk level knitr options (see
#' \code{\link[knitr:opts_template]{opts_template}})
#' @return An list that can be passed as the \code{knitr} argument
#' of the \code{\link{output_format}} function.
#' @seealso \link{output_format}
#' @export
knitr_options <- function(opts_knit = NULL,
opts_chunk = NULL,
knit_hooks = NULL,
opts_hooks = NULL,
opts_template = NULL) {
list(opts_knit = opts_knit,
opts_chunk = opts_chunk,
knit_hooks = knit_hooks,
opts_hooks = opts_hooks,
opts_template = opts_template)
}
#' Knitr options for a PDF output format
#'
#' Define knitr options for an R Markdown output format
#' that creates PDF output.
#' @inheritParams html_document
#' @inheritParams pdf_document
#' @return An list that can be passed as the \code{knitr} argument of the
#' \code{\link{output_format}} function.
#' @seealso \link{knitr_options}, \link{output_format}
#' @export
knitr_options_pdf <- function(fig_width,
fig_height,
fig_crop,
dev = 'pdf') {
# default options
opts_knit <- NULL
opts_chunk <- list(dev = dev,
fig.width = fig_width,
fig.height = fig_height)
# set the dingbats option for the pdf device if required
if (dev == 'pdf')
opts_chunk$dev.args <- list(pdf = list(useDingbats = FALSE))
knit_hooks <- NULL
# apply cropping if requested and we have pdfcrop
crop <- fig_crop && !is_windows() && nzchar(find_program("pdfcrop"))
if (crop) {
knit_hooks = list(crop = knitr::hook_pdfcrop)
opts_chunk$crop = TRUE
}
# return options
knitr_options(opts_knit = opts_knit,
opts_chunk = opts_chunk,
knit_hooks = knit_hooks)
}
#' Pandoc options for an output format
#'
#' Define the pandoc options for an R Markdown output format.
#'
#' The \code{from} argument should be used very cautiously as it's
#' important for users to be able to rely on a stable definition of supported
#' markdown extensions.
#' @param to Pandoc format to convert to
#' @param from Pandoc format to convert from
#' @param args Character vector of command line arguments to pass to pandoc
#' @param keep_tex Keep the intermediate tex file used in the conversion to PDF
#' (applies only to 'latex' and 'beamer' target formats)
#' @param latex_engine LaTeX engine to producing PDF output (applies only to
#' 'latex' and 'beamer' target formats)
#' @param ext File extension (e.g. ".tex") for output file (if \code{NULL}
#' chooses default based on \code{to}). This is typically used to force
#' the final output of a latex or beamer conversion to be \code{.tex}
#' rather than \code{.pdf}.
#' @return An list that can be passed as the \code{pandoc} argument of the
#' \code{\link{output_format}} function.
#' @seealso \link{output_format}, \link{rmarkdown_format}
#' @export
pandoc_options <- function(to,
from = rmarkdown_format(),
args = NULL,
keep_tex = FALSE,
latex_engine = c("pdflatex", "lualatex", "xelatex"),
ext = NULL) {
list(to = to,
from = from,
args = args,
keep_tex = keep_tex,
latex_engine = match.arg(latex_engine),
ext = ext)
}
#' R Markdown input format definition
#'
#' Compose a pandoc markdown input definition for R Markdown
#' that can be passed as the \code{from} argument of \link{pandoc_options}.
#'
#' By default R Markdown is defined as all pandoc markdown extensions with
#' the following tweaks for backward compatibility with the markdown package
#' (+ features are added, - features are removed):
#'
#' \tabular{l}{
#' \code{+autolink_bare_uris} \cr
#' \code{+ascii_identifier} \cr
#' \code{+tex_math_single_backslash} \cr
#' }
#'
#' For more on pandoc markdown see the
#' \href{http://pandoc.org/README.html}{pandoc online documentation}.
#' @param implicit_figures Automatically make figures from images (defaults to \code{TRUE}).
#' @param extensions Markdown extensions to be added or removed from the
#' default definition of R Markdown.
#' @return Pandoc markdown format specification
#' @examples
#' \dontrun{
#' rmarkdown_format("-implicit_figures")
#' }
#' @seealso \link{output_format}, \link{pandoc_options}
#' @export
rmarkdown_format <- function(extensions = NULL) {
format <- c("markdown")
# only add extensions if the user hasn't already specified
# a manual override for them
addExtension <- function(extension) {
if (length(grep(extension, extensions)) == 0)
format <<- c(format, paste0("+", extension))
}
addExtension("autolink_bare_uris")
addExtension("ascii_identifiers")
addExtension("tex_math_single_backslash")
format <- c(format, extensions, recursive = TRUE)
paste(format, collapse = "")
}
# Add the +smart extension for Pandoc >= 2.0
smart_extension <- function(smart, extension) {
c(extension, if (smart && pandoc2.0()) "+smart")
}
#' Determine the default output format for an R Markdown document
#'
#' Read the YAML metadata (and any common output YAML file) for the
#' document and return the output format that will be generated by
#' a call to \code{\link{render}}.
#'
#' This function is useful for front-end tools that require additional
#' knowledge of the output to be produced by \code{\link{render}} (e.g. to
#' customize the preview experience).
#' @param input Input file (Rmd or plain markdown)
#' @param output_yaml Paths to YAML files specifying output formats and their
#' configurations. The first existing one is used. If none are found, then
#' the function searches YAML files specified to the \code{output_yaml} top-level
#' parameter in the YAML front matter, _output.yml or _output.yaml, and then uses
#' the first existing one.
#' @param encoding The encoding of the input file; see \code{\link{file}}
#' @return A named list with a \code{name} value containing the format
#' name and an \code{options} value that is a list containing all the options
#' for the format and their values. An option's default value will be returned
#' if the option isn't set explicitly in the document.
#' @export
default_output_format <- function(input,
encoding = "UTF-8",
output_yaml = NULL) {
# execute within the input file's directory (this emulates the way
# yaml front matter discovery is done within render)
oldwd <- setwd(dirname(abs_path(input)))
on.exit(setwd(oldwd), add = TRUE)
# because we're now within the same directory as the input file,
# we just need its basename
input <- basename(input)
# parse the YAML and front matter and get the explicitly set options
input_lines <- read_utf8(input, encoding)
format <- output_format_from_yaml_front_matter(
input_lines, output_yaml = output_yaml, encoding = encoding)
# look up the formals of the output function to get the full option list and
# merge against the explicitly set list
format_function <- eval(parse(text = format$name))
format$options <- merge_lists(as.list(formals(format_function)),
format$options,
recursive = FALSE)
format
}
#' Resolve the output format for an R Markdown document
#'
#' Read the YAML metadata (and any common output YAML file) for the
#' document and return an output format object that can be
#' passed to the \code{\link{render}} function.
#'
#' This function is useful for front-end tools that need to modify
#' the default behavior of an output format.
#' @inheritParams default_output_format
#' @param input Input file (Rmd or plain markdown)
#' @param output_format Name of output format (or \code{NULL} to use
#' the default format for the input file).
#' @param output_options List of output options that should override the
#' options specified in metadata.
#' @param encoding The encoding of the input file; see \code{\link{file}}.
#' @return An R Markdown output format definition that can be passed to
#' \code{\link{render}}.
#' @export
resolve_output_format <- function(input,
output_format = NULL,
output_options = NULL,
output_yaml = NULL,
encoding = "UTF-8") {
# read the input file
input_lines <- read_utf8(input, encoding)
# validate that the output format is either NULL or a character vector
if (!is.null(output_format) && !is.character(output_format))
stop("output_format must be a character vector")
# resolve the output format by looking at the yaml
output_format <-
output_format_from_yaml_front_matter(
input_lines,
output_options,
output_format,
output_yaml,
encoding = encoding)
# return it
create_output_format(output_format$name, output_format$options)
}
#' Determine all output formats for an R Markdown document
#'
#' Read the YAML metadata (and any common output YAML file) for the
#' document and return the output formats that will be generated by
#' a call to \code{\link{render}}.
#'
#' This function is useful for front-end tools that require additional
#' knowledge of the output to be produced by \code{\link{render}} (e.g. to
#' customize the preview experience).
#' @inheritParams default_output_format
#' @param input Input file (Rmd or plain markdown)
#' @param encoding The encoding of the input file; see \code{\link{file}}.
#' @return A character vector with the names of all output formats.
#' @export
all_output_formats <- function(input,
encoding = "UTF-8",
output_yaml = NULL) {
enumerate_output_formats(
input = input,
envir = parent.frame(),
output_yaml = output_yaml,
encoding = encoding)
}
# Synthesize the output format for a document from it's YAML. If we can't
# find an output format then we just return html_document
output_format_from_yaml_front_matter <- function(input_lines,
output_options = NULL,
output_format_name = NULL,
output_yaml = NULL,
encoding = "UTF-8") {
format_name <- output_format_name
# ensure input is the correct data type
if (!is_null_or_string(format_name)) {
stop("Unrecognized output format specified", call. = FALSE)
}
# parse the yaml
yaml_input <- parse_yaml_front_matter(input_lines)
# default to no options
format_options <- list()
# parse _site.yml output format if we have it
config <- site_config(".", encoding = encoding)
yaml_site <- config[["output"]]
# parse common output yaml file if we have it
output_yaml <- c(output_yaml, yaml_input$output_yaml, "_output.yml", "_output.yaml")
output_yaml <- output_yaml[file.exists(output_yaml)][1L]
yaml_common <- if (!is.na(output_yaml)) yaml_load_file(output_yaml)
# merge _site.yml and output_yaml
yaml_common <- merge_output_options(yaml_site, yaml_common)
# parse output format from front-matter if we have it
if (length(yaml_common) || length(yaml_input[["output"]])) {
# alias the output format yaml
yaml_output <- yaml_input[["output"]]
# merge against common output yaml
yaml_output <- merge_output_options(yaml_common, yaml_output)
# if a named format was provided then try to find it
if (!is.null(format_name)) {
# if this is a named element of the list then use that
if (format_name %in% names(yaml_output)) {
format_options <- yaml_output[[format_name]]
# otherwise this could be a heterogeneous list of characters and
# lists so scan for an embedded list
} else {
for (format in yaml_output) {
if (is.list(format) && !is.null(format[[format_name]]))
format_options <- format[[format_name]]
}
}
# if the options are just "default" then that's the same as empty list
if (identical(format_options, "default")) format_options <- list()
# no named format passed so take the first element
} else {
if (is.list(yaml_output[[1]])) {
# check for named list
if (nzchar(format_name <- names(yaml_output)[[1]])) {
format_options <- yaml_output[[1]]
# nested named list
} else {
format_name <- names(yaml_output[[1]])[[1]]
format_options <- yaml_output[[1]][[format_name]]
}
} else if (is.list(yaml_output) &&
(is.null(yaml_output[[1]]) ||
identical(yaml_output[[1]], "default"))) {
format_name <- names(yaml_output)[[1]]
} else {
format_name <- yaml_output[[1]]
}
}
# no output formats defined in the file, just take the passed format
# by name (or default to html_document if no named format was specified)
} else {
if (is.null(format_name)) format_name <- "html_document"
}
# merge any output_options passed in the call to render
if (!is.null(output_options)) {
# create the output format function so we can check it's formals. strip options
# not within the formals
output_func <- create_output_format_function(format_name)
output_func_params <- names(formals(output_func))
if (!"..." %in% output_func_params) {
unsupported_options <- setdiff(names(output_options), output_func_params)
output_options[unsupported_options] <- NULL
}
# merge the output_options
format_options <- merge_output_options(format_options, output_options)
}
# return the format name and options
list(name = format_name, options = format_options)
}
create_output_format <- function(name,
options) {
# validate the name
if (is.null(name))
stop("The output format name must not be NULL", call. = FALSE)
if (name == "revealjs_presentation")
stop("reveal.js presentations are now located in a separate package: ",
"https://github.com/jjallaire/revealjs")
# lookup the function
output_format_func <- create_output_format_function(name)
# call the function
output_format <- do.call(output_format_func, options)
if (!is_output_format(output_format))
stop("Format is not of class rmarkdown_output_format", call. = FALSE)
# return the format
output_format
}
create_output_format_function <- function(name) {
output_format_func <- eval(parse(text = name))
if (!is.function(output_format_func))
stop("YAML output format must evaluate to a function", call. = FALSE)
output_format_func
}
is_output_format <- function(x) {
inherits(x, "rmarkdown_output_format")
}
enumerate_output_formats <- function(input,
envir,
encoding,
output_yaml = NULL) {
# read the input
input_lines <- read_utf8(input, encoding)
# if this is an R file then spin it
if (identical(tolower(tools::file_ext(input)), "r"))
input_lines <- knitr::spin(text = input_lines, knit = FALSE, envir = envir)
# parse _site.yml output format if we have it
config <- site_config(input, encoding = encoding)
if (!is.null(config) && !is.null(config[["output"]])) {
site_output_format_yaml <- config[["output"]]
} else {
site_output_format_yaml <- list()
}
# read the ymal front matter
yaml_front_matter <- parse_yaml_front_matter(input_lines)
# read any output yaml
output_yaml <- file.path(
dirname(input),
c(output_yaml, yaml_front_matter$output_yaml, "_output.yml", "_output.yaml")
)
output_yaml <- output_yaml[file.exists(output_yaml)][1L]
common_output_format_yaml <- if (is.na(output_yaml)) {
list()
} else {
yaml_load_file(output_yaml)
}
# merge site and common
common_output_format_yaml <- merge_output_options(site_output_format_yaml,
common_output_format_yaml)
# parse output formats from front-matter if we have it
if (length(common_output_format_yaml) > 0 ||
length(yaml_front_matter[["output"]]) > 0) {
# alias the output format yaml
output_format_yaml <- yaml_front_matter[["output"]]
# merge against common output yaml
output_format_yaml <- merge_output_options(common_output_format_yaml,
output_format_yaml)
} else {
output_format_yaml <- NULL
}
# return them by name
if (is.character(output_format_yaml)) {
output_format_yaml
} else if (is.list(output_format_yaml)) {
names(output_format_yaml)
} else {
NULL
}
}
#' Parse the YAML front matter from a file
#' @inheritParams default_output_format
#' @keywords internal
#' @export
yaml_front_matter <- function(input,
encoding = "UTF-8") {
# read the input file
input_lines <- read_utf8(input, encoding)
# parse the yaml front matter
parse_yaml_front_matter(input_lines)
}
parse_yaml_front_matter <- function(input_lines) {
partitions <- partition_yaml_front_matter(input_lines)
if (!is.null(partitions$front_matter)) {
front_matter <- partitions$front_matter
if (length(front_matter) > 2) {
front_matter <- front_matter[2:(length(front_matter) - 1)]
front_matter <- one_string(front_matter)
validate_front_matter(front_matter)
parsed_yaml <- yaml_load(front_matter)
if (is.list(parsed_yaml))
parsed_yaml
else
list()
}
else
list()
}
else
list()
}
validate_front_matter <- function(front_matter) {
front_matter <- trim_trailing_ws(front_matter)
if (grepl(":$", front_matter))
stop("Invalid YAML front matter (ends with ':')", call. = FALSE)
}
partition_yaml_front_matter <- function(input_lines) {
validate_front_matter <- function(delimiters) {
if (length(delimiters) >= 2 &&
(delimiters[2] - delimiters[1] > 1) &&
grepl("^---\\s*$", input_lines[delimiters[1]])) {
# verify that it's truly front matter (not preceded by other content)
if (delimiters[1] == 1)
TRUE
else
is_blank(input_lines[1:delimiters[1] - 1])
} else {
FALSE
}
}
# is there yaml front matter?
delimiters <- grep("^(---|\\.\\.\\.)\\s*$", input_lines)
if (validate_front_matter(delimiters)) {
front_matter <- input_lines[(delimiters[1]):(delimiters[2])]
input_body <- c()
if (delimiters[1] > 1)
input_body <- c(input_body,
input_lines[1:delimiters[1] - 1])
if (delimiters[2] < length(input_lines))
input_body <- c(input_body,
input_lines[-(1:delimiters[2])])
list(front_matter = front_matter,
body = input_body)
}
else {
list(front_matter = NULL,
body = input_lines)
}
}
merge_output_options <- function(base_options,
overlay_options) {
# if either one of these is a character vector then normalize to a named list
normalize_list <- function(target) {
if (is.null(target)) {
list()
} else if (is.character(target)) {
setNames(lapply(target, function(x) list()), target)
} else {
target[names(target) != "..."] # remove symbols (...) from list
}
}
merge_lists(normalize_list(base_options), normalize_list(overlay_options))
}
is_pandoc_to_html <- function(options) {
options$to %in% c("html", "html4", "html5")
}
citeproc_required <- function(yaml_front_matter,
input_lines = NULL) {
(
is.null(yaml_front_matter$citeproc) ||
yaml_front_matter$citeproc
) && (
!is.null(yaml_front_matter$bibliography) ||
!is.null(yaml_front_matter$references) ||
length(grep("^references\\:\\s*$", input_lines)) > 0
)
}