Module:Convert: Difference between revisions

m
1 revision imported
(update from sandbox per Template talk:Convert#Module version 11)
m (1 revision imported)
 
(15 intermediate revisions by 4 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
local ignore_extra_units -- if true, do not require the 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 spelling is wantedneeded)
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(catcatkey, catsort, want_warning)
-- Return catmessage category if it is wanted in current namespace, otherwise return nil.
-- otherwise return ''.
-- This is so tracking categories only include pages that need correction.
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]
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.
-- 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 first %s'$1' if any in message)
-- mcode[3] = 'parm2' (string to replace second %s'$2' if any in message)
-- mcode[4] = 'parm3' (string to replace third %s'$3' if any in message)
local msg = text_code.all_messages[mcode[1]]
if type(mcode) == 'table' then
local nowiki = mw.text.nowiki
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()
-- Return true if a prominent message should be shown.
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
local title = format(msg[1] or 'Missing message', parts[1], parts[2], parts[3])
not config.warnings and -- show unobtrusive warnings if config.warnings not configured
local text = msg[2] or 'Missing message'
not msg.nowarn -- but use msg settings, not standard warning, if specified
local cat = wanted_category(text_code.all_categories[msg[3]]) or ''
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 fmtkey = ispreview() and 'cvt_format_preview' or
local fmt = text_code.all_messages[msg.format or 'cvt_format'] or 'convert: bug'
(want_warning and 'cvt_format2' or msg.format or 'cvt_format')
title = title:gsub('"', '"')
local fmt = text_code.all_messages[fmtkey] or 'convert: bug'
return format(fmt, anchor, title, text, cat)
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 level < 01) then
if level <= (tonumber(configparms.warnings) or== 1)nil then
if parms.warnings == nilmessage(parms, { key, text1, text2 }, thentrue)
parms.warnings = message({ key, text1, text2 })
end
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 552 ⟶ 590:
-- 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 577 ⟶ 616:
}
 
local function make_per(unit_tableunitcode, force_sp_usunit_table, ulookup)
-- 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 = { utype = unit_table.utype, per = {} }
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 ⟶ 636:
if not success then return false, t end
result.per[i] = t
if t.sp_us then -- if the top or bottom unit forces sp=us, set the per unit to use the correct name/symbol
force_sp_us = true
end
end
end
Line 617 ⟶ 657:
result.scalemultiplier = multiplier or 1
result.vprefix = prefix or false -- set to non-nil to avoid calling __index
result.sp_us = force_sp_us
return true, setmetatable(result, unit_per_mt)
end
 
local function lookup(unitcodeparms, opt_sp_usunitcode, what, utable, fails, depth)
-- 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 opt_sp_us is true for US spelling of SI prefixes and
-- the symbol and name of the unit. If true, the result includes field
-- sp_us = true (that field may also have been in the unit definition).
-- Parameter 'what' determines whether combination units are accepted:
-- 'no_combination' : single unit only
Line 640 ⟶ 676:
-- Wikignomes may also put two spaces or "&nbsp;" in combinations, so
-- replace underscore, "&nbsp;", 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 ⟶ 689:
end
unitcode = unitcode:gsub('_', ' '):gsub('&nbsp;', ' '):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 ⟶ 699:
return false, { 'cvt_should_be', t.shouldbe }
end
local force_sp_us = opt_sp_us
if t.sp_us then
force_sp_usparms.opt_sp_us = true
opt_sp_us = true
end
local target = t.target -- nil, or unitcode is an alias for this target
if target then
local success, result = lookup(targetparms, opt_sp_ustarget, what, utable, fails, depth)
if not success then return false, result end
override_from(result, t, { 'customary', 'default', 'link', 'symbol', 'symlink' })
Line 676 ⟶ 715:
end
if t.per then
return call_make_per(t)
return make_per(t, force_sp_us, function (ucode) return lookup(ucode, opt_sp_us, 'no_combination', utable, fails, depth) end)
end
local combo = t.combination -- nil or a table of unitcodes
Line 689 ⟶ 728:
local cvt = result.combination
for i, v in ipairs(combo) do
local success, t = lookup(vparms, opt_sp_usv, multiple and 'no_combination' or 'only_multiple', utable, fails, depth)
if not success then return false, t end
cvt[i] = t
Line 696 ⟶ 735:
end
local result = shallow_copy(t)
result.sp_usunitcode = force_sp_usunitcode
if result.prefixes then
result.si_name = ''
Line 715 ⟶ 754:
if t and t.prefixes then
local result = shallow_copy(t)
result.unitcode = unitcode
if opt_sp_us then
result.sp_ussi_name = trueparms.opt_sp_us and si.name_us or si.name
end
if result.sp_us and si.name_us then
result.si_name = si.name_us
else
result.si_name = si.name
end
result.si_prefix = si.prefix or prefix
result.scale = t.scale * 10 ^ (si.exponent * t.prefixes)
Line 740 ⟶ 773:
local engscale = text_code.eng_scales[exponent]
if engscale then
local success, result = lookup(baseunitparms, opt_sp_usbaseunit, '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
Line 776 ⟶ 810:
local cvt = result.combination
for i, v in ipairs(combo) do
local success, t = lookup(vparms, opt_sp_usv, 'only_multiple', utable, fails, depth)
if not success then return false, t end
if i == 1 then
Line 802 ⟶ 836:
-- 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 = make_percall_make_per({ per = {top, bottom} }, opt_sp_us, function (ucode) return lookup(ucode, opt_sp_us, 'no_combination', utable, fails, depth) end)
if success then
return true, result
end
end
if not ignore_extra_unitsparms.opt_ignore_error and not get_range(unitcode) then
-- 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 823 ⟶ 857:
fails[unitcode] = true
local other = (utable == all_units) and extra_units or all_units
local success, result = lookup(unitcodeparms, opt_sp_usunitcode, what, other, fails, depth)
if success then
return true, result
Line 834 ⟶ 868:
local en_code = ustring.gsub(unitcode, '%d', to_en_table)
if en_code ~= unitcode then
return lookup(en_codeparms, opt_sp_usen_code, what, utable, fails, depth)
end
end
Line 929 ⟶ 963:
end
return sep .. id .. mid
end
 
local function change_sign(text)
-- Change sign of text for correct appearance because it is negated.
if text:sub(1, 1) == '-' then
return text:sub(2)
end
return '-' .. text
end
 
Line 1,020 ⟶ 1,046:
-- When using gaps, they are inserted before and after the decimal mark.
-- Separators are inserted only before the decimal mark.
-- 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)
Line 1,297 ⟶ 1,330:
-- with the hands unit (not worth adding code to enforce that).
------------------------------------------------------------------------
local numstr, whole
local leading_plus, prefix, numstr, slashes, denstr =
text:match('^%s*(%+?)%s*(.-)%s*(%d+)%s*(/+)%s*(%d+)%s*$')
Line 1,311 ⟶ 1,343:
return nil
end
local whole, wholestr
if prefix == '' then
wholestr = ''
Line 1,377 ⟶ 1,409:
while #remainder > 0 do
local ref, spaces
ref, spaces, remainder = remainder:match('^(\127UNIQ127[^\127]*UNIQ[^\127]*%-ref%-%x+%-QINU[^\127]*\127)(%s*)(.*)')
if ref then
table.insert(refs, ref)
Line 1,442 ⟶ 1,474:
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,448 ⟶ 1,480:
-- 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.opt_ri
if precision then
local fmt = '%.' .. format('%d', precision) .. 'f'
returnlocal result = fmt:format(tonumber(value) + 2e-14) -- fudge for some common cases of bad rounding
if not exponent then
singular = (tonumber(result) == 1)
end
return result
end
return default
Line 1,460 ⟶ 1,496:
local significand, exponent = clean:match('^([%d.]+)[Ee]([+%-]?%d+)')
if significand then
show = with_exponent(parms, rounded(significand, significand, exponent), exponent)
scientific = true
else
Line 1,467 ⟶ 1,503:
show = propersign .. show
if parms.opt_spell_in then
show = spell_number(parms, 'in', propersign .. rounded(cleanvalue, clean)) or show
scientific = false
end
Line 1,474 ⟶ 1,510:
end
end
local altvalue = altvalue or value
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,500 ⟶ 1,535:
local number = tonumber(to_en(text))
if number then
local integer_, fracpart = math.modf(number)
return number, (fracpart == 0)
end
Line 1,578 ⟶ 1,613:
-- 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,606 ⟶ 1,642:
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
preunit1 = PLUS
end
if trim1trim2 ~== '+' then
if trim1 == '' then
preunit1 = withspace(preunit1, 1)
return nil, nil
end
end
if trim2 == '&#32;' then -- trick to make preunit2 empty
preunit2 = nil
elseif trim2 == '' then
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
Line 1,653 ⟶ 1,698:
 
local function get_composite(parms, iparm, in_unit_table)
-- Look for a composite input unit. For example, "{{convert|1|yd|2|ft|3|in}}"
-- would result in a call to this function with
-- iparm = 3 (parms[iparm] = "2", just after the first unit)
Line 1,674 ⟶ 1,719:
end
local success
success, subunit = lookup(subcodeparms, parms.opt_sp_ussubcode, 'no_combination')
if not success then return false, subunit end -- should never occur
success, subinfo = extract_number(parms, parms[iparm])
Line 1,702 ⟶ 1,747:
composite_units[i].fixed_name = name
else
local success, alternate = lookup(unitparms, parms.opt_sp_usunit, 'no_combination')
if not success then return false, alternate end -- should never occur
alternate.inout = 'in'
Line 1,724 ⟶ 1,769:
-- Return true if successful or return false, t where t is an error message table.
currency_text = nil -- local testing can hold module in memory; must clear globals
local accept_any_text = {
input = true,
qid = true,
qual = true,
stylein = true,
styleout = true,
tracking = true,
}
if kv_pairs.adj and kv_pairs.sing then
-- For enwiki (before translation), warn if attempt to use adj and sing
Line 1,757 ⟶ 1,810:
en_value = number
else
add_warning(parms, 1, (en_name == 'frac' and 'cvt_bad_frac' or 'cvt_bad_sigfig'), loc_name .. '=' .. loc_value)
end
end
elseif accept_any_text[en_name == 'stylein' or en_name == 'styleout'] then
en_value = loc_value ~= '' and loc_value or nil -- accept non-empty user text with no validation
if 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 = text_code.en_option_value[en_name][loc_value]
Line 1,810 ⟶ 1,868:
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,816 ⟶ 1,878:
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
Line 1,957 ⟶ 2,026:
range:add(range_item)
if type(range_item) == 'table' then
-- For range "x", if append unit to some values, append it to all.
parms.is_range_x = range_item.is_range_x
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,974 ⟶ 2,046:
local function simple_get_values(parms)
-- If input is like "{{convert|valid_value|valid_unit|...}}",
-- return true, 3i, in_unit, in_unit_table
-- 3i = index in parms of whateverwhat follows valid_unit, if anything).
-- 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 andor callerreturn willfalse, reparseparm1 for caller theto inputinterpret.
-- 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 #clean > 10 or not clean:match('^[0-9.]+$') then return end
return false, clean
end
local value = tonumber(clean)
if not value then return end
Line 1,994 ⟶ 2,068:
}
local in_unit = strip(parms[2])
local success, in_unit_table = lookup(in_unitparms, parms.opt_sp_usin_unit, 'no_combination')
if not success then return end
in_unit_table.valinfo = { info }
Line 2,000 ⟶ 2,074:
end
 
local function get_parmswikidata_call(argsparms, operation, ...)
-- Return true, s where s is the result of a Wikidata operation,
-- If successful, return true, parms, unit where
-- 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,012 ⟶ 2,107:
-- whitespace entered in the template, and whitespace is used by some
-- parameters (example: the numbered parameters associated with "disp=x").
local parms = {} -- arguments passed to template, after translation
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,020 ⟶ 2,114:
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
ignore_extra_units = parms.opt_ignore_error
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,031 ⟶ 2,140:
in_unit = strip(parms[i])
i = i + 1
success, in_unit_table = lookup(in_unitparms, parms.opt_sp_usin_unit, 'no_combination')
if not success then
if in_unit == nilin_unit or then''
in_unit = ''
end
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,
defaultsymbol = "m"in_unit, defkeyname2 = "m"in_unit, linkeyutype = "m"in_unit,
utypescale = "length"1, scaledefault = 1'', bad_mcodedefkey = in_unit_table }'', unit_mt)linkey = '',
bad_mcode = in_unit_table }, unit_mt)
end
in_unit_table.valinfo = valinfo
Line 2,076 ⟶ 2,184:
end
end
local nextword = strip(parms[i])
i = i + 1
local precision, is_bad_precision
Line 2,091 ⟶ 2,199:
end
end
if word and not set_precision(nextword) then
parms.out_unit = nextparms.out_unit or word
if set_precision(strip(parms[i])) then
i = i + 1
Line 2,098 ⟶ 2,206:
end
if parms.opt_adj_mid then
nextword = parms[i]
i = i + 1
if nextword then -- mid-text words
if nextword:sub(1, 1) == '-' then
parms.mid = nextword
else
parms.mid = ' ' .. nextword
end
end
Line 2,144 ⟶ 2,252:
parms.precision = precision
end
for j = i, i + 3 do
return true, parms, in_unit_table
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,180 ⟶ 2,295:
local fudge = 1e-14 -- {{Order of magnitude}} adds this, so we do too
local prec, minprec, adjust
local utype = out_current.utype
local subunit_ignore_trailing_zero
local subunit_more_precision -- kludge for "in" used in input like "|2|ft|6|in"
Line 2,211 ⟶ 2,325:
end
if in_current.istemperature and out_current.istemperature then
-- Converting between common temperatures (°C, °F, °R, K); not keVT, MK.
-- 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,364 ⟶ 2,478:
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
local sortkey
-- 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
Line 2,381 ⟶ 2,500:
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
Line 2,401 ⟶ 2,531:
end
end
local sortspan
if sortkey and (parms.opt_sortable_debug or not parms.table_align) then
parms.join_beforesortspan = parms.opt_sortable_debug and
'<span style="border:1px solid;display:inline;" class="sortkey">' .. sortkey .. '</span>' or
'<span style="display:none" class="sortkey">' .. sortkey .. '</span>'
parms.join_before = sortspan
end
if parms.table_align then
Line 2,415 ⟶ 2,547:
parms.table_joins = joins
end
return sortspan, scaled_value
end
 
Line 2,426 ⟶ 2,559:
-- 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 true, nil if no value specified;
-- 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.
local invalue
if info then
invalue = info.value
if in_current.builtin == 'hand' then
invalue = info.altvalue
end
end
if invalue == nil or invalue == '' then
return true, nil
end
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
Line 2,461 ⟶ 2,584:
outvalue = -outvalue
end
local numerator, precision, success, show, exponent
local denominator = out_current.frac
if denominator then
Line 2,472 ⟶ 2,595:
elseif parms.opt_round then
local n = parms.opt_round
show = format('%.0f', floor((outvalue /if n) +== 0.5) * n)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
else
local inclean = info.clean
Line 2,704 ⟶ 2,836:
local linked_pages -- to record linked pages so will not link to the same page more than once
 
local function make_linkunlink(link, id, link_keyunit_table)
-- 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,711 ⟶ 2,851:
-- * 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
-- Linking with a unit uses the unit table as the link key, which fails to detect
if unit_table then
-- overlinking for conversions like the following (each links "mile" twice):
link_key = unit_table.unitcode or unit_table
-- {{convert|1|impgal/mi|USgal/mi|lk=on}}
else
-- {{convert|1|l/km|impgal/mi USgal/mi|lk=on}}
link_key = link
link_key = link_key or link -- use key if given (the key, but not the link, may be known when need to cancel a link record)
end
if not link or link == '' or linked_pages[link_key] then
return id
Line 2,759 ⟶ 2,900:
else
i = 3
end
if i > 1 and varname == 'pl' then
i = i - 1
end
vname = split(unit_table.varname, '!')[i]
Line 2,775 ⟶ 2,919:
end
 
local function linked_id(parms, unit_table, key_id, want_link, clean)
-- Return final unit id (symbol or name), optionally with a wikilink,
-- and update unit_table.sep if required.
Line 2,789 ⟶ 2,933:
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,800 ⟶ 2,945:
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,822 ⟶ 2,970:
if want_link and unit_table.link then
if abbr_on or not varname then
result = (unit1 and linked_id(parms, unit1, key_id, false, clean) or '') .. result .. linked_id(parms, unit2, key_id2, false, '1')
else
result = (unit1 and variable_name(clean, unit1) or '') .. result .. variable_name('1', unit2)
Line 2,832 ⟶ 2,980:
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,839 ⟶ 2,987:
unit_table.sep = ''
end
return result .. paren1 .. linked_id(parms, unit2, key_id2, want_link, '1') .. paren2
end
if multiplier then
Line 2,866 ⟶ 3,014:
local before = ''
local i = unit_table.customary
if i == 1 and unit_tableparms.sp_usopt_sp_us then
i = 2 -- show "U.S." not "US"
end
Line 2,908 ⟶ 3,056:
-- id = unit name or symbol, possibly modified
-- f = true if id is a name, or false if id is a symbol
-- using 1stthe orvalue 2ndfor valuesindex ('which)', and for 'in' or 'out' (unit_table.inout).
-- Result is '' if no symbol/name is to be used.
-- In addition, set unit_table.sep = ' ' or '&nbsp;' or ''
Line 2,920 ⟶ 3,068:
local abbr_org = parms.abbr_org
local adjectival = parms.opt_adjectival
local disp = parms.disp
local lk = parms.lk
local want_link = (lk == 'on' or lk == inout)
Line 2,968 ⟶ 3,115:
end
end
if unit_table.engscale or parms.is_range_x then
-- engscale: so "|1|e3kg" gives "1 thousand kilograms" (plural)
-- is_range_x: so "|0.5|x|0.9|mi" gives "0.5 by 0.9 miles" (plural)
singular = false
end
key = (adjectival or singular) and 'name1' or 'name2'
if unit_tableparms.sp_usopt_sp_us then
key = key .. '_us'
end
Line 2,984 ⟶ 3,130:
end
unit_table.sep = '&nbsp;'
key = unit_tableparms.sp_usopt_sp_us and 'sym_us' or 'symbol'
end
return linked_id(parms, unit_table, key, want_link, info.clean), want_name
end
 
local function decorate_value(parms, unit_table, which, 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),
Line 3,006 ⟶ 3,152:
local inout = unit_table.inout
local abbr = parms.abbr
if (abbr == 'on' or abbr == inout) and not parms.number_word then
info.show = info.show ..
'<span style="margin-left:0.2em">×<span style="margin-left:0.1em">' ..
Line 3,012 ⟶ 3,158:
'</span></span><s style="display:none">^</s><sup>' ..
from_en(tostring(engscale.exponent)) .. '</sup>'
elseif number_word then
else
local number_id
local lk = parms.lk
Line 3,068 ⟶ 3,214:
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[first_unitparms.sp_usopt_sp_us and 'sym_us' or 'symbol'] .. ']' .. join1 , parms.joins[2] }
end
end
Line 3,108 ⟶ 3,254:
return table.concat(parts, sep2) .. mid
end
local result,add_unit = (parms.abbr == 'mos') or
parms[parms.opt_flip and 'out_range_x' or 'in_range_x'] or
local abbr = parms.abbr
(not want_name and parms.abbr_range_x)
local range = parms.range
if range and not add_unit then
unlink(first_unit)
mos = (abbr == 'mos')
if not (mos or (parms.is_range_x and not want_name)) then
linked_pages[first_unit] = nil -- so the second and only id will be linked, if wanted
end
end
local id = (range == nil) and id1 or make_id(parms, 2range.n + 1, first_unit) or id1
local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, 'in')
if mos and was_hyphenated then
add_unit = false
mos = false -- suppress repeat of unit in a range
if linked_pages[first_unit] then
linked_pages[first_unit] = nil
id = make_id(parms, 2, first_unit)
extra = hyphenated_maybe(parms, want_name, sep, id, 'in')
end
end
local result
local valinfo = first_unit.valinfo
if range then
iffor range.ni == 10, range.n thendo
local number_word
-- Like {{convert|1|x|2|ft}} (one range item; two values).
if i == range.n then
-- Do what old template did.
add_unit = false
local sep1 = first_unit.sep
if number_word mos= thentrue
end
decorate_value(parms, in_current, 1)
decorate_value(parms, in_currentfirst_unit, 2i+1, number_word)
resultlocal show = valinfo[i+1].show .. sep1 .. id1
if add_unit then
elseif parms.is_range_x and not want_name then
show = show .. first_unit.sep .. (i == 0 and id1 or make_id(parms, i+1, first_unit))
if abbr == 'in' or abbr == 'on' then
end
decorate_value(parms, in_current, 1)
if i == 0 then
end
result = show
decorate_value(parms, in_current, 2)
result = valinfo[1].show .. sep1 .. id1
else
result = range_text(range[i], want_name, parms, result, show, 'in')
if abbr == 'in' or abbr == 'on' then
decorate_value(parms, in_current, 1)
end
decorate_value(parms, in_current, 2)
result = valinfo[1].show
end
result = range_text(range[1], want_name, parms, result, valinfo[2].show, 'in')
else
-- Like {{convert|1|x|2|x|3|ft}} (two or more range items): simplify.
decorate_value(parms, in_current, 1)
result = valinfo[1].show
for i = 1, range.n do
decorate_value(parms, in_current, i+1)
result = range_text(range[i], want_name, parms, result, valinfo[i+1].show, 'in')
end
end
else
decorate_value(parms, first_unit, 1, true)
result = valinfo[1].show
end
Line 3,170 ⟶ 3,296:
-- 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,191 ⟶ 3,318:
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, 'out'inout)
end
return preunit .. result
end
local add_unit = (parms[parms.opt_flip and 'in_range_x' or 'out_range_x'] or
local result
(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)
if not (parms.is_range_x and not want_name) then
linked_pages[out_current] = nil -- so the second and only id will be linked, if wanted
end
end
local id = (range == nil) and id1 or make_id(parms, 2range.n + 1, out_current) or id1
local extra, was_hyphenated = hyphenated_maybe(parms, want_name, sep, id, 'out'inout)
if was_hyphenated then
add_unit = false
end
local result
local valinfo = out_current.valinfo
if range then
iffor range.ni == 10, range.n thendo
local sep1 = out_current.sepnumber_word
localif abbri == parmsrange.abbrn then
add_unit = false
if parms.is_range_x and not want_name then
number_word = true
if abbr == 'out' or abbr == 'on' then
end
decorate_value(parms, out_current, 1)
decorate_value(parms, out_current, i+1, number_word)
end
local show = valinfo[i+1].show
decorate_value(parms, out_current, 2)
if add_unit then
result = valinfo[1].show .. sep1 .. id1
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)
if abbr == 'out' or abbr == 'on' then
decorate_value(parms, out_current, 1)
end
decorate_value(parms, out_current, 2)
result = valinfo[1].show
end
result = range_text(range[1], want_name, parms, result, valinfo[2].show, 'out')
else
-- Like {{convert|1|x|2|x|3|ft}} (two or more range items): simplify.
decorate_value(parms, out_current, 1)
result = valinfo[1].show
for i = 1, range.n do
decorate_value(parms, out_current, i+1)
result = range_text(range[i], want_name, parms, result, valinfo[i+1].show, 'out')
end
end
else
decorate_value(parms, out_current, 1, true)
result = valinfo[1].show
end
Line 3,246 ⟶ 3,368:
-- 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 = collection()
out_unit_table.valinfo = in_unit_table.valinfo
local range = parms.range
else
for i = 1, (range and (range.n + 1) or 1) do
out_unit_table.valinfo = collection()
local success, info = cvtround(parms, in_unit_table.valinfo[i], in_unit_table, out_unit_table)
for _, v in ipairs(in_unit_table.valinfo) do
if not success then return false, info end
local success, info = cvtround(parms, v, in_unit_table, out_unit_table)
out_unit_table.valinfo:add(info)
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,260 ⟶ 3,385:
-- 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,266 ⟶ 3,392:
local disp = parms.disp
local want_name = (abbr_org == nil and (disp == 'or' or disp == 'slash')) or
not (abbr == 'on' or abbr == 'out'inout or abbr == 'mos')
local want_link = (parms.lk == 'on' or parms.lk == 'out'inout)
local mid = parms.opt_flip and parms.mid or ''
local sep1 = '&nbsp;'
Line 3,283 ⟶ 3,409:
local tfrac, thisvalue, strforce
local out_current = combos[i]
out_current.inout = 'out'inout
local scale = multiple[i]
if i == 1 then -- least significant unit ('in' from 'ftin')
Line 3,365 ⟶ 3,491:
end
local strval
local inoutspell_inout = (i == #combos or outvalue == 0) and 'out'inout or '' -- trick so the last value processed (first displayed) has uppercase, if requested
if strforce and outvalue == 0 then
sign = '' -- any sign is in strforce
Line 3,371 ⟶ 3,497:
elseif tfrac then
local wholestr = (thisvalue > 0) and tostring(thisvalue) or nil
strval = format_fraction(parms, inoutspell_inout, false, wholestr, tfrac.numstr, tfrac.denstr, do_spell)
else
strval = (thisvalue == 0) and from_en('0') or with_separator(parms, format(fmt, thisvalue))
if do_spell then
strval = spell_number(parms, inoutspell_inout, strval) or strval
end
end
Line 3,398 ⟶ 3,524:
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, 'out'inout)
end
end
Line 3,405 ⟶ 3,531:
 
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 -- falsenil if input unit is a valid convert unit
local invalue1 = in_unit_table.valinfo[1].value
local out_unit = parms.out_unit
if out_unit == nil or out_unit == '' or type(out_unit) == 'function' then
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(invalue1, 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,424 ⟶ 3,550:
end
if not bad_output and not out_unit_table then
success, out_unit_table = lookup(out_unitparms, parms.opt_sp_usout_unit, 'any_combination')
if success then
local mismatch = check_mismatch(in_unit_table, out_unit_table)
Line 3,434 ⟶ 3,560:
end
end
local lhs, rhs
local flipped = parms.opt_flip and not bad_input_mcode
if bad_output then
local parts = {}
rhs = (bad_output == '') and '' or message(parms, bad_output)
for part = 1, 2 do
elseif parms.opt_input_unit_only then
-- The LHS (parts[1]) is normally the input, but is the output if flipped.
rhs = ''
-- Process LHS first so it will be linked, if wanted.
else
-- Linking to the same item is suppressed in the RHS to avoid overlinking.
iflocal (partcombos == 1-- andnil not(for 'ft' or flipped'ftin'), or (parttable ==of 2unit andtables flipped)(for then'm ft')
if not out_unit_table.multiple then -- nil/false ('ft' or 'm ft'), or table of factors ('ftin')
parts[part] = process_input(parms, in_unit_table)
combos = out_unit_table.combination
elseif bad_output then
end
parts[part] = (bad_output == '') and '' or message(bad_output)
local frac = parms.frac -- nil or denominator of fraction for output values
else
if frac then
local outputs = {}
local-- combosApply fraction --to nilthe unit (forif 'ft'only or 'ftin'one), or tableto ofnon-SI unit tablesunits (forif 'ma ft'combination),
-- except that if a precision is also specified, the fraction only applies to
if not out_unit_table.multiple then -- nil/false ('ft' or 'm ft'), or table of factors ('ftin')
-- the hand unit; that allows the following result:
combos = out_unit_table.combination
-- {{convert|156|cm|in hand|1|frac=2}} → 156 centimetres (61.4 in; 15.1½ hands)
end
-- However, the following is handled elsewhere as a special case:
local frac = parms.frac -- nil or denominator of fraction for output values
-- {{convert|156|cm|hand in|1|frac=2}} → 156 centimetres (15.1½ hands; 61½ in)
if frac then
if combos then
-- Apply fraction to the unit (if only one), or to non-SI units (if a combination),
local precision = parms.precision
-- except that if a precision is also specified, the fraction only applies to
--for the hand_, unit; that allows thein followingipairs(combos) result:do
if unit.builtin == 'hand' or (not precision and not unit.prefixes) then
-- {{convert|156|cm|in hand|1|frac=2}} → 156 centimetres (61.4 in; 15.1½ hands)
unit.frac = frac
-- 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
else
out_unit_table.frac = frac
end
end
local out_first
local outputs = {}
local imax = combos and #combos or 1 -- 1 (single unit) or number of unit tables
local imax = combos and #combos or 1 -- 1 (single unit) or number of unit tables
for i = 1, imax do
if imax == 1 then
local success, item
parms.opt_order_out = nil -- only useful with an output combination
local out_current = combos and combos[i] or out_unit_table
end
out_current.inout = 'out'
if inot ==flipped 1and not parms.opt_order_out then
-- Process left side first so any duplicate links (from lk=on) are suppressed
out_first = out_current
-- on right. Example: {{convert|28|e9pc|e9ly|abbr=off|lk=on}}
if imax > 1 and out_current.builtin == 'hand' then
lhs = process_input(parms, in_unit_table)
out_current.out_next = combos[2] -- built-in hand can influence next unit in a combination
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_currentparms.multipleopt_order_out then
out_current.inout = 'in'
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
table.insert(outputs, item)
end
if parmsout_current.opt_input_unit_onlymultiple then
success, item = make_output_multiple(parms, in_unit_table, out_current)
parts[part] = ''
else
success, item = make_output_single(parms, in_unit_table, out_current)
local sep = parms.table_joins and parms.table_joins[2] or parms.join_between
parts[part] = table.concat(outputs, sep)
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 flipped or not lhs then
local input = process_input(parms, in_unit_table)
if flipped then
lhs = rhs
rhs = input
else
lhs = input
end
end
if parms.join_before then
parts[1]lhs = parms.join_before .. parts[1]lhs
end
local wikitext
if bad_input_mcode then
if bad_input_mcode == '' then
wikitext = parts[1]lhs
else
wikitext = parts[1]lhs .. message(parms, bad_input_mcode)
end
elseif parms.table_joins then
wikitext = parms.table_joins[1] .. parts[1]lhs .. parms.table_joins[2] .. parts[2]rhs
else
wikitext = parts[1]lhs .. parms.joins[1] .. parts[2]rhs .. parms.joins[2]
end
if parms.warnings and not bad_input_mcode then
Line 3,520 ⟶ 3,659:
local function main_convert(frame)
-- Do convert, and if needed, do it again with higher default precision.
local parms = { frame = frame } -- will hold template arguments, after translation
set_config(frame.args)
local success, result = get_parms(parms, out_unit_tableframe:getParent().args)
local success, parms, in_unit_table = get_parms(frame:getParent().args)
if success then
if type(result) ~= 'table' then
for i = 1, 2 do -- use counter so cannot get stuck repeating convert
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,532 ⟶ 3,676:
end
end
else
result = parms
end
-- If input=x gives a problem, the result should be just the user input
if success then
-- (if x is a property like P123 it has been replaced with '').
return result
-- 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 _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, _unit = _unit }