index.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. /*
  2. * md ast - pluggable markdown parser
  3. */
  4. const syntax = {
  5. bold: {
  6. paired: true,
  7. recursive: true,
  8. startRegexp: /\s\*\*\S.*/,
  9. endRegexp: /\S\*\*\s/,
  10. content: {
  11. start: {
  12. point: 'start',
  13. offset: 3
  14. },
  15. end: {
  16. point: 'end',
  17. offset: 1
  18. }
  19. },
  20. forward: {
  21. point: 'endEnd', //start, startEnd, end, endEnd
  22. offset: -1
  23. }
  24. },
  25. bold2: {
  26. paired: true,
  27. recursive: true,
  28. startRegexp: /__\S.*/,
  29. endRegexp: /\S__\s/,
  30. content: {
  31. start: {
  32. point: 'start',
  33. offset: 3
  34. },
  35. end: {
  36. point: 'end',
  37. offset: 1
  38. }
  39. },
  40. forward: {
  41. point: 'endEnd', //start, startEnd, end, endEnd
  42. offset: -1
  43. }
  44. },
  45. italic: {
  46. paired: true,
  47. recursive: true,
  48. startRegexp: /\s\*\S.*/,
  49. endRegexp: /\S\*\s/,
  50. content: {
  51. start: {
  52. point: 'start',
  53. offset: 2
  54. },
  55. end: {
  56. point: 'end',
  57. offset: 1
  58. }
  59. },
  60. forward: {
  61. point: 'endEnd', //start, startEnd, end, endEnd
  62. offset: -1
  63. }
  64. },
  65. italic2: {
  66. paired: true,
  67. recursive: true,
  68. startRegexp: /_\S.*/,
  69. endRegexp: /\S_\s/,
  70. content: {
  71. start: {
  72. point: 'start',
  73. offset: 2
  74. },
  75. end: {
  76. point: 'end',
  77. offset: 1
  78. }
  79. },
  80. forward: {
  81. point: 'endEnd', //start, startEnd, end, endEnd
  82. offset: -1
  83. }
  84. },
  85. }
  86. function findNearest(md, mdTags){
  87. let nearest, nearestMatch = {index: Infinity};
  88. for (let [mdTag, {paired,
  89. recursive,
  90. startRegexp,
  91. endRegexp,
  92. content: {start,
  93. end},
  94. forward}] of Object.entries(mdTags)) {
  95. let match = md.match(startRegexp)
  96. if (match && match.index < nearestMatch.index){
  97. nearestMatch = match
  98. nearest = mdTag
  99. }
  100. }
  101. return [nearest, nearestMatch]
  102. }
  103. function buildAST(md, mdTags=syntax, tree=[], path=[]){
  104. console.log(findNearest(md, mdTags))
  105. }
  106. buildAST("I just __love__ __bold text__. ")