block by joyrexus 5174134

Convert your literate script to a code-fenced variant.

Fence

Note: see the fence repo for enhanced npm-packaged version of this script.


Convert your literate script to a GH-flavored code-fenced variant.

Handy if you want to have your code blocks highlighted when posting your literate script as a Gist or as a README file for your repo.

Example usage:

fence demo.python.md > demo.md
fence demo.coffee.md > demo.md
fence demo.litcoffee > demo.md

cat demo.python.md | fence --lang python > demo.md
cat demo.coffee.md | fence --lang coffee > demo.md

HT to Mr. Ashkenas, this is but a tweak of journo’s Cakefile.

Source

fs = require 'fs'
argv = require('optimist')
        .alias('l', 'lang')
        .describe('l', 'Language tag for fences')
        .argv

# Get language from filename's extension
getLang = (file) ->   
  return 'coffeescript' if /\.(litcoffee|coffee\.md)$/.test file
  ext = file.match /(\.(\w+))?\.(md)/
  return if ext?[1] then ext[2] else ''

# Factory method returning a fence filter for specified language
makeFencer = (lang='') ->
  (data) ->
    text = data.toString()
    indented = /\n\n    ([\s\S]*?)\n\n(?!    )/mg
    asFenced = (match, code) ->
      dedented = code.replace(/^    /mg, '')
      "\n\n```#{lang}\n#{dedented}\n```\n"
    console.log text.replace indented, asFenced

if argv._.length
  for file in argv._
    lang = argv.lang or getLang file
    fence = makeFencer lang
    source = fs.readFileSync(file)
    fence source
else
  fence = makeFencer argv.lang
  process.stdin.on 'data', fence
  process.stdin.resume()

fence.coffee