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
-- 获取条目内容(沿用你给的方式)
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 startPos, endPos, eqs =
mw.ustring.find(content,
"\n(=+)%s*" .. safeSection .. "%s*%1%s*\n"
)
-- 兼容标题在页面开头
if not startPos then
startPos, endPos, eqs =
mw.ustring.find(content,
"^(=+)%s*" .. safeSection .. "%s*%1%s*\n"
)
end
if not endPos or not eqs then
return ""
end
local level = mw.ustring.len(eqs)
----------------------------------------------------------------
-- 2. 从标题结束后,顺序扫描后续标题
-- 第一个 level' <= level 的标题即为终点
----------------------------------------------------------------
local after = mw.ustring.sub(content, endPos + 1)
local cutPos = nil
for pos, marks in mw.ustring.gmatch(after, "()\n(=+)") do
local nextLevel = mw.ustring.len(marks)
if nextLevel <= level then
cutPos = pos
break
end
end
local body
if cutPos then
body = mw.ustring.sub(after, 1, cutPos - 1)
else
body = after
end
----------------------------------------------------------------
-- 3. 维基百科帽注样式
----------------------------------------------------------------
local hatnote =
'<div class="hatnote">主条目:[[' .. page .. ']]</div>\n\n'
return hatnote .. body
end
return p