转换为Markdown时,请在pandoc中保留自定义代码块属性



我正在将一个组织文件转换为Markdown(特别是commonmark(。我正在向我的代码块添加commonmark编写器不支持的自定义属性,并在转换过程中将其从代码块中剥离。我正试图找到一种方法来保留我的自定义属性。

这就是我所拥有的:

#+begin_src python :hl_lines "2"
def some_function():
print("foo bar")
return
#+end_src

这就是我想要的.md文件:

``` python hl_lines="2"
def some_function():
print("foo bar")
return
```

在做了一些研究之后,我认为过滤器可以解决我的问题:我现在正在玩panflute,一个用于编写pandoc过滤器的python库。

我发现了一些相关的问题,但它们适用于其他转换(rST->html,rST->latex(,我对Lua的了解不够,无法将代码翻译成Python和org.>md转换。

谢谢你的帮助。

我能够编写一个脚本,并将其发布在这里,以供将来关于pandoc过滤器的基于Python的问题使用。

下面的过滤器需要panflute,但Python中还有其他用于pandoc过滤器的库。

import panflute

def keep_attributes_markdown(elem, doc, format="commonmark"):
"""Keep custom attributes specified in code block headers when exporting to Markdown"""
if type(elem) == panflute.CodeBlock:
language = "." + elem.classes[0]
attributes = ""
attributes = " ".join(
[key + "=" + value for key, value in elem.attributes.items()]
)
header = "``` { " + " ".join([language, attributes]).strip() + " }"
panflute.debug(header)
code = elem.text.strip()
footer = "```"
content = [
panflute.RawBlock(header, format=format),
panflute.RawBlock(code, format=format),
panflute.RawBlock(footer, format=format),
]
return content

def main(doc=None):
return panflute.run_filter(keep_attributes_markdown, doc=doc)

if __name__ == "__main__":
main()

您现在可以运行以下命令:

pandoc --from=org --to=commonmark --filter=/full/path/to/keep_attributes_markdown.py --output=target_file.md your_file.org 

最新更新