Difference between revisions of "Module:Documentation"

From CWS Planet
Jump to navigation Jump to search
m (1 revision imported)
(update to resolve broken docs?)
Tag: Manual revert
 
Line 1: Line 1:
local export = {}
-- This module implements {{documentation}}.


-- it is either here, or in [[Module:ugly hacks]], and it is not in ugly hacks.
-- Get required modules.
function export.CONTENTMODEL()
local getArgs = require('Module:Arguments').getArgs
return mw.title.getCurrentTitle().contentModel
 
end
-- Get the config table.
local cfg = mw.loadData('Module:Documentation/config')
 
local p = {}
 
-- Often-used functions.
local ugsub = mw.ustring.gsub
local format = mw.ustring.format
 
----------------------------------------------------------------------------
-- Helper functions
--
-- These are defined as local functions, but are made available in the p
-- table for testing purposes.
----------------------------------------------------------------------------


local skins = {
local function message(cfgKey, valArray, expectType)
["common"    ] = "";
--[[
["vector"    ] = "Vector";
-- Gets a message from the cfg table and formats it if appropriate.
["monobook"   ] = "Monobook";
-- The function raises an error if the value from the cfg table is not
["cologneblue"] = "Cologne Blue";
-- of the type expectType. The default type for expectType is 'string'.
["modern"    ] = "Modern";
-- If the table valArray is present, strings such as $1, $2 etc. in the
}
-- message are substituted with values from the table keys [1], [2] etc.
-- For example, if the message "foo-message" had the value 'Foo $2 bar $1.',
-- message('foo-message', {'baz', 'qux'}) would return "Foo qux bar baz."
--]]
local msg = cfg[cfgKey]
expectType = expectType or 'string'
if type(msg) ~= expectType then
error('message: type error in message cfg.' .. cfgKey .. ' (' .. expectType .. ' expected, got ' .. type(msg) .. ')', 2)
end
if not valArray then
return msg
end


local Array = require "Module:array"
local function getMessageVal(match)
match = tonumber(match)
return valArray[match] or error('message: no value found for key $' .. match .. ' in message cfg.' .. cfgKey, 4)
end


local function track(page)
return ugsub(msg, '$([1-9][0-9]*)', getMessageVal)
require("Module:debug/track")("documentation/" .. page)
return true
end
end


local function compare_pages(page1, page2, text)
p.message = message
return "[" .. tostring(
 
mw.uri.fullUrl("Special:ComparePages", { page1 = page1, page2 = page2 }))
local function makeWikilink(page, display)
.. " " .. text .. "]"
if display then
return format('[[%s|%s]]', page, display)
else
return format('[[%s]]', page)
end
end
end


local function page_exists(title)
p.makeWikilink = makeWikilink
local success, title_obj = pcall(mw.title.new, title)
 
return success and title_obj.exists
local function makeCategoryLink(cat, sort)
local catns = mw.site.namespaces[14].name
return makeWikilink(catns .. ':' .. cat, sort)
end
end


-- Avoid transcluding [[Module:languages/cache]] everywhere.
p.makeCategoryLink = makeCategoryLink
local lang_cache = setmetatable({}, { __index = function (self, k)
return require "Module:languages/cache"[k]
end })


local function zh_link(word)
local function makeUrlLink(url, display)
return require("Module:links").full_link{
return format('[%s %s]', url, display)
lang = lang_cache.zh,
term = word
}
end
end


local function make_languages_data_documentation(title, cats, division)
p.makeUrlLink = makeUrlLink
local doc_template, module_cat
 
if division:find("/extra$") then
local function makeToolbar(...)
division = division:gsub("/extra$", "")
local ret = {}
doc_template = "language extradata documentation"
local lim = select('#', ...)
module_cat = "Language extra data modules"
if lim < 1 then
else
return nil
doc_template = "language data documentation"
module_cat = "Language data modules"
end
end
local sort_key
for i = 1, lim do
if division == "exceptional" then
ret[#ret + 1] = select(i, ...)
sort_key = "x"
else
sort_key = division:gsub("/", "")
end
end
cats:insert(module_cat .. "|" .. sort_key)
-- 'documentation-toolbar'
return {
return format(
title = doc_template
'<span class="%s">(%s)</span>',
}
message('toolbar-class'),
end
table.concat(ret, ' &#124; ')
)
end
 
p.makeToolbar = makeToolbar
 
----------------------------------------------------------------------------
-- Argument processing
----------------------------------------------------------------------------


local function make_Unicode_data_documentation(title, cats)
local function makeInvokeFunc(funcName)
local subpage, first_three_of_code_point
return function (frame)
= title.fullText:match("^Module:Unicode data/([^/]+)/(%x%x%x)$")
local args = getArgs(frame, {
if subpage == "names" or subpage == "images" then
valueFunc = function (key, value)
local low, high =
if type(value) == 'string' then
tonumber(first_three_of_code_point .. "000", 16),
value = value:match('^%s*(.-)%s*$') -- Remove whitespace.
tonumber(first_three_of_code_point .. "FFF", 16)
if key == 'heading' or value ~= '' then
return string.format(
return value
"This data module contains the %s of " ..
else
"[[Appendix:Unicode|Unicode]] code points within the range U+%04X to U+%04X.",
return nil
subpage == "images" and "titles of images" or "names",
end
low, high)
else
return value
end
end
})
return p[funcName](args)
end
end
end
end


local function insert_lang_data_module_cats(cats, langcode, overall_data_module_cat)
----------------------------------------------------------------------------
local lang = lang_cache[langcode]
-- Entry points
if lang then
----------------------------------------------------------------------------
local langname = lang:getCanonicalName()
 
cats:insert(overall_data_module_cat .. "|" .. langname)
function p.nonexistent(frame)
cats:insert(langname .. " modules")
if mw.title.getCurrentTitle().subpageText == 'testcases' then
cats:insert(langname .. " data modules")
return frame:expandTemplate{title = 'module test cases notice'}
return lang, langname
else
return p.main(frame)
end
end
end
end


--[=[
p.main = makeInvokeFunc('_main')
This provides categories and documentation for various data modules, so that [[Category:Uncategorized modules]] isn't
unnecessarily cluttered. It is a list of tables, each of which have the following possible fields:


`regex` (required): A Lua pattern to match the module's title. If it matches, the data in this entry will be used.
function p._main(args)
Any captures in the pattern can by referenced in the `cat` field using %1 for the first capture, %2 for the
--[[
second, etc. (often used for creating the sortkey for the category). In addition, the captures are passed to the
-- This function defines logic flow for the module.
`process` function as the third and subsequent parameters.
-- @args - table of arguments passed by the user
--]]
local env = p.getEnvironment(args)
local root = mw.html.create()
root
:wikitext(p._getModuleWikitext(args, env))
:wikitext(p.protectionTemplate(env))
:wikitext(p.sandboxNotice(args, env))
:tag('div')
-- 'documentation-container'
:addClass(message('container'))
:attr('role', 'complementary')
:attr('aria-labelledby', args.heading ~= '' and 'documentation-heading' or nil)
:attr('aria-label', args.heading == '' and 'Documentation' or nil)
:newline()
:tag('div')
-- 'documentation'
:addClass(message('main-div-classes'))
:newline()
:wikitext(p._startBox(args, env))
:wikitext(p._content(args, env))
:tag('div')
-- 'documentation-clear'
:addClass(message('clear'))
:done()
:newline()
:done()
:wikitext(p._endBox(args, env))
:done()
:wikitext(p.addTrackingCategories(env))
-- 'Module:Documentation/styles.css'
return mw.getCurrentFrame():extensionTag (
'templatestyles', '', {src=cfg['templatestyles']
}) .. tostring(root)
end


`process` (optional): This may be a function or a string. If it is a function, it is called as follows:
----------------------------------------------------------------------------
  `process(TITLE, CATS, CAPTURE1, CAPTURE2, ...)`
-- Environment settings
where:
----------------------------------------------------------------------------
  * TITLE is a title object describing the module's title; see
    [https://www.mediawiki.org/wiki/Extension:Scribunto/Lua_reference_manual#Title_objects].
  * CATS is an array object (see [[Module:array]]) of categories that the module will be added to.
  * CAPTURE1, CAPTURE2, ... contain any captures in the `regex` field.
The return value of `process` should either be a string (which will be used as the module's documentation), or a
table specifying the name of a template to expand to get the documentation, along with the arguments to that
template. In the latter format, the template name (bare, without the "Template:" prefix) should be in the `title`
field, and any arguments should be in `args; in this case, the template name will be listed above the generated
documentation as the source of the documentation, along with an edit button to edit the template's contents.
If, however, the return value of the `process` function is a string, any template invocations will be expanded
using frame:preprocess(), and [[Module:documentation]] will be listed as the source of the documentation.


If `process` itself is a string rather than a function, it should name a submodule under
function p.getEnvironment(args)
[[Module:documentation/functions/]] which returns a function, of the same type as described above. This submodule
--[[
will be specified as the source of the documentation (unless it returns a table naming a template to expand to get
-- Returns a table with information about the environment, including title
the documentation, as described above).
-- objects and other namespace- or path-related data.
 
-- @args - table of arguments passed by the user
If `process` is omitted entirely, the module will have no documentation.
--
 
-- Title objects include:
`cat` (optional): A string naming the category into which the module should be placed, or a list of such strings.
-- env.title - the page we are making documentation for (usually the current title)
Captures specified in `regex` may be referenced in this string using %1 for the first capture, %2 for the second,
-- env.templateTitle - the template (or module, file, etc.)
etc. It is also possible to add categories in the `process` function by inserting them into the passed-in CATS
-- env.docTitle - the /doc subpage.
array (the second parameter).
-- env.sandboxTitle - the /sandbox subpage.
]=]
-- env.testcasesTitle - the /testcases subpage.
--
-- Data includes:
-- env.protectionLevels - the protection levels table of the title object.
-- env.subjectSpace - the number of the title's subject namespace.
-- env.docSpace - the number of the namespace the title puts its documentation in.
-- env.docpageBase - the text of the base page of the /doc, /sandbox and /testcases pages, with namespace.
-- env.compareUrl - URL of the Special:ComparePages page comparing the sandbox with the template.
--  
-- All table lookups are passed through pcall so that errors are caught. If an error occurs, the value
-- returned will be nil.
--]]
local env, envFuncs = {}, {}


local module_regex = {
-- Set up the metatable. If triggered we call the corresponding function in the envFuncs table. The value
{
-- returned by that function is memoized in the env table so that we don't call any of the functions
regex = "^Module:languages/data/(3/./extra)$",
-- more than once. (Nils won't be memoized.)
process = make_languages_data_documentation,
setmetatable(env, {
},
__index = function (t, key)
{
local envFunc = envFuncs[key]
regex = "^Module:languages/data/(3/.)$",
if envFunc then
process = make_languages_data_documentation,
local success, val = pcall(envFunc)
},
if success then
{
env[key] = val -- Memoise the value.
regex = "^Module:languages/data/(2/extra)$",
return val
process = make_languages_data_documentation,
},
{
regex = "^Module:languages/data/(2)$",
process = make_languages_data_documentation,
},
{
regex = "^Module:languages/data/(exceptional/extra)$",
process = make_languages_data_documentation,
},
{
regex = "^Module:languages/data/(exceptional)$",
process = make_languages_data_documentation,
},
{
regex = "^Module:languages/.+$",
cat = "Language and script modules",
},
{
regex = "^Module:scripts/.+$",
cat = "Language and script modules",
},
{
regex = "^Module:data tables/data..?.?.?$",
cat = "Reference module sharded data tables",
},
{
regex = "^Module:zh/data/dial%-pron/.+$",
cat = "Chinese dialectal pronunciation data modules",
process = "zh dial or syn",
},
{
regex = "^Module:zh/data/dial%-syn/.+$",
cat = "Chinese dialect synonyms data modules",
process = "zh dial or syn",
},
{
regex = "^Module:zh/data/glyph%-data/.+$",
cat = "Chinese historical character forms data modules",
process = function(title, cats)
local character = title.fullText:match("^Module:zh/data/glyph%-data/(.+)")
if character then
return ("This module contains data on historical forms of the Chinese character %s.")
:format(zh_link(character))
end
end,
},
{
regex = "^Module:zh/data/ltc%-pron/(.+)$",
cat = "Middle Chinese pronunciation data modules|%1",
process = "zh data",
},
{
regex = "^Module:zh/data/och%-pron%-BS/(.+)$",
cat = "Old Chinese (Baxter-Sagart) pronunciation data modules|%1",
process = "zh data",
},
{
regex = "^Module:zh/data/och%-pron%-ZS/(.+)$",
cat = "Old Chinese (Zhengzhang) pronunciation data modules|%1",
process = "zh data",
},
{
-- capture rest of zh/data submodules
regex = "^Module:zh/data/(.+)$",
cat = "Chinese data modules|%1",
},
{
regex = "^Module:mul/guoxue%-data/cjk%-?(.*)$",
process = "guoxue-data",
},
{
regex = "^Module:Unicode data/(.+)$",
cat = "Unicode data modules|%1",
process = make_Unicode_data_documentation,
},
{
regex = "^Module:number list/data/(.+)$",
process = function(title, cats, lang_code)
local lang, langname = insert_lang_data_module_cats(cats, lang_code, "Number data modules")
if lang then
return ("This module contains data on various types of numbers in %s.\n%s")
:format(lang:makeCategoryLink(), require("Module:number list/show").table() or "")
end
end,
},
{
regex = "^Module:accel/(.+)$",
process = function(title, cats)
local lang_code = title.subpageText
local lang = lang_cache[lang_code]
if lang then
cats:insert(lang:getCanonicalName() .. " modules|accel")
cats:insert(("Accel submodules|%s"):format(lang:getCanonicalName()))
return ("This module contains new entry creation rules for %s; see [[WT:ACCEL]] for an overview, and [[Module:accel]] for information on creating new rules.")
:format(lang:makeCategoryLink())
end
end,
},
{
regex = "^Module:inc%-ash/dial/data/(.+)$",
cat = "Ashokan Prakrit modules|%1",
process = function(title, cats)
local word = title.fullText:match("^Module:inc%-ash/dial/data/(.+)$")
if word then
local lang = lang_cache["inc-ash"]
return ("This module contains data on the pronunciation of %s in dialects of %s.")
:format(require("Module:links").full_link({ term = word, lang = lang }, "term"),
lang:makeCategoryLink())
end
end,
},
{
regex = "^.+%-translit$",
process = "translit",
},
{
regex = "^Module:form of/lang%-data/(.+)$",
process = function(title, cats, lang_code)
local lang, langname = insert_lang_data_module_cats(cats, lang_code, "Language-specific form-of modules")
if lang then
-- FIXME, display more info.
return "This module contains language-specific form-of data (tags, shortcuts, base lemma params. etc.) for " ..
langname .. ".\n\n'''NOTE:''' If you add a new language-specific module, you must add the language code to the " ..
"list at the top of [[Module:form of]] in order for the module to be recognized."
end
end
},
{
regex = "^Module:labels/data/lang/(.+)$",
process = function(title, cats, lang_code)
local lang, langname = insert_lang_data_module_cats(cats, lang_code, "Language-specific label data modules")
if lang then
return {
title = "label language-specific data documentation",
args = { [1] = lang_code },
}
end
end
},
{
regex = "^Module:category tree/poscatboiler/data/lang%-specific/(.+)$",
process = function(title, cats, lang_code)
local lang, langname = insert_lang_data_module_cats(cats, lang_code, "Category tree data modules/poscatboiler")
if lang then
return "This module handles generating the descriptions and categorization for " .. langname .. " category pages "
.. "of the format \"" .. langname .. " LABEL\" where LABEL can be any text. Examples are "
.. "[[:Category:Bulgarian conjugation 2.1 verbs]] and [[:Category:Russian velar-stem neuter-form nouns]]. "
.. "This module is part of the poscatboiler system, which is a general framework for generating the "
.. "descriptions and categorization of category pages.\n\n"
.. "For more information, see [[Module:category tree/poscatboiler/data/lang-specific/documentation]].\n\n"
.. "'''NOTE:''' If you add a new language-specific module, you must add the language code to the "
.. "list at the top of [[Module:category tree/poscatboiler/data/lang-specific]] in order for the module to be "
.. "recognized."
end
end
},
{
regex = "^Module:category tree/poscatboiler/data/(.+)$",
process = function(title, cats, submodule)
cats:insert("Category tree data modules/poscatboiler| ")
return {
title = "poscatboiler data submodule documentation"
}
end
},
{
regex = "^Module:category tree/topic cat/data/(.+)$",
process = function(title, cats, submodule)
cats:insert("Category tree data modules/topic cat| ")
return {
title = "topic cat data submodule documentation"
}
end
},
{
regex = "^Module:ja/data/(.+)$",
cat = "Japanese data modules|%1",
},
{
regex = "^Module:fi%-dialects/data/feature/Kettunen1940 ([0-9]+)$",
cat = "Finnish dialectal data atlas modules|%1",
process = function(title, cats, shard)
return "This module contains shard " .. shard .. " of the online version of Lauri Kettunen's 1940 work " ..
"''Suomen murteet III A. Murrekartasto'' (\"Finnish dialects III A: Dialect atlas\"). " ..
"It was imported and converted from urn:nbn:fi:csc-kata20151130145346403821, published by the " ..
"''Kotimaisten kielten keskus'' under the CC BY 4.0 license."
end
},
{
regex = "^Module:Swadesh/data/([a-z-]+)$",
process = function(title, cats, lang_code)
local lang, langname = insert_lang_data_module_cats(cats, lang_code, "Swadesh modules")
if lang then
return "This module contains the [[Swadesh list]] of basic vocabulary in " .. langname .. "."
end
end
},
{
regex = "^Module:Swadesh/data/([a-z-]+)/([^/]*)$",
process = function(title, cats, lang_code, variety)
local lang, langname = insert_lang_data_module_cats(cats, lang_code, "Swadesh modules")
if lang then
local prefix = "This module contains the [[Swadesh list]] of basic vocabulary in the "
local etym_lang = require("Module:languages").getByCode(variety, nil, "allow etym")
if etym_lang then
return ("%s %s variety of %s."):format(prefix, etym_lang:getCanonicalName(), langname)
end
end
local script = require("Module:scripts").getByCode(variety)
if script then
return ("%s %s %s script."):format(prefix, langname, script:getCanonicalName())
end
return ("%s %s variety of %s."):format(prefix, variety, langname)
end
end
return nil
end
end
},
})
{
regex = "^Module:typing%-aids",
process = function(title, cats)
local data_suffix = title.fullText:match("^Module:typing%-aids/data/(.+)$")
local sortkey
if data_suffix then
if data_suffix:find "^[%l-]+$" then
local lang = require("Module:languages").getByCode(data_suffix)
if lang then
sortkey = lang:getCanonicalName()
cats:insert(sortkey .. " data modules")
end
elseif data_suffix:find "^%u%l%l%l$" then
local script = require("Module:scripts").getByCode(data_suffix)
if script then
sortkey = script:getCanonicalName()
cats:insert(script:getCategoryName())
end
end
cats:insert("Character insertion data modules|" .. (sortkey or data_suffix))
end
end,
},
{
regex = "^Module:R:([a-z%-]+):(.+)$",
process = function(title, cats, lang_code, refname)
local lang = lang_cache[lang_code]
if lang then
cats:insert(lang:getCanonicalName() .. " modules|" .. refname)
cats:insert(("Reference modules|%s"):format(lang:getCanonicalName()))
return "This module implements the reference template {{temp|R:" .. lang_code .. ":" .. refname .. "}}."
end
end,
},
{
regex = "^Module:Quotations/([a-z-]+)/?(.*)",
process = "Quotation",
},
{
regex = "^Module:affix/lang%-data/([a-z-]+)",
process = "affix lang-data",
},
{
regex = "^Module:dialect synonyms/([a-z-]+)$",
process = function(title, cats, lang_code)
local lang = lang_cache[lang_code]
if lang then
local langname = lang:getCanonicalName()
cats:insert("Dialect synonyms data modules|" .. langname)
cats:insert(langname .. " dialect synonyms data modules| ")
return "This module contains data on specific varieties of " .. langname .. ", for use by " ..
"{{tl|dialect synonyms}}. The actual synonyms themselves are contained in submodules."
end
end,
},
{
regex = "^Module:dialect synonyms/([a-z-]+)/(.+)$",
process = function(title, cats, lang_code, term)
local lang = lang_cache[lang_code]
if lang then
local langname = lang:getCanonicalName()
cats:insert("Dialect synonyms data modules|" .. langname)
cats:insert(langname .. " dialect synonyms data modules|" .. term)
return ("This module contains dialectal %s synonyms for {{m|%s|%s}}."):format(langname, lang_code, term)
end
end,
},
}


function export.show(frame)
function envFuncs.title()
local params = {
-- The title object for the current page, or a test page passed with args.page.
["hr"] = {},
local title
["for"] = {},
local titleArg = args.page
["from"] = {},
if titleArg then
["notsubpage"] = { type = "boolean", default = false },
title = mw.title.new(titleArg)
["nodoc"] = { type = "boolean", default = false },
else
["nolinks"] = { type = "boolean", default = false }, -- suppress all "Useful links"
title = mw.title.getCurrentTitle()
}
end
return title
local args = require("Module:parameters").process(frame.args, params)
local output = Array('\n<div class="documentation" style="display:block; clear:both">\n')
local cats = Array()
local nodoc = args.nodoc
if (not args.hr) or (args.hr == "above") then
output:insert("----\n")
end
end
 
local title = args["for"] and mw.title.new(args["for"]) or mw.title.getCurrentTitle()
function envFuncs.templateTitle()
local doc_title = args.from ~= "-" and mw.title.new(args.from or title.fullText .. '/documentation') or nil
--[[
local contentModel = title.contentModel
-- The template (or module, etc.) title object.
-- Messages:
local pagetype = mw.getContentLanguage():lcfirst(title.nsText) .. " page"
-- 'sandbox-subpage' --> 'sandbox'
local preload, fallback_docs, doc_content, old_doc_title, user_name, skin_name, needs_doc
-- 'testcases-subpage' --> 'testcases'
local doc_content_source = "Module:documentation"
--]]
local auto_generated_cat_source
local subjectSpace = env.subjectSpace
local cats_auto_generated = false
local title = env.title
local subpage = title.subpageText
if contentModel == "javascript" then
if subpage == message('sandbox-subpage') or subpage == message('testcases-subpage') then
pagetype = "script"
return mw.title.makeTitle(subjectSpace, title.baseText)
if title.nsText == 'MediaWiki' then
if title.text:find('Gadget-') then
preload = 'Template:documentation/preloadGadget'
else
preload = 'Template:documentation/preloadMediaWikiJavaScript'
end
else
else
preload  = 'Template:documentation/preloadTemplate' -- XXX
return mw.title.makeTitle(subjectSpace, title.text)
end
end
if title.nsText == 'User' then
end
user_name = title.rootText
 
end
function envFuncs.docTitle()
elseif contentModel == "css" then
--[[
pagetype = "style sheet"
-- Title object of the /doc subpage.
preload  = 'Template:documentation/preloadTemplate' -- XXX
-- Messages:
if title.nsText == 'User' then
-- 'doc-subpage' --> 'doc'
user_name = title.rootText
--]]
end
local title = env.title
elseif contentModel == "Scribunto" then
local docname = args[1] -- User-specified doc page.
pagetype = "module"
local docpage
user_name = title.rootText:match("^[Uu]ser:(.+)")
if docname then
if user_name then
docpage = docname
preload  = 'Template:documentation/preloadModuleSandbox'
else
else
preload  = 'Template:documentation/preloadModule'
docpage = env.docpageBase .. '/' .. message('doc-subpage')
end
end
elseif title.nsText == "Template" then
return mw.title.new(docpage)
pagetype = "template"
end
preload  = 'Template:documentation/preloadTemplate'
elseif title.nsText == "Wiktionary" then
function envFuncs.sandboxTitle()
pagetype = "project page"
--[[
preload  = 'Template:documentation/preloadTemplate' -- XXX
-- Title object for the /sandbox subpage.
-- Messages:
-- 'sandbox-subpage' --> 'sandbox'
--]]
return mw.title.new(env.docpageBase .. '/' .. message('sandbox-subpage'))
end
end
if doc_title and doc_title.isRedirect then
function envFuncs.testcasesTitle()
old_doc_title = doc_title
--[[
doc_title = mw.title.new(string.match(doc_title:getContent(),
-- Title object for the /testcases subpage.
"^#[Rr][Ee][Dd][Ii][Rr][Ee][Cc][Tt]%s*:?%s*%[%[([^%[%]]-)%]%]"))
-- Messages:
-- 'testcases-subpage' --> 'testcases'
--]]
return mw.title.new(env.docpageBase .. '/' .. message('testcases-subpage'))
end
 
function envFuncs.protectionLevels()
-- The protection levels table of the title object.
return env.title.protectionLevels
end
end


output:insert("<dl class=\"plainlinks\" style=\"font-size: smaller;\">")
function envFuncs.subjectSpace()
-- The subject namespace number.
return mw.site.namespaces[env.title.namespace].subject.id
end


local function get_module_doc_and_cats(categories_only)
function envFuncs.docSpace()
cats_auto_generated = true
-- The documentation namespace number. For most namespaces this is the
local automatic_cats = nil
-- same as the subject namespace. However, pages in the Article, File,
if user_name then
-- MediaWiki or Category namespaces must have their /doc, /sandbox and
fallback_docs = "documentation/fallback/user module"
-- /testcases pages in talk space.
automatic_cats = {"User sandbox modules"}
local subjectSpace = env.subjectSpace
if subjectSpace == 0 or subjectSpace == 6 or subjectSpace == 8 or subjectSpace == 14 then
return subjectSpace + 1
else
else
for _, data in ipairs(module_regex) do
return subjectSpace
local captures = {mw.ustring.match(title.fullText, data.regex)}
end
if #captures > 0 then
end
local cat
local process_function
if type(data.process) == "function" then
process_function = data.process
elseif type(data.process) == "string" then
doc_content_source = "Module:documentation/functions/" .. data.process
process_function = require(doc_content_source)
end


if process_function then
function envFuncs.docpageBase()
doc_content = process_function(title, cats, unpack(captures))
-- The base page of the /doc, /sandbox, and /testcases subpages.
end
-- For some namespaces this is the talk page, rather than the template page.
if type(doc_content) == "table" then
local templateTitle = env.templateTitle
doc_content_source = doc_content.title and "Template:" .. doc_content.title or doc_content_source
local docSpace = env.docSpace
doc_content = mw.getCurrentFrame():expandTemplate(doc_content)
local docSpaceText = mw.site.namespaces[docSpace].name
elseif doc_content and doc_content:find("{{") then
-- Assemble the link. docSpace is never the main namespace, so we can hardcode the colon.
doc_content = mw.getCurrentFrame():preprocess(doc_content)
return docSpaceText .. ':' .. templateTitle.text
end
end
cat = data.cat
function envFuncs.compareUrl()
if cat then
-- Diff link between the sandbox and the main template using [[Special:ComparePages]].
if type(cat) == "string" then
local templateTitle = env.templateTitle
cat = {cat}
local sandboxTitle = env.sandboxTitle
end
if templateTitle.exists and sandboxTitle.exists then
for _, c in ipairs(cat) do
local compareUrl = mw.uri.canonicalUrl(
-- gsub() and Lua :gsub() return two arguments, which causes all sorts of problems.
'Special:ComparePages',
-- Terrible design, there should have been a separate two-argument function.
{ page1 = templateTitle.prefixedText, page2 = sandboxTitle.prefixedText}
local gsub_sucks = mw.ustring.gsub(title.fullText, data.regex, c)
)
table.insert(cats, gsub_sucks)
return tostring(compareUrl)
end
else
end
return nil
break
end
end
end
end
end
return env
end


if title.subpageText == "templates" then
----------------------------------------------------------------------------
cats:insert("Template interface modules")
-- Auxiliary templates
end
----------------------------------------------------------------------------


if automatic_cats then
p.getModuleWikitext = makeInvokeFunc('_getModuleWikitext')
for _, c in ipairs(automatic_cats) do
cats:insert(c)
end
end
if #cats == 0 then
local auto_cats = require("Module:module categorization").categorize(frame, "return raw", "noerror")
if #auto_cats > 0 then
auto_generated_cat_source = "Module:module categorization"
end
for _, category in ipairs(auto_cats) do
cats:insert(category)
end
end


-- meaning module is not in user’s sandbox or one of many datamodule boring series
function p._getModuleWikitext(args, env)
needs_doc = not categories_only and not (automatic_cats or doc_content or fallback_docs)
local currentTitle = mw.title.getCurrentTitle()
if currentTitle.contentModel ~= 'Scribunto' then return end
pcall(require, currentTitle.prefixedText) -- if it fails, we don't care
local moduleWikitext =  package.loaded["Module:Module wikitext"]
if moduleWikitext then
return moduleWikitext.main()
end
end
end


-- Override automatic documentation, if present.
function p.sandboxNotice(args, env)
if doc_title and doc_title.exists then
--[=[
local cats_auto_generated_text = ""
-- Generates a sandbox notice for display above sandbox pages.
if contentModel == "Scribunto" then
-- @args - a table of arguments passed by the user
local doc_page_content = doc_title:getContent()
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
if doc_page_content and doc_page_content:find("< *includeonly *>") then
--
track("module-includeonly")
-- Messages:
elseif doc_page_content and doc_page_content:find("{{module cat") then
-- 'sandbox-notice-image' --> '[[File:Sandbox.svg|50px|alt=|link=]]'
-- do nothing
-- 'sandbox-notice-blurb' --> 'This is the $1 for $2.'
else
-- 'sandbox-notice-diff-blurb' --> 'This is the $1 for $2 ($3).'
get_module_doc_and_cats("categories only")
-- 'sandbox-notice-pagetype-template' --> '[[Wikipedia:Template test cases|template sandbox]] page'
auto_generated_cat_source = auto_generated_cat_source or doc_content_source
-- 'sandbox-notice-pagetype-module' --> '[[Wikipedia:Template test cases|module sandbox]] page'
cats_auto_generated_text = " Categories were auto-generated by [[" .. auto_generated_cat_source .. "]]. <sup>[[" ..
-- 'sandbox-notice-pagetype-other' --> 'sandbox page'
mw.title.new(auto_generated_cat_source):fullUrl { action = "edit" } .. " edit]]</sup>"
-- 'sandbox-notice-compare-link-display' --> 'diff'
end
-- 'sandbox-notice-testcases-blurb' --> 'See also the companion subpage for $1.'
end
-- 'sandbox-notice-testcases-link-display' --> 'test cases'
 
-- 'sandbox-category' --> 'Template sandboxes'
output:insert(
-- 'module-sandbox-category' --> 'Module sandboxes'
"<dd><i style=\"font-size: larger;\">The following " ..
-- 'other-sandbox-category' --> 'Sandboxes outside of template or module namespace'
"[[Help:Documenting templates and modules|documentation]] is located at [[" ..
--]=]
doc_title.fullText .. "]]. " .. "<sup>[[" .. doc_title:fullUrl { action = "edit" } .. " edit]]</sup>" ..
local title = env.title
cats_auto_generated_text .. "</i></dd>")
local sandboxTitle = env.sandboxTitle
local templateTitle = env.templateTitle
local subjectSpace = env.subjectSpace
if not (subjectSpace and title and sandboxTitle and templateTitle
and mw.title.equals(title, sandboxTitle)) then
return nil
end
-- Build the table of arguments to pass to {{ombox}}. We need just two fields, "image" and "text".
local omargs = {}
omargs.image = message('sandbox-notice-image')
-- Get the text. We start with the opening blurb, which is something like
-- "This is the template sandbox for [[Template:Foo]] (diff)."
local text = ''
local pagetype, sandboxCat
if subjectSpace == 10 then
pagetype = message('sandbox-notice-pagetype-template')
sandboxCat = message('sandbox-category')
elseif subjectSpace == 828 then
pagetype = message('sandbox-notice-pagetype-module')
sandboxCat = message('module-sandbox-category')
else
pagetype = message('sandbox-notice-pagetype-other')
sandboxCat = message('other-sandbox-category')
end
local templateLink = makeWikilink(templateTitle.prefixedText)
local compareUrl = env.compareUrl
if compareUrl then
local compareDisplay = message('sandbox-notice-compare-link-display')
local compareLink = makeUrlLink(compareUrl, compareDisplay)
text = text .. message('sandbox-notice-diff-blurb', {pagetype, templateLink, compareLink})
else
else
if contentModel == "Scribunto" then
text = text .. message('sandbox-notice-blurb', {pagetype, templateLink})
get_module_doc_and_cats(false)
end
elseif title.nsText == "Template" then
-- Get the test cases page blurb if the page exists. This is something like
--cats:insert("Uncategorized templates")
-- "See also the companion subpage for [[Template:Foo/testcases|test cases]]."
needs_doc = not (fallback_docs or nodoc)
local testcasesTitle = env.testcasesTitle
elseif (contentModel == "css") or (contentModel == "javascript") then
if testcasesTitle and testcasesTitle.exists then
if user_name then
if testcasesTitle.contentModel == "Scribunto" then
skin_name = skins[title.text:sub(#title.rootText + 1):match("^/([a-z]+)%.[jc]ss?$")]
local testcasesLinkDisplay = message('sandbox-notice-testcases-link-display')
if skin_name then
local testcasesRunLinkDisplay = message('sandbox-notice-testcases-run-link-display')
fallback_docs = "documentation/fallback/user " .. contentModel
local testcasesLink = makeWikilink(testcasesTitle.prefixedText, testcasesLinkDisplay)
end
local testcasesRunLink = makeWikilink(testcasesTitle.talkPageTitle.prefixedText, testcasesRunLinkDisplay)
end
text = text .. '<br />' .. message('sandbox-notice-testcases-run-blurb', {testcasesLink, testcasesRunLink})
end
else
local testcasesLinkDisplay = message('sandbox-notice-testcases-link-display')
if doc_content then
local testcasesLink = makeWikilink(testcasesTitle.prefixedText, testcasesLinkDisplay)
output:insert(
text = text .. '<br />' .. message('sandbox-notice-testcases-blurb', {testcasesLink})
"<dd><i style=\"font-size: larger;\">The following " ..
"[[Help:Documenting templates and modules|documentation]] is " ..
"generated by [[" .. doc_content_source .. "]]. <sup>[[" ..
mw.title.new(doc_content_source):fullUrl { action = 'edit' } ..
" edit]]</sup> </i></dd>")
elseif not nodoc then
if doc_title then
output:insert(
"<dd><i style=\"font-size: larger;\">This " .. pagetype ..
" lacks a [[Help:Documenting templates and modules|documentation subpage]]. " ..
(fallback_docs and "You may " or "Please ") ..
"[" .. doc_title:fullUrl { action = 'edit', preload = preload }
.. " create it].</i></dd>\n")
else
output:insert(
"<dd><i style=\"font-size: larger; color: #FF0000;\">Unable to auto-generate " ..
"documentation for this " .. pagetype ..".</i></dd>\n")
end
end
end
end
end
if title.fullText:match("^MediaWiki:Gadget%-") then
-- Add the sandbox to the sandbox category.
local is_gadget = false
omargs.text = text .. makeCategoryLink(sandboxCat)
local gadget_list = mw.title.new("MediaWiki:Gadgets-definition"):getContent()
for line in mw.text.gsplit(gadget_list, "\n") do
local gadget, opts, items = line:match("^%*%s*([A-Za-z][A-Za-z0-9_%-]*)%[(.-)%]|(.+)$") -- opts is unused
if not gadget then
gadget, items = line:match("^%*%s*([A-Za-z][A-Za-z0-9_%-]*)|(.+)$")
end
if gadget then
items = Array(mw.text.split(items, "|"))
for i, item in ipairs(items) do
if title.fullText == ("MediaWiki:Gadget-" .. item) then
is_gadget = true


output:insert("<dd> ''This script is a part of the <code>")
-- 'documentation-clear'
output:insert(gadget)
return '<div class="' .. message('clear') .. '"></div>'
output:insert("</code> gadget ([")
.. require('Module:Message box').main('ombox', omargs)
output:insert(tostring(mw.uri.fullUrl('MediaWiki:Gadgets-definition', 'action=edit')))
end
output:insert(" edit definitions])'' <dl>")
output:insert("<dd> ''Description ([")
output:insert(tostring(mw.uri.fullUrl('MediaWiki:Gadget-' .. gadget, 'action=edit')))
output:insert(" edit])'': ")
local gadget_description = mw.message.new('Gadget-' .. gadget):plain()
gadget_description = frame:preprocess(gadget_description)
output:insert(gadget_description)
output:insert(" </dd>")


items:remove(i)
function p.protectionTemplate(env)
if #items > 0 then
-- Generates the padlock icon in the top right.
for j, item in ipairs(items) do
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
items[j] = '[[MediaWiki:Gadget-' .. item .. '|' .. item .. ']]'
-- Messages:
end
-- 'protection-template' --> 'pp-template'
output:insert("<dd> ''Other parts'': ")
-- 'protection-template-args' --> {docusage = 'yes'}
output:insert(mw.text.listToText(items))
local protectionLevels = env.protectionLevels
output:insert("</dd>")
if not protectionLevels then
end
return nil
end
local editProt = protectionLevels.edit and protectionLevels.edit[1]
local moveProt = protectionLevels.move and protectionLevels.move[1]
if editProt then
-- The page is edit-protected.
return require('Module:Protection banner')._main{
message('protection-reason-edit'), small = true
}
elseif moveProt and moveProt ~= 'autoconfirmed' then
-- The page is move-protected but not edit-protected. Exclude move
-- protection with the level "autoconfirmed", as this is equivalent to
-- no move protection at all.
return require('Module:Protection banner')._main{
action = 'move', small = true
}
else
return nil
end
end


output:insert("</dl></dd>")
----------------------------------------------------------------------------
-- Start box
----------------------------------------------------------------------------


break
p.startBox = makeInvokeFunc('_startBox')
end
 
end
function p._startBox(args, env)
end
--[[
end
-- This function generates the start box.
-- @args - a table of arguments passed by the user
if not is_gadget then
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
output:insert("<dd> ''This script is not a part of any [")
--
output:insert(tostring(mw.uri.fullUrl('Special:Gadgets', 'uselang=en')))
-- The actual work is done by p.makeStartBoxLinksData and p.renderStartBoxLinks which make
output:insert(' gadget] ([')
-- the [view] [edit] [history] [purge] links, and by p.makeStartBoxData and p.renderStartBox
output:insert(tostring(mw.uri.fullUrl('MediaWiki:Gadgets-definition', 'action=edit')))
-- which generate the box HTML.
output:insert(' edit definitions]).</dd>')
--]]
-- else
env = env or p.getEnvironment(args)
-- cats:insert("Wiktionary gadgets")
local links
local content = args.content
if not content or args[1] then
-- No need to include the links if the documentation is on the template page itself.
local linksData = p.makeStartBoxLinksData(args, env)
if linksData then
links = p.renderStartBoxLinks(linksData)
end
end
end
end
-- Generate the start box html.
if old_doc_title then
local data = p.makeStartBoxData(args, env, links)
output:insert("<dd> ''Redirected from'' [")
if data then
output:insert(old_doc_title:fullUrl { redirect = 'no' })
return p.renderStartBox(data)
output:insert(" ")
else
output:insert(old_doc_title.fullText)
-- User specified no heading.
output:insert("] ([")
return nil
output:insert(old_doc_title:fullUrl { action = 'edit' })
end
output:insert(" edit]).</dd>\n")
end
 
function p.makeStartBoxLinksData(args, env)
--[[
-- Does initial processing of data to make the [view] [edit] [history] [purge] links.
-- @args - a table of arguments passed by the user
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
--
-- Messages:
-- 'view-link-display' --> 'view'
-- 'edit-link-display' --> 'edit'
-- 'history-link-display' --> 'history'
-- 'purge-link-display' --> 'purge'
-- 'module-preload' --> 'Template:Documentation/preload-module-doc'
-- 'docpage-preload' --> 'Template:Documentation/preload'
-- 'create-link-display' --> 'create'
--]]
local subjectSpace = env.subjectSpace
local title = env.title
local docTitle = env.docTitle
if not title or not docTitle then
return nil
end
if docTitle.isRedirect then
docTitle = docTitle.redirectTarget
end
end
if not args.nolinks then
local links = Array()


if title.isSubpage and not args.notsubpage then
-- Create link if /doc doesn't exist.
links:insert("[[:" .. title.nsText .. ":" .. title.rootText .. "|root page]]")
local preload = args.preload
links:insert("[[Special:PrefixIndex/" .. title.nsText .. ":" .. title.rootText .. "/|root page’s subpages]]")
if not preload then
else
if subjectSpace == 828 then -- Module namespace
links:insert("[[Special:PrefixIndex/" .. title.fullText .. "/|subpage list]]")
preload = message('module-preload')
end
links:insert(
'[' .. tostring(mw.uri.fullUrl('Special:WhatLinksHere/' .. title.fullText,
'hidetrans=1&hideredirs=1')) .. ' links]')
if contentModel ~= "Scribunto" then
links:insert(
'[' .. tostring(mw.uri.fullUrl('Special:WhatLinksHere/' .. title.fullText,
'hidelinks=1&hidetrans=1')) .. ' redirects]')
end
if (contentModel == "javascript") or (contentModel == "css") then
if user_name then
links:insert("[[Special:MyPage" .. title.text:sub(#title.rootText + 1) .. "|your own]]")
end
else
else
links:insert(
preload = message('docpage-preload')
'[' .. tostring(mw.uri.fullUrl('Special:WhatLinksHere/' .. title.fullText,
'hidelinks=1&hideredirs=1')) .. ' transclusions]')
end
if contentModel == "Scribunto" then
local is_testcases = title.isSubpage and title.subpageText == "testcases"
local without_subpage = title.nsText .. ":" .. title.baseText
if is_testcases then
links:insert("[[:" .. without_subpage .. "|tested module]]")
else
links:insert("[[" .. title.fullText .. "/testcases|testcases]]")
end
if user_name then
links:insert("[[User:" .. user_name .. "|user page]]")
links:insert("[[User talk:" .. user_name .. "|user talk page]]")
links:insert("[[Special:PrefixIndex/User:" .. user_name .. "/|userspace]]")
else
-- If sandbox module, add a link to the module that this is a sandbox of.
-- Exclude user sandbox modules like [[User:Dine2016/sandbox]].
if title.text:find("/sandbox%d*%f[/%z]") then
cats:insert("Sandbox modules")
-- Sandbox modules don’t really need documentation.
needs_doc = false
-- Will behave badly if “/sandbox” occurs twice in title!
local sandbox_of = title.fullText:gsub("/sandbox%d*%f[/%z]", "")
local diff
if page_exists(sandbox_of) then
diff = " (" .. compare_pages(title.fullText, sandbox_of, "diff") .. ")"
else
track("no sandbox of")
end
links:insert("[[:" .. sandbox_of .. "|sandbox of]]" .. (diff or ""))
-- If not a sandbox module, add link to sandbox module.
-- Sometimes there are multiple sandboxes for a single module:
-- [[Module:sa-pronunc/sandbox]],  [[Module:sa-pronunc/sandbox2]].
-- Occasionally sandbox modules have their own subpages that are also
-- sandboxes: [[Module:grc-decl/sandbox/decl]].
else
local sandbox_title
if title.fullText:find("^Module:grc%-decl/") then
sandbox_title = title.fullText:gsub("^Module:grc%-decl/", "Module:grc-decl/sandbox/")
elseif is_testcases then
sandbox_title = title.fullText:gsub("/testcases", "/sandbox/testcases")
else
sandbox_title = title.fullText .. "/sandbox"
end
local sandbox_link = "[[:" .. sandbox_title .. "|sandbox]]"
local diff
if page_exists(sandbox_title) then
diff = " (" .. compare_pages(title.fullText, sandbox_title, "diff") .. ")"
end
links:insert(sandbox_link .. (diff or ""))
end
end
end
if title.nsText == "Template" then
-- Error search: all(any namespace), hastemplate (show pages using the template), insource (show source code), incategory (any/specific error) -- [[mw:Help:CirrusSearch]], [[w:Help:Searching/Regex]]
-- apparently same with/without: &profile=advanced&fulltext=1
local errorq = 'searchengineselect=mediawiki&search=all: hastemplate:\"'..title.rootText..'\" insource:\"'..title.rootText..'\" incategory:'
local eincategory = "Pages_with_module_errors|ParserFunction_errors|DisplayTitle_errors|Pages_with_ISBN_errors|Pages_with_ISSN_errors|Pages_with_reference_errors|Pages_with_syntax_highlighting_errors|Pages_with_TemplateStyles_errors"
links:insert(
'[' .. tostring(mw.uri.fullUrl('Special:Search', errorq..eincategory )) .. ' errors]'
.. ' (' ..
'[' .. tostring(mw.uri.fullUrl('Special:Search', errorq..'ParserFunction_errors' )) .. ' parser]'
.. '/' ..
'[' .. tostring(mw.uri.fullUrl('Special:Search', errorq..'Pages_with_module_errors' )) .. ' module]'
.. ')'
)
if title.isSubpage and title.text:find("/sandbox%d*%f[/%z]") then -- This is a sandbox template.
-- At the moment there are no user sandbox templates with subpage
-- “/sandbox”.
cats:insert("Sandbox templates")
-- Sandbox templates don’t really need documentation.
needs_doc = false
-- Will behave badly if “/sandbox” occurs twice in title!
local sandbox_of = title.fullText:gsub("/sandbox%d*%f[/%z]", "")
local diff
if page_exists(sandbox_of) then
diff = " (" .. compare_pages(title.fullText, sandbox_of, "diff") .. ")"
else
track("no sandbox of")
end
links:insert("[[:" .. sandbox_of .. "|sandbox of]]" .. (diff or ""))
else -- This is a template that can have a sandbox.
local sandbox_title = title.fullText .. "/sandbox"
local diff
if page_exists(sandbox_title) then
diff = " (" .. compare_pages(title.fullText, sandbox_title, "diff") .. ")"
end
links:insert("[[:" .. sandbox_title .. "|sandbox]]" .. (diff or ""))
end
end
if #links > 0 then
output:insert("<dd> ''Useful links'': " .. links:concat(" • ") .. "</dd>")
end
end
end
end
output:insert("</dl>\n")
return {
title = title,
docTitle = docTitle,
-- View, display, edit, and purge links if /doc exists.
viewLinkDisplay = message('view-link-display'),
editLinkDisplay = message('edit-link-display'),
historyLinkDisplay = message('history-link-display'),
purgeLinkDisplay = message('purge-link-display'),
preload = preload,
createLinkDisplay = message('create-link-display')
}
end
 
function p.renderStartBoxLinks(data)
--[[
-- Generates the [view][edit][history][purge] or [create][purge] links from the data table.
-- @data - a table of data generated by p.makeStartBoxLinksData
--]]
local docTitle = data.docTitle
-- yes, we do intend to purge the template page on which the documentation appears
local purgeLink = makeWikilink("Special:Purge/" .. data.title.prefixedText, data.purgeLinkDisplay)
-- Show error from [[Module:category tree/topic cat/data]] on its submodules'
if docTitle.exists then
-- documentation to, for instance, warn about duplicate labels.
local viewLink = makeWikilink(docTitle.prefixedText, data.viewLinkDisplay)
if title.fullText:find("Module:category tree/topic cat/data", 1, true) == 1 then
local editLink = makeWikilink("Special:EditPage/" .. docTitle.prefixedText, data.editLinkDisplay)
local ok, err = pcall(require, "Module:category tree/topic cat/data")
local historyLink = makeWikilink("Special:PageHistory/" .. docTitle.prefixedText, data.historyLinkDisplay)
if not ok then
return "&#91;" .. viewLink .. "&#93; &#91;" .. editLink .. "&#93; &#91;" .. historyLink .. "&#93; &#91;" .. purgeLink .. "&#93;"
output:insert('<span class="error">' .. err .. '</span>\n\n')
else
end
local createLink = makeUrlLink(docTitle:canonicalUrl{action = 'edit', preload = data.preload}, data.createLinkDisplay)
end
return  "&#91;" .. createLink .. "&#93; &#91;" .. purgeLink .. "&#93;"
if doc_title and doc_title.exists then
-- Override automatic documentation, if present.
doc_content = frame:expandTemplate { title = doc_title.fullText }
elseif not doc_content and fallback_docs then
doc_content = frame:expandTemplate {
title = fallback_docs,
args = {
['user'] = user_name,
['page'] = title.fullText,
['skin name'] = skin_name,
},
}
end
end
return ret
end


if doc_content then
function p.makeStartBoxData(args, env, links)
output:insert(doc_content)
--[=[
-- Does initial processing of data to pass to the start-box render function, p.renderStartBox.
-- @args - a table of arguments passed by the user
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
-- @links - a string containing the [view][edit][history][purge] links - could be nil if there's an error.
--
-- Messages:
-- 'documentation-icon-wikitext' --> '[[File:Test Template Info-Icon - Version (2).svg|50px|link=|alt=]]'
-- 'template-namespace-heading' --> 'Template documentation'
-- 'module-namespace-heading' --> 'Module documentation'
-- 'file-namespace-heading' --> 'Summary'
-- 'other-namespaces-heading' --> 'Documentation'
-- 'testcases-create-link-display' --> 'create'
--]=]
local subjectSpace = env.subjectSpace
if not subjectSpace then
-- Default to an "other namespaces" namespace, so that we get at least some output
-- if an error occurs.
subjectSpace = 2
end
end
 
local data = {}
output:insert(('\n<%s style="clear: both;" />'):format(args.hr == "below" and "hr" or "br"))
if cats_auto_generated and not cats[1] and (not doc_content or not doc_content:find("%[%[Category:")) then
-- Heading
if contentModel == "Scribunto" then
local heading = args.heading -- Blank values are not removed.
cats:insert("Uncategorized modules")
if heading == '' then
-- elseif title.nsText == "Template" then
-- Don't display the start box if the heading arg is defined but blank.
-- cats:insert("Uncategorized templates")
return nil
end
end
if heading then
data.heading = heading
elseif subjectSpace == 10 then -- Template namespace
data.heading = message('documentation-icon-wikitext') .. ' ' .. message('template-namespace-heading')
elseif subjectSpace == 828 then -- Module namespace
data.heading = message('documentation-icon-wikitext') .. ' ' .. message('module-namespace-heading')
elseif subjectSpace == 6 then -- File namespace
data.heading = message('file-namespace-heading')
else
data.heading = message('other-namespaces-heading')
end
end
if needs_doc then
-- Heading CSS
cats:insert("Templates and modules needing documentation")
local headingStyle = args['heading-style']
if headingStyle then
data.headingStyleText = headingStyle
else
-- 'documentation-heading'
data.headingClass = message('main-div-heading-class')
end
end
for _, cat in ipairs(cats) do
-- Data for the [view][edit][history][purge] or [create] links.
output:insert("[[Category:" .. cat .. "]]")
if links then
-- 'mw-editsection-like plainlinks'
data.linksClass = message('start-box-link-classes')
data.links = links
end
end
output:insert("</div>\n")
return data
end


return output:concat()
function p.renderStartBox(data)
-- Renders the start box html.
-- @data - a table of data generated by p.makeStartBoxData.
local sbox = mw.html.create('div')
sbox
-- 'documentation-startbox'
:addClass(message('start-box-class'))
:newline()
:tag('span')
:addClass(data.headingClass)
:attr('id', 'documentation-heading')
:cssText(data.headingStyleText)
:wikitext(data.heading)
local links = data.links
if links then
sbox:tag('span')
:addClass(data.linksClass)
:attr('id', data.linksId)
:wikitext(links)
end
return tostring(sbox)
end
end


function export.module_auto_doc_table()
----------------------------------------------------------------------------
local parts = {}
-- Documentation content
local function ins(text)
----------------------------------------------------------------------------
table.insert(parts, text)
 
p.content = makeInvokeFunc('_content')
 
function p._content(args, env)
-- Displays the documentation contents
-- @args - a table of arguments passed by the user
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
env = env or p.getEnvironment(args)
local docTitle = env.docTitle
local content = args.content
if not content and docTitle and docTitle.exists then
content = args._content or mw.getCurrentFrame():expandTemplate{title = docTitle.prefixedText}
end
end
ins('{|class="wikitable"')
-- The line breaks below are necessary so that "=== Headings ===" at the start and end
ins("! Regex !! Category !! Handling modules")
-- of docs are interpreted correctly.
for _, spec in ipairs(module_regex) do
return '\n' .. (content or '') .. '\n'
local cat_text
end
local cats = spec.cat
 
if cats then
p.contentTitle = makeInvokeFunc('_contentTitle')
local cat_parts = {}
 
if type(cats) == "string" then
function p._contentTitle(args, env)
cats = {cats}
env = env or p.getEnvironment(args)
end
local docTitle = env.docTitle
for _, cat in ipairs(cats) do
if not args.content and docTitle and docTitle.exists then
table.insert(cat_parts, ("<code>%s</code>"):format((cat:gsub("|", "&#124;"))))
return docTitle.prefixedText
end
else
cat_text = table.concat(cat_parts, ", ")
return ''
else
cat_text = "''(unspecified)''"
end
ins("|-")
ins(("| <code>%s</code> || %s || %s"):format(spec.regex, cat_text,
type(spec.process) == "function" and "''(handled internally)''" or
type(spec.process) == "string" and ("[[Module:documentation/functions/%s]]"):format(spec.process) or
"''(no documentation generator)''"))
end
end
ins("|}")
return table.concat(parts, "\n")
end
end


-- Used by {{translit module documentation}}.
----------------------------------------------------------------------------
function export.translitModuleLangList(frame)
-- End box
local pagename, subpage
----------------------------------------------------------------------------
 
p.endBox = makeInvokeFunc('_endBox')
 
function p._endBox(args, env)
--[=[
-- This function generates the end box (also known as the link box).
-- @args - a table of arguments passed by the user
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
--
--]=]
if frame.args[1] then
-- Get environment data.
pagename = frame.args[1]
env = env or p.getEnvironment(args)
else
local subjectSpace = env.subjectSpace
local title = mw.title.getCurrentTitle()
local docTitle = env.docTitle
subpage = title.subpageText
if not subjectSpace or not docTitle then
pagename = title.text
return nil
if subpage ~= pagename then
pagename = title.rootText
end
end
end
local translitModule = pagename
local languageObjects = require("Module:languages/byTranslitModule")(translitModule)
local codeInPagename = pagename:match("^([%l-]+)%-.*translit$")
local categories = Array()
local codeInPagenameInList = false
if codeInPagename then
if languageObjects[1] and subpage ~= "documentation" then
local agreement = languageObjects[2] and "s" or ""
categories:insert("[[Category:Transliteration modules used by " ..
#languageObjects .. " language" .. agreement .. "]]")
end
languageObjects = Array(languageObjects)
-- Check whether we should output the end box at all. Add the end
:filter(
-- box by default if the documentation exists or if we are in the
function (lang)
-- user, module or template namespaces.
local result = lang:getCode() ~= codeInPagename
local linkBox = args['link box']
codeInPagenameInList = codeInPagenameInList or result
if linkBox == 'off'
return result
or not (
end)
docTitle.exists
or subjectSpace == 2
or subjectSpace == 828
or subjectSpace == 10
)
then
return nil
end
end
 
if subpage ~= "documentation" then
-- Assemble the link box.
for script_code in pagename:gmatch("%f[^-%z]%u%l%l%l%f[-]") do
local text = ''
local script = require "Module:scripts".getByCode(script_code)
if linkBox then
if script then
text = text .. linkBox
categories:insert("[[Category:" .. script:getCategoryName() .. "]]")
else
text = text .. (p.makeDocPageBlurb(args, env) or '') -- "This documentation is transcluded from [[Foo]]."  
if subjectSpace == 2 or subjectSpace == 10 or subjectSpace == 828 then
-- We are in the user, template or module namespaces.
-- Add sandbox and testcases links.
-- "Editors can experiment in this template's sandbox and testcases pages."
text = text .. (p.makeExperimentBlurb(args, env) or '') .. '<br />'
if not args.content and not args[1] then
-- "Please add categories to the /doc subpage."
-- Don't show this message with inline docs or with an explicitly specified doc page,
-- as then it is unclear where to add the categories.
text = text .. (p.makeCategoriesBlurb(args, env) or '')
end
end
text = text .. ' ' .. (p.makeSubpagesBlurb(args, env) or '') --"Subpages of this template"
end
end
end
end
if subpage ~= "documentation" and not page_exists("Module:" .. pagename .. "/testcases") then
local box = mw.html.create('div')
categories:insert("[[Category:Transliteration modules without a testcases subpage]]")
-- 'documentation-metadata'
box:attr('role', 'note')
:addClass(message('end-box-class'))
-- 'plainlinks'
:addClass(message('end-box-plainlinks'))
:wikitext(text)
:done()
 
return '\n' .. tostring(box)
end
 
function p.makeDocPageBlurb(args, env)
--[=[
-- Makes the blurb "This documentation is transcluded from [[Template:Foo]] (edit, history)".
-- @args - a table of arguments passed by the user
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
--
-- Messages:
-- 'edit-link-display' --> 'edit'
-- 'history-link-display' --> 'history'
-- 'transcluded-from-blurb' -->
-- 'The above [[Wikipedia:Template documentation|documentation]]
-- is [[Help:Transclusion|transcluded]] from $1.'
-- 'module-preload' --> 'Template:Documentation/preload-module-doc'
-- 'create-link-display' --> 'create'
-- 'create-module-doc-blurb' -->
-- 'You might want to $1 a documentation page for this [[Wikipedia:Lua|Scribunto module]].'
--]=]
local docTitle = env.docTitle
if not docTitle then
return nil
end
end
if docTitle.exists then
if not languageObjects[1] then
-- /doc exists; link to it.
return categories:concat()
local docLink = makeWikilink(docTitle.prefixedText)
local editDisplay = message('edit-link-display')
local editLink = makeWikilink("Special:EditPage/" .. docTitle.prefixedText, editDisplay)
local historyDisplay = message('history-link-display')
local historyLink = makeWikilink("Special:PageHistory/" .. docTitle.prefixedText, historyDisplay)
return message('transcluded-from-blurb', {docLink})
.. ' '
.. makeToolbar(editLink, historyLink)
.. '<br />'
elseif env.subjectSpace == 828 then
-- /doc does not exist; ask to create it.
local createUrl = docTitle:canonicalUrl{action = 'edit', preload = message('module-preload')}
local createDisplay = message('create-link-display')
local createLink = makeUrlLink(createUrl, createDisplay)
return message('create-module-doc-blurb', {createLink})
.. '<br />'
end
end
local langs = Array(languageObjects)
:sort(
function(lang1, lang2)
return lang1:getCode() < lang2:getCode()
end)
-- This will not error because languageObjects is not empty.
:map(languageObjects[1].makeCategoryLink)
:serial_comma_join()
return "It is " .. ( codeInPagenameInList and "also" or "" ) ..
" used to transliterate " .. langs .. "." .. categories:concat()
end
end


-- Used by {{entry name module documentation}}.
function p.makeExperimentBlurb(args, env)
function export.entryNameModuleLangList(frame)
--[[
local pagename, subpage
-- Renders the text "Editors can experiment in this template's sandbox (edit | diff) and testcases (edit) pages."
-- @args - a table of arguments passed by the user
if frame.args[1] then
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
pagename = frame.args[1]
--
-- Messages:
-- 'sandbox-link-display' --> 'sandbox'
-- 'sandbox-edit-link-display' --> 'edit'
-- 'compare-link-display' --> 'diff'
-- 'module-sandbox-preload' --> 'Template:Documentation/preload-module-sandbox'
-- 'template-sandbox-preload' --> 'Template:Documentation/preload-sandbox'
-- 'sandbox-create-link-display' --> 'create'
-- 'mirror-edit-summary' --> 'Create sandbox version of $1'
-- 'mirror-link-display' --> 'mirror'
-- 'mirror-link-preload' --> 'Template:Documentation/mirror'
-- 'sandbox-link-display' --> 'sandbox'
-- 'testcases-link-display' --> 'testcases'
-- 'testcases-edit-link-display'--> 'edit'
-- 'template-sandbox-preload' --> 'Template:Documentation/preload-sandbox'
-- 'testcases-create-link-display' --> 'create'
-- 'testcases-link-display' --> 'testcases'
-- 'testcases-edit-link-display' --> 'edit'
-- 'module-testcases-preload' --> 'Template:Documentation/preload-module-testcases'
-- 'template-testcases-preload' --> 'Template:Documentation/preload-testcases'
-- 'experiment-blurb-module' --> 'Editors can experiment in this module's $1 and $2 pages.'
-- 'experiment-blurb-template' --> 'Editors can experiment in this template's $1 and $2 pages.'
--]]
local subjectSpace = env.subjectSpace
local templateTitle = env.templateTitle
local sandboxTitle = env.sandboxTitle
local testcasesTitle = env.testcasesTitle
local templatePage = templateTitle.prefixedText
if not subjectSpace or not templateTitle or not sandboxTitle or not testcasesTitle then
return nil
end
-- Make links.
local sandboxLinks, testcasesLinks
if sandboxTitle.exists then
local sandboxPage = sandboxTitle.prefixedText
local sandboxDisplay = message('sandbox-link-display')
local sandboxLink = makeWikilink(sandboxPage, sandboxDisplay)
local sandboxEditDisplay = message('sandbox-edit-link-display')
local sandboxEditLink = makeWikilink("Special:EditPage/" .. sandboxPage, sandboxEditDisplay)
local compareUrl = env.compareUrl
local compareLink
if compareUrl then
local compareDisplay = message('compare-link-display')
compareLink = makeUrlLink(compareUrl, compareDisplay)
end
sandboxLinks = sandboxLink .. ' ' .. makeToolbar(sandboxEditLink, compareLink)
else
else
local title = mw.title.getCurrentTitle()
local sandboxPreload
subpage = title.subpageText
if subjectSpace == 828 then
pagename = title.text
sandboxPreload = message('module-sandbox-preload')
else
if subpage ~= pagename then
sandboxPreload = message('template-sandbox-preload')
pagename = title.rootText
end
local sandboxCreateUrl = sandboxTitle:canonicalUrl{action = 'edit', preload = sandboxPreload}
local sandboxCreateDisplay = message('sandbox-create-link-display')
local sandboxCreateLink = makeUrlLink(sandboxCreateUrl, sandboxCreateDisplay)
local mirrorSummary = message('mirror-edit-summary', {makeWikilink(templatePage)})
local mirrorPreload = message('mirror-link-preload')
local mirrorUrl = sandboxTitle:canonicalUrl{action = 'edit', preload = mirrorPreload, summary = mirrorSummary}
if subjectSpace == 828 then
mirrorUrl = sandboxTitle:canonicalUrl{action = 'edit', preload = templateTitle.prefixedText, summary = mirrorSummary}
end
end
local mirrorDisplay = message('mirror-link-display')
local mirrorLink = makeUrlLink(mirrorUrl, mirrorDisplay)
sandboxLinks = message('sandbox-link-display') .. ' ' .. makeToolbar(sandboxCreateLink, mirrorLink)
end
end
if testcasesTitle.exists then
local entryNameModule = pagename
local testcasesPage = testcasesTitle.prefixedText
local testcasesDisplay = message('testcases-link-display')
local languageObjects = require("Module:languages/byEntryNameModule")(entryNameModule)
local testcasesLink = makeWikilink(testcasesPage, testcasesDisplay)
local codeInPagename = pagename:match("^([%l-]+)%-.*entryname$")
local testcasesEditUrl = testcasesTitle:canonicalUrl{action = 'edit'}
local testcasesEditDisplay = message('testcases-edit-link-display')
local categories = Array()
local testcasesEditLink = makeWikilink("Special:EditPage/" .. testcasesPage, testcasesEditDisplay)
local codeInPagenameInList = false
-- for Modules, add testcases run link if exists
if codeInPagename then
if testcasesTitle.contentModel == "Scribunto" and testcasesTitle.talkPageTitle and testcasesTitle.talkPageTitle.exists then
if languageObjects[1] and subpage ~= "documentation" then
local testcasesRunLinkDisplay = message('testcases-run-link-display')
local agreement = languageObjects[2] and "s" or ""
local testcasesRunLink = makeWikilink(testcasesTitle.talkPageTitle.prefixedText, testcasesRunLinkDisplay)
categories:insert("[[Category:Entry name-generating modules used by " ..
testcasesLinks = testcasesLink .. ' ' .. makeToolbar(testcasesEditLink, testcasesRunLink)
#languageObjects .. " language" .. agreement .. "]]")
else
testcasesLinks = testcasesLink .. ' ' .. makeToolbar(testcasesEditLink)
end
end
else
languageObjects = Array(languageObjects)
local testcasesPreload
:filter(
if subjectSpace == 828 then
function (lang)
testcasesPreload = message('module-testcases-preload')
local result = lang:getCode() ~= codeInPagename
else
codeInPagenameInList = codeInPagenameInList or result
testcasesPreload = message('template-testcases-preload')
return result
end)
end
if subpage ~= "documentation" then
for script_code in pagename:gmatch("%f[^-%z]%u%l%l%l%f[-]") do
local script = require "Module:scripts".getByCode(script_code)
if script then
categories:insert("[[Category:" .. script:getCategoryName() .. "]]")
end
end
end
local testcasesCreateUrl = testcasesTitle:canonicalUrl{action = 'edit', preload = testcasesPreload}
local testcasesCreateDisplay = message('testcases-create-link-display')
local testcasesCreateLink = makeUrlLink(testcasesCreateUrl, testcasesCreateDisplay)
testcasesLinks = message('testcases-link-display') .. ' ' .. makeToolbar(testcasesCreateLink)
end
end
local messageName
if subpage ~= "documentation" and not page_exists("Module:" .. pagename .. "/testcases") then
if subjectSpace == 828 then
categories:insert("[[Category:Entry name-generating modules without a testcases subpage]]")
messageName = 'experiment-blurb-module'
else
messageName = 'experiment-blurb-template'
end
end
return message(messageName, {sandboxLinks, testcasesLinks})
if not languageObjects[1] then
end
return categories:concat()
 
function p.makeCategoriesBlurb(args, env)
--[[
-- Generates the text "Please add categories to the /doc subpage."
-- @args - a table of arguments passed by the user
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
-- Messages:
-- 'doc-link-display' --> '/doc'
-- 'add-categories-blurb' --> 'Please add categories to the $1 subpage.'
--]]
local docTitle = env.docTitle
if not docTitle then
return nil
end
end
local docPathLink = makeWikilink(docTitle.prefixedText, message('doc-link-display'))
local langs = Array(languageObjects)
return message('add-categories-blurb', {docPathLink})
:sort(
function(lang1, lang2)
return lang1:getCode() < lang2:getCode()
end)
-- This will not error because languageObjects is not empty.
:map(languageObjects[1].makeCategoryLink)
:serial_comma_join()
return "It is " .. ( codeInPagenameInList and "also" or "" ) ..
" used to generate entry names for " .. langs .. "." .. categories:concat()
end
end


-- Used by {{sortkey module documentation}}.
function p.makeSubpagesBlurb(args, env)
function export.sortkeyModuleLangList(frame)
--[[
local pagename, subpage
-- Generates the "Subpages of this template" link.
-- @args - a table of arguments passed by the user
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
if frame.args[1] then
-- Messages:
pagename = frame.args[1]
-- 'template-pagetype' --> 'template'
-- 'module-pagetype' --> 'module'
-- 'default-pagetype' --> 'page'
-- 'subpages-link-display' --> 'Subpages of this $1'
--]]
local subjectSpace = env.subjectSpace
local templateTitle = env.templateTitle
if not subjectSpace or not templateTitle then
return nil
end
local pagetype
if subjectSpace == 10 then
pagetype = message('template-pagetype')
elseif subjectSpace == 828 then
pagetype = message('module-pagetype')
else
else
local title = mw.title.getCurrentTitle()
pagetype = message('default-pagetype')
subpage = title.subpageText
pagename = title.text
if subpage ~= pagename then
pagename = title.rootText
end
end
end
local subpagesLink = makeWikilink(
'Special:PrefixIndex/' .. templateTitle.prefixedText .. '/',
message('subpages-link-display', {pagetype})
)
return message('subpages-blurb', {subpagesLink})
end
----------------------------------------------------------------------------
-- Tracking categories
----------------------------------------------------------------------------
function p.addTrackingCategories(env)
--[[
-- Check if {{documentation}} is transcluded on a /doc or /testcases page.
-- @env - environment table containing title objects, etc., generated with p.getEnvironment
local sortkeyModule = pagename
-- Messages:
-- 'display-strange-usage-category' --> true
local languageObjects = require("Module:languages/bySortkeyModule")(sortkeyModule)
-- 'doc-subpage' --> 'doc'
local codeInPagename = pagename:match("^([%l-]+)%-.*sortkey$")
-- 'testcases-subpage' --> 'testcases'
-- 'strange-usage-category' --> 'Wikipedia pages with strange ((documentation)) usage'
local categories = Array()
--
local codeInPagenameInList = false
-- /testcases pages in the module namespace are not categorised, as they may have
if codeInPagename then
-- {{documentation}} transcluded automatically.
if languageObjects[1] and subpage ~= "documentation" then
--]]
local agreement = languageObjects[2] and "s" or ""
local title = env.title
categories:insert("[[Category:Sortkey-generating modules used by " ..
local subjectSpace = env.subjectSpace
#languageObjects .. " language" .. agreement .. "]]")
if not title or not subjectSpace then
end
return nil
languageObjects = Array(languageObjects)
:filter(
function (lang)
local result = lang:getCode() ~= codeInPagename
codeInPagenameInList = codeInPagenameInList or result
return result
end)
end
end
local subpage = title.subpageText
if subpage ~= "documentation" then
if message('display-strange-usage-category', nil, 'boolean')
for script_code in pagename:gmatch("%f[^-%z]%u%l%l%l%f[-]") do
and (
local script = require "Module:scripts".getByCode(script_code)
subpage == message('doc-subpage')
if script then
or subjectSpace ~= 828 and subpage == message('testcases-subpage')
categories:insert("[[Category:" .. script:getCategoryName() .. "]]")
)
end
then
end
return makeCategoryLink(message('strange-usage-category'))
end
if subpage ~= "documentation" and not page_exists("Module:" .. pagename .. "/testcases") then
categories:insert("[[Category:Sortkey-generating modules without a testcases subpage]]")
end
end
return ''
if not languageObjects[1] then
return categories:concat()
end
local langs = Array(languageObjects)
:sort(
function(lang1, lang2)
return lang1:getCode() < lang2:getCode()
end)
-- This will not error because languageObjects is not empty.
:map(languageObjects[1].makeCategoryLink)
:serial_comma_join()
return "It is " .. ( codeInPagenameInList and "also" or "" ) ..
" used to sort " .. langs .. "." .. categories:concat()
end
end


return export
return p

Latest revision as of 11:31, 2 July 2024

Lua error: Module:TNT:172: Missing JsonConfig extension, or not properly configured; Cannot load https://commons.wikimedia.org/wiki/Data:I18n/Lua banner.tab. See https://www.mediawiki.org/wiki/Extension:JsonConfig#Supporting_Wikimedia_templates. Lua error: Module:TNT:172: Missing JsonConfig extension, or not properly configured; Cannot load https://commons.wikimedia.org/wiki/Data:I18n/Uses TemplateStyles.tab. See https://www.mediawiki.org/wiki/Extension:JsonConfig#Supporting_Wikimedia_templates. This module displays a blue box containing documentation for templates, Lua modules, or other pages. The {{documentation}} template invokes it.

Normal usage

For most uses, you should use the {{documentation}} template; please see that template's page for its usage instructions and parameters.

Use in other modules

To use this module from another Lua module, first load it with require:

local documentation = require('Module:Documentation').main

Then you can simply call it using a table of arguments.

documentation{content = 'Some documentation', ['link box'] = 'My custom link box'}

Please refer to the template documentation for usage instructions and a list of parameters.

Porting to other wikis

The module has a configuration file at Module:Documentation/config which is intended to allow easy translation and porting to other wikis. Please see the code comments in the config page for instructions. If you have any questions, or you need a feature which is not currently implemented, please leave a message at Template talk:Documentation to get the attention of a developer.

The messages that need to be customized to display a documentation template/module at the top of module pages are MediaWiki:Scribunto-doc-page-show and MediaWiki:Scribunto-doc-page-does-not-exist.


-- This module implements {{documentation}}.

-- Get required modules.
local getArgs = require('Module:Arguments').getArgs

-- Get the config table.
local cfg = mw.loadData('Module:Documentation/config')

local p = {}

-- Often-used functions.
local ugsub = mw.ustring.gsub
local format = mw.ustring.format

----------------------------------------------------------------------------
-- Helper functions
--
-- These are defined as local functions, but are made available in the p
-- table for testing purposes.
----------------------------------------------------------------------------

local function message(cfgKey, valArray, expectType)
	--[[
	-- Gets a message from the cfg table and formats it if appropriate.
	-- The function raises an error if the value from the cfg table is not
	-- of the type expectType. The default type for expectType is 'string'.
	-- If the table valArray is present, strings such as $1, $2 etc. in the
	-- message are substituted with values from the table keys [1], [2] etc.
	-- For example, if the message "foo-message" had the value 'Foo $2 bar $1.',
	-- message('foo-message', {'baz', 'qux'}) would return "Foo qux bar baz."
	--]]
	local msg = cfg[cfgKey]
	expectType = expectType or 'string'
	if type(msg) ~= expectType then
		error('message: type error in message cfg.' .. cfgKey .. ' (' .. expectType .. ' expected, got ' .. type(msg) .. ')', 2)
	end
	if not valArray then
		return msg
	end

	local function getMessageVal(match)
		match = tonumber(match)
		return valArray[match] or error('message: no value found for key $' .. match .. ' in message cfg.' .. cfgKey, 4)
	end

	return ugsub(msg, '$([1-9][0-9]*)', getMessageVal)
end

p.message = message

local function makeWikilink(page, display)
	if display then
		return format('[[%s|%s]]', page, display)
	else
		return format('[[%s]]', page)
	end
end

p.makeWikilink = makeWikilink

local function makeCategoryLink(cat, sort)
	local catns = mw.site.namespaces[14].name
	return makeWikilink(catns .. ':' .. cat, sort)
end

p.makeCategoryLink = makeCategoryLink

local function makeUrlLink(url, display)
	return format('[%s %s]', url, display)
end

p.makeUrlLink = makeUrlLink

local function makeToolbar(...)
	local ret = {}
	local lim = select('#', ...)
	if lim < 1 then
		return nil
	end
	for i = 1, lim do
		ret[#ret + 1] = select(i, ...)
	end
	-- 'documentation-toolbar'
	return format(
		'<span class="%s">(%s)</span>',
		message('toolbar-class'),
		table.concat(ret, ' &#124; ')
	)
end	

p.makeToolbar = makeToolbar

----------------------------------------------------------------------------
-- Argument processing
----------------------------------------------------------------------------

local function makeInvokeFunc(funcName)
	return function (frame)
		local args = getArgs(frame, {
			valueFunc = function (key, value)
				if type(value) == 'string' then
					value = value:match('^%s*(.-)%s*$') -- Remove whitespace.
					if key == 'heading' or value ~= '' then
						return value
					else
						return nil
					end
				else
					return value
				end
			end
		})
		return p[funcName](args)
	end
end

----------------------------------------------------------------------------
-- Entry points
----------------------------------------------------------------------------

function p.nonexistent(frame)
	if mw.title.getCurrentTitle().subpageText == 'testcases' then
		return frame:expandTemplate{title = 'module test cases notice'}
	else
		return p.main(frame)
	end
end

p.main = makeInvokeFunc('_main')

function p._main(args)
	--[[
	-- This function defines logic flow for the module.
	-- @args - table of arguments passed by the user
	--]]
	local env = p.getEnvironment(args)
	local root = mw.html.create()
	root
		:wikitext(p._getModuleWikitext(args, env))
		:wikitext(p.protectionTemplate(env))
		:wikitext(p.sandboxNotice(args, env))
		:tag('div')
			-- 'documentation-container'
			:addClass(message('container'))
			:attr('role', 'complementary')
			:attr('aria-labelledby', args.heading ~= '' and 'documentation-heading' or nil)
			:attr('aria-label', args.heading == '' and 'Documentation' or nil)
			:newline()
			:tag('div')
				-- 'documentation'
				:addClass(message('main-div-classes'))
				:newline()
				:wikitext(p._startBox(args, env))
				:wikitext(p._content(args, env))
				:tag('div')
					-- 'documentation-clear'
					:addClass(message('clear'))
					:done()
				:newline()
				:done()
			:wikitext(p._endBox(args, env))
			:done()
		:wikitext(p.addTrackingCategories(env))
	-- 'Module:Documentation/styles.css'
	return mw.getCurrentFrame():extensionTag (
		'templatestyles', '', {src=cfg['templatestyles']
	}) .. tostring(root)
end

----------------------------------------------------------------------------
-- Environment settings
----------------------------------------------------------------------------

function p.getEnvironment(args)
	--[[
	-- Returns a table with information about the environment, including title
	-- objects and other namespace- or path-related data.
	-- @args - table of arguments passed by the user
	--
	-- Title objects include:
	-- env.title - the page we are making documentation for (usually the current title)
	-- env.templateTitle - the template (or module, file, etc.)
	-- env.docTitle - the /doc subpage.
	-- env.sandboxTitle - the /sandbox subpage.
	-- env.testcasesTitle - the /testcases subpage.
	--
	-- Data includes:
	-- env.protectionLevels - the protection levels table of the title object.
	-- env.subjectSpace - the number of the title's subject namespace.
	-- env.docSpace - the number of the namespace the title puts its documentation in.
	-- env.docpageBase - the text of the base page of the /doc, /sandbox and /testcases pages, with namespace.
	-- env.compareUrl - URL of the Special:ComparePages page comparing the sandbox with the template.
	-- 
	-- All table lookups are passed through pcall so that errors are caught. If an error occurs, the value
	-- returned will be nil.
	--]]
	
	local env, envFuncs = {}, {}

	-- Set up the metatable. If triggered we call the corresponding function in the envFuncs table. The value
	-- returned by that function is memoized in the env table so that we don't call any of the functions
	-- more than once. (Nils won't be memoized.)
	setmetatable(env, {
		__index = function (t, key)
			local envFunc = envFuncs[key]
			if envFunc then
				local success, val = pcall(envFunc)
				if success then
					env[key] = val -- Memoise the value.
					return val
				end
			end
			return nil
		end
	})	

	function envFuncs.title()
		-- The title object for the current page, or a test page passed with args.page.
		local title
		local titleArg = args.page
		if titleArg then
			title = mw.title.new(titleArg)
		else
			title = mw.title.getCurrentTitle()
		end
		return title
	end

	function envFuncs.templateTitle()
		--[[
		-- The template (or module, etc.) title object.
		-- Messages:
		-- 'sandbox-subpage' --> 'sandbox'
		-- 'testcases-subpage' --> 'testcases'
		--]]
		local subjectSpace = env.subjectSpace
		local title = env.title
		local subpage = title.subpageText
		if subpage == message('sandbox-subpage') or subpage == message('testcases-subpage') then
			return mw.title.makeTitle(subjectSpace, title.baseText)
		else
			return mw.title.makeTitle(subjectSpace, title.text)
		end
	end

	function envFuncs.docTitle()
		--[[
		-- Title object of the /doc subpage.
		-- Messages:
		-- 'doc-subpage' --> 'doc'
		--]]
		local title = env.title
		local docname = args[1] -- User-specified doc page.
		local docpage
		if docname then
			docpage = docname
		else
			docpage = env.docpageBase .. '/' .. message('doc-subpage')
		end
		return mw.title.new(docpage)
	end
	
	function envFuncs.sandboxTitle()
		--[[
		-- Title object for the /sandbox subpage.
		-- Messages:
		-- 'sandbox-subpage' --> 'sandbox'
		--]]
		return mw.title.new(env.docpageBase .. '/' .. message('sandbox-subpage'))
	end
	
	function envFuncs.testcasesTitle()
		--[[
		-- Title object for the /testcases subpage.
		-- Messages:
		-- 'testcases-subpage' --> 'testcases'
		--]]
		return mw.title.new(env.docpageBase .. '/' .. message('testcases-subpage'))
	end

	function envFuncs.protectionLevels()
		-- The protection levels table of the title object.
		return env.title.protectionLevels
	end

	function envFuncs.subjectSpace()
		-- The subject namespace number.
		return mw.site.namespaces[env.title.namespace].subject.id
	end

	function envFuncs.docSpace()
		-- The documentation namespace number. For most namespaces this is the
		-- same as the subject namespace. However, pages in the Article, File,
		-- MediaWiki or Category namespaces must have their /doc, /sandbox and
		-- /testcases pages in talk space.
		local subjectSpace = env.subjectSpace
		if subjectSpace == 0 or subjectSpace == 6 or subjectSpace == 8 or subjectSpace == 14 then
			return subjectSpace + 1
		else
			return subjectSpace
		end
	end

	function envFuncs.docpageBase()
		-- The base page of the /doc, /sandbox, and /testcases subpages.
		-- For some namespaces this is the talk page, rather than the template page.
		local templateTitle = env.templateTitle
		local docSpace = env.docSpace
		local docSpaceText = mw.site.namespaces[docSpace].name
		-- Assemble the link. docSpace is never the main namespace, so we can hardcode the colon.
		return docSpaceText .. ':' .. templateTitle.text
	end
	
	function envFuncs.compareUrl()
		-- Diff link between the sandbox and the main template using [[Special:ComparePages]].
		local templateTitle = env.templateTitle
		local sandboxTitle = env.sandboxTitle
		if templateTitle.exists and sandboxTitle.exists then
			local compareUrl = mw.uri.canonicalUrl(
				'Special:ComparePages',
				{ page1 = templateTitle.prefixedText, page2 = sandboxTitle.prefixedText}
			)
			return tostring(compareUrl)
		else
			return nil
		end
	end		

	return env
end	

----------------------------------------------------------------------------
-- Auxiliary templates
----------------------------------------------------------------------------

p.getModuleWikitext = makeInvokeFunc('_getModuleWikitext')

function p._getModuleWikitext(args, env)
	local currentTitle = mw.title.getCurrentTitle()
	if currentTitle.contentModel ~= 'Scribunto' then return end
	pcall(require, currentTitle.prefixedText) -- if it fails, we don't care
	local moduleWikitext =  package.loaded["Module:Module wikitext"]
	if moduleWikitext then
		return moduleWikitext.main()
	end
end

function p.sandboxNotice(args, env)
	--[=[
	-- Generates a sandbox notice for display above sandbox pages.
	-- @args - a table of arguments passed by the user
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	-- 
	-- Messages:
	-- 'sandbox-notice-image' --> '[[File:Sandbox.svg|50px|alt=|link=]]'
	-- 'sandbox-notice-blurb' --> 'This is the $1 for $2.'
	-- 'sandbox-notice-diff-blurb' --> 'This is the $1 for $2 ($3).'
	-- 'sandbox-notice-pagetype-template' --> '[[Wikipedia:Template test cases|template sandbox]] page'
	-- 'sandbox-notice-pagetype-module' --> '[[Wikipedia:Template test cases|module sandbox]] page'
	-- 'sandbox-notice-pagetype-other' --> 'sandbox page'
	-- 'sandbox-notice-compare-link-display' --> 'diff'
	-- 'sandbox-notice-testcases-blurb' --> 'See also the companion subpage for $1.'
	-- 'sandbox-notice-testcases-link-display' --> 'test cases'
	-- 'sandbox-category' --> 'Template sandboxes'
	-- 'module-sandbox-category' --> 'Module sandboxes'
	-- 'other-sandbox-category' --> 'Sandboxes outside of template or module namespace'
	--]=]
	local title = env.title
	local sandboxTitle = env.sandboxTitle
	local templateTitle = env.templateTitle
	local subjectSpace = env.subjectSpace
	if not (subjectSpace and title and sandboxTitle and templateTitle
		and mw.title.equals(title, sandboxTitle)) then
		return nil
	end
	-- Build the table of arguments to pass to {{ombox}}. We need just two fields, "image" and "text".
	local omargs = {}
	omargs.image = message('sandbox-notice-image')
	-- Get the text. We start with the opening blurb, which is something like
	-- "This is the template sandbox for [[Template:Foo]] (diff)."
	local text = ''
	local pagetype, sandboxCat
	if subjectSpace == 10 then
		pagetype = message('sandbox-notice-pagetype-template')
		sandboxCat = message('sandbox-category')
	elseif subjectSpace == 828 then
		pagetype = message('sandbox-notice-pagetype-module')
		sandboxCat = message('module-sandbox-category')
	else
		pagetype = message('sandbox-notice-pagetype-other')
		sandboxCat = message('other-sandbox-category')
	end
	local templateLink = makeWikilink(templateTitle.prefixedText)
	local compareUrl = env.compareUrl
	if compareUrl then
		local compareDisplay = message('sandbox-notice-compare-link-display')
		local compareLink = makeUrlLink(compareUrl, compareDisplay)
		text = text .. message('sandbox-notice-diff-blurb', {pagetype, templateLink, compareLink})
	else
		text = text .. message('sandbox-notice-blurb', {pagetype, templateLink})
	end
	-- Get the test cases page blurb if the page exists. This is something like
	-- "See also the companion subpage for [[Template:Foo/testcases|test cases]]."
	local testcasesTitle = env.testcasesTitle
	if testcasesTitle and testcasesTitle.exists then
		if testcasesTitle.contentModel == "Scribunto" then
			local testcasesLinkDisplay = message('sandbox-notice-testcases-link-display')
			local testcasesRunLinkDisplay = message('sandbox-notice-testcases-run-link-display')
			local testcasesLink = makeWikilink(testcasesTitle.prefixedText, testcasesLinkDisplay)
			local testcasesRunLink = makeWikilink(testcasesTitle.talkPageTitle.prefixedText, testcasesRunLinkDisplay)
			text = text .. '<br />' .. message('sandbox-notice-testcases-run-blurb', {testcasesLink, testcasesRunLink})
		else
			local testcasesLinkDisplay = message('sandbox-notice-testcases-link-display')
			local testcasesLink = makeWikilink(testcasesTitle.prefixedText, testcasesLinkDisplay)
			text = text .. '<br />' .. message('sandbox-notice-testcases-blurb', {testcasesLink})
		end
	end
	
	-- Add the sandbox to the sandbox category.
	omargs.text = text .. makeCategoryLink(sandboxCat)

	-- 'documentation-clear'
	return '<div class="' .. message('clear') .. '"></div>'
		.. require('Module:Message box').main('ombox', omargs)
end

function p.protectionTemplate(env)
	-- Generates the padlock icon in the top right.
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	-- Messages:
	-- 'protection-template' --> 'pp-template'
	-- 'protection-template-args' --> {docusage = 'yes'}
	local protectionLevels = env.protectionLevels
	if not protectionLevels then
		return nil
	end
	local editProt = protectionLevels.edit and protectionLevels.edit[1]
	local moveProt = protectionLevels.move and protectionLevels.move[1]
	if editProt then
		-- The page is edit-protected.
		return require('Module:Protection banner')._main{
			message('protection-reason-edit'), small = true
		}
	elseif moveProt and moveProt ~= 'autoconfirmed' then
		-- The page is move-protected but not edit-protected. Exclude move
		-- protection with the level "autoconfirmed", as this is equivalent to
		-- no move protection at all.
		return require('Module:Protection banner')._main{
			action = 'move', small = true
		}
	else
		return nil
	end
end

----------------------------------------------------------------------------
-- Start box
----------------------------------------------------------------------------

p.startBox = makeInvokeFunc('_startBox')

function p._startBox(args, env)
	--[[
	-- This function generates the start box.
	-- @args - a table of arguments passed by the user
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	-- 
	-- The actual work is done by p.makeStartBoxLinksData and p.renderStartBoxLinks which make
	-- the [view] [edit] [history] [purge] links, and by p.makeStartBoxData and p.renderStartBox
	-- which generate the box HTML.
	--]]
	env = env or p.getEnvironment(args)
	local links
	local content = args.content
	if not content or args[1] then
		-- No need to include the links if the documentation is on the template page itself.
		local linksData = p.makeStartBoxLinksData(args, env)
		if linksData then
			links = p.renderStartBoxLinks(linksData)
		end
	end
	-- Generate the start box html.
	local data = p.makeStartBoxData(args, env, links)
	if data then
		return p.renderStartBox(data)
	else
		-- User specified no heading.
		return nil
	end
end

function p.makeStartBoxLinksData(args, env)
	--[[
	-- Does initial processing of data to make the [view] [edit] [history] [purge] links.
	-- @args - a table of arguments passed by the user
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	-- 
	-- Messages:
	-- 'view-link-display' --> 'view'
	-- 'edit-link-display' --> 'edit'
	-- 'history-link-display' --> 'history'
	-- 'purge-link-display' --> 'purge'
	-- 'module-preload' --> 'Template:Documentation/preload-module-doc'
	-- 'docpage-preload' --> 'Template:Documentation/preload'
	-- 'create-link-display' --> 'create'
	--]]
	local subjectSpace = env.subjectSpace
	local title = env.title
	local docTitle = env.docTitle
	if not title or not docTitle then
		return nil
	end
	if docTitle.isRedirect then 
		docTitle = docTitle.redirectTarget
	end

	-- Create link if /doc doesn't exist.
	local preload = args.preload
	if not preload then
		if subjectSpace == 828 then -- Module namespace
			preload = message('module-preload')
		else
			preload = message('docpage-preload')
		end
	end
	
	return {
		title = title,
		docTitle = docTitle,
		-- View, display, edit, and purge links if /doc exists.
		viewLinkDisplay = message('view-link-display'),
		editLinkDisplay = message('edit-link-display'),
		historyLinkDisplay = message('history-link-display'),
		purgeLinkDisplay = message('purge-link-display'),
		preload = preload,
		createLinkDisplay = message('create-link-display')
	}
end

function p.renderStartBoxLinks(data)
	--[[
	-- Generates the [view][edit][history][purge] or [create][purge] links from the data table.
	-- @data - a table of data generated by p.makeStartBoxLinksData
	--]]
	local docTitle = data.docTitle
	-- yes, we do intend to purge the template page on which the documentation appears
	local purgeLink = makeWikilink("Special:Purge/" .. data.title.prefixedText, data.purgeLinkDisplay)
	
	if docTitle.exists then
		local viewLink = makeWikilink(docTitle.prefixedText, data.viewLinkDisplay)
		local editLink = makeWikilink("Special:EditPage/" .. docTitle.prefixedText, data.editLinkDisplay)
		local historyLink = makeWikilink("Special:PageHistory/" .. docTitle.prefixedText, data.historyLinkDisplay)
		return "&#91;" .. viewLink .. "&#93; &#91;" .. editLink .. "&#93; &#91;" .. historyLink .. "&#93; &#91;" .. purgeLink .. "&#93;"
	else
		local createLink = makeUrlLink(docTitle:canonicalUrl{action = 'edit', preload = data.preload}, data.createLinkDisplay)
		return  "&#91;" .. createLink .. "&#93; &#91;" .. purgeLink .. "&#93;"
	end
	return ret
end

function p.makeStartBoxData(args, env, links)
	--[=[
	-- Does initial processing of data to pass to the start-box render function, p.renderStartBox.
	-- @args - a table of arguments passed by the user
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	-- @links - a string containing the [view][edit][history][purge] links - could be nil if there's an error.
	--
	-- Messages:
	-- 'documentation-icon-wikitext' --> '[[File:Test Template Info-Icon - Version (2).svg|50px|link=|alt=]]'
	-- 'template-namespace-heading' --> 'Template documentation'
	-- 'module-namespace-heading' --> 'Module documentation'
	-- 'file-namespace-heading' --> 'Summary'
	-- 'other-namespaces-heading' --> 'Documentation'
	-- 'testcases-create-link-display' --> 'create'
	--]=]
	local subjectSpace = env.subjectSpace
	if not subjectSpace then
		-- Default to an "other namespaces" namespace, so that we get at least some output
		-- if an error occurs.
		subjectSpace = 2
	end
	local data = {}
	
	-- Heading
	local heading = args.heading -- Blank values are not removed.
	if heading == '' then
		-- Don't display the start box if the heading arg is defined but blank.
		return nil
	end
	if heading then
		data.heading = heading
	elseif subjectSpace == 10 then -- Template namespace
		data.heading = message('documentation-icon-wikitext') .. ' ' .. message('template-namespace-heading')
	elseif subjectSpace == 828 then -- Module namespace
		data.heading = message('documentation-icon-wikitext') .. ' ' .. message('module-namespace-heading')
	elseif subjectSpace == 6 then -- File namespace
		data.heading = message('file-namespace-heading')
	else
		data.heading = message('other-namespaces-heading')
	end
	
	-- Heading CSS
	local headingStyle = args['heading-style']
	if headingStyle then
		data.headingStyleText = headingStyle
	else
		-- 'documentation-heading'
		data.headingClass = message('main-div-heading-class')
	end
	
	-- Data for the [view][edit][history][purge] or [create] links.
	if links then
		-- 'mw-editsection-like plainlinks'
		data.linksClass = message('start-box-link-classes')
		data.links = links
	end
	
	return data
end

function p.renderStartBox(data)
	-- Renders the start box html.
	-- @data - a table of data generated by p.makeStartBoxData.
	local sbox = mw.html.create('div')
	sbox
		-- 'documentation-startbox'
		:addClass(message('start-box-class'))
		:newline()
		:tag('span')
			:addClass(data.headingClass)
			:attr('id', 'documentation-heading')
			:cssText(data.headingStyleText)
			:wikitext(data.heading)
	local links = data.links
	if links then
		sbox:tag('span')
			:addClass(data.linksClass)
			:attr('id', data.linksId)
			:wikitext(links)
	end
	return tostring(sbox)
end

----------------------------------------------------------------------------
-- Documentation content
----------------------------------------------------------------------------

p.content = makeInvokeFunc('_content')

function p._content(args, env)
	-- Displays the documentation contents
	-- @args - a table of arguments passed by the user
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	env = env or p.getEnvironment(args)
	local docTitle = env.docTitle
	local content = args.content
	if not content and docTitle and docTitle.exists then
		content = args._content or mw.getCurrentFrame():expandTemplate{title = docTitle.prefixedText}
	end
	-- The line breaks below are necessary so that "=== Headings ===" at the start and end
	-- of docs are interpreted correctly.
	return '\n' .. (content or '') .. '\n' 
end

p.contentTitle = makeInvokeFunc('_contentTitle')

function p._contentTitle(args, env)
	env = env or p.getEnvironment(args)
	local docTitle = env.docTitle
	if not args.content and docTitle and docTitle.exists then
		return docTitle.prefixedText
	else
		return ''
	end
end

----------------------------------------------------------------------------
-- End box
----------------------------------------------------------------------------

p.endBox = makeInvokeFunc('_endBox')

function p._endBox(args, env)
	--[=[
	-- This function generates the end box (also known as the link box).
	-- @args - a table of arguments passed by the user
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	-- 
	--]=]
	
	-- Get environment data.
	env = env or p.getEnvironment(args)
	local subjectSpace = env.subjectSpace
	local docTitle = env.docTitle
	if not subjectSpace or not docTitle then
		return nil
	end
		
	-- Check whether we should output the end box at all. Add the end
	-- box by default if the documentation exists or if we are in the
	-- user, module or template namespaces.
	local linkBox = args['link box']
	if linkBox == 'off'
		or not (
			docTitle.exists
			or subjectSpace == 2
			or subjectSpace == 828
			or subjectSpace == 10
		)
	then
		return nil
	end

	-- Assemble the link box.
	local text = ''
	if linkBox then
		text = text .. linkBox
	else
		text = text .. (p.makeDocPageBlurb(args, env) or '') -- "This documentation is transcluded from [[Foo]]." 
		if subjectSpace == 2 or subjectSpace == 10 or subjectSpace == 828 then
			-- We are in the user, template or module namespaces.
			-- Add sandbox and testcases links.
			-- "Editors can experiment in this template's sandbox and testcases pages."
			text = text .. (p.makeExperimentBlurb(args, env) or '') .. '<br />'
			if not args.content and not args[1] then
				-- "Please add categories to the /doc subpage."
				-- Don't show this message with inline docs or with an explicitly specified doc page,
				-- as then it is unclear where to add the categories.
				text = text .. (p.makeCategoriesBlurb(args, env) or '')
			end
			text = text .. ' ' .. (p.makeSubpagesBlurb(args, env) or '') --"Subpages of this template"
		end
	end
	
	local box = mw.html.create('div')
	-- 'documentation-metadata'
	box:attr('role', 'note')
		:addClass(message('end-box-class'))
		-- 'plainlinks'
		:addClass(message('end-box-plainlinks'))
		:wikitext(text)
		:done()

	return '\n' .. tostring(box)
end

function p.makeDocPageBlurb(args, env)
	--[=[
	-- Makes the blurb "This documentation is transcluded from [[Template:Foo]] (edit, history)".
	-- @args - a table of arguments passed by the user
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	-- 
	-- Messages:
	-- 'edit-link-display' --> 'edit'
	-- 'history-link-display' --> 'history'
	-- 'transcluded-from-blurb' --> 
	-- 'The above [[Wikipedia:Template documentation|documentation]] 
	-- is [[Help:Transclusion|transcluded]] from $1.'
	-- 'module-preload' --> 'Template:Documentation/preload-module-doc'
	-- 'create-link-display' --> 'create'
	-- 'create-module-doc-blurb' -->
	-- 'You might want to $1 a documentation page for this [[Wikipedia:Lua|Scribunto module]].'
	--]=]
	local docTitle = env.docTitle
	if not docTitle then
		return nil
	end
	if docTitle.exists then
		-- /doc exists; link to it.
		local docLink = makeWikilink(docTitle.prefixedText)
		local editDisplay = message('edit-link-display')
		local editLink = makeWikilink("Special:EditPage/" .. docTitle.prefixedText, editDisplay)
		local historyDisplay = message('history-link-display')
		local historyLink = makeWikilink("Special:PageHistory/" .. docTitle.prefixedText, historyDisplay)
		return message('transcluded-from-blurb', {docLink})
			.. ' '
			.. makeToolbar(editLink, historyLink)
			.. '<br />'
	elseif env.subjectSpace == 828 then
		-- /doc does not exist; ask to create it.
		local createUrl = docTitle:canonicalUrl{action = 'edit', preload = message('module-preload')}
		local createDisplay = message('create-link-display')
		local createLink = makeUrlLink(createUrl, createDisplay)
		return message('create-module-doc-blurb', {createLink})
			.. '<br />'
	end
end

function p.makeExperimentBlurb(args, env)
	--[[
	-- Renders the text "Editors can experiment in this template's sandbox (edit | diff) and testcases (edit) pages."
	-- @args - a table of arguments passed by the user
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	-- 
	-- Messages:
	-- 'sandbox-link-display' --> 'sandbox'
	-- 'sandbox-edit-link-display' --> 'edit'
	-- 'compare-link-display' --> 'diff'
	-- 'module-sandbox-preload' --> 'Template:Documentation/preload-module-sandbox'
	-- 'template-sandbox-preload' --> 'Template:Documentation/preload-sandbox'
	-- 'sandbox-create-link-display' --> 'create'
	-- 'mirror-edit-summary' --> 'Create sandbox version of $1'
	-- 'mirror-link-display' --> 'mirror'
	-- 'mirror-link-preload' --> 'Template:Documentation/mirror'
	-- 'sandbox-link-display' --> 'sandbox'
	-- 'testcases-link-display' --> 'testcases'
	-- 'testcases-edit-link-display'--> 'edit'
	-- 'template-sandbox-preload' --> 'Template:Documentation/preload-sandbox'
	-- 'testcases-create-link-display' --> 'create'
	-- 'testcases-link-display' --> 'testcases'
	-- 'testcases-edit-link-display' --> 'edit'
	-- 'module-testcases-preload' --> 'Template:Documentation/preload-module-testcases'
	-- 'template-testcases-preload' --> 'Template:Documentation/preload-testcases'
	-- 'experiment-blurb-module' --> 'Editors can experiment in this module's $1 and $2 pages.'
	-- 'experiment-blurb-template' --> 'Editors can experiment in this template's $1 and $2 pages.'
	--]]
	local subjectSpace = env.subjectSpace
	local templateTitle = env.templateTitle
	local sandboxTitle = env.sandboxTitle
	local testcasesTitle = env.testcasesTitle
	local templatePage = templateTitle.prefixedText
	if not subjectSpace or not templateTitle or not sandboxTitle or not testcasesTitle then
		return nil
	end
	-- Make links.
	local sandboxLinks, testcasesLinks
	if sandboxTitle.exists then
		local sandboxPage = sandboxTitle.prefixedText
		local sandboxDisplay = message('sandbox-link-display')
		local sandboxLink = makeWikilink(sandboxPage, sandboxDisplay)
		local sandboxEditDisplay = message('sandbox-edit-link-display')
		local sandboxEditLink = makeWikilink("Special:EditPage/" .. sandboxPage, sandboxEditDisplay)
		local compareUrl = env.compareUrl
		local compareLink
		if compareUrl then
			local compareDisplay = message('compare-link-display')
			compareLink = makeUrlLink(compareUrl, compareDisplay)
		end
		sandboxLinks = sandboxLink .. ' ' .. makeToolbar(sandboxEditLink, compareLink)
	else
		local sandboxPreload
		if subjectSpace == 828 then
			sandboxPreload = message('module-sandbox-preload')
		else
			sandboxPreload = message('template-sandbox-preload')
		end
		local sandboxCreateUrl = sandboxTitle:canonicalUrl{action = 'edit', preload = sandboxPreload}
		local sandboxCreateDisplay = message('sandbox-create-link-display')
		local sandboxCreateLink = makeUrlLink(sandboxCreateUrl, sandboxCreateDisplay)
		local mirrorSummary = message('mirror-edit-summary', {makeWikilink(templatePage)})
		local mirrorPreload = message('mirror-link-preload')
		local mirrorUrl = sandboxTitle:canonicalUrl{action = 'edit', preload = mirrorPreload, summary = mirrorSummary}
		if subjectSpace == 828 then
			mirrorUrl = sandboxTitle:canonicalUrl{action = 'edit', preload = templateTitle.prefixedText, summary = mirrorSummary}
		end
		local mirrorDisplay = message('mirror-link-display')
		local mirrorLink = makeUrlLink(mirrorUrl, mirrorDisplay)
		sandboxLinks = message('sandbox-link-display') .. ' ' .. makeToolbar(sandboxCreateLink, mirrorLink)
	end
	if testcasesTitle.exists then
		local testcasesPage = testcasesTitle.prefixedText
		local testcasesDisplay = message('testcases-link-display')
		local testcasesLink = makeWikilink(testcasesPage, testcasesDisplay)
		local testcasesEditUrl = testcasesTitle:canonicalUrl{action = 'edit'}
		local testcasesEditDisplay = message('testcases-edit-link-display')
		local testcasesEditLink = makeWikilink("Special:EditPage/" .. testcasesPage, testcasesEditDisplay)
		-- for Modules, add testcases run link if exists
		if testcasesTitle.contentModel == "Scribunto"  and testcasesTitle.talkPageTitle and testcasesTitle.talkPageTitle.exists then
			local testcasesRunLinkDisplay = message('testcases-run-link-display')
			local testcasesRunLink = makeWikilink(testcasesTitle.talkPageTitle.prefixedText, testcasesRunLinkDisplay)
			testcasesLinks = testcasesLink .. ' ' .. makeToolbar(testcasesEditLink, testcasesRunLink)
		else
			testcasesLinks = testcasesLink .. ' ' .. makeToolbar(testcasesEditLink)
		end
	else
		local testcasesPreload
		if subjectSpace == 828 then
			testcasesPreload = message('module-testcases-preload')
		else
			testcasesPreload = message('template-testcases-preload')
		end
		local testcasesCreateUrl = testcasesTitle:canonicalUrl{action = 'edit', preload = testcasesPreload}
		local testcasesCreateDisplay = message('testcases-create-link-display')
		local testcasesCreateLink = makeUrlLink(testcasesCreateUrl, testcasesCreateDisplay)
		testcasesLinks = message('testcases-link-display') .. ' ' .. makeToolbar(testcasesCreateLink)
	end
	local messageName
	if subjectSpace == 828 then
		messageName = 'experiment-blurb-module'
	else
		messageName = 'experiment-blurb-template'
	end
	return message(messageName, {sandboxLinks, testcasesLinks})
end

function p.makeCategoriesBlurb(args, env)
	--[[
	-- Generates the text "Please add categories to the /doc subpage."
	-- @args - a table of arguments passed by the user
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	-- Messages:
	-- 'doc-link-display' --> '/doc'
	-- 'add-categories-blurb' --> 'Please add categories to the $1 subpage.'
	--]]
	local docTitle = env.docTitle
	if not docTitle then
		return nil
	end
	local docPathLink = makeWikilink(docTitle.prefixedText, message('doc-link-display'))
	return message('add-categories-blurb', {docPathLink})
end

function p.makeSubpagesBlurb(args, env)
	--[[
	-- Generates the "Subpages of this template" link.
	-- @args - a table of arguments passed by the user
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	
	-- Messages:
	-- 'template-pagetype' --> 'template'
	-- 'module-pagetype' --> 'module'
	-- 'default-pagetype' --> 'page'
	-- 'subpages-link-display' --> 'Subpages of this $1'
	--]]
	local subjectSpace = env.subjectSpace
	local templateTitle = env.templateTitle
	if not subjectSpace or not templateTitle then
		return nil
	end
	local pagetype
	if subjectSpace == 10 then
		pagetype = message('template-pagetype')
	elseif subjectSpace == 828 then
		pagetype = message('module-pagetype')
	else
		pagetype = message('default-pagetype')
	end
	local subpagesLink = makeWikilink(
		'Special:PrefixIndex/' .. templateTitle.prefixedText .. '/',
		message('subpages-link-display', {pagetype})
	)
	return message('subpages-blurb', {subpagesLink})
end

----------------------------------------------------------------------------
-- Tracking categories
----------------------------------------------------------------------------

function p.addTrackingCategories(env)
	--[[
	-- Check if {{documentation}} is transcluded on a /doc or /testcases page.
	-- @env - environment table containing title objects, etc., generated with p.getEnvironment
	
	-- Messages:
	-- 'display-strange-usage-category' --> true
	-- 'doc-subpage' --> 'doc'
	-- 'testcases-subpage' --> 'testcases'
	-- 'strange-usage-category' --> 'Wikipedia pages with strange ((documentation)) usage'
	-- 
	-- /testcases pages in the module namespace are not categorised, as they may have
	-- {{documentation}} transcluded automatically.
	--]]
	local title = env.title
	local subjectSpace = env.subjectSpace
	if not title or not subjectSpace then
		return nil
	end
	local subpage = title.subpageText
	if message('display-strange-usage-category', nil, 'boolean')
		and (
			subpage == message('doc-subpage')
			or subjectSpace ~= 828 and subpage == message('testcases-subpage')
		)
	then
		return makeCategoryLink(message('strange-usage-category'))
	end
	return ''
end

return p