Skip to content

Instantly share code, notes, and snippets.

@joyrexus
Last active Oct 19, 2018
Embed
What would you like to do?
Demonstrate how to extract and run code blocks from *.lang.md* files.
% marko.coffee -x try.python.md > try.py
% python try.py
hello world!
yes!
% marko.coffee -x try.python.md | python -s
hello world!
yes!
#!/usr/bin/env coffee
help = '''
marko [options] FILES
options:
-h, --help show help
-r, --run run code blocks
-x, --extract extract code blocks
'''
fs = require 'fs'
coffee = require 'coffee-script'
marked = require 'marked'
argv = require('optimist')
.boolean(['h', 'r', 'x'])
.alias('h', 'help')
.alias('r', 'run')
.alias('x', 'extract')
.argv
print = console.log
print help if argv.help
head = '''
<!DOCTYPE html>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<body>
'''
codeFrom = (source) ->
(t.text for t in marked.lexer(source) when t.type == 'code').join "\n"
for file in argv._ when file.match /\.(litcoffee|md)/i
source = fs.readFileSync file, 'utf8'
if argv.run and /coffee/.test file
coffee.eval codeFrom source
else if argv.extract
print codeFrom source
else
print head, marked source

Demo

Note that Marked's lexer makes it easy to extract code blocks from markdown files:

# codeFrom = (source) ->
#  (t.text for t in marked.lexer(source) when t.type == 'code').join "\n"

Hence, it's not hard to use this to extract and run, say, python code blocks.

print "hello world!"

A bit more.

from collections import defaultdict as dd

def autodict(): return dd(autodict)

d = autodict()
d['an']['arbitrarily']['deep']['dictionary'] = "yes!"
print d['an']['arbitrarily']['deep']['dictionary']

To dump to a file: marko.coffee -x try.python.md > try.py

To extract and run: marko.coffee -x try.python.md | python -s

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment