请输入您要查询的百科知识:

 

词条 Module:Citation/CS1
释义

local cs1 ={};

--[[--------------------------< F O R W A R D D E C L A R A T I O N S >--------------------------------------

]]

local dates, year_date_check, reformat_dates, date_hyphen_to_dash, -- functions in Module:Citation/CS1/Date_validation

date_name_xlate

local is_set, in_array, substitute, error_comment, set_error, select_one, -- functions in Module:Citation/CS1/Utilities

add_maint_cat, wrap_style, safe_for_italics, is_wikilink, make_wikilink;

local z ={}; -- tables in Module:Citation/CS1/Utilities

local extract_ids, extract_id_access_levels, build_id_list, is_embargoed; -- functions in Module:Citation/CS1/Identifiers

local make_coins_title, get_coins_pages, COinS; -- functions in Module:Citation/CS1/COinS

local cfg = {}; -- table of configuration tables that are defined in Module:Citation/CS1/Configuration

local whitelist = {}; -- table of tables listing valid template parameter names; defined in Module:Citation/CS1/Whitelist

--[[--------------------------< P A G E S C O P E V A R I A B L E S >--------------------------------------

delare variables here that have page-wide scope that are not brought in from other modules; thatare created here

and used here

]]

local added_deprecated_cat; -- boolean flag so that the category is added only once

local added_prop_cats = {}; -- list of property categories that have been added to z.properties_cats

local added_vanc_errs; -- boolean flag so we only emit one Vancouver error / category

local Frame; -- holds the module's frame table

--[[--------------------------< F I R S T _ S E T >------------------------------------------------------------

Locates and returns the first set value in a table of values where the order established in the table,

left-to-right (or top-to-bottom), is the order in which the values are evaluated. Returns nil if none are set.

This version replaces the original 'for _, val in pairs do' and a similar version that used ipairs. With the pairs

version the order of evaluation could not be guaranteed. With the ipairs version, a nil value would terminate

the for-loop before it reached the actual end of the list.

]]

local function first_set (list, count)

local i = 1;

while i <= count do -- loop through all items in list

if is_set( list[i] ) then

return list[i]; -- return the first set list member

end

i = i + 1; -- point to next

end

end

--[[--------------------------< A D D _ P R O P _ C A T >--------------------------------------------------------

Adds a category to z.properties_cats using names from the configuration file with additional text if any.

foreign_lang_source and foreign_lang_source_2 keys have a language code appended to them so that multiple languages

may be categorized but multiples of the same language are not categorized.

added_prop_cats is a table declared in page scope variables above

]]

local function add_prop_cat (key, arguments)

if not added_prop_cats [key] then

added_prop_cats [key] = true; -- note that we've added this category

key = key:gsub ('(foreign_lang_source_?2?)%a%a%a?', '%1'); -- strip lang code from keyname

table.insert( z.properties_cats, substitute (cfg.prop_cats [key], arguments)); -- make name then add to table

end

end

--[[--------------------------< A D D _ V A N C _ E R R O R >----------------------------------------------------

Adds a single Vancouver system error message to the template's output regardless of how many error actually exist.

To prevent duplication, added_vanc_errs is nil until an error message is emitted.

added_vanc_errs is a boolean declared in page scope variables above

]]

local function add_vanc_error (source)

if not added_vanc_errs then

added_vanc_errs = true; -- note that we've added this category

table.insert( z.message_tail, { set_error( 'vancouver', {source}, true ) } );

end

end

--[[--------------------------< I S _ S C H E M E >------------------------------------------------------------

does this thing that purports to be a uri scheme seem to be a valid scheme? The scheme is checked to see if it

is in agreement with http://tools.ietf.org/html/std66#section-3.1 which says:

Scheme names consist of a sequence of characters beginning with a

   letter and followed by any combination of letters, digits, plus   ("+"), period ("."), or hyphen ("-").

returns true if it does, else false

]]

local function is_scheme (scheme)

return scheme and scheme:match ('^%a[%a%d%+%.%-]*:'); -- true if scheme is set and matches the pattern

end

--[=[-------------------------< I S _ D O M A I N _ N A M E >--------------------------------------------------

Does this thing that purports to be a domain name seem to be a valid domain name?

Syntax defined here: http://tools.ietf.org/html/rfc1034#section-3.5

BNF defined here: https://tools.ietf.org/html/rfc4234

Single character names are generally reserved; see https://tools.ietf.org/html/draft-ietf-dnsind-iana-dns-01#page-15;

see also Single-letter second-level domain

list of tlds: https://www.iana.org/domains/root/db

rfc952 (modified by rfc 1123) requires the first and last character of a hostname to be a letter or a digit. Between

the first and last characters the name may use letters, digits, and the hyphen.

Also allowed are IPv4 addresses. IPv6 not supported

domain is expected to be stripped of any path so that the last character in the last character of the tld. tld

is two or more alpha characters. Any preceding '//' (from splitting a url with a scheme) will be stripped

here. Perhaps not necessary but retained incase it is necessary for IPv4 dot decimal.

There are several tests:

the first character of the whole domain name including subdomains must be a letter or a digit

internationalized domain name (ascii characters with .xn-- ASCII Compatible Encoding (ACE) prefix xn-- in the tld) see https://tools.ietf.org/html/rfc3490

single-letter/digit second-level domains in the .org and .cash TLDs

q, x, and z SL domains in the .com TLD

i and q SL domains in the .net TLD

single-letter SL domains in the ccTLDs (where the ccTLD is two letters)

two-character SL domains in gTLDs (where the gTLD is two or more letters)

three-plus-character SL domains in gTLDs (where the gTLD is two or more letters)

IPv4 dot-decimal address format; TLD not allowed

returns true if domain appears to be a proper name and tld or IPv4 address, else false

]=]

local function is_domain_name (domain)

if not domain then

return false; -- if not set, abandon

end

domain = domain:gsub ('^//', ); -- strip '//' from domain name if present; done here so we only have to do it once

if not domain:match ('^[%a%d]') then -- first character must be letter or digit

return false;

end

if domain:match ('^%a+:') then -- hack to detect things that look like s:Page:Title where Page: is namespace at wikisource

return false;

end

-- Do most common case first

if domain:match ('%f[%a%d][%a%d][%a%d%-]+[%a%d]%.%a%a+$') then -- three or more character hostname.hostname or hostname.tld

return true;

elseif domain:match ('%f[%a%d][%a%d][%a%d%-]+[%a%d]%.xn%-%-[%a%d]+$') then -- internationalized domain name with ACE prefix

return true;

elseif domain:match ('%f[%a%d][%a%d]%.cash$') then -- one character/digit .cash hostname

return true;

elseif domain:match ('%f[%a%d][%a%d]%.org$') then -- one character/digit .org hostname

return true;

elseif domain:match ('%f[%a][qxz]%.com$') then -- assigned one character .com hostname (x.com times out 2015-12-10)

return true;

elseif domain:match ('%f[%a][iq]%.net$') then -- assigned one character .net hostname (q.net registered but not active 2015-12-10)

return true;

elseif domain:match ('%f[%a%d][%a%d]%.%a%a$') then -- one character hostname and cctld (2 chars)

return true;

elseif domain:match ('%f[%a%d][%a%d][%a%d]%.%a%a+$') then -- two character hostname and tld

return true;

elseif domain:match ('^%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?') then -- IPv4 address

return true;

else

return false;

end

end

--[[--------------------------< I S _ U R L >------------------------------------------------------------------

returns true if the scheme and domain parts of a url appear to be a valid url; else false.

This function is the last step in the validation process. This function is separate because there are cases that

are not covered by split_url(), for example is_parameter_ext_wikilink() which is looking for bracketted external

wikilinks.

]]

local function is_url (scheme, domain)

if is_set (scheme) then -- if scheme is set check it and domain

return is_scheme (scheme) and is_domain_name (domain);

else

return is_domain_name (domain); -- scheme not set when url is protocol relative

end

end

--[[--------------------------< S P L I T _ U R L >------------------------------------------------------------

Split a url into a scheme, authority indicator, and domain.

First remove Fully Qualified Domain Name terminator (a dot following tld) (if any) and any path(/), query(?) or fragment(#).

If protocol relative url, return nil scheme and domain else return nil for both scheme and domain.

When not protocol relative, get scheme, authority indicator, and domain. If there is an authority indicator (one

or more '/' characters immediately following the scheme's colon), make sure that there are only 2.

Strip off any port and path;

]]

local function split_url (url_str)

local scheme, authority, domain;

url_str = url_str:gsub ('([%a%d])%.?[/%?#].*$', '%1'); -- strip FQDN terminator and path(/), query(?), fragment (#) (the capture prevents false replacement of '//')

if url_str:match ('^//%S*') then -- if there is what appears to be a protocol relative url

domain = url_str:match ('^//(%S*)')

elseif url_str:match ('%S-:/*%S+') then -- if there is what appears to be a scheme, optional authority indicator, and domain name

scheme, authority, domain = url_str:match ('(%S-:)(/*)(%S+)'); -- extract the scheme, authority indicator, and domain portions

authority = authority:gsub ('//', , 1); -- replace place 1 pair of '/' with nothing;

if is_set(authority) then -- if anything left (1 or 3+ '/' where authority should be) then

return scheme; -- return scheme only making domain nil which will cause an error message

end

domain = domain:gsub ('(%a):%d+', '%1'); -- strip port number if present

end

return scheme, domain;

end

--[[--------------------------< L I N K _ P A R A M _ O K >---------------------------------------------------

checks the content of |title-link=, |series-link=, |author-link= etc for properly formatted content: no wikilinks, no urls

Link parameters are to hold the title of a wikipedia article so none of the WP:TITLESPECIALCHARACTERS are allowed:

# < > | { } _

except the underscore which is used as a space in wiki urls and # which is used for section links

returns false when the value contains any of these characters.

When there are no illegal characters, this function returns TRUE if value DOES NOT appear to be a valid url (the


|-link= parameter is ok); else false when value appears to be a valid url (the |-link= parameter is NOT ok).

]]

local function link_param_ok (value)

local scheme, domain;

if value:find ('[<>%[%]|{}]') then -- if any prohibited characters

return false;

end

scheme, domain = split_url (value); -- get scheme or nil and domain or nil from url;

return not is_url (scheme, domain); -- return true if value DOES NOT appear to be a valid url

end

--[[--------------------------< L I N K _ T I T L E _ O K >---------------------------------------------------

Use link_param_ok() to validate |-link= value and its matching |= value.</p><br />|<title>= may be wikilinked but not when |<param>-link= has a value. This function emits an error message when<p>that condition exists</p><p>]]</p><p>local function link_title_ok (link, lorig, title, torig)</p><p>local orig;</p><p> if is_set (link) then -- don't bother if <param>-link doesn't have a value</p><p> if not link_param_ok (link) then -- check |<param>-link= markup</p><p> orig = lorig; -- identify the failing link parameter</p><p> elseif title:find ('%[%[') then -- check |title= for wikilink markup</p><p> orig = torig; -- identify the failing |title= parameter</p><p> end</p><p> end</p><p> if is_set (orig) then</p><p> table.insert( z.message_tail, { set_error( 'bad_paramlink', orig)}); -- url or wikilink in |title= with |title-link=;</p><p> end</p><p>end</p>--[[--------------------------< C H E C K _ U R L >------------------------------------------------------------<p>Determines whether a URL string appears to be valid.</p><p>First we test for space characters. If any are found, return false. Then split the url into scheme and domain</p><p>portions, or for protocol relative (//example.com) urls, just the domain. Use is_url() to validate the two</p><p>portions of the url. If both are valid, or for protocol relative if domain is valid, return true, else false.</p><p>Because it is different from a standard url, and because this module used external_link() to make external links</p><p>that work for standard and news: links, we validate newsgroup names here. The specification for a newsgroup name</p><p>is at https://tools.ietf.org/html/rfc5536#section-3.1.4</p><p>]]</p><p>local function check_url( url_str )</p><p> if nil == url_str:match ("^%S+$") then -- if there are any spaces in |url=value it can't be a proper url</p><p> return false;</p><p> end</p><p> local scheme, domain;</p><p> scheme, domain = split_url (url_str); -- get scheme or nil and domain or nil from url;</p><p> </p><p> if 'news:' == scheme then -- special case for newsgroups</p><p> return domain:match('^[%a%d%+%-_]+%.[%a%d%+%-_%.]*[%a%d%+%-_]$');</p><p> end</p><p> </p><p> return is_url (scheme, domain); -- return true if value appears to be a valid url</p><p>end</p>--[=[-------------------------< I S _ P A R A M E T E R _ E X T _ W I K I L I N K >----------------------------<p>Return true if a parameter value has a string that begins and ends with square brackets [ and ] and the first</p><p>non-space characters following the opening bracket appear to be a url. The test will also find external wikilinks</p><p>that use protocol relative urls. Also finds bare urls.</p><p>The frontier pattern prevents a match on interwiki links which are similar to scheme:path urls. The tests that</p><p>find bracketed urls are required because the parameters that call this test (currently |title=, |chapter=, |work=,</p><p>and |publisher=) may have wikilinks and there are articles or redirects like '//Hus' so, while uncommon, |title=//Hus</p><p>is possible as might be <br />en://Hus<br />.</p><p>]=]</p><p>local function is_parameter_ext_wikilink (value)</p><p>local scheme, domain;</p><p> if value:match ('%f[%[]%[%a%S*:%S+.*%]') then -- if ext wikilink with scheme and domain: [xxxx://yyyyy.zzz]</p><p> scheme, domain = split_url (value:match ('%f[%[]%[(%a%S*:%S+).*%]'));</p><p> elseif value:match ('%f[%[]%[//%S+.*%]') then -- if protocol relative ext wikilink: [//yyyyy.zzz]</p><p> scheme, domain = split_url (value:match ('%f[%[]%[(//%S+).*%]'));</p><p> elseif value:match ('%a%S*:%S+') then -- if bare url with scheme; may have leading or trailing plain text</p><p> scheme, domain = split_url (value:match ('(%a%S*:%S+)'));</p><p> elseif value:match ('//%S+') then -- if protocol relative bare url: //yyyyy.zzz; may have leading or trailing plain text</p><p> scheme, domain = split_url (value:match ('(//%S+)')); -- what is left should be the domain</p><p> else</p><p> return false; -- didn't find anything that is obviously a url</p><p> end</p><p> return is_url (scheme, domain); -- return true if value appears to be a valid url</p><p>end</p>--[[-------------------------< C H E C K _ F O R _ U R L >-----------------------------------------------------<p>loop through a list of parameters and their values. Look at the value and if it has an external link, emit an error message.</p><p>]]</p><p>local function check_for_url (parameter_list)</p><p>local error_message = <i>;</i></p><p> for k, v in pairs (parameter_list) do -- for each parameter in the list</p><p> if is_parameter_ext_wikilink (v) then -- look at the value; if there is a url add an error message</p><p> if is_set(error_message) then -- once we've added the first portion of the error message ...</p><p> error_message=error_message .. ", "; -- ... add a comma space separator</p><p> end</p><p> error_message=error_message .. "|" .. k .. "="; -- add the failed parameter</p><p> end</p><p> end</p><p> if is_set (error_message) then -- done looping, if there is an error message, display it</p><p> table.insert( z.message_tail, { set_error( 'param_has_ext_link', {error_message}, true ) } );</p><p> end</p><p>end</p>--[[--------------------------< S A F E _ F O R _ U R L >------------------------------------------------------<p>Escape sequences for content that will be used for URL descriptions</p><p>]]</p><p>local function safe_for_url( str )</p><p> if str:match( "%[%[.-%]%]" ) ~= nil then</p><p> table.insert( z.message_tail, { set_error( 'wikilink_in_url', {}, true ) } );</p><p> end</p><p> </p><p> return str:gsub( '[%[%]\]', { </p><p> ['['] = '[',</p><p> [']'] = ']',</p><p> ['\'] = ' ' } );</p><p>end</p>--[[--------------------------< E X T E R N A L _ L I N K >----------------------------------------------------<p>Format an external link with error checking</p><p>]]</p><p>local function external_link( URL, label, source, access)</p><p> local error_str = "";</p><p> local domain;</p><p> local path;</p><p> local base_url;</p><p> if not is_set( label ) then</p><p> label = URL;</p><p> if is_set( source ) then</p><p> error_str = set_error( 'bare_url_missing_title', { wrap_style ('parameter', source) }, false, " " );</p><p> else</p><p> error( cfg.messages["bare_url_no_origin"] );</p><p> end </p><p> end</p><p> if not check_url( URL ) then</p><p> error_str = set_error( 'bad_url', {wrap_style ('parameter', source)}, false, " " ) .. error_str;</p><p> end</p><p> </p><p> domain, path = URL:match ('^([/%.%-%+:%a%d]+)([/%?#].*)$'); -- split the url into scheme plus domain and path</p><p> if path then -- if there is a path portion</p><p> path = path:gsub ('[%[%]]', {['[']='%5b',[']']='%5d'}); -- replace '[' and ']' with their percent encoded values</p><p> URL = table.concat ({domain, path}); -- and reassemble</p><p> end</p><p> base_url = table.concat({ "[", URL, " ", safe_for_url (label), "]" }); -- assemble a wikimarkup url</p><p> if is_set (access) then -- access level (subscription, registration, limited)</p><p> base_url = substitute (cfg.presentation['ext-link-access-signal'], {cfg.presentation[access].class, cfg.presentation[access].title, base_url}); -- add the appropriate icon</p><p> end</p><p> </p><p> return table.concat ({base_url, error_str});</p><p>end</p>--[[--------------------------< D E P R E C A T E D _ P A R A M E T E R >--------------------------------------<p>Categorize and emit an error message when the citation contains one or more deprecated parameters. The function includes the</p><p>offending parameter name to the error message. Only one error message is emitted regardless of the number of deprecated</p><p>parameters in the citation.</p><p>added_deprecated_cat is a boolean declared in page scope variables above</p><p>]]</p><p>local function deprecated_parameter(name)</p><p> if not added_deprecated_cat then</p><p> added_deprecated_cat = true; -- note that we've added this category</p><p> table.insert( z.message_tail, { set_error( 'deprecated_params', {name}, true ) } ); -- add error message</p><p> end</p><p>end</p>--[=[-------------------------< K E R N _ Q U O T E S >--------------------------------------------------------<p>Apply kerning to open the space between the quote mark provided by the Module and a leading or trailing quote</p><p>mark contained in a |title= or |chapter= parameter's value.</p><p>This function will positive kern either single or double quotes:</p><p> "'Unkerned title with leading and trailing single quote marks'"</p><p> " 'Kerned title with leading and trailing single quote marks' " (in real life the kerning isn't as wide as this example)</p><p>Double single quotes (italic or bold wikimarkup) are not kerned.</p><p>Replaces unicode quotemarks in plain text or in the label portion of a D style wikilink with typewriter</p><p>quote marks regardless of the need for kerning. Unicode quote marks are not replaced in simple D wikilinks.</p><p>Call this function for chapter titles, for website titles, etc; not for book titles.</p><p>]=]</p><p>local function kern_quotes (str)</p><p> local cap=<i>;</i></p><p> local cap2=<i>;</i></p><p> local wl_type, label, link;</p><p> wl_type, label, link = is_wikilink (str); -- wl_type is: 0, no wl (text in label variable); 1, D; 2, D</p><p> </p><p> if 1 == wl_type then -- D simple wikilink with or without quote marks</p><p> if mw.ustring.match (str, '%[%[[\\"“”\\'‘’].+[\\"“”\\'‘’]%]%]') then -- leading and trailing quote marks</p><p> str = substitute (cfg.presentation['kern-wl-both'], str);</p><p> elseif mw.ustring.match (str, '%[%[[\\"“”\\'‘’].+%]%]') then -- leading quote marks</p><p> str = substitute (cfg.presentation['kern-wl-left'], str);</p><p> elseif mw.ustring.match (str, '%[%[.+[\\"“”\\'‘’]%]%]') then -- trailing quote marks</p><p> str = substitute (cfg.presentation['kern-wl-right'], str);</p><p> end</p><p> else -- plain text or D; text in label variable</p><p> label= mw.ustring.gsub (label, '[“”]', '\\"'); -- replace “” (U+201C & U+201D) with " (typewriter double quote mark)</p><p> label= mw.ustring.gsub (label, '[‘’]', '\\<i>); -- replace ‘’ (U+2018 & U+2019) with ' (typewriter single quote mark)</i></p><p> cap, cap2 = mw.ustring.match (label, "^([\\"\\'])([^\\'].+)"); -- match leading double or single quote but not doubled single quotes (italic markup)</p><p> if is_set (cap) then</p><p> label = substitute (cfg.presentation['kern-left'], {cap, cap2});</p><p> end</p><p> </p><p> cap, cap2 = mw.ustring.match (label, "^(.+[^\\'])([\\"\\'])$") -- match trailing double or single quote but not doubled single quotes (italic markup)</p><p> if is_set (cap) then</p><p> label = substitute (cfg.presentation['kern-right'], {cap, cap2});</p><p> end</p><p> </p><p> if 2 == wl_type then</p><p> str = make_wikilink (link, label); -- reassemble the wikilink</p><p> else</p><p> str = label;</p><p> end</p><p> end</p><p> return str;</p><p>end</p>--[[--------------------------< F O R M A T _ S C R I P T _ V A L U E >----------------------------------------<br />|script-title= holds title parameters that are not written in Latin based scripts: Chinese, Japanese, Arabic, Hebrew, etc. These scripts should<p>not be italicized and may be written right-to-left. The value supplied by |script-title= is concatenated onto Title after Title has been wrapped</p><p>in italic markup.</p><p>Regardless of language, all values provided by |script-title= are wrapped in <bdi>...</bdi> tags to isolate rtl languages from the English left to right.</p><br />|script-title= provides a unique feature. The value in |script-title= may be prefixed with a two-character ISO639-1 language code and a colon:<p> |script-title=ja*** *** (where * represents a Japanese character)</p><p>Spaces between the two-character code and the colon and the colon and the first script character are allowed:</p><p> |script-title=ja : *** ***</p><p> |script-title=ja: *** ***</p><p> |script-title=ja *** ***</p><p>Spaces preceding the prefix are allowed: |script-title = ja*** ***</p><p>The prefix is checked for validity. If it is a valid ISO639-1 language code, the lang attribute (lang="ja") is added to the <bdi> tag so that browsers can</p><p>know the language the tag contains. This may help the browser render the script more correctly. If the prefix is invalid, the lang attribute</p><p>is not added. At this time there is no error message for this condition.</p><p>Supports |script-title= and |script-chapter=</p><p>TODO: error messages when prefix is invalid ISO639-1 code; when script_value has prefix but no script;</p><p>]]</p><p>local function format_script_value (script_value)</p><p> local lang=<i>; -- initialize to empty string</i></p><p> local name;</p><p> if script_value:match('^%l%l%s*:') then -- if first 3 non-space characters are script language prefix</p><p> lang = script_value:match('^(%l%l)%s*:%s*%S.*'); -- get the language prefix or nil if there is no script</p><p> if not is_set (lang) then</p><p> return <i>; -- script_value was just the prefix so return empty string</i></p><p> end</p><p> -- if we get this far we have prefix and script</p><p> name = cfg.lang_code_remap[lang] or mw.language.fetchLanguageName( lang, "en" ); -- get language name so that we can use it to categorize</p><p> if is_set (name) then -- is prefix a proper ISO 639-1 language code?</p><p> script_value = script_value:gsub ('^%l%l%s*:%s*', <i>); -- strip prefix from script</i></p><p> -- is prefix one of these language codes?</p><p> if in_array (lang, cfg.script_lang_codes) then</p><p> add_prop_cat ('script_with_name', {name, lang})</p><p> else</p><p> add_prop_cat ('script')</p><p> end</p><p> lang = ' lang="' .. lang .. '" '; -- convert prefix into a lang attribute</p><p> else</p><p> lang = <i>; -- invalid so set lang to empty string</i></p><p> end</p><p> end</p><p> script_value = substitute (cfg.presentation['bdi'], {lang, script_value}); -- isolate in case script is rtl</p><p> return script_value;</p><p>end</p>--[[--------------------------< S C R I P T _ C O N C A T E N A T E >------------------------------------------<p>Initially for |title= and |script-title=, this function concatenates those two parameter values after the script value has been</p><p>wrapped in <bdi> tags.</p><p>]]</p><p>local function script_concatenate (title, script)</p><p> if is_set (script) then</p><p> script = format_script_value (script); -- <bdi> tags, lang atribute, categorization, etc; returns empty string on error</p><p> if is_set (script) then</p><p> title = title .. ' ' .. script; -- concatenate title and script title</p><p> end</p><p> end</p><p> return title;</p><p>end</p>--[[--------------------------< W R A P _ M S G >--------------------------------------------------------------<p>Applies additional message text to various parameter values. Supplied string is wrapped using a message_list</p><p>configuration taking one argument. Supports lower case text for {{citation}} templates. Additional text taken</p><p>from citation_config.messages - the reason this function is similar to but separate from wrap_style().</p><p>]]</p><p>local function wrap_msg (key, str, lower)</p><p> if not is_set( str ) then</p><p> return "";</p><p> end</p><p> if true == lower then</p><p> local msg;</p><p> msg = cfg.messages[key]:lower(); -- set the message to lower case before</p><p> return substitute( msg, str ); -- including template text</p><p> else</p><p> return substitute( cfg.messages[key], str );</p><p> end </p><p>end</p>--[[--------------------------< W I K I S O U R C E _ U R L _ M A K E >----------------------------------------<p>makes a wikisource url from wikisource interwiki link. returns the url and appropriate label; nil else.</p><p>str is the value assigned to |chapter= (or aliases) or |title= or |title-link=</p><p>]]</p><p>local function wikisource_url_make (str)</p><p> local wl_type, D, L;</p><p> local ws_url, ws_label;</p><p> wl_type, D, L = is_wikilink (str); -- wl_type is 0 (not a wikilink), 1 (simple wikilink), 2 (complex wikilink)</p><p> if 0 == wl_type then -- not a wikilink; might be from |title-link=</p><p> str = D:match ('^[Ww]ikisource:(.+)') or D:match ('^[Ss]:(.+)'); -- article title from interwiki link with long-form or short-form namespace</p><p> if is_set (str) then</p><p> ws_url = table.concat ({ -- build a wikisource url</p><p> 'https://en.wikisource.org/wiki/', -- prefix</p><p> str, -- article title</p><p> });</p><p> ws_label = str; -- label for the url</p><p> end</p><p> elseif 1 == wl_type then -- simple wikilink: <span class="namespace">ws article</span></p><p> str = D:match ('^[Ww]ikisource:(.+)') or D:match ('^[Ss]:(.+)'); -- article title from interwiki link with long-form or short-form namespace</p><p> if is_set (str) then</p><p> ws_url = table.concat ({ -- build a wikisource url</p><p> 'https://en.wikisource.org/wiki/', -- prefix</p><p> str, -- article title</p><p> });</p><p> ws_label = str; -- label for the url</p><p> end</p><p> elseif 2 == wl_type then -- non-so-simple wikilink: <span class="namespace">displayed text</span> (D)</p><p> str = L:match ('^[Ww]ikisource:(.+)') or L:match ('^[Ss]:(.+)'); -- article title from interwiki link with long-form or short-form namespace</p><p> if is_set (str) then</p><p> ws_label = D; -- get ws article name from display portion of interwiki link</p><p> ws_url = table.concat ({ -- build a wikisource url</p><p> 'https://en.wikisource.org/wiki/', -- prefix</p><p> str, -- article title without namespace from link portion of wikilink</p><p> });</p><p> end</p><p> end</p><p> </p><p> if ws_url then</p><p> ws_url = mw.uri.encode (ws_url, 'WIKI'); -- make a usable url</p><p> ws_url = ws_url:gsub ('%%23', '#'); -- undo percent encoding of anchor</p><p> end</p><p> return ws_url, ws_label, L or D; -- return proper url or nil and a label or nil</p><p>end</p>--[[--------------------------< F O R M A T _ C H A P T E R _ T I T L E >--------------------------------------<p>Format the four chapter parameters: |script-chapter=, |chapter=, |trans-chapter=, and |chapter-url= into a single Chapter meta-</p><p>parameter (chapter_url_source used for error messages).</p><p>]]</p><p>local function format_chapter_title (scriptchapter, chapter, transchapter, chapterurl, chapter_url_source, no_quotes, access)</p><p> local chapter_error = <i>;</i></p><p> local ws_url, ws_label, L = wikisource_url_make (chapter); -- make a wikisource url and label from a wikisource interwiki link</p><p> if ws_url then</p><p> ws_label = ws_label:gsub ('_', <i>); -- replace underscore separaters with space characters</i></p><p> chapter = ws_label;</p><p> end</p><p> if not is_set (chapter) then</p><p> chapter = <i>; -- to be safe for concatenation</i></p><p> else</p><p> if false == no_quotes then</p><p> chapter = kern_quotes (chapter); -- if necessary, separate chapter title's leading and trailing quote marks from Module provided quote marks</p><p> chapter = wrap_style ('quoted-title', chapter);</p><p> end</p><p> end</p><p> chapter = script_concatenate (chapter, scriptchapter) -- <bdi> tags, lang atribute, categorization, etc; must be done after title is wrapped</p><p> if is_set (chapterurl) then</p><p> chapter = external_link (chapterurl, chapter, chapter_url_source, access); -- adds bare_url_missing_title error if appropriate</p><p> elseif ws_url then</p><p> chapter = external_link (ws_url, chapter .. ' ', 'ws link in chapter'); -- adds bare_url_missing_title error if appropriate; space char to move icon away from chap text; TODO: better way to do this?</p><p> chapter = substitute (cfg.presentation['interwiki-icon'], {cfg.presentation['class-wikisource'], L, chapter}); </p><p> end</p><p> if is_set (transchapter) then</p><p> transchapter = wrap_style ('trans-quoted-title', transchapter);</p><p> if is_set (chapter) then</p><p> chapter = chapter .. ' ' .. transchapter;</p><p> else -- here when transchapter without chapter or script-chapter</p><p> chapter = transchapter; --</p><p> chapter_error = ' ' .. set_error ('trans_missing_title', {'chapter'});</p><p> end</p><p> end</p>-- if is_set (chapterurl) then-- chapter = external_link (chapterurl, chapter, chapter_url_source, access); -- adds bare_url_missing_title error if appropriate-- end<p> return chapter .. chapter_error;</p><p>end</p>--[[--------------------------< H A S _ I N V I S I B L E _ C H A R S >----------------------------------------<p>This function searches a parameter's value for nonprintable or invisible characters. The search stops at the</p><p>first match.</p><p>This function will detect the visible replacement character when it is part of the wikisource.</p><p>Detects but ignores nowiki and math stripmarkers. Also detects other named stripmarkers (gallery, math, pre, ref)</p><p>and identifies them with a slightly different error message. See also coins_cleanup().</p><p>Detects but ignores the character pattern that results from the transclusion of {{'}} templates.</p><p>Output of this function is an error message that identifies the character or the Unicode group, or the stripmarker</p><p>that was detected along with its position (or, for multi-byte characters, the position of its first byte) in the</p><p>parameter value.</p><p>]]</p><p>local function has_invisible_chars (param, v)</p><p> local position = <i>; -- position of invisible char or starting position of stripmarker</i></p><p> local dummy; -- end of matching string; not used but required to hold end position when a capture is returned</p><p> local capture; -- used by stripmarker detection to hold name of the stripmarker</p><p> local i=1;</p><p> local stripmarker, apostrophe;</p><p> </p><p> capture = string.match (v, '[%w%p ]*'); -- Test for values that are simple ASCII text and bypass other tests if true</p><p> if capture == v then -- if same there are no unicode characters</p><p> return;</p><p> end</p><p> while cfg.invisible_chars[i] do</p><p> local char=cfg.invisible_chars[i][1] -- the character or group name</p><p> local pattern=cfg.invisible_chars[i][2] -- the pattern used to find it</p><p> position, dummy, capture = mw.ustring.find (v, pattern) -- see if the parameter value contains characters that match the pattern</p><p> </p><p> if position and (char == 'zero width joiner') then -- if we found a zero width joiner character</p><p> if mw.ustring.find (v, cfg.indic_script) then -- its ok if one of the indic scripts</p><p> position = nil; -- unset position</p><p> end</p><p> end</p><p> </p><p> if position then</p><p> if 'nowiki' == capture or 'math' == capture or -- nowiki and math stripmarkers (not an error condition)</p><p> ('templatestyles' == capture and in_array (param, {'id', 'quote'})) then -- templatestyles stripmarker allowed in these parameters</p><p> stripmarker = true; -- set a flag</p><p> elseif true == stripmarker and 'delete' == char then -- because stripmakers begin and end with the delete char, assume that we've found one end of a stripmarker</p><p> position = nil; -- unset</p><p> else</p><p> local err_msg;</p><p> if capture then</p><p> err_msg = capture .. ' ' .. char;</p><p> else</p><p> err_msg = char .. ' ' .. 'character';</p><p> end</p><p> table.insert( z.message_tail, { set_error( 'invisible_char', {err_msg, wrap_style ('parameter', param), position}, true ) } ); -- add error message</p><p> return; -- and done with this parameter</p><p> end</p><p> end</p><p> i=i+1; -- bump our index</p><p> end</p><p>end</p>--[[--------------------------< A R G U M E N T _ W R A P P E R >----------------------------------------------<p>Argument wrapper. This function provides support for argument mapping defined in the configuration file so that</p><p>multiple names can be transparently aliased to single internal variable.</p><p>]]</p><p>local function argument_wrapper( args )</p><p> local origin = {};</p><p> </p><p> return setmetatable({</p><p> ORIGIN = function( self, k )</p><p> local dummy = self[k]; --force the variable to be loaded.</p><p> return origin[k];</p><p> end</p><p> },</p><p> {</p><p> __index = function ( tbl, k )</p><p> if origin[k] ~= nil then</p><p> return nil;</p><p> end</p><p> </p><p> local args, list, v = args, cfg.aliases[k];</p><p> </p><p> if type( list ) == 'table' then</p><p> v, origin[k] = select_one( args, list, 'redundant_parameters' );</p><p> if origin[k] == nil then</p><p> origin[k] = <i>; -- Empty string, not nil</i></p><p> end</p><p> elseif list ~= nil then</p><p> v, origin[k] = args[list], list;</p><p> else</p><p> -- maybe let through instead of raising an error?</p><p> -- v, origin[k] = args[k], k;</p><p> error( cfg.messages['unknown_argument_map'] );</p><p> end</p><p> </p><p> -- Empty strings, not nil;</p><p> if v == nil then</p><p> v = cfg.defaults[k] or <i>;</i></p><p> origin[k] = <i>;</i></p><p> end</p><p> </p><p> tbl = rawset( tbl, k, v );</p><p> return v;</p><p> end,</p><p> });</p><p>end</p>--[[--------------------------< N O W R A P _ D A T E >--------------------------------------------------------<p>When date is YYYY-MM-DD format wrap in nowrap span: <span ...>YYYY-MM-DD</span>. When date is DD MMMM YYYY or is</p><p>MMMM DD, YYYY then wrap in nowrap span: <span ...>DD MMMM</span> YYYY or <span ...>MMMM DD,</span> YYYY</p><p>DOES NOT yet support MMMM YYYY or any of the date ranges.</p><p>]]</p><p>local function nowrap_date (date)</p><p> local cap=<i>;</i></p><p> local cap2=<i>;</i></p><p> if date:match("^%d%d%d%d%-%d%d%-%d%d$") then</p><p> date = substitute (cfg.presentation['nowrap1'], date);</p><p> </p><p> elseif date:match("^%a+%s*%d%d?,%s+%d%d%d%d$") or date:match ("^%d%d?%s*%a+%s+%d%d%d%d$") then</p><p> cap, cap2 = string.match (date, "^(.*)%s+(%d%d%d%d)$");</p><p> date = substitute (cfg.presentation['nowrap2'], {cap, cap2});</p><p> end</p><p> </p><p> return date;</p><p>end</p>--[[--------------------------< S E T _ T I T L E T Y P E >----------------------------------------------------<p>This function sets default title types (equivalent to the citation including |type=<default value>) for those templates that have defaults.</p><p>Also handles the special case where it is desirable to omit the title type from the rendered citation (|type=none).</p><p>]]</p><p>local function set_titletype (cite_class, title_type)</p><p> if is_set(title_type) then</p><p> if "none" == title_type then</p><p> title_type = ""; -- if |type=none then type parameter not displayed</p><p> end</p><p> return title_type; -- if |type= has been set to any other value use that value</p><p> end</p><p> return cfg.title_types [cite_class] or <i>; -- set template's default title type; else empty string for concatenation</i></p><p>end</p>--[[--------------------------< H Y P H E N _ T O _ D A S H >--------------------------------------------------<p>Converts a hyphen to a dash under certain conditions. The hyphen must separate like items; unlike items are</p><p>returned unmodified. These forms are modified:</p><p> letter - letter (A - B)</p><p> digit - digit (4-5)</p><p> digit separator digit - digit separator digit (4.1-4.5 or 4-1-4-5)</p><p> letterdigit - letterdigit (A1-A5) (an optional separator between letter and digit is supported – a.1-a.5 or a-1-a-5)</p><p> digitletter - digitletter (5a - 5d) (an optional separator between letter and digit is supported – 5.a-5.d or 5-a-5-d)</p><p>any other forms are returned unmodified.</p><p>str may be a comma- or semicolon-separated list</p><p>]]</p><p>local function hyphen_to_dash( str )</p><p> if not is_set (str) then</p><p> return str;</p><p> end</p><p> </p><p> str, count = str:gsub ('^%(%((.+)%)%)$', '%1'); -- remove accept-this-as-written markup when it wraps all of str</p><p> if 0 ~= count then -- non-zero when markup removed; zero else</p><p> return str; -- nothing to do, we're done</p><p> end</p><p> </p><p> str = str:gsub ('&[nm]dash;', {['–'] = '–', ['—'] = '—'}); -- replace — and – entities with their characters; semicolon mucks up the text.split</p><p> </p><p> local out = {};</p><p> local list = mw.text.split (str, '%s*[,;]%s*'); -- split str at comma or semicolon separators if there are any</p><p> for _, item in ipairs (list) do -- for each item in the list</p><p> if mw.ustring.match (item, '^%w*[%.%-]?%w+%s*[%-–—]%s*%w*[%.%-]?%w+$') then -- if a hyphenated range or has endash or emdash separators</p><p> if item:match ('%a+[%.%-]?%d+%s*%-%s*%a+[%.%-]?%d+') or -- letterdigit hyphen letterdigit (optional separator between letter and digit)</p><p> item:match ('%d+[%.%-]?%a+%s*%-%s*%d+[%.%-]?%a+') or -- digitletter hyphen digitletter (optional separator between digit and letter)</p><p> item:match ('%d+[%.%-]%d+%s*%-%s*%d+[%.%-]%d+') or -- digit separator digit hyphen digit separator digit</p><p> item:match ('%d+%s*%-%s*%d+') or -- digit hyphen digit</p><p> item:match ('%a+%s*%-%s*%a+') then -- letter hyphen letter</p><p> item = item:gsub ('(%w*[%.%-]?%w+)%s*%-%s*(%w*[%.%-]?%w+)', '%1–%2'); -- replace hyphen, remove extraneous space characters</p><p> else</p><p> item = mw.ustring.gsub (item, '%s*[–—]%s*', '–'); -- for endash or emdash separated ranges, replace em with en, remove extraneous white space</p><p> end</p><p> end</p><p> item = item:gsub ('^%(%((.+)%)%)$', '%1'); -- remove the accept-this-as-written markup</p><p> table.insert (out, item); -- add the (possibly modified) item to the output table</p><p> end</p><p> return table.concat (out, ', '); -- concatenate the output table into a comma separated string</p><p>end</p>--[[--------------------------< S A F E _ J O I N >------------------------------------------------------------<p>Joins a sequence of strings together while checking for duplicate separation characters.</p><p>]]</p><p>local function safe_join( tbl, duplicate_char )</p><p> local f = {}; -- create a function table appropriate to type of 'dupicate character'</p><p> if 1 == #duplicate_char then -- for single byte ascii characters use the string library functions</p><p> f.gsub=string.gsub</p><p> f.match=string.match</p><p> f.sub=string.sub</p><p> else -- for multi-byte characters use the ustring library functions</p><p> f.gsub=mw.ustring.gsub</p><p> f.match=mw.ustring.match</p><p> f.sub=mw.ustring.sub</p><p> end</p><p> local str = <i>; -- the output string</i></p><p> local comp = <i>; -- what does 'comp' mean?</i></p><p> local end_chr = <i>;</i></p><p> local trim;</p><p> for _, value in ipairs( tbl ) do</p><p> if value == nil then value = <i>; end</i></p><p> </p><p> if str == <i> then -- if output string is empty</i></p><p> str = value; -- assign value to it (first time through the loop)</p><p> elseif value ~= <i> then</i></p><p> if value:sub(1,1) == '<' then -- Special case of values enclosed in spans and other markup.</p><p> comp = value:gsub( "%b<>", "" ); -- remove html markup (<span>string</span> -> string)</p><p> else</p><p> comp = value;</p><p> end</p><p> -- typically duplicate_char is sepc</p><p> if f.sub(comp, 1,1) == duplicate_char then -- is first character same as duplicate_char? why test first character?</p><p> -- Because individual string segments often (always?) begin with terminal punct for the</p><p> -- preceding segment: 'First element' .. 'sepc next element' .. etc?</p><p> trim = false;</p><p> end_chr = f.sub(str, -1,-1); -- get the last character of the output string</p><p> -- str = str .. "<HERE(enchr=" .. end_chr.. ")" -- debug stuff?</p><p> if end_chr == duplicate_char then -- if same as separator</p><p> str = f.sub(str, 1,-2); -- remove it</p><p> elseif end_chr == "'" then -- if it might be wikimarkup</p><p> if f.sub(str, -3,-1) == duplicate_char .. "<i>" then -- if last three chars of str are sepc</i></p><p> str = f.sub(str, 1, -4) .. "<i>"; -- remove them and add back </i></p><p> elseif f.sub(str, -5,-1) == duplicate_char .. "]]<i>" then -- if last five chars of str are sepc]]</i></p><p> trim = true; -- why? why do this and next differently from previous?</p><p> elseif f.sub(str, -4,-1) == duplicate_char .. "]<i>" then -- if last four chars of str are sepc]</i></p><p> trim = true; -- same question</p><p> end</p><p> elseif end_chr == "]" then -- if it might be wikimarkup</p><p> if f.sub(str, -3,-1) == duplicate_char .. "]]" then -- if last three chars of str are sepc]] wikilink</p><p> trim = true;</p><p> elseif f.sub(str, -3,-1) == duplicate_char .. '"]' then -- if last three chars of str are sepc"] quoted external link</p><p> trim = true;</p><p> elseif f.sub(str, -2,-1) == duplicate_char .. "]" then -- if last two chars of str are sepc] external link</p><p> trim = true;</p><p> elseif f.sub(str, -4,-1) == duplicate_char .. "<i>]" then -- normal case when |url=something & |title=Title.</i></p><p> trim = true;</p><p> end</p><p> elseif end_chr == " " then -- if last char of output string is a space</p><p> if f.sub(str, -2,-1) == duplicate_char .. " " then -- if last two chars of str are <sepc><space></p><p> str = f.sub(str, 1,-3); -- remove them both</p><p> end</p><p> end</p><p> if trim then</p><p> if value ~= comp then -- value does not equal comp when value contains html markup</p><p> local dup2 = duplicate_char;</p><p> if f.match(dup2, "%A" ) then dup2 = "%" .. dup2; end -- if duplicate_char not a letter then escape it</p><p> </p><p> value = f.gsub(value, "(%b<>)" .. dup2, "%1", 1 ) -- remove duplicate_char if it follows html markup</p><p> else</p><p> value = f.sub(value, 2, -1 ); -- remove duplicate_char when it is first character</p><p> end</p><p> end</p><p> end</p><p> str = str .. value; --add it to the output string</p><p> end</p><p> end</p><p> return str;</p><p>end</p>--[[--------------------------< I S _ S U F F I X >------------------------------------------------------------<p>returns true is suffix is properly formed Jr, Sr, or ordinal in the range 2–9. Puncutation not allowed.</p><p>]]</p><p>local function is_suffix (suffix)</p><p> if in_array (suffix, {'Jr', 'Sr', '2nd', '3rd'}) or suffix:match ('^%dth$') then</p><p> return true;</p><p> end</p><p> return false;</p><p>end</p>--[[--------------------------< I S _ G O O D _ V A N C _ N A M E >--------------------------------------------<p>For Vancouver Style, author/editor names are supposed to be rendered in Latin (read ASCII) characters. When a name</p><p>uses characters that contain diacritical marks, those characters are to converted to the corresponding Latin character.</p><p>When a name is written using a non-Latin alphabet or logogram, that name is to be transliterated into Latin characters.</p><p>These things are not currently possible in this module so are left to the editor to do.</p><p>This test allows |first= and |last= names to contain any of the letters defined in the four Unicode Latin character sets</p><p> <span class='url'>C0 Controls and Basic Latin</span> 0041–005A, 0061–007A</p><p> <span class='url'>C1 Controls and Latin-1 Supplement</span> 00C0–00D6, 00D8–00F6, 00F8–00FF</p><p> <span class='url'>Latin Extended-A</span> 0100–017F</p><p> <span class='url'>Latin Extended-B</span> 0180–01BF, 01C4–024F</p><br />|lastn= also allowed to contain hyphens, spaces, and apostrophes. (http://www.ncbi.nlm.nih.gov/books/NBK7271/box/A35029/)<br />|firstn= also allowed to contain hyphens, spaces, apostrophes, and periods<p>This original test:</p><p> if nil == mw.ustring.find (last, "^[A-Za-zÀ-ÖØ-öø-ƿDŽ-ɏ%-%s%']*$") or nil == mw.ustring.find (first, "^[A-Za-zÀ-ÖØ-öø-ƿDŽ-ɏ%-%s%'%.]+[2-6%a]*$") then</p><p>was written ouside of the code editor and pasted here because the code editor gets confused between character insertion point and cursor position.</p><p>The test has been rewritten to use decimal character escape sequence for the individual bytes of the unicode characters so that it is not necessary</p><p>to use an external editor to maintain this code.</p><p> \\195\\128-\\195\\150 – À-Ö (U+00C0–U+00D6 – C0 controls)</p><p> \\195\\152-\\195\\182 – Ø-ö (U+00D8-U+00F6 – C0 controls)</p><p> \\195\\184-\\198\\191 – ø-ƿ (U+00F8-U+01BF – C0 controls, Latin extended A & B)</p><p> \\199\\132-\\201\\143 – DŽ-ɏ (U+01C4-U+024F – Latin extended B)</p><p>]]</p><p>local function is_good_vanc_name (last, first)</p><p> local first, suffix = first:match ('(.-),?%s*([%dJS][%drndth]+)%.?$') or first; -- if first has something that looks like a generational suffix, get it</p><p> if is_set (suffix) then</p><p> if not is_suffix (suffix) then</p><p> add_vanc_error ('suffix');</p><p> return false; -- not a name with an appropriate suffix</p><p> end</p><p> end</p><p> if nil == mw.ustring.find (last, "^[A-Za-z\\195\\128-\\195\\150\\195\\152-\\195\\182\\195\\184-\\198\\191\\199\\132-\\201\\143%-%s%']*$") or</p><p> nil == mw.ustring.find (first, "^[A-Za-z\\195\\128-\\195\\150\\195\\152-\\195\\182\\195\\184-\\198\\191\\199\\132-\\201\\143%-%s%'%.]*$") then</p><p> add_vanc_error ('non-Latin character');</p><p> return false; -- not a string of latin characters; Vancouver requires Romanization</p><p> end;</p><p> return true;</p><p>end</p>--[[--------------------------< R E D U C E _ T O _ I N I T I A L S >------------------------------------------<p>Attempts to convert names to initials in support of |name-list-format=vanc.</p><p>Names in |firstn= may be separated by spaces or hyphens, or for initials, a period. See http://www.ncbi.nlm.nih.gov/books/NBK7271/box/A35062/.</p><p>Vancouver style requires family rank designations (Jr, II, III, etc) to be rendered as Jr, 2nd, 3rd, etc. See http://www.ncbi.nlm.nih.gov/books/NBK7271/box/A35085/.</p><p>This code only accepts and understands generational suffix in the Vancouver format because Roman numerals look like, and can be mistaken for, initials.</p><p>This function uses ustring functions because firstname initials may be any of the unicode Latin characters accepted by is_good_vanc_name ().</p><p>]]</p><p>local function reduce_to_initials(first)</p><p> local name, suffix = mw.ustring.match(first, "^(%u+) ([%dJS][%drndth]+)$");</p><p> if not name then -- if not initials and a suffix</p><p> name = mw.ustring.match(first, "^(%u+)$"); -- is it just intials?</p><p> end</p><p> if name then -- if first is initials with or without suffix</p><p> if 3 > mw.ustring.len (name) then -- if one or two initials</p><p> if suffix then -- if there is a suffix</p><p> if is_suffix (suffix) then -- is it legitimate?</p><p> return first; -- one or two initials and a valid suffix so nothing to do</p><p> else</p><p> add_vanc_error ('suffix'); -- one or two initials with invalid suffix so error message</p><p> return first; -- and return first unmolested</p><p> end</p><p> else</p><p> return first; -- one or two initials without suffix; nothing to do</p><p> end</p><p> end</p><p> end -- if here then name has 3 or more uppercase letters so treat them as a word</p><p> local initials, names = {}, {}; -- tables to hold name parts and initials</p><p> local i = 1; -- counter for number of initials</p><p> names = mw.text.split (first, '[%s,]+'); -- split into a table of names and possible suffix</p><p> while names[i] do -- loop through the table</p><p> if 1 < i and names[i]:match ('[%dJS][%drndth]+%.?$') then -- if not the first name, and looks like a suffix (may have trailing dot)</p><p> names[i] = names[i]:gsub ('%.', <i>); -- remove terminal dot if present</i></p><p> if is_suffix (names[i]) then -- if a legitimate suffix</p><p> table.insert (initials, ' ' .. names[i]); -- add a separator space, insert at end of initials table</p><p> break; -- and done because suffix must fall at the end of a name</p><p> end -- no error message if not a suffix; possibly because of Romanization</p><p> end</p><p> if 3 > i then</p><p> table.insert (initials, mw.ustring.sub(names[i],1,1)); -- insert the intial at end of initials table</p><p> end</p><p> i = i+1; -- bump the counter</p><p> end</p><p> </p><p> return table.concat(initials) -- Vancouver format does not include spaces.</p><p>end</p>--[[--------------------------< L I S T _ P E O P L E >-------------------------------------------------------<p>Formats a list of people (e.g. authors / editors)</p><p>]]</p><p>local function list_people(control, people, etal)</p><p> local sep;</p><p> local namesep;</p><p> local format = control.format</p><p> local maximum = control.maximum</p><p> local lastauthoramp = control.lastauthoramp;</p><p> local text = {}</p><p> if 'vanc' == format then -- Vancouver-like author/editor name styling?</p><p> sep = cfg.presentation['sep_nl_vanc']; -- name-list separator between authors is a comma</p><p> namesep = cfg.presentation['sep_name_vanc']; -- last/first separator is a space</p><p> else</p><p> sep = cfg.presentation['sep_nl']; -- name-list separator between authors is a semicolon</p><p> namesep = cfg.presentation['sep_name']; -- last/first separator is <comma><space></p><p> end</p><p> </p><p> if sep:sub(-1,-1) ~= " " then sep = sep .. " " end</p><p> if is_set (maximum) and maximum < 1 then return "", 0; end -- returned 0 is for EditorCount; not used for authors</p><p> </p><p> for i,person in ipairs(people) do</p><p> if is_set(person.last) then</p><p> local mask = person.mask</p><p> local one</p><p> local sep_one = sep;</p><p> if is_set (maximum) and i > maximum then</p><p> etal = true;</p><p> break;</p><p> elseif (mask ~= nil) then</p><p> local n = tonumber(mask)</p><p> if (n ~= nil) then</p><p> one = string.rep("—",n)</p><p> else</p><p> one = mask;</p><p> sep_one = " ";</p><p> end</p><p> else</p><p> one = person.last</p><p> local first = person.first</p><p> if is_set(first) then</p><p> if ( "vanc" == format ) then -- if vancouver format</p><p> one = one:gsub ('%.', <i>); -- remove periods from surnames (http://www.ncbi.nlm.nih.gov/books/NBK7271/box/A35029/)</i></p><p> if not person.corporate and is_good_vanc_name (one, first) then -- and name is all Latin characters; corporate authors not tested</p><p> first = reduce_to_initials(first) -- attempt to convert first name(s) to initials</p><p> end</p><p> end</p><p> one = one .. namesep .. first;</p><p> end</p><p> if is_set(person.link) and person.link ~= control.page_name then</p><p> one = make_wikilink (person.link, one); -- link author/editor if this page is not the author's/editor's page</p><p> end</p><p> end</p><p> table.insert( text, one )</p><p> table.insert( text, sep_one )</p><p> end</p><p> end</p><p> local count = #text / 2; -- (number of names + number of separators) divided by 2</p><p> if count > 0 then</p><p> if count > 1 and is_set(lastauthoramp) and not etal then</p><p> text[#text-2] = " & "; -- replace last separator with ampersand text</p><p> end</p><p> text[#text] = nil; -- erase the last separator</p><p> end</p><p> </p><p> local result = table.concat(text) -- construct list</p><p> if etal and is_set (result) then -- etal may be set by |display-authors=etal but we might not have a last-first list</p><p> result = result .. sep .. ' ' .. cfg.messages['et al']; -- we've go a last-first list and etal so add et al.</p><p> end</p><p> </p><p> return result, count</p><p>end</p>--[[--------------------------< A N C H O R _ I D >------------------------------------------------------------<p>Generates a CITEREF anchor ID if we have at least one name or a date. Otherwise returns an empty string.</p><p>namelist is one of the contributor-, author-, or editor-name lists chosen in that order. year is Year or anchor_year.</p><p>]]</p><p>local function anchor_id (namelist, year)</p><p> local names={}; -- a table for the one to four names and year</p><p> for i,v in ipairs (namelist) do -- loop through the list and take up to the first four last names</p><p> names[i] = v.last</p><p> if i == 4 then break end -- if four then done</p><p> end</p><p> table.insert (names, year); -- add the year at the end</p><p> local id = table.concat(names); -- concatenate names and year for CITEREF id</p><p> if is_set (id) then -- if concatenation is not an empty string</p><p> return "CITEREF" .. id; -- add the CITEREF portion</p><p> else</p><p> return <i>; -- return an empty string; no reason to include CITEREF id in this citation</i></p><p> end</p><p>end</p>--[[--------------------------< N A M E _ H A S _ E T A L >----------------------------------------------------<p>Evaluates the content of author and editor name parameters for variations on the theme of et al. If found,</p><p>the et al. is removed, a flag is set to true and the function returns the modified name and the flag.</p><p>This function never sets the flag to false but returns it's previous state because it may have been set by</p><p>previous passes through this function or by the parameters |display-authors=etal or |display-editors=etal</p><p>]]</p><p>local function name_has_etal (name, etal, nocat)</p><p> if is_set (name) then -- name can be nil in which case just return</p><p> local etal_pattern = "[;,]? *[\\"']*%f[%a][Ee][Tt] *[Aa][Ll][%.\\"']*$" -- variations on the 'et al' theme</p><p> local others_pattern = "[;,]? *%f[%a]and [Oo]thers"; -- and alternate to et al.</p><p> </p><p> if name:match (etal_pattern) then -- variants on et al.</p><p> name = name:gsub (etal_pattern, <i>); -- if found, remove</i></p><p> etal = true; -- set flag (may have been set previously here or by |display-authors=etal)</p><p> if not nocat then -- no categorization for |vauthors=</p><p> add_maint_cat ('etal'); -- and add a category if not already added</p><p> end</p><p> elseif name:match (others_pattern) then -- if not 'et al.', then 'and others'?</p><p> name = name:gsub (others_pattern, <i>); -- if found, remove</i></p><p> etal = true; -- set flag (may have been set previously here or by |display-authors=etal)</p><p> if not nocat then -- no categorization for |vauthors=</p><p> add_maint_cat ('etal'); -- and add a category if not already added</p><p> end</p><p> end</p><p> end</p><p> return name, etal; --</p><p>end</p>--[[--------------------------< N A M E _ H A S _ E D _ M A R K U P >------------------------------------------<p>Evaluates the content of author and editor parameters for extranious editor annotations: ed, ed., eds, (Ed.), etc.</p><p>These annotation do not belong in author parameters and are redundant in editor parameters. If found, the function</p><p>adds the editor markup maintenance category.</p><p>]]</p><p>local function name_has_ed_markup (name, list_name)</p><p> local _, pattern;</p><p> local patterns = { -- these patterns match annotations at end of name</p><p> '%f[%(%[][%(%[]%s*[Ee][Dd][Ss]?%.?%s*[%)%]]?$', -- (ed) or (eds): leading '(', case insensitive 'ed', optional 's', '.' and/or ')'</p><p> '[,%.%s]%f[e]eds?%.?$', -- ed or eds: without '('or ')'; case sensitive (ED could be initials Ed could be name)</p><p> '%f[%(%[][%(%[]%s*[Ee][Dd][Ii][Tt][Oo][Rr][Ss]?%.?%s*[%)%]]?$', -- (editor) or (editors): leading '(', case insensitive, optional '.' and/or ')'</p><p> '[,%.%s]%f[Ee][Ee][Dd][Ii][Tt][Oo][Rr][Ss]?%.?$', -- editor or editors: without '('or ')'; case insensitive</p><p> </p><p> -- these patterns match annotations at beginning of name</p><p> '^eds?[%.,;]', -- ed. or eds.: lower case only, optional 's', requires '.'</p><p> '^[%(%[]%s*[Ee][Dd][Ss]?%.?%s*[%)%]]', -- (ed) or (eds): also sqare brackets, case insensitive, optional 's', '.'</p><p> '^[%(%[]?%s*[Ee][Dd][Ii][Tt][Oo][Rr][Ss]?%A', -- (editor or (editors: also sq brackets, case insensitive, optional brackets, 's'</p><p> '^[%(%[]?%s*[Ee][Dd][Ii][Tt][Ee][Dd]%A', -- (edited: also sq brackets, case insensitive, optional brackets</p><p> }</p><p> if is_set (name) then</p><p> for _, pattern in ipairs (patterns) do -- spin through patterns table and</p><p> if name:match (pattern) then</p><p> add_maint_cat ('extra_text_names', cfg.special_case_translation [list_name]); -- add a maint cat for this template</p><p> break;</p><p> end</p><p> end</p><p> end</p><p> return name; -- and done</p><p>end</p>--[[--------------------------< N A M E _ H A S _ M U L T _ N A M E S >----------------------------------------<p>Evaluates the content of author and editor (surnames only) parameters for multiple names. Multiple names are</p><p>indicated if there is more than one comma and or semicolon. If found, the function adds the multiple name</p><p>(author or editor) maintenance category.</p><p>]]</p><p>local function name_has_mult_names (name, list_name)</p><p>local count, _;</p><p> if is_set (name) then</p><p> _, count = name:gsub ('[;,]', <i>); -- count the number of separator-like characters</i></p><p> </p><p> if 1 < count then -- param could be |author= or |editor= so one separator character is acceptable</p><p> add_maint_cat ('mult_names', cfg.special_case_translation [list_name]); -- more than one separator indicates multiple names so add a maint cat for this template</p><p> end</p><p> end</p><p> return name; -- and done</p><p>end</p>--[[--------------------------< N A M E _ C H E C K S >--------------------------------------------------------<p>This function calls various name checking functions used to validate the content of the various name-holding</p><p>parameters.</p><p>]]</p><p>local function name_checks (last, first, list_name)</p><p> if is_set (last) then</p><p> if last:match ('^%(%(.*%)%)$') then -- if wrapped in doubled parentheses, accept as written</p><p> last = last:match ('^%(%((.*)%)%)$'); -- strip parens</p><p> else</p><p> last = name_has_mult_names (last, list_name); -- check for multiple names in the parameter (last only)</p><p> last = name_has_ed_markup (last, list_name); -- check for extraneous 'editor' annotation</p><p> end</p><p> end</p><p> if is_set (first) then</p><p> if first:match ('^%(%(.*%)%)$') then -- if wrapped in doubled parentheses, accept as written</p><p> first = first:match ('^%(%((.*)%)%)$'); -- strip parens</p><p> else</p><p> first = name_has_ed_markup (first, list_name); -- check for extraneous 'editor' annotation</p><p> end</p><p> end</p><p> return last, first; -- done</p><p> end</p>--[[--------------------------< E X T R A C T _ N A M E S >----------------------------------------------------<p>Gets name list from the input arguments</p><p>Searches through args in sequential order to find |lastn= and |firstn= parameters (or their aliases), and their matching link and mask parameters.</p><p>Stops searching when both |lastn= and |firstn= are not found in args after two sequential attempts: found |last1=, |last2=, and |last3= but doesn't</p><p>find |last4= and |last5= then the search is done.</p><p>This function emits an error message when there is a |firstn= without a matching |lastn=. When there are 'holes' in the list of last names, |last1= and |last3=</p><p>are present but |last2= is missing, an error message is emitted. |lastn= is not required to have a matching |firstn=.</p><p>When an author or editor parameter contains some form of 'et al.', the 'et al.' is stripped from the parameter and a flag (etal) returned</p><p>that will cause list_people() to add the static 'et al.' text from Module:Citation/CS1/Configuration. This keeps 'et al.' out of the</p><p>template's metadata. When this occurs, the page is added to a maintenance category.</p><p>]]</p><p>local function extract_names(args, list_name)</p><p> local names = {}; -- table of names</p><p> local last; -- individual name components</p><p> local first;</p><p> local link;</p><p> local mask;</p><p> local i = 1; -- loop counter/indexer</p><p> local n = 1; -- output table indexer</p><p> local count = 0; -- used to count the number of times we haven't found a |last= (or alias for authors, |editor-last or alias for editors)</p><p> local etal=false; -- return value set to true when we find some form of et al. in an author parameter</p><p> local err_msg_list_name = list_name:match ("(%w+)List") .. 's list'; -- modify AuthorList or EditorList for use in error messages if necessary</p><p> while true do</p><p> last = select_one( args, cfg.aliases[list_name .. '-Last'], 'redundant_parameters', i ); -- search through args for name components beginning at 1</p><p> first = select_one( args, cfg.aliases[list_name .. '-First'], 'redundant_parameters', i );</p><p> link = select_one( args, cfg.aliases[list_name .. '-Link'], 'redundant_parameters', i );</p><p> mask = select_one( args, cfg.aliases[list_name .. '-Mask'], 'redundant_parameters', i );</p><p> last, etal = name_has_etal (last, etal, false); -- find and remove variations on et al.</p><p> first, etal = name_has_etal (first, etal, false); -- find and remove variations on et al.</p><p> last, first= name_checks (last, first, list_name); -- multiple names, extraneous annotation, etc checks</p><p> </p><p> if first and not last then -- if there is a firstn without a matching lastn</p><p> table.insert( z.message_tail, { set_error( 'first_missing_last', {err_msg_list_name, i}, true ) } ); -- add this error message</p><p> elseif not first and not last then -- if both firstn and lastn aren't found, are we done?</p><p> count = count + 1; -- number of times we haven't found last and first</p><p> if 2 <= count then -- two missing names and we give up</p><p> break; -- normal exit or there is a two-name hole in the list; can't tell which</p><p> end</p><p> else -- we have last with or without a first</p><p> link_title_ok (link, list_name:match ("(%w+)List"):lower() .. '-link' .. i, last, list_name:match ("(%w+)List"):lower() .. '-last' .. i); -- check for improper wikimarkup</p><p> names[n] = {last = last, first = first, link = link, mask = mask, corporate=false}; -- add this name to our names list (corporate for |vauthors= only)</p><p> n = n + 1; -- point to next location in the names table</p><p> if 1 == count then -- if the previous name was missing</p><p> table.insert( z.message_tail, { set_error( 'missing_name', {err_msg_list_name, i-1}, true ) } ); -- add this error message</p><p> end</p><p> count = 0; -- reset the counter, we're looking for two consecutive missing names</p><p> end</p><p> i = i + 1; -- point to next args location</p><p> end</p><p> </p><p> return names, etal; -- all done, return our list of names</p><p>end</p>--[[--------------------------< G E T _ I S O 6 3 9 _ C O D E >------------------------------------------------<p>Validates language names provided in |language= parameter if not an ISO639-1 or 639-2 code.</p><p>Returns the language name and associated two- or three-character code. Because case of the source may be incorrect</p><p>or different from the case that WikiMedia uses, the name comparisons are done in lower case and when a match is</p><p>found, the Wikimedia version (assumed to be correct) is returned along with the code. When there is no match, we</p><p>return the original language name string.</p><p>mw.language.fetchLanguageNames(<local wiki language>, 'all') returns a list of languages that in some cases may include</p><p>extensions. For example, code 'cbk-zam' and its associated name 'Chavacano de Zamboanga' (MediaWiki does not support</p><p>code 'cbk' or name 'Chavacano'. Most (all?) of these languages are not used a 'language' codes per se, rather they</p><p>are used as sub-domain names: cbk-zam.wikipedia.org. A list of language names and codes supported by fetchLanguageNames()</p><p>can be found at Template:Citation Style documentation/language/doc</p><p>Names that are included in the list will be found if that name is provided in the |language= parameter. For example,</p><p>if |language=Chavacano de Zamboanga, that name will be found with the associated code 'cbk-zam'. When names are found</p><p>and the associated code is not two or three characters, this function returns only the WikiMedia language name.</p><p>Some language names have multiple entries under different codes:</p><p> Aromanian has code rup and code roa-rup</p><p>When this occurs, this function returns the language name and the 2- or 3-character code</p><p>Adapted from code taken from Module:Check ISO 639-1.</p><p>]]</p><p>local function get_iso639_code (lang, this_wiki_code)</p><p> if cfg.lang_name_remap[lang:lower()] then -- if there is a remapped name (because MediaWiki uses something that we don't think is correct)</p><p> return cfg.lang_name_remap[lang:lower()][1], cfg.lang_name_remap[lang:lower()][2]; -- for this language 'name', return a possibly new name and appropriate code</p><p> end</p><p> local ietf_code; -- because some languages have both ietf-like codes and iso 639-like codes</p><p> local ietf_name;</p><p> </p><p> local languages = mw.language.fetchLanguageNames(this_wiki_code, 'all') -- get a list of language names known to Wikimedia</p><p> -- ('all' is required for North Ndebele, South Ndebele, and Ojibwa)</p><p> local langlc = mw.ustring.lower(lang); -- lower case version for comparisons</p><p> for code, name in pairs(languages) do -- scan the list to see if we can find our language</p><p> if langlc == mw.ustring.lower(name) then</p><p> if 2 == code:len() or 3 == code:len() then -- two- or three-character codes only; extensions not supported</p><p> return name, code; -- so return the name and the code</p><p> end</p><p> ietf_code = code; -- remember that we found an ietf-like code and save its name</p><p> ietf_name = name; -- but keep looking for a 2- or 3-char code</p><p> end</p><p> end</p><p> -- didn't find name with 2- or 3-char code; if ietf-like code found return</p><p> return ietf_code and ietf_name or lang; -- associated name; return original language text else</p><p>end</p>--[[--------------------------< L A N G U A G E _ P A R A M E T E R >------------------------------------------<p>Gets language name from a provided two- or three-character ISO 639 code. If a code is recognized by MediaWiki,</p><p>use the returned name; if not, then use the value that was provided with the language parameter.</p><p>When |language= contains a recognized language (either code or name), the page is assigned to the category for</p><p>that code: Category:Norwegian-language sources (no). For valid three-character code languages, the page is assigned</p><p>to the single category for '639-2' codes: Category:CS1 ISO 639-2 language sources.</p><p>Languages that are the same as the local wiki are not categorized. MediaWiki does not recognize three-character</p><p>equivalents of two-character codes: code 'ar' is recognized bit code 'ara' is not.</p><p>This function supports multiple languages in the form |language=nb, French, th where the language names or codes are</p><p>separated from each other by commas.</p><p>]]</p><p>local function language_parameter (lang)</p><p> local code; -- the two- or three-character language code</p><p> local name; -- the language name</p><p> local language_list = {}; -- table of language names to be rendered</p><p> local names_table = {}; -- table made from the value assigned to |language=</p><p> local this_wiki = mw.getContentLanguage(); -- get a language object for this wiki</p><p> local this_wiki_code = this_wiki:getCode() -- get this wiki's language code</p><p> local this_wiki_name = mw.language.fetchLanguageName(this_wiki_code, this_wiki_code); -- get this wiki's language name</p><p> names_table = mw.text.split (lang, '%s*,%s*'); -- names should be a comma separated list</p><p> for _, lang in ipairs (names_table) do -- reuse lang</p><p> name = cfg.lang_code_remap[lang:lower()]; -- first see if this is a code that is not supported by MediaWiki but is in remap</p><p> if name then -- there was a remapped code so</p><p> lang = lang:gsub ('^(%a%a%a?)%-.*', '%1'); -- strip ietf tags from code</p><p> else</p><p> if lang:match ('^%a%a%-') then -- strip ietf tags from code; TODO: is there a need to support 3-char with tag?</p><p> lang = lang:match ('(%a%a)%-') -- keep only 639-1 code portion to lang; TODO: do something with 3166 alpha 2 country code?</p><p> end</p><p> if 2 == lang:len() or 3 == lang:len() then -- if two-or three-character code</p><p> name = mw.language.fetchLanguageName (lang:lower(), this_wiki_code); -- get language name if |language= is a proper code</p><p> end</p><p> end</p><p> if is_set (name) then -- if |language= specified a valid code</p><p> code = lang:lower(); -- save it</p><p> else</p><p> name, code = get_iso639_code (lang, this_wiki_code); -- attempt to get code from name (assign name here so that we are sure of proper capitalization)</p><p> end</p><p> </p><p> if is_set (code) then -- only 2- or 3-character codes</p><p> name = cfg.lang_code_remap[code] or name; -- override wikimedia when they misuse language codes/names</p><p> if this_wiki_code ~= code then -- when the language is not the same as this wiki's language</p><p> if 2 == code:len() then -- and is a two-character code</p><p> add_prop_cat ('foreign_lang_source' .. code, {name, code}) -- categorize it</p><p> else -- or is a recognized language (but has a three-character code)</p><p> add_prop_cat ('foreign_lang_source_2' .. code, {code}) -- categorize it differently TODO: support mutliple three-character code categories per cs1|2 template</p><p> end</p><p> end</p><p> else</p><p> add_maint_cat ('unknown_lang'); -- add maint category if not already added</p><p> end</p><p> </p><p> table.insert (language_list, name);</p><p> name = <i>; -- so we can reuse it</i></p><p> end</p><p> </p><p> code = #language_list -- reuse code as number of languages in the list</p><p> if 2 >= code then</p><p> name = table.concat (language_list, cfg.messages['parameter-pair-separator']) -- insert '<space>and<space>' between two language names</p><p> elseif 2 < code then</p><p> name = table.concat (language_list, ', '); -- and concatenate with '<comma><space>' separators</p><p> name = name:gsub (', ([^,]+)$', cfg.messages['parameter-final-separator'] .. '%1'); -- replace last '<comma><space>' separator with '<comma><space>and<space>' separator</p><p> end</p><p> if this_wiki_name == name then</p><p> return <i>; -- if one language and that language is this wiki's return an empty string (no annotation)</i></p><p> end</p><p> return (" " .. wrap_msg ('language', name)); -- otherwise wrap with '(in ...)'</p><p> --[[ TODO: should only return blank or name rather than full list</p><p> so we can clean up the bunched parenthetical elements Language, Type, Format</p><p> ]]</p><p>end</p>--[[--------------------------< S E T _ C S 1 _ S T Y L E >----------------------------------------------------<p>Set style settings for CS1 citation templates. Returns separator and postscript settings</p><p>At en.wiki, for cs1:</p><p> ps gets: '.'</p><p> sep gets: '.'</p><p>]]</p><p>local function set_cs1_style (ps)</p><p> if not is_set (ps) then -- unless explicitely set to something</p><p> ps = cfg.presentation['ps_cs1']; -- terminate the rendered citation</p><p> end</p><p> return cfg.presentation['sep_cs1'], ps; -- element separator</p><p>end</p>--[[--------------------------< S E T _ C S 2 _ S T Y L E >----------------------------------------------------<p>Set style settings for CS2 citation templates. Returns separator, postscript, ref settings</p><p>At en.wiki, for cs2:</p><p> ps gets: <i> (empty string - no terminal punctuation)</i></p><p> sep gets: ','</p><p>]]</p><p>local function set_cs2_style (ps, ref)</p><p> if not is_set (ps) then -- if |postscript= has not been set, set cs2 default</p><p> ps = cfg.presentation['ps_cs2']; -- terminate the rendered citation</p><p> end</p><p> if not is_set (ref) then -- if |ref= is not set</p><p> ref = "harv"; -- set default |ref=harv</p><p> end</p><p> return cfg.presentation['sep_cs2'], ps, ref; -- element separator</p><p>end</p>--[[--------------------------< G E T _ S E T T I N G S _ F R O M _ C I T E _ C L A S S >----------------------<p>When |mode= is not set or when its value is invalid, use config.CitationClass and parameter values to establish</p><p>rendered style.</p><p>]]</p><p>local function get_settings_from_cite_class (ps, ref, cite_class)</p><p> local sep;</p><p> if (cite_class == "citation") then -- for citation templates (CS2)</p><p> sep, ps, ref = set_cs2_style (ps, ref);</p><p> else -- not a citation template so CS1</p><p> sep, ps = set_cs1_style (ps);</p><p> end</p><p> return sep, ps, ref -- return them all</p><p>end</p>--[[--------------------------< S E T _ S T Y L E >------------------------------------------------------------<p>Establish basic style settings to be used when rendering the citation. Uses |mode= if set and valid or uses</p><p>config.CitationClass from the template's #invoke: to establish style.</p><p>]]</p><p>local function set_style (mode, ps, ref, cite_class)</p><p> local sep;</p><p> if 'cs2' == mode then -- if this template is to be rendered in CS2 (citation) style</p><p> sep, ps, ref = set_cs2_style (ps, ref);</p><p> elseif 'cs1' == mode then -- if this template is to be rendered in CS1 (cite xxx) style</p><p> sep, ps = set_cs1_style (ps);</p><p> else -- anything but cs1 or cs2</p><p> sep, ps, ref = get_settings_from_cite_class (ps, ref, cite_class); -- get settings based on the template's CitationClass</p><p> end</p><p> if 'none' == ps:lower() then -- if assigned value is 'none' then</p><p> ps = <i>; -- set to empty string</i></p><p> end</p><p> </p><p> return sep, ps, ref</p><p>end</p>--[=[-------------------------< I S _ P D F >------------------------------------------------------------------<p>Determines if a url has the file extension that is one of the pdf file extensions used by <span class="namespace">Common.css</span> when</p><p>applying the pdf icon to external links.</p><p>returns true if file extension is one of the recognized extensions, else false</p><p>]=]</p><p>local function is_pdf (url)</p><p> return url:match ('%.pdf$') or url:match ('%.PDF$') or url:match ('%.pdf[%?#]') or url:match ('%.PDF[%?#]');</p><p>end</p>--[[--------------------------< S T Y L E _ F O R M A T >------------------------------------------------------<p>Applies css style to |format=, |chapter-format=, etc. Also emits an error message if the format parameter does</p><p>not have a matching url parameter. If the format parameter is not set and the url contains a file extension that</p><p>is recognized as a pdf document by MediaWiki's commons.css, this code will set the format parameter to (PDF) with</p><p>the appropriate styling.</p><p>]]</p><p>local function style_format (format, url, fmt_param, url_param)</p><p> if is_set (format) then</p><p> format = wrap_style ('format', format); -- add leading space, parentheses, resize</p><p> if not is_set (url) then</p><p> format = format .. set_error( 'format_missing_url', {fmt_param, url_param} ); -- add an error message</p><p> end</p><p> elseif is_pdf (url) then -- format is not set so if url is a pdf file then</p><p> format = wrap_style ('format', 'PDF'); -- set format to pdf</p><p> else</p><p> format = <i>; -- empty string for concatenation</i></p><p> end</p><p> return format;</p><p>end</p>--[[--------------------------< G E T _ D I S P L A Y _ A U T H O R S _ E D I T O R S >------------------------<p>Returns a number that defines the number of names displayed for author and editor name lists and a boolean flag</p><p>to indicate when et al. should be appended to the name list.</p><p>When the value assigned to |display-xxxxors= is a number greater than or equal to zero, return the number and</p><p>the previous state of the 'etal' flag (false by default but may have been set to true if the name list contains</p><p>some variant of the text 'et al.').</p><p>When the value assigned to |display-xxxxors= is the keyword 'etal', return a number that is one greater than the</p><p>number of authors in the list and set the 'etal' flag true. This will cause the list_people() to display all of</p><p>the names in the name list followed by 'et al.'</p><p>In all other cases, returns nil and the previous state of the 'etal' flag.</p><p>inputs:</p><p> max: A['DisplayAuthors'] or A['DisplayEditors']; a number or some flavor of etal</p><p> count: #a or #e</p><p> list_name: 'authors' or 'editors'</p><p> etal: author_etal or editor_etal</p><p>]]</p><p>local function get_display_authors_editors (max, count, list_name, etal)</p><p> if is_set (max) then</p><p> if 'etal' == max:lower():gsub("[ '%.]", <i>) then -- the :gsub() portion makes 'etal' from a variety of 'et al.' spellings and stylings</i></p><p> max = count + 1; -- number of authors + 1 so display all author name plus et al.</p><p> etal = true; -- overrides value set by extract_names()</p><p> elseif max:match ('^%d+$') then -- if is a string of numbers</p><p> max = tonumber (max); -- make it a number</p><p> if max >= count then -- if |display-xxxxors= value greater than or equal to number of authors/editors</p><p> add_maint_cat ('disp_auth_ed', cfg.special_case_translation [list_name]);</p><p> end</p><p> else -- not a valid keyword or number</p><p> table.insert( z.message_tail, { set_error( 'invalid_param_val', {'display-' .. list_name, max}, true ) } ); -- add error message</p><p> max = nil; -- unset; as if |display-xxxxors= had not been set</p><p> end</p><p> end</p><p> </p><p> return max, etal;</p><p>end</p>--[[--------------------------< E X T R A _ T E X T _ I N _ P A G E _ C H E C K >------------------------------<p>Adds page to Category:CS1 maint: extra text if |page= or |pages= has what appears to be some form of p. or pp.</p><p>abbreviation in the first characters of the parameter content.</p><p>check Page and Pages for extraneous p, p., pp, and pp. at start of parameter value:</p><p> good pattern: '^P[^%.P%l]' matches when |page(s)= begins PX or P# but not Px where x and X are letters and # is a dgiit</p><p> bad pattern: '^[Pp][Pp]' matches matches when |page(s)= begins pp or pP or Pp or PP</p><p>]]</p><p>local function extra_text_in_page_check (page)</p><p> local good_pattern = '^P[^%.Pp]'; -- ok to begin with uppercase P: P7 (pg 7 of section P) but not p123 (page 123) TODO: add Gg for PG or Pg?</p><p> local bad_pattern = '^[Pp]?[Pp]%.?[ %d]';</p><p> if not page:match (good_pattern) and (page:match (bad_pattern) or page:match ('^[Pp]ages?')) then</p><p> add_maint_cat ('extra_text');</p><p> end</p><p>end</p>--[=[-------------------------< G E T _ V _ N A M E _ T A B L E >----------------------------------------------<p>split apart a |vauthors= or |veditors= parameter. This function allows for corporate names, wrapped in doubled</p><p>parentheses to also have commas; in the old version of the code, the doubled parnetheses were included in the</p><p>rendered citation and in the metadata. Individual author names may be wikilinked</p><p> |vauthors=Jones AB, White EB, ((Black, Brown, and Co.))</p><p>]=]</p><p>local function get_v_name_table (vparam, output_table, output_link_table)</p><p> local name_table = mw.text.split(vparam, "%s*,%s*"); -- names are separated by commas</p><p> local wl_type, label, link; -- wl_type not used here; just a place holder</p><p> </p><p> local i = 1;</p><p> </p><p> while name_table[i] do</p><p> if name_table[i]:match ('^%(%(.*[^%)][^%)]$') then -- first segment of corporate with one or more commas; this segment has the opening doubled parens</p><p> local name = name_table[i];</p><p> i=i+1; -- bump indexer to next segment</p><p> while name_table[i] do</p><p> name = name .. ', ' .. name_table[i]; -- concatenate with previous segments</p><p> if name_table[i]:match ('^.*%)%)$') then -- if this table member has the closing doubled parens</p><p> break; -- and done reassembling so</p><p> end</p><p> i=i+1; -- bump indexer</p><p> end</p><p> table.insert (output_table, name); -- and add corporate name to the output table</p><p> table.insert (output_link_table, <i>); -- no wikilink</i></p><p> else</p><p> wl_type, label, link = is_wikilink (name_table[i]); -- wl_type is: 0, no wl (text in label variable); 1, D; 2, D</p><p> table.insert (output_table, label); -- add this name</p><p> if 1 == wl_type then</p><p> table.insert (output_link_table, label); -- simple wikilink D</p><p> else</p><p> table.insert (output_link_table, link); -- no wikilink or D; add this link if there is one, else empty string</p><p> end</p><p> end</p><p> i = i+1;</p><p> end </p><p> return output_table;</p><p>end</p>--[[--------------------------< P A R S E _ V A U T H O R S _ V E D I T O R S >--------------------------------<p>This function extracts author / editor names from |vauthors= or |veditors= and finds matching |xxxxor-maskn= and</p><br />|xxxxor-linkn= in args. It then returns a table of assembled names just as extract_names() does.<p>Author / editor names in |vauthors= or |veditors= must be in Vancouver system style. Corporate or institutional names</p><p>may sometimes be required and because such names will often fail the is_good_vanc_name() and other format compliance</p><p>tests, are wrapped in doubled paranethese ((corporate name)) to suppress the format tests.</p><p>Supports generational suffixes Jr, 2nd, 3rd, 4th–6th.</p><p>This function sets the vancouver error when a reqired comma is missing and when there is a space between an author's initials.</p><p>]]</p><p>local function parse_vauthors_veditors (args, vparam, list_name)</p><p> local names = {}; -- table of names assembled from |vauthors=, |author-maskn=, |author-linkn=</p><p> local v_name_table = {};</p><p> local v_link_table = {}; -- when name is wikilinked, targets go in this table</p><p> local etal = false; -- return value set to true when we find some form of et al. vauthors parameter</p><p> local last, first, link, mask, suffix;</p><p> local corporate = false;</p><p> vparam, etal = name_has_etal (vparam, etal, true); -- find and remove variations on et al. do not categorize (do it here because et al. might have a period)</p><p> v_name_table = get_v_name_table (vparam, v_name_table, v_link_table); -- names are separated by commas</p><p> for i, v_name in ipairs(v_name_table) do</p><p> if v_name:match ('^%(%(.+%)%)$') then -- corporate authors are wrapped in doubled parentheses to supress vanc formatting and error detection</p><p> first = <i>; -- set to empty string for concatenation and because it may have been set for previous author/editor</i></p><p> last = v_name:match ('^%(%((.+)%)%)$') -- remove doubled parntheses</p><p> corporate = true; -- flag used in list_people()</p><p> elseif string.find(v_name, "%s") then</p><p> if v_name:find('[;%.]') then -- look for commonly occurring punctuation characters;</p><p> add_vanc_error ('punctuation');</p><p> end</p><p> local lastfirstTable = {}</p><p> lastfirstTable = mw.text.split(v_name, "%s")</p><p> first = table.remove(lastfirstTable); -- removes and returns value of last element in table which should be author intials</p><p> if is_suffix (first) then -- if a valid suffix</p><p> suffix = first -- save it as a suffix and</p><p> first = table.remove(lastfirstTable); -- get what should be the initials from the table</p><p> end -- no suffix error message here because letter combination may be result of Romanization; check for digits?</p><p> last = table.concat(lastfirstTable, " ") -- returns a string that is the concatenation of all other names that are not initials</p><p> if mw.ustring.match (last, '%a+%s+%u+%s+%a+') then</p><p> add_vanc_error ('missing comma'); -- matches last II last; the case when a comma is missing</p><p> end</p><p> if mw.ustring.match (v_name, ' %u %u$') then -- this test is in the wrong place TODO: move or replace with a more appropriate test</p><p> add_vanc_error ('name'); -- matches a space between two intiials</p><p> end</p><p> else</p><p> first = <i>; -- set to empty string for concatenation and because it may have been set for previous author/editor</i></p><p> last = v_name; -- last name or single corporate name? Doesn't support multiword corporate names? do we need this?</p><p> end</p><p> </p><p> if is_set (first) then</p><p> if not mw.ustring.match (first, "^%u?%u$") then -- first shall contain one or two upper-case letters, nothing else</p><p> add_vanc_error ('initials'); -- too many initials; mixed case initials (which may be ok Romanization); hyphenated initials</p><p> end</p><p> is_good_vanc_name (last, first); -- check first and last before restoring the suffix which may have a non-Latin digit</p><p> if is_set (suffix) then</p><p> first = first .. ' ' .. suffix; -- if there was a suffix concatenate with the initials</p><p> suffix = <i>; -- unset so we don't add this suffix to all subsequent names</i></p><p> end</p><p> else</p><p> if not corporate then</p><p> is_good_vanc_name (last, <i>);</i></p><p> end</p><p> end</p><p> link = select_one( args, cfg.aliases[list_name .. '-Link'], 'redundant_parameters', i ) or v_link_table[i];</p><p> mask = select_one( args, cfg.aliases[list_name .. '-Mask'], 'redundant_parameters', i );</p><p> names[i] = {last = last, first = first, link = link, mask = mask, corporate=corporate}; -- add this assembled name to our names list</p><p> end</p><p> return names, etal; -- all done, return our list of names</p><p>end</p>--[[--------------------------< S E L E C T _ A U T H O R _ E D I T O R _ S O U R C E >------------------------<p>Select one of |authors=, |authorn= / |lastn / firstn=, or |vauthors= as the source of the author name list or</p><p>select one of |editors=, |editorn= / editor-lastn= / |editor-firstn= or |veditors= as the source of the editor name list.</p><p>Only one of these appropriate three will be used. The hierarchy is: |authorn= (and aliases) highest and |authors= lowest and</p><p>similarly, |editorn= (and aliases) highest and |editors= lowest</p><p>When looking for |authorn= / |editorn= parameters, test |xxxxor1= and |xxxxor2= (and all of their aliases); stops after the second</p><p>test which mimicks the test used in extract_names() when looking for a hole in the author name list. There may be a better</p><p>way to do this, I just haven't discovered what that way is.</p><p>Emits an error message when more than one xxxxor name source is provided.</p><p>In this function, vxxxxors = vauthors or veditors; xxxxors = authors or editors as appropriate.</p><p>]]</p><p>local function select_author_editor_source (vxxxxors, xxxxors, args, list_name)</p><p>local lastfirst = false;</p><p> if select_one( args, cfg.aliases[list_name .. '-Last'], 'none', 1 ) or -- do this twice incase we have a |first1= without a |last1=; this ...</p><p> select_one( args, cfg.aliases[list_name .. '-First'], 'none', 1 ) or -- ... also catches the case where |first= is used with |vauthors=</p><p> select_one( args, cfg.aliases[list_name .. '-Last'], 'none', 2 ) or</p><p> select_one( args, cfg.aliases[list_name .. '-First'], 'none', 2 ) then</p><p> lastfirst=true;</p><p> end</p><p> if (is_set (vxxxxors) and true == lastfirst) or -- these are the three error conditions</p><p> (is_set (vxxxxors) and is_set (xxxxors)) or</p><p> (true == lastfirst and is_set (xxxxors)) then</p><p> local err_name;</p><p> if 'AuthorList' == list_name then -- figure out which name should be used in error message</p><p> err_name = 'author';</p><p> else</p><p> err_name = 'editor';</p><p> end</p><p> table.insert( z.message_tail, { set_error( 'redundant_parameters',</p><p> {err_name .. '-name-list parameters'}, true ) } ); -- add error message</p><p> end</p><p> if true == lastfirst then return 1 end; -- return a number indicating which author name source to use</p><p> if is_set (vxxxxors) then return 2 end;</p><p> if is_set (xxxxors) then return 3 end;</p><p> return 1; -- no authors so return 1; this allows missing author name test to run in case there is a first without last</p><p>end</p>--[[--------------------------< I S _ V A L I D _ P A R A M E T E R _ V A L U E >------------------------------<p>This function is used to validate a parameter's assigned value for those parameters that have only a limited number</p><p>of allowable values (yes, y, true, no, etc). When the parameter value has not been assigned a value (missing or empty</p><p>in the source template) the function returns true. If the parameter value is one of the list of allowed values returns</p><p>true; else, emits an error message and returns false.</p><p>]]</p><p>local function is_valid_parameter_value (value, name, possible)</p><p> if not is_set (value) then</p><p> return true; -- an empty parameter is ok</p><p> elseif in_array(value:lower(), possible) then</p><p> return true;</p><p> else</p><p> table.insert( z.message_tail, { set_error( 'invalid_param_val', {name, value}, true ) } ); -- not an allowed value so add error message</p><p> return false</p><p> end</p><p>end</p>--[[--------------------------< T E R M I N A T E _ N A M E _ L I S T >----------------------------------------<p>This function terminates a name list (author, contributor, editor) with a separator character (sepc) and a space</p><p>when the last character is not a sepc character or when the last three characters are not sepc followed by two</p><p>closing square brackets (close of a wikilink). When either of these is true, the name_list is terminated with a</p><p>single space character.</p><p>]]</p><p>local function terminate_name_list (name_list, sepc)</p><p> if (string.sub (name_list,-3,-1) == sepc .. '. ') then -- if already properly terminated</p><p> return name_list; -- just return the name list</p><p> elseif (string.sub (name_list,-1,-1) == sepc) or (string.sub (name_list,-3,-1) == sepc .. ']]') then -- if last name in list ends with sepc char</p><p> return name_list .. " "; -- don't add another</p><p> else</p><p> return name_list .. sepc .. ' '; -- otherwise terninate the name list</p><p> end</p><p>end</p>--[[-------------------------< F O R M A T _ V O L U M E _ I S S U E >----------------------------------------<p>returns the concatenation of the formatted volume and issue parameters as a single string; or formatted volume</p><p>or formatted issue, or an empty string if neither are set.</p><p>]]</p><p> </p><p>local function format_volume_issue (volume, issue, cite_class, origin, sepc, lower)</p><p> if not is_set (volume) and not is_set (issue) then</p><p> return <i>;</i></p><p> end</p><p> </p><p> if 'magazine' == cite_class or (in_array (cite_class, {'citation', 'map'}) and 'magazine' == origin) then</p><p> if is_set (volume) and is_set (issue) then</p><p> return wrap_msg ('vol-no', {sepc, volume, issue}, lower);</p><p> elseif is_set (volume) then</p><p> return wrap_msg ('vol', {sepc, volume}, lower);</p><p> else</p><p> return wrap_msg ('issue', {sepc, issue}, lower);</p><p> end</p><p> end</p><p> local vol = <i>; -- here for all cites except magazine</i></p><p> </p><p> if is_set (volume) then</p><p> if volume:match ('^[MDCLXVI]+$') or volume:match ('^%d+$')then -- volume value is all digits or all uppercase roman numerals</p><p> vol = substitute (cfg.presentation['vol-bold'], {sepc, hyphen_to_dash(volume)}); -- render in bold face</p><p> elseif (4 < mw.ustring.len(volume)) then -- not all digits or roman numerals and longer than 4 characters</p><p> vol = substitute (cfg.messages['j-vol'], {sepc, volume}); -- not bold</p><p> add_prop_cat ('long_vol');</p><p> else -- four or less characters</p><p> vol = substitute (cfg.presentation['vol-bold'], {sepc, hyphen_to_dash(volume)}); -- bold</p><p> end</p><p> end</p><p> if is_set (issue) then</p><p> return vol .. substitute (cfg.messages['j-issue'], issue);</p><p> end</p><p> return vol;</p><p>end</p>--[[-------------------------< F O R M A T _ P A G E S _ S H E E T S >-----------------------------------------<p>adds static text to one of |page(s)= or |sheet(s)= values and returns it with all of the others set to empty strings.</p><p>The return order is:</p><p> page, pages, sheet, sheets</p><p>Singular has priority over plural when both are provided.</p><p>]]</p><p>local function format_pages_sheets (page, pages, sheet, sheets, cite_class, origin, sepc, nopp, lower)</p><p> if 'map' == cite_class then -- only cite map supports sheet(s) as in-source locators</p><p> if is_set (sheet) then</p><p> if 'journal' == origin then</p><p> return <i>, </i>, wrap_msg ('j-sheet', sheet, lower), <i>;</i></p><p> else</p><p> return <i>, </i>, wrap_msg ('sheet', {sepc, sheet}, lower), <i>;</i></p><p> end</p><p> elseif is_set (sheets) then</p><p> if 'journal' == origin then</p><p> return <i>, </i>, <i>, wrap_msg ('j-sheets', sheets, lower);</i></p><p> else</p><p> return <i>, </i>, <i>, wrap_msg ('sheets', {sepc, sheets}, lower);</i></p><p> end</p><p> end</p><p> end</p><p> local is_journal = 'journal' == cite_class or (in_array (cite_class, {'citation', 'map', 'interview'}) and 'journal' == origin);</p><p> </p><p> if is_set (page) then</p><p> if is_journal then</p><p> return substitute (cfg.messages['j-page(s)'], page), <i>, </i>, <i>;</i></p><p> elseif not nopp then</p><p> return substitute (cfg.messages['p-prefix'], {sepc, page}), <i>, </i>, <i>;</i></p><p> else</p><p> return substitute (cfg.messages['nopp'], {sepc, page}), <i>, </i>, <i>;</i></p><p> end</p><p> elseif is_set(pages) then</p><p> if is_journal then</p><p> return substitute (cfg.messages['j-page(s)'], pages), <i>, </i>, <i>;</i></p><p> elseif tonumber(pages) ~= nil and not nopp then -- if pages is only digits, assume a single page number</p><p> return <i>, substitute (cfg.messages['p-prefix'], {sepc, pages}), </i>, <i>;</i></p><p> elseif not nopp then</p><p> return <i>, substitute (cfg.messages['pp-prefix'], {sepc, pages}), </i>, <i>;</i></p><p> else</p><p> return <i>, substitute (cfg.messages['nopp'], {sepc, pages}), </i>, <i>;</i></p><p> end</p><p> end</p><p> </p><p> return <i>, </i>, <i>, </i>; -- return empty strings</p><p>end</p>--[[--------------------------< I N S O U R C E _ L O C _ G E T >----------------------------------------------<p>returns one of the in-source locators: page, pages, or at.</p><p>If any of these are interwiki links to wikisource, returns the label portion of the interwikilink as plain text</p><p>for use in COinS. This COinS thing is done because here we convert an interwiki link to and external link and</p><p>add an icon span around that; get_coins_pages() doesn't know about the span. TODO: should it?</p><p>TODO: add support for sheet and sheets?; streamline;</p><p>TODO: make it so that this function returns only one of the three as the single in-source (the return value assigned</p><p>to a new name)?</p><p>]]</p><p>local function insource_loc_get (page, pages, at)</p><p> local ws_url, ws_label, coins_pages, L; -- for wikisource interwikilinks; TODO: this corrupts page metadata (span remains in place after cleanup; fix there?)</p><p> if is_set (page) then</p><p> if is_set (pages) or is_set(at) then</p><p> pages = <i>; -- unset the others</i></p><p> at = <i>;</i></p><p> end</p><p> extra_text_in_page_check (page); -- add this page to maint cat if |page= value begins with what looks like p. or pp.</p><p> ws_url, ws_label, L = wikisource_url_make (page); -- make ws url from |page= interwiki link; link portion L becomes tool tip label</p><p> if ws_url then</p><p> page = external_link (ws_url, ws_label .. ' ', 'ws link in page'); -- space char after label to move icon away from in-source text; TODO: a better way to do this?</p><p> page = substitute (cfg.presentation['interwiki-icon'], {cfg.presentation['class-wikisource'], L, page});</p><p> coins_pages = ws_label;</p><p> end</p><p> elseif is_set (pages) then</p><p> if is_set (at) then</p><p> at = <i>; -- unset</i></p><p> end</p><p> extra_text_in_page_check (pages); -- add this page to maint cat if |pages= value begins with what looks like p. or pp.</p><p> ws_url, ws_label, L = wikisource_url_make (pages); -- make ws url from |pages= interwiki link; link portion L becomes tool tip label</p><p> if ws_url then</p><p> pages = external_link (ws_url, ws_label .. ' ', 'ws link in pages'); -- space char after label to move icon away from in-source text; TODO: a better way to do this?</p><p> pages = substitute (cfg.presentation['interwiki-icon'], {cfg.presentation['class-wikisource'], L, pages});</p><p> coins_pages = ws_label;</p><p> end</p><p> elseif is_set (at) then</p><p> ws_url, ws_label, L = wikisource_url_make (at); -- make ws url from |at= interwiki link; link portion L becomes tool tip label</p><p> if ws_url then</p><p> at = external_link (ws_url, ws_label .. ' ', 'ws link in at'); -- space char after label to move icon away from in-source text; TODO: a better way to do this?</p><p> at = substitute (cfg.presentation['interwiki-icon'], {cfg.presentation['class-wikisource'], L, at});</p><p> coins_pages = ws_label;</p><p> end</p><p> end</p><p> </p><p> return page, pages, at, coins_pages;</p><p>end</p>--[=[-------------------------< A R C H I V E _ U R L _ C H E C K >--------------------------------------------<p>Check archive.org urls to make sure they at least look like they are pointing at valid archives and not to the</p><p>save snapshot url or to calendar pages. When the archive url is 'https://web.archive.org/save/' (or http://...)</p><p>archive.org saves a snapshot of the target page in the url. That is something that Wikipedia should not allow</p><p>unwitting readers to do.</p><p>When the archive.org url does not have a complete timestamp, archive.org chooses a snapshot according to its own</p><p>algorithm or provides a calendar 'search' result. <span class="namespace">ELNO</span> discourages links to search results.</p><p>This function looks at the value assigned to |archive-url= and returns empty strings for |archive-url= and</p><br />|archive-date= and an error message when:<p> |archive-url= holds an archive.org save command url</p><p> |archive-url= is an archive.org url that does not have a complete timestamp (YYYYMMDDhhmmss 14 digits) in the</p><p> correct place</p><p>otherwise returns |archive-url= and |archive-date=</p><p>There are two mostly compatible archive.org urls:</p><p> //web.archive.org/<timestamp>... -- the old form</p><p> //web.archive.org/web/<timestamp>... -- the new form</p><p>The old form does not support or map to the new form when it contains a display flag. There are four identified flags</p><p>('id_', 'js_', 'cs_', 'im_') but since archive.org ignores others following the same form (two letters and an underscore)</p><p>we don't check for these specific flags but we do check the form.</p><p>This function supports a preview mode. When the article is rendered in preview mode, this funct may return a modified</p><p>archive url:</p><p> for save command errors, return undated wildcard (/*/)</p><p> for timestamp errors when the timestamp has a wildcard, return the url unmodified</p><p> for timestamp errors when the timestamp does not have a wildcard, return with timestamp limited to six digits plus wildcard (/yyyymm*/)</p><p>]=]</p><p>local function archive_url_check (url, date)</p><p> local err_msg = <i>; -- start with the error message empty</i></p><p> local path, timestamp, flag; -- portions of the archive.or url</p><p> </p><p> if (not url:match('//web%.archive%.org/')) and (not url:match('//liveweb%.archive%.org/')) then -- also deprecated liveweb Wayback machine url</p><p> return url, date; -- not an archive.org archive, return ArchiveURL and ArchiveDate</p><p> end</p><p> if url:match('//web%.archive%.org/save/') then -- if a save command url, we don't want to allow saving of the target page</p><p> err_msg = 'save command';</p><p> url = url:gsub ('(//web%.archive%.org)/save/', '%1/*/', 1); -- for preview mode: modify ArchiveURL</p><p> elseif url:match('//liveweb%.archive%.org/') then</p><p> err_msg = 'liveweb';</p><p> else</p><p> path, timestamp, flag = url:match('//web%.archive%.org/([^%d]*)(%d+)([^/]*)/'); -- split out some of the url parts for evaluation</p><p> </p><p> if not is_set(timestamp) or 14 ~= timestamp:len() then -- path and flag optional, must have 14-digit timestamp here</p><p> err_msg = 'timestamp';</p><p> if '*' ~= flag then</p><p> url=url:gsub ('(//web%.archive%.org/[^%d]*%d?%d?%d?%d?%d?%d?)[^/]*', '%1*', 1) -- for preview, modify ts to be yearmo* max (0-6 digits plus splat)</p><p> end</p><p> elseif is_set(path) and 'web/' ~= path then -- older archive urls do not have the extra 'web/' path element</p><p> err_msg = 'path';</p><p> elseif is_set (flag) and not is_set (path) then -- flag not allowed with the old form url (without the 'web/' path element)</p><p> err_msg = 'flag';</p><p> elseif is_set (flag) and not flag:match ('%a%a_') then -- flag if present must be two alpha characters and underscore (requires 'web/' path element)</p><p> err_msg = 'flag';</p><p> else</p><p> return url, date; -- return archiveURL and ArchiveDate</p><p> end</p><p> end</p><p> -- if here, something not right so</p><p> table.insert( z.message_tail, { set_error( 'archive_url', {err_msg}, true ) } ); -- add error message and</p><p> if is_set (Frame:preprocess('{{REVISIONID}}')) then</p><p> return <i>, </i>; -- return empty strings for archiveURL and ArchiveDate</p><p> else</p><p> return url, date; -- preview mode so return archiveURL and ArchiveDate</p><p> end</p><p>end</p>--[[--------------------------< C I T A T I O N 0 >------------------------------------------------------------<p>This is the main function doing the majority of the citation formatting.</p><p>]]</p><p>local function citation0( config, args)</p><p> --[[</p><p> Load Input Parameters</p><p> The argument_wrapper facilitates the mapping of multiple aliases to single internal variable.</p><p> ]]</p><p> local A = argument_wrapper( args );</p><p> local i</p><p> -- Pick out the relevant fields from the arguments. Different citation templates</p><p> -- define different field names for the same underlying things. </p>-- set default parameter values defined by |mode= parameter.<p> local Mode = A['Mode'];</p><p> if not is_valid_parameter_value (Mode, 'mode', cfg.keywords['mode']) then</p><p> Mode = <i>;</i></p><p> end</p><p> local author_etal;</p><p> local a = {}; -- authors list from |lastn= / |firstn= pairs or |vauthors=</p><p> local Authors;</p><p> local NameListFormat = A['NameListFormat'];</p><p> local Collaboration = A['Collaboration'];</p><p> do -- to limit scope of selected</p><p> local selected = select_author_editor_source (A['Vauthors'], A['Authors'], args, 'AuthorList');</p><p> if 1 == selected then</p><p> a, author_etal = extract_names (args, 'AuthorList'); -- fetch author list from |authorn= / |lastn= / |firstn=, |author-linkn=, and |author-maskn=</p><p> elseif 2 == selected then</p><p> NameListFormat = 'vanc'; -- override whatever |name-list-format= might be</p><p> a, author_etal = parse_vauthors_veditors (args, args.vauthors, 'AuthorList'); -- fetch author list from |vauthors=, |author-linkn=, and |author-maskn=</p><p> elseif 3 == selected then</p><p> Authors = A['Authors']; -- use content of |authors=</p><p> if 'authors' == A:ORIGIN('Authors') then -- but add a maint cat if the parameter is |authors=</p><p> add_maint_cat ('authors'); -- because use of this parameter is discouraged; what to do about the aliases is a TODO:</p><p> end</p><p> end</p><p> if is_set (Collaboration) then</p><p> author_etal = true; -- so that |display-authors=etal not required</p><p> end</p><p> end</p><p> local Others = A['Others'];</p><p> local editor_etal;</p><p> local e = {}; -- editors list from |editor-lastn= / |editor-firstn= pairs or |veditors=</p><p> local Editors;</p><p> do -- to limit scope of selected</p><p> local selected = select_author_editor_source (A['Veditors'], A['Editors'], args, 'EditorList');</p><p> if 1 == selected then</p><p> e, editor_etal = extract_names (args, 'EditorList'); -- fetch editor list from |editorn= / |editor-lastn= / |editor-firstn=, |editor-linkn=, and |editor-maskn=</p><p> elseif 2 == selected then</p><p> NameListFormat = 'vanc'; -- override whatever |name-list-format= might be</p><p> e, editor_etal = parse_vauthors_veditors (args, args.veditors, 'EditorList'); -- fetch editor list from |veditors=, |editor-linkn=, and |editor-maskn=</p><p> elseif 3 == selected then</p><p> Editors = A['Editors']; -- use content of |editors=</p><p> add_maint_cat ('editors'); -- but add a maint cat because use of this parameter is discouraged</p><p> end</p><p> end</p><p> local t = {}; -- translators list from |translator-lastn= / translator-firstn= pairs</p><p> local Translators; -- assembled translators name list</p><p> t = extract_names (args, 'TranslatorList'); -- fetch translator list from |translatorn= / |translator-lastn=, -firstn=, -linkn=, -maskn=</p><p> local interviewers_list = {}; </p><p> local Interviewers; -- used later</p><p> interviewers_list = extract_names (args, 'InterviewerList'); -- process preferred interviewers parameters</p><p> local c = {}; -- contributors list from |contributor-lastn= / contributor-firstn= pairs</p><p> local Contributors; -- assembled contributors name list</p><p> local Contribution = A['Contribution'];</p><p> if in_array(config.CitationClass, {"book","citation"}) and not is_set(A['Periodical']) then -- |contributor= and |contribution= only supported in book cites</p><p> c = extract_names (args, 'ContributorList'); -- fetch contributor list from |contributorn= / |contributor-lastn=, -firstn=, -linkn=, -maskn=</p><p> </p><p> if 0 < #c then</p><p> if not is_set (Contribution) then -- |contributor= requires |contribution=</p><p> table.insert( z.message_tail, { set_error( 'contributor_missing_required_param', 'contribution')}); -- add missing contribution error message</p><p> c = {}; -- blank the contributors' table; it is used as a flag later</p><p> end</p><p> if 0 == #a then -- |contributor= requires |author=</p><p> table.insert( z.message_tail, { set_error( 'contributor_missing_required_param', 'author')}); -- add missing author error message</p><p> c = {}; -- blank the contributors' table; it is used as a flag later</p><p> end</p><p> end</p><p> else -- if not a book cite</p><p> if select_one (args, cfg.aliases['ContributorList-Last'], 'redundant_parameters', 1 ) then -- are there contributor name list parameters?</p><p> table.insert( z.message_tail, { set_error( 'contributor_ignored')}); -- add contributor ignored error message</p><p> end</p><p> Contribution = nil; -- unset</p><p> end</p><p> if not is_valid_parameter_value (NameListFormat, 'name-list-format', cfg.keywords['name-list-format']) then -- only accepted value for this parameter is 'vanc'</p><p> NameListFormat = <i>; -- anything else, set to empty string</i></p><p> end</p><p> local Year = A['Year'];</p><p> local PublicationDate = A['PublicationDate'];</p><p> local OrigYear = A['OrigYear'];</p><p> local Date = A['Date'];</p><p> local LayDate = A['LayDate'];</p><p> ------------------------------------------------- Get title data</p><p> local Title = A['Title'];</p><p> local ScriptTitle = A['ScriptTitle'];</p><p> local BookTitle = A['BookTitle'];</p><p> local Conference = A['Conference'];</p><p> local TransTitle = A['TransTitle'];</p><p> local TitleNote = A['TitleNote'];</p><p> local TitleLink = A['TitleLink'];</p><p> link_title_ok (TitleLink, A:ORIGIN ('TitleLink'), Title, 'title'); -- check for wikimarkup in |title-link= or wikimarkup in |title= when |title-link= is set</p><p> local Chapter = A['Chapter'];</p><p> local ScriptChapter = A['ScriptChapter'];</p><p> local ChapterLink -- = A['ChapterLink']; -- deprecated as a parameter but still used internally by cite episode</p><p> local TransChapter = A['TransChapter'];</p><p> local TitleType = A['TitleType'];</p><p> local Degree = A['Degree'];</p><p> local Docket = A['Docket'];</p><p> local ArchiveFormat = A['ArchiveFormat'];</p><p> local ArchiveDate;</p><p> local ArchiveURL;</p><p> ArchiveURL, ArchiveDate = archive_url_check (A['ArchiveURL'], A['ArchiveDate'])</p><p> </p><p> local DeadURL = A['DeadURL']</p><p> if not is_valid_parameter_value (DeadURL, 'dead-url', cfg.keywords ['deadurl']) then -- set in config.defaults to 'yes'</p><p> DeadURL = <i>; -- anything else, set to empty string</i></p><p> end</p><p> local URL = A['URL']</p><p> local URLorigin = A:ORIGIN('URL'); -- get name of parameter that holds URL</p><p> local ChapterURL = A['ChapterURL'];</p><p> local ChapterURLorigin = A:ORIGIN('ChapterURL'); -- get name of parameter that holds ChapterURL</p><p> local ConferenceFormat = A['ConferenceFormat'];</p><p> local ConferenceURL = A['ConferenceURL'];</p><p> local ConferenceURLorigin = A:ORIGIN('ConferenceURL'); -- get name of parameter that holds ConferenceURL</p><p> local Periodical = A['Periodical'];</p><p> local Periodical_origin = A:ORIGIN('Periodical'); -- get the name of the periodical parameter</p><p> local Series = A['Series'];</p><p> </p><p> local Volume;</p><p> local Issue;</p><p> local Page;</p><p> local Pages;</p><p> local At;</p><p> if in_array (config.CitationClass, cfg.templates_using_volume) then</p><p> Volume = A['Volume'];</p><p> end</p><p> -- conference & map books do not support issue</p><p> if in_array (config.CitationClass, cfg.templates_using_issue) and not (in_array (config.CitationClass, {'conference', 'map'}) and not is_set (Periodical))then</p><p> Issue = hyphen_to_dash (A['Issue']);</p><p> end</p><p> local Position = <i>;</i></p><p> if not in_array (config.CitationClass, cfg.templates_not_using_page) then</p><p> Page = A['Page'];</p><p> Pages = hyphen_to_dash (A['Pages']); </p><p> At = A['At'];</p><p> end</p><p> local Edition = A['Edition'];</p><p> local PublicationPlace = A['PublicationPlace']</p><p> local Place = A['Place'];</p><p> </p><p> local PublisherName = A['PublisherName'];</p><p> local RegistrationRequired = A['RegistrationRequired'];</p><p> if not is_valid_parameter_value (RegistrationRequired, 'registration', cfg.keywords ['yes_true_y']) then</p><p> RegistrationRequired=nil;</p><p> end</p><p> local SubscriptionRequired = A['SubscriptionRequired'];</p><p> if not is_valid_parameter_value (SubscriptionRequired, 'subscription', cfg.keywords ['yes_true_y']) then</p><p> SubscriptionRequired=nil;</p><p> end</p><p> local UrlAccess = A['UrlAccess'];</p><p> if not is_valid_parameter_value (UrlAccess, 'url-access', cfg.keywords ['url-access']) then</p><p> UrlAccess = nil;</p><p> end</p><p> if not is_set(URL) and is_set(UrlAccess) then</p><p> UrlAccess = nil;</p><p> table.insert( z.message_tail, { set_error( 'param_access_requires_param', {'url'}, true ) } );</p><p> end</p><p> if is_set (UrlAccess) and is_set (SubscriptionRequired) then -- while not aliases, these are much the same so if both are set</p><p> table.insert( z.message_tail, { set_error( 'redundant_parameters', {wrap_style ('parameter', 'url-access') .. ' and ' .. wrap_style ('parameter', 'subscription')}, true ) } ); -- add error message</p><p> SubscriptionRequired = nil; -- unset; prefer |access= over |subscription=</p><p> end</p><p> if is_set (UrlAccess) and is_set (RegistrationRequired) then -- these are not the same but contradictory so if both are set</p><p> table.insert( z.message_tail, { set_error( 'redundant_parameters', {wrap_style ('parameter', 'url-access') .. ' and ' .. wrap_style ('parameter', 'registration')}, true ) } ); -- add error message</p><p> RegistrationRequired = nil; -- unset; prefer |access= over |registration=</p><p> end</p><p> local ChapterUrlAccess = A['ChapterUrlAccess'];</p><p> if not is_valid_parameter_value (ChapterUrlAccess, 'chapter-url-access', cfg.keywords ['url-access']) then -- same as url-access</p><p> ChapterUrlAccess = nil;</p><p> end</p><p> if not is_set(ChapterURL) and is_set(ChapterUrlAccess) then</p><p> ChapterUrlAccess = nil;</p><p> table.insert( z.message_tail, { set_error( 'param_access_requires_param', {'chapter-url'}, true ) } );</p><p> end</p><p> local Via = A['Via'];</p><p> local AccessDate = A['AccessDate'];</p><p> local Agency = A['Agency'];</p><p> local Language = A['Language'];</p><p> local Format = A['Format'];</p><p> local ChapterFormat = A['ChapterFormat'];</p><p> local DoiBroken = A['DoiBroken'];</p><p> local ID = A['ID'];</p><p> local ASINTLD = A['ASINTLD'];</p><p> local IgnoreISBN = A['IgnoreISBN'];</p><p> if not is_valid_parameter_value (IgnoreISBN, 'ignore-isbn-error', cfg.keywords ['yes_true_y']) then</p><p> IgnoreISBN = nil; -- anything else, set to empty string</p><p> end</p><p> local Embargo = A['Embargo'];</p><p> local Class = A['Class']; -- arxiv class identifier</p><p> local ID_list = extract_ids( args );</p><p> local ID_access_levels = extract_id_access_levels( args, ID_list );</p><p> local Quote = A['Quote'];</p><p> local LayFormat = A['LayFormat'];</p><p> local LayURL = A['LayURL'];</p><p> local LaySource = A['LaySource'];</p><p> local Transcript = A['Transcript'];</p><p> local TranscriptFormat = A['TranscriptFormat'];</p><p> local TranscriptURL = A['TranscriptURL']</p><p> local TranscriptURLorigin = A:ORIGIN('TranscriptURL'); -- get name of parameter that holds TranscriptURL</p><p> local LastAuthorAmp = A['LastAuthorAmp'];</p><p> if not is_valid_parameter_value (LastAuthorAmp, 'last-author-amp', cfg.keywords ['yes_true_y']) then</p><p> LastAuthorAmp = nil; -- set to empty string</p><p> end</p><p> local no_tracking_cats = A['NoTracking'];</p><p> if not is_valid_parameter_value (no_tracking_cats, 'no-tracking', cfg.keywords ['yes_true_y']) then</p><p> no_tracking_cats = nil; -- set to empty string</p><p> end</p><p> --local variables that are not cs1 parameters</p><p> local use_lowercase; -- controls capitalization of certain static text</p><p> local this_page = mw.title.getCurrentTitle(); -- also used for COinS and for language</p><p> local anchor_year; -- used in the CITEREF identifier</p><p> local COinS_date = {}; -- holds date info extracted from |date= for the COinS metadata by Module:Date verification</p><p> local DF = A['DF']; -- date format set in cs1|2 template</p><p> if not is_valid_parameter_value (DF, 'df', cfg.keywords['date-format']) then -- validate reformatting keyword</p><p> DF = <i>; -- not valid, set to empty string</i></p><p> end</p><p> local sepc; -- separator between citation elements for CS1 a period, for CS2, a comma</p><p> local PostScript;</p><p> local Ref;</p><p> sepc, PostScript, Ref = set_style (Mode:lower(), A['PostScript'], A['Ref'], config.CitationClass);</p><p> use_lowercase = ( sepc == ',' ); -- used to control capitalization for certain static text</p><p> --check this page to see if it is in one of the namespaces that cs1 is not supposed to add to the error categories</p><p> if not is_set (no_tracking_cats) then -- ignore if we are already not going to categorize this page</p><p> if in_array (this_page.nsText, cfg.uncategorized_namespaces) then</p><p> no_tracking_cats = "true"; -- set no_tracking_cats</p><p> end</p><p> for _,v in ipairs (cfg.uncategorized_subpages) do -- cycle through page name patterns</p><p> if this_page.text:match (v) then -- test page name against each pattern</p><p> no_tracking_cats = "true"; -- set no_tracking_cats</p><p> break; -- bail out if one is found</p><p> end</p><p> end</p><p> end</p><p> -- check for extra |page=, |pages= or |at= parameters. (also sheet and sheets while we're at it)</p><p> select_one( args, {'page', 'p', 'pp', 'pages', 'at', 'sheet', 'sheets'}, 'redundant_parameters' ); -- this is a dummy call simply to get the error message and category</p><p> local coins_pages;</p><p> </p><p> Page, Pages, At, coins_pages = insource_loc_get (Page, Pages, At);</p><p> local NoPP = A['NoPP']</p><p> if is_set (NoPP) and is_valid_parameter_value (NoPP, 'nopp', cfg.keywords ['yes_true_y']) then</p><p> NoPP = true;</p><p> else</p><p> NoPP = nil; -- unset, used as a flag later</p><p> end</p><p> -- both |publication-place= and |place= (|location=) allowed if different</p><p> if not is_set(PublicationPlace) and is_set(Place) then</p><p> PublicationPlace = Place; -- promote |place= (|location=) to |publication-place</p><p> end</p><p> </p><p> if PublicationPlace == Place then Place = <i>; end -- don't need both if they are the same</i></p><p> </p><p> --[[</p><p> Parameter remapping for cite encyclopedia:</p><p> When the citation has these parameters:</p><p> |encyclopedia and |title then map |title to |article and |encyclopedia to |title</p><p> |encyclopedia and |article then map |encyclopedia to |title</p><p> |encyclopedia then map |encyclopedia to |title</p><p> </p><p> |trans-title maps to |trans-chapter when |title is re-mapped</p><p> |url maps to |chapterurl when |title is remapped</p><p> </p><p> All other combinations of |encyclopedia, |title, and |article are not modified</p><p> </p><p> ]]</p><p>local Encyclopedia = A['Encyclopedia'];</p><p> if ( config.CitationClass == "encyclopaedia" ) or ( config.CitationClass == "citation" and is_set (Encyclopedia)) then -- test code for citation</p><p> if is_set(Periodical) then -- Periodical is set when |encyclopedia is set</p><p> if is_set(Title) or is_set (ScriptTitle) then</p><p> if not is_set(Chapter) then</p><p> Chapter = Title; -- |encyclopedia and |title are set so map |title to |article and |encyclopedia to |title</p><p> ScriptChapter = ScriptTitle;</p><p> TransChapter = TransTitle;</p><p> ChapterURL = URL;</p><p> ChapterUrlAccess = UrlAccess;</p><p> if not is_set (ChapterURL) and is_set (TitleLink) then</p><p> Chapter = make_wikilink (TitleLink, Chapter);</p><p> end</p><p> Title = Periodical;</p><p> ChapterFormat = Format;</p><p> Periodical = <i>; -- redundant so unset</i></p><p> TransTitle = <i>;</i></p><p> URL = <i>;</i></p><p> Format = <i>;</i></p><p> TitleLink = <i>;</i></p><p> ScriptTitle = <i>;</i></p><p> end</p><p> else -- |title not set</p><p> Title = Periodical; -- |encyclopedia set and |article set or not set so map |encyclopedia to |title</p><p> Periodical = <i>; -- redundant so unset</i></p><p> end</p><p> end</p><p> end</p><p> -- Special case for cite techreport.</p><p> if (config.CitationClass == "techreport") then -- special case for cite techreport</p><p> if is_set(A['Number']) then -- cite techreport uses 'number', which other citations alias to 'issue'</p><p> if not is_set(ID) then -- can we use ID for the "number"?</p><p> ID = A['Number']; -- yes, use it</p><p> else -- ID has a value so emit error message</p><p> table.insert( z.message_tail, { set_error('redundant_parameters', {wrap_style ('parameter', 'id') .. ' and ' .. wrap_style ('parameter', 'number')}, true )});</p><p> end</p><p> end </p><p> end</p><p> -- special case for cite mailing list</p><p> if (config.CitationClass == "mailinglist") then</p><p> Periodical = A ['MailingList'];</p><p> elseif 'mailinglist' == A:ORIGIN('Periodical') then</p><p> Periodical = <i>; -- unset because mailing list is only used for cite mailing list</i></p><p> end</p><p> -- Account for the oddity that is {{cite conference}}, before generation of COinS data.</p><p> if 'conference' == config.CitationClass then</p><p> if is_set(BookTitle) then</p><p> Chapter = Title;</p>-- ChapterLink = TitleLink; -- |chapterlink= is deprecated<p> ChapterURL = URL;</p><p> ChapterUrlAccess = UrlAccess;</p><p> ChapterURLorigin = URLorigin;</p><p> URLorigin = <i>;</i></p><p> ChapterFormat = Format;</p><p> TransChapter = TransTitle;</p><p> Title = BookTitle;</p><p> Format = <i>;</i></p>-- TitleLink = <i>;</i><p> TransTitle = <i>;</i></p><p> URL = <i>;</i></p><p> end</p><p> elseif 'speech' ~= config.CitationClass then</p><p> Conference = <i>; -- not cite conference or cite speech so make sure this is empty string</i></p><p> end</p><p> -- cite map oddities</p><p> local Cartography = "";</p><p> local Scale = "";</p><p> local Sheet = A['Sheet'] or <i>;</i></p><p> local Sheets = A['Sheets'] or <i>;</i></p><p> if config.CitationClass == "map" then</p><p> Chapter = A['Map'];</p><p> ChapterURL = A['MapURL'];</p><p> ChapterUrlAccess = UrlAccess;</p><p> TransChapter = A['TransMap'];</p><p> ChapterURLorigin = A:ORIGIN('MapURL');</p><p> ChapterFormat = A['MapFormat'];</p><p> </p><p> Cartography = A['Cartography'];</p><p> if is_set( Cartography ) then</p><p> Cartography = sepc .. " " .. wrap_msg ('cartography', Cartography, use_lowercase);</p><p> end </p><p> Scale = A['Scale'];</p><p> if is_set( Scale ) then</p><p> Scale = sepc .. " " .. Scale;</p><p> end</p><p> end</p><p> -- Account for the oddities that are {{cite episode}} and {{cite serial}}, before generation of COinS data.</p><p> if 'episode' == config.CitationClass or 'serial' == config.CitationClass then</p><p> local AirDate = A['AirDate'];</p><p> local SeriesLink = A['SeriesLink'];</p><p> link_title_ok (SeriesLink, A:ORIGIN ('SeriesLink'), Series, 'series'); -- check for wikimarkup in |series-link= or wikimarkup in |series= when |series-link= is set</p><p> local Network = A['Network'];</p><p> local Station = A['Station'];</p><p> local s, n = {}, {};</p><p> -- do common parameters first</p><p> if is_set(Network) then table.insert(n, Network); end</p><p> if is_set(Station) then table.insert(n, Station); end</p><p> ID = table.concat(n, sepc .. ' ');</p><p> </p><p> if not is_set (Date) and is_set (AirDate) then -- promote airdate to date</p><p> Date = AirDate;</p><p> end</p><p> if 'episode' == config.CitationClass then -- handle the oddities that are strictly {{cite episode}}</p><p> local Season = A['Season'];</p><p> local SeriesNumber = A['SeriesNumber'];</p><p> if is_set (Season) and is_set (SeriesNumber) then -- these are mutually exclusive so if both are set</p><p> table.insert( z.message_tail, { set_error( 'redundant_parameters', {wrap_style ('parameter', 'season') .. ' and ' .. wrap_style ('parameter', 'seriesno')}, true ) } ); -- add error message</p><p> SeriesNumber = <i>; -- unset; prefer |season= over |seriesno=</i></p><p> end</p><p> -- assemble a table of parts concatenated later into Series</p><p> if is_set(Season) then table.insert(s, wrap_msg ('season', Season, use_lowercase)); end</p><p> if is_set(SeriesNumber) then table.insert(s, wrap_msg ('series', SeriesNumber, use_lowercase)); end</p><p> if is_set(Issue) then table.insert(s, wrap_msg ('episode', Issue, use_lowercase)); end</p><p> Issue = <i>; -- unset because this is not a unique parameter</i></p><p> </p><p> Chapter = Title; -- promote title parameters to chapter</p><p> ScriptChapter = ScriptTitle;</p><p> ChapterLink = TitleLink; -- alias episodelink</p><p> TransChapter = TransTitle;</p><p> ChapterURL = URL;</p><p> ChapterUrlAccess = UrlAccess;</p><p> ChapterURLorigin = A:ORIGIN('URL');</p><p> </p><p> Title = Series; -- promote series to title</p><p> TitleLink = SeriesLink;</p><p> Series = table.concat(s, sepc .. ' '); -- this is concatenation of season, seriesno, episode number</p><p> if is_set (ChapterLink) and not is_set (ChapterURL) then -- link but not URL</p><p> Chapter = make_wikilink (ChapterLink, Chapter);</p><p> elseif is_set (ChapterLink) and is_set (ChapterURL) then -- if both are set, URL links episode;</p><p> Series = make_wikilink (ChapterLink, Series);</p><p> end</p><p> URL = <i>; -- unset</i></p><p> TransTitle = <i>;</i></p><p> ScriptTitle = <i>;</i></p><p> </p><p> else -- now oddities that are cite serial</p><p> Issue = <i>; -- unset because this parameter no longer supported by the citation/core version of cite serial</i></p><p> Chapter = A['Episode']; -- TODO: make |episode= available to cite episode someday?</p><p> if is_set (Series) and is_set (SeriesLink) then</p><p> Series = make_wikilink (SeriesLink, Series);</p><p> end</p><p> Series = wrap_style ('italic-title', Series); -- series is italicized</p><p> end </p><p> end</p><p> -- end of {{cite episode}} stuff</p><p> -- Account for the oddities that are {{cite arxiv}}, {{cite biorxiv}}, {{cite citeseerx}}, before generation of COinS data.</p><p> do</p><p> if in_array (config.CitationClass, {'arxiv', 'biorxiv', 'citeseerx'}) then</p><p> if not is_set (ID_list[config.CitationClass:upper()]) then -- |arxiv= or |eprint= required for cite arxiv; |biorxiv= & |citeseerx= required for their templates</p><p> table.insert( z.message_tail, { set_error( config.CitationClass .. '_missing', {}, true ) } ); -- add error message</p><p> end</p><p> </p><p> if 'arxiv' == config.CitationClass then</p><p> Periodical = 'arXiv'; -- set to arXiv for COinS; after that, must be set to empty string</p><p> end</p><p> if 'biorxiv' == config.CitationClass then</p><p> Periodical = 'bioRxiv'; -- set to bioRxiv for COinS; after that, must be set to empty string</p><p> end</p><p> if 'citeseerx' == config.CitationClass then</p><p> Periodical = 'CiteSeerX'; -- set to CiteSeerX for COinS; after that, must be set to empty string</p><p> end</p><p> end</p><p> end</p><p> -- handle type parameter for those CS1 citations that have default values</p><p> if in_array(config.CitationClass, {"AV-media-notes", "interview", "mailinglist", "map", "podcast", "pressrelease", "report", "techreport", "thesis"}) then</p><p> TitleType = set_titletype (config.CitationClass, TitleType);</p><p> if is_set(Degree) and "Thesis" == TitleType then -- special case for cite thesis</p><p> TitleType = Degree .. ' ' .. cfg.title_types ['thesis']:lower();</p><p> end</p><p> end</p><p> if is_set(TitleType) then -- if type parameter is specified</p><p> TitleType = substitute( cfg.messages['type'], TitleType); -- display it in parentheses</p><p> -- TODO: Hack on TitleType to fix bunched parentheses problem</p><p> end</p><p> -- legacy: promote PublicationDate to Date if neither Date nor Year are set.</p><p> if not is_set (Date) then</p><p> Date = Year; -- promote Year to Date</p><p> Year = nil; -- make nil so Year as empty string isn't used for CITEREF</p><p> if not is_set (Date) and is_set(PublicationDate) then -- use PublicationDate when |date= and |year= are not set</p><p> Date = PublicationDate; -- promote PublicationDate to Date</p><p> PublicationDate = <i>; -- unset, no longer needed</i></p><p> Date_origin = A:ORIGIN('PublicationDate'); -- save the name of the promoted parameter</p><p> else</p><p> Date_origin = A:ORIGIN('Year'); -- save the name of the promoted parameter</p><p> end</p><p> else</p><p> Date_origin = A:ORIGIN('Date'); -- not a promotion; name required for error messaging</p><p> end</p><p> if PublicationDate == Date then PublicationDate = <i>; end -- if PublicationDate is same as Date, don't display in rendered citation</i></p><p> --[[</p><p> Go test all of the date-holding parameters for valid MOS:DATE format and make sure that dates are real dates. This must be done before we do COinS because here is where</p><p> we get the date used in the metadata.</p><p> </p><p> Date validation supporting code is in Module:Citation/CS1/Date_validation</p><p> ]]</p><p> do -- create defined block to contain local variables error_message, date_parameters_list, mismatch</p><p> local error_message = <i>;</i></p><p> -- AirDate has been promoted to Date so not necessary to check it</p><p> local date_parameters_list = {</p><p> ['access-date'] = {val=AccessDate, name=A:ORIGIN ('AccessDate')},</p><p> ['archive-date'] = {val=ArchiveDate, name=A:ORIGIN ('ArchiveDate')},</p><p> ['date'] = {val=Date, name=Date_origin},</p><p> ['doi-broken-date'] = {val=DoiBroken, name=A:ORIGIN ('DoiBroken')},</p><p> ['embargo'] = {val=Embargo, name=A:ORIGIN ('Embargo')},</p><p> ['lay-date'] = {val=LayDate, name=A:ORIGIN ('LayDate')},</p><p> ['publication-date'] ={val=PublicationDate, name=A:ORIGIN ('PublicationDate')},</p><p> ['year'] = {val=Year, name=A:ORIGIN ('Year')},</p><p> };</p><p> anchor_year, Embargo, error_message = dates(date_parameters_list, COinS_date);</p>-- start temporary Julian / Gregorian calendar uncertainty categorization<p> if COinS_date.inter_cal_cat then</p><p> add_prop_cat ('jul_greg_uncertainty');</p><p> end</p>-- end temporary Julian / Gregorian calendar uncertainty categorization<p> if is_set (Year) and is_set (Date) then -- both |date= and |year= not normally needed;</p><p> local mismatch = year_date_check (Year, Date)</p><p> if 0 == mismatch then -- |year= does not match a year-value in |date=</p><p> if is_set (error_message) then -- if there is already an error message</p><p> error_message = error_message .. ', '; -- tack on this additional message</p><p> end</p><p> error_message = error_message .. '|year= / |date= mismatch';</p><p> elseif 1 == mismatch then -- |year= matches year-value in |date=</p><p> add_maint_cat ('date_year');</p><p> end</p><p> end</p><p> </p><p> if not is_set(error_message) then -- error free dates only</p><p> local modified = false; -- flag</p><p> </p><p> if is_set (DF) then -- if we need to reformat dates</p><p> modified = reformat_dates (date_parameters_list, DF, false); -- reformat to DF format, use long month names if appropriate</p><p> end</p><p> if true == date_hyphen_to_dash (date_parameters_list) then -- convert hyphens to dashes where appropriate</p><p> modified = true;</p><p> add_maint_cat ('date_format'); -- hyphens were converted so add maint category</p><p> end</p><p> </p><p> -- for those wikis that can and want to have English date names translated to the local language,</p><p> -- uncomment these three lines. Not supported by en.wiki (for obvious reasons)</p><p> -- set date_name_xlate() second argument to true to translate English digits to local digits (will translate ymd dates)</p>-- if date_name_xlate (date_parameters_list, false) then-- modified = true;-- end<p> if modified then -- if the date_parameters_list values were modified</p><p> AccessDate = date_parameters_list['access-date'].val; -- overwrite date holding parameters with modified values</p><p> ArchiveDate = date_parameters_list['archive-date'].val;</p><p> Date = date_parameters_list['date'].val;</p><p> DoiBroken = date_parameters_list['doi-broken-date'].val;</p><p> LayDate = date_parameters_list['lay-date'].val;</p><p> PublicationDate = date_parameters_list['publication-date'].val;</p><p> end</p><p> else</p><p> table.insert( z.message_tail, { set_error( 'bad_date', {error_message}, true ) } ); -- add this error message</p><p> end</p><p> end -- end of do</p><p> -- Account for the oddity that is {{cite journal}} with |pmc= set and |url= not set. Do this after date check but before COInS.</p><p> -- Here we unset Embargo if PMC not embargoed (|embargo= not set in the citation) or if the embargo time has expired. Otherwise, holds embargo date</p><p> Embargo = is_embargoed (Embargo);</p><p> if config.CitationClass == "journal" and not is_set(URL) and is_set(ID_list['PMC']) then</p><p> if not is_set (Embargo) then -- if not embargoed or embargo has expired</p><p> URL=cfg.id_handlers['PMC'].prefix .. ID_list['PMC']; -- set url to be the same as the PMC external link if not embargoed</p><p> URLorigin = cfg.id_handlers['PMC'].parameters[1]; -- set URLorigin to parameter name for use in error message if citation is missing a |title=</p><p> if is_set(AccessDate) then -- access date requires |url=; pmc created url is not |url=</p><p> table.insert( z.message_tail, { set_error( 'accessdate_missing_url', {}, true ) } );</p><p> AccessDate = <i>; -- unset</i></p><p> end</p><p> end</p><p> end</p><p> -- At this point fields may be nil if they weren't specified in the template use. We can use that fact.</p><p> -- Test if citation has no title</p><p> if not is_set(Title) and</p><p> not is_set(TransTitle) and</p><p> not is_set(ScriptTitle) then</p><p> if 'episode' == config.CitationClass then -- special case for cite episode; TODO: is there a better way to do this?</p><p> table.insert( z.message_tail, { set_error( 'citation_missing_title', {'series'}, true ) } );</p><p> else</p><p> table.insert( z.message_tail, { set_error( 'citation_missing_title', {'title'}, true ) } );</p><p> end</p><p> end</p><p> </p><p> if 'none' == Title and in_array (config.CitationClass, {'journal', 'citation'}) and is_set (Periodical) and 'journal' == A:ORIGIN('Periodical') then -- special case for journal cites</p><p> Title = <i>; -- set title to empty string</i></p><p> add_maint_cat ('untitled');</p><p> end</p><p> check_for_url ({ -- add error message when any of these parameters contains a URL</p><p> ['title']=Title,</p><p> [A:ORIGIN('Chapter')]=Chapter,</p><p> [A:ORIGIN('Periodical')]=Periodical,</p><p> [A:ORIGIN('PublisherName')] = PublisherName</p><p> });</p><p> -- COinS metadata (see <http://ocoins.info/>) for automated parsing of citation information.</p><p> -- handle the oddity that is cite encyclopedia and {{citation |encyclopedia=something}}. Here we presume that</p><p> -- when Periodical, Title, and Chapter are all set, then Periodical is the book (encyclopedia) title, Title</p><p> -- is the article title, and Chapter is a section within the article. So, we remap</p><p> </p><p> local coins_chapter = Chapter; -- default assuming that remapping not required</p><p> local coins_title = Title; -- et tu</p><p> if 'encyclopaedia' == config.CitationClass or ('citation' == config.CitationClass and is_set (Encyclopedia)) then</p><p> if is_set (Chapter) and is_set (Title) and is_set (Periodical) then -- if all are used then</p><p> coins_chapter = Title; -- remap</p><p> coins_title = Periodical;</p><p> end</p><p> end</p><p> local coins_author = a; -- default for coins rft.au</p><p> if 0 < #c then -- but if contributor list</p><p> coins_author = c; -- use that instead</p><p> end</p><p> -- this is the function call to COinS()</p><p> local OCinSoutput = COinS({</p><p> ['Periodical'] = Periodical,</p><p> ['Encyclopedia'] = Encyclopedia,</p><p> ['Chapter'] = make_coins_title (coins_chapter, ScriptChapter), -- Chapter and ScriptChapter stripped of bold / italic wikimarkup</p><p> ['Degree'] = Degree; -- cite thesis only</p><p> ['Title'] = make_coins_title (coins_title, ScriptTitle), -- Title and ScriptTitle stripped of bold / italic wikimarkup</p><p> ['PublicationPlace'] = PublicationPlace,</p><p> ['Date'] = COinS_date.rftdate, -- COinS_date has correctly formatted date if Date is valid;</p><p> ['Season'] = COinS_date.rftssn,</p><p> ['Chron'] = COinS_date.rftchron or (not COinS_date.rftdate and Date) or <i>, -- chron but if not set and invalid date format use Date; keep this last bit?</i></p><p> ['Series'] = Series,</p><p> ['Volume'] = Volume,</p><p> ['Issue'] = Issue,</p><p> ['Pages'] = coins_pages or get_coins_pages (first_set ({Sheet, Sheets, Page, Pages, At}, 5)), -- pages stripped of external links</p><p> ['Edition'] = Edition,</p><p> ['PublisherName'] = PublisherName,</p><p> ['URL'] = first_set ({ChapterURL, URL}, 2),</p><p> ['Authors'] = coins_author,</p><p> ['ID_list'] = ID_list,</p><p> ['RawPage'] = this_page.prefixedText,</p><p> }, config.CitationClass);</p><p> -- Account for the oddities that are {{cite arxiv}}, {{cite biorxiv}}, and {{cite citeseerx}} AFTER generation of COinS data.</p><p> if in_array (config.CitationClass, {'arxiv', 'biorxiv', 'citeseerx'}) then -- we have set rft.jtitle in COinS to arXiv, bioRxiv, or CiteSeerX now unset so it isn't displayed</p><p> Periodical = <i>; -- periodical not allowed in these templates; if article has been published, use cite journal</i></p><p> end</p><p> -- special case for cite newsgroup. Do this after COinS because we are modifying Publishername to include some static text</p><p> if 'newsgroup' == config.CitationClass then</p><p> if is_set (PublisherName) then</p><p> PublisherName = substitute (cfg.messages['newsgroup'], external_link( 'news:' .. PublisherName, PublisherName, A:ORIGIN('PublisherName'), nil ));</p><p> end</p><p> end</p><p> -- Now perform various field substitutions.</p><p> -- We also add leading spaces and surrounding markup and punctuation to the</p><p> -- various parts of the citation, but only when they are non-nil.</p><p> local EditorCount; -- used only for choosing {ed.) or (eds.) annotation at end of editor name-list</p><p> do</p><p> local last_first_list;</p><p> local control = {</p><p> format = NameListFormat, -- empty string or 'vanc'</p><p> maximum = nil, -- as if display-authors or display-editors not set</p><p> lastauthoramp = LastAuthorAmp,</p><p> page_name = this_page.text, -- get current page name so that we don't wikilink to it via editorlinkn</p><p> mode = Mode</p><p> };</p><p> do -- do editor name list first because the now unsupported coauthors used to modify control table</p><p> control.maximum , editor_etal = get_display_authors_editors (A['DisplayEditors'], #e, 'editors', editor_etal);</p><p> last_first_list, EditorCount = list_people(control, e, editor_etal);</p><p> if is_set (Editors) then</p><p> if editor_etal then</p><p> Editors = Editors .. ' ' .. cfg.messages['et al']; -- add et al. to editors parameter beause |display-editors=etal</p><p> EditorCount = 2; -- with et al., |editors= is multiple names; spoof to display (eds.) annotation</p><p> else</p><p> EditorCount = 2; -- we don't know but assume |editors= is multiple names; spoof to display (eds.) annotation</p><p> end</p><p> else</p><p> Editors = last_first_list; -- either an author name list or an empty string</p><p> end</p><p> if 1 == EditorCount and (true == editor_etal or 1 < #e) then -- only one editor displayed but includes etal then</p><p> EditorCount = 2; -- spoof to display (eds.) annotation</p><p> end</p><p> end</p><p> do -- now do interviewers</p><p> control.maximum = #interviewers_list; -- number of interviewerss</p><p> Interviewers = list_people(control, interviewers_list, false); -- et al not currently supported</p><p> end</p><p> do -- now do translators</p><p> control.maximum = #t; -- number of translators</p><p> Translators = list_people(control, t, false); -- et al not currently supported</p><p> end</p><p> do -- now do contributors</p><p> control.maximum = #c; -- number of contributors</p><p> Contributors = list_people(control, c, false); -- et al not currently supported</p><p> end</p><p> do -- now do authors</p><p> control.maximum , author_etal = get_display_authors_editors (A['DisplayAuthors'], #a, 'authors', author_etal);</p><p> last_first_list = list_people(control, a, author_etal);</p><p> if is_set (Authors) then</p><p> Authors, author_etal = name_has_etal (Authors, author_etal, false); -- find and remove variations on et al.</p><p> if author_etal then</p><p> Authors = Authors .. ' ' .. cfg.messages['et al']; -- add et al. to authors parameter</p><p> end</p><p> else</p><p> Authors = last_first_list; -- either an author name list or an empty string</p><p> end</p><p> end -- end of do</p><p> </p><p> if is_set (Authors) and is_set (Collaboration) then</p><p> Authors = Authors .. ' (' .. Collaboration .. ')'; -- add collaboration after et al.</p><p> end</p><p> end</p><p> -- apply |[xx-]format= styling; at the end, these parameters hold correctly styled format annotation,</p><p> -- an error message if the associated url is not set, or an empty string for concatenation</p><p> ArchiveFormat = style_format (ArchiveFormat, ArchiveURL, 'archive-format', 'archive-url');</p><p> ConferenceFormat = style_format (ConferenceFormat, ConferenceURL, 'conference-format', 'conference-url');</p><p> Format = style_format (Format, URL, 'format', 'url');</p><p> LayFormat = style_format (LayFormat, LayURL, 'lay-format', 'lay-url');</p><p> TranscriptFormat = style_format (TranscriptFormat, TranscriptURL, 'transcript-format', 'transcripturl');</p><p> -- special case for chapter format so no error message or cat when chapter not supported</p><p> if not (in_array(config.CitationClass, {'web', 'news', 'journal', 'magazine', 'pressrelease', 'podcast', 'newsgroup', 'arxiv', 'biorxiv', 'citeseerx'}) or</p><p> ('citation' == config.CitationClass and is_set (Periodical) and not is_set (Encyclopedia))) then</p><p> ChapterFormat = style_format (ChapterFormat, ChapterURL, 'chapter-format', 'chapter-url');</p><p> end</p><p> if not is_set(URL) then</p><p> if in_array(config.CitationClass, {"web","podcast", "mailinglist"}) then -- |url= required for cite web, cite podcast, and cite mailinglist</p><p> table.insert( z.message_tail, { set_error( 'cite_web_url', {}, true ) } );</p><p> end</p><p> </p><p> -- do we have |accessdate= without either |url= or |chapter-url=?</p><p> if is_set(AccessDate) and not is_set(ChapterURL)then -- ChapterURL may be set when URL is not set;</p><p> table.insert( z.message_tail, { set_error( 'accessdate_missing_url', {}, true ) } );</p><p> AccessDate = <i>;</i></p><p> end</p><p> end</p><p> local OriginalURL, OriginalURLorigin, OriginalFormat, OriginalAccess;</p><p> DeadURL = DeadURL:lower(); -- used later when assembling archived text</p><p> if is_set( ArchiveURL ) then</p><p> if is_set (ChapterURL) then -- if chapter-url is set apply archive url to it</p><p> OriginalURL = ChapterURL; -- save copy of source chapter's url for archive text</p><p> OriginalURLorigin = ChapterURLorigin; -- name of chapter-url parameter for error messages</p><p> OriginalFormat = ChapterFormat; -- and original |chapter-format=</p><p> if 'no' ~= DeadURL then</p><p> ChapterURL = ArchiveURL -- swap-in the archive's url</p><p> ChapterURLorigin = A:ORIGIN('ArchiveURL') -- name of archive-url parameter for error messages</p><p> ChapterFormat = ArchiveFormat or <i>; -- swap in archive's format</i></p><p> ChapterUrlAccess = nil; -- restricted access levels do not make sense for archived urls</p><p> end</p><p> elseif is_set (URL) then</p><p> OriginalURL = URL; -- save copy of original source URL</p><p> OriginalURLorigin = URLorigin; -- name of url parameter for error messages</p><p> OriginalFormat = Format; -- and original |format=</p><p> OriginalAccess = UrlAccess;</p><p> if 'no' ~= DeadURL then -- if URL set then archive-url applies to it</p><p> URL = ArchiveURL -- swap-in the archive's url</p><p> URLorigin = A:ORIGIN('ArchiveURL') -- name of archive url parameter for error messages</p><p> Format = ArchiveFormat or <i>; -- swap in archive's format</i></p><p> UrlAccess = nil; -- restricted access levels do not make sense for archived urls</p><p> end</p><p> end</p><p> if in_array(config.CitationClass, {'web','news','journal', 'magazine', 'pressrelease', 'podcast', 'newsgroup', 'arxiv', 'biorxiv', 'citeseerx'}) or -- if any of the 'periodical' cites except encyclopedia</p><p> ('citation' == config.CitationClass and is_set (Periodical) and not is_set (Encyclopedia)) then</p><p> local chap_param;</p><p> if is_set (Chapter) then -- get a parameter name from one of these chapter related meta-parameters</p><p> chap_param = A:ORIGIN ('Chapter')</p><p> elseif is_set (TransChapter) then</p><p> chap_param = A:ORIGIN ('TransChapter')</p><p> elseif is_set (ChapterURL) then</p><p> chap_param = A:ORIGIN ('ChapterURL')</p><p> elseif is_set (ScriptChapter) then</p><p> chap_param = A:ORIGIN ('ScriptChapter')</p><p> else is_set (ChapterFormat)</p><p> chap_param = A:ORIGIN ('ChapterFormat')</p><p> end</p><p> if is_set (chap_param) then -- if we found one</p><p> table.insert( z.message_tail, { set_error( 'chapter_ignored', {chap_param}, true ) } ); -- add error message</p><p> Chapter = <i>; -- and set them to empty string to be safe with concatenation</i></p><p> TransChapter = <i>;</i></p><p> ChapterURL = <i>;</i></p><p> ScriptChapter = <i>;</i></p><p> ChapterFormat = <i>;</i></p><p> end</p><p> else -- otherwise, format chapter / article title</p><p> local no_quotes = false; -- default assume that we will be quoting the chapter parameter value</p><p> if is_set (Contribution) and 0 < #c then -- if this is a contribution with contributor(s)</p><p> if in_array (Contribution:lower(), cfg.keywords.contribution) then -- and a generic contribution title</p><p> no_quotes = true; -- then render it unquoted</p><p> end</p><p> end</p><p> Chapter = format_chapter_title (ScriptChapter, Chapter, TransChapter, ChapterURL, ChapterURLorigin, no_quotes, ChapterUrlAccess); -- Contribution is also in Chapter</p><p> if is_set (Chapter) then</p><p> Chapter = Chapter .. ChapterFormat ;</p><p> if 'map' == config.CitationClass and is_set (TitleType) then</p><p> Chapter = Chapter .. ' ' .. TitleType; -- map annotation here; not after title</p><p> end</p><p> Chapter = Chapter.. sepc .. ' ';</p><p> elseif is_set (ChapterFormat) then -- |chapter= not set but |chapter-format= is so ...</p><p> Chapter = ChapterFormat .. sepc .. ' '; -- ... ChapterFormat has error message, we want to see it</p><p> end</p><p> end</p><p> -- Format main title.</p><p> if is_set (ArchiveURL) and mw.ustring.match (mw.ustring.lower(Title), cfg.special_case_translation['archived_copy']) then -- if title is 'Archived copy' (place holder added by bots that can't find proper title)</p><p> add_maint_cat ('archived_copy'); -- add maintenance category before we modify the content of Title</p><p> end</p><p> if Title:match ('^%(%(.*%)%)$') then -- if keep as written markup:</p><p> Title= Title:gsub ('^%(%((.*)%)%)$', '%1') -- remove the markup</p><p> else</p><p> if '...' == Title:sub (-3) then -- if elipsis is the last three characters of |title=</p><p> Title = Title:gsub ('(%.%.%.)%.+$', '%1'); -- limit the number of dots to three</p><p> elseif not mw.ustring.find (Title, '%.%s*%a%.$') and -- end of title is not a 'dot-(optional space-)letter-dot' initialism ...</p><p> not mw.ustring.find (Title, '%s+%a%.$') then -- ...and not a 'space-letter-dot' initial (<i>Allium canadense</i> L.)</p><p> Title = mw.ustring.gsub(Title, '%'..sepc..'$', <i>); -- remove any trailing separator character; sepc and ms.ustring() here for languages that use multibyte separator characters</i></p><p> end</p><p> end</p><p> </p><p> if in_array(config.CitationClass, {'web', 'news', 'journal', 'magazine', 'pressrelease', 'podcast', 'newsgroup', 'mailinglist', 'interview', 'arxiv', 'biorxiv', 'citeseerx'}) or</p><p> ('citation' == config.CitationClass and is_set (Periodical) and not is_set (Encyclopedia)) or</p><p> ('map' == config.CitationClass and is_set (Periodical)) then -- special case for cite map when the map is in a periodical treat as an article</p><p> Title = kern_quotes (Title); -- if necessary, separate title's leading and trailing quote marks from Module provided quote marks</p><p> Title = wrap_style ('quoted-title', Title);</p><p> Title = script_concatenate (Title, ScriptTitle); -- <bdi> tags, lang atribute, categorization, etc; must be done after title is wrapped</p><p> TransTitle= wrap_style ('trans-quoted-title', TransTitle );</p><p> elseif 'report' == config.CitationClass then -- no styling for cite report</p><p> Title = script_concatenate (Title, ScriptTitle); -- <bdi> tags, lang atribute, categorization, etc; must be done after title is wrapped</p><p> TransTitle= wrap_style ('trans-quoted-title', TransTitle ); -- for cite report, use this form for trans-title</p><p> else</p><p> Title = wrap_style ('italic-title', Title);</p><p> Title = script_concatenate (Title, ScriptTitle); -- <bdi> tags, lang atribute, categorization, etc; must be done after title is wrapped</p><p> TransTitle = wrap_style ('trans-italic-title', TransTitle);</p><p> end</p><p> local TransError = "";</p><p> if is_set(TransTitle) then</p><p> if is_set(Title) then</p><p> TransTitle = " " .. TransTitle;</p><p> else</p><p> TransError = " " .. set_error( 'trans_missing_title', {'title'} );</p><p> end</p><p> end</p><p> if is_set(Title) then</p><p> if not is_set (TitleLink) and is_set (URL) then</p><p> Title = external_link (URL, Title, URLorigin, UrlAccess) .. TransTitle .. TransError .. Format;</p><p> URL = <i>; -- unset these because no longer needed</i></p><p> Format = "";</p><p> elseif is_set (TitleLink) and not is_set (URL) then</p><p> local ws_url;</p><p> ws_url = wikisource_url_make (TitleLink); -- ignore ws_label return; not used here</p><p> if ws_url then</p><p> Title = external_link (ws_url, Title .. ' ', 'ws link in title-link'); -- space char after Title to move icon away from italic text; TODO: a better way to do this?</p><p> Title = substitute (cfg.presentation['interwiki-icon'], {cfg.presentation['class-wikisource'], TitleLink, Title}); </p><p> Title = Title .. TransTitle .. TransError;</p><p> else</p><p> Title = make_wikilink (TitleLink, Title) .. TransTitle .. TransError;</p><p> end</p><p> else</p><p> local ws_url, ws_label;</p><p> ws_url, ws_label, L = wikisource_url_make (Title); -- make ws url from |title= interwiki link; link portion L becomes tool tip label</p><p> if ws_url then</p><p> Title = Title:gsub ('%b[]', ws_label); -- replace interwiki link with ws_label to retain markup</p><p> Title = external_link (ws_url, Title .. ' ', 'ws link in title'); -- space char after Title to move icon away from italic text; TODO: a better way to do this?</p><p> Title = substitute (cfg.presentation['interwiki-icon'], {cfg.presentation['class-wikisource'], L, Title}); </p><p> Title = Title .. TransTitle .. TransError;</p><p> else</p><p> Title = Title .. TransTitle .. TransError;</p><p> end</p><p> end</p><p> else</p><p> Title = TransTitle .. TransError;</p><p> end</p><p> if is_set(Place) then</p><p> Place = " " .. wrap_msg ('written', Place, use_lowercase) .. sepc .. " ";</p><p> end</p><p> if is_set (Conference) then</p><p> if is_set (ConferenceURL) then</p><p> Conference = external_link( ConferenceURL, Conference, ConferenceURLorigin, nil );</p><p> end</p><p> Conference = sepc .. " " .. Conference .. ConferenceFormat;</p><p> elseif is_set(ConferenceURL) then</p><p> Conference = sepc .. " " .. external_link( ConferenceURL, nil, ConferenceURLorigin, nil );</p><p> end</p><p> if not is_set(Position) then</p><p> local Minutes = A['Minutes'];</p><p> local Time = A['Time'];</p><p> if is_set(Minutes) then</p><p> if is_set (Time) then</p><p> table.insert( z.message_tail, { set_error( 'redundant_parameters', {wrap_style ('parameter', 'minutes') .. ' and ' .. wrap_style ('parameter', 'time')}, true ) } );</p><p> end</p><p> Position = " " .. Minutes .. " " .. cfg.messages['minutes'];</p><p> else</p><p> if is_set(Time) then</p><p> local TimeCaption = A['TimeCaption']</p><p> if not is_set(TimeCaption) then</p><p> TimeCaption = cfg.messages['event'];</p><p> if sepc ~= '.' then</p><p> TimeCaption = TimeCaption:lower();</p><p> end</p><p> end</p><p> Position = " " .. TimeCaption .. " " .. Time;</p><p> end</p><p> end</p><p> else</p><p> Position = " " .. Position;</p><p> At = <i>;</i></p><p> end</p><p> Page, Pages, Sheet, Sheets = format_pages_sheets (Page, Pages, Sheet, Sheets, config.CitationClass, Periodical_origin, sepc, NoPP, use_lowercase);</p><p> At = is_set(At) and (sepc .. " " .. At) or "";</p><p> Position = is_set(Position) and (sepc .. " " .. Position) or "";</p><p> if config.CitationClass == 'map' then</p><p> local Section = A['Section'];</p><p> local Sections = A['Sections'];</p><p> local Inset = A['Inset'];</p><p> </p><p> if is_set( Inset ) then</p><p> Inset = sepc .. " " .. wrap_msg ('inset', Inset, use_lowercase);</p><p> end </p><p> if is_set( Sections ) then</p><p> Section = sepc .. " " .. wrap_msg ('sections', Sections, use_lowercase);</p><p> elseif is_set( Section ) then</p><p> Section = sepc .. " " .. wrap_msg ('section', Section, use_lowercase);</p><p> end</p><p> At = At .. Inset .. Section; </p><p> end </p><p> if is_set (Language) then</p><p> Language = language_parameter (Language); -- format, categories, name from ISO639-1, etc</p><p> else</p><p> Language=""; -- language not specified so make sure this is an empty string;</p><p> --[[ TODO: need to extract the wrap_msg from language_parameter</p><p> so that we can solve parentheses bunching problem with Format/Language/TitleType</p><p> ]]</p><p> end</p><p> Others = is_set(Others) and (sepc .. " " .. Others) or "";</p><p> </p><p> if is_set (Translators) then</p><p> Others = safe_join ({sepc .. ' ', wrap_msg ('translated', Translators, use_lowercase), Others}, sepc);</p><p> end</p><p> if is_set (Interviewers) then</p><p> Others = safe_join ({sepc .. ' ', wrap_msg ('interview', Interviewers, use_lowercase), Others}, sepc);</p><p> end</p><p> </p><p> TitleNote = is_set(TitleNote) and (sepc .. " " .. TitleNote) or "";</p><p> if is_set (Edition) then</p><p> if Edition:match ('%f[%a][Ee]d%.?$') or Edition:match ('%f[%a][Ee]dition$') then</p><p> add_maint_cat ('extra_text', 'edition');</p><p> end</p><p> Edition = " " .. wrap_msg ('edition', Edition);</p><p> else</p><p> Edition = <i>;</i></p><p> end</p><p> Series = is_set(Series) and (sepc .. " " .. Series) or "";</p><p> OrigYear = is_set(OrigYear) and (" [" .. OrigYear .. "]") or ""; -- TODO: presentation</p><p> Agency = is_set(Agency) and (sepc .. " " .. Agency) or "";</p><p> Volume = format_volume_issue (Volume, Issue, config.CitationClass, Periodical_origin, sepc, use_lowercase);</p><p> ------------------------------------ totally unrelated data</p><p> if is_set(Via) then</p><p> Via = " " .. wrap_msg ('via', Via);</p><p> end</p><p> --[[</p><p> Subscription implies paywall; Registration does not. If both are used in a citation, the subscription required link</p><p> note is displayed. There are no error messages for this condition.</p><p> </p><p> ]]</p><p> if is_set (SubscriptionRequired) then</p><p> SubscriptionRequired = sepc .. " " .. cfg.messages['subscription']; -- subscription required message</p><p> elseif is_set (RegistrationRequired) then</p><p> SubscriptionRequired = sepc .. " " .. cfg.messages['registration']; -- registration required message</p><p> else</p><p> SubscriptionRequired = <i>; -- either or both might be set to something other than yes true y</i></p><p> end</p><p> if is_set(AccessDate) then</p><p> local retrv_text = " " .. cfg.messages['retrieved']</p><p> AccessDate = nowrap_date (AccessDate); -- wrap in nowrap span if date in appropriate format</p><p> if (sepc ~= ".") then retrv_text = retrv_text:lower() end -- if mode is cs2, lower case</p><p> AccessDate = substitute (retrv_text, AccessDate); -- add retrieved text</p><p> AccessDate = substitute (cfg.presentation['accessdate'], {sepc, AccessDate}); -- allow editors to hide accessdates</p><p> end</p><p> </p><p> if is_set(ID) then ID = sepc .." ".. ID; end</p><p> ID = sepc .." Docket ".. Docket .. ID;</p><p> end</p><p> ID = sepc .. ' ' .. Docket; -- overwrite ID even if |id= is set</p><p> end</p><p> ID_list = build_id_list( ID_list, {IdAccessLevels=ID_access_levels, DoiBroken = DoiBroken, ASINTLD = ASINTLD, IgnoreISBN = IgnoreISBN, Embargo=Embargo, Class = Class} );</p><p> if is_set(URL) then</p><p> URL = " " .. external_link( URL, nil, URLorigin, UrlAccess );</p><p> end</p><p> if is_set(Quote) then</p><p> if Quote:sub(1,1) == '"' and Quote:sub(-1,-1) == '"' then -- if first and last characters of quote are quote marks</p><p> Quote = Quote:sub(2,-2); -- strip them off</p><p> end</p><p> Quote = sepc .." " .. wrap_style ('quoted-text', Quote ); -- wrap in <q>...</q> tags</p><p> PostScript = ""; -- cs1|2 does not supply terminal punctuation when |quote= is set</p><p> end</p><p> </p><p> local Archived</p><p> if is_set(ArchiveURL) then</p><p> if not is_set(ArchiveDate) then</p><p> ArchiveDate = set_error('archive_missing_date');</p><p> end</p><p> if "no" == DeadURL then</p><p> local arch_text = cfg.messages['archived'];</p><p> if sepc ~= "." then arch_text = arch_text:lower() end</p><p> Archived = sepc .. " " .. substitute( cfg.messages['archived-not-dead'],</p><p> { external_link( ArchiveURL, arch_text, A:ORIGIN('ArchiveURL'), nil ) .. ArchiveFormat, ArchiveDate } );</p><p> if not is_set(OriginalURL) then</p><p> Archived = Archived .. " " .. set_error('archive_missing_url'); </p><p> end</p><p> elseif is_set(OriginalURL) then -- DeadURL is empty, 'yes', 'true', 'y', 'unfit', 'usurped'</p><p> local arch_text = cfg.messages['archived-dead'];</p><p> if sepc ~= "." then arch_text = arch_text:lower() end</p><p> if in_array (DeadURL, {'unfit', 'usurped', 'bot: unknown'}) then</p><p> Archived = sepc .. " " .. 'Archived from the original on ' .. ArchiveDate; -- format already styled</p><p> if 'bot: unknown' == DeadURL then</p><p> add_maint_cat ('bot:_unknown'); -- and add a category if not already added</p><p> else</p><p> add_maint_cat ('unfit'); -- and add a category if not already added</p><p> end</p><p> else -- DeadURL is empty, 'yes', 'true', or 'y'</p><p> Archived = sepc .. " " .. substitute( arch_text,</p><p> { external_link( OriginalURL, cfg.messages['original'], OriginalURLorigin, OriginalAccess ) .. OriginalFormat, ArchiveDate } ); -- format already styled</p><p> end </p><p> else</p><p> local arch_text = cfg.messages['archived-missing'];</p><p> if sepc ~= "." then arch_text = arch_text:lower() end</p><p> Archived = sepc .. " " .. substitute( arch_text,</p><p> { set_error('archive_missing_url'), ArchiveDate } );</p><p> end</p><p> elseif is_set (ArchiveFormat) then</p><p> Archived = ArchiveFormat; -- if set and ArchiveURL not set ArchiveFormat has error message</p><p> else</p><p> Archived = ""</p><p> end</p><p> </p><p> local Lay = <i>;</i></p><p> if is_set(LayURL) then</p><p> if is_set(LayDate) then LayDate = " (" .. LayDate .. ")" end</p><p> if is_set(LaySource) then</p><p> LaySource = " – <i>" .. safe_for_italics(LaySource) .. "</i>";</p><p> else</p><p> LaySource = "";</p><p> end</p><p> if sepc == '.' then</p><p> Lay = sepc .. " " .. external_link( LayURL, cfg.messages['lay summary'], A:ORIGIN('LayURL'), nil ) .. LayFormat .. LaySource .. LayDate</p><p> else</p><p> Lay = sepc .. " " .. external_link( LayURL, cfg.messages['lay summary']:lower(), A:ORIGIN('LayURL'), nil ) .. LayFormat .. LaySource .. LayDate</p><p> end </p><p> elseif is_set (LayFormat) then -- Test if |lay-format= is given without giving a |lay-url=</p><p> Lay = sepc .. LayFormat; -- if set and LayURL not set, then LayFormat has error message</p><p> end</p><p> if is_set(Transcript) then</p><p> if is_set(TranscriptURL) then</p><p> Transcript = external_link( TranscriptURL, Transcript, TranscriptURLorigin, nil );</p><p> end</p><p> Transcript = sepc .. ' ' .. Transcript .. TranscriptFormat;</p><p> elseif is_set(TranscriptURL) then</p><p> Transcript = external_link( TranscriptURL, nil, TranscriptURLorigin, nil );</p><p> end</p><p> local Publisher;</p><p> if is_set(PublicationDate) then</p><p> PublicationDate = wrap_msg ('published', PublicationDate);</p><p> end</p><p> if is_set(PublisherName) then</p><p> if is_set(PublicationPlace) then</p><p> Publisher = sepc .. " " .. PublicationPlace .. ": " .. PublisherName .. PublicationDate;</p><p> else</p><p> Publisher = sepc .. " " .. PublisherName .. PublicationDate;</p><p> end </p><p> elseif is_set(PublicationPlace) then</p><p> Publisher= sepc .. " " .. PublicationPlace .. PublicationDate;</p><p> else</p><p> Publisher = PublicationDate;</p><p> end</p><p> </p><p> -- Several of the above rely upon detecting this as nil, so do it last.</p><p> if is_set(Periodical) then</p><p> if is_set(Title) or is_set(TitleNote) then</p><p> Periodical = sepc .. " " .. wrap_style ('italic-title', Periodical)</p><p> else</p><p> Periodical = wrap_style ('italic-title', Periodical)</p><p> end</p><p> end</p><p> --[[</p><p> Handle the oddity that is cite speech. This code overrides whatever may be the value assigned to TitleNote (through |department=) and forces it to be " (Speech)" so that</p><p> the annotation directly follows the |title= parameter value in the citation rather than the |event= parameter value (if provided).</p><p> ]]</p><p> if "speech" == config.CitationClass then -- cite speech only</p><p> TitleNote = " (Speech)"; -- annotate the citation</p><p> if is_set (Periodical) then -- if Periodical, perhaps because of an included |website= or |journal= parameter</p><p> if is_set (Conference) then -- and if |event= is set</p><p> Conference = Conference .. sepc .. " "; -- then add appropriate punctuation to the end of the Conference variable before rendering</p><p> end</p><p> end</p><p> end</p><p> -- Piece all bits together at last. Here, all should be non-nil.</p><p> -- We build things this way because it is more efficient in LUA</p><p> -- not to keep reassigning to the same string variable over and over.</p><p> local tcommon;</p><p> local tcommon2; -- used for book cite when |contributor= is set</p><p> </p><p> if in_array(config.CitationClass, {"journal","citation"}) and is_set(Periodical) then</p><p> if is_set(Others) then Others = safe_join ({Others, sepc .. " "}, sepc) end -- add terminal punctuation & space; check for dup sepc; TODO why do we need to do this here?</p><p> tcommon = safe_join( {Others, Title, TitleNote, Conference, Periodical, Format, TitleType, Series, Language, Edition, Publisher, Agency, Volume}, sepc );</p><p> elseif in_array(config.CitationClass, {"book","citation"}) and not is_set(Periodical) then -- special cases for book cites</p><p> if is_set (Contributors) then -- when we are citing foreword, preface, introduction, etc</p><p> tcommon = safe_join( {Title, TitleNote}, sepc ); -- author and other stuff will come after this and before tcommon2</p><p> tcommon2 = safe_join( {Conference, Periodical, Format, TitleType, Series, Language, Volume, Others, Edition, Publisher, Agency}, sepc );</p><p> else</p><p> tcommon = safe_join( {Title, TitleNote, Conference, Periodical, Format, TitleType, Series, Language, Volume, Others, Edition, Publisher, Agency}, sepc );</p><p> end</p><p> elseif 'map' == config.CitationClass then -- special cases for cite map</p><p> if is_set (Chapter) then -- map in a book; TitleType is part of Chapter</p><p> tcommon = safe_join( {Title, Format, Edition, Scale, Series, Language, Cartography, Others, Publisher, Volume}, sepc );</p><p> elseif is_set (Periodical) then -- map in a periodical</p><p> tcommon = safe_join( {Title, TitleType, Format, Periodical, Scale, Series, Language, Cartography, Others, Publisher, Volume}, sepc );</p><p> else -- a sheet or stand-alone map</p><p> tcommon = safe_join( {Title, TitleType, Format, Edition, Scale, Series, Language, Cartography, Others, Publisher}, sepc );</p><p> end</p><p> </p><p> elseif 'episode' == config.CitationClass then -- special case for cite episode</p><p> tcommon = safe_join( {Title, TitleNote, TitleType, Series, Transcript, Language, Edition, Publisher}, sepc );</p><p> else -- all other CS1 templates</p><p> tcommon = safe_join( {Title, TitleNote, Conference, Periodical, Format, TitleType, Series, Language,</p><p> Volume, Others, Edition, Publisher, Agency}, sepc );</p><p> end</p><p> </p><p> if #ID_list > 0 then</p><p> ID_list = safe_join( { sepc .. " ", table.concat( ID_list, sepc .. " " ), ID }, sepc );</p><p> else</p><p> ID_list = ID;</p><p> end</p><p> </p><p> local idcommon = safe_join( { ID_list, URL, Archived, AccessDate, Via, SubscriptionRequired, Lay, Quote }, sepc );</p><p> local text;</p><p> local pgtext = Position .. Sheet .. Sheets .. Page .. Pages .. At;</p><p> if is_set(Date) then</p><p> if is_set (Authors) or is_set (Editors) then -- date follows authors or editors when authors not set</p><p> Date = " (" .. Date ..")" .. OrigYear .. sepc .. " "; -- in paranetheses</p><p> else -- neither of authors and editors set</p><p> if (string.sub(tcommon,-1,-1) == sepc) then -- if the last character of tcommon is sepc</p><p> Date = " " .. Date .. OrigYear; -- Date does not begin with sepc</p><p> else</p><p> Date = sepc .. " " .. Date .. OrigYear; -- Date begins with sepc</p><p> end</p><p> end</p><p> end </p><p> if is_set(Authors) then</p><p> if (not is_set (Date)) then -- when date is set it's in parentheses; no Authors termination</p><p> Authors = terminate_name_list (Authors, sepc); -- when no date, terminate with 0 or 1 sepc and a space</p><p> end</p><p> if is_set(Editors) then</p><p> local in_text = " ";</p><p> local post_text = "";</p><p> if is_set(Chapter) and 0 == #c then</p><p> in_text = in_text .. cfg.messages['in'] .. " "</p><p> if (sepc ~= '.') then</p><p> in_text = in_text:lower() -- lowercase for cs2</p><p> end</p><p> else</p><p> if EditorCount <= 1 then</p><p> post_text = ", " .. cfg.messages['editor'];</p><p> else</p><p> post_text = ", " .. cfg.messages['editors'];</p><p> end</p><p> end</p><p> Editors = terminate_name_list (in_text .. Editors .. post_text, sepc); -- terminate with 0 or 1 sepc and a space</p><p> end</p><p> if is_set (Contributors) then -- book cite and we're citing the intro, preface, etc</p><p> local by_text = sepc .. ' ' .. cfg.messages['by'] .. ' ';</p><p> if (sepc ~= '.') then by_text = by_text:lower() end -- lowercase for cs2</p><p> Authors = by_text .. Authors; -- author follows title so tweak it here</p><p> if is_set (Editors) and is_set (Date) then -- when Editors make sure that Authors gets terminated</p><p> Authors = terminate_name_list (Authors, sepc); -- terminate with 0 or 1 sepc and a space</p><p> end</p><p> if (not is_set (Date)) then -- when date is set it's in parentheses; no Contributors termination</p><p> Contributors = terminate_name_list (Contributors, sepc); -- terminate with 0 or 1 sepc and a space</p><p> end</p><p> text = safe_join( {Contributors, Date, Chapter, tcommon, Authors, Place, Editors, tcommon2, pgtext, idcommon }, sepc );</p><p> else</p><p> text = safe_join( {Authors, Date, Chapter, Place, Editors, tcommon, pgtext, idcommon }, sepc );</p><p> end</p><p> elseif is_set(Editors) then</p><p> if is_set(Date) then</p><p> if EditorCount <= 1 then</p><p> Editors = Editors .. ", " .. cfg.messages['editor'];</p><p> else</p><p> Editors = Editors .. ", " .. cfg.messages['editors'];</p><p> end</p><p> else</p><p> if EditorCount <= 1 then</p><p> Editors = Editors .. " (" .. cfg.messages['editor'] .. ")" .. sepc .. " "</p><p> else</p><p> Editors = Editors .. " (" .. cfg.messages['editors'] .. ")" .. sepc .. " "</p><p> end</p><p> end</p><p> text = safe_join( {Editors, Date, Chapter, Place, tcommon, pgtext, idcommon}, sepc );</p><p> else</p><p> if in_array(config.CitationClass, {"journal","citation"}) and is_set(Periodical) then</p><p> text = safe_join( {Chapter, Place, tcommon, pgtext, Date, idcommon}, sepc );</p><p> else</p><p> text = safe_join( {Chapter, Place, tcommon, Date, pgtext, idcommon}, sepc );</p><p> end</p><p> end</p><p> </p><p> if is_set(PostScript) and PostScript ~= sepc then</p><p> text = safe_join( {text, sepc}, sepc ); --Deals with italics, spaces, etc.</p><p> text = text:sub(1,-sepc:len()-1);</p><p> end </p><p> </p><p> text = safe_join( {text, PostScript}, sepc );</p><p> -- Now enclose the whole thing in a <cite/> element</p><p> local options = {};</p><p> </p><p> if is_set(config.CitationClass) and config.CitationClass ~= "citation" then</p><p> options.class = config.CitationClass;</p><p> options.class = "citation " .. config.CitationClass; -- class=citation required for blue highlight when used with |ref=</p><p> else</p><p> options.class = "citation";</p><p> end</p><p> </p><p> if is_set(Ref) and Ref:lower() ~= "none" then -- set reference anchor if appropriate</p><p> local id = Ref</p><p> if ('harv' == Ref ) then</p><p> local namelist = {}; -- holds selected contributor, author, editor name list</p><p> local year = first_set ({Year, anchor_year}, 2); -- Year first for legacy citations and for YMD dates that require disambiguation</p><p> if #c > 0 then -- if there is a contributor list</p><p> namelist = c; -- select it</p><p> elseif #a > 0 then -- or an author list</p><p> namelist = a;</p><p> elseif #e > 0 then -- or an editor list</p><p> namelist = e;</p><p> end</p><p> if #namelist > 0 then -- if there are names in namelist</p><p> id = anchor_id (namelist, year); -- go make the CITEREF anchor</p><p> else</p><p> id = <i>; -- unset</i></p><p> end</p><p> end</p><p> options.id = id;</p><p> end</p><p> </p><p> if string.len(text:gsub("<span[^>/]*>(.-)</span>", "%1"):gsub("%b<>","")) <= 2 then -- remove <span> tags and other html-like markup; then get length of what remains</p><p> z.error_categories = {};</p><p> text = set_error('empty_citation');</p><p> z.message_tail = {};</p><p> end</p><p> </p><p> local render = {}; -- here we collect the final bits for concatenation into the rendered citation</p><p> if is_set(options.id) then -- here we wrap the rendered citation in <cite ...>...</cite> tags</p><p> table.insert (render, substitute (cfg.presentation['cite-id'], {mw.uri.anchorEncode(options.id), mw.text.nowiki(options.class), text})); -- when |ref= is set</p><p> else</p><p> table.insert (render, substitute (cfg.presentation['cite'], {mw.text.nowiki(options.class), text})); -- all other cases</p><p> end </p><p> table.insert (render, substitute (cfg.presentation['ocins'], {OCinSoutput})); -- append metadata to the citation</p><p> if 0 ~= #z.message_tail then</p><p> table.insert (render, ' ');</p><p> for i,v in ipairs( z.message_tail ) do</p><p> if is_set(v[1]) then</p><p> if i == #z.message_tail then</p><p> table.insert (render, error_comment( v[1], v[2] ));</p><p> else</p><p> table.insert (render, error_comment( v[1] .. "; ", v[2] ));</p><p> end</p><p> end</p><p> end</p><p> end</p><p> if 0 ~= #z.maintenance_cats then</p><p> local maint_msgs = {}; -- here we collect all of the maint messages</p><p> for _, v in ipairs( z.maintenance_cats ) do -- append maintenance categories</p><p> local maint = {}; -- here we assemble a maintenence message</p><p> table.insert (maint, v); -- maint msg is the category name</p><p> table.insert (maint, ' ('); -- open the link text</p><p> table.insert (maint, make_wikilink (':Category:' .. v, 'link')); -- add the link</p><p> table.insert (maint, ')'); -- and close it</p><p> table.insert (maint_msgs, table.concat (maint)); -- assemble new maint message and add it to the maint_msgs table</p><p> end</p><p> table.insert (render, substitute (cfg.presentation['hidden-maint'], table.concat (maint_msgs, ' '))); -- wrap the group of maint message with proper presentation and save</p><p> end</p><p> </p><p> no_tracking_cats = no_tracking_cats:lower();</p><p> if in_array(no_tracking_cats, {"", "no", "false", "n"}) then</p><p> for _, v in ipairs( z.error_categories ) do</p><p> table.insert (render, make_wikilink ('Category:' .. v));</p><p> end</p><p> for _, v in ipairs( z.maintenance_cats ) do -- append maintenance categories</p><p> table.insert (render, make_wikilink ('Category:' .. v));</p><p> end</p><p> for _, v in ipairs( z.properties_cats ) do -- append properties categories</p><p> table.insert (render, make_wikilink ('Category:' .. v));</p><p> end</p><p> end</p><p> return table.concat (render); </p><p>end</p>--[[--------------------------< V A L I D A T E >--------------------------------------------------------------<p>Looks for a parameter's name in one of several whitelists.</p><p>Parameters in the whitelist can have three values:</p><p> true - active, supported parameters</p><p> false - deprecated, supported parameters</p><p> nil - unsupported parameters</p><p> </p><p>]]</p><p>local function validate (name, cite_class)</p><p> local name = tostring (name);</p><p> local state;</p><p> </p><p> if in_array (cite_class, {'arxiv', 'biorxiv', 'citeseerx'}) then -- limited parameter sets allowed for these templates</p><p> state = whitelist.limited_basic_arguments[name];</p><p> if true == state then return true; end -- valid actively supported parameter</p><p> if false == state then</p><p> deprecated_parameter (name); -- parameter is deprecated but still supported</p><p> return true;</p><p> end</p><p> state = whitelist[cite_class .. '_basic_arguments'][name]; -- look in the parameter-list for the template identified by cite_class</p><p> if true == state then return true; end -- valid actively supported parameter</p><p> if false == state then</p><p> deprecated_parameter (name); -- parameter is deprecated but still supported</p><p> return true;</p><p> end</p><p> -- limited enumerated parameters list</p><p> name = name:gsub("%d+", "#" ); -- replace digit(s) with # (last25 becomes last#) (mw.ustring because non-Western 'local' digits)</p><p> state = whitelist.limited_numbered_arguments[name];</p><p> if true == state then return true; end -- valid actively supported parameter</p><p> if false == state then</p><p> deprecated_parameter (name); -- parameter is deprecated but still supported</p><p> return true;</p><p> end</p><p> return false; -- not supported because not found or name is set to nil</p><p> end -- end limited parameter-set templates</p><p> </p><p> state = whitelist.basic_arguments[name]; -- all other templates; all normal parameters allowed</p><p> </p><p> if true == state then return true; end -- valid actively supported parameter</p><p> if false == state then</p><p> deprecated_parameter (name); -- parameter is deprecated but still supported</p><p> return true;</p><p> end</p><p> -- all enumerated parameters allowed</p><p> name = name:gsub("%d+", "#" ); -- replace digit(s) with # (last25 becomes last#) (mw.ustring because non-Western 'local' digits)</p><p> state = whitelist.numbered_arguments[name];</p><p> if true == state then return true; end -- valid actively supported parameter</p><p> if false == state then</p><p> deprecated_parameter (name); -- parameter is deprecated but still supported</p><p> return true;</p><p> end</p><p> </p><p> return false; -- not supported because not found or name is set to nil</p><p>end</p>--[[--------------------------< M I S S I N G _ P I P E _ C H E C K >------------------------------------------<p>Look at the contents of a parameter. If the content has a string of characters and digits followed by an equal</p><p>sign, compare the alphanumeric string to the list of cs1|2 parameters. If found, then the string is possibly a</p><p>parameter that is missing its pipe:</p><p> {{cite ... |title=Title access-date=2016-03-17}}</p><p>cs1|2 shares some parameter names with xml/html atributes: class=, title=, etc. To prevent false positives xml/html</p><p>tags are removed before the search.</p><p>If a missing pipe is detected, this function adds the missing pipe maintenance category.</p><p>]]</p><p>local function missing_pipe_check (value)</p><p> local capture;</p><p> value = value:gsub ('%b<>', <i>); -- remove xml/html tags because attributes: class=, title=, etc</i></p><p> capture = value:match ('%s+(%a[%a%d]+)%s*=') or value:match ('^(%a[%a%d]+)%s*='); -- find and categorize parameters with possible missing pipes</p><p> if capture and validate (capture) then -- if the capture is a valid parameter name</p><p> add_maint_cat ('missing_pipe');</p><p> end</p><p>end</p>--[[--------------------------< C S 1 . C I T A T I O N >------------------------------------------------------<p>This is used by templates such as {{cite book}} to create the actual citation text.</p><p>]]</p><p>function cs1.citation(frame)</p><p> Frame = frame; -- save a copy incase we need to display an error message in preview mode</p><p> local pframe = frame:getParent()</p><p> local validation, utilities, identifiers, metadata, styles;</p><p> </p><p> if nil ~= string.find (frame:getTitle(), 'sandbox', 1, true) then -- did the {{#invoke:}} use sandbox version?</p><p> cfg = mw.loadData ('Module:Citation/CS1/Configuration/sandbox'); -- load sandbox versions of support modules</p><p> whitelist = mw.loadData ('Module:Citation/CS1/Whitelist/sandbox');</p><p> utilities = require ('Module:Citation/CS1/Utilities/sandbox');</p><p> validation = require ('Module:Citation/CS1/Date_validation/sandbox');</p><p> identifiers = require ('Module:Citation/CS1/Identifiers/sandbox');</p><p> metadata = require ('Module:Citation/CS1/COinS/sandbox');</p><p> styles = 'Module:Citation/CS1/sandbox/styles.css';</p><p> </p><p> else -- otherwise</p><p> cfg = mw.loadData ('Module:Citation/CS1/Configuration'); -- load live versions of support modules</p><p> whitelist = mw.loadData ('Module:Citation/CS1/Whitelist');</p><p> utilities = require ('Module:Citation/CS1/Utilities');</p><p> validation = require ('Module:Citation/CS1/Date_validation');</p><p> identifiers = require ('Module:Citation/CS1/Identifiers');</p><p> metadata = require ('Module:Citation/CS1/COinS');</p><p> styles = 'Module:Citation/CS1/styles.css';</p><p> end</p><p> utilities.set_selected_modules (cfg); -- so that functions in Utilities can see the cfg tables</p><p> identifiers.set_selected_modules (cfg, utilities); -- so that functions in Identifiers can see the selected cfg tables and selected Utilities module</p><p> validation.set_selected_modules (cfg, utilities); -- so that functions in Date validataion can see selected cfg tables and the selected Utilities module</p><p> metadata.set_selected_modules (cfg, utilities); -- so that functions in COinS can see the selected cfg tables and selected Utilities module</p><p> dates = validation.dates; -- imported functions from Module:Citation/CS1/Date validation</p><p> year_date_check = validation.year_date_check;</p><p> reformat_dates = validation.reformat_dates;</p><p> date_hyphen_to_dash = validation.date_hyphen_to_dash;</p><p> date_name_xlate = validation.date_name_xlate;</p><p> is_set = utilities.is_set; -- imported functions from Module:Citation/CS1/Utilities</p><p> in_array = utilities.in_array;</p><p> substitute = utilities.substitute;</p><p> error_comment = utilities.error_comment;</p><p> set_error = utilities.set_error;</p><p> select_one = utilities.select_one;</p><p> add_maint_cat = utilities.add_maint_cat;</p><p> wrap_style = utilities.wrap_style;</p><p> safe_for_italics = utilities.safe_for_italics;</p><p> is_wikilink = utilities.is_wikilink;</p><p> make_wikilink = utilities.make_wikilink;</p><p> z = utilities.z; -- table of error and category tables in Module:Citation/CS1/Utilities</p><p> extract_ids = identifiers.extract_ids; -- imported functions from Module:Citation/CS1/Identifiers</p><p> build_id_list = identifiers.build_id_list;</p><p> is_embargoed = identifiers.is_embargoed;</p><p> extract_id_access_levels = identifiers.extract_id_access_levels;</p><p> </p><p> make_coins_title = metadata.make_coins_title; -- imported functions from Module:Citation/CS1/COinS</p><p> get_coins_pages = metadata.get_coins_pages;</p><p> COinS = metadata.COinS;</p><p> local args = {}; -- table where we store all of the template's arguments</p><p> local suggestions = {}; -- table where we store suggestions if we need to loadData them</p><p> local error_text, error_state;</p><p> local config = {}; -- table to store parameters from the module {{#invoke:}}</p><p> for k, v in pairs( frame.args ) do</p><p> config[k] = v;</p>-- args[k] = v; -- debug tool that allows us to render a citation from module {{#invoke:}}<p> end </p><p> local capture; -- the single supported capture when matching unknown parameters using patterns</p><p> for k, v in pairs( pframe.args ) do</p><p> if v ~= <i> then</i></p><p> if ('string' == type (k)) then</p><p> k = mw.ustring.gsub (k, '%d', cfg.date_names.local_digits); -- for enumerated parameters, translate 'local' digits to Western 0-9</p><p> end</p><p> if not validate( k, config.CitationClass ) then </p><p> error_text = "";</p><p> if type( k ) ~= 'string' then</p><p> -- Exclude empty numbered parameters</p><p> if v:match("%S+") ~= nil then</p><p> error_text, error_state = set_error( 'text_ignored', {v}, true );</p><p> end</p><p> elseif validate( k:lower(), config.CitationClass ) then</p><p> error_text, error_state = set_error( 'parameter_ignored_suggest', {k, k:lower()}, true ); -- suggest the lowercase version of the parameter</p><p> else</p><p> if nil == suggestions.suggestions then -- if this table is nil then we need to load it</p><p> if nil ~= string.find (frame:getTitle(), 'sandbox', 1, true) then -- did the {{#invoke:}} use sandbox version?</p><p> suggestions = mw.loadData( 'Module:Citation/CS1/Suggestions/sandbox' ); -- use the sandbox version</p><p> else</p><p> suggestions = mw.loadData( 'Module:Citation/CS1/Suggestions' ); -- use the live version</p><p> end</p><p> end</p><p> for pattern, param in pairs (suggestions.patterns) do -- loop through the patterns to see if we can suggest a proper parameter</p><p> capture = k:match (pattern); -- the whole match if no caputre in pattern else the capture if a match</p><p> if capture then -- if the pattern matches</p><p> param = substitute (param, capture); -- add the capture to the suggested parameter (typically the enumerator)</p><p> if validate (param, config.CitationClass) then -- validate the suggestion to make sure that the suggestion is supported by this template (necessary for limited parameter lists)</p><p> error_text, error_state = set_error ('parameter_ignored_suggest', {k, param}, true); -- set the suggestion error message</p><p> else</p><p> error_text, error_state = set_error( 'parameter_ignored', {param}, true ); -- suggested param not supported by this template</p><p> end</p><p> end</p><p> end</p><p> if not is_set (error_text) then -- couldn't match with a pattern, is there an expicit suggestion?</p><p> if suggestions.suggestions[ k:lower() ] ~= nil then</p><p> error_text, error_state = set_error( 'parameter_ignored_suggest', {k, suggestions.suggestions[ k:lower() ]}, true );</p><p> else</p><p> error_text, error_state = set_error( 'parameter_ignored', {k}, true );</p><p> v = <i>; -- unset value assigned to unrecognized parameters (this for the limited parameter lists)</i></p><p> end</p><p> end</p><p> end </p><p> if error_text ~= <i> then</i></p><p> table.insert( z.message_tail, {error_text, error_state} );</p><p> end </p><p> end</p><p> missing_pipe_check (v); -- do we think that there is a parameter that is missing a pipe?</p><p> -- TODO: is this the best place for this translation?</p><p> args[k] = v;</p><p> elseif args[k] ~= nil or (k == 'postscript') then -- here when v is empty string</p><p> args[k] = v; -- why do we do this? we don't support 'empty' parameters</p><p> end </p><p> end </p><p> for k, v in pairs( args ) do</p><p> if 'string' == type (k) then -- don't evaluate positional parameters</p><p> has_invisible_chars (k, v);</p><p> end</p><p> end</p><p> return table.concat ({citation0( config, args), frame:extensionTag ('templatestyles', <i>, {src=styles})});</i></p><p>end</p><p>return cs1;</p></td> </tr> <tr> <td width="61" align="center">随便看</td> <td> <ul class="random"> <li><a target="_blank" href="8772823.html">Charles Pasley (engineer)</a></li> <li><a target="_blank" href="8772824.html">Charles passel</a></li> <li><a target="_blank" href="8772825.html">Charles "Pat" Dougherty</a></li> <li><a target="_blank" href="8772826.html">Charles Paterno</a></li> <li><a target="_blank" href="8772827.html">Charles Paterno (disambiguation)</a></li> <li><a target="_blank" href="8772828.html">Charles Patin</a></li> <li><a target="_blank" href="8772829.html">Charles Patrick Daly</a></li> <li><a target="_blank" href="8772830.html">Charles Patrick Evelyn Brooks</a></li> <li><a target="_blank" href="8772831.html">Charles Patrick John Coghlan</a></li> <li><a target="_blank" href="8772832.html">Charles Patterson</a></li> <li><a target="_blank" href="8772833.html">Charles Patterson (author)</a></li> <li><a target="_blank" href="8772834.html">Charles, Paul</a></li> <li><a target="_blank" href="8772835.html">Charles Paul</a></li> <li><a target="_blank" href="8772836.html">Charles Paul De Kock</a></li> <li><a target="_blank" href="8772837.html">Charles Paul Ernest, Count of Bentheim-Steinfurt</a></li> <li><a target="_blank" href="8772838.html">Charles Paul Gruppé</a></li> <li><a target="_blank" href="8772839.html">Charles Paulk</a></li> <li><a target="_blank" href="8772840.html">Charles Paullin</a></li> <li><a target="_blank" href="8772841.html">Charles Paul McClelland</a></li> <li><a target="_blank" href="8772842.html">Charles Paul Narcisse Moreau</a></li> <li><a target="_blank" href="8772843.html">Charles Pawlica</a></li> <li><a target="_blank" href="8772844.html">Charles Payne</a></li> <li><a target="_blank" href="8772845.html">Charles Payne (cricketer)</a></li> <li><a target="_blank" href="8772846.html">Charles Payne (cricketer, born 1827)</a></li> <li><a target="_blank" href="8772847.html">Charles Payne (cricketer, born 1832)</a></li> </ul> </td> </tr> </table> <p> </p> <p>开放百科全书收录14589846条英语、德语、日语等多语种百科知识,基本涵盖了大多数领域的百科知识,是一部内容自由、开放的电子版国际百科全书。<p> </p> <div class="foot">Copyright © 2023 OENC.NET All Rights Reserved<BR>京ICP备2021023879号<span class="updatetime"> 更新时间:2024/11/10 20:59:31</span><script src="Images/tongji.js" type="text/javascript"></script></div> </body> </html>