Skip to content

Instantly share code, notes, and snippets.

@bcdavasconcelos
Created September 27, 2021 00:15
Show Gist options
  • Save bcdavasconcelos/e46d9bbd0b2a1bb1ef3ad18fc57c0bed to your computer and use it in GitHub Desktop.
Save bcdavasconcelos/e46d9bbd0b2a1bb1ef3ad18fc57c0bed to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# frozen_string_literal: false
# bcdav 2021
# inspired by https://github.com/ltrgoddard/inliner
Encoding.default_external = Encoding::UTF_8
class String
def inline_mmd
text = self
counter = 0
pandoc_mode = false
loop do
counter += 1
cite = "[^#{counter}]"
ref = "[^#{counter}]:"
ref_start = text.index(ref)
break if ref_start.nil?
next_ref = "[^#{counter + 1}]:"
ref_end = text.index(next_ref).nil? ? -1 : text.index(next_ref) - 2
offset = counter.to_s.length + 5
note = pandoc_mode ? "^[#{text[ref_start + offset..ref_end].strip}]" : "[^#{text[ref_start + offset..ref_end].strip}]"
text.gsub!(cite, note)
end
if counter >= 1
text = pandoc_mode ? text.gsub(/\n\s*\^\[/, "\n^[") : text.gsub(/\n\s*\[\^/, "\n[^")
cut_point = pandoc_mode ? text.index("\n^") : text.index("\n[^")
text = text[0, cut_point]
# puts "#{counter -= 1} notes replaced."
end
puts text
end
def inline_pandoc
text = self
counter = 0
pandoc_mode = true
loop do
counter += 1
cite = "[^#{counter}]"
ref = "[^#{counter}]:"
ref_start = text.index(ref)
break if ref_start.nil?
next_ref = "[^#{counter + 1}]:"
ref_end = text.index(next_ref).nil? ? -1 : text.index(next_ref) - 2
offset = counter.to_s.length + 5
note = pandoc_mode ? "^[#{text[ref_start + offset..ref_end].strip}]" : "[^#{text[ref_start + offset..ref_end].strip}]"
text.gsub!(cite, note)
end
if counter >= 1
text = pandoc_mode ? text.gsub(/\n\s*\^\[/, "\n^[") : text.gsub(/\n\s*\[\^/, "\n[^")
cut_point = pandoc_mode ? text.index("\n^") : text.index("\n[^")
text = text[0, cut_point]
# puts "#{counter -= 1} notes replaced."
end
puts text
end
end
str = <<EOS
Lorem ipsum dolor sit amet[^1], 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.
[^1]: Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
EOS
puts str.inline_pandoc
# puts str.inline_mmd
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment