Skip to content

Instantly share code, notes, and snippets.

Last active October 19, 2018 22:25
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Demonstrate how to extract and run code blocks from ** files.
% -x >
% python
hello world!
% -x | python -s
hello world!
#!/usr/bin/env coffee
help = '''
marko [options] FILES
-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')
print = console.log
print help if
head = '''
<!DOCTYPE html>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
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 and /coffee/.test file
coffee.eval codeFrom source
else if argv.extract
print codeFrom source
print head, marked source


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: -x >

To extract and run: -x | python -s

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