Wow, thanks for that Albert! I wasn't aware that it was your code on stackoverflow. I yet need to understand what it does exactly but I see the key thing is obviously to look at div.content[1] in order to get the link title.

On Wednesday, December 22, 2021 at 3:53:21 PM UTC+1 Albert Krewinkel wrote:
be...-GbY3e145aRm8w6eVIr4Tmg@public.gmane.org <be...-GbY3e145aRm8w6eVIr4Tmg@public.gmane.org> writes:

> I am trying to make a Lua filter that will replace the normal link text in
> internal links with section numbers. I want to use internal links in my
> markdown document like this:
>
> See the [Quick introduction].
>
> So, the links are given by the full title of the respective section they
> refer to.

Here's a quick rewrite of my old code that should do it.
If there are internal links that should not be modified, simply add a
title or a class to that link, and the filter will leave it alone.

``` lua
local sections = {}

function populate_section_numbers (doc)
function populate (blocks)
for _, div in pairs(blocks) do
if div.t == 'Div' and div.attributes.number then
local header = div.content[1]
if header and header.t == 'Header' then
sections['#' .. div.attr.identifier] = {
number = div.attributes.number,
}
populate(div.content)
end
end
end
end
populate(pandoc.utils.make_sections(true, nil, doc.blocks))
end

function resolve_section_ref (link)
-- don't edit non-internal links or those with a title or a class.
if link.target:sub(1, 1) ~= '#' or #link.classes > 0 or #link.title > 0 then
return nil
end
local section = sections[link.target]
if section then
link.content = {pandoc.Str(section.number .. '\u{A0}')} .. link.content
return link
end
end

return {
{Pandoc = populate_section_numbers},
{Link = resolve_section_ref}
}
```


--
Albert Krewinkel
GPG: 8eed e3e2 e8c5 6f18 81fe e836 388d c0b2 1f63 1124

--
You received this message because you are subscribed to the Google Groups "pandoc-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email to pandoc-discuss+unsubscribe-/JYPxA39Uh5TLH3MbocFFw@public.gmane.org.
To view this discussion on the web visit https://groups.google.com/d/msgid/pandoc-discuss/d7ed1a43-0312-408d-a08a-94d1988837een%40googlegroups.com.