| 1 |
hi.keywords = paste('(\\W)(', paste(c( |
| 2 |
'if', 'else', 'repeat', 'while', 'function', 'for', 'in', 'next', 'break', 'repeat', |
| 3 |
'LETTERS', 'letters', 'month.abb', 'month.name', 'pi', |
| 4 |
'TRUE', 'FALSE', 'NULL', 'Inf', 'NaN', 'NA', 'NA_integer_', 'NA_real_', 'NA_complex_', 'NA_character_' |
| 5 |
), collapse = '|'), ')(\\W)', sep = '') |
| 6 |
|
| 7 |
# only highlight function names, strings and comments |
| 8 |
hi_naive_latex = function(x, str, com, kwa, kwd) { |
| 9 |
i = grepl('^\\s*#', x) # whole lines of comments |
| 10 |
x[i] = sprintf(paste(com[1], '%s', com[2], sep = ''), x[i]) |
| 11 |
str = escape_bs(str); com = escape_bs(com); kwd = escape_bs(kwd) |
| 12 |
# comments: what if # inside quotes? |
| 13 |
if (any(idx <- grepl('#', x) & !grepl('"', x) & !i)) |
| 14 |
x[idx] = gsub('(#.*)', sprintf('%s\\1%s', com[1], com[2]), x[idx]) |
| 15 |
i = which(!i) # not comments |
| 16 |
# function names |
| 17 |
x[i] = gsub('([[:alnum:]_\\.]+)(\\s*)\\(', sprintf('%s\\1%s\\2(', kwd[1], kwd[2]), x[i]) |
| 18 |
# character strings |
| 19 |
x[i] = gsub('"([^"]*)"', sprintf('%s"\\1"%s', str[1], str[2]), x[i]) |
| 20 |
x[i] = gsub("'([^']*)'", sprintf("%s'\\1'%s", str[1], str[2]), x[i]) |
| 21 |
x |
| 22 |
} |
| 23 |
hi_naive_html = function(x, str, com, kwa, kwd) { |
| 24 |
# character strings |
| 25 |
x = gsub('"(.*?)"', sprintf('%s"\\1"%s', str[1], str[2]), x) |
| 26 |
x = gsub("'([^']*)'", sprintf("%s'\\1'%s", str[1], str[2]), x) |
| 27 |
# function names |
| 28 |
x = gsub('([[:alnum:]_\\.]+)(\\s*)\\(', sprintf('%s\\1%s\\2(', kwd[1], kwd[2]), x) |
| 29 |
if (any(idx <- grepl('#', x) & !grepl('"', x))) |
| 30 |
x[idx] = gsub('(#.*)', sprintf('%s\\1%s', com[1], com[2]), x[idx]) |
| 31 |
gsub(hi.keywords, sprintf('\\1%s\\2%s\\3', kwa[1], kwa[2]), x) |
| 32 |
} |
| 33 |
|
| 34 |
hi_naive = function(code, format = c('latex', 'html'), markup, escape_fun = identity, |
| 35 |
prompt = NULL) { |
| 36 |
format = match.arg(format) |
| 37 |
code = escape_fun(code) |
| 38 |
if (length(prompt) == 2) { |
| 39 |
# borrowed from knitr:::line_prompt |
| 40 |
code = paste( |
| 41 |
prompt[1], |
| 42 |
gsub('(?<=\n)(?=.|\n)', prompt[2], code, perl = TRUE), sep = '' |
| 43 |
) |
| 44 |
} |
| 45 |
hi_fun = if (format == 'latex') hi_naive_latex else hi_naive_html |
| 46 |
hi_fun(split_lines(code), str = markup['STR_CONST', ], com = markup['COMMENT', ], |
| 47 |
kwa = markup['IF', ], kwd = markup['SYMBOL_FUNCTION_CALL', ]) |
| 48 |
} |
| 49 |
|
| 50 |
# split a character vector by \n |
| 51 |
split_lines = function(x) { |
| 52 |
if (!any(grepl('\n', x))) return(x) |
| 53 |
x[x == ''] = '\n' |
| 54 |
unlist(strsplit(x, '\n')) |
| 55 |
} |
| 56 |
|
| 57 |
# escape backslashes |
| 58 |
escape_bs = function(x) gsub('\\\\', '\\\\\\\\', x) |