r_highlight_rules.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /*
  2. * r_highlight_rules.js
  3. *
  4. * Copyright (C) 2009-11 by RStudio, Inc.
  5. *
  6. * The Initial Developer of the Original Code is
  7. * Ajax.org B.V.
  8. * Portions created by the Initial Developer are Copyright (C) 2010
  9. * the Initial Developer. All Rights Reserved.
  10. *
  11. * Distributed under the BSD license:
  12. *
  13. * Copyright (c) 2010, Ajax.org B.V.
  14. * All rights reserved.
  15. *
  16. * Redistribution and use in source and binary forms, with or without
  17. * modification, are permitted provided that the following conditions are met:
  18. * * Redistributions of source code must retain the above copyright
  19. * notice, this list of conditions and the following disclaimer.
  20. * * Redistributions in binary form must reproduce the above copyright
  21. * notice, this list of conditions and the following disclaimer in the
  22. * documentation and/or other materials provided with the distribution.
  23. * * Neither the name of Ajax.org B.V. nor the
  24. * names of its contributors may be used to endorse or promote products
  25. * derived from this software without specific prior written permission.
  26. *
  27. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  28. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  29. * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  30. * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
  31. * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  32. * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  33. * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  34. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  35. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  36. *
  37. */
  38. define(function(require, exports, module)
  39. {
  40. var oop = require("../lib/oop");
  41. var lang = require("../lib/lang");
  42. var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
  43. var TexHighlightRules = require("./tex_highlight_rules").TexHighlightRules;
  44. var RHighlightRules = function()
  45. {
  46. var keywords = ( // from R's ls('package:base')
  47. "function|if|in|break|next|repeat|else|for|return|switch|while|try|tryCatch|stop|" +
  48. "warning|require|library|attach|detach|source|setMethod|setGeneric|setGroupGeneric|setClass|" +
  49. "Arg|Cstack_info|Encoding<-|Filter|I|ISOdatetime|LETTERS|La_version|Math.Date|" +
  50. "Math.data.frame|Math.factor|NCOL|Negate|OlsonNames|Ops.POSIXt|Ops.difftime|" +
  51. "Ops.numeric_version|Position|R.home|R.version.string|RNGversion|Re|Reduce|Summary.POSIXct|" +
  52. "Summary.data.frame|Summary.factor|Summary.ordered|Sys.chmod|Sys.getlocale|Sys.glob|" +
  53. "Sys.localeconv|Sys.setFileTime|Sys.setlocale|Sys.time|Sys.umask|Sys.which|UseMethod|" +
  54. "[.Date|[.POSIXct|[.data.frame|[.factor|[.listof|[.numeric_version|[.simple.list|[<-|" +
  55. "[<-.POSIXct|[<-.data.frame|[<-.numeric_version|[[.Date|[[.data.frame|[[.numeric_version|" +
  56. "[[<-.data.frame|[[<-.numeric_version|abbreviate|acos|addNA|agrep|alist|all.equal|" +
  57. "all.equal.character|all.equal.envRefClass|all.equal.factor|all.equal.language|" +
  58. "all.equal.numeric|all.names|any|anyDuplicated.array|anyDuplicated.default|anyNA|" +
  59. "anyNA.numeric_version|aperm.default|append|args|arrayInd|as.Date.POSIXct|" +
  60. "as.Date.character|as.Date.dates|as.Date.factor|as.POSIXct|as.POSIXct.POSIXlt|" +
  61. "as.POSIXct.dates|as.POSIXct.numeric|as.POSIXlt.Date|as.POSIXlt.character|" +
  62. "as.POSIXlt.dates|as.POSIXlt.factor|as.array|as.call|as.character.Date|" +
  63. "as.character.condition|as.character.error|as.character.hexmode|as.character.octmode|" +
  64. "as.complex|as.data.frame.AsIs|as.data.frame.POSIXct|as.data.frame.array|" +
  65. "as.data.frame.complex|as.data.frame.default|as.data.frame.factor|as.data.frame.list|" +
  66. "as.data.frame.matrix|as.data.frame.noquote|as.data.frame.numeric_version|" +
  67. "as.data.frame.raw|as.data.frame.ts|as.difftime|as.double.POSIXlt|as.environment|" +
  68. "as.expression.default|as.function|as.hexmode|as.list|as.list.POSIXct|" +
  69. "as.list.default|as.list.factor|as.list.numeric_version|as.logical.factor|" +
  70. "as.matrix.POSIXlt|as.matrix.default|as.name|as.null.default|as.numeric_version|" +
  71. "as.ordered|as.pairlist|as.raw|as.single.default|as.table|as.vector|asNamespace|" +
  72. "asS4|asinh|atan|atanh|attachNamespace|attr.all.equal|attributes|autoload|backsolve|" +
  73. "basename|besselJ|besselY|bindingIsActive|bindtextdomain|bitwNot|bitwShiftL|bitwXor|" +
  74. "body<-|break|browserCondition|browserText|by|by.default|c|c.POSIXct|c.noquote|" +
  75. "c.warnings|callCC|casefold|cbind|ceiling|charToRaw|charmatch|check_tzones|chol.default|" +
  76. "choose|class<-|close|close.srcfile|closeAllConnections|colMeans|colnames|commandArgs|" +
  77. "comment<-|computeRestarts|conditionCall.condition|conditionMessage.condition|" +
  78. "contributors|cosh|crossprod|cummin|cumsum|cut|cut.POSIXt|dQuote|data.frame|date|" +
  79. "debuggingState|default.stringsAsFactors|deparse|detach|determinant.matrix|diag|" +
  80. "diff|diff.POSIXt|difftime|dim|dim<-|dimnames.data.frame|dimnames<-.data.frame|" +
  81. "dir.create|dirname|dontCheck|dput|droplevels|droplevels.factor|duplicated|" +
  82. "duplicated.array|duplicated.default|duplicated.numeric_version|dyn.unload|eapply|" +
  83. "emptyenv|enc2utf8|enquote|environment|environmentIsLocked|eval|evalq|exp|expm1|" +
  84. "extSoftVersion|factorial|file|file.append|file.copy|file.exists|file.link|file.mtime|" +
  85. "file.remove|file.show|file.symlink|findInterval|findRestart|flush|for|forceAndCall|" +
  86. "formals<-|format.AsIs|format.POSIXct|format.data.frame|format.difftime|format.hexmode|" +
  87. "format.libraryIQR|format.octmode|format.pval|formatC|forwardsolve|gamma|gc.time|" +
  88. "gctorture|get|getAllConnections|getCallingDLLe|getDLLRegisteredRoutines|" +
  89. "getDLLRegisteredRoutines.character|getExportedValue|getLoadedDLLs|getNamespaceExports|" +
  90. "getNamespaceInfo|getNamespaceUsers|getNativeSymbolInfo|getRversion|getTaskCallbackNames|" +
  91. "gettext|getwd|globalenv|grep|grepl|gzcon|iconv|icuGetCollate|identical|if|importIntoEnv|" +
  92. "intToBits|integer|interactive|inverse.rle|invokeRestart|is.R|is.atomic|is.character|" +
  93. "is.data.frame|is.element|is.expression|is.finite|is.infinite|is.language|is.loaded|" +
  94. "is.matrix|is.na.POSIXlt|is.na.numeric_version|is.na<-.default|is.na<-.numeric_version|" +
  95. "is.nan|is.numeric|is.numeric.POSIXt|is.numeric_version|is.ordered|is.pairlist|is.qr|" +
  96. "is.recursive|is.symbol|is.unsorted|isBaseNamespace|isNamespace|isOpen|isS4|isSymmetric|" +
  97. "isTRUE|isdebugged|julian|julian.POSIXt|kappa.default|kappa.qr|l10n_info|labels.default|" +
  98. "last.warning|lazyLoadDBexec|lbeta|length|length<-|lengths|levels|levels<-|lfactorial|" +
  99. "libcurlVersion|library.dynam|licence|list|list.files|load|loadedNamespaces|local|" +
  100. "lockEnvironment|log10|log2|logical|ls|make.unique|mapply|mat.or.vec|match.arg|" +
  101. "match.fun|max|mean|mean.POSIXct|mean.default|mem.limits|memDecompress|merge|" +
  102. "merge.default|mget|missing|mode<-|month.name|months.Date|mostattributes<-|names.POSIXlt|" +
  103. "names<-.POSIXlt|namespaceImport|namespaceImportFrom|nargs|ncol|next|nlevels|norm|nrow|" +
  104. "numeric_version|objects|oldClass<-|open|open.srcfile|open.srcfilecopy|order|outer|" +
  105. "packageEvent|packageStartupMessage|pairlist|parent.env<-|parse|paste|path.expand|" +
  106. "pcre_config|pipe|pmax|pmin|polyroot|pretty|prettyNum|print.AsIs|print.DLLInfoList|" +
  107. "print.Date|print.NativeRoutineList|print.POSIXlt|print.condition|print.data.frame|" +
  108. "print.difftime|print.function|print.libraryIQR|print.noquote|print.octmode|" +
  109. "print.proc_time|print.rle|print.srcfile|print.summary.table|print.table|prmatrix|" +
  110. "prod|provideDimnames|pushBack|q|qr.Q|qr.X|qr.default|qr.qty|qr.resid|quarters|" +
  111. "quarters.POSIXt|quote|range.default|rapply|rawConnection|rawShift|rawToChar|" +
  112. "rbind.data.frame|read.dcf|readChar|readRDS|readline|regexec|registerS3method|regmatches|" +
  113. "remove|rep|rep.POSIXct|rep.factor|rep.numeric_version|repeat|replicate|requireNamespace|" +
  114. "restartFormals|return|rev|rle|round|round.POSIXt|row.names|row.names.default|" +
  115. "row.names<-.data.frame|rowMeans|rownames|rowsum|rowsum.default|sample|sapply|save.image|" +
  116. "scale|scan|searchpaths|seek.connection|seq.Date|seq.default|seq_along|sequence|set.seed|" +
  117. "setNamespaceInfo|setTimeLimit|setequal|shQuote|sign|signif|simpleError|simpleWarning|sin|" +
  118. "sinh|sink.number|slice.index|socketSelect|solve.default|sort|sort.default|sort.list|split|" +
  119. "split.POSIXct|split.default|split<-.data.frame|sprintf|srcfile|srcfilecopy|standardGeneric|" +
  120. "stdin|stop|storage.mode|strftime|strsplit|strtrim|strwrap|subset|subset.default|substitute|" +
  121. "substr<-|substring<-|summary|summary.POSIXct|summary.connection|summary.default|" +
  122. "summary.matrix|summary.srcfile|summary.table|suppressPackageStartupMessages|svd|" +
  123. "switch|sys.calls|sys.frames|sys.load.image|sys.on.exit|sys.parents|sys.source|system|" +
  124. "system.time|t|t.default|tabulate|tanh|tapply|tcrossprod|tempfile|textConnection|toString|" +
  125. "tolower|toupper|traceback|tracingState|transform.data.frame|trigamma|trunc|trunc.POSIXt|" +
  126. "truncate.connection|tryCatch|unclass|union|unique.POSIXlt|unique.data.frame|unique.matrix|" +
  127. "unique.warnings|units.difftime|units<-.difftime|unlink|unloadNamespace|unname|unsplit|" +
  128. "untracemem|upper.tri|utf8ToInt|vector|warning|weekdays|weekdays.POSIXt|which.max|while|" +
  129. "with.default|withRestarts|within|within.list|write.dcf|writeChar|xor|xor.octmode|xtfrm|" +
  130. "xtfrm.Date|xtfrm.POSIXlt|xtfrm.default|xtfrm.factor|xzfile|.hexmode"
  131. );
  132. var builtinFunctions = ( // from http://www.sr.bham.ac.uk/~ajrs/R/r-function_list.html
  133. "builtins|options|?NA|abs|append|c|cat|cbind|diff|gl|grep|identical|jitter|julian|length|ls|" +
  134. "mat.or.vec|paste|range|rep|rev|seq|sequence|sign|sort|order|tolower|toupper|unique|system|" +
  135. "vector|formatC|floor|ceiling|round|signif|trunc|Sys.getenv|Sys.putenv|Sys.time|Sys.Date|" +
  136. "getwd|setwd|?files|list.files|file.info|log|logb|log10|log2|exp|expm1|log1p|sqrt|cos|sin|" +
  137. "tan|acos|asin|atan|atan2|cosh|sinh|tanh|acosh|asinh|atanh|union|intersect|setdiff|setequal|" +
  138. "eigen|deriv|integrate|sqrt|sum|?Control|?Extract|?Logic|?Mod|?Paren|?regex|?Syntax|?Special|" +
  139. "help|plot|par|curve|points|arrows|abline|lines|segments|hist|pairs|matplot|?device|postscript|" +
  140. "pdf|png|jpeg|X11|persp|contour|image|lm|glm|nls|lqs|optim|optimize|constrOptim|nlm|nlminb|" +
  141. "?Chisquare|?Poisson|cor.test|cumsum|cumprod|cummin|cummax|density|ks.test|loess|lowess|mad|" +
  142. "meanx|weighted.meanx|medianx|minx|maxx|quantile|rnorm|runif|splinefun|smooth.spline|sd|" +
  143. "summary|t.test|var|sample|ecdf|qqplot"
  144. );
  145. var builtinConstants = (
  146. "NULL|NA|TRUE|FALSE|T|F|Inf|NaN|NA_integer_|NA_real_|NA_character_|" +
  147. "NA_complex_|pi|letters|LETTERS|month.abb,month.name"
  148. );
  149. var keywordMapper = this.$keywords = this.createKeywordMapper({
  150. "support.function": builtinFunctions,
  151. "keyword": keywords,
  152. "constant.language": builtinConstants
  153. }, "identifier");
  154. // regexp must not have capturing parentheses. Use (?:) instead.
  155. // regexps are ordered -> the first match is used
  156. this.$rules = {
  157. "start" : [
  158. {
  159. // Roxygen
  160. token : "comment.sectionhead",
  161. regex : "#+(?!').*(?:----|====|####)\\s*$"
  162. },
  163. {
  164. // Roxygen
  165. token : "comment",
  166. regex : "#+'",
  167. next : "rd-start"
  168. },
  169. {
  170. token : "comment",
  171. regex : "#.*$"
  172. },
  173. {
  174. token : "string", // multi line string start
  175. regex : '["]',
  176. next : "qqstring"
  177. },
  178. {
  179. token : "string", // multi line string start
  180. regex : "[']",
  181. next : "qstring"
  182. },
  183. {
  184. token : "constant.numeric", // hex
  185. regex : "0[xX][0-9a-fA-F]+[Li]?\\b"
  186. },
  187. {
  188. token : "constant.numeric", // explicit integer
  189. regex : "\\d+L\\b"
  190. },
  191. {
  192. token : "constant.numeric", // number
  193. regex : "\\d+(?:\\.\\d*)?(?:[eE][+\\-]?\\d*)?i?\\b"
  194. },
  195. {
  196. token : "constant.numeric", // number with leading decimal
  197. regex : "\\.\\d+(?:[eE][+\\-]?\\d*)?i?\\b"
  198. },
  199. {
  200. token : "constant.language.boolean",
  201. regex : "(?:TRUE|FALSE|T|F)\\b"
  202. },
  203. {
  204. token : "identifier",
  205. regex : "`.*?`"
  206. },
  207. {
  208. token : keywordMapper,
  209. regex : "[a-zA-Z.][a-zA-Z0-9._]*\\b"
  210. },
  211. {
  212. token : "keyword.operator",
  213. regex : "%%|>=|<=|==|!=|\\->|<\\-|\\|\\||&&|=|\\+|\\-|\\*|/|\\^|>|<|!|&|\\||~|\\$|:"
  214. },
  215. {
  216. token : "keyword.operator", // infix operators
  217. regex : "%.*?%"
  218. },
  219. {
  220. // Obviously these are neither keywords nor operators, but
  221. // labelling them as such was the easiest way to get them
  222. // to be colored distinctly from regular text
  223. token : "paren.keyword.operator",
  224. regex : "[[({]"
  225. },
  226. {
  227. // Obviously these are neither keywords nor operators, but
  228. // labelling them as such was the easiest way to get them
  229. // to be colored distinctly from regular text
  230. token : "paren.keyword.operator",
  231. regex : "[\\])}]"
  232. },
  233. {
  234. token : "text",
  235. regex : "\\s+"
  236. }
  237. ],
  238. "qqstring" : [
  239. {
  240. token : "string",
  241. regex : '(?:(?:\\\\.)|(?:[^"\\\\]))*?"',
  242. next : "start"
  243. },
  244. {
  245. token : "string",
  246. regex : '.+'
  247. }
  248. ],
  249. "qstring" : [
  250. {
  251. token : "string",
  252. regex : "(?:(?:\\\\.)|(?:[^'\\\\]))*?'",
  253. next : "start"
  254. },
  255. {
  256. token : "string",
  257. regex : '.+'
  258. }
  259. ]
  260. };
  261. var rdRules = new TexHighlightRules("comment").getRules();
  262. // Make all embedded TeX virtual-comment so they don't interfere with
  263. // auto-indent.
  264. for (var i = 0; i < rdRules["start"].length; i++) {
  265. rdRules["start"][i].token += ".virtual-comment";
  266. }
  267. this.addRules(rdRules, "rd-");
  268. this.$rules["rd-start"].unshift({
  269. token: "text",
  270. regex: "^",
  271. next: "start"
  272. });
  273. this.$rules["rd-start"].unshift({
  274. token : "keyword",
  275. regex : "@(?!@)[^ ]*"
  276. });
  277. this.$rules["rd-start"].unshift({
  278. token : "comment",
  279. regex : "@@"
  280. });
  281. this.$rules["rd-start"].push({
  282. token : "comment",
  283. regex : "[^%\\\\[({\\])}]+"
  284. });
  285. };
  286. oop.inherits(RHighlightRules, TextHighlightRules);
  287. exports.RHighlightRules = RHighlightRules;
  288. });