Created
October 29, 2013 17:32
-
-
Save ttscoff/7219134 to your computer and use it in GitHub Desktop.
Lazy footnotes for Markdown, based on TidBits lazy link style
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# encoding: utf-8 | |
=begin | |
http://marked2app.com | |
Marked 2 preprocessor - "Lazy" footnotes. | |
Allows use of `[^]` or `†` footnote references | |
where the next [^]: or †: note defines the text of the footnote. | |
† - Option-T | |
^ - Shift-6 | |
Footnotes are given random prefixes to avoid duplication of ids within | |
a page. | |
Example: | |
Lorem ipsum dolor sit amet[^], consectetur adipisicing elit, sed do | |
eiusmod tempor† incididunt ut labore et dolore magna aliqua. Ut enim | |
ad minim veniam, quis nostrud exercitation[^] ullamco laboris nisi ut | |
aliquip ex ea commodo consequat. | |
[^]: This footnote will replace the first `[^]` found in the text. | |
†: This one will replace the first `†`. The syntaxes are auto-detected | |
and interchangeable. | |
[^]: This one replaces the second instance. | |
Inspired by [tidbits][^] and Carl Johnson† | |
[^]: http://tidbits.com | |
†: http://blog.carlsensei.com/ | |
=end | |
# Marked sends the Markdown text to STDIN when calling the script. | |
if RUBY_VERSION.to_f > 1.8 | |
input = STDIN.read.force_encoding('UTF-8') | |
else | |
input = STDIN.read | |
end | |
# random prefix and footnote counter | |
rand = rand(100000) + 100000 | |
counter = 0 | |
def replace_caret(input, prefix, counter) | |
input.sub(/(\[)\^(\].*?\[)\^\]:/m) { | |
%Q{#{$1}^fn#{prefix}-#{counter.to_s}#{$2}^fn#{prefix}-#{counter.to_s}]:} | |
} | |
end | |
def replace_cross(input, prefix, counter) | |
input.sub(/([^†]+)†(.*?)†:/m) { | |
%Q{#{$1}[^fn#{prefix}-#{counter.to_s}]#{$2}[^fn#{prefix}-#{counter.to_s}]:} | |
} | |
end | |
while input =~ /(\[\^\].*?\[\^\]:|†.*?†:)/m | |
idx_caret = input.index(/\[\^\].*?\[\^\]:/m) || false | |
idx_cross = input.index(/†.*?†:/m) || false | |
break if !idx_caret && !idx_cross | |
if ((idx_caret && idx_cross && idx_caret < idx_cross) || (idx_caret && !idx_cross)) | |
input = replace_caret(input, rand, counter += 1) | |
elsif (idx_cross) | |
input = replace_cross(input, rand, counter += 1) | |
end | |
end | |
print input |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment