Module:descendants tree: difference between revisions

From Wiktionary, the free dictionary
Jump to navigation Jump to search
Content deleted Content added
No edit summary
No edit summary
Line 10: Line 10:
local _, index = mw.ustring.find(content, "\n==" .. lang:getCanonicalName() .. "==", nil, true)
local _, index = mw.ustring.find(content, "\n==" .. lang:getCanonicalName() .. "==", nil, true)
_, index = mw.ustring.find(content, "\n====Descendants====", index, true)
_, next_lang = mw.ustring.find(content, "\n==[^=\n]+==", index, false)
_, index = mw.ustring.find(content, "\n(=====?)Descendants%1", index, false)
if (not index) or (next_lang and next_lang < index) then
error("No descendants found")
end
local asterisks, item
local asterisks, item

Revision as of 01:37, 5 March 2017

This module is used by Module:descendants tree/templates to generate the content of {{desctree}}. It gets the content of an entry and searches for a list of descendants. If there is such a list, it displays the contents of the list, or else it displays an error.


local export = {}

local function getDescendants(lang, term)
	local page = mw.title.new(require("Module:links").getLinkPage(term, lang))
	local content = page:getContent()
	
	if not content then
		return ""
	end
	
	local _, index = mw.ustring.find(content, "\n==" .. lang:getCanonicalName() .. "==", nil, true)
	_, next_lang = mw.ustring.find(content, "\n==[^=\n]+==", index, false)
	_, index = mw.ustring.find(content, "\n(=====?)Descendants%1", index, false)
	if (not index) or (next_lang and next_lang < index) then
		error("No descendants found")
	end
	
	local asterisks, item
	local count = 0
	local items = {}
	
	while mw.ustring.sub(content, index + 1, index + 2) == "\n*" do
		_, index, item = mw.ustring.find(content, "\n(%*[^\n]+)", index)
		
		-- Preprocess, but replace recursive calls to avoid template loop errors
		item = mw.ustring.gsub(item, "{{desctree|", "{{#invoke:descendants tree/templates|show|")
		item = mw.getCurrentFrame():preprocess(item)
		
		-- Parse the list item
		asterisks, item = mw.ustring.match(item, "^(%*+:?) *(.-)$")
		item = "<li>" .. item
		
		local newcount = mw.ustring.len(asterisks)
		
		if newcount > count then
			while newcount > count do
				item = "<ul>" .. item
				count = count + 1
			end
		else
			item = "</li>" .. item
		end
		
		while newcount < count do
			item = "</li></ul>" .. item
			count = count - 1
		end

		table.insert(items, item)
	end
	
	while 0 < count do
		table.insert(items, "</li></ul>")
		count = count - 1
	end
	
	return table.concat(items)
end

function export.descendantsTree(terminfo)
	return require("Module:links").full_link(terminfo, nil, true) .. getDescendants(terminfo.lang, terminfo.term)
end

return export