Module:Convert: Difference between revisions

Content deleted Content added
move arg extraction to its own function to allow _convert() to be called from other lua modules
 
(12 intermediate revisions by 2 users not shown)
Line 259:
end
 
local function wanted_category(catcatkey, catsort, want_warning)
-- Return catmessage category if it is wanted in current namespace,
-- otherwise return nil''.
local cat
-- This is so tracking categories only include pages that need correction.
local title = mw.title.getCurrentTitle()
if title then
Line 268 ⟶ 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]
return cat
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.
Line 341 ⟶ 347:
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(text_code.all_categories[msg[3], mcode[2]), or ''want_warning)
local anchor = msg[4] or ''
local fmtkey = ispreview() and 'cvt_format_preview' or
(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)
Line 354 ⟶ 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 level < 01) then
if level <= (tonumber(configparms.warnings) or== 1)nil then
if parms.warnings == nilmessage(parms, { key, text1, text2 }, thentrue)
parms.warnings = message(parms, { key, text1, text2 })
end
end
end
Line 380 ⟶ 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 402 ⟶ 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 302402,499 feet
-- mach_table[a + 4] = s where
-- a = (altitude / 5000) rounded to nearest integer (-3 to 6080)
-- s = speed of sound (mph) at that altitude
-- LATER: Should calculate result from an interpolation between the next
Line 414 ⟶ 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.10, -- 31 to 40
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 426 ⟶ 437:
if a < -3 then
a = -3
elseif a > 6080 then
a = 6080
end
return mach_table[a + 4] * 0.44704 -- mph converted to m/s
Line 433 ⟶ 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 535 ⟶ 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 581 ⟶ 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., and for a symbol
-- this is only called from get_default() for default_exceptions.
__index = function (self, key)
local value
Line 696 ⟶ 731:
local success, result = lookup(parms, target, what, utable, fails, depth)
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 749 ⟶ 784:
result.scale = t.scale * 10 ^ (si.exponent * t.prefixes)
return true, setmetatable(result, unit_prefixed_mt)
end
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 has_plus = unitcode:find('+', 1, true)
if not has_plus then
local exponent, baseunit = unitcode:match('^e(%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
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 780 ⟶ 793:
local err_is_fatal
local combo = collection()
if has_plusunitcode:find('+', 1, true) then
err_is_fatal = true
for item in (unitcode .. '+'):gmatch('%s*(.-)%s*%+') do
Line 817 ⟶ 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 1,110 ⟶ 1,146:
local fracfmt = {
{ -- Like {{frac}} (fraction slash).
'<span class="frac">{SIGN}<span class="num">{NUM}</span>&frasl;<span class="den">{DEN}</span></span>', -- 1/2
-- 1/2 : sign, numerator, denominator
'<span class="frac">{SIGN}{WHOLE}<span class="sr-only">+</span><span class="num">{NUM}</span>&frasl;<span class="den">{DEN}</span></span>', -- 1+2/3
-- 1+2/3 : signed_wholenumber, numerator, denominator
style = 'frac',
'<span class="frac nowrap">%s<sup>%s</sup>&frasl;<sub>%s</sub></span>',
'<span class="frac nowrap">%s<span class="visualhide">&nbsp;</span><sup>%s</sup>&frasl;<sub>%s</sub></span>',
},
{ -- 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
-- 1//2 : sign, numerator, denominator (sign should probably be before the fraction, but then it can wrap, and html is already too long)
'<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
-- 1+2//3 : signed_wholenumber, numerator, denominator
style = 'sfrac',
'<span class="sfrac nowrap" style="display:inline-block; vertical-align:-0.5em; font-size:85%%; text-align:center;"><span style="display:block; line-height:1em; padding:0 0.1em;">%s%s</span><span class="visualhide">/</span><span style="display:block; line-height:1em; padding:0 0.1em; border-top:1px solid;">%s</span></span>',
'<span class="sfrac nowrap">%s<span class="visualhide">&nbsp;</span><span style="display:inline-block; vertical-align:-0.5em; font-size:85%%; text-align:center;"><span style="display:block; line-height:1em; padding:0 0.1em;">%s</span><span class="visualhide">/</span><span style="display:block; line-height:1em; padding:0 0.1em; border-top:1px solid;">%s</span></span></span>',
},
}
Line 1,133 ⟶ 1,167:
wholestr = nil
end
local substitute = {
if wholestr then
SIGN = negative and MINUS or '',
local decorated = with_separator(parms, wholestr)
WHOLE = wholestr and with_separator(parms, wholestr),
if negative then
NUM = from_en(numstr),
decorated = MINUS .. decorated
DEN = from_en(denstr),
end
}
local fmt = fracfmt[style][2]
wikitext = format(fmt,fracfmt[style][wholestr decorated,and from_en2 or 1]:gsub(numstr'{(%u+)}', from_en(denstr)substitute)
else
local sign = negative and MINUS or ''
wikitext = format(fracfmt[style][1], sign, from_en(numstr), from_en(denstr))
end
if do_spell then
if negative then
Line 1,152 ⟶ 1,182:
end
end
wikitextlocal s = spell_number(parms, inout, wholestr, numstr, denstr) or wikitext
if s then
return s
end
end
add_style(parms, fracfmt[style].style)
return wikitext
end
Line 1,372 ⟶ 1,406:
-- Before processing, the input text is cleaned:
-- * Any thousand separators (valid or not) are removed.
-- * Any sign (andis optionalreplaced followingwith '-' (if whitespacenegative) isor replaced'' with(otherwise).
-- '-' (if negative) or '' (otherwise).
-- That replaces Unicode minus with '-'.
-- If successful, the returned info table contains named fields:
Line 1,433 ⟶ 1,466:
local valstr
for _, prefix in ipairs({ '-', MINUS, '&minus;' }) do
-- Including '-' meanssets inputsisnegative likein '-case 2'input (withis space)a arefraction accepted aslike '-2-3/4'.
-- It also sets isnegative in case input is a fraction like '-2-3/4'.
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,520 ⟶ 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 no separators, no Unicode minus, and no fraction.
if text then
local number = tonumber(to_en(text))
Line 1,603 ⟶ 1,638:
-- p2 is text to insert before the output unit
-- p1 or p2 may be nil to mean "no preunit"
-- Using '+ ' gives output like "5+ feet" (no precedingspace before, but space after).
local function withspace(text, iwantboth)
-- InsertReturn spacetext atwith beginningspace ifbefore i == 1and, or at end if i ==wantboth, -1after.
-- However, no space is insertedadded if there is a space or '&nbsp;' or '-'
-- or '-' at that position ('-' is for adjectival text).
-- There is also no space if text starts with '&'
local current = text:sub(i, i)
-- (e.g. '&deg;' would display a degree symbol with no preceding space).
if current == ' ' or current == '-' then
returnlocal char = text:sub(1, 1)
if char == '&' then
return text -- an html entity can be used to specify the exact display
end
if inot (char == ' ' or char == '-' or char == 1'+') then
currenttext = text:sub(1,' 6)' .. text
else
current = text:sub(-6, -1)
end
if current == '&nbsp;'wantboth then
returnchar = text:sub(-1, -1)
if not (char == ' ' or char == '-' or text:sub(-6, -1) == '&nbsp;') then
text = text .. ' '
end
end
return text
if i == 1 then
return ' ' .. text
end
return text .. ' '
end
local PLUS = '+ '
preunit1 = preunit1 or ''
local trim1 = strip(preunit1)
Line 1,631 ⟶ 1,667:
return nil
end
if trim1 == '+' then
return withspace(withspace(preunit1, 1), -1)
return PLUS
end
return withspace(preunit1, true)
end
preunit1 = withspace(preunit1)
preunit2 = preunit2 or ''
local trim2 = strip(preunit2)
if trim1 == '' and trim2 == '+' then
if trim2 == '' or trim2 == '+' then
return nil, nil
return PLUS, PLUS
end
end
if trim1 ~= '+' then
preunit1 = withspace(preunit1, 1)PLUS
end
if trim2 == '&#32;' then -- trick to make preunit2 empty
preunit2if trim1 == '' nilthen
return nil, nil
elseif trim2 == '' then
end
preunit2 = preunit1
elseif trim2 ~== '+' then
preunit2 = withspace(preunit2, 1)PLUS
elseif trim2 == '&#32;' 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,671 ⟶ 1,717:
end
end
if rtext == '–' and (options.spaced or after:sub(1, #MINUS) == MINUS) then
rtext = '&nbsp;– '
end
Line 1,757 ⟶ 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_nameen_value == '$INTEGER' orthen en_name ==-- 'frac'altitude_ft, oraltitude_m, en_namefrac, == 'sigfig' then
en_value = nil
if loc_value == '' 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
else
local minimum
local number, is_integer = get_number(loc_value)
if en_name == 'fracsigfig' then
minimum = 1
elseif en_name == 'frac' then
minimum = 2
if number and number < 0 then
Line 1,777 ⟶ 1,824:
end
else
minimum = 1-1e6
end
if number and is_integer and number >= minimum then
en_value = number
else
local m
add_warning(parms, 1, (en_name == 'frac' and 'cvt_bad_frac' or 'cvt_bad_sigfig'), loc_value)
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_nameen_value == 'styleinTEXT' orthen en_name ==-- 'styleout'$, orinput, en_name == 'qid', orqual, en_namestylein, ==styleout, 'input' thentracking
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 == 'inputqual') 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.
Line 1,793 ⟶ 1,853:
end
else
en_value = text_code.en_option_value[en_name]en_value[loc_value]
if en_value and en_value:sub(-1) == '?' then
en_value = en_value:sub(1, -2)
Line 2,025 ⟶ 2,085:
-- Testing shows this function is successful for 96% of converts in articles,
-- and that on average it speeds up converts by 8%.
if parms.opt_ri or parms.opt_spell_in then return end
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
Line 2,046 ⟶ 2,105:
end
 
local function wikidata_call(parms, operation, ...)
-- Return true, s where s is the result of a Wikidata operation,
-- or return false, t where t is an error message table.
Line 2,057 ⟶ 2,116:
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' }
Line 2,088 ⟶ 2,151:
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
Line 2,142 ⟶ 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.
-- and there is no way to specify an altitude for the output unit.
local success, info
-- Could put more code in this function to get any output unit and check for
success = tonumber(parms[i]) -- this will often work and will give correct result for values like 2e4 without forcing output scientific notation
-- an altitude following that unit.
if success then
local success, info = extract_number(parms, parms[i], false, true)
info = { value = success }
else
success, info = extract_number(parms, parms[i], false, true)
end
if success then
i = i + 1
Line 2,167 ⟶ 2,234:
end
end
if word and not set_precision(word) then
parms.out_unit = parms.out_unit or word
if set_precision(strip(parms[i])) then
i = i + 1
Line 2,219 ⟶ 2,286:
else
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
Line 2,367 ⟶ 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
local adjust
-- 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 = speed_of_sound(in_current.altitude)spd
adjustreturn =invalue outscale* (inscale / 0.1outscale)
else
outscale = speed_of_sound(out_current.altitude)
adjust = 0.1 / inscale
end
outscale = spd
local adjust = 0.1 / inscale
return true, {
outvalue = invalue * (inscale / outscale),
Line 2,493 ⟶ 2,573:
end
local sortspan
if sortkey and (parms.opt_sortable_debug or not parms.table_align) then
sortspan = parms.opt_sortable_debug and
'<span data-sort-value="' .. sortkey .. '♠"><span style="border:1px solid;display:inline;" class="sortkey">' .. sortkey .. '♠</span></span>' or
'<span styledata-sort-value="display:none" class="sortkey">' .. 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 sort = sortkey and ' data-sort-value="' .. sortkey .. '"' or ''
local joins = {}
for i = 1, 2 do
Line 2,566 ⟶ 2,654:
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,834 ⟶ 2,925:
end
 
local function variable_name(clean, unit_table, exp_multiplier, key_id)
-- For slwiki, aA unit name dependsmay depend on the value in some languages.
-- Parameter clean is the unsigned rounded value in en digits, as a string.
-- It may represent a number ("1.0") or a fraction ("1+2/3").
-- Value Source Example for "m"
-- In varname, fields are separated with "!" and are not empty.
-- integer 1: name1 meter (also is the name of the unit)
-- integer 2: var{1} metra
-- integer 3 and 4: var{2} metri
-- integer else: var{3} metrov (0 and 5 or more)
-- real/fraction: var{4} metra
-- var{i} means the i'th field in unit_table.varname if it exists and has
-- an i'th field, otherwise name2.
-- 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
local vname
if clean == '1'exp_multiplier then
clean = exp_multiplier -- force selection of name for a large integer
vname = unit_table.name1
elseif unit_table.varname then
local i
if clean == '2' then
i = 1
elseif clean == '3' or clean == '4' then
i = 2
elseif clean:find('.', 1, true) then
i = 4
else
clean = 34.5 -- force selection of name for a float value
i = 3
end
else
vname = split(unit_table.varname, '!')[i]
clean = tonumber(clean) * (exp_multiplier or 1)
end
local name1, vname
if vname then
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,872 ⟶ 2,961:
vname = si_name .. vname
end
return vname
end
return unit_table.name2vname
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,891 ⟶ 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,902 ⟶ 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,911 ⟶ 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,923 ⟶ 3,018:
end
if want_link and unit_table.link then
if abbr_onvarname orand not varnameabbr_on then
result = (unit1 and linked_idvariable_name(parmsclean, unit1, key_id, false, cleanexp_multiplier) or '') .. result .. linked_idvariable_name(parms'1', unit2, key_id2exp_multiplier, false, '1'key_id2)
else
result = (unit1 and variable_namelinked_id(cleanparms, unit1, key_id, false, clean) or '') .. result .. variable_namelinked_id('1'parms, unit2, key_id2, false, '1')
end
if omit_separator(result) then
Line 2,941 ⟶ 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,959 ⟶ 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 3,020 ⟶ 3,115:
local inout = unit_table.inout
local info = unit_table.valinfo[which]
local abbr_org = parms.abbr_org
local adjectival = parms.opt_adjectival
local lk = parms.lk
local want_link = (lk == 'on' or lk == inout)
local usename = unit_table.usename
local singular = info.singular
local want_name
local exp_multiplier
if usename then
if unit_table.usename then
want_name = true
else
if parms.abbr_org == nil then
if parms.wantname then
want_name = true
Line 3,072 ⟶ 3,165:
-- 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 = (adjectivalparms.opt_adjectival or singular) and 'name1' or 'name2'
if parms.opt_sp_us then
key = key .. '_us'
Line 3,086 ⟶ 3,180:
key = parms.opt_sp_us and 'sym_us' or 'symbol'
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, number_wordenable_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 3,104 ⟶ 3,203:
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 number_wordenable_number_word then
local number_id
local name = engscale.varname and variable_name(info.clean, engscale) or engscale[1]
local lk = parms.lk
if parms.lk == 'on' or parms.lk == inout then
number_id = make_link(engscale.link, engscale[1]name)
else
number_id = engscale[1]name
end
-- WP:NUMERAL recommends "&nbsp;" in values like "12 million".
Line 3,168 ⟶ 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
Line 3,182 ⟶ 3,282:
-- For simplicity and because more not needed, handle one range item only.
local prefix2 = make_id(parms, 2, first_unit) .. '&nbsp;'
result = range_text(range[1], want_name, parms, result, prefix2 .. valinfo[2].show, 'in', {spaced=true})
end
return preunit .. result
Line 3,224 ⟶ 3,324:
if range then
for i = 0, range.n do
local number_wordenable_number_word
if i == range.n then
add_unit = false
number_wordenable_number_word = true
end
decorate_value(parms, first_unit, i+1, number_wordenable_number_word)
local show = valinfo[i+1].show
if add_unit then
Line 3,272 ⟶ 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, inout, {spaced=true})
end
return preunit .. result
Line 3,292 ⟶ 3,392:
if range then
for i = 0, range.n do
local number_wordenable_number_word
if i == range.n then
add_unit = false
number_wordenable_number_word = true
end
decorate_value(parms, out_current, i+1, number_wordenable_number_word)
local show = valinfo[i+1].show
if add_unit then
Line 3,478 ⟶ 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, inout, {spaced=true})
end
end
Line 3,491 ⟶ 3,591:
local bad_input_mcode = in_unit_table.bad_mcode -- nil if input unit is a valid convert unit
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 = get_default(in_unit_table.valinfo[1].value, in_unit_table)
success, out_unit = getdef(in_unit_table.valinfo[1].value, in_unit_table)
parms.out_unit = out_unit
if not success then
Line 3,607 ⟶ 3,709:
wikitext = wikitext .. parms.warnings
end
return true, get_styles(parms) .. wikitext, out_unit_table
end
 
local function main_convert_main_convert(confArgs, parmsArgs, frame)
-- 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(frame.argsconfArgs)
local success, result = get_parms(parms, frame:getParent().argsparmsArgs)
if success then
if type(result) ~= 'table' then
Line 3,634 ⟶ 3,736:
-- 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 tothat outputoutputs an empty string.
if successparms.input_text then
if parms.have_problemsuccess and not parms.input_texthave_problem then
return parms.input_textresult
end
local cat
return result
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 parms.input_textsuccess and parms.input_textresult or message(parms, result)
end
 
local function main_convert(frame)
return _main_convert(frame.args, frame:getParent().args, frame)
end
 
Line 3,726 ⟶ 3,839:
end
 
return { convert = main_convert, _convert = _main_convert, _unit = _unit }