sas.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: http://codemirror.net/LICENSE
  3. // SAS mode copyright (c) 2016 Jared Dean, SAS Institute
  4. // Created by Jared Dean
  5. // TODO
  6. // indent and de-indent
  7. // identify macro variables
  8. //Definitions
  9. // comment -- text withing * ; or /* */
  10. // keyword -- SAS language variable
  11. // variable -- macro variables starts with '&' or variable formats
  12. // variable-2 -- DATA Step, proc, or macro names
  13. // string -- text within ' ' or " "
  14. // operator -- numeric operator + / - * ** le eq ge ... and so on
  15. // builtin -- proc %macro data run mend
  16. // atom
  17. // def
  18. (function(mod) {
  19. if (typeof exports == "object" && typeof module == "object") // CommonJS
  20. mod(require("../../lib/codemirror"));
  21. else if (typeof define == "function" && define.amd) // AMD
  22. define(["../../lib/codemirror"], mod);
  23. else // Plain browser env
  24. mod(CodeMirror);
  25. })(function(CodeMirror) {
  26. "use strict";
  27. CodeMirror.defineMode("sas", function () {
  28. var words = {};
  29. var isDoubleOperatorSym = {
  30. eq: 'operator',
  31. lt: 'operator',
  32. le: 'operator',
  33. gt: 'operator',
  34. ge: 'operator',
  35. "in": 'operator',
  36. ne: 'operator',
  37. or: 'operator'
  38. };
  39. var isDoubleOperatorChar = /(<=|>=|!=|<>)/;
  40. var isSingleOperatorChar = /[=\(:\),{}.*<>+\-\/^\[\]]/;
  41. // Takes a string of words separated by spaces and adds them as
  42. // keys with the value of the first argument 'style'
  43. function define(style, string, context) {
  44. if (context) {
  45. var split = string.split(' ');
  46. for (var i = 0; i < split.length; i++) {
  47. words[split[i]] = {style: style, state: context};
  48. }
  49. }
  50. }
  51. //datastep
  52. define('def', 'stack pgm view source debug nesting nolist', ['inDataStep']);
  53. define('def', 'if while until for do do; end end; then else cancel', ['inDataStep']);
  54. define('def', 'label format _n_ _error_', ['inDataStep']);
  55. define('def', 'ALTER BUFNO BUFSIZE CNTLLEV COMPRESS DLDMGACTION ENCRYPT ENCRYPTKEY EXTENDOBSCOUNTER GENMAX GENNUM INDEX LABEL OBSBUF OUTREP PW PWREQ READ REPEMPTY REPLACE REUSE ROLE SORTEDBY SPILL TOBSNO TYPE WRITE FILECLOSE FIRSTOBS IN OBS POINTOBS WHERE WHEREUP IDXNAME IDXWHERE DROP KEEP RENAME', ['inDataStep']);
  56. define('def', 'filevar finfo finv fipname fipnamel fipstate first firstobs floor', ['inDataStep']);
  57. define('def', 'varfmt varinfmt varlabel varlen varname varnum varray varrayx vartype verify vformat vformatd vformatdx vformatn vformatnx vformatw vformatwx vformatx vinarray vinarrayx vinformat vinformatd vinformatdx vinformatn vinformatnx vinformatw vinformatwx vinformatx vlabel vlabelx vlength vlengthx vname vnamex vnferr vtype vtypex weekday', ['inDataStep']);
  58. define('def', 'zipfips zipname zipnamel zipstate', ['inDataStep']);
  59. define('def', 'put putc putn', ['inDataStep']);
  60. define('builtin', 'data run', ['inDataStep']);
  61. //proc
  62. define('def', 'data', ['inProc']);
  63. // flow control for macros
  64. define('def', '%if %end %end; %else %else; %do %do; %then', ['inMacro']);
  65. //everywhere
  66. define('builtin', 'proc run; quit; libname filename %macro %mend option options', ['ALL']);
  67. define('def', 'footnote title libname ods', ['ALL']);
  68. define('def', '%let %put %global %sysfunc %eval ', ['ALL']);
  69. // automatic macro variables http://support.sas.com/documentation/cdl/en/mcrolref/61885/HTML/default/viewer.htm#a003167023.htm
  70. define('variable', '&sysbuffr &syscc &syscharwidth &syscmd &sysdate &sysdate9 &sysday &sysdevic &sysdmg &sysdsn &sysencoding &sysenv &syserr &syserrortext &sysfilrc &syshostname &sysindex &sysinfo &sysjobid &syslast &syslckrc &syslibrc &syslogapplname &sysmacroname &sysmenv &sysmsg &sysncpu &sysodspath &sysparm &syspbuff &sysprocessid &sysprocessname &sysprocname &sysrc &sysscp &sysscpl &sysscpl &syssite &sysstartid &sysstartname &systcpiphostname &systime &sysuserid &sysver &sysvlong &sysvlong4 &syswarningtext', ['ALL']);
  71. //footnote[1-9]? title[1-9]?
  72. //options statement
  73. define('def', 'source2 nosource2 page pageno pagesize', ['ALL']);
  74. //proc and datastep
  75. define('def', '_all_ _character_ _cmd_ _freq_ _i_ _infile_ _last_ _msg_ _null_ _numeric_ _temporary_ _type_ abort abs addr adjrsq airy alpha alter altlog altprint and arcos array arsin as atan attrc attrib attrn authserver autoexec awscontrol awsdef awsmenu awsmenumerge awstitle backward band base betainv between blocksize blshift bnot bor brshift bufno bufsize bxor by byerr byline byte calculated call cards cards4 catcache cbufno cdf ceil center cexist change chisq cinv class cleanup close cnonct cntllev coalesce codegen col collate collin column comamid comaux1 comaux2 comdef compbl compound compress config continue convert cos cosh cpuid create cross crosstab css curobs cv daccdb daccdbsl daccsl daccsyd dacctab dairy datalines datalines4 datejul datepart datetime day dbcslang dbcstype dclose ddm delete delimiter depdb depdbsl depsl depsyd deptab dequote descending descript design= device dflang dhms dif digamma dim dinfo display distinct dkricond dkrocond dlm dnum do dopen doptname doptnum dread drop dropnote dsname dsnferr echo else emaildlg emailid emailpw emailserver emailsys encrypt end endsas engine eof eov erf erfc error errorcheck errors exist exp fappend fclose fcol fdelete feedback fetch fetchobs fexist fget file fileclose fileexist filefmt filename fileref fmterr fmtsearch fnonct fnote font fontalias fopen foptname foptnum force formatted formchar formdelim formdlim forward fpoint fpos fput fread frewind frlen from fsep fuzz fwrite gaminv gamma getoption getvarc getvarn go goto group gwindow hbar hbound helpenv helploc hms honorappearance hosthelp hostprint hour hpct html hvar ibessel ibr id if index indexc indexw initcmd initstmt inner input inputc inputn inr insert int intck intnx into intrr invaliddata irr is jbessel join juldate keep kentb kurtosis label lag last lbound leave left length levels lgamma lib library libref line linesize link list log log10 log2 logpdf logpmf logsdf lostcard lowcase lrecl ls macro macrogen maps mautosource max maxdec maxr mdy mean measures median memtype merge merror min minute missing missover mlogic mod mode model modify month mopen mort mprint mrecall msglevel msymtabmax mvarsize myy n nest netpv new news nmiss no nobatch nobs nocaps nocardimage nocenter nocharcode nocmdmac nocol nocum nodate nodbcs nodetails nodmr nodms nodmsbatch nodup nodupkey noduplicates noechoauto noequals noerrorabend noexitwindows nofullstimer noicon noimplmac noint nolist noloadlist nomiss nomlogic nomprint nomrecall nomsgcase nomstored nomultenvappl nonotes nonumber noobs noovp nopad nopercent noprint noprintinit normal norow norsasuser nosetinit nosplash nosymbolgen note notes notitle notitles notsorted noverbose noxsync noxwait npv null number numkeys nummousekeys nway obs on open order ordinal otherwise out outer outp= output over ovp p(1 5 10 25 50 75 90 95 99) pad pad2 paired parm parmcards path pathdll pathname pdf peek peekc pfkey pmf point poisson poke position printer probbeta probbnml probchi probf probgam probhypr probit probnegb probnorm probsig probt procleave prt ps pw pwreq qtr quote r ranbin rancau ranexp rangam range ranks rannor ranpoi rantbl rantri ranuni read recfm register regr remote remove rename repeat replace resolve retain return reuse reverse rewind right round rsquare rtf rtrace rtraceloc s s2 samploc sasautos sascontrol sasfrscr sasmsg sasmstore sasscript sasuser saving scan sdf second select selection separated seq serror set setcomm setot sign simple sin sinh siteinfo skewness skip sle sls sortedby sortpgm sortseq sortsize soundex spedis splashlocation split spool sqrt start std stderr stdin stfips stimer stname stnamel stop stopover subgroup subpopn substr sum sumwgt symbol symbolgen symget symput sysget sysin sysleave sysmsg sysparm sysprint sysprintfont sysprod sysrc system t table tables tan tanh tapeclose tbufsize terminal test then timepart tinv tnonct to today tol tooldef totper transformout translate trantab tranwrd trigamma trim trimn trunc truncover type unformatted uniform union until upcase update user usericon uss validate value var weight when where while wincharset window work workinit workterm write wsum xsync xwait yearcutoff yes yyq min max', ['inDataStep', 'inProc']);
  76. define('operator', 'and not ', ['inDataStep', 'inProc']);
  77. // Main function
  78. function tokenize(stream, state) {
  79. // Finally advance the stream
  80. var ch = stream.next();
  81. // BLOCKCOMMENT
  82. if (ch === '/' && stream.eat('*')) {
  83. state.continueComment = true;
  84. return "comment";
  85. } else if (state.continueComment === true) { // in comment block
  86. //comment ends at the beginning of the line
  87. if (ch === '*' && stream.peek() === '/') {
  88. stream.next();
  89. state.continueComment = false;
  90. } else if (stream.skipTo('*')) { //comment is potentially later in line
  91. stream.skipTo('*');
  92. stream.next();
  93. if (stream.eat('/'))
  94. state.continueComment = false;
  95. } else {
  96. stream.skipToEnd();
  97. }
  98. return "comment";
  99. }
  100. // DoubleOperator match
  101. var doubleOperator = ch + stream.peek();
  102. // Match all line comments.
  103. var myString = stream.string;
  104. var myRegexp = /(?:^\s*|[;]\s*)(\*.*?);/ig;
  105. var match = myRegexp.exec(myString);
  106. if (match !== null) {
  107. if (match.index === 0 && (stream.column() !== (match.index + match[0].length - 1))) {
  108. stream.backUp(stream.column());
  109. stream.skipTo(';');
  110. stream.next();
  111. return 'comment';
  112. } else if (match.index + 1 < stream.column() && stream.column() < match.index + match[0].length - 1) {
  113. // the ';' triggers the match so move one past it to start
  114. // the comment block that is why match.index+1
  115. stream.backUp(stream.column() - match.index - 1);
  116. stream.skipTo(';');
  117. stream.next();
  118. return 'comment';
  119. }
  120. } else if (!state.continueString && (ch === '"' || ch === "'")) {
  121. // Have we found a string?
  122. state.continueString = ch; //save the matching quote in the state
  123. return "string";
  124. } else if (state.continueString !== null) {
  125. if (stream.skipTo(state.continueString)) {
  126. // quote found on this line
  127. stream.next();
  128. state.continueString = null;
  129. } else {
  130. stream.skipToEnd();
  131. }
  132. return "string";
  133. } else if (state.continueString !== null && stream.eol()) {
  134. stream.skipTo(state.continueString) || stream.skipToEnd();
  135. return "string";
  136. } else if (/[\d\.]/.test(ch)) { //find numbers
  137. if (ch === ".")
  138. stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/);
  139. else if (ch === "0")
  140. stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);
  141. else
  142. stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/);
  143. return "number";
  144. } else if (isDoubleOperatorChar.test(ch + stream.peek())) { // TWO SYMBOL TOKENS
  145. stream.next();
  146. return "operator";
  147. } else if (isDoubleOperatorSym.hasOwnProperty(doubleOperator)) {
  148. stream.next();
  149. if (stream.peek() === ' ')
  150. return isDoubleOperatorSym[doubleOperator.toLowerCase()];
  151. } else if (isSingleOperatorChar.test(ch)) { // SINGLE SYMBOL TOKENS
  152. return "operator";
  153. }
  154. // Matches one whole word -- even if the word is a character
  155. var word;
  156. if (stream.match(/[%&;\w]+/, false) != null) {
  157. word = ch + stream.match(/[%&;\w]+/, true);
  158. if (/&/.test(word)) return 'variable'
  159. } else {
  160. word = ch;
  161. }
  162. // the word after DATA PROC or MACRO
  163. if (state.nextword) {
  164. stream.match(/[\w]+/);
  165. // match memname.libname
  166. if (stream.peek() === '.') stream.skipTo(' ');
  167. state.nextword = false;
  168. return 'variable-2';
  169. }
  170. // Are we in a DATA Step?
  171. if (state.inDataStep) {
  172. if (word.toLowerCase() === 'run;' || stream.match(/run\s;/)) {
  173. state.inDataStep = false;
  174. return 'builtin';
  175. }
  176. // variable formats
  177. if ((word) && stream.next() === '.') {
  178. //either a format or libname.memname
  179. if (/\w/.test(stream.peek())) return 'variable-2';
  180. else return 'variable';
  181. }
  182. // do we have a DATA Step keyword
  183. if (word && words.hasOwnProperty(word.toLowerCase()) &&
  184. (words[word.toLowerCase()].state.indexOf("inDataStep") !== -1 ||
  185. words[word.toLowerCase()].state.indexOf("ALL") !== -1)) {
  186. //backup to the start of the word
  187. if (stream.start < stream.pos)
  188. stream.backUp(stream.pos - stream.start);
  189. //advance the length of the word and return
  190. for (var i = 0; i < word.length; ++i) stream.next();
  191. return words[word.toLowerCase()].style;
  192. }
  193. }
  194. // Are we in an Proc statement?
  195. if (state.inProc) {
  196. if (word.toLowerCase() === 'run;' || word.toLowerCase() === 'quit;') {
  197. state.inProc = false;
  198. return 'builtin';
  199. }
  200. // do we have a proc keyword
  201. if (word && words.hasOwnProperty(word.toLowerCase()) &&
  202. (words[word.toLowerCase()].state.indexOf("inProc") !== -1 ||
  203. words[word.toLowerCase()].state.indexOf("ALL") !== -1)) {
  204. stream.match(/[\w]+/);
  205. return words[word].style;
  206. }
  207. }
  208. // Are we in a Macro statement?
  209. if (state.inMacro) {
  210. if (word.toLowerCase() === '%mend') {
  211. if (stream.peek() === ';') stream.next();
  212. state.inMacro = false;
  213. return 'builtin';
  214. }
  215. if (word && words.hasOwnProperty(word.toLowerCase()) &&
  216. (words[word.toLowerCase()].state.indexOf("inMacro") !== -1 ||
  217. words[word.toLowerCase()].state.indexOf("ALL") !== -1)) {
  218. stream.match(/[\w]+/);
  219. return words[word.toLowerCase()].style;
  220. }
  221. return 'atom';
  222. }
  223. // Do we have Keywords specific words?
  224. if (word && words.hasOwnProperty(word.toLowerCase())) {
  225. // Negates the initial next()
  226. stream.backUp(1);
  227. // Actually move the stream
  228. stream.match(/[\w]+/);
  229. if (word.toLowerCase() === 'data' && /=/.test(stream.peek()) === false) {
  230. state.inDataStep = true;
  231. state.nextword = true;
  232. return 'builtin';
  233. }
  234. if (word.toLowerCase() === 'proc') {
  235. state.inProc = true;
  236. state.nextword = true;
  237. return 'builtin';
  238. }
  239. if (word.toLowerCase() === '%macro') {
  240. state.inMacro = true;
  241. state.nextword = true;
  242. return 'builtin';
  243. }
  244. if (/title[1-9]/i.test(word)) return 'def';
  245. if (word.toLowerCase() === 'footnote') {
  246. stream.eat(/[1-9]/);
  247. return 'def';
  248. }
  249. // Returns their value as state in the prior define methods
  250. if (state.inDataStep === true && words[word.toLowerCase()].state.indexOf("inDataStep") !== -1)
  251. return words[word.toLowerCase()].style;
  252. if (state.inProc === true && words[word.toLowerCase()].state.indexOf("inProc") !== -1)
  253. return words[word.toLowerCase()].style;
  254. if (state.inMacro === true && words[word.toLowerCase()].state.indexOf("inMacro") !== -1)
  255. return words[word.toLowerCase()].style;
  256. if (words[word.toLowerCase()].state.indexOf("ALL") !== -1)
  257. return words[word.toLowerCase()].style;
  258. return null;
  259. }
  260. // Unrecognized syntax
  261. return null;
  262. }
  263. return {
  264. startState: function () {
  265. return {
  266. inDataStep: false,
  267. inProc: false,
  268. inMacro: false,
  269. nextword: false,
  270. continueString: null,
  271. continueComment: false
  272. };
  273. },
  274. token: function (stream, state) {
  275. // Strip the spaces, but regex will account for them either way
  276. if (stream.eatSpace()) return null;
  277. // Go through the main process
  278. return tokenize(stream, state);
  279. },
  280. blockCommentStart: "/*",
  281. blockCommentEnd: "*/"
  282. };
  283. });
  284. CodeMirror.defineMIME("text/x-sas", "sas");
  285. });