Skip to content

Instantly share code, notes, and snippets.

@csabahenk
Last active December 24, 2015 05:49
Show Gist options
  • Save csabahenk/6752999 to your computer and use it in GitHub Desktop.
Save csabahenk/6752999 to your computer and use it in GitHub Desktop.
Utility script for publishing Markdown Extra documents as Gist

While Gist's markdown flavor is a superset of basic Markdown, it's not exactly the same as Markdown Extra.

To publish documents written in Markdown Extra as Gist so that it looks good:

  1. Convert the document to basic Markdown with Pandoc:

$ pandoc -f markdown -t markdown_strict ```

  1. Run the resulting document through this script to emulate Markdown Extra features in a Gist compatible way.

Note:

  • the script relies on Pandoc's formatting conventions for dumbing down extra constructs to basic, so it can be expected to work only with Pandoc produced basic Markdown
  • the script relies on some particularities of Gist's way to generate HTML from Markdown, so the result can be expected to look good only on Gist
  • needless to say it's a hack, not tested thoroughly
#!/usr/bin/env ruby
# enhance (Pandoc-normalized) basic markdown
# to emulate markdown-extra
require 'ap'
SUP = %w[⁰ ¹ ² ³ ⁴ ⁵ ⁶ ⁷ ⁸ ⁹]
ma = []
doc = $<.read
# replace [<index>] type dead footnotes with
# superscripted back-and-forth links
doc.gsub!(/\[(\d+)\]/) { |m|
n = Integer $1
ma[n] ||= 0
ma[n] += 1
case ma[n]
when 1
%[<a name="fni-#{n}"/>[#{SUP[n]}](#fnb-#{n})]
when 2
%[<a name="fnb-#{n}"/>[^#{SUP[n]}](#fni-#{n})]
else
m
end
}
# generate toc with Gist-style section ids
if doc =~ /\[TOC\]/m
t = nil
ha = []
doc.each_line { |l|
if l =~ /^(#+)\s(.*)/
ha << [$1.size, $2]
elsif t
case l
when /^---/
ha << [2, t]
when /^===/
ha << [1, t]
end
end
t = l.strip
}
doc.gsub! "[TOC]", ha.map { |d,t| "#{" " * (d-1)} - [#{t}](##{t.downcase.gsub(/[^a-zA-Z ]/, "").gsub(" ", "-")})\n" }.join
end
# hack to fix some Pandoc-Gist incompatibility
# XXX this is pretty narrow this way, I wonder if it could be gerenalized
doc.gsub!(/\(\*([^*]+)\*\)/) { "( *#{$1.gsub "\\", ""}* )" }
$> << doc
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment