Debian Codegraph @

R/header.R

raw
1 #' @include themes.R
2 #' @include highlight.R
3
4 # doc is the output of processed document
5 insert_header = function(doc) {
6 if (is.null(b <- knit_patterns$get('header.begin'))) return(doc)
7
8 if (out_format('html'))
9 return(insert_header_html(doc, b))
10 if (out_format(c('latex', 'listings', 'sweave')))
11 return(insert_header_latex(doc, b))
12 doc
13 }
14
15 # Makes latex header with macros required for highlighting, tikz and framed
16 make_header_latex = function(doc) {
17 h = one_string(c(
18 header_latex_packages(doc),
19 .header.maxwidth, opts_knit$get('header'),
20 if (length(grep('\\hlstd', doc, fixed = TRUE))) '\\let\\hlstd\\hldef',
21 if (length(grep('\\hlstr', doc, fixed = TRUE))) '\\let\\hlstr\\hlsng',
22 if (getOption('OutDec') != '.') '\\usepackage{amsmath}',
23 if (out_format('latex')) '\\usepackage{alltt}'
24 ))
25 if (opts_knit$get('self.contained')) h else {
26 write_utf8(h, 'knitr.sty')
27 '\\usepackage{knitr}'
28 }
29 }
30
31 # if the document already contains \usepackage[options]{pkg}, use the same
32 # options to avoid the option clash error in LaTeX
33 use_package = function(pkg, doc) {
34 opts = sapply(pkg, function(p) {
35 r = sprintf('.*?\\\\usepackage\\[(.+?)]\\{%s}.*', p)
36 o = xfun::grep_sub(r, '\\1', doc)
37 if (length(o)) return(o[1])
38 opts_knit$get(paste0('latex.options.', p)) %n% ''
39 })
40 sprintf('\\usepackage[%s]{%s}', opts, pkg)
41 }
42
43 # for backward-compatibility, use xcolor package unless the latex.options.color
44 # has been set; xcolor is preferred: https://github.com/latex3/latex2e/pull/719
45 header_latex_packages = function(doc) {
46 paste(use_package(c('graphicx', 'xcolor'), doc), collapse = '')
47 }
48
49 insert_header_latex = function(doc, b) {
50 i = grep(b, doc)
51 if (length(i) >= 1L) {
52 # it is safer to add usepackage{upquote} before begin{document} than after
53 # documentclass{article} because it must appear after usepackage{fontenc};
54 # see this weird problem: http://stackoverflow.com/q/12448507/559676
55 p = '(?<!%)(\\s*)(\\\\begin\\{document\\})'
56 if (!out_format('listings') && length(j <- grep(p, doc, perl = TRUE))) {
57 j = j[1]
58 doc[j] = sub(p, '\n\\\\IfFileExists{upquote.sty}{\\\\usepackage{upquote}}{}\n\\2', doc[j], perl = TRUE)
59 }
60 i = i[1L]; l = str_locate(doc[i], b, FALSE)
61 doc[i] = str_insert(doc[i], l[, 2], make_header_latex(doc))
62 } else if (parent_mode() && !child_mode()) {
63 # in parent mode, we fill doc to be a complete document
64 doc[1L] = one_string(c(
65 getOption('tikzDocumentDeclaration'), make_header_latex(doc),
66 .knitEnv$tikzPackages, '\\begin{document}', doc[1L]
67 ))
68 doc[length(doc)] = one_string(
69 c(doc[length(doc)], .knitEnv$bibliography, '\\end{document}')
70 )
71 }
72 doc
73 }
74
75 make_header_html = function() {
76 h = opts_knit$get('header')
77 h = h[setdiff(names(h), c('tikz', 'framed'))]
78 if (opts_knit$get('self.contained')) one_string(c(
79 '<style type="text/css">', h[['highlight']], '</style>',
80 unlist(h[setdiff(names(h), 'highlight')])
81 )) else {
82 write_utf8(h, 'knitr.css')
83 '<link rel="stylesheet" href="knitr.css" type="text/css" />'
84 }
85 }
86
87 insert_header_html = function(doc, b) {
88 i = grep(b, doc)
89 if (length(i) == 1L) {
90 l = str_locate(doc[i], b, FALSE)
91 doc[i] = str_insert(doc[i], l[, 2], paste0('\n', make_header_html()))
92 }
93 doc
94 }
95
96 #' Set the header information
97 #'
98 #' Some output documents may need appropriate header information. For example,
99 #' for LaTeX output, we need to write \samp{\\usepackage{tikz}} into the
100 #' preamble if we use tikz graphics; this function sets the header information
101 #' to be written into the output.
102 #'
103 #' By default, \pkg{knitr} will set up the header automatically. For example, if
104 #' the tikz device is used, \pkg{knitr} will add \samp{\\usepackage{tikz}} to
105 #' the LaTeX preamble, and this is done by setting the header component
106 #' \code{tikz} to be a character string: \code{set_header(tikz =
107 #' '\\usepackage{tikz}')}. Similary, when we highlight R code using the
108 #' \pkg{highlight} package (i.e. the chunk option \code{highlight = TRUE}),
109 #' \pkg{knitr} will set the \code{highlight} component of the header vector
110 #' automatically; if the output type is HTML, this component will be different
111 #' -- instead of LaTeX commands, it contains CSS definitions.
112 #'
113 #' For power users, all the components can be modified to adapt to a customized
114 #' type of output. For instance, we can change \code{highlight} to LaTeX
115 #' definitions of the \pkg{listings} package (and modify the output hooks
116 #' accordingly), so we can decorate R code using the \pkg{listings} package.
117 #' @param ... Header components; currently possible components are
118 #' \code{highlight}, \code{tikz} and \code{framed}, which contain the
119 #' necessary commands to be used in the HTML header or LaTeX preamble. Note that
120 #' HTML output does not use the \code{tikz} and \code{framed} components, since
121 #' they do not make sense in the context of HTML.
122 #' @return The header vector in \code{opts_knit} is set.
123 #' @export
124 #' @examples set_header(tikz = '\\usepackage{tikz}')
125 #' opts_knit$get('header')
126 set_header = function(...) {
127 opts_knit$set(header = merge_list(opts_knit$get('header'), c(...)))
128 }
129
130 .default.sty = inst_dir('themes', 'default.css')
131 # header for Latex Syntax Highlighting
132 .header.hi.tex = theme_to_header_latex(.default.sty)$highlight
133 .knitr.sty = inst_dir('misc', 'knitr.sty')
134 .header.framed = one_string(read_utf8(.knitr.sty))
135 # CSS for html syntax highlighting
136 .header.hi.html = theme_to_header_html(.default.sty)$highlight
137 rm(list = c('.default.sty', '.knitr.sty')) # do not need them any more
138
139 .header.sweave.cmd =
140 '\\newcommand{\\SweaveOpts}[1]{} % do not interfere with LaTeX
141 \\newcommand{\\SweaveInput}[1]{} % because they are not real TeX commands
142 \\newcommand{\\Sexpr}[1]{} % will only be parsed by R
143 '
144
145 .header.maxwidth =
146 '% maxwidth is the original width if it is less than linewidth
147 % otherwise use linewidth (to make sure the graphics do not exceed the margin)
148 \\makeatletter
149 \\def\\maxwidth{ %
150 \\ifdim\\Gin@nat@width>\\linewidth
151 \\linewidth
152 \\else
153 \\Gin@nat@width
154 \\fi
155 }
156 \\makeatother
157 '