pandoc 抱怨 utf-8 解码错误,即使我的文件是有效的 utf-8 编码文件

pandoc complains about utf-8 decoding error even if my file is valid utf-8 encoded file

我正在尝试在 Windows 系统上使用 pandoc 将降价文件转换为 pdf。由于我的 markdown 包含中文字符,我使用以下命令生成 pdf:

pandoc --pdf-engine=xelatex -V CJKmainfont=KaiTi test.md -o test.pdfbut

但是 pandoc 抱怨该文件包含它无法处理的非 utf8 字符,确切的错误消息是:

Error producing PDF.
! Undefined control sequence.
pandoc.exe: Cannot decode byte '\xae': >Data.Text.Internal.Encoding.streamDecodeUtf8With: Invalid UTF-8 stream

根据我在网上查到的。这主要是由于 markdown 文件的编码,可能与 pandoc 无关。我的文件包含很多汉字和英文字符。我已经将它转换为utf-8编码。

我尝试过但没有成功的事情

非 utf8 字符的 Grep

按照说明进行here and here。我已验证系统区域设置为 UTF-8,localectl status 的输出为:

   System Locale: LANG=en_US.UTF-8
       VC Keymap: us
      X11 Layout: us

我试图用 grep 查找非 utf8 字符。使用的命令是 grep -axv '.*' test.md。但是命令没有输出任何内容。 (我认为这意味着没有不能被 utf-8 解码的无效字符。)

尝试丢弃无效字符

我按照说明 here 尝试从我的文件中删除非 utf8 字符。我使用的命令是:

iconv -f utf-8 -t utf-8 -c test.md > output.md

之后,当我尝试使用 pandocoutput.md 转换为 pdf 时。我仍然遇到相同的错误消息,这表明该文件仍然包含非 utf8 字符。

我的问题

如何查明文件的哪一部分导致了问题,或者如何真正从文件中删除非 utf8 字符,以便编译时出错?

其他信息

问题是markdown中使用反斜杠没有转义导致的。 Pandoc 将反斜杠后跟 markdown 中的文本视为 LaTeX 命令。使用以下命令生成pdf:

pandoc -f markdown-raw_tex --pdf-engine=xelatex -V CJKmainfont=KaiTi test.md -o test.pdf

然后错误消失,可以成功生成pdf文件

跟进

感谢tex.stackexchange中的大师,终于找到了原因。本质上,如果 xelatex 在处理 tex 文件时遇到无效的控制序列,则会产生无效的 utf-8 序列。有关详细信息,请参阅 here and here

更新2017.12.29
使用 release of Pandoc 2.0.6,可以更恰当地处理此行为:

Allow lenient decoding of latex error logs, which are not always properly UTF8-encoded

现在调试这类问题更容易了。