Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Process footnotes #101

Open
fauno opened this issue Feb 22, 2022 · 0 comments
Open

Process footnotes #101

fauno opened this issue Feb 22, 2022 · 0 comments

Comments

@fauno
Copy link

fauno commented Feb 22, 2022

I need to process footnotes and came up with this extension, if you think it could be a generic way to process footnotes, I'll be happy to open a PR.

# frozen_string_literal: true

require 'reverse_markdown'

# Sent as a patch to reverse_markdown
# https://github.com/xijo/reverse_markdown/issues/101
module ReverseMarkdown
  module Converters
    class Footnote < A
      def convert(node, state = {})
        # If the link has a circular reference, we need to check if it's
        # inside a paragraph or it's the first element of a paragraph or
        # list item.
        if node['id'] && node['href']&.start_with?('#')
          parent = node.parent

          # The link could be contained in a <sup>
          until %[p li].include?(parent.name) do
            parent = parent.parent

            # Don't go further than this
            break if parent.name == 'body'
          end

          first_child = parent.first_element_child

          # If it's the first link on the parent, it's the footnote
          # itself, otherwise it's the reference.
          if first_child == node || first_child.children.include?(node)
            "[^#{node['href'].tr('#', '')}]:"
          else
            "[^#{node['id']}]"
          end
        # Just process the link.
        else
          super
        end
      end
    end

    register :a, Footnote.new
  end
end

Edit: The footnote was pointing to it's id instead of the href for the reference. Also the markdown syntax was incorrect.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant