需要帮助编写 lua 过滤器以根据标题级别替换文本中的变量

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

我正在用 markdown 编写文档,并使用 pandoc 将其转换为 word 脚本。我使用了一个现成的过滤器,它改变了我通过数据输入的变量。但我希望变量根据标题级别应用值。如果标题级别发生变化,则变量的值也应相应变化。 例如 simple.md

chapter: chapter
refchapter: "%chapter%"
subsec: subsection
refsubsec: "%subsec%"
pr: point
refpr: "%pr%"
subpr: subitem
refsubpr: "%subpr%"
nameInLink: true
linkReferences: true

第一章

%refchapter%

第二章{#sec:1}

%refsubsec%-@sec:1

第三章{#sec:2}

%refsubpr%-@sec:2

例如Finished filter:

local vars = {}

function get_vars (meta)
  for k, v in pairs(meta) do
    if type(v) == 'table' and v.t == 'MetaInlines' then
      vars["%" .. k .. "%"] = {table.unpack(v)}
    end
  end
end

function replace (el)
  if vars[el.text] then
    return pandoc.walk_inline(pandoc.Span(vars[el.text]), {Str=replace})
  else
    return el
  end
end

return {{Meta = get_vars}, {Str = replace}}

变量值被正确替换,但不依赖于标题级别

我尝试了不同的选项来重写过滤器,但对我来说没有用,因为我根本不是程序员,也不懂编程语言。

-- Set the variables to be replaced in the text
local variables = {
   chapter = "section",
   refchapter = "%chapter%",
   subsec = "subsection",
   refsubsec="%subsec%",
   pr = "item",
   refpr = "%pr%",
   subpr = "subitem",
   refsubpr = "%subpr%"
}

-- Function to replace variables in a string
-- Accepts a string and a table with variables
-- Returns the updated string
local function replaceVariables(str, variables)
   for k,v in pairs(variables) do
     str = str:gsub("%" .. k .. "%", v)
   end
   return str
end

-- Create a function to process headers and replace variables
-- Takes a title line and a line of text
-- Returns the updated string of text
local function processHeader(header, text)
   local level = header:match("^#+") -- Get header level
   if level then
     -- Get the variable for the current header level
     local variable = "ref" .. string.lower(level):gsub("#","") .. "chapter"
     -- Replace this variable in the text
     text = replaceVariables(text, { [variable] = variables. chapter })
   end
   return text
end
-- An example of using the function
local header = "# First section"
local text = "This is just the text after the title and the %refchapter% variable to replace with the value."
text = processHeader(header, text)
print(text) -- "This is just the text after the title and the section variable to be replaced by the value."

header = "## Second section"
text = "This is just text, after the title, and a %subsec% variable to replace with a value."
text = processHeader(header, text)
print(text) -- "This is just the text after the heading and the variable subsection to be replaced by the value."
lua pandoc markwon
© www.soinside.com 2019 - 2024. All rights reserved.