brainfuck.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. // Brainfuck mode created by Michael Kaminsky https://github.com/mkaminsky11
  4. ;(function (mod) {
  5. if (typeof exports == 'object' && typeof module == 'object') mod(require('../../lib/codemirror'))
  6. else if (typeof define == 'function' && define.amd) define(['../../lib/codemirror'], mod)
  7. else mod(CodeMirror)
  8. })(function (CodeMirror) {
  9. 'use strict'
  10. var reserve = '><+-.,[]'.split('')
  11. /*
  12. comments can be either:
  13. placed behind lines
  14. +++ this is a comment
  15. where reserved characters cannot be used
  16. or in a loop
  17. [
  18. this is ok to use [ ] and stuff
  19. ]
  20. or preceded by #
  21. */
  22. CodeMirror.defineMode('brainfuck', function () {
  23. return {
  24. startState: function () {
  25. return {
  26. commentLine: false,
  27. left: 0,
  28. right: 0,
  29. commentLoop: false,
  30. }
  31. },
  32. token: function (stream, state) {
  33. if (stream.eatSpace()) return null
  34. if (stream.sol()) {
  35. state.commentLine = false
  36. }
  37. var ch = stream.next().toString()
  38. if (reserve.indexOf(ch) !== -1) {
  39. if (state.commentLine === true) {
  40. if (stream.eol()) {
  41. state.commentLine = false
  42. }
  43. return 'comment'
  44. }
  45. if (ch === ']' || ch === '[') {
  46. if (ch === '[') {
  47. state.left++
  48. } else {
  49. state.right++
  50. }
  51. return 'bracket'
  52. } else if (ch === '+' || ch === '-') {
  53. return 'keyword'
  54. } else if (ch === '<' || ch === '>') {
  55. return 'atom'
  56. } else if (ch === '.' || ch === ',') {
  57. return 'def'
  58. }
  59. } else {
  60. state.commentLine = true
  61. if (stream.eol()) {
  62. state.commentLine = false
  63. }
  64. return 'comment'
  65. }
  66. if (stream.eol()) {
  67. state.commentLine = false
  68. }
  69. },
  70. }
  71. })
  72. CodeMirror.defineMIME('text/x-brainfuck', 'brainfuck')
  73. })