yaml-frontmatter.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // CodeMirror, copyright (c) by Marijn Haverbeke and others
  2. // Distributed under an MIT license: https://codemirror.net/LICENSE
  3. (function (mod) {
  4. if (typeof exports == "object" && typeof module == "object") // CommonJS
  5. mod(require("../../lib/codemirror"), require("../yaml/yaml"))
  6. else if (typeof define == "function" && define.amd) // AMD
  7. define(["../../lib/codemirror", "../yaml/yaml"], mod)
  8. else // Plain browser env
  9. mod(CodeMirror)
  10. })(function (CodeMirror) {
  11. var START = 0, FRONTMATTER = 1, BODY = 2
  12. // a mixed mode for Markdown text with an optional YAML front matter
  13. CodeMirror.defineMode("yaml-frontmatter", function (config, parserConfig) {
  14. var yamlMode = CodeMirror.getMode(config, "yaml")
  15. var innerMode = CodeMirror.getMode(config, parserConfig && parserConfig.base || "gfm")
  16. function curMode(state) {
  17. return state.state == BODY ? innerMode : yamlMode
  18. }
  19. return {
  20. startState: function () {
  21. return {
  22. state: START,
  23. inner: CodeMirror.startState(yamlMode)
  24. }
  25. },
  26. copyState: function (state) {
  27. return {
  28. state: state.state,
  29. inner: CodeMirror.copyState(curMode(state), state.inner)
  30. }
  31. },
  32. token: function (stream, state) {
  33. if (state.state == START) {
  34. if (stream.match(/---/, false)) {
  35. state.state = FRONTMATTER
  36. return yamlMode.token(stream, state.inner)
  37. } else {
  38. state.state = BODY
  39. state.inner = CodeMirror.startState(innerMode)
  40. return innerMode.token(stream, state.inner)
  41. }
  42. } else if (state.state == FRONTMATTER) {
  43. var end = stream.sol() && stream.match(/---/, false)
  44. var style = yamlMode.token(stream, state.inner)
  45. if (end) {
  46. state.state = BODY
  47. state.inner = CodeMirror.startState(innerMode)
  48. }
  49. return style
  50. } else {
  51. return innerMode.token(stream, state.inner)
  52. }
  53. },
  54. innerMode: function (state) {
  55. return {mode: curMode(state), state: state.inner}
  56. },
  57. blankLine: function (state) {
  58. var mode = curMode(state)
  59. if (mode.blankLine) return mode.blankLine(state.inner)
  60. }
  61. }
  62. })
  63. });