pandoc: How to link to a section in another markdown file?
Asked Answered
C

2

6

I would like to create two markdown files with links between their sections. The challenge here it's that I want the files to work correctly whether I ask pandic to concatenate them to a single HTML file, or to separate HTML files. The trouble is that in the latter case the link needs to know there name of the other HTML file in order to work properly.

It's there some way for pandoc to manage this without creating distinct versions of the markdown input?

Cardiograph answered 9/1, 2018 at 14:8 Comment(0)
C
7

The following uses Lua filters to fix your links. It assumes that links are written by prefixing them with the file in which the link is defined, for example [see here](some-other-file.md#topic). Some editors make it simple to switch to the respective file, so this can be an additional advantage.

When converting to multiple HTML files, all we need to do is replace the .md file extension in these links with .html.

-- fix-links-multiple-files.lua
function Link (link)
  link.target = link.target:gsub('(.+)%.md%#(.+)', '%1.html#%2')
  return link
end

Run it with

pandoc --lua-filter fix-links-multiple-files.lua file-1.md -o file-1.html

In the case of a single file, we can just drop the file part of the link:

-- fix-links-single-file.lua
function Link (link)
  link.target = link.target:gsub('.+%.md%#(.+)', '#%1')
  return link
end

Run with

pandoc --lua-filter fix-links-single-file.lua *.md -o outfile.html
Cluff answered 9/1, 2018 at 15:57 Comment(1)
this worked for me if the link does not contain any spaces. is there something special when spaces are involved?Ecker
S
0

You could use Lua filters to fix the links.

To replace the .md with an .html we use the gsub command from lua which uses pattern matching and replacement.

The pattern to match against is as follows: (.+)%.md(.*). This provides the option to either have #Topic attached or not. For example, if you don't just concatenate, but rather use multiple files.
For single file just don't input the name of the document in the markdown.

The Lua for multiple files looks as follows:

-- fix-links-multiple-files.lua
function Link (link)
  link.target = link.target:gsub('(.+)%.md%(.*)', '%1.html%2')
  return link
end

Run it with

pandoc --lua-filter fix-links-multiple-files.lua file-1.md -o file-1.html

In the case of a single file, as stated above, we can just drop the file part of the link:

-- fix-links-single-file.lua
function Link (link)
  link.target = link.target:gsub('.+%.md%#(.+)', '#%1')
  return link
end

Run with

pandoc --lua-filter fix-links-single-file.lua *.md -o outfile.html

Thank to @tarleb for the answer before, it was really helpful

Seizing answered 2/1, 2024 at 14:55 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.