43 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Lua
		
	
	
	
	
	
			
		
		
	
	
			43 lines
		
	
	
		
			1.3 KiB
		
	
	
	
		
			Lua
		
	
	
	
	
	
| -- custom-toc.lua
 | ||
| -- This filter builds a custom TOC without images in the link text,
 | ||
| -- leaving the actual header content (with images) untouched.
 | ||
| 
 | ||
| -- Helper function: remove all image inlines from a list of inlines.
 | ||
| local function remove_images(inlines)
 | ||
|   local result = {}
 | ||
|   for _, item in ipairs(inlines) do
 | ||
|     if item.t ~= "Image" then
 | ||
|       table.insert(result, item)
 | ||
|     end
 | ||
|   end
 | ||
|   return result
 | ||
| end
 | ||
| 
 | ||
| -- Build a bullet list representing the table of contents.
 | ||
| local function build_toc(doc)
 | ||
|   local toc_items = {}
 | ||
|   for _, block in ipairs(doc.blocks) do
 | ||
|     if block.t == "Header" then
 | ||
|       -- Remove images from the header content to use for the TOC.
 | ||
|       local clean_inlines = remove_images(block.content)
 | ||
|       local header_text = pandoc.utils.stringify(clean_inlines)
 | ||
|       if header_text ~= "" then
 | ||
|         -- Create a link using the cleaned inlines and the header’s identifier.
 | ||
|         local link = pandoc.Link(clean_inlines, "#" .. block.identifier)
 | ||
|         table.insert(toc_items, { link })
 | ||
|       end
 | ||
|     end
 | ||
|   end
 | ||
|   return pandoc.BulletList(toc_items)
 | ||
| end
 | ||
| 
 | ||
| -- The Pandoc function runs after the document is fully constructed.
 | ||
| function Pandoc(doc)
 | ||
|   -- Build the custom TOC.
 | ||
|   local toc = build_toc(doc)
 | ||
|   -- Insert the TOC at the very beginning of the document.
 | ||
|   table.insert(doc.blocks, 1, toc)
 | ||
|   return doc
 | ||
| end
 | ||
| 
 |