解决Pandoc导出含exam类TeX文档为Markdown的内容缺失问题
解决Exam类TeX文档转Markdown的内容丢失问题
问题描述
使用exam类编写的TeX文档,通过Pandoc执行命令pandoc -i mytest.tex -o mytest.md转换为Markdown时,题目部分内容为空。已知Pandoc旧问题#4023的解决方法,但无法覆盖填空、选择题场景,需要实现包含题目及解答的完整转换。
示例TeX文档:
\documentclass[answers]{exam} \usepackage{minted} \let\oldpart\part \renewcommand{\part}[1][]{\oldpart[#1]{}} \begin{document} \begin{questions} \question Exercise 1 \begin{parts} \part[1] This fills in the \fillin[blanks] \end{parts} \question Exercise 2 \begin{parts} \part[2] Please tick the \textbf{right} statements \begin{checkboxes} \CorrectChoice This is correct. \choice The correct answer is not this answer. \choice This is the wrong answer. \CorrectChoice This is right. \end{checkboxes} \end{parts} \end{questions} \end{document}
解决方案
方法1:自定义Lua过滤器(推荐)
Pandoc默认不识别exam类的专属环境与命令,编写Lua过滤器可直接解析这些元素并转换为Markdown格式。
- 创建过滤器文件
exam-filter.lua,内容如下:
-- 转换exam类环境为Markdown列表 function Div(el) if el.classes[1] == "questions" then return pandoc.OrderedList(el.content) elseif el.classes[1] == "parts" then return pandoc.BulletList(el.content) elseif el.classes[1] == "checkboxes" then return pandoc.BulletList(el.content) end end -- 处理exam类命令 function RawInline(el) if el.format == "tex" then -- 解析\question local question_text = el.text:match("^\\question(.*)$") if question_text then return pandoc.Strong(pandoc.Str("问题" .. question_text)) end -- 解析带分数的\part local part_score = el.text:match("^\\part%[(%d+)%]") if part_score then return pandoc.Strong(pandoc.Str("(" .. part_score .. "分) ")) end -- 解析\fillin填空 local fillin_answer = el.text:match("^\\fillin%[(.*)%]$") if fillin_answer then return pandoc.Emph(pandoc.Str("[" .. fillin_answer .. "]")) end -- 处理正确选项 if el.text == "\\CorrectChoice" then return pandoc.Str("[✓] ") end -- 处理普通选项 if el.text == "\\choice" then return pandoc.Str("[ ] ") end end end
- 执行转换命令:
pandoc -i mytest.tex -o mytest.md --lua-filter=exam-filter.lua
转换后的Markdown效果:
1. **问题 Exercise 1** - **(1分) ** This fills in the *[blanks]* 2. **问题 Exercise 2** - **(2分) ** Please tick the **right** statements - [✓] This is correct. - [ ] The correct answer is not this answer. - [ ] This is the wrong answer. - [✓] This is right.
方法2:预处理TeX文档
如果不想编写过滤器,可手动修改TeX文档,将exam类专属语法替换为Pandoc可识别的通用LaTeX结构:
修改后的TeX示例:
\documentclass{article} \usepackage{minted} \begin{document} \begin{enumerate} \item \textbf{Exercise 1} \begin{itemize} \item \textbf{(1分)} This fills in the \textit{[blanks]} \end{itemize} \item \textbf{Exercise 2} \begin{itemize} \item \textbf{(2分)} Please tick the \textbf{right} statements \begin{itemize} \item [✓] This is correct. \item [ ] The correct answer is not this answer. \item [ ] This is the wrong answer. \item [✓] This is right. \end{itemize} \end{itemize} \end{enumerate} \end{document}
再执行原Pandoc转换命令即可得到正常的Markdown文档。
内容的提问来源于stack exchange,提问作者Andy
相关产品推荐
相关产品推荐

