Pandoc : set document title to first title

删除回忆录丶 提交于 2019-12-24 00:46:04

问题


I'm creating a library on github, so I'm using a Markdown file for that, with the following structure:

# My main title
## My first section
...
## My second section
...

But unfortunately, when I use pandoc to convert this document into latex:

pandoc README.md --number-sections -f markdown -t latex -s -o doc.tex

the document does not have any title, and the numbering starts from the main title:

1. My main title
1.1. My first section
...
1.2. My second section
...

While I'd like something like

My main title <=== document title
1. My first section
...
2. My second section
...

I could of course use sed to change all ## to #, and replace the main title with % Document My main title but it looks quite dirty to me. What is the good way to proceed?

Thanks!


回答1:


Best to use a pandoc filter to do this. Here's a Lua filter that does what you need. Store it in a file, e.g. promote-headers.lua and call pandoc with pandoc --lua-filter=promote-headers.lua.

local title

-- Promote all headers by one level. Set title from level 1 headers,
-- unless it has been set before.
function promote_header (header)

  if header.level >= 2 then
    header.level = header.level - 1
    return header
  end

  if not title then
    title = header.content
    return {}
  end

  local msg = '[WARNING] title already set; discarding header "%s"\n'
  io.stderr:write(msg:format(pandoc.utils.stringify(header)))
  return {}
end

return {
  {Meta = function (meta) title = meta.title end}, -- init title
  {Header = promote_header},
  {Meta = function (meta) meta.title = title; return meta end}, -- set title
}


来源:https://stackoverflow.com/questions/56004886/pandoc-set-document-title-to-first-title

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!