summaryrefslogtreecommitdiff
path: root/docs/modules/extend/examples/advanced-inline-pagenum-macro.rb
blob: 1713319ee2986c1b78706e5a48703d4e912ecefe (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Asciidoctor::Extensions.register do
  inline_macro :pagenum do
    format :short
    parse_content_as :text
    process do |parent, scope|
      doc = parent.document
      if scope == 'section'
        if doc.nested?
          inner_doc = doc
          parent = (doc = doc.parent_document).find_by(context: :table_cell) do |it|
            it.style == :asciidoc && it.inner_document == inner_doc
          end.first
        end
        section = (closest parent, :section) || doc
        physical_pagenum = section.attr 'pdf-page-start'
      else
        physical_pagenum = doc.converter.page_number
      end
      create_inline parent, :quoted, %(#{physical_pagenum + 1 - (start_page_number doc)})
    end

    def closest node, context
      node.context == context ? node : ((parent = node.parent) && (closest parent, context))
    end

    def start_page_number doc
      doc.converter.index.start_page_number
    end
  end
end