Documentation for this module may be created at ಮೋಡ್ಯೂಲ್:Auto parents/doc

require('strict')

local p = {} --p stands for package

local getArgs = require('Module:Arguments').getArgs
local yesno = require('Module:Yesno')

--[=[
Return a formatted list of links referring to the parents of the current page

Parameters:
 * page: the page title to use, if not the current page name
 * display: an override display title to use for the top level.
 * no_links: if yes, do not link page titles
 * existing_links: if yes, check whether pages exist before making them links

Example:

 * page = A/B/C/D => [[A|A]], [[A/B|B]], [[A/B/C|C]]
 * page = A/B/C, display=Foo => [[A|Foo]], [[A/B|B]]
]=]
function p._parent_links(args)
	args = args or {}
	
	local no_links = yesno(args.no_links or args['no links']) or false
	local existing_links = yesno(args.existing_links or args['existing links']) or false
	
	-- select override page name if given
	local title
	if args['page'] then
		title = mw.title.new(args['page'])
	else
		title = mw.title.getCurrentTitle()
	end
	local title_text = title.prefixedText
	
	-- the parts of the page title
	local parts = mw.text.split(title_text, '/', true)
	
	-- collected links for each parent
	-- at the top level, substitute the work display name if needed
	-- don't include namespace in link name
	local links = {
		args['display'] or title.rootText
	}
	
	if not no_links and (not existing_links or (existing_links and mw.title.new(parts[1]).exists)) then
		links[1] = '[[' .. parts[1] .. '|' .. links[1] .. ']]'
	end
	
	-- count forwards from the second-highest level to the second-lowest
	-- (the lowest level is the current page, not a parent)
	for level = 2, #parts - 1, 1 do
		local link_name = parts[level]
    	local link_target = table.concat(parts, '/', 1, level)
		
        -- construct the link wikitext
        local link
        if no_links then
        	link = link_name
        elseif existing_links then
        	if mw.title.new(link_target).exists then
        		link = '[[' .. link_target .. '|' .. link_name .. ']]'
        	else
        		link = link_name
        	end
        else
    		link = '[[' .. link_target .. '|' .. link_name .. ']]'
    	end
    	
    	table.insert(links, link)
    end
	
    return table.concat(links, ', ')
end

function p.parent_links(frame)
	return p._parent_links(getArgs(frame))
end

return p