scheme.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245
  1. /**
  2. * Author: Koh Zi Han, based on implementation by Koh Zi Chun
  3. */
  4. (function(mod) {
  5. if (typeof exports == "object" && typeof module == "object") // CommonJS
  6. mod(require("../../lib/codemirror"));
  7. else if (typeof define == "function" && define.amd) // AMD
  8. define(["../../lib/codemirror"], mod);
  9. else // Plain browser env
  10. mod(CodeMirror);
  11. })(function(CodeMirror) {
  12. "use strict";
  13. CodeMirror.defineMode("scheme", function () {
  14. var BUILTIN = "builtin", COMMENT = "comment", STRING = "string",
  15. ATOM = "atom", NUMBER = "number", BRACKET = "bracket";
  16. var INDENT_WORD_SKIP = 2;
  17. function makeKeywords(str) {
  18. var obj = {}, words = str.split(" ");
  19. for (var i = 0; i < words.length; ++i) obj[words[i]] = true;
  20. return obj;
  21. }
  22. var keywords = makeKeywords("λ case-lambda call/cc class define-class 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 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?");
  23. var indentKeys = makeKeywords("define let letrec let* lambda");
  24. function stateStack(indent, type, prev) { // represents a state stack object
  25. this.indent = indent;
  26. this.type = type;
  27. this.prev = prev;
  28. }
  29. function pushStack(state, indent, type) {
  30. state.indentStack = new stateStack(indent, type, state.indentStack);
  31. }
  32. function popStack(state) {
  33. state.indentStack = state.indentStack.prev;
  34. }
  35. var binaryMatcher = new RegExp(/^(?:[-+]i|[-+][01]+#*(?:\/[01]+#*)?i|[-+]?[01]+#*(?:\/[01]+#*)?@[-+]?[01]+#*(?:\/[01]+#*)?|[-+]?[01]+#*(?:\/[01]+#*)?[-+](?:[01]+#*(?:\/[01]+#*)?)?i|[-+]?[01]+#*(?:\/[01]+#*)?)(?=[()\s;"]|$)/i);
  36. 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);
  37. 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);
  38. 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);
  39. function isBinaryNumber (stream) {
  40. return stream.match(binaryMatcher);
  41. }
  42. function isOctalNumber (stream) {
  43. return stream.match(octalMatcher);
  44. }
  45. function isDecimalNumber (stream, backup) {
  46. if (backup === true) {
  47. stream.backUp(1);
  48. }
  49. return stream.match(decimalMatcher);
  50. }
  51. function isHexNumber (stream) {
  52. return stream.match(hexMatcher);
  53. }
  54. return {
  55. startState: function () {
  56. return {
  57. indentStack: null,
  58. indentation: 0,
  59. mode: false,
  60. sExprComment: false
  61. };
  62. },
  63. token: function (stream, state) {
  64. if (state.indentStack == null && stream.sol()) {
  65. // update indentation, but only if indentStack is empty
  66. state.indentation = stream.indentation();
  67. }
  68. // skip spaces
  69. if (stream.eatSpace()) {
  70. return null;
  71. }
  72. var returnType = null;
  73. switch(state.mode){
  74. case "string": // multi-line string parsing mode
  75. var next, escaped = false;
  76. while ((next = stream.next()) != null) {
  77. if (next == "\"" && !escaped) {
  78. state.mode = false;
  79. break;
  80. }
  81. escaped = !escaped && next == "\\";
  82. }
  83. returnType = STRING; // continue on in scheme-string mode
  84. break;
  85. case "comment": // comment parsing mode
  86. var next, maybeEnd = false;
  87. while ((next = stream.next()) != null) {
  88. if (next == "#" && maybeEnd) {
  89. state.mode = false;
  90. break;
  91. }
  92. maybeEnd = (next == "|");
  93. }
  94. returnType = COMMENT;
  95. break;
  96. case "s-expr-comment": // s-expr commenting mode
  97. state.mode = false;
  98. if(stream.peek() == "(" || stream.peek() == "["){
  99. // actually start scheme s-expr commenting mode
  100. state.sExprComment = 0;
  101. }else{
  102. // if not we just comment the entire of the next token
  103. stream.eatWhile(/[^/s]/); // eat non spaces
  104. returnType = COMMENT;
  105. break;
  106. }
  107. default: // default parsing mode
  108. var ch = stream.next();
  109. if (ch == "\"") {
  110. state.mode = "string";
  111. returnType = STRING;
  112. } else if (ch == "'") {
  113. returnType = ATOM;
  114. } else if (ch == '#') {
  115. if (stream.eat("|")) { // Multi-line comment
  116. state.mode = "comment"; // toggle to comment mode
  117. returnType = COMMENT;
  118. } else if (stream.eat(/[tf]/i)) { // #t/#f (atom)
  119. returnType = ATOM;
  120. } else if (stream.eat(';')) { // S-Expr comment
  121. state.mode = "s-expr-comment";
  122. returnType = COMMENT;
  123. } else {
  124. var numTest = null, hasExactness = false, hasRadix = true;
  125. if (stream.eat(/[ei]/i)) {
  126. hasExactness = true;
  127. } else {
  128. stream.backUp(1); // must be radix specifier
  129. }
  130. if (stream.match(/^#b/i)) {
  131. numTest = isBinaryNumber;
  132. } else if (stream.match(/^#o/i)) {
  133. numTest = isOctalNumber;
  134. } else if (stream.match(/^#x/i)) {
  135. numTest = isHexNumber;
  136. } else if (stream.match(/^#d/i)) {
  137. numTest = isDecimalNumber;
  138. } else if (stream.match(/^[-+0-9.]/, false)) {
  139. hasRadix = false;
  140. numTest = isDecimalNumber;
  141. // re-consume the intial # if all matches failed
  142. } else if (!hasExactness) {
  143. stream.eat('#');
  144. }
  145. if (numTest != null) {
  146. if (hasRadix && !hasExactness) {
  147. // consume optional exactness after radix
  148. stream.match(/^#[ei]/i);
  149. }
  150. if (numTest(stream))
  151. returnType = NUMBER;
  152. }
  153. }
  154. } else if (/^[-+0-9.]/.test(ch) && isDecimalNumber(stream, true)) { // match non-prefixed number, must be decimal
  155. returnType = NUMBER;
  156. } else if (ch == ";") { // comment
  157. stream.skipToEnd(); // rest of the line is a comment
  158. returnType = COMMENT;
  159. } else if (ch == "(" || ch == "[") {
  160. var keyWord = ''; var indentTemp = stream.column(), letter;
  161. /**
  162. Either
  163. (indent-word ..
  164. (non-indent-word ..
  165. (;something else, bracket, etc.
  166. */
  167. while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) {
  168. keyWord += letter;
  169. }
  170. if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) { // indent-word
  171. pushStack(state, indentTemp + INDENT_WORD_SKIP, ch);
  172. } else { // non-indent word
  173. // we continue eating the spaces
  174. stream.eatSpace();
  175. if (stream.eol() || stream.peek() == ";") {
  176. // nothing significant after
  177. // we restart indentation 1 space after
  178. pushStack(state, indentTemp + 1, ch);
  179. } else {
  180. pushStack(state, indentTemp + stream.current().length, ch); // else we match
  181. }
  182. }
  183. stream.backUp(stream.current().length - 1); // undo all the eating
  184. if(typeof state.sExprComment == "number") state.sExprComment++;
  185. returnType = BRACKET;
  186. } else if (ch == ")" || ch == "]") {
  187. returnType = BRACKET;
  188. if (state.indentStack != null && state.indentStack.type == (ch == ")" ? "(" : "[")) {
  189. popStack(state);
  190. if(typeof state.sExprComment == "number"){
  191. if(--state.sExprComment == 0){
  192. returnType = COMMENT; // final closing bracket
  193. state.sExprComment = false; // turn off s-expr commenting mode
  194. }
  195. }
  196. }
  197. } else {
  198. stream.eatWhile(/[\w\$_\-!$%&*+\.\/:<=>?@\^~]/);
  199. if (keywords && keywords.propertyIsEnumerable(stream.current())) {
  200. returnType = BUILTIN;
  201. } else returnType = "variable";
  202. }
  203. }
  204. return (typeof state.sExprComment == "number") ? COMMENT : returnType;
  205. },
  206. indent: function (state) {
  207. if (state.indentStack == null) return state.indentation;
  208. return state.indentStack.indent;
  209. },
  210. lineComment: ";;"
  211. };
  212. });
  213. CodeMirror.defineMIME("text/x-scheme", "scheme");
  214. });