Debian Codegraph @

R/pandoc.R

raw
1 #' Indent text
2 #'
3 #' Indent all (optionally concatenated) lines of provided text with given level.
4 #' @param x character vector
5 #' @param level integer
6 #' @export
7 #' @examples
8 #' pandoc.indent('FOO', 1)
9 #' pandoc.indent(pandoc.table.return(table(mtcars$gear)), 2)
10 #' cat(pandoc.indent(pandoc.table.return(table(mtcars$gear)), 3))
11 pandoc.indent <- function(x, level = 0) {
12
13 if (!is.character(x)) {
14 stop('Only character strings are allowed.')
15 }
16 indent <- repChar(' ', level * 4)
17 res <- paste0(indent, gsub('\n', paste0('\n', indent), x))
18
19 ## remove wasted space
20 res <- gsub(' *\n', '\n', res)
21 res <- sub(' *$', '', res)
22
23 res
24
25 }
26
27
28 #' Paragraphs
29 #'
30 #' Pandoc's markdown paragraph.
31 #' @param x character vector
32 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
33 #' @export
34 #' @aliases pandoc.p
35 #' @seealso \code{\link{pandoc.emphasis}} \code{\link{pandoc.strikeout}} \code{\link{pandoc.verbatim}}
36 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
37 #' @examples
38 #' pandoc.p('FOO')
39 #' pandoc.p(c('Lorem', 'ipsum', 'lorem ipsum'))
40 pandoc.p.return <- function(x)
41 add.blank.lines(add.blank.lines(paste(x, collapse = '\n')))
42
43 #' @export
44 pandoc.p <- function(...)
45 cat(pandoc.p.return(...))
46
47
48 #' @keywords internal
49 pandoc.add.formatting <- function(x, f) {
50
51 attributes(x) <- NULL
52 if (!is.vector(x)) {
53 stop('Sorry, vectors only!')
54 }
55
56 ## escape chars
57 f.e <- gsub('*', '\\*', f, fixed = TRUE)
58
59 ## remove trailing or leading spaces
60 x <- trim.spaces(x)
61
62 ## do not stack formatting chars
63 w <- which(!grepl(sprintf('^%s.*%s$', f.e, f.e), x) & x != '')
64
65 ## add an extra space if the string starts with a formatting char
66 x[w] <- sapply(x[w],
67 function(x) ifelse(grepl(paste0('^', f.e), x), paste0('\\ ', x), x),
68 USE.NAMES = FALSE)
69
70 ## add formatting chars
71 x[w] <- paste0(f, x[w], f)
72
73 return(x)
74
75 }
76
77
78 #' Strong emphasis
79 #'
80 #' Pandoc's markdown strong emphasis format (e.g. \code{**FOO**}) is added to character string.
81 #' @param x character vector
82 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
83 #' @export
84 #' @aliases pandoc.strong
85 #' @seealso \code{\link{pandoc.emphasis}} \code{\link{pandoc.strikeout}} \code{\link{pandoc.verbatim}}
86 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
87 #' @examples
88 #' pandoc.strong('FOO')
89 #' pandoc.strong(c('FOO', '**FOO**'))
90 #' pandoc.strong.return('FOO')
91 pandoc.strong.return <- function(x)
92 pandoc.add.formatting(x, '**')
93
94 #' @export
95 pandoc.strong <- function(...)
96 cat(pandoc.strong.return(...))
97
98
99 #' Emphasis
100 #'
101 #' Pandoc's markdown emphasis format (e.g. \code{*FOO*}) is added to character string.
102 #' @param x character vector
103 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
104 #' @export
105 #' @aliases pandoc.emphasis
106 #' @seealso \code{\link{pandoc.strong}} \code{\link{pandoc.strikeout}} \code{\link{pandoc.verbatim}}
107 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
108 #' @examples
109 #' pandoc.emphasis('FOO')
110 #' pandoc.emphasis(c('FOO', '*FOO*'))
111 #' pandoc.emphasis.return('FOO')
112 pandoc.emphasis.return <- function(x)
113 pandoc.add.formatting(x, '*')
114
115 #' @export
116 pandoc.emphasis <- function(...)
117 cat(pandoc.emphasis.return(...))
118
119
120 #' Add strikeout
121 #'
122 #' Pandoc's markdown strikeout format (e.g. \code{~~FOO~~}) is added to character string.
123 #' @param x character vector
124 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
125 #' @export
126 #' @aliases pandoc.strikeout
127 #' @seealso \code{\link{pandoc.emphasis}} \code{\link{pandoc.strong}} \code{\link{pandoc.verbatim}}
128 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
129 #' @examples
130 #' pandoc.strikeout('FOO')
131 #' pandoc.strikeout(c('FOO', '~~FOO~~'))
132 #' pandoc.strikeout.return('FOO')
133 pandoc.strikeout.return <- function(x)
134 pandoc.add.formatting(x, '~~') #nolint
135
136 #' @export
137 pandoc.strikeout <- function(...)
138 cat(pandoc.strikeout.return(...))
139
140
141 #' Add verbatim
142 #'
143 #' Pandoc's markdown verbatim format (e.g. \code{`FOO`}) is added to character string.
144 #' @param x character vector
145 #' @param style show code \code{inline} or in a separate (\code{indent}ed or \code{delim}ited) block
146 #' @param attrs (optionally) pass ID, classes and any attribute to the \code{delimited} block
147 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
148 #' @export
149 #' @aliases pandoc.verbatim
150 #' @seealso \code{\link{pandoc.emphasis}} \code{\link{pandoc.strikeout}} \code{\link{pandoc.strong}}
151 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
152 #' @examples
153 #' # different styles/formats
154 #' pandoc.verbatim('FOO')
155 #'
156 #' src <- c('FOO', 'indent', 'BAR' )
157 #' pandoc.verbatim(src)
158 #' pandoc.verbatim.return(src)
159 #' pandoc.verbatim(c('FOOO\nBAR ', ' I do R'), 'indent')
160 #' pandoc.verbatim(c('FOOO\nBAR ', ' I do R'), 'delim')
161 #'
162 #' # add highlighting and HTML/LaTeX ID and classes (even custom attribute)
163 #' pandoc.verbatim(c('cat("FOO")', 'mean(bar)'), 'delim', '.R #MyCode custom_var="10"')
164 pandoc.verbatim.return <- function(x, style = c('inline', 'indent', 'delim'), attrs = '') {
165
166 style <- match.arg(style)
167 if (style != 'delim' & !missing(attrs)) {
168 warning('Providing attrs is only meaningful with delimited blocks.')
169 }
170
171 switch(style,
172 'inline' = paste0('`', trim.spaces(paste(x, collapse = ' ')), '`'),
173 'indent' = sprintf('\n%s\n',
174 paste(paste0(repChar(' ', 4), unlist(strsplit(trim.spaces(x), '\n')), collapse = '\n'))),
175 'delim' = paste0('\n', repChar('`', 7), ifelse(attrs == '', '', sprintf('{%s}', attrs)), '\n', paste(trim.spaces(x), collapse = '\n'), '\n', repChar('`', 7), '\n') #nolint
176 )
177
178 }
179
180 #' @export
181 pandoc.verbatim <- function(...)
182 cat(pandoc.verbatim.return(...))
183
184
185 #' Create pandoc link
186 #' Pandoc's markdown format link.
187 #' @param url hyperlink
188 #' @param text link text
189 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
190 #' @export
191 #' @aliases pandoc.link
192 #' @examples
193 #' pandoc.link('https://www.r-project.org/')
194 #' pandoc.link('https://www.r-project.org/', 'R')
195 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
196 pandoc.link.return <- function(url, text = url)
197 sprintf('[%s](%s)', text, url)
198
199 #' @export
200 pandoc.link <- function(...)
201 cat(pandoc.link.return(...))
202
203
204 #' Create pandoc image tags
205 #'
206 #' Creates a Pandoc's markdown format image hyperlink.
207 #' @param img image path
208 #' @param caption text
209 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
210 #' @export
211 #' @aliases pandoc.image
212 #' @seealso \code{\link{set.caption}}
213 #' @note The \code{caption} text is read from an internal buffer which defaults to \code{NULL}. To update that, call \code{link{set.caption}} before.
214 #' @examples
215 #' pandoc.image('foo.png')
216 #' pandoc.image('foo.png', 'Nice image, huh?')
217 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
218 pandoc.image.return <- function(img, caption = storage$caption) {
219
220 check_caption(caption)
221
222 if (is.null(caption)) {
223 caption <- ''
224 }
225
226 ## truncating caption buffer if needed
227 if (!is.null(storage$caption)) {
228 storage$caption <- NULL
229 }
230
231 sprintf('![%s](%s)', caption, img)
232 }
233
234 #' @export
235 pandoc.image <- function(...)
236 cat(pandoc.image.return(...))
237
238
239 #' Footnote
240 #'
241 #' Creates a Pandoc's markdown format footnote.
242 #' @param x character vector
243 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
244 #' @export
245 #' @aliases pandoc.footnote
246 #' @examples
247 #' pandoc.footnote('Automatically numbered footnote, right?')
248 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
249 pandoc.footnote.return <- function(x)
250 gsub('[\n][\n]*', '\n', sprintf('^[%s]', paste(x, collapse = ' ')))
251
252 #' @export
253 pandoc.footnote <- function(...)
254 cat(pandoc.footnote.return(...))
255
256
257 #' Create horizontal rule
258 #'
259 #' Creates a Pandoc's markdown format horizontal line with trailing and leading newlines.
260 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
261 #' @export
262 #' @aliases pandoc.horizontal.rule
263 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
264 pandoc.horizontal.rule.return <- function()
265 add.blank.lines('---')
266
267 #' @export
268 pandoc.horizontal.rule <- function(...)
269 cat(pandoc.horizontal.rule.return(...))
270
271
272 #' Create header
273 #'
274 #' Creates a (Pandoc's) markdown style header with given level.
275 #' @param x character vector
276 #' @param level integer
277 #' @param style atx or setext type of heading
278 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
279 #' @export
280 #' @aliases pandoc.header
281 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
282 #' @examples
283 #' pandoc.header('Foo!', 4)
284 #' pandoc.header('Foo!', 2, 'setext')
285 #' pandoc.header('Foo **bar**!', 1, 'setext')
286 pandoc.header.return <- function(x, level = 1, style = c('atx', 'setext')) {
287
288 if (missing(style)) {
289 style <- panderOptions('header.style')
290 } else {
291 style <- match.arg(style)
292 }
293
294 if (!is.numeric(level)) {
295 stop('Wrong level provided!')
296 }
297 if (any( (style == 'atx' & level > 6), (style == 'setext' & level > 2))) {
298 stop('Too high level provided!')
299 }
300 if (level < 1) {
301 stop('Too low level provided!')
302 }
303
304 res <- switch(style,
305 'atx' = paste(repChar('#', level), x),
306 'setext' = paste(x, repChar(ifelse(level == 1, '=', '-'), nchar(x, type = 'width')), sep = '\n')
307 )
308
309 add.blank.lines(res)
310
311 }
312
313 #' @export
314 pandoc.header <- function(...)
315 cat(pandoc.header.return(...))
316
317
318 #' Create title block
319 #'
320 #' Creates a Pandoc's markdown style title block with optional author, title and date fields.
321 #' @param author character vector or semicolon delimited list of authors without line break
322 #' @param title character vector of lines of title or multiline string with \code{\\n} separators
323 #' @param date any string fit in one line
324 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
325 #' @export
326 #' @aliases pandoc.title
327 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
328 #' @examples
329 #' pandoc.title('Tom', 'Render pandoc in R', '2012-05-16')
330 #' pandoc.title(c('Tom', 'Jerry'), 'Render pandoc in R', '2012-05-16')
331 #' pandoc.title('Tom; Jerry', 'Render pandoc in R', '2012-05-16')
332 #' pandoc.title('Tom; Jerry', c('Render', 'pandoc', 'in R'), '2012-05-16')
333 #' pandoc.title('Tom; Jerry', 'Render\n pandoc \n in R', '2012-05-16')
334 #'
335 #' ## missing fields
336 #'
337 #' pandoc.title('Tom; Jerry', 'Render pandoc in R')
338 #' pandoc.title('Tom; Jerry')
339 #' pandoc.title(title = 'Render pandoc in R', date= '2012-05-16')
340 pandoc.title.return <- function(author = '', title = '', date = '') {
341
342 ## updating title tags
343 if (length(author) > 1) {
344 author <- paste('%', paste(author, collapse = '; '))
345 }
346 if (length(title) > 1) {
347 title <- paste0(
348 '% ',
349 gsub('[\t ][\t ]*', ' ', gsub('\n', '\n ', paste(title, collapse = '\n'))))
350 }
351
352 if (author == '' && title == '' && date != '') {
353 stop('You cannot create a title with only date specified!')
354 }
355
356 ## formatting result
357 if (title == '') {
358 ## author
359 res <- paste0('%\n', author)
360 } else {
361 if (date == '') {
362 if (author == '') {
363 ## title
364 res <- title
365 } else {
366 ## author and title
367 res <- paste(title, author, sep = '\n')
368 }
369 } else {
370 date <- paste0('% ', gsub('\n', ' ', date)[1])
371 if (author == '') {
372 ## title and date
373 res <- paste(title, '%', date, sep = '\n')
374 } else {
375 ## author, title and date
376 res <- paste(title, author, date, sep = '\n')
377 }
378 }
379 }
380
381 sprintf('%s\n', res)
382
383 }
384
385 #' @export
386 pandoc.title <- function(...)
387 cat(pandoc.title.return(...))
388
389
390 #' Create a list
391 #'
392 #' Creates a Pandoc's markdown format list from provided character vector/list.
393 #' @param elements character vector of strings
394 #' @param style the required style of the list
395 #' @param loose adding a newline between elements
396 #' @param add.line.breaks adding a leading and trailing newline before/after the list
397 #' @param add.end.of.list adding a separator comment after the list
398 #' @param indent.level the level of indent
399 #' @param missing string to replace missing values
400 #' @param ... extra arguments passed by from parent call, disregarded
401 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
402 #' @export
403 #' @aliases pandoc.list
404 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
405 #' @examples
406 #' ## basic lists
407 #' pandoc.list(letters[1:5])
408 #' pandoc.list(letters[1:5])
409 #' pandoc.list(letters[1:5], 'ordered')
410 #' pandoc.list(letters[1:5], 'roman')
411 #' pandoc.list(letters[1:5], loose = TRUE)
412 #'
413 #' ## nested lists
414 #' l <- list("First list element",
415 #' rep.int('sub element', 5),
416 #' "Second element",
417 #' list('F', 'B', 'I', c('phone', 'pad', 'talics')))
418 #' pandoc.list(l)
419 #' pandoc.list(l, loose = TRUE)
420 #' pandoc.list(l, 'roman')
421 #'
422 #' ## complex nested lists
423 #' pandoc.list(list('one', as.list(2)))
424 #' pandoc.list(list('one', list('two')))
425 #' pandoc.list(list('one', list(2:3)))
426 #' @importFrom utils as.roman
427 pandoc.list.return <- function(elements, style = c('bullet', 'ordered', 'roman'), loose = FALSE, add.line.breaks = TRUE, add.end.of.list = TRUE, indent.level = 0, missing = panderOptions('missing'), ...) { #nolint
428
429 ## checks
430 if (!is.logical(loose)) {
431 stop('Wrong argument provided: loose')
432 }
433
434 ## default values
435 if (missing(style)) {
436 style <- panderOptions('list.style')
437 } else {
438 style <- match.arg(style)
439 }
440
441 ## replace missing values
442 w <- which(is.na(elements))
443 if (length(w) > 0) {
444 elements[w] <- missing
445 }
446
447 ## helpers
448 elements.l <- length(elements)
449 marker <- switch(style,
450 'bullet' = rep('* ', elements.l),
451 'ordered' = paste0(1:elements.l, '. '),
452 'roman' = paste0(as.roman(1:elements.l), '. '))
453
454 ## number of elements should be more than one
455 if (elements.l == 0) {
456 return('')
457 }
458
459 ## recursive call
460 i.lag <- 0
461 res <- ifelse(add.line.breaks, '\n', '')
462 res <- paste(sapply(1:elements.l, function(i) {
463 if (length(elements[[i]]) == 1 && !is.list(elements[[i]])) {
464 paste0(paste(rep(' ', indent.level * 4), collapse = ''), marker[i - i.lag], elements[i])
465 } else {
466 i.lag <<- i.lag + 1
467 pandoc.list.return(elements[[i]], style, loose, FALSE, FALSE, indent.level + 1)
468 }}),
469 collapse = '\n', ifelse(loose, '\n', ''))
470
471 ## closing tag
472 if (add.end.of.list) {
473 res <- paste0(res, ifelse(loose, '', '\n\n'), '<!-- end of list -->\n')
474 }
475 if (add.line.breaks) {
476 res <- add.blank.lines(res)
477 }
478
479 return(res)
480
481 }
482
483 #' @export
484 pandoc.list <- function(...)
485 cat(pandoc.list.return(...))
486
487
488 #' Create a table
489 #'
490 #' Creates a Pandoc's markdown style table with optional caption and some other tweaks. See 'Details' below.
491 #'
492 #' This function takes any tabular data as its first argument and will try to make it pretty like: rounding and applying \code{digits} and custom \code{decimal.mark} to numbers, auto-recognizing if row names should be included, setting alignment of cells and dropping trailing zeros by default.
493 #'
494 #' \code{pandoc.table} also tries to split large cells with line breaks or even the whole table to separate parts on demand. Other arguments lets the use to highlight some rows/cells/cells in the table with italic or bold text style.
495 #'
496 #' For more details please see the parameters above and passed arguments of \code{\link{panderOptions}}.
497 #' @param t data frame, matrix or table
498 #' @param caption caption (string) to be shown under the table
499 #' @param digits passed to \code{format}. Can be a vector specifying values for each column (has to be the same length as number of columns).
500 #' @param decimal.mark passed to \code{format}
501 #' @param big.mark passed to \code{format}
502 #' @param round passed to \code{round}. Can be a vector specifying values for each column (has to be the same length as number of columns). Values for non-numeric columns will be disregarded.
503 #' @param missing string to replace missing values
504 #' @param justify defines alignment in cells passed to \code{format}. Can be \code{left}, \code{right} or \code{centre}, which latter can be also spelled as \code{center}. Defaults to \code{centre}. Can be abbreviated to a string consisting of the letters \code{l}, \code{c} and \code{r} (e.g. 'lcr' instead of c('left', 'centre', 'right').
505 #' @param style which Pandoc style to use: \code{simple}, \code{multiline}, \code{grid} or \code{rmarkdown}
506 #' @param split.tables where to split wide tables to separate tables. The default value (\code{80}) suggests the conventional number of characters used in a line, feel free to change (e.g. to \code{Inf} to disable this feature) if you are not using a VT100 terminal any more :)
507 #' @param split.cells where to split cells' text with line breaks. Default to \code{30}, to disable set to \code{Inf}. Can be also supplied as a vector, for each cell separately (if length(split.cells) == number of columns + 1, then first value in split.cells if for row names, and others are for columns). Supports relative (percentage) parameters in combination with split.tables.
508 #' @param keep.trailing.zeros to show or remove trailing zeros in numbers on a column basis width
509 #' @param keep.line.breaks (default: \code{FALSE}) if to keep or remove line breaks from cells in a table
510 #' @param plain.ascii (default: \code{FALSE}) if output should be in plain ascii (without markdown markup) or not
511 #' @param use.hyphening boolean (default: \code{FALSE}) if try to use hyphening when splitting large cells according to table.split.cells. Requires \pkg{sylly}.
512 #' @param row.names if \code{FALSE}, row names are suppressed. A character vector of row names can also be specified here. By default, row names are included if \code{rownames(t)} is neither
513 #' \code{NULL} nor identical to \code{1:nrow(x)}
514 #' @param col.names a character vector of column names to be used in the table
515 #' @param emphasize.rownames boolean (default: \code{TRUE}) if row names should be highlighted
516 #' @param emphasize.rows deprecated for \code{emphasize.italics.rows} argument
517 #' @param emphasize.cols deprecated for \code{emphasize.italics.cols} argument
518 #' @param emphasize.cells deprecated for \code{emphasize.italics.cells} argument
519 #' @param emphasize.italics.rows a vector for a two dimensional table specifying which rows to emphasize
520 #' @param emphasize.italics.cols a vector for a two dimensional table specifying which cols to emphasize
521 #' @param emphasize.italics.cells a vector for one-dimensional tables or a matrix like structure with two columns for row and column indexes to be emphasized in two dimensional tables. See e.g. \code{which(..., arr.ind = TRUE)}
522 #' @param emphasize.strong.rows see \code{emphasize.italics.rows} but in bold
523 #' @param emphasize.strong.cols see \code{emphasize.italics.cols} but in bold
524 #' @param emphasize.strong.cells see \code{emphasize.italics.cells} but in bold
525 #' @param emphasize.verbatim.rows see \code{emphasize.italics.rows} but in verbatim
526 #' @param emphasize.verbatim.cols see \code{emphasize.italics.cols} but in verbatim
527 #' @param emphasize.verbatim.cells see \code{emphasize.italics.cells} but in verbatim
528 #' @param ... unsupported extra arguments directly placed into \code{/dev/null}
529 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call \code{pandoc.table.return} instead.
530 #' @export
531 #' @useDynLib pander
532 #' @importFrom Rcpp evalCpp
533 #' @importFrom stats ftable
534 #' @aliases pandoc.table
535 #' @seealso \code{\link{set.caption}}, \code{\link{set.alignment}}
536 #' @note If \code{caption} is missing, then the value is first checked in \code{t} object's \code{caption} attribute and if not found in an internal buffer set by \code{link{set.caption}}. \code{justify} parameter works similarly, see \code{\link{set.alignment}} for details.
537 #' @references John MacFarlane (2012): _Pandoc User's Guide_. \url{https://johnmacfarlane.net/pandoc/README.html}
538 #' @examples
539 #' pandoc.table(mtcars)
540 #'
541 #' # caption
542 #' pandoc.table(mtcars, 'Motor Trend Car Road Tests')
543 #'
544 #' # other input/output formats
545 #' pandoc.table(mtcars[, 1:3], decimal.mark = ',')
546 #' pandoc.table(mtcars[, 1:3], decimal.mark = ',', justify = 'right')
547 #' pandoc.table(matrix(sample(1:1000, 25), 5, 5))
548 #' pandoc.table(matrix(runif(25), 5, 5))
549 #' pandoc.table(matrix(runif(25), 5, 5), digits = 5)
550 #' pandoc.table(matrix(runif(25),5,5), round = 1)
551 #' pandoc.table(table(mtcars$am))
552 #' pandoc.table(table(mtcars$am, mtcars$gear))
553 #' pandoc.table(table(state.division, state.region))
554 #' pandoc.table(table(state.division, state.region), justify = 'centre')
555 #'
556 #' m <- data.frame(a = c(1, -500, 10320, 23, 77),
557 #' b = runif(5),
558 #' c = c('a', 'bb', 'ccc', 'dddd', 'eeeee'))
559 #' pandoc.table(m)
560 #' pandoc.table(m, justify = c('right', 'left', 'centre'))
561 #' pandoc.table(m, justify = 'rlc') # Same as upper statement
562 #'
563 #' ## splitting up too wide tables
564 #' pandoc.table(mtcars)
565 #' pandoc.table(mtcars, caption = 'Only once after the first part!')
566 #'
567 #' ## tables with line breaks in cells
568 #' ## NOTE: line breaks are removed from table content in case keep.line.breaks is set to FALSE
569 #' ## and added automatically based on "split.cells" parameter!
570 #' t <- data.frame(a = c('hundreds\nof\nmouses', '3 cats'), b=c('FOO is nice', 'BAR\nBAR2'))
571 #' pandoc.table(t)
572 #' pandoc.table(t, split.cells = 5)
573 #'
574 #' ## exporting tables in other Pandoc styles
575 #' pandoc.table(m)
576 #' pandoc.table(m, style = "grid")
577 #' pandoc.table(m, style = "simple")
578 #' pandoc.table(t, style = "grid")
579 #' pandoc.table(t, style = "grid", split.cells = 5)
580 #' tryCatch(pandoc.table(t, style = "simple", split.cells = 5),
581 #' error = function(e) 'Yeah, no newline support in simple tables')
582 #'
583 #' ## highlight cells
584 #' t <- mtcars[1:3, 1:5]
585 #' pandoc.table(t$mpg, emphasize.italics.cells = 1)
586 #' pandoc.table(t$mpg, emphasize.strong.cells = 1)
587 #' pandoc.table(t$mpg, emphasize.italics.cells = 1, emphasize.strong.cells = 1)
588 #' pandoc.table(t$mpg, emphasize.italics.cells = 1:2)
589 #' pandoc.table(t$mpg, emphasize.strong.cells = 1:2)
590 #' pandoc.table(t, emphasize.italics.cells = which(t > 20, arr.ind = TRUE))
591 #' pandoc.table(t, emphasize.italics.cells = which(t == 6, arr.ind = TRUE))
592 #' pandoc.table(t, emphasize.verbatim.cells = which(t == 6, arr.ind = TRUE))
593 #' pandoc.table(t, emphasize.verbatim.cells = which(t == 6, arr.ind = TRUE),
594 #' emphasize.italics.rows = 1)
595 #' ## with helpers
596 #' emphasize.cols(1)
597 #' emphasize.rows(1)
598 #' pandoc.table(t)
599 #'
600 #' emphasize.strong.cells(which(t > 20, arr.ind = TRUE))
601 #' pandoc.table(t)
602 #'
603 #' ### plain.ascii
604 #' pandoc.table(mtcars[1:3, 1:3], plain.ascii = TRUE)
605 #'
606 #' ### keep.line.breaks
607 #' x <- data.frame(a="Pandoc\nPackage")
608 #' pandoc.table(x)
609 #' pandoc.table(x, keep.line.breaks = TRUE)
610 #'
611 #' ## split.cells
612 #' x <- data.frame(a = "foo bar", b = "foo bar")
613 #' pandoc.table(x, split.cells = 4)
614 #' pandoc.table(x, split.cells = 7)
615 #' pandoc.table(x, split.cells = c(4, 7))
616 #' pandoc.table(x, split.cells = c("20%", "80%"), split.tables = 30)
617 #'
618 #' y <- c("aa aa aa", "aaa aaa", "a a a a a", "aaaaa", "bbbb bbbb bbbb", "bb bbb bbbb")
619 #' y <- matrix(y, ncol = 3, nrow = 2)
620 #' rownames(y) <- c("rowname one", "rowname two")
621 #' colnames(y) <- c("colname one", "colname two", "colname three")
622 #' pandoc.table(y, split.cells = 2)
623 #' pandoc.table(y, split.cells = 6)
624 #' pandoc.table(y, split.cells = c(2, 6, 10))
625 #' pandoc.table(y, split.cells = c(2, Inf, Inf))
626 #'
627 #' ## first value used for rownames
628 #' pander(y, split.cells = c(5, 2, Inf, Inf))
629 #' pandoc.table(y, split.cells = c(5, 2, Inf, 5, 3, 10))
630 #'
631 #' ## when not enough reverting to default values
632 #' pandoc.table(y, split.cells = c(5, 2))
633 #'
634 #' ## split.cells with hyphenation
635 #' x <- data.frame(a = "Can be also supplied as a vector, for each cell separately",
636 #' b = "Can be also supplied as a vector, for each cell separately")
637 #' pandoc.table(x, split.cells = 10, use.hyphening = TRUE)
638 pandoc.table.return <- function(t, caption, digits = panderOptions('digits'), decimal.mark = panderOptions('decimal.mark'), big.mark = panderOptions('big.mark'), round = panderOptions('round'), missing = panderOptions('missing'), justify, style = c('multiline', 'grid', 'simple', 'rmarkdown', 'jira'), split.tables = panderOptions('table.split.table'), split.cells = panderOptions('table.split.cells'), keep.trailing.zeros = panderOptions('keep.trailing.zeros'), keep.line.breaks = panderOptions('keep.line.breaks'), plain.ascii = panderOptions('plain.ascii'), use.hyphening = panderOptions('use.hyphening'), row.names, col.names, emphasize.rownames = panderOptions('table.emphasize.rownames'), emphasize.rows, emphasize.cols, emphasize.cells, emphasize.strong.rows, emphasize.strong.cols, emphasize.strong.cells, emphasize.italics.rows, emphasize.italics.cols, emphasize.italics.cells, emphasize.verbatim.rows, emphasize.verbatim.cols, emphasize.verbatim.cells, ...) { #nolint
639
640 row.names.provided <- !missing(row.names)
641
642 ## expands cells for output
643 table.expand <- function(cells, cols.width, justify, sep.cols) {
644 ## fix encoding issue in C++ on Windows
645 if (l10n_info()$`UTF-8` == FALSE) {
646 cells <- enc2native(cells)
647 }
648 tableExpand_cpp(cells, cols.width, justify, sep.cols, style)
649 }
650
651 ## cell conversion to plain-ascii (deletion of markup characters)
652 to.plain.ascii <- function(x){
653 x <- gsub('[\\\\]', '', x) # backslashes
654 x <- gsub('&nbsp;', ' ', x) # table non-breaking space
655 x <- gsub('[*]+([^\\*.]*)[*]+', '\\1', x) # emphasis and strong
656 x <- gsub('^[`]|[`]$', '', x) # verbatium
657 x <- gsub('^[~]{2}|[~]{2}$', '', x) # strikeout
658 gsub('^[_]|[_]$', '', x) # italic
659 }
660
661 ## split single cell with line breaks based on max.width
662 split.single.cell <- function(x, max.width){
663 if (!is.character(x)) {
664 x <- as.character(x)
665 }
666 ## as.character(NA) remains NA, which causes isses with nchar since 2015-04-23
667 ## https://stat.ethz.ch/pipermail/r-devel/2015-April/071007.html
668 if (is.na(x)) {
669 x <- 'NA'
670 }
671 if (!style %in% c('simple', 'rmarkdown')) {
672 ## split
673 if (nchar(x) == nchar(encodeString(x)) && !use.hyphening) {
674 x <- paste(strwrap(x, width = max.width + 1), collapse = '\n')
675 } else {
676 ## dealing with CJK chars + also it does not count \n, \t, etc.
677 ## this happens because width - counts only the number of columns
678 ## cat will use to print the string in a monospaced font.
679 if (!keep.line.breaks){
680 x <- gsub('\n', ' ', x)
681 x <- splitLine(x, max.width, use.hyphening)
682 } else {
683 lines <- strsplit(x, '\\n')[[1]]
684 x <- ''
685 for (line in lines) {
686 sl <- splitLine(line, max.width, use.hyphening)
687 x <- paste0(x, sl, sep = '\n')
688 }
689 }
690 }
691 }else{
692 x <- gsub('^\\s+|\\s+$', '', x)
693 }
694 x
695 }
696
697 split.large.cells <- function(cells, for.rownames = FALSE) {
698
699 ## if we have a single value, extend it to a vector to do less checks laters
700 if (length(split.cells) == 1) {
701 split.cells <- rep(split.cells, length(cells))
702 }
703 if (for.rownames) {
704 ## in case it is used for rownames, we only need the first value
705 split.cells <- rep(split.cells[1], length(cells))
706 }
707
708 res <- NULL
709 rn <- rownames(cells)
710 ## single value and vectors/lists
711 if (length(dim(cells)) < 2) {
712
713 ## discard first value which was for rownames
714 if (!for.rownames && (length(split.cells) >= length(cells) + 1)) {
715 split.cells <- split.cells[-1]
716 }
717
718 if (length(cells) > length(split.cells)) {
719 warning('length of split.cells vector is smaller than data. Default value will be used for other cells') #nolint
720 split.cells <- c(split.cells, rep(panderOptions('table.split.cells'), length(cells) - length(split.cells))) #nolint
721 }
722 res <- sapply(seq_along(cells), function(x, i) split.single.cell(x[i], max.width = split.cells[i]), x = cells, USE.NAMES = FALSE) #nolint
723
724 } else {
725 ## matrixes and tables
726 ## discard first value which was for rownames
727 if (length(split.cells) >= dim(cells)[2] + 1) {
728 split.cells <- split.cells[-1]
729 }
730
731 if (dim(cells)[2] > length(split.cells)) {
732 warning('length of split.cells vector is smaller than data. Default value will be used for other cells')
733 split.cells <- c(split.cells, rep(panderOptions('table.split.cells'),
734 dim(cells)[2] - length(split.cells)))
735 }
736
737 for (j in 1:dim(cells)[2]) {
738 res <- cbind(res, sapply(cells[, j], split.single.cell, max.width = split.cells[j], USE.NAMES = FALSE))
739 }
740
741 }
742 rownames(res) <- rn
743 ## return
744 res
745
746 }
747
748 align.hdr <- function(t.width, justify) {
749 justify.vec <- rep(justify, length.out = length(t.width))
750 dashes <- mapply(function(justify, width)
751 switch(
752 justify,
753 left = paste0(':', repChar('-', width + 1)),
754 right = paste0(repChar('-', width + 1), ':'),
755 centre = paste0(':', repChar('-', width), ':')
756 ),
757 justify.vec, t.width)
758 hdr <- paste0('|', paste(dashes, collapse = '|'), '|')
759 return(hdr)
760 }
761 is.wholenumber <- function(x, tol = .Machine$double.eps ^ 0.5)
762 abs(x - round(x)) < tol
763 check.highlight.parameters <- function(x, num, num2) {
764 if (!all(is.wholenumber(x))){
765 stop('Only integers (whole numbers) can be passed to highlight table cell(s), row(s) or column(s).')
766 }
767 if (!all(x > 0)) {
768 stop('Only positive numbers can be passed to highlight table cell(s), row(s) or column(s).')
769 }
770 if (missing(num2)) {
771 if (!is.vector(x)) {
772 stop('Only a vector or NULL can be passed to highlight table cell(s), row(s) or column(s).')
773 }
774 if (!all(x < (num + 1))) {
775 stop(paste('Too high number passed that should be kept below', num + 1))
776 }
777 } else {
778 if (ncol(x) != 2) {
779 stop('A matrix like structure should be passed to highlight cells of a table with two columns for row and column indexes - just like what is returned by `which(..., arr.ind = TRUE)`.') #nolint
780 }
781 if (!all(x[, 1] < (num + 1))) {
782 stop(paste('Too high number passed for row indexes that should be kept below', num + 1))
783 }
784 if (!all(x[, 2] < (num2 + 1))) {
785 stop(paste('Too high number passed for column indexes that should be kept below', num + 1))
786 }
787 }
788 }
789
790 ## #########################################################################
791 ## converting the table into intermediate representation
792 ## #########################################################################
793
794 ## revert dplyr to a normal data.frame
795 if (inherits(t, 'tbl_df')) {
796 t <- as.data.frame(t)
797 }
798
799 ## we have a high-dimensional table to be converted to 2D
800 if (length(dim(t)) > 2){
801 t <- ftable(t)
802
803 } else {
804
805 ## we have a pseudo-table with only one or NULL dimension
806 if (length(dim(t)) < 2) {
807
808 tn <- names(t)
809
810 ## print.summaryDefault stores NAs in a very special way
811 ## see eg: pander(summary(c(Sys.Date(), NA)))
812 if ( (inherits(t, 'Date') || inherits(t, 'POSIXct')) & length(attr(t, 'NAs'))) {
813 tn <- c(tn, 'NAs')
814 }
815
816 ## matrix/rbind will coerce cells to atomic (e.g. Date to numeric)
817 ## so we should first convert these values to a character vector
818 if (!is.numeric(t)) {
819 t <- as.character(t)
820 }
821
822 ## make a table
823 t <- rbind(matrix(nrow = 0, ncol = length(t)), t)
824
825 ## restore col/row names
826 colnames(t) <- tn
827 rownames(t) <- NULL
828
829 ## special conversion for emphasize.cells, emphasize.strong.cells
830 if (!missing(emphasize.cells)) {
831 emphasize.cells <- cbind(rep(1, length(emphasize.cells)), emphasize.cells)
832 }
833 if (!missing(emphasize.verbatim.cells)) {
834 emphasize.verbatim.cells <- cbind(rep(1, length(emphasize.verbatim.cells)), emphasize.verbatim.cells)
835 }
836 if (!missing(emphasize.italics.cells)) {
837 emphasize.italics.cells <- cbind(rep(1, length(emphasize.italics.cells)), emphasize.italics.cells)
838 }
839 if (!missing(emphasize.strong.cells)) {
840 emphasize.strong.cells <- cbind(rep(1, length(emphasize.strong.cells)), emphasize.strong.cells)
841 }
842
843 } else {
844 if (dim(t)[1] == 0) {
845 ## check for empty objects
846 if (!is.null(colnames(t)) && length(colnames(t)) > 0) {
847 t <- matrix(data = pandoc.strong.return(colnames(t)), nrow = 1)
848 } else {
849 warning('Object is empty and without header. No output will be produced')
850 return(invisible())
851 }
852 }
853 }
854 }
855
856
857 ## #########################################################################
858 ## check passed parameters and set sane defaults
859 ## #########################################################################
860
861 ## check correct split.cells param
862 if (length(split.cells) == 0) {
863 warning('split.cells is a vector of length 0, reverting to default value')
864 split.cells <- panderOptions('table.split.cells')
865 }
866
867 ## check for relative split.cells
868 if (all(grepl('%$', split.cells))){
869 d <- dim(t)[2]
870 split.cells <- as.numeric(gsub('%$', '', split.cells))
871 if (sum(split.cells) == 100){
872 if (is.infinite(split.tables)){
873 warning('Split.tables is an infinite value, so split cells can\'t be suplied as relative value. Reverting to default') #nolint
874 split.cells <- panderOptions('table.split.cells')
875 } else{
876 d <- ifelse(length(rownames(t)) != 0, d, d + 1)
877 if (length(split.cells) < d) {
878 cat('d - ', d, '\n')
879 warning('Using relative split.cells require a value for every column and rownames. Reverting to default') #nolint
880 split.cells <- panderOptions('table.split.cells')
881 } else {
882 split.cells <- round(split.cells * 0.01 * split.tables)
883 }
884 }
885 } else {
886 warning('Supplied relative values don\'t add up to 100%. Reverting to default')
887 split.cells <- panderOptions('table.split.cells')
888 }
889 }
890
891 ## initializing
892 mc <- match.call()
893 if (is.null(mc$style)) {
894 style <- panderOptions('table.style')
895 } else {
896 style <- match.arg(style)
897 }
898 if (row.names.provided) {
899 if (identical(row.names, FALSE)) {
900 rownames(t) <- NULL
901 row.names.provided <- FALSE
902 } else {
903 rownames(t) <- row.names
904 }
905 }
906 if (!missing(col.names)) {
907 colnames(t) <- col.names
908 }
909 if (is.null(mc$justify)) {
910 if (is.null(attr(t, 'alignment'))) {
911 if (inherits(t, 'ftable')) {
912 justify <- get.alignment(format(t), remove.obious.rownames = !row.names.provided)
913 } else {
914 justify <- get.alignment(t, remove.obious.rownames = !row.names.provided)
915 }
916 } else {
917 justify <- attr(t, 'alignment')
918 }
919 }
920 if (is.null(mc$caption)) {
921 if (is.null(attr(t, 'caption'))) {
922 caption <- get.caption()
923 } else {
924 caption <- attr(t, 'caption')
925 }
926 }
927
928
929 ## check if emphasize parameters were passed
930 emphasize.parameters <- c('emphasize.rows',
931 'emphasize.cols',
932 'emphasize.cells',
933 'emphasize.strong.rows',
934 'emphasize.strong.cols',
935 'emphasize.strong.cells',
936 'emphasize.italics.rows',
937 'emphasize.italics.cols',
938 'emphasize.italics.cells',
939 'emphasize.verbatim.rows',
940 'emphasize.verbatim.cols',
941 'emphasize.verbatim.cells')
942 if (all(sapply(emphasize.parameters, function(p) is.null(mc[[p]]), USE.NAMES = FALSE))) {
943 ## check if emphasize parameters were set in attributes
944 if (all(sapply(emphasize.parameters, function(p) is.null(attr(t, p)), USE.NAMES = FALSE))) {
945 t <- get.emphasize(t)
946 }
947 ## set emphasize parameters at last
948 for (p in emphasize.parameters) {
949 assign(p, attr(t, p))
950 }
951 } else {
952 ## some emphasize parameters passed, other should be set to NULL
953 for (p in emphasize.parameters) {
954 if (is.null(mc[[p]])) {
955 assign(p, NULL)
956 }
957 }
958 }
959 res <- ''
960
961 ## store missing values
962 wm <- which(is.na(t), arr.ind = TRUE)
963
964 ## #########################################################################
965 ## update numeric values
966 ## #########################################################################
967
968 ## round numbers & cut digits & apply decimal mark & optionally remove trailing zeros
969 digits <- check_digits(digits, 'digits', ncol(t))
970
971 ## Temporary conversion of matrix to data.frame,
972 ## because matrix columns can't be formatted separately:
973 ## as soon as first column is formatted all others are fomatted too.
974 ## Formatting each column separately is needed
975 ## to support digits and round params as vectors with values for each column.
976 rn <- rownames(t)
977 cln <- colnames(t)
978 if (inherits(t, 'matrix') & !inherits(t, 'table')) {
979 rownames(t) <- NULL
980 temp.t <- t <- as.data.frame(t)
981 } else {
982 temp.t <- t
983 }
984 t.n <- which(sapply(1:ncol(t), function(x) is.numeric(t[, x])))
985 if (length(t.n) > 0) {
986 ## make sure it's numeric (eg convert integer64 first as sapply having issues)
987 ## see eg: sapply(bit64::as.integer64(1:5), format)
988 for (j in t.n) {
989 t[, j] <- as.numeric(t[, j])
990 }
991 ## round digits as needed
992 round <- check_digits(round, 'round', ncol(t))
993 ## for-loop is needed to preserve row/col names and use index to get appropriate value from round vector
994 for (j in 1:ncol(temp.t)) {
995 if (j %in% t.n) {
996 t[, j] <- round(t[, j], digits = round[j])
997 }
998 }
999 if (!keep.trailing.zeros) {
1000 ## for-loop is needed to preserve row/col names and use index to get appropriate value from digits vector
1001 for (j in 1:ncol(temp.t)) {
1002 temp.t[, j] <- sapply(t[, j],
1003 format,
1004 trim = TRUE,
1005 digits = digits[j],
1006 decimal.mark = decimal.mark,
1007 big.mark = big.mark,
1008 quote = FALSE)
1009 }
1010 }
1011 }
1012
1013 ## drop unexpected classes and revert back to a common format
1014 if (keep.trailing.zeros) {
1015 ## for-loop is needed to preserve row/col names and use index to get appropriate value from digits vector
1016 for (j in 1:ncol(t)) {
1017 temp.t[, j] <- format(t[, j],
1018 trim = TRUE,
1019 digits = digits[j],
1020 decimal.mark = decimal.mark,
1021 big.mark = big.mark,
1022 quote = FALSE)
1023 }
1024 } else {
1025 ## here adds unneeded zero's
1026 temp.t <- format(temp.t, trim = TRUE, quote = FALSE)
1027 }
1028
1029 ## transform to matrix with proper row/colnames
1030 t <- as.matrix(temp.t)
1031 colnames(t) <- cln
1032 rownames(t) <- rn
1033
1034 ## force all non-numeric cells to character vectors
1035 wf <- which(sapply(t, is.factor))
1036 if (length(wf) > 0) {
1037 t[, wf] <- apply(t[wf], 2, as.character)
1038 }
1039
1040 ## replace missing values
1041 if (length(wm) > 0) {
1042 t[wm] <- missing
1043 }
1044
1045 ## #########################################################################
1046 ## adding formatting (emphasis, strong etc.)
1047 ## #########################################################################
1048
1049 is.empty <- function(x) {
1050 is.null(x) || length(x) == 0
1051 }
1052
1053 if (is.null(emphasize.italics.rows)) {
1054 emphasize.italics.rows <- emphasize.rows
1055 }
1056 if (is.null(emphasize.italics.cols)) {
1057 emphasize.italics.cols <- emphasize.cols
1058 }
1059 if (is.null(emphasize.italics.cells)) {
1060 emphasize.italics.cells <- emphasize.cells
1061 }
1062 if (!is.empty(emphasize.verbatim.rows) && !plain.ascii) {
1063 check.highlight.parameters(emphasize.verbatim.rows, nrow(t))
1064 t[emphasize.verbatim.rows, ] <- apply(t[emphasize.verbatim.rows, , drop = FALSE], #nolint
1065 c(1, 2),
1066 pandoc.verbatim.return)
1067 }
1068 if (!is.empty(emphasize.verbatim.cols) && !plain.ascii) {
1069 check.highlight.parameters(emphasize.verbatim.cols, ncol(t))
1070 t[, emphasize.verbatim.cols] <- apply(t[, emphasize.verbatim.cols, drop = FALSE],
1071 c(1, 2), pandoc.verbatim.return)
1072 }
1073 if (!is.empty(emphasize.verbatim.cells) && !plain.ascii) {
1074 t <- as.matrix(t)
1075 check.highlight.parameters(emphasize.verbatim.cells, nrow(t), ncol(t))
1076 t[emphasize.verbatim.cells] <- sapply(t[emphasize.verbatim.cells], pandoc.verbatim.return)
1077 }
1078 if (!is.empty(emphasize.italics.rows) && !plain.ascii) {
1079 check.highlight.parameters(emphasize.italics.rows, nrow(t))
1080 t[emphasize.italics.rows, ] <- base::t(apply(t[emphasize.italics.rows, , drop = FALSE], #nolint
1081 c(1),
1082 pandoc.emphasis.return))
1083 }
1084 if (!is.empty(emphasize.strong.rows) && !plain.ascii) {
1085 check.highlight.parameters(emphasize.strong.rows, nrow(t))
1086 t[emphasize.strong.rows, ] <- base::t(apply(t[emphasize.strong.rows, , drop = FALSE], #nolint
1087 c(1),
1088 pandoc.strong.return))
1089 }
1090 if (!is.empty(emphasize.italics.cols) && !plain.ascii) {
1091 check.highlight.parameters(emphasize.italics.cols, ncol(t))
1092 t[, emphasize.italics.cols] <- apply(t[, emphasize.italics.cols, drop = FALSE], c(2), pandoc.emphasis.return)
1093 }
1094 if (!is.empty(emphasize.strong.cols) && !plain.ascii) {
1095 check.highlight.parameters(emphasize.strong.cols, ncol(t))
1096 t[, emphasize.strong.cols] <- apply(t[, emphasize.strong.cols, drop = FALSE], c(2), pandoc.strong.return)
1097 }
1098 if (!is.empty(emphasize.italics.cells) && !plain.ascii) {
1099 t <- as.matrix(t)
1100 check.highlight.parameters(emphasize.italics.cells, nrow(t), ncol(t))
1101 t[emphasize.italics.cells] <- pandoc.emphasis.return(t[emphasize.italics.cells])
1102 }
1103 if (!is.empty(emphasize.strong.cells) && !plain.ascii) {
1104 t <- as.matrix(t)
1105 check.highlight.parameters(emphasize.strong.cells, nrow(t), ncol(t))
1106 t[emphasize.strong.cells] <- pandoc.strong.return(t[emphasize.strong.cells])
1107 }
1108
1109 ## #########################################################################
1110 ## (re)set row and column names
1111 ## #########################################################################
1112
1113 ## get (col/row)names if any
1114 t.colnames <- tryCatch(colnames(t), error = function(e) NULL)
1115 t.rownames <- tryCatch(rownames(t), error = function(e) NULL)
1116
1117 ## fixed for incorrect pipelining with rmarkdown (#186)
1118 if (style == 'rmarkdown') {
1119 t <- apply(t, c(1,2), function(x) gsub('\\|', '\\\\|', x)) #nolint
1120 t.rownames <- sapply(t.rownames, function(x) gsub('\\|', '\\\\|', x)) #nolint
1121 }
1122
1123 t <- split.large.cells(t)
1124
1125 ## re-set col/rownames to be passed to split tables
1126 if (!is.null(t.rownames)) {
1127 rownames(t) <- t.rownames
1128 }
1129 if (!is.null(t.colnames)) {
1130 colnames(t) <- t.colnames
1131 }
1132
1133 ## #########################################################################
1134 ## compute column width
1135 ## #########################################################################
1136
1137 if (plain.ascii) {
1138 t <- apply(t, c(1, 2), to.plain.ascii)
1139 }
1140
1141 ## header width
1142 if (!is.null(t.colnames)) {
1143 t.colnames <- replace(t.colnames, which(t.colnames == ''), '&nbsp;')
1144 t.colnames <- split.large.cells(t.colnames)
1145 t.colnames.width <- sapply(t.colnames,
1146 function(x) max(nchar(strsplit(x, '\n')[[1]], type = 'width'), 0),
1147 USE.NAMES = FALSE)
1148 } else {
1149 t.colnames.width <- 0
1150 }
1151
1152 ## remove traling spaces, because they affect formatting negatively
1153 t <- apply(t, c(1, 2), function(x) gsub('[[:space:]]*$', '', x))
1154
1155 ## also dealing with cells split by newlines
1156 t.width <- as.numeric(apply(cbind(t.colnames.width, apply(t, 2, function(x) max(sapply(strsplit(x,'\n'), function(x) max(nchar(x, type = 'width'), 0))))), 1, max)) #nolint
1157
1158 ## remove obvious row.names
1159 if ((!row.names.provided && (all(t.rownames == 1:nrow(t)) | all(t.rownames == ''))) |
1160 row.names.provided && length(row.names) == 1 && row.names == FALSE) {
1161 t.rownames <- NULL
1162 }
1163
1164 if (!is.null(t.rownames) && emphasize.rownames) {
1165 t.rownames <- pandoc.strong.return(t.rownames)
1166 }
1167
1168 if (length(t.rownames) != 0) {
1169
1170 if ((length(split.cells) <= dim(t)[2]) && (length(split.cells) > 1)) {
1171 split.cells <- c(panderOptions('table.split.cells'), split.cells)
1172 }
1173 t.rownames <- split.large.cells(t.rownames, TRUE)
1174
1175 if (!is.null(t.colnames)) {
1176 t.colnames <- c('&nbsp;', t.colnames)
1177 }
1178 t.width <- c(max(sapply(strsplit(t.rownames, '\n'), function(x) max(nchar(x, type = 'width'), 0))), t.width)
1179 t.width[1] <- t.width[1]
1180
1181 ## if we have a non-breaking space in the header
1182 if (!is.null(t.colnames)) {
1183 t.width[1] <- max(t.width[1], 6)
1184 }
1185
1186 }
1187
1188 if (length(justify) != 1) {
1189 if (length(justify) != length(t.width)) {
1190 stop(sprintf('Wrong number of parameters (%s instead of *%s*) passed: justify',
1191 length(justify), length(t.width)))
1192 }
1193 } else {
1194 if (all (strsplit(justify, '')[[1]] %in% c('c', 'l', 'r') )) {
1195 if (nchar(justify) != length(t.width)) {
1196 stop(sprintf('Wrong number of parameters (%s instead of *%s*) passed: justify',
1197 nchar(justify), length(t.width)))
1198 }
1199 justify <- c(l = 'left', c = 'centre', r = 'right')[ strsplit(justify, '')[[1]] ]
1200 } else {
1201 justify <- rep(justify, length(t.width))
1202 }
1203 }
1204 justify <- sub('^center$', 'centre', justify)
1205 if (!all(justify %in% c('left', 'right', 'centre'))) {
1206 stop('Invalid values passed for `justify` that can be "left", "right" or "centre/center".')
1207 }
1208
1209 ## #########################################################################
1210 ## Jira format is simple, let's print early
1211 ## #########################################################################
1212
1213 if (style == 'jira') {
1214
1215 if (length(t.rownames) != 0) {
1216 t <- cbind(t.rownames, t)
1217 }
1218
1219 if (length(t.colnames) != 0) {
1220 res <- paste0('|', paste(wrap(t.colnames, '|'), collapse = ''), '|')
1221 } else {
1222 res <- ''
1223 }
1224
1225 for (i in seq_len(nrow(t))) {
1226 res <- paste0(res, '\n|')
1227 for (j in seq_len(ncol(t))) {
1228 res <- paste0(res, t[i, j], '|')
1229 }
1230 }
1231
1232 return(paste0(res, '\n\n'))
1233
1234 }
1235
1236 ## #########################################################################
1237 ## split too wide tables
1238 ## #########################################################################
1239
1240 ## determine weather separator influences column's width (#164)
1241 extra.spaces.width <- switch(style,
1242 ## 3 because 2 spaces + 1 separator
1243 'grid' =, 'rmarkdown' = 3, #nolint
1244 'multiline' = , 'simple' = 0) #nolint
1245
1246 ## add extra 2 spaces for alignment
1247 if (style %in% c('simple', 'multiline')) {
1248 t.width <- t.width + 2
1249 }
1250
1251 ## +1 for the middle separator
1252 if (sum(t.width + extra.spaces.width) + 1 > split.tables
1253 & length(t.width) > 1 + (length(t.rownames) != 0)) {
1254
1255 t.split <- max(which(cumsum(t.width + extra.spaces.width + 1) > split.tables + 1)[1] - 1, 1)
1256 if (t.split == 1 & length(t.rownames) != 0) {
1257 t.split <- 2
1258 }
1259
1260 ## update caption
1261 if (!is.null(caption)) {
1262 caption <- paste(caption, panderOptions('table.continues.affix'))
1263 } else {
1264 caption <- panderOptions('table.continues')
1265 }
1266
1267 ## split
1268 if (length(t.rownames) != 0) {
1269 justify <- list(justify[1:t.split], justify[c(1, (t.split + 1):length(t.width))])
1270 t.split <- t.split - 1
1271 } else {
1272 justify <- list(justify[1 : (t.split)], justify[c( (t.split + 1):length(t.width) )])
1273 }
1274 res <- list(t[, 1 : (t.split), drop = FALSE], t[, (t.split + 1):ncol(t), drop = FALSE])
1275
1276 ## recursive call
1277 res <- paste(
1278 pandoc.table.return(res[[1]], caption = caption, digits = digits, decimal.mark = decimal.mark, round = round, missing = missing, justify = justify[[1]], style = style, split.tables = split.tables, split.cells = split.cells, keep.trailing.zeros = keep.trailing.zeros, keep.line.breaks = keep.line.breaks, plain.ascii = plain.ascii, use.hyphening = use.hyphening, emphasize.rownames = emphasize.rownames), #nolint
1279 pandoc.table.return(res[[2]], caption = NULL, digits = digits, decimal.mark = decimal.mark, round = round, justify = justify[[2]], style = style, split.tables = split.tables, split.cells = split.cells, keep.trailing.zeros = keep.trailing.zeros, keep.line.breaks = keep.line.breaks, plain.ascii = plain.ascii, use.hyphening = use.hyphening, emphasize.rownames = emphasize.rownames)) #nolint
1280
1281 return(res)
1282
1283 } else {
1284
1285 ## #########################################################################
1286 ## define markdown dialects
1287 ## #########################################################################
1288
1289 switch(style,
1290 'grid' = {
1291 sep.row <- paste0('\n+', paste(sapply(t.width + 2, function(x) repChar('-', x)), collapse = '+'), '+') #nolint
1292 sep.top <- sep.row
1293 sep.btn <- sep.row
1294 sep.hdr <- paste0('+', paste(sapply(t.width + 2, function(x) repChar('=', x)), collapse = '+'), '+')
1295 sep.col <- c('| ', ' | ', ' |')
1296 },
1297 'multiline' = {
1298 sep.row <- '\n'
1299 sep.hdr <- paste(sapply(t.width, function(x) repChar('-', x)), collapse = ' ')
1300 if (length(t.colnames) != 0) {
1301 sep.top <- gsub(' ', '-', sep.hdr)
1302 } else {
1303 sep.top <- paste(sapply(t.width, function(x) repChar('-', x)), collapse = ' ')
1304 }
1305 sep.btn <- sep.top
1306 sep.col <- c('', ' ', '')
1307 },
1308 'simple' = {
1309 sep.row <- ''
1310 if (length(t.colnames) == 0) {
1311 sep.top <- paste(sapply(t.width, function(x) repChar('-', x)), collapse = ' ')
1312 sep.btn <- paste0('\n', sep.top)
1313 } else {
1314 sep.top <- sep.btn <- ''
1315 }
1316 sep.hdr <- paste(sapply(t.width, function(x) repChar('-', x)), collapse = ' ')
1317 sep.col <- c('', ' ', '')
1318 },
1319 'rmarkdown' = {
1320 sep.row <- ''
1321 sep.top <- ''
1322 sep.btn <- ''
1323 sep.hdr <- align.hdr(t.width, justify)
1324 sep.col <- c('| ', ' | ', ' |')
1325 })
1326
1327 if (plain.ascii) {
1328 t.rownames <- sapply(t.rownames, to.plain.ascii)
1329 t.colnames <- sapply(t.colnames, to.plain.ascii)
1330 }
1331
1332 ## #########################################################################
1333 ## Actual printing starts here
1334 ## #########################################################################
1335
1336 ## header
1337 if (length(t.colnames) != 0) {
1338 res <- paste(res, sep.top,
1339 table.expand(t.colnames, t.width, justify, sep.col), sep.hdr, sep = '\n')
1340 } else {
1341 if (style == 'rmarkdown') {
1342 blank.hdr <- paste0('| ', paste(sapply(t.width, function(x) repChar(' ', x)), collapse = ' | '), ' |')
1343 res <- paste(res, blank.hdr, sep.hdr, sep = '\n')
1344 } else {
1345 res <- paste(res, sep.top, sep = '\n')
1346 }
1347 }
1348
1349 ## body
1350 res <- paste0(res, '\n')
1351
1352 if (length(t.rownames) != 0) {
1353 t <- cbind(t.rownames, t)
1354 }
1355
1356 res <- paste0(res, paste(apply(t, 1, function(x) paste0(table.expand(x, t.width, justify, sep.col), sep.row)), collapse = '\n')) #nolint
1357
1358 ## It is possible for a multiline table to have just one row,
1359 ## but the row should be followed by a blank line (and then
1360 ## the row of dashes that ends the table), or the table may
1361 ## be interpreted as a simple table.
1362 if (style == 'multiline' & nrow(t) == 1 & length(t.colnames) == 0) {
1363 res <- paste0(res, '\n')
1364 }
1365
1366 ## footer
1367 if (style != 'grid') {
1368 res <- paste0(res, sep.btn, '\n\n')
1369 } else {
1370 res <- paste0(res, '\n\n')
1371 }
1372
1373 ## (optional) caption
1374 check_caption(caption)
1375 if (!is.null(caption) && caption != '') {
1376 res <- paste0(res, panderOptions('table.caption.prefix'), caption, '\n\n')
1377 }
1378
1379 return(res)
1380
1381 }
1382 }
1383
1384 #' @export
1385 pandoc.table <- function(...)
1386 cat(pandoc.table.return(...))
1387
1388 #' Formulas
1389 #'
1390 #' Pandoc's mardown formula.
1391 #' @param x formula
1392 #' @param text text to be written before result in the same line. Typically used by calls from other functions in the package
1393 #' @param max.width maximum width in characters per line
1394 #' @param caption caption (string) to be shown under the formula
1395 #' @param add.line.breaks if to add 2 line breaks after formula
1396 #' @param ... extra arguments passed by from parent call, disregarded
1397 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
1398 #' @export
1399 #' @aliases pandoc.formula
1400 #' @examples
1401 #' pandoc.formula(y ~ x)
1402 #' pandoc.formula(formula(paste('y ~ ', paste0('x', 1:12, collapse = ' + '))))
1403 pandoc.formula.return <- function(x, text = NULL, max.width = 80, caption, add.line.breaks = FALSE, ...){
1404 mc <- match.call()
1405 if (is.null(mc$caption)) {
1406 if (is.null(attr(t, 'caption'))) {
1407 caption <- get.caption()
1408 } else {
1409 caption <- attr(t, 'caption')
1410 }
1411 }
1412 res <- paste(sub('^[ ]*', '', deparse(x, width.cutoff = max.width)), collapse = '')
1413 if (!is.null(text)) {
1414 res <- paste(text, res, sep = ' ')
1415 }
1416 if (add.line.breaks) {
1417 res <- paste(res, '\n\n')
1418 }
1419 ## (optional) caption
1420 if (!is.null(caption) && caption != '' && check_caption(caption)) {
1421 res <- paste0(res, '\n\n', panderOptions('formula.caption.prefix'), caption, '\n\n')
1422 }
1423 return(res)
1424 }
1425
1426 #' @export
1427 pandoc.formula <- function(...)
1428 cat(pandoc.formula.return(...))
1429
1430
1431 #' Dates
1432 #'
1433 #' Pandoc's mardown date.
1434 #' @param x date or vector of dates
1435 #' @param inline if to render vector of dates as inline paragraph or not (as list)
1436 #' @param simplified if just add date formatting to vector of dates
1437 #' @param ... extra arguments passed by from parent call, disregarded
1438 #' @return By default this function outputs (see: \code{cat}) the result. If you would want to catch the result instead, then call the function ending in \code{.return}.
1439 #' @export
1440 #' @aliases pandoc.date
1441 #' @examples
1442 #' pandoc.date(Sys.Date())
1443 #' pandoc.date(Sys.Date() - 1:10)
1444 #' pandoc.date(Sys.Date() - 1:10, inline = FALSE)
1445 pandoc.date.return <- function(x, inline = TRUE, simplified = FALSE, ...){
1446 if (length(x) == 1 || simplified){
1447 format(x, format = panderOptions('date'))
1448 } else {
1449 if (inline) {
1450 p(as.character(format(x, format = panderOptions('date'))))
1451 } else {
1452 pandoc.list.return(as.list(format(x, format = panderOptions('date'))), add.end.of.list = FALSE)
1453 }
1454 }
1455 }
1456
1457 #' @export
1458 pandoc.date <- function(...){
1459 cat(pandoc.date.return(...))
1460 }