Add relative file links extension (#897) (#968)

Adds the opt-in UseRelativeFileLinks() extension, which rewrites relative links to .md/.markdown files into links to the generated pages through HtmlRenderer.LinkRewriter, keeping the query and fragment. Also fixes email autolinks to pass mailto: through WriteEscapeUrl, so BaseUrl no longer prefixes them and a LinkRewriter sees the full mailto: URL.
This commit is contained in:
Stefan Greve
2026-10-23 21:09:54 +02:00
committed by GitHub
parent 96a7f45ada
commit 13b2d9a53b
17 changed files with 782 additions and 6 deletions

View File

@@ -53,6 +53,7 @@ You can **try Markdig online** and compare it to other implementations on [babel
- [**YAML Front Matter**](src/Markdig.Tests/Specs/YamlSpecs.md) to parse without evaluating the front matter and to discard it from the HTML output (typically used for previewing without the front matter in MarkdownEditor)
- [**JIRA links**](src/Markdig.Tests/Specs/JiraLinks.md) to automatically generate links for JIRA project references (Thanks to @clarkd: https://github.com/clarkd/MarkdigJiraLinker)
- [**CJK-friendly Emphasis**](src/Markdig.Tests/Specs/CJKFriendlyEmphasis.md) to mitigate a CommonMark specification issue in CJK languages (Thanks to @tats-u: https://github.com/tats-u/markdown-cjk-friendly)
- [**Relative file links**](https://xoofx.github.io/markdig/docs/extensions/relative-file-links/) to rewrite links to Markdown files, such as `usage.md#preview`, into links to the generated pages, such as `usage.html#preview`
- Starting with Markdig version `0.20.0+`, Markdig is compatible only with `NETStandard 2.0`, `NETStandard 2.1`, `NETCoreApp 2.1` and `NETCoreApp 3.1`.
If you are looking for support for an old .NET Framework 3.5 or 4.0, you can download Markdig `0.18.3`.

View File

@@ -19,4 +19,5 @@ doc:
- {path: media-links.md, title: "Media links"}
- {path: list-extras.md, title: "List extras"}
- {path: yaml-frontmatter.md, title: "YAML front matter"}
- {path: relative-file-links.md, title: "Relative file links"}
- {path: other.md, title: "Other extensions"}

View File

@@ -70,6 +70,7 @@ var pipeline = new MarkdownPipelineBuilder()
| [Pragma lines](other.md) | `.UsePragmaLines()` | Line number pragma IDs |
| [Non-ASCII no escape](other.md) | `.UseNonAsciiNoEscape()` | Disable URI escaping for non-ASCII |
| [CJK friendly emphasis](cjk-friendly-emphasis.md) | `.UseCjkFriendlyEmphasis()` | Improved emphasis delimiter rules for CJK text |
| [Relative file links](relative-file-links.md) | `.UseRelativeFileLinks()` | Rewrite links to `.md` files into links to `.html` pages |
## Extension ordering

View File

@@ -0,0 +1,87 @@
---
title: Relative file links
---
# Relative file links
Enable with `.UseRelativeFileLinks()` (not included in `UseAdvancedExtensions()`).
This extension rewrites links to Markdown files into links to the HTML pages generated from them. A set of Markdown files that link to each other, such as a `docs` folder, then works both when browsed on GitHub and as a generated site.
```csharp
var pipeline = new MarkdownPipelineBuilder()
.UseRelativeFileLinks()
.Build();
var html = Markdown.ToHtml("See the [usage guide](usage.md#preview).", pipeline);
// <p>See the <a href="usage.html#preview">usage guide</a>.</p>
```
## Rules
A link is rewritten when the path of its target ends with `.md` or `.markdown`, compared case-insensitively. That extension is replaced with `.html`, and the query and the fragment are kept. Only the target changes: the link text and the title stay as written. Links with a scheme, such as `https:` or `mailto:`, and protocol-relative links (`//host/path`) point outside the site and are left unchanged.
{.table}
| Markdown | Rendered `href` |
|---|---|
| `[a](usage.md)` | `usage.html` |
| `[a](usage.md?v=1#preview)` | `usage.html?v=1#preview` |
| `[a](../guide/install.md)` | `../guide/install.html` |
| `[a](/docs/README.MD)` | `/docs/README.html` |
| `[a](https://github.com/xoofx/markdig/blob/main/readme.md)` | unchanged |
| `[a](//cdn.example.com/usage.md)` | unchanged |
| `<info@example.md>` | unchanged (`mailto:info@example.md`) |
| `[a](notes.html#usage.md)` | unchanged |
| `[a](usage.mdx)` | unchanged |
## Options
`UseRelativeFileLinks` accepts a `RelativeFileLinkOptions` object:
```csharp
using Markdig.Extensions.RelativeFileLinks;
var options = new RelativeFileLinkOptions
{
TargetExtension = "/" // usage.md#preview becomes usage/#preview
};
options.SourceExtensions.Remove(".markdown"); // rewrite .md links only
var pipeline = new MarkdownPipelineBuilder()
.UseRelativeFileLinks(options)
.Build();
```
{.table}
| Option | Default | Description |
|---|---|---|
| `SourceExtensions` | `.md`, `.markdown` | The file extensions to rewrite, each starting with `.`. The list starts with the defaults; clear it to replace them. |
| `TargetExtension` | `.html` | The replacement, inserted verbatim: `""` produces extensionless links and `/` directory links. |
The extension copies the options when it is created, so changing them afterwards has no effect.
## Base URL and link rewriters
The extension sets `HtmlRenderer.LinkRewriter`, so it works together with the other URL settings of the renderer:
- `HtmlRenderer.BaseUrl` resolves relative links before the extension sees them. When a base URL is set, the extension therefore rewrites every absolute link with the same scheme, host and port as the base URL, including links that the Markdown source spells out as absolute URLs.
- A `LinkRewriter` assigned to the renderer before the pipeline sets it up runs after the extension, so it receives `usage.html` rather than `usage.md`. A `LinkRewriter` assigned afterwards replaces the extension.
```csharp
using Markdig.Renderers;
var writer = new StringWriter();
var renderer = new HtmlRenderer(writer) { BaseUrl = new Uri("https://example.com/docs/") };
pipeline.Setup(renderer);
renderer.Render(Markdown.Parse("[Install](../guide/install.md)", pipeline));
// <p><a href="https://example.com/guide/install.html">Install</a></p>
```
`BaseUrl` also resolves fragment-only links such as `#install`. Set it to the URL of the rendered page rather than to its folder if links within the page must stay on the page.
## Limitations
- Links written as raw HTML, such as `<a href="usage.md">`, are not rewritten.
- Only the file extension changes: `index.md` becomes `index.html`, not a directory URL. For a mapping that depends on the layout of your site, use your own `HtmlRenderer.LinkRewriter` instead.
- Only HTML output is affected. The parsed `MarkdownDocument` and the output of `Markdown.Normalize` keep the original link targets.

View File

@@ -139,7 +139,7 @@ var pipeline = new MarkdownPipelineBuilder()
.Build();
```
Available extension tokens: `common`, `advanced`, `alerts`, `pipetables`, `gfm-pipetables`, `emphasisextras`, `listextras`, `hardlinebreak`, `footnotes`, `footers`, `citations`, `attributes`, `gridtables`, `abbreviations`, `emojis`, `definitionlists`, `customcontainers`, `figures`, `mathematics`, `bootstrap`, `medialinks`, `smartypants`, `autoidentifiers`, `tasklists`, `diagrams`, `nofollowlinks`, `noopenerlinks`, `noreferrerlinks`, `nohtml`, `yaml`, `nonascii-noescape`, `autolinks`, `globalization`, `cjk-friendly-emphasis`.
Available extension tokens: `common`, `advanced`, `alerts`, `pipetables`, `gfm-pipetables`, `emphasisextras`, `listextras`, `hardlinebreak`, `footnotes`, `footers`, `citations`, `attributes`, `gridtables`, `abbreviations`, `emojis`, `definitionlists`, `customcontainers`, `figures`, `mathematics`, `bootstrap`, `medialinks`, `smartypants`, `autoidentifiers`, `tasklists`, `diagrams`, `nofollowlinks`, `noopenerlinks`, `noreferrerlinks`, `nohtml`, `yaml`, `nonascii-noescape`, `autolinks`, `globalization`, `cjk-friendly-emphasis`, `relativefilelinks`.
## The MarkdownParserContext

View File

@@ -0,0 +1,175 @@
// --------------------------------
// Relative File Links
// --------------------------------
using System;
using NUnit.Framework;
namespace Markdig.Tests.Specs.RelativeFileLinks
{
[TestFixture]
public class TestExtensionsRelativeFileLinks
{
// # Extensions
//
// This section describes the different extensions supported:
//
// ## Relative File Links
//
// The relative file link extension rewrites links to Markdown files into links to the HTML pages generated from them, so that the same files can be browsed on GitHub and as a generated site. It is enabled with `UseRelativeFileLinks()`.
//
// A link whose path ends with `.md` or `.markdown`, compared case-insensitively, has that extension replaced with `.html`:
[Test]
public void ExtensionsRelativeFileLinks_Example001()
{
// Example 1
// Section: Extensions / Relative File Links
//
// The following Markdown:
// [Usage](usage.md)
//
// [Read me](README.MD)
//
// [Guide](guide.markdown)
//
// Should be rendered as:
// <p><a href="usage.html">Usage</a></p>
// <p><a href="README.html">Read me</a></p>
// <p><a href="guide.html">Guide</a></p>
TestParser.TestSpec("[Usage](usage.md)\n\n[Read me](README.MD)\n\n[Guide](guide.markdown)", "<p><a href=\"usage.html\">Usage</a></p>\n<p><a href=\"README.html\">Read me</a></p>\n<p><a href=\"guide.html\">Guide</a></p>", "relativefilelinks|advanced+relativefilelinks", context: "Example 1\nSection Extensions / Relative File Links\n");
}
// The query and the fragment are kept:
[Test]
public void ExtensionsRelativeFileLinks_Example002()
{
// Example 2
// Section: Extensions / Relative File Links
//
// The following Markdown:
// [Preview](usage.md#preview)
//
// [Version](usage.md?v=1#preview)
//
// Should be rendered as:
// <p><a href="usage.html#preview">Preview</a></p>
// <p><a href="usage.html?v=1#preview">Version</a></p>
TestParser.TestSpec("[Preview](usage.md#preview)\n\n[Version](usage.md?v=1#preview)", "<p><a href=\"usage.html#preview\">Preview</a></p>\n<p><a href=\"usage.html?v=1#preview\">Version</a></p>", "relativefilelinks|advanced+relativefilelinks", context: "Example 2\nSection Extensions / Relative File Links\n");
}
// Relative and root-relative paths are rewritten, and so are the targets of reference links:
[Test]
public void ExtensionsRelativeFileLinks_Example003()
{
// Example 3
// Section: Extensions / Relative File Links
//
// The following Markdown:
// [Usage](./usage.md)
//
// [Install](../guide/install.md)
//
// [Docs](/docs/usage.md)
//
// [Linux][linux]
//
// [linux]: guide/install.md#linux
//
// Should be rendered as:
// <p><a href="./usage.html">Usage</a></p>
// <p><a href="../guide/install.html">Install</a></p>
// <p><a href="/docs/usage.html">Docs</a></p>
// <p><a href="guide/install.html#linux">Linux</a></p>
TestParser.TestSpec("[Usage](./usage.md)\n\n[Install](../guide/install.md)\n\n[Docs](/docs/usage.md)\n\n[Linux][linux]\n\n[linux]: guide/install.md#linux", "<p><a href=\"./usage.html\">Usage</a></p>\n<p><a href=\"../guide/install.html\">Install</a></p>\n<p><a href=\"/docs/usage.html\">Docs</a></p>\n<p><a href=\"guide/install.html#linux\">Linux</a></p>", "relativefilelinks|advanced+relativefilelinks", context: "Example 3\nSection Extensions / Relative File Links\n");
}
// Only the link target changes. The link text and the title stay as written, and the target is escaped as usual:
[Test]
public void ExtensionsRelativeFileLinks_Example004()
{
// Example 4
// Section: Extensions / Relative File Links
//
// The following Markdown:
// [usage.md](<my usage.md> "usage.md")
//
// Should be rendered as:
// <p><a href="my%20usage.html" title="usage.md">usage.md</a></p>
TestParser.TestSpec("[usage.md](<my usage.md> \"usage.md\")", "<p><a href=\"my%20usage.html\" title=\"usage.md\">usage.md</a></p>", "relativefilelinks|advanced+relativefilelinks", context: "Example 4\nSection Extensions / Relative File Links\n");
}
// Links with a scheme and protocol-relative links point outside the site and are left unchanged, email autolinks included:
[Test]
public void ExtensionsRelativeFileLinks_Example005()
{
// Example 5
// Section: Extensions / Relative File Links
//
// The following Markdown:
// [Source](https://github.com/xoofx/markdig/blob/main/readme.md)
//
// [CDN](//cdn.example.com/usage.md)
//
// [Mail](mailto:info@example.md)
//
// <info@example.md>
//
// Should be rendered as:
// <p><a href="https://github.com/xoofx/markdig/blob/main/readme.md">Source</a></p>
// <p><a href="//cdn.example.com/usage.md">CDN</a></p>
// <p><a href="mailto:info@example.md">Mail</a></p>
// <p><a href="mailto:info@example.md">info@example.md</a></p>
TestParser.TestSpec("[Source](https://github.com/xoofx/markdig/blob/main/readme.md)\n\n[CDN](//cdn.example.com/usage.md)\n\n[Mail](mailto:info@example.md)\n\n<info@example.md>", "<p><a href=\"https://github.com/xoofx/markdig/blob/main/readme.md\">Source</a></p>\n<p><a href=\"//cdn.example.com/usage.md\">CDN</a></p>\n<p><a href=\"mailto:info@example.md\">Mail</a></p>\n<p><a href=\"mailto:info@example.md\">info@example.md</a></p>", "relativefilelinks|advanced+relativefilelinks", context: "Example 5\nSection Extensions / Relative File Links\n");
}
// A link is left unchanged when its path does not end with a Markdown extension, even if the query or the fragment does:
[Test]
public void ExtensionsRelativeFileLinks_Example006()
{
// Example 6
// Section: Extensions / Relative File Links
//
// The following Markdown:
// [Notes](notes.html#usage.md)
//
// [Download](get.html?file=usage.md)
//
// [Anchor](#usage.md)
//
// [MDX](usage.mdx)
//
// [Folder](docs.md/)
//
// Should be rendered as:
// <p><a href="notes.html#usage.md">Notes</a></p>
// <p><a href="get.html?file=usage.md">Download</a></p>
// <p><a href="#usage.md">Anchor</a></p>
// <p><a href="usage.mdx">MDX</a></p>
// <p><a href="docs.md/">Folder</a></p>
TestParser.TestSpec("[Notes](notes.html#usage.md)\n\n[Download](get.html?file=usage.md)\n\n[Anchor](#usage.md)\n\n[MDX](usage.mdx)\n\n[Folder](docs.md/)", "<p><a href=\"notes.html#usage.md\">Notes</a></p>\n<p><a href=\"get.html?file=usage.md\">Download</a></p>\n<p><a href=\"#usage.md\">Anchor</a></p>\n<p><a href=\"usage.mdx\">MDX</a></p>\n<p><a href=\"docs.md/\">Folder</a></p>", "relativefilelinks|advanced+relativefilelinks", context: "Example 6\nSection Extensions / Relative File Links\n");
}
// Links written as raw HTML are not rewritten:
[Test]
public void ExtensionsRelativeFileLinks_Example007()
{
// Example 7
// Section: Extensions / Relative File Links
//
// The following Markdown:
// <a href="usage.md">Usage</a>
//
// Should be rendered as:
// <p><a href="usage.md">Usage</a></p>
TestParser.TestSpec("<a href=\"usage.md\">Usage</a>", "<p><a href=\"usage.md\">Usage</a></p>", "relativefilelinks|advanced+relativefilelinks", context: "Example 7\nSection Extensions / Relative File Links\n");
}
}
}

View File

@@ -0,0 +1,104 @@
# Extensions
This section describes the different extensions supported:
## Relative File Links
The relative file link extension rewrites links to Markdown files into links to the HTML pages generated from them, so that the same files can be browsed on GitHub and as a generated site. It is enabled with `UseRelativeFileLinks()`.
A link whose path ends with `.md` or `.markdown`, compared case-insensitively, has that extension replaced with `.html`:
```````````````````````````````` example
[Usage](usage.md)
[Read me](README.MD)
[Guide](guide.markdown)
.
<p><a href="usage.html">Usage</a></p>
<p><a href="README.html">Read me</a></p>
<p><a href="guide.html">Guide</a></p>
````````````````````````````````
The query and the fragment are kept:
```````````````````````````````` example
[Preview](usage.md#preview)
[Version](usage.md?v=1#preview)
.
<p><a href="usage.html#preview">Preview</a></p>
<p><a href="usage.html?v=1#preview">Version</a></p>
````````````````````````````````
Relative and root-relative paths are rewritten, and so are the targets of reference links:
```````````````````````````````` example
[Usage](./usage.md)
[Install](../guide/install.md)
[Docs](/docs/usage.md)
[Linux][linux]
[linux]: guide/install.md#linux
.
<p><a href="./usage.html">Usage</a></p>
<p><a href="../guide/install.html">Install</a></p>
<p><a href="/docs/usage.html">Docs</a></p>
<p><a href="guide/install.html#linux">Linux</a></p>
````````````````````````````````
Only the link target changes. The link text and the title stay as written, and the target is escaped as usual:
```````````````````````````````` example
[usage.md](<my usage.md> "usage.md")
.
<p><a href="my%20usage.html" title="usage.md">usage.md</a></p>
````````````````````````````````
Links with a scheme and protocol-relative links point outside the site and are left unchanged, email autolinks included:
```````````````````````````````` example
[Source](https://github.com/xoofx/markdig/blob/main/readme.md)
[CDN](//cdn.example.com/usage.md)
[Mail](mailto:info@example.md)
<info@example.md>
.
<p><a href="https://github.com/xoofx/markdig/blob/main/readme.md">Source</a></p>
<p><a href="//cdn.example.com/usage.md">CDN</a></p>
<p><a href="mailto:info@example.md">Mail</a></p>
<p><a href="mailto:info@example.md">info@example.md</a></p>
````````````````````````````````
A link is left unchanged when its path does not end with a Markdown extension, even if the query or the fragment does:
```````````````````````````````` example
[Notes](notes.html#usage.md)
[Download](get.html?file=usage.md)
[Anchor](#usage.md)
[MDX](usage.mdx)
[Folder](docs.md/)
.
<p><a href="notes.html#usage.md">Notes</a></p>
<p><a href="get.html?file=usage.md">Download</a></p>
<p><a href="#usage.md">Anchor</a></p>
<p><a href="usage.mdx">MDX</a></p>
<p><a href="docs.md/">Folder</a></p>
````````````````````````````````
Links written as raw HTML are not rewritten:
```````````````````````````````` example
<a href="usage.md">Usage</a>
.
<p><a href="usage.md">Usage</a></p>
````````````````````````````````

View File

@@ -32,6 +32,7 @@ You will find from the following links the supported extensions in markdig and t
- [**Diagrams**](DiagramsSpecs.md)
- [**YAML frontmatter**](YamlSpecs.md)
- [**JIRA links**](JiraLinks.md)
- [**Relative file links**](RelativeFileLinkSpecs.md)
- [**CJK-friendly Emphasis**](CJKFriendlyEmphasis.md)
> Notice that the links above are not yet the final documentation but are "specification" files used for testing the correctness of markdig for each extension

View File

@@ -22,6 +22,12 @@ public class TestLinkRewriter
TestSpec(null, "Image: ![alt text](/image.jpg)", "/image.jpg");
}
[Test]
public void RewritesEmailAutolinksWithMailtoScheme()
{
TestSpec(s => "x" + s, "Email: <info@example.com>", "xmailto:info@example.com");
}
public static void TestSpec(Func<string,string> linkRewriter, string markdown, string expectedLink)
{
var pipeline = new MarkdownPipelineBuilder().Build();
@@ -37,4 +43,4 @@ public class TestLinkRewriter
Assert.That(writer.ToString(), Contains.Substring("=\"" + expectedLink + "\""));
}
}
}

View File

@@ -0,0 +1,169 @@
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using Markdig.Extensions.RelativeFileLinks;
using Markdig.Renderers;
using Markdig.Syntax;
using Markdig.Syntax.Inlines;
namespace Markdig.Tests;
public class TestRelativeFileLinks
{
private static readonly MarkdownPipeline s_pipeline = new MarkdownPipelineBuilder().UseRelativeFileLinks().Build();
[TestCase("usage.md#preview", "https://example.com/docs/usage.html#preview")]
[TestCase("../api/usage.md", "https://example.com/api/usage.html")]
[TestCase("/root.md", "https://example.com/root.html")]
[TestCase("https://example.com/other.md", "https://example.com/other.html")]
[TestCase("//cdn.example.com/usage.md", "https://cdn.example.com/usage.md")]
[TestCase("https://github.com/xoofx/markdig/blob/main/readme.md", "https://github.com/xoofx/markdig/blob/main/readme.md")]
[TestCase("http://example.com/docs/usage.md", "http://example.com/docs/usage.md")]
[TestCase("https://example.com:8443/docs/usage.md", "https://example.com:8443/docs/usage.md")]
public void RewritesLinksWithTheOriginOfBaseUrl(string url, string expectedUrl)
{
string html = Render($"[a]({url})", renderer => renderer.BaseUrl = new Uri("https://example.com/docs/"));
Assert.AreEqual($"<p><a href=\"{expectedUrl}\">a</a></p>\n", html);
}
[TestCase("//cdn.example.com/usage.md")]
[TestCase("C:/docs/usage.md")]
[TestCase("notes:usage.md")]
[TestCase("usage.rmd")]
[TestCase("usage.md.txt")]
[TestCase("")]
public void LeavesOtherLinksUnchanged(string url)
{
Assert.AreEqual($"<p><a href=\"{url}\">a</a></p>\n", Markdown.ToHtml($"[a]({url})", s_pipeline));
}
[Test]
public void ReadsBaseUrlWhenRendering()
{
var writer = new StringWriter();
var renderer = new HtmlRenderer(writer);
s_pipeline.Setup(renderer);
renderer.BaseUrl = new Uri("https://example.com/docs/");
renderer.Render(Markdown.Parse("[a](usage.md)", s_pipeline));
writer.Flush();
Assert.AreEqual("<p><a href=\"https://example.com/docs/usage.html\">a</a></p>\n", writer.ToString());
}
[Test]
public void RunsBeforeExistingLinkRewriter()
{
string html = Render("[a](usage.md)", renderer => renderer.LinkRewriter = url => "https://cdn.example.com/" + url);
Assert.AreEqual("<p><a href=\"https://cdn.example.com/usage.html\">a</a></p>\n", html);
}
[Test]
public void DoesNotWrapLinkRewriterTwice()
{
var renderer = new HtmlRenderer(new StringWriter());
Markdown.Convert("[a](usage.md)", renderer, s_pipeline);
Func<string, string> rewriter = renderer.LinkRewriter;
Markdown.Convert("[b](usage.md)", renderer, s_pipeline);
Assert.That(renderer.LinkRewriter, Is.SameAs(rewriter));
}
[TestCase("", "usage#preview")]
[TestCase("/", "usage/#preview")]
[TestCase(".xhtml", "usage.xhtml#preview")]
public void ReplacesSourceExtensionWithTargetExtension(string targetExtension, string expectedUrl)
{
var pipeline = new MarkdownPipelineBuilder().UseRelativeFileLinks(new RelativeFileLinkOptions { TargetExtension = targetExtension }).Build();
Assert.AreEqual($"<p><a href=\"{expectedUrl}\">a</a></p>\n", Markdown.ToHtml("[a](usage.md#preview)", pipeline));
}
[Test]
public void RewritesOnlyConfiguredSourceExtensions()
{
var options = new RelativeFileLinkOptions();
options.SourceExtensions.Clear();
options.SourceExtensions.Add(".mdx");
var pipeline = new MarkdownPipelineBuilder().UseRelativeFileLinks(options).Build();
Assert.AreEqual("<p><a href=\"guide.html\">a</a> <a href=\"usage.md\">b</a></p>\n", Markdown.ToHtml("[a](guide.mdx) [b](usage.md)", pipeline));
}
[Test]
public void CopiesOptions()
{
var options = new RelativeFileLinkOptions();
var builder = new MarkdownPipelineBuilder().UseRelativeFileLinks(options);
options.SourceExtensions.Clear();
options.SourceExtensions.Add(".txt");
options.TargetExtension = ".htm";
Assert.AreEqual("<p><a href=\"usage.html\">a</a> <a href=\"notes.txt\">b</a></p>\n", Markdown.ToHtml("[a](usage.md) [b](notes.txt)", builder.Build()));
}
[Test]
public void LastUseRelativeFileLinksCallWins()
{
var options = new RelativeFileLinkOptions();
options.SourceExtensions.Clear();
options.SourceExtensions.Add(".txt");
var pipeline = new MarkdownPipelineBuilder().UseRelativeFileLinks(options).UseRelativeFileLinks().Build();
Assert.AreEqual("<p><a href=\"usage.html\">a</a> <a href=\"notes.txt\">b</a></p>\n", Markdown.ToHtml("[a](usage.md) [b](notes.txt)", pipeline));
}
[Test]
public void ThrowsForNullOptions()
{
Assert.Throws<ArgumentNullException>(() => new MarkdownPipelineBuilder().UseRelativeFileLinks(null));
}
[TestCase(null)]
[TestCase("")]
[TestCase("md")]
public void ThrowsForInvalidSourceExtension(string extension)
{
var options = new RelativeFileLinkOptions();
options.SourceExtensions.Add(extension);
Assert.Throws<ArgumentException>(() => new MarkdownPipelineBuilder().UseRelativeFileLinks(options));
}
[Test]
public void ThrowsForMissingExtensions()
{
var noSource = new RelativeFileLinkOptions();
noSource.SourceExtensions.Clear();
var noTarget = new RelativeFileLinkOptions { TargetExtension = null };
Assert.Throws<ArgumentException>(() => new MarkdownPipelineBuilder().UseRelativeFileLinks(noSource));
Assert.Throws<ArgumentException>(() => new MarkdownPipelineBuilder().UseRelativeFileLinks(noTarget));
}
[Test]
public void LeavesDocumentUnchanged()
{
MarkdownDocument document = Markdown.Parse("[a](usage.md)", s_pipeline);
Assert.AreEqual("<p><a href=\"usage.html\">a</a></p>\n", document.ToHtml(s_pipeline));
Assert.AreEqual("usage.md", document.Descendants<LinkInline>().Single().Url);
Assert.AreEqual("[a](usage.md)", Markdown.Normalize("[a](usage.md)", pipeline: s_pipeline));
}
private static string Render(string markdown, Action<HtmlRenderer> configure)
{
var writer = new StringWriter();
var renderer = new HtmlRenderer(writer);
configure(renderer);
s_pipeline.Setup(renderer);
renderer.Render(Markdown.Parse(markdown, s_pipeline));
writer.Flush();
return writer.ToString();
}
}

View File

@@ -25,6 +25,13 @@ public class TestRelativeUrlReplacement
TestSpec(null, "Image: ![alt text](/image.jpg)", "/image.jpg");
}
[Test]
public void DoesNotReplaceEmailAutolinks()
{
TestSpec("https://example.com", "Email: <info@example.com>", "mailto:info@example.com");
TestSpec(null, "Email: <info@example.com>", "mailto:info@example.com");
}
public static void TestSpec(string baseUrl, string markdown, string expectedLink)
{
var pipeline = new MarkdownPipelineBuilder().Build();

View File

@@ -0,0 +1,173 @@
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
using Markdig.Helpers;
using Markdig.Renderers;
namespace Markdig.Extensions.RelativeFileLinks;
/// <summary>
/// Extension that rewrites relative links to Markdown files (e.g. `usage.md#preview`) into links to the generated HTML pages (e.g. `usage.html#preview`).
/// </summary>
/// <remarks>
/// The extension sets <see cref="HtmlRenderer.LinkRewriter"/> and calls any rewriter assigned before. Links with a scheme and protocol-relative links are left unchanged.
/// When <see cref="HtmlRenderer.BaseUrl"/> is set, relative links are already resolved against it, so absolute links with the same scheme, host and port are rewritten too.
/// </remarks>
public sealed class RelativeFileLinkExtension : IMarkdownExtension
{
private readonly string[] _sourceExtensions;
private readonly string _targetExtension;
/// <summary>
/// Initializes a new instance of the <see cref="RelativeFileLinkExtension"/> class with the default options.
/// </summary>
public RelativeFileLinkExtension() : this(new RelativeFileLinkOptions())
{
}
/// <summary>
/// Initializes a new instance of the <see cref="RelativeFileLinkExtension"/> class. The options are copied.
/// </summary>
/// <exception cref="ArgumentNullException"><paramref name="options"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException">The target extension is <c>null</c>, or the source extensions are empty or contain an extension that does not start with `.`.</exception>
public RelativeFileLinkExtension(RelativeFileLinkOptions options)
{
if (options is null) ThrowHelper.ArgumentNullException(nameof(options));
if (options.TargetExtension is null)
{
ThrowHelper.ArgumentException("The target extension must not be null.", nameof(options));
}
if (options.SourceExtensions.Count == 0)
{
ThrowHelper.ArgumentException("At least one source extension is required.", nameof(options));
}
foreach (string extension in options.SourceExtensions)
{
if (string.IsNullOrEmpty(extension) || extension[0] != '.')
{
ThrowHelper.ArgumentException($"Invalid source extension `{extension}`: a source extension must start with `.`.", nameof(options));
}
}
_sourceExtensions = options.SourceExtensions.ToArray();
_targetExtension = options.TargetExtension;
}
/// <summary>
/// Configures this extension for the specified pipeline stage.
/// </summary>
public void Setup(MarkdownPipelineBuilder pipeline)
{
}
/// <summary>
/// Configures this extension for the specified pipeline stage.
/// </summary>
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
if (renderer is not HtmlRenderer htmlRenderer)
{
return;
}
// Markdown.Convert sets up a caller-owned renderer again on every call, so don't wrap the rewriter twice
if (htmlRenderer.LinkRewriter?.Target is ChainedRewriter chained && chained.Extension == this)
{
return;
}
htmlRenderer.LinkRewriter = new ChainedRewriter(this, htmlRenderer, htmlRenderer.LinkRewriter).Rewrite;
}
private string Rewrite(string url, Uri? baseUrl)
{
int pathLength = url.AsSpan().IndexOfAny('?', '#');
if (pathLength < 0)
{
pathLength = url.Length;
}
int extensionLength = GetSourceExtensionLength(url.AsSpan(0, pathLength));
if (extensionLength == 0 || !IsInternal(url, baseUrl))
{
return url;
}
var builder = new ValueStringBuilder(stackalloc char[ValueStringBuilder.StackallocThreshold]);
builder.Append(url.AsSpan(0, pathLength - extensionLength));
builder.Append(_targetExtension);
builder.Append(url.AsSpan(pathLength));
return builder.ToString();
}
private int GetSourceExtensionLength(ReadOnlySpan<char> path)
{
foreach (string extension in _sourceExtensions)
{
if (path.EndsWith(extension.AsSpan(), StringComparison.OrdinalIgnoreCase))
{
return extension.Length;
}
}
return 0;
}
private static bool IsInternal(string url, Uri? baseUrl)
{
if (url.StartsWith("//", StringComparison.Ordinal))
{
return false;
}
if (!HasScheme(url))
{
return true;
}
// BaseUrl resolves relative links before the rewriter runs, so an absolute link with the same origin is internal
return baseUrl is { IsAbsoluteUri: true }
&& Uri.TryCreate(url, UriKind.Absolute, out Uri? uri)
&& Uri.Compare(uri, baseUrl, UriComponents.SchemeAndServer, UriFormat.SafeUnescaped, StringComparison.OrdinalIgnoreCase) == 0;
}
private static bool HasScheme(string url)
{
// RFC 3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) ":"
if (url.Length == 0 || !url[0].IsAlpha())
{
return false;
}
for (int i = 1; i < url.Length; i++)
{
char c = url[i];
if (c == ':')
{
return true;
}
if (!c.IsAlphaNumeric() && c is not ('+' or '-' or '.'))
{
return false;
}
}
return false;
}
private sealed class ChainedRewriter(RelativeFileLinkExtension extension, HtmlRenderer renderer, Func<string, string>? next)
{
public RelativeFileLinkExtension Extension => extension;
public string Rewrite(string url)
{
url = extension.Rewrite(url, renderer.BaseUrl);
return next is null ? url : next(url);
}
}
}

View File

@@ -0,0 +1,21 @@
// Copyright (c) Alexandre Mutel. All rights reserved.
// This file is licensed under the BSD-Clause 2 license.
// See the license.txt file in the project root for more information.
namespace Markdig.Extensions.RelativeFileLinks;
/// <summary>
/// Options for the <see cref="RelativeFileLinkExtension"/>.
/// </summary>
public sealed class RelativeFileLinkOptions
{
/// <summary>
/// Gets the file extensions of the link targets to rewrite, compared case-insensitively (`.md` and `.markdown` by default). Clear the list to replace the defaults.
/// </summary>
public List<string> SourceExtensions { get; } = [".md", ".markdown"];
/// <summary>
/// Gets or sets the file extension that replaces a source extension (`.html` by default). An empty string produces extensionless links.
/// </summary>
public string TargetExtension { get; set; } = ".html";
}

View File

@@ -26,6 +26,7 @@ using Markdig.Extensions.MediaLinks;
using Markdig.Extensions.NonAsciiNoEscape;
using Markdig.Extensions.PragmaLines;
using Markdig.Extensions.ReferralLinks;
using Markdig.Extensions.RelativeFileLinks;
using Markdig.Extensions.SelfPipeline;
using Markdig.Extensions.SmartyPants;
using Markdig.Extensions.Tables;
@@ -505,6 +506,31 @@ public static class MarkdownExtensions
return pipeline;
}
/// <summary>
/// Uses the relative file link extension to rewrite relative links to Markdown files (e.g. `usage.md#preview`) into links to HTML files (e.g. `usage.html#preview`).
/// </summary>
/// <param name="pipeline">The pipeline.</param>
/// <returns>The modified pipeline</returns>
public static MarkdownPipelineBuilder UseRelativeFileLinks(this MarkdownPipelineBuilder pipeline)
{
pipeline.Extensions.ReplaceOrAdd<RelativeFileLinkExtension>(new RelativeFileLinkExtension());
return pipeline;
}
/// <summary>
/// Uses the relative file link extension to rewrite relative links to files with one of the source extensions into links to files with the target extension.
/// </summary>
/// <param name="pipeline">The pipeline.</param>
/// <param name="options">The options.</param>
/// <returns>The modified pipeline</returns>
/// <exception cref="ArgumentNullException"><paramref name="options"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="options"/> contains an invalid value.</exception>
public static MarkdownPipelineBuilder UseRelativeFileLinks(this MarkdownPipelineBuilder pipeline, RelativeFileLinkOptions options)
{
pipeline.Extensions.ReplaceOrAdd<RelativeFileLinkExtension>(new RelativeFileLinkExtension(options));
return pipeline;
}
/// <summary>
/// Adds support for right-to-left content by adding appropriate html attribtues.
/// </summary>
@@ -669,6 +695,9 @@ public static class MarkdownExtensions
case "cjk-friendly-emphasis":
pipeline.UseCjkFriendlyEmphasis();
break;
case "relativefilelinks":
pipeline.UseRelativeFileLinks();
break;
default:
throw new ArgumentException($"Invalid extension `{extension}` from `{extensions}`", nameof(extensions));
}

View File

@@ -24,8 +24,8 @@ public class AutolinkInlineRenderer : HtmlObjectRenderer<AutolinkInline>
{
if (renderer.EnableHtmlForInline)
{
renderer.Write(obj.IsEmail ? "<a href=\"mailto:" : "<a href=\"");
renderer.WriteEscapeUrl(obj.Url);
renderer.Write("<a href=\"");
renderer.WriteEscapeUrl(obj.IsEmail ? "mailto:" + obj.Url : obj.Url);
renderer.WriteRaw('"');
renderer.WriteAttributes(obj);

View File

@@ -89,12 +89,12 @@ public class HtmlRenderer : TextRendererBase<HtmlRenderer>
public bool UseNonAsciiNoEscape { get; set; }
/// <summary>
/// Gets a value to use as the base url for all relative links
/// Gets or sets the base URL used to resolve relative links.
/// </summary>
public Uri? BaseUrl { get; set; }
/// <summary>
/// Allows links to be rewritten
/// Gets or sets a function to rewrite the URLs written by <see cref="WriteEscapeUrl"/>. It receives the complete URL, after <see cref="BaseUrl"/> has been applied and before escaping.
/// </summary>
public Func<string, string>? LinkRewriter { get; set; }

View File

@@ -86,6 +86,7 @@ class Program
new Spec("Yaml", "YamlSpecs.md", "yaml"),
new Spec("Auto Links", "AutoLinks.md", "autolinks|advanced"),
new Spec("Jira Links", "JiraLinks.md", "jiralinks"),
new Spec("Relative File Links", "RelativeFileLinkSpecs.md", "relativefilelinks|advanced+relativefilelinks"),
new Spec("Globalization", "GlobalizationSpecs.md", "globalization+advanced+emojis"),
new Spec("Figures, Footers and Cites", "FigureFooterAndCiteSpecs.md", "figures+footers+citations|advanced"),
new Spec("CJK-friendly Emphasis", "CJKFriendlyEmphasis.md", "cjk-friendly-emphasis"),