blob: 62c0a4e953fd7631b4558c1d1959f5decaa31fc7 [file] [log] [blame]
Hao Zhu8f417202017-05-20 16:37:14 -04001#' Add indentations to row headers
2#' @export
3add_indent <- function(kable_input, positions) {
Hao Zhud972e7f2017-05-22 13:27:15 -04004 if (!is.numeric(positions)) {
5 stop("Positions can only take numeric row numbers (excluding header rows).")
6 }
Hao Zhu8f417202017-05-20 16:37:14 -04007 kable_format <- attr(kable_input, "format")
8 if (!kable_format %in% c("html", "latex")) {
9 message("Currently generic markdown table using pandoc is not supported.")
10 return(kable_input)
11 }
12 if (kable_format == "html") {
Hao Zhu62cdde52017-05-20 22:16:03 -040013 return(add_indent_html(kable_input, positions))
Hao Zhu8f417202017-05-20 16:37:14 -040014 }
15 if (kable_format == "latex") {
16 return(add_indent_latex(kable_input, positions))
17 }
18}
19
Hao Zhu62cdde52017-05-20 22:16:03 -040020# Add indentation for LaTeX
Hao Zhu8f417202017-05-20 16:37:14 -040021add_indent_latex <- function(kable_input, positions) {
Hao Zhud972e7f2017-05-22 13:27:15 -040022 table_info <- magic_mirror(kable_input)
Hao Zhu8f417202017-05-20 16:37:14 -040023
Hao Zhu8f417202017-05-20 16:37:14 -040024 if (max(positions) > table_info$nrow - 1) {
25 stop("There aren't that many rows in the table. Check positions in ",
26 "add_indent_latex.")
27 }
28
29 out <- kable_input
30 for (i in positions) {
31 rowtext <- table_info$contents[i + 1]
32 out <- sub(rowtext, latex_indent_unit(rowtext), out)
33 }
34 return(out)
35}
36
37latex_indent_unit <- function(rowtext) {
38 paste0("\\\\hspace{1em}", rowtext)
39}
Hao Zhu62cdde52017-05-20 22:16:03 -040040
41# Add indentation for HTML
42add_indent_html <- function(kable_input, positions) {
43 kable_attrs <- attributes(kable_input)
44
45 kable_xml <- read_xml(as.character(kable_input), options = "COMPACT")
46 kable_tbody <- xml_tpart(kable_xml, "tbody")
47
48 group_header_rows <- attr(kable_input, "group_header_rows")
49 if (!is.null(group_header_rows)) {
50 positions <- positions_corrector(positions, group_header_rows,
51 length(xml_children(kable_tbody)))
52 }
53 for (i in positions) {
54 node_to_edit <- xml_child(xml_children(kable_tbody)[[i]], 1)
55 if (!xml_has_attr(node_to_edit, "indentLevel")) {
56 xml_attr(node_to_edit, "style") <- paste(
57 xml_attr(node_to_edit, "style"), "padding-left: 2em;"
58 )
59 xml_attr(node_to_edit, "indentLevel") <- 1
60 } else {
61 indentLevel <- as.numeric(xml_attr(node_to_edit, "indentLevel"))
62 xml_attr(node_to_edit, "style") <- sub(
63 paste0("padding-left: ", indentLevel * 2, "em;"),
64 paste0("padding-left: ", (indentLevel + 1) * 2, "em;"),
65 xml_attr(node_to_edit, "style")
66 )
67 xml_attr(node_to_edit, "indentLevel") <- indentLevel + 1
68 }
69 }
70 out <- structure(as.character(kable_xml), format = "html",
71 class = "knitr_kable")
72 attributes(out) <- kable_attrs
73 return(out)
74}