如何将一些降价(带有 yaml 标头)文件组合成单个 pandoc 输出

问题描述 投票:0回答:1

我想将几个

markdown files
(0*.md,即 02.md、03.md 和 05.md)与包含标题和摘要(index.md)文件的文件组合成一个
pandoc
输出.所有文件都包含标题,例如:

---
title: title02 
abstract: abstract02
---

后跟文字。

结果是用

产生的
pandoc -o readme.pdf index.md 0*.md 

几乎令人满意。标题和摘要是最后一个 05.md 文件的标题(不是 index.md 文件的)。然而,0*.md 文件的标题不包括在内。

是否有可能使用 pandoc 命令实现所需的输出,或者我是否需要恢复到程序来组合文件?我可以改变什么来改善结果?

我看到了一些与advice的相似之处,但是这个过程太复杂了;我需要一个在不同的结构相似的文件集上自动运行的程序。

pandoc
1个回答
1
投票

Pandoc 对这种情况有一个有用的特性:自定义 Lua 阅读器。我们可以使用它来按照我们需要的方式使用输入文件。

下面的脚本假定第一个输入文件 (

index.md
) 是特殊的,因为它定义了顶级元数据。所有其他输入文件都略有修改:标题被转换为顶级标题,所有其他标题都被移动以适应这一点。同样,摘要作为单独的部分添加。如果需要,您可以进一步自定义。

通过将下面的内容保存到文件中来使用

combine.lua
,然后调用 pandoc
pandoc --from=combine.lua index.md 01.md ...
.

function Reader(inputs, opts)
  local doc = pandoc.Pandoc{}  -- the resulting document

  -- parse input as Markdown
  local parse = function (input)
    return pandoc.read(tostring(input), 'markdown', opts)
  end

  -- The first file is assumed to be special. Just use as-is.
  doc = doc .. parse(inputs:remove(1))

  -- Process each input file separately and merge it into the top-level
  -- document.
  for i, input in ipairs(inputs) do
    local part = parse(input, opts)
    -- add the title as a top-level heading
    if part.meta.title then
      doc.blocks:insert(pandoc.Header(1, part.meta.title))
      part.meta.title = nil  -- unset, so it won't conflict with main title
    end
    -- add the abstract under a new heading
    if part.meta.abstract then
      doc.blocks:insert(pandoc.Header(2, 'Abstract'))
      doc.blocks:extend(
        pandoc.utils.type(part.meta.abstract) == 'Inlines' and
        pandoc.Plain(part.meta.abstract) or
        part.meta.abstract
      )
      part.meta.abstract = nil  -- prevent conflicts
    end
    -- append the main contents to the result doc and merge all meta
    -- information. Shift headings in the part.
    doc = doc .. part:walk {
      Header = function (h)
        h.level = h.level + 1
        return h
      end
    }
  end
  return doc
end
© www.soinside.com 2019 - 2024. All rights reserved.