diff --git a/readme.md b/readme.md index 34ad4bfa..a19735db 100644 --- a/readme.md +++ b/readme.md @@ -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`. diff --git a/site/docs/extensions/menu.yml b/site/docs/extensions/menu.yml index 36a88a59..6c9895ae 100644 --- a/site/docs/extensions/menu.yml +++ b/site/docs/extensions/menu.yml @@ -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"} diff --git a/site/docs/extensions/readme.md b/site/docs/extensions/readme.md index 80ccf966..396adecf 100644 --- a/site/docs/extensions/readme.md +++ b/site/docs/extensions/readme.md @@ -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 diff --git a/site/docs/extensions/relative-file-links.md b/site/docs/extensions/relative-file-links.md new file mode 100644 index 00000000..6c253e82 --- /dev/null +++ b/site/docs/extensions/relative-file-links.md @@ -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); +//

See the usage guide.

+``` + +## 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 | +| `` | 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)); +//

Install

+``` + +`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 ``, 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. diff --git a/site/docs/usage.md b/site/docs/usage.md index d3e383de..d6968747 100644 --- a/site/docs/usage.md +++ b/site/docs/usage.md @@ -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 diff --git a/src/Markdig.Tests/Specs/RelativeFileLinkSpecs.generated.cs b/src/Markdig.Tests/Specs/RelativeFileLinkSpecs.generated.cs new file mode 100644 index 00000000..3fecc390 --- /dev/null +++ b/src/Markdig.Tests/Specs/RelativeFileLinkSpecs.generated.cs @@ -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: + //

Usage

+ //

Read me

+ //

Guide

+ + TestParser.TestSpec("[Usage](usage.md)\n\n[Read me](README.MD)\n\n[Guide](guide.markdown)", "

Usage

\n

Read me

\n

Guide

", "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: + //

Preview

+ //

Version

+ + TestParser.TestSpec("[Preview](usage.md#preview)\n\n[Version](usage.md?v=1#preview)", "

Preview

\n

Version

", "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: + //

Usage

+ //

Install

+ //

Docs

+ //

Linux

+ + 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", "

Usage

\n

Install

\n

Docs

\n

Linux

", "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]( "usage.md") + // + // Should be rendered as: + //

usage.md

+ + TestParser.TestSpec("[usage.md]( \"usage.md\")", "

usage.md

", "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) + // + // + // + // Should be rendered as: + //

Source

+ //

CDN

+ //

Mail

+ //

info@example.md

+ + 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", "

Source

\n

CDN

\n

Mail

\n

info@example.md

", "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: + //

Notes

+ //

Download

+ //

Anchor

+ //

MDX

+ //

Folder

+ + 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/)", "

Notes

\n

Download

\n

Anchor

\n

MDX

\n

Folder

", "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: + // Usage + // + // Should be rendered as: + //

Usage

+ + TestParser.TestSpec("Usage", "

Usage

", "relativefilelinks|advanced+relativefilelinks", context: "Example 7\nSection Extensions / Relative File Links\n"); + } + } +} diff --git a/src/Markdig.Tests/Specs/RelativeFileLinkSpecs.md b/src/Markdig.Tests/Specs/RelativeFileLinkSpecs.md new file mode 100644 index 00000000..b9021e94 --- /dev/null +++ b/src/Markdig.Tests/Specs/RelativeFileLinkSpecs.md @@ -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) +. +

Usage

+

Read me

+

Guide

+```````````````````````````````` + +The query and the fragment are kept: + +```````````````````````````````` example +[Preview](usage.md#preview) + +[Version](usage.md?v=1#preview) +. +

Preview

+

Version

+```````````````````````````````` + +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 +. +

Usage

+

Install

+

Docs

+

Linux

+```````````````````````````````` + +Only the link target changes. The link text and the title stay as written, and the target is escaped as usual: + +```````````````````````````````` example +[usage.md]( "usage.md") +. +

usage.md

+```````````````````````````````` + +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) + + +. +

Source

+

CDN

+

Mail

+

info@example.md

+```````````````````````````````` + +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/) +. +

Notes

+

Download

+

Anchor

+

MDX

+

Folder

+```````````````````````````````` + +Links written as raw HTML are not rewritten: + +```````````````````````````````` example +Usage +. +

Usage

+```````````````````````````````` diff --git a/src/Markdig.Tests/Specs/readme.md b/src/Markdig.Tests/Specs/readme.md index a88f15ec..b8ccf969 100644 --- a/src/Markdig.Tests/Specs/readme.md +++ b/src/Markdig.Tests/Specs/readme.md @@ -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 \ No newline at end of file diff --git a/src/Markdig.Tests/TestLinkRewriter.cs b/src/Markdig.Tests/TestLinkRewriter.cs index fa2ea1df..4e0ea341 100644 --- a/src/Markdig.Tests/TestLinkRewriter.cs +++ b/src/Markdig.Tests/TestLinkRewriter.cs @@ -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: ", "xmailto:info@example.com"); + } + public static void TestSpec(Func linkRewriter, string markdown, string expectedLink) { var pipeline = new MarkdownPipelineBuilder().Build(); @@ -37,4 +43,4 @@ public class TestLinkRewriter Assert.That(writer.ToString(), Contains.Substring("=\"" + expectedLink + "\"")); } -} \ No newline at end of file +} diff --git a/src/Markdig.Tests/TestRelativeFileLinks.cs b/src/Markdig.Tests/TestRelativeFileLinks.cs new file mode 100644 index 00000000..9a256497 --- /dev/null +++ b/src/Markdig.Tests/TestRelativeFileLinks.cs @@ -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($"

a

\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($"

a

\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("

a

\n", writer.ToString()); + } + + [Test] + public void RunsBeforeExistingLinkRewriter() + { + string html = Render("[a](usage.md)", renderer => renderer.LinkRewriter = url => "https://cdn.example.com/" + url); + + Assert.AreEqual("

a

\n", html); + } + + [Test] + public void DoesNotWrapLinkRewriterTwice() + { + var renderer = new HtmlRenderer(new StringWriter()); + Markdown.Convert("[a](usage.md)", renderer, s_pipeline); + Func 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($"

a

\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("

a b

\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("

a b

\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("

a b

\n", Markdown.ToHtml("[a](usage.md) [b](notes.txt)", pipeline)); + } + + [Test] + public void ThrowsForNullOptions() + { + Assert.Throws(() => new MarkdownPipelineBuilder().UseRelativeFileLinks(null)); + } + + [TestCase(null)] + [TestCase("")] + [TestCase("md")] + public void ThrowsForInvalidSourceExtension(string extension) + { + var options = new RelativeFileLinkOptions(); + options.SourceExtensions.Add(extension); + + Assert.Throws(() => new MarkdownPipelineBuilder().UseRelativeFileLinks(options)); + } + + [Test] + public void ThrowsForMissingExtensions() + { + var noSource = new RelativeFileLinkOptions(); + noSource.SourceExtensions.Clear(); + var noTarget = new RelativeFileLinkOptions { TargetExtension = null }; + + Assert.Throws(() => new MarkdownPipelineBuilder().UseRelativeFileLinks(noSource)); + Assert.Throws(() => new MarkdownPipelineBuilder().UseRelativeFileLinks(noTarget)); + } + + [Test] + public void LeavesDocumentUnchanged() + { + MarkdownDocument document = Markdown.Parse("[a](usage.md)", s_pipeline); + + Assert.AreEqual("

a

\n", document.ToHtml(s_pipeline)); + Assert.AreEqual("usage.md", document.Descendants().Single().Url); + Assert.AreEqual("[a](usage.md)", Markdown.Normalize("[a](usage.md)", pipeline: s_pipeline)); + } + + private static string Render(string markdown, Action 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(); + } +} diff --git a/src/Markdig.Tests/TestRelativeUrlReplacement.cs b/src/Markdig.Tests/TestRelativeUrlReplacement.cs index c13ef18d..a5e0571a 100644 --- a/src/Markdig.Tests/TestRelativeUrlReplacement.cs +++ b/src/Markdig.Tests/TestRelativeUrlReplacement.cs @@ -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: ", "mailto:info@example.com"); + TestSpec(null, "Email: ", "mailto:info@example.com"); + } + public static void TestSpec(string baseUrl, string markdown, string expectedLink) { var pipeline = new MarkdownPipelineBuilder().Build(); diff --git a/src/Markdig/Extensions/RelativeFileLinks/RelativeFileLinkExtension.cs b/src/Markdig/Extensions/RelativeFileLinks/RelativeFileLinkExtension.cs new file mode 100644 index 00000000..004b5b27 --- /dev/null +++ b/src/Markdig/Extensions/RelativeFileLinks/RelativeFileLinkExtension.cs @@ -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; + +/// +/// 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`). +/// +/// +/// The extension sets and calls any rewriter assigned before. Links with a scheme and protocol-relative links are left unchanged. +/// When is set, relative links are already resolved against it, so absolute links with the same scheme, host and port are rewritten too. +/// +public sealed class RelativeFileLinkExtension : IMarkdownExtension +{ + private readonly string[] _sourceExtensions; + private readonly string _targetExtension; + + /// + /// Initializes a new instance of the class with the default options. + /// + public RelativeFileLinkExtension() : this(new RelativeFileLinkOptions()) + { + } + + /// + /// Initializes a new instance of the class. The options are copied. + /// + /// is null. + /// The target extension is null, or the source extensions are empty or contain an extension that does not start with `.`. + 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; + } + + /// + /// Configures this extension for the specified pipeline stage. + /// + public void Setup(MarkdownPipelineBuilder pipeline) + { + } + + /// + /// Configures this extension for the specified pipeline stage. + /// + 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 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? next) + { + public RelativeFileLinkExtension Extension => extension; + + public string Rewrite(string url) + { + url = extension.Rewrite(url, renderer.BaseUrl); + return next is null ? url : next(url); + } + } +} diff --git a/src/Markdig/Extensions/RelativeFileLinks/RelativeFileLinkOptions.cs b/src/Markdig/Extensions/RelativeFileLinks/RelativeFileLinkOptions.cs new file mode 100644 index 00000000..e96125f3 --- /dev/null +++ b/src/Markdig/Extensions/RelativeFileLinks/RelativeFileLinkOptions.cs @@ -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; + +/// +/// Options for the . +/// +public sealed class RelativeFileLinkOptions +{ + /// + /// 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. + /// + public List SourceExtensions { get; } = [".md", ".markdown"]; + + /// + /// Gets or sets the file extension that replaces a source extension (`.html` by default). An empty string produces extensionless links. + /// + public string TargetExtension { get; set; } = ".html"; +} diff --git a/src/Markdig/MarkdownExtensions.cs b/src/Markdig/MarkdownExtensions.cs index 268ea100..49cda4f5 100644 --- a/src/Markdig/MarkdownExtensions.cs +++ b/src/Markdig/MarkdownExtensions.cs @@ -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; } + /// + /// 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`). + /// + /// The pipeline. + /// The modified pipeline + public static MarkdownPipelineBuilder UseRelativeFileLinks(this MarkdownPipelineBuilder pipeline) + { + pipeline.Extensions.ReplaceOrAdd(new RelativeFileLinkExtension()); + return pipeline; + } + + /// + /// 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. + /// + /// The pipeline. + /// The options. + /// The modified pipeline + /// is null. + /// contains an invalid value. + public static MarkdownPipelineBuilder UseRelativeFileLinks(this MarkdownPipelineBuilder pipeline, RelativeFileLinkOptions options) + { + pipeline.Extensions.ReplaceOrAdd(new RelativeFileLinkExtension(options)); + return pipeline; + } + /// /// Adds support for right-to-left content by adding appropriate html attribtues. /// @@ -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)); } diff --git a/src/Markdig/Renderers/Html/Inlines/AutolinkInlineRenderer.cs b/src/Markdig/Renderers/Html/Inlines/AutolinkInlineRenderer.cs index 24f62f56..163a3363 100644 --- a/src/Markdig/Renderers/Html/Inlines/AutolinkInlineRenderer.cs +++ b/src/Markdig/Renderers/Html/Inlines/AutolinkInlineRenderer.cs @@ -24,8 +24,8 @@ public class AutolinkInlineRenderer : HtmlObjectRenderer { if (renderer.EnableHtmlForInline) { - renderer.Write(obj.IsEmail ? " public bool UseNonAsciiNoEscape { get; set; } /// - /// Gets a value to use as the base url for all relative links + /// Gets or sets the base URL used to resolve relative links. /// public Uri? BaseUrl { get; set; } /// - /// Allows links to be rewritten + /// Gets or sets a function to rewrite the URLs written by . It receives the complete URL, after has been applied and before escaping. /// public Func? LinkRewriter { get; set; } diff --git a/src/SpecFileGen/Program.cs b/src/SpecFileGen/Program.cs index 4c17337d..564ed118 100644 --- a/src/SpecFileGen/Program.cs +++ b/src/SpecFileGen/Program.cs @@ -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"),