Debian Codegraph @

R/hooks-md.R

raw
1 #' @rdname hook_plot
2 #' @export
3 hook_plot_md = function(x, options) {
4 # if not using R Markdown v2 or output is HTML, just return v1 output
5 if (is.null(to <- pandoc_to()) || is_html_output(to))
6 return(hook_plot_md_base(x, options))
7 if ((options$fig.show == 'animate' || is_tikz_dev(options)) && is_latex_output())
8 return(hook_plot_tex(x, options))
9 office_output = to %in% c('docx', 'pptx', 'rtf', 'odt')
10 if (need_special_plot_hook(options)) {
11 if (is_latex_output()) {
12 # Pandoc < 1.13 does not support \caption[]{} so suppress short caption
13 if (is.null(options$fig.scap)) options$fig.scap = NA
14 return(hook_plot_tex(x, options))
15 }
16 if (office_output) {
17 if (options$fig.align != 'default') {
18 warn_options_unsupported('fig.align', to)
19 options$fig.align = 'default'
20 }
21 if (!is.null(options$fig.alt)) {
22 warn_options_unsupported('fig.alt', to)
23 options$fig.alt = NULL
24 }
25 return(hook_plot_md_pandoc(x, options))
26 }
27 }
28 hook_plot_md_base(x, options)
29 }
30
31 # decide if the markdown plot hook is not enough and needs special hooks like
32 # hook_plot_tex() to handle chunk options like out.width
33 need_special_plot_hook = function(options) {
34 opts = opts_chunk$get(default = TRUE)
35 for (i in c(
36 'out.width', 'out.height', 'out.extra', 'fig.align', 'fig.subcap',
37 'fig.env', 'fig.scap', 'fig.alt'
38 )) if (!identical(options[[i]], opts[[i]])) return(TRUE)
39 FALSE
40 }
41
42 hook_plot_md_base = function(x, options) {
43 # when fig.id = TRUE, add an `id` attribute to images of the form fig:label-i
44 if (isTRUE(options$fig.id)) options$fig.id = function(options) {
45 id = sprintf('%s%s-%s', options$fig.lp, options$label, options$fig.cur)
46 sprintf('id="%s"', xfun::alnum_id(id))
47 }
48 if (is.function(options$fig.id)) options$out.extra = c(
49 options$out.extra, options$fig.id(options)
50 )
51 if (options$fig.show == 'animate') return(hook_plot_html(x, options))
52
53 cap = .img.cap(options)
54 alt = .img.cap(options, alt = TRUE, escape = TRUE)
55
56 w = options[['out.width']]; h = options[['out.height']]
57 s = options$out.extra; a = options$fig.align
58 ai = options$fig.show == 'asis'
59 # whether to use <object> to embed SVG graphics
60 is_svg = grepl('[.]svg$', x, ignore.case = TRUE) && getOption('knitr.svg.object', FALSE)
61 # self-contained mode?
62 sc = any(c('--embed-resources', '--self-contained') %in% opts_knit$get('rmarkdown.pandoc.args'))
63 lnk = options$fig.link
64 pandoc_html = cap != '' && is_html_output()
65 in_bookdown = isTRUE(opts_knit$get('bookdown.internal.label'))
66 plot1 = ai || options$fig.cur <= 1L
67 plot2 = ai || options$fig.cur == options$fig.num
68 to = pandoc_to(); from = pandoc_from()
69 if (is.null(w) && is.null(h) && is.null(s) && is.null(options$fig.alt) &&
70 a == 'default' && !(pandoc_html && in_bookdown) && !is_svg) {
71 # append <!-- --> to ![]() to prevent the figure environment in these cases
72 nocap = cap == '' && !is.null(to) && !grepl('^markdown', to) &&
73 (options$fig.num == 1 || ai) && !grepl('-implicit_figures', from)
74 x2 = paste0(opts_knit$get('base.url'), .upload.url(x))
75 res = sprintf('![%s](%s)', cap, x2)
76 if (!is.null(lnk) && !is.na(lnk)) res = sprintf('[%s](%s)', res, lnk)
77 res = paste0(res, if (nocap) '<!-- -->' else '', if (is_latex_output()) ' ' else '')
78 return(res)
79 }
80 add_link = function(x) {
81 if (is.null(lnk) || is.na(lnk)) return(x)
82 sprintf('<a href="%s" target="_blank">%s</a>', lnk, x)
83 }
84 img_code = function(s2 = NULL) {
85 img = if (is_svg && sc) svg_code(x, s) else .img.tag(x, w, h, alt, c(s, s2))
86 add_link(img)
87 }
88 # use HTML syntax <img src=...>
89 if (pandoc_html && !isTRUE(grepl('-implicit_figures', from))) {
90 d1 = if (plot1) sprintf('<div class="figure"%s>\n', css_text_align(a))
91 d2 = sprintf('<p class="caption">%s</p>', cap)
92 img = img_code()
93 # whether to place figure caption at the top or bottom of a figure
94 if (isTRUE(options$fig.topcaption)) {
95 paste0(d1, if (ai || options$fig.cur <= 1) d2, img, if (plot2) '</div>')
96 } else {
97 paste0(d1, img, if (plot2) paste0('\n', d2, '\n</div>'))
98 }
99 } else {
100 img_code(sprintf('style="%s"', css_align(a)))
101 }
102 }
103
104 # read svg, remove the xml/doctype declaration, and put the code in a raw html block
105 svg_code = function(file, extra = NULL) {
106 x = read_utf8(file)
107 while (length(x) > 0 && !grepl('^\\s*<svg .+', x[1])) x = x[-1]
108 if (length(x) > 0 && length(extra) == 1) {
109 if (grepl(r <- '\\s*>\\s*$', x[1])) {
110 x[1] = paste0(gsub(r, ' ', x[1]), extra, '>')
111 } else {
112 x[1] = paste(x[1], extra)
113 }
114 }
115 raw_html(x)
116 }
117
118 hook_plot_md_pandoc = function(x, options) {
119 if (options$fig.show == 'animate') return(hook_plot_html(x, options))
120
121 base = opts_knit$get('base.url') %n% ''
122 cap = .img.cap(options)
123
124 at = paste(
125 c(
126 sprintf('width=%s', options[['out.width']]),
127 sprintf('height=%s', options[['out.height']]),
128 options[['out.extra']]
129 ),
130 collapse = ' '
131 )
132 if (at != '') at = paste0('{', at, '}')
133
134 sprintf('![%s](%s%s)%s', cap, base, .upload.url(x), at)
135 }
136
137 css_align = function(align) {
138 sprintf('display: block; margin: %s;', switch(
139 align, left = 'auto auto auto 0', center = 'auto', right = 'auto 0 auto auto'
140 ))
141 }
142
143 css_text_align = function(align) {
144 if (align == 'default') '' else sprintf(' style="text-align: %s"', align)
145 }
146
147 #' @rdname output_hooks
148 #' @export
149 #' @param strict Boolean; whether to use strict markdown or reST syntax. For markdown, if
150 #' \code{TRUE}, code blocks will be indented by 4 spaces, otherwise they are
151 #' put in fences made by three backticks. For reST, if \code{TRUE}, code is
152 #' put under two colons and indented by 4 spaces, otherwise it is put under the
153 #' \samp{sourcecode} directive (this is useful for e.g. Sphinx).
154 #' @param fence_char A single character to be used in the code blocks fence.
155 #' This can be e.g. a backtick or a tilde, depending on your Markdown rendering
156 #' engine.
157 render_markdown = function(strict = FALSE, fence_char = '`') {
158 set_html_dev()
159 opts_knit$set(out.format = 'markdown')
160 knit_hooks$set(hooks_markdown(strict, fence_char))
161 }
162
163 #' @rdname output_hooks
164 #' @export
165 hooks_markdown = function(strict = FALSE, fence_char = '`') {
166 fence = paste(rep(fence_char, 3), collapse = '')
167 # four spaces will generate a <pre> block
168 hook.t = function(x, attr = NULL, class = NULL) {
169 if (strict) {
170 paste('\n', indent_block(x), '\n', sep = '\n')
171 } else {
172 fenced_block(x, attr, class, .char = fence_char)
173 }
174 }
175 hook.o = function(class) {
176 force(class)
177 function(x, options) {
178 if (class == 'output' && output_asis(x, options)) return(x)
179 hook.t(x, options[[paste0('attr.', class)]], options[[paste0('class.', class)]])
180 }
181 }
182 hook.r = function(x, options) {
183 lang = tolower(options$lang %n% eng2lang(options$engine))
184 if (!options$highlight) lang = 'text'
185 fenced_block(x, options$attr.source, c(lang, options$class.source), .char = fence_char)
186 }
187 list(
188 source = function(x, options) {
189 x = hilight_source(x, 'markdown', options)
190 if (strict) hook.t(x) else hook.r(sub('\n$', '\n\n', x), options)
191 },
192 inline = function(x) {
193 if (is_latex_output()) .inline.hook.tex(x) else {
194 .inline.hook(format_sci(x, if (length(pandoc_to()) == 1L) 'latex' else 'html'))
195 }
196 },
197 plot = hook_plot_md,
198 chunk = function(x, options) {
199 x = gsub(paste0('[\n]{2,}(', fence, '| )'), '\n\n\\1', x)
200 x = gsub('[\n]+$', '', x)
201 x = gsub('^[\n]+', '\n', x)
202 if (isTRUE(options$collapse)) {
203 r = sprintf('\n([%s]{3,})\n+\\1((\\{[.]| )?%s[^\n]*)?\n', fence_char, tolower(options$engine))
204 x = gsub(r, '\n', x)
205 x = gsub(asis_token, '', x, fixed = TRUE)
206 }
207 x = pandoc_div(x, options[['attr.chunk']], options[['class.chunk']])
208 if (is.null(s <- options$indent)) return(x)
209 line_prompt(x, prompt = s, continue = s)
210 },
211 output = hook.o('output'), warning = hook.o('warning'),
212 error = hook.o('error'), message = hook.o('message')
213 )
214 }
215
216 pandoc_div = function(x, attr = NULL, class = NULL) {
217 if (is.null(attr) && is.null(class)) return(x)
218 x = fenced_block(x, attr, class, .char = ':')
219 x = gsub('^\n\n|\n\n$', '', x)
220 gsub('^(:::+) *', '\\1 ', x) # add a space if necessary
221 }
222
223 # turn a class string "a b" to c(".a", ".b") for Pandoc fenced code blocks
224 block_class = function(x, attr = NULL) {
225 if (length(x)) x = unlist(strsplit(x, '\\s+'))
226 if (length(x) > 1 || length(attr)) gsub('^[.]*', '.', x) else x
227 }
228
229 # add a fence around content (either fenced code block ``` or Div :::)
230 fenced_block = function(x, attr = NULL, class = NULL, .char = '`') {
231 x = sub('\n$', '', x)
232 x = xfun::fenced_block(x, c(block_class(class, attr), attr), char = .char)
233 x = one_string(c('', x, '', ''))
234 # remove the space between ``` and { for backward-compatibility
235 sub('``` {', '```{', x, fixed = TRUE)
236 }
237
238 # convert some engine names to language names
239 eng2lang = function(x) {
240 d = c(
241 asy = 'cpp', mysql = 'sql', node = 'javascript', psql = 'sql',
242 rscript = 'r', rcpp = 'cpp', tikz = 'tex'
243 )
244 x = tolower(x)
245 if (x %in% names(d)) d[x] else x
246 }
247
248 #' @param highlight Which code highlighting engine to use: if \code{pygments},
249 #' the Liquid syntax is used (default approach Jekyll); if \code{prettify},
250 #' the output is prepared for the JavaScript library \file{prettify.js}; if
251 #' \code{none}, no highlighting engine will be used, and code blocks are simply
252 #' indented by 4 spaces).
253 #' @param extra Extra tags for the highlighting engine. For \code{pygments}, this
254 #' can be \code{'linenos'}; for \code{prettify}, it can be \code{'linenums'}.
255 #' @rdname output_hooks
256 #' @export
257 render_jekyll = function(highlight = c('pygments', 'prettify', 'none'), extra = '') {
258 render_markdown(TRUE)
259 knit_hooks$set(hooks_jekyll(highlight = highlight, extra = extra))
260 }
261
262 #' @rdname output_hooks
263 #' @export
264 hooks_jekyll = function(highlight = c('pygments', 'prettify', 'none'), extra = '') {
265 hook.m = hooks_markdown(TRUE)
266 hi = match.arg(highlight)
267 if (hi == 'none') return(hook.m)
268 switch(hi, pygments = {
269 hook.r = function(x, options) {
270 paste0(
271 '\n\n{% highlight ', tolower(options$engine), if (extra != '') ' ', extra,
272 ' %}\n', x, '\n{% endhighlight %}\n\n'
273 )
274 }
275 hook.t = function(x, options) paste0(
276 '\n\n{% highlight text %}\n', x, '{% endhighlight %}\n\n'
277 )
278 }, prettify = {
279 hook.r = function(x, options) {
280 paste0(
281 '\n\n<pre><code class="prettyprint ', extra, '">', html_escape(x),
282 '</code></pre>\n\n'
283 )
284 }
285 hook.t = function(x, options) paste0(
286 '\n\n<pre><code>', html_escape(x), '</code></pre>\n\n'
287 )
288 })
289 source = function(x, options) {
290 x = one_string(hilight_source(x, 'markdown', options))
291 hook.r(x, options)
292 }
293 merge_list(hook.m, list(
294 source = source, warning = hook.t, message = hook.t, error = hook.t,
295 output = function(x, options) {
296 if (output_asis(x, options)) x else hook.t(x, options)
297 }
298 ))
299 }