Module:User:Theknightwho/discussion

From Wiktionary, the free dictionary
Jump to navigation Jump to search

This is a private module sandbox of Theknightwho, for their own experimentation. Items in this module may be added and removed at Theknightwho's discretion; do not rely on this module's stability.


local export = {}

local function heading(level, text, pagename, section)
	return tostring(mw.html.create("h" .. level)
		:attr("data-source", pagename)
		:attr("data-section", section)
		:wikitext(text)
	)
end

--[==[
Headings must follow \n, \r or the page start, with no intervening characters (including whitespace). They must be followed by \n, \r or the page end, with any spaces and tabs after the final equals sign being ignored. The heading must have a length of at least 1 character (which can be whitespace), and cannot contain \n or \r.
The max heading level is 6. Any that try to go beyond this are still level 6, with the extra equals signs being incorporated into the start and end of the heading text.
The function below first removes any HTML comments, then iterates over all the section headings on a page. It accurately handles the following horrible inputs:
	"===abc==" (level 2 heading "=abc");
	"= =" (level 1 heading with just a space);
	"======" (level 2 heading "==");
	"=======abc=======" (level 6 heading "=abc=");
	"==" (plaintext "==", so no match).
]==]
local function replace_headings(title)
	local section = 0
	return (title:getContent()
		:gsub("<!%-%-.-%-%->", "")
		:gsub("<!%-%-.*", "")
		:gsub("%f[^%z\n\r](=+)([^\n\r]+)%1[\t ]*%f[%z\n\r]", function(m1, m2)
			section = section + 1
			if #m1 <= 6 then
				return heading(#m1, m2, title.fullText, section)
			end
			local excess = ("="):rep(#m1 - 6)
			return heading(6, excess .. m2 .. excess, title.fullText, section)
		end))
end

function export.recent_months(frame)
	local title = mw.title.getCurrentTitle()
	
	local date = os.date("*t")
	date.month = date.month - 1
	if date.month == 0 then
		date.year = date.year - 1
		date.month = 12
	end
	local last_month = os.time{year = date.year, month = date.month, day = 1}
	
	local last_month_page = title:subPageTitle(os.date("%Y/%B", last_month))
	local this_month_page = title:subPageTitle(os.date("%Y/%B"))
	
	local content = tostring(mw.html.create("div")
		:tag("h1")
			:wikitext("[[" .. os.date("/%Y/%B", last_month) .. "|" .. os.date("%B %Y", last_month) .. "]]")
			:done()
		:wikitext(replace_headings(last_month_page))
		:tag("h1")
			:wikitext("[[" .. os.date("/%Y/%B") .. "|" .. os.date("%B %Y") .. "]]")
			:done()
		:wikitext(replace_headings(this_month_page)))
	
	return frame:preprocess(content)
end

function export.test(frame)
	return mw.getCurrentFrame():preprocess(replace_headings(mw.title.new(frame.args[1])))
end

return export