From 0661ce699fe83c64dd5a5874e8ab17241b19550c Mon Sep 17 00:00:00 2001
From: John MacFarlane <jgm@berkeley.edu>
Date: Thu, 27 May 2021 13:53:26 -0700
Subject: [PATCH] rebase_relative_paths extension: don't change fragment paths.

We don't want a pure fragment path to be rewritten, since
these are used for cross-referencing.
---
 MANUAL.txt                          | 3 +++
 src/Text/Pandoc/Readers/Markdown.hs | 3 ++-
 test/command/3752.md                | 3 +++
 test/command/chap1/text.md          | 2 ++
 4 files changed, 10 insertions(+), 1 deletion(-)

diff --git a/MANUAL.txt b/MANUAL.txt
index d755c0c00..fb1a76e9a 100644
--- a/MANUAL.txt
+++ b/MANUAL.txt
@@ -5081,6 +5081,9 @@ Without this extension, you would have to use
 `![image](chap2/spider.jpg)` in `chap2/text.md`.  Links with
 relative paths will be rewritten in the same way as images.
 
+Absolute paths and URLs are not changed.  Neither are paths
+consisting entirely of a fragment, e.g. `[section one](#foo)`.
+
 Note that relative paths in reference links and images will
 be rewritten relative to the file containing the link
 reference definition, not the file containing the reference link
diff --git a/src/Text/Pandoc/Readers/Markdown.hs b/src/Text/Pandoc/Readers/Markdown.hs
index e5cbadc94..74f2668e4 100644
--- a/src/Text/Pandoc/Readers/Markdown.hs
+++ b/src/Text/Pandoc/Readers/Markdown.hs
@@ -1923,7 +1923,8 @@ autoLink = try $ do
 rebasePath :: SourcePos -> Text -> Text
 rebasePath pos path = do
   let fp = sourceName pos
-   in if isAbsolute (T.unpack path) || isURI path
+      isFragment = T.take 1 path == "#"
+   in if isFragment || isAbsolute (T.unpack path) || isURI path
          then path
          else
            case takeDirectory fp of
diff --git a/test/command/3752.md b/test/command/3752.md
index 6d31eb450..2765d79ac 100644
--- a/test/command/3752.md
+++ b/test/command/3752.md
@@ -18,6 +18,8 @@ URL left alone: manual.
 
 Absolute path left alone: absolute.
 
+Link to fragment: chapter two.
+
 Chapter two
 
 A spider: [spider]
@@ -33,6 +35,7 @@ A spider: [spider]
 <p>Link to <a href="command/chap1/spider.png">spider picture</a>.</p>
 <p>URL left alone: <a href="https://pandoc.org/MANUAL.html">manual</a>.</p>
 <p>Absolute path left alone: <a href="/foo/bar/baz.png">absolute</a>.</p>
+<p>Link to fragment: <a href="#chapter-two">chapter two</a>.</p>
 <h1 id="chapter-two">Chapter two</h1>
 <p>A spider: <img src="command/chap2/spider.png" alt="spider" /></p>
 ```
diff --git a/test/command/chap1/text.md b/test/command/chap1/text.md
index d25514241..68a317161 100644
--- a/test/command/chap1/text.md
+++ b/test/command/chap1/text.md
@@ -11,3 +11,5 @@ Link to [spider picture](spider.png).
 URL left alone: [manual](https://pandoc.org/MANUAL.html).
 
 Absolute path left alone: [absolute](/foo/bar/baz.png).
+
+Link to fragment: [chapter two](#chapter-two).