Bookdown中含特殊字符的URL文本引用失效问题及解决咨询
The issue you’re encountering stems from how Pandoc’s parser handles special characters like underscores (_) or colons (:) in URLs when used within text references—especially problematic when compiling to PDF, since LaTeX is strict about underscores outside of math mode. Here are two reliable fixes tailored to your use case:
1. Enclose the URL in Angle Brackets
Wrap the full URL in angle brackets <> inside the link definition. This tells Pandoc to treat the entire string as a raw URL, bypassing parsing conflicts with special characters. This method works across all output formats (PDF, HTML, etc.), making it ideal for cross-compatibility.
--- output: bookdown::pdf_book --- (ref:good) [This Works](https://commons.wikimedia.org/wiki) (ref:good) (ref:fixed-bad) [This Now Works](<https://commons.wikimedia.org/wiki/File:Linear_visible_spectrum.svg>) (ref:fixed-bad)
2. Use LaTeX’s \url{} Command (PDF-Only)
Since you’re targeting bookdown::pdf_book, leveraging LaTeX’s built-in \url{} command directly resolves issues with special characters that would otherwise break LaTeX compilation.
--- output: bookdown::pdf_book --- (ref:latex-fixed) [This Works for PDF](\url{https://commons.wikimedia.org/wiki/File:Linear_visible_spectrum.svg}) (ref:latex-fixed)
Note: This method is specific to PDF output. If you plan to render your book to HTML or other formats, stick with the angle bracket approach instead.
Quick Tip
Double-check that there are no extra spaces around the URL in your text reference definition—unintended spaces can also trigger parsing errors.
内容的提问来源于stack exchange,提问作者Mikey Harper

