Content deleted Content added
update from sandbox per Template talk:Convert#Module version 9 |
move arg extraction to its own function to allow _convert() to be called from other lua modules |
||
(20 intermediate revisions by 3 users not shown) | |||
Line 35:
local extra_module -- name of module with extra units
local extra_units -- nil or table of extra units from extra_module
-- Some options in the invoking template can set variables used later in the module.
Line 137 ⟶ 136:
local spell_module -- name of module that can spell numbers
local speller -- function from that module to handle spelling (set if
local wikidata_module, wikidata_data_module -- names of Wikidata modules
local wikidata_code, wikidata_data -- exported tables from those modules (set if needed)
local function set_config(args)
Line 148 ⟶ 149:
text_module = "Module:Convert/text" .. sandbox
extra_module = "Module:Convert/extra" .. sandbox
wikidata_module = "Module:Convert/wikidata" .. sandbox
wikidata_data_module = "Module:Convert/wikidata/data" .. sandbox
spell_module = "Module:ConvertNumeric"
data_code = mw.loadData(data_module)
Line 256 ⟶ 259:
end
local function wanted_category(
-- Return
-- otherwise return local cat
local title = mw.title.getCurrentTitle()
if title then
Line 265 ⟶ 269:
for _, v in ipairs(split(config.nscat or nsdefault, ',')) do
if namespace == tonumber(v) then
cat = text_code.all_categories[want_warning and 'warning' or catkey]
if catsort and catsort ~= '' and cat:sub(-2) == ']]' then
cat = cat:sub(1, -3) .. '|' .. mw.text.nowiki(usub(catsort, 1, 20)) .. ']]'
end
break
end
end
end
return cat or ''
end
local function message(parms, mcode, is_warning)
-- Return wikitext for an error message, including category if specified
-- for the message type.
-- mcode = numbered table specifying the message:
-- mcode[1] = 'cvt_xxx' (string used as a key to get message info)
-- mcode[2] = 'parm1' (string to replace
-- mcode[3] = 'parm2' (string to replace
-- mcode[4] = 'parm3' (string to replace
local msg
if type(mcode) == 'table' then
if mcode[1] == 'cvt_no_output' then
-- Some errors should cause convert to output an empty string,
-- for example, for an optional field in an infobox.
return ''
end
msg = text_code.all_messages[mcode[1]]
end
parms.have_problem = true
local function subparm(fmt, ...)
local rep = {}
for i, v in ipairs({...}) do
rep['$' .. i] = v
end
return (fmt:gsub('$%d+', rep))
end
if msg then
local parts = {}
Line 306 ⟶ 330:
append = '...'
end
s = mw.text.nowiki(s) .. (append or '')
else
s = '?'
end
parts['$' .. i] = s
end
local function ispreview()
if parms.test == 'preview' or parms.test == 'nopreview' then
-- For testing, can preview a real message or simulate a preview
-- when running automated tests.
return parms.test == 'preview'
end
local success, revid = pcall(function ()
return (parms.frame):preprocess('{{REVISIONID}}') end)
return success and (revid == '')
end
local want_warning = is_warning and
not config.warnings and -- show unobtrusive warnings if config.warnings not configured
not msg.nowarn -- but use msg settings, not standard warning, if specified
local title = string.gsub(msg[1] or 'Missing message', '$%d+', parts)
local text = want_warning and '*' or msg[2] or 'Missing message'
local cat = wanted_category(msg[3], mcode[2], want_warning)
local anchor = msg[4] or ''
local
(want_warning and 'cvt_format2' or msg.format or 'cvt_format')
local fmt = text_code.all_messages[fmtkey] or 'convert: bug'
return subparm(fmt, title:gsub('"', '"'), text, cat, anchor)
end
return 'Convert internal error: unknown message'
Line 325 ⟶ 364:
function add_warning(parms, level, key, text1, text2) -- for forward declaration above
-- If enabled, add a warning that will be displayed after the convert result.
-- A higher level is more verbose: more kinds of warnings are displayed.
-- To reduce output noise, only the first warning is displayed.
if level <= (tonumber(config.warnings) or 1) then
if
end
end
Line 351 ⟶ 389:
success, speller = pcall(get_speller, spell_module)
if not success or type(speller) ~= 'function' then
add_warning(parms, 1, 'cvt_no_spell', 'spell')
return nil
end
Line 373 ⟶ 411:
-- If no altitude given, use default (zero altitude = sea level).
-- Table gives speed of sound in miles per hour at various altitudes:
-- altitude = -17,499 to
-- mach_table[a + 4] = s where
-- a = (altitude / 5000) rounded to nearest integer (-3 to
-- s = speed of sound (mph) at that altitude
-- LATER: Should calculate result from an interpolation between the next
Line 385 ⟶ 423:
660.1, 660.1, 660.1, 662.0, 664.3, 666.5, 668.9, 671.1, 673.4, 675.6, -- 11 to 20
677.9, 683.7, 689.9, 696.0, 702.1, 708.1, 714.0, 719.9, 725.8, 731.6, -- 21 to 30
737.3, 737.7, 737.7, 736.2, 730.5, 724.6, 718.8, 712.9, 707.0, 701.
695.0, 688.9, 682.8, 676.6, 670.4, 664.1, 657.8, 652.9, 648.3, 643.7, -- 41 to 50
639.1, 634.4, 629.6, 624.8, 620.0, 615.2, 613.2, 613.2, 613.2, 613.5, -- 51 to 60
614.4, 615.3, 616.7, 619.8, 623.4, 629.7, 635.0, 641.1, 650.6, 660.0, -- 61 to 70
672.5, 674.3, 676.1, 677.9, 679.7, 681.5, 683.3, 685.1, 686.8, 688.6, -- 71 to 80
}
altitude = altitude or 0
Line 397 ⟶ 437:
if a < -3 then
a = -3
elseif a >
a =
end
return mach_table[a + 4] * 0.44704 -- mph converted to m/s
Line 404 ⟶ 444:
-- END: Code required only for built-in units.
------------------------------------------------------------------------
local function add_style(parms, class)
-- Add selected template style to parms if not already present.
parms.templatestyles = parms.templatestyles or {}
if not parms.templatestyles[class] then
parms.templatestyles[class] = parms.frame:extensionTag({
name = 'templatestyles', args = { src = text_code.titles[class] }
})
end
end
local function get_styles(parms)
-- Return string of required template styles, empty if none.
if parms.templatestyles then
local t = {}
for _, v in pairs(parms.templatestyles) do
table.insert(t, v)
end
return table.concat(t)
end
return ''
end
local function get_range(word)
Line 506 ⟶ 568:
if key == 'symbol' then
value = self.si_prefix .. self._symbol
if value == 'l' then value = 'L' end
elseif key == 'sym_us' then
value = rawget(self, '_sym_us')
Line 552 ⟶ 615:
-- This is never called to determine a unit name or link because per units
-- are handled as a special case.
-- Similarly, the default output is handled elsewhere
-- this is only called from get_default() for default_exceptions.
__index = function (self, key)
local value
Line 577 ⟶ 641:
}
local function make_per(
-- Return true, t where t is a per unit with unit codes expanded to unit tables,
-- or return false, t where t is an error message table.
local result = {
unitcode = unitcode, utype = unit_table.utype, per = { }
override_from(result, unit_table, { 'invert', 'iscomplex', 'default', 'link', 'symbol', 'symlink' })
result.symbol_raw = (result.symbol or false) -- to distinguish between a defined exception and a metatable calculation
Line 593 ⟶ 661:
if not success then return false, t end
result.per[i] = t
end
end
Line 617 ⟶ 682:
result.scalemultiplier = multiplier or 1
result.vprefix = prefix or false -- set to non-nil to avoid calling __index
return true, setmetatable(result, unit_per_mt)
end
local function lookup(
-- Return true, t where t is a copy of the unit's converter table,
-- or return false, t where t is an error message table.
-- Parameter 'what' determines whether combination units are accepted:
-- 'no_combination' : single unit only
Line 640 ⟶ 701:
-- Wikignomes may also put two spaces or " " in combinations, so
-- replace underscore, " ", and multiple spaces with a single space.
utable = utable or parms.unittable or all_units
fails = fails or {}
depth = depth and depth + 1 or 1
Line 653 ⟶ 714:
end
unitcode = unitcode:gsub('_', ' '):gsub(' ', ' '):gsub(' +', ' ')
local function call_make_per(t)
return make_per(unitcode, t,
function (ucode) return lookup(parms, ucode, 'no_combination', utable, fails, depth) end
)
end
local t = utable[unitcode]
if t then
Line 658 ⟶ 724:
return false, { 'cvt_should_be', t.shouldbe }
end
if t.sp_us then
end
local target = t.target -- nil, or unitcode is an alias for this target
if target then
local success, result = lookup(
if not success then return false, result end
override_from(result, t, { 'customary', 'default', 'link', 'symbol', 'symlink', 'usename' })
local multiplier = t.multiplier
if multiplier then
Line 676 ⟶ 740:
end
if t.per then
return call_make_per(t)
end
local combo = t.combination -- nil or a table of unitcodes
Line 689 ⟶ 753:
local cvt = result.combination
for i, v in ipairs(combo) do
local success, t = lookup(
if not success then return false, t end
cvt[i] = t
Line 696 ⟶ 760:
end
local result = shallow_copy(t)
result.
if result.prefixes then
result.si_name = ''
Line 715 ⟶ 779:
if t and t.prefixes then
local result = shallow_copy(t)
result.unitcode = unitcode
result.si_prefix = si.prefix or prefix
result.scale = t.scale * 10 ^ (si.exponent * t.prefixes)
return true, setmetatable(result, unit_prefixed_mt)
end
end
Line 757 ⟶ 793:
local err_is_fatal
local combo = collection()
if
err_is_fatal = true
for item in (unitcode .. '+'):gmatch('%s*(.-)%s*%+') do
Line 777 ⟶ 813:
local cvt = result.combination
for i, v in ipairs(combo) do
local success, t = lookup(
if not success then return false, t end
if i == 1 then
Line 794 ⟶ 830:
if success or err_is_fatal then
return success, result
end
end
-- Accept any unit with an engineering notation prefix like "e6cuft"
-- (million cubic feet), but not chained prefixes like "e3e6cuft",
-- and not if the unit is a combination or multiple,
-- and not if the unit has an offset or is a built-in.
-- Only en digits are accepted.
local e, exponent, baseunit = unitcode:match('^([Ee])(%d+)(.*)')
if exponent then
local engscale = text_code.eng_scales[exponent]
if engscale then
local success, result = lookup(parms, baseunit, 'no_combination', utable, fails, depth)
if success and not (result.offset or result.builtin or result.engscale) then
if e == 'E' then
result.this_number_word = true
unitcode = 'e' .. unitcode:sub(2)
end
result.unitcode = unitcode -- 'e6cuft' not 'cuft'
result.defkey = unitcode -- key to lookup default exception
result.engscale = engscale
result.scale = result.scale * 10 ^ tonumber(exponent)
return true, result
end
end
end
Line 803 ⟶ 862:
-- Engineering notation (apart from at start and which has been stripped before here),
-- is not supported so do not make a per unit if find text like 'e3' in unitcode.
local success, result =
if success then
return true, result
end
end
if not
-- Want the "what links here" list for the extra_module to show only cases
-- where an extra unit is used, so do not require it if invoked from {{val}}
Line 824 ⟶ 883:
fails[unitcode] = true
local other = (utable == all_units) and extra_units or all_units
local success, result = lookup(
if success then
return true, result
Line 835 ⟶ 894:
local en_code = ustring.gsub(unitcode, '%d', to_en_table)
if en_code ~= unitcode then
return lookup(
end
end
Line 849 ⟶ 908:
return true
end
end
Line 913 ⟶ 938:
return name:sub(1, pos+1) .. name:sub(pos+2):gsub(' ', '-')
end
elseif name:sub(
pos = name:find('(', 1, true)
if pos then
Line 964 ⟶ 989:
end
return sep .. id .. mid
end
Line 982 ⟶ 999:
end
local function
-- Return a numbered table
-- Parameter method is a number or nil:
-- 3 for 3-digit grouping (default), or
-- 2 for 3-then-2 grouping (only for digits before decimal mark).
local len_right
local len_left = text:find('.', 1, true)
if len_left then
len_right = #text - len_left
else
len_left = #text
end
local twos = method == 2 and len_left > 5
local groups = collection()
local n
if run < 4 or (run == 4 and parms.opt_comma5) then
if parms.opt_gaps then
n = run
end
elseif twos then
n = run % 2 == 0 and 1 or 2
else
n = run % 3 == 0 and 3 or run % 3
end
while run > 0 do
groups:add(n)
run = run - n
n = (twos and run > 3) and 2 or 3
end
if len_right then
if groups.n == 0 then
groups:add(0)
end
if parms.opt_gaps and len_right > 3 then
local want4 = not parms.opt_gaps3 -- true gives no gap before trailing single digit
local isfirst = true
run = len_right
while run > 0 do
n = (want4 and run == 4) and 4 or (run > 3 and 3 or run)
if isfirst then
isfirst = false
groups[groups.n] = groups[groups.n] + 1 + n
else
groups:add(n)
end
end
groups[groups.n] = groups[groups.n] + 1 + len_right
end
end
local pos = 1
for i, length in ipairs(groups) do
groups[i] = from_en(text:sub(pos, pos + length - 1))
pos = pos + length
return groups
end
function with_separator(parms, text) -- for forward declaration above
-- Input text is a number in en digits
-- Return an equivalent
-- with a custom decimal mark instead of '.', if wanted
-- with thousand separators inserted, if wanted
-- digits in local language
-- The given text is like '123' or '
-- The text has no sign (caller inserts that later, if necessary).
--
--
-- A trailing dot (as in '123.') is removed because their use appears to
-- be accidental, and such a number should be shown as '123' or '123.0'.
-- It is useful for convert to suppress the dot so, for example, '4000.'
-- is a simple way of indicating that all the digits are significant.
if text:sub(-1) == '.' then
text = text:sub(1, -2)
end
if #text < 4 or parms.opt_nocomma or numsep == '' then
return from_en(text)
end
local groups =
if parms.opt_gaps then
if groups.n <= 1 then
return groups[1] or ''
end
local nowrap = '<span style="white-space: nowrap">'
local gap = '<span style="margin-left: 0.25em">'
local close = '</span>'
return nowrap .. groups[1] .. gap .. table.concat(groups, close .. gap, 2, groups.n) .. close .. close
end
return table.concat(groups
end
Line 1,066 ⟶ 1,101:
local fmtpower = '%s<span style="margin:0 .15em 0 .25em">×</span>%s<sup>%s</sup>'
local function with_exponent(parms, show, exponent)
-- Return wikitext to display the implied value in scientific notation.
-- Input uses en digits; output uses digits in local language.
return format(fmtpower,
end
Line 1,111 ⟶ 1,146:
local fracfmt = {
{ -- Like {{frac}} (fraction slash).
'<span class="frac">{SIGN}<span class="num">{NUM}</span>⁄<span class="den">{DEN}</span></span>', -- 1/2
'<span class="frac">{SIGN}{WHOLE}<span class="sr-only">+</span><span class="num">{NUM}</span>⁄<span class="den">{DEN}</span></span>', -- 1+2/3
style = 'frac',
},
{ -- Like {{sfrac}} (stacked fraction, that is, horizontal bar).
'<span class="sfrac tion">{SIGN}<span class="num">{NUM}</span><span class="sr-only">/</span><span class="den">{DEN}</span></span>', -- 1//2
'<span class="sfrac">{SIGN}{WHOLE}<span class="sr-only">+</span><span class="tion"><span class="num">{NUM}</span><span class="sr-only">/</span><span class="den">{DEN}</span></span></span>', -- 1+2//3
style = 'sfrac',
},
}
Line 1,134 ⟶ 1,167:
wholestr = nil
end
local substitute = {
SIGN = negative and MINUS or '',
WHOLE = wholestr and with_separator(parms, wholestr),
NUM = from_en(numstr),
DEN = from_en(denstr),
}
if do_spell then
if negative then
Line 1,153 ⟶ 1,182:
end
end
if s then
return s
end
end
add_style(parms, fracfmt[style].style)
return wikitext
end
Line 1,256 ⟶ 1,289:
exponent = exponent,
sign = sign,
show = sign .. with_exponent(parms, significand, exponent-1),
is_scientific = true,
}
Line 1,321 ⟶ 1,354:
-- with the hands unit (not worth adding code to enforce that).
------------------------------------------------------------------------
local leading_plus, prefix, numstr, slashes, denstr =
text:match('^%s*(%+?)%s*(.-)%s*(%d+)%s*(/+)%s*(%d+)%s*$')
Line 1,335 ⟶ 1,367:
return nil
end
local whole, wholestr
if prefix == '' then
wholestr = ''
Line 1,369 ⟶ 1,401:
-- or return false, t where t is an error message table.
-- Input can use en digits or digits in local language and can
-- have
-- for use in infoboxes with a field for a value passed to convert.
-- Parameter another = true if the expected value is not the first.
-- Before processing, the input text is cleaned:
-- * Any thousand separators (valid or not) are removed.
-- * Any sign
-- That replaces Unicode minus with '-'.
-- If successful, the returned info table contains named fields:
Line 1,384 ⟶ 1,415:
-- clean = cleaned text with any separators and sign removed
-- (en digits and '.' decimal mark)
-- show = text formatted for output, possibly with ref strip
-- (digits in local language and custom decimal mark)
-- The resulting show:
Line 1,393 ⟶ 1,424:
-- '+' (if the input text used '+'), or is '' (if no sign in input).
text = strip(text or '')
local
local pos = text:find('\127', 1, true)
if pos then
local before = text:sub(1, pos - 1)
local remainder = text:sub(pos)
local refs = {}
while #remainder > 0 do
local ref, spaces
ref, spaces, remainder = remainder:match('^(\127[^\127]*UNIQ[^\127]*%-ref[^\127]*\127)(%s*)(.*)')
if ref then
table.insert(refs, ref)
else
refs = {}
break
end
end
if #refs > 0 then
text = strip(before)
reference = table.concat(refs)
end
end
local clean = to_en(text, parms)
Line 1,418 ⟶ 1,466:
local valstr
for _, prefix in ipairs({ '-', MINUS, '−' }) do
-- Including '-'
local plen = #prefix
if clean:sub(1, plen) == prefix then
valstr = clean:sub(plen + 1)
if valstr:match('^%s') then -- "- 1" is invalid but "-1 - 1/2" is ok
return false, { 'cvt_bad_num', text }
end
break
end
Line 1,449 ⟶ 1,499:
if show == nil then
-- clean is a non-empty string with no spaces, and does not represent a fraction,
-- and value = tonumber(clean) is a number >= 0.
-- If the input uses e-notation, show will be displayed using a power of ten, but
-- we use the number as given so it might not be normalized scientific notation.
Line 1,455 ⟶ 1,505:
-- that allows input like 2e6 to be spelled as "two million" which works
-- because the spell module converts '2e6' to '2000000' before spelling.
local function rounded(value, default, exponent)
local precision = parms.
if precision
local fmt = '%.' .. format('%d', precision) .. 'f'
if not exponent then
singular = (tonumber(result) == 1)
end
return result
end
return default
end
singular = (value == 1)
Line 1,466 ⟶ 1,521:
local significand, exponent = clean:match('^([%d.]+)[Ee]([+%-]?%d+)')
if significand then
show = with_exponent(parms, rounded
scientific = true
else
show = with_separator(parms, rounded(value
end
show = propersign .. show
if parms.opt_spell_in then
show = spell_number(parms, 'in', propersign .. rounded(value, clean)) or show
scientific = false
end
Line 1,480 ⟶ 1,535:
end
end
if isnegative and (value ~= 0) then
value = -value
altvalue = -(altvalue or value)
end
return true, {
value = value,
altvalue = altvalue or value,
singular = singular,
clean = clean,
Line 1,501 ⟶ 1,555:
-- v = value of text (text is a number)
-- f = true if value is an integer
-- Input can use en digits or digits in local language or separators,
-- but
if text then
local number = tonumber(to_en(text))
if number then
local
return number, (fracpart == 0)
end
Line 1,584 ⟶ 1,638:
-- p2 is text to insert before the output unit
-- p1 or p2 may be nil to mean "no preunit"
-- Using '+
local function withspace(text,
--
-- However, no space is
--
-- There is also no space if text starts with '&'
-- (e.g. '°' would display a degree symbol with no preceding space).
if char == '&' then
return text -- an html entity can be used to specify the exact display
end
if
end
if
if not (char == ' ' or char == '-' or text:sub(-6, -1) == ' ') then
text = text .. ' '
end
end
return text
end
local PLUS = '+ '
preunit1 = preunit1 or ''
local trim1 = strip(preunit1)
Line 1,612 ⟶ 1,667:
return nil
end
if trim1 == '+' then
return PLUS
end
return withspace(preunit1, true)
end
preunit1 = withspace(preunit1)
preunit2 = preunit2 or ''
local trim2 = strip(preunit2)
if trim1 == '
if trim2 == '' or trim2 == '+' then
return PLUS, PLUS
end
preunit1 =
end
if trim2 == '
return nil, nil
end
preunit2 = preunit1
elseif trim2
preunit2 =
elseif trim2 == ' ' then -- trick to make preunit2 empty
preunit2 = nil
else
preunit2 = withspace(preunit2)
end
return preunit1, preunit2
end
local function range_text(range, want_name, parms, before, after, inout, options)
-- Return before .. rtext .. after
-- where rtext is the text that separates two values in a range.
local rtext, adj_text, exception
options = options or {}
if type(range) == 'table' then
-- Table must specify range text for ('off' and 'on') or ('input' and 'output'),
Line 1,652 ⟶ 1,717:
end
end
if rtext == '–' and (options.spaced or after:sub(1, #MINUS) == MINUS) then
rtext = ' – '
end
Line 1,659 ⟶ 1,724:
local function get_composite(parms, iparm, in_unit_table)
-- Look for a composite input unit. For example,
-- would result in a call to this function with
-- iparm = 3 (parms[iparm] = "2", just after the first unit)
Line 1,680 ⟶ 1,745:
end
local success
success, subunit = lookup(
if not success then return false, subunit end -- should never occur
success, subinfo = extract_number(parms, parms[iparm])
Line 1,708 ⟶ 1,773:
composite_units[i].fixed_name = name
else
local success, alternate = lookup(
if not success then return false, alternate end -- should never occur
alternate.inout = 'in'
Line 1,738 ⟶ 1,803:
kv_pairs.sing = nil
end
kv_pairs.comma = kv_pairs.comma or config.comma -- for plwiki who want default comma=5
for loc_name, loc_value in pairs(kv_pairs) do
local en_name = text_code.en_option_name[loc_name]
if en_name then
local en_value = text_code.en_option_value[en_name]
if
en_value = nil
if loc_value == '' then
add_warning(parms, 2, 'cvt_empty_option', loc_name)
else
local minimum
local number, is_integer = get_number(loc_value)
if en_name == '
minimum = 1
elseif en_name == 'frac' then
minimum = 2
if number and number < 0 then
Line 1,758 ⟶ 1,824:
end
else
minimum =
end
if number and is_integer and number >= minimum then
en_value = number
else
local m
if en_name == 'frac' then
m = 'cvt_bad_frac'
elseif en_name == 'sigfig' then
m = 'cvt_bad_sigfig'
else
m = 'cvt_bad_altitude'
end
add_warning(parms, 1, m, loc_name .. '=' .. loc_value)
end
end
elseif en_value == 'TEXT' then -- $, input, qid, qual, stylein, styleout, tracking
en_value = loc_value ~= '' and loc_value or nil -- accept non-empty user text with no validation
if not en_value and (en_name == '$' or en_name == 'qid' or en_name == 'qual') then
add_warning(parms, 2, 'cvt_empty_option', loc_name)
elseif en_name == '$' then
-- Value should be a single character like "€" for the euro currency symbol, but anything is accepted.
currency_text = (loc_value == 'euro') and '€' or loc_value
elseif en_name == 'input' then
-- May have something like {{convert|input=}} (empty input) if source is an infobox
-- with optional fields. In that case, want to output nothing rather than an error.
parms.input_text = loc_value -- keep input because parms.input is nil if loc_value == ''
end
else
en_value =
if en_value and en_value:sub(-1) == '?' then
en_value = en_value:sub(1, -2)
add_warning(parms, -1, 'cvt_deprecated', loc_name .. '=' .. loc_value)
end
if en_value == nil then
if loc_value == '' then
add_warning(parms, 2, 'cvt_empty_option', loc_name)
else
add_warning(parms, 1, 'cvt_unknown_option', loc_name .. '=' .. loc_value)
end
elseif en_value == '' then
Line 1,781 ⟶ 1,868:
elseif type(en_value) == 'string' and en_value:sub(1, 4) == 'opt_' then
for _, v in ipairs(split(en_value, ',')) do
local lhs, rhs = v:match('^(.-)=(.+)$')
if rhs then
parms[lhs] = tonumber(rhs) or rhs
else
parms[v] = true
end
end
en_value = nil
Line 1,789 ⟶ 1,881:
else
add_warning(parms, 1, 'cvt_unknown_option', loc_name .. '=' .. loc_value)
end
end
Line 1,816 ⟶ 1,900:
end
if parms.abbr then
if parms.abbr == 'unit' then
parms.abbr = 'on'
parms.number_word = true
end
parms.abbr_org = parms.abbr -- original abbr, before any flip
elseif parms.opt_hand_hh then
Line 1,822 ⟶ 1,910:
else
parms.abbr = 'out' -- default is to abbreviate output only (use symbol, not name)
end
if parms.opt_order_out then
-- Disable options that do not work in a useful way with order=out.
parms.opt_flip = nil -- override adj=flip
parms.opt_spell_in = nil
parms.opt_spell_out = nil
parms.opt_spell_upper = nil
end
if parms.opt_spell_out and not abbr_entered then
parms.abbr = 'off' -- should show unit name when spelling the output value
end
if parms.opt_flip then
Line 1,848 ⟶ 1,946:
parms.opt_values = true
end
end
if parms.table_align or parms.opt_sortable_on then
parms.need_table_or_sort = true
end
local disp_joins = text_code.disp_joins
Line 1,958 ⟶ 2,058:
range:add(range_item)
if type(range_item) == 'table' then
-- For range "x", if append unit to some values, append it to all.
parms.in_range_x = parms.in_range_x or range_item.in_range_x
parms.out_range_x = parms.out_range_x or range_item.out_range_x
parms.abbr_range_x = parms.abbr_range_x or range_item.abbr_range_x
is_change = range_item.is_range_change
end
Line 1,975 ⟶ 2,078:
local function simple_get_values(parms)
-- If input is like "{{convert|valid_value|valid_unit|...}}",
-- return true,
--
-- The valid_value is not negative and does not use a fraction, and
-- no options requiring further processing of the input are used.
-- Otherwise, return nothing
-- Testing shows this function is successful for 96% of converts in articles,
-- and that on average it speeds up converts by 8%.
local clean = to_en(strip(parms[1] or ''), parms)
if parms.opt_ri or parms.opt_spell_in or #clean > 10 or not clean:match('^[0-9.]+$') then
return false, clean
end
local value = tonumber(clean)
if not value then return end
Line 1,995 ⟶ 2,099:
}
local in_unit = strip(parms[2])
local success, in_unit_table = lookup(
if not success then return end
in_unit_table.valinfo = { info }
Line 2,001 ⟶ 2,105:
end
local function
-- Return true, s where s is the result of a Wikidata operation,
-- or return false, t where t is an error message table.
local function worker(...)
wikidata_code = wikidata_code or require(wikidata_module)
wikidata_data = wikidata_data or mw.loadData(wikidata_data_module)
return wikidata_code[operation](wikidata_data, ...)
end
local success, status, result = pcall(worker, ...)
if success then
return status, result
end
if parms.opt_sortable_debug then
-- Use debug=yes to crash if an error while accessing Wikidata.
error('Error accessing Wikidata: ' .. status, 0)
end
return false, { 'cvt_wd_fail' }
end
local function get_parms(parms, args)
-- If successful, update parms and return true, unit where
-- parms is a table of all arguments passed to the template
-- converted to named arguments, and
-- unit is the input unit table;
-- or return false, t where t is an error message table.
-- For special processing (not a convert), can also return
-- true, wikitext where wikitext is the final result.
-- The returned input unit table may be for a fake unit using the specified
-- unit code as the symbol and name, and with bad_mcode = message code table.
Line 2,013 ⟶ 2,138:
-- whitespace entered in the template, and whitespace is used by some
-- parameters (example: the numbered parameters associated with "disp=x").
local kv_pairs = {} -- table of input key:value pairs where key is a name; needed because cannot iterate parms and add new fields to it
for k, v in pairs(args) do
Line 2,021 ⟶ 2,145:
kv_pairs[k] = v
end
end
if parms.test == 'wikidata' then
local ulookup = function (ucode)
-- Use empty table for parms so it does not accumulate results when used repeatedly.
return lookup({}, ucode, 'no_combination')
end
return wikidata_call(parms, '_listunits', ulookup)
end
local success, msg = translate_parms(parms, kv_pairs)
if not success then return false, msg end
if parms.input then
success, msg = wikidata_call(parms, '_adjustparameters', parms, 1)
if not success then return false, msg end
end
local success, i, in_unit, in_unit_table = simple_get_values(parms)
if not success then
if type(i) == 'string' and i:match('^NNN+$') then
-- Some infoboxes have examples like {{convert|NNN|m}} (3 or more "N").
-- Output an empty string for these.
return false, { 'cvt_no_output' }
end
local valinfo
success, valinfo, i = get_values(parms)
Line 2,032 ⟶ 2,171:
in_unit = strip(parms[i])
i = i + 1
success, in_unit_table = lookup(
if not success then
if parms.opt_ignore_error then -- display given unit code with no error (for use with {{val}})
in_unit_table = '' -- suppress error message and prevent processing of output unit
end
in_unit_table = setmetatable({
symbol = in_unit, name2 = in_unit, utype = in_unit, scale = 1, default =
end
in_unit_table.valinfo = valinfo
Line 2,067 ⟶ 2,205:
end
if in_unit_table.builtin == 'mach' then
-- As with old template, a number following Mach as the input unit is the altitude
-- That is deprecated: should use altitude_ft=NUMBER or altitude_m=NUMBER.
local success, info
success = tonumber(parms[i]) -- this will often work and will give correct result for values like 2e4 without forcing output scientific notation
if success then
info = { value = success }
else
success, info = extract_number(parms, parms[i], false, true)
end
if success then
i = i + 1
Line 2,077 ⟶ 2,219:
end
end
local
i = i + 1
local precision, is_bad_precision
Line 2,092 ⟶ 2,234:
end
end
if word and not set_precision(
parms.out_unit =
if set_precision(strip(parms[i])) then
i = i + 1
Line 2,099 ⟶ 2,241:
end
if parms.opt_adj_mid then
i = i + 1
if
if
parms.mid =
else
parms.mid = ' ' ..
end
end
Line 2,145 ⟶ 2,287:
parms.precision = precision
end
for j = i, i + 3 do
local parm = parms[j] -- warn if find a non-empty extraneous parameter
if parm and parm:match('%S') then
add_warning(parms, 1, 'cvt_unknown_option', parm)
break
end
end
return true, in_unit_table
end
Line 2,181 ⟶ 2,330:
local fudge = 1e-14 -- {{Order of magnitude}} adds this, so we do too
local prec, minprec, adjust
local subunit_ignore_trailing_zero
local subunit_more_precision -- kludge for "in" used in input like "|2|ft|6|in"
Line 2,212 ⟶ 2,360:
end
if in_current.istemperature and out_current.istemperature then
-- Converting between common temperatures (°C, °F, °R, K); not keVT
-- Kelvin value can be almost zero, or small but negative due to precision problems.
-- Also, an input value like -300 C (below absolute zero) gives negative kelvins.
Line 2,293 ⟶ 2,441:
end
if in_builtin == 'mach' or out_builtin == 'mach' then
-- Should check that only one altitude is given but am planning to remove
-- in_current.altitude (which can only occur when Mach is the input unit),
-- and out_current.altitude cannot occur.
local alt = parms.altitude_ft or in_current.altitude
if not alt and parms.altitude_m then
alt = parms.altitude_m / 0.3048 -- 1 ft = 0.3048 m
end
local spd = speed_of_sound(alt)
if in_builtin == 'mach' then
inscale =
end
outscale = spd
local adjust = 0.1 / inscale
return true, {
outvalue = invalue * (inscale / outscale),
Line 2,347 ⟶ 2,501:
end
return false, { 'cvt_bug_convert' } -- should never occur
end
local function user_style(parms, i)
-- Return text for a user-specified style for a table cell, or '' if none,
-- given i = 1 (input style) or 2 (output style).
local style = parms[(i == 1) and 'stylein' or 'styleout']
if style then
style = style:gsub('"', '')
if style ~= '' then
if style:sub(-1) ~= ';' then
style = style .. ';'
end
return style
end
end
return ''
end
local function make_table_or_sort(parms, invalue, info, in_current, scaled_top)
-- Set options to handle output for a table or a sort key, or both.
-- The text sort key is based on the value resulting from converting
-- the input to a fake base unit with scale = 1, and other properties
-- required for a conversion derived from the input unit.
-- For other modules, return the sort key in a hidden span element, and
-- the scaled value used to generate the sort key.
-- If scaled_top is set, it is the scaled value of the numerator of a per unit
-- to be combined with this unit (the denominator) to make the sort key.
-- Scaling only works with units that convert with a factor (not temperature).
local sortkey, scaled_value
if parms.opt_sortable_on then
local base = { -- a fake unit with enough fields for a valid convert
scale = 1,
invert = in_current.invert and 1,
iscomplex = in_current.iscomplex,
offset = in_current.offset and 0,
}
local outvalue, extra = convert(parms, invalue, info, in_current, base)
if extra then
outvalue = extra.outvalue
end
if in_current.istemperature then
-- Have converted to kelvin; assume numbers close to zero have a
-- rounding error and should be zero.
if abs(outvalue) < 1e-12 then
outvalue = 0
end
end
if scaled_top and outvalue ~= 0 then
outvalue = scaled_top / outvalue
end
scaled_value = outvalue
if not valid_number(outvalue) then
if outvalue < 0 then
sortkey = '1000000000000000000'
else
sortkey = '9000000000000000000'
end
elseif outvalue == 0 then
sortkey = '5000000000000000000'
else
local mag = floor(log10(abs(outvalue)) + 1e-14)
local prefix
if outvalue > 0 then
prefix = 7000 + mag
else
prefix = 2999 - mag
outvalue = outvalue + 10^(mag+1)
end
sortkey = format('%d', prefix) .. format('%015.0f', floor(outvalue * 10^(14-mag)))
end
end
local sortspan
if sortkey and not parms.table_align then
sortspan = parms.opt_sortable_debug and
'<span data-sort-value="' .. sortkey .. '♠"><span style="border:1px solid">' .. sortkey .. '♠</span></span>' or
'<span data-sort-value="' .. sortkey .. '♠"></span>'
parms.join_before = sortspan
end
if parms.table_align then
local sort
if sortkey then
sort = ' data-sort-value="' .. sortkey .. '"'
if parms.opt_sortable_debug then
parms.join_before = '<span style="border:1px solid">' .. sortkey .. '</span>'
end
else
sort = ''
end
local style = 'style="text-align:' .. parms.table_align .. ';'
local joins = {}
for i = 1, 2 do
joins[i] = (i == 1 and '' or '\n|') .. style .. user_style(parms, i) .. '"' .. sort .. '|'
end
parms.table_joins = joins
end
return sortspan, scaled_value
end
Line 2,358 ⟶ 2,608:
-- is "1", or like "1.00", or is a fraction with value < 1;
-- (and more fields shown below, and a calculated 'absvalue' field).
-- or return false, t where t is an error message table.
-- Input info.clean uses en digits (it has been translated, if necessary).
-- Output show uses en or non-en digits as appropriate, or can be spelled.
if out_current.builtin == 'hand' then
return cvt_to_hand(parms, info, in_current, out_current)
end
local invalue = in_current.builtin == 'hand' and info.altvalue or info.value
local outvalue, extra = convert(parms, invalue, info, in_current, out_current)
if parms.need_table_or_sort then
parms.need_table_or_sort = nil -- process using first input value only
make_table_or_sort(parms, invalue, info, in_current)
end
if extra then
if not outvalue then return false, extra end
Line 2,389 ⟶ 2,633:
outvalue = -outvalue
end
local
local denominator = out_current.frac
if denominator then
Line 2,396 ⟶ 2,640:
precision = parms.precision
if not precision then
show, exponent = make_sigfig(outvalue, parms.sigfig)
elseif parms.opt_round then
local n = parms.opt_round
if n == 0.5 then
local integer, fracpart = math.modf(floor(2 * outvalue + 0.5) / 2)
if fracpart == 0 then
show = format('%.0f', integer)
else
show = format('%.1f', integer + fracpart)
end
else
show = format('%.0f', floor((outvalue / n) + 0.5) * n)
end
elseif in_current.builtin == 'mach' then
local sigfig = info.clean:gsub('^[0.]+', ''):gsub('%.', ''):len() + 1
show, exponent = make_sigfig(outvalue, sigfig)
else
local inclean = info.clean
Line 2,597 ⟶ 2,852:
local i = t.multiple and table_len(combo) or 1
ucode = combo[i]
end
else
-- Try for an automatically generated combination.
local item = ucode:match('^(.-)%+') or ucode:match('^(%S+)%s')
if all_units[item] then
return item
end
end
Line 2,627 ⟶ 2,888:
local linked_pages -- to record linked pages so will not link to the same page more than once
local function
-- Forget that the given unit has previously been linked (if it has).
-- That is needed when processing a range of inputs or outputs when an id
-- for the first range value may have been evaluated, but only an id for
-- the last value is displayed, and that id may need to be linked.
linked_pages[unit_table.unitcode or unit_table] = nil
end
local function make_link(link, id, unit_table)
-- Return wikilink "[[link|id]]", possibly abbreviated as in examples:
-- [[Mile|mile]] --> [[mile]]
Line 2,634 ⟶ 2,903:
-- * no link given (so caller does not need to check if a link was defined); or
-- * link has previously been used during the current convert (to avoid overlinking).
local link_key
if unit_table then
link_key = unit_table.unitcode or unit_table
else
link_key = link
end
if not link or link == '' or linked_pages[link_key] then
return id
Line 2,655 ⟶ 2,925:
end
local function variable_name(clean, unit_table, exp_multiplier, key_id)
--
-- Parameter clean is the unsigned
-- It may represent a number ("1.0") or a fraction ("1+2/3").
-- In varname, fields are separated with "!" and are not empty.
-- A field for a unit using an SI prefix has the prefix name inserted,
-- replacing '#' if found, or before the field otherwise.
if clean:match('[./]') then -- float or fraction
clean = exp_multiplier -- force selection of name for a large integer
else
clean = 34.5 -- force selection of name for a float value
end
else
clean = tonumber(clean) * (exp_multiplier or 1)
end
local name1, vname
if key_id == 'pername' and unit_table.pername then
vname = unit_table.pername
elseif unit_table.varname then
local splitvname = split(unit_table.varname, '!')
name1 = unit_table.name1
vname = mw.language.getContentLanguage():convertPlural(clean, name1, unpack(splitvname))
else
return clean == 1 and unit_table.name1 or unit_table.name2
end
if vname == name1 then
-- SI prefix (if any) has been inserted by unit_prefixed_mt.
else
local si_name = rawget(unit_table, 'si_name') or ''
local pos = vname:find('#', 1, true)
Line 2,693 ⟶ 2,961:
vname = si_name .. vname
end
end
return
end
local function linked_id(parms, unit_table, key_id, want_link, clean, exp_multiplier)
-- Return final unit id (symbol or name), optionally with a wikilink,
-- and update unit_table.sep if required.
-- key_id is one of: 'symbol', 'sym_us', 'name1', 'name1_us', 'name2', 'name2_us', 'pername'.
local abbr_on = (key_id == 'symbol' or key_id == 'sym_us')
if abbr_on and want_link then
Line 2,712 ⟶ 2,979:
local per = unit_table.per
if per then
local paren1, paren2 = '', '' -- possible parentheses around bottom unit
local unit1 = per[1] -- top unit_table, or nil
local unit2 = per[2] -- bottom unit_table
Line 2,723 ⟶ 2,991:
return symbol -- for exceptions that have the symbol built-in
end
end
if (unit2.symbol):find('⋅', 1, true) then
paren1, paren2 = '(', ')'
end
end
Line 2,732 ⟶ 3,003:
else
key_id2 = key_id
end
if key_id2 == 'name1' or key_id2 == 'name1_us' then
key_id2 = unit2.pername and 'pername' or key_id2 -- ukwiki has some units with a different name in "per unitname"
end
local result
Line 2,744 ⟶ 3,018:
end
if want_link and unit_table.link then
if
result = (unit1 and
else
result = (unit1 and
end
if omit_separator(result) then
Line 2,755 ⟶ 3,029:
end
if unit1 then
result = linked_id(parms, unit1, key_id, want_link, clean) .. result
if unit1.sep then
unit_table.sep = unit1.sep
Line 2,762 ⟶ 3,036:
unit_table.sep = ''
end
return result .. paren1 .. linked_id(parms, unit2, key_id2, want_link, '1') .. paren2
end
if multiplier then
Line 2,780 ⟶ 3,054:
multiplier = ''
end
local id = unit_table.fixed_name or ((varname and not abbr_on) and variable_name(clean, unit_table, exp_multiplier, key_id) or unit_table[key_id])
if omit_separator(id) then
unit_table.sep = ''
Line 2,789 ⟶ 3,063:
local before = ''
local i = unit_table.customary
if i == 1 and
i = 2 -- show "U.S." not "US"
end
Line 2,831 ⟶ 3,105:
-- id = unit name or symbol, possibly modified
-- f = true if id is a name, or false if id is a symbol
-- using
-- Result is '' if no symbol/name is to be used.
-- In addition, set unit_table.sep = ' ' or ' ' or ''
Line 2,841 ⟶ 3,115:
local inout = unit_table.inout
local info = unit_table.valinfo[which]
local lk = parms.lk
local want_link = (lk == 'on' or lk == inout)
local singular = info.singular
local want_name
local exp_multiplier
if unit_table.usename then
want_name = true
else
if parms.abbr_org == nil then
if parms.wantname then
want_name = true
Line 2,891 ⟶ 3,162:
end
end
if unit_table.engscale
-- engscale: so "|1|e3kg" gives "1 thousand kilograms" (plural)
singular = false
exp_multiplier = 10^unit_table.engscale.exponent -- '1 gram' and '1 thousand grams', for example, may use different names for the unit in some languages
end
key = (
if
key = key .. '_us'
end
Line 2,907 ⟶ 3,178:
end
unit_table.sep = ' '
key =
end
return linked_id(parms, unit_table, key, want_link, info.clean, exp_multiplier), want_name
end
local function decorate_value(parms, unit_table, which, enable_number_word)
-- If needed, update unit_table so values will be shown with extra information.
-- For consistency with the old template (but different from fmtpower),
-- the style to display powers of 10 includes "display:none" to allow some
-- browsers to copy, for example, "10³" as "10^3", rather than as "103".
-- The engscale table may have entries such as either of the following:
-- ["3"] = { "thousand", exponent = 3 },
-- ["3"] = { name1 = "A", varname = "B!C!D", exponent = 3 },
-- The first option always uses "thousand" as the exponent name.
-- The second option uses one of A, B, C, D as the exponent name, depending on the value.
local info
local engscale = unit_table.engscale
Line 2,926 ⟶ 3,202:
end
info.decorated = true
if engscale then
-- Range |10|-|20|e3km| gives '10×10³–20×10³' or '10–20 thousand'.
local inout = unit_table.inout
local abbr = parms.abbr
if (abbr == 'on' or abbr == inout) and not (unit_table.this_number_word or parms.number_word) then
info.show = info.show ..
'<span style="margin-left:0.2em">×<span style="margin-left:0.1em">' ..
from_en('10') ..
'</span></span><s style="display:none">^</s><sup>' ..
from_en(tostring(engscale.exponent)) .. '</sup>'
elseif enable_number_word then
local number_id
local name = engscale.varname and variable_name(info.clean, engscale) or engscale[1]
if parms.lk == 'on' or parms.lk == inout then
number_id = make_link(engscale.link,
else
number_id =
end
-- WP:NUMERAL recommends " " in values like "12 million".
info.show = info.show .. (parms.opt_adjectival and '-' or ' ') .. number_id
end
end
if prefix then
end
end
end
Line 2,991 ⟶ 3,268:
return preunit .. id1
end
if parms.opt_also_symbol and not composite and not parms.opt_flip then
local join1 = parms.joins[1]
if join1 == ' (' or join1 == ' [' then
parms.joins = { ' [' .. first_unit[
end
end
Line 3,005 ⟶ 3,282:
-- For simplicity and because more not needed, handle one range item only.
local prefix2 = make_id(parms, 2, first_unit) .. ' '
result = range_text(range[1], want_name, parms, result, prefix2 .. valinfo[2].show, 'in', {spaced=true})
end
return preunit .. result
Line 3,031 ⟶ 3,308:
return table.concat(parts, sep2) .. mid
end
local
parms[parms.opt_flip and 'out_range_x' or 'in_range_x'] or
(not want_name and parms.abbr_range_x)
local range = parms.range
if range and not add_unit then
unlink(first_unit)
end
local id =
local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, 'in')
if
add_unit = false
end
local result
local valinfo = first_unit.valinfo
if range then
local enable_number_word
if i == range.n then
add_unit = false
enable_number_word = true
end
if add_unit then
show = show .. first_unit.sep .. (i == 0 and id1 or make_id(parms, i+1, first_unit))
end
if i == 0 then
result = show
else
result = range_text(range[i], want_name, parms, result, show, 'in')
end
end
else
decorate_value(parms, first_unit, 1, true)
result = valinfo[1].show
end
Line 3,093 ⟶ 3,350:
-- Processing required for each output unit.
-- Return block of text to represent output (value/unit).
local inout = out_current.inout -- normally 'out' but can be 'in' for order=out
local id1, want_name = make_id(parms, 1, out_current)
local sep = out_current.sep -- set by make_id
Line 3,114 ⟶ 3,372:
if range then
-- For simplicity and because more not needed, handle one range item only.
result = range_text(range[1], want_name, parms, result, prefix .. valinfo[2].show,
end
return preunit .. result
end
local add_unit = (parms[parms.opt_flip and 'in_range_x' or 'out_range_x'] or
(not want_name and parms.abbr_range_x)) and
not parms.opt_output_number_only
local range = parms.range
if range and not add_unit then
unlink(out_current)
end
local id =
local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id,
if was_hyphenated then
add_unit = false
end
local result
local valinfo = out_current.valinfo
if range then
local
add_unit = false
enable_number_word = true
end
decorate_value(parms, out_current, i+1, enable_number_word)
local show = valinfo[i+1].show
if add_unit then
show = show .. out_current.sep .. (i == 0 and id1 or make_id(parms, i+1, out_current))
end
if i == 0 then
result = show
else
result = range_text(range[i], want_name, parms, result, show, inout)
end
end
else
decorate_value(parms, out_current, 1, true)
result = valinfo[1].show
end
Line 3,169 ⟶ 3,422:
-- for a single output (which is not a combination or a multiple);
-- or return false, t where t is an error message table.
if parms.opt_order_out and in_unit_table.unitcode == out_unit_table.unitcode then
out_unit_table.valinfo = in_unit_table.valinfo
else
out_unit_table.valinfo = collection()
for _, v in ipairs(in_unit_table.valinfo) do
local success, info = cvtround(parms, v, in_unit_table, out_unit_table)
if not success then return false, info end
out_unit_table.valinfo:add(info)
end
end
return true, process_one_output(parms, out_unit_table)
Line 3,183 ⟶ 3,439:
-- for an output which is a multiple (like 'ftin');
-- or return false, t where t is an error message table.
local inout = out_unit_table.inout -- normally 'out' but can be 'in' for order=out
local multiple = out_unit_table.multiple -- table of scaling factors (will not be nil)
local combos = out_unit_table.combination -- table of unit tables (will not be nil)
Line 3,189 ⟶ 3,446:
local disp = parms.disp
local want_name = (abbr_org == nil and (disp == 'or' or disp == 'slash')) or
not (abbr == 'on' or abbr ==
local want_link = (parms.lk == 'on' or parms.lk ==
local mid = parms.opt_flip and parms.mid or ''
local sep1 = ' '
Line 3,206 ⟶ 3,463:
local tfrac, thisvalue, strforce
local out_current = combos[i]
out_current.inout =
local scale = multiple[i]
if i == 1 then -- least significant unit ('in' from 'ftin')
Line 3,288 ⟶ 3,545:
end
local strval
local
if strforce and outvalue == 0 then
sign = '' -- any sign is in strforce
Line 3,294 ⟶ 3,551:
elseif tfrac then
local wholestr = (thisvalue > 0) and tostring(thisvalue) or nil
strval = format_fraction(parms,
else
strval = (thisvalue == 0) and from_en('0') or with_separator(parms, format(fmt, thisvalue))
if do_spell then
strval = spell_number(parms,
end
end
Line 3,321 ⟶ 3,578:
local success, result2 = make_result(valinfo[i+1])
if not success then return false, result2 end
result = range_text(range[i], want_name, parms, result, result2,
end
end
Line 3,328 ⟶ 3,585:
local function process(parms, in_unit_table, out_unit_table)
-- Return true, s, outunit where s = final wikitext result,
-- or return false, t where t is an error message table.
linked_pages = {}
local success, bad_output
local bad_input_mcode = in_unit_table.bad_mcode --
local out_unit = parms.out_unit
if out_unit == nil or out_unit == '' or type(out_unit) == 'function' then
-- out_unit can be set to a function by adjustparameters in Module:Convert/wikidata.
if bad_input_mcode or parms.opt_input_unit_only then
bad_output = ''
else
local getdef = type(out_unit) == 'function' and out_unit or get_default
success, out_unit = getdef(in_unit_table.valinfo[1].value, in_unit_table)
parms.out_unit = out_unit
if not success then
Line 3,347 ⟶ 3,605:
end
if not bad_output and not out_unit_table then
success, out_unit_table = lookup(
if success then
local mismatch = check_mismatch(in_unit_table, out_unit_table)
Line 3,357 ⟶ 3,615:
end
end
local lhs, rhs
local flipped = parms.opt_flip and not bad_input_mcode
if bad_output then
rhs = (bad_output == '') and '' or message(parms, bad_output)
elseif parms.opt_input_unit_only then
rhs = ''
else
local combos -- nil (for 'ft' or 'ftin'), or table of unit tables (for 'm ft')
if not out_unit_table.multiple then -- nil/false ('ft' or 'm ft'), or table of factors ('ftin')
combos = out_unit_table.combination
end
local frac = parms.frac -- nil or denominator of fraction for output values
if frac then
-- Apply fraction to the unit (if only one), or to non-SI units (if a combination),
-- except that if a precision is also specified, the fraction only applies to
-- the hand unit; that allows the following result:
-- {{convert|156|cm|in hand|1|frac=2}} → 156 centimetres (61.4 in; 15.1½ hands)
-- However, the following is handled elsewhere as a special case:
-- {{convert|156|cm|hand in|1|frac=2}} → 156 centimetres (15.1½ hands; 61½ in)
if combos then
local precision = parms.precision
for _, unit in ipairs(combos) do
if unit.builtin == 'hand' or (not precision and not unit.prefixes) then
unit.frac = frac
end
end
else
out_unit_table.frac = frac
end
end
local outputs = {}
local imax = combos and #combos or 1 -- 1 (single unit) or number of unit tables parms.opt_order_out = nil -- only useful with an output combination
end
if not flipped and not parms.opt_order_out then
-- Process left side first so any duplicate links (from lk=on) are suppressed
-- on right. Example: {{convert|28|e9pc|e9ly|abbr=off|lk=on}}
lhs = process_input(parms, in_unit_table)
end
for i = 1, imax do
local success, item
local out_current = combos and combos[i] or out_unit_table
out_current.inout = 'out'
if i == 1 then
if imax > 1 and out_current.builtin == 'hand' then
out_current.out_next = combos[2] -- built-in hand can influence next unit in a combination
end
if
out_current.inout = 'in'
end
end
if
success, item = make_output_multiple(parms, in_unit_table, out_current)
else
success, item = make_output_single(parms, in_unit_table, out_current)
end
if not success then return false, item end
outputs[i] = item
end
if parms.opt_order_out then
lhs = outputs[1]
table.remove(outputs, 1)
end
local sep = parms.table_joins and parms.table_joins[2] or parms.join_between
rhs = table.concat(outputs, sep)
end
if
local input = process_input(parms, in_unit_table)
else
lhs = input
end
end
if parms.join_before then
lhs = parms.join_before .. lhs
end
local wikitext
if bad_input_mcode then
if bad_input_mcode == '' then
wikitext =
else
wikitext =
end
elseif parms.table_joins then
wikitext = parms.table_joins[1] ..
else
wikitext =
end
if parms.warnings and not bad_input_mcode then
wikitext = wikitext .. parms.warnings
end
return true, get_styles(parms) .. wikitext, out_unit_table
end
local function
-- Do convert, and if needed, do it again with higher default precision.
local parms = { frame = frame or mw.getCurrentFrame() } -- will hold template arguments, after translation
set_config(confArgs)
local success,
if success then
if type(result) ~= 'table' then
return tostring(result)
end
local in_unit_table = result
local out_unit_table
for _ = 1, 2 do -- use counter so cannot get stuck repeating convert
success, result, out_unit_table = process(parms, in_unit_table, out_unit_table)
if success and parms.do_convert_again then
Line 3,482 ⟶ 3,731:
end
end
end
-- If input=x gives a problem, the result should be just the user input
-- (if x is a property like P123 it has been replaced with '').
-- An unknown input unit would display the input and an error message
-- with success == true at this point.
-- Also, can have success == false with a message that outputs an empty string.
if parms.input_text then
if success and not parms.have_problem then
return result
end
local cat
if parms.tracking then
-- Add a tracking category using the given text as the category sort key.
-- There is currently only one type of tracking, but in principle multiple
-- items could be tracked, using different sort keys for convenience.
cat = wanted_category('tracking', parms.tracking)
end
return parms.input_text .. (cat or '')
end
return success and result or message(parms, result)
end
local function main_convert(frame)
return _main_convert(frame.args, frame:getParent().args, frame)
end
local function _unit(unitcode, options)
-- Helper function for Module:Val to look up a unit.
-- Parameter unitcode must be a string to identify the wanted unit.
-- Parameter options must be nil or a table with optional fields:
-- value = number (for sort key; default value is 1)
-- scaled_top = nil for a normal unit, or a number for a unit which is
-- the denominator of a per unit (for sort key)
-- si = { 'symbol', 'link' }
-- (a table with two strings) to make an SI unit
-- that will be used for the look up
-- link = true if result should be [[linked]]
-- sort = 'on' or 'debug' if result should include a sort key in a
-- span element ('debug' makes the key visible)
-- name = true for the name of the unit instead of the symbol
-- us = true for the US spelling of the unit, if any
-- Return nil if unitcode is not a non-empty string.
-- Otherwise return a table with fields:
-- text = requested symbol or name of unit, optionally linked
-- scaled_value = input value adjusted by unit scale; used for sort key
-- sortspan = span element with sort key like that provided by {{ntsh}},
-- calculated from the result of converting value
-- to a base unit with scale 1.
-- unknown = true if the unitcode was not known
unitcode = strip(unitcode)
if unitcode == nil or unitcode == '' then
return nil
end
set_config({})
linked_pages = {}
options = options or {}
local parms = {
abbr = options.name and 'off' or 'on',
lk = options.link and 'on' or nil,
opt_sp_us = options.us and true or nil,
opt_ignore_error = true, -- do not add pages using this function to 'what links here' for Module:Convert/extra
opt_sortable_on = options.sort == 'on' or options.sort == 'debug',
opt_sortable_debug = options.sort == 'debug',
}
if options.si then
-- Make a dummy table of units (just one unit) for lookup to use.
-- This makes lookup recognize any SI prefix in the unitcode.
local symbol = options.si[1] or '?'
parms.unittable = { [symbol] = {
_name1 = symbol,
_name2 = symbol,
_symbol = symbol,
utype = symbol,
scale = symbol == 'g' and 0.001 or 1,
prefixes = 1,
default = symbol,
link = options.si[2],
}}
end
local success, unit_table = lookup(parms, unitcode, 'no_combination')
if not success then
unit_table = setmetatable({
symbol = unitcode, name2 = unitcode, utype = unitcode,
scale = 1, default = '', defkey = '', linkey = '' }, unit_mt)
end
local value = tonumber(options.value) or 1
local clean = tostring(abs(value))
local info = {
value = value,
altvalue = value,
singular = (clean == '1'),
clean = clean,
show = clean,
}
unit_table.inout = 'in'
unit_table.valinfo = { info }
local sortspan, scaled_value
if options.sort then
sortspan, scaled_value = make_table_or_sort(parms, value, info, unit_table, options.scaled_top)
end
return {
text = make_id(parms, 1, unit_table),
sortspan = sortspan,
scaled_value = scaled_value,
unknown = not success and true or nil,
}
end
return { convert = main_convert, _convert = _main_convert, _unit = _unit }
|