Skip to content

Instantly share code, notes, and snippets.

@timoxley
Created June 20, 2014 03:29
Show Gist options
  • Select an option

  • Save timoxley/9a774655aef8689d3c74 to your computer and use it in GitHub Desktop.

Select an option

Save timoxley/9a774655aef8689d3c74 to your computer and use it in GitHub Desktop.
"non-destructive" injecting of file content into markdown files
[ 'markdown',
[ 'header', { level: 1 }, 'Test' ],
[ 'para',
'This is a ',
[ 'link',
{ href: 'test' },
'test' ] ],
[ 'header',
{ level: 3 },
'Examples' ],
[ 'para', 'An example:' ],
[ 'para',
[ 'inlinecode',
'js\nconsole.log(\'Hello\')\n' ],
'\n',
[ 'link',
{ href: 'example.js', title: '^' },
'example.js' ] ] ]
[ 'markdown',
[ 'header', { level: 1 }, 'Test' ],
[ 'para',
'This is a ',
[ 'link',
{ href: 'test' },
'test' ] ],
[ 'header',
{ level: 3 },
'Examples' ],
[ 'para', 'An example:' ],
[ 'para',
[ 'inlinecode', 'js\n' ],
'\n',
[ 'link',
{ href: 'example.js', title: '^' },
'example.js' ] ] ]
console.log('Hello')
"use strict"
var fs = require('fs')
var path = require('path')
var md = require('markdown').markdown
module.exports = function(file, options) {
var dirName = path.dirname(file)
options = options || {gfm: true}
var input = fs.readFileSync(file, 'utf8')
var ast = md.parse(input)
var injects = findInjects(ast)
injects.forEach(function(inject) {
var injectFile = inject.link[1].href
var ext = path.extname(injectFile).slice(1)
inject.code[1] = [
ext,
fs.readFileSync(path.resolve(dirName, injectFile), 'utf8')
].join('\n')
})
// ast is now modified but wtf do I do with it?
console.log(ast) // ???
}
function findInjects(node, links) {
links = links || []
if (!Array.isArray(node)) return links
var foundCode = null
node.forEach(function(node) {
if (!Array.isArray(node)) return
if (foundCode) {
if (node[0] === 'link') {
if (node[1].title && node[1].title[0] === '^') {
links.push({
code: foundCode,
link: node
})
}
}
foundCode = false
} else {
if (node[0] === 'inlinecode') foundCode = node
}
findInjects(node, links)
})
return links
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment