Last active
January 10, 2024 20:00
-
-
Save dk949/b1f07b81d30c55f327609d75de228f69 to your computer and use it in GitHub Desktop.
Pandoc numbered section links
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
--[[ | |
Based on [this](https://stackoverflow.com/a/54130482) stack overfloaw answer which no longer works | |
License: CC BY-SA 4.0 | |
Usage: | |
See Section [](#some-section-name) | |
# Some section name | |
text text text | |
--------- | |
`[](#some-section-name)` will be replaced by the number of the section. | |
`numbersections` is not required, but the links will not make much sense without it. | |
]] | |
local make_sections = (require 'pandoc').utils.make_sections | |
local section_numbers = {} | |
local function populate_section_numbers(doc) | |
local function populate(elements) | |
for _, elem in pairs(elements) do | |
if elem.t == "Div" then | |
section_numbers["#" .. elem.identifier] = elem.attributes.number | |
populate(elem.content) | |
end | |
end | |
end | |
populate(make_sections(true, nil, doc.blocks)) | |
end | |
local function resolve_section_ref(link) | |
if #link.content > 0 or link.target:sub(1, 1) ~= '#' then | |
return nil | |
end | |
local num = section_numbers[link.target] | |
local section_number = nil | |
if not num then | |
section_number = pandoc.Str("??") | |
warn("Could not identify section number for targer `" .. | |
link.target .. "`. Possibly trying to link unnumbered section") | |
else | |
section_number = pandoc.Str(num) | |
end | |
return pandoc.Link(section_number, link.target, link.title, link.attr) | |
end | |
return { | |
{ Pandoc = populate_section_numbers }, | |
{ Link = resolve_section_ref } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment