| 1 |
# some special symbols (keywords a) |
| 2 |
.keywords = c('FUNCTION', 'IF', 'ELSE', 'WHILE', 'FOR', 'IN', 'BREAK', 'REPEAT', 'NEXT', 'NULL_CONST') |
| 3 |
|
| 4 |
.operators = c( |
| 5 |
sprintf("'%s'", c('+', '-', '*', '/', '^', '$', '@', ':', '?', '~', '!')), |
| 6 |
'SPECIAL', 'GT', 'GE', 'LT', 'LE', 'EQ', 'NE', 'AND', 'AND2', 'OR', 'OR2', |
| 7 |
'NS_GET', 'NS_GET_INT' |
| 8 |
) |
| 9 |
|
| 10 |
.cmd.list = sort(c( |
| 11 |
NUM_CONST = 'num', # numbers |
| 12 |
SYMBOL_FUNCTION_CALL = 'kwd', # function calls |
| 13 |
STR_CONST = 'sng', # character strings |
| 14 |
COMMENT = 'com', # comment |
| 15 |
SYMBOL_FORMALS = 'kwc', # function(formals) |
| 16 |
SYMBOL_SUB = 'kwc', # FUN(args) |
| 17 |
SLOT = 'kwc', # S4 slot |
| 18 |
LEFT_ASSIGN = 'kwb', # assignment |
| 19 |
EQ_ASSIGN = 'kwb', |
| 20 |
RIGHT_ASSIGN = 'kwb', |
| 21 |
setNames(rep('opt', length(.operators)), .operators), |
| 22 |
setNames(rep('kwa', length(.keywords)), .keywords), |
| 23 |
DEFAULT = 'def' # everything else |
| 24 |
)) |
| 25 |
|
| 26 |
cmd_latex = data.frame( |
| 27 |
cmd1 = paste('\\hl', .cmd.list, '{', sep = ''), |
| 28 |
cmd2 = '}', |
| 29 |
stringsAsFactors = FALSE, |
| 30 |
row.names = names(.cmd.list) |
| 31 |
) |
| 32 |
|
| 33 |
cmd_latex = data.frame( |
| 34 |
cmd1 = paste('\\hl', .cmd.list, '{', sep = ''), |
| 35 |
cmd2 = '}', |
| 36 |
stringsAsFactors = FALSE, |
| 37 |
row.names = names(.cmd.list) |
| 38 |
) |
| 39 |
|
| 40 |
.cmd.pandoc = c( |
| 41 |
num = 'DecValTok', kwd = 'KeywordTok', sng = 'StringTok', com = 'CommentTok', |
| 42 |
kwc = 'DataTypeTok', kwb = 'NormalTok', opt = 'NormalTok', kwa = 'NormalTok', |
| 43 |
def = 'NormalTok' |
| 44 |
) |
| 45 |
|
| 46 |
cmd_pandoc_latex = data.frame( |
| 47 |
cmd1 = paste('\\', .cmd.pandoc[.cmd.list], '{', sep = ''), |
| 48 |
cmd2 = '}', |
| 49 |
stringsAsFactors = FALSE, |
| 50 |
row.names = names(.cmd.list) |
| 51 |
) |
| 52 |
|
| 53 |
cmd_html = data.frame( |
| 54 |
cmd1 = paste('<span class="hl ', .cmd.list, '">', sep = ''), |
| 55 |
cmd2 = '</span>', |
| 56 |
stringsAsFactors = FALSE, |
| 57 |
row.names = names(.cmd.list) |
| 58 |
) |
| 59 |
|
| 60 |
# merge code and markups; use standard markups on unknown tokens |
| 61 |
merge_cmd = function(pdata, cmd) { |
| 62 |
res = cmd[pdata$token, ] |
| 63 |
idx = is.na(res[, 1]) |
| 64 |
res[idx, 1] = cmd['DEFAULT', 1] |
| 65 |
res[idx, 2] = cmd['DEFAULT', 2] |
| 66 |
res[is.na(res)] = '' # if DEFAULT is undefined in the markup data frame |
| 67 |
res |
| 68 |
} |
| 69 |
|
| 70 |
#' Syntax highlight an R code fragment |
| 71 |
#' |
| 72 |
#' This function \code{\link{parse}}s the R code, fetches the tokens in it |
| 73 |
#' (\code{\link{getParseData}}), and attach syntax highlighting commands onto |
| 74 |
#' them. With proper style definitions for these commands (such as colors or |
| 75 |
#' font styles), the R code will be syntax highlighted in the LaTeX/HTML output. |
| 76 |
#' The two functions \code{hi_latex} and \code{hi_html} are wrappers of |
| 77 |
#' \code{hilight} for LaTeX and HTML output, respectively. |
| 78 |
#' |
| 79 |
#' For the \code{markup} data frame, the first column is put before the R |
| 80 |
#' tokens, and the second column is behind; the row names of the data frame must |
| 81 |
#' be the R token names; a special row is named \code{DEFAULT}, which contains |
| 82 |
#' the markup for the standard tokens (i.e. those that do not need to be |
| 83 |
#' highlighted); if missing, the built-in data frames \code{highr:::cmd_latex} |
| 84 |
#' and \code{highr:::cmd_html} will be used. |
| 85 |
#' |
| 86 |
#' This function only binds markups onto R tokens, and the real syntax |
| 87 |
#' highlighting must be done with style definitions, which is out of the scope |
| 88 |
#' of this package. It was designed to be used as the syntax highlighting |
| 89 |
#' infrastructure of other packages such as \pkg{knitr}, where the colors and |
| 90 |
#' font styles are properly defined in the LaTeX preamble and HTML header. |
| 91 |
#' @param code a character string (the R source code) |
| 92 |
#' @param format the output format |
| 93 |
#' @param markup a data frame of two columns containing the markup commands |
| 94 |
#' @param prompt whether to add prompts to the code |
| 95 |
#' @param fallback whether to use the fallback method, i.e. the regular |
| 96 |
#' expression based method; this method is not precise and only highlights a |
| 97 |
#' few types of symbols such as comments, strings and functions; |
| 98 |
#' \code{fallback} will be set to \code{TRUE} when the input \code{code} fails |
| 99 |
#' to be \code{\link{parse}d} |
| 100 |
#' @param ... arguments to be passed to \code{hilight()} |
| 101 |
#' @author Yihui Xie and Yixuan Qiu |
| 102 |
#' @seealso See the package vignettes \code{browseVignettes('highr')} for how |
| 103 |
#' this function works internally. |
| 104 |
#' @return A character vector for the syntax highlighted code. |
| 105 |
#' @examples library(highr) |
| 106 |
#' hilight("x=1 # assignment") |
| 107 |
#' |
| 108 |
#' txt = c("a <- 1 # something", 'c(y="world", z="hello")', 'b=function(x=5) {', |
| 109 |
#' 'for(i in 1:10) { |
| 110 |
#' if (i < x) print(i) else break}}', |
| 111 |
#' "z@@child # S4 slot", "'special chars <>#$%&_{}'") |
| 112 |
#' cat(hi_latex(txt), sep = '\n') |
| 113 |
#' cat(hi_html(txt), sep = '\n') |
| 114 |
#' |
| 115 |
#' # the markup data frames |
| 116 |
#' highr:::cmd_latex; highr:::cmd_html |
| 117 |
#' @import utils |
| 118 |
#' @importFrom xfun valid_syntax split_source raw_string |
| 119 |
#' @export |
| 120 |
hilight = function(code, format = c('latex', 'html'), markup, prompt = FALSE, fallback = FALSE) { |
| 121 |
if (length(code) == 0) return(raw_string(code)) |
| 122 |
format = match.arg(format) |
| 123 |
if (missing(markup) || is.null(markup)) |
| 124 |
markup = if (format == 'latex') cmd_latex else cmd_html |
| 125 |
escape_fun = if (format == 'latex') escape_latex else escape_html |
| 126 |
if (!fallback && !valid_syntax(code, silent = FALSE)) { |
| 127 |
# the code is not valid, so you must use the fallback mode |
| 128 |
warning('the syntax of the source code is invalid; the fallback mode is used') |
| 129 |
fallback = TRUE |
| 130 |
} |
| 131 |
if (!prompt) return(raw_string( |
| 132 |
(if (fallback) hi_naive else hilight_one)(code, format, markup, escape_fun) |
| 133 |
)) |
| 134 |
p1 = escape_fun(getOption('prompt')); p2 = escape_fun(getOption('continue')) |
| 135 |
std = unlist(markup['DEFAULT', ]) |
| 136 |
if (!any(is.na(std))) { |
| 137 |
p1 = paste0(std[1], p1, std[2]); p2 = paste0(std[1], p2, std[2]) |
| 138 |
} |
| 139 |
code = split_source(code) |
| 140 |
res = sapply(mapply(hilight_one, code, MoreArgs = list(format, markup, escape_fun), |
| 141 |
SIMPLIFY = FALSE, USE.NAMES = FALSE), |
| 142 |
function(x) paste0(rep(c(p1, p2), c(1L, length(x) - 1L)), x, collapse = '\n')) |
| 143 |
raw_string(res) |
| 144 |
} |
| 145 |
# highlight one expression |
| 146 |
hilight_one = function(code, format, markup, escape_fun) { |
| 147 |
|
| 148 |
# the data frames do not need factors in this function; need to keep source |
| 149 |
op = options(stringsAsFactors = FALSE, keep.source = TRUE); on.exit(options(op)) |
| 150 |
|
| 151 |
p = parse_source(code) |
| 152 |
z = utils::getParseData(p) |
| 153 |
if (NROW(z) == 0L || !any(z$terminal)) return(code) |
| 154 |
z = z[z$terminal, ] |
| 155 |
|
| 156 |
# record how empty lines before/after the code |
| 157 |
one = paste(code, collapse = '\n') |
| 158 |
r1 = '^(\\s*)\n.*'; r2 = '^.*?\n(\\s*)$' |
| 159 |
s1 = if (grepl(r1, one)) gsub(r1, '\\1', one) |
| 160 |
s2 = if (grepl(r2, one)) gsub(r2, '\\1', one) |
| 161 |
|
| 162 |
res = cbind(z[, c('line1', 'col1', 'line2', 'col2', 'text')], merge_cmd(z, markup)) |
| 163 |
|
| 164 |
# escape special LaTeX/HTML chars |
| 165 |
res$text = escape_fun(res$text) |
| 166 |
|
| 167 |
# record how many blank lines after each token |
| 168 |
blanks = c(pmax(res$line1[-1] - res$line2[-nrow(res)] - 1, 0), 0) |
| 169 |
# add line breaks to the 8th column |
| 170 |
res = cbind(res, strrep('\n', blanks)) |
| 171 |
|
| 172 |
# e.g. a string spans across multiple lines; now need to replace line1 with |
| 173 |
# line2 so that we know the starting and ending positions of spaces; e.g. turn |
| 174 |
# line/col numbers 1 5 2 6 into 2 5 2 6 |
| 175 |
for (i in which(res$line1 != res$line2)) { |
| 176 |
res$line1[res$line1 == res$line1[i]] = res$line2[i] |
| 177 |
} |
| 178 |
|
| 179 |
out = lapply(split(res, res$line1), function(d) { |
| 180 |
# merge adjacent tokens of the same type so that the output is cleaner |
| 181 |
empty = matrix(FALSE, nrow = nrow(d), ncol = 2) |
| 182 |
for (i in seq_len(nrow(d) - 1)) { |
| 183 |
if (all(d[i, 6:7] == d[i + 1, 6:7])) empty[i + 1, 1] = empty[i, 2] = TRUE |
| 184 |
} |
| 185 |
d[, 6:7][empty] = '' |
| 186 |
col = as.matrix(d[, c('col1', 'col2')]) |
| 187 |
# add 0 and remove col[n, 2] to get start/end positions of spaces |
| 188 |
col = matrix(head(c(0, t(col)), -1), ncol = 2, byrow = TRUE) |
| 189 |
paste(strrep(' ', col[, 2] - col[, 1] - 1), d[, 6], d[, 'text'], d[, 7], |
| 190 |
d[, 8], sep = '', collapse = '') |
| 191 |
}) |
| 192 |
c(s1, unlist(out, use.names = FALSE), s2) |
| 193 |
} |
| 194 |
#' @export |
| 195 |
#' @rdname hilight |
| 196 |
hi_latex = function(code, ...) hilight(code, 'latex', ...) |
| 197 |
#' @export |
| 198 |
#' @rdname hilight |
| 199 |
hi_html = function(code, ...) hilight(code, 'html', ...) |
| 200 |
|
| 201 |
#' A wrapper to Andre Simon's Highlight |
| 202 |
#' |
| 203 |
#' This function calls Highlight to syntax highlight a code fragment. |
| 204 |
#' @param code a character string of the source code |
| 205 |
#' @param language the input language (c, cpp, python, r, ...); see |
| 206 |
#' \code{system('highlight -p')} |
| 207 |
#' @param format the output format (html, latex, ...) |
| 208 |
#' @references Andre Simon's Highlight package |
| 209 |
#' \url{https://gitlab.com/saalen/highlight}. |
| 210 |
#' @return A character string for the syntax highlighted code. |
| 211 |
#' @export |
| 212 |
#' @examples \dontrun{hi_andre('1+1', language='R') |
| 213 |
#' hi_andre('void main() {\nreturn(0)\n}', language='c', format='latex')} |
| 214 |
hi_andre = function(code, language, format = 'html') { |
| 215 |
h = Sys.which('highlight') |
| 216 |
os = Sys.info()[['sysname']] |
| 217 |
# highlight on Linux Mint can be something else |
| 218 |
# on OS10 with highlight installed using Homebrew it's often in /usr/local/bin |
| 219 |
if (!nzchar(h) || (h == '/usr/local/bin/highlight' && os != 'Darwin' && |
| 220 |
!file.exists(h <- '/usr/bin/highlight'))) |
| 221 |
stop('please first install highlight from https://gitlab.com/saalen/highlight') |
| 222 |
f = basename(tempfile('code', '.')) |
| 223 |
writeLines(code, f); on.exit(unlink(f)) |
| 224 |
cmd = sprintf('%s -f -S %s -O %s %s', shQuote(h), correct_lang(language), format, f) |
| 225 |
res = system(cmd, intern = TRUE) |
| 226 |
raw_string(res) |
| 227 |
} |
| 228 |
|
| 229 |
# to help knitr engines decide the highlight language |
| 230 |
correct_lang = function(x) { |
| 231 |
switch(x, Rcpp = 'cpp', tikz = 'latex', Rscript = 'R', fortran = 'f', stan = 'R', x) |
| 232 |
} |