123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139 |
- /*
- * md ast - pluggable markdown parser
- */
- const syntax = {
- bold: {
- paired: true,
- recursive: true,
- startRegexp: /\*\*\S.*/,
- endRegexp: /\S\*\*\s/,
- content: {
- start: {
- point: 'start',
- offset: 2
- },
- end: {
- point: 'end',
- offset: 1
- }
- },
- begin: 0,
- forward: {
- point: 'endEnd', //start, startEnd, end, endEnd
- offset: -1
- }
- },
- bold2: {
- paired: true,
- recursive: true,
- startRegexp: /\s__\S.*/,
- endRegexp: /\S__\s/,
- content: {
- start: {
- point: 'start',
- offset: 3
- },
- end: {
- point: 'end',
- offset: 1
- }
- },
- begin: 1,
- forward: {
- point: 'endEnd', //start, startEnd, end, endEnd
- offset: -1
- }
- },
- italic: {
- paired: true,
- recursive: true,
- startRegexp: /\*\S.*/,
- endRegexp: /\S\*\s/,
- content: {
- start: {
- point: 'start',
- offset: 2
- },
- end: {
- point: 'end',
- offset: 1
- }
- },
- begin: 0,
- forward: {
- point: 'endEnd', //start, startEnd, end, endEnd
- offset: -1
- }
- },
- italic2: {
- paired: true,
- recursive: true,
- startRegexp: /\s_\S.*/,
- endRegexp: /\S_\s/,
- content: {
- start: {
- point: 'start',
- offset: 2
- },
- end: {
- point: 'end',
- offset: 1
- }
- },
- begin: 1,
- forward: {
- point: 'endEnd', //start, startEnd, end, endEnd
- offset: -1
- }
- },
- }
- function findNearest(md, mdTags){
- let nearest, nearestMatch = {index: Infinity};
- for (let [mdTag, {paired,
- startRegexp,
- rexexp}] of Object.entries(mdTags)) {
- let match = md.match(startRegexp || regexp)
- if (match && match.index < nearestMatch.index){
- nearestMatch = match
- nearest = mdTag
- }
- }
- return [nearest, nearestMatch]
- }
- function cutNode(md, match, tagName, {paired, recursive, startRegexp, endRegexp, content: {start, end}, begin, forward}){
- //if (paired){
- //md.match()
- //}
- }
- function buildAST(md, mdTags=syntax, tree=[], path=[]){
- const result = []
- while(md){
- const [nearest, nearestMatch] = findNearest(md, mdTags)
- if (nearest){
- const {begin} = mdTags[nearest]
- if (nearestMatch.index){
- result.push(md.slice(0, nearestMatch.index + begin))
- md = md.slice(nearestMatch.index)
- }
- else {
- console.log(nearestMatch)
- break //to avoid infinite loop, add cutNode here
- }
- }
- else {
- result.push(md)
- md = ''
- }
- }
- return result
- }
- console.log(buildAST("I just __love__ __bold text__. "))
|