scheme.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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')
  9. // CommonJS
  10. mod(require('../../lib/codemirror'))
  11. else if (typeof define == 'function' && define.amd)
  12. // AMD
  13. define(['../../lib/codemirror'], mod)
  14. // Plain browser env
  15. else mod(CodeMirror)
  16. })(function (CodeMirror) {
  17. 'use strict'
  18. CodeMirror.defineMode('scheme', function () {
  19. var BUILTIN = 'builtin',
  20. COMMENT = 'comment',
  21. STRING = 'string',
  22. SYMBOL = 'symbol',
  23. ATOM = 'atom',
  24. NUMBER = 'number',
  25. BRACKET = 'bracket'
  26. var INDENT_WORD_SKIP = 2
  27. function makeKeywords(str) {
  28. var obj = {},
  29. words = str.split(' ')
  30. for (var i = 0; i < words.length; ++i) obj[words[i]] = true
  31. return obj
  32. }
  33. var keywords = makeKeywords(
  34. 'λ 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?'
  35. )
  36. 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')
  37. function stateStack(indent, type, prev) {
  38. // represents a state stack object
  39. this.indent = indent
  40. this.type = type
  41. this.prev = prev
  42. }
  43. function pushStack(state, indent, type) {
  44. state.indentStack = new stateStack(indent, type, state.indentStack)
  45. }
  46. function popStack(state) {
  47. state.indentStack = state.indentStack.prev
  48. }
  49. var binaryMatcher = new RegExp(
  50. /^(?:[-+]i|[-+][01]+#*(?:\/[01]+#*)?i|[-+]?[01]+#*(?:\/[01]+#*)?@[-+]?[01]+#*(?:\/[01]+#*)?|[-+]?[01]+#*(?:\/[01]+#*)?[-+](?:[01]+#*(?:\/[01]+#*)?)?i|[-+]?[01]+#*(?:\/[01]+#*)?)(?=[()\s;"]|$)/i
  51. )
  52. var octalMatcher = new RegExp(
  53. /^(?:[-+]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
  54. )
  55. var hexMatcher = new RegExp(
  56. /^(?:[-+]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
  57. )
  58. var decimalMatcher = new RegExp(
  59. /^(?:[-+]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
  60. )
  61. function isBinaryNumber(stream) {
  62. return stream.match(binaryMatcher)
  63. }
  64. function isOctalNumber(stream) {
  65. return stream.match(octalMatcher)
  66. }
  67. function isDecimalNumber(stream, backup) {
  68. if (backup === true) {
  69. stream.backUp(1)
  70. }
  71. return stream.match(decimalMatcher)
  72. }
  73. function isHexNumber(stream) {
  74. return stream.match(hexMatcher)
  75. }
  76. function processEscapedSequence(stream, options) {
  77. var next,
  78. escaped = false
  79. while ((next = stream.next()) != null) {
  80. if (next == options.token && !escaped) {
  81. options.state.mode = false
  82. break
  83. }
  84. escaped = !escaped && next == '\\'
  85. }
  86. }
  87. return {
  88. startState: function () {
  89. return {
  90. indentStack: null,
  91. indentation: 0,
  92. mode: false,
  93. sExprComment: false,
  94. sExprQuote: false,
  95. }
  96. },
  97. token: function (stream, state) {
  98. if (state.indentStack == null && stream.sol()) {
  99. // update indentation, but only if indentStack is empty
  100. state.indentation = stream.indentation()
  101. }
  102. // skip spaces
  103. if (stream.eatSpace()) {
  104. return null
  105. }
  106. var returnType = null
  107. switch (state.mode) {
  108. case 'string': // multi-line string parsing mode
  109. processEscapedSequence(stream, {
  110. token: '"',
  111. state: state,
  112. })
  113. returnType = STRING // continue on in scheme-string mode
  114. break
  115. case 'symbol': // escape symbol
  116. processEscapedSequence(stream, {
  117. token: '|',
  118. state: state,
  119. })
  120. returnType = SYMBOL // continue on in scheme-symbol mode
  121. break
  122. case 'comment': // comment parsing mode
  123. var next,
  124. maybeEnd = false
  125. while ((next = stream.next()) != null) {
  126. if (next == '#' && maybeEnd) {
  127. state.mode = false
  128. break
  129. }
  130. maybeEnd = next == '|'
  131. }
  132. returnType = COMMENT
  133. break
  134. case 's-expr-comment': // s-expr commenting mode
  135. state.mode = false
  136. if (stream.peek() == '(' || stream.peek() == '[') {
  137. // actually start scheme s-expr commenting mode
  138. state.sExprComment = 0
  139. } else {
  140. // if not we just comment the entire of the next token
  141. stream.eatWhile(/[^\s\(\)\[\]]/) // eat symbol atom
  142. returnType = COMMENT
  143. break
  144. }
  145. default:
  146. // default parsing mode
  147. var ch = stream.next()
  148. if (ch == '"') {
  149. state.mode = 'string'
  150. returnType = STRING
  151. } else if (ch == "'") {
  152. if (stream.peek() == '(' || stream.peek() == '[') {
  153. if (typeof state.sExprQuote != 'number') {
  154. state.sExprQuote = 0
  155. } // else already in a quoted expression
  156. returnType = ATOM
  157. } else {
  158. stream.eatWhile(/[\w_\-!$%&*+\.\/:<=>?@\^~]/)
  159. returnType = ATOM
  160. }
  161. } else if (ch == '|') {
  162. state.mode = 'symbol'
  163. returnType = SYMBOL
  164. } else if (ch == '#') {
  165. if (stream.eat('|')) {
  166. // Multi-line comment
  167. state.mode = 'comment' // toggle to comment mode
  168. returnType = COMMENT
  169. } else if (stream.eat(/[tf]/i)) {
  170. // #t/#f (atom)
  171. returnType = ATOM
  172. } else if (stream.eat(';')) {
  173. // S-Expr comment
  174. state.mode = 's-expr-comment'
  175. returnType = COMMENT
  176. } else {
  177. var numTest = null,
  178. hasExactness = false,
  179. hasRadix = true
  180. if (stream.eat(/[ei]/i)) {
  181. hasExactness = true
  182. } else {
  183. stream.backUp(1) // must be radix specifier
  184. }
  185. if (stream.match(/^#b/i)) {
  186. numTest = isBinaryNumber
  187. } else if (stream.match(/^#o/i)) {
  188. numTest = isOctalNumber
  189. } else if (stream.match(/^#x/i)) {
  190. numTest = isHexNumber
  191. } else if (stream.match(/^#d/i)) {
  192. numTest = isDecimalNumber
  193. } else if (stream.match(/^[-+0-9.]/, false)) {
  194. hasRadix = false
  195. numTest = isDecimalNumber
  196. // re-consume the initial # if all matches failed
  197. } else if (!hasExactness) {
  198. stream.eat('#')
  199. }
  200. if (numTest != null) {
  201. if (hasRadix && !hasExactness) {
  202. // consume optional exactness after radix
  203. stream.match(/^#[ei]/i)
  204. }
  205. if (numTest(stream)) returnType = NUMBER
  206. }
  207. }
  208. } else if (/^[-+0-9.]/.test(ch) && isDecimalNumber(stream, true)) {
  209. // match non-prefixed number, must be decimal
  210. returnType = NUMBER
  211. } else if (ch == ';') {
  212. // comment
  213. stream.skipToEnd() // rest of the line is a comment
  214. returnType = COMMENT
  215. } else if (ch == '(' || ch == '[') {
  216. var keyWord = ''
  217. var indentTemp = stream.column(),
  218. letter
  219. /**
  220. Either
  221. (indent-word ..
  222. (non-indent-word ..
  223. (;something else, bracket, etc.
  224. */
  225. while ((letter = stream.eat(/[^\s\(\[\;\)\]]/)) != null) {
  226. keyWord += letter
  227. }
  228. if (keyWord.length > 0 && indentKeys.propertyIsEnumerable(keyWord)) {
  229. // indent-word
  230. pushStack(state, indentTemp + INDENT_WORD_SKIP, ch)
  231. } else {
  232. // non-indent word
  233. // we continue eating the spaces
  234. stream.eatSpace()
  235. if (stream.eol() || stream.peek() == ';') {
  236. // nothing significant after
  237. // we restart indentation 1 space after
  238. pushStack(state, indentTemp + 1, ch)
  239. } else {
  240. pushStack(state, indentTemp + stream.current().length, ch) // else we match
  241. }
  242. }
  243. stream.backUp(stream.current().length - 1) // undo all the eating
  244. if (typeof state.sExprComment == 'number') state.sExprComment++
  245. if (typeof state.sExprQuote == 'number') state.sExprQuote++
  246. returnType = BRACKET
  247. } else if (ch == ')' || ch == ']') {
  248. returnType = BRACKET
  249. if (state.indentStack != null && state.indentStack.type == (ch == ')' ? '(' : '[')) {
  250. popStack(state)
  251. if (typeof state.sExprComment == 'number') {
  252. if (--state.sExprComment == 0) {
  253. returnType = COMMENT // final closing bracket
  254. state.sExprComment = false // turn off s-expr commenting mode
  255. }
  256. }
  257. if (typeof state.sExprQuote == 'number') {
  258. if (--state.sExprQuote == 0) {
  259. returnType = ATOM // final closing bracket
  260. state.sExprQuote = false // turn off s-expr quote mode
  261. }
  262. }
  263. }
  264. } else {
  265. stream.eatWhile(/[\w_\-!$%&*+\.\/:<=>?@\^~]/)
  266. if (keywords && keywords.propertyIsEnumerable(stream.current())) {
  267. returnType = BUILTIN
  268. } else returnType = 'variable'
  269. }
  270. }
  271. return typeof state.sExprComment == 'number' ? COMMENT : typeof state.sExprQuote == 'number' ? ATOM : returnType
  272. },
  273. indent: function (state) {
  274. if (state.indentStack == null) return state.indentation
  275. return state.indentStack.indent
  276. },
  277. fold: 'brace-paren',
  278. closeBrackets: { pairs: '()[]{}""' },
  279. lineComment: ';;',
  280. }
  281. })
  282. CodeMirror.defineMIME('text/x-scheme', 'scheme')
  283. })