blob: d78a242f40d629cadf43c318cf8b2fbb10ad3a2f [file] [log] [blame]
Hao Zhu248bbef2018-04-02 18:25:14 -04001#' Make linebreak in LaTeX Table cells
2#'
Duncan Murdoch7897b5f2021-12-09 16:33:16 -05003#' @description This function generates LaTeX code of `makecell` so that users
Hao Zhu5e4dd502018-04-05 12:01:58 -04004#' can have linebreaks in their table
5#'
6#' @param x A character vector
Duncan Murdoch7897b5f2021-12-09 16:33:16 -05007#' @param align Choose from "l", "c" or "r". Defaults to "l".
Hao Zhu5e4dd502018-04-05 12:01:58 -04008#' @param double_escape Whether special character should be double escaped.
9#' Default is FALSE.
Hao Zhub548aac2018-09-18 13:29:01 -040010#' @param linebreaker Symbol for linebreaks to replace. Default is `\\n`.
Hao Zhu5e4dd502018-04-05 12:01:58 -040011#'
Hao Zhu248bbef2018-04-02 18:25:14 -040012#' @export
Hao Zhua17edd02018-09-15 21:20:44 -040013linebreak <- function(x, align = c("l", "c", "r"), double_escape = F,
14 linebreaker = "\n") {
Hao Zhu248bbef2018-04-02 18:25:14 -040015 if (is.numeric(x) | is.logical(x)) return(x)
Hao Zhu3e0e2b12018-10-23 11:21:29 -040016 x <- as.character(x)
Duncan Murdoch7897b5f2021-12-09 16:33:16 -050017 if (missing(align))
18 align <- "l"
kbrevoortc79c5a82019-08-26 22:44:01 -040019 align <- vapply(align, match.arg, 'a', choices = c("l", "c", "r"))
Hao Zhu248bbef2018-04-02 18:25:14 -040020 if (double_escape) {
Hao Zhua17edd02018-09-15 21:20:44 -040021 ifelse(str_detect(x, linebreaker),
Hao Zhu248bbef2018-04-02 18:25:14 -040022 paste0("\\\\makecell[", align, "]{",
Hao Zhua17edd02018-09-15 21:20:44 -040023 str_replace_all(x, linebreaker, "\\\\\\\\\\\\\\\\"), "}"),
Hao Zhu248bbef2018-04-02 18:25:14 -040024 x)
25 } else {
Hao Zhua17edd02018-09-15 21:20:44 -040026 ifelse(str_detect(x, linebreaker),
Hao Zhu248bbef2018-04-02 18:25:14 -040027 paste0("\\makecell[", align, "]{",
Hao Zhua17edd02018-09-15 21:20:44 -040028 str_replace_all(x, linebreaker, "\\\\\\\\"), "}"),
Hao Zhu248bbef2018-04-02 18:25:14 -040029 x)
30 }
31}
Hao Zhu5e4dd502018-04-05 12:01:58 -040032
33linebreak_html <- function(x) {
34 if (is.numeric(x) | is.logical(x)) return(x)
35 ifelse(str_detect(x, "\n"), str_replace_all(x, "\n", "<br />"), x)
36}