Module:Cite
武外梗百科 爱国好学自强图新的百科全书
更多操作
此模块的文档可以在Module:Cite/doc创建
local p = {}
function p.include(frame)
local page = mw.text.trim(frame.args[1] or frame.args.page or "")
local section = mw.text.trim(frame.args[2] or frame.args.section or "")
if page == "" or section == "" then
return ""
end
-- 和你给的示例一致:直接用 title + getContent
local title = mw.title.new(page)
if not title or not title.exists then
return ""
end
local content = title:getContent()
if not content then
return ""
end
-- 转义标题名(防正则炸)
local safeSection = mw.ustring.gsub(
section,
"([%^%$%(%)%%%.%[%]%*%+%-%?])",
"%%%1"
)
----------------------------------------------------------------
-- 1. 匹配任意级别标题,并捕获 '=' 数量
----------------------------------------------------------------
local headerPattern = "\n(=+)%s*" .. safeSection .. "%s*%1%s*\n"
local startPos, endPos, eqs =
mw.ustring.find(content, headerPattern)
-- 兼容标题在页面最开头
if not startPos then
headerPattern = "^(=+)%s*" .. safeSection .. "%s*%1%s*\n"
startPos, endPos, eqs =
mw.ustring.find(content, headerPattern)
end
if not endPos or not eqs then
return ""
end
local level = mw.ustring.len(eqs)
----------------------------------------------------------------
-- 2. 从标题结束后开始,找下一个“级别 ≤ 当前级别”的标题
----------------------------------------------------------------
local after = mw.ustring.sub(content, endPos + 1)
local nextHeaderPattern = "\n={1," .. level .. "}[^=].-\n"
local nextStart = mw.ustring.find(after, nextHeaderPattern)
local body
if nextStart then
body = mw.ustring.sub(after, 1, nextStart - 1)
else
body = after
end
----------------------------------------------------------------
-- 3. 维基百科式帽注 + 原样正文
----------------------------------------------------------------
local hatnote =
'<div class="hatnote">主条目:[[' .. page .. ']]</div>\n\n'
return hatnote .. body
end
return p