sas.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://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 within * ; 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 ddfm 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 random ranexp rangam range ranks rannor ranpoi rantbl rantri ranuni rcorr read recfm register regr remote remove rename repeat repeated 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 sub 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. if (ch == "*" && stream.column() == stream.indentation()) {
  101. stream.skipToEnd()
  102. return "comment"
  103. }
  104. // DoubleOperator match
  105. var doubleOperator = ch + stream.peek();
  106. if ((ch === '"' || ch === "'") && !state.continueString) {
  107. state.continueString = ch
  108. return "string"
  109. } else if (state.continueString) {
  110. if (state.continueString == ch) {
  111. state.continueString = null;
  112. } else if (stream.skipTo(state.continueString)) {
  113. // quote found on this line
  114. stream.next();
  115. state.continueString = null;
  116. } else {
  117. stream.skipToEnd();
  118. }
  119. return "string";
  120. } else if (state.continueString !== null && stream.eol()) {
  121. stream.skipTo(state.continueString) || stream.skipToEnd();
  122. return "string";
  123. } else if (/[\d\.]/.test(ch)) { //find numbers
  124. if (ch === ".")
  125. stream.match(/^[0-9]+([eE][\-+]?[0-9]+)?/);
  126. else if (ch === "0")
  127. stream.match(/^[xX][0-9a-fA-F]+/) || stream.match(/^0[0-7]+/);
  128. else
  129. stream.match(/^[0-9]*\.?[0-9]*([eE][\-+]?[0-9]+)?/);
  130. return "number";
  131. } else if (isDoubleOperatorChar.test(ch + stream.peek())) { // TWO SYMBOL TOKENS
  132. stream.next();
  133. return "operator";
  134. } else if (isDoubleOperatorSym.hasOwnProperty(doubleOperator)) {
  135. stream.next();
  136. if (stream.peek() === ' ')
  137. return isDoubleOperatorSym[doubleOperator.toLowerCase()];
  138. } else if (isSingleOperatorChar.test(ch)) { // SINGLE SYMBOL TOKENS
  139. return "operator";
  140. }
  141. // Matches one whole word -- even if the word is a character
  142. var word;
  143. if (stream.match(/[%&;\w]+/, false) != null) {
  144. word = ch + stream.match(/[%&;\w]+/, true);
  145. if (/&/.test(word)) return 'variable'
  146. } else {
  147. word = ch;
  148. }
  149. // the word after DATA PROC or MACRO
  150. if (state.nextword) {
  151. stream.match(/[\w]+/);
  152. // match memname.libname
  153. if (stream.peek() === '.') stream.skipTo(' ');
  154. state.nextword = false;
  155. return 'variable-2';
  156. }
  157. word = word.toLowerCase()
  158. // Are we in a DATA Step?
  159. if (state.inDataStep) {
  160. if (word === 'run;' || stream.match(/run\s;/)) {
  161. state.inDataStep = false;
  162. return 'builtin';
  163. }
  164. // variable formats
  165. if ((word) && stream.next() === '.') {
  166. //either a format or libname.memname
  167. if (/\w/.test(stream.peek())) return 'variable-2';
  168. else return 'variable';
  169. }
  170. // do we have a DATA Step keyword
  171. if (word && words.hasOwnProperty(word) &&
  172. (words[word].state.indexOf("inDataStep") !== -1 ||
  173. words[word].state.indexOf("ALL") !== -1)) {
  174. //backup to the start of the word
  175. if (stream.start < stream.pos)
  176. stream.backUp(stream.pos - stream.start);
  177. //advance the length of the word and return
  178. for (var i = 0; i < word.length; ++i) stream.next();
  179. return words[word].style;
  180. }
  181. }
  182. // Are we in an Proc statement?
  183. if (state.inProc) {
  184. if (word === 'run;' || word === 'quit;') {
  185. state.inProc = false;
  186. return 'builtin';
  187. }
  188. // do we have a proc keyword
  189. if (word && words.hasOwnProperty(word) &&
  190. (words[word].state.indexOf("inProc") !== -1 ||
  191. words[word].state.indexOf("ALL") !== -1)) {
  192. stream.match(/[\w]+/);
  193. return words[word].style;
  194. }
  195. }
  196. // Are we in a Macro statement?
  197. if (state.inMacro) {
  198. if (word === '%mend') {
  199. if (stream.peek() === ';') stream.next();
  200. state.inMacro = false;
  201. return 'builtin';
  202. }
  203. if (word && words.hasOwnProperty(word) &&
  204. (words[word].state.indexOf("inMacro") !== -1 ||
  205. words[word].state.indexOf("ALL") !== -1)) {
  206. stream.match(/[\w]+/);
  207. return words[word].style;
  208. }
  209. return 'atom';
  210. }
  211. // Do we have Keywords specific words?
  212. if (word && words.hasOwnProperty(word)) {
  213. // Negates the initial next()
  214. stream.backUp(1);
  215. // Actually move the stream
  216. stream.match(/[\w]+/);
  217. if (word === 'data' && /=/.test(stream.peek()) === false) {
  218. state.inDataStep = true;
  219. state.nextword = true;
  220. return 'builtin';
  221. }
  222. if (word === 'proc') {
  223. state.inProc = true;
  224. state.nextword = true;
  225. return 'builtin';
  226. }
  227. if (word === '%macro') {
  228. state.inMacro = true;
  229. state.nextword = true;
  230. return 'builtin';
  231. }
  232. if (/title[1-9]/.test(word)) return 'def';
  233. if (word === 'footnote') {
  234. stream.eat(/[1-9]/);
  235. return 'def';
  236. }
  237. // Returns their value as state in the prior define methods
  238. if (state.inDataStep === true && words[word].state.indexOf("inDataStep") !== -1)
  239. return words[word].style;
  240. if (state.inProc === true && words[word].state.indexOf("inProc") !== -1)
  241. return words[word].style;
  242. if (state.inMacro === true && words[word].state.indexOf("inMacro") !== -1)
  243. return words[word].style;
  244. if (words[word].state.indexOf("ALL") !== -1)
  245. return words[word].style;
  246. return null;
  247. }
  248. // Unrecognized syntax
  249. return null;
  250. }
  251. return {
  252. startState: function () {
  253. return {
  254. inDataStep: false,
  255. inProc: false,
  256. inMacro: false,
  257. nextword: false,
  258. continueString: null,
  259. continueComment: false
  260. };
  261. },
  262. token: function (stream, state) {
  263. // Strip the spaces, but regex will account for them either way
  264. if (stream.eatSpace()) return null;
  265. // Go through the main process
  266. return tokenize(stream, state);
  267. },
  268. blockCommentStart: "/*",
  269. blockCommentEnd: "*/"
  270. };
  271. });
  272. CodeMirror.defineMIME("text/x-sas", "sas");
  273. });