scheme.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. /**
  4. * Author: Koh Zi Han, based on implementation by Koh Zi Chun
  5. * Improved by: Jakub T. Jankiewicz
  6. */
  7. (function(mod) {
  8. if (typeof exports == "object" && typeof module == "object") // CommonJS
  9. mod(require("../../lib/codemirror"));
  10. else if (typeof define == "function" && define.amd) // AMD
  11. define(["../../lib/codemirror"], mod);
  12. else // Plain browser env
  13. mod(CodeMirror);
  14. })(function(CodeMirror) {
  15. "use strict";
  16. CodeMirror.defineMode("scheme", function () {
  17. var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
  18. SYMBOL = "symbol", ATOM = "atom", NUMBER = "number", BRACKET = "bracket";
  19. var INDENT_WORD_SKIP = 2;
  20. function makeKeywords(str) {
  21. var obj = {}, words = str.split(" ");
  22. for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  23. return obj;
  24. }
  25. var keywords = makeKeywords("λ case-lambda call/cc class cond-expand define-class define-values exit-handler field import inherit init-field interface let*-values let-values let/ec mixin opt-lambda override protect provide public rename require require-for-syntax syntax syntax-case syntax-error unit/sig unless when with-syntax and begin call-with-current-continuation call-with-input-file call-with-output-file case cond define define-syntax define-macro defmacro delay do dynamic-wind else for-each if lambda let let* let-syntax letrec letrec-syntax map or syntax-rules abs acos angle append apply asin assoc assq assv atan boolean? caar cadr call-with-input-file call-with-output-file call-with-values car cdddar cddddr cdr ceiling char->integer char-alphabetic? char-ci<=? char-ci<? char-ci=? char-ci>=? char-ci>? char-downcase char-lower-case? char-numeric? char-ready? char-upcase char-upper-case? char-whitespace? char<=? char<? char=? char>=? char>? char? close-input-port close-output-port complex? cons cos current-input-port current-output-port denominator display eof-object? eq? equal? eqv? eval even? exact->inexact exact? exp expt #f floor force gcd imag-part inexact->exact inexact? input-port? integer->char integer? interaction-environment lcm length list list->string list->vector list-ref list-tail list? load log magnitude make-polar make-rectangular make-string make-vector max member memq memv min modulo negative? newline not null-environment null? number->string number? numerator odd? open-input-file open-output-file output-port? pair? peek-char port? positive? procedure? quasiquote quote quotient rational? rationalize read read-char real-part real? remainder reverse round scheme-report-environment set! set-car! set-cdr! sin sqrt string string->list string->number string->symbol string-append string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? string-copy string-fill! string-length string-ref string-set! string<=? string<? string=? string>=? string>? string? substring symbol->string symbol? #t tan transcript-off transcript-on truncate values vector vector->list vector-fill! vector-length vector-ref vector-set! with-input-from-file with-output-to-file write write-char zero?");
  26. var indentKeys = makeKeywords("define let letrec let* lambda define-macro defmacro let-syntax letrec-syntax let-values let*-values define-syntax syntax-rules define-values when unless");
  27. function stateStack(indent, type, prev) { // represents a state stack object
  28. this.indent = indent;
  29. this.type = type;
  30. this.prev = prev;
  31. }
  32. function pushStack(state, indent, type) {
  33. state.indentStack = new stateStack(indent, type, state.indentStack);
  34. }
  35. function popStack(state) {
  36. state.indentStack = state.indentStack.prev;
  37. }
  38. var binaryMatcher = new RegExp(/^(?:[-+]i|[-+][01]+#*(?:\/[01]+#*)?i|[-+]?[01]+#*(?:\/[01]+#*)?@[-+]?[01]+#*(?:\/[01]+#*)?|[-+]?[01]+#*(?:\/[01]+#*)?[-+](?:[01]+#*(?:\/[01]+#*)?)?i|[-+]?[01]+#*(?:\/[01]+#*)?)(?=[()\s;"]|$)/i);
  39. var octalMatcher = new RegExp(/^(?:[-+]i|[-+][0-7]+#*(?:\/[0-7]+#*)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?@[-+]?[0-7]+#*(?:\/[0-7]+#*)?|[-+]?[0-7]+#*(?:\/[0-7]+#*)?[-+](?:[0-7]+#*(?:\/[0-7]+#*)?)?i|[-+]?[0-7]+#*(?:\/[0-7]+#*)?)(?=[()\s;"]|$)/i);
  40. var hexMatcher = new RegExp(/^(?:[-+]i|[-+][\da-f]+#*(?:\/[\da-f]+#*)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?@[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?[-+](?:[\da-f]+#*(?:\/[\da-f]+#*)?)?i|[-+]?[\da-f]+#*(?:\/[\da-f]+#*)?)(?=[()\s;"]|$)/i);
  41. var decimalMatcher = new RegExp(/^(?:[-+]i|[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)i|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)@[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)|[-+]?(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)[-+](?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*)?i|(?:(?:(?:\d+#+\.?#*|\d+\.\d*#*|\.\d+#*|\d+)(?:[esfdl][-+]?\d+)?)|\d+#*\/\d+#*))(?=[()\s;"]|$)/i);
  42. function isBinaryNumber (stream) {
  43. return stream.match(binaryMatcher);
  44. }
  45. function isOctalNumber (stream) {
  46. return stream.match(octalMatcher);
  47. }
  48. function isDecimalNumber (stream, backup) {
  49. if (backup === true) {
  50. stream.backUp(1);
  51. }
  52. return stream.match(decimalMatcher);
  53. }
  54. function isHexNumber (stream) {
  55. return stream.match(hexMatcher);
  56. }
  57. function processEscapedSequence(stream, options) {
  58. var next, escaped = false;
  59. while ((next = stream.next()) != null) {
  60. if (next == options.token && !escaped) {
  61. options.state.mode = false;
  62. break;
  63. }
  64. escaped = !escaped && next == "\\";
  65. }
  66. }
  67. return {
  68. startState: function () {
  69. return {
  70. indentStack: null,
  71. indentation: 0,
  72. mode: false,
  73. sExprComment: false,
  74. sExprQuote: false
  75. };
  76. },
  77. token: function (stream, state) {
  78. if (state.indentStack == null && stream.sol()) {
  79. // update indentation, but only if indentStack is empty
  80. state.indentation = stream.indentation();
  81. }
  82. // skip spaces
  83. if (stream.eatSpace()) {
  84. return null;
  85. }
  86. var returnType = null;
  87. switch(state.mode){
  88. case "string": // multi-line string parsing mode
  89. processEscapedSequence(stream, {
  90. token: "\"",
  91. state: state
  92. });
  93. returnType = STRING; // continue on in scheme-string mode
  94. break;
  95. case "symbol": // escape symbol
  96. processEscapedSequence(stream, {
  97. token: "|",
  98. state: state
  99. });
  100. returnType = SYMBOL; // continue on in scheme-symbol mode
  101. break;
  102. case "comment": // comment parsing mode
  103. var next, maybeEnd = false;
  104. while ((next = stream.next()) != null) {
  105. if (next == "#" && maybeEnd) {
  106. state.mode = false;
  107. break;
  108. }
  109. maybeEnd = (next == "|");
  110. }
  111. returnType = COMMENT;
  112. break;
  113. case "s-expr-comment": // s-expr commenting mode
  114. state.mode = false;
  115. if(stream.peek() == "(" || stream.peek() == "["){
  116. // actually start scheme s-expr commenting mode
  117. state.sExprComment = 0;
  118. }else{
  119. // if not we just comment the entire of the next token
  120. stream.eatWhile(/[^\s\(\)\[\]]/); // eat symbol atom
  121. returnType = COMMENT;
  122. break;
  123. }
  124. default: // default parsing mode
  125. var ch = stream.next();
  126. if (ch == "\"") {
  127. state.mode = "string";
  128. returnType = STRING;
  129. } else if (ch == "'") {
  130. if (stream.peek() == "(" || stream.peek() == "["){
  131. if (typeof state.sExprQuote != "number") {
  132. state.sExprQuote = 0;
  133. } // else already in a quoted expression
  134. returnType = ATOM;
  135. } else {
  136. stream.eatWhile(/[\w_\-!$%&*+\.\/:<=>?@\^~]/);
  137. returnType = ATOM;
  138. }
  139. } else if (ch == '|') {
  140. state.mode = "symbol";
  141. returnType = SYMBOL;
  142. } else if (ch == '#') {
  143. if (stream.eat("|")) { // Multi-line comment
  144. state.mode = "comment"; // toggle to comment mode
  145. returnType = COMMENT;
  146. } else if (stream.eat(/[tf]/i)) { // #t/#f (atom)
  147. returnType = ATOM;
  148. } else if (stream.eat(';')) { // S-Expr comment
  149. state.mode = "s-expr-comment";
  150. returnType = COMMENT;
  151. } else {
  152. var numTest = null, hasExactness = false, hasRadix = true;
  153. if (stream.eat(/[ei]/i)) {
  154. hasExactness = true;
  155. } else {
  156. stream.backUp(1); // must be radix specifier
  157. }
  158. if (stream.match(/^#b/i)) {
  159. numTest = isBinaryNumber;
  160. } else if (stream.match(/^#o/i)) {
  161. numTest = isOctalNumber;
  162. } else if (stream.match(/^#x/i)) {
  163. numTest = isHexNumber;
  164. } else if (stream.match(/^#d/i)) {
  165. numTest = isDecimalNumber;
  166. } else if (stream.match(/^[-+0-9.]/, false)) {
  167. hasRadix = false;
  168. numTest = isDecimalNumber;
  169. // re-consume the initial # if all matches failed
  170. } else if (!hasExactness) {
  171. stream.eat('#');
  172. }
  173. if (numTest != null) {
  174. if (hasRadix && !hasExactness) {
  175. // consume optional exactness after radix
  176. stream.match(/^#[ei]/i);
  177. }
  178. if (numTest(stream))
  179. returnType = NUMBER;
  180. }
  181. }
  182. } else if (/^[-+0-9.]/.test(ch) && isDecimalNumber(stream, true)) { // match non-prefixed number, must be decimal
  183. returnType = NUMBER;
  184. } else if (ch == ";") { // comment
  185. stream.skipToEnd(); // rest of the line is a comment
  186. returnType = COMMENT;
  187. } else if (ch == "(" || ch == "[") {
  188. var keyWord = ''; var indentTemp = stream.column(), letter;
  189. /**
  190. Either
  191. (indent-word ..
  192. (non-indent-word ..
  193. (;something else, bracket, etc.
  194. */
  195. while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) {
  196. keyWord += letter;
  197. }
  198. if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word
  199. pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
  200. } else { // non-indent word
  201. // we continue eating the spaces
  202. stream.eatSpace();
  203. if (stream.eol() || stream.peek() == ";") {
  204. // nothing significant after
  205. // we restart indentation 1 space after
  206. pushStack(state, indentTemp + 1, ch);
  207. } else {
  208. pushStack(state, indentTemp + stream.current().length, ch); // else we match
  209. }
  210. }
  211. stream.backUp(stream.current().length - 1); // undo all the eating
  212. if(typeof state.sExprComment == "number") state.sExprComment++;
  213. if(typeof state.sExprQuote == "number") state.sExprQuote++;
  214. returnType = BRACKET;
  215. } else if (ch == ")" || ch == "]") {
  216. returnType = BRACKET;
  217. if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
  218. popStack(state);
  219. if(typeof state.sExprComment == "number"){
  220. if(--state.sExprComment == 0){
  221. returnType = COMMENT; // final closing bracket
  222. state.sExprComment = false; // turn off s-expr commenting mode
  223. }
  224. }
  225. if(typeof state.sExprQuote == "number"){
  226. if(--state.sExprQuote == 0){
  227. returnType = ATOM; // final closing bracket
  228. state.sExprQuote = false; // turn off s-expr quote mode
  229. }
  230. }
  231. }
  232. } else {
  233. stream.eatWhile(/[\w_\-!$%&*+\.\/:<=>?@\^~]/);
  234. if (keywords && keywords.propertyIsEnumerable(stream.current())) {
  235. returnType = BUILTIN;
  236. } else returnType = "variable";
  237. }
  238. }
  239. return (typeof state.sExprComment == "number") ? COMMENT : ((typeof state.sExprQuote == "number") ? ATOM : returnType);
  240. },
  241. indent: function (state) {
  242. if (state.indentStack == null) return state.indentation;
  243. return state.indentStack.indent;
  244. },
  245. fold: "brace-paren",
  246. closeBrackets: {pairs: "()[]{}\"\""},
  247. lineComment: ";;"
  248. };
  249. });
  250. CodeMirror.defineMIME("text/x-scheme", "scheme");
  251. });