Created
November 21, 2023 09:29
-
-
Save coderofsalvation/22069784c8c2f18c43476b146caf18f5 to your computer and use it in GitHub Desktop.
visual-meta / bibtex parser (incl. sections & multiplex/demultiplex of text/metadata)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var bibtex = { | |
decode: (str) => { | |
// bibtex: ↓@ ↓<tag|tag{phrase,|{ruler}> ↓property ↓end | |
let pat = [ /@/, /^\S+[,{}]/, /},/, /}/ ] | |
let tags = [], text='', i=0, prop='' | |
let lines = str.replace(/\r?\n/g,'\n').split(/\n/) | |
for( let i = 0; i < lines.length && !String(lines[i]).match( /^@/ ); i++ ) | |
text += lines[i]+'\n' | |
str = lines.join('\n').substr( text.length ) | |
str.split( pat[0] ).map( (t) => { | |
try{ | |
let v = {} | |
if( !(t = t.trim()) ) return | |
if( tag = t.match( pat[1] ) ) tag = tag[0] | |
if( tag.match( /^{.*}$/ ) ) return tags.push({ruler:tag}) | |
if( tag.match( /}$/ ) ) return tags.push({k: tag.replace(/}$/,''), v: {}}) | |
t = t.substr( tag.length ) | |
t.split( pat[2] ) | |
.map( kv => { | |
if( !(kv = kv.trim()) || kv == "}" ) return | |
v[ kv.match(/\s?(\S+)\s?=/)[1] ] = kv.substr( kv.indexOf("{")+1 ) | |
}) | |
tags.push( { k:tag, v } ) | |
}catch(e){ console.error(e) } | |
}) | |
return {text, tags} | |
}, | |
encode: (text,tags) => { | |
let str = text+"\n" | |
for( let i in tags ){ | |
let item = tags[i] | |
if( item.ruler ){ | |
str += `@${item.ruler}\n` | |
continue; | |
} | |
str += `@${item.k}\n` | |
for( let j in item.v ) str += ` ${j} = {${item.v[j]}}\n` | |
str += `}\n` | |
} | |
return str | |
} | |
} | |
str = ` | |
hello world | |
Lorem ipsum dolor sit amet | |
@{some-section} | |
@flap{ | |
asdf = {23423} | |
}` | |
var {tags,text} = bibtex.decode(str) // demultiplex text & bibtex | |
tags.find( (t) => t.k == 'flap{' ).v.asdf = 1 // edit tag | |
tags.push({ k:'bar{', v:{abc:123} }) // add tag | |
console.log( bibtex.encode(text,tags) ) // multiplex text & bibtex back together | |
console.dir({tags,text}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment