Module:Category handler: Difference between revisions

m
1 revision imported
m (Protected "Module:Category handler": mol is done (‎[edit=sysop] (indefinite) ‎[move=sysop] (indefinite)))
 
m (1 revision imported)
Line 1: Line 1:
--[=[ <pre>
--------------------------------------------------------------------------------
-- Implements [Template:Ctg]
--                                                                            --
-- Sorts pages into a category more appropriately than pagename alone
--                              CATEGORY HANDLER                              --
-- Default and custom rules are outlined at [[Template:Category handler/doc]]
--                                                                            --
--]=]
--      This module implements the {{category handler}} template in Lua,      --
--      with a few improvements: all namespaces and all namespace aliases    --
--      are supported, and namespace names are detected automatically for    --
--      the local wiki. This module requires [[Module:Namespace detect]]      --
--     and [[Module:Yesno]] to be available on the local wiki. It can be    --
--     configured for different wikis by altering the values in              --
--     [[Module:Category handler/config]], and pages can be blacklisted      --
--     from categorisation by using [[Module:Category handler/blacklist]].  --
--                                                                            --
--------------------------------------------------------------------------------


local p = {}
-- Load required modules
local yesno = require('Module:Yesno')


local ucf = require('Module:Paramtest').ucfirst
-- Lazily load things we don't always need
local mShared, mappings


local curpage = mw.title.getCurrentTitle()
local p = {}


function p.main(frame)
--------------------------------------------------------------------------------
local ns = curpage.namespace
-- Helper functions
--------------------------------------------------------------------------------


-- Just don't bother unless we're in content namespaces
local function trimWhitespace(s, removeBlanks)
if not (ns == 0 or ns == 120) then
if type(s) ~= 'string' then
return ''
return s
end
s = s:match('^%s*(.-)%s*$')
if removeBlanks then
if s ~= '' then
return s
else
return nil
end
else
return s
end
end
end


local args = frame:getParent().args
--------------------------------------------------------------------------------
local cats = {}
-- CategoryHandler class
--------------------------------------------------------------------------------


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


-- Replace underscores with spaces
function CategoryHandler.new(data, args)
-- Condense and trim white-space; remove new lines (just in case)
local obj = setmetatable({ _data = data, _args = args }, CategoryHandler)
v = mw.text.trim(v)
:gsub('[_%s]+',' ')
-- Set the title object
:gsub('\n','')
do
local pagename = obj:parameter('demopage')
local success, titleObj
if pagename then
success, titleObj = pcall(mw.title.new, pagename)
end
if success and titleObj then
obj.title = titleObj
if titleObj == mw.title.getCurrentTitle() then
obj._usesCurrentTitle = true
end
else
obj.title = mw.title.getCurrentTitle()
obj._usesCurrentTitle = true
end
end


-- Snip category name now, up to the index of the first set of two colons
-- Set suppression parameter values
-- If no colons, just use the whole string
for _, key in ipairs{'nocat', 'categories'} do
local cat_n = (v:match('^([^:]+)::') or v)
local value = obj:parameter(key)
:gsub('[Cc]ategory:%s*','')
value = trimWhitespace(value, true)
obj['_' .. key] = yesno(value)
end
do
local subpage = obj:parameter('subpage')
local category2 = obj:parameter('category2')
if type(subpage) == 'string' then
subpage = mw.ustring.lower(subpage)
end
if type(category2) == 'string' then
subpage = mw.ustring.lower(category2)
end
obj._subpage = trimWhitespace(subpage, true)
obj._category2 = trimWhitespace(category2) -- don't remove blank values
end
return obj
end


-- Set category name to the name just snipped
function CategoryHandler:parameter(key)
cat_x.name = cat_n
local parameterNames = self._data.parameters[key]
local pntype = type(parameterNames)
if pntype == 'string' or pntype == 'number' then
return self._args[parameterNames]
elseif pntype == 'table' then
for _, name in ipairs(parameterNames) do
local value = self._args[name]
if value ~= nil then
return value
end
end
return nil
else
error(string.format(
'invalid config key "%s"',
tostring(key)
), 2)
end
end


-- Page title includes matched text
function CategoryHandler:isSuppressedByArguments()
-- Matched text is defined by ::ifmatches[text]
return
-- or if empty, defaults to category name
-- See if a category suppression argument has been set.
if v:find('::ifmatches') then
self._nocat == true
-- Look for brackets used as delimiters and capture them all
or self._categories == false
local match_set = v:match('::ifmatches(%[[^:]+%])')
or (
self._category2
and self._category2 ~= self._data.category2Yes
and self._category2 ~= self._data.category2Negative
)


-- If none are found, use the pagename
-- Check whether we are on a subpage, and see if categories are
if not match_set then
-- suppressed based on our subpage status.
cat_x.ifmatch = {cat_n}
or self._subpage == self._data.subpageNo and self.title.isSubpage
else
or self._subpage == self._data.subpageOnly and not self.title.isSubpage
cat_x.ifmatch = {}
end
-- Split match into table, delimited by brackets
match_set = mw.text.split(match_set,'[%]%[]+')


-- Add to match table; only if not blank
function CategoryHandler:shouldSkipBlacklistCheck()
-- An empty string is created by "[" at the beginning
-- Check whether the category suppression arguments indicate we
for _, w in ipairs(match_set) do
-- should skip the blacklist check.
if w:find('%S') then
return self._nocat == false
table.insert(cat_x.ifmatch,w)
or self._categories == true
end
or self._category2 == self._data.category2Yes
end
end
end


-- Iterate through and escape all metacharacters
function CategoryHandler:matchesBlacklist()
-- Prevents errors when they're passed to string.match() below
if self._usesCurrentTitle then
-- Make everything lowercase
return self._data.currentTitleMatchesBlacklist
for i, w in ipairs(cat_x.ifmatch) do
else
cat_x.ifmatch[i] = w:gsub(
mShared = mShared or require('Module:Category handler/shared')
-- Chars: - ^ $ * ( ) + ?
return mShared.matchesBlacklist(
'([%-^$*()+?])',
self.title.prefixedText,
'%%%1'):lower()
mw.loadData('Module:Category handler/blacklist')
end
)
end
end
end


-- Text to strip from the front of the sort
function CategoryHandler:isSuppressed()
-- Can be user defined with ::remove[text]
-- Find if categories are suppressed by either the arguments or by
-- Defaults to category name exactly
-- matching the blacklist.
-- Escape metacharacters to prevent errors when they're passed to string.match() below
return self:isSuppressedByArguments()
cat_x.trim = string.gsub(
or not self:shouldSkipBlacklistCheck() and self:matchesBlacklist()
v:match('::remove%[%s*([^]:]+)%s*%]') or
end
cat_n,
-- Chars: - ^ $ * ( ) + ?
'([%-^$*()+?])',
'%%%1')


-- Add category and its rules into the list
function CategoryHandler:getNamespaceParameters()
table.insert(cats,cat_x)
if self._usesCurrentTitle then
return self._data.currentTitleNamespaceParameters
else
if not mappings then
mShared = mShared or require('Module:Category handler/shared')
mappings = mShared.getParamMappings(true) -- gets mappings with mw.loadData
end
return mShared.getNamespaceParameters(
self.title,
mappings
)
end
end
return p._main(cats)
end
end


function p._main(cat_list)
function CategoryHandler:namespaceParametersExist()
-- Pagename, exactly, in all lowercase, and escaped (used for matching)
-- Find whether any namespace parameters have been specified.
local pagename = curpage.text
-- We use the order "all" --> namespace params --> "other" as this is what
local pagelc = pagename:lower()
-- the old template did.
local pageesc = pagelc:gsub(
if self:parameter('all') then
-- Chars: - ^ $ * ( ) + ?
return true
'([%-^$*()+?])',
end
'%%%1')
if not mappings then
-- Return table
mShared = mShared or require('Module:Category handler/shared')
local ctg = {}
mappings = mShared.getParamMappings(true) -- gets mappings with mw.loadData
 
end
for _, v in ipairs(cat_list) do
for ns, params in pairs(mappings) do
-- Category name and in lowercase
for i, param in ipairs(params) do
local cn = v.name
if self._args[param] then
local cnl = cn:lower()
return true
-- Text to remove
local rmv = v.trim:lower()
 
-- Little thing that checks pagename against everything in the matches table
-- If there's no table, keep as false (it won't matter)
local pagematches = false
if v.ifmatch then
for _, w in ipairs(v.ifmatch) do
-- Look for exact match, and with faux-singular too
if pagelc:find(w) or
(w:find('s$') and
pagelc:find(w:match('(.*)s$')))
then
pagematches = true
end
end
end
end
end
end
if self:parameter('other') then
return true
end
return false
end


-- Create a second string that counts as the singular of the text to remove
function CategoryHandler:getCategories()
-- If it works as a singular, and the page name is singular, then use it too
local params = self:getNamespaceParameters()
-- Otherwise, just make it the same as rmv
local nsCategory
local rmvpl = rmv
for i, param in ipairs(params) do
if rmv:find('s$') then
local value = self._args[param]
rmvpl = rmv:match('(.*)s$')
if value ~= nil then
if pagelc:find('^'..rmvpl) and
nsCategory = value
(not pagelc:find('^'..rmv))
break
then
end
-- Nothing
end
else
if nsCategory ~= nil or self:namespaceParametersExist() then
rmvpl = rmv
-- Namespace parameters exist - advanced usage.
end
if nsCategory == nil then
nsCategory = self:parameter('other')
end
local ret = {self:parameter('all')}
local numParam = tonumber(nsCategory)
if numParam and numParam >= 1 and math.floor(numParam) == numParam then
-- nsCategory is an integer
ret[#ret + 1] = self._args[numParam]
else
ret[#ret + 1] = nsCategory
end
if #ret < 1 then
return nil
else
return table.concat(ret)
end
end
elseif self._data.defaultNamespaces[self.title.namespace] then
-- Namespace parameters don't exist, simple usage.
return self._args[1]
end
return nil
end


-- If v.ifmatch is not specified or
--------------------------------------------------------------------------------
-- It is and the pattern matches any part of the pagename
-- Exports
-- Continue to add categories
--------------------------------------------------------------------------------
if (not v.ifmatch) or
(v.ifmatch and pagematches)
then
-- If the pagename matches category name exactly
-- Or either is a simple plural of the other
-- Or the text to remove exactly
-- Sort to front
if pagelc:find('^'..cnl..'$') or
cnl:find('^'..pageesc..'s$') or
pagelc:find('^'..cnl..'s$') or
pagelc:find('^'..rmv..'$')
then
table.insert(ctg,string.format('[[Category:%s| ]]',cn))


-- If the pagename begins with the category name
local p = {}
-- Sort with beginning remove
elseif pagelc:find('^'..rmv) or
pagelc:find('^'..rmvpl)
then
-- Offset by an extra character if it's not plural
-- Or the page starts with plural
if rmvpl == rmv then
offset = 1
else
offset = 0
end


-- Unescape metacharacters for proper length
function p._exportClasses()
local key = pagename:sub( #(rmv:gsub('%%','')) + offset )
-- Used for testing purposes.
return {
CategoryHandler = CategoryHandler
}
end


key = ucf(mw.text.trim(key))
function p._main(args, data)
data = data or mw.loadData('Module:Category handler/data')
local handler = CategoryHandler.new(data, args)
if handler:isSuppressed() then
return nil
end
return handler:getCategories()
end


-- Remove punctuation from start if leftover
function p.main(frame, data)
-- Such as "/" leftover on subpages
data = data or mw.loadData('Module:Category handler/data')
-- Or "(" for disambiguated pages
local args = require('Module:Arguments').getArgs(frame, {
if key:find('^%p') then
wrappers = data.wrappers,
key = ucf(key:sub(2))
valueFunc = function (k, v)
-- Just in case, remove "s" preceding punctuation
v = trimWhitespace(v)
elseif key:find('^S%p') then
if type(k) == 'number' then
key = ucf(key:sub(3))
if v ~= '' then
return v
else
return nil
end
end
table.insert(ctg,string.format('[[Category:%s|%s]]',cn,key))
-- Everything else just gets the category added plainly
else
else
table.insert(ctg,string.format('[[Category:%s]]',cn))
return v
end
end
end
end
end
})
 
return p._main(args, data)
return table.concat(ctg)
end
end


return p
return p