/* * 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__. "))