Module:Category handler

-- -- Implements [Template:Ctg] -- Sorts pages into a category more appropriately than pagename alone -- e.g. - Ruby amulet would be in Category:Ruby under "R" -- This module will instead modify the sort key to be "Amulet" -- Pages whose whole title match the category exactly will have their sort key as " ", placing the page at the top of the category. --

local p = {}

local onmain = require('Module:Mainonly').on_main local ucf = require('Module:Paramtest').ucfirst

function p.main(frame) -- Just don't bother unless we're in the mainspace if not onmain then return '' end

local args = frame:getParent.args local cats = {}

for _, v in ipairs(args) do		local cat_x = { }

v = mw.text.trim(v) :gsub('[_%s]+',' ')

-- Trim category name now, up to the index of the first set of two colons -- If not present, just use the whole string local cat_n = (v:match('^([^:]+)::') or v)				:gsub('[Cc]ategory:%s*','')

cat_x.name = cat_n

-- Page title includes matched text -- Matched text is defined by ::ifmatches[text] -- or if empty, defaults to category name if v:find('::ifmatches') then cat_x.ifmatch = v:match('::ifmatches%[%s*([%w%(%)\'%d ]+)%s*%]') or cat_n end

-- Text to strip from the front of the sort -- Can be user defined with ::remove[text] -- Defaults to category name exactly cat_x.trim = v:match('::remove%[%s*([%w%(%)\'%d ]+)%s*%]') or cat_n

table.insert(cats,cat_x) end

return p._main(cats) end

function p._main(cat_list) local pagename = mw.title.getCurrentTitle.fullText local pagelc = pagename:lower local ctg = ''

for _, v in ipairs(cat_list) do		local cn = v.name local cnl = cn:lower local rmv = v.trim:lower

-- If v.ifmatch is not specified or		-- It is and the pattern matches any part of the pagename -- Continue to add categories if (not v.ifmatch) or		( v.ifmatch and pagelc:match( v.ifmatch:lower ) ) then -- If the pagename matches category name exactly -- (or the text to remove exactly; just in case) -- Sort to front if pagelc:match('^'..cnl..'$') or pagelc:match('^'..rmv..'$') then ctg = ctg .. ''

-- If the pagename begins with the category name -- Sort with beginning remove elseif pagelc:match('^'..rmv) then local key = pagename:sub(#rmv+1) key = ucf( mw.text.trim( key ) )

-- Remove "/" leftover on subpages if key:match('^/') then key = key:sub(2) end

ctg = ctg .. ''

-- Everything else just gets the category added plainly else ctg = ctg .. ''			end end end

return ctg end

return p