Modiwl:Citation/CS1: Gwahaniaeth rhwng fersiynau
Cynnwys wedi'i ddileu Cynnwys wedi'i ychwanegu
Crëwyd tudalen newydd yn dechrau gyda ' local z = { error_categories = {}; -- for categorizing citations that contain errors error_ids = {}; message_tail = {}; maintenance_cats = {}; -- f...' |
diweddaru |
||
Llinell 8:
}
--[[--------------------------< F O R W A R D D E C L A R A T I O N S >--------------------------------------
]]
local dates, year_date_check -- functions in Module:Citation/CS1/Date_validation
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
--[[--------------------------< I S _ S E T >------------------------------------------------------------------
Returns true if argument is set; false otherwise. Argument is 'set' when it exists (not nil) or when it is not an empty string.
This function is global because it is called from both this module and from Date validation
]]
function is_set( var )
return not (var == nil or var == '');
end
--[[--------------------------< F I R S T _ S E T >------------------------------------------------------------
First set variable or nil if none
]]
local function first_set(...)
local list = {...};
for _, var in pairs(list) do
Llinell 23 ⟶ 40:
end
--[[--------------------------< I N _ A R R A Y >--------------------------------------------------------------
Whether needle is in haystack
]]
local function in_array( needle, haystack )
if needle == nil then
return false;
Llinell 36 ⟶ 58:
end
--[[--------------------------< S U B S T I T U T E >----------------------------------------------------------
Populates numbered arguments in a message string using an argument table.
]]
local function substitute( msg, args )
return args and mw.message.newRawMessage( msg, args ):plain() or msg;
end
--[[--------------------------< E R R O R _ C O M M E N T >----------------------------------------------------
Wraps error messages with css markup according to the state of hidden.
]]
local function error_comment( content, hidden )
return substitute( hidden and cfg.presentation['hidden-error'] or cfg.presentation['visible-error'], content );
end
--[[--------------------------< S E T _ E R R O R >--------------------------------------------------------------
Sets an error condition and returns the appropriate error message. The actual placement of the error message in the output is
the responsibility of the calling function.
]]
local function set_error( error_id, arguments, raw, prefix, suffix )
local error_state = cfg.error_conditions[ error_id ];
prefix = prefix or "";
suffix = suffix or "";
if error_state == nil then
error( cfg.messages['undefined_error'] );
elseif is_set( error_state.category ) then
table.insert( z.error_categories, error_state.category );
end
local message = substitute( error_state.message, arguments );
message = message .. " ([[" .. cfg.messages['help page link'] ..
"#" .. error_state.anchor .. "|" ..
cfg.messages['help page label'] .. "]])";
z.error_ids[ error_id ] = true;
if in_array( error_id, { 'bare_url_missing_title', 'trans_missing_title' } )
and z.error_ids['citation_missing_title'] then
return '', false;
end
message = table.concat({ prefix, message, suffix });
if raw == true then
return message, error_state.hidden;
end
return error_comment( message, error_state.hidden );
end
--[[--------------------------< A D D _ M A I N T _ C A T >------------------------------------------------------
Adds a category to z.maintenance_cats using names from the configuration file with additional text if any.
To prevent duplication, the added_maint_cats table lists the categories by key that have been added to z.maintenance_cats.
]]
local added_maint_cats = {} -- list of maintenance categories that have been added to z.maintenance_cats
local function add_maint_cat (key, arguments)
if not added_maint_cats [key] then
added_maint_cats [key] = true; -- note that we've added this category
table.insert( z.maintenance_cats, substitute (cfg.maint_cats [key], arguments)); -- make name then add to table
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.
]]
local added_prop_cats = {} -- list of property categories that have been added to z.properties_cats
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
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.
]]
local added_vanc_errs; -- flag so we only emit one Vancouver error / category
local function add_vanc_error ()
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', {}, true ) } );
end
end
--[[--------------------------< C H E C K _ U R L >------------------------------------------------------------
Determines whether a URL string is valid.
At present the only check is whether the string appears to be prefixed with a URI scheme. It is not determined whether
the URI scheme is valid or whether the URL is otherwise well formed.
]]
local function check_url( url_str )
return url_str:sub(1,2) == "//" or url_str:match( "^[^/]*:" ) ~= nil; -- Protocol-relative or URL scheme
end
--[[--------------------------< S A F E _ F O R _ I T A L I C S >----------------------------------------------
Protects a string that will be wrapped in wiki italic markup '' ... ''
Note: We cannot use <i> for italics, as the expected behavior for italics specified by ''...'' in the title is that
they will be inverted (i.e. unitalicized) in the resulting references. In addition, <i> and '' tend to interact
poorly under Mediawiki's HTML tidy.
]]
local function safe_for_italics( str )
if not is_set(str) then
return str;
else
if str:sub(1,1) == "'" then str = "<span />" .. str; end
if str:sub(-1,-1) == "'" then str = str .. "<span />"; end
-- Remove newlines as they break italics.
return str:gsub( '\n', ' ' );
end
end
--[[--------------------------< S A F E _ F O R _ U R L >------------------------------------------------------
Escape sequences for content that will be used for URL descriptions
]]
local function safe_for_url( str )
if str:match( "%[%[.-%]%]" ) ~= nil then
table.insert( z.message_tail, { set_error( 'wikilink_in_url', {}, true ) } );
end
return str:gsub( '[%[%]\n]', {
['['] = '[',
[']'] = ']',
['\n'] = ' ' } );
end
--[[--------------------------< W R A P _ S T Y L E >----------------------------------------------------------
Applies styling to various parameters. Supplied string is wrapped using a message_list configuration taking one
argument; protects italic styled parameters. Additional text taken from citation_config.presentation - the reason
this function is similar to but separate from wrap_msg().
]]
local function wrap_style (key, str)
if not is_set( str ) then
return "";
elseif in_array( key, { 'italic-title', 'trans-italic-title' } ) then
str = safe_for_italics( str );
end
return substitute( cfg.presentation[key], {str} );
end
--[[--------------------------< E X T E R N A L _ L I N K >----------------------------------------------------
Format an external link with error checking
]]
local function external_link( URL, label, source )
local error_str = "";
if not is_set( label ) then
label = URL;
if is_set( source ) then
error_str = set_error( 'bare_url_missing_title', { wrap_style ('parameter', source) }, false, " " );
else
error( cfg.messages["bare_url_no_origin"] );
end
end
if not check_url( URL ) then
error_str = set_error( 'bad_url', {}, false, " " ) .. error_str;
end
return table.concat({ "[", URL, " ", safe_for_url( label ), "]", error_str });
end
--[[--------------------------< E X T E R N A L _ L I N K _ I D >----------------------------------------------
Formats a wiki style external link
]]
local function external_link_id(options)
local url_string = options.id;
if options.encode == true or options.encode == nil then
url_string = mw.uri.encode( url_string );
end
return mw.ustring.format( '[[%s|%s]]%s[%s%s%s %s]',
options.link, options.label, options.separator or " ",
options.prefix, url_string, options.suffix or "",
mw.text.nowiki(options.id)
);
end
--[[--------------------------< D E P R E C A T E D _ P A R A M E T E R >--------------------------------------
Categorize and emit an error message when the citation contains one or more deprecated parameters. The function includes the
offending parameter name to the error message. Only one error message is emitted regardless of the number of deprecated
parameters in the citation.
]]
local page_in_deprecated_cat; -- sticky flag so that the category is added only once
local function deprecated_parameter(name)
if not page_in_deprecated_cat then
page_in_deprecated_cat = true; -- note that we've added this category
table.insert( z.message_tail, { set_error( 'deprecated_params', {name}, true ) } ); -- add error message
end
end
Llinell 65 ⟶ 298:
]]
local function kern_quotes (str)
local cap='';
local cap2='';
Llinell 106 ⟶ 339:
]]
local function format_script_value (script_value)
local lang=''; -- initialize to empty string
local name;
Llinell 119 ⟶ 352:
script_value = script_value:gsub ('^%l%l%s*:%s*', ''); -- strip prefix from script
-- is prefix one of these language codes?
if
add_prop_cat ('script_with_name', {name, lang})
else
add_prop_cat ('script')
end
lang = ' lang="' .. lang .. '" '; -- convert prefix into a lang attribute
Llinell 140 ⟶ 373:
]]
local function script_concatenate (title, script)
if is_set (script) then
script = format_script_value (script); -- <bdi> tags, lang atribute, categorization, etc; returns empty string on error
Llinell 148 ⟶ 381:
end
return title;
end
Llinell 178 ⟶ 392:
]]
local function wrap_msg (key, str, lower)
if not is_set( str ) then
return "";
Llinell 190 ⟶ 404:
return substitute( cfg.messages[key], {str} );
end
end
--[[--------------------------< S E L E C T _ O N E >----------------------------------------------------------
Chooses one matching parameter from a list of parameters to consider
Generates an error if more than one match is present.
]]
local function select_one( args, possible, error_condition, index )
local value = nil;
local selected = '';
local error_list = {};
if index ~= nil then index = tostring(index); end
-- Handle special case of "#" replaced by empty string
if index == '1' then
for _, v in ipairs( possible ) do
v = v:gsub( "#", "" );
if is_set(args[v]) then
if value ~= nil and selected ~= v then
table.insert( error_list, v );
else
value = args[v];
selected = v;
end
end
end
end
for _, v in ipairs( possible ) do
if index ~= nil then
v = v:gsub( "#", index );
end
if is_set(args[v]) then
if value ~= nil and selected ~= v then
table.insert( error_list, v );
else
value = args[v];
selected = v;
end
end
end
if #error_list > 0 then
local error_str = "";
for _, k in ipairs( error_list ) do
if error_str ~= "" then error_str = error_str .. cfg.messages['parameter-separator'] end
error_str = error_str .. wrap_style ('parameter', k);
end
if #error_list > 1 then
error_str = error_str .. cfg.messages['parameter-final-separator'];
else
error_str = error_str .. cfg.messages['parameter-pair-separator'];
end
error_str = error_str .. wrap_style ('parameter', selected);
table.insert( z.message_tail, { set_error( error_condition, {error_str}, true ) } );
end
return value, selected;
end
Llinell 199 ⟶ 474:
]]
local function format_chapter_title (chapter, transchapter, chapterurl, chapter_url_source)
local chapter_error = '';
Llinell 206 ⟶ 481:
if is_set (transchapter) then
chapter = wrap_style ('trans-quoted-title', transchapter);
chapter_error = " " ..
end
if is_set (chapterurl) then
chapter =
end
return chapter .. chapter_error;
Llinell 220 ⟶ 495:
end
if is_set (chapterurl) then
chapter =
end
end
Llinell 231 ⟶ 506:
can be transparently aliased to single internal variable.
]]
local function argument_wrapper( args )
local origin = {};
Llinell 249 ⟶ 525:
if type( list ) == 'table' then
v, origin[k] =
if origin[k] == nil then
origin[k] = ''; -- Empty string, not nil
Llinell 281 ⟶ 557:
nil - unsupported parameters
]]
local function validate( name )
local name = tostring( name );
local state = whitelist.basic_arguments[ name ];
Llinell 304 ⟶ 581:
end
-- Formats a wiki style internal link
local function
return mw.ustring.format( '[[%s|%s]]%s[[%s%s%s|%s]]',
options.link, options.label, options.separator or " ",
Llinell 372 ⟶ 591:
end
--[[--------------------------< N O W R A P _ D A T E >--------------------------------------------------------
Llinell 398 ⟶ 601:
]]
local function nowrap_date (date)
local cap='';
local cap2='';
Llinell 405 ⟶ 608:
date = substitute (cfg.presentation['nowrap1'], date);
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
cap, cap2 = string.match (date, "^(.*)%s+(%d%d%d%d)$");
date = substitute (cfg.presentation['nowrap2'], {cap, cap2});
Llinell 411 ⟶ 614:
return date;
end
--[[--------------------------< IS _ V A L I D _ I S X N >-----------------------------------------------------
ISBN-10 and ISSN validator code calculates checksum across all isbn/issn digits including the check digit. ISBN-13 is checked in check_isbn().
If the number is valid the result will be 0. Before calling this function, issbn/issn must be checked for length and stripped of dashes,
spaces and other non-isxn characters.
]]
local function is_valid_isxn (isxn_str, len)
local temp = 0;
isxn_str = { isxn_str:byte(1, len) }; -- make a table of byte values '0' → 0x30 .. '9' → 0x39, 'X' → 0x58
len = len+1; -- adjust to be a loop counter
for i, v in ipairs( isxn_str ) do -- loop through all of the bytes and calculate the checksum
if v == string.byte( "X" ) then -- if checkdigit is X (compares the byte value of 'X' which is 0x58)
temp = temp + 10*( len - i ); -- it represents 10 decimal
else
temp = temp + tonumber( string.char(v) )*(len-i);
end
end
return temp % 11 == 0; -- returns true if calculation result is zero
end
--[[--------------------------< IS _ V A L I D _ I S X N _ 1 3 >----------------------------------------------
ISBN-13 and ISMN validator code calculates checksum across all 13 isbn/ismn digits including the check digit.
If the number is valid, the result will be 0. Before calling this function, isbn-13/ismn must be checked for length
and stripped of dashes, spaces and other non-isxn-13 characters.
]]
local function is_valid_isxn_13 (isxn_str)
local temp=0;
isxn_str = { isxn_str:byte(1, 13) }; -- make a table of byte values '0' → 0x30 .. '9' → 0x39
for i, v in ipairs( isxn_str ) do
temp = temp + (3 - 2*(i % 2)) * tonumber( string.char(v) ); -- multiply odd index digits by 1, even index digits by 3 and sum; includes check digit
end
return temp % 10 == 0; -- sum modulo 10 is zero when isbn-13/ismn is correct
end
--[[--------------------------< C H E C K _ I S B N >------------------------------------------------------------
Determines whether an ISBN string is valid
]]
local function check_isbn( isbn_str )
if nil ~= isbn_str:match("[^%s-0-9X]") then return false; end -- fail if isbn_str contains anything but digits, hyphens, or the uppercase X
isbn_str = isbn_str:gsub( "-", "" ):gsub( " ", "" ); -- remove hyphens and spaces
local len = isbn_str:len();
if len ~= 10 and len ~= 13 then
return false;
end
if len == 10 then
if isbn_str:match( "^%d*X?$" ) == nil then return false; end
return is_valid_isxn(isbn_str, 10);
else
local temp = 0;
if isbn_str:match( "^97[89]%d*$" ) == nil then return false; end -- isbn13 begins with 978 or 979; ismn begins with 979
return is_valid_isxn_13 (isbn_str);
end
end
--[[--------------------------< C H E C K _ I S M N >------------------------------------------------------------
Determines whether an ISMN string is valid. Similar to isbn-13, ismn is 13 digits begining 979-0-... and uses the
same check digit calculations. See http://www.ismn-international.org/download/Web_ISMN_Users_Manual_2008-6.pdf
section 2, pages 9–12.
]]
local function ismn (id)
local handler = cfg.id_handlers['ISMN'];
local text;
local valid_ismn = true;
id=id:gsub( "[%s-–]", "" ); -- strip spaces, hyphens, and endashes from the ismn
if 13 ~= id:len() or id:match( "^9790%d*$" ) == nil then -- ismn must be 13 digits and begin 9790
valid_ismn = false;
else
valid_ismn=is_valid_isxn_13 (id); -- validate ismn
end
-- text = internal_link_id({link = handler.link, label = handler.label, -- use this (or external version) when there is some place to link to
-- prefix=handler.prefix,id=id,separator=handler.separator, encode=handler.encode})
text="[[" .. handler.link .. "|" .. handler.label .. "]]:" .. handler.separator .. id; -- because no place to link to yet
if false == valid_ismn then
text = text .. ' ' .. set_error( 'bad_ismn' ) -- add an error message if the issn is invalid
end
return text;
end
--[[--------------------------< I S S N >----------------------------------------------------------------------
Validate and format an issn. This code fixes the case where an editor has included an ISSN in the citation but has separated the two groups of four
digits with a space. When that condition occurred, the resulting link looked like this:
|issn=0819 4327 gives: [http://www.worldcat.org/issn/0819 4327 0819 4327] -- can't have spaces in an external link
This code now prevents that by inserting a hyphen at the issn midpoint. It also validates the issn for length and makes sure that the checkdigit agrees
with the calculated value. Incorrect length (8 digits), characters other than 0-9 and X, or checkdigit / calculated value mismatch will all cause a check issn
error message. The issn is always displayed with a hyphen, even if the issn was given as a single group of 8 digits.
]]
local function issn(id)
local issn_copy = id; -- save a copy of unadulterated issn; use this version for display if issn does not validate
local handler = cfg.id_handlers['ISSN'];
local text;
local valid_issn = true;
id=id:gsub( "[%s-–]", "" ); -- strip spaces, hyphens, and endashes from the issn
if 8 ~= id:len() or nil == id:match( "^%d*X?$" ) then -- validate the issn: 8 digits long, containing only 0-9 or X in the last position
valid_issn=false; -- wrong length or improper character
else
valid_issn=is_valid_isxn(id, 8); -- validate issn
end
if true == valid_issn then
id = string.sub( id, 1, 4 ) .. "-" .. string.sub( id, 5 ); -- if valid, display correctly formatted version
else
id = issn_copy; -- if not valid, use the show the invalid issn with error message
end
text = external_link_id({link = handler.link, label = handler.label,
prefix=handler.prefix,id=id,separator=handler.separator, encode=handler.encode})
if false == valid_issn then
text = text .. ' ' .. set_error( 'bad_issn' ) -- add an error message if the issn is invalid
end
return text
end
Llinell 422 ⟶ 767:
]]
local function amazon(id, domain)
local err_cat = ""
if not id:match("^[%d%u][%d%u][%d%u][%d%u][%d%u][%d%u][%d%u][%d%u][%d%u][%d%u]$") then
err_cat = ' ' ..
else
if id:match("^%d%d%d%d%d%d%d%d%d[%dX]$") then -- if 10-digit numeric (or 9 digits with terminal X)
if
add_maint_cat ('ASIN');
elseif not is_set (err_cat) then
err_cat = ' ' ..
end
elseif not id:match("^%u[%d%u]+$") then
err_cat = ' ' ..
end
end
if not is_set(domain) then
domain = "com";
elseif
domain = "co." .. domain;
elseif
domain = "com." .. domain;
end
local handler = cfg.id_handlers['ASIN'];
return
label=handler.label , prefix="//www.amazon."..domain.."/dp/",id=id,
encode=handler.encode, separator = handler.separator}) .. err_cat;
Llinell 480 ⟶ 825:
]]
local function arxiv (id, class)
local handler = cfg.id_handlers['ARXIV'];
local year, month, version;
local err_cat =
local text;
if id:match("^%a[%a%.%-]+/[90]%d[01]%d%d%d%d$") or id:match("^%a[%a%.%-]+/[90]%d[01]%d%d%d%dv%d+$") then -- test for the 9108-0703 format w/ & w/o version
Llinell 491 ⟶ 837:
if ((not (90 < year or 8 > year)) or (1 > month or 12 < month)) or -- if invalid year or invalid month
((91 == year and 7 > month) or (7 == year and 3 < month)) then -- if years ok, are starting and ending months ok?
err_cat = ' ' ..
end
elseif id:match("^%d%d[01]%d%.%d%d%d%d$") or id:match("^%d%d[01]%d%.%d%d%d%dv%d+$") then -- test for the 0704-1412 w/ & w/o version
Llinell 499 ⟶ 845:
if ((7 > year) or (14 < year) or (1 > month or 12 < month)) or -- is year invalid or is month invalid? (doesn't test for future years)
((7 == year) and (4 > month)) then --or -- when year is 07, is month invalid (before April)?
err_cat = ' ' ..
end
elseif id:match("^%d%d[01]%d%.%d%d%d%d%d$") or id:match("^%d%d[01]%d%.%d%d%d%d%dv%d+$") then -- test for the 1501- format w/ & w/o version
Llinell 506 ⟶ 852:
month = tonumber(month);
if ((15 > year) or (1 > month or 12 < month)) then -- is year invalid or is month invalid? (doesn't test for future years)
err_cat = ' ' ..
end
else
err_cat = ' ' ..
end
prefix=handler.prefix,id=id,separator=handler.separator, encode=handler.encode}) .. err_cat;
if is_set (class) then
class = ' [[' .. '//arxiv.org/archive/' .. class .. ' ' .. class .. ']]'; -- external link within square brackets, not wikilink
else
class = ''; -- empty string for concatenation
end
return text .. class;
end
--[[
Llinell 530 ⟶ 883:
]]
local function normalize_lccn (lccn)
lccn = lccn:gsub ("%s", ""); -- 1. strip whitespace
Llinell 560 ⟶ 913:
]]
local function lccn(lccn)
local handler = cfg.id_handlers['LCCN'];
local err_cat = ''; -- presume that LCCN is valid
Llinell 570 ⟶ 924:
if 8 == len then
if id:match("[^%d]") then -- if LCCN has anything but digits (nil if only digits)
err_cat = ' ' ..
end
elseif 9 == len then -- LCCN should be adddddddd
if nil == id:match("%l%d%d%d%d%d%d%d%d") then -- does it match our pattern?
err_cat = ' ' ..
end
elseif 10 == len then -- LCCN should be aadddddddd or dddddddddd
if id:match("[^%d]") then -- if LCCN has anything but digits (nil if only digits) ...
if nil == id:match("^%l%l%d%d%d%d%d%d%d%d") then -- ... see if it matches our pattern
err_cat = ' ' ..
end
end
elseif 11 == len then -- LCCN should be aaadddddddd or adddddddddd
if not (id:match("^%l%l%l%d%d%d%d%d%d%d%d") or id:match("^%l%d%d%d%d%d%d%d%d%d%d")) then -- see if it matches one of our patterns
err_cat = ' ' ..
end
elseif 12 == len then -- LCCN should be aadddddddddd
if not id:match("^%l%l%d%d%d%d%d%d%d%d%d%d") then -- see if it matches our pattern
err_cat = ' ' ..
end
else
err_cat = ' ' ..
end
if not is_set (err_cat) and nil ~= lccn:find ('%s') then
err_cat = ' ' ..
end
return
prefix=handler.prefix,id=lccn,separator=handler.separator, encode=handler.encode}) .. err_cat;
end
Llinell 606 ⟶ 960:
contains only digits and is less than test_limit; the value in local variable test_limit will need to be updated periodically as more PMIDs are issued.
]]
local function pmid(id)
local test_limit = 30000000; -- update this value as PMIDs approach
local handler = cfg.id_handlers['PMID'];
Llinell 612 ⟶ 967:
if id:match("[^%d]") then -- if PMID has anything but digits
err_cat = ' ' ..
else -- PMID is only digits
local id_num = tonumber(id); -- convert id to a number for range testing
if 1 > id_num or test_limit < id_num then -- if PMID is outside test limit boundaries
err_cat = ' ' ..
end
end
return
prefix=handler.prefix,id=id,separator=handler.separator, encode=handler.encode}) .. err_cat;
end
--[[--------------------------< I S _ E M B A R G O E D >------------------------------------------------------
Determines if a PMC identifier's online version is embargoed. Compares the date in |embargo= against today's date. If embargo date is
in the future, returns
|embargo= was not set in this cite. ]]
if is_set (embargo) then
local lang = mw.getContentLanguage();
local good1, embargo_date, good2, todays_date;
Llinell 635 ⟶ 994:
good2, todays_date = pcall( lang.formatDate, lang, 'U' );
if good1 and good2 then -- if embargo date and today's date are good dates
if tonumber( embargo_date ) >= tonumber( todays_date ) then -- is embargo date is in the future? return
else
add_maint_cat ('embargo')
return ''; -- unset because embargo has expired
end
end
end
return
end
--[[--------------------------< P M C >------------------------------------------------------------------------
Format a PMC, do simple error checking, and check for embargoed articles.
The embargo parameter takes a date for a value. If the embargo date is in the future the PMC identifier will not
PMC embargo date testing is done in function is_embargoed () which is called earlier because when the citation
has |pmc=<value> but does not have a |url= then |title= is linked with the PMC link. Function is_embargoed ()
returns the embargo date if the PMC article is still embargoed, otherwise it returns an empty string.
PMCs are sequential numbers beginning at 1 and counting up. This code checks the PMC to see that it contains only digits and is less
than test_limit; the value in local variable test_limit will need to be updated periodically as more PMCs are issued.
]]
local function pmc(id, embargo)
local test_limit = 5000000; -- update this value as PMCs approach
local handler = cfg.id_handlers['PMC'];
Llinell 660 ⟶ 1,031:
if id:match("[^%d]") then -- if PMC has anything but digits
err_cat = ' ' ..
else -- PMC is only digits
local id_num = tonumber(id); -- convert id to a number for range testing
if 1 > id_num or test_limit < id_num then -- if PMC is outside test limit boundaries
err_cat = ' ' ..
end
end
if
text="[[" .. handler.link .. "|" .. handler.label .. "]]:" .. handler.separator .. id .. err_cat; -- still embargoed so no external link
else
text =
prefix=handler.prefix,id=id,separator=handler.separator, encode=handler.encode}) .. err_cat;
end
Llinell 689 ⟶ 1,060:
-- and terminal punctuation may not be technically correct but it appears, that in practice these characters are rarely if ever used in doi names.
local function doi(id, inactive)
local cat = ""
local handler = cfg.id_handlers['DOI'];
Llinell 704 ⟶ 1,075:
inactive = " (" .. cfg.messages['inactive'] .. " " .. inactive .. ")"
else
text =
prefix=handler.prefix,id=id,separator=handler.separator, encode=handler.encode})
inactive = ""
Llinell 710 ⟶ 1,081:
if nil == id:match("^10%.[^%s–]-/[^%s–]-[^%.,]$") then -- doi must begin with '10.', must contain a fwd slash, must not contain spaces or endashes, and must not end with period or comma
cat = ' ' ..
end
return text .. inactive .. cat
Llinell 716 ⟶ 1,087:
-- Formats an OpenLibrary link, and checks for associated errors.
local function openlibrary(id)
local code = id:match("^%d+([AMW])$"); -- only digits followed by 'A', 'M', or 'W'
local handler = cfg.id_handlers['OL'];
if ( code == "A" ) then
return
prefix="http://openlibrary.org/authors/OL",id=id, separator=handler.separator,
encode = handler.encode})
elseif ( code == "M" ) then
return
prefix="http://openlibrary.org/books/OL",id=id, separator=handler.separator,
encode = handler.encode})
elseif ( code == "W" ) then
return
prefix= "http://openlibrary.org/works/OL",id=id, separator=handler.separator,
encode = handler.encode})
else
return
prefix= "http://openlibrary.org/OL",id=id, separator=handler.separator,
encode = handler.encode}) ..
' ' ..
end
end
--[[--------------------------< M E S S A G E _ I D >----------------------------------------------------------
Llinell 787 ⟶ 1,119:
]]
local function message_id (id)
local handler = cfg.id_handlers['USENETID'];
text =
prefix=handler.prefix,id=id,separator=handler.separator, encode=handler.encode})
if not id:match('^.+@.+$') or not id:match('^[^<].*[^>]$')then -- doesn't have '@' or has one or first or last character is '< or '>'
text = text .. ' ' ..
end
return text
end
--[[--------------------------< S E T _ T I T L E T Y P E >----------------------------------------------------
This function sets default title types (equivalent to the citation including |type=<default value>) for those
Also handles the special case where it is desirable to omit the title type from the rendered citation (|type=none).
]]
local function set_titletype (cite_class, title_type)
if is_set(title_type) then
if "none" == title_type then
title_type = ""; -- if |type=none then type parameter not displayed
end
return title_type; -- if |type= has been set to any other value use that value
end
return cfg.title_types [cite_class] or ''; -- set template's default title type; else empty string for concatenation
end
--[[--------------------------< C L E A N _ I S B N >----------------------------------------------------------
Removes irrelevant text and dashes from ISBN number
Similar to that used for Special:BookSources
]]
local function clean_isbn( isbn_str )
return isbn_str:gsub( "[^-0-9X]", "" );
end
Llinell 863 ⟶ 1,166:
string.gsub() treat their pattern and replace strings as patterns, not literal strings.
]]
local function escape_lua_magic_chars (argument)
argument = argument:gsub("%%", "%%%%"); -- replace % with %%
argument = argument:gsub("([%^%$%(%)%.%[%]%*%+%-%?])", "%%%1"); -- replace all other lua magic pattern characters
Llinell 876 ⟶ 1,179:
]]
local function strip_apostrophe_markup (argument)
if not is_set (argument) then return argument; end
Llinell 903 ⟶ 1,207:
]]
local function make_coins_title (title, script)
if is_set (title) then
title = strip_apostrophe_markup (title); -- strip any apostrophe markup
Llinell 926 ⟶ 1,230:
]]
local function get_coins_pages (pages)
local pattern;
if not is_set (pages) then return pages; end -- if no page numbers then we're done
Llinell 940 ⟶ 1,245:
pages = pages:gsub("&%w+;", "-" ); -- and replace html entities (– etc.) with hyphens; do we need to replace numerical entities like   and the like?
return pages;
end
-- Gets the display text for a wikilink like [[A|B]] or [[B]] gives B
local function
return (str:gsub( "%[%[([^%[%]]*)%]%]", function(l)
return l:gsub( "^[^|]*|(.*)$", "%1" ):gsub("^%s*(.-)%s*$", "%1");
end));
end
-- Converts a hyphen to a dash
local function
if not is_set(str) or str:match( "[%[%]{}<>]" ) ~= nil then
return str;
Llinell 1,012 ⟶ 1,262:
end
--[[--------------------------< S A F E _ J O I N >------------------------------------------------------------
Joins a sequence of strings together while checking for duplicate separation characters.
]]
local function safe_join( tbl, duplicate_char )
--[[
Note: we use string functions here, rather than ustring functions.
Llinell 1,107 ⟶ 1,340:
end
--[[--------------------------< I S _ G O O D _ V A N C _ N A M E >--------------------------------------------
For Vancouver Style, author/editor names are supposed to be rendered in Latin (read ASCII) characters. When a name
uses characters that contain diacritical marks, those characters are to converted to the corresponding Latin character.
When a name is written using a non-Latin alphabet or logogram, that name is to be transliterated into Latin characters.
These things are not currently possible in this module so are left to the editor to do.
This test allows |first= and |last= names to contain any of the letters defined in the four Unicode Latin character sets
[http://www.unicode.org/charts/PDF/U0000.pdf C0 Controls and Basic Latin] 0041–005A, 0061–007A
[http://www.unicode.org/charts/PDF/U0080.pdf C1 Controls and Latin-1 Supplement] 00C0–00D6, 00D8–00F6, 00F8–00FF
[http://www.unicode.org/charts/PDF/U0100.pdf Latin Extended-A] 0100–017F
[http://www.unicode.org/charts/PDF/U0180.pdf Latin Extended-B] 0180–01BF, 01C4–024F
|lastn= also allowed to contain hyphens, spaces, and apostrophes. (http://www.ncbi.nlm.nih.gov/books/NBK7271/box/A35029/)
|firstn= also allowed to contain hyphens, spaces, apostrophes, and periods
At the time of this writing, I had to write the 'if nil == mw.ustring.find ...' test ouside of the code editor and paste it here
because the code editor gets confused between character insertion point and cursor position.
]]
local function is_good_vanc_name (last, first)
if nil == mw.ustring.find (last, "^[A-Za-zÀ-ÖØ-öø-ƿDŽ-ɏ%-%s%']*$") or nil == mw.ustring.find (first, "^[A-Za-zÀ-ÖØ-öø-ƿDŽ-ɏ%-%s%'%.]*$") then
add_vanc_error ();
return false; -- not a string of latin characters; Vancouver required Romanization
end;
return true;
end
--[[--------------------------< R E D U C E _ T O _ I N I T I A L S >------------------------------------------
Attempts to convert names to initials in support of |name-list-format=vanc.
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/.
Vancouver style requires family rank designations (Jr, II, III, etc) to be rendered as Jr, 2nd, 3rd, etc. This form is not
currently supported by this code so correctly formed names like Smith JL 2nd are converted to Smith J2. See http://www.ncbi.nlm.nih.gov/books/NBK7271/box/A35085/.
This function uses ustring functions because firstname initials may be any of the unicode Latin characters accepted by is_good_vanc_name ().
]]
local function reduce_to_initials(first)
if mw.ustring.match(first, "^%u%u$") then return first end; -- when first contains just two upper-case letters, nothing to do
local initials = {}
local i = 0; -- counter for number of initials
for word in
table.insert(initials,
i = i + 1; -- bump the counter
if 2 <= i then break; end -- only two initials allowed in Vancouver system; if 2, quit
end
return table.concat(initials) -- Vancouver format does not include spaces.
end
--[[--------------------------< L I S T _ P E O P L E >-------------------------------------------------------
Formats a list of people (e.g. authors / editors)
]]
local function list_people(control, people, etal)
local sep;
local namesep;
Llinell 1,127 ⟶ 1,407:
local lastauthoramp = control.lastauthoramp;
local text = {}
if 'vanc' == format then -- Vancouver-like author/editor name styling?
sep = ','; -- name-list separator between authors is a comma
Llinell 1,138 ⟶ 1,417:
if sep:sub(-1,-1) ~= " " then sep = sep .. " " end
if
for i,person in ipairs(people) do
Llinell 1,145 ⟶ 1,424:
local one
local sep_one = sep;
if is_set (maximum
etal = true;
break;
Llinell 1,160 ⟶ 1,439:
local first = person.first
if is_set(first) then
if ( "vanc" == format ) then --
one = one:gsub ('%.', ''); -- remove periods from surnames (http://www.ncbi.nlm.nih.gov/books/NBK7271/box/A35029/)
if not person.corporate and is_good_vanc_name (one, first) then -- and name is all Latin characters; corporate authors not tested
first = reduce_to_initials(first) -- attempt to convert first name(s) to initials
end
end
one = one .. namesep .. first
end
if is_set(person.link) and person.link ~= control.page_name then
one = "[[" .. person.link .. "|" .. one .. "]]" -- link author/editor if this page is not the author's/editor's page
end
if is_set(person.link) and ((nil ~= person.link:find("//")) or (nil ~= person.link:find("[%[%]]"))) then
one = one .. " " ..
end
table.insert( text, one )
Llinell 1,175 ⟶ 1,459:
end
local count = #text / 2; -- (number of names + number of separators) divided by 2
if count > 0 then
if count > 1 and is_set(lastauthoramp) and not etal then
text[#text-2] = " & "; -- replace last separator with ampersand text
end
text[#text] = nil; -- erase the last separator
end
local result = table.concat(text)
if etal and is_set (result) then -- etal may be set by |display-authors=etal but we might not have a last-first list
end
Llinell 1,192 ⟶ 1,475:
end
--[[--------------------------< A N C H O R _ I D >
Generates a CITEREF anchor ID if we have at least one name or a date. Otherwise returns an empty string.
]]
local function
local id = table.concat( options ); -- concatenate names and year for CITEREF id
if is_set (id) then -- if concatenation is not an empty string
Llinell 1,206 ⟶ 1,490:
end
--[[--------------------------< N A M E _ H A S _ E T A L >----------------------------------------------------
Evaluates the content of author and editor name parameters for variations on the theme eof et al. If found,
the et al. is removed, a flag is set to true and the function returns the modified name and the flag.
This function never sets the flag to false but returns it's previous state because it may have been set by
previous passes through this function or by the parameters |display-authors=etal or |displayeditors=etal
]]
local function name_has_etal (name, etal, nocat)
if is_set (name) then -- name can be nil in which case just return
local pattern = "[;,]? *[\"']*%f[Ee][Ee][Tt] *[Aa][Ll][%.\"']*$" -- variations on the 'et al' theme
if name:match (pattern) then -- variants on et al.
name = name:gsub (pattern, ''); -- if found, remove
etal = true; -- set flag (may have been set previously here or by |display-authors=etal)
if not nocat then -- no categorization for |vauthors=
add_maint_cat ('etal'); -- and add a category if not already added
end
end
end
return name, etal; --
end
--[[--------------------------< E X T R A C T _ N A M E S >----------------------------------------------------
Gets name list from the input arguments
Llinell 1,215 ⟶ 1,525:
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=
are present but |last2= is missing, an error message is emitted. |lastn= is not required to have a matching |firstn=.
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
that will cause list_people() to add the static 'et al.' text from Module:Citation/CS1/Configuration. This keeps 'et al.' out of the
template's metadata. When this occurs, the page is added to a maintenance category.
]]
local function extract_names(args, list_name)
local names = {}; -- table of names
local last; -- individual name components
Llinell 1,225 ⟶ 1,541:
local n = 1; -- output table indexer
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)
local etal=false; -- return value set to true when we find some form of et al. in an author parameter
local err_msg_list_name = list_name:match ("(%w+)List") .. 's list'; -- modify AuthorList or EditorList for use in error messages if necessary
while true do
last =
first =
link =
mask =
last, etal = name_has_etal (last, etal, false); -- find and remove variations on et al.
first, etal = name_has_etal (first, etal, false); -- find and remove variations on et al.
if first and not last then -- if there is a firstn without a matching lastn
table.insert( z.message_tail, {
elseif not first and not last then -- if both firstn and lastn aren't found, are we done?
count = count + 1; -- number of times we haven't found last and first
if 2
break; -- normal exit or there is a two-name hole in the list; can't tell which
end
else -- we have last with or without a first
names[n] = {last = last, first = first, link = link, mask = mask, corporate=false}; -- add this name to our names list (corporate for |vauthors= only)
n = n + 1; -- point to next location in the names table
if 1 == count then -- if the previous name was missing
table.insert( z.message_tail, {
end
count = 0; -- reset the counter, we're looking for two consecutive missing names
Llinell 1,251 ⟶ 1,571:
i = i + 1; -- point to next args location
end
return names, etal; -- all done, return our list of names
end
-- Populates ID table from arguments using configuration settings
local function
local id_list = {};
for k, v in pairs( cfg.id_handlers ) do
v =
if is_set(v) then id_list[k] = v; end
end
Llinell 1,264 ⟶ 1,585:
end
--[[--------------------------< B U I L D _ I D _ L I S T >--------------------------------------------------------
Takes a table of IDs and turns it into a table of formatted ID outputs.
]]
local function build_id_list( id_list, options )
local new_list, handler = {};
Llinell 1,278 ⟶ 1,601:
if handler.mode == 'external' then
table.insert( new_list, {handler.label,
elseif handler.mode == 'internal' then
table.insert( new_list, {handler.label,
elseif handler.mode ~= 'manual' then
error( cfg.messages['unknown_ID_mode'] );
Llinell 1,286 ⟶ 1,609:
table.insert( new_list, {handler.label, doi( v, options.DoiBroken ) } );
elseif k == 'ARXIV' then
table.insert( new_list, {handler.label, arxiv( v, options.Class ) } );
elseif k == 'ASIN' then
table.insert( new_list, {handler.label, amazon( v, options.ASINTLD ) } );
Llinell 1,297 ⟶ 1,620:
elseif k == 'PMID' then
table.insert( new_list, {handler.label, pmid( v ) } );
elseif k == 'ISMN' then
table.insert( new_list, {handler.label, ismn( v ) } );
elseif k == 'ISSN' then
table.insert( new_list, {handler.label, issn( v ) } );
elseif k == 'ISBN' then
local ISBN =
if not
ISBN = ISBN ..
end
table.insert( new_list, {handler.label, ISBN } );
Llinell 1,324 ⟶ 1,649:
end
-- COinS metadata (see <http://ocoins.info/>) allows automated tools to parse
-- the citation information.
local function COinS(data, class)
if 'table' ~= type(data) or nil == next(data) then
return '';
Llinell 1,393 ⟶ 1,663:
__newindex = function(self, key, value)
if is_set(value) then
rawset( self, #self+1, table.concat{ key, '=', mw.uri.encode(
end
end
Llinell 1,405 ⟶ 1,675:
elseif is_set(data.Periodical) then
OCinSoutput.rft_val_fmt = "info:ofi/fmt:kev:mtx:journal";
if 'arxiv' == class then
OCinSoutput["rft.genre"] = "preprint"; -- cite arxiv
else
OCinSoutput["rft.genre"] = "article";
end
OCinSoutput["rft.jtitle"] = data.Periodical;
OCinSoutput["rft.atitle"] = data.Title;
Llinell 1,425 ⟶ 1,699:
for k, v in pairs( data.ID_list ) do
local id, value = cfg.id_handlers[k].COinS;
if k == 'ISBN' then value =
if string.sub( id or "", 1, 4 ) == 'info' then
OCinSoutput["rft_id"] = table.concat{ id, "/", v };
Llinell 1,477 ⟶ 1,751:
Adapted from code taken from Module:Check ISO 639-1.
]]
local function get_iso639_code (lang)
if 'norwegian' == lang:lower() then -- special case related to Wikimedia remap of code 'no' at Extension:CLDR
return 'Norwegian', 'no'; -- Make sure rendered version is properly capitalized
Llinell 1,514 ⟶ 1,789:
When |language= contains a valid ISO639-1 code, the page is assigned to the category for that code: Category:Norwegian-language sources (no) if
the page is a mainspace page and the ISO639-1 code is not 'en'. Similarly, if the parameter is |language=Norwegian, it will be categorized in the same way.
This function supports multiple languages in the form |language=nb, French, th where the language names or codes are separated from each other by commas.
]]
local function language_parameter (lang
local code; -- the ISO639-1 two character code
local name; -- the language name
local language_list = {}; -- table of language names to be rendered
local names_table = {}; -- table made from the value assigned to |language=
names_table = mw.text.split (lang, '%s*,%s*'); -- names should be a comma separated list
for _, lang in ipairs (names_table) do -- reuse lang
if 2 == lang:len() then -- ISO639-1 language code are 2 characters (fetchLanguageName also supports 3 character codes)
name = mw.language.fetchLanguageName( lang:lower(), "en" ); -- get ISO 639-1 language name if Language is a proper code
end
if is_set (name) then -- if Language specified a valid ISO639-1 code
code = lang:lower(); -- save it
else
name, code = get_iso639_code (lang); -- attempt to get code from name (assign name here so that we are sure of proper capitalization)
end
if is_set (code) then
if 'no' == code then name = 'Norwegian' end; -- override wikimedia when code is 'no'
if 'en' ~= code then -- English not the language
add_prop_cat ('foreign_lang_source', {name, code})
end
else
add_maint_cat ('unknown_lang'); -- add maint category if not already added
end
table.insert (language_list, name);
name = ''; -- so we can reuse it
end
if 2 >= code then
name = table.concat (language_list, ' and ') -- insert '<space>and<space>' between two language names
elseif 2 < code then
language_list[code] = 'and ' .. language_list[code]; -- prepend last name with 'and<space>'
name = table.concat (language_list, ', ') -- and concatenate with '<comma><space>' separators
end
if 'English' == name then
return ''; -- if one language and that language is English return an enpty string (no annotation)
end
return (" " .. wrap_msg ('language', name)); -- otherwise wrap with '(in ...)'
end
--[[--------------------------< S E T _ C S 1 _ S T Y L E >----------------------------------------------------
Set style settings for CS1 citation templates. Returns separator and postscript settings
]]
local function set_cs1_style (ps)
if not is_set (ps) then -- unless explicitely set to something
ps = '.'; -- terminate the rendered citation with a period
end
return '.', ps; -- separator is a full stop
end
--[[--------------------------< S E T _ C S 2 _ S T Y L E >----------------------------------------------------
Set style settings for CS2 citation templates. Returns separator, postscript, ref settings
]]
local function set_cs2_style (ps, ref)
if not is_set (ps) then -- if |postscript= has not been set, set cs2 default
ps = ''; -- make sure it isn't nil
end
if not is_set (ref) then -- if |ref= is not set
ref = "harv"; -- set default |ref=harv
end
return
end
--[[--------------------------< G E T _ S E T T I N G S _ F R O M _ C I T E _ C L A S S >----------------------
When |mode= is not set or when its value is invalid, use config.CitationClass and parameter values to establish
rendered style.
Llinell 1,553 ⟶ 1,876:
]]
local function get_settings_from_cite_class (ps, ref, cite_class)
local sep;
if (cite_class == "citation") then -- for citation templates (CS2)
sep, ps, ref = set_cs2_style (ps, ref);
else -- not a citation template so CS1
sep, ps = set_cs1_style (ps);
end
Llinell 1,580 ⟶ 1,894:
]]
local function set_style (mode, ps, ref, cite_class)
local sep;
if 'cs2' == mode then -- if this template is to be rendered in CS2 (citation) style
sep, ps, ref = set_cs2_style (ps, ref);
sep, ps = set_cs1_style (ps);
else
if is_set (mode) then
table.insert( z.message_tail, { set_error( 'invalid_param_val', {'mode', mode}, true ) } ); -- add error message
end
sep, ps, ref = get_settings_from_cite_class (ps, ref, cite_class); -- get settings based on the template's CitationClass
end
Llinell 1,610 ⟶ 1,913:
end
--[=[-------------------------< I S _ P D F >------------------------------------------------------------------
Determines if a url has the file extension is one of the pdf file extensions used by [[MediaWiki:Common.css]] when
applying the pdf icon to external links.
returns true if file extension is one of the recognized extension, else false
]=]
local function is_pdf (url)
return url:match ('%.pdf[%?#]?') or url:match ('%.PDF[%?#]?');
end
--[[--------------------------< S T Y L E _ F O R M A T >------------------------------------------------------
Applies css style to |format=, |chapter-format=, etc. Also emits an error message if the format parameter does
not have a matching url parameter. If the format parameter is not set and the url contains a file extension that
is recognized as a pdf document by MediaWiki's commons.css, this code will set the format parameter to (PDF) with
the appropriate styling.
]]
local function style_format (format, url, fmt_param, url_param)
if is_set (format) then
format = wrap_style ('format', format); -- add leading space, parenthases, resize
if not is_set (url) then
format = format .. set_error( 'format_missing_url', {fmt_param, url_param} ); -- add an error message
end
elseif is_pdf (url) then -- format is not set so if url is a pdf file then
format = wrap_style ('format', 'PDF'); -- set format to pdf
else
format = ''; -- empty string for concatenation
end
return format;
end
--[[--------------------------< G E T _ D I S P L A Y _ A U T H O R S _ E D I T O R S >------------------------
Returns a number that may or may not limit the length of the author or editor name lists.
When the value assigned to |display-authors= is a number greater than or equal to zero, return the number and
the previous state of the 'etal' flag (false by default but may have been set to true if the name list contains
some variant of the text 'et al.').
When the value assigned to |display-authors= is the keyword 'etal', return a number that is one greater than the
number of authors in the list and set the 'etal' flag true. This will cause the list_people() to display all of
the names in the name list followed by 'et al.'
In all other cases, returns nil and the previous state of the 'etal' flag.
]]
local function get_display_authors_editors (max, count, list_name, etal)
if is_set (max) then
if 'etal' == max:lower():gsub("[ '%.]", '') then -- the :gsub() portion makes 'etal' from a variety of 'et al.' spellings and stylings
max = count + 1; -- number of authors + 1 so display all author name plus et al.
etal = true; -- overrides value set by extract_names()
elseif max:match ('^%d+$') then -- if is a string of numbers
max = tonumber (max); -- make it a number
if max >= count and 'authors' == list_name then -- AUTHORS ONLY -- if |display-xxxxors= value greater than or equal to number of authors/editors
add_maint_cat ('disp_auth_ed', list_name);
end
else -- not a valid keyword or number
table.insert( z.message_tail, { set_error( 'invalid_param_val', {'display-' .. list_name, max}, true ) } ); -- add error message
max = nil; -- unset
end
elseif 'authors' == list_name then -- AUTHORS ONLY need to clear implicit et al category
max = count + 1; -- number of authors + 1
end
return max, etal;
end
--[[--------------------------< E X T R A _ T E X T _ I N _ P A G E _ C H E C K >------------------------------
Adds page to Category:CS1 maint: extra text if |page= or |pages= has what appears to be some form of p. or pp.
abbreviation in the first characters of the parameter content.
check Page and Pages for extraneous p, p., pp, and pp. at start of parameter value:
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
bad pattern: '^[Pp][Pp]' matches matches when |page(s)= begins pp or pP or Pp or PP
]]
local function extra_text_in_page_check (page, nopp)
-- local good_pattern = '^P[^%.P%l]';
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?
-- local bad_pattern = '^[Pp][Pp]';
local bad_pattern = '^[Pp]?[Pp]%.?[ %d]';
if is_set (nopp) then -- don't bother checking if |nopp= is set
return;
end
if not page:match (good_pattern) and (page:match (bad_pattern) or page:match ('^[Pp]ages?')) then
add_maint_cat ('extra_text');
end
-- if Page:match ('^[Pp]?[Pp]%.?[ %d]') or Page:match ('^[Pp]ages?[ %d]') or
-- Pages:match ('^[Pp]?[Pp]%.?[ %d]') or Pages:match ('^[Pp]ages?[ %d]') then
-- add_maint_cat ('extra_text');
-- end
end
--[[--------------------------< P A R S E _ V A U T H O R S _ V E D I T O R S >--------------------------------
This function extracts author / editor names from |vauthors= or |veditors= and finds matching |xxxxor-maskn= and
|xxxxor-linkn= in args. It then returns a table of assembled names just as extract_names() does.
Author / editor names in |vauthors= or |veditors= must be in Vancouver system style. Corporate or institutional names
may sometimes be required and because such names will often fail the is_good_vanc_name() and other format compliance
tests, are wrapped in doubled paranethese ((corporate name)) to suppress the format tests.
]]
local function parse_vauthors_veditors (args, vparam, list_name)
local names = {}; -- table of names assembled from |vauthors=, |author-maskn=, |author-linkn=
local v_name_table = {};
local etal = false; -- return value set to true when we find some form of et al. vauthors parameter
local last, first, link, mask;
local corporate = false;
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)
if vparam:find ('%[%[') or vparam:find ('%]%]') then -- no wikilinking vauthors names
add_vanc_error ();
end
v_name_table = mw.text.split(vparam, "%s*,%s*") -- names are separated by commas
for i, v_name in ipairs(v_name_table) do
if v_name:match ('^%(%(.+%)%)$') then -- corporate authors are wrapped in doubled parenthese to supress vanc formatting and error detection
first = ''; -- set to empty string for concatenation and because it may have been set for previous author/editor
last = v_name:match ('^%(%((.+)%)%)$')
corporate = true;
elseif string.find(v_name, "%s") then
lastfirstTable = {}
lastfirstTable = mw.text.split(v_name, "%s")
first = table.remove(lastfirstTable); -- removes and returns value of last element in table which should be author intials
last = table.concat(lastfirstTable, " ") -- returns a string that is the concatenation of all other names that are not initials
else
first = ''; -- set to empty string for concatenation and because it may have been set for previous author/editor
last = v_name; -- last name or single corporate name? Doesn't support multiword corporate names? do we need this?
end
if is_set (first) and not mw.ustring.match (first, "^%u?%u$") then -- first shall contain one or two upper-case letters, nothing else
add_vanc_error ();
end
-- this from extract_names ()
link = select_one( args, cfg.aliases[list_name .. '-Link'], 'redundant_parameters', i );
mask = select_one( args, cfg.aliases[list_name .. '-Mask'], 'redundant_parameters', i );
names[i] = {last = last, first = first, link = link, mask = mask, corporate=corporate}; -- add this assembled name to our names list
end
return names, etal; -- all done, return our list of names
end
--[[--------------------------< S E L E C T _ A U T H O R _ E D I T O R _ S O U R C E >------------------------
Select one of |authors=, |authorn= / |lastn / firstn=, or |vauthors= as the source of the author name list or
select one of |editors=, |editorn= / editor-lastn= / |editor-firstn= or |veditors= as the source of the editor name list.
Only one of these appropriate three will be used. The hierarchy is: |authorn= (and aliases) highest and |authors= lowest and
similarly, |editorn= (and aliases) highest and |editors= lowest
When looking for |authorn= / |editorn= parameters, test |xxxxor1= and |xxxxor2= (and all of their aliases); stops after the second
test which mimicks the test used in extract_names() when looking for a hole in the author name list. There may be a better
way to do this, I just haven't discovered what that way is.
Emits an error message when more than one xxxxor name source is provided.
In this function, vxxxxors = vauthors or veditors; xxxxors = authors or editors as appropriate.
]]
local function select_author_editor_source (vxxxxors, xxxxors, args, list_name)
local lastfirst = false;
if select_one( args, cfg.aliases[list_name .. '-Last'], 'redundant_parameters', 1 ) or -- do this twice incase we have a first 1 without a last1
select_one( args, cfg.aliases[list_name .. '-Last'], 'redundant_parameters', 2 ) then
lastfirst=true;
end
if (is_set (vxxxxors) and true == lastfirst) or -- these are the three error conditions
(is_set (vxxxxors) and is_set (xxxxors)) or
(true == lastfirst and is_set (xxxxors)) then
local err_name;
if 'AuthorList' == list_name then -- figure out which name should be used in error message
err_name = 'author';
else
err_name = 'editor';
end
table.insert( z.message_tail, { set_error( 'redundant_parameters',
{err_name .. '-name-list parameters'}, true ) } ); -- add error message
end
if true == lastfirst then return 1 end; -- return a number indicating which author name source to use
if is_set (vxxxxors) then return 2 end;
if is_set (xxxxors) then return 3 end;
return 0; -- no authors so return 0
end
--[[--------------------------< C I T A T I O N 0 >------------------------------------------------------------
This is the main function doing the majority of the citation formatting.
]]
local function citation0( config, args)
--[[
Load Input Parameters
The argument_wrapper facilitates the mapping of multiple aliases to single internal variable.
]]
local A = argument_wrapper( args );
Llinell 1,626 ⟶ 2,127:
local PPrefix = A['PPrefix']
local PPPrefix = A['PPPrefix']
if in_array(NoPP:lower(), {'yes', 'true', 'y'}) then
PPPrefix = ''; -- unset these, prefix if used is in |page= or |pages=
PPrefix = '';
else
NoPP = nil; -- unset, used as a flag later
end
-- Pick out the relevant fields from the arguments. Different citation templates
-- define different field names for the same underlying things.
local
local a = {}; -- authors list from |lastn= / |firstn= pairs or |vauthors=
local Authors;
local NameListFormat = A['NameListFormat']; -- replaces |author-format= and |editor-format=
do -- to limit scope of selected
local selected = select_author_editor_source (A['Vauthors'], A['Authors'], args, 'AuthorList');
if 1 == selected then
a, author_etal = extract_names (args, 'AuthorList'); -- fetch author list from |authorn= / |lastn= / |firstn=, |author-linkn=, and |author-maskn=
elseif 2 == selected then
NameListFormat = 'vanc'; -- override whatever |name-list-format= might be
a, author_etal = parse_vauthors_veditors (args, args.vauthors, 'AuthorList'); -- fetch author list from |vauthors=, |author-linkn=, and |author-maskn=
elseif 3 == selected then
Authors = A['Authors']; -- use content of |authors=
end
end
local Coauthors = A['Coauthors'];
local Others = A['Others'];
local editor_etal;
local e = {}; -- editors list from |editor-lastn= / |editor-firstn= pairs or |veditors=
local Editors;
do -- to limit scope of selected
local selected = select_author_editor_source (A['Veditors'], A['Editors'], args, 'EditorList');
if 1 == selected then
e, editor_etal = extract_names (args, 'EditorList'); -- fetch editor list from |editorn= / |editor-lastn= / |editor-firstn=, |editor-linkn=, and |editor-maskn=
elseif 2 == selected then
NameListFormat = 'vanc'; -- override whatever |name-list-format= might be
e, editor_etal = parse_vauthors_veditors (args, args.veditors, 'EditorList'); -- fetch editor list from |veditors=, |editor-linkn=, and |editor-maskn=
elseif 3 == selected then
Editors = A['Editors']; -- use content of |editors=
end
end
if is_set (NameListFormat) and ('vanc' ~= NameListFormat) then -- only accepted value for this parameter is 'vanc'
table.insert( z.message_tail, {
NameListFormat = ''; -- set to empty string
end
Llinell 1,658 ⟶ 2,192:
local TitleLink = A['TitleLink'];
local Chapter = A['Chapter'];
local ChapterLink = A['ChapterLink']; -- deprecated but used internally by cite episode
local TransChapter = A['TransChapter'];
local TitleType = A['TitleType'];
local Degree = A['Degree'];
local Docket = A['Docket'];
local ArchiveFormat = A['ArchiveFormat'];
local ArchiveURL = A['ArchiveURL'];
local URL = A['URL']
Llinell 1,668 ⟶ 2,203:
local ChapterURL = A['ChapterURL'];
local ChapterURLorigin = A:ORIGIN('ChapterURL'); -- get name of parameter that holds ChapterURL
local ConferenceFormat = A['ConferenceFormat'];
local ConferenceURL = A['ConferenceURL'];
local ConferenceURLorigin = A:ORIGIN('ConferenceURL'); -- get name of parameter that holds ConferenceURL
Llinell 1,677 ⟶ 2,213:
local Position = '';
local Page = A['Page'];
local Pages =
local At = A['At'];
Llinell 1,700 ⟶ 2,236:
local IgnoreISBN = A['IgnoreISBN'];
local Embargo = A['Embargo'];
local Class = A['Class']; -- arxiv class identifier
local ID_list =
local Quote = A['Quote'];
local LayFormat = A['LayFormat'];
local LayURL = A['LayURL'];
local LaySource = A['LaySource'];
local Transcript = A['Transcript'];
local TranscriptFormat = A['TranscriptFormat'];
local TranscriptURL = A['TranscriptURL']
local TranscriptURLorigin = A:ORIGIN('TranscriptURL'); -- get name of parameter that holds TranscriptURL
Llinell 1,732 ⟶ 2,271:
use_lowercase = ( sepc == ',' ); -- used to control capitalization for certain static text
--check this page to see if it is in one of the namespaces that cs1 is not supposed to add to the error categories
if not is_set (no_tracking_cats) then -- ignore if we are already not going to categorize this page
if
no_tracking_cats = "true"; -- set no_tracking_cats
end
for _,v in ipairs (cfg.uncategorized_subpages) do -- cycle through page name patterns
if this_page.text:match (v) then -- test page name against each pattern
no_tracking_cats = "true"; -- set no_tracking_cats
break; -- bail out if one is found
end
end
end
Llinell 1,742 ⟶ 2,287:
if is_set(Page) then
if is_set(Pages) or is_set(At) then
Page = Page .. " " ..
Pages = ''; -- unset the others
At = '';
end
extra_text_in_page_check (Page, NoPP); -- add this page to maint cat if |page= value begins with what looks like p. or pp.
elseif is_set(Pages) then
if is_set(At) then
Pages = Pages .. " " ..
At = ''; -- unset
end
extra_text_in_page_check (Pages, NoPP); -- add this page to maint cat if |page= value begins with what looks like p. or pp.
end
Llinell 1,783 ⟶ 2,330:
TransChapter = TransTitle;
ChapterURL = URL;
if not is_set (ChapterURL) and is_set (TitleLink) then
Chapter= '[[' .. TitleLink .. '|' .. Chapter .. ']]';
end
Title = Periodical;
ChapterFormat = Format;
Llinell 1,789 ⟶ 2,339:
URL = ''; -- redundant so unset
Format = ''; -- redundant so unset
TitleLink = ''; -- redundant so unset
end
else -- |title not set
Llinell 1,804 ⟶ 2,355:
Issue = ""; -- unset Issue so that "number" isn't duplicated in the rendered citation or COinS metadata
else -- can't use ID so emit error message
ID = ID .. " " ..
end
end
Llinell 1,844 ⟶ 2,395:
if (config.CitationClass == "mailinglist") then
Periodical = A ['MailingList'];
end
Llinell 1,870 ⟶ 2,413:
URL = '';
end
elseif 'speech' ~= config.CitationClass then
Conference = ''; -- not cite conference or cite speech so make sure this is empty string
end
-- cite map oddities
local Cartography = "";
local Scale = "";
local Sheet = A['Sheet'] or '';
local Sheets = A['Sheets'] or '';
if config.CitationClass == "map" then
Chapter = A['Map'];
ChapterURL = A['MapURL'];
TransChapter = A['TransMap'];
ChapterURLorigin = A:ORIGIN('MapURL');
ChapterFormat = A['MapFormat'];
Cartography = A['Cartography'];
if is_set( Cartography ) then
Cartography = sepc .. " " .. wrap_msg ('cartography', Cartography, use_lowercase);
end
Scale = A['Scale'];
if is_set( Scale ) then
Scale = sepc .. " " .. Scale;
end
end
-- Account for the oddities that are {{cite episode}} and {{cite serial}}, before generation of COinS data.
if 'episode' == config.CitationClass or 'serial' == config.CitationClass then
local AirDate = A['AirDate'];
local Began = A['Began']; -- these two are deprecated because the module understands date ranges
local Ended = A['Ended'];
local SeriesLink = A['SeriesLink'];
local Network = A['Network'];
local Station = A['Station'];
local s, n = {}, {};
-- do common parameters first
if is_set(Network) then table.insert(n, Network); end
if is_set(Station) then table.insert(n, Station); end
ID = table.concat(n, sepc .. ' ');
if not is_set (Date) then -- promote airdate or Began/Ended to date
if is_set (AirDate) then
elseif is_set (Began) then -- deprecated
if Began:match('%s') or Ended:match('%s') then -- so we don't create errors: if either has spaces then
Date = Began .. ' – ' .. Ended; -- use spaced ndash as separator
else
Date = Began .. '–' .. Ended; -- elsewise no spaces
end
end
end
if 'episode' == config.CitationClass then -- handle the oddities that are strictly {{cite episode}}
local Season = A['Season'];
local SeriesNumber = A['SeriesNumber'];
if is_set (Season) and is_set (SeriesNumber) then -- these are mutually exclusive so if both are set
table.insert( z.message_tail, { set_error( 'redundant_parameters', {wrap_style ('parameter', 'season') .. ' and ' .. wrap_style ('parameter', 'seriesno')}, true ) } ); -- add error message
SeriesNumber = ''; -- unset; prefer |season= over |seriesno=
end
-- assemble a table of parts concatenated later into Series
if is_set(Season) then table.insert(s, wrap_msg ('season', Season, use_lowercase)); end
if is_set(SeriesNumber) then table.insert(s, wrap_msg ('series', SeriesNumber, use_lowercase)); end
if is_set(Issue) then table.insert(s, wrap_msg ('episode', Issue, use_lowercase)); end
Issue = ''; -- unset because this is not a unique parameter
Chapter = Title; -- promote title parameters to chapter
ChapterLink = TitleLink; -- alias episodelink
TransChapter = TransTitle;
ChapterURL = URL;
ChapterURLorigin = A:ORIGIN('URL');
Title = Series; -- promote series to title
TitleLink = SeriesLink;
Series = table.concat(s, sepc .. ' '); -- this is concatenation of season, seriesno, episode number
if is_set (ChapterLink) and not is_set (ChapterURL) then -- link but not URL
Chapter = '[[' .. ChapterLink .. '|' .. Chapter .. ']]'; -- ok to wikilink
elseif is_set (ChapterLink) and is_set (ChapterURL) then -- if both are set, URL links episode;
Series = '[[' .. ChapterLink .. '|' .. Series .. ']]'; -- series links with ChapterLink (episodelink -> TitleLink -> ChapterLink) ugly
end
URL = ''; -- unset
TransTitle = ''; -- unset
else -- now oddities that are cite serial
Issue = ''; -- unset because this parameter no longer supported by the citation/core version of cite serial
Chapter = A['Episode']; -- TODO: make |episode= available to cite episode someday?
if is_set (Series) and is_set (SeriesLink) then
Series = '[[' .. SeriesLink .. '|' .. Series .. ']]';
end
Series = wrap_style ('italic-title', Series); -- series is italicized
end
end
-- end of {{cite episode}} stuff
-- Account for the oddities that are {{cite arxiv}}, before generation of COinS data.
if 'arxiv' == config.CitationClass then
if not is_set (ID_list['ARXIV']) then -- |arxiv= or |eprint= required for cite arxiv
table.insert( z.message_tail, { set_error( 'arxiv_missing', {}, true ) } ); -- add error message
elseif is_set (Series) then -- series is an alias of version
ID_list['ARXIV'] = ID_list['ARXIV'] .. Series; -- concatenate version onto the end of the arxiv identifier
Series = ''; -- unset
deprecated_parameter ('version'); -- deprecated parameter but only for cite arxiv
end
if first_set (AccessDate, At, Chapter, Format, Page, Pages, Periodical, PublisherName, URL, -- a crude list of parameters that are not supported by cite arxiv
ID_list['ASIN'], ID_list['BIBCODE'], ID_list['DOI'], ID_list['ISBN'], ID_list['ISSN'],
ID_list['JFM'], ID_list['JSTOR'], ID_list['LCCN'], ID_list['MR'], ID_list['OCLC'], ID_list['OL'],
ID_list['OSTI'], ID_list['PMC'], ID_list['PMID'], ID_list['RFC'], ID_list['SSRN'], ID_list['USENETID'], ID_list['ZBL']) then
table.insert( z.message_tail, { set_error( 'arxiv_params_not_supported', {}, true ) } ); -- add error message
AccessDate= ''; -- set these to empty string; not supported in cite arXiv
PublisherName = ''; -- (if the article has been published, use cite journal, or other)
Chapter = '';
URL = '';
Format = '';
Page = ''; Pages = ''; At = '';
end
Periodical = 'arXiv'; -- set to arXiv for COinS; after that, must be set to empty string
end
-- handle type parameter for those CS1 citations that have default values
if in_array(config.CitationClass, {"AV-media-notes", "DVD-notes", "mailinglist", "map", "podcast", "pressrelease", "report", "techreport", "thesis"}) then
TitleType = set_titletype (config.CitationClass, TitleType);
if is_set(Degree) and "Thesis" == TitleType then -- special case for cite thesis
TitleType = Degree .. " thesis";
end
end
if is_set(TitleType) then -- if type parameter is specified
TitleType = " (" .. TitleType .. ")"; -- display it in parentheses
end
-- legacy: promote concatenation of |month=, and |year= to Date if Date not set; or, promote PublicationDate to Date if neither Date nor Year are set.
if not is_set (Date) then
Date = Year; -- promote Year to Date
Year = nil; -- make nil so Year as empty string isn't used for CITEREF
Llinell 1,925 ⟶ 2,564:
if PublicationDate == Date then PublicationDate = ''; end -- if PublicationDate is same as Date, don't display in rendered citation
--[[
Llinell 1,933 ⟶ 2,571:
Date validation supporting code is in Module:Citation/CS1/Date_validation
]]
do -- create defined block to contain local variables error_message and mismatch
local error_message = '';
-- AirDate has been promoted to Date so not necessary to check it
anchor_year, COinS_date, error_message = dates({['accessdate']=AccessDate, ['archivedate']=ArchiveDate, ['date']=Date, ['doi_brokendate']=DoiBroken,
['embargo']=Embargo, ['laydate']=LayDate, ['publicationdate']=PublicationDate, ['year']=Year});
if is_set (Year) and is_set (Date) then -- both |date= and |year= not normally needed;
local mismatch = year_date_check (Year, Date)
if 0 == mismatch then -- |year= does not match a year-value in |date=
if is_set (error_message) then -- if there is already an error message
error_message = error_message .. ', '; -- tack on this additional message
end
error_message = error_message .. '|year= / |date= mismatch';
elseif 1 == mismatch then -- |year= matches year-value in |date=
add_maint_cat ('date_year');
end
end
if is_set(error_message) then
table.insert( z.message_tail, { set_error( 'bad_date', {error_message}, true ) } ); -- add this error message
end
end -- end of do
-- Account for the oddity that is {{cite journal}} with |pmc= set and |url= not set. Do this after date check but before COInS.
-- 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
Embargo = is_embargoed (Embargo); --
if config.CitationClass == "journal" and not is_set(URL) and is_set(ID_list['PMC']) then
if not is_set (Embargo) then -- if not embargoed or embargo has expired
URL=cfg.id_handlers['PMC'].prefix .. ID_list['PMC']; -- set url to be the same as the PMC external link if not embargoed
URLorigin = cfg.id_handlers['PMC'].parameters[1]; -- set URLorigin to parameter name for use in error message if citation is missing a |title=
end
end
Llinell 1,942 ⟶ 2,608:
-- Test if citation has no title
if not is_set(Title) and
not is_set(TransTitle) and
not is_set(ScriptTitle) then
table.insert( z.message_tail, {
end
if 'none' == Title and is_set(Periodical) and not (( config.CitationClass == "encyclopaedia" ) or ( config.CitationClass == "citation" and is_set (Encyclopedia))) then -- special case
Title = ''; -- set title to empty string
add_maint_cat ('untitled');
end
Llinell 1,969 ⟶ 2,633:
-- this is the function call to COinS()
local OCinSoutput = COinS({
['Periodical'] = Periodical,
['Chapter'] = strip_apostrophe_markup (coins_chapter), -- Chapter stripped of bold / italic wikimarkup
Llinell 1,978 ⟶ 2,642:
['Volume'] = Volume,
['Issue'] = Issue,
['Pages'] = get_coins_pages (first_set(Sheet, Sheets, Page, Pages, At)), -- pages stripped of external links
['Edition'] = Edition,
['PublisherName'] = PublisherName,
Llinell 1,985 ⟶ 2,649:
['ID_list'] = ID_list,
['RawPage'] = this_page.prefixedText,
}, config.CitationClass);
-- Account for the oddities that are {{cite arxiv}}, AFTER generation of COinS data.
if 'arxiv' == config.CitationClass then -- we have set rft.jtitle in COinS to arXiv, now unset so it isn't displayed
Periodical = ''; -- periodical not allowed in cite arxiv; if article has been published, use cite journal
end
-- special case for cite newsgroup. Do this after COinS because we are modifying Publishername to include some static text
if 'newsgroup' == config.CitationClass then
if is_set (PublisherName) then
PublisherName = '[[Usenet newsgroup|Newsgroup]]: ' ..
end
end
Llinell 2,009 ⟶ 2,668:
-- We also add leading spaces and surrounding markup and punctuation to the
-- various parts of the citation, but only when they are non-nil.
do -- do-block to limit scope of last_first_list
local last_first_list;
local maximum = A['DisplayAuthors'];
maximum , author_etal = get_display_authors_editors (maximum, #a, 'authors', author_etal);
local control = {
format = NameListFormat, -- empty string or 'vanc'
maximum =
lastauthoramp = LastAuthorAmp,
page_name = this_page.text -- get current page name so that we don't wikilink to it via authorlinkn
};
if is_set(Coauthors) then --
control.lastauthoramp = nil;
control.maximum = #a + 1;
end
if is_set (Authors) then
Authors, author_etal = name_has_etal (Authors, author_etal, false); -- find and remove variations on et al.
if author_etal then
Authors = Authors .. ' ' .. cfg.messages['et al']; -- add et al. to authors parameter
end
else
Authors = last_first_list; -- either an author name list or an empty string
end
end -- end of do
if not is_set(Authors) and is_set(Coauthors) then -- coauthors aren't displayed if one of authors=, authorn=, or lastn= isn't specified
table.insert( z.message_tail, {
end
local EditorCount; -- used only for choosing {ed.) or (eds.) annotation at end of editor name-list
do
local last_first_list;
local maximum = A['DisplayEditors'];
maximum , editor_etal = get_display_authors_editors (maximum, #e, 'editors', editor_etal);
-- Preserve old-style implicit et al.
if not is_set(
table.insert( z.message_tail, {
end
local control = {
format = NameListFormat, -- empty string or 'vanc'
maximum =
lastauthoramp = LastAuthorAmp,
page_name = this_page.text -- get current page name so that we don't wikilink to it via editorlinkn
};
if is_set (Editors) then
if editor_etal then
Editors = Editors .. ' ' .. cfg.messages['et al']; -- add et al. to editors parameter beause |display-editors=etal
EditorCount = 2; -- with et al., |editors= is multiple names; spoof to display (eds.) annotation
else
EditorCount = 2; -- we don't know but assume |editors= is multiple names; spoof to display (eds.) annotation
end
else
Editors = last_first_list; -- either an author name list or an empty string
end
if 1 == EditorCount and (true == editor_etal or 1 < #e) then -- only one editor displayed but includes etal then
EditorCount = 2; -- spoof to display (eds.) annotation
end
end
-- apply |[xx-]format= styling; at the end, these parameters hold correctly styled format annotation,
-- an error message if the associated url is not set, or an empty string for concatenation
ArchiveFormat = style_format (ArchiveFormat, ArchiveURL, 'archive-format', 'archive-url');
ChapterFormat = style_format (ChapterFormat, ChapterURL, 'chapter-format', 'chapter-url');
ConferenceFormat = style_format (ConferenceFormat, ConferenceURL, 'conference-format', 'conference-url');
Format = style_format (Format, URL, 'format', 'url');
LayFormat = style_format (LayFormat, LayURL, 'lay-format', 'lay-url');
TranscriptFormat = style_format (TranscriptFormat, TranscriptURL, 'transcript-format', 'transcripturl');
if not is_set(URL) then --and
-- not is_set(ArchiveURL) then --and -- prevents format_missing_url error from registering
-- not is_set(ConferenceURL) and -- TODO: keep this here? conference as part of cite web or cite podcast?
-- not is_set(TranscriptURL) then -- TODO: remove? |transcript-url= and |transcript= has separate test
-- Test if cite web or cite podcast |url= is missing or empty
if
table.insert( z.message_tail, {
end
-- Test if accessdate is given without giving a URL
if is_set(AccessDate) and not is_set(ChapterURL)then -- ChapterURL may be set when the others are not set; TODO: move this to a separate test?
table.insert( z.message_tail, {
AccessDate = '';
end
end
local OriginalURL, OriginalFormat; -- TODO: swap chapter and title here so that archive applies to most specific if both are set?
DeadURL = DeadURL:lower(); -- used later when assembling archived text
if is_set( ArchiveURL ) then
if is_set (URL) then
OriginalURL = URL; -- save copy of original source URL
OriginalFormat = Format; -- and original |format=
if 'no' ~= DeadURL then -- if URL set then archive-url applies to it
URL = ArchiveURL -- swap-in the archive's url
URLorigin = A:ORIGIN('ArchiveURL') -- name of archive url parameter for error messages
Format = ArchiveFormat or ''; -- swap in archive's format
end
elseif is_set (ChapterURL) then -- URL not set so if chapter-url is set apply archive url to it
OriginalURL = ChapterURL; -- save copy of source chapter's url for archive text
OriginalFormat = ChapterFormat; -- and original |format=
if 'no' ~= DeadURL then
ChapterURL = ArchiveURL -- swap-in the archive's url
URLorigin = A:ORIGIN('ArchiveURL') -- name of archive url parameter for error messages
ChapterFormat = ArchiveFormat or ''; -- swap in archive's format
end
end
end
if
('citation' == config.CitationClass and is_set (Periodical) and not is_set (Encyclopedia)) then
if is_set (Chapter) or is_set (TransChapter) or is_set (ChapterURL)then -- chapter parameters not supported for these citation types
table.insert( z.message_tail, {
Chapter = ''; -- set to empty string to be safe with concatenation
TransChapter = '';
Llinell 2,147 ⟶ 2,800:
Chapter = format_chapter_title (Chapter, TransChapter, ChapterURL, ChapterURLorigin);
if is_set (Chapter) then
if 'map' == config.CitationClass and is_set (TitleType) then
Chapter = Chapter .. ' ' .. TitleType;
end
Chapter = Chapter .. ChapterFormat .. sepc .. ' ';
Llinell 2,160 ⟶ 2,812:
end
if
('citation' == config.CitationClass and is_set (Periodical) and not is_set (Encyclopedia))
('map' == config.CitationClass and is_set (Periodical)) then -- special case for cite map when the map is in a periodical treat as an article
Title = kern_quotes (Title); -- if necessary, separate title's leading and trailing quote marks from Module provided quote marks
Title = wrap_style ('quoted-title', Title);
Title = script_concatenate (Title, ScriptTitle);
TransTitle= wrap_style ('trans-quoted-title', TransTitle );
elseif 'report' == config.CitationClass then -- no styling for cite report
Llinell 2,181 ⟶ 2,834:
TransTitle = " " .. TransTitle;
else
TransError = " " ..
end
end
Llinell 2,189 ⟶ 2,842:
if is_set(Title) then
if not is_set(TitleLink) and is_set(URL) then
Title =
URL = "";
Format = "";
Llinell 2,200 ⟶ 2,853:
Place = " " .. wrap_msg ('written', Place, use_lowercase) .. sepc .. " ";
end
if is_set (Conference) then
if is_set (ConferenceURL) then
Conference =
end
Conference = sepc .. " " .. Conference .. ConferenceFormat;
elseif is_set(ConferenceURL) then
Conference = sepc .. " " ..
end
if not is_set(Position) then
local Minutes = A['Minutes'];
Llinell 2,235 ⟶ 2,888:
if is_set(Pages) then
if is_set(Periodical) and
not
Pages = ": " .. Pages;
elseif tonumber(Pages) ~= nil then
Llinell 2,245 ⟶ 2,898:
else
if is_set(Periodical) and
not
Page = ": " .. Page;
else
Llinell 2,251 ⟶ 2,904:
end
end
if 'map' == config.CitationClass then -- cite map oddity done after COinS call (and with other in-source locators)
if is_set (Sheet) or is_set (Sheets) then
local err_msg1 = 'sheet=, |sheets'; -- default error message in case any of page pages or at are set
local err_msg2;
if is_set (Page) or is_set (Pages) or is_set (At) then -- are any set?
err_msg2 = 'page=, |pages=, |at'; -- a generic error message
Page = ''; Pages = ''; At = '';
elseif is_set (Sheet) and is_set (Sheets) then -- if both are set make error message
err_msg1 = 'sheet';
err_msg2 = 'sheets';
end
if is_set (err_msg2) then
table.insert( z.message_tail, { set_error( 'redundant_parameters', {wrap_style ('parameter', err_msg1) .. ' and ' .. wrap_style ('parameter', err_msg2)}, true ) } ); -- add error message
end
if not is_set (Sheet) then -- do sheet static text and formatting; Sheet has priority over Sheets if both provided
if is_set (Sheets) then
if is_set (Periodical) then
Sheet = ": Sheets " .. Sheets; -- because Sheet has priority, no need to support both later on
else
Sheet = sepc .. " Sheets " .. Sheets;
end
end
else
if is_set (Periodical) then
Sheet = ": Sheet " .. Sheet;
else
Sheet = sepc .. " Sheet " .. Sheet;
end
end
end
end
At = is_set(At) and (sepc .. " " .. At) or "";
Position = is_set(Position) and (sepc .. " " .. Position) or "";
if config.CitationClass == 'map' then
local Section = A['Section'];
local Sections = A['Sections'];
local Inset = A['Inset'];
end
if is_set( Sections ) then
Section = sepc .. " " .. wrap_msg ('sections', Sections, use_lowercase);
elseif is_set( Section ) then
Section = sepc .. " " .. wrap_msg ('section', Section, use_lowercase);
end
At = At .. Inset .. Section;
end
if is_set (Language) then
Language = language_parameter (Language
else
Language=""; -- language not specified so make sure this is an empty string;
Llinell 2,285 ⟶ 2,964:
Others = is_set(Others) and (sepc .. " " .. Others) or "";
TitleNote = is_set(TitleNote) and (sepc .. " " .. TitleNote) or "";
if is_set (Edition) then
if Edition:match ('[Ee]d%.?$') or Edition:match ('[Ee]dition$') then
add_maint_cat ('extra_text', 'edition');
end
Edition = " " .. wrap_msg ('edition', Edition);
else
Edition = '';
end
Issue = is_set(Issue) and (" (" .. Issue .. ")") or "";
Series = is_set(Series) and (sepc .. " " .. Series) or "";
Llinell 2,308 ⟶ 2,981:
if ( mw.ustring.len(Volume) > 4 )
then Volume = sepc .." " .. Volume;
else Volume = " <b>" ..
end
end
Llinell 2,322 ⟶ 2,995:
]]
if
SubscriptionRequired = sepc .. " " .. cfg.messages['subscription']; -- subscription required message
elseif
SubscriptionRequired = sepc .. " " .. cfg.messages['registration']; -- registration required message
else
Llinell 2,348 ⟶ 3,021:
end
ID_list =
if is_set(URL) then
URL = " " ..
end
Llinell 2,365 ⟶ 3,038:
if is_set(ArchiveURL) then
if not is_set(ArchiveDate) then
ArchiveDate =
end
if "no" == DeadURL then
Llinell 2,371 ⟶ 3,044:
if sepc ~= "." then arch_text = arch_text:lower() end
Archived = sepc .. " " .. substitute( cfg.messages['archived-not-dead'],
{
if not is_set(OriginalURL) then
Archived = Archived .. " " ..
end
elseif is_set(OriginalURL) then
Llinell 2,379 ⟶ 3,052:
if sepc ~= "." then arch_text = arch_text:lower() end
Archived = sepc .. " " .. substitute( arch_text,
{
else
local arch_text = cfg.messages['archived-missing'];
if sepc ~= "." then arch_text = arch_text:lower() end
Archived = sepc .. " " .. substitute( arch_text,
{
end
elseif is_set (ArchiveFormat) then
Archived = ArchiveFormat; -- if set and ArchiveURL not set ArchiveFormat has error message
else
Archived = ""
end
local Lay = '';
if is_set(LayURL) then
if is_set(LayDate) then LayDate = " (" .. LayDate .. ")" end
if is_set(LaySource) then
LaySource = " – ''" ..
else
LaySource = "";
end
if sepc == '.' then
Lay = sepc .. " " ..
else
Lay = sepc .. " " ..
end
elseif is_set (LayFormat) then -- Test if |lay-format= is given without giving a |lay-url=
Lay = sepc .. LayFormat; -- if set and LayURL not set, then LayFormat has error message
end
if is_set(Transcript) then
if is_set(TranscriptURL) then
Transcript = end Transcript = sepc .. ' ' .. Transcript .. TranscriptFormat;
elseif is_set(TranscriptURL) then
Transcript =
end
local Publisher;
if is_set(Periodical) and
not
if is_set(PublisherName) then
if is_set(PublicationPlace) then
Llinell 2,481 ⟶ 3,159:
local tcommon
if
if is_set(Others) then Others = Others .. sepc .. " " end
tcommon =
Language
elseif 'map' == config.CitationClass then -- special cases for cite map
if is_set (Chapter) then -- map in a book; TitleType is part of Chapter
tcommon = safe_join( {Title, Format, Edition, Scale, Series, Language, Cartography, Others, Publisher, Volume}, sepc );
elseif is_set (Periodical) then -- map in a periodical
tcommon = safe_join( {Title, TitleType, Format, Periodical, Scale, Series, Language, Cartography, Others, Publisher, Volume, Issue}, sepc );
else -- a sheet or stand-alone map
tcommon = safe_join( {Title, TitleType, Format, Edition, Scale, Series, Language, Cartography, Others, Publisher}, sepc );
end
elseif 'episode' == config.CitationClass then -- special case for cite episode
tcommon = safe_join( {Title, TitleNote, TitleType, Series, Transcript, Language, Edition, Publisher}, sepc );
else -- all other CS1 templates
tcommon = safe_join( {Title, TitleNote, Conference, Periodical, Format, TitleType, Series, Language,
Volume, Issue, Others, Edition, Publisher, Agency}, sepc );
end
if #ID_list > 0 then
ID_list =
else
ID_list = ID;
end
local idcommon =
local text;
local pgtext = Position .. Sheet .. Page .. Pages .. At;
if is_set(Authors) then
Llinell 2,529 ⟶ 3,219:
if (sepc ~= '.') then in_text = in_text:lower() end
Editors = in_text .. Editors .. post_text;
if (string.sub(Editors,-1,-1) == sepc) or (string.sub(Editors,-3,-1) == sepc .. ']]') then -- if last editor name ends with sepc char
else
Editors = Editors .. sepc .. " " -- otherwise terninate the editor list
end
end
text =
text =
elseif is_set(Editors) then
if is_set(Date) then
Llinell 2,551 ⟶ 3,242:
end
end
text =
text =
else
if is_set(Date) then
Llinell 2,561 ⟶ 3,252:
end
if config.CitationClass=="journal" and is_set(Periodical) then
text =
text =
else
text =
text =
end
end
if is_set(PostScript) and PostScript ~= sepc then
text =
text = text:sub(1,-sepc:len()-1);
end
text =
-- Now enclose the whole thing in a <span/> element
Llinell 2,602 ⟶ 3,292:
end
names[ #names + 1 ] = first_set(Year, anchor_year); -- Year first for legacy citations and for YMD dates that require disambiguation
id =
end
options.id = id;
Llinell 2,609 ⟶ 3,299:
if string.len(text:gsub("<span[^>/]*>.-</span>", ""):gsub("%b<>","")) <= 2 then
z.error_categories = {};
text =
z.message_tail = {};
end
Llinell 2,630 ⟶ 3,320:
if is_set(v[1]) then
if i == #z.message_tail then
text = text ..
else
text = text ..
end
end
end
end
if #z.maintenance_cats ~= 0 then
text = text .. '<span class="citation-comment" style="display:none; color:#33aa33">';
for _, v in ipairs( z.maintenance_cats ) do -- append maintenance categories
text = text .. ' ' .. v .. ' ([[:Category:' .. v ..'|link]])';
end
text = text .. '</span>'; -- maintenance mesages (realy just the names of the categories for now)
end
no_tracking_cats = no_tracking_cats:lower();
if
for _, v in ipairs( z.error_categories ) do
text = text .. '[[Category:' .. v ..']]';
Llinell 2,657 ⟶ 3,355:
function z.citation(frame)
local pframe = frame:getParent()
local validation;
if nil ~= string.find
cfg = mw.loadData (
whitelist = mw.loadData (
else -- otherwise
validation = require ('Module:Citation/CS1/Date_validation'); -- ... live version of date validation code
end
dates = validation.dates; -- imported functions
year_date_check = validation.year_date_check;
local args = {};
local suggestions = {};
Llinell 2,685 ⟶ 3,388:
-- Exclude empty numbered parameters
if v:match("%S+") ~= nil then
error_text, error_state =
end
elseif validate( k:lower() ) then
error_text, error_state =
else
if #suggestions == 0 then
Llinell 2,694 ⟶ 3,397:
end
if suggestions[ k:lower() ] ~= nil then
error_text, error_state =
else
error_text, error_state =
end
end
|