Wiktionary siwiktionary https://si.wiktionary.org/wiki/%E0%B7%80%E0%B7%92%E0%B6%9A%E0%B7%8A%E0%B7%82%E0%B6%B1%E0%B6%BB%E0%B7%92:%E0%B6%B8%E0%B7%94%E0%B6%BD%E0%B7%8A_%E0%B6%B4%E0%B7%92%E0%B6%A7%E0%B7%94%E0%B7%80 MediaWiki 1.48.0-wmf.4 case-sensitive මාධ්‍යය විශේෂ සාකච්ඡාව පරිශීලක පරිශීලක සාකච්ඡාව වික්ෂනරි වික්ෂනරි සාකච්ඡාව ගොනුව ගොනුව සාකච්ඡාව මාධ්‍යවිකි මාධ්‍යවිකි සාකච්ඡාව සැකිල්ල සැකිලි සාකච්ඡාව උදවු උදවු සාකච්ඡාව ප්‍රවර්ගය ප්‍රවර්ග සාකච්ඡාව TimedText TimedText talk Module Module talk Event Event talk Module:parameters 828 4890 239027 238170 2026-11-09T01:06:44Z en>Benwing2 0 convert third argument in `process` to `props`, and add support for `allow_params` 239027 Scribunto text/plain --[==[TODO: * Change certain flag names, as some are misnomers: * Change `allow_holes` to `keep_holes`, because it's not the inverse of `disallow_holes`. * Change `allow_empty` to `keep_empty`, as it causes them to be kept as "" instead of deleted. * Sort out all the internal error calls. Manual error(format()) calls are used when certain parameters shouldn't be dumped, so find a way to avoid that. ]==] local export = {} local collation_module = "Module:collation" local families_module = "Module:families" local functions_module = "Module:fun" local gender_and_number_utilities_module = "Module:gender and number utilities" local labels_module = "Module:labels" local languages_module = "Module:languages" local math_module = "Module:math" local pages_module = "Module:pages" local parameters_finalize_set_module = "Module:parameters/finalizeSet" local parameters_track_module = "Module:parameters/track" local parse_utilities_module = "Module:parse utilities" local references_module = "Module:references" local scribunto_module = "Module:Scribunto" local scripts_module = "Module:scripts" local string_utilities_module = "Module:string utilities" local table_module = "Module:table" local wikimedia_languages_module = "Module:wikimedia languages" local yesno_module = "Module:yesno" local mw = mw local mw_title = mw.title local string = string local table = table local dump = mw.dumpObject local find = string.find local format = string.format local gsub = string.gsub local insert = table.insert local ipairs = ipairs local list_to_text = mw.text.listToText local make_title = mw_title.makeTitle local match = string.match local max = math.max local new_title = mw_title.new local next = next local pairs = pairs local pcall = pcall local require = require local sub = string.sub local tonumber = tonumber local type = type local unpack = unpack or table.unpack -- Lua 5.2 compatibility local current_title_text, current_namespace, sets -- Defined when needed. local namespaces = mw.site.namespaces --[==[ Loaders for functions in other modules, which overwrite themselves with the target function when called. This ensures modules are only loaded when needed, retains the speed/convenience of locally-declared pre-loaded functions, and has no overhead after the first call, since the target functions are called directly in any subsequent calls. ]==] local function decode_entities(...) decode_entities = require(string_utilities_module).decode_entities return decode_entities(...) end local function extend(...) extend = require(table_module).extend return extend(...) end local function finalize_set(...) finalize_set = require(parameters_finalize_set_module) return finalize_set(...) end local function get_family_by_code(...) get_family_by_code = require(families_module).getByCode return get_family_by_code(...) end local function get_family_by_name(...) get_family_by_name = require(families_module).getByCanonicalName return get_family_by_name(...) end local function get_language_by_code(...) get_language_by_code = require(languages_module).getByCode return get_language_by_code(...) end local function get_language_by_name(...) get_language_by_name = require(languages_module).getByCanonicalName return get_language_by_name(...) end local function get_script_by_code(...) get_script_by_code = require(scripts_module).getByCode return get_script_by_code(...) end local function get_script_by_name(...) get_script_by_name = require(scripts_module).getByCanonicalName return get_script_by_name(...) end local function get_wm_lang_by_code(...) get_wm_lang_by_code = require(wikimedia_languages_module).getByCode return get_wm_lang_by_code(...) end local function get_wm_lang_by_code_with_fallback(...) get_wm_lang_by_code_with_fallback = require(wikimedia_languages_module).getByCodeWithFallback return get_wm_lang_by_code_with_fallback(...) end local function gsplit(...) gsplit = require(string_utilities_module).gsplit return gsplit(...) end local function is_callable(...) is_callable = require(functions_module).is_callable return is_callable(...) end local function is_integer(...) is_integer = require(math_module).is_integer return is_integer(...) end local function is_internal_title(...) is_internal_title = require(pages_module).is_internal_title return is_internal_title(...) end local function is_positive_integer(...) is_positive_integer = require(math_module).is_positive_integer return is_positive_integer(...) end local function iterate_list(...) iterate_list = require(table_module).iterateList return iterate_list(...) end local function num_keys(...) num_keys = require(table_module).numKeys return num_keys(...) end local function parse_gender_and_number_spec(...) parse_gender_and_number_spec = require(gender_and_number_utilities_module).parse_gender_and_number_spec return parse_gender_and_number_spec(...) end local function parse_references(...) parse_references = require(references_module).parse_references return parse_references(...) end local function pattern_escape(...) pattern_escape = require(string_utilities_module).pattern_escape return pattern_escape(...) end local function php_trim(...) php_trim = require(scribunto_module).php_trim return php_trim(...) end local function scribunto_parameter_key(...) scribunto_parameter_key = require(scribunto_module).scribunto_parameter_key return scribunto_parameter_key(...) end local function sort(...) sort = require(collation_module).sort return sort(...) end local function sorted_pairs(...) sorted_pairs = require(table_module).sortedPairs return sorted_pairs(...) end local function split(...) split = require(string_utilities_module).split return split(...) end local function split_labels_on_comma(...) split_labels_on_comma = require(labels_module).split_labels_on_comma return split_labels_on_comma(...) end local function split_on_comma(...) split_on_comma = require(parse_utilities_module).split_on_comma return split_on_comma(...) end local function tonumber_extended(...) tonumber_extended = require(math_module).tonumber_extended return tonumber_extended(...) end local function track(...) track = require(parameters_track_module) return track(...) end local function yesno(...) yesno = require(yesno_module) return yesno(...) end --[==[ intro: This module is used to standardize template argument processing and checking. A typical workflow is as follows (based on [[Module:translations]]): { ... local parent_args = frame:getParent().args local params = { [1] = {required = true, type = "language", default = "und"}, [2] = true, [3] = {list = true}, ["alt"] = true, ["id"] = true, ["sc"] = {type = "script"}, ["tr"] = true, ["ts"] = true, ["lit"] = true, } local args = require("Module:parameters").process(parent_args, params) -- Do further processing of the parsed arguments in `args`. ... } The `params` table should have the parameter names as the keys, and a (possibly empty) table of parameter tags as the value. An empty table as the value merely states that the parameter exists, but should not receive any special treatment; if desired, empty tables can be replaced with the value `true` as a perforamnce optimization. Possible parameter tags are listed below: ; {required = true} : The parameter is required; an error is shown if it is not present. The template's page itself is an exception; no error is shown there. ; {default =} : Specifies a default input value for the parameter, if it is absent or empty. This will be processed as though it were the input instead, so (for example) {default = "und"} with the type {"language"} will return a language object for [[:Category:Undetermined language|Undetermined language]] if no language code is provided. (As an exception, numbers and booleans can be specified either as-is or in string format.) When used on list parameters, this specifies a default value for the first item in the list only. Note that it is not possible to generate a default that depends on the value of other parameters. If used together with {required = true}, the default applies only to template pages (see the following entry), as a side effect of the fact that "required" parameters aren't actually required on template pages. This can be used to show an example of the template in action when the template page is visited; however, it is preferred to use `template_default` for this purpose, for clarity. ; {template_default =} : Specifies a default input value for absent or empty parameters only on the template demo invocation (the invocation of the template that is displayed when the template page that implements the template is viewed). Template pages are pages in template space that invoke (through {{tl|#invoke:}}) the module that implements the template and calls [[Module:parameters]]. For example, the page [[Template:en-noun]] implements the {{tl|en-noun}} template, which in turn invokes [[Module:en-headword]], and is a template page for [[Module:en-headword]]. When the template page [[Template:en-noun]] is visited, the {{tl|#invoke:}} of the template's module is expanded as if the template were called without arguments, and the output is inserted at that point into the processed page. This output serves as a sort of demo of the template's functionality. `template_default` can be used to supply default values for use only in this demo. Since the template page may also contain other invocations of the same template (e.g. on the template's documentation page, which is typically transcluded into the template page itself), `template_default` does not apply if there are any arguments passed to the template or if the template is invoked on any other page but its own template page (which is checked by comparing the name of the invoking template to the current pagename). Both `template_default` and `default` can be specified for the same parameter. If this is done, `template_default` applies for the argumentless template invocation on the template page, and `default` in all other circumstances As an example, {{tl|cs-IPA}} uses the equivalent of {[1] = {default = "+", template_default = "příklad"}} to supply a default of {"+"} for mainspace and documentation pages (which tells the module to use the value of the {{para|pagename}} parameter, falling back to the actual pagename), but {"příklad"} (which means "example"), on [[Template:cs-IPA]]. ; {alias_of =} : Treat the parameter as an alias of another. When arguments are specified for this parameter, they will automatically be renamed and stored under the alias name. This allows for parameters with multiple alternative names, while still treating them as if they had only one name. The conversion-related properties of an aliased parameter (e.g. `type`, `set`, `convert`, `sublist`) are taken from the aliasee, and the corrresponding properties set on the alias itself are ignored; but other properties on the alias are taken from the alias's spec and not from the aliasee's spec. This means, for example, that if you create an alias of a list parameter, the alias must also specify the `list` property or it is not a list. (In such a case, a value specified for the alias goes into the first item of the aliasee's list. You cannot make a list alias of a non-list parameter; this causes an error to be thrown.) Similarly, if you specify `separate_no_index` on an aliasee but not on the alias, uses of the unindexed aliasee parameter are stored into the `.default` key, but uses of the unindexed alias are stored into the first numbered key of the aliasee's list. Aliases cannot be required, as this prevents the other name or names of the parameter from being used. Parameters that are aliases and required at the same time cause an error to be thrown. ; {allow_empty = true} : If the argument is an empty string value, it is not converted to {nil}, but kept as-is. The use of `allow_empty` is disallowed if a type has been specified, and causes an error to be thrown. ; {no_trim = true} : Spacing characters such as spaces and newlines at the beginning and end of a positional parameter are not removed. (MediaWiki itself automatically trims spaces and newlines at the edge of named parameters.) The use of `no_trim` is disallowed if a type has been specified, and causes an error to be thrown. ; {type =} : Specifies what value type to convert the argument into. The default is to leave it as a text string. Alternatives are: :; {type = "boolean"} :: The value is treated as a boolean value, either true or false. No value, the empty string, and the strings {"0"}, {"no"}, {"n"}, {"false"}, {"f"} and {"off"} (case-insensitive) are treated as {false}, all other values are considered {true}. :; {type = "boolean or string"} :: The value is treated as either a boolean value (true or false) or some other string value. The strings {"0"}, {"no"}, {"n"}, {"false"}, {"f"} and {"off"} (case-insensitive) are treated as {false}; the string {"1"}, {"yes"}, {"y"}, {"true"}, {"t"} and {"on"} (case-insensitive) are treated as {true}; and all other values are left as-is. You can use `set` to restrict the possible strings that are allowed; the values specified using `set` should not include {true} or {false}. :; {type = "number"} :: The value is converted into a number, and throws an error if the value is not parsable as a number. Input values may be signed (`+` or `-`), and may contain decimal points and leading zeroes. If {allow_hex = true}, then hexadecimal values in the form {"0x100"} may optionally be used instead, which otherwise have the same syntax restrictions (including signs, decimal digits, and leading zeroes after {"0x"}). Hexadecimal inputs are not case-sensitive. Lua's special number values (`inf` and `nan`) are not possible inputs. :; {type = "range"} :: The value is interpreted as a hyphen-separated range of two numbers (e.g. {"2-4"} is interpreted as the range from {2} to {4}). A number input without a hyphen is interpreted as a range from that number to itself (e.g. the input {"1"} is interpreted as the range from {1} to {1}). Any optional flags which are available for numbers will also work for ranges. :; {type = "language"} :: The value is interpreted as a full or [[Wiktionary:Languages#Etymology-only languages|etymology-only language]] code language code (or name, if {method = "name"}) and converted into the corresponding object (see [[Module:languages]]). If the code or name is invalid, then an error is thrown. The additional setting {family = true} can be given to allow [[Wiktionary:Language families|language family codes]] to be considered valid and the corresponding object returned. Note that to distinguish an etymology-only language object from a full language object, use {object:hasType("language", "etymology-only")}. :; {type = "full language"} :: The value is interpreted as a full language code (or name, if {method = "name"}) and converted into the corresponding object (see [[Module:languages]]). If the code or name is invalid, then an error is thrown. Etymology-only languages are not allowed. The additional setting {family = true} can be given to allow [[Wiktionary:Language families|language family codes]] to be considered valid and the corresponding object returned. :; {type = "Wikimedia language"} :: The value is interpreted as a code and converted into a Wikimedia language object. If the code is invalid, then an error is thrown. If {fallback = true} is specified, conventional language codes which are different from their Wikimedia equivalent will also be accepted as a fallback. :; {type = "family"} :: The value is interpreted as a language family code (or name, if {method = "name"}) and converted into the corresponding object (see [[Module:families]]). If the code or name is invalid, then an error is thrown. :; {type = "script"} :: The value is interpreted as a script code (or name, if {method = "name"}) and converted into the corresponding object (see [[Module:scripts]]). If the code or name is invalid, then an error is thrown. :; {type = "title"} :: The value is interpreted as a page title and converted into the corresponding object (see the [[mw:Extension:Scribunto/Lua_reference_manual#Title_library|Title library]]). If the page title is invalid, then an error is thrown; by default, external titles (i.e. those on other wikis) are not treated as valid. Options are: ::; {namespace = n} ::: The default namespace, where {n} is a namespace number; this is treated as {0} (the mainspace) if not specified. ::; {allow_external = true} ::: External titles are treated as valid. ::; {prefix = "namespace override"} (default) ::: The default namespace prefix will be prefixed to the value is already prefixed by a namespace prefix. For instance, the input {"Foo"} with namespace {10} returns {"Template:Foo"}, {"Wiktionary:Foo"} returns {"Wiktionary:Foo"}, and {"Template:Foo"} returns {"Template:Foo"}. Interwiki prefixes cannot act as overrides, however: the input {"fr:Foo"} returns {"Template:fr:Foo"}. ::; {prefix = "force"} ::: The default namespace prefix will be prefixed unconditionally, even if the value already appears to be prefixed. This is the way that {{tl|#invoke:}} works when calling modules from the module namespace ({828}): the input {"Foo"} returns {"Module:Foo"}, {"Wiktionary:Foo"} returns {"Module:Wiktionary:Foo"}, and {"Module:Foo"} returns {"Module:Module:Foo"}. ::; {prefix = "full override"} ::: The same as {prefix = "namespace override"}, except that interwiki prefixes can also act as overrides. For instance, {"el:All topics"} with namespace {14} returns {"el:Category:All topics"}. Due to the limitations of MediaWiki, only the first prefix in the value may act as an override, so the namespace cannot be overridden if the first prefix is an interwiki prefix: e.g. {"el:Template:All topics"} with namespace {14} returns {"el:Category:Template:All topics"}. :; {type = "parameter"} :: The value is interpreted as the name of a parameter, and will be normalized using the method that Scribunto uses when constructing a {frame.args} table of arguments. This means that integers will be converted to numbers, but all other arguments will remain as strings (e.g. {"1"} will be normalized to {1}, but {"foo"} and {"1.5"} will remain unchanged). Note that Scribunto also trims parameter names, following the same trimming method that this module applies by default to all parameter types. :: This type is useful when one set of input arguments is used to construct a {params} table for use in a subsequent {export.process()} call with another set of input arguments; for instance, the set of valid parameters for a template might be defined as {{tl|#invoke:[some module]|args=}} in the template, where {args} is a sublist of valid parameters for the template. :; {type = "qualifier"} :: The value is interpreted as a qualifier and converted into the correct format for passing into `format_qualifiers()` in [[Module:qualifier]] (which currently just means converting it to a one-item list). :; {type = "labels"} :: The value is interpreted as a comma-separated list of labels and converted into the correct format for passing into `show_labels()` in [[Module:labels]] (which is currently a list of strings). Splitting is done on commas not followed by whitespace, except that commas inside of double angle brackets do not count even if not followed by whitespace. This type should be used by for normal labels (typically specified using {{para|l}} or {{para|ll}}) and accent qualifiers (typically specified using {{para|a}} and {{para|aa}}). :; {type = "references"} :: The value is interpreted as one or more references, in the format prescribed by `parse_references()` in [[Module:references]], and converted into a list of objects of the form accepted by `format_references()` in the same module. If a syntax error is found in the reference format, an error is thrown. :; {type = "genders"} :: The value is interpreted as one or more comma-separated gender/number specs, in the format prescribed by [[Module:gender and number]]. Inline modifiers (`<q:...>`, `<qq:...>`, `<l:...>`, `<ll:...>` or `<ref:...>`) may be attached to a gender/number spec. :; {type = "form of tags"} :: The value is interpreted as an ampersand-separated list of grammar tags and converted into the correct format for passing as `tags` into `tagged_inflections()` in [[Module:form of]] (which is currently a list of strings). Splitting is always done by ampersands. This type should be used by for inflection qualifiers that act as grammar tags (typically specified using {{para|infl}}). :; {type = function(val) ... end} :: `type` may be set to a function (or callable table), which must take the argument value as its sole argument, and must output one of the other recognized types. This is particularly useful for lists (see below), where certain values need to be interpreted differently to others. ; {list =} : Treat the parameter as a list of values, each having its own parameter name, rather than a single value. The parameters will have a number at the end, except optionally for the first (but see also {require_index = true}). For example, {list = true} on a parameter named "head" will include the parameters {{para|head}} (or {{para|head1}}), {{para|head2}}, {{para|head3}} and so on. If the parameter name is a number, another number doesn't get appended, but the counting simply continues, e.g. for parameter {3} the sequence is {{para|3}}, {{para|4}}, {{para|5}} etc. List parameters are returned as numbered lists, so for a template that is given the parameters `|head=a|head2=b|head3=c`, the processed value of the parameter {"head"} will be { { "a", "b", "c" }}}. : The value for {list =} can also be a string. This tells the module that parameters other than the first should have a different name, which is useful when the first parameter in a list is a number, but the remainder is named. An example would be for genders: {list = "g"} on a parameter named {1} would have parameters {{para|1}}, {{para|g2}}, {{para|g3}} etc. : If the number is not located at the end, it can be specified by putting {"\1"} at the number position. For example, parameters {{para|f1accel}}, {{para|f2accel}}, ... can be captured by using the parameter name {"f\1accel"}, as is done in [[Module:headword/templates]]. ; {set =} : Require that the value of the parameter be one of the specified values (or omitted, if {required = true} isn't given). Two formats are allowed; either a list of possible values can be supplied, or a table can be supplied where the keys are allowed values and the values are either `true` or a string naming a value found elsewhere in the table as a key. In the latter case, the key is an alias and the value is the canonical value, and if the user uses the alias, it will automatically be mapped to the canonical value. In such a case, the canonical value cannot itself be an alias. The use of `set` is disallowed if {type = "boolean"} and causes an error to be thrown. The values given should be strings (i.e. pre-conversion values) unless {type = "number"}, in which case they should be numbers. If {type = "boolean or string"}, the values specified using {set =} are those that ''cannot'' be interpreted as a boolean; boolean strings (e.g. {"1"}, {"0"}, {"true"}, {"false"}, etc.) are always allowed in addition. ; {sublist =} : The value of the parameter is a delimiter-separated list of individual raw values. The resulting field in `args` will be a Lua list (i.e. a table with numeric indices) of the converted values. If {sublist = true} is given, the values will be split on commas (possibly with whitespace on one or both sides of the comma, which is ignored). If {sublist = "comma without whitespace"} is given, the values will be split on commas which are not followed by whitespace, and which aren't preceded by an escaping backslash. Otherwise, the value of `sublist` should be either a Lua pattern specifying the delimiter(s) to split on or a function (or callable table) to do the splitting, which is passed two values (the value to split and a function to signal an error) and should return a list of the split values. ; {convert =} : If given, this specifies a function (or callable table) to convert the raw parameter value into the Lua object used during further processing. The function is passed two arguments, the raw parameter value itself and a function used to signal an error during parsing or conversion, and should return one value, the converted parameter. The error-signaling function contains the name and raw value of the parameter embedded into the message it generates, so these do not need to specified in the message passed into it. If `type` is specified in conjunction with `convert`, the processing by `type` happens first. If `sublist` is given in conjunction with `convert`, the raw parameter value will be split appropriately and `convert` called on each resulting item. ; {allow_hex = true} : When used in conjunction with {type = "number"}, allows hexadecimal numbers as inputs, in the format {"0x100"} (which is not case-sensitive). ; {family = true} : When used in conjunction with {type = "language"}, allows [[Wiktionary:Language families|language family codes]] to be returned. To check if a given object refers to a language family, use {object:hasType("family")}. ; {method = "name"} : When used in conjunction with {type = "language"}, {type = "family"} or {type = "script"}, checks for and parses a language, family or script name instead of a code. ; {allow_holes = true} : This is used in conjunction with list-type parameters. By default, the values are tightly packed in the resulting list. This means that if, for example, an entry specified `head=a|head3=c` but not {{para|head2}}, the returned list will be { {"a", "c"}}}, with the values stored at the indices {1} and {2}, not {1} and {3}. If it is desirable to keep the numbering intact, for example if the numbers of several list parameters correlate with each other (like those of {{tl|affix}}), then this tag should be specified. : If {allow_holes = true} is given, there may be {nil} values in between two real values, which makes many of Lua's table processing functions no longer work, like {#} or {ipairs()}. To remedy this, the resulting table will contain an additional named value, `maxindex`, which tells you the highest numeric index that is present in the table. In the example above, the resulting table will now be { { "a", nil, "c", maxindex = 3}}}. That way, you can iterate over the values from {1} to `maxindex`, while skipping {nil} values in between. ; {disallow_holes = true} : This is used in conjunction with list-type parameters. As mentioned above, normally if there is a hole in the source arguments, e.g. `head=a|head3=c` but not {{para|head2}}, it will be removed in the returned list. If {disallow_holes = true} is specified, however, an error is thrown in such a case. This should be used whenever there are multiple list-type parameters that need to line up (e.g. both {{para|head}} and {{para|tr}} are available and {{para|head3}} lines up with {{para|tr3}}), unless {allow_holes = true} is given and you are prepared to handle the holes in the returned lists. ; {disallow_missing = true} : This is similar to {disallow_holes = true}, but an error will not be thrown if an argument is blank, rather than completely missing. This may be used to tolerate intermediate blank numerical parameters, which sometimes occur in list templates. For instance, `head=a|head2=|head3=c` will not throw an error, but `head=a|head3=c` will. ; {require_index = true} : This is used in conjunction with list-type parameters. By default, the first parameter can have its index omitted. For example, a list parameter named `head` can have its first parameter specified as either {{para|head}} or {{para|head1}}. If {require_index = true} is specified, however, only {{para|head1}} is recognized, and {{para|head}} will be treated as an unknown parameter. {{tl|affixusex}} (and variants {{tl|suffixusex}}, {{tl|prefixusex}}) use this, for example, on all list parameters. ; {separate_no_index = true} : This is used to distinguish between {{para|head}} and {{para|head1}} as different parameters. For example, in {{tl|affixusex}}, to distinguish between {{para|sc}} (a script code for all elements in the usex's language) and {{para|sc1}} (the script code of the first element, used when the first element is prefixed with a language code to indicate that it is in a different language). When this is used, the resulting table will contain an additional named value, `default`, which contains the value for the indexless argument. ; {flatten = true} : This is used in conjunction with list-type parameters when `sublist` or a list-generating type such as {"labels"} or {"genders"} is also specified, and causes the resulting list to be flattened. Not currently compatible with {allow_holes = true}. ; {replaced_by =} : Specifies that the parameter is no longer valid, and has been replaced by some other mechanism. If the value of `replaced_by` is a string, it is the name of the new parameter to use instead. Use the `reason` tag to specify the reason why this change has been made, e.g. {reason = "for consistency with the corresponding parameter in other Romance-language headword templates"}. If the value of `replaced_by` is {false}, there is no replacement parameter. In this case, `instead` should be supplied with a description of what to do instead, e.g. {instead = "use an inline modifier on |2= such as <q:...>, <qq:...>, <l:...> or <ll:...>"}. You can also supply a justification in `reason` if you feel it is appropriate or necessary to do so. ; {reason =} : When used in conjunction with `replaced_by`, specifies the reason for the parameter replacement. ; {instead =} : When used in conjunction with {replaced_by = false}, specifies what to do instead of using the removed parameter. ; {demo = true} : This is used as a way to ensure that the parameter is only enabled on the template's own page (and its documentation page), and in the User: namespace; otherwise, it will be treated as an unknown parameter. This should only be used if special settings are required to showcase a template in its documentation (e.g. adjusting the pagename or disabling categorization). In most cases, it should be possible to do this without using demo parameters, but they may be required if a template/documentation page also contains real uses of the same template as well (e.g. {{tl|shortcut}}), as a way to distinguish them. ; {deprecated = true} : This is for tracking the use of deprecated parameters, including any aliases that are being brought out of use. See [[Wiktionary:Tracking]] for more information. ]==] -- Returns true if the current page is a template or module containing the current {{#invoke}}. -- If the include_documentation argument is given, also returns true if the current page is either page's documentation page. local own_page, own_page_or_documentation local function is_own_page(include_documentation) if own_page == nil then if current_namespace == nil then local current_title = mw_title.getCurrentTitle() current_title_text, current_namespace = current_title.prefixedText, current_title.namespace end local frame = current_namespace == 828 and mw.getCurrentFrame() or current_namespace == 10 and mw.getCurrentFrame():getParent() if frame then local frame_title_text = frame:getTitle() own_page = current_title_text == frame_title_text own_page_or_documentation = own_page or current_title_text == frame_title_text .. "/documentation" else own_page, own_page_or_documentation = false, false end end return include_documentation and own_page_or_documentation or own_page end -------------------------------------- Some helper functions ----------------------------- -- Convert a list in `list` to a string, separating the final element from the preceding one(s) by `conjunction`. If -- `dump_vals` is given, pass all values in `list` through mw.dumpObject() (WARNING: this destructively modifies -- `list`). This is similar to serialCommaJoin() in [[Module:table]] when used with the `dontTag = true` option, but -- internally uses mw.text.listToText(). local function concat_list(list, conjunction, dump_vals) if dump_vals then for k, v in pairs(list) do list[k] = dump(v) end end return list_to_text(list, nil, conjunction) end -- A helper function for use with generating error-signaling functions in the presence of raw value conversion. Format a -- message `msg`, including the processed value `processed` if it is different from the raw value `rawval`; otherwise, -- just return `msg`. local function msg_with_processed(msg, rawval, processed) if rawval == processed then return msg end local processed_type = type(processed) return format("%s (processed value %s)", msg, (processed_type == "string" or processed_type == "number") and processed or dump(processed) ) end -- Separate form of tags with ampersand (&). local function split_tags_on_ampersand(tags) return split(tags, "&") end -------------------------------------- Error handling ----------------------------- local function process_error(fmt, ...) local args = {...} for i, val in ipairs(args) do args[i] = dump(val) end if type(fmt) == "table" then -- hacky signal that we're called from internal_process_error(), and not to omit stack frames return error(format(fmt[1], unpack(args))) end return error(format(fmt, unpack(args)), 3) end local function internal_process_error(fmt, ...) process_error({"Internal error in `params` table: " .. fmt}, ...) end -- Check that a parameter or argument is in the form form Scribunto normalizes input argument keys into (e.g. 1 not "1", "foo" not " foo "). Otherwise, it won't be possible to normalize inputs in the expected way. Unless is_argument is set, also check that the name only contains one placeholder at most, and that strings don't resolve to numeric keys once the placeholder has been substituted. local function validate_name(name, desc, extra_name, is_argument) local normalized = scribunto_parameter_key(name) if name and name == normalized then if is_argument or type(name) ~= "string" then return end local placeholder = find(name, "\1", nil, true) if not placeholder then return elseif find(name, "\1", placeholder + 1, true) then error(format( "Internal error: expected %s to only contain one placeholder, but saw %s", extra_name and (desc .. dump(extra_name)) or desc, dump(name) )) end local first_name = gsub(name, "\1", "1") normalized = scribunto_parameter_key(first_name) if first_name == normalized then return end error(format( "Internal error: %s cannot resolve to numeric parameters once any placeholder has been substituted, but %s resolves to %s", extra_name and (desc .. dump(extra_name)) or desc, dump(name), dump(normalized) )) elseif normalized == nil then error(format( "Internal error: expected %s to be of type string or number, but saw %s", extra_name and (desc .. dump(extra_name)) or desc, type(name) )) end error(format( "Internal error: expected %s to be Scribunto-compatible: %s (a %s) should be %s (a %s)", extra_name and (desc .. dump(extra_name)) or desc, dump(name), type(name), dump(normalized), type(normalized) )) end local function validate_alias_options(...) local invalid = { required = true, default = true, template_default = true, allow_holes = true, disallow_holes = true, disallow_missing = true, } function validate_alias_options(param, name, main_param, alias_of) for k in pairs(param) do if invalid[k] then track("bad alias option") -- internal_process_error( -- "parameter %s cannot have the option %s, as it is an alias of parameter %s.", -- name, option, alias_of -- ) end end -- Soon, aliases will inherit options from the main parameter via __index. Track cases where this would happen. if main_param ~= true then for k in pairs(main_param) do if param[k] == nil and not invalid[k] then if k == "list" then -- these need to be changed to list = false to retain current behaviour track("mismatched list alias option") elseif not (k == "type" or k == "set" or k == "sublist") then -- rarely specified on aliases, as they're effectively inherited already track("mismatched alias option") end end end end end validate_alias_options(...) end -- TODO: give ranges instead of long lists, if possible. --[==[ func: export.params_list_error(params, msg) Given a key-value table of raw parameters `params`, display an error message about all the parameters seen in the table. The parameter names are displayed in sorted order. `msg` should be e.g. {"required"} or {"not used by this template"}. This is used internally to display error messages about required or invalid parameters, and can be used for the same purpose by code that processes its own parameters (e.g. if the `props.return_unknown` flag is specified to `process`). ]==] local function params_list_error(params, msg) local list, n = {}, 0 for name in sorted_pairs(params) do n = n + 1 list[n] = name end error(format( "Parameter%s %s.", format(n == 1 and " %s is" or "s %s are", concat_list(list, " and ", true)), msg ), 3) end export.params_list_error = params_list_error -- Helper function for use with convert_val_error(). Format a list of possible choices using `concat_list` and -- conjunction "or", displaying "either " before the choices if there's more than one. local function format_choice_list(valid) return (#valid > 1 and "either " or "") .. concat_list(valid, " or ") end -- Signal an error for a value `val` that is not of the right type `valid` (which is either a string specifying a type, or -- a list of possible values, in the case where `set` was used). `name` is the name of the parameter and can be a -- function to signal an error (which is assumed to automatically display the parameter's name and value). `seetext` is -- an optional additional explanatory link to display (e.g. [[WT:LOL]], the list of possible languages and codes). local function convert_val_error(val, name, valid, seetext) if is_callable(name) then if type(valid) == "table" then valid = "choice, must be " .. format_choice_list(valid) end name(format("Invalid %s; the value %s is not valid%s", valid, val, seetext and "; see " .. seetext or "")) else if type(valid) == "table" then valid = format_choice_list(valid) else valid = "a valid " .. valid end error(format("Parameter %s must be %s; the value %s is not valid.%s", dump(name), valid, dump(val), seetext and " See " .. seetext .. "." or "")) end end -- Generate the appropriate error-signaling function given parameter value `val` and name `name`. If `name` is already -- a function, it is just returned; otherwise a function is generated and returned that displays the passed-in messaeg -- along with the parameter's name and value. local function make_parse_err(val, name) if is_callable(name) then return name end return function(msg) error(format("%s: parameter %s=%s", msg, name, val)) end end -------------------------------------- Value conversion ----------------------------- -- For a list parameter `name` and corresponding value `list_name` of the `list` field (which should have the same value -- as `name` if `list = true` was given), generate a pattern to match parameters of the list and store the pattern as a -- key in `patterns`, with corresponding value set to `name`. For example, if `list_name` is "tr", the pattern will -- match "tr" as well as "tr1", "tr2", ..., "tr10", "tr11", etc. If the `list_name` contains a \1 in it, the numeric -- portion goes in place of the \1. For example, if `list_name` is "f\1accel", the pattern will match "faccel", -- "f1accel", "f2accel", etc. Any \1 in `name` is removed before storing into `patterns`. local function save_pattern(name, list_name, patterns) name = type(name) == "string" and gsub(name, "\1", "") or name if find(list_name, "\1", nil, true) then patterns["^" .. gsub(pattern_escape(list_name), "\1", "([1-9]%%d*)") .. "$"] = name else patterns["^" .. pattern_escape(list_name) .. "([1-9]%d*)$"] = name list_name = list_name .. "\1" end validate_name(list_name, "the list field of parameter ", name) return patterns end -- A helper function for use with `sublist`. It is an iterator function for use in a for-loop that returns split -- elements of `val` using `sublist` (a Lua split pattern; boolean `true` to split on commas optionally surrounded by -- whitespace; "comma without whitespace" to split only on commas not followed by whitespace which have not been escaped -- by a backslash; or a function to do the splitting, which is passed two values, the value to split and a function to -- signal an error, and should return a list of the split elements). `name` is the parameter name or error-signaling -- function passed into convert_val(). local function split_sublist(val, name, sublist) if sublist == true then return gsplit(val, "%s*,%s*") -- Split an argument on comma, but not comma followed by whitespace. elseif sublist == "comma without whitespace" then -- If difficult cases, use split_on_comma. if find(val, "\\", nil, true) or match(val, ",%s") then return iterate_list(split_on_comma(val)) end -- Otherwise, use gsplit. return gsplit(val, ",") elseif type(sublist) == "string" then return gsplit(val, sublist) elseif not is_callable(sublist) then error(format('Internal error: expected `sublist` to be of type "string" or "function" or boolean `true`, but saw %s', dump(sublist))) end return iterate_list(sublist(val, make_parse_err(val, name))) end --[=[ For parameter named `name` with value `val` and param spec `param`, if the `set` field is specified, verify that the value is one of the one specified in `set`, and throw an error otherwise. `name` is taken directly from the corresponding parameter passed into convert_val() and may be a function to signal an error. Optional `param_type` is a string specifying the conversion type of `val` and is used for special-casing: If `param_type` is "boolean", an internal error is thrown (since `set` cannot be used in conjunction with booleans); and if `param_type` is "number" or "boolean or string", and `called_from_converter` is not given, no checking happens because in these cases `set` needs to be called by the conversion function itself (respectively after converting `val` to a number or processing boolean strings). Return the canonical value of `val` (which may be different from `val` if an alias map is given). ]=] local function check_set(val, name, param, param_type, called_from_converter) -- Needs to be special cased because the check happens after conversion to numbers. if (param_type == "number" or param_type == "boolean or string") and not called_from_converter then return val end local set = param.set local map if sets == nil then map = finalize_set(set, name) sets = {[set] = map} else map = sets[set] if map == nil then map = finalize_set(set, name) sets[set] = map end end local newval = map[val] if newval == true then return val elseif newval ~= nil then return newval end local list = {} for k, v in sorted_pairs(map) do if v == true then insert(list, dump(k)) else insert(list, ("%s (alias of %s)"):format(dump(k), dump(v))) end end -- If the parameter type is "boolean or string", put "a boolean string value" because such values are allowed. if param_type == "boolean or string" then insert(list, "a boolean string value") end -- If the parameter is not required then put "or empty" at the end of the list, to avoid implying the parameter is -- actually required. if not param.required then insert(list, "empty") end convert_val_error(val, name, list) end local function convert_language(val, name, param, allow_etym) local method = param.method local func if method == nil or method == "code" then func, method = get_language_by_code, "code" elseif method == "name" then func, method = get_language_by_name, "name" else error(format('Internal error: expected `method` for type `language` to be "code", "name" or undefined, but saw %s', dump(method))) end local lang = func(val, nil, allow_etym, param.family) if lang then return lang end local list, links = {"language"}, {"[[WT:LOL]]"} if allow_etym then insert(list, "etymology language") insert(links, "[[WT:LOL/E]]") end if param.family then insert(list, "family") insert(links, "[[WT:LOF]]") end convert_val_error(val, name, concat_list(list, " or ") .. " " .. (method == "name" and "name" or "code"), concat_list(links, " and ")) end local function convert_number(val, allow_hex) -- Call tonumber_extended with the `real_finite` flag, which filters out ±infinity and NaN. -- By default, specify base 10, which prevents 0x hex inputs from being converted. -- If `allow_hex` is set, then don't give a base, which means 0x hex inputs will work. local num = tonumber_extended(val, not allow_hex and 10 or nil, "finite_real") if not num then return num end if match(val, "[eEpP.]") then -- float track("number not an integer") end if find(val, "+", nil, true) then track("number with +") end -- Track various unusual number inputs to determine if it should be restricted to positive integers by default (possibly including 0). if not is_positive_integer(num) then track("number not a positive integer") if num == 0 then track("number is 0") elseif not is_integer(num) then track("number not an integer") end end return num end -- TODO: validate parameter specs separately, as it's making the handler code really messy at the moment. local type_handlers = setmetatable({ ["boolean"] = function(val, name, param) local newval = yesno(val, val) if newval ~= true and newval ~= false then newval = true end return newval end, ["boolean or string"] = function(val, name, param) local newval = yesno(val, val) if newval ~= true and newval ~= false then if param.set then newval = check_set(newval, name, param, "boolean or string", "called_from_converter") else newval = true end end return newval end, ["family"] = function(val, name, param) local method = param.method local func if method == nil or method == "code" then func, method = get_family_by_code, "code" elseif method == "name" then func, method = get_family_by_name, "name" else error(format('Internal error: expected `method` for type `family` to be "code", "name" or undefined, but saw %s', dump(method))) end return func(val) or convert_val_error(val, name, "family " .. method, "[[WT:LOF]]") end, ["labels"] = function(val, name, param) -- FIXME: Should be able to pass in a parse_err function. return split_labels_on_comma(val) end, ["form of tags"] = function(val, name, param) return split_tags_on_ampersand(val) end, ["language"] = function(val, name, param) return convert_language(val, name, param, true) end, ["full language"] = convert_language, ["number"] = function(val, name, param) local allow_hex = param.allow_hex if allow_hex and allow_hex ~= true then error(format( 'Internal error: expected `allow_hex` for type `number` to be of type "boolean" or undefined, but saw %s', dump(allow_hex) )) end local num = convert_number(val, allow_hex) if param.set then num = check_set(num, name, param, "number", "called_from_converter") end if num then return num end convert_val_error(val, name, (allow_hex and "decimal or hexadecimal " or "") .. "number") end, ["range"] = function(val, name, param) local allow_hex = param.allow_hex if allow_hex and allow_hex ~= true then error(format( 'Internal error: expected `allow_hex` for type `range` to be of type "boolean" or undefined, but saw %s', dump(allow_hex) )) end -- Pattern ensures leading minus signs are accounted for. local m1, m2 = match(val, "^(%s*%S.-)%-(%s*%S.*)") if m1 then m1 = convert_number(m1, allow_hex) if m1 then m2 = convert_number(m2, allow_hex) if m2 then return {m1, m2} end end end -- Try `val` if it couldn't be split into a range, and return a range of `val` to `val` if possible. local num = convert_number(val, allow_hex) if num then return {num, num} end convert_val_error(val, name, (allow_hex and "decimal or hexadecimal " or "") .. "number or a hyphen-separated range of two numbers") end, ["parameter"] = function(val, name, param) -- Use the `no_trim` option, as any trimming will have already been done. return scribunto_parameter_key(val, true) end, ["qualifier"] = function(val, name, param) return {val} end, ["references"] = function(val, name, param) return parse_references(val, make_parse_err(val, name)) end, ["genders"] = function(val, name, param) if not val:find("[,<]") then return {{spec = val}} end -- NOTE: We don't pass in allow_space_around_comma. Consistent with other comma-separated types, there shouldn't -- be spaces around the comma. return parse_gender_and_number_spec { spec = val, parse_err = make_parse_err(val, name), allow_multiple = true, } end, ["script"] = function(val, name, param) local method = param.method local func if method == nil or method == "code" then func, method = get_script_by_code, "code" elseif method == "name" then func, method = get_script_by_name, "name" else error(format('Internal error: expected `method` for type `script` to be "code", "name" or undefined, but saw %s', dump(method))) end return func(val) or convert_val_error(val, name, "script " .. method, "[[WT:LOS]]") end, ["string"] = function(val, name, param) -- To be removed as unnecessary. track("string") return val end, -- TODO: add support for resolving to unsupported titles. -- TODO: split this into "page name" (i.e. internal) and "link target" (i.e. external as well), which is more intuitive. ["title"] = function(val, name, param) local namespace = param.namespace if namespace == nil then namespace = 0 else local valid_type = type(namespace) ~= "number" and 'of type "number" or undefined' or not namespaces[namespace] and "a valid namespace number" or nil if valid_type then error(format('Internal error: expected `namespace` for type `title` to be %s, but saw %s', valid_type, dump(namespace))) end end -- Decode entities. WARNING: mw.title.makeTitle must be called with `decoded` (as it doesn't decode) and mw.title.new must be called with `val` (as it does decode, so double-decoding needs to be avoided). local decoded, prefix = decode_entities(val), param.prefix local title -- If the input is a fragment, treat the title as the current title with the input fragment. if sub(decoded, 1, 1) == "#" then -- If prefix is "force", only get the current title if it's in the specified namespace. current_title includes the namespace prefix. if current_namespace == nil then local current_title = mw_title.getCurrentTitle() current_title_text, current_namespace = current_title.prefixedText, current_title.namespace end if not (prefix == "force" and namespace ~= current_namespace) then title = new_title(current_title_text .. val) end elseif prefix == "force" then -- Unconditionally add the namespace prefix (mw.title.makeTitle). title = make_title(namespace, decoded) elseif prefix == "full override" then -- The first input prefix will be used as an override (mw.title.new). This can be a namespace or interwiki prefix. title = new_title(val, namespace) elseif prefix == nil or prefix == "namespace override" then -- Only allow namespace prefixes to override. Interwiki prefixes therefore need to be treated as plaintext (e.g. "el:All topics" with namespace 14 returns "el:Category:All topics", but we want "Category:el:All topics" instead; if the former is really needed, then the input ":el:Category:All topics" will work, as the initial colon overrides the namespace). mw.title.new can take namespace names as well as numbers in the second argument, and will throw an error if the input isn't a valid namespace, so this can be used to determine if a prefix is for a namespace, since mw.title.new will return successfully only if there's either no prefix or the prefix is for a valid namespace (in which case we want the override). local success success, title = pcall(new_title, val, match(decoded, "^.-%f[:]") or namespace) -- Otherwise, get the title with mw.title.makeTitle, which unconditionally adds the namespace prefix, but behaves like mw.title.new if the namespace is 0. if not success then title = make_title(namespace, decoded) end else error(format('Internal error: expected `prefix` for type `title` to be "force", "full override", "namespace override" or undefined, but saw %s', dump(prefix))) end local allow_external = param.allow_external if allow_external == true then return title or convert_val_error(val, name, "Wiktionary or external page title") elseif not allow_external then return title and is_internal_title(title) and title or convert_val_error(val, name, "Wiktionary page title") end error(format('Internal error: expected `allow_external` for type `title` to be of type "boolean" or undefined, but saw %s', dump(allow_external))) end, ["Wikimedia language"] = function(val, name, param) local fallback = param.fallback if fallback == true then return get_wm_lang_by_code_with_fallback(val) or convert_val_error(val, name, "Wikimedia language or language code") elseif not fallback then return get_wm_lang_by_code(val) or convert_val_error(val, name, "Wikimedia language code") end error(format('Internal error: expected `fallback` for type `Wikimedia language` to be of type "boolean" or undefined, but saw %s', dump(fallback))) end, }, { -- TODO: decode HTML entities in all input values. Non-trivial to implement, because we need to avoid any downstream -- functions decoding the output from this module, which would be double-decoding. Note that "title" has this -- implemented already, and it needs to have both the raw input and the decoded input to avoid double-decoding by -- mw.title.new, so any implementation can't be as simple as decoding in __call then passing the result to the -- handler. __call = function(self, val, name, param, param_type, default) local val_type = type(val) -- TODO: check this for all possible parameter types. if val_type == param_type or val_type == "boolean" and param_type == "boolean or string" then return val elseif val_type ~= "string" then local expected = "string" if default then if param_type == "boolean or string" then expected = param_type elseif param_type == "boolean" or param_type == "number" then expected = param_type .. " or " .. expected end end error(format( "Internal error: %sargument %s has the type %s; expected a %s.", default and (default .. " for ") or "", name, dump(val_type), expected )) end local func = self[param_type] if func == nil then error(format("Internal error: %s is not a recognized parameter type.", dump(param_type))) end return func(val, name, param) end }) --[==[ func: export.convert_val(val, name, param) Convert a parameter value according to the associated specs listed in the `params` table passed to [[Module:parameters]]. `val` is the value to convert for a parameter whose name is `name` (used only in error messages). `param` is the spec (the value part of the `params` table for the parameter). In place of passing in the parameter name, `name` can be a function that throws an error, displaying the specified message along with the parameter name and value. This function processes all the conversion-related fields in `param`, including `type`, `set`, `sublist`, `convert`, etc. It returns the converted value. ]==] local function convert_val(val, name, param, default) local param_type = param.type or "string" -- If param.type is a function, resolve it to a recognized type. if is_callable(param_type) then param_type = param_type(val) end local convert, sublist = param.convert, param.sublist -- `val` might not be a string if it's the default value. if sublist and type(val) == "string" then local retlist, set = {}, param.set if convert then local thisindex = 0 local thisval, insval, parse_err if is_callable(name) then -- We assume the passed-in error function in `name` already shows the parameter name and raw value. function parse_err(msg) name(format("%s: item #%s=%s", msg_with_processed(msg, thisval, insval), thisindex, thisval) ) end else function parse_err(msg) error(format("%s: item #%s=%s of parameter %s=%s", msg_with_processed(msg, thisval, insval), thisindex, thisval, name, val) ) end end for v in split_sublist(val, name, sublist) do thisindex, thisval = thisindex + 1, v if set then v = check_set(v, name, param, param_type) end insval = v insert(retlist, convert(type_handlers(v, name, param, param_type, default), parse_err)) end else for v in split_sublist(val, name, sublist) do if set then v = check_set(v, name, param, param_type) end insert(retlist, type_handlers(v, name, param, param_type, default)) end end return retlist elseif param.set then val = check_set(val, name, param, param_type) end local retval = type_handlers(val, name, param, param_type, default) if convert then local parse_err if is_callable(name) then -- We assume the passed-in error function in `name` already shows the parameter name and raw value. if retval == val then -- This is an optimization to avoid creating a closure. The second arm works correctly even -- when retval == val. parse_err = name else function parse_err(msg) name(msg_with_processed(msg, val, retval)) end end else function parse_err(msg) error(format("%s: parameter %s=%s", msg_with_processed(msg, val, retval), name, val)) end end retval = convert(retval, parse_err) end -- If `sublist` is set but the input wasn't a string, return `retval` as a one-item list. if sublist then retval = {retval} end return retval end export.convert_val = convert_val -- used by [[Module:parameter utilities]] local function unknown_param(name, val, args_unknown) track("unknown parameters") args_unknown[name] = val return args_unknown end local function check_string_param_modifier(param_type, name, tag) if param_type and not (param_type == "string" or param_type == "parameter" or is_callable(param_type)) then internal_process_error( "%s cannot be set unless %s is set to %s (the default), %s or a function: parameter %s has the type %s.", tag, "type", "string", "parameter", name, param_type ) end end local function hole_error(params, name, listname, this, nxt, extra) -- `process_error` calls `dump` on values to be inserted into -- error messages, but with numeric lists this causes "numeric" -- to look like the name of the list rather than a description, -- as `dump` adds quote marks. Insert it early to avoid this, -- but add another %s specifier in all other cases, so that -- actual list names will be displayed properly. local offset, specifier, starting_from = 0, "%s", "" local msg = "Item %%d in the list of %s parameters must be given if item %%d is given, because %sthere shouldn't be any gaps due to missing%s parameters." local specs = {} if type(listname) == "string" then specs[2] = listname elseif type(name) == "number" then offset = name - 1 -- To get the original parameter. specifier = "numeric" -- If the list doesn't start at parameter 1, avoid implying -- there can't be any gaps in the numeric parameters if -- some parameter with a lower key is optional. for j = name - 1, 1, -1 do local _param = params[j] if not (_param and _param.required) then starting_from = format("(starting from parameter %d) ", dump(j + 1)) break end end else specs[2] = name end specs[1] = this + offset -- Absolute index for this item. insert(specs, nxt + offset) -- Absolute index for the next item. process_error(format(msg, specifier, starting_from, extra or ""), unpack(specs)) end local function check_disallow_holes(params, val, name, listname, extra) for i = 1, val.maxindex do if val[i] == nil then hole_error(params, name, listname, i, num_keys(val)[i], extra) end end end local function handle_holes(params, val, name) local param = params[name] local disallow_holes = param.disallow_holes -- Iterate up the list, and throw an error if a hole is found. if disallow_holes then check_disallow_holes(params, val, name, param.list, " or empty") end -- Iterate up the list, and throw an error if a hole is found due to a -- missing parameter, treating empty parameters as part of the list. This -- applies beyond maxindex if blank arguments are supplied beyond it, so -- isn't mutually exclusive with `disallow_holes`. local empty = val.empty if param.disallow_missing then if empty then -- Remove `empty` from `val`, so it doesn't get returned. val.empty = nil for i = 1, max(val.maxindex, empty.maxindex) do if val[i] == nil and not empty[i] then local keys = extend(num_keys(val), num_keys(empty)) sort(keys) hole_error(params, name, param.list, i, keys[i]) end end -- If there's no table of empty parameters, the check is identical to -- `disallow_holes`, except that the error message only refers to -- missing parameters, not missing or empty ones. If `disallow_holes` is -- also set, there's no point checking again. elseif not disallow_holes then check_disallow_holes(params, val, name, param.list) end end -- If `allow_holes` is set, there's nothing left to do. if param.allow_holes then -- do nothing -- Otherwise, remove any holes: `pairs` won't work, as it's unsorted, and -- iterating from 1 to `maxindex` times out with inputs like |100000000000=, -- so use num_keys to get a list of numerical keys sorted from lowest to -- highest, then iterate up the list, moving each value in `val` to the -- lowest unused positive integer key. This also avoids the need to create a -- new table. If `disallow_holes` is specified, then there can't be any -- holes in the list, so there's no reason to check again; this doesn't -- apply to `disallow_missing`, however. else if not disallow_holes then local keys, i = num_keys(val), 0 while true do i = i + 1 local key = keys[i] if key == nil then break elseif i ~= key then track("holes compressed") val[i], val[key] = val[key], nil end end end -- Some code depends on only numeric params being present when no holes are -- allowed (e.g. by checking for the presence of arguments using next()), so -- remove `maxindex`. val.maxindex = nil end end local function maybe_flatten(params, val, name) local param = params[name] if param.flatten then if param.allow_holes then process_error("For parameter %s, can't set both `allow_holes` and `flatten`", name) end if not param.sublist and param.type ~= "genders" and param.type ~= "labels" and param.type ~= "references" and param.type ~= "qualifier" and param.type ~= "form of tags" then process_error("For parameter %s, can only set `flatten` along with `sublist` or a list-generating type", name) end -- Do the flattening ourselves rather than calling flatten() in [[Module:table]], which will attempt to -- flatten non-list objects like title objects, and cause an error in the process. -- FIXME: We should do this in-place if possible. local newlist = {} for _, sublist in ipairs(val) do for _, item in ipairs(sublist) do insert(newlist, item) end end val = newlist end return val end -- If both `template_default` and `default` are given, `template_default` takes precedence, but only on the template or -- module page. This means a different default can be specified for the template or module page example. However, -- `template_default` doesn't apply if any args are set, which helps (somewhat) with examples on documentation pages -- transcluded into the template page. HACK: We still run into problems on documentation pages transcluded into the -- template page when pagename= is set. Check this on the assumption that pagename= is fairly standard. local function convert_default_val(name, param, pagename_set, any_args_set, add_empty_sublist) if not pagename_set then local val = param.template_default if val ~= nil and not any_args_set and is_own_page() then return convert_val(val, name, param, "template default") end end local val = param.default if val ~= nil then return convert_val(val, name, param, "default") -- Sublist parameters should return an empty table if not given, but only do -- this if the parameter isn't also a list (in which case it will already -- be an empty table). -- FIXME: do this once all modules that pass in a sublist parameter treat an empty sublist identically to a nil argument; some currently do things based on the fact an argument exists at all. -- elseif add_empty_sublist and param.sublist then --return {} end end --[==[ Process arguments with a given list of parameters. Return a table containing the processed arguments. The `args` parameter specifies the arguments to be processed; they are the arguments you might retrieve from {frame:getParent().args} (the template arguments) or in some cases {frame.args} (the invocation arguments). The `params` parameter specifies a list of valid parameters, and consists of a table. If an argument is encountered that is not in the parameter table, an error is thrown. The structure of the `params` table is as described above in the intro comment. '''WARNING:''' The `params` table is destructively modified to save memory. Nonetheless, different keys can share the same value objects in memory without causing problems. The `props` parameter is an optional table of additional properties. Currently the following properties are supported: * `return_unknown`: If set to {true}, prevents the function from triggering an error when it comes across an argument with a name that it doesn't recognise. Instead, the return value is a pair of values: the first is the processed arguments as usual, while the second contains all the unrecognised arguments that were left unprocessed. This allows you to do multi-stage processing, where the entire set of arguments that a template should accept is not known at once. For example, an inflection-table might do some generic processing on some arguments, but then defer processing of the remainder to the function that handles a specific inflectional type. * `allow_params`: An optional function to allow and return additional parameters. The function is passed the name of each unrecognized parameter, and should return the appropriate parameter spec for processing the parameter. In most cases, simply return `true`, indicating that the parameter should be processed as a normal string parameter. Return {nil} if the parameter name is unrecognized. For compatibility, `props` can be a boolean or string, which is treated as the `return_unknown` property. ]==] function export.process(args, params, props) if type(props) ~= "table" then props = { return_unknown = props } end -- Process parameters for specific properties local args_new = {} local args_unknown, any_args_set, required, patterns, list_args, index_list, args_placeholders, placeholders_n -- TODO: memoize the processing of each unique `param` value, since it's common for the same value to be used for -- many parameter names. for name, param in pairs(params) do validate_name(name, "parameter names") if param ~= true then local spec_type = type(param) if type(param) ~= "table" then internal_process_error( "spec for parameter %s must be a table of specs or the value true, but found %s.", name, spec_type ~= "boolean" and spec_type or param ) end -- Populate required table, and make sure aliases aren't set to required. if param.required then if required == nil then required = {} end required[name] = true end local listname, alias_of = param.list, param.alias_of if alias_of then validate_name(alias_of, "the alias_of field of parameter ", name) if alias_of == name then internal_process_error( "parameter %s cannot be an alias of itself.", name ) end local main_param = params[alias_of] -- Check that the alias_of is set to a valid parameter. if not (main_param == true or type(main_param) == "table") then internal_process_error( "parameter %s is an alias of an invalid parameter.", name ) end validate_alias_options(param, name, main_param, alias_of) -- Aliases can't be lists unless the canonical parameter is also a list. if listname and (main_param == true or not main_param.list) then internal_process_error( "list parameter %s is set as an alias of %s, which is not a list parameter.", name, alias_of ) -- Can't be an alias of an alias. elseif main_param ~= true then local main_alias_of = main_param.alias_of if main_alias_of ~= nil then internal_process_error( "alias_of cannot be set to another alias: parameter %s is set as an alias of %s, which is in turn an alias of %s. Set alias_of for %s to %s.", name, alias_of, main_alias_of, name, main_alias_of ) end end end local replaced_by = param.replaced_by if replaced_by then -- replaced_by can be `false`, which is OK validate_name(replaced_by, "the replaced_by field of parameter ", name) if replaced_by == name then internal_process_error( "parameter %s cannot be replaced by itself.", name ) end local main_param = params[replaced_by] -- Check that the replaced_by is set to a valid parameter. if not (main_param == true or type(main_param) == "table") then internal_process_error( "parameter %s is set to be replaced by an invalid parameter.", name ) end -- Can't be a replaced-by of a replaced-by. if main_param ~= true then local main_replaced_by = main_param.replaced_by if main_replaced_by ~= nil then internal_process_error( "replaced_by cannot be set to another replaced-by parameter: parameter %s is set as replaced by %s, which is in turn replaced by %s. Set replaced_by for %s to %s.", name, replaced_by, main_replaced_by, name, main_replaced_by ) end end if param.instead ~= nil then internal_process_error("the `instead` tag can only be given when `replaced_by` is set to `false`.") end elseif replaced_by == false then if param.instead ~= nil and type(param.instead) ~= "string" then internal_process_error( "the `instead` tag must be a string, but saw %s.", param.instead ) end end if replaced_by ~= nil then if param.reason ~= nil and type(param.reason) ~= "string" then internal_process_error( "the `reason` tag must be a string, but saw %s.", param.reason ) end end if listname then if not alias_of then local key = name if type(name) == "string" then key = gsub(name, "\1", "") end local list_arg = {maxindex = 0} args_new[key] = list_arg if list_args == nil then list_args = {} end list_args[key] = list_arg end local list_type = type(listname) if list_type == "string" then -- If the list property is a string, then it represents the name -- to be used as the prefix for list items. This is for use with lists -- where the first item is a numbered parameter and the -- subsequent ones are named, such as 1, pl2, pl3. patterns = save_pattern(name, listname, patterns or {}) elseif listname ~= true then internal_process_error( "list field for parameter %s must be a boolean, string or undefined, but saw a %s.", name, list_type ) elseif type(name) == "number" then if index_list ~= nil then internal_process_error( "only one numeric parameter can be a list, unless the list property is a string." ) end -- If the name is a number, then all indexed parameters from -- this number onwards go in the list. index_list = name else patterns = save_pattern(name, name, patterns or {}) end if find(name, "\1", nil, true) then if args_placeholders then placeholders_n = placeholders_n + 1 args_placeholders[placeholders_n] = name else args_placeholders, placeholders_n = {name}, 1 end end end end end --Process required changes to `params`. if args_placeholders then for i = 1, placeholders_n do local name = args_placeholders[i] params[gsub(name, "\1", "")], params[name] = params[name], nil end end -- Process the arguments for name, val in pairs(args) do any_args_set = true validate_name(name, "argument names", nil, true) -- Guaranteeing that all values are strings avoids issues with type coercion being inconsistent between functions. local val_type = type(val) if val_type ~= "string" then internal_process_error( "argument %s has the type %s; all arguments must be strings.", name, val_type ) end local orig_name, raw_type = name, type(name) local index, canonical if raw_type == "number" then if index_list and name >= index_list then index = name - index_list + 1 name = index_list end elseif patterns then -- Does this argument name match a pattern? for pattern, pname in next, patterns do index = match(name, pattern) -- It matches, so store the parameter name and the -- numeric index extracted from the argument name. if index then index = tonumber(index) name = pname break end end end local param = params[name] if not param and props.allow_params then param = props.allow_params(name) end -- If the argument is not in the list of parameters, store it in a separate list. if not param then args_unknown = unknown_param(name, val, args_unknown or {}) elseif param == true then canonical = orig_name val = php_trim(val) if val ~= "" then -- If the parameter is duplicated, throw an error. if args_new[name] ~= nil then process_error( "Parameter %s has been entered more than once. This is probably because a parameter alias has been used.", canonical ) end args_new[name] = val end else if param.replaced_by == false then process_error( ("Parameter %%s has been removed and is no longer valid%s.%s"):format( param.reason and ", " .. param.reason or "", param.instead and " Instead, " .. param.instead .. "." or ""), name ) elseif param.replaced_by then process_error( ("Parameter %%s has been replaced by %%s%s."):format( param.reason and ", " .. param.reason or ""), name, param.replaced_by ) end if param.deprecated then track("deprecated parameter", name) end if param.require_index then -- Disallow require_index for numeric parameter names, as this doesn't make sense. if raw_type == "number" then internal_process_error( "cannot set require_index for numeric parameter %s.", name ) -- If a parameter without the trailing index was found, and -- require_index is set on the param, treat it -- as if it isn't recognized. elseif not index then args_unknown = unknown_param(name, val, args_unknown or {}) end end -- Check that separate_no_index is not being used with a numeric parameter. if param.separate_no_index then if raw_type == "number" then internal_process_error( "cannot set separate_no_index for numeric parameter %s.", name ) elseif type(param.alias_of) == "number" then internal_process_error( "cannot set separate_no_index for parameter %s, as it is an alias of numeric parameter %s.", name, param.alias_of ) end end -- If no index was found, use 1 as the default index. -- This makes list parameters like g, g2, g3 put g at index 1. -- If `separate_no_index` is set, then use 0 as the default instead. if not index and param.list then index = param.separate_no_index and 0 or 1 end -- Normalize to the canonical parameter name. If it's a list, but the alias is not, then determine the index. local raw_name = param.alias_of if raw_name then raw_type = type(raw_name) if raw_type == "number" then name = raw_name local main_param = params[raw_name] if main_param ~= true and main_param.list then if not index then index = param.separate_no_index and 0 or 1 end canonical = raw_name + index - 1 else canonical = raw_name end else name = gsub(raw_name, "\1", "") local main_param = params[name] if not index and main_param ~= true and main_param.list then index = param.separate_no_index and 0 or 1 end if not index or index == 0 then canonical = name elseif name == raw_name then canonical = name .. index else canonical = gsub(raw_name, "\1", index) end end else canonical = orig_name end -- Only recognize demo parameters if this is the current template or module's -- page, or its documentation page. if param.demo and not is_own_page("include_documentation") then args_unknown = unknown_param(name, val, args_unknown or {}) end -- Remove leading and trailing whitespace unless no_trim is true. if param.no_trim then check_string_param_modifier(param.type, name, "no_trim") else val = php_trim(val) end -- Empty string is equivalent to nil unless allow_empty is true. if param.allow_empty then check_string_param_modifier(param.type, name, "allow_empty") elseif val == "" then -- If `disallow_missing` is set, keep track of empty parameters -- via the `empty` field in `arg`, which will be used by the -- `disallow_missing` check. This will be deleted before -- returning. if index and param.disallow_missing then local arg = args_new[name] local empty = arg.empty if empty == nil then empty = {maxindex = 0} arg.empty = empty end empty[index] = true if index > empty.maxindex then empty.maxindex = index end end val = nil end -- Allow boolean false. if val ~= nil then -- Convert to proper type if necessary. local main_param = params[raw_name] if main_param ~= true then val = convert_val(val, orig_name, main_param or param) end -- Mark it as no longer required, as it is present. if required then required[name] = nil end -- Store the argument value. if index then local arg = args_new[name] -- If the parameter is duplicated, throw an error. if arg[index] ~= nil then process_error( "Parameter %s has been entered more than once. This is probably because a list parameter has been entered without an index and with index 1 at the same time, or because a parameter alias has been used.", canonical ) end arg[index] = val -- Store the highest index we find. local maxindex = arg.maxindex if index > maxindex then maxindex = index end if arg[0] ~= nil then arg.default, arg[0] = arg[0], nil if maxindex < 1 then maxindex = 1 end end arg.maxindex = maxindex if not params[name].list then args_new[name] = val -- Don't store index 0, as it's a proxy for the default. elseif index > 0 then arg[index] = val end else -- If the parameter is duplicated, throw an error. if args_new[name] ~= nil then process_error( "Parameter %s has been entered more than once. This is probably because a parameter alias has been used.", canonical ) end if not raw_name then args_new[name] = val else local main_param = params[raw_name] if main_param ~= true and main_param.list then local main_arg = args_new[raw_name] main_arg[1] = val -- Store the highest index we find. if main_arg.maxindex < 1 then main_arg.maxindex = 1 end else args_new[raw_name] = val end end end end end end -- Remove holes in any list parameters if needed. This must be handled -- straight after the previous loop, as any instances of `empty` need to be -- converted to nil. if list_args then for name, val in next, list_args do handle_holes(params, val, name) end end -- If the current page is the template which invoked this Lua instance, then ignore the `require` flag, as it -- means we're viewing the template directly. Required parameters sometimes have a `template_default` key set, -- which gets used in such cases as a demo. -- Note: this won't work on other pages in the Template: namespace (including the /documentation subpage), -- or if the #invoke: is on a page in another namespace. local pagename_set = args_new.pagename -- Handle defaults. for name, param in pairs(params) do if param ~= true then local arg_new = args_new[name] if arg_new == nil then args_new[name] = convert_default_val(name, param, pagename_set, any_args_set, true) elseif param.list and arg_new[1] == nil then local default_val = convert_default_val(name, param, pagename_set, any_args_set) if default_val ~= nil then arg_new[1] = default_val if arg_new.maxindex == 0 then arg_new.maxindex = 1 end end end end end -- Flatten nested lists if called for. This must come after setting the default. if list_args then for name, val in next, list_args do args_new[name] = maybe_flatten(params, val, name) end end -- The required table should now be empty. -- If any parameters remain, throw an error, unless we're on the current template or module's page. if required and next(required) ~= nil and not is_own_page() then params_list_error(required, "required") -- Return the arguments table. If there are any unknown parameters, throw an error, unless return_unknown is set, -- in which case return args_unknown as a second return value. elseif props.return_unknown then return args_new, args_unknown or {} elseif args_unknown and next(args_unknown) ~= nil then params_list_error(args_unknown, "not used by this template") end return args_new end return export c6iobggtd1vtxa1ex5tah8gwyezp499 239028 239027 2026-11-15T04:07:18Z Lee 19 [[:en:Module:parameters]] වෙතින් එක් සංශෝධනයක් 239027 Scribunto text/plain --[==[TODO: * Change certain flag names, as some are misnomers: * Change `allow_holes` to `keep_holes`, because it's not the inverse of `disallow_holes`. * Change `allow_empty` to `keep_empty`, as it causes them to be kept as "" instead of deleted. * Sort out all the internal error calls. Manual error(format()) calls are used when certain parameters shouldn't be dumped, so find a way to avoid that. ]==] local export = {} local collation_module = "Module:collation" local families_module = "Module:families" local functions_module = "Module:fun" local gender_and_number_utilities_module = "Module:gender and number utilities" local labels_module = "Module:labels" local languages_module = "Module:languages" local math_module = "Module:math" local pages_module = "Module:pages" local parameters_finalize_set_module = "Module:parameters/finalizeSet" local parameters_track_module = "Module:parameters/track" local parse_utilities_module = "Module:parse utilities" local references_module = "Module:references" local scribunto_module = "Module:Scribunto" local scripts_module = "Module:scripts" local string_utilities_module = "Module:string utilities" local table_module = "Module:table" local wikimedia_languages_module = "Module:wikimedia languages" local yesno_module = "Module:yesno" local mw = mw local mw_title = mw.title local string = string local table = table local dump = mw.dumpObject local find = string.find local format = string.format local gsub = string.gsub local insert = table.insert local ipairs = ipairs local list_to_text = mw.text.listToText local make_title = mw_title.makeTitle local match = string.match local max = math.max local new_title = mw_title.new local next = next local pairs = pairs local pcall = pcall local require = require local sub = string.sub local tonumber = tonumber local type = type local unpack = unpack or table.unpack -- Lua 5.2 compatibility local current_title_text, current_namespace, sets -- Defined when needed. local namespaces = mw.site.namespaces --[==[ Loaders for functions in other modules, which overwrite themselves with the target function when called. This ensures modules are only loaded when needed, retains the speed/convenience of locally-declared pre-loaded functions, and has no overhead after the first call, since the target functions are called directly in any subsequent calls. ]==] local function decode_entities(...) decode_entities = require(string_utilities_module).decode_entities return decode_entities(...) end local function extend(...) extend = require(table_module).extend return extend(...) end local function finalize_set(...) finalize_set = require(parameters_finalize_set_module) return finalize_set(...) end local function get_family_by_code(...) get_family_by_code = require(families_module).getByCode return get_family_by_code(...) end local function get_family_by_name(...) get_family_by_name = require(families_module).getByCanonicalName return get_family_by_name(...) end local function get_language_by_code(...) get_language_by_code = require(languages_module).getByCode return get_language_by_code(...) end local function get_language_by_name(...) get_language_by_name = require(languages_module).getByCanonicalName return get_language_by_name(...) end local function get_script_by_code(...) get_script_by_code = require(scripts_module).getByCode return get_script_by_code(...) end local function get_script_by_name(...) get_script_by_name = require(scripts_module).getByCanonicalName return get_script_by_name(...) end local function get_wm_lang_by_code(...) get_wm_lang_by_code = require(wikimedia_languages_module).getByCode return get_wm_lang_by_code(...) end local function get_wm_lang_by_code_with_fallback(...) get_wm_lang_by_code_with_fallback = require(wikimedia_languages_module).getByCodeWithFallback return get_wm_lang_by_code_with_fallback(...) end local function gsplit(...) gsplit = require(string_utilities_module).gsplit return gsplit(...) end local function is_callable(...) is_callable = require(functions_module).is_callable return is_callable(...) end local function is_integer(...) is_integer = require(math_module).is_integer return is_integer(...) end local function is_internal_title(...) is_internal_title = require(pages_module).is_internal_title return is_internal_title(...) end local function is_positive_integer(...) is_positive_integer = require(math_module).is_positive_integer return is_positive_integer(...) end local function iterate_list(...) iterate_list = require(table_module).iterateList return iterate_list(...) end local function num_keys(...) num_keys = require(table_module).numKeys return num_keys(...) end local function parse_gender_and_number_spec(...) parse_gender_and_number_spec = require(gender_and_number_utilities_module).parse_gender_and_number_spec return parse_gender_and_number_spec(...) end local function parse_references(...) parse_references = require(references_module).parse_references return parse_references(...) end local function pattern_escape(...) pattern_escape = require(string_utilities_module).pattern_escape return pattern_escape(...) end local function php_trim(...) php_trim = require(scribunto_module).php_trim return php_trim(...) end local function scribunto_parameter_key(...) scribunto_parameter_key = require(scribunto_module).scribunto_parameter_key return scribunto_parameter_key(...) end local function sort(...) sort = require(collation_module).sort return sort(...) end local function sorted_pairs(...) sorted_pairs = require(table_module).sortedPairs return sorted_pairs(...) end local function split(...) split = require(string_utilities_module).split return split(...) end local function split_labels_on_comma(...) split_labels_on_comma = require(labels_module).split_labels_on_comma return split_labels_on_comma(...) end local function split_on_comma(...) split_on_comma = require(parse_utilities_module).split_on_comma return split_on_comma(...) end local function tonumber_extended(...) tonumber_extended = require(math_module).tonumber_extended return tonumber_extended(...) end local function track(...) track = require(parameters_track_module) return track(...) end local function yesno(...) yesno = require(yesno_module) return yesno(...) end --[==[ intro: This module is used to standardize template argument processing and checking. A typical workflow is as follows (based on [[Module:translations]]): { ... local parent_args = frame:getParent().args local params = { [1] = {required = true, type = "language", default = "und"}, [2] = true, [3] = {list = true}, ["alt"] = true, ["id"] = true, ["sc"] = {type = "script"}, ["tr"] = true, ["ts"] = true, ["lit"] = true, } local args = require("Module:parameters").process(parent_args, params) -- Do further processing of the parsed arguments in `args`. ... } The `params` table should have the parameter names as the keys, and a (possibly empty) table of parameter tags as the value. An empty table as the value merely states that the parameter exists, but should not receive any special treatment; if desired, empty tables can be replaced with the value `true` as a perforamnce optimization. Possible parameter tags are listed below: ; {required = true} : The parameter is required; an error is shown if it is not present. The template's page itself is an exception; no error is shown there. ; {default =} : Specifies a default input value for the parameter, if it is absent or empty. This will be processed as though it were the input instead, so (for example) {default = "und"} with the type {"language"} will return a language object for [[:Category:Undetermined language|Undetermined language]] if no language code is provided. (As an exception, numbers and booleans can be specified either as-is or in string format.) When used on list parameters, this specifies a default value for the first item in the list only. Note that it is not possible to generate a default that depends on the value of other parameters. If used together with {required = true}, the default applies only to template pages (see the following entry), as a side effect of the fact that "required" parameters aren't actually required on template pages. This can be used to show an example of the template in action when the template page is visited; however, it is preferred to use `template_default` for this purpose, for clarity. ; {template_default =} : Specifies a default input value for absent or empty parameters only on the template demo invocation (the invocation of the template that is displayed when the template page that implements the template is viewed). Template pages are pages in template space that invoke (through {{tl|#invoke:}}) the module that implements the template and calls [[Module:parameters]]. For example, the page [[Template:en-noun]] implements the {{tl|en-noun}} template, which in turn invokes [[Module:en-headword]], and is a template page for [[Module:en-headword]]. When the template page [[Template:en-noun]] is visited, the {{tl|#invoke:}} of the template's module is expanded as if the template were called without arguments, and the output is inserted at that point into the processed page. This output serves as a sort of demo of the template's functionality. `template_default` can be used to supply default values for use only in this demo. Since the template page may also contain other invocations of the same template (e.g. on the template's documentation page, which is typically transcluded into the template page itself), `template_default` does not apply if there are any arguments passed to the template or if the template is invoked on any other page but its own template page (which is checked by comparing the name of the invoking template to the current pagename). Both `template_default` and `default` can be specified for the same parameter. If this is done, `template_default` applies for the argumentless template invocation on the template page, and `default` in all other circumstances As an example, {{tl|cs-IPA}} uses the equivalent of {[1] = {default = "+", template_default = "příklad"}} to supply a default of {"+"} for mainspace and documentation pages (which tells the module to use the value of the {{para|pagename}} parameter, falling back to the actual pagename), but {"příklad"} (which means "example"), on [[Template:cs-IPA]]. ; {alias_of =} : Treat the parameter as an alias of another. When arguments are specified for this parameter, they will automatically be renamed and stored under the alias name. This allows for parameters with multiple alternative names, while still treating them as if they had only one name. The conversion-related properties of an aliased parameter (e.g. `type`, `set`, `convert`, `sublist`) are taken from the aliasee, and the corrresponding properties set on the alias itself are ignored; but other properties on the alias are taken from the alias's spec and not from the aliasee's spec. This means, for example, that if you create an alias of a list parameter, the alias must also specify the `list` property or it is not a list. (In such a case, a value specified for the alias goes into the first item of the aliasee's list. You cannot make a list alias of a non-list parameter; this causes an error to be thrown.) Similarly, if you specify `separate_no_index` on an aliasee but not on the alias, uses of the unindexed aliasee parameter are stored into the `.default` key, but uses of the unindexed alias are stored into the first numbered key of the aliasee's list. Aliases cannot be required, as this prevents the other name or names of the parameter from being used. Parameters that are aliases and required at the same time cause an error to be thrown. ; {allow_empty = true} : If the argument is an empty string value, it is not converted to {nil}, but kept as-is. The use of `allow_empty` is disallowed if a type has been specified, and causes an error to be thrown. ; {no_trim = true} : Spacing characters such as spaces and newlines at the beginning and end of a positional parameter are not removed. (MediaWiki itself automatically trims spaces and newlines at the edge of named parameters.) The use of `no_trim` is disallowed if a type has been specified, and causes an error to be thrown. ; {type =} : Specifies what value type to convert the argument into. The default is to leave it as a text string. Alternatives are: :; {type = "boolean"} :: The value is treated as a boolean value, either true or false. No value, the empty string, and the strings {"0"}, {"no"}, {"n"}, {"false"}, {"f"} and {"off"} (case-insensitive) are treated as {false}, all other values are considered {true}. :; {type = "boolean or string"} :: The value is treated as either a boolean value (true or false) or some other string value. The strings {"0"}, {"no"}, {"n"}, {"false"}, {"f"} and {"off"} (case-insensitive) are treated as {false}; the string {"1"}, {"yes"}, {"y"}, {"true"}, {"t"} and {"on"} (case-insensitive) are treated as {true}; and all other values are left as-is. You can use `set` to restrict the possible strings that are allowed; the values specified using `set` should not include {true} or {false}. :; {type = "number"} :: The value is converted into a number, and throws an error if the value is not parsable as a number. Input values may be signed (`+` or `-`), and may contain decimal points and leading zeroes. If {allow_hex = true}, then hexadecimal values in the form {"0x100"} may optionally be used instead, which otherwise have the same syntax restrictions (including signs, decimal digits, and leading zeroes after {"0x"}). Hexadecimal inputs are not case-sensitive. Lua's special number values (`inf` and `nan`) are not possible inputs. :; {type = "range"} :: The value is interpreted as a hyphen-separated range of two numbers (e.g. {"2-4"} is interpreted as the range from {2} to {4}). A number input without a hyphen is interpreted as a range from that number to itself (e.g. the input {"1"} is interpreted as the range from {1} to {1}). Any optional flags which are available for numbers will also work for ranges. :; {type = "language"} :: The value is interpreted as a full or [[Wiktionary:Languages#Etymology-only languages|etymology-only language]] code language code (or name, if {method = "name"}) and converted into the corresponding object (see [[Module:languages]]). If the code or name is invalid, then an error is thrown. The additional setting {family = true} can be given to allow [[Wiktionary:Language families|language family codes]] to be considered valid and the corresponding object returned. Note that to distinguish an etymology-only language object from a full language object, use {object:hasType("language", "etymology-only")}. :; {type = "full language"} :: The value is interpreted as a full language code (or name, if {method = "name"}) and converted into the corresponding object (see [[Module:languages]]). If the code or name is invalid, then an error is thrown. Etymology-only languages are not allowed. The additional setting {family = true} can be given to allow [[Wiktionary:Language families|language family codes]] to be considered valid and the corresponding object returned. :; {type = "Wikimedia language"} :: The value is interpreted as a code and converted into a Wikimedia language object. If the code is invalid, then an error is thrown. If {fallback = true} is specified, conventional language codes which are different from their Wikimedia equivalent will also be accepted as a fallback. :; {type = "family"} :: The value is interpreted as a language family code (or name, if {method = "name"}) and converted into the corresponding object (see [[Module:families]]). If the code or name is invalid, then an error is thrown. :; {type = "script"} :: The value is interpreted as a script code (or name, if {method = "name"}) and converted into the corresponding object (see [[Module:scripts]]). If the code or name is invalid, then an error is thrown. :; {type = "title"} :: The value is interpreted as a page title and converted into the corresponding object (see the [[mw:Extension:Scribunto/Lua_reference_manual#Title_library|Title library]]). If the page title is invalid, then an error is thrown; by default, external titles (i.e. those on other wikis) are not treated as valid. Options are: ::; {namespace = n} ::: The default namespace, where {n} is a namespace number; this is treated as {0} (the mainspace) if not specified. ::; {allow_external = true} ::: External titles are treated as valid. ::; {prefix = "namespace override"} (default) ::: The default namespace prefix will be prefixed to the value is already prefixed by a namespace prefix. For instance, the input {"Foo"} with namespace {10} returns {"Template:Foo"}, {"Wiktionary:Foo"} returns {"Wiktionary:Foo"}, and {"Template:Foo"} returns {"Template:Foo"}. Interwiki prefixes cannot act as overrides, however: the input {"fr:Foo"} returns {"Template:fr:Foo"}. ::; {prefix = "force"} ::: The default namespace prefix will be prefixed unconditionally, even if the value already appears to be prefixed. This is the way that {{tl|#invoke:}} works when calling modules from the module namespace ({828}): the input {"Foo"} returns {"Module:Foo"}, {"Wiktionary:Foo"} returns {"Module:Wiktionary:Foo"}, and {"Module:Foo"} returns {"Module:Module:Foo"}. ::; {prefix = "full override"} ::: The same as {prefix = "namespace override"}, except that interwiki prefixes can also act as overrides. For instance, {"el:All topics"} with namespace {14} returns {"el:Category:All topics"}. Due to the limitations of MediaWiki, only the first prefix in the value may act as an override, so the namespace cannot be overridden if the first prefix is an interwiki prefix: e.g. {"el:Template:All topics"} with namespace {14} returns {"el:Category:Template:All topics"}. :; {type = "parameter"} :: The value is interpreted as the name of a parameter, and will be normalized using the method that Scribunto uses when constructing a {frame.args} table of arguments. This means that integers will be converted to numbers, but all other arguments will remain as strings (e.g. {"1"} will be normalized to {1}, but {"foo"} and {"1.5"} will remain unchanged). Note that Scribunto also trims parameter names, following the same trimming method that this module applies by default to all parameter types. :: This type is useful when one set of input arguments is used to construct a {params} table for use in a subsequent {export.process()} call with another set of input arguments; for instance, the set of valid parameters for a template might be defined as {{tl|#invoke:[some module]|args=}} in the template, where {args} is a sublist of valid parameters for the template. :; {type = "qualifier"} :: The value is interpreted as a qualifier and converted into the correct format for passing into `format_qualifiers()` in [[Module:qualifier]] (which currently just means converting it to a one-item list). :; {type = "labels"} :: The value is interpreted as a comma-separated list of labels and converted into the correct format for passing into `show_labels()` in [[Module:labels]] (which is currently a list of strings). Splitting is done on commas not followed by whitespace, except that commas inside of double angle brackets do not count even if not followed by whitespace. This type should be used by for normal labels (typically specified using {{para|l}} or {{para|ll}}) and accent qualifiers (typically specified using {{para|a}} and {{para|aa}}). :; {type = "references"} :: The value is interpreted as one or more references, in the format prescribed by `parse_references()` in [[Module:references]], and converted into a list of objects of the form accepted by `format_references()` in the same module. If a syntax error is found in the reference format, an error is thrown. :; {type = "genders"} :: The value is interpreted as one or more comma-separated gender/number specs, in the format prescribed by [[Module:gender and number]]. Inline modifiers (`<q:...>`, `<qq:...>`, `<l:...>`, `<ll:...>` or `<ref:...>`) may be attached to a gender/number spec. :; {type = "form of tags"} :: The value is interpreted as an ampersand-separated list of grammar tags and converted into the correct format for passing as `tags` into `tagged_inflections()` in [[Module:form of]] (which is currently a list of strings). Splitting is always done by ampersands. This type should be used by for inflection qualifiers that act as grammar tags (typically specified using {{para|infl}}). :; {type = function(val) ... end} :: `type` may be set to a function (or callable table), which must take the argument value as its sole argument, and must output one of the other recognized types. This is particularly useful for lists (see below), where certain values need to be interpreted differently to others. ; {list =} : Treat the parameter as a list of values, each having its own parameter name, rather than a single value. The parameters will have a number at the end, except optionally for the first (but see also {require_index = true}). For example, {list = true} on a parameter named "head" will include the parameters {{para|head}} (or {{para|head1}}), {{para|head2}}, {{para|head3}} and so on. If the parameter name is a number, another number doesn't get appended, but the counting simply continues, e.g. for parameter {3} the sequence is {{para|3}}, {{para|4}}, {{para|5}} etc. List parameters are returned as numbered lists, so for a template that is given the parameters `|head=a|head2=b|head3=c`, the processed value of the parameter {"head"} will be { { "a", "b", "c" }}}. : The value for {list =} can also be a string. This tells the module that parameters other than the first should have a different name, which is useful when the first parameter in a list is a number, but the remainder is named. An example would be for genders: {list = "g"} on a parameter named {1} would have parameters {{para|1}}, {{para|g2}}, {{para|g3}} etc. : If the number is not located at the end, it can be specified by putting {"\1"} at the number position. For example, parameters {{para|f1accel}}, {{para|f2accel}}, ... can be captured by using the parameter name {"f\1accel"}, as is done in [[Module:headword/templates]]. ; {set =} : Require that the value of the parameter be one of the specified values (or omitted, if {required = true} isn't given). Two formats are allowed; either a list of possible values can be supplied, or a table can be supplied where the keys are allowed values and the values are either `true` or a string naming a value found elsewhere in the table as a key. In the latter case, the key is an alias and the value is the canonical value, and if the user uses the alias, it will automatically be mapped to the canonical value. In such a case, the canonical value cannot itself be an alias. The use of `set` is disallowed if {type = "boolean"} and causes an error to be thrown. The values given should be strings (i.e. pre-conversion values) unless {type = "number"}, in which case they should be numbers. If {type = "boolean or string"}, the values specified using {set =} are those that ''cannot'' be interpreted as a boolean; boolean strings (e.g. {"1"}, {"0"}, {"true"}, {"false"}, etc.) are always allowed in addition. ; {sublist =} : The value of the parameter is a delimiter-separated list of individual raw values. The resulting field in `args` will be a Lua list (i.e. a table with numeric indices) of the converted values. If {sublist = true} is given, the values will be split on commas (possibly with whitespace on one or both sides of the comma, which is ignored). If {sublist = "comma without whitespace"} is given, the values will be split on commas which are not followed by whitespace, and which aren't preceded by an escaping backslash. Otherwise, the value of `sublist` should be either a Lua pattern specifying the delimiter(s) to split on or a function (or callable table) to do the splitting, which is passed two values (the value to split and a function to signal an error) and should return a list of the split values. ; {convert =} : If given, this specifies a function (or callable table) to convert the raw parameter value into the Lua object used during further processing. The function is passed two arguments, the raw parameter value itself and a function used to signal an error during parsing or conversion, and should return one value, the converted parameter. The error-signaling function contains the name and raw value of the parameter embedded into the message it generates, so these do not need to specified in the message passed into it. If `type` is specified in conjunction with `convert`, the processing by `type` happens first. If `sublist` is given in conjunction with `convert`, the raw parameter value will be split appropriately and `convert` called on each resulting item. ; {allow_hex = true} : When used in conjunction with {type = "number"}, allows hexadecimal numbers as inputs, in the format {"0x100"} (which is not case-sensitive). ; {family = true} : When used in conjunction with {type = "language"}, allows [[Wiktionary:Language families|language family codes]] to be returned. To check if a given object refers to a language family, use {object:hasType("family")}. ; {method = "name"} : When used in conjunction with {type = "language"}, {type = "family"} or {type = "script"}, checks for and parses a language, family or script name instead of a code. ; {allow_holes = true} : This is used in conjunction with list-type parameters. By default, the values are tightly packed in the resulting list. This means that if, for example, an entry specified `head=a|head3=c` but not {{para|head2}}, the returned list will be { {"a", "c"}}}, with the values stored at the indices {1} and {2}, not {1} and {3}. If it is desirable to keep the numbering intact, for example if the numbers of several list parameters correlate with each other (like those of {{tl|affix}}), then this tag should be specified. : If {allow_holes = true} is given, there may be {nil} values in between two real values, which makes many of Lua's table processing functions no longer work, like {#} or {ipairs()}. To remedy this, the resulting table will contain an additional named value, `maxindex`, which tells you the highest numeric index that is present in the table. In the example above, the resulting table will now be { { "a", nil, "c", maxindex = 3}}}. That way, you can iterate over the values from {1} to `maxindex`, while skipping {nil} values in between. ; {disallow_holes = true} : This is used in conjunction with list-type parameters. As mentioned above, normally if there is a hole in the source arguments, e.g. `head=a|head3=c` but not {{para|head2}}, it will be removed in the returned list. If {disallow_holes = true} is specified, however, an error is thrown in such a case. This should be used whenever there are multiple list-type parameters that need to line up (e.g. both {{para|head}} and {{para|tr}} are available and {{para|head3}} lines up with {{para|tr3}}), unless {allow_holes = true} is given and you are prepared to handle the holes in the returned lists. ; {disallow_missing = true} : This is similar to {disallow_holes = true}, but an error will not be thrown if an argument is blank, rather than completely missing. This may be used to tolerate intermediate blank numerical parameters, which sometimes occur in list templates. For instance, `head=a|head2=|head3=c` will not throw an error, but `head=a|head3=c` will. ; {require_index = true} : This is used in conjunction with list-type parameters. By default, the first parameter can have its index omitted. For example, a list parameter named `head` can have its first parameter specified as either {{para|head}} or {{para|head1}}. If {require_index = true} is specified, however, only {{para|head1}} is recognized, and {{para|head}} will be treated as an unknown parameter. {{tl|affixusex}} (and variants {{tl|suffixusex}}, {{tl|prefixusex}}) use this, for example, on all list parameters. ; {separate_no_index = true} : This is used to distinguish between {{para|head}} and {{para|head1}} as different parameters. For example, in {{tl|affixusex}}, to distinguish between {{para|sc}} (a script code for all elements in the usex's language) and {{para|sc1}} (the script code of the first element, used when the first element is prefixed with a language code to indicate that it is in a different language). When this is used, the resulting table will contain an additional named value, `default`, which contains the value for the indexless argument. ; {flatten = true} : This is used in conjunction with list-type parameters when `sublist` or a list-generating type such as {"labels"} or {"genders"} is also specified, and causes the resulting list to be flattened. Not currently compatible with {allow_holes = true}. ; {replaced_by =} : Specifies that the parameter is no longer valid, and has been replaced by some other mechanism. If the value of `replaced_by` is a string, it is the name of the new parameter to use instead. Use the `reason` tag to specify the reason why this change has been made, e.g. {reason = "for consistency with the corresponding parameter in other Romance-language headword templates"}. If the value of `replaced_by` is {false}, there is no replacement parameter. In this case, `instead` should be supplied with a description of what to do instead, e.g. {instead = "use an inline modifier on |2= such as <q:...>, <qq:...>, <l:...> or <ll:...>"}. You can also supply a justification in `reason` if you feel it is appropriate or necessary to do so. ; {reason =} : When used in conjunction with `replaced_by`, specifies the reason for the parameter replacement. ; {instead =} : When used in conjunction with {replaced_by = false}, specifies what to do instead of using the removed parameter. ; {demo = true} : This is used as a way to ensure that the parameter is only enabled on the template's own page (and its documentation page), and in the User: namespace; otherwise, it will be treated as an unknown parameter. This should only be used if special settings are required to showcase a template in its documentation (e.g. adjusting the pagename or disabling categorization). In most cases, it should be possible to do this without using demo parameters, but they may be required if a template/documentation page also contains real uses of the same template as well (e.g. {{tl|shortcut}}), as a way to distinguish them. ; {deprecated = true} : This is for tracking the use of deprecated parameters, including any aliases that are being brought out of use. See [[Wiktionary:Tracking]] for more information. ]==] -- Returns true if the current page is a template or module containing the current {{#invoke}}. -- If the include_documentation argument is given, also returns true if the current page is either page's documentation page. local own_page, own_page_or_documentation local function is_own_page(include_documentation) if own_page == nil then if current_namespace == nil then local current_title = mw_title.getCurrentTitle() current_title_text, current_namespace = current_title.prefixedText, current_title.namespace end local frame = current_namespace == 828 and mw.getCurrentFrame() or current_namespace == 10 and mw.getCurrentFrame():getParent() if frame then local frame_title_text = frame:getTitle() own_page = current_title_text == frame_title_text own_page_or_documentation = own_page or current_title_text == frame_title_text .. "/documentation" else own_page, own_page_or_documentation = false, false end end return include_documentation and own_page_or_documentation or own_page end -------------------------------------- Some helper functions ----------------------------- -- Convert a list in `list` to a string, separating the final element from the preceding one(s) by `conjunction`. If -- `dump_vals` is given, pass all values in `list` through mw.dumpObject() (WARNING: this destructively modifies -- `list`). This is similar to serialCommaJoin() in [[Module:table]] when used with the `dontTag = true` option, but -- internally uses mw.text.listToText(). local function concat_list(list, conjunction, dump_vals) if dump_vals then for k, v in pairs(list) do list[k] = dump(v) end end return list_to_text(list, nil, conjunction) end -- A helper function for use with generating error-signaling functions in the presence of raw value conversion. Format a -- message `msg`, including the processed value `processed` if it is different from the raw value `rawval`; otherwise, -- just return `msg`. local function msg_with_processed(msg, rawval, processed) if rawval == processed then return msg end local processed_type = type(processed) return format("%s (processed value %s)", msg, (processed_type == "string" or processed_type == "number") and processed or dump(processed) ) end -- Separate form of tags with ampersand (&). local function split_tags_on_ampersand(tags) return split(tags, "&") end -------------------------------------- Error handling ----------------------------- local function process_error(fmt, ...) local args = {...} for i, val in ipairs(args) do args[i] = dump(val) end if type(fmt) == "table" then -- hacky signal that we're called from internal_process_error(), and not to omit stack frames return error(format(fmt[1], unpack(args))) end return error(format(fmt, unpack(args)), 3) end local function internal_process_error(fmt, ...) process_error({"Internal error in `params` table: " .. fmt}, ...) end -- Check that a parameter or argument is in the form form Scribunto normalizes input argument keys into (e.g. 1 not "1", "foo" not " foo "). Otherwise, it won't be possible to normalize inputs in the expected way. Unless is_argument is set, also check that the name only contains one placeholder at most, and that strings don't resolve to numeric keys once the placeholder has been substituted. local function validate_name(name, desc, extra_name, is_argument) local normalized = scribunto_parameter_key(name) if name and name == normalized then if is_argument or type(name) ~= "string" then return end local placeholder = find(name, "\1", nil, true) if not placeholder then return elseif find(name, "\1", placeholder + 1, true) then error(format( "Internal error: expected %s to only contain one placeholder, but saw %s", extra_name and (desc .. dump(extra_name)) or desc, dump(name) )) end local first_name = gsub(name, "\1", "1") normalized = scribunto_parameter_key(first_name) if first_name == normalized then return end error(format( "Internal error: %s cannot resolve to numeric parameters once any placeholder has been substituted, but %s resolves to %s", extra_name and (desc .. dump(extra_name)) or desc, dump(name), dump(normalized) )) elseif normalized == nil then error(format( "Internal error: expected %s to be of type string or number, but saw %s", extra_name and (desc .. dump(extra_name)) or desc, type(name) )) end error(format( "Internal error: expected %s to be Scribunto-compatible: %s (a %s) should be %s (a %s)", extra_name and (desc .. dump(extra_name)) or desc, dump(name), type(name), dump(normalized), type(normalized) )) end local function validate_alias_options(...) local invalid = { required = true, default = true, template_default = true, allow_holes = true, disallow_holes = true, disallow_missing = true, } function validate_alias_options(param, name, main_param, alias_of) for k in pairs(param) do if invalid[k] then track("bad alias option") -- internal_process_error( -- "parameter %s cannot have the option %s, as it is an alias of parameter %s.", -- name, option, alias_of -- ) end end -- Soon, aliases will inherit options from the main parameter via __index. Track cases where this would happen. if main_param ~= true then for k in pairs(main_param) do if param[k] == nil and not invalid[k] then if k == "list" then -- these need to be changed to list = false to retain current behaviour track("mismatched list alias option") elseif not (k == "type" or k == "set" or k == "sublist") then -- rarely specified on aliases, as they're effectively inherited already track("mismatched alias option") end end end end end validate_alias_options(...) end -- TODO: give ranges instead of long lists, if possible. --[==[ func: export.params_list_error(params, msg) Given a key-value table of raw parameters `params`, display an error message about all the parameters seen in the table. The parameter names are displayed in sorted order. `msg` should be e.g. {"required"} or {"not used by this template"}. This is used internally to display error messages about required or invalid parameters, and can be used for the same purpose by code that processes its own parameters (e.g. if the `props.return_unknown` flag is specified to `process`). ]==] local function params_list_error(params, msg) local list, n = {}, 0 for name in sorted_pairs(params) do n = n + 1 list[n] = name end error(format( "Parameter%s %s.", format(n == 1 and " %s is" or "s %s are", concat_list(list, " and ", true)), msg ), 3) end export.params_list_error = params_list_error -- Helper function for use with convert_val_error(). Format a list of possible choices using `concat_list` and -- conjunction "or", displaying "either " before the choices if there's more than one. local function format_choice_list(valid) return (#valid > 1 and "either " or "") .. concat_list(valid, " or ") end -- Signal an error for a value `val` that is not of the right type `valid` (which is either a string specifying a type, or -- a list of possible values, in the case where `set` was used). `name` is the name of the parameter and can be a -- function to signal an error (which is assumed to automatically display the parameter's name and value). `seetext` is -- an optional additional explanatory link to display (e.g. [[WT:LOL]], the list of possible languages and codes). local function convert_val_error(val, name, valid, seetext) if is_callable(name) then if type(valid) == "table" then valid = "choice, must be " .. format_choice_list(valid) end name(format("Invalid %s; the value %s is not valid%s", valid, val, seetext and "; see " .. seetext or "")) else if type(valid) == "table" then valid = format_choice_list(valid) else valid = "a valid " .. valid end error(format("Parameter %s must be %s; the value %s is not valid.%s", dump(name), valid, dump(val), seetext and " See " .. seetext .. "." or "")) end end -- Generate the appropriate error-signaling function given parameter value `val` and name `name`. If `name` is already -- a function, it is just returned; otherwise a function is generated and returned that displays the passed-in messaeg -- along with the parameter's name and value. local function make_parse_err(val, name) if is_callable(name) then return name end return function(msg) error(format("%s: parameter %s=%s", msg, name, val)) end end -------------------------------------- Value conversion ----------------------------- -- For a list parameter `name` and corresponding value `list_name` of the `list` field (which should have the same value -- as `name` if `list = true` was given), generate a pattern to match parameters of the list and store the pattern as a -- key in `patterns`, with corresponding value set to `name`. For example, if `list_name` is "tr", the pattern will -- match "tr" as well as "tr1", "tr2", ..., "tr10", "tr11", etc. If the `list_name` contains a \1 in it, the numeric -- portion goes in place of the \1. For example, if `list_name` is "f\1accel", the pattern will match "faccel", -- "f1accel", "f2accel", etc. Any \1 in `name` is removed before storing into `patterns`. local function save_pattern(name, list_name, patterns) name = type(name) == "string" and gsub(name, "\1", "") or name if find(list_name, "\1", nil, true) then patterns["^" .. gsub(pattern_escape(list_name), "\1", "([1-9]%%d*)") .. "$"] = name else patterns["^" .. pattern_escape(list_name) .. "([1-9]%d*)$"] = name list_name = list_name .. "\1" end validate_name(list_name, "the list field of parameter ", name) return patterns end -- A helper function for use with `sublist`. It is an iterator function for use in a for-loop that returns split -- elements of `val` using `sublist` (a Lua split pattern; boolean `true` to split on commas optionally surrounded by -- whitespace; "comma without whitespace" to split only on commas not followed by whitespace which have not been escaped -- by a backslash; or a function to do the splitting, which is passed two values, the value to split and a function to -- signal an error, and should return a list of the split elements). `name` is the parameter name or error-signaling -- function passed into convert_val(). local function split_sublist(val, name, sublist) if sublist == true then return gsplit(val, "%s*,%s*") -- Split an argument on comma, but not comma followed by whitespace. elseif sublist == "comma without whitespace" then -- If difficult cases, use split_on_comma. if find(val, "\\", nil, true) or match(val, ",%s") then return iterate_list(split_on_comma(val)) end -- Otherwise, use gsplit. return gsplit(val, ",") elseif type(sublist) == "string" then return gsplit(val, sublist) elseif not is_callable(sublist) then error(format('Internal error: expected `sublist` to be of type "string" or "function" or boolean `true`, but saw %s', dump(sublist))) end return iterate_list(sublist(val, make_parse_err(val, name))) end --[=[ For parameter named `name` with value `val` and param spec `param`, if the `set` field is specified, verify that the value is one of the one specified in `set`, and throw an error otherwise. `name` is taken directly from the corresponding parameter passed into convert_val() and may be a function to signal an error. Optional `param_type` is a string specifying the conversion type of `val` and is used for special-casing: If `param_type` is "boolean", an internal error is thrown (since `set` cannot be used in conjunction with booleans); and if `param_type` is "number" or "boolean or string", and `called_from_converter` is not given, no checking happens because in these cases `set` needs to be called by the conversion function itself (respectively after converting `val` to a number or processing boolean strings). Return the canonical value of `val` (which may be different from `val` if an alias map is given). ]=] local function check_set(val, name, param, param_type, called_from_converter) -- Needs to be special cased because the check happens after conversion to numbers. if (param_type == "number" or param_type == "boolean or string") and not called_from_converter then return val end local set = param.set local map if sets == nil then map = finalize_set(set, name) sets = {[set] = map} else map = sets[set] if map == nil then map = finalize_set(set, name) sets[set] = map end end local newval = map[val] if newval == true then return val elseif newval ~= nil then return newval end local list = {} for k, v in sorted_pairs(map) do if v == true then insert(list, dump(k)) else insert(list, ("%s (alias of %s)"):format(dump(k), dump(v))) end end -- If the parameter type is "boolean or string", put "a boolean string value" because such values are allowed. if param_type == "boolean or string" then insert(list, "a boolean string value") end -- If the parameter is not required then put "or empty" at the end of the list, to avoid implying the parameter is -- actually required. if not param.required then insert(list, "empty") end convert_val_error(val, name, list) end local function convert_language(val, name, param, allow_etym) local method = param.method local func if method == nil or method == "code" then func, method = get_language_by_code, "code" elseif method == "name" then func, method = get_language_by_name, "name" else error(format('Internal error: expected `method` for type `language` to be "code", "name" or undefined, but saw %s', dump(method))) end local lang = func(val, nil, allow_etym, param.family) if lang then return lang end local list, links = {"language"}, {"[[WT:LOL]]"} if allow_etym then insert(list, "etymology language") insert(links, "[[WT:LOL/E]]") end if param.family then insert(list, "family") insert(links, "[[WT:LOF]]") end convert_val_error(val, name, concat_list(list, " or ") .. " " .. (method == "name" and "name" or "code"), concat_list(links, " and ")) end local function convert_number(val, allow_hex) -- Call tonumber_extended with the `real_finite` flag, which filters out ±infinity and NaN. -- By default, specify base 10, which prevents 0x hex inputs from being converted. -- If `allow_hex` is set, then don't give a base, which means 0x hex inputs will work. local num = tonumber_extended(val, not allow_hex and 10 or nil, "finite_real") if not num then return num end if match(val, "[eEpP.]") then -- float track("number not an integer") end if find(val, "+", nil, true) then track("number with +") end -- Track various unusual number inputs to determine if it should be restricted to positive integers by default (possibly including 0). if not is_positive_integer(num) then track("number not a positive integer") if num == 0 then track("number is 0") elseif not is_integer(num) then track("number not an integer") end end return num end -- TODO: validate parameter specs separately, as it's making the handler code really messy at the moment. local type_handlers = setmetatable({ ["boolean"] = function(val, name, param) local newval = yesno(val, val) if newval ~= true and newval ~= false then newval = true end return newval end, ["boolean or string"] = function(val, name, param) local newval = yesno(val, val) if newval ~= true and newval ~= false then if param.set then newval = check_set(newval, name, param, "boolean or string", "called_from_converter") else newval = true end end return newval end, ["family"] = function(val, name, param) local method = param.method local func if method == nil or method == "code" then func, method = get_family_by_code, "code" elseif method == "name" then func, method = get_family_by_name, "name" else error(format('Internal error: expected `method` for type `family` to be "code", "name" or undefined, but saw %s', dump(method))) end return func(val) or convert_val_error(val, name, "family " .. method, "[[WT:LOF]]") end, ["labels"] = function(val, name, param) -- FIXME: Should be able to pass in a parse_err function. return split_labels_on_comma(val) end, ["form of tags"] = function(val, name, param) return split_tags_on_ampersand(val) end, ["language"] = function(val, name, param) return convert_language(val, name, param, true) end, ["full language"] = convert_language, ["number"] = function(val, name, param) local allow_hex = param.allow_hex if allow_hex and allow_hex ~= true then error(format( 'Internal error: expected `allow_hex` for type `number` to be of type "boolean" or undefined, but saw %s', dump(allow_hex) )) end local num = convert_number(val, allow_hex) if param.set then num = check_set(num, name, param, "number", "called_from_converter") end if num then return num end convert_val_error(val, name, (allow_hex and "decimal or hexadecimal " or "") .. "number") end, ["range"] = function(val, name, param) local allow_hex = param.allow_hex if allow_hex and allow_hex ~= true then error(format( 'Internal error: expected `allow_hex` for type `range` to be of type "boolean" or undefined, but saw %s', dump(allow_hex) )) end -- Pattern ensures leading minus signs are accounted for. local m1, m2 = match(val, "^(%s*%S.-)%-(%s*%S.*)") if m1 then m1 = convert_number(m1, allow_hex) if m1 then m2 = convert_number(m2, allow_hex) if m2 then return {m1, m2} end end end -- Try `val` if it couldn't be split into a range, and return a range of `val` to `val` if possible. local num = convert_number(val, allow_hex) if num then return {num, num} end convert_val_error(val, name, (allow_hex and "decimal or hexadecimal " or "") .. "number or a hyphen-separated range of two numbers") end, ["parameter"] = function(val, name, param) -- Use the `no_trim` option, as any trimming will have already been done. return scribunto_parameter_key(val, true) end, ["qualifier"] = function(val, name, param) return {val} end, ["references"] = function(val, name, param) return parse_references(val, make_parse_err(val, name)) end, ["genders"] = function(val, name, param) if not val:find("[,<]") then return {{spec = val}} end -- NOTE: We don't pass in allow_space_around_comma. Consistent with other comma-separated types, there shouldn't -- be spaces around the comma. return parse_gender_and_number_spec { spec = val, parse_err = make_parse_err(val, name), allow_multiple = true, } end, ["script"] = function(val, name, param) local method = param.method local func if method == nil or method == "code" then func, method = get_script_by_code, "code" elseif method == "name" then func, method = get_script_by_name, "name" else error(format('Internal error: expected `method` for type `script` to be "code", "name" or undefined, but saw %s', dump(method))) end return func(val) or convert_val_error(val, name, "script " .. method, "[[WT:LOS]]") end, ["string"] = function(val, name, param) -- To be removed as unnecessary. track("string") return val end, -- TODO: add support for resolving to unsupported titles. -- TODO: split this into "page name" (i.e. internal) and "link target" (i.e. external as well), which is more intuitive. ["title"] = function(val, name, param) local namespace = param.namespace if namespace == nil then namespace = 0 else local valid_type = type(namespace) ~= "number" and 'of type "number" or undefined' or not namespaces[namespace] and "a valid namespace number" or nil if valid_type then error(format('Internal error: expected `namespace` for type `title` to be %s, but saw %s', valid_type, dump(namespace))) end end -- Decode entities. WARNING: mw.title.makeTitle must be called with `decoded` (as it doesn't decode) and mw.title.new must be called with `val` (as it does decode, so double-decoding needs to be avoided). local decoded, prefix = decode_entities(val), param.prefix local title -- If the input is a fragment, treat the title as the current title with the input fragment. if sub(decoded, 1, 1) == "#" then -- If prefix is "force", only get the current title if it's in the specified namespace. current_title includes the namespace prefix. if current_namespace == nil then local current_title = mw_title.getCurrentTitle() current_title_text, current_namespace = current_title.prefixedText, current_title.namespace end if not (prefix == "force" and namespace ~= current_namespace) then title = new_title(current_title_text .. val) end elseif prefix == "force" then -- Unconditionally add the namespace prefix (mw.title.makeTitle). title = make_title(namespace, decoded) elseif prefix == "full override" then -- The first input prefix will be used as an override (mw.title.new). This can be a namespace or interwiki prefix. title = new_title(val, namespace) elseif prefix == nil or prefix == "namespace override" then -- Only allow namespace prefixes to override. Interwiki prefixes therefore need to be treated as plaintext (e.g. "el:All topics" with namespace 14 returns "el:Category:All topics", but we want "Category:el:All topics" instead; if the former is really needed, then the input ":el:Category:All topics" will work, as the initial colon overrides the namespace). mw.title.new can take namespace names as well as numbers in the second argument, and will throw an error if the input isn't a valid namespace, so this can be used to determine if a prefix is for a namespace, since mw.title.new will return successfully only if there's either no prefix or the prefix is for a valid namespace (in which case we want the override). local success success, title = pcall(new_title, val, match(decoded, "^.-%f[:]") or namespace) -- Otherwise, get the title with mw.title.makeTitle, which unconditionally adds the namespace prefix, but behaves like mw.title.new if the namespace is 0. if not success then title = make_title(namespace, decoded) end else error(format('Internal error: expected `prefix` for type `title` to be "force", "full override", "namespace override" or undefined, but saw %s', dump(prefix))) end local allow_external = param.allow_external if allow_external == true then return title or convert_val_error(val, name, "Wiktionary or external page title") elseif not allow_external then return title and is_internal_title(title) and title or convert_val_error(val, name, "Wiktionary page title") end error(format('Internal error: expected `allow_external` for type `title` to be of type "boolean" or undefined, but saw %s', dump(allow_external))) end, ["Wikimedia language"] = function(val, name, param) local fallback = param.fallback if fallback == true then return get_wm_lang_by_code_with_fallback(val) or convert_val_error(val, name, "Wikimedia language or language code") elseif not fallback then return get_wm_lang_by_code(val) or convert_val_error(val, name, "Wikimedia language code") end error(format('Internal error: expected `fallback` for type `Wikimedia language` to be of type "boolean" or undefined, but saw %s', dump(fallback))) end, }, { -- TODO: decode HTML entities in all input values. Non-trivial to implement, because we need to avoid any downstream -- functions decoding the output from this module, which would be double-decoding. Note that "title" has this -- implemented already, and it needs to have both the raw input and the decoded input to avoid double-decoding by -- mw.title.new, so any implementation can't be as simple as decoding in __call then passing the result to the -- handler. __call = function(self, val, name, param, param_type, default) local val_type = type(val) -- TODO: check this for all possible parameter types. if val_type == param_type or val_type == "boolean" and param_type == "boolean or string" then return val elseif val_type ~= "string" then local expected = "string" if default then if param_type == "boolean or string" then expected = param_type elseif param_type == "boolean" or param_type == "number" then expected = param_type .. " or " .. expected end end error(format( "Internal error: %sargument %s has the type %s; expected a %s.", default and (default .. " for ") or "", name, dump(val_type), expected )) end local func = self[param_type] if func == nil then error(format("Internal error: %s is not a recognized parameter type.", dump(param_type))) end return func(val, name, param) end }) --[==[ func: export.convert_val(val, name, param) Convert a parameter value according to the associated specs listed in the `params` table passed to [[Module:parameters]]. `val` is the value to convert for a parameter whose name is `name` (used only in error messages). `param` is the spec (the value part of the `params` table for the parameter). In place of passing in the parameter name, `name` can be a function that throws an error, displaying the specified message along with the parameter name and value. This function processes all the conversion-related fields in `param`, including `type`, `set`, `sublist`, `convert`, etc. It returns the converted value. ]==] local function convert_val(val, name, param, default) local param_type = param.type or "string" -- If param.type is a function, resolve it to a recognized type. if is_callable(param_type) then param_type = param_type(val) end local convert, sublist = param.convert, param.sublist -- `val` might not be a string if it's the default value. if sublist and type(val) == "string" then local retlist, set = {}, param.set if convert then local thisindex = 0 local thisval, insval, parse_err if is_callable(name) then -- We assume the passed-in error function in `name` already shows the parameter name and raw value. function parse_err(msg) name(format("%s: item #%s=%s", msg_with_processed(msg, thisval, insval), thisindex, thisval) ) end else function parse_err(msg) error(format("%s: item #%s=%s of parameter %s=%s", msg_with_processed(msg, thisval, insval), thisindex, thisval, name, val) ) end end for v in split_sublist(val, name, sublist) do thisindex, thisval = thisindex + 1, v if set then v = check_set(v, name, param, param_type) end insval = v insert(retlist, convert(type_handlers(v, name, param, param_type, default), parse_err)) end else for v in split_sublist(val, name, sublist) do if set then v = check_set(v, name, param, param_type) end insert(retlist, type_handlers(v, name, param, param_type, default)) end end return retlist elseif param.set then val = check_set(val, name, param, param_type) end local retval = type_handlers(val, name, param, param_type, default) if convert then local parse_err if is_callable(name) then -- We assume the passed-in error function in `name` already shows the parameter name and raw value. if retval == val then -- This is an optimization to avoid creating a closure. The second arm works correctly even -- when retval == val. parse_err = name else function parse_err(msg) name(msg_with_processed(msg, val, retval)) end end else function parse_err(msg) error(format("%s: parameter %s=%s", msg_with_processed(msg, val, retval), name, val)) end end retval = convert(retval, parse_err) end -- If `sublist` is set but the input wasn't a string, return `retval` as a one-item list. if sublist then retval = {retval} end return retval end export.convert_val = convert_val -- used by [[Module:parameter utilities]] local function unknown_param(name, val, args_unknown) track("unknown parameters") args_unknown[name] = val return args_unknown end local function check_string_param_modifier(param_type, name, tag) if param_type and not (param_type == "string" or param_type == "parameter" or is_callable(param_type)) then internal_process_error( "%s cannot be set unless %s is set to %s (the default), %s or a function: parameter %s has the type %s.", tag, "type", "string", "parameter", name, param_type ) end end local function hole_error(params, name, listname, this, nxt, extra) -- `process_error` calls `dump` on values to be inserted into -- error messages, but with numeric lists this causes "numeric" -- to look like the name of the list rather than a description, -- as `dump` adds quote marks. Insert it early to avoid this, -- but add another %s specifier in all other cases, so that -- actual list names will be displayed properly. local offset, specifier, starting_from = 0, "%s", "" local msg = "Item %%d in the list of %s parameters must be given if item %%d is given, because %sthere shouldn't be any gaps due to missing%s parameters." local specs = {} if type(listname) == "string" then specs[2] = listname elseif type(name) == "number" then offset = name - 1 -- To get the original parameter. specifier = "numeric" -- If the list doesn't start at parameter 1, avoid implying -- there can't be any gaps in the numeric parameters if -- some parameter with a lower key is optional. for j = name - 1, 1, -1 do local _param = params[j] if not (_param and _param.required) then starting_from = format("(starting from parameter %d) ", dump(j + 1)) break end end else specs[2] = name end specs[1] = this + offset -- Absolute index for this item. insert(specs, nxt + offset) -- Absolute index for the next item. process_error(format(msg, specifier, starting_from, extra or ""), unpack(specs)) end local function check_disallow_holes(params, val, name, listname, extra) for i = 1, val.maxindex do if val[i] == nil then hole_error(params, name, listname, i, num_keys(val)[i], extra) end end end local function handle_holes(params, val, name) local param = params[name] local disallow_holes = param.disallow_holes -- Iterate up the list, and throw an error if a hole is found. if disallow_holes then check_disallow_holes(params, val, name, param.list, " or empty") end -- Iterate up the list, and throw an error if a hole is found due to a -- missing parameter, treating empty parameters as part of the list. This -- applies beyond maxindex if blank arguments are supplied beyond it, so -- isn't mutually exclusive with `disallow_holes`. local empty = val.empty if param.disallow_missing then if empty then -- Remove `empty` from `val`, so it doesn't get returned. val.empty = nil for i = 1, max(val.maxindex, empty.maxindex) do if val[i] == nil and not empty[i] then local keys = extend(num_keys(val), num_keys(empty)) sort(keys) hole_error(params, name, param.list, i, keys[i]) end end -- If there's no table of empty parameters, the check is identical to -- `disallow_holes`, except that the error message only refers to -- missing parameters, not missing or empty ones. If `disallow_holes` is -- also set, there's no point checking again. elseif not disallow_holes then check_disallow_holes(params, val, name, param.list) end end -- If `allow_holes` is set, there's nothing left to do. if param.allow_holes then -- do nothing -- Otherwise, remove any holes: `pairs` won't work, as it's unsorted, and -- iterating from 1 to `maxindex` times out with inputs like |100000000000=, -- so use num_keys to get a list of numerical keys sorted from lowest to -- highest, then iterate up the list, moving each value in `val` to the -- lowest unused positive integer key. This also avoids the need to create a -- new table. If `disallow_holes` is specified, then there can't be any -- holes in the list, so there's no reason to check again; this doesn't -- apply to `disallow_missing`, however. else if not disallow_holes then local keys, i = num_keys(val), 0 while true do i = i + 1 local key = keys[i] if key == nil then break elseif i ~= key then track("holes compressed") val[i], val[key] = val[key], nil end end end -- Some code depends on only numeric params being present when no holes are -- allowed (e.g. by checking for the presence of arguments using next()), so -- remove `maxindex`. val.maxindex = nil end end local function maybe_flatten(params, val, name) local param = params[name] if param.flatten then if param.allow_holes then process_error("For parameter %s, can't set both `allow_holes` and `flatten`", name) end if not param.sublist and param.type ~= "genders" and param.type ~= "labels" and param.type ~= "references" and param.type ~= "qualifier" and param.type ~= "form of tags" then process_error("For parameter %s, can only set `flatten` along with `sublist` or a list-generating type", name) end -- Do the flattening ourselves rather than calling flatten() in [[Module:table]], which will attempt to -- flatten non-list objects like title objects, and cause an error in the process. -- FIXME: We should do this in-place if possible. local newlist = {} for _, sublist in ipairs(val) do for _, item in ipairs(sublist) do insert(newlist, item) end end val = newlist end return val end -- If both `template_default` and `default` are given, `template_default` takes precedence, but only on the template or -- module page. This means a different default can be specified for the template or module page example. However, -- `template_default` doesn't apply if any args are set, which helps (somewhat) with examples on documentation pages -- transcluded into the template page. HACK: We still run into problems on documentation pages transcluded into the -- template page when pagename= is set. Check this on the assumption that pagename= is fairly standard. local function convert_default_val(name, param, pagename_set, any_args_set, add_empty_sublist) if not pagename_set then local val = param.template_default if val ~= nil and not any_args_set and is_own_page() then return convert_val(val, name, param, "template default") end end local val = param.default if val ~= nil then return convert_val(val, name, param, "default") -- Sublist parameters should return an empty table if not given, but only do -- this if the parameter isn't also a list (in which case it will already -- be an empty table). -- FIXME: do this once all modules that pass in a sublist parameter treat an empty sublist identically to a nil argument; some currently do things based on the fact an argument exists at all. -- elseif add_empty_sublist and param.sublist then --return {} end end --[==[ Process arguments with a given list of parameters. Return a table containing the processed arguments. The `args` parameter specifies the arguments to be processed; they are the arguments you might retrieve from {frame:getParent().args} (the template arguments) or in some cases {frame.args} (the invocation arguments). The `params` parameter specifies a list of valid parameters, and consists of a table. If an argument is encountered that is not in the parameter table, an error is thrown. The structure of the `params` table is as described above in the intro comment. '''WARNING:''' The `params` table is destructively modified to save memory. Nonetheless, different keys can share the same value objects in memory without causing problems. The `props` parameter is an optional table of additional properties. Currently the following properties are supported: * `return_unknown`: If set to {true}, prevents the function from triggering an error when it comes across an argument with a name that it doesn't recognise. Instead, the return value is a pair of values: the first is the processed arguments as usual, while the second contains all the unrecognised arguments that were left unprocessed. This allows you to do multi-stage processing, where the entire set of arguments that a template should accept is not known at once. For example, an inflection-table might do some generic processing on some arguments, but then defer processing of the remainder to the function that handles a specific inflectional type. * `allow_params`: An optional function to allow and return additional parameters. The function is passed the name of each unrecognized parameter, and should return the appropriate parameter spec for processing the parameter. In most cases, simply return `true`, indicating that the parameter should be processed as a normal string parameter. Return {nil} if the parameter name is unrecognized. For compatibility, `props` can be a boolean or string, which is treated as the `return_unknown` property. ]==] function export.process(args, params, props) if type(props) ~= "table" then props = { return_unknown = props } end -- Process parameters for specific properties local args_new = {} local args_unknown, any_args_set, required, patterns, list_args, index_list, args_placeholders, placeholders_n -- TODO: memoize the processing of each unique `param` value, since it's common for the same value to be used for -- many parameter names. for name, param in pairs(params) do validate_name(name, "parameter names") if param ~= true then local spec_type = type(param) if type(param) ~= "table" then internal_process_error( "spec for parameter %s must be a table of specs or the value true, but found %s.", name, spec_type ~= "boolean" and spec_type or param ) end -- Populate required table, and make sure aliases aren't set to required. if param.required then if required == nil then required = {} end required[name] = true end local listname, alias_of = param.list, param.alias_of if alias_of then validate_name(alias_of, "the alias_of field of parameter ", name) if alias_of == name then internal_process_error( "parameter %s cannot be an alias of itself.", name ) end local main_param = params[alias_of] -- Check that the alias_of is set to a valid parameter. if not (main_param == true or type(main_param) == "table") then internal_process_error( "parameter %s is an alias of an invalid parameter.", name ) end validate_alias_options(param, name, main_param, alias_of) -- Aliases can't be lists unless the canonical parameter is also a list. if listname and (main_param == true or not main_param.list) then internal_process_error( "list parameter %s is set as an alias of %s, which is not a list parameter.", name, alias_of ) -- Can't be an alias of an alias. elseif main_param ~= true then local main_alias_of = main_param.alias_of if main_alias_of ~= nil then internal_process_error( "alias_of cannot be set to another alias: parameter %s is set as an alias of %s, which is in turn an alias of %s. Set alias_of for %s to %s.", name, alias_of, main_alias_of, name, main_alias_of ) end end end local replaced_by = param.replaced_by if replaced_by then -- replaced_by can be `false`, which is OK validate_name(replaced_by, "the replaced_by field of parameter ", name) if replaced_by == name then internal_process_error( "parameter %s cannot be replaced by itself.", name ) end local main_param = params[replaced_by] -- Check that the replaced_by is set to a valid parameter. if not (main_param == true or type(main_param) == "table") then internal_process_error( "parameter %s is set to be replaced by an invalid parameter.", name ) end -- Can't be a replaced-by of a replaced-by. if main_param ~= true then local main_replaced_by = main_param.replaced_by if main_replaced_by ~= nil then internal_process_error( "replaced_by cannot be set to another replaced-by parameter: parameter %s is set as replaced by %s, which is in turn replaced by %s. Set replaced_by for %s to %s.", name, replaced_by, main_replaced_by, name, main_replaced_by ) end end if param.instead ~= nil then internal_process_error("the `instead` tag can only be given when `replaced_by` is set to `false`.") end elseif replaced_by == false then if param.instead ~= nil and type(param.instead) ~= "string" then internal_process_error( "the `instead` tag must be a string, but saw %s.", param.instead ) end end if replaced_by ~= nil then if param.reason ~= nil and type(param.reason) ~= "string" then internal_process_error( "the `reason` tag must be a string, but saw %s.", param.reason ) end end if listname then if not alias_of then local key = name if type(name) == "string" then key = gsub(name, "\1", "") end local list_arg = {maxindex = 0} args_new[key] = list_arg if list_args == nil then list_args = {} end list_args[key] = list_arg end local list_type = type(listname) if list_type == "string" then -- If the list property is a string, then it represents the name -- to be used as the prefix for list items. This is for use with lists -- where the first item is a numbered parameter and the -- subsequent ones are named, such as 1, pl2, pl3. patterns = save_pattern(name, listname, patterns or {}) elseif listname ~= true then internal_process_error( "list field for parameter %s must be a boolean, string or undefined, but saw a %s.", name, list_type ) elseif type(name) == "number" then if index_list ~= nil then internal_process_error( "only one numeric parameter can be a list, unless the list property is a string." ) end -- If the name is a number, then all indexed parameters from -- this number onwards go in the list. index_list = name else patterns = save_pattern(name, name, patterns or {}) end if find(name, "\1", nil, true) then if args_placeholders then placeholders_n = placeholders_n + 1 args_placeholders[placeholders_n] = name else args_placeholders, placeholders_n = {name}, 1 end end end end end --Process required changes to `params`. if args_placeholders then for i = 1, placeholders_n do local name = args_placeholders[i] params[gsub(name, "\1", "")], params[name] = params[name], nil end end -- Process the arguments for name, val in pairs(args) do any_args_set = true validate_name(name, "argument names", nil, true) -- Guaranteeing that all values are strings avoids issues with type coercion being inconsistent between functions. local val_type = type(val) if val_type ~= "string" then internal_process_error( "argument %s has the type %s; all arguments must be strings.", name, val_type ) end local orig_name, raw_type = name, type(name) local index, canonical if raw_type == "number" then if index_list and name >= index_list then index = name - index_list + 1 name = index_list end elseif patterns then -- Does this argument name match a pattern? for pattern, pname in next, patterns do index = match(name, pattern) -- It matches, so store the parameter name and the -- numeric index extracted from the argument name. if index then index = tonumber(index) name = pname break end end end local param = params[name] if not param and props.allow_params then param = props.allow_params(name) end -- If the argument is not in the list of parameters, store it in a separate list. if not param then args_unknown = unknown_param(name, val, args_unknown or {}) elseif param == true then canonical = orig_name val = php_trim(val) if val ~= "" then -- If the parameter is duplicated, throw an error. if args_new[name] ~= nil then process_error( "Parameter %s has been entered more than once. This is probably because a parameter alias has been used.", canonical ) end args_new[name] = val end else if param.replaced_by == false then process_error( ("Parameter %%s has been removed and is no longer valid%s.%s"):format( param.reason and ", " .. param.reason or "", param.instead and " Instead, " .. param.instead .. "." or ""), name ) elseif param.replaced_by then process_error( ("Parameter %%s has been replaced by %%s%s."):format( param.reason and ", " .. param.reason or ""), name, param.replaced_by ) end if param.deprecated then track("deprecated parameter", name) end if param.require_index then -- Disallow require_index for numeric parameter names, as this doesn't make sense. if raw_type == "number" then internal_process_error( "cannot set require_index for numeric parameter %s.", name ) -- If a parameter without the trailing index was found, and -- require_index is set on the param, treat it -- as if it isn't recognized. elseif not index then args_unknown = unknown_param(name, val, args_unknown or {}) end end -- Check that separate_no_index is not being used with a numeric parameter. if param.separate_no_index then if raw_type == "number" then internal_process_error( "cannot set separate_no_index for numeric parameter %s.", name ) elseif type(param.alias_of) == "number" then internal_process_error( "cannot set separate_no_index for parameter %s, as it is an alias of numeric parameter %s.", name, param.alias_of ) end end -- If no index was found, use 1 as the default index. -- This makes list parameters like g, g2, g3 put g at index 1. -- If `separate_no_index` is set, then use 0 as the default instead. if not index and param.list then index = param.separate_no_index and 0 or 1 end -- Normalize to the canonical parameter name. If it's a list, but the alias is not, then determine the index. local raw_name = param.alias_of if raw_name then raw_type = type(raw_name) if raw_type == "number" then name = raw_name local main_param = params[raw_name] if main_param ~= true and main_param.list then if not index then index = param.separate_no_index and 0 or 1 end canonical = raw_name + index - 1 else canonical = raw_name end else name = gsub(raw_name, "\1", "") local main_param = params[name] if not index and main_param ~= true and main_param.list then index = param.separate_no_index and 0 or 1 end if not index or index == 0 then canonical = name elseif name == raw_name then canonical = name .. index else canonical = gsub(raw_name, "\1", index) end end else canonical = orig_name end -- Only recognize demo parameters if this is the current template or module's -- page, or its documentation page. if param.demo and not is_own_page("include_documentation") then args_unknown = unknown_param(name, val, args_unknown or {}) end -- Remove leading and trailing whitespace unless no_trim is true. if param.no_trim then check_string_param_modifier(param.type, name, "no_trim") else val = php_trim(val) end -- Empty string is equivalent to nil unless allow_empty is true. if param.allow_empty then check_string_param_modifier(param.type, name, "allow_empty") elseif val == "" then -- If `disallow_missing` is set, keep track of empty parameters -- via the `empty` field in `arg`, which will be used by the -- `disallow_missing` check. This will be deleted before -- returning. if index and param.disallow_missing then local arg = args_new[name] local empty = arg.empty if empty == nil then empty = {maxindex = 0} arg.empty = empty end empty[index] = true if index > empty.maxindex then empty.maxindex = index end end val = nil end -- Allow boolean false. if val ~= nil then -- Convert to proper type if necessary. local main_param = params[raw_name] if main_param ~= true then val = convert_val(val, orig_name, main_param or param) end -- Mark it as no longer required, as it is present. if required then required[name] = nil end -- Store the argument value. if index then local arg = args_new[name] -- If the parameter is duplicated, throw an error. if arg[index] ~= nil then process_error( "Parameter %s has been entered more than once. This is probably because a list parameter has been entered without an index and with index 1 at the same time, or because a parameter alias has been used.", canonical ) end arg[index] = val -- Store the highest index we find. local maxindex = arg.maxindex if index > maxindex then maxindex = index end if arg[0] ~= nil then arg.default, arg[0] = arg[0], nil if maxindex < 1 then maxindex = 1 end end arg.maxindex = maxindex if not params[name].list then args_new[name] = val -- Don't store index 0, as it's a proxy for the default. elseif index > 0 then arg[index] = val end else -- If the parameter is duplicated, throw an error. if args_new[name] ~= nil then process_error( "Parameter %s has been entered more than once. This is probably because a parameter alias has been used.", canonical ) end if not raw_name then args_new[name] = val else local main_param = params[raw_name] if main_param ~= true and main_param.list then local main_arg = args_new[raw_name] main_arg[1] = val -- Store the highest index we find. if main_arg.maxindex < 1 then main_arg.maxindex = 1 end else args_new[raw_name] = val end end end end end end -- Remove holes in any list parameters if needed. This must be handled -- straight after the previous loop, as any instances of `empty` need to be -- converted to nil. if list_args then for name, val in next, list_args do handle_holes(params, val, name) end end -- If the current page is the template which invoked this Lua instance, then ignore the `require` flag, as it -- means we're viewing the template directly. Required parameters sometimes have a `template_default` key set, -- which gets used in such cases as a demo. -- Note: this won't work on other pages in the Template: namespace (including the /documentation subpage), -- or if the #invoke: is on a page in another namespace. local pagename_set = args_new.pagename -- Handle defaults. for name, param in pairs(params) do if param ~= true then local arg_new = args_new[name] if arg_new == nil then args_new[name] = convert_default_val(name, param, pagename_set, any_args_set, true) elseif param.list and arg_new[1] == nil then local default_val = convert_default_val(name, param, pagename_set, any_args_set) if default_val ~= nil then arg_new[1] = default_val if arg_new.maxindex == 0 then arg_new.maxindex = 1 end end end end end -- Flatten nested lists if called for. This must come after setting the default. if list_args then for name, val in next, list_args do args_new[name] = maybe_flatten(params, val, name) end end -- The required table should now be empty. -- If any parameters remain, throw an error, unless we're on the current template or module's page. if required and next(required) ~= nil and not is_own_page() then params_list_error(required, "required") -- Return the arguments table. If there are any unknown parameters, throw an error, unless return_unknown is set, -- in which case return args_unknown as a second return value. elseif props.return_unknown then return args_new, args_unknown or {} elseif args_unknown and next(args_unknown) ~= nil then params_list_error(args_unknown, "not used by this template") end return args_new end return export c6iobggtd1vtxa1ex5tah8gwyezp499 Module:languages/data/3/d 828 6257 239009 234992 2026-09-14T04:02:39Z en>WingerBot 0 Language:generateForms -> Language:generateAlternants; generate_forms key -> generate_alternants; clean up [[Module:languages]] documentation (manually assisted) 239009 Scribunto text/plain local m_langdata = require("Module:languages/data") -- Loaded on demand, as it may not be needed (depending on the data). local function u(...) u = require("Module:string utilities").char return u(...) end local c = m_langdata.chars local p = m_langdata.puaChars local s = m_langdata.shared local m = {} m["daa"] = { "Dangaléat", 942591, "cdc-est", "Latn", } m["dac"] = { "Dambi", 12629491, "poz-ocw", "Latn", } m["dad"] = { "Marik", 6763404, "poz-ocw", "Latn", } m["dae"] = { "Duupa", 35263, "alv-dur", "Latn", } m["dag"] = { "Dagbani", 32238, "nic-dag", "Latn", } m["dah"] = { "Gwahatike", 5623246, "ngf-war", "Latn", } m["dai"] = { "Day", 35163, "alv-mbd", "Latn", } m["daj"] = { "Dar Fur Daju", 56370, "sdv-daj", "Latn", } m["dak"] = { "Dakota", 530384, "sio-dkt", "Latn", } m["dal"] = { "Dahalo", 35143, "cus", "Latn", } m["dam"] = { "Damakawa", 1158134, "nic-knn", "Latn", } m["dao"] = { "Daai Chin", 860029, "tbq-kuk", "Latn", } m["daq"] = { "Dandami Maria", 12952805, "dra-mdy", "Deva", } m["dar"] = { "Dargwa", 32332, "cau-drg", "Cyrl, Latn, Arab", translit = {Cyrl = "dar-translit"}, override_translit = true, display_text = {Cyrl = s["cau-Cyrl-displaytext"]}, strip_diacritics = { Cyrl = s["cau-Cyrl-stripdiacritics"], Latn = s["cau-Latn-stripdiacritics"], }, sort_key = { Cyrl = { from = { "къкъ", "хьхь", -- 4 chars "гъ", "гь", "гӏ", "ё", "къ", "кь", "кӏ", "пп", "пӏ", "сс", "тт", "тӏ", "хх", "хъ", "хь", "хӏ", "цц", "цӏ", "чч", "чӏ" -- 2 chars }, to = { "к" .. p[2], "х" .. p[4], "г" .. p[1], "г" .. p[2], "г" .. p[3], "е" .. p[1], "к" .. p[1], "к" .. p[3], "к" .. p[4], "п" .. p[1], "п" .. p[2], "с" .. p[1], "т" .. p[1], "т" .. p[2], "х" .. p[1], "х" .. p[2], "х" .. p[3], "х" .. p[5], "ц" .. p[1], "ц" .. p[2], "ч" .. p[1], "ч" .. p[2] } }, }, } m["das"] = { "Daho-Doo", 3915369, "kro-wee", "Latn", } m["dau"] = { "Dar Sila Daju", 7514020, "sdv-daj", "Latn", } m["dav"] = { "Taita", 2387274, "bnt-cht", "Latn", } m["daw"] = { "Davawenyo", 5228174, "phi", "Latn", } m["dax"] = { "Dayi", 10467281, "aus-yol", "Latn", } m["daz"] = { "Dao", 5221513, "ngf-pan", "Latn", } m["dba"] = { "Bangime", 1982696, "qfa-iso", -- southern Mali "Latn", } m["dbb"] = { "Deno", 56275, "cdc-wst", "Latn", } m["dbd"] = { "Dadiya", 3914436, "alv-wjk", "Latn", } m["dbe"] = { "Dabe", 5207451, "paa-tor", "Latn", } m["dbf"] = { "Edopi", 12953516, "paa-lpl", "Latn", } m["dbg"] = { "Dogul Dom", 3912880, "nic-npd", "Latn", } m["dbi"] = { "Doka", 3913293, "nic-plc", "Latn", } m["dbj"] = { "Ida'an", 3041552, "poz-san", "Latn", } m["dbl"] = { "Dyirbal", 35465, "aus-dyb", "Latn", } m["dbm"] = { "Duguri", 7194057, "nic-jrw", "Latn", } m["dbn"] = { "Duriankere", 5316627, "ngf-sbh", "Latn", } m["dbo"] = { "Dulbu", 5313310, "nic-jrn", "Latn", } m["dbp"] = { "Duwai", 56301, "cdc-wst", "Latn", } m["dbq"] = { "Daba", 3913342, "cdc-cbm", "Latn", } m["dbr"] = { "Dabarre", 3447286, "cus-som", "Latn", } m["dbt"] = { "Ben Tey", 4886561, "nic-nwa", "Latn", } m["dbu"] = { "Bondum Dom Dogon", 3912758, "nic-npd", "Latn", } m["dbv"] = { "Dungu", 5315230, "nic-kau", "Latn", } m["dbw"] = { "Bankan Tey Dogon", 4856243, "nic-nwa", "Latn", } m["dby"] = { "Dibiyaso", 5272268, "qfa-dis", -- Papuan; isolate per Glottolog, unclassified per Pawley and Hammarström (2018), sometimes classified with Bosavi languages "Latn", } m["dcc"] = { "Deccani", 669431, "inc-hnd", "Aran", ancestors = "ur", } m["dcr"] = { "Negerhollands", 1815830, "crp", "Latn", ancestors = "nl", } m["dda"] = { "Dadi Dadi", 50207890, "aus-pam", "Latn", } m["ddd"] = { "Dongotono", 56676, "sdv-lma", "Latn", } m["dde"] = { "Doondo", 11003401, "bnt-kng", "Latn", } m["ddg"] = { "Fataluku", 35353, "paa-eti", "Latn", } m["ddi"] = { "Diodio", 3028668, "poz-ocw", "Latn", } m["ddj"] = { "Jaru", 3162806, "aus-pam", "Latn", } m["ddn"] = { "Dendi", 35164, "son", "Latn", } m["ddo"] = { "Tsez", 34033, "cau-wts", "Cyrl", translit = "ddo-translit", display_text = {Cyrl = s["cau-Cyrl-displaytext"]}, strip_diacritics = {Cyrl = s["cau-Cyrl-stripdiacritics"]}, } m["ddr"] = { "Dhudhuroa", 5269842, "aus-pam", "Latn", } m["dds"] = { "Donno So Dogon", 1234776, "nic-dge", "Latn", } m["ddw"] = { "Dawera-Daweloor", 5242304, "poz-tim", "Latn", } m["dec"] = { "Dagik", 35125, "alv-tal", "Latn", } m["ded"] = { "Dedua", 5249850, "ngf-huo", "Latn", } m["dee"] = { "Dewoin", 3914892, "kro-wkr", "Latn", } m["def"] = { "Dezfuli", 4115412, "ira-swi", "Arab", ancestors = "pal", } m["deg"] = { "Degema", 35182, "alv-dlt", "Latn", } m["deh"] = { "Dehwari", 5704314, "ira-swi", "Arab", ancestors = "fa", } m["dei"] = { "Demisa", 56380, "paa-egb", "Latn", } -- "dek" is no longer an ISO code; spurious m["dem"] = { "Dem", 5254989, "qfa-dis", -- Papuan; isolate in Glottolog; unclassified in Palmer (2018); grouped with Amung by Usher, ultimately in TNG "Latn", } m["dep"] = { "Pidgin Delaware", 1183938, "crp", "Latn", ancestors = "unm", } -- deq is not included, see [[WT:LT]] m["der"] = { "Deori", 56478, "tbq-bdg", "Beng, Latn", } m["des"] = { "Desano", 962392, "sai-tuc", "Latn", } m["dev"] = { "Domung", 5291378, "ngf-yup", "Latn", } m["dez"] = { "Dengese", 2909984, "bnt-tet", "Latn", } m["dga"] = { "Southern Dagaare", 35159, "nic-mre", "Latn", } m["dgb"] = { "Bunoge", 4985178, "nic-dgw", "Latn", } m["dgc"] = { "Casiguran Dumagat Agta", 5313599, "phi", "Latn", } m["dgd"] = { "Dagaari Dioula", 11153465, "nic-mre", "Latn", } m["dge"] = { "Degenan", 5251770, "ngf-war", "Latn", } m["dgg"] = { "Doga", 3033726, "poz-ocw", "Latn", } m["dgh"] = { "Dghwede", 56293, "cdc-cbm", "Latn", } m["dgi"] = { "Northern Dagara", 11004218, "nic-mre", "Latn", } m["dgk"] = { "Dagba", 12952357, "csu-sar", "Latn", } m["dgn"] = { "Dagoman", 10465931, "aus-yng", "Latn", } m["dgr"] = { "Dogrib", 20979, "ath-nor", "Latn", } m["dgs"] = { "Dogoso", 35343, "nic-gur", } m["dgt"] = { "Ntra'ngith", 6983809, "aus-pam", "Latn", } -- dgu is not a language; see [[w:Dhekaru]] m["dgw"] = { "Daungwurrung", 5228050, "aus-pam", "Latn", } m["dgx"] = { "Doghoro", 12952392, "ngf-bin", "Latn", } m["dgz"] = { "Daga", 5208442, "ngf-dag", "Latn", } m["dhg"] = { "Dhangu", 5268960, "aus-yol", "Latn", } m["dhd"] = { "Dhundhari", 633359, "raj", "Deva", translit = "hi-translit", } m["dhi"] = { "Dhimal", 35229, "sit-dhi", "Deva", } m["dhl"] = { "Dhalandji", 5268787, "aus-psw", "Latn", } m["dhm"] = { "Zemba", 3502283, "bnt-swb", "Latn", ancestors = "hz", } m["dhn"] = { "Dhanki", 5268992, "inc-bhi", } m["dho"] = { "Dhodia", 5269658, "inc-bhi", "Deva", } m["dhr"] = { "Tharrgari", 10470289, "aus-psw", "Latn", } m["dhs"] = { "Dhaiso", 11001788, "bnt-kka", "Latn", } m["dhu"] = { "Dhurga", 1285318, "aus-yuk", "Latn", } m["dhv"] = { "Drehu", 3039319, "poz-cln", "Latn", } m["dhw"] = { "Danuwar", 3522797, "inc-bhi", "Deva", } m["dhx"] = { "Dhungaloo", 16960599, "aus-pam", "Latn", } m["dia"] = { "Dia", 3446591, "paa-wap", "Latn", } m["dib"] = { "South Central Dinka", 35154, "sdv-dnu", "Latn", ancestors = "din", } m["dic"] = { "Lakota Dida", 11001730, "kro-did", "Latn", } m["did"] = { "Didinga", 56365, "sdv", "Latn", } m["dif"] = { "Dieri", 25559563, "aus-kar", "Latn", } m["dig"] = { "Digo", 3362072, "bnt-mij", "Latn", } -- "dih" is split into nai-ipa, nai-kum, nai-tip, see [[WT:LT]] m["dii"] = { "Dimbong", 35196, "bnt-baf", "Latn", } m["dij"] = { "Dai", 5209056, "poz-tim", "Latn", } m["dik"] = { "Southwestern Dinka", 36540, "sdv-dnu", "Latn", ancestors = "din", } m["dil"] = { "Dilling", 35152, "nub-hil", "Latn", } m["dim"] = { "Dime", 35311, "omv-aro", } m["din"] = { "Dinka", 56466, "sdv-dnu", "Latn", } m["dio"] = { "Dibo", 3914891, "alv-ngb", "Latn", } m["dip"] = { "Northeastern Dinka", 36246, "sdv-dnu", "Latn", ancestors = "din", } m["dir"] = { "Dirim", 11130804, "nic-dak", "Latn", } m["dis"] = { "Dimasa", 56664, "tbq-bdg", "Latn, Beng", } m["diu"] = { "Gciriku", 3780954, "bnt-kav", "Latn", } m["diw"] = { "Northwestern Dinka", 36249, "sdv-dnu", "Latn", ancestors = "din", } m["dix"] = { "Dixon Reef", 5284967, "poz-vnc", "Latn", } m["diy"] = { "Diuwe", 5283765, "ngf-asm", "Latn", } m["diz"] = { "Ding", 35202, "bnt-bdz", "Latn", } m["dja"] = { "Djadjawurrung", 5285190, "aus-pam", "Latn", } m["djb"] = { "Djinba", 5285351, "aus-yol", "Latn", } m["djc"] = { "Dar Daju Daju", 5209890, "sdv-daj", "Latn", } m["djd"] = { "Jaminjung", 6147825, "aus-mir", "Latn", } m["dje"] = { "Zarma", 36990, "son", "Latn, Arab, Brai", } m["djf"] = { "Djangun", 10474818, "aus-pmn", "Latn", } m["dji"] = { "Djinang", 5285350, "aus-yol", "Latn", } m["djj"] = { "Ndjébbana", 5285274, "aus-arn", "Latn", } m["djk"] = { "Aukan", 2659044, "crp", "Latn, Afak", ancestors = "en", } m["djl"] = { "Djiwarli", 2669569, "aus-psw", "Latn", } m["djm"] = { "Jamsay", 3913290, "nic-pld", "Latn", } m["djn"] = { "Djauan", 13553748, "aus-gun", "Latn", } m["djo"] = { "Jangkang", 12952388, "day", } m["djr"] = { "Djambarrpuyngu", 3915679, "aus-yol", "Latn", } m["dju"] = { "Kapriman", 6367199, "paa-sep", "Latn", } m["djw"] = { "Djawi", 3913844, "aus-nyu", "Latn", ancestors = "bcj", } m["dka"] = { "Dakpa", 3695189, "sit-ebo", "Tibt", override_translit = true, -- Tibt translit, display_text, strip_diacritics, sort_key in [[Module:scripts/data]] } m["dkk"] = { "Dakka", 5209962, "poz-ssw", "Latn", } m["dkr"] = { "Kuijau", 13580777, "poz-bnn", "Latn", } m["dks"] = { "Southeastern Dinka", 36538, "sdv-dnu", "Latn", ancestors = "din", } m["dkx"] = { "Mazagway", 6798209, "cdc-cbm", "Latn", } m["dlg"] = { "Dolgan", 32878, "trk-nsb", "Cyrl", sort_key = { from = {"ё", "һ", "ӈ", "ө", "ү"}, to = {"е" .. p[1], "к" .. p[1], "н" .. p[1], "о" .. p[1], "у" .. p[1]} }, } m["dlk"] = { "Dahalik", 32260, "sem-eth", "Ethi", translit = "Ethi-translit", } m["dlm"] = { "Dalmatian", 35527, "roa-dal", "Latn", } m["dln"] = { "Darlong", 5224029, "tbq-kuk", "Latn", } m["dma"] = { "Duma", 35319, "bnt-nze", "Latn", } m["dmb"] = { "Mombo Dogon", 6897074, "nic-dgw", "Latn", } m["dmc"] = { "Gavak", 5277406, "ngf-nad", "Latn", } m["dmd"] = { "Madhi Madhi", 6727353, "aus-pam", "Latn", } m["dme"] = { "Dugwor", 56313, "cdc-cbm", "Latn", } m["dmf"] = { "Medefaidrin", 1519764, "art", "Medf", type = "appendix-constructed", } m["dmg"] = { "Upper Kinabatangan", 16109975, "poz-san", "Latn", } m["dmk"] = { "Domaaki", 32900, "inc-wes", "Arab", } m["dml"] = { "Dameli", 32288, "inc-kun", } m["dmm"] = { "Dama (Nigeria)", 5211865, "alv-mbm", "Latn", } m["dmo"] = { "Kemezung", 35562, "nic-bbe", "Latn", } m["dmr"] = { "East Damar", 5328200, "poz-cet", "Latn", } m["dms"] = { "Dampelas", 5212928, "poz-tot", "Latn", } m["dmu"] = { "Dubu", 7692059, "paa-wpw", "Latn", } m["dmv"] = { "Dumpas", 12953512, "poz-san", "Latn", } m["dmw"] = { "Mudburra", 6931573, "aus-pam", "Latn", } m["dmx"] = { "Dema", 3553423, "bnt-sho", "Latn", } m["dmy"] = { "Demta", 14466283, "paa-sen", "Latn", } m["dna"] = { "Upper Grand Valley Dani", 12952361, "ngf-gvd", "Latn", } m["dnd"] = { "Daonda", 5221528, "paa-war", "Latn", } m["dne"] = { "Ndendeule", 6983725, "bnt-mbi", "Latn", } m["dng"] = { "Dungan", 33050, "zhx-man", "Cyrl, Latn, Hants", generate_alternants = "zh-generatealternants", translit = {Cyrl = "dng-translit"}, sort_key = { Cyrl = { from = {"ё", "ә", "җ", "ң", "ў", "ү"}, to = {"е" .. p[1], "е" .. p[2], "ж" .. p[1], "н" .. p[1], "у" .. p[1], "у" .. p[2]} }, Hani = "Hani-sortkey", }, } m["dni"] = { "Lower Grand Valley Dani", 12635807, "ngf-gvd", "Latn", } m["dnj"] = { "Dan", 1158971, "dmn-mda", "Latn", } m["dnk"] = { "Dengka", 5256954, "poz-tim", "Latn", } m["dnn"] = { "Dzuun", 10973260, "dmn-smg", "Latn", } m["dno"] = { "Ndrulo", 60785094, "csu-lnd", } m["dnr"] = { "Danaru", 5214932, "ngf-pek", "Latn", } m["dnt"] = { "Mid Grand Valley Dani", 12952359, "ngf-gvd", "Latn", } m["dnu"] = { "Danau", 5013745, "mkh-pal", "Mymr", } m["dnv"] = { "Danu", 5221251, "tbq-brm", "Mymr", ancestors = "obr", } m["dnw"] = { "Western Dani", 7987774, "ngf-cda", "Latn", } m["dny"] = { "Dení", 56562, "auf", "Latn", } m["doa"] = { "Dom", 5289770, "ngf-sim", "Latn", } m["dob"] = { "Dobu", 952133, "poz-ocw", "Latn", } m["doc"] = { "Northern Kam", 17195499, "qfa-tak", "Latn", } m["doe"] = { "Doe", 5288055, "bnt-ruv", "Latn", } m["dof"] = { "Domu", 5291375, "paa-mal", "Latn", } m["doh"] = { "Dong", 3438405, "nic-dak", "Latn", } m["doi"] = { "Dogri", 32730, "him", "Deva, Takr, Aran, Dogr", translit = { Deva = "hi-translit", Dogr = "Dogr-translit", }, } m["dok"] = { "Dondo", 5295571, "poz-tot", "Latn", } m["dol"] = { "Doso", 4167202, "paa-dtu", "Latn", } m["don"] = { "Doura", 7829037, "poz-ocw", "Latn", } m["doo"] = { "Dongo", 35303, "nic-mbc", "Latn", } m["dop"] = { "Lukpa", 3258739, "nic-gne", "Latn", } m["doq"] = { "Dominican Sign Language", 5290820, "sgn", "Latn", -- when documented } m["dor"] = { "Dori'o", 3037084, "poz-sls", "Latn", } m["dos"] = { "Dogosé", 3913314, "nic-gur", "Latn", } m["dot"] = { "Dass", 3441293, "cdc-wst", "Latn", } m["dov"] = { "Toka-Leya", 11001779, "bnt-bot", "Latn", ancestors = "toi", } m["dow"] = { "Doyayo", 35299, "alv-dur", "Latn", } m["dox"] = { "Bussa", 35123, "cus-eas", "Latn", } m["doy"] = { "Dompo", 35270, "alv-gng", "Latn", } m["doz"] = { "Dorze", 56336, "omv-nom", "Latn", } m["dpp"] = { "Papar", 7132487, "poz-san", "Latn", } m["drb"] = { "Dair", 12952360, "nub-hil", "Latn", } m["drc"] = { "Minderico", 6863806, "roa-gap", "Latn", ancestors = "pt", } m["drd"] = { "Darmiya", 5224058, "sit-alm", } m["drg"] = { "Rungus", 6897407, "poz-san", "Latn", } m["dri"] = { "Lela", 3914004, "nic-knn", "Latn", } m["drl"] = { "Baagandji", 5223941, "aus-pam", "Latn", } m["drn"] = { "West Damar", 3450459, "poz-tim", "Latn", } m["dro"] = { "Daro-Matu Melanau", 5224156, "poz-bnn", "Latn", } m["drq"] = { "Dura", 3449842, "sit-gma", "Deva", } m["drs"] = { "Gedeo", 56622, "cus-hec", "Ethi", } m["dru"] = { "Rukai", 49232, "map", "Latn", ancestors = "dru-pro", } m["dry"] = { "Darai", 46995026, "inc-bih", "Deva", } m["dsb"] = { "Lower Sorbian", 13286, "wen", "Latn", sort_key = s["wen-sortkey"], standard_chars = "AaBbCcČčĆćDdEeĚěFfGgHhIiJjKkŁłLlMmNnŃńOoÓóPpRrŔŕSsŠšŚśTtUuWwYyZzŽžŹź" .. c.punc, } m["dse"] = { "Dutch Sign Language", 2201099, "sgn", "Latn", -- when documented } m["dsh"] = { "Daasanach", 56637, "cus-eas", "Latn", } m["dsi"] = { "Disa", 3914455, "csu-bgr", "Latn", } m["dsl"] = { "Danish Sign Language", 2605298, "sgn", "Latn", -- when documented } m["dsn"] = { "Dusner", 5316948, "poz-hce", "Latn", } m["dso"] = { "Desiya", 12629755, "inc-eas", "Orya", ancestors = "or", } m["dsq"] = { "Tadaksahak", 36568, "son", "Arab, Latn", } m["dta"] = { "Daur", 32430, "xgn", "Latn, Hani, Cyrl, Mong", ancestors = "xng", -- Mong translit, display_text and strip_diacritics in [[Module:scripts/data]] sort_key = {Hani = "Hani-sortkey"}, } m["dtb"] = { "Labuk-Kinabatangan Kadazan", 5330240, "poz-san", "Latn", } m["dtd"] = { "Ditidaht", 13728042, "wak", "Latn", } m["dth"] = { -- contrast 'rrt' "Adithinngithigh", 4683034, "aus-pmn", "Latn", } m["dti"] = { "Ana Tinga Dogon", 4750346, "qfa-dgn", "Latn", } m["dtk"] = { "Tene Kan Dogon", 11018863, "nic-pld", "Latn", } m["dtm"] = { "Tomo Kan Dogon", 11137719, "nic-pld", "Latn", } m["dto"] = { "Tommo So", 47012992, "nic-dge", "Latn", } m["dtp"] = { "Central Dusun", 5317225, "poz-san", "Latn", } m["dtr"] = { "Lotud", 6685078, "poz-san", "Latn", } m["dts"] = { "Toro So Dogon", 11003311, "nic-dge", "Latn", } m["dtt"] = { "Toro Tegu Dogon", 3913924, "nic-pld", "Latn", } m["dtu"] = { "Tebul Ure Dogon", 7692089, "qfa-dgn", "Latn", } m["dty"] = { "Doteli", 18415595, "inc-pae", "Deva", translit = "ne-translit", } m["dua"] = { "Duala", 33013, "bnt-saw", "Latn", } m["dub"] = { "Dubli", 5310792, "inc-bhi", } m["duc"] = { "Duna", 5314039, "qfa-dis", -- Papuan; isolate in Glottolog; tentatively grouped with Bogaya into a Duna-Pogaya [sic] family, -- ultimately in TNG "Latn", } m["due"] = { "Umiray Dumaget Agta", 7881585, "phi", "Latn", } m["duf"] = { "Dumbea", 6983819, "poz-cln", "Latn", } m["dug"] = { "Chiduruma", 35614, "bnt-mij", "Latn", } m["duh"] = { "Dungra Bhil", 12953513, "inc-bhi", "Deva, Gujr", } m["dui"] = { "Dumun", 5314004, "ngf-yag", "Latn", } m["duk"] = { "Uyajitaya", 7904085, "ngf-nur", "Latn", } m["dul"] = { "Alabat Island Agta", 3399709, "phi", "Latn", } m["dum"] = { "Middle Dutch", 178806, "gmw-frk", "Latn", ancestors = "odt", strip_diacritics = {remove_diacritics = c.circ .. c.macron .. c.diaer}, } m["dun"] = { "Dusun Deyah", 2784033, "poz-bre", "Latn", } m["duo"] = { "Dupaningan Agta", 5315912, "phi", "Latn", } m["dup"] = { "Duano", 3040468, "poz-mly", "Latn", } m["duq"] = { "Dusun Malang", 3041711, "poz-bre", "Latn", } m["dur"] = { "Dii", 35208, "alv-dur", "Latn", } m["dus"] = { "Dumi", 56315, "sit-kiw", "Deva", } m["duu"] = { "Drung", 56406, "sit-nng", "Latn", } m["duv"] = { "Duvle", 56364, "paa-lpl", "Latn", } m["duw"] = { "Dusun Witu", 2381310, "poz-bre", "Latn", } m["dux"] = { "Duun", 3914880, "dmn-smg", "Latn", } m["duy"] = { "Dicamay Agta", 5272321, "phi", "Latn", } m["duz"] = { "Duli", 5313405, "alv-ada", "Latn", } m["dva"] = { "Duau", 5310448, "poz-ocw", "Latn", } m["dwa"] = { "Diri", 56286, "cdc-wst", "Latn", } m["dwr"] = { "Dawro", 12629647, "omv-nom", "Ethi, Latn", } m["dwu"] = { "Dhuwal", 3120791, "aus-yol", "Latn", } m["dww"] = { "Dawawa", 5242286, "poz-ocw", "Latn", } m["dwy"] = { "Dhuwaya", 63348560, "aus-yol", "Latn", } m["dwz"] = { "Dewas Rai", 62663667, "inc-bhi", } m["dya"] = { "Dyan", 35340, "nic-gur", "Latn", } m["dyb"] = { "Dyaberdyaber", 5285185, "aus-nyu", "Latn", } m["dyd"] = { "Dyugun", 3913785, "aus-nyu", "Latn", } -- dyg (Villa Viciosa Agta) deleted as extinct and unattested; per Wikipedia: "Villa Viciosa Atta, supposed once spoken -- in Villaviciosa, Abra, is presumed to be related, but is unattested." m["dyi"] = { "Djimini", 35336, "alv-tdj", "Latn", } m["dym"] = { "Yanda Dogon", 8048316, "qfa-dgn", "Latn", } m["dyn"] = { "Dyangadi", 3913820, "aus-cww", "Latn", } m["dyo"] = { "Jola-Fonyi", 3507832, "alv-jol", "Latn", } m["dyu"] = { "Dyula", 32706, "dmn-man", "Latn", } m["dyy"] = { "Dyaabugay", 2591320, "aus-yid", "Latn", } m["dza"] = { "Tunzu", 3915845, "nic-jer", "Latn", } m["dzg"] = { "Dazaga", 35244, "ssa-sah", "Latn", } m["dzl"] = { "Dzala", 56607, "sit-ebo", "Tibt", override_translit = true, -- Tibt translit, display_text, strip_diacritics, sort_key in [[Module:scripts/data]] } m["dzn"] = { "Dzando", 5319622, "bnt-bun", "Latn", } return require("Module:languages").finalizeData(m, "language") qr249rev5i7zx1r0cgyf4ex167cvt2g 239010 239009 2026-11-15T03:39:12Z Lee 19 [[:en:Module:languages/data/3/d]] වෙතින් එක් සංශෝධනයක් 239009 Scribunto text/plain local m_langdata = require("Module:languages/data") -- Loaded on demand, as it may not be needed (depending on the data). local function u(...) u = require("Module:string utilities").char return u(...) end local c = m_langdata.chars local p = m_langdata.puaChars local s = m_langdata.shared local m = {} m["daa"] = { "Dangaléat", 942591, "cdc-est", "Latn", } m["dac"] = { "Dambi", 12629491, "poz-ocw", "Latn", } m["dad"] = { "Marik", 6763404, "poz-ocw", "Latn", } m["dae"] = { "Duupa", 35263, "alv-dur", "Latn", } m["dag"] = { "Dagbani", 32238, "nic-dag", "Latn", } m["dah"] = { "Gwahatike", 5623246, "ngf-war", "Latn", } m["dai"] = { "Day", 35163, "alv-mbd", "Latn", } m["daj"] = { "Dar Fur Daju", 56370, "sdv-daj", "Latn", } m["dak"] = { "Dakota", 530384, "sio-dkt", "Latn", } m["dal"] = { "Dahalo", 35143, "cus", "Latn", } m["dam"] = { "Damakawa", 1158134, "nic-knn", "Latn", } m["dao"] = { "Daai Chin", 860029, "tbq-kuk", "Latn", } m["daq"] = { "Dandami Maria", 12952805, "dra-mdy", "Deva", } m["dar"] = { "Dargwa", 32332, "cau-drg", "Cyrl, Latn, Arab", translit = {Cyrl = "dar-translit"}, override_translit = true, display_text = {Cyrl = s["cau-Cyrl-displaytext"]}, strip_diacritics = { Cyrl = s["cau-Cyrl-stripdiacritics"], Latn = s["cau-Latn-stripdiacritics"], }, sort_key = { Cyrl = { from = { "къкъ", "хьхь", -- 4 chars "гъ", "гь", "гӏ", "ё", "къ", "кь", "кӏ", "пп", "пӏ", "сс", "тт", "тӏ", "хх", "хъ", "хь", "хӏ", "цц", "цӏ", "чч", "чӏ" -- 2 chars }, to = { "к" .. p[2], "х" .. p[4], "г" .. p[1], "г" .. p[2], "г" .. p[3], "е" .. p[1], "к" .. p[1], "к" .. p[3], "к" .. p[4], "п" .. p[1], "п" .. p[2], "с" .. p[1], "т" .. p[1], "т" .. p[2], "х" .. p[1], "х" .. p[2], "х" .. p[3], "х" .. p[5], "ц" .. p[1], "ц" .. p[2], "ч" .. p[1], "ч" .. p[2] } }, }, } m["das"] = { "Daho-Doo", 3915369, "kro-wee", "Latn", } m["dau"] = { "Dar Sila Daju", 7514020, "sdv-daj", "Latn", } m["dav"] = { "Taita", 2387274, "bnt-cht", "Latn", } m["daw"] = { "Davawenyo", 5228174, "phi", "Latn", } m["dax"] = { "Dayi", 10467281, "aus-yol", "Latn", } m["daz"] = { "Dao", 5221513, "ngf-pan", "Latn", } m["dba"] = { "Bangime", 1982696, "qfa-iso", -- southern Mali "Latn", } m["dbb"] = { "Deno", 56275, "cdc-wst", "Latn", } m["dbd"] = { "Dadiya", 3914436, "alv-wjk", "Latn", } m["dbe"] = { "Dabe", 5207451, "paa-tor", "Latn", } m["dbf"] = { "Edopi", 12953516, "paa-lpl", "Latn", } m["dbg"] = { "Dogul Dom", 3912880, "nic-npd", "Latn", } m["dbi"] = { "Doka", 3913293, "nic-plc", "Latn", } m["dbj"] = { "Ida'an", 3041552, "poz-san", "Latn", } m["dbl"] = { "Dyirbal", 35465, "aus-dyb", "Latn", } m["dbm"] = { "Duguri", 7194057, "nic-jrw", "Latn", } m["dbn"] = { "Duriankere", 5316627, "ngf-sbh", "Latn", } m["dbo"] = { "Dulbu", 5313310, "nic-jrn", "Latn", } m["dbp"] = { "Duwai", 56301, "cdc-wst", "Latn", } m["dbq"] = { "Daba", 3913342, "cdc-cbm", "Latn", } m["dbr"] = { "Dabarre", 3447286, "cus-som", "Latn", } m["dbt"] = { "Ben Tey", 4886561, "nic-nwa", "Latn", } m["dbu"] = { "Bondum Dom Dogon", 3912758, "nic-npd", "Latn", } m["dbv"] = { "Dungu", 5315230, "nic-kau", "Latn", } m["dbw"] = { "Bankan Tey Dogon", 4856243, "nic-nwa", "Latn", } m["dby"] = { "Dibiyaso", 5272268, "qfa-dis", -- Papuan; isolate per Glottolog, unclassified per Pawley and Hammarström (2018), sometimes classified with Bosavi languages "Latn", } m["dcc"] = { "Deccani", 669431, "inc-hnd", "Aran", ancestors = "ur", } m["dcr"] = { "Negerhollands", 1815830, "crp", "Latn", ancestors = "nl", } m["dda"] = { "Dadi Dadi", 50207890, "aus-pam", "Latn", } m["ddd"] = { "Dongotono", 56676, "sdv-lma", "Latn", } m["dde"] = { "Doondo", 11003401, "bnt-kng", "Latn", } m["ddg"] = { "Fataluku", 35353, "paa-eti", "Latn", } m["ddi"] = { "Diodio", 3028668, "poz-ocw", "Latn", } m["ddj"] = { "Jaru", 3162806, "aus-pam", "Latn", } m["ddn"] = { "Dendi", 35164, "son", "Latn", } m["ddo"] = { "Tsez", 34033, "cau-wts", "Cyrl", translit = "ddo-translit", display_text = {Cyrl = s["cau-Cyrl-displaytext"]}, strip_diacritics = {Cyrl = s["cau-Cyrl-stripdiacritics"]}, } m["ddr"] = { "Dhudhuroa", 5269842, "aus-pam", "Latn", } m["dds"] = { "Donno So Dogon", 1234776, "nic-dge", "Latn", } m["ddw"] = { "Dawera-Daweloor", 5242304, "poz-tim", "Latn", } m["dec"] = { "Dagik", 35125, "alv-tal", "Latn", } m["ded"] = { "Dedua", 5249850, "ngf-huo", "Latn", } m["dee"] = { "Dewoin", 3914892, "kro-wkr", "Latn", } m["def"] = { "Dezfuli", 4115412, "ira-swi", "Arab", ancestors = "pal", } m["deg"] = { "Degema", 35182, "alv-dlt", "Latn", } m["deh"] = { "Dehwari", 5704314, "ira-swi", "Arab", ancestors = "fa", } m["dei"] = { "Demisa", 56380, "paa-egb", "Latn", } -- "dek" is no longer an ISO code; spurious m["dem"] = { "Dem", 5254989, "qfa-dis", -- Papuan; isolate in Glottolog; unclassified in Palmer (2018); grouped with Amung by Usher, ultimately in TNG "Latn", } m["dep"] = { "Pidgin Delaware", 1183938, "crp", "Latn", ancestors = "unm", } -- deq is not included, see [[WT:LT]] m["der"] = { "Deori", 56478, "tbq-bdg", "Beng, Latn", } m["des"] = { "Desano", 962392, "sai-tuc", "Latn", } m["dev"] = { "Domung", 5291378, "ngf-yup", "Latn", } m["dez"] = { "Dengese", 2909984, "bnt-tet", "Latn", } m["dga"] = { "Southern Dagaare", 35159, "nic-mre", "Latn", } m["dgb"] = { "Bunoge", 4985178, "nic-dgw", "Latn", } m["dgc"] = { "Casiguran Dumagat Agta", 5313599, "phi", "Latn", } m["dgd"] = { "Dagaari Dioula", 11153465, "nic-mre", "Latn", } m["dge"] = { "Degenan", 5251770, "ngf-war", "Latn", } m["dgg"] = { "Doga", 3033726, "poz-ocw", "Latn", } m["dgh"] = { "Dghwede", 56293, "cdc-cbm", "Latn", } m["dgi"] = { "Northern Dagara", 11004218, "nic-mre", "Latn", } m["dgk"] = { "Dagba", 12952357, "csu-sar", "Latn", } m["dgn"] = { "Dagoman", 10465931, "aus-yng", "Latn", } m["dgr"] = { "Dogrib", 20979, "ath-nor", "Latn", } m["dgs"] = { "Dogoso", 35343, "nic-gur", } m["dgt"] = { "Ntra'ngith", 6983809, "aus-pam", "Latn", } -- dgu is not a language; see [[w:Dhekaru]] m["dgw"] = { "Daungwurrung", 5228050, "aus-pam", "Latn", } m["dgx"] = { "Doghoro", 12952392, "ngf-bin", "Latn", } m["dgz"] = { "Daga", 5208442, "ngf-dag", "Latn", } m["dhg"] = { "Dhangu", 5268960, "aus-yol", "Latn", } m["dhd"] = { "Dhundhari", 633359, "raj", "Deva", translit = "hi-translit", } m["dhi"] = { "Dhimal", 35229, "sit-dhi", "Deva", } m["dhl"] = { "Dhalandji", 5268787, "aus-psw", "Latn", } m["dhm"] = { "Zemba", 3502283, "bnt-swb", "Latn", ancestors = "hz", } m["dhn"] = { "Dhanki", 5268992, "inc-bhi", } m["dho"] = { "Dhodia", 5269658, "inc-bhi", "Deva", } m["dhr"] = { "Tharrgari", 10470289, "aus-psw", "Latn", } m["dhs"] = { "Dhaiso", 11001788, "bnt-kka", "Latn", } m["dhu"] = { "Dhurga", 1285318, "aus-yuk", "Latn", } m["dhv"] = { "Drehu", 3039319, "poz-cln", "Latn", } m["dhw"] = { "Danuwar", 3522797, "inc-bhi", "Deva", } m["dhx"] = { "Dhungaloo", 16960599, "aus-pam", "Latn", } m["dia"] = { "Dia", 3446591, "paa-wap", "Latn", } m["dib"] = { "South Central Dinka", 35154, "sdv-dnu", "Latn", ancestors = "din", } m["dic"] = { "Lakota Dida", 11001730, "kro-did", "Latn", } m["did"] = { "Didinga", 56365, "sdv", "Latn", } m["dif"] = { "Dieri", 25559563, "aus-kar", "Latn", } m["dig"] = { "Digo", 3362072, "bnt-mij", "Latn", } -- "dih" is split into nai-ipa, nai-kum, nai-tip, see [[WT:LT]] m["dii"] = { "Dimbong", 35196, "bnt-baf", "Latn", } m["dij"] = { "Dai", 5209056, "poz-tim", "Latn", } m["dik"] = { "Southwestern Dinka", 36540, "sdv-dnu", "Latn", ancestors = "din", } m["dil"] = { "Dilling", 35152, "nub-hil", "Latn", } m["dim"] = { "Dime", 35311, "omv-aro", } m["din"] = { "Dinka", 56466, "sdv-dnu", "Latn", } m["dio"] = { "Dibo", 3914891, "alv-ngb", "Latn", } m["dip"] = { "Northeastern Dinka", 36246, "sdv-dnu", "Latn", ancestors = "din", } m["dir"] = { "Dirim", 11130804, "nic-dak", "Latn", } m["dis"] = { "Dimasa", 56664, "tbq-bdg", "Latn, Beng", } m["diu"] = { "Gciriku", 3780954, "bnt-kav", "Latn", } m["diw"] = { "Northwestern Dinka", 36249, "sdv-dnu", "Latn", ancestors = "din", } m["dix"] = { "Dixon Reef", 5284967, "poz-vnc", "Latn", } m["diy"] = { "Diuwe", 5283765, "ngf-asm", "Latn", } m["diz"] = { "Ding", 35202, "bnt-bdz", "Latn", } m["dja"] = { "Djadjawurrung", 5285190, "aus-pam", "Latn", } m["djb"] = { "Djinba", 5285351, "aus-yol", "Latn", } m["djc"] = { "Dar Daju Daju", 5209890, "sdv-daj", "Latn", } m["djd"] = { "Jaminjung", 6147825, "aus-mir", "Latn", } m["dje"] = { "Zarma", 36990, "son", "Latn, Arab, Brai", } m["djf"] = { "Djangun", 10474818, "aus-pmn", "Latn", } m["dji"] = { "Djinang", 5285350, "aus-yol", "Latn", } m["djj"] = { "Ndjébbana", 5285274, "aus-arn", "Latn", } m["djk"] = { "Aukan", 2659044, "crp", "Latn, Afak", ancestors = "en", } m["djl"] = { "Djiwarli", 2669569, "aus-psw", "Latn", } m["djm"] = { "Jamsay", 3913290, "nic-pld", "Latn", } m["djn"] = { "Djauan", 13553748, "aus-gun", "Latn", } m["djo"] = { "Jangkang", 12952388, "day", } m["djr"] = { "Djambarrpuyngu", 3915679, "aus-yol", "Latn", } m["dju"] = { "Kapriman", 6367199, "paa-sep", "Latn", } m["djw"] = { "Djawi", 3913844, "aus-nyu", "Latn", ancestors = "bcj", } m["dka"] = { "Dakpa", 3695189, "sit-ebo", "Tibt", override_translit = true, -- Tibt translit, display_text, strip_diacritics, sort_key in [[Module:scripts/data]] } m["dkk"] = { "Dakka", 5209962, "poz-ssw", "Latn", } m["dkr"] = { "Kuijau", 13580777, "poz-bnn", "Latn", } m["dks"] = { "Southeastern Dinka", 36538, "sdv-dnu", "Latn", ancestors = "din", } m["dkx"] = { "Mazagway", 6798209, "cdc-cbm", "Latn", } m["dlg"] = { "Dolgan", 32878, "trk-nsb", "Cyrl", sort_key = { from = {"ё", "һ", "ӈ", "ө", "ү"}, to = {"е" .. p[1], "к" .. p[1], "н" .. p[1], "о" .. p[1], "у" .. p[1]} }, } m["dlk"] = { "Dahalik", 32260, "sem-eth", "Ethi", translit = "Ethi-translit", } m["dlm"] = { "Dalmatian", 35527, "roa-dal", "Latn", } m["dln"] = { "Darlong", 5224029, "tbq-kuk", "Latn", } m["dma"] = { "Duma", 35319, "bnt-nze", "Latn", } m["dmb"] = { "Mombo Dogon", 6897074, "nic-dgw", "Latn", } m["dmc"] = { "Gavak", 5277406, "ngf-nad", "Latn", } m["dmd"] = { "Madhi Madhi", 6727353, "aus-pam", "Latn", } m["dme"] = { "Dugwor", 56313, "cdc-cbm", "Latn", } m["dmf"] = { "Medefaidrin", 1519764, "art", "Medf", type = "appendix-constructed", } m["dmg"] = { "Upper Kinabatangan", 16109975, "poz-san", "Latn", } m["dmk"] = { "Domaaki", 32900, "inc-wes", "Arab", } m["dml"] = { "Dameli", 32288, "inc-kun", } m["dmm"] = { "Dama (Nigeria)", 5211865, "alv-mbm", "Latn", } m["dmo"] = { "Kemezung", 35562, "nic-bbe", "Latn", } m["dmr"] = { "East Damar", 5328200, "poz-cet", "Latn", } m["dms"] = { "Dampelas", 5212928, "poz-tot", "Latn", } m["dmu"] = { "Dubu", 7692059, "paa-wpw", "Latn", } m["dmv"] = { "Dumpas", 12953512, "poz-san", "Latn", } m["dmw"] = { "Mudburra", 6931573, "aus-pam", "Latn", } m["dmx"] = { "Dema", 3553423, "bnt-sho", "Latn", } m["dmy"] = { "Demta", 14466283, "paa-sen", "Latn", } m["dna"] = { "Upper Grand Valley Dani", 12952361, "ngf-gvd", "Latn", } m["dnd"] = { "Daonda", 5221528, "paa-war", "Latn", } m["dne"] = { "Ndendeule", 6983725, "bnt-mbi", "Latn", } m["dng"] = { "Dungan", 33050, "zhx-man", "Cyrl, Latn, Hants", generate_alternants = "zh-generatealternants", translit = {Cyrl = "dng-translit"}, sort_key = { Cyrl = { from = {"ё", "ә", "җ", "ң", "ў", "ү"}, to = {"е" .. p[1], "е" .. p[2], "ж" .. p[1], "н" .. p[1], "у" .. p[1], "у" .. p[2]} }, Hani = "Hani-sortkey", }, } m["dni"] = { "Lower Grand Valley Dani", 12635807, "ngf-gvd", "Latn", } m["dnj"] = { "Dan", 1158971, "dmn-mda", "Latn", } m["dnk"] = { "Dengka", 5256954, "poz-tim", "Latn", } m["dnn"] = { "Dzuun", 10973260, "dmn-smg", "Latn", } m["dno"] = { "Ndrulo", 60785094, "csu-lnd", } m["dnr"] = { "Danaru", 5214932, "ngf-pek", "Latn", } m["dnt"] = { "Mid Grand Valley Dani", 12952359, "ngf-gvd", "Latn", } m["dnu"] = { "Danau", 5013745, "mkh-pal", "Mymr", } m["dnv"] = { "Danu", 5221251, "tbq-brm", "Mymr", ancestors = "obr", } m["dnw"] = { "Western Dani", 7987774, "ngf-cda", "Latn", } m["dny"] = { "Dení", 56562, "auf", "Latn", } m["doa"] = { "Dom", 5289770, "ngf-sim", "Latn", } m["dob"] = { "Dobu", 952133, "poz-ocw", "Latn", } m["doc"] = { "Northern Kam", 17195499, "qfa-tak", "Latn", } m["doe"] = { "Doe", 5288055, "bnt-ruv", "Latn", } m["dof"] = { "Domu", 5291375, "paa-mal", "Latn", } m["doh"] = { "Dong", 3438405, "nic-dak", "Latn", } m["doi"] = { "Dogri", 32730, "him", "Deva, Takr, Aran, Dogr", translit = { Deva = "hi-translit", Dogr = "Dogr-translit", }, } m["dok"] = { "Dondo", 5295571, "poz-tot", "Latn", } m["dol"] = { "Doso", 4167202, "paa-dtu", "Latn", } m["don"] = { "Doura", 7829037, "poz-ocw", "Latn", } m["doo"] = { "Dongo", 35303, "nic-mbc", "Latn", } m["dop"] = { "Lukpa", 3258739, "nic-gne", "Latn", } m["doq"] = { "Dominican Sign Language", 5290820, "sgn", "Latn", -- when documented } m["dor"] = { "Dori'o", 3037084, "poz-sls", "Latn", } m["dos"] = { "Dogosé", 3913314, "nic-gur", "Latn", } m["dot"] = { "Dass", 3441293, "cdc-wst", "Latn", } m["dov"] = { "Toka-Leya", 11001779, "bnt-bot", "Latn", ancestors = "toi", } m["dow"] = { "Doyayo", 35299, "alv-dur", "Latn", } m["dox"] = { "Bussa", 35123, "cus-eas", "Latn", } m["doy"] = { "Dompo", 35270, "alv-gng", "Latn", } m["doz"] = { "Dorze", 56336, "omv-nom", "Latn", } m["dpp"] = { "Papar", 7132487, "poz-san", "Latn", } m["drb"] = { "Dair", 12952360, "nub-hil", "Latn", } m["drc"] = { "Minderico", 6863806, "roa-gap", "Latn", ancestors = "pt", } m["drd"] = { "Darmiya", 5224058, "sit-alm", } m["drg"] = { "Rungus", 6897407, "poz-san", "Latn", } m["dri"] = { "Lela", 3914004, "nic-knn", "Latn", } m["drl"] = { "Baagandji", 5223941, "aus-pam", "Latn", } m["drn"] = { "West Damar", 3450459, "poz-tim", "Latn", } m["dro"] = { "Daro-Matu Melanau", 5224156, "poz-bnn", "Latn", } m["drq"] = { "Dura", 3449842, "sit-gma", "Deva", } m["drs"] = { "Gedeo", 56622, "cus-hec", "Ethi", } m["dru"] = { "Rukai", 49232, "map", "Latn", ancestors = "dru-pro", } m["dry"] = { "Darai", 46995026, "inc-bih", "Deva", } m["dsb"] = { "Lower Sorbian", 13286, "wen", "Latn", sort_key = s["wen-sortkey"], standard_chars = "AaBbCcČčĆćDdEeĚěFfGgHhIiJjKkŁłLlMmNnŃńOoÓóPpRrŔŕSsŠšŚśTtUuWwYyZzŽžŹź" .. c.punc, } m["dse"] = { "Dutch Sign Language", 2201099, "sgn", "Latn", -- when documented } m["dsh"] = { "Daasanach", 56637, "cus-eas", "Latn", } m["dsi"] = { "Disa", 3914455, "csu-bgr", "Latn", } m["dsl"] = { "Danish Sign Language", 2605298, "sgn", "Latn", -- when documented } m["dsn"] = { "Dusner", 5316948, "poz-hce", "Latn", } m["dso"] = { "Desiya", 12629755, "inc-eas", "Orya", ancestors = "or", } m["dsq"] = { "Tadaksahak", 36568, "son", "Arab, Latn", } m["dta"] = { "Daur", 32430, "xgn", "Latn, Hani, Cyrl, Mong", ancestors = "xng", -- Mong translit, display_text and strip_diacritics in [[Module:scripts/data]] sort_key = {Hani = "Hani-sortkey"}, } m["dtb"] = { "Labuk-Kinabatangan Kadazan", 5330240, "poz-san", "Latn", } m["dtd"] = { "Ditidaht", 13728042, "wak", "Latn", } m["dth"] = { -- contrast 'rrt' "Adithinngithigh", 4683034, "aus-pmn", "Latn", } m["dti"] = { "Ana Tinga Dogon", 4750346, "qfa-dgn", "Latn", } m["dtk"] = { "Tene Kan Dogon", 11018863, "nic-pld", "Latn", } m["dtm"] = { "Tomo Kan Dogon", 11137719, "nic-pld", "Latn", } m["dto"] = { "Tommo So", 47012992, "nic-dge", "Latn", } m["dtp"] = { "Central Dusun", 5317225, "poz-san", "Latn", } m["dtr"] = { "Lotud", 6685078, "poz-san", "Latn", } m["dts"] = { "Toro So Dogon", 11003311, "nic-dge", "Latn", } m["dtt"] = { "Toro Tegu Dogon", 3913924, "nic-pld", "Latn", } m["dtu"] = { "Tebul Ure Dogon", 7692089, "qfa-dgn", "Latn", } m["dty"] = { "Doteli", 18415595, "inc-pae", "Deva", translit = "ne-translit", } m["dua"] = { "Duala", 33013, "bnt-saw", "Latn", } m["dub"] = { "Dubli", 5310792, "inc-bhi", } m["duc"] = { "Duna", 5314039, "qfa-dis", -- Papuan; isolate in Glottolog; tentatively grouped with Bogaya into a Duna-Pogaya [sic] family, -- ultimately in TNG "Latn", } m["due"] = { "Umiray Dumaget Agta", 7881585, "phi", "Latn", } m["duf"] = { "Dumbea", 6983819, "poz-cln", "Latn", } m["dug"] = { "Chiduruma", 35614, "bnt-mij", "Latn", } m["duh"] = { "Dungra Bhil", 12953513, "inc-bhi", "Deva, Gujr", } m["dui"] = { "Dumun", 5314004, "ngf-yag", "Latn", } m["duk"] = { "Uyajitaya", 7904085, "ngf-nur", "Latn", } m["dul"] = { "Alabat Island Agta", 3399709, "phi", "Latn", } m["dum"] = { "Middle Dutch", 178806, "gmw-frk", "Latn", ancestors = "odt", strip_diacritics = {remove_diacritics = c.circ .. c.macron .. c.diaer}, } m["dun"] = { "Dusun Deyah", 2784033, "poz-bre", "Latn", } m["duo"] = { "Dupaningan Agta", 5315912, "phi", "Latn", } m["dup"] = { "Duano", 3040468, "poz-mly", "Latn", } m["duq"] = { "Dusun Malang", 3041711, "poz-bre", "Latn", } m["dur"] = { "Dii", 35208, "alv-dur", "Latn", } m["dus"] = { "Dumi", 56315, "sit-kiw", "Deva", } m["duu"] = { "Drung", 56406, "sit-nng", "Latn", } m["duv"] = { "Duvle", 56364, "paa-lpl", "Latn", } m["duw"] = { "Dusun Witu", 2381310, "poz-bre", "Latn", } m["dux"] = { "Duun", 3914880, "dmn-smg", "Latn", } m["duy"] = { "Dicamay Agta", 5272321, "phi", "Latn", } m["duz"] = { "Duli", 5313405, "alv-ada", "Latn", } m["dva"] = { "Duau", 5310448, "poz-ocw", "Latn", } m["dwa"] = { "Diri", 56286, "cdc-wst", "Latn", } m["dwr"] = { "Dawro", 12629647, "omv-nom", "Ethi, Latn", } m["dwu"] = { "Dhuwal", 3120791, "aus-yol", "Latn", } m["dww"] = { "Dawawa", 5242286, "poz-ocw", "Latn", } m["dwy"] = { "Dhuwaya", 63348560, "aus-yol", "Latn", } m["dwz"] = { "Dewas Rai", 62663667, "inc-bhi", } m["dya"] = { "Dyan", 35340, "nic-gur", "Latn", } m["dyb"] = { "Dyaberdyaber", 5285185, "aus-nyu", "Latn", } m["dyd"] = { "Dyugun", 3913785, "aus-nyu", "Latn", } -- dyg (Villa Viciosa Agta) deleted as extinct and unattested; per Wikipedia: "Villa Viciosa Atta, supposed once spoken -- in Villaviciosa, Abra, is presumed to be related, but is unattested." m["dyi"] = { "Djimini", 35336, "alv-tdj", "Latn", } m["dym"] = { "Yanda Dogon", 8048316, "qfa-dgn", "Latn", } m["dyn"] = { "Dyangadi", 3913820, "aus-cww", "Latn", } m["dyo"] = { "Jola-Fonyi", 3507832, "alv-jol", "Latn", } m["dyu"] = { "Dyula", 32706, "dmn-man", "Latn", } m["dyy"] = { "Dyaabugay", 2591320, "aus-yid", "Latn", } m["dza"] = { "Tunzu", 3915845, "nic-jer", "Latn", } m["dzg"] = { "Dazaga", 35244, "ssa-sah", "Latn", } m["dzl"] = { "Dzala", 56607, "sit-ebo", "Tibt", override_translit = true, -- Tibt translit, display_text, strip_diacritics, sort_key in [[Module:scripts/data]] } m["dzn"] = { "Dzando", 5319622, "bnt-bun", "Latn", } return require("Module:languages").finalizeData(m, "language") qr249rev5i7zx1r0cgyf4ex167cvt2g Module:parse utilities 828 6858 239029 235162 2026-08-11T18:52:33Z en>Benwing2 0 move generate_obj_maybe_parsing_lang_prefix here and document it 239029 Scribunto text/plain local export = {} local fun_is_callable_module = "Module:fun/isCallable" local languages_module = "Module:languages" local parameters_module = "Module:parameters" local string_char_module = "Module:string/char" local string_utilities_module = "Module:string utilities" local table_insert_if_not_module = "Module:table/insertIfNot" local assert = assert local concat = table.concat local dump = mw.dumpObject local error = error local insert = table.insert local ipairs = ipairs local list_to_text = mw.text.listToText local pairs = pairs local require = require local sort = table.sort local type = type local ugsub = mw.ustring.gsub local function convert_val(...) convert_val = require(parameters_module).convert_val return convert_val(...) end local function get_lang(...) get_lang = require(languages_module).getByCode return get_lang(...) end local function insert_if_not(...) insert_if_not = require(table_insert_if_not_module) return insert_if_not(...) end local function is_callable(...) is_callable = require(fun_is_callable_module) return is_callable(...) end local function split(...) split = require(string_utilities_module).split return split(...) end local function u(...) u = require(string_char_module) return u(...) end local function umatch(...) umatch = require(string_utilities_module).match return umatch(...) end --[==[ intro: In order to understand the following parsing code, you need to understand how inflected text specs work. They are intended to work with inflected text where individual words to be inflected may be followed by inflection specs in angle brackets. The format of the text inside of the angle brackets is up to the individual language and part-of-speech specific implementation. A real-world example is as follows: `<nowiki>[[медичний|меди́чна]]<+> [[сестра́]]<*,*#.pr></nowiki>`. This is the inflection of the Ukrainian multiword expression {{m|uk|меди́чна сестра́||nurse|lit=medical sister}}, consisting of two words: the adjective {{m|uk|меди́чна||medical|pos=feminine singular}} and the noun {{m|uk|сестра́||sister}}. The specs in angle brackets follow each word to be inflected; for example, `<+>` means that the preceding word should be declined as an adjective. The code below works in terms of balanced expressions, which are bounded by delimiters such as `< >` or `[ ]`. The intention is to allow separators such as spaces to be embedded inside of delimiters; such embedded separators will not be parsed as separators. For example, Ukrainian noun specs allow footnotes in brackets to be inserted inside of angle brackets; something like `меди́чна<+> сестра́<pr.[this is a footnote]>` is legal, as is `<nowiki>[[медичний|меди́чна]]<+> [[сестра́]]<pr.[this is an <i>italicized footnote</i>]></nowiki>`, and the parsing code should not be confused by the embedded brackets, spaces or angle brackets. The parsing is done by two functions, which work in close concert: {parse_balanced_segment_run()} and {split_alternating_runs()}. To illustrate, consider the following: {parse_balanced_segment_run("foo<M.proper noun> bar<F>", "<", ">")} =<br /> { {"foo", "<M.proper noun>", " bar", "<F>", ""}} then {split_alternating_runs({"foo", "<M.proper noun>", " bar", "<F>", ""}, " ")} =<br /> { {{"foo", "<M.proper noun>", ""}, {"bar", "<F>", ""}}} Here, we start out with a typical inflected text spec `foo<M.proper noun> bar<F>`, call {parse_balanced_segment_run()} on it, and call {split_alternating_runs()} on the result. The output of {parse_balanced_segment_run()} is a list where even-numbered segments are bounded by the bracket-like characters passed into the function, and odd-numbered segments consist of the surrounding text. {split_alternating_runs()} is called on this, and splits '''only''' the odd-numbered segments, grouping all segments between the specified character. Note that the inner lists output by {split_alternating_runs()} are themselves in the same format as the output of {parse_balanced_segment_run()}, with bracket-bounded text in the even-numbered segments. Hence, such lists can be passed again to {split_alternating_runs()}. ]==] --[==[ Parse a string containing matched instances of parens, brackets or the like. Return a list of strings, alternating between textual runs not containing the open/close characters and runs beginning and ending with the open/close characters. For example, {parse_balanced_segment_run("foo(x(1)), bar(2)", "(", ")") = {"foo", "(x(1))", ", bar", "(2)", ""}} ]==] function export.parse_balanced_segment_run(segment_run, open, close) return split(segment_run, "(%b" .. open .. close .. ")") end -- The following is an equivalent, older implementation that does not use %b (written before I was aware of %b). --[=[ function export.parse_balanced_segment_run(segment_run, open, close) local break_on_open_close = split(segment_run, "([%" .. open .. "%" .. close .. "])") local text_and_specs = {} local level = 0 local seg_group = {} for i, seg in ipairs(break_on_open_close) do if i % 2 == 0 then if seg == open then insert(seg_group, seg) level = level + 1 else assert(seg == close) insert(seg_group, seg) level = level - 1 if level < 0 then error("Unmatched " .. close .. " sign: '" .. segment_run .. "'") elseif level == 0 then insert(text_and_specs, concat(seg_group)) seg_group = {} end end elseif level > 0 then insert(seg_group, seg) else insert(text_and_specs, seg) end end if level > 0 then error("Unmatched " .. open .. " sign: '" .. segment_run .. "'") end return text_and_specs end ]=] --[==[ Like parse_balanced_segment_run() but accepts multiple sets of delimiters. For example, {parse_multi_delimiter_balanced_segment_run("foo[bar(baz[bat])], quux<glorp>", {{"[", "]"}, {"(", ")"}, {"<", ">"}}) = {"foo", "[bar(baz[bat])]", ", quux", "<glorp>", ""}}. Each element in the list of delimiter pairs is a string specifying an equivalence class of possible delimiter characters. You can use this, for example, to allow either "[" or "&amp;#91;" to be treated equivalently, with either one closed by either "]" or "&amp;#93;". To do this, first replace "&amp;#91;" and "&amp;#93;" with single Unicode characters such as U+FFF0 and U+FFF1, and then specify a two-character string containing "[" and U+FFF0 as the opening delimiter, and a two-character string containing "]" and U+FFF1 as the corresponding closing delimiter. If `no_error_on_unmatched` is given and an error is found during parsing, a string is returned containing the error message instead of throwing an error. ]==] function export.parse_multi_delimiter_balanced_segment_run(segment_run, delimiter_pairs, no_error_on_unmatched) local escaped_delimiter_pairs = {} local open_to_close_map = {} local open_close_items = {} local open_items = {} for _, open_close in ipairs(delimiter_pairs) do local open, close = open_close[1], open_close[2] open = open:gsub("([%[%]%%%%-])", "%%%1") close = close:gsub("([%[%]%%%%-])", "%%%1") insert(open_close_items, open) insert(open_close_items, close) insert(open_items, open) open = "[" .. open .. "]" close = "[" .. close .. "]" open_to_close_map[open] = close insert(escaped_delimiter_pairs, {open, close}) end local open_close_pattern = "([" .. concat(open_close_items) .. "])" local open_pattern = "([" .. concat(open_items) .. "])" local break_on_open_close = split(segment_run, open_close_pattern) local text_and_specs = {} local level = 0 local seg_group = {} local open_at_level_zero for i, seg in ipairs(break_on_open_close) do if i % 2 == 0 then insert(seg_group, seg) if level == 0 then if not umatch(seg, open_pattern) then local errmsg = "Unmatched close sign " .. seg .. ": '" .. segment_run .. "'" if no_error_on_unmatched then return errmsg else error(errmsg) end end assert(open_at_level_zero == nil) for _, open_close in ipairs(escaped_delimiter_pairs) do local open = open_close[1] if umatch(seg, open) then open_at_level_zero = open break end end if open_at_level_zero == nil then error(("Internal error: Segment %s didn't match any open regex"):format(seg)) end level = level + 1 elseif umatch(seg, open_at_level_zero) then level = level + 1 elseif umatch(seg, open_to_close_map[open_at_level_zero]) then level = level - 1 assert(level >= 0) if level == 0 then insert(text_and_specs, concat(seg_group)) seg_group = {} open_at_level_zero = nil end end elseif level > 0 then insert(seg_group, seg) else insert(text_and_specs, seg) end end if level > 0 then local errmsg = "Unmatched open sign " .. open_at_level_zero .. ": '" .. segment_run .. "'" if no_error_on_unmatched then return errmsg else error(errmsg) end end return text_and_specs end --[==[ Check whether a term contains top-level HTML. We want to distinguish inline modifiers from HTML. We assume an inline modifier is either a boolean modifier like `<bor>` or a prefix modifier like `<tr:Miryem>`. All other things inside of angle brackets, e.g. `<nowiki><span class="foo"></nowiki>`, `<nowiki></span></nowiki>`, `<nowiki><br/></nowiki>`, etc., should be flagged as HTML (typically caused by wrapping an argument in {{tl|m|...}}, {{tl|af|...}} or similar, but sometimes specified directly, e.g. `<nowiki><sup>6</sup></nowiki>`). By default, we assume the tag in an inline modifier contains either letters, numbers, hyphens or underscore (but not spaces), and must either stand alone or be followed by a colon, leading to a default HTML-checking pattern of {"<[%w_%-]*[^%w_%-:>]"}. But this can be modified; e.g. [[Module:tl-pronunciation]] allows modifiers of the form `<<var>pos</var>^<var>defn</var>>` or `<<var>pos</var>,<var>pos</var>,<var>pos</var>^<var>defn</var>>`, and would need to use its own HTML pattern. It's important we restrict the check for HTML to top-level to allow for generated HTML inside of e.g. qualifier tags, such as `<nowiki>foo<q:similar to {{m|fr|bar}}></nowiki>`. ]==] function export.term_contains_top_level_html(term, html_pattern) html_pattern = html_pattern or "<[%w_%-]*[^%w_%-:>]" -- If no HTML anywhere, the answer is no. if not term:find(html_pattern) then return false end -- Otherwise, we have to call parse_balanced_segment_run() and check alternate runs at top level. local runs = export.parse_balanced_segment_run(term, "<", ">") for i = 2, #runs, 2 do if runs[i]:find("^" .. html_pattern) then return true end end return false end --[==[ Check whether a term appears to have already been passed through `full_link()`. Passing it again will mangle it in various ways; at best it will have unnecessary lang/script wrapping, which might do nothing but might result in overly large fonts or other issues. We also check for uses of {{tl|ja-r/args}}, {{tl|ryu-r/args}} or {{tl|ko-l/args}}, which will be manged by `full_link()`. If this check succeeds, use the text raw instead of passing through `full_link()`. ]==] function export.term_already_linked(term) return term:find("<span") or term:find("{{ja%-r|") or term:find("{{ryu%-r|") or term:find("{{ko%-l|") end --[==[ Split a list of alternating textual runs of the format returned by `parse_balanced_segment_run` on `splitchar`. This only splits the odd-numbered textual runs (the portions between the balanced open/close characters). The return value is a list of lists, where each list contains an odd number of elements, where the even-numbered elements of the sublists are the original balanced textual run portions. For example, if we do {parse_balanced_segment_run("foo<M.proper noun> bar<F>", "<", ">") = {"foo", "<M.proper noun>", " bar", "<F>", ""}} then {split_alternating_runs({"foo", "<M.proper noun>", " bar", "<F>", ""}, " ") = {{"foo", "<M.proper noun>", ""}, {"bar", "<F>", ""}}} Note that we did not touch the text "<M.proper noun>" even though it contains a space in it, because it is an even-numbered element of the input list. This is intentional and allows for embedded separators inside of brackets/parens/etc. Note also that the inner lists in the return value are of the same form as the input list (i.e. they consist of alternating textual runs where the even-numbered segments are balanced runs), and can in turn be passed to split_alternating_runs(). If `preserve_splitchar` is passed in, the split character is included in the output, as follows: {split_alternating_runs({"foo", "<M.proper noun>", " bar", "<F>", ""}, " ", true) = {{"foo", "<M.proper noun>", ""}, {" "}, {"bar", "<F>", ""}}} Consider what happens if the original string has multiple spaces between brackets, and multiple sets of brackets without spaces between them. {parse_balanced_segment_run("foo[dated][low colloquial] baz-bat quux xyzzy[archaic]", "[", "]") = {"foo", "[dated]", "", "[low colloquial]", " baz-bat quux xyzzy", "[archaic]", ""}} then {split_alternating_runs({"foo", "[dated]", "", "[low colloquial]", " baz-bat quux xyzzy", "[archaic]", ""}, "[ %-]") = {{"foo", "[dated]", "", "[low colloquial]", ""}, {"baz"}, {"bat"}, {"quux"}, {"xyzzy", "[archaic]", ""}}} If `preserve_splitchar` is passed in, the split character is included in the output, as follows: {split_alternating_runs({"foo", "[dated]", "", "[low colloquial]", " baz bat quux xyzzy", "[archaic]", ""}, "[ %-]", true) = {{"foo", "[dated]", "", "[low colloquial]", ""}, {" "}, {"baz"}, {"-"}, {"bat"}, {" "}, {"quux"}, {" "}, {"xyzzy", "[archaic]", ""}}} As can be seen, the even-numbered elements in the outer list are one-element lists consisting of the separator text. ]==] function export.split_alternating_runs(segment_runs, splitchar, preserve_splitchar) local grouped_runs = {} local run = {} for i, seg in ipairs(segment_runs) do if i % 2 == 0 then insert(run, seg) else local parts = split(seg, preserve_splitchar and "(" .. splitchar .. ")" or splitchar) insert(run, parts[1]) for j=2,#parts do insert(grouped_runs, run) run = {parts[j]} end end end if #run > 0 then insert(grouped_runs, run) end return grouped_runs end --[==[ After calling `parse_multi_delimiter_balanced_segment_run()`, rejoin delimiter-bounded textual runs (i.e. textual runs surrounded by certain matched delimiters) with the runs on either side. This can be used when some of the matched delimiters are specified only in order to ensure that delimiters inside of other delimiters aren't parsed. As an example, [[Module:object usage]] calls {m_parse_utilities.parse_multi_delimiter_balanced_segment_run(object, {{"[", "]"}, {"(", ")"}, {"<", ">"}})} but the actual syntax of {{tl|+obj}} only uses parens and angle brackets as delimiters. Square brackets are included so that internal links are treated as units (i.e. parens and angle brackets occurring inside of them aren't parsed), but beyond that we don't treat square brackets as delimiters, so we want to rejoin square-bracket-delimited textual runs with adjacent runs before further parsing. There are two primary workflows when using this function: # If you only care about balanced delimiters occurring inside of other balanced delimiters (e.g. in the above example with [[Module:object usage]], you can call `rejoin_delimited_runs()` directly after `parse_multi_delimiter_balanced_segment_run()`. # However, if you care about single delimiters such as commas and slashes occurring inside of balanced delimiters (e.g. if you allow multiple comma-separated terms, e.g. of which can have associated inline modifiers, and you don't want commas inside of internal links to be treated as delimiters), you need to call `rejoin_delimited_runs()` ''after'' calling `split_alternating_runs()`. This is used, for example, in `parse_inline_modifiers()` for exactly this reason, when a `splitchar` is provided. `data` is an object of properties. Currently there are two: `runs` (the output of calling `parse_multi_delimiter_balanced_segment_run()`, i.e. a list of textual runs, where even-numbered elements begin and end with a matched delimiter and odd-numbered elements are surrounding text) and `delimiter_pattern` (a Lua pattern matching delimited textual runs that we want to rejoin with the surrounding text). `delimiter_pattern` should normally be anchored at the beginning; e.g. {"^%["} would be the correct pattern to use when rejoining square-bracket-delimited textual runs, as described above. ]==] function export.rejoin_delimited_runs(data) local joined_runs = {} local i = 1 while i <= #data.runs do local run = data.runs[i] if i % 2 == 0 and run:find(data.delimiter_pattern) then joined_runs[#joined_runs] = joined_runs[#joined_runs] .. run .. data.runs[i + 1] i = i + 2 else insert(joined_runs, run) i = i + 1 end end return joined_runs end function export.strip_spaces(text) return (ugsub(text, "^%s*(.-)%s*$", "%1")) end --[==[ Apply an arbitrary function `frob` to the "raw-text" segments in a split run set (the output of split_alternating_runs()). We leave alone stuff within balanced delimiters (footnotes, inflection specs and the like), as well as splitchars themselves if present. `preserve_splitchar` indicates whether splitchars are present in the split run set. `frob` is a function of one argument (the string to frob) and should return one argument (the frobbed string). We operate by only frobbing odd-numbered segments, and only in odd-numbered runs if preserve_splitchar is given. ]==] function export.frob_raw_text_alternating_runs(split_run_set, frob, preserve_splitchar) for i, run in ipairs(split_run_set) do if not preserve_splitchar or i % 2 == 1 then for j, segment in ipairs(run) do if j % 2 == 1 then run[j] = frob(segment) end end end end end --[==[ Like split_alternating_runs() but applies an arbitrary function `frob` to "raw-text" segments in the result (i.e. not stuff within balanced delimiters such as footnotes and inflection specs, and not splitchars if present). `frob` is a function of one argument (the string to frob) and should return one argument (the frobbed string). ]==] function export.split_alternating_runs_and_frob_raw_text(run, splitchar, frob, preserve_splitchar) local split_runs = export.split_alternating_runs(run, splitchar, preserve_splitchar) export.frob_raw_text_alternating_runs(split_runs, frob, preserve_splitchar) return split_runs end --[==[ FIXME: Older entry point. Call `split_alternating_runs_and_frob_raw_text()` in [[Module:parse utilities]] directly. Like `split_alternating_runs()` but strips spaces from both ends of the odd-numbered elements (only in odd-numbered runs if `preserve_splitchar` is given). Effectively we leave alone the footnotes and splitchars themselves, but otherwise strip extraneous spaces. Spaces in the middle of an element are also left alone. ]==] function export.split_alternating_runs_and_strip_spaces(segment_runs, splitchar, preserve_splitchar) return export.split_alternating_runs_and_frob_raw_text(segment_runs, splitchar, export.strip_spaces, preserve_splitchar) end --[==[ Split the non-modifier parts of an alternating run (after parse_balanced_segment_run() is called) on a Lua pattern, but not on certain sequences involving characters in that pattern (e.g. comma+whitespace). `splitchar` is the pattern to split on; `preserve_splitchar` indicates whether to preserve the delimiter and is the same as in split_alternating_runs(). `escape_fun` is called beforehand on each run of raw text and should return two values: the escaped run and whether unescaping is needed. If any call to `escape_fun` indicates that unescaping is needed, `unescape_fun` will be called on each run of raw text after splitting on `splitchar`. The return value of this function is as in split_alternating_runs(). ]==] function export.split_alternating_runs_escaping(run, splitchar, preserve_splitchar, escape_fun, unescape_fun) -- First replace comma with a temporary character in comma+whitespace sequences. local need_unescape = false for i in ipairs(run) do if i % 2 == 1 and escape_fun then local this_need_unescape run[i], this_need_unescape = escape_fun(run[i]) need_unescape = need_unescape or this_need_unescape end end if need_unescape then return export.split_alternating_runs_and_frob_raw_text(run, splitchar, unescape_fun, preserve_splitchar) else return export.split_alternating_runs(run, splitchar, preserve_splitchar) end end --[==[ Replace comma with a temporary char in comma + whitespace. ]==] function export.escape_comma_whitespace(run, tempcomma) tempcomma = tempcomma or u(0xFFF0) local escaped = false if run:find("\\,") then -- FIXME: we should probably convert literal \\ to \ to allow people to put a backslash before a comma that -- should be passed through; but maybe it's enough to use an HTML escape for the comma or backslash. run = (run:gsub("\\,", tempcomma)) -- discard backslash before comma, doing its duty to protect the comma escaped = true end if run:find(",%s") then run = (run:gsub(",(%s)", tempcomma .. "%1")) escaped = true end return run, escaped end --[==[ Undo the replacement of comma with a temporary char. ]==] function export.unescape_comma_whitespace(run, tempcomma) tempcomma = tempcomma or u(0xFFF0) return (run:gsub(tempcomma, ",")) end --[==[ Split the non-modifier parts of an alternating run (after parse_balanced_segment_run() is called) on comma, but not on comma+whitespace. See `split_on_comma()` above for more information and the meaning of `tempcomma`. ]==] function export.split_alternating_runs_on_comma(run, tempcomma) tempcomma = tempcomma or u(0xFFF0) -- Replace comma with a temporary char in comma + whitespace. local function escape_comma_whitespace(seg) return export.escape_comma_whitespace(seg, tempcomma) end -- Undo replacement of comma with a temporary char in comma + whitespace. local function unescape_comma_whitespace(seg) return export.unescape_comma_whitespace(seg, tempcomma) end return export.split_alternating_runs_escaping(run, ",", false, escape_comma_whitespace, unescape_comma_whitespace) end --[==[ Split text on a Lua pattern, but not on certain sequences involving characters in that pattern (e.g. comma+whitespace). `splitchar` is the pattern to split on; `preserve_splitchar` indicates whether to preserve the delimiter between split segments. `escape_fun` is called beforehand on the text and should return two values: the escaped run and whether unescaping is needed. If the call to `escape_fun` indicates that unescaping is needed, `unescape_fun` will be called on each run of text after splitting on `splitchar`. The return value of this a list of runs, interspersed with delimiters if `preserve_splitchar` is specified. ]==] function export.split_escaping(text, splitchar, preserve_splitchar, escape_fun, unescape_fun) if not umatch(text, splitchar) then return {text} end -- If there are square or angle brackets, we don't want to split on delimiters inside of them. To effect this, we -- use parse_multi_delimiter_balanced_segment_run() to parse balanced brackets, then do delimiter splitting on the -- non-bracketed portions of text using split_alternating_runs_escaping(), and concatenate back to a list of -- strings. When calling parse_multi_delimiter_balanced_segment_run(), we make sure not to throw an error on -- unbalanced brackets; in that case, we fall through to the code below that handles the case without brackets. if text:find("[%[<]") then local runs = export.parse_multi_delimiter_balanced_segment_run(text, {{"[", "]"}, {"<", ">"}}, "no error on unmatched") if type(runs) ~= "string" then local split_runs = export.split_alternating_runs_escaping(runs, splitchar, preserve_splitchar, escape_fun, unescape_fun) for i = 1, #split_runs do split_runs[i] = concat(split_runs[i]) end return split_runs end end -- First escape sequences we don't want to count for splitting. local need_unescape if escape_fun then text, need_unescape = escape_fun(text) end local parts = split(text, preserve_splitchar and "(" .. splitchar .. ")" or splitchar) if need_unescape then for i = 1, #parts, (preserve_splitchar and 2 or 1) do parts[i] = unescape_fun(parts[i]) end end return parts end --[==[ Split text on comma, but not on comma+whitespace. This is similar to `mw.text.split(text, ",")` but will not split on commas directly followed by whitespace, to handle embedded commas in terms (which are almost always followed by a space). `tempcomma` is the Unicode character to temporarily use when doing the splitting; normally U+FFF0, but you can specify a different character if you use U+FFF0 for some internal purpose. ]==] function export.split_on_comma(text, tempcomma) -- Don't do anything if no comma. Note that split_escaping() has a similar check at the beginning, so if there's a -- comma we effectively do this check twice, but this is worth it to optimize for the common no-comma case. if not text:find(",") then return {text} end tempcomma = tempcomma or u(0xFFF0) -- Replace comma with a temporary char in comma + whitespace. local function escape_comma_whitespace(run) return export.escape_comma_whitespace(run, tempcomma) end -- Undo replacement of comma with a temporary char in comma + whitespace. local function unescape_comma_whitespace(run) return export.unescape_comma_whitespace(run, tempcomma) end return export.split_escaping(text, ",", false, escape_comma_whitespace, unescape_comma_whitespace) end --[==[ Ensure that Wikicode (template calls, bracketed links, HTML, bold/italics, etc.) displays literally in error messages by inserting a Unicode word-joiner symbol after all characters that may trigger Wikicode interpretation. Replacing with equivalent HTML escapes doesn't work because they are displayed literally. I could not get this to work using <nowiki>...</nowiki> (those tags display literally), using using {{#tag:nowiki|...}} (same thing) or using mw.getCurrentFrame():extensionTag("nowiki", ...) (everything gets converted to a strip marker `UNIQ--nowiki-00000000-QINU` or similar). FIXME: This is a massive hack; there must be a better way. ]==] function export.escape_wikicode(term) term = term:gsub("([%[<'{])", "%1" .. u(0x2060)) return term end function export.make_parse_err(arg_gloss) return function(msg, stack_frames_to_ignore) error(export.escape_wikicode(("%s: %s"):format(msg, arg_gloss)), stack_frames_to_ignore) end end -- Parse a term that may include a link '[[LINK]]' or a two-part link '[[LINK|DISPLAY]]'. FIXME: Doesn't currently -- handle embedded links like '[[FOO]] [[BAR]]' or [[FOO|BAR]] [[BAZ]]' or '[[FOO]]s'; if they are detected, it returns -- the term unchanged and `nil` for the display form. local function parse_bracketed_term(term, parse_err) local inside = term:match("^%[%[(.*)%]%]$") if inside then if inside:find("%[%[") or inside:find("%]%]") then -- embedded links, e.g. '[[FOO]] [[BAR]]'; FIXME: we should process them properly return term, nil end local parts = split(inside, "|") if #parts > 2 then parse_err("Saw more than two parts inside a bracketed link") end return parts[1], parts[2] end return term, nil end --[==[ Parse a term that may have a language code (or possibly multiple plus-separated language codes, if `data.allow_multiple` is given) preceding it (e.g. {la:minūtia} or {grc:[[σκῶρ|σκατός]]} or {nan-hbl+hak:[[毋]][[知]]}). Return five arguments: # the original prefixed term; in the case of a Wikipedia or Wikisource prefix followed by a two-part link, it is a two-part link with the Wikipedia/Wikisource prefix moved inside the link; in the case of a Wikipedia or Wikisource prefix followed by a redundant one-part link, the brackets are removed; # the language object corresponding to the language code (possibly a family object if `data.allow_family` is given), or a list of such objects if `data.allow_multiple` is given; # the link if the unprefixed term is of the form <code>[[<var>link</var>|<var>display</var>]]</code> or of the form <code>[[<var>link</var>]]</code>, otherwise the full unprefixed term; # the display part if the term is of the form <code>[[<var>link</var>|<var>display</var>]]</code> or has a Wikipedia or Wikisource prefix (in which case the part minus the prefix and any following language code will be returned, with redundant brackets stripped), else {nil}; # {true} if the term has a Wikipedia/Wikisource prefix, else {false}. Etymology-only languages are always allowed. This function also correctly handles Wikipedia prefixes (e.g. {w:Abatemarco} or {w:it:Colle Val d'Elsa} or {lw:ru:Филарет}) and Wikisource prefixes (e.g. {s:Twelve O'Clock} or {s:[[Walden/Chapter XVIII|Walden]]} or {s:fr:Perceval ou le conte du Graal} or {s:ro:[[Domnul Vucea|Mr. Vucea]]} or {ls:ko:이상적 부인} or {ls:ko:[[조선 독립의 서#一. 槪論|조선 독립의 서]]}) and converts them into two-part links, with the display form not including the Wikipedia or Wikisource prefix unless it was explicitly specified using a two-part link as in {lw:ru:[[Филарет (Дроздов)|Митрополи́т Филаре́т]]} or {ls:ko:[[조선 독립의 서#一. 槪論|조선 독립의 서]]}. The difference between {w:} ("Wikipedia") and {lw:} ("Wikipedia link") is that the latter requires a language code and returns the corresponding language object; same for the difference between {s:} ("Wikisource") and {ls:} ("Wikisource link"). NOTE: Embedded links are not correctly handled currently. If an embedded link is detected, the whole term is returned as the link part (third argument), and the display part is nil. If you construct your own link from the link and display parts, you must check for this. The calling convention is to pass in a single argument `data` containing the following fields: * `term`: The term to parse. * `parse_err`: An optional function of one or two arguments to display an error. (The second argument to the function is the number of stack frames to ignore when calling error(); if you declare your error function with only one argument, things will still work fine.) * `paramname`: If `parse_err` is omitted, this should be a string naming a parameter to display in the error message, along with the term in question, and will be used to generate a `parse_err` function using `make_parse_err()`. (If `paramname` is omitted, just the term itself appears in the error message.) * `allow_multiple`: Allow multiple plus-separated language codes, e.g. {nan-hbl+hak:[[毋]][[知]]}. See above. * `allow_family`: Allow family objects to appear in place of language codes. * `allow_bad`: Don't throw an error on invalid language code prefixes; instead, include the prefix and colon as part of the term. Note that if a prefix doesn't look like a language code (e.g. if it's a number), the code won't even try to parse it as a language code, regardless of the `allow_bad` setting, but will always include it in the term. * `lang_cache`: A table mapping language codes to language objects, where invalid language codes are indicated by the value `false`. If this field is specified, the cache will be consulted before calling `getByCode()` in [[Module:languages]], and the result cached. If not specified, no cache will be used. ]==] function export.parse_term_with_lang(data) local term = data.term local parse_err = data.parse_err or data.paramname and export.make_parse_err(("%s=%s"):format(data.paramname, term)) or export.make_parse_err(term) -- Parse off an initial language code (e.g. 'la:minūtia' or 'grc:[[σκῶρ|σκατός]]'). First check for Wikipedia -- prefixes ('w:Abatemarco' or 'w:it:Colle Val d'Elsa' or 'lw:zh:邹衡') and Wikisource prefixes -- ('s:ro:[[Domnul Vucea|Mr. Vucea]]' or 'ls:ko:이상적 부인'). Wikipedia/Wikisource language codes follow a similar -- format to Wiktionary language codes (see below). Here and below we don't parse if there's a space after the -- colon (happens e.g. if the user uses {{desc|...}} inside of {{col}}, grrr ...). local termlang, foreign_wiki, actual_term = term:match("^(l?[ws]):([a-z][a-z][a-z-]*):([^ ].*)$") if not termlang then termlang, actual_term = term:match("^([ws]):([^ ].*)$") end if termlang then local wiki_links = termlang:find("^l") local base_wiki_prefix = termlang:find("w$") and "w:" or "s:" local wiki_prefix = base_wiki_prefix .. (foreign_wiki and foreign_wiki .. ":" or "") local link, display = parse_bracketed_term(actual_term, parse_err) if link:find("%[%[") or display and display:find("%[%[") then -- FIXME, this should be handlable with the right parsing code parse_err("Cannot have embedded brackets following a Wikipedia (w:... or lw:...) link; expand the term to a fully bracketed term w:[[LINK|DISPLAY]] or similar") end local lang = wiki_links and get_lang(foreign_wiki, parse_err, "allow etym") or nil local prefixed_link = wiki_prefix .. link if display then return ("[[%s|%s]]"):format(prefixed_link, display), lang, prefixed_link, display, true else -- Return the link minus any language codes as the fourth term (display form). Previously we returned `actual_term` -- but this causes problems with redundant Wikipedia links of the form `w:[[Dragon Ball Z]]`. Don't generate a -- two-part link so you can specify a display form in 3=. Note that the fourth and fifth params are currently only -- used in [[Module:quote]]. return prefixed_link, lang, prefixed_link, link, true end end -- Wiktionary language codes are in one of the following formats, where 'x' is a lowercase letter and 'X' an -- uppercase letter: -- xx -- xxx -- xxx-xxx -- xxx-xxx-xxx (esp. for protolanguages) -- xx-xxx (for etymology-only languages) -- xx-xxx-xxx (maybe? for etymology-only languages) -- xx-XX (for etymology-only languages, where XX is a country code, e.g. en-US) -- xxx-XX (for etymology-only languages, where XX is a country code) -- xx-xxx-XX (for etymology-only languages, where XX is a country code) -- xxx-xxx-XX (for etymology-only langauges, where XX is a country code, e.g. nan-hbl-PH) -- Things like xxx-x+ (e.g. cmn-pinyin, cmn-tongyong) -- VL., LL., etc. -- -- We check the for nonstandard Latin etymology language codes separately, and otherwise make only the following -- assumptions: -- (1) There are one to three hyphen-separated components. -- (2) The last component can consist of two uppercase ASCII letters; otherwise, all components contain only -- lowercase ASCII letters. -- (3) Each component must have at least two letters. -- (4) The first component must have two or three letters. local function is_possible_lang_code(code) -- Special hack for Latin variants, which can have nonstandard etym codes, e.g. VL., LL. if code:find("^[A-Z]L%.$") then return true end return code:find("^([a-z][a-z][a-z]?)$") or code:find("^[a-z][a-z][a-z]?%-[A-Z][A-Z]$") or code:find("^[a-z][a-z][a-z]?%-[a-z][a-z]+$") or code:find("^[a-z][a-z][a-z]?%-[a-z][a-z]+%-[A-Z][A-Z]$") or code:find("^[a-z][a-z][a-z]?%-[a-z][a-z]+%-[a-z][a-z]+$") end local function get_by_code(code, allow_bad) local lang if data.lang_cache then lang = data.lang_cache[code] end if lang == nil then lang = get_lang(code, not allow_bad and parse_err or nil, "allow etym", data.allow_family) if data.lang_cache then data.lang_cache[code] = lang or false end end return lang or nil end if data.allow_multiple then local termlang_spec termlang_spec, actual_term = term:match("^([a-zA-Z.,+-]+):([^ ].*)$") if termlang_spec then termlang = split(termlang_spec, "[,+]") local all_possible_code = true for _, code in ipairs(termlang) do if not is_possible_lang_code(code) then all_possible_code = false break end end if all_possible_code then local saw_nil = false for i, code in ipairs(termlang) do termlang[i] = get_by_code(code, data.allow_bad) if not termlang[i] then saw_nil = true end end if saw_nil then termlang = nil else term = actual_term end else termlang = nil end end else termlang, actual_term = term:match("^([a-zA-Z.-]+):([^ ].*)$") if termlang then if is_possible_lang_code(termlang) then termlang = get_by_code(termlang, data.allow_bad) if termlang then term = actual_term end else termlang = nil end end end local link, display = parse_bracketed_term(term, parse_err) return term, termlang, link, display, false end --[==[ Maybe parse any language prefix off of a given term and store the term and language(s) into a new or existing object. This function is useful for implementing a `generate_obj` handler of `parse_inline_modifiers` that can support terms with prefixed language(s). This wraps `parse_term_with_lang` and has the same handling of language prefixes as that function. The calling convention is to pass in a single argument `data` containing the following fields (NOTE: you must set `parse_lang_prefix` to get language-prefix-parsing behavior): * `term`: The term to parse. This is the only required parameter. * `parse_lang_prefix`: This must be specified in order for language prefixes to be recognized and parsed off. * `termobj`: The existing object to store results into. If unspecified, a new object is created. * `term_dest`: The field in `termobj` into which the term itself (minus any language prefix) is stored. If unspecified, defaults to {"term"}. * `parse_err`: An optional function of one or two arguments to display an error. (The second argument to the function is the number of stack frames to ignore when calling error(); if you declare your error function with only one argument, things will still work fine.) * `paramname`: If `parse_err` is omitted, this should be a string naming a parameter to display in the error message, along with the term in question, and will be used to generate a `parse_err` function using `make_parse_err()`. (If `paramname` is omitted, just the term itself appears in the error message.) * `allow_multiple_lang_prefixes`: Allow multiple plus-separated language codes, e.g. {nan-hbl+hak:[[毋]][[知]]}. See `parse_term_with_lang` for more information. * `allow_bad_lang_prefix`: Don't throw an error on invalid language code prefixes; instead, include the prefix and colon as part of the term. Note that if a prefix doesn't look like a language code (e.g. if it's a number), the code won't even try to parse it as a language code, regardless of this setting, but will always include it in the term. * `allow_family_as_lang_prefix`: Allow family objects to appear in place of language codes. * `lang_cache`: A table mapping language codes to language objects, where invalid language codes are indicated by the value `false`. If this field is specified, the cache will be consulted before calling `getByCode()` in [[Module:languages]], and the result cached. If not specified, no cache will be used. The return value is the object in `data.termobj` (if non-{nil}) or a newly-created object (otherwise), with the parsed-off term stored in the field named by the `data.term_dest` property (normally `.term`). If `data.allow_multiple_lang_prefixes` was not given and a language prefix was parsed off, the corresponding language object is stored into both `lang` and `termlang` (the storage into `termlang` is so that the presence of a language prefix can specifically be determined in the event that `lang` is already set in an existing termobj). If `data.allow_multiple_lang_prefixes` was given and one or more language prefixes were parsed off, the first such language object is stored into `lang`, and the list of all language objects stored into `termlangs. ]==] function export.generate_obj_maybe_parsing_lang_prefix(data) local term = data.term local term_dest = data.term_dest or "term" local termobj = data.termobj or {} if data.parse_lang_prefix and term:find(":", nil, true) then local actual_term, termlangs = export.parse_term_with_lang { term = term, parse_err = data.parse_err, paramname = data.paramname, allow_bad = data.allow_bad_lang_prefix, allow_multiple = data.allow_multiple_lang_prefixes, allow_family = data.allow_family_as_lang_prefix, lang_cache = data.lang_cache, } termobj[term_dest] = actual_term ~= "" and actual_term or nil if termlangs then -- If we couldn't parse a language code, don't overwrite an existing setting in `lang` -- that may have originated from a separate |langN= param. if data.allow_multiple_lang_prefixes then termobj.termlangs = termlangs termobj.lang = termlangs and termlangs[1] or nil else termobj.termlang = termlangs termobj.lang = termlangs end end else termobj[term_dest] = term ~= "" and term or nil end return termobj end --[==[ Parse a term that may have inline modifiers attached (e.g. {rifiuti<q:plural-only>} or {rinfusa<t:bulk cargo><lit:resupplying><qq:more common in the plural {{m|it|rinfuse}}>}). * `arg` is the term to parse. * `props` is an object holding further properties controlling how to parse the term (only `param_mods` and `generate_obj` are required): ** `paramname` is the name of the parameter where `arg` comes from, or nil if this isn't available (it is used only in error messages). ** `param_mods` is a table describing the allowed inline modifiers (see below). ** `generate_obj` is a function of one or two arguments that should parse the argument minus the inline modifiers and return a corresponding parsed object (into which the inline modifiers will be rewritten). If declared with one argument, that will be the raw value to parse; if declared with two arguments, the second argument will be the `parse_err` function (see below). ** `parse_err` is an optional function of one argument (an error message) and should display the error message, along with any desired contextual text (e.g. the argument name and value that triggered the error). If omitted, a default function will be generated which displays the error along with the original value of `arg` (passed through {escape_wikicode()} above to ensure that Wikicode (such as links) is displayed literally). ** `splitchar` is a Lua pattern. If specified, `arg` can consist of multiple delimiter-separated terms, each of which may be followed by inline modifiers, and the return value will be a list of parsed objects instead of a single object. Note that splitting on delimiters will not happen in certain protected sequences (by default comma+whitespace; see below). The algorithm to split on delimiters is sensitive to inline modifier syntax and will not be confused by delimiters inside of inline modifiers, which do not trigger splitting (whether or not contained within protected sequences). ** `outer_container`, if specified, is used when multiple delimiter-separated terms are possible, and is the object into which the list of per-term objects is stored (into the `terms` field) and into which any modifiers that are given the `overall` property (see below) will be stored. If given, this value will be returned as the value of {parse_inline_modifiers()}. If `outer_container` is not given, {parse_inline_modifiers()} will return the list of per-term objects directly, and no modifier may have an `overall` property. ** `preserve_splitchar`, if specified, causes the actual delimiter matched by `splitchar` to be returned in the parsed object describing the element that comes after the delimiter. The delimiter is stored in a key whose name is controlled by `delimiter_key`, which defaults to "delimiter". ** `delimiter_key` controls the key into which the actual delimiter is written when `preserve_splitchar` is used. See above. ** `escape_fun` and `unescape_fun` are as in split_escaping() and split_alternating_runs_escaping() above and control the protected sequences that won't be split. By default, `escape_comma_whitespace` and `unescape_comma_whitespace` are used, so that comma+whitespace sequences won't be split. Set to `false` to disable escaping/unescaping. ** `pre_normalize_modifiers`, if specified, is a function of one argument, which can be used to "normalize" modifiers prior to further parsing. This is used, for example, in [[Module:tl-pronunciation]] to convert modifiers of the form `<noun^expectation; hope>` to `<t:noun^expectation; hope>`, so they can be processed as standard modifiers. It is also used in [[Module:ar-verb]] to convert footnotes of the form `[rare]` to `<footnote:[rare]>`, to allow for mixing bracketed footnotes and inline modifiers when overriding verbal nouns and such. It could similarly be used to handle boolean modifiers like `<slb>` in {{tl|desc}} and convert them to a standard form `<slb:1>`. It runs just before parsing out the modifier prefix and value, and is passed an object containing fields `modtext` (the un-normalized modifier text, including surrounding angle brackets, or in some cases, text surrounded by other delimiters such as square brackets, if `parse_inline_modifiers_from_segments()` is being called and the caller did their own parsing of balanced segment runs) and `parse_err` (the passed-in or autogenerated function to signal an error during parsing; a function of one argument, a message, which throws an error displaying that message). It should return a single value, the normalized value of `modtext`, including surrounding angle brackets. `param_mods` is a table describing allowed modifiers. The keys of the table are modifier prefixes and the values are tables describing how to parse and store the associated modifier values. Here is a typical example, for an item that takes the standard modifiers associated with `full_link()` in [[Module:links]], as well as left and right qualifiers and labels: { local param_mods = { alt = {}, t = { -- [[Module:links]] expects the gloss in "gloss". item_dest = "gloss", }, gloss = {}, tr = {}, ts = {}, g = { -- [[Module:links]] expects the genders in "g". `sublist = true` automatically splits on comma (optionally -- with surrounding whitespace). item_dest = "genders", sublist = true, }, pos = {}, lit = {}, id = {}, sc = { -- Automatically parse as a script code and convert to a script object. type = "script", }, -- Qualifiers and labels q = { type = "qualifier", }, qq = { type = "qualifier", }, l = { type = "labels", }, ll = { type = "labels", }, } } In the table values: * `item_dest` specifies the destination key to store the object into (if not the same as the modifier key itself). * `type`, `set`, `sublist` and `convert` have the same meaning as in [[Module:parameters]] and are used for converting the object from the string form given by the user into the form needed for further processing. Note that `type` makes use of additional properties that may be specified. Specifically, if {type = "language"}, the properties `family` and `method` are also examined, and if {type = "family"} or {type = "script"}, the property `method` is examined. * `store` describes how to store the converted modifier value into the parsed object. If omitted, the converted value is simply written into the parsed object under the appropriate key; but an error is generated if the key already has a value. (This means that multiple occurrences of a given modifier are allowed if `store` is given, but not otherwise.) `store` can be one of the following: ** {"insert"}: the converted value is appended to the key's value using {insert()}; if the key has no value, it is first converted to an empty list; ** {"insertIfNot"}: is similar but appends the value using {insertIfNot()} in [[Module:table]]; ** {"insert-flattened"}, the converted value is assumed to be a list and the objects are appended one-by-one into the key's existing value using {insert()}; ** {"insertIfNot-flattened"} is similar but appends using {insertIfNot()} in [[Module:table]]; (WARNING: When using {"insert-flattened"} and {"insertIfNot-flattened"}, if there is no existing value for the key, the converted value is just stored directly. This means that future appends will side-effect that value, so make sure that the return value of the conversion function for this key generates a fresh list each time.) ** a function of one argument, an object with the following properties: *** `dest`: the object to write the value into; *** `key`: the field where the value should be written; *** `converted`: the (converted) value to write; *** `raw_val`: the raw, user-specified value (a string); *** `parse_err`: a function of one argument (an error string), which signals an error, and includes extra context in the message about the modifier in question, the angle-bracket spec that includes the modifier in it, the overall value, and (if `paramname` was given) the parameter holding the overall value. * `overall` only applies if `splitchar` is given. In this case, the modifier applies to the entire argument rather than to an individual term in the argument, and must occur after the last item separated by `splitchar`, instead of being allowed to occur after any of them. The modifier will be stored into the outer container object, which must exist (i.e. `outer_container` must have been given). The return value of {parse_inline_modifiers()} depends on whether `splitchar` and `outer_container` have been given. If neither is given, the return value is the object returned by `generate_obj`. If `splitchar` but not `outer_container` is given, the return value is a list of per-term objects, each of which is generated by `generate_obj`. If both `splitchar` and `outer_container` are given, the return value is the value of `outer_container` and the per-term objects are stored into the `terms` field of this object. ]==] function export.parse_inline_modifiers(arg, props) local segments local function rejoin_bracket_delimited_runs(segments) return export.rejoin_delimited_runs { runs = segments, delimiter_pattern = "^%[.*%]$", } end local rejoin_square_brackets_after_split = false -- The following is an optimization. If we see a square bracket (normally a double square bracket internal link -- [[...]]), we want to not treat delimiter characters inside (either <...> balanced delimiters or separators such -- as commas) as delimiters. But this requires a more sophisticated and slower algorithm, and most of the time it -- isn't needed because there are no square brackets. So we check for a square bracket and fall back to a simpler -- algorithm otherwise (which, since it involves only a single balanced delimiter, can use the built-in %b() Lua -- pattern syntax, which AFAIK is implemented in C). if arg:find("%[") then segments = export.parse_multi_delimiter_balanced_segment_run(arg, {{"[", "]"}, {"<", ">"}}) if not props.splitchar then segments = rejoin_bracket_delimited_runs(segments) else rejoin_square_brackets_after_split = true end else segments = export.parse_balanced_segment_run(arg, "<", ">") end local function verify_no_overall() for _, mod_props in pairs(props.param_mods) do if mod_props.overall then error("Internal caller error: Can't specify `overall` for a modifier in `param_mods` unless `outer_container` property is given") end end end if not props.splitchar then if props.outer_container then error("Internal caller error: Can't specify `outer_container` property unless `splitchar` is given") end verify_no_overall() return export.parse_inline_modifiers_from_segments { group = segments, group_index = nil, separated_groups = nil, arg = arg, props = props, } else local terms = {} if props.outer_container then props.outer_container.terms = terms else verify_no_overall() end local escape_fun = props.escape_fun if escape_fun == nil then escape_fun = export.escape_comma_whitespace end local unescape_fun = props.unescape_fun if unescape_fun == nil then unescape_fun = export.unescape_comma_whitespace end local separated_groups = export.split_alternating_runs_escaping(segments, props.splitchar, props.preserve_splitchar, escape_fun, unescape_fun) for j = 1, #separated_groups, (props.preserve_splitchar and 2 or 1) do if rejoin_square_brackets_after_split then separated_groups[j] = rejoin_bracket_delimited_runs(separated_groups[j]) end local parsed = export.parse_inline_modifiers_from_segments { group = separated_groups[j], group_index = j, separated_groups = separated_groups, arg = arg, props = props, } if props.preserve_splitchar and j > 1 then parsed[props.delimiter_key or "delimiter"] = separated_groups[j - 1][1] end insert(terms, parsed) end if props.outer_container then return props.outer_container else return terms end end end --[==[ Parse a single term that may have inline modifiers attached. This is a helper function of {parse_inline_modifiers()} but is exported separately in case the caller needs to make their own call to {parse_balanced_segment_run()} (as in [[Module:quote]], which splits on several matched delimiters simultaneously). It takes only a single argument, `data`, which is an object with the following fields: * `group`: A list of segments as output by {parse_balanced_segment_run()} (see the overall comment at the top of [[Module:parse utilities]]), or one of the lists returned by calling {split_alternating_runs()}. * `separated_groups`: The list of groups (each of which is of the form of `group`) describing all the terms in the argument parsed by {parse_inline_modifiers()}, or {nil} if this isn't applicable (i.e. multiple terms aren't allowed in the argument). Currently used only the check the number of groups in the list against `group_index`. * `group_index`: The index into `separated_groups` where `group` can be found, or {nil} if not applicable (see below). * `arg`: The original user-specified argument being parsed; used only for error messages and only when `props.parse_err` is not specified. * `props`: The `props` argument to {parse_inline_modifiers()}. The return value is the object created by `generate_obj`, with properties filled in describing the modifiers of the term in question. Note that `props.outer_container` and the `overall` setting of the `props.param_mods` structure are respected, but `props.splitchar` is ignored because the splitting happens in the caller. Specifically, if there are any modifiers with the `overall` setting, `props.separated_groups` and `props.group_index` must be given so that the function is able to determine if the modifier is indeed attached to the last term, and `props.outer_container` must be given because that is where such modifiers are stored. Otherwise, none of these settings need be given. ]==] function export.parse_inline_modifiers_from_segments(data) local props = data.props local group = data.group local function get_valid_prefixes() local valid_prefixes = {} for param_mod, mod_props in pairs(props.param_mods) do if not mod_props.deprecated then insert(valid_prefixes, param_mod) end end sort(valid_prefixes) return valid_prefixes end local function get_arg_gloss() if props.paramname then return ("%s=%s"):format(props.paramname, data.arg) else return data.arg end end local parse_err = props.parse_err or export.make_parse_err(get_arg_gloss()) local term_obj = props.generate_obj(group[1], parse_err) for k = 2, #group - 1, 2 do if group[k + 1] ~= "" then parse_err("Extraneous text '" .. group[k + 1] .. "' after modifier") end local group_k = group[k] if props.pre_normalize_modifiers then -- FIXME: For some use cases, we might have to pass more information. group_k = props.pre_normalize_modifiers { modtext = group_k, parse_err = parse_err } end local modtext = group_k:match("^<(.*)>$") if not modtext then parse_err("Internal error: Modifier '" .. group_k .. "' isn't surrounded by angle brackets") end local prefix, val = modtext:match("^([a-zA-Z0-9+_-]+):(.*)$") if not prefix then local valid_prefixes = get_valid_prefixes() for i, valid_prefix in ipairs(valid_prefixes) do valid_prefixes[i] = "'" .. valid_prefix .. ":'" end parse_err(("Modifier %s%s lacks a prefix, should begin with one of %s"):format( group_k, group_k ~= group[k] and (" (normalized from %s)"):format(group[k]) or "", list_to_text(valid_prefixes))) end local prefix_parse_err if props.parse_err then prefix_parse_err = function(msg, stack_frames_to_ignore) props.parse_err(("%s: modifier prefix '%s' in %s"):format(msg, prefix, group[k]), stack_frames_to_ignore) end else prefix_parse_err = export.make_parse_err(("modifier prefix '%s' in %s in %s"):format( prefix, group[k], get_arg_gloss())) end if props.param_mods[prefix] then local mod_props = props.param_mods[prefix] if mod_props.replaced_by == false then prefix_parse_err( ("Prefix has been removed and is no longer valid%s%s"):format( mod_props.reason and ", " .. mod_props.reason or "", mod_props.instead and "; instead, " .. mod_props.instead or "") ) elseif mod_props.replaced_by then prefix_parse_err( ("Prefix has been replaced by '%s'%s"):format( mod_props.replaced_by, mod_props.reason and ", " .. mod_props.reason or "") ) end local key = mod_props.item_dest or prefix local dest if mod_props.overall then if not data.separated_groups then prefix_parse_err("Internal error: `data.separated_groups` not given when `overall` is seen") end if not props.outer_container then -- This should have been caught earlier during validation in parse_inline_modifiers(). prefix_parse_err("Internal error: `props.outer_container` not given when `overall` is seen") end if data.group_index ~= #data.separated_groups then prefix_parse_err("Prefix should occur after the last comma-separated term") end dest = props.outer_container else dest = term_obj end local converted = val if mod_props.type or mod_props.set or mod_props.sublist or mod_props.convert then -- WARNING: Here as an optimization we embed some knowledge of convert_val() in [[Module:parameters]], -- specifically that if none of `type`, `set`, `sublist` and `convert` are set, the conversion is an -- identity operation and can be skipped. (convert_val() also makes use of the fields `method` and -- `family`, but only if `type` is set to certain values such as "language", "family" or "script", and -- makes use of the field `required`, but only if `set` is set.) If this becomes problematic, consider -- removing the optimization. converted = convert_val(converted, prefix_parse_err, mod_props) end local store = props.param_mods[prefix].store if not store then if dest[key] then prefix_parse_err("Prefix occurs twice") end dest[key] = converted elseif store == "insert" then if not dest[key] then dest[key] = {converted} else insert(dest[key], converted) end elseif store == "insertIfNot" then if not dest[key] then dest[key] = {converted} else insert_if_not(dest[key], converted) end elseif store == "insert-flattened" then if not dest[key] then dest[key] = converted else for _, obj in ipairs(converted) do insert(dest[key], obj) end end elseif store == "insertIfNot-flattened" then if not dest[key] then dest[key] = converted else for _, obj in ipairs(converted) do insert_if_not(dest[key], obj) end end elseif type(store) == "string" then prefix_parse_err(("Internal caller error: Unrecognized value '%s' for `store` property"):format(store)) elseif not is_callable(store) then prefix_parse_err(("Internal caller error: Unrecognized type for `store` property %s"):format(dump(store))) else store{ dest = dest, key = key, converted = converted, raw = val, parse_err = prefix_parse_err } end else local valid_prefixes = get_valid_prefixes() for i, valid_prefix in ipairs(valid_prefixes) do valid_prefixes[i] = "'" .. valid_prefix .. "'" end prefix_parse_err("Unrecognized prefix, should be one of " .. list_to_text(valid_prefixes)) end end return term_obj end return export 7m7efxuys6lveo94nvwye55dw2c55on 239030 239029 2026-11-15T04:09:10Z Lee 19 [[:en:Module:parse_utilities]] වෙතින් එක් සංශෝධනයක් 239029 Scribunto text/plain local export = {} local fun_is_callable_module = "Module:fun/isCallable" local languages_module = "Module:languages" local parameters_module = "Module:parameters" local string_char_module = "Module:string/char" local string_utilities_module = "Module:string utilities" local table_insert_if_not_module = "Module:table/insertIfNot" local assert = assert local concat = table.concat local dump = mw.dumpObject local error = error local insert = table.insert local ipairs = ipairs local list_to_text = mw.text.listToText local pairs = pairs local require = require local sort = table.sort local type = type local ugsub = mw.ustring.gsub local function convert_val(...) convert_val = require(parameters_module).convert_val return convert_val(...) end local function get_lang(...) get_lang = require(languages_module).getByCode return get_lang(...) end local function insert_if_not(...) insert_if_not = require(table_insert_if_not_module) return insert_if_not(...) end local function is_callable(...) is_callable = require(fun_is_callable_module) return is_callable(...) end local function split(...) split = require(string_utilities_module).split return split(...) end local function u(...) u = require(string_char_module) return u(...) end local function umatch(...) umatch = require(string_utilities_module).match return umatch(...) end --[==[ intro: In order to understand the following parsing code, you need to understand how inflected text specs work. They are intended to work with inflected text where individual words to be inflected may be followed by inflection specs in angle brackets. The format of the text inside of the angle brackets is up to the individual language and part-of-speech specific implementation. A real-world example is as follows: `<nowiki>[[медичний|меди́чна]]<+> [[сестра́]]<*,*#.pr></nowiki>`. This is the inflection of the Ukrainian multiword expression {{m|uk|меди́чна сестра́||nurse|lit=medical sister}}, consisting of two words: the adjective {{m|uk|меди́чна||medical|pos=feminine singular}} and the noun {{m|uk|сестра́||sister}}. The specs in angle brackets follow each word to be inflected; for example, `<+>` means that the preceding word should be declined as an adjective. The code below works in terms of balanced expressions, which are bounded by delimiters such as `< >` or `[ ]`. The intention is to allow separators such as spaces to be embedded inside of delimiters; such embedded separators will not be parsed as separators. For example, Ukrainian noun specs allow footnotes in brackets to be inserted inside of angle brackets; something like `меди́чна<+> сестра́<pr.[this is a footnote]>` is legal, as is `<nowiki>[[медичний|меди́чна]]<+> [[сестра́]]<pr.[this is an <i>italicized footnote</i>]></nowiki>`, and the parsing code should not be confused by the embedded brackets, spaces or angle brackets. The parsing is done by two functions, which work in close concert: {parse_balanced_segment_run()} and {split_alternating_runs()}. To illustrate, consider the following: {parse_balanced_segment_run("foo<M.proper noun> bar<F>", "<", ">")} =<br /> { {"foo", "<M.proper noun>", " bar", "<F>", ""}} then {split_alternating_runs({"foo", "<M.proper noun>", " bar", "<F>", ""}, " ")} =<br /> { {{"foo", "<M.proper noun>", ""}, {"bar", "<F>", ""}}} Here, we start out with a typical inflected text spec `foo<M.proper noun> bar<F>`, call {parse_balanced_segment_run()} on it, and call {split_alternating_runs()} on the result. The output of {parse_balanced_segment_run()} is a list where even-numbered segments are bounded by the bracket-like characters passed into the function, and odd-numbered segments consist of the surrounding text. {split_alternating_runs()} is called on this, and splits '''only''' the odd-numbered segments, grouping all segments between the specified character. Note that the inner lists output by {split_alternating_runs()} are themselves in the same format as the output of {parse_balanced_segment_run()}, with bracket-bounded text in the even-numbered segments. Hence, such lists can be passed again to {split_alternating_runs()}. ]==] --[==[ Parse a string containing matched instances of parens, brackets or the like. Return a list of strings, alternating between textual runs not containing the open/close characters and runs beginning and ending with the open/close characters. For example, {parse_balanced_segment_run("foo(x(1)), bar(2)", "(", ")") = {"foo", "(x(1))", ", bar", "(2)", ""}} ]==] function export.parse_balanced_segment_run(segment_run, open, close) return split(segment_run, "(%b" .. open .. close .. ")") end -- The following is an equivalent, older implementation that does not use %b (written before I was aware of %b). --[=[ function export.parse_balanced_segment_run(segment_run, open, close) local break_on_open_close = split(segment_run, "([%" .. open .. "%" .. close .. "])") local text_and_specs = {} local level = 0 local seg_group = {} for i, seg in ipairs(break_on_open_close) do if i % 2 == 0 then if seg == open then insert(seg_group, seg) level = level + 1 else assert(seg == close) insert(seg_group, seg) level = level - 1 if level < 0 then error("Unmatched " .. close .. " sign: '" .. segment_run .. "'") elseif level == 0 then insert(text_and_specs, concat(seg_group)) seg_group = {} end end elseif level > 0 then insert(seg_group, seg) else insert(text_and_specs, seg) end end if level > 0 then error("Unmatched " .. open .. " sign: '" .. segment_run .. "'") end return text_and_specs end ]=] --[==[ Like parse_balanced_segment_run() but accepts multiple sets of delimiters. For example, {parse_multi_delimiter_balanced_segment_run("foo[bar(baz[bat])], quux<glorp>", {{"[", "]"}, {"(", ")"}, {"<", ">"}}) = {"foo", "[bar(baz[bat])]", ", quux", "<glorp>", ""}}. Each element in the list of delimiter pairs is a string specifying an equivalence class of possible delimiter characters. You can use this, for example, to allow either "[" or "&amp;#91;" to be treated equivalently, with either one closed by either "]" or "&amp;#93;". To do this, first replace "&amp;#91;" and "&amp;#93;" with single Unicode characters such as U+FFF0 and U+FFF1, and then specify a two-character string containing "[" and U+FFF0 as the opening delimiter, and a two-character string containing "]" and U+FFF1 as the corresponding closing delimiter. If `no_error_on_unmatched` is given and an error is found during parsing, a string is returned containing the error message instead of throwing an error. ]==] function export.parse_multi_delimiter_balanced_segment_run(segment_run, delimiter_pairs, no_error_on_unmatched) local escaped_delimiter_pairs = {} local open_to_close_map = {} local open_close_items = {} local open_items = {} for _, open_close in ipairs(delimiter_pairs) do local open, close = open_close[1], open_close[2] open = open:gsub("([%[%]%%%%-])", "%%%1") close = close:gsub("([%[%]%%%%-])", "%%%1") insert(open_close_items, open) insert(open_close_items, close) insert(open_items, open) open = "[" .. open .. "]" close = "[" .. close .. "]" open_to_close_map[open] = close insert(escaped_delimiter_pairs, {open, close}) end local open_close_pattern = "([" .. concat(open_close_items) .. "])" local open_pattern = "([" .. concat(open_items) .. "])" local break_on_open_close = split(segment_run, open_close_pattern) local text_and_specs = {} local level = 0 local seg_group = {} local open_at_level_zero for i, seg in ipairs(break_on_open_close) do if i % 2 == 0 then insert(seg_group, seg) if level == 0 then if not umatch(seg, open_pattern) then local errmsg = "Unmatched close sign " .. seg .. ": '" .. segment_run .. "'" if no_error_on_unmatched then return errmsg else error(errmsg) end end assert(open_at_level_zero == nil) for _, open_close in ipairs(escaped_delimiter_pairs) do local open = open_close[1] if umatch(seg, open) then open_at_level_zero = open break end end if open_at_level_zero == nil then error(("Internal error: Segment %s didn't match any open regex"):format(seg)) end level = level + 1 elseif umatch(seg, open_at_level_zero) then level = level + 1 elseif umatch(seg, open_to_close_map[open_at_level_zero]) then level = level - 1 assert(level >= 0) if level == 0 then insert(text_and_specs, concat(seg_group)) seg_group = {} open_at_level_zero = nil end end elseif level > 0 then insert(seg_group, seg) else insert(text_and_specs, seg) end end if level > 0 then local errmsg = "Unmatched open sign " .. open_at_level_zero .. ": '" .. segment_run .. "'" if no_error_on_unmatched then return errmsg else error(errmsg) end end return text_and_specs end --[==[ Check whether a term contains top-level HTML. We want to distinguish inline modifiers from HTML. We assume an inline modifier is either a boolean modifier like `<bor>` or a prefix modifier like `<tr:Miryem>`. All other things inside of angle brackets, e.g. `<nowiki><span class="foo"></nowiki>`, `<nowiki></span></nowiki>`, `<nowiki><br/></nowiki>`, etc., should be flagged as HTML (typically caused by wrapping an argument in {{tl|m|...}}, {{tl|af|...}} or similar, but sometimes specified directly, e.g. `<nowiki><sup>6</sup></nowiki>`). By default, we assume the tag in an inline modifier contains either letters, numbers, hyphens or underscore (but not spaces), and must either stand alone or be followed by a colon, leading to a default HTML-checking pattern of {"<[%w_%-]*[^%w_%-:>]"}. But this can be modified; e.g. [[Module:tl-pronunciation]] allows modifiers of the form `<<var>pos</var>^<var>defn</var>>` or `<<var>pos</var>,<var>pos</var>,<var>pos</var>^<var>defn</var>>`, and would need to use its own HTML pattern. It's important we restrict the check for HTML to top-level to allow for generated HTML inside of e.g. qualifier tags, such as `<nowiki>foo<q:similar to {{m|fr|bar}}></nowiki>`. ]==] function export.term_contains_top_level_html(term, html_pattern) html_pattern = html_pattern or "<[%w_%-]*[^%w_%-:>]" -- If no HTML anywhere, the answer is no. if not term:find(html_pattern) then return false end -- Otherwise, we have to call parse_balanced_segment_run() and check alternate runs at top level. local runs = export.parse_balanced_segment_run(term, "<", ">") for i = 2, #runs, 2 do if runs[i]:find("^" .. html_pattern) then return true end end return false end --[==[ Check whether a term appears to have already been passed through `full_link()`. Passing it again will mangle it in various ways; at best it will have unnecessary lang/script wrapping, which might do nothing but might result in overly large fonts or other issues. We also check for uses of {{tl|ja-r/args}}, {{tl|ryu-r/args}} or {{tl|ko-l/args}}, which will be manged by `full_link()`. If this check succeeds, use the text raw instead of passing through `full_link()`. ]==] function export.term_already_linked(term) return term:find("<span") or term:find("{{ja%-r|") or term:find("{{ryu%-r|") or term:find("{{ko%-l|") end --[==[ Split a list of alternating textual runs of the format returned by `parse_balanced_segment_run` on `splitchar`. This only splits the odd-numbered textual runs (the portions between the balanced open/close characters). The return value is a list of lists, where each list contains an odd number of elements, where the even-numbered elements of the sublists are the original balanced textual run portions. For example, if we do {parse_balanced_segment_run("foo<M.proper noun> bar<F>", "<", ">") = {"foo", "<M.proper noun>", " bar", "<F>", ""}} then {split_alternating_runs({"foo", "<M.proper noun>", " bar", "<F>", ""}, " ") = {{"foo", "<M.proper noun>", ""}, {"bar", "<F>", ""}}} Note that we did not touch the text "<M.proper noun>" even though it contains a space in it, because it is an even-numbered element of the input list. This is intentional and allows for embedded separators inside of brackets/parens/etc. Note also that the inner lists in the return value are of the same form as the input list (i.e. they consist of alternating textual runs where the even-numbered segments are balanced runs), and can in turn be passed to split_alternating_runs(). If `preserve_splitchar` is passed in, the split character is included in the output, as follows: {split_alternating_runs({"foo", "<M.proper noun>", " bar", "<F>", ""}, " ", true) = {{"foo", "<M.proper noun>", ""}, {" "}, {"bar", "<F>", ""}}} Consider what happens if the original string has multiple spaces between brackets, and multiple sets of brackets without spaces between them. {parse_balanced_segment_run("foo[dated][low colloquial] baz-bat quux xyzzy[archaic]", "[", "]") = {"foo", "[dated]", "", "[low colloquial]", " baz-bat quux xyzzy", "[archaic]", ""}} then {split_alternating_runs({"foo", "[dated]", "", "[low colloquial]", " baz-bat quux xyzzy", "[archaic]", ""}, "[ %-]") = {{"foo", "[dated]", "", "[low colloquial]", ""}, {"baz"}, {"bat"}, {"quux"}, {"xyzzy", "[archaic]", ""}}} If `preserve_splitchar` is passed in, the split character is included in the output, as follows: {split_alternating_runs({"foo", "[dated]", "", "[low colloquial]", " baz bat quux xyzzy", "[archaic]", ""}, "[ %-]", true) = {{"foo", "[dated]", "", "[low colloquial]", ""}, {" "}, {"baz"}, {"-"}, {"bat"}, {" "}, {"quux"}, {" "}, {"xyzzy", "[archaic]", ""}}} As can be seen, the even-numbered elements in the outer list are one-element lists consisting of the separator text. ]==] function export.split_alternating_runs(segment_runs, splitchar, preserve_splitchar) local grouped_runs = {} local run = {} for i, seg in ipairs(segment_runs) do if i % 2 == 0 then insert(run, seg) else local parts = split(seg, preserve_splitchar and "(" .. splitchar .. ")" or splitchar) insert(run, parts[1]) for j=2,#parts do insert(grouped_runs, run) run = {parts[j]} end end end if #run > 0 then insert(grouped_runs, run) end return grouped_runs end --[==[ After calling `parse_multi_delimiter_balanced_segment_run()`, rejoin delimiter-bounded textual runs (i.e. textual runs surrounded by certain matched delimiters) with the runs on either side. This can be used when some of the matched delimiters are specified only in order to ensure that delimiters inside of other delimiters aren't parsed. As an example, [[Module:object usage]] calls {m_parse_utilities.parse_multi_delimiter_balanced_segment_run(object, {{"[", "]"}, {"(", ")"}, {"<", ">"}})} but the actual syntax of {{tl|+obj}} only uses parens and angle brackets as delimiters. Square brackets are included so that internal links are treated as units (i.e. parens and angle brackets occurring inside of them aren't parsed), but beyond that we don't treat square brackets as delimiters, so we want to rejoin square-bracket-delimited textual runs with adjacent runs before further parsing. There are two primary workflows when using this function: # If you only care about balanced delimiters occurring inside of other balanced delimiters (e.g. in the above example with [[Module:object usage]], you can call `rejoin_delimited_runs()` directly after `parse_multi_delimiter_balanced_segment_run()`. # However, if you care about single delimiters such as commas and slashes occurring inside of balanced delimiters (e.g. if you allow multiple comma-separated terms, e.g. of which can have associated inline modifiers, and you don't want commas inside of internal links to be treated as delimiters), you need to call `rejoin_delimited_runs()` ''after'' calling `split_alternating_runs()`. This is used, for example, in `parse_inline_modifiers()` for exactly this reason, when a `splitchar` is provided. `data` is an object of properties. Currently there are two: `runs` (the output of calling `parse_multi_delimiter_balanced_segment_run()`, i.e. a list of textual runs, where even-numbered elements begin and end with a matched delimiter and odd-numbered elements are surrounding text) and `delimiter_pattern` (a Lua pattern matching delimited textual runs that we want to rejoin with the surrounding text). `delimiter_pattern` should normally be anchored at the beginning; e.g. {"^%["} would be the correct pattern to use when rejoining square-bracket-delimited textual runs, as described above. ]==] function export.rejoin_delimited_runs(data) local joined_runs = {} local i = 1 while i <= #data.runs do local run = data.runs[i] if i % 2 == 0 and run:find(data.delimiter_pattern) then joined_runs[#joined_runs] = joined_runs[#joined_runs] .. run .. data.runs[i + 1] i = i + 2 else insert(joined_runs, run) i = i + 1 end end return joined_runs end function export.strip_spaces(text) return (ugsub(text, "^%s*(.-)%s*$", "%1")) end --[==[ Apply an arbitrary function `frob` to the "raw-text" segments in a split run set (the output of split_alternating_runs()). We leave alone stuff within balanced delimiters (footnotes, inflection specs and the like), as well as splitchars themselves if present. `preserve_splitchar` indicates whether splitchars are present in the split run set. `frob` is a function of one argument (the string to frob) and should return one argument (the frobbed string). We operate by only frobbing odd-numbered segments, and only in odd-numbered runs if preserve_splitchar is given. ]==] function export.frob_raw_text_alternating_runs(split_run_set, frob, preserve_splitchar) for i, run in ipairs(split_run_set) do if not preserve_splitchar or i % 2 == 1 then for j, segment in ipairs(run) do if j % 2 == 1 then run[j] = frob(segment) end end end end end --[==[ Like split_alternating_runs() but applies an arbitrary function `frob` to "raw-text" segments in the result (i.e. not stuff within balanced delimiters such as footnotes and inflection specs, and not splitchars if present). `frob` is a function of one argument (the string to frob) and should return one argument (the frobbed string). ]==] function export.split_alternating_runs_and_frob_raw_text(run, splitchar, frob, preserve_splitchar) local split_runs = export.split_alternating_runs(run, splitchar, preserve_splitchar) export.frob_raw_text_alternating_runs(split_runs, frob, preserve_splitchar) return split_runs end --[==[ FIXME: Older entry point. Call `split_alternating_runs_and_frob_raw_text()` in [[Module:parse utilities]] directly. Like `split_alternating_runs()` but strips spaces from both ends of the odd-numbered elements (only in odd-numbered runs if `preserve_splitchar` is given). Effectively we leave alone the footnotes and splitchars themselves, but otherwise strip extraneous spaces. Spaces in the middle of an element are also left alone. ]==] function export.split_alternating_runs_and_strip_spaces(segment_runs, splitchar, preserve_splitchar) return export.split_alternating_runs_and_frob_raw_text(segment_runs, splitchar, export.strip_spaces, preserve_splitchar) end --[==[ Split the non-modifier parts of an alternating run (after parse_balanced_segment_run() is called) on a Lua pattern, but not on certain sequences involving characters in that pattern (e.g. comma+whitespace). `splitchar` is the pattern to split on; `preserve_splitchar` indicates whether to preserve the delimiter and is the same as in split_alternating_runs(). `escape_fun` is called beforehand on each run of raw text and should return two values: the escaped run and whether unescaping is needed. If any call to `escape_fun` indicates that unescaping is needed, `unescape_fun` will be called on each run of raw text after splitting on `splitchar`. The return value of this function is as in split_alternating_runs(). ]==] function export.split_alternating_runs_escaping(run, splitchar, preserve_splitchar, escape_fun, unescape_fun) -- First replace comma with a temporary character in comma+whitespace sequences. local need_unescape = false for i in ipairs(run) do if i % 2 == 1 and escape_fun then local this_need_unescape run[i], this_need_unescape = escape_fun(run[i]) need_unescape = need_unescape or this_need_unescape end end if need_unescape then return export.split_alternating_runs_and_frob_raw_text(run, splitchar, unescape_fun, preserve_splitchar) else return export.split_alternating_runs(run, splitchar, preserve_splitchar) end end --[==[ Replace comma with a temporary char in comma + whitespace. ]==] function export.escape_comma_whitespace(run, tempcomma) tempcomma = tempcomma or u(0xFFF0) local escaped = false if run:find("\\,") then -- FIXME: we should probably convert literal \\ to \ to allow people to put a backslash before a comma that -- should be passed through; but maybe it's enough to use an HTML escape for the comma or backslash. run = (run:gsub("\\,", tempcomma)) -- discard backslash before comma, doing its duty to protect the comma escaped = true end if run:find(",%s") then run = (run:gsub(",(%s)", tempcomma .. "%1")) escaped = true end return run, escaped end --[==[ Undo the replacement of comma with a temporary char. ]==] function export.unescape_comma_whitespace(run, tempcomma) tempcomma = tempcomma or u(0xFFF0) return (run:gsub(tempcomma, ",")) end --[==[ Split the non-modifier parts of an alternating run (after parse_balanced_segment_run() is called) on comma, but not on comma+whitespace. See `split_on_comma()` above for more information and the meaning of `tempcomma`. ]==] function export.split_alternating_runs_on_comma(run, tempcomma) tempcomma = tempcomma or u(0xFFF0) -- Replace comma with a temporary char in comma + whitespace. local function escape_comma_whitespace(seg) return export.escape_comma_whitespace(seg, tempcomma) end -- Undo replacement of comma with a temporary char in comma + whitespace. local function unescape_comma_whitespace(seg) return export.unescape_comma_whitespace(seg, tempcomma) end return export.split_alternating_runs_escaping(run, ",", false, escape_comma_whitespace, unescape_comma_whitespace) end --[==[ Split text on a Lua pattern, but not on certain sequences involving characters in that pattern (e.g. comma+whitespace). `splitchar` is the pattern to split on; `preserve_splitchar` indicates whether to preserve the delimiter between split segments. `escape_fun` is called beforehand on the text and should return two values: the escaped run and whether unescaping is needed. If the call to `escape_fun` indicates that unescaping is needed, `unescape_fun` will be called on each run of text after splitting on `splitchar`. The return value of this a list of runs, interspersed with delimiters if `preserve_splitchar` is specified. ]==] function export.split_escaping(text, splitchar, preserve_splitchar, escape_fun, unescape_fun) if not umatch(text, splitchar) then return {text} end -- If there are square or angle brackets, we don't want to split on delimiters inside of them. To effect this, we -- use parse_multi_delimiter_balanced_segment_run() to parse balanced brackets, then do delimiter splitting on the -- non-bracketed portions of text using split_alternating_runs_escaping(), and concatenate back to a list of -- strings. When calling parse_multi_delimiter_balanced_segment_run(), we make sure not to throw an error on -- unbalanced brackets; in that case, we fall through to the code below that handles the case without brackets. if text:find("[%[<]") then local runs = export.parse_multi_delimiter_balanced_segment_run(text, {{"[", "]"}, {"<", ">"}}, "no error on unmatched") if type(runs) ~= "string" then local split_runs = export.split_alternating_runs_escaping(runs, splitchar, preserve_splitchar, escape_fun, unescape_fun) for i = 1, #split_runs do split_runs[i] = concat(split_runs[i]) end return split_runs end end -- First escape sequences we don't want to count for splitting. local need_unescape if escape_fun then text, need_unescape = escape_fun(text) end local parts = split(text, preserve_splitchar and "(" .. splitchar .. ")" or splitchar) if need_unescape then for i = 1, #parts, (preserve_splitchar and 2 or 1) do parts[i] = unescape_fun(parts[i]) end end return parts end --[==[ Split text on comma, but not on comma+whitespace. This is similar to `mw.text.split(text, ",")` but will not split on commas directly followed by whitespace, to handle embedded commas in terms (which are almost always followed by a space). `tempcomma` is the Unicode character to temporarily use when doing the splitting; normally U+FFF0, but you can specify a different character if you use U+FFF0 for some internal purpose. ]==] function export.split_on_comma(text, tempcomma) -- Don't do anything if no comma. Note that split_escaping() has a similar check at the beginning, so if there's a -- comma we effectively do this check twice, but this is worth it to optimize for the common no-comma case. if not text:find(",") then return {text} end tempcomma = tempcomma or u(0xFFF0) -- Replace comma with a temporary char in comma + whitespace. local function escape_comma_whitespace(run) return export.escape_comma_whitespace(run, tempcomma) end -- Undo replacement of comma with a temporary char in comma + whitespace. local function unescape_comma_whitespace(run) return export.unescape_comma_whitespace(run, tempcomma) end return export.split_escaping(text, ",", false, escape_comma_whitespace, unescape_comma_whitespace) end --[==[ Ensure that Wikicode (template calls, bracketed links, HTML, bold/italics, etc.) displays literally in error messages by inserting a Unicode word-joiner symbol after all characters that may trigger Wikicode interpretation. Replacing with equivalent HTML escapes doesn't work because they are displayed literally. I could not get this to work using <nowiki>...</nowiki> (those tags display literally), using using {{#tag:nowiki|...}} (same thing) or using mw.getCurrentFrame():extensionTag("nowiki", ...) (everything gets converted to a strip marker `UNIQ--nowiki-00000000-QINU` or similar). FIXME: This is a massive hack; there must be a better way. ]==] function export.escape_wikicode(term) term = term:gsub("([%[<'{])", "%1" .. u(0x2060)) return term end function export.make_parse_err(arg_gloss) return function(msg, stack_frames_to_ignore) error(export.escape_wikicode(("%s: %s"):format(msg, arg_gloss)), stack_frames_to_ignore) end end -- Parse a term that may include a link '[[LINK]]' or a two-part link '[[LINK|DISPLAY]]'. FIXME: Doesn't currently -- handle embedded links like '[[FOO]] [[BAR]]' or [[FOO|BAR]] [[BAZ]]' or '[[FOO]]s'; if they are detected, it returns -- the term unchanged and `nil` for the display form. local function parse_bracketed_term(term, parse_err) local inside = term:match("^%[%[(.*)%]%]$") if inside then if inside:find("%[%[") or inside:find("%]%]") then -- embedded links, e.g. '[[FOO]] [[BAR]]'; FIXME: we should process them properly return term, nil end local parts = split(inside, "|") if #parts > 2 then parse_err("Saw more than two parts inside a bracketed link") end return parts[1], parts[2] end return term, nil end --[==[ Parse a term that may have a language code (or possibly multiple plus-separated language codes, if `data.allow_multiple` is given) preceding it (e.g. {la:minūtia} or {grc:[[σκῶρ|σκατός]]} or {nan-hbl+hak:[[毋]][[知]]}). Return five arguments: # the original prefixed term; in the case of a Wikipedia or Wikisource prefix followed by a two-part link, it is a two-part link with the Wikipedia/Wikisource prefix moved inside the link; in the case of a Wikipedia or Wikisource prefix followed by a redundant one-part link, the brackets are removed; # the language object corresponding to the language code (possibly a family object if `data.allow_family` is given), or a list of such objects if `data.allow_multiple` is given; # the link if the unprefixed term is of the form <code>[[<var>link</var>|<var>display</var>]]</code> or of the form <code>[[<var>link</var>]]</code>, otherwise the full unprefixed term; # the display part if the term is of the form <code>[[<var>link</var>|<var>display</var>]]</code> or has a Wikipedia or Wikisource prefix (in which case the part minus the prefix and any following language code will be returned, with redundant brackets stripped), else {nil}; # {true} if the term has a Wikipedia/Wikisource prefix, else {false}. Etymology-only languages are always allowed. This function also correctly handles Wikipedia prefixes (e.g. {w:Abatemarco} or {w:it:Colle Val d'Elsa} or {lw:ru:Филарет}) and Wikisource prefixes (e.g. {s:Twelve O'Clock} or {s:[[Walden/Chapter XVIII|Walden]]} or {s:fr:Perceval ou le conte du Graal} or {s:ro:[[Domnul Vucea|Mr. Vucea]]} or {ls:ko:이상적 부인} or {ls:ko:[[조선 독립의 서#一. 槪論|조선 독립의 서]]}) and converts them into two-part links, with the display form not including the Wikipedia or Wikisource prefix unless it was explicitly specified using a two-part link as in {lw:ru:[[Филарет (Дроздов)|Митрополи́т Филаре́т]]} or {ls:ko:[[조선 독립의 서#一. 槪論|조선 독립의 서]]}. The difference between {w:} ("Wikipedia") and {lw:} ("Wikipedia link") is that the latter requires a language code and returns the corresponding language object; same for the difference between {s:} ("Wikisource") and {ls:} ("Wikisource link"). NOTE: Embedded links are not correctly handled currently. If an embedded link is detected, the whole term is returned as the link part (third argument), and the display part is nil. If you construct your own link from the link and display parts, you must check for this. The calling convention is to pass in a single argument `data` containing the following fields: * `term`: The term to parse. * `parse_err`: An optional function of one or two arguments to display an error. (The second argument to the function is the number of stack frames to ignore when calling error(); if you declare your error function with only one argument, things will still work fine.) * `paramname`: If `parse_err` is omitted, this should be a string naming a parameter to display in the error message, along with the term in question, and will be used to generate a `parse_err` function using `make_parse_err()`. (If `paramname` is omitted, just the term itself appears in the error message.) * `allow_multiple`: Allow multiple plus-separated language codes, e.g. {nan-hbl+hak:[[毋]][[知]]}. See above. * `allow_family`: Allow family objects to appear in place of language codes. * `allow_bad`: Don't throw an error on invalid language code prefixes; instead, include the prefix and colon as part of the term. Note that if a prefix doesn't look like a language code (e.g. if it's a number), the code won't even try to parse it as a language code, regardless of the `allow_bad` setting, but will always include it in the term. * `lang_cache`: A table mapping language codes to language objects, where invalid language codes are indicated by the value `false`. If this field is specified, the cache will be consulted before calling `getByCode()` in [[Module:languages]], and the result cached. If not specified, no cache will be used. ]==] function export.parse_term_with_lang(data) local term = data.term local parse_err = data.parse_err or data.paramname and export.make_parse_err(("%s=%s"):format(data.paramname, term)) or export.make_parse_err(term) -- Parse off an initial language code (e.g. 'la:minūtia' or 'grc:[[σκῶρ|σκατός]]'). First check for Wikipedia -- prefixes ('w:Abatemarco' or 'w:it:Colle Val d'Elsa' or 'lw:zh:邹衡') and Wikisource prefixes -- ('s:ro:[[Domnul Vucea|Mr. Vucea]]' or 'ls:ko:이상적 부인'). Wikipedia/Wikisource language codes follow a similar -- format to Wiktionary language codes (see below). Here and below we don't parse if there's a space after the -- colon (happens e.g. if the user uses {{desc|...}} inside of {{col}}, grrr ...). local termlang, foreign_wiki, actual_term = term:match("^(l?[ws]):([a-z][a-z][a-z-]*):([^ ].*)$") if not termlang then termlang, actual_term = term:match("^([ws]):([^ ].*)$") end if termlang then local wiki_links = termlang:find("^l") local base_wiki_prefix = termlang:find("w$") and "w:" or "s:" local wiki_prefix = base_wiki_prefix .. (foreign_wiki and foreign_wiki .. ":" or "") local link, display = parse_bracketed_term(actual_term, parse_err) if link:find("%[%[") or display and display:find("%[%[") then -- FIXME, this should be handlable with the right parsing code parse_err("Cannot have embedded brackets following a Wikipedia (w:... or lw:...) link; expand the term to a fully bracketed term w:[[LINK|DISPLAY]] or similar") end local lang = wiki_links and get_lang(foreign_wiki, parse_err, "allow etym") or nil local prefixed_link = wiki_prefix .. link if display then return ("[[%s|%s]]"):format(prefixed_link, display), lang, prefixed_link, display, true else -- Return the link minus any language codes as the fourth term (display form). Previously we returned `actual_term` -- but this causes problems with redundant Wikipedia links of the form `w:[[Dragon Ball Z]]`. Don't generate a -- two-part link so you can specify a display form in 3=. Note that the fourth and fifth params are currently only -- used in [[Module:quote]]. return prefixed_link, lang, prefixed_link, link, true end end -- Wiktionary language codes are in one of the following formats, where 'x' is a lowercase letter and 'X' an -- uppercase letter: -- xx -- xxx -- xxx-xxx -- xxx-xxx-xxx (esp. for protolanguages) -- xx-xxx (for etymology-only languages) -- xx-xxx-xxx (maybe? for etymology-only languages) -- xx-XX (for etymology-only languages, where XX is a country code, e.g. en-US) -- xxx-XX (for etymology-only languages, where XX is a country code) -- xx-xxx-XX (for etymology-only languages, where XX is a country code) -- xxx-xxx-XX (for etymology-only langauges, where XX is a country code, e.g. nan-hbl-PH) -- Things like xxx-x+ (e.g. cmn-pinyin, cmn-tongyong) -- VL., LL., etc. -- -- We check the for nonstandard Latin etymology language codes separately, and otherwise make only the following -- assumptions: -- (1) There are one to three hyphen-separated components. -- (2) The last component can consist of two uppercase ASCII letters; otherwise, all components contain only -- lowercase ASCII letters. -- (3) Each component must have at least two letters. -- (4) The first component must have two or three letters. local function is_possible_lang_code(code) -- Special hack for Latin variants, which can have nonstandard etym codes, e.g. VL., LL. if code:find("^[A-Z]L%.$") then return true end return code:find("^([a-z][a-z][a-z]?)$") or code:find("^[a-z][a-z][a-z]?%-[A-Z][A-Z]$") or code:find("^[a-z][a-z][a-z]?%-[a-z][a-z]+$") or code:find("^[a-z][a-z][a-z]?%-[a-z][a-z]+%-[A-Z][A-Z]$") or code:find("^[a-z][a-z][a-z]?%-[a-z][a-z]+%-[a-z][a-z]+$") end local function get_by_code(code, allow_bad) local lang if data.lang_cache then lang = data.lang_cache[code] end if lang == nil then lang = get_lang(code, not allow_bad and parse_err or nil, "allow etym", data.allow_family) if data.lang_cache then data.lang_cache[code] = lang or false end end return lang or nil end if data.allow_multiple then local termlang_spec termlang_spec, actual_term = term:match("^([a-zA-Z.,+-]+):([^ ].*)$") if termlang_spec then termlang = split(termlang_spec, "[,+]") local all_possible_code = true for _, code in ipairs(termlang) do if not is_possible_lang_code(code) then all_possible_code = false break end end if all_possible_code then local saw_nil = false for i, code in ipairs(termlang) do termlang[i] = get_by_code(code, data.allow_bad) if not termlang[i] then saw_nil = true end end if saw_nil then termlang = nil else term = actual_term end else termlang = nil end end else termlang, actual_term = term:match("^([a-zA-Z.-]+):([^ ].*)$") if termlang then if is_possible_lang_code(termlang) then termlang = get_by_code(termlang, data.allow_bad) if termlang then term = actual_term end else termlang = nil end end end local link, display = parse_bracketed_term(term, parse_err) return term, termlang, link, display, false end --[==[ Maybe parse any language prefix off of a given term and store the term and language(s) into a new or existing object. This function is useful for implementing a `generate_obj` handler of `parse_inline_modifiers` that can support terms with prefixed language(s). This wraps `parse_term_with_lang` and has the same handling of language prefixes as that function. The calling convention is to pass in a single argument `data` containing the following fields (NOTE: you must set `parse_lang_prefix` to get language-prefix-parsing behavior): * `term`: The term to parse. This is the only required parameter. * `parse_lang_prefix`: This must be specified in order for language prefixes to be recognized and parsed off. * `termobj`: The existing object to store results into. If unspecified, a new object is created. * `term_dest`: The field in `termobj` into which the term itself (minus any language prefix) is stored. If unspecified, defaults to {"term"}. * `parse_err`: An optional function of one or two arguments to display an error. (The second argument to the function is the number of stack frames to ignore when calling error(); if you declare your error function with only one argument, things will still work fine.) * `paramname`: If `parse_err` is omitted, this should be a string naming a parameter to display in the error message, along with the term in question, and will be used to generate a `parse_err` function using `make_parse_err()`. (If `paramname` is omitted, just the term itself appears in the error message.) * `allow_multiple_lang_prefixes`: Allow multiple plus-separated language codes, e.g. {nan-hbl+hak:[[毋]][[知]]}. See `parse_term_with_lang` for more information. * `allow_bad_lang_prefix`: Don't throw an error on invalid language code prefixes; instead, include the prefix and colon as part of the term. Note that if a prefix doesn't look like a language code (e.g. if it's a number), the code won't even try to parse it as a language code, regardless of this setting, but will always include it in the term. * `allow_family_as_lang_prefix`: Allow family objects to appear in place of language codes. * `lang_cache`: A table mapping language codes to language objects, where invalid language codes are indicated by the value `false`. If this field is specified, the cache will be consulted before calling `getByCode()` in [[Module:languages]], and the result cached. If not specified, no cache will be used. The return value is the object in `data.termobj` (if non-{nil}) or a newly-created object (otherwise), with the parsed-off term stored in the field named by the `data.term_dest` property (normally `.term`). If `data.allow_multiple_lang_prefixes` was not given and a language prefix was parsed off, the corresponding language object is stored into both `lang` and `termlang` (the storage into `termlang` is so that the presence of a language prefix can specifically be determined in the event that `lang` is already set in an existing termobj). If `data.allow_multiple_lang_prefixes` was given and one or more language prefixes were parsed off, the first such language object is stored into `lang`, and the list of all language objects stored into `termlangs. ]==] function export.generate_obj_maybe_parsing_lang_prefix(data) local term = data.term local term_dest = data.term_dest or "term" local termobj = data.termobj or {} if data.parse_lang_prefix and term:find(":", nil, true) then local actual_term, termlangs = export.parse_term_with_lang { term = term, parse_err = data.parse_err, paramname = data.paramname, allow_bad = data.allow_bad_lang_prefix, allow_multiple = data.allow_multiple_lang_prefixes, allow_family = data.allow_family_as_lang_prefix, lang_cache = data.lang_cache, } termobj[term_dest] = actual_term ~= "" and actual_term or nil if termlangs then -- If we couldn't parse a language code, don't overwrite an existing setting in `lang` -- that may have originated from a separate |langN= param. if data.allow_multiple_lang_prefixes then termobj.termlangs = termlangs termobj.lang = termlangs and termlangs[1] or nil else termobj.termlang = termlangs termobj.lang = termlangs end end else termobj[term_dest] = term ~= "" and term or nil end return termobj end --[==[ Parse a term that may have inline modifiers attached (e.g. {rifiuti<q:plural-only>} or {rinfusa<t:bulk cargo><lit:resupplying><qq:more common in the plural {{m|it|rinfuse}}>}). * `arg` is the term to parse. * `props` is an object holding further properties controlling how to parse the term (only `param_mods` and `generate_obj` are required): ** `paramname` is the name of the parameter where `arg` comes from, or nil if this isn't available (it is used only in error messages). ** `param_mods` is a table describing the allowed inline modifiers (see below). ** `generate_obj` is a function of one or two arguments that should parse the argument minus the inline modifiers and return a corresponding parsed object (into which the inline modifiers will be rewritten). If declared with one argument, that will be the raw value to parse; if declared with two arguments, the second argument will be the `parse_err` function (see below). ** `parse_err` is an optional function of one argument (an error message) and should display the error message, along with any desired contextual text (e.g. the argument name and value that triggered the error). If omitted, a default function will be generated which displays the error along with the original value of `arg` (passed through {escape_wikicode()} above to ensure that Wikicode (such as links) is displayed literally). ** `splitchar` is a Lua pattern. If specified, `arg` can consist of multiple delimiter-separated terms, each of which may be followed by inline modifiers, and the return value will be a list of parsed objects instead of a single object. Note that splitting on delimiters will not happen in certain protected sequences (by default comma+whitespace; see below). The algorithm to split on delimiters is sensitive to inline modifier syntax and will not be confused by delimiters inside of inline modifiers, which do not trigger splitting (whether or not contained within protected sequences). ** `outer_container`, if specified, is used when multiple delimiter-separated terms are possible, and is the object into which the list of per-term objects is stored (into the `terms` field) and into which any modifiers that are given the `overall` property (see below) will be stored. If given, this value will be returned as the value of {parse_inline_modifiers()}. If `outer_container` is not given, {parse_inline_modifiers()} will return the list of per-term objects directly, and no modifier may have an `overall` property. ** `preserve_splitchar`, if specified, causes the actual delimiter matched by `splitchar` to be returned in the parsed object describing the element that comes after the delimiter. The delimiter is stored in a key whose name is controlled by `delimiter_key`, which defaults to "delimiter". ** `delimiter_key` controls the key into which the actual delimiter is written when `preserve_splitchar` is used. See above. ** `escape_fun` and `unescape_fun` are as in split_escaping() and split_alternating_runs_escaping() above and control the protected sequences that won't be split. By default, `escape_comma_whitespace` and `unescape_comma_whitespace` are used, so that comma+whitespace sequences won't be split. Set to `false` to disable escaping/unescaping. ** `pre_normalize_modifiers`, if specified, is a function of one argument, which can be used to "normalize" modifiers prior to further parsing. This is used, for example, in [[Module:tl-pronunciation]] to convert modifiers of the form `<noun^expectation; hope>` to `<t:noun^expectation; hope>`, so they can be processed as standard modifiers. It is also used in [[Module:ar-verb]] to convert footnotes of the form `[rare]` to `<footnote:[rare]>`, to allow for mixing bracketed footnotes and inline modifiers when overriding verbal nouns and such. It could similarly be used to handle boolean modifiers like `<slb>` in {{tl|desc}} and convert them to a standard form `<slb:1>`. It runs just before parsing out the modifier prefix and value, and is passed an object containing fields `modtext` (the un-normalized modifier text, including surrounding angle brackets, or in some cases, text surrounded by other delimiters such as square brackets, if `parse_inline_modifiers_from_segments()` is being called and the caller did their own parsing of balanced segment runs) and `parse_err` (the passed-in or autogenerated function to signal an error during parsing; a function of one argument, a message, which throws an error displaying that message). It should return a single value, the normalized value of `modtext`, including surrounding angle brackets. `param_mods` is a table describing allowed modifiers. The keys of the table are modifier prefixes and the values are tables describing how to parse and store the associated modifier values. Here is a typical example, for an item that takes the standard modifiers associated with `full_link()` in [[Module:links]], as well as left and right qualifiers and labels: { local param_mods = { alt = {}, t = { -- [[Module:links]] expects the gloss in "gloss". item_dest = "gloss", }, gloss = {}, tr = {}, ts = {}, g = { -- [[Module:links]] expects the genders in "g". `sublist = true` automatically splits on comma (optionally -- with surrounding whitespace). item_dest = "genders", sublist = true, }, pos = {}, lit = {}, id = {}, sc = { -- Automatically parse as a script code and convert to a script object. type = "script", }, -- Qualifiers and labels q = { type = "qualifier", }, qq = { type = "qualifier", }, l = { type = "labels", }, ll = { type = "labels", }, } } In the table values: * `item_dest` specifies the destination key to store the object into (if not the same as the modifier key itself). * `type`, `set`, `sublist` and `convert` have the same meaning as in [[Module:parameters]] and are used for converting the object from the string form given by the user into the form needed for further processing. Note that `type` makes use of additional properties that may be specified. Specifically, if {type = "language"}, the properties `family` and `method` are also examined, and if {type = "family"} or {type = "script"}, the property `method` is examined. * `store` describes how to store the converted modifier value into the parsed object. If omitted, the converted value is simply written into the parsed object under the appropriate key; but an error is generated if the key already has a value. (This means that multiple occurrences of a given modifier are allowed if `store` is given, but not otherwise.) `store` can be one of the following: ** {"insert"}: the converted value is appended to the key's value using {insert()}; if the key has no value, it is first converted to an empty list; ** {"insertIfNot"}: is similar but appends the value using {insertIfNot()} in [[Module:table]]; ** {"insert-flattened"}, the converted value is assumed to be a list and the objects are appended one-by-one into the key's existing value using {insert()}; ** {"insertIfNot-flattened"} is similar but appends using {insertIfNot()} in [[Module:table]]; (WARNING: When using {"insert-flattened"} and {"insertIfNot-flattened"}, if there is no existing value for the key, the converted value is just stored directly. This means that future appends will side-effect that value, so make sure that the return value of the conversion function for this key generates a fresh list each time.) ** a function of one argument, an object with the following properties: *** `dest`: the object to write the value into; *** `key`: the field where the value should be written; *** `converted`: the (converted) value to write; *** `raw_val`: the raw, user-specified value (a string); *** `parse_err`: a function of one argument (an error string), which signals an error, and includes extra context in the message about the modifier in question, the angle-bracket spec that includes the modifier in it, the overall value, and (if `paramname` was given) the parameter holding the overall value. * `overall` only applies if `splitchar` is given. In this case, the modifier applies to the entire argument rather than to an individual term in the argument, and must occur after the last item separated by `splitchar`, instead of being allowed to occur after any of them. The modifier will be stored into the outer container object, which must exist (i.e. `outer_container` must have been given). The return value of {parse_inline_modifiers()} depends on whether `splitchar` and `outer_container` have been given. If neither is given, the return value is the object returned by `generate_obj`. If `splitchar` but not `outer_container` is given, the return value is a list of per-term objects, each of which is generated by `generate_obj`. If both `splitchar` and `outer_container` are given, the return value is the value of `outer_container` and the per-term objects are stored into the `terms` field of this object. ]==] function export.parse_inline_modifiers(arg, props) local segments local function rejoin_bracket_delimited_runs(segments) return export.rejoin_delimited_runs { runs = segments, delimiter_pattern = "^%[.*%]$", } end local rejoin_square_brackets_after_split = false -- The following is an optimization. If we see a square bracket (normally a double square bracket internal link -- [[...]]), we want to not treat delimiter characters inside (either <...> balanced delimiters or separators such -- as commas) as delimiters. But this requires a more sophisticated and slower algorithm, and most of the time it -- isn't needed because there are no square brackets. So we check for a square bracket and fall back to a simpler -- algorithm otherwise (which, since it involves only a single balanced delimiter, can use the built-in %b() Lua -- pattern syntax, which AFAIK is implemented in C). if arg:find("%[") then segments = export.parse_multi_delimiter_balanced_segment_run(arg, {{"[", "]"}, {"<", ">"}}) if not props.splitchar then segments = rejoin_bracket_delimited_runs(segments) else rejoin_square_brackets_after_split = true end else segments = export.parse_balanced_segment_run(arg, "<", ">") end local function verify_no_overall() for _, mod_props in pairs(props.param_mods) do if mod_props.overall then error("Internal caller error: Can't specify `overall` for a modifier in `param_mods` unless `outer_container` property is given") end end end if not props.splitchar then if props.outer_container then error("Internal caller error: Can't specify `outer_container` property unless `splitchar` is given") end verify_no_overall() return export.parse_inline_modifiers_from_segments { group = segments, group_index = nil, separated_groups = nil, arg = arg, props = props, } else local terms = {} if props.outer_container then props.outer_container.terms = terms else verify_no_overall() end local escape_fun = props.escape_fun if escape_fun == nil then escape_fun = export.escape_comma_whitespace end local unescape_fun = props.unescape_fun if unescape_fun == nil then unescape_fun = export.unescape_comma_whitespace end local separated_groups = export.split_alternating_runs_escaping(segments, props.splitchar, props.preserve_splitchar, escape_fun, unescape_fun) for j = 1, #separated_groups, (props.preserve_splitchar and 2 or 1) do if rejoin_square_brackets_after_split then separated_groups[j] = rejoin_bracket_delimited_runs(separated_groups[j]) end local parsed = export.parse_inline_modifiers_from_segments { group = separated_groups[j], group_index = j, separated_groups = separated_groups, arg = arg, props = props, } if props.preserve_splitchar and j > 1 then parsed[props.delimiter_key or "delimiter"] = separated_groups[j - 1][1] end insert(terms, parsed) end if props.outer_container then return props.outer_container else return terms end end end --[==[ Parse a single term that may have inline modifiers attached. This is a helper function of {parse_inline_modifiers()} but is exported separately in case the caller needs to make their own call to {parse_balanced_segment_run()} (as in [[Module:quote]], which splits on several matched delimiters simultaneously). It takes only a single argument, `data`, which is an object with the following fields: * `group`: A list of segments as output by {parse_balanced_segment_run()} (see the overall comment at the top of [[Module:parse utilities]]), or one of the lists returned by calling {split_alternating_runs()}. * `separated_groups`: The list of groups (each of which is of the form of `group`) describing all the terms in the argument parsed by {parse_inline_modifiers()}, or {nil} if this isn't applicable (i.e. multiple terms aren't allowed in the argument). Currently used only the check the number of groups in the list against `group_index`. * `group_index`: The index into `separated_groups` where `group` can be found, or {nil} if not applicable (see below). * `arg`: The original user-specified argument being parsed; used only for error messages and only when `props.parse_err` is not specified. * `props`: The `props` argument to {parse_inline_modifiers()}. The return value is the object created by `generate_obj`, with properties filled in describing the modifiers of the term in question. Note that `props.outer_container` and the `overall` setting of the `props.param_mods` structure are respected, but `props.splitchar` is ignored because the splitting happens in the caller. Specifically, if there are any modifiers with the `overall` setting, `props.separated_groups` and `props.group_index` must be given so that the function is able to determine if the modifier is indeed attached to the last term, and `props.outer_container` must be given because that is where such modifiers are stored. Otherwise, none of these settings need be given. ]==] function export.parse_inline_modifiers_from_segments(data) local props = data.props local group = data.group local function get_valid_prefixes() local valid_prefixes = {} for param_mod, mod_props in pairs(props.param_mods) do if not mod_props.deprecated then insert(valid_prefixes, param_mod) end end sort(valid_prefixes) return valid_prefixes end local function get_arg_gloss() if props.paramname then return ("%s=%s"):format(props.paramname, data.arg) else return data.arg end end local parse_err = props.parse_err or export.make_parse_err(get_arg_gloss()) local term_obj = props.generate_obj(group[1], parse_err) for k = 2, #group - 1, 2 do if group[k + 1] ~= "" then parse_err("Extraneous text '" .. group[k + 1] .. "' after modifier") end local group_k = group[k] if props.pre_normalize_modifiers then -- FIXME: For some use cases, we might have to pass more information. group_k = props.pre_normalize_modifiers { modtext = group_k, parse_err = parse_err } end local modtext = group_k:match("^<(.*)>$") if not modtext then parse_err("Internal error: Modifier '" .. group_k .. "' isn't surrounded by angle brackets") end local prefix, val = modtext:match("^([a-zA-Z0-9+_-]+):(.*)$") if not prefix then local valid_prefixes = get_valid_prefixes() for i, valid_prefix in ipairs(valid_prefixes) do valid_prefixes[i] = "'" .. valid_prefix .. ":'" end parse_err(("Modifier %s%s lacks a prefix, should begin with one of %s"):format( group_k, group_k ~= group[k] and (" (normalized from %s)"):format(group[k]) or "", list_to_text(valid_prefixes))) end local prefix_parse_err if props.parse_err then prefix_parse_err = function(msg, stack_frames_to_ignore) props.parse_err(("%s: modifier prefix '%s' in %s"):format(msg, prefix, group[k]), stack_frames_to_ignore) end else prefix_parse_err = export.make_parse_err(("modifier prefix '%s' in %s in %s"):format( prefix, group[k], get_arg_gloss())) end if props.param_mods[prefix] then local mod_props = props.param_mods[prefix] if mod_props.replaced_by == false then prefix_parse_err( ("Prefix has been removed and is no longer valid%s%s"):format( mod_props.reason and ", " .. mod_props.reason or "", mod_props.instead and "; instead, " .. mod_props.instead or "") ) elseif mod_props.replaced_by then prefix_parse_err( ("Prefix has been replaced by '%s'%s"):format( mod_props.replaced_by, mod_props.reason and ", " .. mod_props.reason or "") ) end local key = mod_props.item_dest or prefix local dest if mod_props.overall then if not data.separated_groups then prefix_parse_err("Internal error: `data.separated_groups` not given when `overall` is seen") end if not props.outer_container then -- This should have been caught earlier during validation in parse_inline_modifiers(). prefix_parse_err("Internal error: `props.outer_container` not given when `overall` is seen") end if data.group_index ~= #data.separated_groups then prefix_parse_err("Prefix should occur after the last comma-separated term") end dest = props.outer_container else dest = term_obj end local converted = val if mod_props.type or mod_props.set or mod_props.sublist or mod_props.convert then -- WARNING: Here as an optimization we embed some knowledge of convert_val() in [[Module:parameters]], -- specifically that if none of `type`, `set`, `sublist` and `convert` are set, the conversion is an -- identity operation and can be skipped. (convert_val() also makes use of the fields `method` and -- `family`, but only if `type` is set to certain values such as "language", "family" or "script", and -- makes use of the field `required`, but only if `set` is set.) If this becomes problematic, consider -- removing the optimization. converted = convert_val(converted, prefix_parse_err, mod_props) end local store = props.param_mods[prefix].store if not store then if dest[key] then prefix_parse_err("Prefix occurs twice") end dest[key] = converted elseif store == "insert" then if not dest[key] then dest[key] = {converted} else insert(dest[key], converted) end elseif store == "insertIfNot" then if not dest[key] then dest[key] = {converted} else insert_if_not(dest[key], converted) end elseif store == "insert-flattened" then if not dest[key] then dest[key] = converted else for _, obj in ipairs(converted) do insert(dest[key], obj) end end elseif store == "insertIfNot-flattened" then if not dest[key] then dest[key] = converted else for _, obj in ipairs(converted) do insert_if_not(dest[key], obj) end end elseif type(store) == "string" then prefix_parse_err(("Internal caller error: Unrecognized value '%s' for `store` property"):format(store)) elseif not is_callable(store) then prefix_parse_err(("Internal caller error: Unrecognized type for `store` property %s"):format(dump(store))) else store{ dest = dest, key = key, converted = converted, raw = val, parse_err = prefix_parse_err } end else local valid_prefixes = get_valid_prefixes() for i, valid_prefix in ipairs(valid_prefixes) do valid_prefixes[i] = "'" .. valid_prefix .. "'" end prefix_parse_err("Unrecognized prefix, should be one of " .. list_to_text(valid_prefixes)) end end return term_obj end return export 7m7efxuys6lveo94nvwye55dw2c55on Module:form of doc 828 8098 239032 221674 2025-12-13T03:17:00Z en>WingerBot 0 use mw.loadData("Module:headword/data").pagename in place of directly fetching pagename using mw.title.getCurrentTitle().text or .subpageText to properly support mammoth (split) pages and unsupported titles (manually assisted) 239032 Scribunto text/plain local export = {} -- Author: Benwing2 --[==[ intro: This module contains functions to implement {{form of/*doc}} templates. The module contains the actual implementation, meant to be called from other Lua code. See [[Module:form of doc/templates]] for the functions meant to be called directly from templates. ]==] local en_utilities_module = "Module:en-utilities" local form_of_module = "Module:form of" local form_of_data_module = "Module:form of/data" local function_module = "Module:fun" local labels_module = "Module:labels" local languages_module = "Module:languages" local load_module = "Module:load" local parse_interface_module = "Module:parse interface" local string_utilities_module = "Module:string utilities" local table_module = "Module:table" local template_parser_module = "Module:template parser" local require = require local m_form_of = require(form_of_module) local m_form_of_data = require(form_of_data_module) local m_cats = require(m_form_of.form_of_cats_module) local m_str_utils = require(string_utilities_module) local m_table = require(table_module) local concat = table.concat local get_indefinite_article = require(en_utilities_module).get_indefinite_article local get_label_info = require(labels_module).get_label_info local get_lang = require(languages_module).getByCode local get_tag_display_form = m_form_of.get_tag_display_form local get_tag_set_display_form = m_form_of.get_tag_set_display_form local insert = table.insert local ipairs = ipairs local is_link_or_html = m_form_of.is_link_or_html local iterate_from = require(function_module).iterateFrom local list_to_set = m_table.listToSet local normalize_tag_set = m_form_of.normalize_tag_set local pairs = pairs local remove_duplicates = m_table.removeDuplicates local safe_require = require(load_module).safe_require local serial_comma_join = m_table.serialCommaJoin local shallow_copy = m_table.shallowCopy local sort = table.sort local table_extend = m_table.extend local tostring = tostring local ucfirst = m_str_utils.ucfirst local unpack = unpack or table.unpack -- Lua 5.2 compatibility local form_of_lang_data_module_prefix = m_form_of.form_of_lang_data_module_prefix local form_of_data1 = require(m_form_of.form_of_data1_module) local form_of_data2 = require(m_form_of.form_of_data2_module) local form_of_pos = mw.loadData(m_form_of.headword_data_module).pos_aliases local SHORTCUTS = m_form_of_data.SHORTCUTS local TAG_TYPE = m_form_of_data.TAG_TYPE local function lang_name(langcode, param) return get_lang(langcode, param):getCanonicalName() end local function link_box(content) return "<div class=\"noprint plainlinks\" style=\"float: right; clear: both; margin: 0 0 .5em 1em; background: var(--wikt-palette-paleblue, #f9f9f9); border: 1px var(--border-color-base,#aaaaaa) solid; margin-top: -1px; padding: 5px; font-weight: bold; font-size: small;\">" .. content .. "</div>" end local function raw_editpage(page) return tostring(mw.uri.fullUrl(page, "action=edit")) end local function show_editlink(page) return link_box("[" .. raw_editpage(page) .. " Edit]") end local function template_name(preserve_lang_code) -- Fetch the template name, minus the '/documentation' suffix that may follow -- and without any language-specific prefixes (e.g. 'el-' or 'ine-bsl-pro-') -- (unless `preserve_lang_code` is given). local PAGENAME = mw.title.getCurrentTitle().text -- DO NOT replace with mw.loadData("Module:headword/data").pagename; we want the whole template name local tempname = PAGENAME:gsub("/documentation$", "") if not preserve_lang_code then while true do -- Repeatedly strip off language code prefixes, in case there are multiple. local newname = tempname:gsub("^%l%l%l?%-", "") if newname == tempname then break end tempname = newname end end return tempname end function export.introdoc(args) local lang = args.lang local langname = lang and lang_name(lang, "lang") local exlangnames = {} for _, exlang in ipairs(args.exlang) do insert(exlangnames, lang_name(exlang, "exlang")) end local parts = {} local function ins(txt) insert(parts, txt) end if args.etymtemp then ins("{{hatnote|This template is for definition sections. For the template used in etymology sections, see [[Template:" .. args.etymtemp .. "]].}}\n") end ins(("{{uses lua|%s/templates}}"):format(form_of_module)) ins("This template creates a definition line for ") ins(args.pldesc or template_name():gsub(" of$", "") .. "s") ins(" ") ins(args.primaryentrytext or "of primary entries") if lang then ins(" in " .. langname) elseif args.exlang[1] then ins(", e.g. in " .. serial_comma_join(exlangnames, {conj = "or"})) end ins(".") local cats = args.cat if cats[1] then ins(" It also categorizes the page into ") local catparts = {} if lang then for _, cat in ipairs(cats) do insert(catparts, "[[:Category:" .. langname .. " " .. cat .. "]]") end else for _, cat in ipairs(cats) do insert(catparts, "the proper language-specific subcategory of [[:Category:" .. ucfirst(cat) .. " by language]] (e.g. [[:Category:" .. (exlangnames[1] or "English") .. " " .. cat .. "]])") end end ins(serial_comma_join(catparts)) ins(".") end if args.addlintrotext then ins(" ") ins(args.addlintrotext) end ins("\n") if args.withcap and args.withdot then ins([===[ By default, this template displays its output as a full sentence, with an initial capital letter and a trailing period (full stop). This can be overridden using {{para|nocap|1}} and/or {{para|nodot|1}} (see below). ]===]) elseif args.withcap or args.withencap and lang == "en" then ins([===[ By default, this template displays its output with an initial capital letter. This can be overridden using {{para|nocap|1}} (see below). ]===]) elseif args.withencap then ins([===[ By default, this template displays its output with an initial capital letter if the term's language in {{para|1}} is English (but not otherwise]===]) if args.usedwithlimitedlangs then ins([==[, and there are likely no English examples for this template).]==]) else ins([==[). This can be overridden by using {{para|nocap|1}} to make the initial letter lowercase for English. This does not auto-add a final period; if (and only if) the term's language is English, you should manually include it after the template unless other text follows, since English definitions should be formatted like full sentences.]==]) end ins("\n") else ins([===[ By default, this template displays its output with an initial lowercase letter. This can be overridden by using {{para|cap|1}} to make the initial letter capitalized]===] .. (lang == "en" and ".\n" or " (but this is not " .. "generally recommended for non-English languages, as non-English definitions should be lowercase).\n")) end ins([===[ This template is '''not''' meant to be used in etymology sections.]===]) if args.etymtemp then ins(" For those sections, use {{tl|" .. args.etymtemp .. "}} instead.\n") else ins("\n") end ins([===[ '''Note:''' This is a “form of” template. The full list of such templates, including their distinctive properties and how to customize the output of this template, can be found at [[:Category:Form-of templates]]. ''The documentation for this page is auto-generated by [[Module:form of doc]].<sup>[<span class="plainlinks">[]===] .. raw_editpage("Module:form of doc") .. " edit]</span>]</sup> As a result, the edit buttons on most section links do not work.''\n") return concat(parts) end local function param(params, list, required) local paramparts = {} if type(params) ~= "table" then params = {params} end for _, p in ipairs(params) do local listparts = {} insert(listparts, "{{para|" .. p .. "}}") if list then insert(listparts, ", {{para|" .. p .. "2}}") insert(listparts, ", {{para|" .. p .. "3}}") insert(listparts, ", etc.") end insert(paramparts, concat(listparts)) end local reqtext = required and "'''(required)'''" or "''(optional)''" return concat(paramparts, " or ") .. " " .. reqtext end function export.paramdoc(args) local parts = {} local function ins(txt) insert(parts, txt) end local function param_and_doc(params, list, required, doc) ins("; ") ins(param(params, list, required)) ins("\n") ins(": ") ins(doc) ins("\n") end local tempname = template_name() local art = args.art or get_indefinite_article(tempname) local sgdescof = args.sgdescof or art .. " " .. tempname ins("''Positional (unnamed) parameters:''\n") local lang = args.lang if args.lang then param_and_doc("1", false, true, "The term to link to (which this page is " .. sgdescof .. "). This should include any needed diacritics as " .. "appropriate to " .. lang_name(lang, "lang") .. ". These diacritics will automatically be stripped out in " .. "the appropriate fashion in order to create the link to the page. This parameter can also include multiple " .. "terms separated by a comma, as long as there is no space after the comma, and each such term can have " .. "inline modifiers specifying transliterations, display forms, qualifiers, labels, genders and other " .. "properties. See below.") param_and_doc("2", false, false, "The text to be shown in the link to the term. If empty or omitted, the term specified by the first " .. "parameter will be used. This parameter is normally not necessary, and should not be used solely to " .. "indicate diacritics; instead, put the diacritics in the first parameter.") else param_and_doc("1", false, true, "The [[WT:LANGCODE|language code]] of the term linked to (which this page is " .. sgdescof .. "). See " .. "[[Wiktionary:List of languages]]. <small>The parameter {{para|lang}} is a deprecated synonym; please do " .. "not use. If this is used, all numbered parameters move down by one.</small>") param_and_doc("2", false, true, "The term to link to (which this page is " .. sgdescof .. "). This should include diacritics as appropriate " .. "to the language (e.g. accents in Russian to mark the stress, vowel diacritics in Arabic, macrons in Latin " .. "to indicate vowel length, etc.). These diacritics will automatically be stripped out in a " .. "language-specific fashion in order to create the link to the page. This parameter can also include " .. "multiple terms separated by a comma, as long as there is no space after the comma, and each such term can " .. "have inline modifiers specifying transliterations, display forms, qualifiers, labels, genders and other " .. "properties. See below.") param_and_doc("3", false, false, "The text to be shown in the link to the term. If empty or omitted, the term specified by the second " .. "parameter will be used. This parameter is normally not necessary, and should not be used solely to " .. "indicate diacritics; instead, put the diacritics in the second parameter.") end ins("''Named parameters:''\n") param_and_doc({"t", lang and "3" or "4"}, false, false, "A gloss or short translation of the term linked " .. "to. <small>The parameter {{para|gloss}} is a deprecated synonym; please do not use.</small>") param_and_doc("tr", false, false, "Transliteration for non-Latin-script terms, if different from the automatically-generated one.") param_and_doc("ts", false, false, "Transcription for non-Latin-script terms whose transliteration is " .. "markedly different from the actual pronunciation. Should not be used for IPA pronunciations.") param_and_doc("cat", true, false, "Additional categories to place the page into. They are automatically " .. "prepended with the language name. A single parameter can contain multiple comma-separated categories as long " .. "as there is no space after the comma.") param_and_doc("addl", false, false, "Additional text to display at the end, before the final closing " .. "<code>&lt;/span></code> tag. It is normally joined to the preceding text by a comma followed by a space. However, if the " .. "value of {{para|addl}} begins with a colon or semicolon, it is appended directly with no joining punctuation, " .. "and if the value begins with an underscore, the remainder is joined to the preceding text with a space.") if args.withfrom then param_and_doc("from", true, false, "A label (see {{tl|label}}) that gives additional information on " .. "the language variety that the term belongs to, the place that it originates from, or something similar.") end if args.withdot then param_and_doc("dot", false, false, "A character to replace the final dot that is normally shown automatically.") param_and_doc("nodot", false, false, "If {{para|nodot|1}}, then no automatic dot will be shown.") end if (args.withcap or args.withencap) and not args.usedwithlimitedlangs then -- Don't even mention if usedwithlimitedlangs=1, because there are unlikely to be English examples. param_and_doc("nocap", false, false, "If {{para|nocap|1}}, then the first letter will be in lowercase." .. (args.withencap and " Only useful for English, because other languages already begin with a lowercase letter." or "")) end if not args.withcap then param_and_doc("cap", false, false, "If {{para|cap|1}}, then the first letter will be in capitalized. " .. "Not generally recommended" .. (args.withencap and "" or ", except for English definitions") .. ", because non-English definitions should begin with a lowercase letter and be formatted like a phrase, " .. "rather than a full sentence.") end if args.cat and args.cat[1] then param_and_doc("nocat", false, false, "Disable categorization of categories built into the template. " .. "For example, {{tl|ellipsis of|en|...}} normally categories into e.g. [[:Category:English ellipses]], but " .. "this can be disabled using {{para|nocat|1}}. This does not affect categories explicitly specified in the " .. "template call itself using {{para|cat}}.") end param_and_doc("notext", false, false, "If {{para|notext|1}}, don't display the initial text preceding the " .. "term(s), but only the actual term or terms. The page is still categorized as normal, unless {{para|nocat|1}} " .. "is given.") param_and_doc("id", false, false, "A sense id for the term, which links to anchors on the page set by " .. "the {{tl|senseid}} template.") param_and_doc("sc", false, false, "Script code to use, if script detection does not work. See " .. "[[Wiktionary:Scripts]]. Rarely needs to be given.") param_and_doc("sort", false, false, "Sort key for sorting any categories the page is added to. Rarely needs " .. "to be given except for Japanese, and even then, only when there are multiple possible pronunciations.") if args.addlparamtext then ins("\n") ins(args.addlparamtext) ins("\n") end ins([==[ ===Inline modifiers=== Use a syntax like <code>Изабе́лла<tr:Izabɛ́lla><t:Isabelle></code> to specify modifiers such as transliterations, glosses, labels and qualifiers. In this example, for the Russian name {{m|ru|Изабе́лла|tr=Izabɛ́lla|t=Isabelle}}, the manual transliteration ''Izabɛ́lla'' and gloss "Isabelle" are given. The following modifiers are recognized; see [[WT:Inline modifiers]] for more detailed discussion of inline modifiers and the meanings of the modifiers given below. * <code>t</code>: gloss * <code>tr</code>: transliteration * <code>ts</code>: transcription, for languages where the transliteration and pronunciation are markedly different * <code>l</code>: comma-separated left labels, e.g. {{cd|<l:rare>}} or {{cd|<l:UK,Australia>}} or {{cd|<l:archaic,or,dialectal>}} or {{cd|<l:<<rare>>, <<archaic>> or <<dialectal>>>}} *: As shown, in the syntax without {{cd|<<...>>}}, there must not be a space after the comma for it to be recognized as a delimiter. *: The labels appear '''before''' the term, parenthesized, italicized and appropriately linked as if {{tl|lb}} were used (but without categorization). * <code>ll</code>: comma-separated right labels; these appear '''after''' the term, parenthesized, italicized and appropriately linked as for left labels * <code>q</code>: left qualifier; this appears '''before''' the term, parenthesized and italicized, but displayed as-is, without interpretation; useful for one-off explanatory notes * <code>qq</code>: right qualifier; this appears '''after''' the term, parenthesized and italicized * <code>ref</code>: reference or references, using the syntax documented in [[Template:IPA#References]] * <code>g</code>: comma-separated list of gender/number specifications; see [[Module:gender and number]] for the complete list * <code>alt</code>: alternative display text * <code>pos</code>: part of speech * <code>ng</code>: arbitrary non-gloss explanatory text * <code>lit</code>: literal meaning * <code>id</code>: sense ID; see {{temp|senseid}} * <code>sc</code>: script code]==]) return concat(parts) end function export.usagedoc(args) local exlangs = {} for _, exlang in ipairs(args.exlang) do insert(exlangs, exlang) end if not args.usedwithlimitedlangs then insert(exlangs, 'en') insert(exlangs, 'de') insert(exlangs, 'ja') end exlangs = remove_duplicates(exlangs) local sub = {} local langparts = {} for _, langcode in ipairs(exlangs) do insert(langparts, '<code>' .. langcode .. '</code> for ' .. lang_name(langcode, "exlang")) end local exlangs = serial_comma_join(langparts, {conj = "or"}) local tempname = template_name("preserve lang code") if args.lang then return ([===[ ==Usage== Use in the definition line, most commonly as follows: # <code><nowiki>{{%s</nowiki>|<var><primary entry goes here></var>}}</code> ===Parameters=== ]===]):format(tempname) .. export.paramdoc(args) else return ([===[ ==Usage== Use in the definition line, most commonly as follows: # <code><nowiki>{{%s</nowiki>|<var><langcode></var>|<var><primary entry goes here></var>}}</code> where <code><var><langcode></var></code> is the [[Wiktionary:Languages|language code]], e.g. %s. ===Parameters=== ]===]):format(tempname, exlangs) .. export.paramdoc(args) end end function export.fulldoc(args) local shortcuts = args.shortcut[1] and ("{{shortcut|%s}}"):format(concat(args.shortcut, "|")) or "" local introdoc = export.introdoc(args) local usagedoc = export.usagedoc(args) return "{{documentation subpage}}\n" .. shortcuts .. introdoc .. "\n" .. usagedoc end function export.infldoc(args) args = shallow_copy(args) args.sgdesc = args.sgdesc or (args.art or "the") .. " " .. template_name():gsub(" of$", "") .. (args.form and " " .. args.form or "") args.pldesc = args.sgdesc args.sgdescof = args.sgdescof or args.sgdesc .. " of" args.primaryentrytext = args.primaryentrytext or "of a primary entry" return export.fulldoc(args) end local tag_type_to_description = { -- If not listed, we just capitalize the first letter ["tense-aspect"] = "Tense/aspect", ["voice-valence"] = "Voice/valence", ["comparison"] = "Degrees of comparison", ["class"] = "Inflectional class", ["sound change"] = "Sound changes", ["grammar"] = "Misc grammar", ["other"] = "Other tags", } local tag_type_order = { "person", "number", "gender", "animacy", "tense-aspect", "mood", "voice-valence", "non-finite", "case", "state", "comparison", "register", "deixis", "clusivity", "class", "attitude", "sound change", "grammar", "other", } local function tag_type_desc(tag_type) return tag_type_to_description[tag_type] or ucfirst(tag_type) end local function sort_by_first(a, b) return a[1] < b[1] end local function get_display_form(tag_set, lang) local norm_tag_sets = normalize_tag_set(tag_set, lang) if #norm_tag_sets == 1 then return get_tag_set_display_form(norm_tag_sets[1], lang) end -- If we have a conjoined shortcut that expands to multiple tag sets, display them using a numbered list. -- In order to do that inside a table we need a newline before the list. local display_forms = {} for _, norm_tag_set in ipairs(norm_tag_sets) do insert(display_forms, "\n# " .. get_tag_set_display_form(norm_tag_set, lang)) end return concat(display_forms) end local function organize_tag_data(data_module) local tab = {} for name, data in pairs(data_module.tags) do local tag_type = data[TAG_TYPE] if not tag_type then -- Throw an error because hopefully it will get noticed and fixed. If we just skip it, it may never get -- fixed. error("Tag '" .. name .. "' has no tag_type") end if not tab[tag_type] then tab[tag_type] = {} end insert(tab[tag_type], {name, data}) end local tag_type_order_set = list_to_set(tag_type_order) for tag_type, tags_of_type in pairs(tab) do if not tag_type_order_set[tag_type] then -- See justification above for throwing an error. error("Tag type '" .. tag_type .. "' not listed in tag_type_order") end sort(tags_of_type, sort_by_first) end return tab end local function insert_group(parts, group) for _, namedata in ipairs(group) do local sparts = {} local name, data = unpack(namedata) insert(sparts, "| <code>" .. name .. "</code> || ") local shortcuts = data[SHORTCUTS] if shortcuts then local ssparts = {} if type(shortcuts) == "string" then shortcuts = {shortcuts} end for _, shortcut in ipairs(shortcuts) do insert(ssparts, "<code>" .. shortcut .. "</code>") end insert(sparts, concat(ssparts, ", ") .. " ") end insert(sparts, "|| " .. get_tag_display_form(name)) insert(parts, "|-") insert(parts, concat(sparts)) end end function export.tagtable() local data1_tab = organize_tag_data(form_of_data1) local data2_tab = organize_tag_data(form_of_data2) local parts = {} insert(parts, '{|class="wikitable"') insert(parts, "! Canonical tag !! Shortcut(s) !! Display form") for _, tag_type in ipairs(tag_type_order) do local group_tab = data1_tab[tag_type] if group_tab then insert(parts, "|-") insert(parts, '! colspan="3" style="text-align: center; background: var(--wikt-palette-lightergrey);" | ' .. tag_type_desc(tag_type) .. " (more common)") insert_group(parts, group_tab) end group_tab = data2_tab[tag_type] if group_tab then insert(parts, "|-") insert(parts, '! colspan="3" style="text-align: center; background: var(--wikt-palette-lightergrey);" | ' .. tag_type_desc(tag_type) .. " (less common)") insert_group(parts, group_tab) end end insert(parts, "|}") return concat(parts, "\n") end local function organize_non_alias_shortcut_data(data_module, lang) local non_alias_shortcuts = {} for shortcut, full in pairs(data_module.shortcuts) do if type(full) == "table" or is_link_or_html(full) or full:find("//") or full:find(":") then insert(non_alias_shortcuts, {shortcut, full, get_display_form({shortcut}, lang)}) end end sort(non_alias_shortcuts, sort_by_first) return non_alias_shortcuts end local function insert_shortcut_group(parts, shortcuts) for _, spec in ipairs(shortcuts) do local shortcut, full, display = unpack(spec) insert(parts, "|-") if type(full) == "table" then full = "{" .. concat(full, " ") .. "}" end insert(parts, ("| <code>%s</code> || <code>%s</code> || %s"):format(shortcut, full, display)) end end function export.non_alias_shortcut_table() local non_alias_shortcuts1 = organize_non_alias_shortcut_data(form_of_data1) local non_alias_shortcuts2 = organize_non_alias_shortcut_data(form_of_data2) local parts = {} insert(parts, '{|class="wikitable"') insert(parts, "! Shortcut !! Expansion !! Display form") if non_alias_shortcuts1[1] then insert(parts, "|-") insert(parts, '! colspan="3" style="text-align: center; background: var(--wikt-palette-grey-3, #dddddd);" | More common:') insert_shortcut_group(parts, non_alias_shortcuts1) end if non_alias_shortcuts2[1] then insert(parts, "|-") insert(parts, '! colspan="3" style="text-align: center; background: var(--wikt-palette-grey-3, #dddddd);" | Less common:') insert_shortcut_group(parts, non_alias_shortcuts2) end insert(parts, "|}") return concat(parts, "\n") end local function process_spec(spec, cats, labels) if type(spec) == "string" then insert(cats, spec) return elseif not spec or spec == true then -- Ignore labels, etc. return elseif type(spec) ~= "table" then error("Wrong type of condition " .. spec .. ": " .. type(spec)) elseif spec.labels then table_extend(labels, spec.labels) return end local predicate = spec[1] if predicate == "multi" or predicate == "cond" then for _, sp in iterate_from(2, ipairs(spec)) do -- Iterate from 2. process_spec(sp, cats, labels) end elseif predicate == "pexists" then process_spec(spec[2], cats, labels) process_spec(spec[3], cats, labels) elseif predicate == "has" or predicate == "hasall" or predicate == "hasany" or predicate == "tags=" or predicate == "p=" or predicate == "pany" or predicate == "not" then process_spec(spec[3], cats, labels) process_spec(spec[4], cats, labels) elseif predicate == "and" or predicate == "or" then process_spec(spec[3], cats, labels) process_spec(spec[4], cats, labels) elseif predicate == "call" then return else error("Unrecognized predicate: " .. predicate) end end local function find_categories_and_labels(catstruct) local cats, labels = {}, {} for _, spec in ipairs(catstruct) do process_spec(spec, cats, labels) end return cats, labels end local function construct_category_table(cats) local category_parts = {} insert(category_parts, '{|class="wikitable"') insert(category_parts, "! Category") for _, cat in ipairs(cats) do insert(category_parts, "|-") insert(category_parts, "| <code>" .. cat .. "</code>") end insert(category_parts, "|}") return concat(category_parts, "\n") end local function construct_label_table(labels, lang, replace_und) local label_parts = {} insert(label_parts, '{|class="wikitable"') insert(label_parts, "! Label !! Display form !! Associated categories") for _, label in ipairs(labels) do insert(label_parts, "|-") local label_data = get_label_info{ label = label, lang = lang, } local coded_categories = {} for _, cat in ipairs(label_data.categories) do if replace_und then cat = cat:gsub("^und:", "LANGCODE:") cat = cat:gsub("^Undetermined ", "LANG ") end insert(coded_categories, "<code>" .. cat .. "</code>") end insert(label_parts, ("| <code>%s</code> || %s || %s"):format(label, label_data.label, concat(coded_categories, ","))) end insert(label_parts, "|}") return concat(label_parts, "\n") end local function iterate_languages(langcodes_module, data_by_lang) for langcode in pairs(require(langcodes_module)) do local data_module_name = form_of_lang_data_module_prefix .. langcode local data_module = safe_require(data_module_name) if data_module or m_cats[langcode] and langcode ~= "und" then local lang = get_lang(langcode, nil, true) -- First do base-lemma params. local base_lemma_param_table if data_module and data_module.base_lemma_params and data_module.base_lemma_params[1] then local base_lemma_param_parts = {} insert(base_lemma_param_parts, '{|class="wikitable"') insert(base_lemma_param_parts, "! Parameter !! Display form") for _, base_lemma_param in ipairs(data_module.base_lemma_params) do insert(base_lemma_param_parts, "|-") insert(base_lemma_param_parts, ("| <code>%s</code> || %s"):format(base_lemma_param.param, get_display_form(base_lemma_param.tags, lang))) end insert(base_lemma_param_parts, "|}") base_lemma_param_table = concat(base_lemma_param_parts, "\n") end -- Then do inflection tags. local data1_tab = data_module and organize_tag_data(data_module) or {} local tag_parts = {} insert(tag_parts, '{|class="wikitable"') insert(tag_parts, "! Canonical tag !! Shortcut(s) !! Tag type !! Display form") local saw_any_tag = false for _, tag_type in ipairs(tag_type_order) do local group_tab = data1_tab[tag_type] if group_tab then for _, namedata in ipairs(group_tab) do local sparts = {} local name, data = unpack(namedata) insert(sparts, "| <code>" .. name .. "</code> || ") if data.shortcuts then local ssparts = {} for _, shortcut in ipairs(data.shortcuts) do insert(ssparts, "<code>" .. shortcut .. "</code>") end insert(sparts, concat(ssparts, ", ") .. " ") end insert(sparts, "|| " .. tag_type_desc(tag_type) .. " || " .. get_tag_display_form(name, lang)) insert(tag_parts, "|-") insert(tag_parts, concat(sparts)) saw_any_tag = true end end end insert(tag_parts, "|}") local tag_table = saw_any_tag and concat(tag_parts, "\n") or nil -- Then do non-alias shortcuts. local non_alias_shortcut_table local non_alias_shortcuts = data_module and organize_non_alias_shortcut_data(data_module, lang) or {} if non_alias_shortcuts[1] then local non_alias_shortcut_parts = {} insert(non_alias_shortcut_parts, '{|class="wikitable"') insert(non_alias_shortcut_parts, "! Shortcut !! Expansion !! Display form") for _, spec in ipairs(non_alias_shortcuts) do local shortcut, full, display = unpack(spec) insert(non_alias_shortcut_parts, "|-") if type(full) == "table" then full = "{" .. concat(full, " ") .. "}" end insert(non_alias_shortcut_parts, ("| <code>%s</code> || <code>%s</code> || %s"):format(shortcut, full, display)) end insert(non_alias_shortcut_parts, "|}") non_alias_shortcut_table = concat(non_alias_shortcut_parts, "\n") end -- Then do categories and labels. local category_table, label_table if m_cats[langcode] then local cats, labels = find_categories_and_labels(m_cats[langcode]) if cats[1] then category_table = construct_category_table(cats) end if labels[1] then label_table = construct_label_table(labels, lang) end end -- Concatenate all the tables together, with appropriate explanatory text. if base_lemma_param_table or tag_table or non_alias_shortcut_table or category_table or label_table then local langname, lang_parts = lang:getCanonicalName(), {} insert(lang_parts, "===" .. langname .. "===") insert(lang_parts, show_editlink(data_module_name)) if base_lemma_param_table then insert(lang_parts, ("%s-specific base lemma parameters:"):format(langname)) insert(lang_parts, base_lemma_param_table) end if tag_table then insert(lang_parts, ("%s-specific inflection tags:"):format(langname)) insert(lang_parts, tag_table) end if non_alias_shortcut_table then insert(lang_parts, ("%s-specific non-alias shortcuts:"):format(langname)) insert(lang_parts, non_alias_shortcut_table) end if category_table then insert(lang_parts, ("%s-specific categories (the exact conditions under which these are added are described in [[Module:form of/cats]]):"): format(langname)) insert(lang_parts, category_table) end if label_table then insert(lang_parts, ("%s-specific labels (the exact conditions under which these are added are described in [[Module:form of/cats]]):"): format(langname)) insert(lang_parts, label_table) end insert(data_by_lang, {langname, concat(lang_parts, "\n")}) end end end end local function sort_by_first_english_first(langdata1, langdata2) if langdata1[1] == "English" then -- English is "less than" (goes before) all other languages return true elseif langdata2[1] == "English" then -- All other languages are not "less than" (do not go before) English return false end return langdata1[1] < langdata2[1] end function export.lang_specific_tables() local data_by_lang = {} iterate_languages("Module:languages/code to canonical name", data_by_lang) iterate_languages("Module:etymology languages/code to canonical name", data_by_lang) sort(data_by_lang, sort_by_first_english_first) local parts = {} for _, lang_and_data in ipairs(data_by_lang) do insert(parts, lang_and_data[2]) end return concat(parts, "\n") end function export.postable() local shortcut_tab = {} for shortcut, full in pairs(form_of_pos) do if not shortcut_tab[full] then shortcut_tab[full] = {} end insert(shortcut_tab[full], shortcut) end local shorcut_list = {} for full, shortcuts in pairs(shortcut_tab) do sort(shortcuts) insert(shorcut_list, {full, shortcuts}) end sort(shorcut_list, sort_by_first) local parts = {} insert(parts, '{|class="wikitable"') insert(parts, "! Canonical part of speech !! Shortcut(s)") for _, full_shortcuts in ipairs(shorcut_list) do local full = full_shortcuts[1] local shortcuts = full_shortcuts[2] insert(parts, "|-") local sparts = {} for _, shortcut in ipairs(shortcuts) do insert(sparts, "<code>" .. shortcut .. "</code>") end insert(parts, "| <code>" .. full .. "</code> || " .. concat(sparts, ", ")) end insert(parts, "|}") return concat(parts, "\n") end function export.lang_independent_category_table() if m_cats["und"] then local cats = find_categories_and_labels(m_cats["und"]) if cats[1] then return construct_category_table(cats) end end return "(no language-independent categories currently)" end function export.lang_independent_label_table() if m_cats["und"] then local labels = select(2, find_categories_and_labels(m_cats["und"])) if labels[1] then return construct_label_table(labels, get_lang("und"), "replace und") end end return "(no language-independent labels currently)" end return export 5p79r28n5qfxf61v4c4h83vfwhgth0m 239033 239032 2026-11-15T04:13:26Z Lee 19 [[:en:Module:form_of_doc]] වෙතින් එක් සංශෝධනයක් 239032 Scribunto text/plain local export = {} -- Author: Benwing2 --[==[ intro: This module contains functions to implement {{form of/*doc}} templates. The module contains the actual implementation, meant to be called from other Lua code. See [[Module:form of doc/templates]] for the functions meant to be called directly from templates. ]==] local en_utilities_module = "Module:en-utilities" local form_of_module = "Module:form of" local form_of_data_module = "Module:form of/data" local function_module = "Module:fun" local labels_module = "Module:labels" local languages_module = "Module:languages" local load_module = "Module:load" local parse_interface_module = "Module:parse interface" local string_utilities_module = "Module:string utilities" local table_module = "Module:table" local template_parser_module = "Module:template parser" local require = require local m_form_of = require(form_of_module) local m_form_of_data = require(form_of_data_module) local m_cats = require(m_form_of.form_of_cats_module) local m_str_utils = require(string_utilities_module) local m_table = require(table_module) local concat = table.concat local get_indefinite_article = require(en_utilities_module).get_indefinite_article local get_label_info = require(labels_module).get_label_info local get_lang = require(languages_module).getByCode local get_tag_display_form = m_form_of.get_tag_display_form local get_tag_set_display_form = m_form_of.get_tag_set_display_form local insert = table.insert local ipairs = ipairs local is_link_or_html = m_form_of.is_link_or_html local iterate_from = require(function_module).iterateFrom local list_to_set = m_table.listToSet local normalize_tag_set = m_form_of.normalize_tag_set local pairs = pairs local remove_duplicates = m_table.removeDuplicates local safe_require = require(load_module).safe_require local serial_comma_join = m_table.serialCommaJoin local shallow_copy = m_table.shallowCopy local sort = table.sort local table_extend = m_table.extend local tostring = tostring local ucfirst = m_str_utils.ucfirst local unpack = unpack or table.unpack -- Lua 5.2 compatibility local form_of_lang_data_module_prefix = m_form_of.form_of_lang_data_module_prefix local form_of_data1 = require(m_form_of.form_of_data1_module) local form_of_data2 = require(m_form_of.form_of_data2_module) local form_of_pos = mw.loadData(m_form_of.headword_data_module).pos_aliases local SHORTCUTS = m_form_of_data.SHORTCUTS local TAG_TYPE = m_form_of_data.TAG_TYPE local function lang_name(langcode, param) return get_lang(langcode, param):getCanonicalName() end local function link_box(content) return "<div class=\"noprint plainlinks\" style=\"float: right; clear: both; margin: 0 0 .5em 1em; background: var(--wikt-palette-paleblue, #f9f9f9); border: 1px var(--border-color-base,#aaaaaa) solid; margin-top: -1px; padding: 5px; font-weight: bold; font-size: small;\">" .. content .. "</div>" end local function raw_editpage(page) return tostring(mw.uri.fullUrl(page, "action=edit")) end local function show_editlink(page) return link_box("[" .. raw_editpage(page) .. " Edit]") end local function template_name(preserve_lang_code) -- Fetch the template name, minus the '/documentation' suffix that may follow -- and without any language-specific prefixes (e.g. 'el-' or 'ine-bsl-pro-') -- (unless `preserve_lang_code` is given). local PAGENAME = mw.title.getCurrentTitle().text -- DO NOT replace with mw.loadData("Module:headword/data").pagename; we want the whole template name local tempname = PAGENAME:gsub("/documentation$", "") if not preserve_lang_code then while true do -- Repeatedly strip off language code prefixes, in case there are multiple. local newname = tempname:gsub("^%l%l%l?%-", "") if newname == tempname then break end tempname = newname end end return tempname end function export.introdoc(args) local lang = args.lang local langname = lang and lang_name(lang, "lang") local exlangnames = {} for _, exlang in ipairs(args.exlang) do insert(exlangnames, lang_name(exlang, "exlang")) end local parts = {} local function ins(txt) insert(parts, txt) end if args.etymtemp then ins("{{hatnote|This template is for definition sections. For the template used in etymology sections, see [[Template:" .. args.etymtemp .. "]].}}\n") end ins(("{{uses lua|%s/templates}}"):format(form_of_module)) ins("This template creates a definition line for ") ins(args.pldesc or template_name():gsub(" of$", "") .. "s") ins(" ") ins(args.primaryentrytext or "of primary entries") if lang then ins(" in " .. langname) elseif args.exlang[1] then ins(", e.g. in " .. serial_comma_join(exlangnames, {conj = "or"})) end ins(".") local cats = args.cat if cats[1] then ins(" It also categorizes the page into ") local catparts = {} if lang then for _, cat in ipairs(cats) do insert(catparts, "[[:Category:" .. langname .. " " .. cat .. "]]") end else for _, cat in ipairs(cats) do insert(catparts, "the proper language-specific subcategory of [[:Category:" .. ucfirst(cat) .. " by language]] (e.g. [[:Category:" .. (exlangnames[1] or "English") .. " " .. cat .. "]])") end end ins(serial_comma_join(catparts)) ins(".") end if args.addlintrotext then ins(" ") ins(args.addlintrotext) end ins("\n") if args.withcap and args.withdot then ins([===[ By default, this template displays its output as a full sentence, with an initial capital letter and a trailing period (full stop). This can be overridden using {{para|nocap|1}} and/or {{para|nodot|1}} (see below). ]===]) elseif args.withcap or args.withencap and lang == "en" then ins([===[ By default, this template displays its output with an initial capital letter. This can be overridden using {{para|nocap|1}} (see below). ]===]) elseif args.withencap then ins([===[ By default, this template displays its output with an initial capital letter if the term's language in {{para|1}} is English (but not otherwise]===]) if args.usedwithlimitedlangs then ins([==[, and there are likely no English examples for this template).]==]) else ins([==[). This can be overridden by using {{para|nocap|1}} to make the initial letter lowercase for English. This does not auto-add a final period; if (and only if) the term's language is English, you should manually include it after the template unless other text follows, since English definitions should be formatted like full sentences.]==]) end ins("\n") else ins([===[ By default, this template displays its output with an initial lowercase letter. This can be overridden by using {{para|cap|1}} to make the initial letter capitalized]===] .. (lang == "en" and ".\n" or " (but this is not " .. "generally recommended for non-English languages, as non-English definitions should be lowercase).\n")) end ins([===[ This template is '''not''' meant to be used in etymology sections.]===]) if args.etymtemp then ins(" For those sections, use {{tl|" .. args.etymtemp .. "}} instead.\n") else ins("\n") end ins([===[ '''Note:''' This is a “form of” template. The full list of such templates, including their distinctive properties and how to customize the output of this template, can be found at [[:Category:Form-of templates]]. ''The documentation for this page is auto-generated by [[Module:form of doc]].<sup>[<span class="plainlinks">[]===] .. raw_editpage("Module:form of doc") .. " edit]</span>]</sup> As a result, the edit buttons on most section links do not work.''\n") return concat(parts) end local function param(params, list, required) local paramparts = {} if type(params) ~= "table" then params = {params} end for _, p in ipairs(params) do local listparts = {} insert(listparts, "{{para|" .. p .. "}}") if list then insert(listparts, ", {{para|" .. p .. "2}}") insert(listparts, ", {{para|" .. p .. "3}}") insert(listparts, ", etc.") end insert(paramparts, concat(listparts)) end local reqtext = required and "'''(required)'''" or "''(optional)''" return concat(paramparts, " or ") .. " " .. reqtext end function export.paramdoc(args) local parts = {} local function ins(txt) insert(parts, txt) end local function param_and_doc(params, list, required, doc) ins("; ") ins(param(params, list, required)) ins("\n") ins(": ") ins(doc) ins("\n") end local tempname = template_name() local art = args.art or get_indefinite_article(tempname) local sgdescof = args.sgdescof or art .. " " .. tempname ins("''Positional (unnamed) parameters:''\n") local lang = args.lang if args.lang then param_and_doc("1", false, true, "The term to link to (which this page is " .. sgdescof .. "). This should include any needed diacritics as " .. "appropriate to " .. lang_name(lang, "lang") .. ". These diacritics will automatically be stripped out in " .. "the appropriate fashion in order to create the link to the page. This parameter can also include multiple " .. "terms separated by a comma, as long as there is no space after the comma, and each such term can have " .. "inline modifiers specifying transliterations, display forms, qualifiers, labels, genders and other " .. "properties. See below.") param_and_doc("2", false, false, "The text to be shown in the link to the term. If empty or omitted, the term specified by the first " .. "parameter will be used. This parameter is normally not necessary, and should not be used solely to " .. "indicate diacritics; instead, put the diacritics in the first parameter.") else param_and_doc("1", false, true, "The [[WT:LANGCODE|language code]] of the term linked to (which this page is " .. sgdescof .. "). See " .. "[[Wiktionary:List of languages]]. <small>The parameter {{para|lang}} is a deprecated synonym; please do " .. "not use. If this is used, all numbered parameters move down by one.</small>") param_and_doc("2", false, true, "The term to link to (which this page is " .. sgdescof .. "). This should include diacritics as appropriate " .. "to the language (e.g. accents in Russian to mark the stress, vowel diacritics in Arabic, macrons in Latin " .. "to indicate vowel length, etc.). These diacritics will automatically be stripped out in a " .. "language-specific fashion in order to create the link to the page. This parameter can also include " .. "multiple terms separated by a comma, as long as there is no space after the comma, and each such term can " .. "have inline modifiers specifying transliterations, display forms, qualifiers, labels, genders and other " .. "properties. See below.") param_and_doc("3", false, false, "The text to be shown in the link to the term. If empty or omitted, the term specified by the second " .. "parameter will be used. This parameter is normally not necessary, and should not be used solely to " .. "indicate diacritics; instead, put the diacritics in the second parameter.") end ins("''Named parameters:''\n") param_and_doc({"t", lang and "3" or "4"}, false, false, "A gloss or short translation of the term linked " .. "to. <small>The parameter {{para|gloss}} is a deprecated synonym; please do not use.</small>") param_and_doc("tr", false, false, "Transliteration for non-Latin-script terms, if different from the automatically-generated one.") param_and_doc("ts", false, false, "Transcription for non-Latin-script terms whose transliteration is " .. "markedly different from the actual pronunciation. Should not be used for IPA pronunciations.") param_and_doc("cat", true, false, "Additional categories to place the page into. They are automatically " .. "prepended with the language name. A single parameter can contain multiple comma-separated categories as long " .. "as there is no space after the comma.") param_and_doc("addl", false, false, "Additional text to display at the end, before the final closing " .. "<code>&lt;/span></code> tag. It is normally joined to the preceding text by a comma followed by a space. However, if the " .. "value of {{para|addl}} begins with a colon or semicolon, it is appended directly with no joining punctuation, " .. "and if the value begins with an underscore, the remainder is joined to the preceding text with a space.") if args.withfrom then param_and_doc("from", true, false, "A label (see {{tl|label}}) that gives additional information on " .. "the language variety that the term belongs to, the place that it originates from, or something similar.") end if args.withdot then param_and_doc("dot", false, false, "A character to replace the final dot that is normally shown automatically.") param_and_doc("nodot", false, false, "If {{para|nodot|1}}, then no automatic dot will be shown.") end if (args.withcap or args.withencap) and not args.usedwithlimitedlangs then -- Don't even mention if usedwithlimitedlangs=1, because there are unlikely to be English examples. param_and_doc("nocap", false, false, "If {{para|nocap|1}}, then the first letter will be in lowercase." .. (args.withencap and " Only useful for English, because other languages already begin with a lowercase letter." or "")) end if not args.withcap then param_and_doc("cap", false, false, "If {{para|cap|1}}, then the first letter will be in capitalized. " .. "Not generally recommended" .. (args.withencap and "" or ", except for English definitions") .. ", because non-English definitions should begin with a lowercase letter and be formatted like a phrase, " .. "rather than a full sentence.") end if args.cat and args.cat[1] then param_and_doc("nocat", false, false, "Disable categorization of categories built into the template. " .. "For example, {{tl|ellipsis of|en|...}} normally categories into e.g. [[:Category:English ellipses]], but " .. "this can be disabled using {{para|nocat|1}}. This does not affect categories explicitly specified in the " .. "template call itself using {{para|cat}}.") end param_and_doc("notext", false, false, "If {{para|notext|1}}, don't display the initial text preceding the " .. "term(s), but only the actual term or terms. The page is still categorized as normal, unless {{para|nocat|1}} " .. "is given.") param_and_doc("id", false, false, "A sense id for the term, which links to anchors on the page set by " .. "the {{tl|senseid}} template.") param_and_doc("sc", false, false, "Script code to use, if script detection does not work. See " .. "[[Wiktionary:Scripts]]. Rarely needs to be given.") param_and_doc("sort", false, false, "Sort key for sorting any categories the page is added to. Rarely needs " .. "to be given except for Japanese, and even then, only when there are multiple possible pronunciations.") if args.addlparamtext then ins("\n") ins(args.addlparamtext) ins("\n") end ins([==[ ===Inline modifiers=== Use a syntax like <code>Изабе́лла<tr:Izabɛ́lla><t:Isabelle></code> to specify modifiers such as transliterations, glosses, labels and qualifiers. In this example, for the Russian name {{m|ru|Изабе́лла|tr=Izabɛ́lla|t=Isabelle}}, the manual transliteration ''Izabɛ́lla'' and gloss "Isabelle" are given. The following modifiers are recognized; see [[WT:Inline modifiers]] for more detailed discussion of inline modifiers and the meanings of the modifiers given below. * <code>t</code>: gloss * <code>tr</code>: transliteration * <code>ts</code>: transcription, for languages where the transliteration and pronunciation are markedly different * <code>l</code>: comma-separated left labels, e.g. {{cd|<l:rare>}} or {{cd|<l:UK,Australia>}} or {{cd|<l:archaic,or,dialectal>}} or {{cd|<l:<<rare>>, <<archaic>> or <<dialectal>>>}} *: As shown, in the syntax without {{cd|<<...>>}}, there must not be a space after the comma for it to be recognized as a delimiter. *: The labels appear '''before''' the term, parenthesized, italicized and appropriately linked as if {{tl|lb}} were used (but without categorization). * <code>ll</code>: comma-separated right labels; these appear '''after''' the term, parenthesized, italicized and appropriately linked as for left labels * <code>q</code>: left qualifier; this appears '''before''' the term, parenthesized and italicized, but displayed as-is, without interpretation; useful for one-off explanatory notes * <code>qq</code>: right qualifier; this appears '''after''' the term, parenthesized and italicized * <code>ref</code>: reference or references, using the syntax documented in [[Template:IPA#References]] * <code>g</code>: comma-separated list of gender/number specifications; see [[Module:gender and number]] for the complete list * <code>alt</code>: alternative display text * <code>pos</code>: part of speech * <code>ng</code>: arbitrary non-gloss explanatory text * <code>lit</code>: literal meaning * <code>id</code>: sense ID; see {{temp|senseid}} * <code>sc</code>: script code]==]) return concat(parts) end function export.usagedoc(args) local exlangs = {} for _, exlang in ipairs(args.exlang) do insert(exlangs, exlang) end if not args.usedwithlimitedlangs then insert(exlangs, 'en') insert(exlangs, 'de') insert(exlangs, 'ja') end exlangs = remove_duplicates(exlangs) local sub = {} local langparts = {} for _, langcode in ipairs(exlangs) do insert(langparts, '<code>' .. langcode .. '</code> for ' .. lang_name(langcode, "exlang")) end local exlangs = serial_comma_join(langparts, {conj = "or"}) local tempname = template_name("preserve lang code") if args.lang then return ([===[ ==Usage== Use in the definition line, most commonly as follows: # <code><nowiki>{{%s</nowiki>|<var><primary entry goes here></var>}}</code> ===Parameters=== ]===]):format(tempname) .. export.paramdoc(args) else return ([===[ ==Usage== Use in the definition line, most commonly as follows: # <code><nowiki>{{%s</nowiki>|<var><langcode></var>|<var><primary entry goes here></var>}}</code> where <code><var><langcode></var></code> is the [[Wiktionary:Languages|language code]], e.g. %s. ===Parameters=== ]===]):format(tempname, exlangs) .. export.paramdoc(args) end end function export.fulldoc(args) local shortcuts = args.shortcut[1] and ("{{shortcut|%s}}"):format(concat(args.shortcut, "|")) or "" local introdoc = export.introdoc(args) local usagedoc = export.usagedoc(args) return "{{documentation subpage}}\n" .. shortcuts .. introdoc .. "\n" .. usagedoc end function export.infldoc(args) args = shallow_copy(args) args.sgdesc = args.sgdesc or (args.art or "the") .. " " .. template_name():gsub(" of$", "") .. (args.form and " " .. args.form or "") args.pldesc = args.sgdesc args.sgdescof = args.sgdescof or args.sgdesc .. " of" args.primaryentrytext = args.primaryentrytext or "of a primary entry" return export.fulldoc(args) end local tag_type_to_description = { -- If not listed, we just capitalize the first letter ["tense-aspect"] = "Tense/aspect", ["voice-valence"] = "Voice/valence", ["comparison"] = "Degrees of comparison", ["class"] = "Inflectional class", ["sound change"] = "Sound changes", ["grammar"] = "Misc grammar", ["other"] = "Other tags", } local tag_type_order = { "person", "number", "gender", "animacy", "tense-aspect", "mood", "voice-valence", "non-finite", "case", "state", "comparison", "register", "deixis", "clusivity", "class", "attitude", "sound change", "grammar", "other", } local function tag_type_desc(tag_type) return tag_type_to_description[tag_type] or ucfirst(tag_type) end local function sort_by_first(a, b) return a[1] < b[1] end local function get_display_form(tag_set, lang) local norm_tag_sets = normalize_tag_set(tag_set, lang) if #norm_tag_sets == 1 then return get_tag_set_display_form(norm_tag_sets[1], lang) end -- If we have a conjoined shortcut that expands to multiple tag sets, display them using a numbered list. -- In order to do that inside a table we need a newline before the list. local display_forms = {} for _, norm_tag_set in ipairs(norm_tag_sets) do insert(display_forms, "\n# " .. get_tag_set_display_form(norm_tag_set, lang)) end return concat(display_forms) end local function organize_tag_data(data_module) local tab = {} for name, data in pairs(data_module.tags) do local tag_type = data[TAG_TYPE] if not tag_type then -- Throw an error because hopefully it will get noticed and fixed. If we just skip it, it may never get -- fixed. error("Tag '" .. name .. "' has no tag_type") end if not tab[tag_type] then tab[tag_type] = {} end insert(tab[tag_type], {name, data}) end local tag_type_order_set = list_to_set(tag_type_order) for tag_type, tags_of_type in pairs(tab) do if not tag_type_order_set[tag_type] then -- See justification above for throwing an error. error("Tag type '" .. tag_type .. "' not listed in tag_type_order") end sort(tags_of_type, sort_by_first) end return tab end local function insert_group(parts, group) for _, namedata in ipairs(group) do local sparts = {} local name, data = unpack(namedata) insert(sparts, "| <code>" .. name .. "</code> || ") local shortcuts = data[SHORTCUTS] if shortcuts then local ssparts = {} if type(shortcuts) == "string" then shortcuts = {shortcuts} end for _, shortcut in ipairs(shortcuts) do insert(ssparts, "<code>" .. shortcut .. "</code>") end insert(sparts, concat(ssparts, ", ") .. " ") end insert(sparts, "|| " .. get_tag_display_form(name)) insert(parts, "|-") insert(parts, concat(sparts)) end end function export.tagtable() local data1_tab = organize_tag_data(form_of_data1) local data2_tab = organize_tag_data(form_of_data2) local parts = {} insert(parts, '{|class="wikitable"') insert(parts, "! Canonical tag !! Shortcut(s) !! Display form") for _, tag_type in ipairs(tag_type_order) do local group_tab = data1_tab[tag_type] if group_tab then insert(parts, "|-") insert(parts, '! colspan="3" style="text-align: center; background: var(--wikt-palette-lightergrey);" | ' .. tag_type_desc(tag_type) .. " (more common)") insert_group(parts, group_tab) end group_tab = data2_tab[tag_type] if group_tab then insert(parts, "|-") insert(parts, '! colspan="3" style="text-align: center; background: var(--wikt-palette-lightergrey);" | ' .. tag_type_desc(tag_type) .. " (less common)") insert_group(parts, group_tab) end end insert(parts, "|}") return concat(parts, "\n") end local function organize_non_alias_shortcut_data(data_module, lang) local non_alias_shortcuts = {} for shortcut, full in pairs(data_module.shortcuts) do if type(full) == "table" or is_link_or_html(full) or full:find("//") or full:find(":") then insert(non_alias_shortcuts, {shortcut, full, get_display_form({shortcut}, lang)}) end end sort(non_alias_shortcuts, sort_by_first) return non_alias_shortcuts end local function insert_shortcut_group(parts, shortcuts) for _, spec in ipairs(shortcuts) do local shortcut, full, display = unpack(spec) insert(parts, "|-") if type(full) == "table" then full = "{" .. concat(full, " ") .. "}" end insert(parts, ("| <code>%s</code> || <code>%s</code> || %s"):format(shortcut, full, display)) end end function export.non_alias_shortcut_table() local non_alias_shortcuts1 = organize_non_alias_shortcut_data(form_of_data1) local non_alias_shortcuts2 = organize_non_alias_shortcut_data(form_of_data2) local parts = {} insert(parts, '{|class="wikitable"') insert(parts, "! Shortcut !! Expansion !! Display form") if non_alias_shortcuts1[1] then insert(parts, "|-") insert(parts, '! colspan="3" style="text-align: center; background: var(--wikt-palette-grey-3, #dddddd);" | More common:') insert_shortcut_group(parts, non_alias_shortcuts1) end if non_alias_shortcuts2[1] then insert(parts, "|-") insert(parts, '! colspan="3" style="text-align: center; background: var(--wikt-palette-grey-3, #dddddd);" | Less common:') insert_shortcut_group(parts, non_alias_shortcuts2) end insert(parts, "|}") return concat(parts, "\n") end local function process_spec(spec, cats, labels) if type(spec) == "string" then insert(cats, spec) return elseif not spec or spec == true then -- Ignore labels, etc. return elseif type(spec) ~= "table" then error("Wrong type of condition " .. spec .. ": " .. type(spec)) elseif spec.labels then table_extend(labels, spec.labels) return end local predicate = spec[1] if predicate == "multi" or predicate == "cond" then for _, sp in iterate_from(2, ipairs(spec)) do -- Iterate from 2. process_spec(sp, cats, labels) end elseif predicate == "pexists" then process_spec(spec[2], cats, labels) process_spec(spec[3], cats, labels) elseif predicate == "has" or predicate == "hasall" or predicate == "hasany" or predicate == "tags=" or predicate == "p=" or predicate == "pany" or predicate == "not" then process_spec(spec[3], cats, labels) process_spec(spec[4], cats, labels) elseif predicate == "and" or predicate == "or" then process_spec(spec[3], cats, labels) process_spec(spec[4], cats, labels) elseif predicate == "call" then return else error("Unrecognized predicate: " .. predicate) end end local function find_categories_and_labels(catstruct) local cats, labels = {}, {} for _, spec in ipairs(catstruct) do process_spec(spec, cats, labels) end return cats, labels end local function construct_category_table(cats) local category_parts = {} insert(category_parts, '{|class="wikitable"') insert(category_parts, "! Category") for _, cat in ipairs(cats) do insert(category_parts, "|-") insert(category_parts, "| <code>" .. cat .. "</code>") end insert(category_parts, "|}") return concat(category_parts, "\n") end local function construct_label_table(labels, lang, replace_und) local label_parts = {} insert(label_parts, '{|class="wikitable"') insert(label_parts, "! Label !! Display form !! Associated categories") for _, label in ipairs(labels) do insert(label_parts, "|-") local label_data = get_label_info{ label = label, lang = lang, } local coded_categories = {} for _, cat in ipairs(label_data.categories) do if replace_und then cat = cat:gsub("^und:", "LANGCODE:") cat = cat:gsub("^Undetermined ", "LANG ") end insert(coded_categories, "<code>" .. cat .. "</code>") end insert(label_parts, ("| <code>%s</code> || %s || %s"):format(label, label_data.label, concat(coded_categories, ","))) end insert(label_parts, "|}") return concat(label_parts, "\n") end local function iterate_languages(langcodes_module, data_by_lang) for langcode in pairs(require(langcodes_module)) do local data_module_name = form_of_lang_data_module_prefix .. langcode local data_module = safe_require(data_module_name) if data_module or m_cats[langcode] and langcode ~= "und" then local lang = get_lang(langcode, nil, true) -- First do base-lemma params. local base_lemma_param_table if data_module and data_module.base_lemma_params and data_module.base_lemma_params[1] then local base_lemma_param_parts = {} insert(base_lemma_param_parts, '{|class="wikitable"') insert(base_lemma_param_parts, "! Parameter !! Display form") for _, base_lemma_param in ipairs(data_module.base_lemma_params) do insert(base_lemma_param_parts, "|-") insert(base_lemma_param_parts, ("| <code>%s</code> || %s"):format(base_lemma_param.param, get_display_form(base_lemma_param.tags, lang))) end insert(base_lemma_param_parts, "|}") base_lemma_param_table = concat(base_lemma_param_parts, "\n") end -- Then do inflection tags. local data1_tab = data_module and organize_tag_data(data_module) or {} local tag_parts = {} insert(tag_parts, '{|class="wikitable"') insert(tag_parts, "! Canonical tag !! Shortcut(s) !! Tag type !! Display form") local saw_any_tag = false for _, tag_type in ipairs(tag_type_order) do local group_tab = data1_tab[tag_type] if group_tab then for _, namedata in ipairs(group_tab) do local sparts = {} local name, data = unpack(namedata) insert(sparts, "| <code>" .. name .. "</code> || ") if data.shortcuts then local ssparts = {} for _, shortcut in ipairs(data.shortcuts) do insert(ssparts, "<code>" .. shortcut .. "</code>") end insert(sparts, concat(ssparts, ", ") .. " ") end insert(sparts, "|| " .. tag_type_desc(tag_type) .. " || " .. get_tag_display_form(name, lang)) insert(tag_parts, "|-") insert(tag_parts, concat(sparts)) saw_any_tag = true end end end insert(tag_parts, "|}") local tag_table = saw_any_tag and concat(tag_parts, "\n") or nil -- Then do non-alias shortcuts. local non_alias_shortcut_table local non_alias_shortcuts = data_module and organize_non_alias_shortcut_data(data_module, lang) or {} if non_alias_shortcuts[1] then local non_alias_shortcut_parts = {} insert(non_alias_shortcut_parts, '{|class="wikitable"') insert(non_alias_shortcut_parts, "! Shortcut !! Expansion !! Display form") for _, spec in ipairs(non_alias_shortcuts) do local shortcut, full, display = unpack(spec) insert(non_alias_shortcut_parts, "|-") if type(full) == "table" then full = "{" .. concat(full, " ") .. "}" end insert(non_alias_shortcut_parts, ("| <code>%s</code> || <code>%s</code> || %s"):format(shortcut, full, display)) end insert(non_alias_shortcut_parts, "|}") non_alias_shortcut_table = concat(non_alias_shortcut_parts, "\n") end -- Then do categories and labels. local category_table, label_table if m_cats[langcode] then local cats, labels = find_categories_and_labels(m_cats[langcode]) if cats[1] then category_table = construct_category_table(cats) end if labels[1] then label_table = construct_label_table(labels, lang) end end -- Concatenate all the tables together, with appropriate explanatory text. if base_lemma_param_table or tag_table or non_alias_shortcut_table or category_table or label_table then local langname, lang_parts = lang:getCanonicalName(), {} insert(lang_parts, "===" .. langname .. "===") insert(lang_parts, show_editlink(data_module_name)) if base_lemma_param_table then insert(lang_parts, ("%s-specific base lemma parameters:"):format(langname)) insert(lang_parts, base_lemma_param_table) end if tag_table then insert(lang_parts, ("%s-specific inflection tags:"):format(langname)) insert(lang_parts, tag_table) end if non_alias_shortcut_table then insert(lang_parts, ("%s-specific non-alias shortcuts:"):format(langname)) insert(lang_parts, non_alias_shortcut_table) end if category_table then insert(lang_parts, ("%s-specific categories (the exact conditions under which these are added are described in [[Module:form of/cats]]):"): format(langname)) insert(lang_parts, category_table) end if label_table then insert(lang_parts, ("%s-specific labels (the exact conditions under which these are added are described in [[Module:form of/cats]]):"): format(langname)) insert(lang_parts, label_table) end insert(data_by_lang, {langname, concat(lang_parts, "\n")}) end end end end local function sort_by_first_english_first(langdata1, langdata2) if langdata1[1] == "English" then -- English is "less than" (goes before) all other languages return true elseif langdata2[1] == "English" then -- All other languages are not "less than" (do not go before) English return false end return langdata1[1] < langdata2[1] end function export.lang_specific_tables() local data_by_lang = {} iterate_languages("Module:languages/code to canonical name", data_by_lang) iterate_languages("Module:etymology languages/code to canonical name", data_by_lang) sort(data_by_lang, sort_by_first_english_first) local parts = {} for _, lang_and_data in ipairs(data_by_lang) do insert(parts, lang_and_data[2]) end return concat(parts, "\n") end function export.postable() local shortcut_tab = {} for shortcut, full in pairs(form_of_pos) do if not shortcut_tab[full] then shortcut_tab[full] = {} end insert(shortcut_tab[full], shortcut) end local shorcut_list = {} for full, shortcuts in pairs(shortcut_tab) do sort(shortcuts) insert(shorcut_list, {full, shortcuts}) end sort(shorcut_list, sort_by_first) local parts = {} insert(parts, '{|class="wikitable"') insert(parts, "! Canonical part of speech !! Shortcut(s)") for _, full_shortcuts in ipairs(shorcut_list) do local full = full_shortcuts[1] local shortcuts = full_shortcuts[2] insert(parts, "|-") local sparts = {} for _, shortcut in ipairs(shortcuts) do insert(sparts, "<code>" .. shortcut .. "</code>") end insert(parts, "| <code>" .. full .. "</code> || " .. concat(sparts, ", ")) end insert(parts, "|}") return concat(parts, "\n") end function export.lang_independent_category_table() if m_cats["und"] then local cats = find_categories_and_labels(m_cats["und"]) if cats[1] then return construct_category_table(cats) end end return "(no language-independent categories currently)" end function export.lang_independent_label_table() if m_cats["und"] then local labels = select(2, find_categories_and_labels(m_cats["und"])) if labels[1] then return construct_label_table(labels, get_lang("und"), "replace und") end end return "(no language-independent labels currently)" end return export 5p79r28n5qfxf61v4c4h83vfwhgth0m සැකිල්ල:affix/documentation 10 8495 239017 218096 2026-07-14T15:20:31Z en>Kiril kovachev 0 /* Parameters */ Add explanation of ng parameter 239017 wikitext text/x-wiki {{documentation subpage}} {{uses lua|affix|affix/templates}} {{shortcut|Template:af}} This template displays the [[morpheme]]s (parts) that compose a word and categorizes its affixes, used in [[Wiktionary:Etymology|etymology sections]]. Despite the name, this template may be used for compounds similar to {{temp|compound}}. ==Parameters== ; {{para|1}} : The language code. See [[Wiktionary:Languages]]. ; {{para|2}}, {{para|3}} etc. : The parts of the terms to show. Either: :# At least one of the provided parts must begin or end with a hyphen (prefix, suffix, interfix); :# or there must be two or more parts (it may be a compound, with or without prefixes, suffixes, interfixes). : A term can begin with a language code followed by a colon. This overrides the default provided by {{para|1}}. When this is provided, the language name is displayed before the part, and a derivational category is also added to the entry. This is used for the occasional term which was directly affixed at the time of borrowing, and for which no native base form existed at the time, such as {{m|en|vexillology}}. ; {{para|pos}} : The part of speech to include in the category names, in plural form. Defaults to <code>terms</code>. This is separate from (and conceptually very different from) the {{para|pos<var>N</var>}} parameters, which specify clarifying parts of speech or similar descriptive text to display in parentheses after individual terms, next to the gloss. ; {{para|lit}} : The literal meaning of the overall term. This is separate from the {{para|lit<var>N</var>}} parameters, which specify literal meanings of individual parts. ; {{para|sort}} : The sort key to use when placing the entry in categories. This is rarely needed, as the default generated sort key is usually correct. ; {{para|sc}} : The script code. See [[Wiktionary:Scripts]]. This is rarely needed as the script can generally be automatically detected. This is separate from the {{para|sc<var>N</var>}} parameters, which specify script codes for individual parts in languages distinct from the overall language specified using {{para|1}}. ; {{para|nocat|1}} : Do not add categories to the entry. ; {{para|type}} : Type of compound, e.g. [[bahuvrihi]] or [[alliterative]]. See [[#Compound subtypes]] below. If this parameter is given, extra text is generated before the listed parts (e.g. ''{{glossary|bahuvrihi|Bahuvrīhi}} compound of FOO + BAR''), and the page is placed in an additional category (e.g. [[:Category:Hindi bahuvrihi compounds]]). ; {{para|nocap|1}} : Do not capitalize the first letter of the extra text generated by {{para|type}}. ; {{para|notext|1}} : When {{para|type}} is used, do not generate the extra text that is normally placed before the listed parts. The page will still be placed in the additional type-specific category unless {{para|nocat|1}} is given. The following parameters are available for each matching part in the numbered/positional parameters. The <code><var>N</var></code> must be replaced by the corresponding part index. For example, for the second part (positional parameter 3), use 2 for <code><var>N</var></code>. Most of these parameters correspond directly to the equivalent parameters in the standard {{temp|l}} (and {{temp|m}}) template. ; {{para|alt<var>N</var>}} : The alternative display form. Equivalent to the third parameter of {{temp|l}}. ; {{para|t<var>N</var>}} : A gloss to show after the part. Equivalent to the fourth parameter of {{temp|l}}. <small>The parameter {{para|gloss<var>N</var>}} is deprecated for this purpose.</small> ; {{para|ng<var>N</var>}} : Arbitrary explanatory text, placed after the gloss in plain text. Prefer to use this over {{para|pos<var>N</var>}} for anything other than purely grammatical uses. ; {{para|tr<var>N</var>}} : The transliteration, as in {{temp|l}}. ; {{para|ts<var>N</var>}} : The transcription, in languages where the transliteration and transcription differ markedly, as in {{temp|l}}. ; {{para|g<var>N</var>}} : The gender (multiple comma-separated genders may be specified for a given part). ; {{para|id<var>N</var>}} : The sense id, as in {{temp|l}}. As distinguished by mere linking templates, the affix template, categorizing terms by affix, also adds the sense id to the category name to distinguish various purposes of the same affix shape, hence the sense id in the dictionary entry for the affix should have a reasonable name in respect to this categorization. Changes the category name from <code><var>language name</var> terms <var>affix</var>ed with <var>affix</var></code> to <code><var>language name</var> terms <var>affix</var>ed with <var>affix</var> (<var>value of id parameter</var>)</code>. ; {{para|pos<var>N</var>}} : The part of speech label to show after the part, as in {{temp|l}}. If this parameter contains <code>patronym(ic)</code>, the entry will be added to a [[:Category:Patronymics by language|language's patronymic category]]. If this parameter contains <code>diminutive</code> and the {{para|pos}} parameter is defined, the entry will be added to a diminutive part-of-speech category. For instance, the parameter values {{para|pos|noun}} and {{para|pos2|diminutive suffix}} will add an entry to the language's [[:Category:Diminutive nouns by language|diminutive nouns]] category. ; {{para|lit<var>N</var>}} : The literal meaning to show after the part, as in {{temp|l}}. ; {{para|type<var>N</var>}} : Override the affix type, e.g. {{para|type2|prefix}}. '''Not''' the same as the compound type specified using {{para|type}}. ; {{para|q<var>N</var>}} : Qualifier text to display before the part, in parens and normally italicized. ; {{para|qq<var>N</var>}} : Qualifier text to display after the part, in parens and normally italicized. ; {{para|l<var>N</var>}} : Comma-separated label(s) to display before the part, as in {{tl|lb}}. ; {{para|ll<var>N</var>}} : Comma-separated label(s) to display after the part, as in {{tl|lb}}. ; {{para|infl<var>N</var>}} : Ampersand-separated grammar tag(s) to display after the part, as in {{tl|inflection of}}. ; {{para|ref<var>N</var>}} : Reference(s) to display after the part, as in {{tl|IPA}}. ; {{para|lang<var>N</var>}} : The language code to use for this particular part. This overrides the default provided by {{para|1}}. When this is provided, the language name is displayed before the part, and a derivational category is also added to the entry. This is used for the occasional term which was directly affixed at the time of borrowing, and for which no native base form existed at the time, such as {{m|en|vexillology}}. ; {{para|sc<var>N</var>}} : The script code to use for this particular part. This overrides the default provided by {{para|sc}}. ==Examples== Basic examples: :{{temp|af|en|complete|-ness}} → {{af|en|complete|-ness}} :{{temp|af|en|pre-|date}} → {{af|en|pre-|date}} :{{temp|af|en|acro-|-nym}} → {{af|en|acro-|-nym}} :{{temp|af|en|pest|-i-|-cide}} → {{af|en|pest|-i-|-cide}} :{{temp|af|en|volley|ball}} → {{af|en|volley|ball}} :{{temp|af|en|small|en- -en}} → {{af|en|small|en- -en}} ===In foreign languages=== 1. For {{m+|pt|aviãozão||large plane}}, which can be viewed as being composed of {{m|pt|avião||plane}}, an interfix {{m|pt|-z-}} and an augmentative suffix {{m|pt|-ão}}, use the following: {{demo|<nowiki>{{af|pt|avião<t:plane>|-z-|-ão<pos:augmentative suffix>}}</nowiki>|indent=:}} This can equivalently be written using separate parameters (the older way of doing things) like this: :<code><nowiki>{{af|pt|avião|t1=plane|-z-|-ão|pos3=augmentative suffix}}</nowiki></code> 2. The Portuguese medical term {{m|pt|acromia||[[achromia]] (lack of pigmentation)}} can be viewed as being composed directly from {{m+|grc|χρῶμα||color}} using the Portuguese [[privative]] (i.e. expressing "lack of") suffix {{m|pt|a-}} and the abstract noun suffix {{m|pt|-ia}}. Write this as follows: {{demo|<nowiki>{{af|pt|a-<id:privative>|grc:χρῶμα<t:color>|-ia}}</nowiki>|indent=:}} In this case, there are multiple Portuguese prefixes spelled {{m|pt|a-}}, with different origins and meanings. To identify the privative prefix specifically, we use the <code><id:...></code> modifier (see {{tl|senseid}}). 3. The Italian relational adjective {{m|it|litoraneo||coastal, [[littoral]]}} was constructed directly from the {{m+|la|lītus||shore}} based on its stem ''lītor-'' (as found for example in the genitive singular {{m|la|lītoris}}). Write this as follows: {{demo|<nowiki>{{af|it|la:[[lītus|lītoris]]<t:shore>|-aneo}}</nowiki>|indent=:}} The use of the bracketed expression allows us to display the accusative singular form while linking to the lemma form (the nominative singular). This could also be implemented using the <code><alt:...></code> modifier. 4. The Portuguese toponym {{m|pt|Nova Escócia||[[Nova Scotia]]}} is composed of two words, literally meaning "New Scotland". This can be written as follows: {{demo|<nowiki>{{af|pt|nova<pos:feminine of {{m|pt|novo|t=new}}>|Escócia<t:Scotland>}}</nowiki>|indent=:}} Here, we use the <code><pos:...></code> ("part of speech") modifier to display the grammatical derivation of the word {{m|pt|nova}}. This example shows that arbitrary template code can be embedded inside an inline modifier. 5. For the Japanese term {{m|ja|粉|tr=kona|t=powder}}, the following is an actual etymology: {{demo|<nowiki>Appears to be {{af|ja|sort=こな|粉<tr:ko><t:powder><ng:see above>|<alt:な><tr:na><pos:suffixing element><ng:meaning unclear>}}.</nowiki>|indent=:}} The use of the <code><alt:...></code> modifier with an empty term serves to prevent the term from being linked. The {{para|sort}} parameter is needed in general with any Japanese templates that generate categories, because the sort key for this language cannot be automatically generated. (It is based on the pronunciation of the term, and many Japanese terms have multiple pronunciations.) 6. An example of using {{cd|<type:...>}}, for {{m+|tl|sumasaibabaw}}: {{demo|<nowiki>From {{af|tl|sa-|ibabaw|-um-<type:infix>}} with initial {{rdp|tl|nocap=1}}.</nowiki>|indent=:}} ==Inline modifiers== All of the per-term parameters described above can alternatively be specified as ''inline modifiers'', using a syntax like <code>детекти́в<tr:dɛtɛktív><t:detective></code> to specify modifiers such as transliterations, glosses and qualifiers. In this example, for the Russian term {{m|ru|детекти́в|tr=dɛtɛktív|t=detective}}, the manual transliteration ''dɛtɛktív'' and gloss "detective" are given. Specifically, the following modifiers are recognized; see the above documentation for more information on the exact meaning of each modifier. * <code>t</code> or <code>gloss</code>: gloss * <code>alt</code>: alternative display text * <code>tr</code>: transliteration * <code>ts</code>: transcription, for languages where the transliteration and pronunciation are markedly different * <code>q</code>: qualifier, e.g. ''high-register''; this appears before the term, parenthesized and italicized * <code>qq</code>: qualifier, e.g. ''high-register''; this appears after the term, parenthesized and italicized * <code>l</code>: comma-separated label(s), e.g. ''rare''; these appear before the term, parenthesized, italicized and appropriately linked * <code>ll</code>: comma-separated label(s), e.g. ''rare''; these appear after the term, parenthesized, italicized and appropriately linked * <code>ref</code>: reference(s), as in {{tl|IPA}} * <code>lit</code>: literal meaning * <code>pos</code>: part of speech * <code>type</code>: affix type (''not'' compound/etymology type) * <code>g</code>: comma-separated list of gender/number specifications * <code>id</code>: sense ID; see {{temp|senseid}} * <code>lang</code>: language code * <code>sc</code>: script code ===Examples=== The following: <pre> From {{af|pt|Patrícia|t1=Patricia|pos1=given name|-inha|pos2=diminutive suffix}}. </pre> can be equivalently written as follows using inline modifiers: <pre> From {{af|pt|Patrícia<t:Patricia><pos:given name>|-inha<pos:diminutive suffix>}}. </pre> Both produce the following: From {{af|pt|Patrícia<t:Patricia><pos:given name>|-inha<pos:diminutive suffix>}}. Note how the use of inline modifiers frees you from having to make sure the numbers of indexed parameters like {{para|t1}}, {{para|pos2}} correctly line up with the terms they are referring to. ==Categories== The template will automatically categorize the entry based on the types of affixes it sees. * If a part begins with a hyphen, it is a suffix. * If a part ends with a hyphen, it's a prefix. * If a part has a hyphen at both ends, it's an interfix. This behavior can be overridden using the inline modifier <code><type:TYPE></code> (or just <code><TYPE></code> for short). This should be used, for example, for Proto-Indo-European roots, which are conventionally written with a trailing hyphen but aren't prefixes, and for certain Korean suffixes such as {{m|ko|-고-}} that are written with a hypen on both ends. The recognized affix types are {|class="wikitable" | {{cd|prefix}} or {{cd|pre}} || prefix |- | {{cd|suffix}} or {{cd|suf}} || suffix |- | {{cd|infix}} or {{cd|in}} || infix |- | {{cd|interfix}} or {{cd|inter}} || interfix |- | {{cd|circumfix}} or {{cd|circum}} || circumfix |- | {{cd|non-affix}} or {{cd|naf}} or {{cd|root}} || non-affix |} What is considered a hyphen depends on the specified language, so it can also support language-specific types of hyphen. In particular, the Hebrew script has its own script-specific hyphen character (which has the correct right-to-left behavior). The Arabic script does not traditionally use hyphens, though some languages have elected to use the kashida ({{lang|ar|ـ}}) for this purpose. Some languages (e.g. most East Asian languages) don't use hyphens with affixes. For these languages, you should still add a regular hyphen (<code>-</code>) to the affix as appropriate, but the term will be displayed and linked without a hyphen. ==Compound subtypes== The {{para|type}} parameter can be used to specify the subtype of compound when {{temp|affix}} is used to specify the parts of a compound. For example, if {{para|type|bahuvrihi}} is given (or {{para|type|bahu}} or {{para|type|bv}}), extra text ''{{glossary|bahuvrihi|Bahuvrīhi}} compound of'' is generated before the listed parts (where the word [[bahuvrihi|bahuvrīhi]] links appropriately to the appendix, with an explanation of what this term means). In addition, the page is placed in a type-specific category, e.g. [[:Category:Hindi bahuvrihi compounds]] if the language in question is Hindi (code <code>hi</code>). The parameter {{para|nocap|1}} can be used to disable capitalization of the first letter of the extra text generated, and {{para|notext|1}} can be used to suppress the extra text entirely. Using {{para|type}} along with {{para|notext}} is still useful because of the extra type-specific category that the page is placed in. It's also possible to use {{para|type}} without any parts, e.g. {{temp|affix|hi|type=bahuvrihi}}. This generates just the extra text (without the word ''of'' after it), and places the page in the type-specific category. The following types are currently supported: {{#invoke:affix doc|etymology_type_table}} ==Limitations== * If an entry both begins and ends with a hyphen, it is considered an interfix, not an infix. Use {{tl|infix}} for infixes. ==See also== * {{temp|prefix}} * {{temp|compound}} * {{temp|confix}} * {{temp|suffix}} * {{temp|infix}} * {{temp|surf}} == Template Data == {{TemplateData header}} <templatedata> { "params": { "1": { "label": "language code", "type": "string", "required": true, "aliases": [ "lang" ], "description": "the 2- or 3-letter language code for the current section", "example": "en" }, "2": { "label": "first part", "type": "wiki-page-name", "suggested": true, "description": "the first part of the affixed word", "example": "neuro" }, "3": { "label": "second part", "type": "wiki-page-name", "suggested": true, "description": "the second part of the affixed word", "example": "genic" }, "sc": { "label": "script code", "type": "string" }, "pos1": { "label": "first part of speech", "type": "string" }, "pos2": { "label": "second part of speech", "type": "string" }, "alt1": { "label": "first part alternative text", "type": "string", "description": "Text to show instead of the first part for the link to its entry" }, "alt2": { "label": "second part alternative text", "type": "string", "description": "Text to show instead of the second part for the link to its entry" }, "t1": { "label": "first gloss", "type": "string", "description": "brief gloss of the first part" }, "t2": { "label": "second gloss", "type": "string", "description": "brief gloss of the second part" }, "tr1": { "label": "first part transliteration", "type": "string", "description": "Transliteration of the first part (for non-Latin scripts)" }, "tr2": { "label": "second part transliteration", "type": "string", "description": "Transliteration of the second part (for non-Latin scripts)" } }, "format": "inline" } </templatedata> <includeonly> [[Category:Morphology templates]] </includeonly> e318djimflk95xnpxwxedmtp3rihrsm 239018 239017 2026-11-15T03:49:27Z Lee 19 [[:en:Template:affix/documentation]] වෙතින් එක් සංශෝධනයක් 239017 wikitext text/x-wiki {{documentation subpage}} {{uses lua|affix|affix/templates}} {{shortcut|Template:af}} This template displays the [[morpheme]]s (parts) that compose a word and categorizes its affixes, used in [[Wiktionary:Etymology|etymology sections]]. Despite the name, this template may be used for compounds similar to {{temp|compound}}. ==Parameters== ; {{para|1}} : The language code. See [[Wiktionary:Languages]]. ; {{para|2}}, {{para|3}} etc. : The parts of the terms to show. Either: :# At least one of the provided parts must begin or end with a hyphen (prefix, suffix, interfix); :# or there must be two or more parts (it may be a compound, with or without prefixes, suffixes, interfixes). : A term can begin with a language code followed by a colon. This overrides the default provided by {{para|1}}. When this is provided, the language name is displayed before the part, and a derivational category is also added to the entry. This is used for the occasional term which was directly affixed at the time of borrowing, and for which no native base form existed at the time, such as {{m|en|vexillology}}. ; {{para|pos}} : The part of speech to include in the category names, in plural form. Defaults to <code>terms</code>. This is separate from (and conceptually very different from) the {{para|pos<var>N</var>}} parameters, which specify clarifying parts of speech or similar descriptive text to display in parentheses after individual terms, next to the gloss. ; {{para|lit}} : The literal meaning of the overall term. This is separate from the {{para|lit<var>N</var>}} parameters, which specify literal meanings of individual parts. ; {{para|sort}} : The sort key to use when placing the entry in categories. This is rarely needed, as the default generated sort key is usually correct. ; {{para|sc}} : The script code. See [[Wiktionary:Scripts]]. This is rarely needed as the script can generally be automatically detected. This is separate from the {{para|sc<var>N</var>}} parameters, which specify script codes for individual parts in languages distinct from the overall language specified using {{para|1}}. ; {{para|nocat|1}} : Do not add categories to the entry. ; {{para|type}} : Type of compound, e.g. [[bahuvrihi]] or [[alliterative]]. See [[#Compound subtypes]] below. If this parameter is given, extra text is generated before the listed parts (e.g. ''{{glossary|bahuvrihi|Bahuvrīhi}} compound of FOO + BAR''), and the page is placed in an additional category (e.g. [[:Category:Hindi bahuvrihi compounds]]). ; {{para|nocap|1}} : Do not capitalize the first letter of the extra text generated by {{para|type}}. ; {{para|notext|1}} : When {{para|type}} is used, do not generate the extra text that is normally placed before the listed parts. The page will still be placed in the additional type-specific category unless {{para|nocat|1}} is given. The following parameters are available for each matching part in the numbered/positional parameters. The <code><var>N</var></code> must be replaced by the corresponding part index. For example, for the second part (positional parameter 3), use 2 for <code><var>N</var></code>. Most of these parameters correspond directly to the equivalent parameters in the standard {{temp|l}} (and {{temp|m}}) template. ; {{para|alt<var>N</var>}} : The alternative display form. Equivalent to the third parameter of {{temp|l}}. ; {{para|t<var>N</var>}} : A gloss to show after the part. Equivalent to the fourth parameter of {{temp|l}}. <small>The parameter {{para|gloss<var>N</var>}} is deprecated for this purpose.</small> ; {{para|ng<var>N</var>}} : Arbitrary explanatory text, placed after the gloss in plain text. Prefer to use this over {{para|pos<var>N</var>}} for anything other than purely grammatical uses. ; {{para|tr<var>N</var>}} : The transliteration, as in {{temp|l}}. ; {{para|ts<var>N</var>}} : The transcription, in languages where the transliteration and transcription differ markedly, as in {{temp|l}}. ; {{para|g<var>N</var>}} : The gender (multiple comma-separated genders may be specified for a given part). ; {{para|id<var>N</var>}} : The sense id, as in {{temp|l}}. As distinguished by mere linking templates, the affix template, categorizing terms by affix, also adds the sense id to the category name to distinguish various purposes of the same affix shape, hence the sense id in the dictionary entry for the affix should have a reasonable name in respect to this categorization. Changes the category name from <code><var>language name</var> terms <var>affix</var>ed with <var>affix</var></code> to <code><var>language name</var> terms <var>affix</var>ed with <var>affix</var> (<var>value of id parameter</var>)</code>. ; {{para|pos<var>N</var>}} : The part of speech label to show after the part, as in {{temp|l}}. If this parameter contains <code>patronym(ic)</code>, the entry will be added to a [[:Category:Patronymics by language|language's patronymic category]]. If this parameter contains <code>diminutive</code> and the {{para|pos}} parameter is defined, the entry will be added to a diminutive part-of-speech category. For instance, the parameter values {{para|pos|noun}} and {{para|pos2|diminutive suffix}} will add an entry to the language's [[:Category:Diminutive nouns by language|diminutive nouns]] category. ; {{para|lit<var>N</var>}} : The literal meaning to show after the part, as in {{temp|l}}. ; {{para|type<var>N</var>}} : Override the affix type, e.g. {{para|type2|prefix}}. '''Not''' the same as the compound type specified using {{para|type}}. ; {{para|q<var>N</var>}} : Qualifier text to display before the part, in parens and normally italicized. ; {{para|qq<var>N</var>}} : Qualifier text to display after the part, in parens and normally italicized. ; {{para|l<var>N</var>}} : Comma-separated label(s) to display before the part, as in {{tl|lb}}. ; {{para|ll<var>N</var>}} : Comma-separated label(s) to display after the part, as in {{tl|lb}}. ; {{para|infl<var>N</var>}} : Ampersand-separated grammar tag(s) to display after the part, as in {{tl|inflection of}}. ; {{para|ref<var>N</var>}} : Reference(s) to display after the part, as in {{tl|IPA}}. ; {{para|lang<var>N</var>}} : The language code to use for this particular part. This overrides the default provided by {{para|1}}. When this is provided, the language name is displayed before the part, and a derivational category is also added to the entry. This is used for the occasional term which was directly affixed at the time of borrowing, and for which no native base form existed at the time, such as {{m|en|vexillology}}. ; {{para|sc<var>N</var>}} : The script code to use for this particular part. This overrides the default provided by {{para|sc}}. ==Examples== Basic examples: :{{temp|af|en|complete|-ness}} → {{af|en|complete|-ness}} :{{temp|af|en|pre-|date}} → {{af|en|pre-|date}} :{{temp|af|en|acro-|-nym}} → {{af|en|acro-|-nym}} :{{temp|af|en|pest|-i-|-cide}} → {{af|en|pest|-i-|-cide}} :{{temp|af|en|volley|ball}} → {{af|en|volley|ball}} :{{temp|af|en|small|en- -en}} → {{af|en|small|en- -en}} ===In foreign languages=== 1. For {{m+|pt|aviãozão||large plane}}, which can be viewed as being composed of {{m|pt|avião||plane}}, an interfix {{m|pt|-z-}} and an augmentative suffix {{m|pt|-ão}}, use the following: {{demo|<nowiki>{{af|pt|avião<t:plane>|-z-|-ão<pos:augmentative suffix>}}</nowiki>|indent=:}} This can equivalently be written using separate parameters (the older way of doing things) like this: :<code><nowiki>{{af|pt|avião|t1=plane|-z-|-ão|pos3=augmentative suffix}}</nowiki></code> 2. The Portuguese medical term {{m|pt|acromia||[[achromia]] (lack of pigmentation)}} can be viewed as being composed directly from {{m+|grc|χρῶμα||color}} using the Portuguese [[privative]] (i.e. expressing "lack of") suffix {{m|pt|a-}} and the abstract noun suffix {{m|pt|-ia}}. Write this as follows: {{demo|<nowiki>{{af|pt|a-<id:privative>|grc:χρῶμα<t:color>|-ia}}</nowiki>|indent=:}} In this case, there are multiple Portuguese prefixes spelled {{m|pt|a-}}, with different origins and meanings. To identify the privative prefix specifically, we use the <code><id:...></code> modifier (see {{tl|senseid}}). 3. The Italian relational adjective {{m|it|litoraneo||coastal, [[littoral]]}} was constructed directly from the {{m+|la|lītus||shore}} based on its stem ''lītor-'' (as found for example in the genitive singular {{m|la|lītoris}}). Write this as follows: {{demo|<nowiki>{{af|it|la:[[lītus|lītoris]]<t:shore>|-aneo}}</nowiki>|indent=:}} The use of the bracketed expression allows us to display the accusative singular form while linking to the lemma form (the nominative singular). This could also be implemented using the <code><alt:...></code> modifier. 4. The Portuguese toponym {{m|pt|Nova Escócia||[[Nova Scotia]]}} is composed of two words, literally meaning "New Scotland". This can be written as follows: {{demo|<nowiki>{{af|pt|nova<pos:feminine of {{m|pt|novo|t=new}}>|Escócia<t:Scotland>}}</nowiki>|indent=:}} Here, we use the <code><pos:...></code> ("part of speech") modifier to display the grammatical derivation of the word {{m|pt|nova}}. This example shows that arbitrary template code can be embedded inside an inline modifier. 5. For the Japanese term {{m|ja|粉|tr=kona|t=powder}}, the following is an actual etymology: {{demo|<nowiki>Appears to be {{af|ja|sort=こな|粉<tr:ko><t:powder><ng:see above>|<alt:な><tr:na><pos:suffixing element><ng:meaning unclear>}}.</nowiki>|indent=:}} The use of the <code><alt:...></code> modifier with an empty term serves to prevent the term from being linked. The {{para|sort}} parameter is needed in general with any Japanese templates that generate categories, because the sort key for this language cannot be automatically generated. (It is based on the pronunciation of the term, and many Japanese terms have multiple pronunciations.) 6. An example of using {{cd|<type:...>}}, for {{m+|tl|sumasaibabaw}}: {{demo|<nowiki>From {{af|tl|sa-|ibabaw|-um-<type:infix>}} with initial {{rdp|tl|nocap=1}}.</nowiki>|indent=:}} ==Inline modifiers== All of the per-term parameters described above can alternatively be specified as ''inline modifiers'', using a syntax like <code>детекти́в<tr:dɛtɛktív><t:detective></code> to specify modifiers such as transliterations, glosses and qualifiers. In this example, for the Russian term {{m|ru|детекти́в|tr=dɛtɛktív|t=detective}}, the manual transliteration ''dɛtɛktív'' and gloss "detective" are given. Specifically, the following modifiers are recognized; see the above documentation for more information on the exact meaning of each modifier. * <code>t</code> or <code>gloss</code>: gloss * <code>alt</code>: alternative display text * <code>tr</code>: transliteration * <code>ts</code>: transcription, for languages where the transliteration and pronunciation are markedly different * <code>q</code>: qualifier, e.g. ''high-register''; this appears before the term, parenthesized and italicized * <code>qq</code>: qualifier, e.g. ''high-register''; this appears after the term, parenthesized and italicized * <code>l</code>: comma-separated label(s), e.g. ''rare''; these appear before the term, parenthesized, italicized and appropriately linked * <code>ll</code>: comma-separated label(s), e.g. ''rare''; these appear after the term, parenthesized, italicized and appropriately linked * <code>ref</code>: reference(s), as in {{tl|IPA}} * <code>lit</code>: literal meaning * <code>pos</code>: part of speech * <code>type</code>: affix type (''not'' compound/etymology type) * <code>g</code>: comma-separated list of gender/number specifications * <code>id</code>: sense ID; see {{temp|senseid}} * <code>lang</code>: language code * <code>sc</code>: script code ===Examples=== The following: <pre> From {{af|pt|Patrícia|t1=Patricia|pos1=given name|-inha|pos2=diminutive suffix}}. </pre> can be equivalently written as follows using inline modifiers: <pre> From {{af|pt|Patrícia<t:Patricia><pos:given name>|-inha<pos:diminutive suffix>}}. </pre> Both produce the following: From {{af|pt|Patrícia<t:Patricia><pos:given name>|-inha<pos:diminutive suffix>}}. Note how the use of inline modifiers frees you from having to make sure the numbers of indexed parameters like {{para|t1}}, {{para|pos2}} correctly line up with the terms they are referring to. ==Categories== The template will automatically categorize the entry based on the types of affixes it sees. * If a part begins with a hyphen, it is a suffix. * If a part ends with a hyphen, it's a prefix. * If a part has a hyphen at both ends, it's an interfix. This behavior can be overridden using the inline modifier <code><type:TYPE></code> (or just <code><TYPE></code> for short). This should be used, for example, for Proto-Indo-European roots, which are conventionally written with a trailing hyphen but aren't prefixes, and for certain Korean suffixes such as {{m|ko|-고-}} that are written with a hypen on both ends. The recognized affix types are {|class="wikitable" | {{cd|prefix}} or {{cd|pre}} || prefix |- | {{cd|suffix}} or {{cd|suf}} || suffix |- | {{cd|infix}} or {{cd|in}} || infix |- | {{cd|interfix}} or {{cd|inter}} || interfix |- | {{cd|circumfix}} or {{cd|circum}} || circumfix |- | {{cd|non-affix}} or {{cd|naf}} or {{cd|root}} || non-affix |} What is considered a hyphen depends on the specified language, so it can also support language-specific types of hyphen. In particular, the Hebrew script has its own script-specific hyphen character (which has the correct right-to-left behavior). The Arabic script does not traditionally use hyphens, though some languages have elected to use the kashida ({{lang|ar|ـ}}) for this purpose. Some languages (e.g. most East Asian languages) don't use hyphens with affixes. For these languages, you should still add a regular hyphen (<code>-</code>) to the affix as appropriate, but the term will be displayed and linked without a hyphen. ==Compound subtypes== The {{para|type}} parameter can be used to specify the subtype of compound when {{temp|affix}} is used to specify the parts of a compound. For example, if {{para|type|bahuvrihi}} is given (or {{para|type|bahu}} or {{para|type|bv}}), extra text ''{{glossary|bahuvrihi|Bahuvrīhi}} compound of'' is generated before the listed parts (where the word [[bahuvrihi|bahuvrīhi]] links appropriately to the appendix, with an explanation of what this term means). In addition, the page is placed in a type-specific category, e.g. [[:Category:Hindi bahuvrihi compounds]] if the language in question is Hindi (code <code>hi</code>). The parameter {{para|nocap|1}} can be used to disable capitalization of the first letter of the extra text generated, and {{para|notext|1}} can be used to suppress the extra text entirely. Using {{para|type}} along with {{para|notext}} is still useful because of the extra type-specific category that the page is placed in. It's also possible to use {{para|type}} without any parts, e.g. {{temp|affix|hi|type=bahuvrihi}}. This generates just the extra text (without the word ''of'' after it), and places the page in the type-specific category. The following types are currently supported: {{#invoke:affix doc|etymology_type_table}} ==Limitations== * If an entry both begins and ends with a hyphen, it is considered an interfix, not an infix. Use {{tl|infix}} for infixes. ==See also== * {{temp|prefix}} * {{temp|compound}} * {{temp|confix}} * {{temp|suffix}} * {{temp|infix}} * {{temp|surf}} == Template Data == {{TemplateData header}} <templatedata> { "params": { "1": { "label": "language code", "type": "string", "required": true, "aliases": [ "lang" ], "description": "the 2- or 3-letter language code for the current section", "example": "en" }, "2": { "label": "first part", "type": "wiki-page-name", "suggested": true, "description": "the first part of the affixed word", "example": "neuro" }, "3": { "label": "second part", "type": "wiki-page-name", "suggested": true, "description": "the second part of the affixed word", "example": "genic" }, "sc": { "label": "script code", "type": "string" }, "pos1": { "label": "first part of speech", "type": "string" }, "pos2": { "label": "second part of speech", "type": "string" }, "alt1": { "label": "first part alternative text", "type": "string", "description": "Text to show instead of the first part for the link to its entry" }, "alt2": { "label": "second part alternative text", "type": "string", "description": "Text to show instead of the second part for the link to its entry" }, "t1": { "label": "first gloss", "type": "string", "description": "brief gloss of the first part" }, "t2": { "label": "second gloss", "type": "string", "description": "brief gloss of the second part" }, "tr1": { "label": "first part transliteration", "type": "string", "description": "Transliteration of the first part (for non-Latin scripts)" }, "tr2": { "label": "second part transliteration", "type": "string", "description": "Transliteration of the second part (for non-Latin scripts)" } }, "format": "inline" } </templatedata> <includeonly> [[Category:Morphology templates]] </includeonly> e318djimflk95xnpxwxedmtp3rihrsm 239031 239018 2026-11-15T04:11:28Z Lee 19 /* Examples */ 239031 wikitext text/x-wiki {{documentation subpage}} {{uses lua|affix|affix/templates}} {{shortcut|Template:af}} This template displays the [[morpheme]]s (parts) that compose a word and categorizes its affixes, used in [[Wiktionary:Etymology|etymology sections]]. Despite the name, this template may be used for compounds similar to {{temp|compound}}. ==Parameters== ; {{para|1}} : The language code. See [[Wiktionary:Languages]]. ; {{para|2}}, {{para|3}} etc. : The parts of the terms to show. Either: :# At least one of the provided parts must begin or end with a hyphen (prefix, suffix, interfix); :# or there must be two or more parts (it may be a compound, with or without prefixes, suffixes, interfixes). : A term can begin with a language code followed by a colon. This overrides the default provided by {{para|1}}. When this is provided, the language name is displayed before the part, and a derivational category is also added to the entry. This is used for the occasional term which was directly affixed at the time of borrowing, and for which no native base form existed at the time, such as {{m|en|vexillology}}. ; {{para|pos}} : The part of speech to include in the category names, in plural form. Defaults to <code>terms</code>. This is separate from (and conceptually very different from) the {{para|pos<var>N</var>}} parameters, which specify clarifying parts of speech or similar descriptive text to display in parentheses after individual terms, next to the gloss. ; {{para|lit}} : The literal meaning of the overall term. This is separate from the {{para|lit<var>N</var>}} parameters, which specify literal meanings of individual parts. ; {{para|sort}} : The sort key to use when placing the entry in categories. This is rarely needed, as the default generated sort key is usually correct. ; {{para|sc}} : The script code. See [[Wiktionary:Scripts]]. This is rarely needed as the script can generally be automatically detected. This is separate from the {{para|sc<var>N</var>}} parameters, which specify script codes for individual parts in languages distinct from the overall language specified using {{para|1}}. ; {{para|nocat|1}} : Do not add categories to the entry. ; {{para|type}} : Type of compound, e.g. [[bahuvrihi]] or [[alliterative]]. See [[#Compound subtypes]] below. If this parameter is given, extra text is generated before the listed parts (e.g. ''{{glossary|bahuvrihi|Bahuvrīhi}} compound of FOO + BAR''), and the page is placed in an additional category (e.g. [[:Category:Hindi bahuvrihi compounds]]). ; {{para|nocap|1}} : Do not capitalize the first letter of the extra text generated by {{para|type}}. ; {{para|notext|1}} : When {{para|type}} is used, do not generate the extra text that is normally placed before the listed parts. The page will still be placed in the additional type-specific category unless {{para|nocat|1}} is given. The following parameters are available for each matching part in the numbered/positional parameters. The <code><var>N</var></code> must be replaced by the corresponding part index. For example, for the second part (positional parameter 3), use 2 for <code><var>N</var></code>. Most of these parameters correspond directly to the equivalent parameters in the standard {{temp|l}} (and {{temp|m}}) template. ; {{para|alt<var>N</var>}} : The alternative display form. Equivalent to the third parameter of {{temp|l}}. ; {{para|t<var>N</var>}} : A gloss to show after the part. Equivalent to the fourth parameter of {{temp|l}}. <small>The parameter {{para|gloss<var>N</var>}} is deprecated for this purpose.</small> ; {{para|ng<var>N</var>}} : Arbitrary explanatory text, placed after the gloss in plain text. Prefer to use this over {{para|pos<var>N</var>}} for anything other than purely grammatical uses. ; {{para|tr<var>N</var>}} : The transliteration, as in {{temp|l}}. ; {{para|ts<var>N</var>}} : The transcription, in languages where the transliteration and transcription differ markedly, as in {{temp|l}}. ; {{para|g<var>N</var>}} : The gender (multiple comma-separated genders may be specified for a given part). ; {{para|id<var>N</var>}} : The sense id, as in {{temp|l}}. As distinguished by mere linking templates, the affix template, categorizing terms by affix, also adds the sense id to the category name to distinguish various purposes of the same affix shape, hence the sense id in the dictionary entry for the affix should have a reasonable name in respect to this categorization. Changes the category name from <code><var>language name</var> terms <var>affix</var>ed with <var>affix</var></code> to <code><var>language name</var> terms <var>affix</var>ed with <var>affix</var> (<var>value of id parameter</var>)</code>. ; {{para|pos<var>N</var>}} : The part of speech label to show after the part, as in {{temp|l}}. If this parameter contains <code>patronym(ic)</code>, the entry will be added to a [[:Category:Patronymics by language|language's patronymic category]]. If this parameter contains <code>diminutive</code> and the {{para|pos}} parameter is defined, the entry will be added to a diminutive part-of-speech category. For instance, the parameter values {{para|pos|noun}} and {{para|pos2|diminutive suffix}} will add an entry to the language's [[:Category:Diminutive nouns by language|diminutive nouns]] category. ; {{para|lit<var>N</var>}} : The literal meaning to show after the part, as in {{temp|l}}. ; {{para|type<var>N</var>}} : Override the affix type, e.g. {{para|type2|prefix}}. '''Not''' the same as the compound type specified using {{para|type}}. ; {{para|q<var>N</var>}} : Qualifier text to display before the part, in parens and normally italicized. ; {{para|qq<var>N</var>}} : Qualifier text to display after the part, in parens and normally italicized. ; {{para|l<var>N</var>}} : Comma-separated label(s) to display before the part, as in {{tl|lb}}. ; {{para|ll<var>N</var>}} : Comma-separated label(s) to display after the part, as in {{tl|lb}}. ; {{para|infl<var>N</var>}} : Ampersand-separated grammar tag(s) to display after the part, as in {{tl|inflection of}}. ; {{para|ref<var>N</var>}} : Reference(s) to display after the part, as in {{tl|IPA}}. ; {{para|lang<var>N</var>}} : The language code to use for this particular part. This overrides the default provided by {{para|1}}. When this is provided, the language name is displayed before the part, and a derivational category is also added to the entry. This is used for the occasional term which was directly affixed at the time of borrowing, and for which no native base form existed at the time, such as {{m|en|vexillology}}. ; {{para|sc<var>N</var>}} : The script code to use for this particular part. This overrides the default provided by {{para|sc}}. {{af|en|complete|-ness}} ==Inline modifiers== All of the per-term parameters described above can alternatively be specified as ''inline modifiers'', using a syntax like <code>детекти́в<tr:dɛtɛktív><t:detective></code> to specify modifiers such as transliterations, glosses and qualifiers. In this example, for the Russian term {{m|ru|детекти́в|tr=dɛtɛktív|t=detective}}, the manual transliteration ''dɛtɛktív'' and gloss "detective" are given. Specifically, the following modifiers are recognized; see the above documentation for more information on the exact meaning of each modifier. * <code>t</code> or <code>gloss</code>: gloss * <code>alt</code>: alternative display text * <code>tr</code>: transliteration * <code>ts</code>: transcription, for languages where the transliteration and pronunciation are markedly different * <code>q</code>: qualifier, e.g. ''high-register''; this appears before the term, parenthesized and italicized * <code>qq</code>: qualifier, e.g. ''high-register''; this appears after the term, parenthesized and italicized * <code>l</code>: comma-separated label(s), e.g. ''rare''; these appear before the term, parenthesized, italicized and appropriately linked * <code>ll</code>: comma-separated label(s), e.g. ''rare''; these appear after the term, parenthesized, italicized and appropriately linked * <code>ref</code>: reference(s), as in {{tl|IPA}} * <code>lit</code>: literal meaning * <code>pos</code>: part of speech * <code>type</code>: affix type (''not'' compound/etymology type) * <code>g</code>: comma-separated list of gender/number specifications * <code>id</code>: sense ID; see {{temp|senseid}} * <code>lang</code>: language code * <code>sc</code>: script code ===Examples=== The following: <pre> From {{af|pt|Patrícia|t1=Patricia|pos1=given name|-inha|pos2=diminutive suffix}}. </pre> can be equivalently written as follows using inline modifiers: <pre> From {{af|pt|Patrícia<t:Patricia><pos:given name>|-inha<pos:diminutive suffix>}}. </pre> Both produce the following: From {{af|pt|Patrícia<t:Patricia><pos:given name>|-inha<pos:diminutive suffix>}}. Note how the use of inline modifiers frees you from having to make sure the numbers of indexed parameters like {{para|t1}}, {{para|pos2}} correctly line up with the terms they are referring to. ==Categories== The template will automatically categorize the entry based on the types of affixes it sees. * If a part begins with a hyphen, it is a suffix. * If a part ends with a hyphen, it's a prefix. * If a part has a hyphen at both ends, it's an interfix. This behavior can be overridden using the inline modifier <code><type:TYPE></code> (or just <code><TYPE></code> for short). This should be used, for example, for Proto-Indo-European roots, which are conventionally written with a trailing hyphen but aren't prefixes, and for certain Korean suffixes such as {{m|ko|-고-}} that are written with a hypen on both ends. The recognized affix types are {|class="wikitable" | {{cd|prefix}} or {{cd|pre}} || prefix |- | {{cd|suffix}} or {{cd|suf}} || suffix |- | {{cd|infix}} or {{cd|in}} || infix |- | {{cd|interfix}} or {{cd|inter}} || interfix |- | {{cd|circumfix}} or {{cd|circum}} || circumfix |- | {{cd|non-affix}} or {{cd|naf}} or {{cd|root}} || non-affix |} What is considered a hyphen depends on the specified language, so it can also support language-specific types of hyphen. In particular, the Hebrew script has its own script-specific hyphen character (which has the correct right-to-left behavior). The Arabic script does not traditionally use hyphens, though some languages have elected to use the kashida ({{lang|ar|ـ}}) for this purpose. Some languages (e.g. most East Asian languages) don't use hyphens with affixes. For these languages, you should still add a regular hyphen (<code>-</code>) to the affix as appropriate, but the term will be displayed and linked without a hyphen. ==Compound subtypes== The {{para|type}} parameter can be used to specify the subtype of compound when {{temp|affix}} is used to specify the parts of a compound. For example, if {{para|type|bahuvrihi}} is given (or {{para|type|bahu}} or {{para|type|bv}}), extra text ''{{glossary|bahuvrihi|Bahuvrīhi}} compound of'' is generated before the listed parts (where the word [[bahuvrihi|bahuvrīhi]] links appropriately to the appendix, with an explanation of what this term means). In addition, the page is placed in a type-specific category, e.g. [[:Category:Hindi bahuvrihi compounds]] if the language in question is Hindi (code <code>hi</code>). The parameter {{para|nocap|1}} can be used to disable capitalization of the first letter of the extra text generated, and {{para|notext|1}} can be used to suppress the extra text entirely. Using {{para|type}} along with {{para|notext}} is still useful because of the extra type-specific category that the page is placed in. It's also possible to use {{para|type}} without any parts, e.g. {{temp|affix|hi|type=bahuvrihi}}. This generates just the extra text (without the word ''of'' after it), and places the page in the type-specific category. The following types are currently supported: {{#invoke:affix doc|etymology_type_table}} ==Limitations== * If an entry both begins and ends with a hyphen, it is considered an interfix, not an infix. Use {{tl|infix}} for infixes. ==See also== * {{temp|prefix}} * {{temp|compound}} * {{temp|confix}} * {{temp|suffix}} * {{temp|infix}} * {{temp|surf}} == Template Data == {{TemplateData header}} <templatedata> { "params": { "1": { "label": "language code", "type": "string", "required": true, "aliases": [ "lang" ], "description": "the 2- or 3-letter language code for the current section", "example": "en" }, "2": { "label": "first part", "type": "wiki-page-name", "suggested": true, "description": "the first part of the affixed word", "example": "neuro" }, "3": { "label": "second part", "type": "wiki-page-name", "suggested": true, "description": "the second part of the affixed word", "example": "genic" }, "sc": { "label": "script code", "type": "string" }, "pos1": { "label": "first part of speech", "type": "string" }, "pos2": { "label": "second part of speech", "type": "string" }, "alt1": { "label": "first part alternative text", "type": "string", "description": "Text to show instead of the first part for the link to its entry" }, "alt2": { "label": "second part alternative text", "type": "string", "description": "Text to show instead of the second part for the link to its entry" }, "t1": { "label": "first gloss", "type": "string", "description": "brief gloss of the first part" }, "t2": { "label": "second gloss", "type": "string", "description": "brief gloss of the second part" }, "tr1": { "label": "first part transliteration", "type": "string", "description": "Transliteration of the first part (for non-Latin scripts)" }, "tr2": { "label": "second part transliteration", "type": "string", "description": "Transliteration of the second part (for non-Latin scripts)" } }, "format": "inline" } </templatedata> <includeonly> [[Category:Morphology templates]] </includeonly> dvtz9e5hiizasbnytcqy3652fnw5e93 239034 239031 2026-11-15T04:14:17Z Lee 19 [[Special:Contributions/Lee|Lee]] මගින් සිදුකල [[Special:Diff/239031|239031]] සංශෝධනය අහෝසි කරන්න ([[User talk:Lee|සාකච්ඡා]]) 239034 wikitext text/x-wiki {{documentation subpage}} {{uses lua|affix|affix/templates}} {{shortcut|Template:af}} This template displays the [[morpheme]]s (parts) that compose a word and categorizes its affixes, used in [[Wiktionary:Etymology|etymology sections]]. Despite the name, this template may be used for compounds similar to {{temp|compound}}. ==Parameters== ; {{para|1}} : The language code. See [[Wiktionary:Languages]]. ; {{para|2}}, {{para|3}} etc. : The parts of the terms to show. Either: :# At least one of the provided parts must begin or end with a hyphen (prefix, suffix, interfix); :# or there must be two or more parts (it may be a compound, with or without prefixes, suffixes, interfixes). : A term can begin with a language code followed by a colon. This overrides the default provided by {{para|1}}. When this is provided, the language name is displayed before the part, and a derivational category is also added to the entry. This is used for the occasional term which was directly affixed at the time of borrowing, and for which no native base form existed at the time, such as {{m|en|vexillology}}. ; {{para|pos}} : The part of speech to include in the category names, in plural form. Defaults to <code>terms</code>. This is separate from (and conceptually very different from) the {{para|pos<var>N</var>}} parameters, which specify clarifying parts of speech or similar descriptive text to display in parentheses after individual terms, next to the gloss. ; {{para|lit}} : The literal meaning of the overall term. This is separate from the {{para|lit<var>N</var>}} parameters, which specify literal meanings of individual parts. ; {{para|sort}} : The sort key to use when placing the entry in categories. This is rarely needed, as the default generated sort key is usually correct. ; {{para|sc}} : The script code. See [[Wiktionary:Scripts]]. This is rarely needed as the script can generally be automatically detected. This is separate from the {{para|sc<var>N</var>}} parameters, which specify script codes for individual parts in languages distinct from the overall language specified using {{para|1}}. ; {{para|nocat|1}} : Do not add categories to the entry. ; {{para|type}} : Type of compound, e.g. [[bahuvrihi]] or [[alliterative]]. See [[#Compound subtypes]] below. If this parameter is given, extra text is generated before the listed parts (e.g. ''{{glossary|bahuvrihi|Bahuvrīhi}} compound of FOO + BAR''), and the page is placed in an additional category (e.g. [[:Category:Hindi bahuvrihi compounds]]). ; {{para|nocap|1}} : Do not capitalize the first letter of the extra text generated by {{para|type}}. ; {{para|notext|1}} : When {{para|type}} is used, do not generate the extra text that is normally placed before the listed parts. The page will still be placed in the additional type-specific category unless {{para|nocat|1}} is given. The following parameters are available for each matching part in the numbered/positional parameters. The <code><var>N</var></code> must be replaced by the corresponding part index. For example, for the second part (positional parameter 3), use 2 for <code><var>N</var></code>. Most of these parameters correspond directly to the equivalent parameters in the standard {{temp|l}} (and {{temp|m}}) template. ; {{para|alt<var>N</var>}} : The alternative display form. Equivalent to the third parameter of {{temp|l}}. ; {{para|t<var>N</var>}} : A gloss to show after the part. Equivalent to the fourth parameter of {{temp|l}}. <small>The parameter {{para|gloss<var>N</var>}} is deprecated for this purpose.</small> ; {{para|ng<var>N</var>}} : Arbitrary explanatory text, placed after the gloss in plain text. Prefer to use this over {{para|pos<var>N</var>}} for anything other than purely grammatical uses. ; {{para|tr<var>N</var>}} : The transliteration, as in {{temp|l}}. ; {{para|ts<var>N</var>}} : The transcription, in languages where the transliteration and transcription differ markedly, as in {{temp|l}}. ; {{para|g<var>N</var>}} : The gender (multiple comma-separated genders may be specified for a given part). ; {{para|id<var>N</var>}} : The sense id, as in {{temp|l}}. As distinguished by mere linking templates, the affix template, categorizing terms by affix, also adds the sense id to the category name to distinguish various purposes of the same affix shape, hence the sense id in the dictionary entry for the affix should have a reasonable name in respect to this categorization. Changes the category name from <code><var>language name</var> terms <var>affix</var>ed with <var>affix</var></code> to <code><var>language name</var> terms <var>affix</var>ed with <var>affix</var> (<var>value of id parameter</var>)</code>. ; {{para|pos<var>N</var>}} : The part of speech label to show after the part, as in {{temp|l}}. If this parameter contains <code>patronym(ic)</code>, the entry will be added to a [[:Category:Patronymics by language|language's patronymic category]]. If this parameter contains <code>diminutive</code> and the {{para|pos}} parameter is defined, the entry will be added to a diminutive part-of-speech category. For instance, the parameter values {{para|pos|noun}} and {{para|pos2|diminutive suffix}} will add an entry to the language's [[:Category:Diminutive nouns by language|diminutive nouns]] category. ; {{para|lit<var>N</var>}} : The literal meaning to show after the part, as in {{temp|l}}. ; {{para|type<var>N</var>}} : Override the affix type, e.g. {{para|type2|prefix}}. '''Not''' the same as the compound type specified using {{para|type}}. ; {{para|q<var>N</var>}} : Qualifier text to display before the part, in parens and normally italicized. ; {{para|qq<var>N</var>}} : Qualifier text to display after the part, in parens and normally italicized. ; {{para|l<var>N</var>}} : Comma-separated label(s) to display before the part, as in {{tl|lb}}. ; {{para|ll<var>N</var>}} : Comma-separated label(s) to display after the part, as in {{tl|lb}}. ; {{para|infl<var>N</var>}} : Ampersand-separated grammar tag(s) to display after the part, as in {{tl|inflection of}}. ; {{para|ref<var>N</var>}} : Reference(s) to display after the part, as in {{tl|IPA}}. ; {{para|lang<var>N</var>}} : The language code to use for this particular part. This overrides the default provided by {{para|1}}. When this is provided, the language name is displayed before the part, and a derivational category is also added to the entry. This is used for the occasional term which was directly affixed at the time of borrowing, and for which no native base form existed at the time, such as {{m|en|vexillology}}. ; {{para|sc<var>N</var>}} : The script code to use for this particular part. This overrides the default provided by {{para|sc}}. ==Examples== Basic examples: :{{temp|af|en|complete|-ness}} → {{af|en|complete|-ness}} :{{temp|af|en|pre-|date}} → {{af|en|pre-|date}} :{{temp|af|en|acro-|-nym}} → {{af|en|acro-|-nym}} :{{temp|af|en|pest|-i-|-cide}} → {{af|en|pest|-i-|-cide}} :{{temp|af|en|volley|ball}} → {{af|en|volley|ball}} :{{temp|af|en|small|en- -en}} → {{af|en|small|en- -en}} ===In foreign languages=== 1. For {{m+|pt|aviãozão||large plane}}, which can be viewed as being composed of {{m|pt|avião||plane}}, an interfix {{m|pt|-z-}} and an augmentative suffix {{m|pt|-ão}}, use the following: {{demo|<nowiki>{{af|pt|avião<t:plane>|-z-|-ão<pos:augmentative suffix>}}</nowiki>|indent=:}} This can equivalently be written using separate parameters (the older way of doing things) like this: :<code><nowiki>{{af|pt|avião|t1=plane|-z-|-ão|pos3=augmentative suffix}}</nowiki></code> 2. The Portuguese medical term {{m|pt|acromia||[[achromia]] (lack of pigmentation)}} can be viewed as being composed directly from {{m+|grc|χρῶμα||color}} using the Portuguese [[privative]] (i.e. expressing "lack of") suffix {{m|pt|a-}} and the abstract noun suffix {{m|pt|-ia}}. Write this as follows: {{demo|<nowiki>{{af|pt|a-<id:privative>|grc:χρῶμα<t:color>|-ia}}</nowiki>|indent=:}} In this case, there are multiple Portuguese prefixes spelled {{m|pt|a-}}, with different origins and meanings. To identify the privative prefix specifically, we use the <code><id:...></code> modifier (see {{tl|senseid}}). 3. The Italian relational adjective {{m|it|litoraneo||coastal, [[littoral]]}} was constructed directly from the {{m+|la|lītus||shore}} based on its stem ''lītor-'' (as found for example in the genitive singular {{m|la|lītoris}}). Write this as follows: {{demo|<nowiki>{{af|it|la:[[lītus|lītoris]]<t:shore>|-aneo}}</nowiki>|indent=:}} The use of the bracketed expression allows us to display the accusative singular form while linking to the lemma form (the nominative singular). This could also be implemented using the <code><alt:...></code> modifier. 4. The Portuguese toponym {{m|pt|Nova Escócia||[[Nova Scotia]]}} is composed of two words, literally meaning "New Scotland". This can be written as follows: {{demo|<nowiki>{{af|pt|nova<pos:feminine of {{m|pt|novo|t=new}}>|Escócia<t:Scotland>}}</nowiki>|indent=:}} Here, we use the <code><pos:...></code> ("part of speech") modifier to display the grammatical derivation of the word {{m|pt|nova}}. This example shows that arbitrary template code can be embedded inside an inline modifier. 5. For the Japanese term {{m|ja|粉|tr=kona|t=powder}}, the following is an actual etymology: {{demo|<nowiki>Appears to be {{af|ja|sort=こな|粉<tr:ko><t:powder><ng:see above>|<alt:な><tr:na><pos:suffixing element><ng:meaning unclear>}}.</nowiki>|indent=:}} The use of the <code><alt:...></code> modifier with an empty term serves to prevent the term from being linked. The {{para|sort}} parameter is needed in general with any Japanese templates that generate categories, because the sort key for this language cannot be automatically generated. (It is based on the pronunciation of the term, and many Japanese terms have multiple pronunciations.) 6. An example of using {{cd|<type:...>}}, for {{m+|tl|sumasaibabaw}}: {{demo|<nowiki>From {{af|tl|sa-|ibabaw|-um-<type:infix>}} with initial {{rdp|tl|nocap=1}}.</nowiki>|indent=:}} ==Inline modifiers== All of the per-term parameters described above can alternatively be specified as ''inline modifiers'', using a syntax like <code>детекти́в<tr:dɛtɛktív><t:detective></code> to specify modifiers such as transliterations, glosses and qualifiers. In this example, for the Russian term {{m|ru|детекти́в|tr=dɛtɛktív|t=detective}}, the manual transliteration ''dɛtɛktív'' and gloss "detective" are given. Specifically, the following modifiers are recognized; see the above documentation for more information on the exact meaning of each modifier. * <code>t</code> or <code>gloss</code>: gloss * <code>alt</code>: alternative display text * <code>tr</code>: transliteration * <code>ts</code>: transcription, for languages where the transliteration and pronunciation are markedly different * <code>q</code>: qualifier, e.g. ''high-register''; this appears before the term, parenthesized and italicized * <code>qq</code>: qualifier, e.g. ''high-register''; this appears after the term, parenthesized and italicized * <code>l</code>: comma-separated label(s), e.g. ''rare''; these appear before the term, parenthesized, italicized and appropriately linked * <code>ll</code>: comma-separated label(s), e.g. ''rare''; these appear after the term, parenthesized, italicized and appropriately linked * <code>ref</code>: reference(s), as in {{tl|IPA}} * <code>lit</code>: literal meaning * <code>pos</code>: part of speech * <code>type</code>: affix type (''not'' compound/etymology type) * <code>g</code>: comma-separated list of gender/number specifications * <code>id</code>: sense ID; see {{temp|senseid}} * <code>lang</code>: language code * <code>sc</code>: script code ===Examples=== The following: <pre> From {{af|pt|Patrícia|t1=Patricia|pos1=given name|-inha|pos2=diminutive suffix}}. </pre> can be equivalently written as follows using inline modifiers: <pre> From {{af|pt|Patrícia<t:Patricia><pos:given name>|-inha<pos:diminutive suffix>}}. </pre> Both produce the following: From {{af|pt|Patrícia<t:Patricia><pos:given name>|-inha<pos:diminutive suffix>}}. Note how the use of inline modifiers frees you from having to make sure the numbers of indexed parameters like {{para|t1}}, {{para|pos2}} correctly line up with the terms they are referring to. ==Categories== The template will automatically categorize the entry based on the types of affixes it sees. * If a part begins with a hyphen, it is a suffix. * If a part ends with a hyphen, it's a prefix. * If a part has a hyphen at both ends, it's an interfix. This behavior can be overridden using the inline modifier <code><type:TYPE></code> (or just <code><TYPE></code> for short). This should be used, for example, for Proto-Indo-European roots, which are conventionally written with a trailing hyphen but aren't prefixes, and for certain Korean suffixes such as {{m|ko|-고-}} that are written with a hypen on both ends. The recognized affix types are {|class="wikitable" | {{cd|prefix}} or {{cd|pre}} || prefix |- | {{cd|suffix}} or {{cd|suf}} || suffix |- | {{cd|infix}} or {{cd|in}} || infix |- | {{cd|interfix}} or {{cd|inter}} || interfix |- | {{cd|circumfix}} or {{cd|circum}} || circumfix |- | {{cd|non-affix}} or {{cd|naf}} or {{cd|root}} || non-affix |} What is considered a hyphen depends on the specified language, so it can also support language-specific types of hyphen. In particular, the Hebrew script has its own script-specific hyphen character (which has the correct right-to-left behavior). The Arabic script does not traditionally use hyphens, though some languages have elected to use the kashida ({{lang|ar|ـ}}) for this purpose. Some languages (e.g. most East Asian languages) don't use hyphens with affixes. For these languages, you should still add a regular hyphen (<code>-</code>) to the affix as appropriate, but the term will be displayed and linked without a hyphen. ==Compound subtypes== The {{para|type}} parameter can be used to specify the subtype of compound when {{temp|affix}} is used to specify the parts of a compound. For example, if {{para|type|bahuvrihi}} is given (or {{para|type|bahu}} or {{para|type|bv}}), extra text ''{{glossary|bahuvrihi|Bahuvrīhi}} compound of'' is generated before the listed parts (where the word [[bahuvrihi|bahuvrīhi]] links appropriately to the appendix, with an explanation of what this term means). In addition, the page is placed in a type-specific category, e.g. [[:Category:Hindi bahuvrihi compounds]] if the language in question is Hindi (code <code>hi</code>). The parameter {{para|nocap|1}} can be used to disable capitalization of the first letter of the extra text generated, and {{para|notext|1}} can be used to suppress the extra text entirely. Using {{para|type}} along with {{para|notext}} is still useful because of the extra type-specific category that the page is placed in. It's also possible to use {{para|type}} without any parts, e.g. {{temp|affix|hi|type=bahuvrihi}}. This generates just the extra text (without the word ''of'' after it), and places the page in the type-specific category. The following types are currently supported: {{#invoke:affix doc|etymology_type_table}} ==Limitations== * If an entry both begins and ends with a hyphen, it is considered an interfix, not an infix. Use {{tl|infix}} for infixes. ==See also== * {{temp|prefix}} * {{temp|compound}} * {{temp|confix}} * {{temp|suffix}} * {{temp|infix}} * {{temp|surf}} == Template Data == {{TemplateData header}} <templatedata> { "params": { "1": { "label": "language code", "type": "string", "required": true, "aliases": [ "lang" ], "description": "the 2- or 3-letter language code for the current section", "example": "en" }, "2": { "label": "first part", "type": "wiki-page-name", "suggested": true, "description": "the first part of the affixed word", "example": "neuro" }, "3": { "label": "second part", "type": "wiki-page-name", "suggested": true, "description": "the second part of the affixed word", "example": "genic" }, "sc": { "label": "script code", "type": "string" }, "pos1": { "label": "first part of speech", "type": "string" }, "pos2": { "label": "second part of speech", "type": "string" }, "alt1": { "label": "first part alternative text", "type": "string", "description": "Text to show instead of the first part for the link to its entry" }, "alt2": { "label": "second part alternative text", "type": "string", "description": "Text to show instead of the second part for the link to its entry" }, "t1": { "label": "first gloss", "type": "string", "description": "brief gloss of the first part" }, "t2": { "label": "second gloss", "type": "string", "description": "brief gloss of the second part" }, "tr1": { "label": "first part transliteration", "type": "string", "description": "Transliteration of the first part (for non-Latin scripts)" }, "tr2": { "label": "second part transliteration", "type": "string", "description": "Transliteration of the second part (for non-Latin scripts)" } }, "format": "inline" } </templatedata> <includeonly> [[Category:Morphology templates]] </includeonly> e318djimflk95xnpxwxedmtp3rihrsm Module:affix 828 13847 239022 226982 2026-10-23T06:10:56Z en>Benwing2 0 allow ^ to signal empty term without [Term?] for emulation of {{suf}} and {{pre}} 239022 Scribunto text/plain local export = {} local debug_force_cat = false -- if set to true, always display categories even on userspace pages local m_links = require("Module:links") local m_str_utils = require("Module:string utilities") local m_table = require("Module:table") local decorations_module = "Module:decorations" local en_utilities_module = "Module:en-utilities" local etymology_module = "Module:etymology" local scripts_module = "Module:scripts" local utilities_module = "Module:utilities" -- Export this so the category code in [[Module:category tree/etymology]] can access it. export.affix_lang_data_module_prefix = "Module:affix/lang-data/" local ulen = m_str_utils.len local ufind = m_str_utils.find local umatch = m_str_utils.match local pluralize = require(en_utilities_module).pluralize local singularize = require(en_utilities_module).singularize local u = m_str_utils.char local ucfirst = m_str_utils.ucfirst local concat = table.concat local insert = table.insert local unpack = unpack or table.unpack -- Lua 5.2 compatibility function export.affix_variants(canonical, variants) local mappings = {} for _, variant in ipairs(variants) do mappings[variant] = canonical end return mappings end function export.id_mapping(default, ids) local mapping = { default = default } if ids then for id, target in pairs(ids) do mapping[id] = target end end return mapping end function export.id_mapping_with_affix_variants(base, id_variants) local mappings = {} for id, variants in pairs(id_variants) do for _, variant in ipairs(variants) do mappings[variant] = export.id_mapping(base, {[id] = base}) end end return mappings end function export.merge_tables(...) local result = {} for i = 1, select('#', ...) do local t = select(i, ...) if t then for k, v in pairs(t) do result[k] = v end end end return result end -- Export this so the category code in [[Module:category tree/etymology]] can access it. export.langs_with_lang_specific_data = { ["az"] = true, ["fi"] = true, ["fr"] = true, ["izh"] = true, ["la"] = true, ["sah"] = true, ["tr"] = true, ["trk-pro"] = true, } local default_pos = "term" local function pluralize_pos(pos) return pluralize(singularize(pos)) end --[==[ intro: ===About different types of hyphens ("template", "display" and "lookup"):=== * The "template hyphen" is the per-script hyphen character that is used in template calls to indicate that a term is an affix. This is always a single Unicode char, but there may be multiple possible hyphens for a given script. Normally this is just the regular hyphen character "-", but for some non-Latin-script languages (currently only right-to-left languages), it is different. * The "display hyphen" is the string (which might be an empty string) that is added onto a term as displayed and linked, to indicate that a term is an affix. Currently this is always either the same as the template hyphen or an empty string, but the code below is written generally enough to handle arbitrary display hyphens. Specifically: *# For East Asian languages, the display hyphen is always blank. *# For Arabic-script languages, either tatweel (ـ) or ZWNJ (zero-width non-joiner) are allowed as template hyphens, where ZWNJ is supported primarily for Farsi, because some suffixes have non-joining behavior. The display hyphen corresponding to tatweel is also tatweel, but the display hyphen corresponding to ZWNJ is blank (tatweel is also the default display hyphen, for calls to {{tl|prefix}}/{{tl|suffix}}/etc. that don't include an explicit hyphen). * The "lookup hyphen" is the hyphen that is used when looking up language-specific affix mappings. (These mappings are discussed in more detail below when discussing link affixes.) It depends only on the script of the affix in question. Most scripts (including East Asian scripts) use a regular hyphen "-" as the lookup hyphen, but Hebrew and Arabic have their own lookup hyphens (respectively maqqef and tatweel). Note that for Arabic in particular, there are three possible template hyphens that are recognized (tatweel, ZWNJ and regular hyphen), but mappings must use tatweel. ===About different types of affixes ("template", "display", "link", "lookup" and "category"):=== * A "template affix" is an affix in its source form as it appears in a template call. Generally, a template affix has an attached template hyphen (see above) to indicate that it is an affix and indicate what type of affix it is (prefix, suffix, interfix or circumfix), but some of the older-style templates such as {{tl|suffix}}, {{tl|prefix}}, {{tl|confix}}, etc. have "positional" affixes where the presence of the affix in a certain position (e.g. the second or third parameter) indicates that it is a certain type of affix, whether or not it has an attached template hyphen. * A "display affix" is the corresponding affix as it is actually displayed to the user. The display affix may differ from the template affix for various reasons: *# The display affix may be specified explicitly using the {{para|alt<var>N</var>}} parameter, the `<alt:...>` inline modifier or a piped link of the form e.g. `<nowiki>[[-kas|-käs]]</nowiki>` (here indicating that the affix should display as `-käs` but be linked as `-kas`). Here, the template affix is arguably the entire piped link, while the display affix is `-käs`. *# Even in the absence of {{para|alt<var>N</var>}} parameters, `<alt:...>` inline modifiers and piped links, certain languages have differences between the "template hyphen" specified in the template (which always needs to be specified somehow or other in templates like {{tl|affix}}, to indicate that the term is an affix and what type of affix it is) and the display hyphen (see above), with corresponding differences between template and display affixes. * A (regular) "link affix" is the affix that is linked to when the affix is shown to the user. The link affix is usually the same as the display affix, but will differ in one of three circumstances: *# The display and link affixes are explicitly made different using {{para|alt<var>N</var>}} parameters, `<alt:...>` inline modifiers or piped links, as described above under "display affix". *# For certain languages, certain affixes are mapped to canonical form using language-specific mappings. For example, in Finnish, the adjective-forming suffix {{m|fi|-kas}} appears as {{m|fi|-käs}} after front vowels, but logically both forms are the same suffix and should be linked and categorized the same. Similarly, in Latin, the negative and intensive prefixes spelled {{m|la|in-}} (etymologically two distinct prefixes) appear variously as {{m|la|il-}}, {{m|la|im-}} or {{m|la|ir-}} before certain consonants. Mappings are supplied in [[Module:affix/lang-data/LANGCODE]] to convert Finnish {{m|fi|-käs}} to {{m|fi|-kas}} for linking and categorization purposes. Note that the affixes in the mappings use "lookup hyphens" to indicate the different types of affixes, which is usually the same as the template hyphen but differs for Arabic scripts, because there are multiple possible template hyphens recognized but only one lookup hyphen (tatweel). The form of the affix as used to look up in the mapping tables is called the "lookup affix"; see below. * A "stripped link affix" is a link affix that has been passed through the language's `stripDiacritics()` function, which may strip certain diacritics: e.g. macrons in Latin and Old English (indicating length); acute and grave accents in Russian and various other Slavic languages (indicating stress); vowel diacritics in most Arabic-script languages; and also tatweel in some Arabic-script languages (currently, for example, Persian, Arabic and Urdu strip tatweel, but Ottoman Turkish does not). Stripped link affixes are currently what are used in category names. * A "lookup affix" is the form of the affix as it is looked up in the language-specific lookup mappings described above under link affixes. There are actually two lookup stages: *# First, the affix is looked up in a modified display form (specifically, the same as the display affix but using lookup hyphens). Note that this lookup does not occur if an explicit display form is given using {{para|alt<var>N</var>}} or an `<alt:...>` inline modifier, or if the template affix contains a piped or embedded link. *# If no entry is found, the affix is then looked up in a modified link form (specifically, the modified display form passed through the language's `stripDiacritics()` function, which strips out certain diacritics, but with the lookup hyphen re-added if it was stripped out, as in the case of tatweel in many Arabic-script languages). The reason for this double lookup procedure is to allow for mappings that are sensitive to the extra diacritics, but also allow for mappings that are not sensitive in this fashion (e.g. Russian {{m|ru|-ливый}} occurs both stressed and unstressed, but is the same prefix either way). * A "category affix" is the affix as it appears in categories such as [[:Category:Finnish terms suffixed with -kas| Category:Finnish terms suffixed with ''-kas'']]. The category affix is currently always the same as the stripped link affix. This means that for Arabic-script languages, it may or may not have a tatweel, even if the correponding display affix and regular link affix have a tatweel. As mentioned above, stripDiacritics() strips tatweel for Arabic, Persian and Urdu, but not for Ottoman Turkish. Hence affix categories for Arabic, Persian and Urdu will be missing the tatweel, but affix categories for Ottoman Turkish will have it. An additional complication is that if the template affix contains a ZWNJ, the display (and hence the link and category affixes) will have no hyphen attached in any case. ]==] ----------------------------------------------------------------------------------------- -- Template and display hyphens -- ----------------------------------------------------------------------------------------- --[=[ Per-script template hyphens. The template hyphen is what appears in the {{affix}}/{{prefix}}/{{suffix}}/etc. template (in the wikicode). See above. They key below is a script code, after removing a hyphen and anything preceding. Hence, script codes like 'mnc-Mong' and 'xwo-Mong' will match 'Mong'. The value below is a string consisting of one or more hyphen characters. If there is more than one character, the default hyphen must come last and a non-default function must be specified for the script in display_hyphens[] so the correct display hyphen will be specified when no template hyphen is given (in {{suffix}}/{{prefix}}/etc.). Script detection is normally done when linking, but we need to do it earlier. However, under most circumstances we don't need to do script detection. Specifically, we only need to do script detection for a given language if (a) the language has multiple scripts; and (b) at least one of those scripts is listed below or in display_hyphens. ]=] local ZWNJ = u(0x200C) -- zero-width non-joiner local template_hyphens = { -- This covers all Arabic scripts. See above. ["Arab"] = "ـ" .. ZWNJ .. "-", -- tatweel + zero-width non-joiner + regular hyphen ["Aran"] = "ـ" .. ZWNJ .. "-", -- tatweel + zero-width non-joiner + regular hyphen ["Hebr"] = "־", -- Hebrew-specific hyphen termed "maqqef" ["Mong"] = "᠊", -- FIXME! What about the following right-to-left scripts? -- Adlm (Adlam) -- Armi (Imperial Aramaic) -- Avst (Avestan) -- Cprt (Cypriot) -- Khar (Kharoshthi) -- Mand (Mandaic/Mandaean) -- Mani (Manichaean) -- Mend (Mende/Mende Kikakui) -- Narb (Old North Arabian) -- Nbat (Nabataean/Nabatean) -- Nkoo (N'Ko) -- Orkh (Orkhon runes) -- Phli (Inscriptional Pahlavi) -- Phlp (Psalter Pahlavi) -- Phlv (Book Pahlavi) -- Phnx (Phoenician) -- Prti (Inscriptional Parthian) -- Rohg (Hanifi Rohingya) -- Samr (Samaritan) -- Sarb (Old South Arabian) -- Sogd (Sogdian) -- Sogo (Old Sogdian) -- Syrc (Syriac) -- Thaa (Thaana) } -- Hyphens used when looking up an affix in a lang-specific affix mapping. Defaults to regular hyphen (-). The keys -- are script codes, after removing a hyphen and anything preceding. Hence, script codes like 'mnc-Mong' and 'xwo-Mong' -- will match 'Mong'. The value should be a single character. local lookup_hyphens = { ["Hebr"] = "־", -- This covers all Arabic scripts. See above. ["Arab"] = "ـ", ["Aran"] = "ـ", } -- Default display-hyphen function. local function default_display_hyphen(script, hyph) if not hyph then return template_hyphens[script] or "-" end return hyph end local function arab_get_display_hyphen(_script, hyph) if not hyph then return "ـ" -- tatweel elseif hyph == ZWNJ then return "" else return hyph end end local function no_display_hyphen(_script, _hyph) return "" end -- Per-script function to return the correct display hyphen given the script and template hyphen. The function should -- also handle the case where the passed-in template hyphen is nil, corresponding to the situation in -- {{prefix}}/{{suffix}}/etc. where no template hyphen is specified. The key is the script code after removing a hyphen -- and anything preceding, so 'mnc-Mong', 'xwo-Mong' etc. will match 'Mong'. local display_hyphens = { -- This covers all Arabic scripts. See above. ["Arab"] = arab_get_display_hyphen, ["Aran"] = arab_get_display_hyphen, ["Bopo"] = no_display_hyphen, ["Hani"] = no_display_hyphen, ["Hans"] = no_display_hyphen, ["Hant"] = no_display_hyphen, -- The following is a mixture of several scripts. Hopefully the specs here are correct! ["Jpan"] = no_display_hyphen, ["Jurc"] = no_display_hyphen, ["Kitl"] = no_display_hyphen, ["Kits"] = no_display_hyphen, ["Laoo"] = no_display_hyphen, ["Nshu"] = no_display_hyphen, ["Shui"] = no_display_hyphen, ["Tang"] = no_display_hyphen, ["Thaa"] = no_display_hyphen, ["Thai"] = no_display_hyphen, ["Tibt"] = no_display_hyphen, } ----------------------------------------------------------------------------------------- -- Basic Utility functions -- ----------------------------------------------------------------------------------------- local function glossary_link(entry, text) text = text or entry return "[[Appendix:Glossary#" .. entry .. "|" .. text .. "]]" end local function track(page) if type(page) == "table" then for i, pg in ipairs(page) do page[i] = "affix/" .. pg end else page = "affix/" .. page end require("Module:debug/track")(page) end local function ine(val) return val ~= "" and val or nil end ----------------------------------------------------------------------------------------- -- Compound types -- ----------------------------------------------------------------------------------------- local function make_compound_type(typ, alttext) return { text = glossary_link(typ, alttext) .. " compound", cat = typ .. " compounds", } end -- Make a compound type entry with a simple rather than glossary link. -- These should be replaced with a glossary link when the entry in the glossary -- is created. local function make_non_glossary_compound_type(typ, alttext) local link = alttext and "[[" .. typ .. "|" .. alttext .. "]]" or "[[" .. typ .. "]]" return { text = link .. " compound", cat = typ .. " compounds", } end local function make_raw_compound_type(typ, alttext) return { text = glossary_link(typ, alttext), cat = pluralize(typ), } end local function make_borrowing_type(typ, alttext) return { text = glossary_link(typ, alttext), borrowing_type = pluralize(typ), } end export.etymology_types = { ["adapted borrowing"] = make_borrowing_type("adapted borrowing"), ["adap"] = "adapted borrowing", ["abor"] = "adapted borrowing", ["alliterative"] = make_non_glossary_compound_type("alliterative"), ["allit"] = "alliterative", ["antonymous"] = make_non_glossary_compound_type("antonymous"), ["ant"] = "antonymous", ["bahuvrihi"] = make_compound_type("bahuvrihi", "bahuvrīhi"), ["bahu"] = "bahuvrihi", ["bv"] = "bahuvrihi", ["coordinative"] = make_compound_type("coordinative"), ["coord"] = "coordinative", ["descriptive"] = make_compound_type("descriptive"), ["desc"] = "descriptive", ["determinative"] = make_compound_type("determinative"), ["det"] = "determinative", ["dvandva"] = make_compound_type("dvandva"), ["dva"] = "dvandva", ["dvigu"] = make_compound_type("dvigu"), ["dvi"] = "dvigu", ["endocentric"] = make_compound_type("endocentric"), ["endo"] = "endocentric", ["exocentric"] = make_compound_type("exocentric"), ["exo"] = "exocentric", ["izafet I"] = make_compound_type("izafet I"), ["iz1"] = "izafet I", ["izafet II"] = make_compound_type("izafet II"), ["iz2"] = "izafet II", ["izafet III"] = make_compound_type("izafet III"), ["iz3"] = "izafet III", ["karmadharaya"] = make_compound_type("karmadharaya", "karmadhāraya"), ["karma"] = "karmadharaya", ["kd"] = "karmadharaya", ["kenning"] = make_raw_compound_type("kenning"), ["ken"] = "kenning", ["rhyming"] = make_non_glossary_compound_type("rhyming"), ["rhy"] = "rhyming", ["synonymous"] = make_non_glossary_compound_type("synonymous"), ["syn"] = "synonymous", ["tatpurusa"] = make_compound_type("tatpurusa", "tatpuruṣa"), ["tat"] = "tatpurusa", ["tp"] = "tatpurusa", } local function process_etymology_type(typ, nocap, notext, has_parts) local text_sections = {} local categories = {} local borrowing_type if typ then local typdata = export.etymology_types[typ] if type(typdata) == "string" then typdata = export.etymology_types[typdata] end if not typdata then error("Internal error: Unrecognized type '" .. typ .. "'") end local text = typdata.text if not nocap then text = ucfirst(text) end local cat = typdata.cat borrowing_type = typdata.borrowing_type local oftext = typdata.oftext or " of" if not notext then insert(text_sections, text) if has_parts then insert(text_sections, oftext) insert(text_sections, " ") end end if cat then insert(categories, cat) end end return text_sections, categories, borrowing_type end ----------------------------------------------------------------------------------------- -- Utility functions -- ----------------------------------------------------------------------------------------- -- Iterate an array up to the greatest integer index found. local function ipairs_with_gaps(t) local indices = m_table.numKeys(t) local max_index = #indices > 0 and math.max(unpack(indices)) or 0 local i = 0 return function() if i < max_index then i = i + 1 return i, t[i] end end end export.ipairs_with_gaps = ipairs_with_gaps --[==[ Join formatted parts together with any overall {{para|lit}} spec, overall left and/or right qualifiers and labels, and categories. On input, `data` is a structure with the following fields: * `affixdata`: The affix data passed into an entry point such as `##show_affix()`; the code in this function examines the `lang`, `lit`, `force_cat`, `nocat`, `sort_key`, `q`, `qq`, `l` and `ll` fields of this structure, which represent overall values for these properties (as opposed to per-part values, which are found inside the list of per-part objects in `parts`, which are not examined); * `parts_formatted`: List of formatted parts, each a string; * `separator_already_added`: If true, any separators have already been included in `parts_formatted`, so the values should be concatenated with nothing in between; otherwise, the separator {" +&lrm; "} will be used, i.e. a `+` sign surrounded by spaces along with a Unicode left-to-right character to ensure that the parts appear in left-to-right order even if they contain right-to-left text; * `categories`: List of category strings or category objects; category strings are formatted using the `sort_key` field in the affix data structure in `affixdata`, while category objects, which are of the form `{ {cat=``category``, sort_key=``sort_key``, sort_base=``sort_base``}`, specify their own sort key and sort base; if `affixdata.nocat` is given, no categories are added; otherwise, `affixdata.force_cat` or global variable `debug_force_cat` causes categories to be added even on userspace pages. ]==] function export.join_formatted_parts(data) local cattext local affixdata = data.affixdata local lang = affixdata.lang local force_cat = affixdata.force_cat or debug_force_cat if affixdata.nocat then cattext = "" else for i, cat in ipairs(data.categories) do if type(cat) == "table" then data.categories[i] = require(utilities_module).format_categories(lang:getFullName() .. " " .. cat.cat, lang, cat.sort_key, cat.sort_base, force_cat) else data.categories[i] = require(utilities_module).format_categories(lang:getFullName() .. " " .. cat, lang, affixdata.sort_key, nil, force_cat) end end cattext = concat(data.categories) end local result = concat(data.parts_formatted, not data.separator_already_added and " +&lrm; " or nil) .. (affixdata.lit and ", literally " .. m_links.mark(affixdata.lit, "gloss") or "") local q = affixdata.q local qq = affixdata.qq local l = affixdata.l local ll = affixdata.ll if q and q[1] or qq and qq[1] or l and l[1] or ll and ll[1] then result = require(decorations_module).format_decorations { lang = lang, text = result, q = q, qq = qq, l = l, ll = ll, } end return result .. cattext end -- Remove links and call lang:stripDiacritics(term). local function strip_diacritics_no_links(lang, term) return lang:stripDiacritics(m_links.remove_links(term)) end --[=[ Convert a raw part as passed into an entry point into a part ready for linking. `lang` and `sc` are the overall language and script objects. This uses the overall language and script objects as defaults for the part and parses off any fragment from the term. We need to do the latter so that fragments don't end up in categories and so that we correctly do affix mapping even in the presence of fragments. ]=] local function canonicalize_part(part, lang, sc) if not part then return end -- Save the original (user-specified, part-specific) value of `lang`. If such a value is specified, we don't insert -- a '*fixed with' category, and we format the part using format_derived() in [[Module:etymology]] rather than -- full_link() in [[Module:links]]. part.part_lang = part.lang part.lang = part.lang or lang part.sc = part.sc or sc local term = part.term if not term then return elseif not part.fragment then part.term, part.fragment = m_links.get_fragment(term) else part.term = m_links.get_fragment(term) end end --[==[ Construct a single linked part based on the information in `part`, for use by `show_affix()` and other entry points. This should be called after `canonicalize_part()` is called on the part. This is a thin wrapper around `full_link()` in [[Module:links]] unless `part.part_lang` is specified (indicating that a part-specific language was given), in which case `format_derived()` in [[Module:etymology]] is called to display a term in a language other than the language of the overall term (specified in `data.lang`). `data` contains the entire object passed into the entry point and is used to access information for constructing the categories added by `format_derived()`. ]==] function export.link_term(part, data, include_separator) local result if part.part_lang then result = require(etymology_module).format_derived { lang = data.lang, terms = {part}, sources = {part.lang}, sort_key = data.sort_key, nocat = data.nocat, template_name = "affix", decorations_on_outside = true, borrowing_type = data.borrowing_type, force_cat = data.force_cat or debug_force_cat, } else result = m_links.full_link(part, "term") end if include_separator and part.separator then return part.separator .. result else return result end end local function canonicalize_script_code(scode) -- Convert 'mnc-Mong', 'xwo-Mong' etc. to 'Mong'. return (scode:gsub("^.*%-", "")) end ----------------------------------------------------------------------------------------- -- Affix-handling functions -- ----------------------------------------------------------------------------------------- -- Figure out the appropriate script for the given affix and language (unless the script is explicitly passed in), and -- return the values of template_hyphens[], display_hyphens[] and lookup_hyphens[] for that script, substituting -- default values as appropriate. Four values are returned: -- DETECTED_SCRIPT, TEMPLATE_HYPHEN, DISPLAY_HYPHEN, LOOKUP_HYPHEN local function detect_script_and_hyphens(text, lang, sc) local scode -- 1. If the script is explicitly passed in, use it. if sc then scode = sc:getCode() else local possible_script_codes = lang:getScriptCodes() -- YUCK! `possible_script_codes` comes from loadData() so #possible_scripts doesn't work (always returns 0). local num_possible_script_codes = m_table.length(possible_script_codes) if num_possible_script_codes == 0 then -- This shouldn't happen; if the language has no script codes, -- the list {"None"} should be returned. error("Something is majorly wrong! Language " .. lang:getCanonicalName() .. " has no script codes.") end if num_possible_script_codes == 1 then -- 2. If the language has only one possible script, use it. scode = possible_script_codes[1] else -- 3. Check if any of the possible scripts for the language have non-default values for template_hyphens[] -- or display_hyphens[]. If so, we need to do script detection on the text. If not, just use "Latn", -- which may not be technically correct but produces the right results because Latn has all default -- values for template_hyphens[] and display_hyphens[]. local may_have_nondefault_hyphen = false for _, script_code in ipairs(possible_script_codes) do script_code = canonicalize_script_code(script_code) if template_hyphens[script_code] or display_hyphens[script_code] then may_have_nondefault_hyphen = true break end end if not may_have_nondefault_hyphen then scode = "Latn" else scode = lang:findBestScript(text):getCode() end end end scode = canonicalize_script_code(scode) local template_hyphen = template_hyphens[scode] or "-" local lookup_hyphen = lookup_hyphens[scode] or "-" local display_hyphen = display_hyphens[scode] or default_display_hyphen return scode, template_hyphen, display_hyphen, lookup_hyphen end --[=[ Given a template affix `term` and an affix type `affix_type`, change the relevant template hyphen(s) in the affix to the display or lookup hyphen specified in `new_hyphen`, or add them if they are missing. `new_hyphen` can be a string, specifying a fixed hyphen, or a function of two arguments (the script code `scode` and the discovered template hyphen, or nil of no relevant template hyphen is present). `thyph_re` is a Lua pattern (which must be enclosed in parens) that matches the possible template hyphens. Note that not all template hyphens present in the affix are changed, but only the "relevant" ones (e.g. for a prefix, a relevant template hyphen is one coming at the end of the affix). ]=] local function reconstruct_term_per_hyphens(term, affix_type, scode, thyph_re, new_hyphen) local function get_hyphen(hyph) if type(new_hyphen) == "string" then return new_hyphen end return new_hyphen(scode, hyph) end if affix_type == "non-affix" then return term elseif affix_type == "circumfix" then local before, before_hyphen, after_hyphen, after = umatch(term, "^(.*)" .. thyph_re .. " " .. thyph_re .. "(.*)$") if not before or ulen(term) <= 3 then -- Unlike with other types of affixes, don't try to add hyphens in the middle of the term to convert it to -- a circumfix. Also, if the term is just hyphen + space + hyphen, return it. return term end return before .. get_hyphen(before_hyphen) .. " " .. get_hyphen(after_hyphen) .. after elseif affix_type == "infix" or affix_type == "interfix" then local before_hyphen, middle, after_hyphen = umatch(term, "^" .. thyph_re .. "(.*)" .. thyph_re .. "$") if before_hyphen and ulen(term) <= 1 then -- If the term is just a hyphen, return it. return term end return get_hyphen(before_hyphen) .. (middle or term) .. get_hyphen(after_hyphen) elseif affix_type == "prefix" then local middle, after_hyphen = umatch(term, "^(.*)" .. thyph_re .. "$") if middle and ulen(term) <= 1 then -- If the term is just a hyphen, return it. return term end return (middle or term) .. get_hyphen(after_hyphen) elseif affix_type == "suffix" then local before_hyphen, middle = umatch(term, "^" .. thyph_re .. "(.*)$") if before_hyphen and ulen(term) <= 1 then -- If the term is just a hyphen, return it. return term end return get_hyphen(before_hyphen) .. (middle or term) else error(("Internal error: Unrecognized affix type '%s'"):format(affix_type)) end end --[=[ Look up a mapping from a given affix variant to the canonical form used in categories and links. The lookup tables are language-specific according to `lang`, and may be ID-specific according to `affix_id`. The affixes as they appear in the lookup tables (both the variant and the canonical form) are in "lookup affix" format (approximately speaking, they use a regular hyphen for most scripts, but a tatweel for Arabic-script entries and a maqqef for Hebrew-script entries), but the passed-in `affix` param is in "template affix" format (which differs from the lookup affix for Arabic-script entries, because more types of hyphens are allowed in template affixes; see the comments at the top of the file). The remaining parameters to this function are used to convert from template affixes to lookup affixes; see the reconstruct_term_per_hyphens() function above. If the affix contains brackets, no lookup is done. Otherwise, a two-stage process is used, first looking up the affix directly and then stripping diacritics and looking it up again. The reason for this is documented above in the comments at the top of the file (specifically, the comments describing lookup affixes). The value of a mapping can either be a string (do the mapping regardless of affix ID) or a table indexed by affix ID (where the special value `false` indicates no affix ID). The values of entries in this table can also be strings, or tables with keys `affix` and `id` (again, use `false` to indicate no ID). This allows an affix mapping to map from one ID to another (for example, this is used in English to map the [[an-]] prefix with no ID to the [[a-]] prefix with the ID 'not'). The Given a template affix `term` and an affix type `affix_type`, change the relevant template hyphen(s) in the affix to the display or lookup hyphen specified in `new_hyphen`, or add them if they are missing. `new_hyphen` can be a string, specifying a fixed hyphen, or a function of two arguments (the script code `scode` and the discovered template hyphen, or nil of no relevant template hyphen is present). `thyph_re` is a Lua pattern (which must be enclosed in parens) that matches the possible template hyphens. Note that not all template hyphens present in the affix are changed, but only the "relevant" ones (e.g. for a prefix, a relevant template hyphen is one coming at the end of the affix). ]=] local function lookup_affix_mapping(affix, affix_type, lang, scode, thyph_re, lookup_hyph, affix_id) local function do_lookup(afx) -- Ensure that the affix uses lookup hyphens regardless of whether it used a different type of hyphens before -- or no hyphens. local lookup_affix = reconstruct_term_per_hyphens(afx, affix_type, scode, thyph_re, lookup_hyph) local function do_lookup_for_langcode(langcode) if export.langs_with_lang_specific_data[langcode] then local langdata = mw.loadData(export.affix_lang_data_module_prefix .. langcode) if langdata.affix_mappings then local mapping = langdata.affix_mappings[lookup_affix] if mapping then if type(mapping) == "table" then mapping = mapping[affix_id] or mapping.default or mapping[affix_id or false] if mapping then return mapping end else return mapping end end end end end -- If `lang` is an etymology-only language, look for a mapping both for it and its full parent. local langcode = lang:getCode() local mapping = do_lookup_for_langcode(langcode) if mapping then return mapping end local full_langcode = lang:getFullCode() if full_langcode ~= langcode then mapping = do_lookup_for_langcode(full_langcode) if mapping then return mapping end end return nil end if affix:find("%[%[") then return nil end return do_lookup(affix) or do_lookup(lang:stripDiacritics(affix)) or nil end --[==[ For a given template term in a given language (see the definition of "template affix" near the top of the file), possibly in an explicitly specified script `sc` (but usually nil), return the term's affix type ({"prefix"}, {"interfix"}, {"suffix"}, {"circumfix"} or {"non-affix"}) along with the corresponding link and display affixes (see definitions near the top of the file); also the corresponding lookup affix (if `return_lookup_affix` is specified). The term passed in should already have any fragment (after the # sign) parsed off of it. Four values are returned: `affix_type`, `link_term`, `display_term` and `lookup_term`. The affix type can be passed in instead of autodetected; in this case, the template term need not have any attached hyphens, and the appropriate hyphens will be added in the appropriate places. If `do_affix_mapping` is specified, look up the affix in the lang-specific affix mappings, as described in the comment at the top of the file; otherwise, the link and display terms will always be the same. (They will be the same in any case if the template term has a bracketed link in it or is not an affix.) If `return_lookup_affix` is given, the fourth return value contains the term with appropriate lookup hyphens in the appropriate places; otherwise, it is the same as the display term. (This functionality is used in [[Module:category tree/affixes and compounds]] to convert link affixes into lookup affixes so that they can be looked up in the affix mapping tables.) Exported because used by [[Module:headword utilities]] to determine the affix type of a given pagename. ]==] function export.parse_term_for_affixes(term, lang, sc, affix_type, do_affix_mapping, return_lookup_affix, affix_id) if not term then return "non-affix", nil, nil, nil end if term == "^" then -- Indicates a null term to emulate the behavior of {{suffix|foo||bar}}. term = nil return "non-affix", term, term, term end if term:find("^%^") then -- HACK! ^ at the beginning of Korean languages has a special meaning, triggering capitalization of the -- transliteration. Don't interpret it as "force non-affix" for those languages. local langcode = lang:getCode() if langcode ~= "ko" and langcode ~= "okm" and langcode ~= "jje" then -- Formerly we allowed ^ to force non-affix type; this is now handled using an inline modifier -- <naf>, <root>, etc. Throw an error for the moment when the old way is encountered. error("Use of ^ to force non-affix status is no longer supported; use an inline modifier <naf> or <root> " .. "after the component") end end -- Remove an asterisk if the morpheme is reconstructed and add it back at the end. local reconstructed = "" if term:find("^%*") then reconstructed = "*" term = term:gsub("^%*", "") end local scode, thyph, dhyph, lhyph = detect_script_and_hyphens(term, lang, sc) thyph = "([" .. thyph .. "])" if not affix_type then if ufind(term, thyph .. " " .. thyph) then affix_type = "circumfix" else local has_beginning_hyphen = ufind(term, "^" .. thyph) local has_ending_hyphen = ufind(term, thyph .. "$") if has_beginning_hyphen and has_ending_hyphen then affix_type = "interfix" elseif has_ending_hyphen then affix_type = "prefix" elseif has_beginning_hyphen then affix_type = "suffix" else affix_type = "non-affix" end end end local link_term, display_term, lookup_term if affix_type == "non-affix" then link_term = term display_term = term lookup_term = term else display_term = reconstruct_term_per_hyphens(term, affix_type, scode, thyph, dhyph) if do_affix_mapping then link_term = lookup_affix_mapping(term, affix_type, lang, scode, thyph, lhyph, affix_id) -- The return value of lookup_affix_mapping() may be an affix mapping with lookup hyphens if a mapping -- was found, otherwise nil if a mapping was not found. We need to convert to display hyphens in -- either case, but in the latter case we can reuse the display term, which has already been converted. if link_term then link_term = reconstruct_term_per_hyphens(link_term, affix_type, scode, thyph, dhyph) else link_term = display_term end else link_term = display_term end if return_lookup_affix then lookup_term = reconstruct_term_per_hyphens(term, affix_type, scode, thyph, lhyph) else lookup_term = display_term end end link_term = reconstructed .. link_term display_term = reconstructed .. display_term lookup_term = reconstructed .. lookup_term return affix_type, link_term, display_term, lookup_term end --[==[ Add a hyphen to a term in the appropriate place, based on the specified affix type, stripping off any existing hyphens in that place. For example, if `affix_type` == {"prefix"}, we'll add a hyphen onto the end if it's not already there (or is of the wrong type). Three values are returned: the link term, display term and lookup term. This function is a thin wrapper around `parse_term_for_affixes`; see the comments above that function for more information. Note that this function is exposed externally because it is called by [[Module:category tree/affixes and compounds]]; see the comment in `parse_term_for_affixes` for more information. ]==] function export.make_affix(term, lang, sc, affix_type, do_affix_mapping, return_lookup_affix, affix_id) if not (affix_type == "prefix" or affix_type == "suffix" or affix_type == "circumfix" or affix_type == "infix" or affix_type == "interfix" or affix_type == "non-affix") then error("Internal error: Invalid affix type " .. (affix_type or "(nil)")) end local _, link_term, display_term, lookup_term = export.parse_term_for_affixes(term, lang, sc, affix_type, do_affix_mapping, return_lookup_affix, affix_id) return link_term, display_term, lookup_term end ----------------------------------------------------------------------------------------- -- Categorization logic -- ----------------------------------------------------------------------------------------- local function insert_category(categories, cat, sort_key, sort_base) if sort_key or sort_base then insert(categories, {cat = cat, sort_key = sort_key, sort_base = sort_base}) else insert(categories, cat) end end --[=[ Insert a `*fixed with` category such as [[:Category:Welsh terms prefixed with gwe-]] into `categories`. The arguments are: * `categories`: List of category strings or objects to insert into. * `pos`: Part of speech in the category (which is often "terms" but may be something more specific). * `affix_type`: Affix type in the category (e.g. "prefix"); automatically has "ed" appended. * `link_term`: The term that appears in the category, e.g. "gwe-". If this is empty or missing, no category is inserted. * `part`: The part structure being processed. The `lang`, `part_lang`, `nocat` and `id` fields are fetched. * `sort_key`: The sort key for the specific category. If this or `sort_base` are non-nil, a category object is created holding the specified sort key and/or base, and inserted; otherwise, a cateory string is inserted. * `sort_base`: The sort base for the specific category. See `sort_key` just above. ]=] local function insert_affix_category(categories, pos, affix_type, link_term, part, sort_key, sort_base) -- Don't add a category if the link term is empty or is in a different language, or if <nocat:1> was specified for -- the part. if ine(link_term) and not part.part_lang and not part.nocat then local cat = pos .. " " .. affix_type .. "ed with " .. strip_diacritics_no_links(part.lang, link_term) .. (part.id and " (" .. part.id .. ")" or "") insert_category(categories, cat, sort_key, sort_base) end end --[=[ Generate the categories for a single part and insert into `categories`. The arguments are: * `categories` is the list to insert the categories into. * `data` is the overall affix data structure. * `part` is the per-part data structure. * `affix_type` is the type of affix (e.g. "prefix"), as appears in the `*fixed by` category. * `link_term` is the term that (prefix, suffix, etc.) mentioned in the `*fixed by` category. * `sort_key` and `sort_base` are the per-part sort keys and bases for categorization, or nil to use the overall sort key. ]=] local function generate_one_part_categories(categories, data, part, affix_type, link_term, sort_key, sort_base) if data.nocat or part.nocat then return end if part.pos and part.pos:find("patronym") then insert_category(categories, "patronymics", sort_key, sort_base) end if data.pos ~= "terms" and part.pos and part.pos:find("diminutive") then insert_category(categories, "diminutive " .. data.pos, sort_key, sort_base) end insert_affix_category(categories, data.pos, affix_type, link_term, part, sort_key, sort_base) end --[=[ Core categorization logic for affixes. This is shared between show_affix(), show_compound_like() and get_affix_categories_only(). Returns the categories array and other metadata needed for formatting. ]=] local function generate_affix_categories(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) local text_sections, categories, borrowing_type = process_etymology_type(data.type, data.surface_analysis or data.nocap, data.notext, #data.parts > 0) data.borrowing_type = borrowing_type -- Process each part local whole_words = 0 local is_affix_or_compound = false -- Canonicalize and generate links for all the parts first; then do categorization in a separate step, because when -- processing the first part for categorization, we may access the second part and need it already canonicalized. for i, part in ipairs_with_gaps(data.parts) do part = part or {} data.parts[i] = part canonicalize_part(part, data.lang, data.sc) -- Determine affix type and get link and display terms (see text at top of file). Store them in the part -- (in fields that won't clash with fields used by full_link() in [[Module:links]] or link_term()), so they -- can be used in the loop below when categorizing. part.affix_type, part.affix_link_term, part.affix_display_term = export.parse_term_for_affixes(part.term, part.lang, part.sc, part.type, not part.alt, nil, part.id) -- If link_term is an empty string, either a bare ^ was specified or an empty term was used along with inline -- modifiers. The intention in either case is not to link the term. part.term = ine(part.affix_link_term) -- If part.alt would be the same as part.term, make it nil, so that it isn't erroneously tracked as being -- redundant alt text. part.alt = part.alt or (part.affix_display_term ~= part.affix_link_term and part.affix_display_term) or nil end if not data.noaffixcat then -- Now do categorization. for i, part in ipairs_with_gaps(data.parts) do local affix_type = part.affix_type if affix_type ~= "non-affix" then is_affix_or_compound = true -- Make a sort key. For the first part, use the second part as the sort key; the intention is that if the -- term has a prefix, sorting by the prefix won't be very useful so we sort by what follows, which is -- presumably the root. local part_sort_base = nil local part_sort = part.sort or data.sort_key if i == 1 and data.parts[2] and data.parts[2].term then local part2 = data.parts[2] -- If the second-part link term is empty, the user requested an unlinked term; avoid a wikitext error -- by using the alt value if available. part_sort_base = ine(part2.affix_link_term) or ine(part2.alt) if part_sort_base then part_sort_base = strip_diacritics_no_links(part2.lang, part_sort_base) end end generate_one_part_categories(categories, data, part, affix_type, part.affix_link_term, part_sort, part_sort_base) else whole_words = whole_words + 1 if whole_words == 2 then is_affix_or_compound = true insert(categories, "compound " .. data.pos) end end end -- Make sure there was either an affix or a compound (two or more non-affix terms). if not is_affix_or_compound and not data.allow_no_affixes_or_compounds then error("The parameters did not include any affixes, and the term is not a compound. Please provide at least one affix.") end end return text_sections, categories, borrowing_type end -- Return true if specified part has no term or alt and no modifiers. WARNING: Keep this up-to-date -- in case any other fields are added that are always present. local function part_is_empty(part) for k, v in pairs(part) do if k ~= "affix_type" and k ~= "lang" and k ~= "orig_index" and k ~= "itemno" and k ~= "separator" then return false end end return true end ----------------------------------------------------------------------------------------- -- Main entry points -- ----------------------------------------------------------------------------------------- --[==[ Implementation of {{tl|affix}} and {{tl|surface analysis}}. `data` contains all the information describing the affixes to be displayed, and contains the following: * `.lang` ('''required'''): Overall language object. Different from term-specific language objects (see `.parts` below). * `.sc`: Overall script object (usually omitted). Different from term-specific script objects. * `.parts` ('''required'''): List of objects describing the affixes to show. The general format of each object is as would be passed to `full_link()`, except that the `.lang` field should be missing unless the term is of a language different from the overall `.lang` value (in such a case, the language name is shown along with the term and an additional "derived from" category is added). '''WARNING''': The data in `.parts` will be destructively modified. * `.pos`: Overall part of speech (used in categories, defaults to {"terms"}). Different from term-specific part of speech. * `.sort_key`: Overall sort key. Normally omitted except e.g. in Japanese. * `.type`: Type of compound, if the parts in `.parts` describe a compound. Strictly optional, and if supplied, the compound type is displayed before the parts (normally capitalized, unless `.nocap` is given). * `.nocap`: Don't capitalize the first letter of text displayed before the parts (relevant only if `.type` or `.surface_analysis` is given). * `.notext`: Don't display any text before the parts (relevant only if `.type` or `.surface_analysis` is given). * `.nocat`: Disable all categorization. * `.noaffixcat`: Disable affix (and compound) categorization. Relevant for e.g. blends, which may otherwise be incorrectly categorized as compound terms. * `.lit`: Overall literal definition. Different from term-specific literal definitions. * `.force_cat`: Always display categories, even on userspace pages. * `.surface_analysis`: Implement {{surface analysis}}; adds `By surface analysis, ` before the parts. '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.show_affix(data) local text_sections, categories, _ = generate_affix_categories(data) -- Process each part for display local parts_formatted = {} for i, part in ipairs_with_gaps(data.parts) do -- Make a link for the part if part_is_empty(part) then if part.separator then insert(parts_formatted, part.separator) end -- don't call full_link(); we allow this to emulate the behavior of {{suf}} and {{pre}} in such cases. else insert(parts_formatted, export.link_term(part, data, "include_separator")) end end if data.surface_analysis then local text = "by " .. glossary_link("surface analysis") .. ", " if not data.nocap then text = ucfirst(text) end insert(text_sections, 1, text) end insert(text_sections, export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories, separator_already_added = true }) return concat(text_sections) end --[==[ Get only the categories that would be generated by show_affix(), without any text output or formatting. This is used by Module:etymon to get affix categorization. Returns an array of category objects, where each entry is either a string (simple category name) or a table with keys `cat`, `sort_key`, and `sort_base` for more complex categorization. `data` should have the same structure as passed to show_affix(): * `.lang` (required): Overall language object * `.parts` (required): Array of affix part objects with `.term`, `.lang`, `.id`, etc. * `.pos`: Part of speech (defaults to "terms") * `.sort_key`: Overall sort key for categories '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.get_affix_categories_only(data) local _, categories, _ = generate_affix_categories(data) return categories end function export.show_surface_analysis(data) data.surface_analysis = true data.allow_no_affixes_or_compounds = true return export.show_affix(data) end --[==[ Implementation of {{tl|compound}}. '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.show_compound(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) local text_sections, categories, borrowing_type = process_etymology_type(data.type, data.nocap, data.notext, #data.parts > 0) data.borrowing_type = borrowing_type local parts_formatted = {} insert(categories, "compound " .. data.pos) -- Make links out of all the parts local whole_words = 0 for i, part in ipairs(data.parts) do canonicalize_part(part, data.lang, data.sc) -- Determine affix type and get link and display terms (see text at top of file). local affix_type, link_term, display_term = export.parse_term_for_affixes(part.term, part.lang, part.sc, part.type, not part.alt, nil, part.id) -- If the term is an interfix or the type was explicitly given, recognize it as such (which means e.g. that we -- will display the term without hyphens for East Asian languages). Otherwise, ignore the fact that it looks -- like an affix and display as specified in the template (but pay attention to the detected affix type for -- certain tracking purposes). if affix_type == "interfix" or (part.type and part.type ~= "non-affix") then -- Add a `*fixed with` category. However, if link_term is an empty string, either a bare ^ was specified or -- an empty term was used along with inline modifiers. The intention in either case is not to link the term. -- Don't add a category in this case, or if the term is in a different language (or if overall nocat=1 was -- given, or part-specific <nocat:1>). if not data.nocat then -- FIXME, should we be specifying a sort base here? insert_affix_category(categories, data.pos, affix_type, link_term, part, part.sort or data.sort_key) end -- If part.alt would be the same as part.term, make it nil, so that it isn't erroneously tracked as being -- redundant alt text. part.term = link_term ~= "" and link_term or nil part.alt = part.alt or (display_term ~= link_term and display_term) or nil else if affix_type ~= "non-affix" then local langcode = data.lang:getCode() -- If `data.lang` is an etymology-only language, track both using its code and its full parent's code. track { affix_type, affix_type .. "/lang/" .. langcode } local full_langcode = data.lang:getFullCode() if langcode ~= full_langcode then track(affix_type .. "/lang/" .. full_langcode) end else whole_words = whole_words + 1 end end insert(parts_formatted, export.link_term(part, data, "include_separator")) end if whole_words == 1 then track("one whole word") elseif whole_words == 0 then track("looks like confix") end insert(text_sections, export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories, separator_already_added = true }) return concat(text_sections) end --[==[ Implementation of {{tl|blend}}, {{tl|univerbation}} and similar "compound-like" templates. '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.show_compound_like(data) data.allow_no_affixes_or_compounds = true local text_sections, categories, _ = generate_affix_categories(data) if data.cat then insert(categories, data.cat) end -- Process each part for display local parts_formatted = {} for i, part in ipairs_with_gaps(data.parts) do -- Make a link for the part insert(parts_formatted, export.link_term(part, data, "include_separator")) end if #data.parts > 0 and data.oftext then insert(text_sections, 1, " " .. data.oftext .. " ") end if data.text then insert(text_sections, 1, data.text) end insert(text_sections, export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories, separator_already_added = true }) return concat(text_sections) end --[==[ Make `part` (a structure holding information on an affix part) into an affix of type `affix_type`, and apply any relevant affix mappings. For example, if the desired affix type is "suffix", this will (in general) add a hyphen onto the beginning of the term, alt, tr and ts components of the part if not already present. The hyphen that's added is the "display hyphen" (see above) and may be script-specific. (In the case of East Asian scripts, the display hyphen is an empty string whereas the template hyphen is the regular hyphen, meaning that any regular hyphen at the beginning of the part will be effectively removed.) `lang` and `sc` hold overall language and script objects. Note that this also applies any language-specific affix mappings, so that e.g. if the language is Finnish and the user specified [[-käs]] in the affix and didn't specify an `.alt` value, `part.term` will contain [[-kas]] and `part.alt` will contain [[-käs]]. This function is used by the "legacy" templates ({{tl|prefix}}, {{tl|suffix}}, {{tl|confix}}, etc.) where the nature of the affix is specified by the template itself rather than auto-determined from the affix, as is the case with {{tl|affix}}. '''WARNING''': This destructively modifies `part`. ]==] local function make_part_into_affix(part, lang, sc, affix_type) canonicalize_part(part, lang, sc) local link_term, display_term = export.make_affix(part.term, part.lang, part.sc, affix_type, not part.alt, nil, part.id) part.term = link_term -- When we don't specify `do_affix_mapping` to make_affix(), link and display terms (first and second retvals of -- make_affix()) are the same. -- If part.alt would be the same as part.term, make it nil, so that it isn't erroneously tracked as being -- redundant alt text. part.alt = part.alt and export.make_affix(part.alt, part.lang, part.sc, affix_type) or (display_term ~= link_term and display_term) or nil local Latn = require(scripts_module).getByCode("Latn") part.tr = export.make_affix(part.tr, part.lang, Latn, affix_type) part.ts = export.make_affix(part.ts, part.lang, Latn, affix_type) end local function track_wrong_affix_type(template, part, expected_affix_type) if part and not part.type then local affix_type = export.parse_term_for_affixes(part.term, part.lang, part.sc) if affix_type ~= expected_affix_type then local part_name = expected_affix_type or "base" local langcode = part.lang:getCode() local full_langcode = part.lang:getFullCode() require("Module:debug/track") { template, template .. "/" .. part_name, template .. "/" .. part_name .. "/" .. (affix_type or "none"), template .. "/" .. part_name .. "/" .. (affix_type or "none") .. "/lang/" .. langcode } -- If `part.lang` is an etymology-only language, track both using its code and its full parent's code. if full_langcode ~= langcode then require("Module:debug/track")( template .. "/" .. part_name .. "/" .. (affix_type or "none") .. "/lang/" .. full_langcode ) end end end end --[==[ Implementation of {{tl|confix}}. '''WARNING''': This destructively modifies both `data` and `.prefix`, `.base` and `.suffix`. ]==] function export.show_confix(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. make_part_into_affix(data.prefix, data.lang, data.sc, "prefix") make_part_into_affix(data.suffix, data.lang, data.sc, "suffix") track_wrong_affix_type("confix", data.prefix, "prefix") track_wrong_affix_type("confix", data.base, nil) track_wrong_affix_type("confix", data.suffix, "suffix") -- Make links out of all the parts. local parts_formatted = {} local prefix_sort_base if data.base and data.base.term then prefix_sort_base = strip_diacritics_no_links(data.base.lang, data.base.term) elseif data.suffix.term then prefix_sort_base = strip_diacritics_no_links(data.suffix.lang, data.suffix.term) end -- Insert the categories and parts. local categories = {} insert(parts_formatted, export.link_term(data.prefix, data)) insert_affix_category(categories, data.pos, "prefix", data.prefix.term, data.prefix, data.sort_key, prefix_sort_base) if data.base then insert(parts_formatted, export.link_term(data.base, data)) end insert(parts_formatted, export.link_term(data.suffix, data)) -- FIXME, should we be specifying a sort base here? insert_affix_category(categories, data.pos, "suffix", data.suffix.term, data.suffix) return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end --[==[ Implementation of {{tl|infix}}. '''WARNING''': This destructively modifies both `data` and `.base` and `.infix`. ]==] function export.show_infix(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. make_part_into_affix(data.infix, data.lang, data.sc, "infix") track_wrong_affix_type("infix", data.base, nil) track_wrong_affix_type("infix", data.infix, "infix") -- Make links out of all the parts. local parts_formatted = {} local categories = {} insert(parts_formatted, export.link_term(data.base, data)) insert(parts_formatted, export.link_term(data.infix, data)) -- Insert the categories. -- FIXME, should we be specifying a sort base here? insert_affix_category(categories, data.pos, "infix", data.infix.term, data.infix) return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end --[==[ Implementation of {{tl|prefix}}. '''WARNING''': This destructively modifies both `data` and the structures within `.prefixes`, as well as `.base`. ]==] function export.show_prefix(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. for i, prefix in ipairs(data.prefixes) do make_part_into_affix(prefix, data.lang, data.sc, "prefix") end for i, prefix in ipairs(data.prefixes) do track_wrong_affix_type("prefix", prefix, "prefix") end track_wrong_affix_type("prefix", data.base, nil) -- Make links out of all the parts. local parts_formatted = {} local first_sort_base = nil local categories = {} if data.prefixes[2] then first_sort_base = ine(data.prefixes[2].term) or ine(data.prefixes[2].alt) if first_sort_base then first_sort_base = strip_diacritics_no_links(data.prefixes[2].lang, first_sort_base) end elseif data.base then first_sort_base = ine(data.base.term) or ine(data.base.alt) if first_sort_base then first_sort_base = strip_diacritics_no_links(data.base.lang, first_sort_base) end end for i, prefix in ipairs(data.prefixes) do insert(parts_formatted, export.link_term(prefix, data)) generate_one_part_categories(categories, data, prefix, "prefix", prefix.term, data.sort_key, i == 1 and first_sort_base or nil) end if data.base then insert(parts_formatted, export.link_term(data.base, data)) else insert(parts_formatted, "") end return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end --[==[ Implementation of {{tl|suffix}}. '''WARNING''': This destructively modifies both `data` and the structures within `.suffixes`, as well as `.base`. ]==] function export.show_suffix(data) local categories = {} data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. for i, suffix in ipairs(data.suffixes) do make_part_into_affix(suffix, data.lang, data.sc, "suffix") end track_wrong_affix_type("suffix", data.base, nil) for i, suffix in ipairs(data.suffixes) do track_wrong_affix_type("suffix", suffix, "suffix") end -- Make links out of all the parts. local parts_formatted = {} if data.base then insert(parts_formatted, export.link_term(data.base, data)) else insert(parts_formatted, "") end for i, suffix in ipairs(data.suffixes) do insert(parts_formatted, export.link_term(suffix, data)) end -- Insert the categories. for i, suffix in ipairs(data.suffixes) do -- FIXME, should we be specifying a sort base here? generate_one_part_categories(categories, data, suffix, "suffix", suffix.term) end return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end return export 9xcovtr8fgpuq9eoxs0jleym6tojjsp 239023 239022 2026-11-15T04:01:53Z Lee 19 [[:en:Module:affix]] වෙතින් එක් සංශෝධනයක් 239022 Scribunto text/plain local export = {} local debug_force_cat = false -- if set to true, always display categories even on userspace pages local m_links = require("Module:links") local m_str_utils = require("Module:string utilities") local m_table = require("Module:table") local decorations_module = "Module:decorations" local en_utilities_module = "Module:en-utilities" local etymology_module = "Module:etymology" local scripts_module = "Module:scripts" local utilities_module = "Module:utilities" -- Export this so the category code in [[Module:category tree/etymology]] can access it. export.affix_lang_data_module_prefix = "Module:affix/lang-data/" local ulen = m_str_utils.len local ufind = m_str_utils.find local umatch = m_str_utils.match local pluralize = require(en_utilities_module).pluralize local singularize = require(en_utilities_module).singularize local u = m_str_utils.char local ucfirst = m_str_utils.ucfirst local concat = table.concat local insert = table.insert local unpack = unpack or table.unpack -- Lua 5.2 compatibility function export.affix_variants(canonical, variants) local mappings = {} for _, variant in ipairs(variants) do mappings[variant] = canonical end return mappings end function export.id_mapping(default, ids) local mapping = { default = default } if ids then for id, target in pairs(ids) do mapping[id] = target end end return mapping end function export.id_mapping_with_affix_variants(base, id_variants) local mappings = {} for id, variants in pairs(id_variants) do for _, variant in ipairs(variants) do mappings[variant] = export.id_mapping(base, {[id] = base}) end end return mappings end function export.merge_tables(...) local result = {} for i = 1, select('#', ...) do local t = select(i, ...) if t then for k, v in pairs(t) do result[k] = v end end end return result end -- Export this so the category code in [[Module:category tree/etymology]] can access it. export.langs_with_lang_specific_data = { ["az"] = true, ["fi"] = true, ["fr"] = true, ["izh"] = true, ["la"] = true, ["sah"] = true, ["tr"] = true, ["trk-pro"] = true, } local default_pos = "term" local function pluralize_pos(pos) return pluralize(singularize(pos)) end --[==[ intro: ===About different types of hyphens ("template", "display" and "lookup"):=== * The "template hyphen" is the per-script hyphen character that is used in template calls to indicate that a term is an affix. This is always a single Unicode char, but there may be multiple possible hyphens for a given script. Normally this is just the regular hyphen character "-", but for some non-Latin-script languages (currently only right-to-left languages), it is different. * The "display hyphen" is the string (which might be an empty string) that is added onto a term as displayed and linked, to indicate that a term is an affix. Currently this is always either the same as the template hyphen or an empty string, but the code below is written generally enough to handle arbitrary display hyphens. Specifically: *# For East Asian languages, the display hyphen is always blank. *# For Arabic-script languages, either tatweel (ـ) or ZWNJ (zero-width non-joiner) are allowed as template hyphens, where ZWNJ is supported primarily for Farsi, because some suffixes have non-joining behavior. The display hyphen corresponding to tatweel is also tatweel, but the display hyphen corresponding to ZWNJ is blank (tatweel is also the default display hyphen, for calls to {{tl|prefix}}/{{tl|suffix}}/etc. that don't include an explicit hyphen). * The "lookup hyphen" is the hyphen that is used when looking up language-specific affix mappings. (These mappings are discussed in more detail below when discussing link affixes.) It depends only on the script of the affix in question. Most scripts (including East Asian scripts) use a regular hyphen "-" as the lookup hyphen, but Hebrew and Arabic have their own lookup hyphens (respectively maqqef and tatweel). Note that for Arabic in particular, there are three possible template hyphens that are recognized (tatweel, ZWNJ and regular hyphen), but mappings must use tatweel. ===About different types of affixes ("template", "display", "link", "lookup" and "category"):=== * A "template affix" is an affix in its source form as it appears in a template call. Generally, a template affix has an attached template hyphen (see above) to indicate that it is an affix and indicate what type of affix it is (prefix, suffix, interfix or circumfix), but some of the older-style templates such as {{tl|suffix}}, {{tl|prefix}}, {{tl|confix}}, etc. have "positional" affixes where the presence of the affix in a certain position (e.g. the second or third parameter) indicates that it is a certain type of affix, whether or not it has an attached template hyphen. * A "display affix" is the corresponding affix as it is actually displayed to the user. The display affix may differ from the template affix for various reasons: *# The display affix may be specified explicitly using the {{para|alt<var>N</var>}} parameter, the `<alt:...>` inline modifier or a piped link of the form e.g. `<nowiki>[[-kas|-käs]]</nowiki>` (here indicating that the affix should display as `-käs` but be linked as `-kas`). Here, the template affix is arguably the entire piped link, while the display affix is `-käs`. *# Even in the absence of {{para|alt<var>N</var>}} parameters, `<alt:...>` inline modifiers and piped links, certain languages have differences between the "template hyphen" specified in the template (which always needs to be specified somehow or other in templates like {{tl|affix}}, to indicate that the term is an affix and what type of affix it is) and the display hyphen (see above), with corresponding differences between template and display affixes. * A (regular) "link affix" is the affix that is linked to when the affix is shown to the user. The link affix is usually the same as the display affix, but will differ in one of three circumstances: *# The display and link affixes are explicitly made different using {{para|alt<var>N</var>}} parameters, `<alt:...>` inline modifiers or piped links, as described above under "display affix". *# For certain languages, certain affixes are mapped to canonical form using language-specific mappings. For example, in Finnish, the adjective-forming suffix {{m|fi|-kas}} appears as {{m|fi|-käs}} after front vowels, but logically both forms are the same suffix and should be linked and categorized the same. Similarly, in Latin, the negative and intensive prefixes spelled {{m|la|in-}} (etymologically two distinct prefixes) appear variously as {{m|la|il-}}, {{m|la|im-}} or {{m|la|ir-}} before certain consonants. Mappings are supplied in [[Module:affix/lang-data/LANGCODE]] to convert Finnish {{m|fi|-käs}} to {{m|fi|-kas}} for linking and categorization purposes. Note that the affixes in the mappings use "lookup hyphens" to indicate the different types of affixes, which is usually the same as the template hyphen but differs for Arabic scripts, because there are multiple possible template hyphens recognized but only one lookup hyphen (tatweel). The form of the affix as used to look up in the mapping tables is called the "lookup affix"; see below. * A "stripped link affix" is a link affix that has been passed through the language's `stripDiacritics()` function, which may strip certain diacritics: e.g. macrons in Latin and Old English (indicating length); acute and grave accents in Russian and various other Slavic languages (indicating stress); vowel diacritics in most Arabic-script languages; and also tatweel in some Arabic-script languages (currently, for example, Persian, Arabic and Urdu strip tatweel, but Ottoman Turkish does not). Stripped link affixes are currently what are used in category names. * A "lookup affix" is the form of the affix as it is looked up in the language-specific lookup mappings described above under link affixes. There are actually two lookup stages: *# First, the affix is looked up in a modified display form (specifically, the same as the display affix but using lookup hyphens). Note that this lookup does not occur if an explicit display form is given using {{para|alt<var>N</var>}} or an `<alt:...>` inline modifier, or if the template affix contains a piped or embedded link. *# If no entry is found, the affix is then looked up in a modified link form (specifically, the modified display form passed through the language's `stripDiacritics()` function, which strips out certain diacritics, but with the lookup hyphen re-added if it was stripped out, as in the case of tatweel in many Arabic-script languages). The reason for this double lookup procedure is to allow for mappings that are sensitive to the extra diacritics, but also allow for mappings that are not sensitive in this fashion (e.g. Russian {{m|ru|-ливый}} occurs both stressed and unstressed, but is the same prefix either way). * A "category affix" is the affix as it appears in categories such as [[:Category:Finnish terms suffixed with -kas| Category:Finnish terms suffixed with ''-kas'']]. The category affix is currently always the same as the stripped link affix. This means that for Arabic-script languages, it may or may not have a tatweel, even if the correponding display affix and regular link affix have a tatweel. As mentioned above, stripDiacritics() strips tatweel for Arabic, Persian and Urdu, but not for Ottoman Turkish. Hence affix categories for Arabic, Persian and Urdu will be missing the tatweel, but affix categories for Ottoman Turkish will have it. An additional complication is that if the template affix contains a ZWNJ, the display (and hence the link and category affixes) will have no hyphen attached in any case. ]==] ----------------------------------------------------------------------------------------- -- Template and display hyphens -- ----------------------------------------------------------------------------------------- --[=[ Per-script template hyphens. The template hyphen is what appears in the {{affix}}/{{prefix}}/{{suffix}}/etc. template (in the wikicode). See above. They key below is a script code, after removing a hyphen and anything preceding. Hence, script codes like 'mnc-Mong' and 'xwo-Mong' will match 'Mong'. The value below is a string consisting of one or more hyphen characters. If there is more than one character, the default hyphen must come last and a non-default function must be specified for the script in display_hyphens[] so the correct display hyphen will be specified when no template hyphen is given (in {{suffix}}/{{prefix}}/etc.). Script detection is normally done when linking, but we need to do it earlier. However, under most circumstances we don't need to do script detection. Specifically, we only need to do script detection for a given language if (a) the language has multiple scripts; and (b) at least one of those scripts is listed below or in display_hyphens. ]=] local ZWNJ = u(0x200C) -- zero-width non-joiner local template_hyphens = { -- This covers all Arabic scripts. See above. ["Arab"] = "ـ" .. ZWNJ .. "-", -- tatweel + zero-width non-joiner + regular hyphen ["Aran"] = "ـ" .. ZWNJ .. "-", -- tatweel + zero-width non-joiner + regular hyphen ["Hebr"] = "־", -- Hebrew-specific hyphen termed "maqqef" ["Mong"] = "᠊", -- FIXME! What about the following right-to-left scripts? -- Adlm (Adlam) -- Armi (Imperial Aramaic) -- Avst (Avestan) -- Cprt (Cypriot) -- Khar (Kharoshthi) -- Mand (Mandaic/Mandaean) -- Mani (Manichaean) -- Mend (Mende/Mende Kikakui) -- Narb (Old North Arabian) -- Nbat (Nabataean/Nabatean) -- Nkoo (N'Ko) -- Orkh (Orkhon runes) -- Phli (Inscriptional Pahlavi) -- Phlp (Psalter Pahlavi) -- Phlv (Book Pahlavi) -- Phnx (Phoenician) -- Prti (Inscriptional Parthian) -- Rohg (Hanifi Rohingya) -- Samr (Samaritan) -- Sarb (Old South Arabian) -- Sogd (Sogdian) -- Sogo (Old Sogdian) -- Syrc (Syriac) -- Thaa (Thaana) } -- Hyphens used when looking up an affix in a lang-specific affix mapping. Defaults to regular hyphen (-). The keys -- are script codes, after removing a hyphen and anything preceding. Hence, script codes like 'mnc-Mong' and 'xwo-Mong' -- will match 'Mong'. The value should be a single character. local lookup_hyphens = { ["Hebr"] = "־", -- This covers all Arabic scripts. See above. ["Arab"] = "ـ", ["Aran"] = "ـ", } -- Default display-hyphen function. local function default_display_hyphen(script, hyph) if not hyph then return template_hyphens[script] or "-" end return hyph end local function arab_get_display_hyphen(_script, hyph) if not hyph then return "ـ" -- tatweel elseif hyph == ZWNJ then return "" else return hyph end end local function no_display_hyphen(_script, _hyph) return "" end -- Per-script function to return the correct display hyphen given the script and template hyphen. The function should -- also handle the case where the passed-in template hyphen is nil, corresponding to the situation in -- {{prefix}}/{{suffix}}/etc. where no template hyphen is specified. The key is the script code after removing a hyphen -- and anything preceding, so 'mnc-Mong', 'xwo-Mong' etc. will match 'Mong'. local display_hyphens = { -- This covers all Arabic scripts. See above. ["Arab"] = arab_get_display_hyphen, ["Aran"] = arab_get_display_hyphen, ["Bopo"] = no_display_hyphen, ["Hani"] = no_display_hyphen, ["Hans"] = no_display_hyphen, ["Hant"] = no_display_hyphen, -- The following is a mixture of several scripts. Hopefully the specs here are correct! ["Jpan"] = no_display_hyphen, ["Jurc"] = no_display_hyphen, ["Kitl"] = no_display_hyphen, ["Kits"] = no_display_hyphen, ["Laoo"] = no_display_hyphen, ["Nshu"] = no_display_hyphen, ["Shui"] = no_display_hyphen, ["Tang"] = no_display_hyphen, ["Thaa"] = no_display_hyphen, ["Thai"] = no_display_hyphen, ["Tibt"] = no_display_hyphen, } ----------------------------------------------------------------------------------------- -- Basic Utility functions -- ----------------------------------------------------------------------------------------- local function glossary_link(entry, text) text = text or entry return "[[Appendix:Glossary#" .. entry .. "|" .. text .. "]]" end local function track(page) if type(page) == "table" then for i, pg in ipairs(page) do page[i] = "affix/" .. pg end else page = "affix/" .. page end require("Module:debug/track")(page) end local function ine(val) return val ~= "" and val or nil end ----------------------------------------------------------------------------------------- -- Compound types -- ----------------------------------------------------------------------------------------- local function make_compound_type(typ, alttext) return { text = glossary_link(typ, alttext) .. " compound", cat = typ .. " compounds", } end -- Make a compound type entry with a simple rather than glossary link. -- These should be replaced with a glossary link when the entry in the glossary -- is created. local function make_non_glossary_compound_type(typ, alttext) local link = alttext and "[[" .. typ .. "|" .. alttext .. "]]" or "[[" .. typ .. "]]" return { text = link .. " compound", cat = typ .. " compounds", } end local function make_raw_compound_type(typ, alttext) return { text = glossary_link(typ, alttext), cat = pluralize(typ), } end local function make_borrowing_type(typ, alttext) return { text = glossary_link(typ, alttext), borrowing_type = pluralize(typ), } end export.etymology_types = { ["adapted borrowing"] = make_borrowing_type("adapted borrowing"), ["adap"] = "adapted borrowing", ["abor"] = "adapted borrowing", ["alliterative"] = make_non_glossary_compound_type("alliterative"), ["allit"] = "alliterative", ["antonymous"] = make_non_glossary_compound_type("antonymous"), ["ant"] = "antonymous", ["bahuvrihi"] = make_compound_type("bahuvrihi", "bahuvrīhi"), ["bahu"] = "bahuvrihi", ["bv"] = "bahuvrihi", ["coordinative"] = make_compound_type("coordinative"), ["coord"] = "coordinative", ["descriptive"] = make_compound_type("descriptive"), ["desc"] = "descriptive", ["determinative"] = make_compound_type("determinative"), ["det"] = "determinative", ["dvandva"] = make_compound_type("dvandva"), ["dva"] = "dvandva", ["dvigu"] = make_compound_type("dvigu"), ["dvi"] = "dvigu", ["endocentric"] = make_compound_type("endocentric"), ["endo"] = "endocentric", ["exocentric"] = make_compound_type("exocentric"), ["exo"] = "exocentric", ["izafet I"] = make_compound_type("izafet I"), ["iz1"] = "izafet I", ["izafet II"] = make_compound_type("izafet II"), ["iz2"] = "izafet II", ["izafet III"] = make_compound_type("izafet III"), ["iz3"] = "izafet III", ["karmadharaya"] = make_compound_type("karmadharaya", "karmadhāraya"), ["karma"] = "karmadharaya", ["kd"] = "karmadharaya", ["kenning"] = make_raw_compound_type("kenning"), ["ken"] = "kenning", ["rhyming"] = make_non_glossary_compound_type("rhyming"), ["rhy"] = "rhyming", ["synonymous"] = make_non_glossary_compound_type("synonymous"), ["syn"] = "synonymous", ["tatpurusa"] = make_compound_type("tatpurusa", "tatpuruṣa"), ["tat"] = "tatpurusa", ["tp"] = "tatpurusa", } local function process_etymology_type(typ, nocap, notext, has_parts) local text_sections = {} local categories = {} local borrowing_type if typ then local typdata = export.etymology_types[typ] if type(typdata) == "string" then typdata = export.etymology_types[typdata] end if not typdata then error("Internal error: Unrecognized type '" .. typ .. "'") end local text = typdata.text if not nocap then text = ucfirst(text) end local cat = typdata.cat borrowing_type = typdata.borrowing_type local oftext = typdata.oftext or " of" if not notext then insert(text_sections, text) if has_parts then insert(text_sections, oftext) insert(text_sections, " ") end end if cat then insert(categories, cat) end end return text_sections, categories, borrowing_type end ----------------------------------------------------------------------------------------- -- Utility functions -- ----------------------------------------------------------------------------------------- -- Iterate an array up to the greatest integer index found. local function ipairs_with_gaps(t) local indices = m_table.numKeys(t) local max_index = #indices > 0 and math.max(unpack(indices)) or 0 local i = 0 return function() if i < max_index then i = i + 1 return i, t[i] end end end export.ipairs_with_gaps = ipairs_with_gaps --[==[ Join formatted parts together with any overall {{para|lit}} spec, overall left and/or right qualifiers and labels, and categories. On input, `data` is a structure with the following fields: * `affixdata`: The affix data passed into an entry point such as `##show_affix()`; the code in this function examines the `lang`, `lit`, `force_cat`, `nocat`, `sort_key`, `q`, `qq`, `l` and `ll` fields of this structure, which represent overall values for these properties (as opposed to per-part values, which are found inside the list of per-part objects in `parts`, which are not examined); * `parts_formatted`: List of formatted parts, each a string; * `separator_already_added`: If true, any separators have already been included in `parts_formatted`, so the values should be concatenated with nothing in between; otherwise, the separator {" +&lrm; "} will be used, i.e. a `+` sign surrounded by spaces along with a Unicode left-to-right character to ensure that the parts appear in left-to-right order even if they contain right-to-left text; * `categories`: List of category strings or category objects; category strings are formatted using the `sort_key` field in the affix data structure in `affixdata`, while category objects, which are of the form `{ {cat=``category``, sort_key=``sort_key``, sort_base=``sort_base``}`, specify their own sort key and sort base; if `affixdata.nocat` is given, no categories are added; otherwise, `affixdata.force_cat` or global variable `debug_force_cat` causes categories to be added even on userspace pages. ]==] function export.join_formatted_parts(data) local cattext local affixdata = data.affixdata local lang = affixdata.lang local force_cat = affixdata.force_cat or debug_force_cat if affixdata.nocat then cattext = "" else for i, cat in ipairs(data.categories) do if type(cat) == "table" then data.categories[i] = require(utilities_module).format_categories(lang:getFullName() .. " " .. cat.cat, lang, cat.sort_key, cat.sort_base, force_cat) else data.categories[i] = require(utilities_module).format_categories(lang:getFullName() .. " " .. cat, lang, affixdata.sort_key, nil, force_cat) end end cattext = concat(data.categories) end local result = concat(data.parts_formatted, not data.separator_already_added and " +&lrm; " or nil) .. (affixdata.lit and ", literally " .. m_links.mark(affixdata.lit, "gloss") or "") local q = affixdata.q local qq = affixdata.qq local l = affixdata.l local ll = affixdata.ll if q and q[1] or qq and qq[1] or l and l[1] or ll and ll[1] then result = require(decorations_module).format_decorations { lang = lang, text = result, q = q, qq = qq, l = l, ll = ll, } end return result .. cattext end -- Remove links and call lang:stripDiacritics(term). local function strip_diacritics_no_links(lang, term) return lang:stripDiacritics(m_links.remove_links(term)) end --[=[ Convert a raw part as passed into an entry point into a part ready for linking. `lang` and `sc` are the overall language and script objects. This uses the overall language and script objects as defaults for the part and parses off any fragment from the term. We need to do the latter so that fragments don't end up in categories and so that we correctly do affix mapping even in the presence of fragments. ]=] local function canonicalize_part(part, lang, sc) if not part then return end -- Save the original (user-specified, part-specific) value of `lang`. If such a value is specified, we don't insert -- a '*fixed with' category, and we format the part using format_derived() in [[Module:etymology]] rather than -- full_link() in [[Module:links]]. part.part_lang = part.lang part.lang = part.lang or lang part.sc = part.sc or sc local term = part.term if not term then return elseif not part.fragment then part.term, part.fragment = m_links.get_fragment(term) else part.term = m_links.get_fragment(term) end end --[==[ Construct a single linked part based on the information in `part`, for use by `show_affix()` and other entry points. This should be called after `canonicalize_part()` is called on the part. This is a thin wrapper around `full_link()` in [[Module:links]] unless `part.part_lang` is specified (indicating that a part-specific language was given), in which case `format_derived()` in [[Module:etymology]] is called to display a term in a language other than the language of the overall term (specified in `data.lang`). `data` contains the entire object passed into the entry point and is used to access information for constructing the categories added by `format_derived()`. ]==] function export.link_term(part, data, include_separator) local result if part.part_lang then result = require(etymology_module).format_derived { lang = data.lang, terms = {part}, sources = {part.lang}, sort_key = data.sort_key, nocat = data.nocat, template_name = "affix", decorations_on_outside = true, borrowing_type = data.borrowing_type, force_cat = data.force_cat or debug_force_cat, } else result = m_links.full_link(part, "term") end if include_separator and part.separator then return part.separator .. result else return result end end local function canonicalize_script_code(scode) -- Convert 'mnc-Mong', 'xwo-Mong' etc. to 'Mong'. return (scode:gsub("^.*%-", "")) end ----------------------------------------------------------------------------------------- -- Affix-handling functions -- ----------------------------------------------------------------------------------------- -- Figure out the appropriate script for the given affix and language (unless the script is explicitly passed in), and -- return the values of template_hyphens[], display_hyphens[] and lookup_hyphens[] for that script, substituting -- default values as appropriate. Four values are returned: -- DETECTED_SCRIPT, TEMPLATE_HYPHEN, DISPLAY_HYPHEN, LOOKUP_HYPHEN local function detect_script_and_hyphens(text, lang, sc) local scode -- 1. If the script is explicitly passed in, use it. if sc then scode = sc:getCode() else local possible_script_codes = lang:getScriptCodes() -- YUCK! `possible_script_codes` comes from loadData() so #possible_scripts doesn't work (always returns 0). local num_possible_script_codes = m_table.length(possible_script_codes) if num_possible_script_codes == 0 then -- This shouldn't happen; if the language has no script codes, -- the list {"None"} should be returned. error("Something is majorly wrong! Language " .. lang:getCanonicalName() .. " has no script codes.") end if num_possible_script_codes == 1 then -- 2. If the language has only one possible script, use it. scode = possible_script_codes[1] else -- 3. Check if any of the possible scripts for the language have non-default values for template_hyphens[] -- or display_hyphens[]. If so, we need to do script detection on the text. If not, just use "Latn", -- which may not be technically correct but produces the right results because Latn has all default -- values for template_hyphens[] and display_hyphens[]. local may_have_nondefault_hyphen = false for _, script_code in ipairs(possible_script_codes) do script_code = canonicalize_script_code(script_code) if template_hyphens[script_code] or display_hyphens[script_code] then may_have_nondefault_hyphen = true break end end if not may_have_nondefault_hyphen then scode = "Latn" else scode = lang:findBestScript(text):getCode() end end end scode = canonicalize_script_code(scode) local template_hyphen = template_hyphens[scode] or "-" local lookup_hyphen = lookup_hyphens[scode] or "-" local display_hyphen = display_hyphens[scode] or default_display_hyphen return scode, template_hyphen, display_hyphen, lookup_hyphen end --[=[ Given a template affix `term` and an affix type `affix_type`, change the relevant template hyphen(s) in the affix to the display or lookup hyphen specified in `new_hyphen`, or add them if they are missing. `new_hyphen` can be a string, specifying a fixed hyphen, or a function of two arguments (the script code `scode` and the discovered template hyphen, or nil of no relevant template hyphen is present). `thyph_re` is a Lua pattern (which must be enclosed in parens) that matches the possible template hyphens. Note that not all template hyphens present in the affix are changed, but only the "relevant" ones (e.g. for a prefix, a relevant template hyphen is one coming at the end of the affix). ]=] local function reconstruct_term_per_hyphens(term, affix_type, scode, thyph_re, new_hyphen) local function get_hyphen(hyph) if type(new_hyphen) == "string" then return new_hyphen end return new_hyphen(scode, hyph) end if affix_type == "non-affix" then return term elseif affix_type == "circumfix" then local before, before_hyphen, after_hyphen, after = umatch(term, "^(.*)" .. thyph_re .. " " .. thyph_re .. "(.*)$") if not before or ulen(term) <= 3 then -- Unlike with other types of affixes, don't try to add hyphens in the middle of the term to convert it to -- a circumfix. Also, if the term is just hyphen + space + hyphen, return it. return term end return before .. get_hyphen(before_hyphen) .. " " .. get_hyphen(after_hyphen) .. after elseif affix_type == "infix" or affix_type == "interfix" then local before_hyphen, middle, after_hyphen = umatch(term, "^" .. thyph_re .. "(.*)" .. thyph_re .. "$") if before_hyphen and ulen(term) <= 1 then -- If the term is just a hyphen, return it. return term end return get_hyphen(before_hyphen) .. (middle or term) .. get_hyphen(after_hyphen) elseif affix_type == "prefix" then local middle, after_hyphen = umatch(term, "^(.*)" .. thyph_re .. "$") if middle and ulen(term) <= 1 then -- If the term is just a hyphen, return it. return term end return (middle or term) .. get_hyphen(after_hyphen) elseif affix_type == "suffix" then local before_hyphen, middle = umatch(term, "^" .. thyph_re .. "(.*)$") if before_hyphen and ulen(term) <= 1 then -- If the term is just a hyphen, return it. return term end return get_hyphen(before_hyphen) .. (middle or term) else error(("Internal error: Unrecognized affix type '%s'"):format(affix_type)) end end --[=[ Look up a mapping from a given affix variant to the canonical form used in categories and links. The lookup tables are language-specific according to `lang`, and may be ID-specific according to `affix_id`. The affixes as they appear in the lookup tables (both the variant and the canonical form) are in "lookup affix" format (approximately speaking, they use a regular hyphen for most scripts, but a tatweel for Arabic-script entries and a maqqef for Hebrew-script entries), but the passed-in `affix` param is in "template affix" format (which differs from the lookup affix for Arabic-script entries, because more types of hyphens are allowed in template affixes; see the comments at the top of the file). The remaining parameters to this function are used to convert from template affixes to lookup affixes; see the reconstruct_term_per_hyphens() function above. If the affix contains brackets, no lookup is done. Otherwise, a two-stage process is used, first looking up the affix directly and then stripping diacritics and looking it up again. The reason for this is documented above in the comments at the top of the file (specifically, the comments describing lookup affixes). The value of a mapping can either be a string (do the mapping regardless of affix ID) or a table indexed by affix ID (where the special value `false` indicates no affix ID). The values of entries in this table can also be strings, or tables with keys `affix` and `id` (again, use `false` to indicate no ID). This allows an affix mapping to map from one ID to another (for example, this is used in English to map the [[an-]] prefix with no ID to the [[a-]] prefix with the ID 'not'). The Given a template affix `term` and an affix type `affix_type`, change the relevant template hyphen(s) in the affix to the display or lookup hyphen specified in `new_hyphen`, or add them if they are missing. `new_hyphen` can be a string, specifying a fixed hyphen, or a function of two arguments (the script code `scode` and the discovered template hyphen, or nil of no relevant template hyphen is present). `thyph_re` is a Lua pattern (which must be enclosed in parens) that matches the possible template hyphens. Note that not all template hyphens present in the affix are changed, but only the "relevant" ones (e.g. for a prefix, a relevant template hyphen is one coming at the end of the affix). ]=] local function lookup_affix_mapping(affix, affix_type, lang, scode, thyph_re, lookup_hyph, affix_id) local function do_lookup(afx) -- Ensure that the affix uses lookup hyphens regardless of whether it used a different type of hyphens before -- or no hyphens. local lookup_affix = reconstruct_term_per_hyphens(afx, affix_type, scode, thyph_re, lookup_hyph) local function do_lookup_for_langcode(langcode) if export.langs_with_lang_specific_data[langcode] then local langdata = mw.loadData(export.affix_lang_data_module_prefix .. langcode) if langdata.affix_mappings then local mapping = langdata.affix_mappings[lookup_affix] if mapping then if type(mapping) == "table" then mapping = mapping[affix_id] or mapping.default or mapping[affix_id or false] if mapping then return mapping end else return mapping end end end end end -- If `lang` is an etymology-only language, look for a mapping both for it and its full parent. local langcode = lang:getCode() local mapping = do_lookup_for_langcode(langcode) if mapping then return mapping end local full_langcode = lang:getFullCode() if full_langcode ~= langcode then mapping = do_lookup_for_langcode(full_langcode) if mapping then return mapping end end return nil end if affix:find("%[%[") then return nil end return do_lookup(affix) or do_lookup(lang:stripDiacritics(affix)) or nil end --[==[ For a given template term in a given language (see the definition of "template affix" near the top of the file), possibly in an explicitly specified script `sc` (but usually nil), return the term's affix type ({"prefix"}, {"interfix"}, {"suffix"}, {"circumfix"} or {"non-affix"}) along with the corresponding link and display affixes (see definitions near the top of the file); also the corresponding lookup affix (if `return_lookup_affix` is specified). The term passed in should already have any fragment (after the # sign) parsed off of it. Four values are returned: `affix_type`, `link_term`, `display_term` and `lookup_term`. The affix type can be passed in instead of autodetected; in this case, the template term need not have any attached hyphens, and the appropriate hyphens will be added in the appropriate places. If `do_affix_mapping` is specified, look up the affix in the lang-specific affix mappings, as described in the comment at the top of the file; otherwise, the link and display terms will always be the same. (They will be the same in any case if the template term has a bracketed link in it or is not an affix.) If `return_lookup_affix` is given, the fourth return value contains the term with appropriate lookup hyphens in the appropriate places; otherwise, it is the same as the display term. (This functionality is used in [[Module:category tree/affixes and compounds]] to convert link affixes into lookup affixes so that they can be looked up in the affix mapping tables.) Exported because used by [[Module:headword utilities]] to determine the affix type of a given pagename. ]==] function export.parse_term_for_affixes(term, lang, sc, affix_type, do_affix_mapping, return_lookup_affix, affix_id) if not term then return "non-affix", nil, nil, nil end if term == "^" then -- Indicates a null term to emulate the behavior of {{suffix|foo||bar}}. term = nil return "non-affix", term, term, term end if term:find("^%^") then -- HACK! ^ at the beginning of Korean languages has a special meaning, triggering capitalization of the -- transliteration. Don't interpret it as "force non-affix" for those languages. local langcode = lang:getCode() if langcode ~= "ko" and langcode ~= "okm" and langcode ~= "jje" then -- Formerly we allowed ^ to force non-affix type; this is now handled using an inline modifier -- <naf>, <root>, etc. Throw an error for the moment when the old way is encountered. error("Use of ^ to force non-affix status is no longer supported; use an inline modifier <naf> or <root> " .. "after the component") end end -- Remove an asterisk if the morpheme is reconstructed and add it back at the end. local reconstructed = "" if term:find("^%*") then reconstructed = "*" term = term:gsub("^%*", "") end local scode, thyph, dhyph, lhyph = detect_script_and_hyphens(term, lang, sc) thyph = "([" .. thyph .. "])" if not affix_type then if ufind(term, thyph .. " " .. thyph) then affix_type = "circumfix" else local has_beginning_hyphen = ufind(term, "^" .. thyph) local has_ending_hyphen = ufind(term, thyph .. "$") if has_beginning_hyphen and has_ending_hyphen then affix_type = "interfix" elseif has_ending_hyphen then affix_type = "prefix" elseif has_beginning_hyphen then affix_type = "suffix" else affix_type = "non-affix" end end end local link_term, display_term, lookup_term if affix_type == "non-affix" then link_term = term display_term = term lookup_term = term else display_term = reconstruct_term_per_hyphens(term, affix_type, scode, thyph, dhyph) if do_affix_mapping then link_term = lookup_affix_mapping(term, affix_type, lang, scode, thyph, lhyph, affix_id) -- The return value of lookup_affix_mapping() may be an affix mapping with lookup hyphens if a mapping -- was found, otherwise nil if a mapping was not found. We need to convert to display hyphens in -- either case, but in the latter case we can reuse the display term, which has already been converted. if link_term then link_term = reconstruct_term_per_hyphens(link_term, affix_type, scode, thyph, dhyph) else link_term = display_term end else link_term = display_term end if return_lookup_affix then lookup_term = reconstruct_term_per_hyphens(term, affix_type, scode, thyph, lhyph) else lookup_term = display_term end end link_term = reconstructed .. link_term display_term = reconstructed .. display_term lookup_term = reconstructed .. lookup_term return affix_type, link_term, display_term, lookup_term end --[==[ Add a hyphen to a term in the appropriate place, based on the specified affix type, stripping off any existing hyphens in that place. For example, if `affix_type` == {"prefix"}, we'll add a hyphen onto the end if it's not already there (or is of the wrong type). Three values are returned: the link term, display term and lookup term. This function is a thin wrapper around `parse_term_for_affixes`; see the comments above that function for more information. Note that this function is exposed externally because it is called by [[Module:category tree/affixes and compounds]]; see the comment in `parse_term_for_affixes` for more information. ]==] function export.make_affix(term, lang, sc, affix_type, do_affix_mapping, return_lookup_affix, affix_id) if not (affix_type == "prefix" or affix_type == "suffix" or affix_type == "circumfix" or affix_type == "infix" or affix_type == "interfix" or affix_type == "non-affix") then error("Internal error: Invalid affix type " .. (affix_type or "(nil)")) end local _, link_term, display_term, lookup_term = export.parse_term_for_affixes(term, lang, sc, affix_type, do_affix_mapping, return_lookup_affix, affix_id) return link_term, display_term, lookup_term end ----------------------------------------------------------------------------------------- -- Categorization logic -- ----------------------------------------------------------------------------------------- local function insert_category(categories, cat, sort_key, sort_base) if sort_key or sort_base then insert(categories, {cat = cat, sort_key = sort_key, sort_base = sort_base}) else insert(categories, cat) end end --[=[ Insert a `*fixed with` category such as [[:Category:Welsh terms prefixed with gwe-]] into `categories`. The arguments are: * `categories`: List of category strings or objects to insert into. * `pos`: Part of speech in the category (which is often "terms" but may be something more specific). * `affix_type`: Affix type in the category (e.g. "prefix"); automatically has "ed" appended. * `link_term`: The term that appears in the category, e.g. "gwe-". If this is empty or missing, no category is inserted. * `part`: The part structure being processed. The `lang`, `part_lang`, `nocat` and `id` fields are fetched. * `sort_key`: The sort key for the specific category. If this or `sort_base` are non-nil, a category object is created holding the specified sort key and/or base, and inserted; otherwise, a cateory string is inserted. * `sort_base`: The sort base for the specific category. See `sort_key` just above. ]=] local function insert_affix_category(categories, pos, affix_type, link_term, part, sort_key, sort_base) -- Don't add a category if the link term is empty or is in a different language, or if <nocat:1> was specified for -- the part. if ine(link_term) and not part.part_lang and not part.nocat then local cat = pos .. " " .. affix_type .. "ed with " .. strip_diacritics_no_links(part.lang, link_term) .. (part.id and " (" .. part.id .. ")" or "") insert_category(categories, cat, sort_key, sort_base) end end --[=[ Generate the categories for a single part and insert into `categories`. The arguments are: * `categories` is the list to insert the categories into. * `data` is the overall affix data structure. * `part` is the per-part data structure. * `affix_type` is the type of affix (e.g. "prefix"), as appears in the `*fixed by` category. * `link_term` is the term that (prefix, suffix, etc.) mentioned in the `*fixed by` category. * `sort_key` and `sort_base` are the per-part sort keys and bases for categorization, or nil to use the overall sort key. ]=] local function generate_one_part_categories(categories, data, part, affix_type, link_term, sort_key, sort_base) if data.nocat or part.nocat then return end if part.pos and part.pos:find("patronym") then insert_category(categories, "patronymics", sort_key, sort_base) end if data.pos ~= "terms" and part.pos and part.pos:find("diminutive") then insert_category(categories, "diminutive " .. data.pos, sort_key, sort_base) end insert_affix_category(categories, data.pos, affix_type, link_term, part, sort_key, sort_base) end --[=[ Core categorization logic for affixes. This is shared between show_affix(), show_compound_like() and get_affix_categories_only(). Returns the categories array and other metadata needed for formatting. ]=] local function generate_affix_categories(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) local text_sections, categories, borrowing_type = process_etymology_type(data.type, data.surface_analysis or data.nocap, data.notext, #data.parts > 0) data.borrowing_type = borrowing_type -- Process each part local whole_words = 0 local is_affix_or_compound = false -- Canonicalize and generate links for all the parts first; then do categorization in a separate step, because when -- processing the first part for categorization, we may access the second part and need it already canonicalized. for i, part in ipairs_with_gaps(data.parts) do part = part or {} data.parts[i] = part canonicalize_part(part, data.lang, data.sc) -- Determine affix type and get link and display terms (see text at top of file). Store them in the part -- (in fields that won't clash with fields used by full_link() in [[Module:links]] or link_term()), so they -- can be used in the loop below when categorizing. part.affix_type, part.affix_link_term, part.affix_display_term = export.parse_term_for_affixes(part.term, part.lang, part.sc, part.type, not part.alt, nil, part.id) -- If link_term is an empty string, either a bare ^ was specified or an empty term was used along with inline -- modifiers. The intention in either case is not to link the term. part.term = ine(part.affix_link_term) -- If part.alt would be the same as part.term, make it nil, so that it isn't erroneously tracked as being -- redundant alt text. part.alt = part.alt or (part.affix_display_term ~= part.affix_link_term and part.affix_display_term) or nil end if not data.noaffixcat then -- Now do categorization. for i, part in ipairs_with_gaps(data.parts) do local affix_type = part.affix_type if affix_type ~= "non-affix" then is_affix_or_compound = true -- Make a sort key. For the first part, use the second part as the sort key; the intention is that if the -- term has a prefix, sorting by the prefix won't be very useful so we sort by what follows, which is -- presumably the root. local part_sort_base = nil local part_sort = part.sort or data.sort_key if i == 1 and data.parts[2] and data.parts[2].term then local part2 = data.parts[2] -- If the second-part link term is empty, the user requested an unlinked term; avoid a wikitext error -- by using the alt value if available. part_sort_base = ine(part2.affix_link_term) or ine(part2.alt) if part_sort_base then part_sort_base = strip_diacritics_no_links(part2.lang, part_sort_base) end end generate_one_part_categories(categories, data, part, affix_type, part.affix_link_term, part_sort, part_sort_base) else whole_words = whole_words + 1 if whole_words == 2 then is_affix_or_compound = true insert(categories, "compound " .. data.pos) end end end -- Make sure there was either an affix or a compound (two or more non-affix terms). if not is_affix_or_compound and not data.allow_no_affixes_or_compounds then error("The parameters did not include any affixes, and the term is not a compound. Please provide at least one affix.") end end return text_sections, categories, borrowing_type end -- Return true if specified part has no term or alt and no modifiers. WARNING: Keep this up-to-date -- in case any other fields are added that are always present. local function part_is_empty(part) for k, v in pairs(part) do if k ~= "affix_type" and k ~= "lang" and k ~= "orig_index" and k ~= "itemno" and k ~= "separator" then return false end end return true end ----------------------------------------------------------------------------------------- -- Main entry points -- ----------------------------------------------------------------------------------------- --[==[ Implementation of {{tl|affix}} and {{tl|surface analysis}}. `data` contains all the information describing the affixes to be displayed, and contains the following: * `.lang` ('''required'''): Overall language object. Different from term-specific language objects (see `.parts` below). * `.sc`: Overall script object (usually omitted). Different from term-specific script objects. * `.parts` ('''required'''): List of objects describing the affixes to show. The general format of each object is as would be passed to `full_link()`, except that the `.lang` field should be missing unless the term is of a language different from the overall `.lang` value (in such a case, the language name is shown along with the term and an additional "derived from" category is added). '''WARNING''': The data in `.parts` will be destructively modified. * `.pos`: Overall part of speech (used in categories, defaults to {"terms"}). Different from term-specific part of speech. * `.sort_key`: Overall sort key. Normally omitted except e.g. in Japanese. * `.type`: Type of compound, if the parts in `.parts` describe a compound. Strictly optional, and if supplied, the compound type is displayed before the parts (normally capitalized, unless `.nocap` is given). * `.nocap`: Don't capitalize the first letter of text displayed before the parts (relevant only if `.type` or `.surface_analysis` is given). * `.notext`: Don't display any text before the parts (relevant only if `.type` or `.surface_analysis` is given). * `.nocat`: Disable all categorization. * `.noaffixcat`: Disable affix (and compound) categorization. Relevant for e.g. blends, which may otherwise be incorrectly categorized as compound terms. * `.lit`: Overall literal definition. Different from term-specific literal definitions. * `.force_cat`: Always display categories, even on userspace pages. * `.surface_analysis`: Implement {{surface analysis}}; adds `By surface analysis, ` before the parts. '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.show_affix(data) local text_sections, categories, _ = generate_affix_categories(data) -- Process each part for display local parts_formatted = {} for i, part in ipairs_with_gaps(data.parts) do -- Make a link for the part if part_is_empty(part) then if part.separator then insert(parts_formatted, part.separator) end -- don't call full_link(); we allow this to emulate the behavior of {{suf}} and {{pre}} in such cases. else insert(parts_formatted, export.link_term(part, data, "include_separator")) end end if data.surface_analysis then local text = "by " .. glossary_link("surface analysis") .. ", " if not data.nocap then text = ucfirst(text) end insert(text_sections, 1, text) end insert(text_sections, export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories, separator_already_added = true }) return concat(text_sections) end --[==[ Get only the categories that would be generated by show_affix(), without any text output or formatting. This is used by Module:etymon to get affix categorization. Returns an array of category objects, where each entry is either a string (simple category name) or a table with keys `cat`, `sort_key`, and `sort_base` for more complex categorization. `data` should have the same structure as passed to show_affix(): * `.lang` (required): Overall language object * `.parts` (required): Array of affix part objects with `.term`, `.lang`, `.id`, etc. * `.pos`: Part of speech (defaults to "terms") * `.sort_key`: Overall sort key for categories '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.get_affix_categories_only(data) local _, categories, _ = generate_affix_categories(data) return categories end function export.show_surface_analysis(data) data.surface_analysis = true data.allow_no_affixes_or_compounds = true return export.show_affix(data) end --[==[ Implementation of {{tl|compound}}. '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.show_compound(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) local text_sections, categories, borrowing_type = process_etymology_type(data.type, data.nocap, data.notext, #data.parts > 0) data.borrowing_type = borrowing_type local parts_formatted = {} insert(categories, "compound " .. data.pos) -- Make links out of all the parts local whole_words = 0 for i, part in ipairs(data.parts) do canonicalize_part(part, data.lang, data.sc) -- Determine affix type and get link and display terms (see text at top of file). local affix_type, link_term, display_term = export.parse_term_for_affixes(part.term, part.lang, part.sc, part.type, not part.alt, nil, part.id) -- If the term is an interfix or the type was explicitly given, recognize it as such (which means e.g. that we -- will display the term without hyphens for East Asian languages). Otherwise, ignore the fact that it looks -- like an affix and display as specified in the template (but pay attention to the detected affix type for -- certain tracking purposes). if affix_type == "interfix" or (part.type and part.type ~= "non-affix") then -- Add a `*fixed with` category. However, if link_term is an empty string, either a bare ^ was specified or -- an empty term was used along with inline modifiers. The intention in either case is not to link the term. -- Don't add a category in this case, or if the term is in a different language (or if overall nocat=1 was -- given, or part-specific <nocat:1>). if not data.nocat then -- FIXME, should we be specifying a sort base here? insert_affix_category(categories, data.pos, affix_type, link_term, part, part.sort or data.sort_key) end -- If part.alt would be the same as part.term, make it nil, so that it isn't erroneously tracked as being -- redundant alt text. part.term = link_term ~= "" and link_term or nil part.alt = part.alt or (display_term ~= link_term and display_term) or nil else if affix_type ~= "non-affix" then local langcode = data.lang:getCode() -- If `data.lang` is an etymology-only language, track both using its code and its full parent's code. track { affix_type, affix_type .. "/lang/" .. langcode } local full_langcode = data.lang:getFullCode() if langcode ~= full_langcode then track(affix_type .. "/lang/" .. full_langcode) end else whole_words = whole_words + 1 end end insert(parts_formatted, export.link_term(part, data, "include_separator")) end if whole_words == 1 then track("one whole word") elseif whole_words == 0 then track("looks like confix") end insert(text_sections, export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories, separator_already_added = true }) return concat(text_sections) end --[==[ Implementation of {{tl|blend}}, {{tl|univerbation}} and similar "compound-like" templates. '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.show_compound_like(data) data.allow_no_affixes_or_compounds = true local text_sections, categories, _ = generate_affix_categories(data) if data.cat then insert(categories, data.cat) end -- Process each part for display local parts_formatted = {} for i, part in ipairs_with_gaps(data.parts) do -- Make a link for the part insert(parts_formatted, export.link_term(part, data, "include_separator")) end if #data.parts > 0 and data.oftext then insert(text_sections, 1, " " .. data.oftext .. " ") end if data.text then insert(text_sections, 1, data.text) end insert(text_sections, export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories, separator_already_added = true }) return concat(text_sections) end --[==[ Make `part` (a structure holding information on an affix part) into an affix of type `affix_type`, and apply any relevant affix mappings. For example, if the desired affix type is "suffix", this will (in general) add a hyphen onto the beginning of the term, alt, tr and ts components of the part if not already present. The hyphen that's added is the "display hyphen" (see above) and may be script-specific. (In the case of East Asian scripts, the display hyphen is an empty string whereas the template hyphen is the regular hyphen, meaning that any regular hyphen at the beginning of the part will be effectively removed.) `lang` and `sc` hold overall language and script objects. Note that this also applies any language-specific affix mappings, so that e.g. if the language is Finnish and the user specified [[-käs]] in the affix and didn't specify an `.alt` value, `part.term` will contain [[-kas]] and `part.alt` will contain [[-käs]]. This function is used by the "legacy" templates ({{tl|prefix}}, {{tl|suffix}}, {{tl|confix}}, etc.) where the nature of the affix is specified by the template itself rather than auto-determined from the affix, as is the case with {{tl|affix}}. '''WARNING''': This destructively modifies `part`. ]==] local function make_part_into_affix(part, lang, sc, affix_type) canonicalize_part(part, lang, sc) local link_term, display_term = export.make_affix(part.term, part.lang, part.sc, affix_type, not part.alt, nil, part.id) part.term = link_term -- When we don't specify `do_affix_mapping` to make_affix(), link and display terms (first and second retvals of -- make_affix()) are the same. -- If part.alt would be the same as part.term, make it nil, so that it isn't erroneously tracked as being -- redundant alt text. part.alt = part.alt and export.make_affix(part.alt, part.lang, part.sc, affix_type) or (display_term ~= link_term and display_term) or nil local Latn = require(scripts_module).getByCode("Latn") part.tr = export.make_affix(part.tr, part.lang, Latn, affix_type) part.ts = export.make_affix(part.ts, part.lang, Latn, affix_type) end local function track_wrong_affix_type(template, part, expected_affix_type) if part and not part.type then local affix_type = export.parse_term_for_affixes(part.term, part.lang, part.sc) if affix_type ~= expected_affix_type then local part_name = expected_affix_type or "base" local langcode = part.lang:getCode() local full_langcode = part.lang:getFullCode() require("Module:debug/track") { template, template .. "/" .. part_name, template .. "/" .. part_name .. "/" .. (affix_type or "none"), template .. "/" .. part_name .. "/" .. (affix_type or "none") .. "/lang/" .. langcode } -- If `part.lang` is an etymology-only language, track both using its code and its full parent's code. if full_langcode ~= langcode then require("Module:debug/track")( template .. "/" .. part_name .. "/" .. (affix_type or "none") .. "/lang/" .. full_langcode ) end end end end --[==[ Implementation of {{tl|confix}}. '''WARNING''': This destructively modifies both `data` and `.prefix`, `.base` and `.suffix`. ]==] function export.show_confix(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. make_part_into_affix(data.prefix, data.lang, data.sc, "prefix") make_part_into_affix(data.suffix, data.lang, data.sc, "suffix") track_wrong_affix_type("confix", data.prefix, "prefix") track_wrong_affix_type("confix", data.base, nil) track_wrong_affix_type("confix", data.suffix, "suffix") -- Make links out of all the parts. local parts_formatted = {} local prefix_sort_base if data.base and data.base.term then prefix_sort_base = strip_diacritics_no_links(data.base.lang, data.base.term) elseif data.suffix.term then prefix_sort_base = strip_diacritics_no_links(data.suffix.lang, data.suffix.term) end -- Insert the categories and parts. local categories = {} insert(parts_formatted, export.link_term(data.prefix, data)) insert_affix_category(categories, data.pos, "prefix", data.prefix.term, data.prefix, data.sort_key, prefix_sort_base) if data.base then insert(parts_formatted, export.link_term(data.base, data)) end insert(parts_formatted, export.link_term(data.suffix, data)) -- FIXME, should we be specifying a sort base here? insert_affix_category(categories, data.pos, "suffix", data.suffix.term, data.suffix) return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end --[==[ Implementation of {{tl|infix}}. '''WARNING''': This destructively modifies both `data` and `.base` and `.infix`. ]==] function export.show_infix(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. make_part_into_affix(data.infix, data.lang, data.sc, "infix") track_wrong_affix_type("infix", data.base, nil) track_wrong_affix_type("infix", data.infix, "infix") -- Make links out of all the parts. local parts_formatted = {} local categories = {} insert(parts_formatted, export.link_term(data.base, data)) insert(parts_formatted, export.link_term(data.infix, data)) -- Insert the categories. -- FIXME, should we be specifying a sort base here? insert_affix_category(categories, data.pos, "infix", data.infix.term, data.infix) return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end --[==[ Implementation of {{tl|prefix}}. '''WARNING''': This destructively modifies both `data` and the structures within `.prefixes`, as well as `.base`. ]==] function export.show_prefix(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. for i, prefix in ipairs(data.prefixes) do make_part_into_affix(prefix, data.lang, data.sc, "prefix") end for i, prefix in ipairs(data.prefixes) do track_wrong_affix_type("prefix", prefix, "prefix") end track_wrong_affix_type("prefix", data.base, nil) -- Make links out of all the parts. local parts_formatted = {} local first_sort_base = nil local categories = {} if data.prefixes[2] then first_sort_base = ine(data.prefixes[2].term) or ine(data.prefixes[2].alt) if first_sort_base then first_sort_base = strip_diacritics_no_links(data.prefixes[2].lang, first_sort_base) end elseif data.base then first_sort_base = ine(data.base.term) or ine(data.base.alt) if first_sort_base then first_sort_base = strip_diacritics_no_links(data.base.lang, first_sort_base) end end for i, prefix in ipairs(data.prefixes) do insert(parts_formatted, export.link_term(prefix, data)) generate_one_part_categories(categories, data, prefix, "prefix", prefix.term, data.sort_key, i == 1 and first_sort_base or nil) end if data.base then insert(parts_formatted, export.link_term(data.base, data)) else insert(parts_formatted, "") end return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end --[==[ Implementation of {{tl|suffix}}. '''WARNING''': This destructively modifies both `data` and the structures within `.suffixes`, as well as `.base`. ]==] function export.show_suffix(data) local categories = {} data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. for i, suffix in ipairs(data.suffixes) do make_part_into_affix(suffix, data.lang, data.sc, "suffix") end track_wrong_affix_type("suffix", data.base, nil) for i, suffix in ipairs(data.suffixes) do track_wrong_affix_type("suffix", suffix, "suffix") end -- Make links out of all the parts. local parts_formatted = {} if data.base then insert(parts_formatted, export.link_term(data.base, data)) else insert(parts_formatted, "") end for i, suffix in ipairs(data.suffixes) do insert(parts_formatted, export.link_term(suffix, data)) end -- Insert the categories. for i, suffix in ipairs(data.suffixes) do -- FIXME, should we be specifying a sort base here? generate_one_part_categories(categories, data, suffix, "suffix", suffix.term) end return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end return export 9xcovtr8fgpuq9eoxs0jleym6tojjsp 239024 239023 2026-11-15T04:02:18Z Lee 19 පැරණි සංස්කරණයකින් ගත් කොටස්... 239024 Scribunto text/plain local m_sinhala = require("Module:sinhala") local export = {} local debug_force_cat = false -- if set to true, always display categories even on userspace pages local m_links = require("Module:links") local m_str_utils = require("Module:string utilities") local m_table = require("Module:table") local decorations_module = "Module:decorations" local en_utilities_module = "Module:en-utilities" local etymology_module = "Module:etymology" local scripts_module = "Module:scripts" local utilities_module = "Module:utilities" -- Export this so the category code in [[Module:category tree/etymology]] can access it. export.affix_lang_data_module_prefix = "Module:affix/lang-data/" local ulen = m_str_utils.len local ufind = m_str_utils.find local umatch = m_str_utils.match local pluralize = require(en_utilities_module).pluralize local singularize = require(en_utilities_module).singularize local u = m_str_utils.char local ucfirst = m_str_utils.ucfirst local concat = table.concat local insert = table.insert local unpack = unpack or table.unpack -- Lua 5.2 compatibility function export.affix_variants(canonical, variants) local mappings = {} for _, variant in ipairs(variants) do mappings[variant] = canonical end return mappings end function export.id_mapping(default, ids) local mapping = { default = default } if ids then for id, target in pairs(ids) do mapping[id] = target end end return mapping end function export.id_mapping_with_affix_variants(base, id_variants) local mappings = {} for id, variants in pairs(id_variants) do for _, variant in ipairs(variants) do mappings[variant] = export.id_mapping(base, {[id] = base}) end end return mappings end function export.merge_tables(...) local result = {} for i = 1, select('#', ...) do local t = select(i, ...) if t then for k, v in pairs(t) do result[k] = v end end end return result end -- Export this so the category code in [[Module:category tree/etymology]] can access it. export.langs_with_lang_specific_data = { ["az"] = true, ["fi"] = true, ["fr"] = true, ["izh"] = true, ["la"] = true, ["sah"] = true, ["tr"] = true, ["trk-pro"] = true, } local default_pos = "term" local function pluralize_pos(pos) return pluralize(singularize(pos)) end --[==[ intro: ===About different types of hyphens ("template", "display" and "lookup"):=== * The "template hyphen" is the per-script hyphen character that is used in template calls to indicate that a term is an affix. This is always a single Unicode char, but there may be multiple possible hyphens for a given script. Normally this is just the regular hyphen character "-", but for some non-Latin-script languages (currently only right-to-left languages), it is different. * The "display hyphen" is the string (which might be an empty string) that is added onto a term as displayed and linked, to indicate that a term is an affix. Currently this is always either the same as the template hyphen or an empty string, but the code below is written generally enough to handle arbitrary display hyphens. Specifically: *# For East Asian languages, the display hyphen is always blank. *# For Arabic-script languages, either tatweel (ـ) or ZWNJ (zero-width non-joiner) are allowed as template hyphens, where ZWNJ is supported primarily for Farsi, because some suffixes have non-joining behavior. The display hyphen corresponding to tatweel is also tatweel, but the display hyphen corresponding to ZWNJ is blank (tatweel is also the default display hyphen, for calls to {{tl|prefix}}/{{tl|suffix}}/etc. that don't include an explicit hyphen). * The "lookup hyphen" is the hyphen that is used when looking up language-specific affix mappings. (These mappings are discussed in more detail below when discussing link affixes.) It depends only on the script of the affix in question. Most scripts (including East Asian scripts) use a regular hyphen "-" as the lookup hyphen, but Hebrew and Arabic have their own lookup hyphens (respectively maqqef and tatweel). Note that for Arabic in particular, there are three possible template hyphens that are recognized (tatweel, ZWNJ and regular hyphen), but mappings must use tatweel. ===About different types of affixes ("template", "display", "link", "lookup" and "category"):=== * A "template affix" is an affix in its source form as it appears in a template call. Generally, a template affix has an attached template hyphen (see above) to indicate that it is an affix and indicate what type of affix it is (prefix, suffix, interfix or circumfix), but some of the older-style templates such as {{tl|suffix}}, {{tl|prefix}}, {{tl|confix}}, etc. have "positional" affixes where the presence of the affix in a certain position (e.g. the second or third parameter) indicates that it is a certain type of affix, whether or not it has an attached template hyphen. * A "display affix" is the corresponding affix as it is actually displayed to the user. The display affix may differ from the template affix for various reasons: *# The display affix may be specified explicitly using the {{para|alt<var>N</var>}} parameter, the `<alt:...>` inline modifier or a piped link of the form e.g. `<nowiki>[[-kas|-käs]]</nowiki>` (here indicating that the affix should display as `-käs` but be linked as `-kas`). Here, the template affix is arguably the entire piped link, while the display affix is `-käs`. *# Even in the absence of {{para|alt<var>N</var>}} parameters, `<alt:...>` inline modifiers and piped links, certain languages have differences between the "template hyphen" specified in the template (which always needs to be specified somehow or other in templates like {{tl|affix}}, to indicate that the term is an affix and what type of affix it is) and the display hyphen (see above), with corresponding differences between template and display affixes. * A (regular) "link affix" is the affix that is linked to when the affix is shown to the user. The link affix is usually the same as the display affix, but will differ in one of three circumstances: *# The display and link affixes are explicitly made different using {{para|alt<var>N</var>}} parameters, `<alt:...>` inline modifiers or piped links, as described above under "display affix". *# For certain languages, certain affixes are mapped to canonical form using language-specific mappings. For example, in Finnish, the adjective-forming suffix {{m|fi|-kas}} appears as {{m|fi|-käs}} after front vowels, but logically both forms are the same suffix and should be linked and categorized the same. Similarly, in Latin, the negative and intensive prefixes spelled {{m|la|in-}} (etymologically two distinct prefixes) appear variously as {{m|la|il-}}, {{m|la|im-}} or {{m|la|ir-}} before certain consonants. Mappings are supplied in [[Module:affix/lang-data/LANGCODE]] to convert Finnish {{m|fi|-käs}} to {{m|fi|-kas}} for linking and categorization purposes. Note that the affixes in the mappings use "lookup hyphens" to indicate the different types of affixes, which is usually the same as the template hyphen but differs for Arabic scripts, because there are multiple possible template hyphens recognized but only one lookup hyphen (tatweel). The form of the affix as used to look up in the mapping tables is called the "lookup affix"; see below. * A "stripped link affix" is a link affix that has been passed through the language's `stripDiacritics()` function, which may strip certain diacritics: e.g. macrons in Latin and Old English (indicating length); acute and grave accents in Russian and various other Slavic languages (indicating stress); vowel diacritics in most Arabic-script languages; and also tatweel in some Arabic-script languages (currently, for example, Persian, Arabic and Urdu strip tatweel, but Ottoman Turkish does not). Stripped link affixes are currently what are used in category names. * A "lookup affix" is the form of the affix as it is looked up in the language-specific lookup mappings described above under link affixes. There are actually two lookup stages: *# First, the affix is looked up in a modified display form (specifically, the same as the display affix but using lookup hyphens). Note that this lookup does not occur if an explicit display form is given using {{para|alt<var>N</var>}} or an `<alt:...>` inline modifier, or if the template affix contains a piped or embedded link. *# If no entry is found, the affix is then looked up in a modified link form (specifically, the modified display form passed through the language's `stripDiacritics()` function, which strips out certain diacritics, but with the lookup hyphen re-added if it was stripped out, as in the case of tatweel in many Arabic-script languages). The reason for this double lookup procedure is to allow for mappings that are sensitive to the extra diacritics, but also allow for mappings that are not sensitive in this fashion (e.g. Russian {{m|ru|-ливый}} occurs both stressed and unstressed, but is the same prefix either way). * A "category affix" is the affix as it appears in categories such as [[:Category:Finnish terms suffixed with -kas| Category:Finnish terms suffixed with ''-kas'']]. The category affix is currently always the same as the stripped link affix. This means that for Arabic-script languages, it may or may not have a tatweel, even if the correponding display affix and regular link affix have a tatweel. As mentioned above, stripDiacritics() strips tatweel for Arabic, Persian and Urdu, but not for Ottoman Turkish. Hence affix categories for Arabic, Persian and Urdu will be missing the tatweel, but affix categories for Ottoman Turkish will have it. An additional complication is that if the template affix contains a ZWNJ, the display (and hence the link and category affixes) will have no hyphen attached in any case. ]==] ----------------------------------------------------------------------------------------- -- Template and display hyphens -- ----------------------------------------------------------------------------------------- --[=[ Per-script template hyphens. The template hyphen is what appears in the {{affix}}/{{prefix}}/{{suffix}}/etc. template (in the wikicode). See above. They key below is a script code, after removing a hyphen and anything preceding. Hence, script codes like 'mnc-Mong' and 'xwo-Mong' will match 'Mong'. The value below is a string consisting of one or more hyphen characters. If there is more than one character, the default hyphen must come last and a non-default function must be specified for the script in display_hyphens[] so the correct display hyphen will be specified when no template hyphen is given (in {{suffix}}/{{prefix}}/etc.). Script detection is normally done when linking, but we need to do it earlier. However, under most circumstances we don't need to do script detection. Specifically, we only need to do script detection for a given language if (a) the language has multiple scripts; and (b) at least one of those scripts is listed below or in display_hyphens. ]=] local ZWNJ = u(0x200C) -- zero-width non-joiner local template_hyphens = { -- This covers all Arabic scripts. See above. ["Arab"] = "ـ" .. ZWNJ .. "-", -- tatweel + zero-width non-joiner + regular hyphen ["Aran"] = "ـ" .. ZWNJ .. "-", -- tatweel + zero-width non-joiner + regular hyphen ["Hebr"] = "־", -- Hebrew-specific hyphen termed "maqqef" ["Mong"] = "᠊", -- FIXME! What about the following right-to-left scripts? -- Adlm (Adlam) -- Armi (Imperial Aramaic) -- Avst (Avestan) -- Cprt (Cypriot) -- Khar (Kharoshthi) -- Mand (Mandaic/Mandaean) -- Mani (Manichaean) -- Mend (Mende/Mende Kikakui) -- Narb (Old North Arabian) -- Nbat (Nabataean/Nabatean) -- Nkoo (N'Ko) -- Orkh (Orkhon runes) -- Phli (Inscriptional Pahlavi) -- Phlp (Psalter Pahlavi) -- Phlv (Book Pahlavi) -- Phnx (Phoenician) -- Prti (Inscriptional Parthian) -- Rohg (Hanifi Rohingya) -- Samr (Samaritan) -- Sarb (Old South Arabian) -- Sogd (Sogdian) -- Sogo (Old Sogdian) -- Syrc (Syriac) -- Thaa (Thaana) } -- Hyphens used when looking up an affix in a lang-specific affix mapping. Defaults to regular hyphen (-). The keys -- are script codes, after removing a hyphen and anything preceding. Hence, script codes like 'mnc-Mong' and 'xwo-Mong' -- will match 'Mong'. The value should be a single character. local lookup_hyphens = { ["Hebr"] = "־", -- This covers all Arabic scripts. See above. ["Arab"] = "ـ", ["Aran"] = "ـ", } -- Default display-hyphen function. local function default_display_hyphen(script, hyph) if not hyph then return template_hyphens[script] or "-" end return hyph end local function arab_get_display_hyphen(_script, hyph) if not hyph then return "ـ" -- tatweel elseif hyph == ZWNJ then return "" else return hyph end end local function no_display_hyphen(_script, _hyph) return "" end -- Per-script function to return the correct display hyphen given the script and template hyphen. The function should -- also handle the case where the passed-in template hyphen is nil, corresponding to the situation in -- {{prefix}}/{{suffix}}/etc. where no template hyphen is specified. The key is the script code after removing a hyphen -- and anything preceding, so 'mnc-Mong', 'xwo-Mong' etc. will match 'Mong'. local display_hyphens = { -- This covers all Arabic scripts. See above. ["Arab"] = arab_get_display_hyphen, ["Aran"] = arab_get_display_hyphen, ["Bopo"] = no_display_hyphen, ["Hani"] = no_display_hyphen, ["Hans"] = no_display_hyphen, ["Hant"] = no_display_hyphen, -- The following is a mixture of several scripts. Hopefully the specs here are correct! ["Jpan"] = no_display_hyphen, ["Jurc"] = no_display_hyphen, ["Kitl"] = no_display_hyphen, ["Kits"] = no_display_hyphen, ["Laoo"] = no_display_hyphen, ["Nshu"] = no_display_hyphen, ["Shui"] = no_display_hyphen, ["Tang"] = no_display_hyphen, ["Thaa"] = no_display_hyphen, ["Thai"] = no_display_hyphen, ["Tibt"] = no_display_hyphen, } ----------------------------------------------------------------------------------------- -- Basic Utility functions -- ----------------------------------------------------------------------------------------- local function glossary_link(entry, text) text = text or entry return "[[Appendix:Glossary#" .. entry .. "|" .. text .. "]]" end local function track(page) if type(page) == "table" then for i, pg in ipairs(page) do page[i] = "affix/" .. pg end else page = "affix/" .. page end require("Module:debug/track")(page) end local function ine(val) return val ~= "" and val or nil end ----------------------------------------------------------------------------------------- -- Compound types -- ----------------------------------------------------------------------------------------- local function make_compound_type(typ, alttext) return { text = glossary_link(typ, alttext) .. " compound", cat = typ .. " compounds", } end -- Make a compound type entry with a simple rather than glossary link. -- These should be replaced with a glossary link when the entry in the glossary -- is created. local function make_non_glossary_compound_type(typ, alttext) local link = alttext and "[[" .. typ .. "|" .. alttext .. "]]" or "[[" .. typ .. "]]" return { text = link .. " compound", cat = typ .. " compounds", } end local function make_raw_compound_type(typ, alttext) return { text = glossary_link(typ, alttext), cat = pluralize(typ), } end local function make_borrowing_type(typ, alttext) return { text = glossary_link(typ, alttext), borrowing_type = pluralize(typ), } end export.etymology_types = { ["adapted borrowing"] = make_borrowing_type("adapted borrowing"), ["adap"] = "adapted borrowing", ["abor"] = "adapted borrowing", ["alliterative"] = make_non_glossary_compound_type("alliterative"), ["allit"] = "alliterative", ["antonymous"] = make_non_glossary_compound_type("antonymous"), ["ant"] = "antonymous", ["bahuvrihi"] = make_compound_type("bahuvrihi", "bahuvrīhi"), ["bahu"] = "bahuvrihi", ["bv"] = "bahuvrihi", ["coordinative"] = make_compound_type("coordinative"), ["coord"] = "coordinative", ["descriptive"] = make_compound_type("descriptive"), ["desc"] = "descriptive", ["determinative"] = make_compound_type("determinative"), ["det"] = "determinative", ["dvandva"] = make_compound_type("dvandva"), ["dva"] = "dvandva", ["dvigu"] = make_compound_type("dvigu"), ["dvi"] = "dvigu", ["endocentric"] = make_compound_type("endocentric"), ["endo"] = "endocentric", ["exocentric"] = make_compound_type("exocentric"), ["exo"] = "exocentric", ["izafet I"] = make_compound_type("izafet I"), ["iz1"] = "izafet I", ["izafet II"] = make_compound_type("izafet II"), ["iz2"] = "izafet II", ["izafet III"] = make_compound_type("izafet III"), ["iz3"] = "izafet III", ["karmadharaya"] = make_compound_type("karmadharaya", "karmadhāraya"), ["karma"] = "karmadharaya", ["kd"] = "karmadharaya", ["kenning"] = make_raw_compound_type("kenning"), ["ken"] = "kenning", ["rhyming"] = make_non_glossary_compound_type("rhyming"), ["rhy"] = "rhyming", ["synonymous"] = make_non_glossary_compound_type("synonymous"), ["syn"] = "synonymous", ["tatpurusa"] = make_compound_type("tatpurusa", "tatpuruṣa"), ["tat"] = "tatpurusa", ["tp"] = "tatpurusa", } local function process_etymology_type(typ, nocap, notext, has_parts) local text_sections = {} local categories = {} local borrowing_type if typ then local typdata = export.etymology_types[typ] if type(typdata) == "string" then typdata = export.etymology_types[typdata] end if not typdata then error("Internal error: Unrecognized type '" .. typ .. "'") end local text = typdata.text if not nocap then text = ucfirst(text) end local cat = typdata.cat borrowing_type = typdata.borrowing_type local oftext = typdata.oftext or " of" if not notext then insert(text_sections, text) if has_parts then insert(text_sections, oftext) insert(text_sections, " ") end end if cat then insert(categories, cat) end end return text_sections, categories, borrowing_type end ----------------------------------------------------------------------------------------- -- Utility functions -- ----------------------------------------------------------------------------------------- -- Iterate an array up to the greatest integer index found. local function ipairs_with_gaps(t) local indices = m_table.numKeys(t) local max_index = #indices > 0 and math.max(unpack(indices)) or 0 local i = 0 return function() if i < max_index then i = i + 1 return i, t[i] end end end export.ipairs_with_gaps = ipairs_with_gaps --[==[ Join formatted parts together with any overall {{para|lit}} spec, overall left and/or right qualifiers and labels, and categories. On input, `data` is a structure with the following fields: * `affixdata`: The affix data passed into an entry point such as `##show_affix()`; the code in this function examines the `lang`, `lit`, `force_cat`, `nocat`, `sort_key`, `q`, `qq`, `l` and `ll` fields of this structure, which represent overall values for these properties (as opposed to per-part values, which are found inside the list of per-part objects in `parts`, which are not examined); * `parts_formatted`: List of formatted parts, each a string; * `separator_already_added`: If true, any separators have already been included in `parts_formatted`, so the values should be concatenated with nothing in between; otherwise, the separator {" +&lrm; "} will be used, i.e. a `+` sign surrounded by spaces along with a Unicode left-to-right character to ensure that the parts appear in left-to-right order even if they contain right-to-left text; * `categories`: List of category strings or category objects; category strings are formatted using the `sort_key` field in the affix data structure in `affixdata`, while category objects, which are of the form `{ {cat=``category``, sort_key=``sort_key``, sort_base=``sort_base``}`, specify their own sort key and sort base; if `affixdata.nocat` is given, no categories are added; otherwise, `affixdata.force_cat` or global variable `debug_force_cat` causes categories to be added even on userspace pages. ]==] function export.join_formatted_parts(data) local cattext local affixdata = data.affixdata local lang = affixdata.lang local force_cat = affixdata.force_cat or debug_force_cat if affixdata.nocat then cattext = "" else for i, cat in ipairs(data.categories) do if type(cat) == "table" then data.categories[i] = require(utilities_module).format_categories(lang:getFullName() .. " " .. cat.cat, lang, cat.sort_key, cat.sort_base, force_cat) else data.categories[i] = require(utilities_module).format_categories(lang:getFullName() .. " " .. cat, lang, affixdata.sort_key, nil, force_cat) end end cattext = concat(data.categories) end local result = concat(data.parts_formatted, not data.separator_already_added and " +&lrm; " or nil) .. (affixdata.lit and ", literally " .. m_links.mark(affixdata.lit, "gloss") or "") local q = affixdata.q local qq = affixdata.qq local l = affixdata.l local ll = affixdata.ll if q and q[1] or qq and qq[1] or l and l[1] or ll and ll[1] then result = require(decorations_module).format_decorations { lang = lang, text = result, q = q, qq = qq, l = l, ll = ll, } end return result .. cattext end -- Remove links and call lang:stripDiacritics(term). local function strip_diacritics_no_links(lang, term) return lang:stripDiacritics(m_links.remove_links(term)) end --[=[ Convert a raw part as passed into an entry point into a part ready for linking. `lang` and `sc` are the overall language and script objects. This uses the overall language and script objects as defaults for the part and parses off any fragment from the term. We need to do the latter so that fragments don't end up in categories and so that we correctly do affix mapping even in the presence of fragments. ]=] local function canonicalize_part(part, lang, sc) if not part then return end -- Save the original (user-specified, part-specific) value of `lang`. If such a value is specified, we don't insert -- a '*fixed with' category, and we format the part using format_derived() in [[Module:etymology]] rather than -- full_link() in [[Module:links]]. part.part_lang = part.lang part.lang = part.lang or lang part.sc = part.sc or sc local term = part.term if not term then return elseif not part.fragment then part.term, part.fragment = m_links.get_fragment(term) else part.term = m_links.get_fragment(term) end end --[==[ Construct a single linked part based on the information in `part`, for use by `show_affix()` and other entry points. This should be called after `canonicalize_part()` is called on the part. This is a thin wrapper around `full_link()` in [[Module:links]] unless `part.part_lang` is specified (indicating that a part-specific language was given), in which case `format_derived()` in [[Module:etymology]] is called to display a term in a language other than the language of the overall term (specified in `data.lang`). `data` contains the entire object passed into the entry point and is used to access information for constructing the categories added by `format_derived()`. ]==] function export.link_term(part, data, include_separator) local result if part.part_lang then result = require(etymology_module).format_derived { lang = data.lang, terms = {part}, sources = {part.lang}, sort_key = data.sort_key, nocat = data.nocat, template_name = "affix", decorations_on_outside = true, borrowing_type = data.borrowing_type, force_cat = data.force_cat or debug_force_cat, } else result = m_links.full_link(part, "term") end if include_separator and part.separator then return part.separator .. result else return result end end local function canonicalize_script_code(scode) -- Convert 'mnc-Mong', 'xwo-Mong' etc. to 'Mong'. return (scode:gsub("^.*%-", "")) end ----------------------------------------------------------------------------------------- -- Affix-handling functions -- ----------------------------------------------------------------------------------------- -- Figure out the appropriate script for the given affix and language (unless the script is explicitly passed in), and -- return the values of template_hyphens[], display_hyphens[] and lookup_hyphens[] for that script, substituting -- default values as appropriate. Four values are returned: -- DETECTED_SCRIPT, TEMPLATE_HYPHEN, DISPLAY_HYPHEN, LOOKUP_HYPHEN local function detect_script_and_hyphens(text, lang, sc) local scode -- 1. If the script is explicitly passed in, use it. if sc then scode = sc:getCode() else local possible_script_codes = lang:getScriptCodes() -- YUCK! `possible_script_codes` comes from loadData() so #possible_scripts doesn't work (always returns 0). local num_possible_script_codes = m_table.length(possible_script_codes) if num_possible_script_codes == 0 then -- This shouldn't happen; if the language has no script codes, -- the list {"None"} should be returned. error("Something is majorly wrong! Language " .. lang:getCanonicalName() .. " has no script codes.") end if num_possible_script_codes == 1 then -- 2. If the language has only one possible script, use it. scode = possible_script_codes[1] else -- 3. Check if any of the possible scripts for the language have non-default values for template_hyphens[] -- or display_hyphens[]. If so, we need to do script detection on the text. If not, just use "Latn", -- which may not be technically correct but produces the right results because Latn has all default -- values for template_hyphens[] and display_hyphens[]. local may_have_nondefault_hyphen = false for _, script_code in ipairs(possible_script_codes) do script_code = canonicalize_script_code(script_code) if template_hyphens[script_code] or display_hyphens[script_code] then may_have_nondefault_hyphen = true break end end if not may_have_nondefault_hyphen then scode = "Latn" else scode = lang:findBestScript(text):getCode() end end end scode = canonicalize_script_code(scode) local template_hyphen = template_hyphens[scode] or "-" local lookup_hyphen = lookup_hyphens[scode] or "-" local display_hyphen = display_hyphens[scode] or default_display_hyphen return scode, template_hyphen, display_hyphen, lookup_hyphen end --[=[ Given a template affix `term` and an affix type `affix_type`, change the relevant template hyphen(s) in the affix to the display or lookup hyphen specified in `new_hyphen`, or add them if they are missing. `new_hyphen` can be a string, specifying a fixed hyphen, or a function of two arguments (the script code `scode` and the discovered template hyphen, or nil of no relevant template hyphen is present). `thyph_re` is a Lua pattern (which must be enclosed in parens) that matches the possible template hyphens. Note that not all template hyphens present in the affix are changed, but only the "relevant" ones (e.g. for a prefix, a relevant template hyphen is one coming at the end of the affix). ]=] local function reconstruct_term_per_hyphens(term, affix_type, scode, thyph_re, new_hyphen) local function get_hyphen(hyph) if type(new_hyphen) == "string" then return new_hyphen end return new_hyphen(scode, hyph) end if affix_type == "non-affix" then return term elseif affix_type == "circumfix" then local before, before_hyphen, after_hyphen, after = umatch(term, "^(.*)" .. thyph_re .. " " .. thyph_re .. "(.*)$") if not before or ulen(term) <= 3 then -- Unlike with other types of affixes, don't try to add hyphens in the middle of the term to convert it to -- a circumfix. Also, if the term is just hyphen + space + hyphen, return it. return term end return before .. get_hyphen(before_hyphen) .. " " .. get_hyphen(after_hyphen) .. after elseif affix_type == "infix" or affix_type == "interfix" then local before_hyphen, middle, after_hyphen = umatch(term, "^" .. thyph_re .. "(.*)" .. thyph_re .. "$") if before_hyphen and ulen(term) <= 1 then -- If the term is just a hyphen, return it. return term end return get_hyphen(before_hyphen) .. (middle or term) .. get_hyphen(after_hyphen) elseif affix_type == "prefix" then local middle, after_hyphen = umatch(term, "^(.*)" .. thyph_re .. "$") if middle and ulen(term) <= 1 then -- If the term is just a hyphen, return it. return term end return (middle or term) .. get_hyphen(after_hyphen) elseif affix_type == "suffix" then local before_hyphen, middle = umatch(term, "^" .. thyph_re .. "(.*)$") if before_hyphen and ulen(term) <= 1 then -- If the term is just a hyphen, return it. return term end return get_hyphen(before_hyphen) .. (middle or term) else error(("Internal error: Unrecognized affix type '%s'"):format(affix_type)) end end --[=[ Look up a mapping from a given affix variant to the canonical form used in categories and links. The lookup tables are language-specific according to `lang`, and may be ID-specific according to `affix_id`. The affixes as they appear in the lookup tables (both the variant and the canonical form) are in "lookup affix" format (approximately speaking, they use a regular hyphen for most scripts, but a tatweel for Arabic-script entries and a maqqef for Hebrew-script entries), but the passed-in `affix` param is in "template affix" format (which differs from the lookup affix for Arabic-script entries, because more types of hyphens are allowed in template affixes; see the comments at the top of the file). The remaining parameters to this function are used to convert from template affixes to lookup affixes; see the reconstruct_term_per_hyphens() function above. If the affix contains brackets, no lookup is done. Otherwise, a two-stage process is used, first looking up the affix directly and then stripping diacritics and looking it up again. The reason for this is documented above in the comments at the top of the file (specifically, the comments describing lookup affixes). The value of a mapping can either be a string (do the mapping regardless of affix ID) or a table indexed by affix ID (where the special value `false` indicates no affix ID). The values of entries in this table can also be strings, or tables with keys `affix` and `id` (again, use `false` to indicate no ID). This allows an affix mapping to map from one ID to another (for example, this is used in English to map the [[an-]] prefix with no ID to the [[a-]] prefix with the ID 'not'). The Given a template affix `term` and an affix type `affix_type`, change the relevant template hyphen(s) in the affix to the display or lookup hyphen specified in `new_hyphen`, or add them if they are missing. `new_hyphen` can be a string, specifying a fixed hyphen, or a function of two arguments (the script code `scode` and the discovered template hyphen, or nil of no relevant template hyphen is present). `thyph_re` is a Lua pattern (which must be enclosed in parens) that matches the possible template hyphens. Note that not all template hyphens present in the affix are changed, but only the "relevant" ones (e.g. for a prefix, a relevant template hyphen is one coming at the end of the affix). ]=] local function lookup_affix_mapping(affix, affix_type, lang, scode, thyph_re, lookup_hyph, affix_id) local function do_lookup(afx) -- Ensure that the affix uses lookup hyphens regardless of whether it used a different type of hyphens before -- or no hyphens. local lookup_affix = reconstruct_term_per_hyphens(afx, affix_type, scode, thyph_re, lookup_hyph) local function do_lookup_for_langcode(langcode) if export.langs_with_lang_specific_data[langcode] then local langdata = mw.loadData(export.affix_lang_data_module_prefix .. langcode) if langdata.affix_mappings then local mapping = langdata.affix_mappings[lookup_affix] if mapping then if type(mapping) == "table" then mapping = mapping[affix_id] or mapping.default or mapping[affix_id or false] if mapping then return mapping end else return mapping end end end end end -- If `lang` is an etymology-only language, look for a mapping both for it and its full parent. local langcode = lang:getCode() local mapping = do_lookup_for_langcode(langcode) if mapping then return mapping end local full_langcode = lang:getFullCode() if full_langcode ~= langcode then mapping = do_lookup_for_langcode(full_langcode) if mapping then return mapping end end return nil end if affix:find("%[%[") then return nil end return do_lookup(affix) or do_lookup(lang:stripDiacritics(affix)) or nil end --[==[ For a given template term in a given language (see the definition of "template affix" near the top of the file), possibly in an explicitly specified script `sc` (but usually nil), return the term's affix type ({"prefix"}, {"interfix"}, {"suffix"}, {"circumfix"} or {"non-affix"}) along with the corresponding link and display affixes (see definitions near the top of the file); also the corresponding lookup affix (if `return_lookup_affix` is specified). The term passed in should already have any fragment (after the # sign) parsed off of it. Four values are returned: `affix_type`, `link_term`, `display_term` and `lookup_term`. The affix type can be passed in instead of autodetected; in this case, the template term need not have any attached hyphens, and the appropriate hyphens will be added in the appropriate places. If `do_affix_mapping` is specified, look up the affix in the lang-specific affix mappings, as described in the comment at the top of the file; otherwise, the link and display terms will always be the same. (They will be the same in any case if the template term has a bracketed link in it or is not an affix.) If `return_lookup_affix` is given, the fourth return value contains the term with appropriate lookup hyphens in the appropriate places; otherwise, it is the same as the display term. (This functionality is used in [[Module:category tree/affixes and compounds]] to convert link affixes into lookup affixes so that they can be looked up in the affix mapping tables.) Exported because used by [[Module:headword utilities]] to determine the affix type of a given pagename. ]==] function export.parse_term_for_affixes(term, lang, sc, affix_type, do_affix_mapping, return_lookup_affix, affix_id) if not term then return "non-affix", nil, nil, nil end if term == "^" then -- Indicates a null term to emulate the behavior of {{suffix|foo||bar}}. term = nil return "non-affix", term, term, term end if term:find("^%^") then -- HACK! ^ at the beginning of Korean languages has a special meaning, triggering capitalization of the -- transliteration. Don't interpret it as "force non-affix" for those languages. local langcode = lang:getCode() if langcode ~= "ko" and langcode ~= "okm" and langcode ~= "jje" then -- Formerly we allowed ^ to force non-affix type; this is now handled using an inline modifier -- <naf>, <root>, etc. Throw an error for the moment when the old way is encountered. error("Use of ^ to force non-affix status is no longer supported; use an inline modifier <naf> or <root> " .. "after the component") end end -- Remove an asterisk if the morpheme is reconstructed and add it back at the end. local reconstructed = "" if term:find("^%*") then reconstructed = "*" term = term:gsub("^%*", "") end local scode, thyph, dhyph, lhyph = detect_script_and_hyphens(term, lang, sc) thyph = "([" .. thyph .. "])" if not affix_type then if ufind(term, thyph .. " " .. thyph) then affix_type = "circumfix" else local has_beginning_hyphen = ufind(term, "^" .. thyph) local has_ending_hyphen = ufind(term, thyph .. "$") if has_beginning_hyphen and has_ending_hyphen then affix_type = "interfix" elseif has_ending_hyphen then affix_type = "prefix" elseif has_beginning_hyphen then affix_type = "suffix" else affix_type = "non-affix" end end end local link_term, display_term, lookup_term if affix_type == "non-affix" then link_term = term display_term = term lookup_term = term else display_term = reconstruct_term_per_hyphens(term, affix_type, scode, thyph, dhyph) if do_affix_mapping then link_term = lookup_affix_mapping(term, affix_type, lang, scode, thyph, lhyph, affix_id) -- The return value of lookup_affix_mapping() may be an affix mapping with lookup hyphens if a mapping -- was found, otherwise nil if a mapping was not found. We need to convert to display hyphens in -- either case, but in the latter case we can reuse the display term, which has already been converted. if link_term then link_term = reconstruct_term_per_hyphens(link_term, affix_type, scode, thyph, dhyph) else link_term = display_term end else link_term = display_term end if return_lookup_affix then lookup_term = reconstruct_term_per_hyphens(term, affix_type, scode, thyph, lhyph) else lookup_term = display_term end end link_term = reconstructed .. link_term display_term = reconstructed .. display_term lookup_term = reconstructed .. lookup_term return affix_type, link_term, display_term, lookup_term end --[==[ Add a hyphen to a term in the appropriate place, based on the specified affix type, stripping off any existing hyphens in that place. For example, if `affix_type` == {"prefix"}, we'll add a hyphen onto the end if it's not already there (or is of the wrong type). Three values are returned: the link term, display term and lookup term. This function is a thin wrapper around `parse_term_for_affixes`; see the comments above that function for more information. Note that this function is exposed externally because it is called by [[Module:category tree/affixes and compounds]]; see the comment in `parse_term_for_affixes` for more information. ]==] function export.make_affix(term, lang, sc, affix_type, do_affix_mapping, return_lookup_affix, affix_id) if not (affix_type == "prefix" or affix_type == "suffix" or affix_type == "circumfix" or affix_type == "infix" or affix_type == "interfix" or affix_type == "non-affix") then error("Internal error: Invalid affix type " .. (affix_type or "(nil)")) end local _, link_term, display_term, lookup_term = export.parse_term_for_affixes(term, lang, sc, affix_type, do_affix_mapping, return_lookup_affix, affix_id) return link_term, display_term, lookup_term end ----------------------------------------------------------------------------------------- -- Categorization logic -- ----------------------------------------------------------------------------------------- local function insert_category(categories, cat, sort_key, sort_base) if sort_key or sort_base then insert(categories, {cat = cat, sort_key = sort_key, sort_base = sort_base}) else insert(categories, cat) end end --[=[ Insert a `*fixed with` category such as [[:Category:Welsh terms prefixed with gwe-]] into `categories`. The arguments are: * `categories`: List of category strings or objects to insert into. * `pos`: Part of speech in the category (which is often "terms" but may be something more specific). * `affix_type`: Affix type in the category (e.g. "prefix"); automatically has "ed" appended. * `link_term`: The term that appears in the category, e.g. "gwe-". If this is empty or missing, no category is inserted. * `part`: The part structure being processed. The `lang`, `part_lang`, `nocat` and `id` fields are fetched. * `sort_key`: The sort key for the specific category. If this or `sort_base` are non-nil, a category object is created holding the specified sort key and/or base, and inserted; otherwise, a cateory string is inserted. * `sort_base`: The sort base for the specific category. See `sort_key` just above. ]=] local function insert_affix_category(categories, pos, affix_type, link_term, part, sort_key, sort_base) -- Don't add a category if the link term is empty or is in a different language, or if <nocat:1> was specified for -- the part. if ine(link_term) and not part.part_lang and not part.nocat then local cat = m_sinhala.sinhala(pos) .. ", " .. strip_diacritics_no_links(part.lang, link_term) .. (part.id and " (" .. part.id .. ")" or "") .. m_sinhala.sinhala(affix_type .. "es") .. " සහිත" insert_category(categories, cat, sort_key, sort_base) end end --[=[ Generate the categories for a single part and insert into `categories`. The arguments are: * `categories` is the list to insert the categories into. * `data` is the overall affix data structure. * `part` is the per-part data structure. * `affix_type` is the type of affix (e.g. "prefix"), as appears in the `*fixed by` category. * `link_term` is the term that (prefix, suffix, etc.) mentioned in the `*fixed by` category. * `sort_key` and `sort_base` are the per-part sort keys and bases for categorization, or nil to use the overall sort key. ]=] local function generate_one_part_categories(categories, data, part, affix_type, link_term, sort_key, sort_base) if data.nocat or part.nocat then return end if part.pos and part.pos:find("patronym") then insert_category(categories, "patronymics", sort_key, sort_base) end if data.pos ~= "terms" and part.pos and part.pos:find("diminutive") then insert_category(categories, "diminutive " .. data.pos, sort_key, sort_base) end insert_affix_category(categories, data.pos, affix_type, link_term, part, sort_key, sort_base) end --[=[ Core categorization logic for affixes. This is shared between show_affix(), show_compound_like() and get_affix_categories_only(). Returns the categories array and other metadata needed for formatting. ]=] local function generate_affix_categories(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) local text_sections, categories, borrowing_type = process_etymology_type(data.type, data.surface_analysis or data.nocap, data.notext, #data.parts > 0) data.borrowing_type = borrowing_type -- Process each part local whole_words = 0 local is_affix_or_compound = false -- Canonicalize and generate links for all the parts first; then do categorization in a separate step, because when -- processing the first part for categorization, we may access the second part and need it already canonicalized. for i, part in ipairs_with_gaps(data.parts) do part = part or {} data.parts[i] = part canonicalize_part(part, data.lang, data.sc) -- Determine affix type and get link and display terms (see text at top of file). Store them in the part -- (in fields that won't clash with fields used by full_link() in [[Module:links]] or link_term()), so they -- can be used in the loop below when categorizing. part.affix_type, part.affix_link_term, part.affix_display_term = export.parse_term_for_affixes(part.term, part.lang, part.sc, part.type, not part.alt, nil, part.id) -- If link_term is an empty string, either a bare ^ was specified or an empty term was used along with inline -- modifiers. The intention in either case is not to link the term. part.term = ine(part.affix_link_term) -- If part.alt would be the same as part.term, make it nil, so that it isn't erroneously tracked as being -- redundant alt text. part.alt = part.alt or (part.affix_display_term ~= part.affix_link_term and part.affix_display_term) or nil end if not data.noaffixcat then -- Now do categorization. for i, part in ipairs_with_gaps(data.parts) do local affix_type = part.affix_type if affix_type ~= "non-affix" then is_affix_or_compound = true -- Make a sort key. For the first part, use the second part as the sort key; the intention is that if the -- term has a prefix, sorting by the prefix won't be very useful so we sort by what follows, which is -- presumably the root. local part_sort_base = nil local part_sort = part.sort or data.sort_key if i == 1 and data.parts[2] and data.parts[2].term then local part2 = data.parts[2] -- If the second-part link term is empty, the user requested an unlinked term; avoid a wikitext error -- by using the alt value if available. part_sort_base = ine(part2.affix_link_term) or ine(part2.alt) if part_sort_base then part_sort_base = strip_diacritics_no_links(part2.lang, part_sort_base) end end generate_one_part_categories(categories, data, part, affix_type, part.affix_link_term, part_sort, part_sort_base) else whole_words = whole_words + 1 if whole_words == 2 then is_affix_or_compound = true insert(categories, "සංයුක්ත " .. m_sinhala.sinhala(data.pos)) end end end -- Make sure there was either an affix or a compound (two or more non-affix terms). if not is_affix_or_compound and not data.allow_no_affixes_or_compounds then error("The parameters did not include any affixes, and the term is not a compound. Please provide at least one affix.") end end return text_sections, categories, borrowing_type end -- Return true if specified part has no term or alt and no modifiers. WARNING: Keep this up-to-date -- in case any other fields are added that are always present. local function part_is_empty(part) for k, v in pairs(part) do if k ~= "affix_type" and k ~= "lang" and k ~= "orig_index" and k ~= "itemno" and k ~= "separator" then return false end end return true end ----------------------------------------------------------------------------------------- -- Main entry points -- ----------------------------------------------------------------------------------------- --[==[ Implementation of {{tl|affix}} and {{tl|surface analysis}}. `data` contains all the information describing the affixes to be displayed, and contains the following: * `.lang` ('''required'''): Overall language object. Different from term-specific language objects (see `.parts` below). * `.sc`: Overall script object (usually omitted). Different from term-specific script objects. * `.parts` ('''required'''): List of objects describing the affixes to show. The general format of each object is as would be passed to `full_link()`, except that the `.lang` field should be missing unless the term is of a language different from the overall `.lang` value (in such a case, the language name is shown along with the term and an additional "derived from" category is added). '''WARNING''': The data in `.parts` will be destructively modified. * `.pos`: Overall part of speech (used in categories, defaults to {"terms"}). Different from term-specific part of speech. * `.sort_key`: Overall sort key. Normally omitted except e.g. in Japanese. * `.type`: Type of compound, if the parts in `.parts` describe a compound. Strictly optional, and if supplied, the compound type is displayed before the parts (normally capitalized, unless `.nocap` is given). * `.nocap`: Don't capitalize the first letter of text displayed before the parts (relevant only if `.type` or `.surface_analysis` is given). * `.notext`: Don't display any text before the parts (relevant only if `.type` or `.surface_analysis` is given). * `.nocat`: Disable all categorization. * `.noaffixcat`: Disable affix (and compound) categorization. Relevant for e.g. blends, which may otherwise be incorrectly categorized as compound terms. * `.lit`: Overall literal definition. Different from term-specific literal definitions. * `.force_cat`: Always display categories, even on userspace pages. * `.surface_analysis`: Implement {{surface analysis}}; adds `By surface analysis, ` before the parts. '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.show_affix(data) local text_sections, categories, _ = generate_affix_categories(data) -- Process each part for display local parts_formatted = {} for i, part in ipairs_with_gaps(data.parts) do -- Make a link for the part if part_is_empty(part) then if part.separator then insert(parts_formatted, part.separator) end -- don't call full_link(); we allow this to emulate the behavior of {{suf}} and {{pre}} in such cases. else insert(parts_formatted, export.link_term(part, data, "include_separator")) end end if data.surface_analysis then local text = "by " .. glossary_link("surface analysis") .. ", " if not data.nocap then text = ucfirst(text) end insert(text_sections, 1, text) end insert(text_sections, export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories, separator_already_added = true }) return concat(text_sections) end --[==[ Get only the categories that would be generated by show_affix(), without any text output or formatting. This is used by Module:etymon to get affix categorization. Returns an array of category objects, where each entry is either a string (simple category name) or a table with keys `cat`, `sort_key`, and `sort_base` for more complex categorization. `data` should have the same structure as passed to show_affix(): * `.lang` (required): Overall language object * `.parts` (required): Array of affix part objects with `.term`, `.lang`, `.id`, etc. * `.pos`: Part of speech (defaults to "terms") * `.sort_key`: Overall sort key for categories '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.get_affix_categories_only(data) local _, categories, _ = generate_affix_categories(data) return categories end function export.show_surface_analysis(data) data.surface_analysis = true data.allow_no_affixes_or_compounds = true return export.show_affix(data) end --[==[ Implementation of {{tl|compound}}. '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.show_compound(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) local text_sections, categories, borrowing_type = process_etymology_type(data.type, data.nocap, data.notext, #data.parts > 0) data.borrowing_type = borrowing_type local parts_formatted = {} insert(categories, "සංයුක්ත " .. m_sinhala.sinhala(data.pos)) -- Make links out of all the parts local whole_words = 0 for i, part in ipairs(data.parts) do canonicalize_part(part, data.lang, data.sc) -- Determine affix type and get link and display terms (see text at top of file). local affix_type, link_term, display_term = export.parse_term_for_affixes(part.term, part.lang, part.sc, part.type, not part.alt, nil, part.id) -- If the term is an interfix or the type was explicitly given, recognize it as such (which means e.g. that we -- will display the term without hyphens for East Asian languages). Otherwise, ignore the fact that it looks -- like an affix and display as specified in the template (but pay attention to the detected affix type for -- certain tracking purposes). if affix_type == "interfix" or (part.type and part.type ~= "non-affix") then -- Add a `*fixed with` category. However, if link_term is an empty string, either a bare ^ was specified or -- an empty term was used along with inline modifiers. The intention in either case is not to link the term. -- Don't add a category in this case, or if the term is in a different language (or if overall nocat=1 was -- given, or part-specific <nocat:1>). if not data.nocat then -- FIXME, should we be specifying a sort base here? insert_affix_category(categories, data.pos, affix_type, link_term, part, part.sort or data.sort_key) end -- If part.alt would be the same as part.term, make it nil, so that it isn't erroneously tracked as being -- redundant alt text. part.term = link_term ~= "" and link_term or nil part.alt = part.alt or (display_term ~= link_term and display_term) or nil else if affix_type ~= "non-affix" then local langcode = data.lang:getCode() -- If `data.lang` is an etymology-only language, track both using its code and its full parent's code. track { affix_type, affix_type .. "/lang/" .. langcode } local full_langcode = data.lang:getFullCode() if langcode ~= full_langcode then track(affix_type .. "/lang/" .. full_langcode) end else whole_words = whole_words + 1 end end insert(parts_formatted, export.link_term(part, data, "include_separator")) end if whole_words == 1 then track("one whole word") elseif whole_words == 0 then track("looks like confix") end insert(text_sections, export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories, separator_already_added = true }) return concat(text_sections) end --[==[ Implementation of {{tl|blend}}, {{tl|univerbation}} and similar "compound-like" templates. '''WARNING''': This destructively modifies both `data` and the individual structures within `.parts`. ]==] function export.show_compound_like(data) data.allow_no_affixes_or_compounds = true local text_sections, categories, _ = generate_affix_categories(data) if data.cat then insert(categories, data.cat) end -- Process each part for display local parts_formatted = {} for i, part in ipairs_with_gaps(data.parts) do -- Make a link for the part insert(parts_formatted, export.link_term(part, data, "include_separator")) end if #data.parts > 0 and data.oftext then insert(text_sections, 1, " " .. data.oftext .. " ") end if data.text then insert(text_sections, 1, data.text) end insert(text_sections, export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories, separator_already_added = true }) return concat(text_sections) end --[==[ Make `part` (a structure holding information on an affix part) into an affix of type `affix_type`, and apply any relevant affix mappings. For example, if the desired affix type is "suffix", this will (in general) add a hyphen onto the beginning of the term, alt, tr and ts components of the part if not already present. The hyphen that's added is the "display hyphen" (see above) and may be script-specific. (In the case of East Asian scripts, the display hyphen is an empty string whereas the template hyphen is the regular hyphen, meaning that any regular hyphen at the beginning of the part will be effectively removed.) `lang` and `sc` hold overall language and script objects. Note that this also applies any language-specific affix mappings, so that e.g. if the language is Finnish and the user specified [[-käs]] in the affix and didn't specify an `.alt` value, `part.term` will contain [[-kas]] and `part.alt` will contain [[-käs]]. This function is used by the "legacy" templates ({{tl|prefix}}, {{tl|suffix}}, {{tl|confix}}, etc.) where the nature of the affix is specified by the template itself rather than auto-determined from the affix, as is the case with {{tl|affix}}. '''WARNING''': This destructively modifies `part`. ]==] local function make_part_into_affix(part, lang, sc, affix_type) canonicalize_part(part, lang, sc) local link_term, display_term = export.make_affix(part.term, part.lang, part.sc, affix_type, not part.alt, nil, part.id) part.term = link_term -- When we don't specify `do_affix_mapping` to make_affix(), link and display terms (first and second retvals of -- make_affix()) are the same. -- If part.alt would be the same as part.term, make it nil, so that it isn't erroneously tracked as being -- redundant alt text. part.alt = part.alt and export.make_affix(part.alt, part.lang, part.sc, affix_type) or (display_term ~= link_term and display_term) or nil local Latn = require(scripts_module).getByCode("Latn") part.tr = export.make_affix(part.tr, part.lang, Latn, affix_type) part.ts = export.make_affix(part.ts, part.lang, Latn, affix_type) end local function track_wrong_affix_type(template, part, expected_affix_type) if part and not part.type then local affix_type = export.parse_term_for_affixes(part.term, part.lang, part.sc) if affix_type ~= expected_affix_type then local part_name = expected_affix_type or "base" local langcode = part.lang:getCode() local full_langcode = part.lang:getFullCode() require("Module:debug/track") { template, template .. "/" .. part_name, template .. "/" .. part_name .. "/" .. (affix_type or "none"), template .. "/" .. part_name .. "/" .. (affix_type or "none") .. "/lang/" .. langcode } -- If `part.lang` is an etymology-only language, track both using its code and its full parent's code. if full_langcode ~= langcode then require("Module:debug/track")( template .. "/" .. part_name .. "/" .. (affix_type or "none") .. "/lang/" .. full_langcode ) end end end end --[==[ Implementation of {{tl|confix}}. '''WARNING''': This destructively modifies both `data` and `.prefix`, `.base` and `.suffix`. ]==] function export.show_confix(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. make_part_into_affix(data.prefix, data.lang, data.sc, "prefix") make_part_into_affix(data.suffix, data.lang, data.sc, "suffix") track_wrong_affix_type("confix", data.prefix, "prefix") track_wrong_affix_type("confix", data.base, nil) track_wrong_affix_type("confix", data.suffix, "suffix") -- Make links out of all the parts. local parts_formatted = {} local prefix_sort_base if data.base and data.base.term then prefix_sort_base = strip_diacritics_no_links(data.base.lang, data.base.term) elseif data.suffix.term then prefix_sort_base = strip_diacritics_no_links(data.suffix.lang, data.suffix.term) end -- Insert the categories and parts. local categories = {} insert(parts_formatted, export.link_term(data.prefix, data)) insert_affix_category(categories, data.pos, "prefix", data.prefix.term, data.prefix, data.sort_key, prefix_sort_base) if data.base then insert(parts_formatted, export.link_term(data.base, data)) end insert(parts_formatted, export.link_term(data.suffix, data)) -- FIXME, should we be specifying a sort base here? insert_affix_category(categories, data.pos, "suffix", data.suffix.term, data.suffix) return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end --[==[ Implementation of {{tl|infix}}. '''WARNING''': This destructively modifies both `data` and `.base` and `.infix`. ]==] function export.show_infix(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. make_part_into_affix(data.infix, data.lang, data.sc, "infix") track_wrong_affix_type("infix", data.base, nil) track_wrong_affix_type("infix", data.infix, "infix") -- Make links out of all the parts. local parts_formatted = {} local categories = {} insert(parts_formatted, export.link_term(data.base, data)) insert(parts_formatted, export.link_term(data.infix, data)) -- Insert the categories. -- FIXME, should we be specifying a sort base here? insert_affix_category(categories, data.pos, "infix", data.infix.term, data.infix) return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end --[==[ Implementation of {{tl|prefix}}. '''WARNING''': This destructively modifies both `data` and the structures within `.prefixes`, as well as `.base`. ]==] function export.show_prefix(data) data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. for i, prefix in ipairs(data.prefixes) do make_part_into_affix(prefix, data.lang, data.sc, "prefix") end for i, prefix in ipairs(data.prefixes) do track_wrong_affix_type("prefix", prefix, "prefix") end track_wrong_affix_type("prefix", data.base, nil) -- Make links out of all the parts. local parts_formatted = {} local first_sort_base = nil local categories = {} if data.prefixes[2] then first_sort_base = ine(data.prefixes[2].term) or ine(data.prefixes[2].alt) if first_sort_base then first_sort_base = strip_diacritics_no_links(data.prefixes[2].lang, first_sort_base) end elseif data.base then first_sort_base = ine(data.base.term) or ine(data.base.alt) if first_sort_base then first_sort_base = strip_diacritics_no_links(data.base.lang, first_sort_base) end end for i, prefix in ipairs(data.prefixes) do insert(parts_formatted, export.link_term(prefix, data)) generate_one_part_categories(categories, data, prefix, "prefix", prefix.term, data.sort_key, i == 1 and first_sort_base or nil) end if data.base then insert(parts_formatted, export.link_term(data.base, data)) else insert(parts_formatted, "") end return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end --[==[ Implementation of {{tl|suffix}}. '''WARNING''': This destructively modifies both `data` and the structures within `.suffixes`, as well as `.base`. ]==] function export.show_suffix(data) local categories = {} data.pos = data.pos or default_pos data.pos = pluralize_pos(data.pos) canonicalize_part(data.base, data.lang, data.sc) -- Hyphenate the affixes and apply any affix mappings. for i, suffix in ipairs(data.suffixes) do make_part_into_affix(suffix, data.lang, data.sc, "suffix") end track_wrong_affix_type("suffix", data.base, nil) for i, suffix in ipairs(data.suffixes) do track_wrong_affix_type("suffix", suffix, "suffix") end -- Make links out of all the parts. local parts_formatted = {} if data.base then insert(parts_formatted, export.link_term(data.base, data)) else insert(parts_formatted, "") end for i, suffix in ipairs(data.suffixes) do insert(parts_formatted, export.link_term(suffix, data)) end -- Insert the categories. for i, suffix in ipairs(data.suffixes) do -- FIXME, should we be specifying a sort base here? generate_one_part_categories(categories, data, suffix, "suffix", suffix.term) end return export.join_formatted_parts { affixdata = data, parts_formatted = parts_formatted, categories = categories } end return export qsvq5ejulbtjw3yhx02biuu3vx97it0 Module:affix/templates 828 13856 239019 226990 2026-10-14T02:34:13Z en>Benwing2 0 support <nocat:1> at the affix term level and clean up extra_params(); support global debug_force_cat 239019 Scribunto text/plain local export = {} local debug_force_cat = false -- if set to true, always display categories even on userspace pages local m_affix = require("Module:affix") local en_utilities_module = "Module:en-utilities" local parameter_utilities_module = "Module:parameter utilities" local pseudo_loan_module = "Module:affix/pseudo-loan" local insert = table.insert local boolean_param = {type = "boolean"} local function is_property_key(k) return require(parameter_utilities_module).item_key_is_property(k) end local recognized_affix_types = { prefix = "prefix", pre = "prefix", suffix = "suffix", suf = "suffix", interfix = "interfix", inter = "interfix", infix = "infix", ["in"] = "infix", circumfix = "circumfix", circum = "circumfix", ["non-affix"] = "non-affix", naf = "non-affix", root = "non-affix", } local function pre_normalize_affix_type(data) local modtext = data.modtext modtext = modtext:match("^<(.*)>$") if not modtext then error(("Internal error: Passed-in modifier isn't surrounded by angle brackets: %s"):format(data.modtext)) end if recognized_affix_types[modtext] then modtext = "type:" .. modtext end return "<" .. modtext .. ">" end -- Parse raw arguments. A single parameter `data` is passed in, with the following fields: -- * `raw_args`: The raw arguments to parse, normally taken from `frame:getParent().args`. -- * `extra_params`: An optional function of one argument that is called on the `params` structure before parsing; its -- purpose is to specify additional allowed parameters or possibly disable parameters. -- * `has_source`: There is a source-language parameter following 1= (which becomes the "destination" language -- parameter) and preceding the terms. This is currently used for {{pseudo-loan}}. -- * `ilang`: If given, it is a language object that serves as the default for the language. If specified, there is no -- language code specified in 1=; instead the term parameters start directly at 1= (or at 2= if `has_source` is -- given). -- * `require_index_for_pos`: There is no separate |pos= parameter distinct from |pos1=, |pos2=, etc. Instead, -- specifying |pos= results in an error. -- * `dont_require_index`: Allow |foo= to be specified as a synonym for |foo1= (except for |lit=, which remains -- distinct). -- * `allow_type`: Allow |type1=, |type2=, etc. or inline <type:...> for the affix type, and allow a separate |type= -- parameter for the etymology type (FIXME: this may be confusing; consider changing the etymology type to |etype=). -- * `allow_semicolon_separator`: Allow semicolon as a separator, displaying as " or ". This requires changes in the -- display of the output, to not always put a + between the items. -- -- Note that all language parameters are allowed to be etymology-only languages. -- -- Return five values ARGS, ITEMS, LANG_OBJ, SCRIPT_OBJ, SOURCE_LANG_OBJ where ARGS is a table of the parsed arguments; -- ITEMS is the list of parsed items; LANG_OBJ is the language object corresponding to the language code specified in 1= -- (or taken from `ilang` if given); SCRIPT_OBJ is the script object corresponding to sc= (if given, otherwise nil); and -- SOURCE_LANG_OBJ is the language object corresponding to the source-language code specified in 2= (or 1= if `ilang` is -- given) if `has_source` is specified (otherwise nil). local function parse_args(data) local raw_args = data.raw_args local has_source = data.has_source local ilang = data.ilang if raw_args.lang then error("The |lang= parameter is not used by this template. Place the language code in parameter 1 instead.") end local term_index = (ilang and 1 or 2) + (has_source and 1 or 0) local params = { [term_index] = {list = true, allow_holes = true}, ["sort"] = {}, ["nocap"] = boolean_param, -- always allow this even if not used, for use with {{surf}}, which adds it ["force_cat"] = boolean_param, -- for debugging use } if not ilang then params[1] = {required = true, type = "language", default = "und"} end local source_index if has_source then source_index = term_index - 1 params[source_index] = {required = true, type = "language", default = "und"} end local m_param_utils = require(parameter_utilities_module) local param_mod_source = {} if not data.dont_require_index then insert(param_mod_source, -- We want to require an index for all params (or use separate_no_index, which also requires an index for the -- param corresponding to the first item). {default = true, require_index = true} ) end insert(param_mod_source, {group = {"link", "ref", "lang", "q", "l", "infl"}}) -- Override lit= to be separate from lit1=. insert(param_mod_source, {param = "lit", separate_no_index = true}) if not data.dont_require_index and not data.require_index_for_pos then -- Override pos= to be separate from pos1=. insert(param_mod_source, {param = "pos", separate_no_index = true}) end if data.allow_type then insert(param_mod_source, {param = "type", separate_no_index = true}) end insert(param_mod_source, {param = "nocat", type = "boolean", separate_no_index = true}) local param_mods = m_param_utils.construct_param_mods(param_mod_source) if data.extra_params then data.extra_params(params) end local items, args = m_param_utils.parse_list_with_inline_modifiers_and_separate_params { params = params, param_mods = param_mods, raw_args = raw_args, termarg = term_index, parse_lang_prefix = true, track_module = "homophones", -- the inclusion of &lrm; is what [[Module:affix]] has always done default_separator = data.allow_semicolon_separator and " +&lrm; " or nil, special_separators = data.allow_semicolon_separator and {[";"] = " or "} or nil, disallow_custom_separators = not data.allow_semicolon_separator, -- For compatibility, we need to not skip completely unspecified items. It is common, for example, to do -- {{suffix|lang||foo}} to generate "+ -foo". dont_skip_items = true, -- Allow e.g. <infix> to be specified in place of <type:infix>. pre_normalize_modifiers = pre_normalize_affix_type, -- Don't pass in `lang` or `sc`, as they will be used as defaults to initialize the items, which we don't want -- (particularly for `lang`), as the code in [[Module:affix]] uses the presence of `lang` as an indicator that -- a part-specific language was explicitly given. } local lang = ilang or args[1] local source if has_source then source = args[source_index] end -- For compatibility with the prior code, we need to convert items without term or properties to nil. for i = 1, #items do local item = items[i] local saw_item_property = item.term if not saw_item_property then for k, v in pairs(item) do if is_property_key(k) then saw_item_property = true break end end end if not saw_item_property then items[i] = nil elseif item.type then -- Validate and canonicalize affix types. if not recognized_affix_types[item.type] then local valid_types = {} for k in pairs(recognized_affix_types) do insert(valid_types, ("'%s'"):format(k)) end table.sort(recognized_affix_types) error(("Unrecognized affix type '%s' in item %s; valid values are %s"):format( item.type, item.itemno, table.concat(valid_types, ", "))) else item.type = recognized_affix_types[item.type] end end end if args.type and args.type.default and not m_affix.etymology_types[args.type.default] then error("Unrecognized etymology type: '" .. args.type.default .. "'") end return args, items, lang, args.sc.default, source end local function augment_affix_data(data, args, lang, sc) data.lang = lang data.sc = sc data.pos = args.pos and args.pos.default data.lit = args.lit and args.lit.default data.sort_key = args.sort data.type = args.type and args.type.default data.nocap = args.nocap data.notext = args.notext data.nocat = args.nocat.default data.force_cat = args.force_cat or debug_force_cat data.l = args.l.default data.ll = args.ll.default data.q = args.q.default data.qq = args.qq.default data.infl = args.infl.default return data end function export.affix(frame) local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, extra_params = extra_params, allow_type = true, allow_semicolon_separator = true, } -- There must be at least one part to display. If there are gaps, a term -- request will be shown. if not next(parts) and not args.type.default then if mw.title.getCurrentTitle().nsText == "Template" then parts = { {term = "prefix-"}, {term = "base"}, {term = "-suffix"} } else error("You must provide at least one part.") end end return m_affix.show_affix(augment_affix_data({ parts = parts }, args, lang, sc)) end function export.compound(frame) local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, extra_params = extra_params, allow_type = true, allow_semicolon_separator = true, } -- There must be at least one part to display. If there are gaps, a term -- request will be shown. if not next(parts) and not args.type.default then if mw.title.getCurrentTitle().nsText == "Template" then parts = { {term = "first"}, {separator = " +&lrm; ", term = "second"} } else error("You must provide at least one part of a compound.") end end return m_affix.show_compound(augment_affix_data({ parts = parts }, args, lang, sc)) end function export.compound_like(frame) local iparams = { ["lang"] = {type = "language"}, ["template"] = {}, ["text"] = {}, ["oftext"] = {}, ["cat"] = {}, ["noaffixcat"] = boolean_param, ["dont_require_index"] = boolean_param, } local iargs = require("Module:parameters").process(frame.args, iparams) local parent_args = frame:getParent().args local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = parent_args, extra_params = extra_params, ilang = iargs.lang, dont_require_index = iargs.dont_require_index, -- FIXME, why are we doing this? Formerly we had 'params.pos = nil' whose intention was to disable the overall -- pos= while preserving posN=, which is equivalent to the following using the new syntax. But why is this -- necessary? require_index_for_pos = not iargs.dont_require_index, allow_semicolon_separator = true, } local nocat = args.nocat.default local notext = args.notext local text = not notext and iargs.text local oftext = not notext and (iargs.oftext or text and "of") local cat = not nocat and iargs.cat local noaffixcat = nocat or iargs.noaffixcat if not next(parts) then if mw.title.getCurrentTitle().nsText == "Template" then parts = { {term = "first"}, {separator = " +&lrm; ", term = "second"} } end end return m_affix.show_compound_like(augment_affix_data({ parts = parts, text = text, oftext = oftext, cat = cat, noaffixcat = noaffixcat }, args, lang, sc)) end function export.surface_analysis(frame) local function ine(arg) -- Since we're operating before calling [[Module:parameters]], we need to imitate how that module processes -- arguments, including trimming since numbered arguments don't have automatic whitespace trimming. if not arg then return arg end arg = mw.text.trim(arg) if arg == "" then arg = nil end return arg end local parent_args = frame:getParent().args local etymtext local arg1 = ine(parent_args[1]) if not arg1 then -- Allow omitted first argument to just display "By surface analysis". etymtext = "" elseif arg1:find("^%+") then -- If the first argument (normally a language code) is prefixed with a +, it's a template name. local template_name = arg1:sub(2) local new_args = {} for i, v in pairs(parent_args) do if type(i) == "number" then if i > 1 then new_args[i - 1] = v end else new_args[i] = v end end new_args.nocap = true etymtext = ", " .. frame:expandTemplate { title = template_name, args = new_args } end if etymtext then return (ine(parent_args.nocap) and "b" or "B") .. "y [[Appendix:Glossary#surface analysis|surface analysis]]" .. etymtext end local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = parent_args, extra_params = extra_params, allow_type = true, allow_semicolon_separator = true, } -- There must be at least one part to display. If there are gaps, a term -- request will be shown. if not next(parts) then if mw.title.getCurrentTitle().nsText == "Template" then parts = { {term = "first"}, {separator = " +&lrm; ", term = "second"} } else error("You must provide at least one part.") end end return m_affix.show_surface_analysis(augment_affix_data({ parts = parts }, args, lang, sc)) end local function check_max_items(items, max_allowed) if #items > max_allowed then local bad_item = items[max_allowed + 1] if bad_item.term then error(("At most %s terms can be specified but saw a term specified for term #%s") :format(max_allowed, max_allowed + 1)) else for k, v in pairs(bad_item) do if is_property_key(k) then error(("At most %s terms can be specified but saw a value for property '%s' of term #%s") :format(max_allowed, k, max_allowed + 1)) end end end error(("Internal error: Something wrong, %s items generated when there should be at most %s, but item #%s doesn't have a term or any properties") :format(#items, max_allowed, max_allowed + 1)) end end function export.circumfix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } check_max_items(parts, 3) local prefix = parts[1] local base = parts[2] local suffix = parts[3] -- Just to make sure someone didn't use the template in a silly way if not (prefix and base and suffix) then if mw.title.getCurrentTitle().nsText == "Template" then prefix = {term = "circumfix", alt = "prefix"} base = {term = "base"} suffix = {term = "circumfix", alt = "suffix"} else error("You must specify a prefix part, a base term and a suffix part.") end end return m_affix.show_circumfix(augment_affix_data({ prefix = prefix, base = base, suffix = suffix }, args, lang, sc)) end function export.confix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } check_max_items(parts, 3) local prefix = parts[1] local base = parts[3] and parts[2] or nil local suffix = parts[3] or parts[2] -- Just to make sure someone didn't use the template in a silly way if not (prefix and suffix) then if mw.title.getCurrentTitle().nsText == "Template" then prefix = {term = "prefix"} suffix = {term = "suffix"} else error("You must specify a prefix part, an optional base term and a suffix part.") end end return m_affix.show_confix(augment_affix_data({ prefix = prefix, base = base, suffix = suffix }, args, lang, sc)) end function export.pseudo_loan(frame) local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc, source = parse_args { raw_args = frame:getParent().args, extra_params = extra_params, has_source = true, -- FIXME, why are we doing this? Formerly we had 'params.pos = nil' whose intention was to disable the overall -- pos= while preserving posN=, which is equivalent to the following using the new syntax. But why is this -- necessary? require_index_for_pos = true, allow_semicolon_separator = true, } return require(pseudo_loan_module).show_pseudo_loan( augment_affix_data({ source = source, parts = parts }, args, lang, sc)) end function export.infix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } check_max_items(parts, 3) local base = parts[1] local infix = parts[2] -- Just to make sure someone didn't use the template in a silly way if not (base and infix) then if mw.title.getCurrentTitle().nsText == "Template" then base = {term = "base"} infix = {term = "infix"} else error("You must provide a base term and an infix.") end end return m_affix.show_infix(augment_affix_data({ base = base, infix = infix }, args, lang, sc)) end function export.prefix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } local prefixes = parts local base = nil local max_prefix = 0 for k, v in pairs(prefixes) do max_prefix = math.max(k, max_prefix) end if max_prefix >= 2 then base = prefixes[max_prefix] prefixes[max_prefix] = nil end -- Just to make sure someone didn't use the template in a silly way if not next(prefixes) then if mw.title.getCurrentTitle().nsText == "Template" then base = {term = "base"} prefixes = { {term = "prefix"} } else error("You must provide at least one prefix.") end end return m_affix.show_prefix(augment_affix_data({ prefixes = prefixes, base = base }, args, lang, sc)) end function export.suffix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } local base = parts[1] local suffixes = {} for k, v in pairs(parts) do suffixes[k - 1] = v end -- Just to make sure someone didn't use the template in a silly way if not next(suffixes) then if mw.title.getCurrentTitle().nsText == "Template" then base = {term = "base"} suffixes = { {term = "suffix"} } else error("You must provide at least one suffix.") end end return m_affix.show_suffix(augment_affix_data({ base = base, suffixes = suffixes }, args, lang, sc)) end function export.derivsee(frame) local iparams = { ["derivtype"] = {}, } local iargs = require("Module:parameters").process(frame.args, iparams) local params = { id = true, ["sc"] = {type = "script"}, pos = true, pagename = true, head = {alias_of = "pagename"}, } local derivtype = iargs.derivtype params[1] = {required = "true", type = "language", default = "und"} params[2] = {} local args = require("Module:parameters").process(frame:getParent().args, params) local lang = args[1] local term = args[2] or args.pagename local id = args.id local sc = args.sc local pos = require(en_utilities_module).pluralize(args.pos or "term") if not term then local SUBPAGE = mw.loadData("Module:headword/data").pagename if lang:hasType("reconstructed") or mw.title.getCurrentTitle().nsText == "Reconstruction" then term = "*" .. SUBPAGE elseif lang:hasType("appendix-constructed") then term = SUBPAGE else term = SUBPAGE end end local category local langname = lang:getFullName() if (derivtype == "compound" and pos == nil) then category = langname .. " compounds with " .. term elseif derivtype == "compound" and pos == "verbs" then category = langname .. " compound " .. pos .. " formed with " .. term elseif derivtype == "compound" then category = langname .. " compound " .. pos .. " with " .. term else category = langname .. " " .. pos .. " " .. derivtype .. "ed with " .. term .. (id and " (" .. id .. ")" or "") end return require("Module:collapsible category list").make { lang = lang, sc = sc, category = category, } end return export sjo18b9pgtfqgio67j9fkl64oceyb5p 239020 239019 2026-11-15T03:52:12Z Lee 19 [[:en:Module:affix/templates]] වෙතින් එක් සංශෝධනයක් 239019 Scribunto text/plain local export = {} local debug_force_cat = false -- if set to true, always display categories even on userspace pages local m_affix = require("Module:affix") local en_utilities_module = "Module:en-utilities" local parameter_utilities_module = "Module:parameter utilities" local pseudo_loan_module = "Module:affix/pseudo-loan" local insert = table.insert local boolean_param = {type = "boolean"} local function is_property_key(k) return require(parameter_utilities_module).item_key_is_property(k) end local recognized_affix_types = { prefix = "prefix", pre = "prefix", suffix = "suffix", suf = "suffix", interfix = "interfix", inter = "interfix", infix = "infix", ["in"] = "infix", circumfix = "circumfix", circum = "circumfix", ["non-affix"] = "non-affix", naf = "non-affix", root = "non-affix", } local function pre_normalize_affix_type(data) local modtext = data.modtext modtext = modtext:match("^<(.*)>$") if not modtext then error(("Internal error: Passed-in modifier isn't surrounded by angle brackets: %s"):format(data.modtext)) end if recognized_affix_types[modtext] then modtext = "type:" .. modtext end return "<" .. modtext .. ">" end -- Parse raw arguments. A single parameter `data` is passed in, with the following fields: -- * `raw_args`: The raw arguments to parse, normally taken from `frame:getParent().args`. -- * `extra_params`: An optional function of one argument that is called on the `params` structure before parsing; its -- purpose is to specify additional allowed parameters or possibly disable parameters. -- * `has_source`: There is a source-language parameter following 1= (which becomes the "destination" language -- parameter) and preceding the terms. This is currently used for {{pseudo-loan}}. -- * `ilang`: If given, it is a language object that serves as the default for the language. If specified, there is no -- language code specified in 1=; instead the term parameters start directly at 1= (or at 2= if `has_source` is -- given). -- * `require_index_for_pos`: There is no separate |pos= parameter distinct from |pos1=, |pos2=, etc. Instead, -- specifying |pos= results in an error. -- * `dont_require_index`: Allow |foo= to be specified as a synonym for |foo1= (except for |lit=, which remains -- distinct). -- * `allow_type`: Allow |type1=, |type2=, etc. or inline <type:...> for the affix type, and allow a separate |type= -- parameter for the etymology type (FIXME: this may be confusing; consider changing the etymology type to |etype=). -- * `allow_semicolon_separator`: Allow semicolon as a separator, displaying as " or ". This requires changes in the -- display of the output, to not always put a + between the items. -- -- Note that all language parameters are allowed to be etymology-only languages. -- -- Return five values ARGS, ITEMS, LANG_OBJ, SCRIPT_OBJ, SOURCE_LANG_OBJ where ARGS is a table of the parsed arguments; -- ITEMS is the list of parsed items; LANG_OBJ is the language object corresponding to the language code specified in 1= -- (or taken from `ilang` if given); SCRIPT_OBJ is the script object corresponding to sc= (if given, otherwise nil); and -- SOURCE_LANG_OBJ is the language object corresponding to the source-language code specified in 2= (or 1= if `ilang` is -- given) if `has_source` is specified (otherwise nil). local function parse_args(data) local raw_args = data.raw_args local has_source = data.has_source local ilang = data.ilang if raw_args.lang then error("The |lang= parameter is not used by this template. Place the language code in parameter 1 instead.") end local term_index = (ilang and 1 or 2) + (has_source and 1 or 0) local params = { [term_index] = {list = true, allow_holes = true}, ["sort"] = {}, ["nocap"] = boolean_param, -- always allow this even if not used, for use with {{surf}}, which adds it ["force_cat"] = boolean_param, -- for debugging use } if not ilang then params[1] = {required = true, type = "language", default = "und"} end local source_index if has_source then source_index = term_index - 1 params[source_index] = {required = true, type = "language", default = "und"} end local m_param_utils = require(parameter_utilities_module) local param_mod_source = {} if not data.dont_require_index then insert(param_mod_source, -- We want to require an index for all params (or use separate_no_index, which also requires an index for the -- param corresponding to the first item). {default = true, require_index = true} ) end insert(param_mod_source, {group = {"link", "ref", "lang", "q", "l", "infl"}}) -- Override lit= to be separate from lit1=. insert(param_mod_source, {param = "lit", separate_no_index = true}) if not data.dont_require_index and not data.require_index_for_pos then -- Override pos= to be separate from pos1=. insert(param_mod_source, {param = "pos", separate_no_index = true}) end if data.allow_type then insert(param_mod_source, {param = "type", separate_no_index = true}) end insert(param_mod_source, {param = "nocat", type = "boolean", separate_no_index = true}) local param_mods = m_param_utils.construct_param_mods(param_mod_source) if data.extra_params then data.extra_params(params) end local items, args = m_param_utils.parse_list_with_inline_modifiers_and_separate_params { params = params, param_mods = param_mods, raw_args = raw_args, termarg = term_index, parse_lang_prefix = true, track_module = "homophones", -- the inclusion of &lrm; is what [[Module:affix]] has always done default_separator = data.allow_semicolon_separator and " +&lrm; " or nil, special_separators = data.allow_semicolon_separator and {[";"] = " or "} or nil, disallow_custom_separators = not data.allow_semicolon_separator, -- For compatibility, we need to not skip completely unspecified items. It is common, for example, to do -- {{suffix|lang||foo}} to generate "+ -foo". dont_skip_items = true, -- Allow e.g. <infix> to be specified in place of <type:infix>. pre_normalize_modifiers = pre_normalize_affix_type, -- Don't pass in `lang` or `sc`, as they will be used as defaults to initialize the items, which we don't want -- (particularly for `lang`), as the code in [[Module:affix]] uses the presence of `lang` as an indicator that -- a part-specific language was explicitly given. } local lang = ilang or args[1] local source if has_source then source = args[source_index] end -- For compatibility with the prior code, we need to convert items without term or properties to nil. for i = 1, #items do local item = items[i] local saw_item_property = item.term if not saw_item_property then for k, v in pairs(item) do if is_property_key(k) then saw_item_property = true break end end end if not saw_item_property then items[i] = nil elseif item.type then -- Validate and canonicalize affix types. if not recognized_affix_types[item.type] then local valid_types = {} for k in pairs(recognized_affix_types) do insert(valid_types, ("'%s'"):format(k)) end table.sort(recognized_affix_types) error(("Unrecognized affix type '%s' in item %s; valid values are %s"):format( item.type, item.itemno, table.concat(valid_types, ", "))) else item.type = recognized_affix_types[item.type] end end end if args.type and args.type.default and not m_affix.etymology_types[args.type.default] then error("Unrecognized etymology type: '" .. args.type.default .. "'") end return args, items, lang, args.sc.default, source end local function augment_affix_data(data, args, lang, sc) data.lang = lang data.sc = sc data.pos = args.pos and args.pos.default data.lit = args.lit and args.lit.default data.sort_key = args.sort data.type = args.type and args.type.default data.nocap = args.nocap data.notext = args.notext data.nocat = args.nocat.default data.force_cat = args.force_cat or debug_force_cat data.l = args.l.default data.ll = args.ll.default data.q = args.q.default data.qq = args.qq.default data.infl = args.infl.default return data end function export.affix(frame) local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, extra_params = extra_params, allow_type = true, allow_semicolon_separator = true, } -- There must be at least one part to display. If there are gaps, a term -- request will be shown. if not next(parts) and not args.type.default then if mw.title.getCurrentTitle().nsText == "Template" then parts = { {term = "prefix-"}, {term = "base"}, {term = "-suffix"} } else error("You must provide at least one part.") end end return m_affix.show_affix(augment_affix_data({ parts = parts }, args, lang, sc)) end function export.compound(frame) local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, extra_params = extra_params, allow_type = true, allow_semicolon_separator = true, } -- There must be at least one part to display. If there are gaps, a term -- request will be shown. if not next(parts) and not args.type.default then if mw.title.getCurrentTitle().nsText == "Template" then parts = { {term = "first"}, {separator = " +&lrm; ", term = "second"} } else error("You must provide at least one part of a compound.") end end return m_affix.show_compound(augment_affix_data({ parts = parts }, args, lang, sc)) end function export.compound_like(frame) local iparams = { ["lang"] = {type = "language"}, ["template"] = {}, ["text"] = {}, ["oftext"] = {}, ["cat"] = {}, ["noaffixcat"] = boolean_param, ["dont_require_index"] = boolean_param, } local iargs = require("Module:parameters").process(frame.args, iparams) local parent_args = frame:getParent().args local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = parent_args, extra_params = extra_params, ilang = iargs.lang, dont_require_index = iargs.dont_require_index, -- FIXME, why are we doing this? Formerly we had 'params.pos = nil' whose intention was to disable the overall -- pos= while preserving posN=, which is equivalent to the following using the new syntax. But why is this -- necessary? require_index_for_pos = not iargs.dont_require_index, allow_semicolon_separator = true, } local nocat = args.nocat.default local notext = args.notext local text = not notext and iargs.text local oftext = not notext and (iargs.oftext or text and "of") local cat = not nocat and iargs.cat local noaffixcat = nocat or iargs.noaffixcat if not next(parts) then if mw.title.getCurrentTitle().nsText == "Template" then parts = { {term = "first"}, {separator = " +&lrm; ", term = "second"} } end end return m_affix.show_compound_like(augment_affix_data({ parts = parts, text = text, oftext = oftext, cat = cat, noaffixcat = noaffixcat }, args, lang, sc)) end function export.surface_analysis(frame) local function ine(arg) -- Since we're operating before calling [[Module:parameters]], we need to imitate how that module processes -- arguments, including trimming since numbered arguments don't have automatic whitespace trimming. if not arg then return arg end arg = mw.text.trim(arg) if arg == "" then arg = nil end return arg end local parent_args = frame:getParent().args local etymtext local arg1 = ine(parent_args[1]) if not arg1 then -- Allow omitted first argument to just display "By surface analysis". etymtext = "" elseif arg1:find("^%+") then -- If the first argument (normally a language code) is prefixed with a +, it's a template name. local template_name = arg1:sub(2) local new_args = {} for i, v in pairs(parent_args) do if type(i) == "number" then if i > 1 then new_args[i - 1] = v end else new_args[i] = v end end new_args.nocap = true etymtext = ", " .. frame:expandTemplate { title = template_name, args = new_args } end if etymtext then return (ine(parent_args.nocap) and "b" or "B") .. "y [[Appendix:Glossary#surface analysis|surface analysis]]" .. etymtext end local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = parent_args, extra_params = extra_params, allow_type = true, allow_semicolon_separator = true, } -- There must be at least one part to display. If there are gaps, a term -- request will be shown. if not next(parts) then if mw.title.getCurrentTitle().nsText == "Template" then parts = { {term = "first"}, {separator = " +&lrm; ", term = "second"} } else error("You must provide at least one part.") end end return m_affix.show_surface_analysis(augment_affix_data({ parts = parts }, args, lang, sc)) end local function check_max_items(items, max_allowed) if #items > max_allowed then local bad_item = items[max_allowed + 1] if bad_item.term then error(("At most %s terms can be specified but saw a term specified for term #%s") :format(max_allowed, max_allowed + 1)) else for k, v in pairs(bad_item) do if is_property_key(k) then error(("At most %s terms can be specified but saw a value for property '%s' of term #%s") :format(max_allowed, k, max_allowed + 1)) end end end error(("Internal error: Something wrong, %s items generated when there should be at most %s, but item #%s doesn't have a term or any properties") :format(#items, max_allowed, max_allowed + 1)) end end function export.circumfix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } check_max_items(parts, 3) local prefix = parts[1] local base = parts[2] local suffix = parts[3] -- Just to make sure someone didn't use the template in a silly way if not (prefix and base and suffix) then if mw.title.getCurrentTitle().nsText == "Template" then prefix = {term = "circumfix", alt = "prefix"} base = {term = "base"} suffix = {term = "circumfix", alt = "suffix"} else error("You must specify a prefix part, a base term and a suffix part.") end end return m_affix.show_circumfix(augment_affix_data({ prefix = prefix, base = base, suffix = suffix }, args, lang, sc)) end function export.confix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } check_max_items(parts, 3) local prefix = parts[1] local base = parts[3] and parts[2] or nil local suffix = parts[3] or parts[2] -- Just to make sure someone didn't use the template in a silly way if not (prefix and suffix) then if mw.title.getCurrentTitle().nsText == "Template" then prefix = {term = "prefix"} suffix = {term = "suffix"} else error("You must specify a prefix part, an optional base term and a suffix part.") end end return m_affix.show_confix(augment_affix_data({ prefix = prefix, base = base, suffix = suffix }, args, lang, sc)) end function export.pseudo_loan(frame) local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc, source = parse_args { raw_args = frame:getParent().args, extra_params = extra_params, has_source = true, -- FIXME, why are we doing this? Formerly we had 'params.pos = nil' whose intention was to disable the overall -- pos= while preserving posN=, which is equivalent to the following using the new syntax. But why is this -- necessary? require_index_for_pos = true, allow_semicolon_separator = true, } return require(pseudo_loan_module).show_pseudo_loan( augment_affix_data({ source = source, parts = parts }, args, lang, sc)) end function export.infix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } check_max_items(parts, 3) local base = parts[1] local infix = parts[2] -- Just to make sure someone didn't use the template in a silly way if not (base and infix) then if mw.title.getCurrentTitle().nsText == "Template" then base = {term = "base"} infix = {term = "infix"} else error("You must provide a base term and an infix.") end end return m_affix.show_infix(augment_affix_data({ base = base, infix = infix }, args, lang, sc)) end function export.prefix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } local prefixes = parts local base = nil local max_prefix = 0 for k, v in pairs(prefixes) do max_prefix = math.max(k, max_prefix) end if max_prefix >= 2 then base = prefixes[max_prefix] prefixes[max_prefix] = nil end -- Just to make sure someone didn't use the template in a silly way if not next(prefixes) then if mw.title.getCurrentTitle().nsText == "Template" then base = {term = "base"} prefixes = { {term = "prefix"} } else error("You must provide at least one prefix.") end end return m_affix.show_prefix(augment_affix_data({ prefixes = prefixes, base = base }, args, lang, sc)) end function export.suffix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } local base = parts[1] local suffixes = {} for k, v in pairs(parts) do suffixes[k - 1] = v end -- Just to make sure someone didn't use the template in a silly way if not next(suffixes) then if mw.title.getCurrentTitle().nsText == "Template" then base = {term = "base"} suffixes = { {term = "suffix"} } else error("You must provide at least one suffix.") end end return m_affix.show_suffix(augment_affix_data({ base = base, suffixes = suffixes }, args, lang, sc)) end function export.derivsee(frame) local iparams = { ["derivtype"] = {}, } local iargs = require("Module:parameters").process(frame.args, iparams) local params = { id = true, ["sc"] = {type = "script"}, pos = true, pagename = true, head = {alias_of = "pagename"}, } local derivtype = iargs.derivtype params[1] = {required = "true", type = "language", default = "und"} params[2] = {} local args = require("Module:parameters").process(frame:getParent().args, params) local lang = args[1] local term = args[2] or args.pagename local id = args.id local sc = args.sc local pos = require(en_utilities_module).pluralize(args.pos or "term") if not term then local SUBPAGE = mw.loadData("Module:headword/data").pagename if lang:hasType("reconstructed") or mw.title.getCurrentTitle().nsText == "Reconstruction" then term = "*" .. SUBPAGE elseif lang:hasType("appendix-constructed") then term = SUBPAGE else term = SUBPAGE end end local category local langname = lang:getFullName() if (derivtype == "compound" and pos == nil) then category = langname .. " compounds with " .. term elseif derivtype == "compound" and pos == "verbs" then category = langname .. " compound " .. pos .. " formed with " .. term elseif derivtype == "compound" then category = langname .. " compound " .. pos .. " with " .. term else category = langname .. " " .. pos .. " " .. derivtype .. "ed with " .. term .. (id and " (" .. id .. ")" or "") end return require("Module:collapsible category list").make { lang = lang, sc = sc, category = category, } end return export sjo18b9pgtfqgio67j9fkl64oceyb5p 239021 239020 2026-11-15T03:52:32Z Lee 19 පැරණි සංස්කරණයකින් ගත් කොටස්... 239021 Scribunto text/plain local m_sinhala = require("Module:sinhala") local m_sinhala_project = require("Module:sinhala project") local export = {} local debug_force_cat = false -- if set to true, always display categories even on userspace pages local m_affix = require("Module:affix") local en_utilities_module = "Module:en-utilities" local parameter_utilities_module = "Module:parameter utilities" local pseudo_loan_module = "Module:affix/pseudo-loan" local insert = table.insert local boolean_param = {type = "boolean"} local function is_property_key(k) return require(parameter_utilities_module).item_key_is_property(k) end local recognized_affix_types = { prefix = "prefix", pre = "prefix", suffix = "suffix", suf = "suffix", interfix = "interfix", inter = "interfix", infix = "infix", ["in"] = "infix", circumfix = "circumfix", circum = "circumfix", ["non-affix"] = "non-affix", naf = "non-affix", root = "non-affix", } local function pre_normalize_affix_type(data) local modtext = data.modtext modtext = modtext:match("^<(.*)>$") if not modtext then error(("Internal error: Passed-in modifier isn't surrounded by angle brackets: %s"):format(data.modtext)) end if recognized_affix_types[modtext] then modtext = "type:" .. modtext end return "<" .. modtext .. ">" end -- Parse raw arguments. A single parameter `data` is passed in, with the following fields: -- * `raw_args`: The raw arguments to parse, normally taken from `frame:getParent().args`. -- * `extra_params`: An optional function of one argument that is called on the `params` structure before parsing; its -- purpose is to specify additional allowed parameters or possibly disable parameters. -- * `has_source`: There is a source-language parameter following 1= (which becomes the "destination" language -- parameter) and preceding the terms. This is currently used for {{pseudo-loan}}. -- * `ilang`: If given, it is a language object that serves as the default for the language. If specified, there is no -- language code specified in 1=; instead the term parameters start directly at 1= (or at 2= if `has_source` is -- given). -- * `require_index_for_pos`: There is no separate |pos= parameter distinct from |pos1=, |pos2=, etc. Instead, -- specifying |pos= results in an error. -- * `dont_require_index`: Allow |foo= to be specified as a synonym for |foo1= (except for |lit=, which remains -- distinct). -- * `allow_type`: Allow |type1=, |type2=, etc. or inline <type:...> for the affix type, and allow a separate |type= -- parameter for the etymology type (FIXME: this may be confusing; consider changing the etymology type to |etype=). -- * `allow_semicolon_separator`: Allow semicolon as a separator, displaying as " or ". This requires changes in the -- display of the output, to not always put a + between the items. -- -- Note that all language parameters are allowed to be etymology-only languages. -- -- Return five values ARGS, ITEMS, LANG_OBJ, SCRIPT_OBJ, SOURCE_LANG_OBJ where ARGS is a table of the parsed arguments; -- ITEMS is the list of parsed items; LANG_OBJ is the language object corresponding to the language code specified in 1= -- (or taken from `ilang` if given); SCRIPT_OBJ is the script object corresponding to sc= (if given, otherwise nil); and -- SOURCE_LANG_OBJ is the language object corresponding to the source-language code specified in 2= (or 1= if `ilang` is -- given) if `has_source` is specified (otherwise nil). local function parse_args(data) local raw_args = data.raw_args local has_source = data.has_source local ilang = data.ilang if raw_args.lang then error("The |lang= parameter is not used by this template. Place the language code in parameter 1 instead.") end local term_index = (ilang and 1 or 2) + (has_source and 1 or 0) local params = { [term_index] = {list = true, allow_holes = true}, ["sort"] = {}, ["nocap"] = boolean_param, -- always allow this even if not used, for use with {{surf}}, which adds it ["force_cat"] = boolean_param, -- for debugging use } if not ilang then params[1] = {required = true, type = "language", default = "und"} end local source_index if has_source then source_index = term_index - 1 params[source_index] = {required = true, type = "language", default = "und"} end local m_param_utils = require(parameter_utilities_module) local param_mod_source = {} if not data.dont_require_index then insert(param_mod_source, -- We want to require an index for all params (or use separate_no_index, which also requires an index for the -- param corresponding to the first item). {default = true, require_index = true} ) end insert(param_mod_source, {group = {"link", "ref", "lang", "q", "l", "infl"}}) -- Override lit= to be separate from lit1=. insert(param_mod_source, {param = "lit", separate_no_index = true}) if not data.dont_require_index and not data.require_index_for_pos then -- Override pos= to be separate from pos1=. insert(param_mod_source, {param = "pos", separate_no_index = true}) end if data.allow_type then insert(param_mod_source, {param = "type", separate_no_index = true}) end insert(param_mod_source, {param = "nocat", type = "boolean", separate_no_index = true}) local param_mods = m_param_utils.construct_param_mods(param_mod_source) if data.extra_params then data.extra_params(params) end local items, args = m_param_utils.parse_list_with_inline_modifiers_and_separate_params { params = params, param_mods = param_mods, raw_args = raw_args, termarg = term_index, parse_lang_prefix = true, track_module = "homophones", -- the inclusion of &lrm; is what [[Module:affix]] has always done default_separator = data.allow_semicolon_separator and " +&lrm; " or nil, special_separators = data.allow_semicolon_separator and {[";"] = " or "} or nil, disallow_custom_separators = not data.allow_semicolon_separator, -- For compatibility, we need to not skip completely unspecified items. It is common, for example, to do -- {{suffix|lang||foo}} to generate "+ -foo". dont_skip_items = true, -- Allow e.g. <infix> to be specified in place of <type:infix>. pre_normalize_modifiers = pre_normalize_affix_type, -- Don't pass in `lang` or `sc`, as they will be used as defaults to initialize the items, which we don't want -- (particularly for `lang`), as the code in [[Module:affix]] uses the presence of `lang` as an indicator that -- a part-specific language was explicitly given. } local lang = ilang or args[1] local source if has_source then source = args[source_index] end -- For compatibility with the prior code, we need to convert items without term or properties to nil. for i = 1, #items do local item = items[i] local saw_item_property = item.term if not saw_item_property then for k, v in pairs(item) do if is_property_key(k) then saw_item_property = true break end end end if not saw_item_property then items[i] = nil elseif item.type then -- Validate and canonicalize affix types. if not recognized_affix_types[item.type] then local valid_types = {} for k in pairs(recognized_affix_types) do insert(valid_types, ("'%s'"):format(k)) end table.sort(recognized_affix_types) error(("Unrecognized affix type '%s' in item %s; valid values are %s"):format( item.type, item.itemno, table.concat(valid_types, ", "))) else item.type = recognized_affix_types[item.type] end end end if args.type and args.type.default and not m_affix.etymology_types[args.type.default] then error("Unrecognized etymology type: '" .. args.type.default .. "'") end return args, items, lang, args.sc.default, source end local function augment_affix_data(data, args, lang, sc) data.lang = lang data.sc = sc data.pos = args.pos and args.pos.default data.lit = args.lit and args.lit.default data.sort_key = args.sort data.type = args.type and args.type.default data.nocap = args.nocap data.notext = args.notext data.nocat = args.nocat.default data.force_cat = args.force_cat or debug_force_cat data.l = args.l.default data.ll = args.ll.default data.q = args.q.default data.qq = args.qq.default data.infl = args.infl.default return data end function export.affix(frame) local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, extra_params = extra_params, allow_type = true, allow_semicolon_separator = true, } -- There must be at least one part to display. If there are gaps, a term -- request will be shown. if not next(parts) and not args.type.default then if mw.title.getCurrentTitle().nsText == "සැකිල්ල" then parts = { {term = "prefix-"}, {term = "base"}, {term = "-suffix"} } else error("You must provide at least one part.") end end return m_affix.show_affix(augment_affix_data({ parts = parts }, args, lang, sc)) end function export.compound(frame) local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, extra_params = extra_params, allow_type = true, allow_semicolon_separator = true, } -- There must be at least one part to display. If there are gaps, a term -- request will be shown. if not next(parts) and not args.type.default then if mw.title.getCurrentTitle().nsText == "සැකිල්ල" then parts = { {term = "first"}, {separator = " +&lrm; ", term = "second"} } else error("You must provide at least one part of a compound.") end end return m_affix.show_compound(augment_affix_data({ parts = parts }, args, lang, sc)) end function export.compound_like(frame) local iparams = { ["lang"] = {type = "language"}, ["template"] = {}, ["text"] = {}, ["oftext"] = {}, ["cat"] = {}, ["noaffixcat"] = boolean_param, ["dont_require_index"] = boolean_param, } local iargs = require("Module:parameters").process(frame.args, iparams) local parent_args = frame:getParent().args local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = parent_args, extra_params = extra_params, ilang = iargs.lang, dont_require_index = iargs.dont_require_index, -- FIXME, why are we doing this? Formerly we had 'params.pos = nil' whose intention was to disable the overall -- pos= while preserving posN=, which is equivalent to the following using the new syntax. But why is this -- necessary? require_index_for_pos = not iargs.dont_require_index, allow_semicolon_separator = true, } local nocat = args.nocat.default local notext = args.notext local text = not notext and iargs.text local oftext = not notext and (iargs.oftext or text and "of") local cat = not nocat and iargs.cat local noaffixcat = nocat or iargs.noaffixcat if not next(parts) then if mw.title.getCurrentTitle().nsText == "සැකිල්ල" then parts = { {term = "first"}, {separator = " +&lrm; ", term = "second"} } end end return m_affix.show_compound_like(augment_affix_data({ parts = parts, text = text, oftext = oftext, cat = cat, noaffixcat = noaffixcat }, args, lang, sc)) end function export.surface_analysis(frame) local function ine(arg) -- Since we're operating before calling [[Module:parameters]], we need to imitate how that module processes -- arguments, including trimming since numbered arguments don't have automatic whitespace trimming. if not arg then return arg end arg = mw.text.trim(arg) if arg == "" then arg = nil end return arg end local parent_args = frame:getParent().args local etymtext local arg1 = ine(parent_args[1]) if not arg1 then -- Allow omitted first argument to just display "By surface analysis". etymtext = "" elseif arg1:find("^%+") then -- If the first argument (normally a language code) is prefixed with a +, it's a template name. local template_name = arg1:sub(2) local new_args = {} for i, v in pairs(parent_args) do if type(i) == "number" then if i > 1 then new_args[i - 1] = v end else new_args[i] = v end end new_args.nocap = true etymtext = ", " .. frame:expandTemplate { title = template_name, args = new_args } end if etymtext then return (ine(parent_args.nocap) and "b" or "B") .. "y [[Appendix:Glossary#surface analysis|surface analysis]]" .. etymtext end local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc = parse_args { raw_args = parent_args, extra_params = extra_params, allow_type = true, allow_semicolon_separator = true, } -- There must be at least one part to display. If there are gaps, a term -- request will be shown. if not next(parts) then if mw.title.getCurrentTitle().nsText == "සැකිල්ල" then parts = { {term = "first"}, {separator = " +&lrm; ", term = "second"} } else error("You must provide at least one part.") end end return m_affix.show_surface_analysis(augment_affix_data({ parts = parts }, args, lang, sc)) end local function check_max_items(items, max_allowed) if #items > max_allowed then local bad_item = items[max_allowed + 1] if bad_item.term then error(("At most %s terms can be specified but saw a term specified for term #%s") :format(max_allowed, max_allowed + 1)) else for k, v in pairs(bad_item) do if is_property_key(k) then error(("At most %s terms can be specified but saw a value for property '%s' of term #%s") :format(max_allowed, k, max_allowed + 1)) end end end error(("Internal error: Something wrong, %s items generated when there should be at most %s, but item #%s doesn't have a term or any properties") :format(#items, max_allowed, max_allowed + 1)) end end function export.circumfix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } check_max_items(parts, 3) local prefix = parts[1] local base = parts[2] local suffix = parts[3] -- Just to make sure someone didn't use the template in a silly way if not (prefix and base and suffix) then if mw.title.getCurrentTitle().nsText == "සැකිල්ල" then prefix = {term = "circumfix", alt = "prefix"} base = {term = "base"} suffix = {term = "circumfix", alt = "suffix"} else error("You must specify a prefix part, a base term and a suffix part.") end end return m_affix.show_circumfix(augment_affix_data({ prefix = prefix, base = base, suffix = suffix }, args, lang, sc)) end function export.confix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } check_max_items(parts, 3) local prefix = parts[1] local base = parts[3] and parts[2] or nil local suffix = parts[3] or parts[2] -- Just to make sure someone didn't use the template in a silly way if not (prefix and suffix) then if mw.title.getCurrentTitle().nsText == "සැකිල්ල" then prefix = {term = "prefix"} suffix = {term = "suffix"} else error("You must specify a prefix part, an optional base term and a suffix part.") end end return m_affix.show_confix(augment_affix_data({ prefix = prefix, base = base, suffix = suffix }, args, lang, sc)) end function export.pseudo_loan(frame) local function extra_params(params) params.notext = boolean_param end local args, parts, lang, sc, source = parse_args { raw_args = frame:getParent().args, extra_params = extra_params, has_source = true, -- FIXME, why are we doing this? Formerly we had 'params.pos = nil' whose intention was to disable the overall -- pos= while preserving posN=, which is equivalent to the following using the new syntax. But why is this -- necessary? require_index_for_pos = true, allow_semicolon_separator = true, } return require(pseudo_loan_module).show_pseudo_loan( augment_affix_data({ source = source, parts = parts }, args, lang, sc)) end function export.infix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } check_max_items(parts, 3) local base = parts[1] local infix = parts[2] -- Just to make sure someone didn't use the template in a silly way if not (base and infix) then if mw.title.getCurrentTitle().nsText == "සැකිල්ල" then base = {term = "base"} infix = {term = "infix"} else error("You must provide a base term and an infix.") end end return m_affix.show_infix(augment_affix_data({ base = base, infix = infix }, args, lang, sc)) end function export.prefix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } local prefixes = parts local base = nil local max_prefix = 0 for k, v in pairs(prefixes) do max_prefix = math.max(k, max_prefix) end if max_prefix >= 2 then base = prefixes[max_prefix] prefixes[max_prefix] = nil end -- Just to make sure someone didn't use the template in a silly way if not next(prefixes) then if mw.title.getCurrentTitle().nsText == "සැකිල්ල" then base = {term = "base"} prefixes = { {term = "prefix"} } else error("You must provide at least one prefix.") end end return m_affix.show_prefix(augment_affix_data({ prefixes = prefixes, base = base }, args, lang, sc)) end function export.suffix(frame) local args, parts, lang, sc = parse_args { raw_args = frame:getParent().args, } local base = parts[1] local suffixes = {} for k, v in pairs(parts) do suffixes[k - 1] = v end -- Just to make sure someone didn't use the template in a silly way if not next(suffixes) then if mw.title.getCurrentTitle().nsText == "සැකිල්ල" then base = {term = "base"} suffixes = { {term = "suffix"} } else error("You must provide at least one suffix.") end end return m_affix.show_suffix(augment_affix_data({ base = base, suffixes = suffixes }, args, lang, sc)) end function export.derivsee(frame) local iparams = { ["derivtype"] = {}, } local iargs = require("Module:parameters").process(frame.args, iparams) local params = { id = true, ["sc"] = {type = "script"}, pos = true, pagename = true, head = {alias_of = "pagename"}, } local derivtype = iargs.derivtype params[1] = {required = "true", type = "language", default = "und"} params[2] = {} local args = require("Module:parameters").process(frame:getParent().args, params) local lang = args[1] local term = args[2] or args.pagename local id = args.id local sc = args.sc local pos = require(en_utilities_module).pluralize(args.pos or "term") if not term then local SUBPAGE = mw.loadData("Module:headword/data").pagename if lang:hasType("reconstructed") or mw.title.getCurrentTitle().nsText == "Reconstruction" or m_sinhala_project.inNamespace(mw.title.getCurrentTitle(), "Reconstruction") then term = "*" .. m_sinhala_project.getSubpageText(SUBPAGE) elseif lang:hasType("appendix-constructed") then term = SUBPAGE else term = SUBPAGE end end local category local langname = lang:getFullName() if (derivtype == "compound" and pos == nil) then category = langname .. " compounds with " .. term elseif derivtype == "compound" and pos == "verbs" then category = langname .. " compound " .. pos .. " formed with " .. term elseif derivtype == "compound" then category = langname .. " compound " .. pos .. " with " .. term else category = ("%s %s, %s %s සහිත"):format(langname, m_sinhala.sinhala(pos), term, m_sinhala.sinhala(derivtype .. "es")) .. (id and " (" .. id .. ")" or "") end return require("Module:collapsible category list").make { lang = lang, sc = sc, category = category, } end return export 0plbp5r2dtej4s3wlg4tvc2vrfwgw41 ප්‍රවර්ග සාකච්ඡාව:Demotic Egyptian මොඩියුල 15 17639 239002 61405 2026-11-15T03:22:53Z Lee 19 Lee විසින් [[ප්‍රවර්ග සාකච්ඡාව:Demotic මොඩියුල]] සිට [[ප්‍රවර්ග සාකච්ඡාව:Demotic Egyptian මොඩියුල]] වෙත පිටුව ගෙන යන ලදී 48623 wikitext text/x-wiki {| class="wikitable" ! oldid || date/time || username || edit summary |---- | 75810704 || 2023-08-28T07:23:13Z || WingerBot || <nowiki>Created page with "{{auto cat}}"</nowiki> |} ehfd4nn9sgtja4n6e9p4z06v58qtj1d ප්‍රවර්ගය:Demotic Egyptian මොඩියුල 14 17640 239000 61451 2026-11-15T03:22:52Z Lee 19 Lee විසින් [[ප්‍රවර්ගය:Demotic මොඩියුල]] සිට [[ප්‍රවර්ගය:Demotic Egyptian මොඩියුල]] වෙත පිටුව ගෙන යන ලදී 61451 wikitext text/x-wiki {{auto cat}} [[en:Category:Demotic modules]] 0f86qs4ehxppfknna03h5eegzo2yema ප්‍රවර්ග සාකච්ඡාව:බෙලරුසියානු terms with non-redundant manual transliterations 15 22789 238998 59307 2026-11-15T03:21:27Z Lee 19 Lee විසින් [[ප්‍රවර්ග සාකච්ඡාව:Belarusian terms with non-redundant manual transliterations]] සිට [[ප්‍රවර්ග සාකච්ඡාව:බෙලරුසියානු terms with non-redundant manual transliterations]] වෙත පිටුව ගෙන යන ලදී 59307 wikitext text/x-wiki {| class="wikitable" ! oldid || date/time || username || edit summary |---- | 77469893 || 2023-12-30T01:29:33Z || WingerBot || <nowiki>WingerBot moved page [[Category:Terms with manual transliterations different from the automated ones/be]] to [[Category:Belarusian terms with non-redundant manual transliterations]] without leaving a redirect: rename maintenance category per [[Wiktionary:Grease pit/2023/December]]</nowiki> |---- | 61396279 || 2020-12-27T05:16:46Z || WingerBot || <nowiki>use {{auto cat}} (manually assisted)</nowiki> |---- | 42782359 || 2017-05-02T22:48:21Z || Daniel Carrero || <nowiki>removed [[Category:Belarusian terms needing attention]]; added [[Category:Belarusian entry maintenance]] using [[Help:Gadget-HotCat|HotCat]]</nowiki> |---- | 24569131 || 2014-01-02T23:28:05Z || Mulder1982 || <nowiki>Created page with "[[Category:Terms with manual transliterations different from the automated ones|be]] [[Category:Belarusian terms needing attention]] __HIDDENCAT__"</nowiki> |} s3pptswmi8x2g9800ns1chqtlg7h31p ප්‍රවර්ගය:බෙලරුසියානු terms with non-redundant manual transliterations 14 22791 238996 59309 2026-11-15T03:21:27Z Lee 19 Lee විසින් [[ප්‍රවර්ගය:Belarusian terms with non-redundant manual transliterations]] සිට [[ප්‍රවර්ගය:බෙලරුසියානු terms with non-redundant manual transliterations]] වෙත පිටුව ගෙන යන ලදී 59309 wikitext text/x-wiki {{auto cat}} eomzlm5v4j7ond1phrju7cnue91g5qx ප්‍රවර්ග සාකච්ඡාව:Demotic Egyptian සැකිලි 15 25186 239006 69381 2026-11-15T03:23:24Z Lee 19 Lee විසින් [[ප්‍රවර්ග සාකච්ඡාව:Demotic සැකිලි]] සිට [[ප්‍රවර්ග සාකච්ඡාව:Demotic Egyptian සැකිලි]] වෙත පිටුව ගෙන යන ලදී 65967 wikitext text/x-wiki {| class="wikitable" ! oldid || date/time || username || edit summary |---- | 67446712 || 2022-06-20T12:20:54Z || WingerBot || <nowiki>use {{auto cat}}, remove extraneous {{catfix}}/TOC templates (manually assisted)</nowiki> |---- | 47150433 || 2017-07-31T18:03:10Z || Vorziblix || <nowiki>Created page with "{{poscatboiler|egx-dem|templates}}"</nowiki> |} 3taalijxod19xoki9s5ahqh0rv0gjge ප්‍රවර්ගය:Demotic Egyptian සැකිලි 14 25187 239004 74059 2026-11-15T03:23:23Z Lee 19 Lee විසින් [[ප්‍රවර්ගය:Demotic සැකිලි]] සිට [[ප්‍රවර්ගය:Demotic Egyptian සැකිලි]] වෙත පිටුව ගෙන යන ලදී 74059 wikitext text/x-wiki {{auto cat}} [[en:Category:Demotic templates]] lep5okljejbac82czqchcv717k02bab 239008 239004 2026-11-15T03:23:59Z Lee 19 239008 wikitext text/x-wiki {{auto cat}} [[en:Category:Demotic Egyptian templates]] 2yt2gl2jamznsae8i7p7tv5m1hco6oa Module:parameter utilities 828 113982 239025 218002 2026-10-21T02:55:22Z en>Benwing2 0 don't change default separator to a semicolon when the separator is not a comma 239025 Scribunto text/plain local export = {} local debug_track_module = "Module:debug/track" local functions_module = "Module:fun" local parameters_module = "Module:parameters" local parse_interface_module = "Module:parse interface" local parse_utilities_module = "Module:parse utilities" local table_module = "Module:table" local dump = mw.dumpObject local error = error local insert = table.insert local ipairs = ipairs local next = next local pairs = pairs local require = require local tonumber = tonumber local type = type --[==[ Loaders for functions in other modules, which overwrite themselves with the target function when called. This ensures modules are only loaded when needed, retains the speed/convenience of locally-declared pre-loaded functions, and has no overhead after the first call, since the target functions are called directly in any subsequent calls. ]==] local function debug_track(...) debug_track = require(debug_track_module) return debug_track(...) end local function is_callable(...) is_callable = require(functions_module).is_callable return is_callable(...) end local function list_to_set(...) list_to_set = require(table_module).listToSet return list_to_set(...) end local function parse_inline_modifiers(...) parse_inline_modifiers = require(parse_interface_module).parse_inline_modifiers return parse_inline_modifiers(...) end local function process_params(...) process_params = require(parameters_module).process return process_params(...) end local function shallow_copy(...) shallow_copy = require(table_module).shallowCopy return shallow_copy(...) end local function table_len(...) table_len = require(table_module).length return table_len(...) end ----------------- end loaders ---------------- local function track(page, track_module) return debug_track((track_module or "parameter utilities") .. "/" .. page) end -- Throw an error prefixed with the words "Internal error" (and suffixed with a dumped version of `spec`, if provided). -- This is for logic errors in the code itself rather than template user errors. local function internal_error(msg, spec) if spec then msg = ("%s: %s"):format(msg, dump(spec)) end error(("Internal error: %s"):format(msg)) end -- Table listing the default recognized special separator arguments and how they display. export.default_special_separators = { [";"] = "; ", ["_"] = " ", ["~"] = " ~ ", ["→"] = " → ", } -- Table listing how subitem delimiters display. Unlike for `default_special_separators`, the presence of an item in -- this table does not mean that the delimiter is recognized; only those specified by `data.splitchar` are recognized. export.default_subitem_separator_map = { [";"] = "; ", [","] = ", ", ["/"] = "/", ["_"] = " ", ["~"] = " ~ ", ["→"] = " → ", } --[==[ intro: The purpose of this module is to facilitate implementation of templates that can have arguments specified either through inline modifiers or separate parameters. There are two types of templates supported: those that take a list of items with associated properties, which can be specified either through indexed separate parameters (e.g. {{para|t2}}, {{para|pos3}}) or inline modifiers (`<t:...>`, `<pos:...>`, etc.); and those that take a single term, whose properties can be specified through non-indexed separate parameters (e.g. {{para|t}} or {{para|pos}}) or inline modifiers. Both types of templates can optionally have subitems in the term parameter(s), where the subitems are typically (but not necessarily) separated with commas and each subitem can have its own inline modifiers. Some examples of templates that take a list of items are {{tl|alter}}/{{tl|alt}}; {{tl|synonyms}}/{{tl|syn}}, {{tl|antonyms}}/{{tl|ant}}, and other "nyms" templates; {{tl|col}}, {{tl|col2}}, {{tl|col3}}, {{tl|col4}} and other column templates; {{tl|descendant}}/{{tl|desc}}; {{tl|affix}}/{{tl|af}}, {{tl|prefix}}/{{tl|pre}} and related *fix templates; {{tl|affixusex}}/{{tl|afex}} and related templates; {{tl|IPA}}; {{tl|homophones}}; {{tl|rhymes}}; and several others. Examples of templates that take a single item are form-of templates ({{tl|inflection of}}/{{tl|infl of}}, {{tl|form of}}, and specific templates such as {{tl|alt form}}/{{tl|alternative form of}}, {{tl|abbr of}}/{{tl|abbreviation of}}, {{tl|clipping of}}, and many others); for etymology templates ({{tl|bor}}/{{tl|borrowed}}, {{tl|der}}/{{tl|derived}}, etc. as well as `misc_variant` templates like {{tl|ellipsis}}, {{tl|abbrev}}, {{tl|clipping}}, {{tl|reduplication}} and the like); and other templates that take an argument structure similar to {{tl|l}} or {{tl|m}}. This module can be thought of as a combination of [[Module:parameters]] (which parses template parameters, and in particular handles the separate parameter versions of the properties) and `parse_inline_modifiers()` in [[Module:parse utilities]] (which parses inline modifiers). The two main entry points are `parse_list_with_inline_modifiers_and_separate_params()` (for templates that take a list of items) and `parse_term_with_inline_modifiers_and_separate_params()` (for templates that take a single item). However, there are other functions provided, e.g. to initialize the `param_mods` structure that is passed to the two entry points. The typical workflow for using `parse_list_with_inline_modifiers_and_separate_params()` looks as follows (a slightly simplified version of the code in [[Module:nyms]]): { local export = {} local parameter_utilities_module = "Module:parameter utilities" ... -- Entry point to be invoked from a template. function export.show(frame) local parent_args = frame:getParent().args -- Parameters that don't have corresponding inline modifiers. Note in particular that the parameter corresponding to -- the items themselves must be specified this way, and must specify either `allow_holes = true` (if the user can -- omit terms, typically by specifying the term using |altN= or <alt:...> so that they remain unlinked) or -- `disallow_holes = true` (if omitting terms is not allowed). (If neither `allow_holes` nor `disallow_holes` is -- specified, an error is thrown in parse_list_with_inline_modifiers_and_separate_params().) local params = { [1] = {required = true, type = "language", default = "und"}, [2] = {list = true, allow_holes = true, required = true, default = "term"}, } local m_param_utils = require(parameter_utilities_module) -- This constructs the `param_mods` structure by adding well-known groups of parameters (such as all the parameters -- associated with based on full_link() in [[Module:links]], with default properties that can be overridden. This is -- easier and less error-prone than manually specifying the `param_mods` structure (see below for how this would -- look). Here, we specify the group "link" (consisting of all the link parameters for use with full_link()), group -- "ref" (which adds the "ref" parameter for specifying references), group "l" (which adds the "l" and "ll" -- parameters for specifying labels) and group "q" (which adds the "q" and "qq" parameters for specifying regular -- qualifiers). By default, labels and qualifiers have `separate_no_index` set so that e.g. |q1= is distinct from -- |q=, the former specifying the left qualifier for the first item and the latter specifying the overall left -- qualifier. For compatibility, we override the `separate_no_index` setting for the group "q", which causes |q= and -- |q1= to be the same, and likewise for |qq= and |qq1=. Finally, also for compatibility, we add an "lb" parameter -- that is an alias of "ll" (in all respects; |lb= is the same as |ll=, |lb1= is the same as |ll1=, <lb:...> is the -- same as <ll:...>, etc.). local param_mods = m_param_utils.construct_param_mods { {group = {"link", "ref", "l"}}, {group = "q", separate_no_index = false}, {param = "lb", alias_of = "ll"}, } -- This processes the raw arguments in `parent_args`, parses inline modifiers and creates corresponding objects -- containing the property values specified either through inline modifiers or separate parameters. local items, args = m_param_utils.parse_list_with_inline_modifiers_and_separate_params { params = params, param_mods = param_mods, raw_args = parent_args, termarg = 2, parse_lang_prefix = true, track_module = "nyms", lang = 1, sc = "sc.default", } local lang = args[1] -- Now do the actual implementation of the template. Generally this should be split into a separate function, often -- in a separate module (if the implementation goes in [[Module:foo]], the template interface code goes in -- [[Module:foo/templates]]). ... } The `param_mods` structure controls the properties that can be specified by the user for a given item, and is conceptually very similar to the `param_mods` structure used by `parse_inline_modifiers()`. The key is the name of the parameter (e.g. {"t"}, {"pos"}) and the value is a table with optional elements as follows: * `item_dest`, `store`: Same as the corresponding fields in the `param_mods` structure passed to `parse_inline_modifiers()`. * `type`, `set`, `sublist`, `convert` and associated fields such as `family` and `method`: These control parsing and conversion of the raw values specified by the user and have the same meaning as in [[Module:parameters]] and also in `parse_inline_modifiers()` (which delegates the actual conversion to [[Module:parameters]]). These fields — and for that matter, all fields other than `item_dest`, `store` and `overall` — are forwarded to the `process()` function in [[Module:parameters]]. * `alias_of`: This parameter is an alias of some other parameter. This spec is recognized only by `process()` in [[Module:parameters]], and not by `parse_inline_modifiers()`; to set up an alias in `parse_inline_modifiers()`, you need to make sure (using `item_dest`) that both the alias and aliasee modifiers store their values in the same location, and you need to copy the remaining properties from the aliasee's spec to the aliasing modifier's spec. All of this happens automatically if you generate the `param_mods` structure using `construct_param_mods()`. * `require_index`: This means that the non-indexed parameter version of the property is not recognized. E.g. in the case of the {"sc"} property, use of the {{para|sc}} parameter would result in an error, while {{para|sc1}} is recognized and specifies the {"sc"} property for the first item. The default, if neither `require_index` nor `separate_no_index` is given, is for {{para|sc}} and {{para|sc1}} to mean the same thing (both would specify the {"sc"} property of the first item). Note that `require_index` and `separate_no_index` are mutually exclusive, and if either one is specified during processing by `construct_param_mods()`, the other one is automaticallly turned off. * `separate_no_index`: This means that e.g. the {{para|sc}} parameter is distinct from the {{para|sc1}} parameter (and thus from the `<sc:...>` inline modifier on the first item). This is typically used to distinguish an overall version of a property from the corresponding item-specific property on the first item. (In this case, for example, {{para|sc}} overrides the script code for all items, while {{para|sc1}} overrides the script code only for the first item.) If not given, and if `require_index` is not given, {{para|sc}} and {{para|sc1}} would have the same meaning and refer to the item-specific property on the first item. When this is given, the overall value can be accessed using the `.default` field of the property value in `args`, e.g. in this case `args.sc.default`. Note that (as mentioned above) `require_index` and `separate_no_index` are mutually exclusive, and if either one is specified during processing by `construct_param_mods()`, the other one is automaticallly turned off. * `list`, `allow_holes`, `disallow_holes`: These should '''not''' be given. `list` and `allow_holes` are automatically set for all parameter specs added to the `params` structure used by `process()` in [[Module:parameters]], and `disallow_holes` clashes with `allow_holes`. For the above workflow example, the call to `construct_param_mods()` generates the following `param_mods` structure: { local param_mods = { -- the parameters generated by group "link" alt = {}, t = { -- [[Module:links]] expects the gloss in "gloss". item_dest = "gloss", }, gloss = { alias_of = "t", }, tr = {}, ts = {}, g = { -- [[Module:links]] expects the genders in "genders". item_dest = "genders", type = "genders", }, pos = {}, ng = {}, lit = {}, id = {}, sc = { separate_no_index = true, type = "script", }, -- the parameters generated by group "ref" ref = { item_dest = "refs", type = "references", }, -- the parameters generated by group "l" l = { type = "labels", separate_no_index = true, }, ll = { type = "labels", separate_no_index = true, }, -- the parameters generated by group "q"; note that `separate_no_index = true` would be set, but is overridden -- (specifying `separate_no_index = false` in the `param_mods` structure is equivalent to not specifying it at all) q = { type = "qualifier", separate_no_index = false, }, qq = { type = "qualifier", separate_no_index = false, }, infl = { type = "form of tags", separate_no_index = true, }, -- the parameter generated by the individual "lb" parameter spec; note that only `alias_of` was explicitly given, -- while `item_dest` is automatically set so that inline modifier <lb:...> stores into the same place as <ll:...>, -- and the other specs are copied from the `ll` spec so `lb` works like `ll` in all regards lb = { alias_of = "ll", item_dest = "ll", type = "labels", separate_no_index = true, }, } } ]==] local qualifier_spec = { type = "qualifier", separate_no_index = true, } local label_spec = { type = "labels", separate_no_index = true, } local form_of_spec = { type = "form of tags", separate_no_index = true, } local recognized_param_mod_groups = { link = { alt = {}, t = { -- [[Module:links]] expects the gloss in "gloss". item_dest = "gloss", }, gloss = { alias_of = "t", }, tr = {}, ts = {}, g = { -- [[Module:links]] expects the genders in "genders". item_dest = "genders", type = "genders", }, pos = {}, ng = {}, lit = {}, id = {}, sc = { separate_no_index = true, type = "script", }, }, lang = { lang = { require_index = true, type = "language", }, }, q = { q = qualifier_spec, qq = qualifier_spec, }, a = { a = label_spec, aa = label_spec, }, l = { l = label_spec, ll = label_spec, }, infl = { infl = form_of_spec, }, ref = { ref = { item_dest = "refs", type = "references", }, }, } local function merge_param_mod_settings(orig, additions) local merged = shallow_copy(orig) for k, v in pairs(additions) do merged[k] = v if k == "require_index" then merged.separate_no_index = nil elseif k == "separate_no_index" then merged.require_index = nil end end merged.default = nil merged.group = nil merged.param = nil merged.exclude = nil merged.include = nil return merged end local function verify_type(spec, param, typ1, typ2) if not spec[param] then return end local val = spec[param] if type(val) ~= typ1 and (not typ2 or type(val) ~= typ2) then internal_error(("Parameter `%s` must be a %s%s but saw a %s"):format(param, typ1, typ2 and " or " .. typ2 or "", type(val)), spec) end end local function verify_well_constructed_spec(spec) local num_control = (spec.default and 1 or 0) + (spec.group and 1 or 0) + (spec.param and 1 or 0) if num_control == 0 then internal_error( "Spec passed to construct_param_mods() must have either the `default`, `group` or `param` keys set", spec) end if num_control > 1 then internal_error( "Exactly one of `default`, `group` or `param` must be set in construct_param_mods() spec", spec) end if spec.list or spec.allow_holes then -- FIXME: We need to support list = "foo" for list parameters that are stored in e.g. 2=, foo2=, foo3=, etc. internal_error("`list` and `allow_holes` may not be set; they are automatically set when constructing the " .. "corresponding spec in the `params` object passed to [[Module:parameters]]", spec) end if spec.disallow_holes then internal_error("`disallow_holes` may not be set; it conflicts with `allow_holes`, which is automatically " .. "set when constructing the corresponding spec in the `params` object passed to [[Module:parameters]]", spec) end if spec.include and spec.exclude then internal_error("Saw both `include` and `exclude` in the same spec", spec) end if (spec.include or spec.exclude) and not spec.group then internal_error( "`include` and `exclude` can only be specified along with `group`, not with `default` or `param`", spec) end verify_type(spec, "group", "string", "table") verify_type(spec, "param", "string", "table") verify_type(spec, "include", "table") verify_type(spec, "exclude", "table") end --[==[ Construct the `param_mods` structure used in parsing arguments and inline modifiers from a list of specifications. A sample invocation (a slightly simplified version of the actual invocation associated with {{tl|affix}} and related templates) looks like this: { local param_mods = require("Module:parameter utilities").construct_param_mods { -- We want to require an index for all params (or use separate_no_index, which also requires an index for the -- param corresponding to the first item). {default = true, require_index = true}, {group = {"link", "ref", "lang", "q", "l"}}, -- Override these two to have separate_no_index. {param = {"lit", "pos"}, separate_no_index = true}, } } Each specification either sets the default value for further parameter specs or adds one or more parameters. Parameters can be added directly using `param`, or groups of predefined parameters can be added using `group`. Specifications are one of three types: # Those that set the default properties for future-added parameters. These contain {default = true} as one of the properties of the spec. Specs are processed in order and you can change the defaults mid-way through. # Those that add the parameters associated with one or more pre-defined groups. These contain {group = "group"} or {group = {"group1", "group2", ...}}. The pre-defined parameter groups and their associated properties are listed below. The pre-defined properties of parameters in a group override properties associated with a {default = true} spec, and are in turn overridden by any properties given directly in the spec itself. Note as well that setting the `separate_no_index` property will automatically cause the `require_index` property to be unset and vice-versa, as the two are mutually exclusive. (This happens in the example above, where the {separate_no_index = true} setting associated with the params {"lit"} and {"pos"} cancels out the {require_index = true} default setting, as well as less obviously with the pre-defined {"sc"} property of the {"link"} group, the {"q"} and {"qq"} properties of the {"q"} group, and the {"l"} and {"ll"} properties of the {"l"} group, all of which have an associated pre-defined property {separate_no_index = true}, which overrides and cancels out the {require_index = true} default setting. Finally, when adding the parameters of a group, you can request the only a subset of the parameters be added using either the `include` or `exclude` properties, each of whose values is a list of parameters that specify (respectively) the parameters to include (all other parameters of the group are excluded) or to exclude (all other parameters of the group are included). This is used, for example, in [[Module:romance etymology]] and [[Module:it-etymology]], which specify {group = "link", exclude = {"tr", "ts", "sc"}} to exclude link parameters that aren't relevant to Latin-script languages such as the Romance languages, and conversely in [[Module:IPA/templates]], which specifies {group = "link", include = {"t", "gloss", "pos"}} to include only the specified parameters for use with {{tl|IPA}}. # Those that add individual parameters. These contain {param = "param"} or {param = {"param1", "param2", ...}}, the latter syntax used to control a set of parameters together. The resulting spec is formed by initializing the parameter's settings with any previously-specified default properties (using a spec containing {default = true}) if the parameter hasn't already been initialized, and then overriding the resulting settings with any settings given directly in the specification. In the above example, the {"lit"} and {"pos"} parameters were previously initialized through the {"link"} group (specified in the second of the three specifications) but ended up with {require_index = true} due to the {default = true} spec (the first of the three specifications). We override these two parameters to have {separate_no_index = true} (which, as mentioned above, cancels out {require_index = true}). This is done so that {{tl|affix}} and related templates have {{para|pos}} and {{para|lit}} parameters distinct from {{para|pos1}} and {{para|lit1}}, which are used to specify an overall part of speech (which applies to all parts of the affix, as opposed to applying to just one element of the expression) or a literal definition for the entire expression (instead of just for one element of the expression). The built-in parameter groups are as follows: {|class="wikitable" ! Group !! Group meaning !! Parameter !! Parameter meaning !! Default properties |- | rowspan=11| `link` | rowspan=11| link parameters; same as those available on {{tl|l}}, {{tl|m}} and other linking templates | `alt` || display text, overriding the term's display form || — |- | `t` || gloss (translation) of a non-English term || {item_dest = "gloss"} |- | `gloss` || gloss (translation); same as `t` || {alias_of = "t"} |- | `tr` || transliteration of a non-Latin-script term; only needed if the automatic transliteration is incorrect or unavailable (e.g. in Hebrew, which doesn't have automatic transliteration) || — |- | `ts` || transcription of a non-Latin-script term, if the transliteration is markedly different from the actual pronunciation; should not be used for IPA pronunciations || — |- | `g` || comma-separated list of genders; whitespace may surround the comma and will be ignored || {item_dest = "genders", type = "genders"} |- | `pos` || part of speech for the term || — |- | `ng` || arbitrary non-gloss descriptive text for the term || — |- | `lit` || literal meaning (translation) of the term || — |- | `id` || a sense ID for the term, which links to anchors on the page set by the {{tl|senseid}} template || — |- | `sc` || the script code (see [[Wiktionary:Scripts]]) for the script that the term is written in; rarely necessary, as the script is autodetected (in most cases, correctly) || {separate_no_index = true, type = "script"} |- | rowspan=2| `q` | rowspan=2| left and right normal qualifiers (as displayed using {{tl|q}}) | `q` || left normal qualifier || {separate_no_index = true, type = "qualifier"} |- | `qq` || right normal qualifier || {separate_no_index = true, type = "qualifier"} |- | rowspan=2| `a` | rowspan=2| left and right accent qualifiers (as displayed using {{tl|a}}) | `a` || comma-separated list of left accent qualifiers; whitespace must not surround the comma || {separate_no_index = true, type = "labels"} |- | `aa` || comma-separated list of right accent qualifiers; whitespace must not surround the comma || {separate_no_index = true, type = "labels"} |- | rowspan=2| `l` | rowspan=2| left and right labels (as displayed using {{tl|lb}}, but without categorizing) | `l` || comma-separated list of left labels; whitespace must not surround the comma || {separate_no_index = true, type = "labels"} |- | `ll` || comma-separated list of right labels; whitespace must not surround the comma || {separate_no_index = true, type = "labels"} |- | `ref` | reference(s) (in the format accepted by [[Module:references]]; see also the documentation for the {{para|ref}} parameter to {{tl|IPA}}) | `ref` || one or more references, in the format accepted by [[Module:references]] || {item_dest = "refs", type = "references"} |- | `lang` | language for an individual term (provided for compatibility; it is preferred to specify languages for individual terms using language prefixes instead) | `lang` || language code (see [[Wiktionary:Languages]]) for the term || {require_index = true, type = "language"} |} ]==] function export.construct_param_mods(specs) local param_mods = {} local default_specs = {} for _, spec in ipairs(specs) do verify_well_constructed_spec(spec) if spec.default then -- This will have an extra `default` field in it, but it will be erased by merge_param_mod_settings() default_specs = spec else if spec.group then local groups = spec.group if type(groups) ~= "table" then groups = {groups} end local include_set if spec.include then include_set = list_to_set(spec.include) end local exclude_set if spec.exclude then exclude_set = list_to_set(spec.exclude) end for _, group in ipairs(groups) do local group_specs = recognized_param_mod_groups[group] if not group_specs then internal_error(("Unrecognized built-in param mod group '%s'"):format(group), spec) end for group_param, group_param_settings in pairs(group_specs) do local include_param if include_set then include_param = include_set[group_param] elseif exclude_set then include_param = not exclude_set[group_param] else include_param = true end if include_param then local merged_settings = merge_param_mod_settings(merge_param_mod_settings( param_mods[group_param] or default_specs, group_param_settings), spec) param_mods[group_param] = merged_settings end end end end if spec.param then local params = spec.param if type(params) ~= "table" then params = {params} end for _, param in ipairs(params) do local settings = merge_param_mod_settings(param_mods[param] or default_specs, spec) -- If this parameter is an alias of another parameter, we need to copy the specs from the other -- parameter, since parse_inline_modifiers() doesn't know about `alias_of` and having the specs -- duplicated won't cause problems for [[Module:parameters]]. We also need to set `item_dest` to -- point to the `item_dest` of the aliasee (defaulting to the aliasee's value itself), so that -- both modifiers write to the same location. Note that this works correctly in the common case of -- <t:...> with `item_dest = "gloss"` and <gloss:...> with `alias_of = "t"`, because both will end -- up with `item_dest = "gloss"`. local aliasee = settings.alias_of if aliasee then local aliasee_settings = param_mods[aliasee] if not aliasee_settings then internal_error(("Undefined aliasee '%s'"):format(aliasee), spec) end for k, v in pairs(aliasee_settings) do if settings[k] == nil then settings[k] = v end end if settings.item_dest == nil then settings.item_dest = aliasee end end param_mods[param] = settings end end end end return param_mods end -- Return true if `k` is a "built-in" (specially recognized) key in a `param_mod` specification. All other keys -- are forwarded to the structure passed to [[Module:parameters]]. local function param_mod_spec_key_is_builtin(k) return k == "item_dest" or k == "overall" or k == "store" end --[==[ Convert the properties in `param_mods` into the appropriate structures for use by `process()` in [[Module:parameters]] and store them in `params`. If `overall_only` is given, only store the properties in `param_mods` that correspond to overall (non-item-specific) parameters. Currently this only happens when `separate_no_index` is specified. ]==] function export.augment_params_with_modifiers(params, param_mods, overall_only) if overall_only then for param_mod, param_mod_spec in pairs(param_mods) do if overall_only == "always" or param_mod_spec.separate_no_index then local param_spec = {} for k, v in pairs(param_mod_spec) do if k ~= "separate_no_index" and k ~= "require_index" and not param_mod_spec_key_is_builtin(k) then param_spec[k] = v end end params[param_mod] = param_spec end end else local list_with_holes -- Add parameters for each term modifier. for param_mod, param_mod_spec in pairs(param_mods) do local param_spec for k, v in pairs(param_mod_spec) do if not param_mod_spec_key_is_builtin(k) then if param_spec == nil then param_spec = {list = true} end param_spec[k] = v end end if param_spec == nil then if list_with_holes == nil then list_with_holes = {list = true, allow_holes = true} end param_spec = list_with_holes elseif param_spec.alias_of == nil then param_spec.allow_holes = true end params[param_mod] = param_spec end end end --[==[ Return true if `k`, a key in an item, refers to a property of the item (is not one of the specially stored values). Note that `lang` and `sc` are considered properties of the item, although `lang` is set when there's a language prefix and both `lang` and `sc` may be set from default values specified in the `data` structure passed into `parse_list_with_inline_modifiers_and_separate_params()` and `parse_term_with_inline_modifiers_and_separate_params()`. If you don't want these treated as property keys, you need to check for them yourself. ]==] function export.item_key_is_property(k) return k ~= "term" and k ~= "termlang" and k ~= "termlangs" and k ~= "itemno" and k ~= "orig_index" and k ~= "separator" end -- Fetch the argument in `args` corresponding to `index_or_value`, which may be a string of the form "foo.default" -- (requesting the value of `args["foo"].default`); a string or number (requesting the value at that key); a function of -- one argument (`args`), which returns the argument value; or the value itself. Return the resulting value and the -- parameter in `args` that the value came from, or nil if unknown (i.e. a function or direct value was specified). local function fetch_argument(args, index_or_value) if not index_or_value then return index_or_value, nil end local index_or_value_type = type(index_or_value) if index_or_value_type == "string" then if index_or_value:sub(-8) == ".default" then local index_without_default = index_or_value:sub(1, -9) local arg_obj = fetch_argument(args, index_without_default) if type(arg_obj) ~= "table" then internal_error(("Requested that the '.default' key of argument `%s` be fetched, but argument value is undefined or not a table"): format(index_without_default), arg_obj) end return arg_obj.default, index_without_default end if index_or_value:match("^%d+$") then index_or_value = tonumber(index_or_value) end return args[index_or_value], index_or_value elseif index_or_value_type == "number" then return args[index_or_value], index_or_value elseif is_callable(index_or_value) then return index_or_value(args), nil end return index_or_value, nil end function export.generate_obj_maybe_parsing_lang_prefix(data) return require(parse_utilities_module).generate_obj_maybe_parsing_lang_prefix(data) end -- Subfunction of parse_list_with_inline_modifiers_and_separate_params() and -- parse_term_with_inline_modifiers_and_separate_params(), validating certain argument-related fields that are shared -- among the two functions. local function validate_argument_related_fields(data) if not data.termarg then internal_error("`data.termarg` must be given, indicating which argument contains the terms to be parsed", data) end if not data.param_mods then internal_error("`data.param_mods` must be given, indicating the allowed inline modifiers and separate " .. "parameters to copy", data) end local subitem_param_handling = data.subitem_param_handling or "only" if subitem_param_handling ~= "only" and subitem_param_handling ~= "first" and subitem_param_handling ~= "last" then internal_error("Unrecognized value for `data.subitem_param_handling`, should be 'first', 'last' or 'only'", subitem_param_handling) end if data.raw_args then if data.processed_args then internal_error("Only one of `data.raw_args` and `data.processed_args` can be specified", data) end if not data.params then internal_error("When `data.raw_args` is specified, so must `data.params`, so that the raw arguments " .. "can be parsed", data) end if data.params[data.termarg] == nil then internal_error("There must be a spec in `data.params` corresponding to `data.termarg`", data) end else if not data.processed_args then internal_error("Either `data.raw_args` or `data.processed_args` must be specified", data) end if data.params then internal_error("When `data.processed_args` is specified, `data.params` should not be specified", data) end end end local function argval_missing(val) return val == nil or type(val) == "table" and next(val) == nil end -- Subfunction of parse_list_with_inline_modifiers_and_separate_params() and -- parse_term_with_inline_modifiers_and_separate_params(). After parsing inline modifiers, copy the separate parameters -- to the generated object (or to the appropriate subobject if there are multiple). `data` contains the following -- fields: -- -- `args`: The separate-parameter argument structure. -- `param_mods`: The structure describing the inline modifiers. -- `itemno`: The logical item number of the term being processed, or nil if there's only a single term. -- `termobj`: The object to store the inline modifiers into. If there are subitems, they are in the `terms` field; -- otherwise the properties are stored directly into `termobj`. -- `has_subitems`: True if there are subitems. -- `subitem_separator_map`: If `has_subitems` and this is specified, controls the assignment of the `separator` field -- in subitems. If not specified or a delimiter is not in the map, it is copied unchanged. -- `lang`: Language object to store into all items. -- `sc`: Script object to store into all items, or nil. -- `subitem_param_handling`: "only", "first" or "last", indicating what to do if there are multiple subitems. -- `allow_conflicting_inline_mods_and_separate_params`: If true, specifying a value for both an inline modifier and -- corresponding separate parameter is allowed, and the inline modifier takes precedence. Otherwise, an error -- occurs. -- `postprocess_termobj`: Optional function called on all items at the end, to do any postprocessing. Called with one -- argument, the object to postprocess. -- `no_show_decorations`: If true, don't automatically set {show_decorations = true} on the object or subobject if there -- are decorations (i.e. qualifiers, labels or references) specified for the object. local function copy_separate_params_to_termobj_and_postprocess(data) local args, param_mods, itemno, termobj = data.args, data.param_mods, data.itemno, data.termobj local function set_lang_and_sc(termobj) -- Set these after parsing inline modifiers, not in generate_obj(), otherwise we'll get an error in -- parse_inline_modifiers() if we try to use <lang:...> or <sc:...> as inline modifiers. termobj.lang = termobj.lang or data.lang termobj.sc = termobj.sc or data.sc end local function set_show_decorations(termobj) -- Need to set after parsing inline modifiers. if not data.no_show_decorations and (termobj.q or termobj.qq or termobj.a or termobj.aa or termobj.l or termobj.ll or termobj.refs) then termobj.show_decorations = true end end local function fetch_separate_param(args, paramkey, itemno) local argval = args[paramkey] -- Careful with argument values that may be `false`. if argval and itemno then argval = argval[itemno] end return argval end -- Copy separate parameters to a given object. local function copy_separate_params_to_termobj(fetch_destobj) for param_mod, param_mod_spec in pairs(param_mods) do local dest = param_mod_spec.item_dest or param_mod -- Don't do anything with the `sc` param, which will get overwritten below; we don't -- want it to cause an error if there are multiple subitems. if dest ~= "sc" then local argval = fetch_separate_param(args, param_mod, itemno) if not argval_missing(argval) then local destobj = fetch_destobj(param_mod, param_mod_spec, dest) -- Don't overwrite a value already set by an inline modifier. if argval_missing(destobj[dest]) then destobj[dest] = argval elseif not data.allow_conflicting_inline_mods_and_separate_params then error(("Can't specify a value for separate parameter %s%s= because there is " .. "already an inline modifier <%s:...> specifying a value for the term"):format( param_mod, itemno or "", param_mod)) end end end end end if data.has_subitems then -- If there are any separate indexed parameters, we need to copy them to the first, last or only -- subitem, depending on the value of `data.subitem_param_handling` (which defaults to 'only', -- meaning it's an error if there are multiple subitems). Do this before calling -- postprocess_termobj() because the latter sets .lang and .sc and we want the user to be able to -- set separate langN= and scN= parameters. -- If there was no term, `termobj.terms` will not exist; make it exist to make the callers' lives easier. if not termobj.terms then termobj.terms = {} end -- Compute whether any of the separate indexed params exist for this index. local any_param_at_index for param_mod in pairs(param_mods) do local argval = fetch_separate_param(args, param_mod, itemno) if not argval_missing(argval) then any_param_at_index = true break end end -- If there was no term, but there's a separate parameter, we need to create an empty subitem. if any_param_at_index and not termobj.terms[1] then termobj.terms[1] = {} end local function fetch_destobj(param_mod, param_mod_spec, dest) if param_mod_spec.overall then return termobj end if data.subitem_param_handling == "only" and termobj.terms[2] then error(("Can't specify a value for separate parameter %s%s= because there are " .. "multiple subitems (%s) in the term; use an inline modifier"):format( param_mod, itemno or "", #termobj.terms)) end local termind -- q/a/l need to go at the beginning and qq/aa/ll/refs at the end, regardless; otherwise, respect -- `data.subitem_param_handling`. if dest == "q" or dest == "a" or dest == "l" then termind = 1 elseif dest == "qq" or dest == "aa" or dest == "ll" or dest == "refs" then termind = #termobj.terms elseif data.subitem_param_handling == "only" or data.subitem_param_handling == "first" then termind = 1 else termind = #termobj.terms end return termobj.terms[termind] end copy_separate_params_to_termobj(fetch_destobj) for i, subitem in ipairs(termobj.terms) do set_lang_and_sc(subitem) set_show_decorations(subitem) if subitem.delimiter then subitem.separator = i == 1 and "" or data.subitem_separator_map and data.subitem_separator_map[subitem.delimiter] or subitem.delimiter end if data.postprocess_termobj then data.postprocess_termobj(subitem, data) end end else -- Copy all the parsed term-specific parameters into `termobj`. copy_separate_params_to_termobj(function(param_mod, dest) return termobj end) set_lang_and_sc(termobj) set_show_decorations(termobj) if data.postprocess_termobj then data.postprocess_termobj(termobj, data) end end end local function postprocess_termobj(item, data) if not (data.disallow_custom_separators or data.use_semicolon) then if data.has_subitems and item.separator and item.separator:find(",", nil, true) then data.use_semicolon = true else -- If the displayed term (from .term/etc. or .alt) has an embedded comma, use a semicolon to -- join the terms. local term_text = item[data.term_dest] or item.alt if term_text and term_text:find(",", nil, true) then data.use_semicolon = true end end end end --[==[ Parse a list of terms, each of which may have properties specified using inline modifiers or separate parameters. This function is intended for parsing the arguments of templates like {{tl|syn}}, {{tl|ant}} and related ''*nym'' templates; alternative-form templates {{tl|alt}}/{{tl|alter}}; affix templates like {{tl|af}}/{{tl|affix}}, {{tl|com}}/{{tl|compound}}, etc.; affix usex templates like {{tl|afex}}/{{tl|affixusex}}; name templates like {{tl|name translit}}; column templates like {{tl|col}}; pronunciation templates like {{tl|rhyme}}/{{tl|rhymes}} and {{tl|hmp}}/{{tl|homophones}}; etc. In these templates there are one or more terms specified using numeric parameters, and associated separate parameters specifying per-term properties such as {{para|t1}}, {{para|t2}}, {{para|t3}}, ... for the gloss of the first, second, third, ... term respectively. All such properties can also be specified through inline modifiers attached directly to each term (`<t:...>`, `<pos:...>`, etc.). Normally it is an error if both an inline modifier and separate parameter for the same value are given, but this can be overridden (in which case inline modifiers take precedence over separate parameters when both occur). For an example of a typical workflow involving this function, see the comment at the top of this file. Some notable properties of this function: # Processing of the raw frame parent args using `process()` in [[Module:parameters]] can occur either inside of this function (the usual workflow) or outside of this function (for more complex cases). In the former case the raw parent args are passed in along with a partially built `params` structure of the sort required by [[Module:parameters]], containing only the term list itself along with any other parameters that are '''not''' term properties (such as a language code in {{para|1}} and boolean flags like {{para|nocat}}, {{para|nocap}}, etc.). This structure is ''augmented'' with list parameters, one for each per-term property, and [[Module:parameters]] is invoked. In the latter case where raw argument processing is done by the caller, they must build the partial `params` structure; augment it themselves using `augment_params_with_modifiers()`; call [[Module:parameters]] themselves; and pass in the processed arguments. In both cases, the return value of this function contains three values: a list of objects, one per term, specifying the term and all properties; the processed arguments structure, so that the non-term-property arguments can be processed as appropriate; and an object containing miscellaneous global computed properties (currently only `use_semicolon`; see below). # Optionally, each term can consist of a number of ''subitems'' separated by delimiters (usually a comma, but the possible delimiter or delimiters are controllable). Each subitem can have its own inline modifiers. This functionality is used, for example, by {{tl|col}} and variants, which allow each row to have comma-separated or tilde-separated subitems. When this feature is invoked, the format of the per-term object changes; instead of directly being an object describing the term and its properties, it is an object with a `terms` field containing a list of per-subitem objects along with other top-level fields describing per-term properties. By default, if there are separate parameters specified along with multiple subitems, an error occurs, but this is controllable; currently, you can request that the parameters be assigned to the first or last subitem. # By default, special ''separator'' arguments may be present, mixed in among regular term arguments. Examples of such separator arguments are (by default; this can be overridden) a bare semicolon, specifying that the terms on either side should be separated by a semicolon instead of a comma (indicating a higher-level grouping); a bare tilde, replacing the comma separator with a tilde (indicating that the terms on either side are alternants); and a bare underscore, replacing the comma separator with a space. Separator arguments are ignored when numbering the separate parameters. You disable the separator argument handling entirely if it doesn't make sense to have this (e.g. in {{tl|af}}/{{tl|affix}}, where the separator is always a {{cd|+}} sign). `data` is an object containing several possible fields. 1. Fields that are required or recommended (usually related to argument processing): * `raw_args` ('''required''' unless `processed_args` is specified): The raw arguments, normally fetched from {frame:getParent().args}. They are parsed using `process()` in [[Module:parameters]]. Most callers pass in raw arguments. * `processed_args`: The object of parsed arguments returned by `process()` in [[Module:parameters]]. One (but not both) of `raw_args` and `processed_args` must be set. * `param_mods` ('''required'''): A structure describing the possible inline modifiers and their properties. See the introductory comment above. Most often, this is generated using `construct_param_mods()` rather than specified manually. * `params` ('''required''' unless `processed_args` is specified): A structure describing the possible parameters, '''other than''' the ones that are separate-parameter equivalents of inline modifiers. This is automatically "augmented" with the separate-parameter equivalents of the inline modifiers described in `param_mods` prior to parsing the raw arguments with [[Module:parameters]]. '''WARNING:''' This structure is destructively modified, both by the "augmentation" process of adding separate-parameter equivalents of inline modifiers, and by the processing done by [[Module:parameters]] itself. (Nonetheless, substructures can safely be shared in this structure, and will be correctly handled.) * `termarg` ('''required'''): The argument containing the first item with attached inline modifiers to be parsed. Usually a numeric value such as {1} or {2}. * `track_module` ('''recommended'''): The name of the calling module, for use in adding tracking pages that are used internally to track pages containing template invocations with certain properties. Example properties tracked are missing items with corresponding properties as well as missing items without corresponding properties (which are skipped entirely). To find out the exact properties tracked and the name of the tracking pages, read the code. * `lang` ('''recommended'''): The language object for the language of the items, or the name of the argument to fetch the object from. It is not strictly necessary to specify this, as this function only initializes items based on inline modifiers and separate arguments and doesn't actually format the resulting items. However, if specified, it is used for certain purposes: *# It specifies the default for the `lang` property of returned objects if not otherwise set (e.g. by a language prefix). *# It is used to initialize an internal cache for speeding up language-code parsing (primarily useful if the same language code may appear in several items, such as with {{tl|col}} and related templates). The value of `lang` can be any of the following: * If a string of the form "foo.default", it is assumed to be requesting the value of `args["foo"].default`. * Otherwise, if a string or number, it is assumed to be requesting the value of `args` at that key. Note that if the string is in the form of a number (e.g. "3"), it is normalized to a number prior to fetching (this also happens with a spec like "2.default"). * Otherwise, if a function, it is assumed to be a function to return the argument value given `args`, which is passed to the function as its only argument. * Otherwise, it is used directly. * `sc` ('''recommended'''): The script object for the items, or the name of the argument to fetch the object from. The possible values and their handling are the same as with `lang`. In general, as with `lang`, it is not strictly necessary to specify this. However, if specified, it is used to supply the default for the `sc` property of returned items if not otherwise set (e.g. by the {{para|sc<var>N</var>}} parameter or `<sc:...>` inline modifier). The most common value is {"sc.default"}. 2. Other argument-related fields: * `process_args_before_parsing`: An optional function to apply further processing to the processed `args` structure returned by [[Module:parameters]], before parsing inline modifiers. This is passed one argument, the processed arguments. It should make modifications in-place. * `term_dest`: The field to store the value of the item itself into, after inline modifiers and (if allowed) language prefixes are stripped off. Defaults to {"term"}. * `pre_normalize_modifiers`: As in `parse_inline_modifiers()`. * `allow_conflicting_inline_mods_and_separate_params`: If specified, don't throw an error if a value is specified for a given property using both an inline modifier and separate param; in this case, the inline modifier takes precedence. 3. Fields related to language prefixes: * `parse_lang_prefix`: If true, allow and parse off a language code prefix attached to items followed by a colon, such as {la:minūtia} or {grc:[[σκῶρ|σκατός]]}. Etymology-only languages are allowed. Inline modifiers can be attached to such items. The exact syntax allowed is as specified in the `parse_term_with_lang()` function in [[Module:parse utilities]]. If `allow_multiple_lang_prefixes` is given, a {{cd|+}}-sign-separated list of language prefixes can be attached to an item. The resulting language object is stored into the `termlang` field, and also into the `lang` field (or in the case of `allow_multiple_lang_prefixes`, the list of language objects is stored into the `termlangs` field, and the first specified object is stored in the `lang` field). * `allow_multiple_lang_prefixes`: If given in conjunction with `parse_lang_prefix`, multiple language code prefixes can be given, separated by a {{cd|+}} sign. See `parse_lang_prefix` above. * `allow_bad_lang_prefix`: If given in conjunction with `parse_lang_prefix`, unrecognized language prefixes do not trigger an error, but are simply ignored (and not stripped off the item). Note that, regardless of whether this is given, prefixes before a colon do not trigger an error if they do not have the form of a language prefix or if a space follows the colon. It is not recommended that this be given because typos in language prefixes will not trigger an error and will tend to remain unfixed. 4. Fields related to custom/special separators: * `disallow_custom_separators`: If specified, disallow specifying custom separators (semicolon, underscore, tilde; see the internal `default_special_separators` table, or the `special_separators` field) as an item value to override the default separator. By default, the previous separator of each item is considered to be an empty string (for the first item) and otherwise the value of the field `default_separator` (normally a comma + space), unless either the preceding item is one of the values listed in `special_separators`, such as a bare semicolon (which causes the following item's previous separator to be a semicolon + space) or an item has an embedded comma in it (which causes ''all'' items other than the first to have their previous separator be a semicolon + space). The previous separator of each item is set on the item's `separator` property. Bare semicolons and other separator arguments do not count when indexing items using separate parameters. For example, the following is correct: ** {{tl|template|lang|item 1|q1=qualifier 1|;|item 2|q2=qualifier 2}} If `disallow_custom_separators` is specified, however, the `separator` property is not set and separator arguments are not recognized. * `default_separator`: Override the default separator (normally {", "}). * `special_separators`: Table giving the special/custom separators that can be given, and how they should display. If not specified, the default in `default_special_separators` is used. This is a table mapping separator values (such as {"~"}) to the corresponding display string (such as {" ~ "}). 5. Fields related to multiple subitems in a given term: * `splitchar`: A Lua pattern. If specified, each user-specified argument can consist of multiple delimiter-separated subitems, each of which may be followed by inline modifiers. In this case, each element in the returned list of items is no longer an object describing an item, but instead an object with a `terms` field, whose value is a list describing the subitems (whose format is the same as the normal format of an item in the top-level list when `splitchar` is not specified). Each subitem object will have a `delimiter` field holding the actual delimiter occurring before the subitem, which is useful in the case where `splitchar` matches multiple possible characters. In this case, it is possible to specify that a given modifier can only occur after the last subitem and effectively modifies the whole collection of subitems by setting {overall = true} on the modifier. In this case, the modifier's value will be stored in the top-level object (the object with the `terms` field specifying the subitems). Note that splitting on delimiters will not happen in certain protected sequences (by default comma+whitespace; see below). In addition, the algorithm to split on delimiters is sensitive to inline modifier syntax and will not be confused by delimiters inside of inline modifiers or inside of square brackets, which do not trigger splitting (whether or not contained within protected sequences). * `escape_fun` and `unescape_fun`: As in `split_escaping()` and `split_alternating_runs_escaping()` in [[Module:parse utilities]]. They control the protected sequences that won't be split when `splitchar` is specified (see previous item). By default, `escape_comma_whitespace` and `unescape_comma_whitespace` are used, so that comma+whitespace sequences won't be split. * `subitem_param_handling`: How to handle separate parameters that are specified in the presence of multiple subitems. The possible values are {"only"} (only allow separate parameters if there aren't any subitems, otherwise throw an error), {"first"} (store the separate parameters in the first subitem) and {"last"} (store the separate parameters in the last subitem). The default is {"only"}. As a special case, an {{para|scN}} separate parameter will be stored into all subitems. * `subitem_separator_map`: Table mapping user-specified delimiters to displayed separators, stored in the `separator` field of the subitem. If not specified, it defaults to `default_subitem_separator_map`. Note that the presence of an item in this table does not mean that it can be used as a delimiter; only the delimiters specified using `splitchar` are recognized. Delimiters not in this map display as-is. 6. Other fields: * `dont_skip_items`: Normally, items that are completely unspecified (have no term and no properties) are skipped and not inserted into the returned list of items. (Such items cannot occur if {disallow_holes = true} is set on the term specification in the `params` structure passed to `process()` in [[Module:parameters]]. It is generally recommended to do so unless a specific meaning is associated the term value being missing.) If `dont_skip_items` is set, however, items are never skipped, and completely unspecified items will be returned along with others. (They will not have the term or any properties set, but will have the normal non-property fields set; see below.) * `stop_when`: If specified, a function to determine when to prematurely stop processing items. It is passed a single argument, an object containing the following fields: ** `term`: The raw term, prior to parsing off language prefixes and inline modifiers (since the processing of `stop_when` happens before parsing the term). ** `any_param_at_index`: True if any separate property parameters exist for this item. ** `orig_index`: Same as `orig_index` below. ** `itemno`: Same as `itemno` below. ** `stored_itemno`: The index where this item will be stored into the returned items table. This may differ from `itemno` due to skipped items (it will never be different if `dont_skip_items` is set). The function should return true to stop processing items and return the ones processed so far (not including the item currently being processed). This is used, for example, in [[Module:alternative forms]], where an unspecified item signal the end of items and the start of labels. * `no_show_decorations`: If set, don't automatically set {show_decorations = true} on items or subitems that have decorations (i.e. qualifiers, labels or references) attached to them. Normally, {show_decorations = true} is set, causing `full_link()` in [[Module:links]] to appropriately display the decorations when showing the item or subitem. If you handle this display yourself, set {no_show_decorations = true} to prevent double display of decorations. Three values are returned: the list of items; the processed `args` structure; and an object of miscellaneous computed global values (currently only `use_semicolon`, indicating that commas were found in individual arguments and so the default separator should be a semicolon). In each returned item, there will be one field set for each specified property (either through inline modifiers or separate parameters). If subitems are not allowed, each item directly has fields set on it for the specified properties. If subitems ''are'' allowed, each item contains a `terms` field, which is a list of subitem objects, each of which has fields set on it for the specified properties of that subitem. In addition, the following fields may be set on each item or subitem: * `term`: The term portion of the item (minus inline modifiers and language prefixes). {nil} if no term was given. * `orig_index`: The original index into the item in the items table returned by `process()` in [[Module:parameters]]. This may differ from `itemno` if there are raw semiclons and `disallow_custom_separators` is not given. * `itemno`: The logical index of the item. The index of separate parameters corresponds to this index. This may be different from `orig_index` in the presence of raw semicolons; see above. * `termlang`: If there is a language prefix, the corresponding language object is stored here (only if `parse_lang_prefix` is set and `allow_multiple_lang_prefixes` is not set). * `termlangs`: If there is are language prefixes and both `parse_lang_prefix` and `allow_multiple_lang_prefixes` are set, the list of corresponding language objects is stored here. * `lang`: The language object of the item. This is set when either (a) there is a language prefix parsed off (if multiple prefixes are allowed, this corresponds to the first one); (b) the `lang` property is allowed and specified; (c) neither (a) nor (b) apply and the `lang` field of the overall `data` object is set, providing a default value. * `sc`: The script object of the item. This is set when either (a) the `sc` property is allowed and specified; (b) `sc` isn't otherwise set and the `sc` field of the overall `data` object is set, providing a default value. * `delimiter`: If subitems are allowed, this is set on subitems and specifies the delimiter used prior to the given subitem (e.g. {","}). * `separator`: The separator to display before the item. Always set on subitems, and set on top-level items if `disallow_custom_separators` is not given. Controlled by `special_separators` (for top-level items) and `subitem_separator_map` (for subitems). * `show_decorations`: If the item or subitem has any decorations (i.e. qualifiers, labels or references) specified, {show_decorations = true} is normally set on the item, so that these decorations are displayed when `full_link()` is called. Use {no_show_decorations = true} to prevent this. ]==] function export.parse_list_with_inline_modifiers_and_separate_params(data) validate_argument_related_fields(data) local raw_args, termarg, param_mods, args = data.raw_args, data.termarg, data.param_mods if raw_args then local params = data.params local termarg_spec = params[termarg] if termarg_spec == true or not termarg_spec.list then internal_error("Term spec in `data.params` must have `list` set", termarg_spec) end if termarg_spec == true or not (termarg_spec.allow_holes or termarg_spec.disallow_holes) then internal_error("Term spec in `data.params` must have either `allow_holes` or `disallow_holes` set", termarg_spec) end export.augment_params_with_modifiers(params, param_mods) args = process_params(raw_args, params) else args = data.processed_args end local process_args_before_parsing = data.process_args_before_parsing if process_args_before_parsing then process_args_before_parsing(args) end -- Find the maximum index among any of the list parameters. local term_args = args[termarg] -- As a special case, the term args might not have a `maxindex` field because they might have -- been declared with `disallow_holes = true`, so fall back to the actual length of the list -- using the table_len function, since # can be unpredictable with arbitrary tables. local maxmaxindex = term_args.maxindex or table_len(term_args) for _, v in pairs(args) do if type(v) == "table" and v.maxindex and v.maxindex > maxmaxindex then maxmaxindex = v.maxindex end end local special_separators = data.special_separators or export.default_special_separators local items, lang_cache, use_semicolon = {}, data.lang_cache or {} local lang = fetch_argument(args, data.lang) if lang then lang_cache[lang:getCode()] = lang end local sc = fetch_argument(args, data.sc) local term_dest = data.term_dest or "term" -- FIXME: this is vulnerable to abusive inputs like 1000000=. local itemno = 0 for i = 1, maxmaxindex do local term = term_args[i] if data.disallow_custom_separators or not special_separators[term] then itemno = itemno + 1 -- Compute whether any of the separate indexed params exist for this index. local any_param_at_index for param_mod in pairs(param_mods) do local argval = args[param_mod] -- Careful with argument values that may be `false`. if argval then argval = argval[itemno] end if not argval_missing(argval) then any_param_at_index = true break end end if data.stop_when and data.stop_when{ term = term, -- FIXME, we should just pass in `any_param_at_index` directly. any_param_at_index = term ~= nil or any_param_at_index, orig_index = i, itemno = itemno, stored_itemno = #items + 1, } then break end -- If any of the params used for formatting this term is present, create a term and add it to the list. if not data.dont_skip_items and term == nil and not any_param_at_index then track("skipped-term", data.track_module) else if not term then track("missing-term", data.track_module) end local termobj = { itemno = itemno, orig_index = i, } if not data.disallow_custom_separators then termobj.separator = i == 1 and "" or special_separators[term_args[i - 1]] end -- Add 1 because first term index starts at 2. local paramname = termarg + i - 1 if term then local function generate_obj(term, parse_err) return export.generate_obj_maybe_parsing_lang_prefix { term = term, termobj = data.splitchar and {} or termobj, term_dest = term_dest, paramname = paramname, parse_lang_prefix = data.parse_lang_prefix, parse_err = parse_err, allow_bad_lang_prefix = data.allow_bad_lang_prefix, allow_multiple_lang_prefixes = data.allow_multiple_lang_prefixes, lang_cache = lang_cache, } end parse_inline_modifiers(term, { paramname = paramname, param_mods = param_mods, generate_obj = generate_obj, splitchar = data.splitchar, preserve_splitchar = true, escape_fun = data.escape_fun, unescape_fun = data.unescape_fun, outer_container = data.splitchar and termobj or nil, pre_normalize_modifiers = data.pre_normalize_modifiers, }) end -- FIXME: Make into an error, then remove after a month. if data.no_show_qualifiers then track("no_show_qualifiers") end local term_data = { args = args, param_mods = param_mods, itemno = itemno, termobj = termobj, term_dest = term_dest, has_subitems = not not data.splitchar, lang = lang, -- As a special case, if the caller defined a scN= separate param, set it on all subitems if there -- are multiple, falling back to the overall sc= param. sc = args.sc and args.sc[itemno] or sc, subitem_param_handling = data.subitem_param_handling, subitem_separator_map = data.subitem_separator_map or export.default_subitem_separator_map, allow_conflicting_inline_mods_and_separate_params = data.allow_conflicting_inline_mods_and_separate_params, postprocess_termobj = postprocess_termobj, disallow_custom_separators = data.disallow_custom_separators, use_semicolon = use_semicolon, no_show_decorations = data.no_show_decorations or data.no_show_qualifiers, } copy_separate_params_to_termobj_and_postprocess(term_data) use_semicolon = term_data.use_semicolon insert(items, termobj) end end end if not data.disallow_custom_separators then -- Set the default separator of all those items for which a separator wasn't explicitly given to the default -- separator, defaulting to comma + space; but if any items have embedded commas, set the separator to -- semicolon + space. for _, item in ipairs(items) do if not item.separator then -- Only change the separator to a semicolon when the default separator is a comma (or at least has a -- comma in it). We don't want this e.g. in {{affix}}, where the default separator is + and should -- remain so even if there's a comma in an argument. local comma_in_default_separator = not data.default_separator or not not data.default_separator:find(",") item.separator = use_semicolon and comma_in_default_separator and "; " or data.default_separator or ", " end end end return items, args, {use_semicolon = use_semicolon} end --[==[ Parse a single term that may have properties specified through inline modifiers or separate parameters. This differs from `parse_list_with_inline_modifiers_and_separate_params()` in that the latter is for parsing a list of terms, each of which may have properties specified through inline modifiers or separate parameters. Both functions optionally support having multiple subitems in a single term. This function is used e.g. for form-of templates ({{tl|inflection of}}/{{tl|infl of}}, {{tl|form of}}, and specific templates such as {{tl|alt form}}/{{tl|alternative form of}}, {{tl|abbr of}}/{{tl|abbreviation of}}, {{tl|clipping of}}, and many others); for etymology templates ({{tl|bor}}/{{tl|borrowed}}, {{tl|der}}/{{tl|derived}}, etc. as well as `misc_variant` templates like {{tl|ellipsis}}, {{tl|abbrev}}, {{tl|clipping}}, {{tl|reduplication}} and the like); and for other templates with an argument structure similar to {{tl|l}} or {{tl|m}}. In these templates there is a term specified using a numeric parameter and associated separate parameters specifying term properties such as {{para|t}} for the gloss or {{para|tr}} for manual transliteration. All such properties can also be specified through inline modifiers attached directly to each term (`<t:...>`, `<tr:...>`, etc.). Normally it is an error if both an inline modifier and separate parameter for the same value are given, but this can be overridden (in which case inline modifiers take precedence over separate parameters when both occur). Some notable properties of this function: # Processing of the raw frame parent args using `process()` in [[Module:parameters]] can occur either inside of this function (the usual workflow) or outside of this function (for more complex cases). In the former case the raw parent args are passed in along with a partially built `params` structure of the sort required by [[Module:parameters]], containing only the term list itself along with any other parameters that are '''not''' term properties (such as a language code in {{para|1}} and boolean flags like {{para|nocat}}, {{para|nocap}}, etc.). This structure is ''augmented'' with parameters, one for each per-term property, and [[Module:parameters]] is invoked. In the latter case where raw argument processing is done by the caller, they must build the partial `params` structure; augment it themselves using `augment_params_with_modifiers()`; call [[Module:parameters]] themselves; and pass in the processed arguments. In both cases, the return value of this function contains two values, an object specifying the term and all properties; and the processed arguments structure, so that the non-term-property arguments can be processed as appropriate. # Optionally, the term can consist of a number of ''subitems'' separated by delimiters (usually a comma, but the possible delimiter or delimiters are controllable). Each subitem can have its own inline modifiers. This functionality is used, for example, by form-of templates. When this feature is invoked, the format of the term object changes; instead of directly being an object describing the term and its properties, it is an object with a `terms` field containing a list of per-subitem objects along with other top-level fields describing per-term properties. By default, if there are separate parameters specified along with multiple subitems, an error occurs, but this is controllable; currently, you can request that the parameters be assigned to the first or last subitem. `data` is an object containing several possible fields. 1. Fields that are required or recommended (usually related to argument processing): * `raw_args` ('''required''' unless `processed_args` is specified): The raw arguments, normally fetched from {frame:getParent().args}. They are parsed using `process()` in [[Module:parameters]]. Most callers pass in raw arguments. * `processed_args`: The object of parsed arguments returned by `process()` in [[Module:parameters]]. One (but not both) of `raw_args` and `processed_args` must be set. * `param_mods` ('''required'''): A structure describing the possible inline modifiers and their properties. See the introductory comment above. Most often, this is generated using `construct_param_mods()` rather than specified manually. * `params` ('''required''' unless `processed_args` is specified): A structure describing the possible parameters, '''other than''' the ones that are separate-parameter equivalents of inline modifiers. This is automatically "augmented" with the separate-parameter equivalents of the inline modifiers described in `param_mods` prior to parsing the raw arguments with [[Module:parameters]]. '''WARNING:''' This structure is destructively modified, both by the "augmentation" process of adding separate-parameter equivalents of inline modifiers, and by the processing done by [[Module:parameters]] itself. (Nonetheless, substructures can safely be shared in this structure, and will be correctly handled.) * `termarg` ('''required'''): The argument containing the item with attached inline modifiers to be parsed. Usually a numeric value such as {1} or {2}. * `track_module` ('''recommended'''): The name of the calling module, for use in adding tracking pages that are used internally to track pages containing template invocations with certain properties. * `lang` ('''recommended'''): The language object for the language of the item or subitems, or the name of the argument to fetch the object from. It is not strictly necessary to specify this, as this function only initializes items based on inline modifiers and separate arguments and doesn't actually format the resulting items. However, if specified, it is used for certain purposes: *# It specifies the default for the `lang` property of returned objects if not otherwise set (e.g. by a language prefix). *# It is used to initialize an internal cache for speeding up language-code parsing (primarily useful if the same language code may appear in several subitems). The value of `lang` can be any of the following: * If a string or number, it is assumed to be requesting the value of `args` at that key. Note that if the string is in the form of a number (e.g. "3"), it is normalized to a number prior to fetching. * Otherwise, if a function, it is assumed to be a function to return the argument value given `args`, which is passed to the function as its only argument. * Otherwise, it is used directly. * `sc` ('''recommended'''): The script object for the item or subitems, or the name of the argument to fetch the object from. The possible values and their handling are the same as with `lang`. In general, as with `lang`, it is not strictly necessary to specify this. However, if specified, it is used to supply the default for the `sc` property of returned items if not otherwise set (e.g. by the {{para|sc}} parameter or `<sc:...>` inline modifier). The most common value is {"sc"}. * `make_separate_g_into_list`: Set this to {true} if separate gender parameters exist are are specified using {{para|g}}, {{para|g2}}, etc. instead of using a single comma-separated {{para|g}} field. 2. Other argument-related fields: * `adjust_params_before_arg_processing`: An optional function to further adjust the `params` structure prior to calling `process()` in [[Module:parameters]]. This should be used when there are mismatches between the format of a given property as an inline modifier and the corresponding property as a separate parameter (as with the {{para|g}} parameter and {{cd|<g:...>}} modifier, but this particular case is handled by the `make_separate_g_into_list` field). * `process_args_before_parsing`: An optional function to apply further processing to the processed `args` structure returned by [[Module:parameters]], before parsing inline modifiers. This is passed one argument, the processed arguments. It should make modifications in-place. * `term_dest`: The field to store the value of the item itself into, after inline modifiers and (if allowed) language prefixes are stripped off. Defaults to {"term"}. * `pre_normalize_modifiers`: As in `parse_inline_modifiers()`. * `allow_conflicting_inline_mods_and_separate_params`: If specified, don't throw an error if a value is specified for a given property using both an inline modifier and separate param; in this case, the inline modifier takes precedence. * `no_show_decorations`: If set, don't automatically set {show_decorations = true} on items or subitems that have decorations (i.e. qualifiers, labels or references) attached to them. Normally, {show_decorations = true} is set, causing `full_link()` in [[Module:links]] to appropriately display the decorations when showing the item or subitem. If you handle this display yourself, set {no_show_decorations = true} to prevent double display of decorations. 3. Fields related to language prefixes: * `parse_lang_prefix`: If true, allow and parse off a language code prefix attached to items followed by a colon, such as {la:minūtia} or {grc:[[σκῶρ|σκατός]]}. Etymology-only languages are allowed. Inline modifiers can be attached to such items. The exact syntax allowed is as specified in the `parse_term_with_lang()` function in [[Module:parse utilities]]. If `allow_multiple_lang_prefixes` is given, a {{cd|+}}-sign-separated list of language prefixes can be attached to an item. The resulting language object is stored into the `termlang` field, and also into the `lang` field (or in the case of `allow_multiple_lang_prefixes`, the list of language objects is stored into the `termlangs` field, and the first specified object is stored in the `lang` field). * `allow_multiple_lang_prefixes`: If given in conjunction with `parse_lang_prefix`, multiple language code prefixes can be given, separated by a {{cd|+}} sign. See `parse_lang_prefix` above. * `allow_bad_lang_prefix`: If given in conjunction with `parse_lang_prefix`, unrecognized language prefixes do not trigger an error, but are simply ignored (and not stripped off the item). Note that, regardless of whether this is given, prefixes before a colon do not trigger an error if they do not have the form of a language prefix or if a space follows the colon. It is not recommended that this be given because typos in language prefixes will not trigger an error and will tend to remain unfixed. 4. Fields related to multiple subitems in the term: * `splitchar`: A Lua pattern. If specified, the user-specified argument can consist of multiple delimiter-separated subitems, each of which may be followed by inline modifiers. In this case, the first returned value is no longer an object describing the item, but instead an object with a `terms` field, whose value is a list describing the subitems (whose format is the same as the normal format of the item when `splitchar` is not specified). Each subitem object will have a `delimiter` field holding the actual delimiter occurring before the subitem, which is useful in the case where `splitchar` matches multiple possible characters. In this case, it is possible to specify that a given modifier can only occur after the last subitem and effectively modifies the whole collection of subitems by setting `overall = true` on the modifier. In this case, the modifier's value will be stored in the top-level object (the object with the `terms` field specifying the subitems). Note that splitting on delimiters will not happen in certain protected sequences (by default comma+whitespace; see below). In addition, the algorithm to split on delimiters is sensitive to inline modifier syntax and will not be confused by delimiters inside of inline modifiers or inside of square brackets, which do not trigger splitting (whether or not contained within protected sequences). * `escape_fun` and `unescape_fun`: As in `split_escaping()` and `split_alternating_runs_escaping()` in [[Module:parse utilities]]. They control the protected sequences that won't be split when `splitchar` is specified (see previous item). By default, `escape_comma_whitespace` and `unescape_comma_whitespace` are used, so that comma+whitespace sequences won't be split. * `subitem_param_handling`: How to handle separate parameters that are specified in the presence of multiple subitems. The possible values are {"only"} (only allow separate parameters if there aren't any subitems, otherwise throw an error), {"first"} (store the separate parameters in the first subitem) and {"last"} (store the separate parameters in the last subitem). The default is {"only"}. As a special case, an {{para|scN}} separate parameter will be stored into all subitems. * `subitem_separator_map`: Table mapping user-specified delimiters to displayed separators, stored in the `separator` field of the subitem. If not specified, it defaults to `default_subitem_separator_map`. Note that the presence of an item in this table does not mean that it can be used as a delimiter; only the delimiters specified using `splitchar` are recognized. Delimiters not in this map display as-is. Two values are returned, an object describing the item (or subitems) and the processed `args` structure. In the returned item, there will be one field set for each specified property (either through inline modifiers or separate parameters). If subitems are not allowed, the item directly has fields set on it for the specified properties. If subitems ''are'' allowed, the item contains a `terms` field, which is a list of subitem objects, each of which has fields set on it for the specified properties of that subitem. In addition, the following fields may be set on the item or each subitem: * `term`: The term portion of the item (minus inline modifiers and language prefixes). {nil} if no term was given. * `termlang`: If there is a language prefix, the corresponding language object is stored here (only if `parse_lang_prefix` is set and `allow_multiple_lang_prefixes` is not set). * `termlangs`: If there is are language prefixes and both `parse_lang_prefix` and `allow_multiple_lang_prefixes` are set, the list of corresponding language objects is stored here. * `lang`: The language object of the item. This is set when either (a) there is a language prefix parsed off (if multiple prefixes are allowed, this corresponds to the first one); (b) the `lang` property is allowed and specified; (c) neither (a) nor (b) apply and the `lang` field of the overall `data` object is set, providing a default value. * `sc`: The script object of the item. This is set when either (a) the `sc` property is allowed and specified; (b) `sc` isn't otherwise set and the `sc` field of the overall `data` object is set, providing a default value. * `delimiter`: If subitems are allowed, this specifies the delimiter used prior to the given subitem (e.g. {","}). * `separator`: If subitems are allowed, this specifies the displayed form of the delimiter to be shown before a given subitem. The mapping from user-specified delimiters to displayed separators is handled by `subitem_separator_map`; see above. The first subitem always has a blank string in the `separator` field. * `show_decorations`: If the item or subitem has any decorations (i.e. qualifiers, labels or references) specified, {show_decorations = true} is normally set on the item, so that these decorations are displayed when `full_link()` is called. Use {no_show_decorations = true} to prevent this. ]==] function export.parse_term_with_inline_modifiers_and_separate_params(data) validate_argument_related_fields(data) local raw_args, termarg, param_mods, args = data.raw_args, data.termarg, data.param_mods if raw_args then local params = data.params local termarg_spec = params[termarg] if type(termarg_spec) == "table" and termarg_spec.list then internal_error("Term spec in `data.params` must not have `list` set", termarg_spec) end export.augment_params_with_modifiers(params, param_mods, "always") if data.make_separate_g_into_list then -- HACK: g= is a list for compatibility, but sublist as an inline parameter. params.g = {list = true, item_dest = "genders", type = "genders", flatten = true} end local adjust_params_before_arg_processing = data.adjust_params_before_arg_processing if adjust_params_before_arg_processing then adjust_params_before_arg_processing(params) end args = process_params(raw_args, params) else args = data.processed_args end local process_args_before_parsing = data.process_args_before_parsing if process_args_before_parsing then process_args_before_parsing(args) end local term, lang_cache = args[termarg], data.lang_cache local lang = fetch_argument(args, data.lang) if lang and lang_cache then lang_cache[lang:getCode()] = lang end local sc = fetch_argument(args, data.sc) local term_dest = data.term_dest or "term" if not term then track("missing-term", data.track_module) end local termobj, splitchar = {}, data.splitchar if term then local function generate_obj(term, parse_err) return export.generate_obj_maybe_parsing_lang_prefix { term = term, termobj = splitchar and {} or termobj, term_dest = term_dest, paramname = termarg, parse_lang_prefix = data.parse_lang_prefix, parse_err = parse_err, allow_bad_lang_prefix = data.allow_bad_lang_prefix, allow_multiple_lang_prefixes = data.allow_multiple_lang_prefixes, lang_cache = lang_cache, } end parse_inline_modifiers(term, { paramname = termarg, param_mods = param_mods, generate_obj = generate_obj, splitchar = splitchar, preserve_splitchar = true, escape_fun = data.escape_fun, unescape_fun = data.unescape_fun, outer_container = splitchar and termobj or nil, pre_normalize_modifiers = data.pre_normalize_modifiers, }) end -- FIXME: Make into an error, then remove after a month. if data.no_show_qualifiers then track("no_show_qualifiers") end copy_separate_params_to_termobj_and_postprocess { args = args, param_mods = param_mods, termobj = termobj, has_subitems = not not splitchar, lang = lang, sc = sc, subitem_param_handling = data.subitem_param_handling, subitem_separator_map = data.subitem_separator_map or export.default_subitem_separator_map, allow_conflicting_inline_mods_and_separate_params = data.allow_conflicting_inline_mods_and_separate_params, no_show_decorations = data.no_show_decorations or data.no_show_qualifiers, } if splitchar and termobj.terms[2] then track("parse-term-multiple-subitems", data.track_module) track("parse-term-multiple-subitems") end return termobj, args end return export 0ocovy5h7vivua56um7mx5b9e7pm8uc 239026 239025 2026-11-15T04:04:04Z Lee 19 [[:en:Module:parameter_utilities]] වෙතින් එක් සංශෝධනයක් 239025 Scribunto text/plain local export = {} local debug_track_module = "Module:debug/track" local functions_module = "Module:fun" local parameters_module = "Module:parameters" local parse_interface_module = "Module:parse interface" local parse_utilities_module = "Module:parse utilities" local table_module = "Module:table" local dump = mw.dumpObject local error = error local insert = table.insert local ipairs = ipairs local next = next local pairs = pairs local require = require local tonumber = tonumber local type = type --[==[ Loaders for functions in other modules, which overwrite themselves with the target function when called. This ensures modules are only loaded when needed, retains the speed/convenience of locally-declared pre-loaded functions, and has no overhead after the first call, since the target functions are called directly in any subsequent calls. ]==] local function debug_track(...) debug_track = require(debug_track_module) return debug_track(...) end local function is_callable(...) is_callable = require(functions_module).is_callable return is_callable(...) end local function list_to_set(...) list_to_set = require(table_module).listToSet return list_to_set(...) end local function parse_inline_modifiers(...) parse_inline_modifiers = require(parse_interface_module).parse_inline_modifiers return parse_inline_modifiers(...) end local function process_params(...) process_params = require(parameters_module).process return process_params(...) end local function shallow_copy(...) shallow_copy = require(table_module).shallowCopy return shallow_copy(...) end local function table_len(...) table_len = require(table_module).length return table_len(...) end ----------------- end loaders ---------------- local function track(page, track_module) return debug_track((track_module or "parameter utilities") .. "/" .. page) end -- Throw an error prefixed with the words "Internal error" (and suffixed with a dumped version of `spec`, if provided). -- This is for logic errors in the code itself rather than template user errors. local function internal_error(msg, spec) if spec then msg = ("%s: %s"):format(msg, dump(spec)) end error(("Internal error: %s"):format(msg)) end -- Table listing the default recognized special separator arguments and how they display. export.default_special_separators = { [";"] = "; ", ["_"] = " ", ["~"] = " ~ ", ["→"] = " → ", } -- Table listing how subitem delimiters display. Unlike for `default_special_separators`, the presence of an item in -- this table does not mean that the delimiter is recognized; only those specified by `data.splitchar` are recognized. export.default_subitem_separator_map = { [";"] = "; ", [","] = ", ", ["/"] = "/", ["_"] = " ", ["~"] = " ~ ", ["→"] = " → ", } --[==[ intro: The purpose of this module is to facilitate implementation of templates that can have arguments specified either through inline modifiers or separate parameters. There are two types of templates supported: those that take a list of items with associated properties, which can be specified either through indexed separate parameters (e.g. {{para|t2}}, {{para|pos3}}) or inline modifiers (`<t:...>`, `<pos:...>`, etc.); and those that take a single term, whose properties can be specified through non-indexed separate parameters (e.g. {{para|t}} or {{para|pos}}) or inline modifiers. Both types of templates can optionally have subitems in the term parameter(s), where the subitems are typically (but not necessarily) separated with commas and each subitem can have its own inline modifiers. Some examples of templates that take a list of items are {{tl|alter}}/{{tl|alt}}; {{tl|synonyms}}/{{tl|syn}}, {{tl|antonyms}}/{{tl|ant}}, and other "nyms" templates; {{tl|col}}, {{tl|col2}}, {{tl|col3}}, {{tl|col4}} and other column templates; {{tl|descendant}}/{{tl|desc}}; {{tl|affix}}/{{tl|af}}, {{tl|prefix}}/{{tl|pre}} and related *fix templates; {{tl|affixusex}}/{{tl|afex}} and related templates; {{tl|IPA}}; {{tl|homophones}}; {{tl|rhymes}}; and several others. Examples of templates that take a single item are form-of templates ({{tl|inflection of}}/{{tl|infl of}}, {{tl|form of}}, and specific templates such as {{tl|alt form}}/{{tl|alternative form of}}, {{tl|abbr of}}/{{tl|abbreviation of}}, {{tl|clipping of}}, and many others); for etymology templates ({{tl|bor}}/{{tl|borrowed}}, {{tl|der}}/{{tl|derived}}, etc. as well as `misc_variant` templates like {{tl|ellipsis}}, {{tl|abbrev}}, {{tl|clipping}}, {{tl|reduplication}} and the like); and other templates that take an argument structure similar to {{tl|l}} or {{tl|m}}. This module can be thought of as a combination of [[Module:parameters]] (which parses template parameters, and in particular handles the separate parameter versions of the properties) and `parse_inline_modifiers()` in [[Module:parse utilities]] (which parses inline modifiers). The two main entry points are `parse_list_with_inline_modifiers_and_separate_params()` (for templates that take a list of items) and `parse_term_with_inline_modifiers_and_separate_params()` (for templates that take a single item). However, there are other functions provided, e.g. to initialize the `param_mods` structure that is passed to the two entry points. The typical workflow for using `parse_list_with_inline_modifiers_and_separate_params()` looks as follows (a slightly simplified version of the code in [[Module:nyms]]): { local export = {} local parameter_utilities_module = "Module:parameter utilities" ... -- Entry point to be invoked from a template. function export.show(frame) local parent_args = frame:getParent().args -- Parameters that don't have corresponding inline modifiers. Note in particular that the parameter corresponding to -- the items themselves must be specified this way, and must specify either `allow_holes = true` (if the user can -- omit terms, typically by specifying the term using |altN= or <alt:...> so that they remain unlinked) or -- `disallow_holes = true` (if omitting terms is not allowed). (If neither `allow_holes` nor `disallow_holes` is -- specified, an error is thrown in parse_list_with_inline_modifiers_and_separate_params().) local params = { [1] = {required = true, type = "language", default = "und"}, [2] = {list = true, allow_holes = true, required = true, default = "term"}, } local m_param_utils = require(parameter_utilities_module) -- This constructs the `param_mods` structure by adding well-known groups of parameters (such as all the parameters -- associated with based on full_link() in [[Module:links]], with default properties that can be overridden. This is -- easier and less error-prone than manually specifying the `param_mods` structure (see below for how this would -- look). Here, we specify the group "link" (consisting of all the link parameters for use with full_link()), group -- "ref" (which adds the "ref" parameter for specifying references), group "l" (which adds the "l" and "ll" -- parameters for specifying labels) and group "q" (which adds the "q" and "qq" parameters for specifying regular -- qualifiers). By default, labels and qualifiers have `separate_no_index` set so that e.g. |q1= is distinct from -- |q=, the former specifying the left qualifier for the first item and the latter specifying the overall left -- qualifier. For compatibility, we override the `separate_no_index` setting for the group "q", which causes |q= and -- |q1= to be the same, and likewise for |qq= and |qq1=. Finally, also for compatibility, we add an "lb" parameter -- that is an alias of "ll" (in all respects; |lb= is the same as |ll=, |lb1= is the same as |ll1=, <lb:...> is the -- same as <ll:...>, etc.). local param_mods = m_param_utils.construct_param_mods { {group = {"link", "ref", "l"}}, {group = "q", separate_no_index = false}, {param = "lb", alias_of = "ll"}, } -- This processes the raw arguments in `parent_args`, parses inline modifiers and creates corresponding objects -- containing the property values specified either through inline modifiers or separate parameters. local items, args = m_param_utils.parse_list_with_inline_modifiers_and_separate_params { params = params, param_mods = param_mods, raw_args = parent_args, termarg = 2, parse_lang_prefix = true, track_module = "nyms", lang = 1, sc = "sc.default", } local lang = args[1] -- Now do the actual implementation of the template. Generally this should be split into a separate function, often -- in a separate module (if the implementation goes in [[Module:foo]], the template interface code goes in -- [[Module:foo/templates]]). ... } The `param_mods` structure controls the properties that can be specified by the user for a given item, and is conceptually very similar to the `param_mods` structure used by `parse_inline_modifiers()`. The key is the name of the parameter (e.g. {"t"}, {"pos"}) and the value is a table with optional elements as follows: * `item_dest`, `store`: Same as the corresponding fields in the `param_mods` structure passed to `parse_inline_modifiers()`. * `type`, `set`, `sublist`, `convert` and associated fields such as `family` and `method`: These control parsing and conversion of the raw values specified by the user and have the same meaning as in [[Module:parameters]] and also in `parse_inline_modifiers()` (which delegates the actual conversion to [[Module:parameters]]). These fields — and for that matter, all fields other than `item_dest`, `store` and `overall` — are forwarded to the `process()` function in [[Module:parameters]]. * `alias_of`: This parameter is an alias of some other parameter. This spec is recognized only by `process()` in [[Module:parameters]], and not by `parse_inline_modifiers()`; to set up an alias in `parse_inline_modifiers()`, you need to make sure (using `item_dest`) that both the alias and aliasee modifiers store their values in the same location, and you need to copy the remaining properties from the aliasee's spec to the aliasing modifier's spec. All of this happens automatically if you generate the `param_mods` structure using `construct_param_mods()`. * `require_index`: This means that the non-indexed parameter version of the property is not recognized. E.g. in the case of the {"sc"} property, use of the {{para|sc}} parameter would result in an error, while {{para|sc1}} is recognized and specifies the {"sc"} property for the first item. The default, if neither `require_index` nor `separate_no_index` is given, is for {{para|sc}} and {{para|sc1}} to mean the same thing (both would specify the {"sc"} property of the first item). Note that `require_index` and `separate_no_index` are mutually exclusive, and if either one is specified during processing by `construct_param_mods()`, the other one is automaticallly turned off. * `separate_no_index`: This means that e.g. the {{para|sc}} parameter is distinct from the {{para|sc1}} parameter (and thus from the `<sc:...>` inline modifier on the first item). This is typically used to distinguish an overall version of a property from the corresponding item-specific property on the first item. (In this case, for example, {{para|sc}} overrides the script code for all items, while {{para|sc1}} overrides the script code only for the first item.) If not given, and if `require_index` is not given, {{para|sc}} and {{para|sc1}} would have the same meaning and refer to the item-specific property on the first item. When this is given, the overall value can be accessed using the `.default` field of the property value in `args`, e.g. in this case `args.sc.default`. Note that (as mentioned above) `require_index` and `separate_no_index` are mutually exclusive, and if either one is specified during processing by `construct_param_mods()`, the other one is automaticallly turned off. * `list`, `allow_holes`, `disallow_holes`: These should '''not''' be given. `list` and `allow_holes` are automatically set for all parameter specs added to the `params` structure used by `process()` in [[Module:parameters]], and `disallow_holes` clashes with `allow_holes`. For the above workflow example, the call to `construct_param_mods()` generates the following `param_mods` structure: { local param_mods = { -- the parameters generated by group "link" alt = {}, t = { -- [[Module:links]] expects the gloss in "gloss". item_dest = "gloss", }, gloss = { alias_of = "t", }, tr = {}, ts = {}, g = { -- [[Module:links]] expects the genders in "genders". item_dest = "genders", type = "genders", }, pos = {}, ng = {}, lit = {}, id = {}, sc = { separate_no_index = true, type = "script", }, -- the parameters generated by group "ref" ref = { item_dest = "refs", type = "references", }, -- the parameters generated by group "l" l = { type = "labels", separate_no_index = true, }, ll = { type = "labels", separate_no_index = true, }, -- the parameters generated by group "q"; note that `separate_no_index = true` would be set, but is overridden -- (specifying `separate_no_index = false` in the `param_mods` structure is equivalent to not specifying it at all) q = { type = "qualifier", separate_no_index = false, }, qq = { type = "qualifier", separate_no_index = false, }, infl = { type = "form of tags", separate_no_index = true, }, -- the parameter generated by the individual "lb" parameter spec; note that only `alias_of` was explicitly given, -- while `item_dest` is automatically set so that inline modifier <lb:...> stores into the same place as <ll:...>, -- and the other specs are copied from the `ll` spec so `lb` works like `ll` in all regards lb = { alias_of = "ll", item_dest = "ll", type = "labels", separate_no_index = true, }, } } ]==] local qualifier_spec = { type = "qualifier", separate_no_index = true, } local label_spec = { type = "labels", separate_no_index = true, } local form_of_spec = { type = "form of tags", separate_no_index = true, } local recognized_param_mod_groups = { link = { alt = {}, t = { -- [[Module:links]] expects the gloss in "gloss". item_dest = "gloss", }, gloss = { alias_of = "t", }, tr = {}, ts = {}, g = { -- [[Module:links]] expects the genders in "genders". item_dest = "genders", type = "genders", }, pos = {}, ng = {}, lit = {}, id = {}, sc = { separate_no_index = true, type = "script", }, }, lang = { lang = { require_index = true, type = "language", }, }, q = { q = qualifier_spec, qq = qualifier_spec, }, a = { a = label_spec, aa = label_spec, }, l = { l = label_spec, ll = label_spec, }, infl = { infl = form_of_spec, }, ref = { ref = { item_dest = "refs", type = "references", }, }, } local function merge_param_mod_settings(orig, additions) local merged = shallow_copy(orig) for k, v in pairs(additions) do merged[k] = v if k == "require_index" then merged.separate_no_index = nil elseif k == "separate_no_index" then merged.require_index = nil end end merged.default = nil merged.group = nil merged.param = nil merged.exclude = nil merged.include = nil return merged end local function verify_type(spec, param, typ1, typ2) if not spec[param] then return end local val = spec[param] if type(val) ~= typ1 and (not typ2 or type(val) ~= typ2) then internal_error(("Parameter `%s` must be a %s%s but saw a %s"):format(param, typ1, typ2 and " or " .. typ2 or "", type(val)), spec) end end local function verify_well_constructed_spec(spec) local num_control = (spec.default and 1 or 0) + (spec.group and 1 or 0) + (spec.param and 1 or 0) if num_control == 0 then internal_error( "Spec passed to construct_param_mods() must have either the `default`, `group` or `param` keys set", spec) end if num_control > 1 then internal_error( "Exactly one of `default`, `group` or `param` must be set in construct_param_mods() spec", spec) end if spec.list or spec.allow_holes then -- FIXME: We need to support list = "foo" for list parameters that are stored in e.g. 2=, foo2=, foo3=, etc. internal_error("`list` and `allow_holes` may not be set; they are automatically set when constructing the " .. "corresponding spec in the `params` object passed to [[Module:parameters]]", spec) end if spec.disallow_holes then internal_error("`disallow_holes` may not be set; it conflicts with `allow_holes`, which is automatically " .. "set when constructing the corresponding spec in the `params` object passed to [[Module:parameters]]", spec) end if spec.include and spec.exclude then internal_error("Saw both `include` and `exclude` in the same spec", spec) end if (spec.include or spec.exclude) and not spec.group then internal_error( "`include` and `exclude` can only be specified along with `group`, not with `default` or `param`", spec) end verify_type(spec, "group", "string", "table") verify_type(spec, "param", "string", "table") verify_type(spec, "include", "table") verify_type(spec, "exclude", "table") end --[==[ Construct the `param_mods` structure used in parsing arguments and inline modifiers from a list of specifications. A sample invocation (a slightly simplified version of the actual invocation associated with {{tl|affix}} and related templates) looks like this: { local param_mods = require("Module:parameter utilities").construct_param_mods { -- We want to require an index for all params (or use separate_no_index, which also requires an index for the -- param corresponding to the first item). {default = true, require_index = true}, {group = {"link", "ref", "lang", "q", "l"}}, -- Override these two to have separate_no_index. {param = {"lit", "pos"}, separate_no_index = true}, } } Each specification either sets the default value for further parameter specs or adds one or more parameters. Parameters can be added directly using `param`, or groups of predefined parameters can be added using `group`. Specifications are one of three types: # Those that set the default properties for future-added parameters. These contain {default = true} as one of the properties of the spec. Specs are processed in order and you can change the defaults mid-way through. # Those that add the parameters associated with one or more pre-defined groups. These contain {group = "group"} or {group = {"group1", "group2", ...}}. The pre-defined parameter groups and their associated properties are listed below. The pre-defined properties of parameters in a group override properties associated with a {default = true} spec, and are in turn overridden by any properties given directly in the spec itself. Note as well that setting the `separate_no_index` property will automatically cause the `require_index` property to be unset and vice-versa, as the two are mutually exclusive. (This happens in the example above, where the {separate_no_index = true} setting associated with the params {"lit"} and {"pos"} cancels out the {require_index = true} default setting, as well as less obviously with the pre-defined {"sc"} property of the {"link"} group, the {"q"} and {"qq"} properties of the {"q"} group, and the {"l"} and {"ll"} properties of the {"l"} group, all of which have an associated pre-defined property {separate_no_index = true}, which overrides and cancels out the {require_index = true} default setting. Finally, when adding the parameters of a group, you can request the only a subset of the parameters be added using either the `include` or `exclude` properties, each of whose values is a list of parameters that specify (respectively) the parameters to include (all other parameters of the group are excluded) or to exclude (all other parameters of the group are included). This is used, for example, in [[Module:romance etymology]] and [[Module:it-etymology]], which specify {group = "link", exclude = {"tr", "ts", "sc"}} to exclude link parameters that aren't relevant to Latin-script languages such as the Romance languages, and conversely in [[Module:IPA/templates]], which specifies {group = "link", include = {"t", "gloss", "pos"}} to include only the specified parameters for use with {{tl|IPA}}. # Those that add individual parameters. These contain {param = "param"} or {param = {"param1", "param2", ...}}, the latter syntax used to control a set of parameters together. The resulting spec is formed by initializing the parameter's settings with any previously-specified default properties (using a spec containing {default = true}) if the parameter hasn't already been initialized, and then overriding the resulting settings with any settings given directly in the specification. In the above example, the {"lit"} and {"pos"} parameters were previously initialized through the {"link"} group (specified in the second of the three specifications) but ended up with {require_index = true} due to the {default = true} spec (the first of the three specifications). We override these two parameters to have {separate_no_index = true} (which, as mentioned above, cancels out {require_index = true}). This is done so that {{tl|affix}} and related templates have {{para|pos}} and {{para|lit}} parameters distinct from {{para|pos1}} and {{para|lit1}}, which are used to specify an overall part of speech (which applies to all parts of the affix, as opposed to applying to just one element of the expression) or a literal definition for the entire expression (instead of just for one element of the expression). The built-in parameter groups are as follows: {|class="wikitable" ! Group !! Group meaning !! Parameter !! Parameter meaning !! Default properties |- | rowspan=11| `link` | rowspan=11| link parameters; same as those available on {{tl|l}}, {{tl|m}} and other linking templates | `alt` || display text, overriding the term's display form || — |- | `t` || gloss (translation) of a non-English term || {item_dest = "gloss"} |- | `gloss` || gloss (translation); same as `t` || {alias_of = "t"} |- | `tr` || transliteration of a non-Latin-script term; only needed if the automatic transliteration is incorrect or unavailable (e.g. in Hebrew, which doesn't have automatic transliteration) || — |- | `ts` || transcription of a non-Latin-script term, if the transliteration is markedly different from the actual pronunciation; should not be used for IPA pronunciations || — |- | `g` || comma-separated list of genders; whitespace may surround the comma and will be ignored || {item_dest = "genders", type = "genders"} |- | `pos` || part of speech for the term || — |- | `ng` || arbitrary non-gloss descriptive text for the term || — |- | `lit` || literal meaning (translation) of the term || — |- | `id` || a sense ID for the term, which links to anchors on the page set by the {{tl|senseid}} template || — |- | `sc` || the script code (see [[Wiktionary:Scripts]]) for the script that the term is written in; rarely necessary, as the script is autodetected (in most cases, correctly) || {separate_no_index = true, type = "script"} |- | rowspan=2| `q` | rowspan=2| left and right normal qualifiers (as displayed using {{tl|q}}) | `q` || left normal qualifier || {separate_no_index = true, type = "qualifier"} |- | `qq` || right normal qualifier || {separate_no_index = true, type = "qualifier"} |- | rowspan=2| `a` | rowspan=2| left and right accent qualifiers (as displayed using {{tl|a}}) | `a` || comma-separated list of left accent qualifiers; whitespace must not surround the comma || {separate_no_index = true, type = "labels"} |- | `aa` || comma-separated list of right accent qualifiers; whitespace must not surround the comma || {separate_no_index = true, type = "labels"} |- | rowspan=2| `l` | rowspan=2| left and right labels (as displayed using {{tl|lb}}, but without categorizing) | `l` || comma-separated list of left labels; whitespace must not surround the comma || {separate_no_index = true, type = "labels"} |- | `ll` || comma-separated list of right labels; whitespace must not surround the comma || {separate_no_index = true, type = "labels"} |- | `ref` | reference(s) (in the format accepted by [[Module:references]]; see also the documentation for the {{para|ref}} parameter to {{tl|IPA}}) | `ref` || one or more references, in the format accepted by [[Module:references]] || {item_dest = "refs", type = "references"} |- | `lang` | language for an individual term (provided for compatibility; it is preferred to specify languages for individual terms using language prefixes instead) | `lang` || language code (see [[Wiktionary:Languages]]) for the term || {require_index = true, type = "language"} |} ]==] function export.construct_param_mods(specs) local param_mods = {} local default_specs = {} for _, spec in ipairs(specs) do verify_well_constructed_spec(spec) if spec.default then -- This will have an extra `default` field in it, but it will be erased by merge_param_mod_settings() default_specs = spec else if spec.group then local groups = spec.group if type(groups) ~= "table" then groups = {groups} end local include_set if spec.include then include_set = list_to_set(spec.include) end local exclude_set if spec.exclude then exclude_set = list_to_set(spec.exclude) end for _, group in ipairs(groups) do local group_specs = recognized_param_mod_groups[group] if not group_specs then internal_error(("Unrecognized built-in param mod group '%s'"):format(group), spec) end for group_param, group_param_settings in pairs(group_specs) do local include_param if include_set then include_param = include_set[group_param] elseif exclude_set then include_param = not exclude_set[group_param] else include_param = true end if include_param then local merged_settings = merge_param_mod_settings(merge_param_mod_settings( param_mods[group_param] or default_specs, group_param_settings), spec) param_mods[group_param] = merged_settings end end end end if spec.param then local params = spec.param if type(params) ~= "table" then params = {params} end for _, param in ipairs(params) do local settings = merge_param_mod_settings(param_mods[param] or default_specs, spec) -- If this parameter is an alias of another parameter, we need to copy the specs from the other -- parameter, since parse_inline_modifiers() doesn't know about `alias_of` and having the specs -- duplicated won't cause problems for [[Module:parameters]]. We also need to set `item_dest` to -- point to the `item_dest` of the aliasee (defaulting to the aliasee's value itself), so that -- both modifiers write to the same location. Note that this works correctly in the common case of -- <t:...> with `item_dest = "gloss"` and <gloss:...> with `alias_of = "t"`, because both will end -- up with `item_dest = "gloss"`. local aliasee = settings.alias_of if aliasee then local aliasee_settings = param_mods[aliasee] if not aliasee_settings then internal_error(("Undefined aliasee '%s'"):format(aliasee), spec) end for k, v in pairs(aliasee_settings) do if settings[k] == nil then settings[k] = v end end if settings.item_dest == nil then settings.item_dest = aliasee end end param_mods[param] = settings end end end end return param_mods end -- Return true if `k` is a "built-in" (specially recognized) key in a `param_mod` specification. All other keys -- are forwarded to the structure passed to [[Module:parameters]]. local function param_mod_spec_key_is_builtin(k) return k == "item_dest" or k == "overall" or k == "store" end --[==[ Convert the properties in `param_mods` into the appropriate structures for use by `process()` in [[Module:parameters]] and store them in `params`. If `overall_only` is given, only store the properties in `param_mods` that correspond to overall (non-item-specific) parameters. Currently this only happens when `separate_no_index` is specified. ]==] function export.augment_params_with_modifiers(params, param_mods, overall_only) if overall_only then for param_mod, param_mod_spec in pairs(param_mods) do if overall_only == "always" or param_mod_spec.separate_no_index then local param_spec = {} for k, v in pairs(param_mod_spec) do if k ~= "separate_no_index" and k ~= "require_index" and not param_mod_spec_key_is_builtin(k) then param_spec[k] = v end end params[param_mod] = param_spec end end else local list_with_holes -- Add parameters for each term modifier. for param_mod, param_mod_spec in pairs(param_mods) do local param_spec for k, v in pairs(param_mod_spec) do if not param_mod_spec_key_is_builtin(k) then if param_spec == nil then param_spec = {list = true} end param_spec[k] = v end end if param_spec == nil then if list_with_holes == nil then list_with_holes = {list = true, allow_holes = true} end param_spec = list_with_holes elseif param_spec.alias_of == nil then param_spec.allow_holes = true end params[param_mod] = param_spec end end end --[==[ Return true if `k`, a key in an item, refers to a property of the item (is not one of the specially stored values). Note that `lang` and `sc` are considered properties of the item, although `lang` is set when there's a language prefix and both `lang` and `sc` may be set from default values specified in the `data` structure passed into `parse_list_with_inline_modifiers_and_separate_params()` and `parse_term_with_inline_modifiers_and_separate_params()`. If you don't want these treated as property keys, you need to check for them yourself. ]==] function export.item_key_is_property(k) return k ~= "term" and k ~= "termlang" and k ~= "termlangs" and k ~= "itemno" and k ~= "orig_index" and k ~= "separator" end -- Fetch the argument in `args` corresponding to `index_or_value`, which may be a string of the form "foo.default" -- (requesting the value of `args["foo"].default`); a string or number (requesting the value at that key); a function of -- one argument (`args`), which returns the argument value; or the value itself. Return the resulting value and the -- parameter in `args` that the value came from, or nil if unknown (i.e. a function or direct value was specified). local function fetch_argument(args, index_or_value) if not index_or_value then return index_or_value, nil end local index_or_value_type = type(index_or_value) if index_or_value_type == "string" then if index_or_value:sub(-8) == ".default" then local index_without_default = index_or_value:sub(1, -9) local arg_obj = fetch_argument(args, index_without_default) if type(arg_obj) ~= "table" then internal_error(("Requested that the '.default' key of argument `%s` be fetched, but argument value is undefined or not a table"): format(index_without_default), arg_obj) end return arg_obj.default, index_without_default end if index_or_value:match("^%d+$") then index_or_value = tonumber(index_or_value) end return args[index_or_value], index_or_value elseif index_or_value_type == "number" then return args[index_or_value], index_or_value elseif is_callable(index_or_value) then return index_or_value(args), nil end return index_or_value, nil end function export.generate_obj_maybe_parsing_lang_prefix(data) return require(parse_utilities_module).generate_obj_maybe_parsing_lang_prefix(data) end -- Subfunction of parse_list_with_inline_modifiers_and_separate_params() and -- parse_term_with_inline_modifiers_and_separate_params(), validating certain argument-related fields that are shared -- among the two functions. local function validate_argument_related_fields(data) if not data.termarg then internal_error("`data.termarg` must be given, indicating which argument contains the terms to be parsed", data) end if not data.param_mods then internal_error("`data.param_mods` must be given, indicating the allowed inline modifiers and separate " .. "parameters to copy", data) end local subitem_param_handling = data.subitem_param_handling or "only" if subitem_param_handling ~= "only" and subitem_param_handling ~= "first" and subitem_param_handling ~= "last" then internal_error("Unrecognized value for `data.subitem_param_handling`, should be 'first', 'last' or 'only'", subitem_param_handling) end if data.raw_args then if data.processed_args then internal_error("Only one of `data.raw_args` and `data.processed_args` can be specified", data) end if not data.params then internal_error("When `data.raw_args` is specified, so must `data.params`, so that the raw arguments " .. "can be parsed", data) end if data.params[data.termarg] == nil then internal_error("There must be a spec in `data.params` corresponding to `data.termarg`", data) end else if not data.processed_args then internal_error("Either `data.raw_args` or `data.processed_args` must be specified", data) end if data.params then internal_error("When `data.processed_args` is specified, `data.params` should not be specified", data) end end end local function argval_missing(val) return val == nil or type(val) == "table" and next(val) == nil end -- Subfunction of parse_list_with_inline_modifiers_and_separate_params() and -- parse_term_with_inline_modifiers_and_separate_params(). After parsing inline modifiers, copy the separate parameters -- to the generated object (or to the appropriate subobject if there are multiple). `data` contains the following -- fields: -- -- `args`: The separate-parameter argument structure. -- `param_mods`: The structure describing the inline modifiers. -- `itemno`: The logical item number of the term being processed, or nil if there's only a single term. -- `termobj`: The object to store the inline modifiers into. If there are subitems, they are in the `terms` field; -- otherwise the properties are stored directly into `termobj`. -- `has_subitems`: True if there are subitems. -- `subitem_separator_map`: If `has_subitems` and this is specified, controls the assignment of the `separator` field -- in subitems. If not specified or a delimiter is not in the map, it is copied unchanged. -- `lang`: Language object to store into all items. -- `sc`: Script object to store into all items, or nil. -- `subitem_param_handling`: "only", "first" or "last", indicating what to do if there are multiple subitems. -- `allow_conflicting_inline_mods_and_separate_params`: If true, specifying a value for both an inline modifier and -- corresponding separate parameter is allowed, and the inline modifier takes precedence. Otherwise, an error -- occurs. -- `postprocess_termobj`: Optional function called on all items at the end, to do any postprocessing. Called with one -- argument, the object to postprocess. -- `no_show_decorations`: If true, don't automatically set {show_decorations = true} on the object or subobject if there -- are decorations (i.e. qualifiers, labels or references) specified for the object. local function copy_separate_params_to_termobj_and_postprocess(data) local args, param_mods, itemno, termobj = data.args, data.param_mods, data.itemno, data.termobj local function set_lang_and_sc(termobj) -- Set these after parsing inline modifiers, not in generate_obj(), otherwise we'll get an error in -- parse_inline_modifiers() if we try to use <lang:...> or <sc:...> as inline modifiers. termobj.lang = termobj.lang or data.lang termobj.sc = termobj.sc or data.sc end local function set_show_decorations(termobj) -- Need to set after parsing inline modifiers. if not data.no_show_decorations and (termobj.q or termobj.qq or termobj.a or termobj.aa or termobj.l or termobj.ll or termobj.refs) then termobj.show_decorations = true end end local function fetch_separate_param(args, paramkey, itemno) local argval = args[paramkey] -- Careful with argument values that may be `false`. if argval and itemno then argval = argval[itemno] end return argval end -- Copy separate parameters to a given object. local function copy_separate_params_to_termobj(fetch_destobj) for param_mod, param_mod_spec in pairs(param_mods) do local dest = param_mod_spec.item_dest or param_mod -- Don't do anything with the `sc` param, which will get overwritten below; we don't -- want it to cause an error if there are multiple subitems. if dest ~= "sc" then local argval = fetch_separate_param(args, param_mod, itemno) if not argval_missing(argval) then local destobj = fetch_destobj(param_mod, param_mod_spec, dest) -- Don't overwrite a value already set by an inline modifier. if argval_missing(destobj[dest]) then destobj[dest] = argval elseif not data.allow_conflicting_inline_mods_and_separate_params then error(("Can't specify a value for separate parameter %s%s= because there is " .. "already an inline modifier <%s:...> specifying a value for the term"):format( param_mod, itemno or "", param_mod)) end end end end end if data.has_subitems then -- If there are any separate indexed parameters, we need to copy them to the first, last or only -- subitem, depending on the value of `data.subitem_param_handling` (which defaults to 'only', -- meaning it's an error if there are multiple subitems). Do this before calling -- postprocess_termobj() because the latter sets .lang and .sc and we want the user to be able to -- set separate langN= and scN= parameters. -- If there was no term, `termobj.terms` will not exist; make it exist to make the callers' lives easier. if not termobj.terms then termobj.terms = {} end -- Compute whether any of the separate indexed params exist for this index. local any_param_at_index for param_mod in pairs(param_mods) do local argval = fetch_separate_param(args, param_mod, itemno) if not argval_missing(argval) then any_param_at_index = true break end end -- If there was no term, but there's a separate parameter, we need to create an empty subitem. if any_param_at_index and not termobj.terms[1] then termobj.terms[1] = {} end local function fetch_destobj(param_mod, param_mod_spec, dest) if param_mod_spec.overall then return termobj end if data.subitem_param_handling == "only" and termobj.terms[2] then error(("Can't specify a value for separate parameter %s%s= because there are " .. "multiple subitems (%s) in the term; use an inline modifier"):format( param_mod, itemno or "", #termobj.terms)) end local termind -- q/a/l need to go at the beginning and qq/aa/ll/refs at the end, regardless; otherwise, respect -- `data.subitem_param_handling`. if dest == "q" or dest == "a" or dest == "l" then termind = 1 elseif dest == "qq" or dest == "aa" or dest == "ll" or dest == "refs" then termind = #termobj.terms elseif data.subitem_param_handling == "only" or data.subitem_param_handling == "first" then termind = 1 else termind = #termobj.terms end return termobj.terms[termind] end copy_separate_params_to_termobj(fetch_destobj) for i, subitem in ipairs(termobj.terms) do set_lang_and_sc(subitem) set_show_decorations(subitem) if subitem.delimiter then subitem.separator = i == 1 and "" or data.subitem_separator_map and data.subitem_separator_map[subitem.delimiter] or subitem.delimiter end if data.postprocess_termobj then data.postprocess_termobj(subitem, data) end end else -- Copy all the parsed term-specific parameters into `termobj`. copy_separate_params_to_termobj(function(param_mod, dest) return termobj end) set_lang_and_sc(termobj) set_show_decorations(termobj) if data.postprocess_termobj then data.postprocess_termobj(termobj, data) end end end local function postprocess_termobj(item, data) if not (data.disallow_custom_separators or data.use_semicolon) then if data.has_subitems and item.separator and item.separator:find(",", nil, true) then data.use_semicolon = true else -- If the displayed term (from .term/etc. or .alt) has an embedded comma, use a semicolon to -- join the terms. local term_text = item[data.term_dest] or item.alt if term_text and term_text:find(",", nil, true) then data.use_semicolon = true end end end end --[==[ Parse a list of terms, each of which may have properties specified using inline modifiers or separate parameters. This function is intended for parsing the arguments of templates like {{tl|syn}}, {{tl|ant}} and related ''*nym'' templates; alternative-form templates {{tl|alt}}/{{tl|alter}}; affix templates like {{tl|af}}/{{tl|affix}}, {{tl|com}}/{{tl|compound}}, etc.; affix usex templates like {{tl|afex}}/{{tl|affixusex}}; name templates like {{tl|name translit}}; column templates like {{tl|col}}; pronunciation templates like {{tl|rhyme}}/{{tl|rhymes}} and {{tl|hmp}}/{{tl|homophones}}; etc. In these templates there are one or more terms specified using numeric parameters, and associated separate parameters specifying per-term properties such as {{para|t1}}, {{para|t2}}, {{para|t3}}, ... for the gloss of the first, second, third, ... term respectively. All such properties can also be specified through inline modifiers attached directly to each term (`<t:...>`, `<pos:...>`, etc.). Normally it is an error if both an inline modifier and separate parameter for the same value are given, but this can be overridden (in which case inline modifiers take precedence over separate parameters when both occur). For an example of a typical workflow involving this function, see the comment at the top of this file. Some notable properties of this function: # Processing of the raw frame parent args using `process()` in [[Module:parameters]] can occur either inside of this function (the usual workflow) or outside of this function (for more complex cases). In the former case the raw parent args are passed in along with a partially built `params` structure of the sort required by [[Module:parameters]], containing only the term list itself along with any other parameters that are '''not''' term properties (such as a language code in {{para|1}} and boolean flags like {{para|nocat}}, {{para|nocap}}, etc.). This structure is ''augmented'' with list parameters, one for each per-term property, and [[Module:parameters]] is invoked. In the latter case where raw argument processing is done by the caller, they must build the partial `params` structure; augment it themselves using `augment_params_with_modifiers()`; call [[Module:parameters]] themselves; and pass in the processed arguments. In both cases, the return value of this function contains three values: a list of objects, one per term, specifying the term and all properties; the processed arguments structure, so that the non-term-property arguments can be processed as appropriate; and an object containing miscellaneous global computed properties (currently only `use_semicolon`; see below). # Optionally, each term can consist of a number of ''subitems'' separated by delimiters (usually a comma, but the possible delimiter or delimiters are controllable). Each subitem can have its own inline modifiers. This functionality is used, for example, by {{tl|col}} and variants, which allow each row to have comma-separated or tilde-separated subitems. When this feature is invoked, the format of the per-term object changes; instead of directly being an object describing the term and its properties, it is an object with a `terms` field containing a list of per-subitem objects along with other top-level fields describing per-term properties. By default, if there are separate parameters specified along with multiple subitems, an error occurs, but this is controllable; currently, you can request that the parameters be assigned to the first or last subitem. # By default, special ''separator'' arguments may be present, mixed in among regular term arguments. Examples of such separator arguments are (by default; this can be overridden) a bare semicolon, specifying that the terms on either side should be separated by a semicolon instead of a comma (indicating a higher-level grouping); a bare tilde, replacing the comma separator with a tilde (indicating that the terms on either side are alternants); and a bare underscore, replacing the comma separator with a space. Separator arguments are ignored when numbering the separate parameters. You disable the separator argument handling entirely if it doesn't make sense to have this (e.g. in {{tl|af}}/{{tl|affix}}, where the separator is always a {{cd|+}} sign). `data` is an object containing several possible fields. 1. Fields that are required or recommended (usually related to argument processing): * `raw_args` ('''required''' unless `processed_args` is specified): The raw arguments, normally fetched from {frame:getParent().args}. They are parsed using `process()` in [[Module:parameters]]. Most callers pass in raw arguments. * `processed_args`: The object of parsed arguments returned by `process()` in [[Module:parameters]]. One (but not both) of `raw_args` and `processed_args` must be set. * `param_mods` ('''required'''): A structure describing the possible inline modifiers and their properties. See the introductory comment above. Most often, this is generated using `construct_param_mods()` rather than specified manually. * `params` ('''required''' unless `processed_args` is specified): A structure describing the possible parameters, '''other than''' the ones that are separate-parameter equivalents of inline modifiers. This is automatically "augmented" with the separate-parameter equivalents of the inline modifiers described in `param_mods` prior to parsing the raw arguments with [[Module:parameters]]. '''WARNING:''' This structure is destructively modified, both by the "augmentation" process of adding separate-parameter equivalents of inline modifiers, and by the processing done by [[Module:parameters]] itself. (Nonetheless, substructures can safely be shared in this structure, and will be correctly handled.) * `termarg` ('''required'''): The argument containing the first item with attached inline modifiers to be parsed. Usually a numeric value such as {1} or {2}. * `track_module` ('''recommended'''): The name of the calling module, for use in adding tracking pages that are used internally to track pages containing template invocations with certain properties. Example properties tracked are missing items with corresponding properties as well as missing items without corresponding properties (which are skipped entirely). To find out the exact properties tracked and the name of the tracking pages, read the code. * `lang` ('''recommended'''): The language object for the language of the items, or the name of the argument to fetch the object from. It is not strictly necessary to specify this, as this function only initializes items based on inline modifiers and separate arguments and doesn't actually format the resulting items. However, if specified, it is used for certain purposes: *# It specifies the default for the `lang` property of returned objects if not otherwise set (e.g. by a language prefix). *# It is used to initialize an internal cache for speeding up language-code parsing (primarily useful if the same language code may appear in several items, such as with {{tl|col}} and related templates). The value of `lang` can be any of the following: * If a string of the form "foo.default", it is assumed to be requesting the value of `args["foo"].default`. * Otherwise, if a string or number, it is assumed to be requesting the value of `args` at that key. Note that if the string is in the form of a number (e.g. "3"), it is normalized to a number prior to fetching (this also happens with a spec like "2.default"). * Otherwise, if a function, it is assumed to be a function to return the argument value given `args`, which is passed to the function as its only argument. * Otherwise, it is used directly. * `sc` ('''recommended'''): The script object for the items, or the name of the argument to fetch the object from. The possible values and their handling are the same as with `lang`. In general, as with `lang`, it is not strictly necessary to specify this. However, if specified, it is used to supply the default for the `sc` property of returned items if not otherwise set (e.g. by the {{para|sc<var>N</var>}} parameter or `<sc:...>` inline modifier). The most common value is {"sc.default"}. 2. Other argument-related fields: * `process_args_before_parsing`: An optional function to apply further processing to the processed `args` structure returned by [[Module:parameters]], before parsing inline modifiers. This is passed one argument, the processed arguments. It should make modifications in-place. * `term_dest`: The field to store the value of the item itself into, after inline modifiers and (if allowed) language prefixes are stripped off. Defaults to {"term"}. * `pre_normalize_modifiers`: As in `parse_inline_modifiers()`. * `allow_conflicting_inline_mods_and_separate_params`: If specified, don't throw an error if a value is specified for a given property using both an inline modifier and separate param; in this case, the inline modifier takes precedence. 3. Fields related to language prefixes: * `parse_lang_prefix`: If true, allow and parse off a language code prefix attached to items followed by a colon, such as {la:minūtia} or {grc:[[σκῶρ|σκατός]]}. Etymology-only languages are allowed. Inline modifiers can be attached to such items. The exact syntax allowed is as specified in the `parse_term_with_lang()` function in [[Module:parse utilities]]. If `allow_multiple_lang_prefixes` is given, a {{cd|+}}-sign-separated list of language prefixes can be attached to an item. The resulting language object is stored into the `termlang` field, and also into the `lang` field (or in the case of `allow_multiple_lang_prefixes`, the list of language objects is stored into the `termlangs` field, and the first specified object is stored in the `lang` field). * `allow_multiple_lang_prefixes`: If given in conjunction with `parse_lang_prefix`, multiple language code prefixes can be given, separated by a {{cd|+}} sign. See `parse_lang_prefix` above. * `allow_bad_lang_prefix`: If given in conjunction with `parse_lang_prefix`, unrecognized language prefixes do not trigger an error, but are simply ignored (and not stripped off the item). Note that, regardless of whether this is given, prefixes before a colon do not trigger an error if they do not have the form of a language prefix or if a space follows the colon. It is not recommended that this be given because typos in language prefixes will not trigger an error and will tend to remain unfixed. 4. Fields related to custom/special separators: * `disallow_custom_separators`: If specified, disallow specifying custom separators (semicolon, underscore, tilde; see the internal `default_special_separators` table, or the `special_separators` field) as an item value to override the default separator. By default, the previous separator of each item is considered to be an empty string (for the first item) and otherwise the value of the field `default_separator` (normally a comma + space), unless either the preceding item is one of the values listed in `special_separators`, such as a bare semicolon (which causes the following item's previous separator to be a semicolon + space) or an item has an embedded comma in it (which causes ''all'' items other than the first to have their previous separator be a semicolon + space). The previous separator of each item is set on the item's `separator` property. Bare semicolons and other separator arguments do not count when indexing items using separate parameters. For example, the following is correct: ** {{tl|template|lang|item 1|q1=qualifier 1|;|item 2|q2=qualifier 2}} If `disallow_custom_separators` is specified, however, the `separator` property is not set and separator arguments are not recognized. * `default_separator`: Override the default separator (normally {", "}). * `special_separators`: Table giving the special/custom separators that can be given, and how they should display. If not specified, the default in `default_special_separators` is used. This is a table mapping separator values (such as {"~"}) to the corresponding display string (such as {" ~ "}). 5. Fields related to multiple subitems in a given term: * `splitchar`: A Lua pattern. If specified, each user-specified argument can consist of multiple delimiter-separated subitems, each of which may be followed by inline modifiers. In this case, each element in the returned list of items is no longer an object describing an item, but instead an object with a `terms` field, whose value is a list describing the subitems (whose format is the same as the normal format of an item in the top-level list when `splitchar` is not specified). Each subitem object will have a `delimiter` field holding the actual delimiter occurring before the subitem, which is useful in the case where `splitchar` matches multiple possible characters. In this case, it is possible to specify that a given modifier can only occur after the last subitem and effectively modifies the whole collection of subitems by setting {overall = true} on the modifier. In this case, the modifier's value will be stored in the top-level object (the object with the `terms` field specifying the subitems). Note that splitting on delimiters will not happen in certain protected sequences (by default comma+whitespace; see below). In addition, the algorithm to split on delimiters is sensitive to inline modifier syntax and will not be confused by delimiters inside of inline modifiers or inside of square brackets, which do not trigger splitting (whether or not contained within protected sequences). * `escape_fun` and `unescape_fun`: As in `split_escaping()` and `split_alternating_runs_escaping()` in [[Module:parse utilities]]. They control the protected sequences that won't be split when `splitchar` is specified (see previous item). By default, `escape_comma_whitespace` and `unescape_comma_whitespace` are used, so that comma+whitespace sequences won't be split. * `subitem_param_handling`: How to handle separate parameters that are specified in the presence of multiple subitems. The possible values are {"only"} (only allow separate parameters if there aren't any subitems, otherwise throw an error), {"first"} (store the separate parameters in the first subitem) and {"last"} (store the separate parameters in the last subitem). The default is {"only"}. As a special case, an {{para|scN}} separate parameter will be stored into all subitems. * `subitem_separator_map`: Table mapping user-specified delimiters to displayed separators, stored in the `separator` field of the subitem. If not specified, it defaults to `default_subitem_separator_map`. Note that the presence of an item in this table does not mean that it can be used as a delimiter; only the delimiters specified using `splitchar` are recognized. Delimiters not in this map display as-is. 6. Other fields: * `dont_skip_items`: Normally, items that are completely unspecified (have no term and no properties) are skipped and not inserted into the returned list of items. (Such items cannot occur if {disallow_holes = true} is set on the term specification in the `params` structure passed to `process()` in [[Module:parameters]]. It is generally recommended to do so unless a specific meaning is associated the term value being missing.) If `dont_skip_items` is set, however, items are never skipped, and completely unspecified items will be returned along with others. (They will not have the term or any properties set, but will have the normal non-property fields set; see below.) * `stop_when`: If specified, a function to determine when to prematurely stop processing items. It is passed a single argument, an object containing the following fields: ** `term`: The raw term, prior to parsing off language prefixes and inline modifiers (since the processing of `stop_when` happens before parsing the term). ** `any_param_at_index`: True if any separate property parameters exist for this item. ** `orig_index`: Same as `orig_index` below. ** `itemno`: Same as `itemno` below. ** `stored_itemno`: The index where this item will be stored into the returned items table. This may differ from `itemno` due to skipped items (it will never be different if `dont_skip_items` is set). The function should return true to stop processing items and return the ones processed so far (not including the item currently being processed). This is used, for example, in [[Module:alternative forms]], where an unspecified item signal the end of items and the start of labels. * `no_show_decorations`: If set, don't automatically set {show_decorations = true} on items or subitems that have decorations (i.e. qualifiers, labels or references) attached to them. Normally, {show_decorations = true} is set, causing `full_link()` in [[Module:links]] to appropriately display the decorations when showing the item or subitem. If you handle this display yourself, set {no_show_decorations = true} to prevent double display of decorations. Three values are returned: the list of items; the processed `args` structure; and an object of miscellaneous computed global values (currently only `use_semicolon`, indicating that commas were found in individual arguments and so the default separator should be a semicolon). In each returned item, there will be one field set for each specified property (either through inline modifiers or separate parameters). If subitems are not allowed, each item directly has fields set on it for the specified properties. If subitems ''are'' allowed, each item contains a `terms` field, which is a list of subitem objects, each of which has fields set on it for the specified properties of that subitem. In addition, the following fields may be set on each item or subitem: * `term`: The term portion of the item (minus inline modifiers and language prefixes). {nil} if no term was given. * `orig_index`: The original index into the item in the items table returned by `process()` in [[Module:parameters]]. This may differ from `itemno` if there are raw semiclons and `disallow_custom_separators` is not given. * `itemno`: The logical index of the item. The index of separate parameters corresponds to this index. This may be different from `orig_index` in the presence of raw semicolons; see above. * `termlang`: If there is a language prefix, the corresponding language object is stored here (only if `parse_lang_prefix` is set and `allow_multiple_lang_prefixes` is not set). * `termlangs`: If there is are language prefixes and both `parse_lang_prefix` and `allow_multiple_lang_prefixes` are set, the list of corresponding language objects is stored here. * `lang`: The language object of the item. This is set when either (a) there is a language prefix parsed off (if multiple prefixes are allowed, this corresponds to the first one); (b) the `lang` property is allowed and specified; (c) neither (a) nor (b) apply and the `lang` field of the overall `data` object is set, providing a default value. * `sc`: The script object of the item. This is set when either (a) the `sc` property is allowed and specified; (b) `sc` isn't otherwise set and the `sc` field of the overall `data` object is set, providing a default value. * `delimiter`: If subitems are allowed, this is set on subitems and specifies the delimiter used prior to the given subitem (e.g. {","}). * `separator`: The separator to display before the item. Always set on subitems, and set on top-level items if `disallow_custom_separators` is not given. Controlled by `special_separators` (for top-level items) and `subitem_separator_map` (for subitems). * `show_decorations`: If the item or subitem has any decorations (i.e. qualifiers, labels or references) specified, {show_decorations = true} is normally set on the item, so that these decorations are displayed when `full_link()` is called. Use {no_show_decorations = true} to prevent this. ]==] function export.parse_list_with_inline_modifiers_and_separate_params(data) validate_argument_related_fields(data) local raw_args, termarg, param_mods, args = data.raw_args, data.termarg, data.param_mods if raw_args then local params = data.params local termarg_spec = params[termarg] if termarg_spec == true or not termarg_spec.list then internal_error("Term spec in `data.params` must have `list` set", termarg_spec) end if termarg_spec == true or not (termarg_spec.allow_holes or termarg_spec.disallow_holes) then internal_error("Term spec in `data.params` must have either `allow_holes` or `disallow_holes` set", termarg_spec) end export.augment_params_with_modifiers(params, param_mods) args = process_params(raw_args, params) else args = data.processed_args end local process_args_before_parsing = data.process_args_before_parsing if process_args_before_parsing then process_args_before_parsing(args) end -- Find the maximum index among any of the list parameters. local term_args = args[termarg] -- As a special case, the term args might not have a `maxindex` field because they might have -- been declared with `disallow_holes = true`, so fall back to the actual length of the list -- using the table_len function, since # can be unpredictable with arbitrary tables. local maxmaxindex = term_args.maxindex or table_len(term_args) for _, v in pairs(args) do if type(v) == "table" and v.maxindex and v.maxindex > maxmaxindex then maxmaxindex = v.maxindex end end local special_separators = data.special_separators or export.default_special_separators local items, lang_cache, use_semicolon = {}, data.lang_cache or {} local lang = fetch_argument(args, data.lang) if lang then lang_cache[lang:getCode()] = lang end local sc = fetch_argument(args, data.sc) local term_dest = data.term_dest or "term" -- FIXME: this is vulnerable to abusive inputs like 1000000=. local itemno = 0 for i = 1, maxmaxindex do local term = term_args[i] if data.disallow_custom_separators or not special_separators[term] then itemno = itemno + 1 -- Compute whether any of the separate indexed params exist for this index. local any_param_at_index for param_mod in pairs(param_mods) do local argval = args[param_mod] -- Careful with argument values that may be `false`. if argval then argval = argval[itemno] end if not argval_missing(argval) then any_param_at_index = true break end end if data.stop_when and data.stop_when{ term = term, -- FIXME, we should just pass in `any_param_at_index` directly. any_param_at_index = term ~= nil or any_param_at_index, orig_index = i, itemno = itemno, stored_itemno = #items + 1, } then break end -- If any of the params used for formatting this term is present, create a term and add it to the list. if not data.dont_skip_items and term == nil and not any_param_at_index then track("skipped-term", data.track_module) else if not term then track("missing-term", data.track_module) end local termobj = { itemno = itemno, orig_index = i, } if not data.disallow_custom_separators then termobj.separator = i == 1 and "" or special_separators[term_args[i - 1]] end -- Add 1 because first term index starts at 2. local paramname = termarg + i - 1 if term then local function generate_obj(term, parse_err) return export.generate_obj_maybe_parsing_lang_prefix { term = term, termobj = data.splitchar and {} or termobj, term_dest = term_dest, paramname = paramname, parse_lang_prefix = data.parse_lang_prefix, parse_err = parse_err, allow_bad_lang_prefix = data.allow_bad_lang_prefix, allow_multiple_lang_prefixes = data.allow_multiple_lang_prefixes, lang_cache = lang_cache, } end parse_inline_modifiers(term, { paramname = paramname, param_mods = param_mods, generate_obj = generate_obj, splitchar = data.splitchar, preserve_splitchar = true, escape_fun = data.escape_fun, unescape_fun = data.unescape_fun, outer_container = data.splitchar and termobj or nil, pre_normalize_modifiers = data.pre_normalize_modifiers, }) end -- FIXME: Make into an error, then remove after a month. if data.no_show_qualifiers then track("no_show_qualifiers") end local term_data = { args = args, param_mods = param_mods, itemno = itemno, termobj = termobj, term_dest = term_dest, has_subitems = not not data.splitchar, lang = lang, -- As a special case, if the caller defined a scN= separate param, set it on all subitems if there -- are multiple, falling back to the overall sc= param. sc = args.sc and args.sc[itemno] or sc, subitem_param_handling = data.subitem_param_handling, subitem_separator_map = data.subitem_separator_map or export.default_subitem_separator_map, allow_conflicting_inline_mods_and_separate_params = data.allow_conflicting_inline_mods_and_separate_params, postprocess_termobj = postprocess_termobj, disallow_custom_separators = data.disallow_custom_separators, use_semicolon = use_semicolon, no_show_decorations = data.no_show_decorations or data.no_show_qualifiers, } copy_separate_params_to_termobj_and_postprocess(term_data) use_semicolon = term_data.use_semicolon insert(items, termobj) end end end if not data.disallow_custom_separators then -- Set the default separator of all those items for which a separator wasn't explicitly given to the default -- separator, defaulting to comma + space; but if any items have embedded commas, set the separator to -- semicolon + space. for _, item in ipairs(items) do if not item.separator then -- Only change the separator to a semicolon when the default separator is a comma (or at least has a -- comma in it). We don't want this e.g. in {{affix}}, where the default separator is + and should -- remain so even if there's a comma in an argument. local comma_in_default_separator = not data.default_separator or not not data.default_separator:find(",") item.separator = use_semicolon and comma_in_default_separator and "; " or data.default_separator or ", " end end end return items, args, {use_semicolon = use_semicolon} end --[==[ Parse a single term that may have properties specified through inline modifiers or separate parameters. This differs from `parse_list_with_inline_modifiers_and_separate_params()` in that the latter is for parsing a list of terms, each of which may have properties specified through inline modifiers or separate parameters. Both functions optionally support having multiple subitems in a single term. This function is used e.g. for form-of templates ({{tl|inflection of}}/{{tl|infl of}}, {{tl|form of}}, and specific templates such as {{tl|alt form}}/{{tl|alternative form of}}, {{tl|abbr of}}/{{tl|abbreviation of}}, {{tl|clipping of}}, and many others); for etymology templates ({{tl|bor}}/{{tl|borrowed}}, {{tl|der}}/{{tl|derived}}, etc. as well as `misc_variant` templates like {{tl|ellipsis}}, {{tl|abbrev}}, {{tl|clipping}}, {{tl|reduplication}} and the like); and for other templates with an argument structure similar to {{tl|l}} or {{tl|m}}. In these templates there is a term specified using a numeric parameter and associated separate parameters specifying term properties such as {{para|t}} for the gloss or {{para|tr}} for manual transliteration. All such properties can also be specified through inline modifiers attached directly to each term (`<t:...>`, `<tr:...>`, etc.). Normally it is an error if both an inline modifier and separate parameter for the same value are given, but this can be overridden (in which case inline modifiers take precedence over separate parameters when both occur). Some notable properties of this function: # Processing of the raw frame parent args using `process()` in [[Module:parameters]] can occur either inside of this function (the usual workflow) or outside of this function (for more complex cases). In the former case the raw parent args are passed in along with a partially built `params` structure of the sort required by [[Module:parameters]], containing only the term list itself along with any other parameters that are '''not''' term properties (such as a language code in {{para|1}} and boolean flags like {{para|nocat}}, {{para|nocap}}, etc.). This structure is ''augmented'' with parameters, one for each per-term property, and [[Module:parameters]] is invoked. In the latter case where raw argument processing is done by the caller, they must build the partial `params` structure; augment it themselves using `augment_params_with_modifiers()`; call [[Module:parameters]] themselves; and pass in the processed arguments. In both cases, the return value of this function contains two values, an object specifying the term and all properties; and the processed arguments structure, so that the non-term-property arguments can be processed as appropriate. # Optionally, the term can consist of a number of ''subitems'' separated by delimiters (usually a comma, but the possible delimiter or delimiters are controllable). Each subitem can have its own inline modifiers. This functionality is used, for example, by form-of templates. When this feature is invoked, the format of the term object changes; instead of directly being an object describing the term and its properties, it is an object with a `terms` field containing a list of per-subitem objects along with other top-level fields describing per-term properties. By default, if there are separate parameters specified along with multiple subitems, an error occurs, but this is controllable; currently, you can request that the parameters be assigned to the first or last subitem. `data` is an object containing several possible fields. 1. Fields that are required or recommended (usually related to argument processing): * `raw_args` ('''required''' unless `processed_args` is specified): The raw arguments, normally fetched from {frame:getParent().args}. They are parsed using `process()` in [[Module:parameters]]. Most callers pass in raw arguments. * `processed_args`: The object of parsed arguments returned by `process()` in [[Module:parameters]]. One (but not both) of `raw_args` and `processed_args` must be set. * `param_mods` ('''required'''): A structure describing the possible inline modifiers and their properties. See the introductory comment above. Most often, this is generated using `construct_param_mods()` rather than specified manually. * `params` ('''required''' unless `processed_args` is specified): A structure describing the possible parameters, '''other than''' the ones that are separate-parameter equivalents of inline modifiers. This is automatically "augmented" with the separate-parameter equivalents of the inline modifiers described in `param_mods` prior to parsing the raw arguments with [[Module:parameters]]. '''WARNING:''' This structure is destructively modified, both by the "augmentation" process of adding separate-parameter equivalents of inline modifiers, and by the processing done by [[Module:parameters]] itself. (Nonetheless, substructures can safely be shared in this structure, and will be correctly handled.) * `termarg` ('''required'''): The argument containing the item with attached inline modifiers to be parsed. Usually a numeric value such as {1} or {2}. * `track_module` ('''recommended'''): The name of the calling module, for use in adding tracking pages that are used internally to track pages containing template invocations with certain properties. * `lang` ('''recommended'''): The language object for the language of the item or subitems, or the name of the argument to fetch the object from. It is not strictly necessary to specify this, as this function only initializes items based on inline modifiers and separate arguments and doesn't actually format the resulting items. However, if specified, it is used for certain purposes: *# It specifies the default for the `lang` property of returned objects if not otherwise set (e.g. by a language prefix). *# It is used to initialize an internal cache for speeding up language-code parsing (primarily useful if the same language code may appear in several subitems). The value of `lang` can be any of the following: * If a string or number, it is assumed to be requesting the value of `args` at that key. Note that if the string is in the form of a number (e.g. "3"), it is normalized to a number prior to fetching. * Otherwise, if a function, it is assumed to be a function to return the argument value given `args`, which is passed to the function as its only argument. * Otherwise, it is used directly. * `sc` ('''recommended'''): The script object for the item or subitems, or the name of the argument to fetch the object from. The possible values and their handling are the same as with `lang`. In general, as with `lang`, it is not strictly necessary to specify this. However, if specified, it is used to supply the default for the `sc` property of returned items if not otherwise set (e.g. by the {{para|sc}} parameter or `<sc:...>` inline modifier). The most common value is {"sc"}. * `make_separate_g_into_list`: Set this to {true} if separate gender parameters exist are are specified using {{para|g}}, {{para|g2}}, etc. instead of using a single comma-separated {{para|g}} field. 2. Other argument-related fields: * `adjust_params_before_arg_processing`: An optional function to further adjust the `params` structure prior to calling `process()` in [[Module:parameters]]. This should be used when there are mismatches between the format of a given property as an inline modifier and the corresponding property as a separate parameter (as with the {{para|g}} parameter and {{cd|<g:...>}} modifier, but this particular case is handled by the `make_separate_g_into_list` field). * `process_args_before_parsing`: An optional function to apply further processing to the processed `args` structure returned by [[Module:parameters]], before parsing inline modifiers. This is passed one argument, the processed arguments. It should make modifications in-place. * `term_dest`: The field to store the value of the item itself into, after inline modifiers and (if allowed) language prefixes are stripped off. Defaults to {"term"}. * `pre_normalize_modifiers`: As in `parse_inline_modifiers()`. * `allow_conflicting_inline_mods_and_separate_params`: If specified, don't throw an error if a value is specified for a given property using both an inline modifier and separate param; in this case, the inline modifier takes precedence. * `no_show_decorations`: If set, don't automatically set {show_decorations = true} on items or subitems that have decorations (i.e. qualifiers, labels or references) attached to them. Normally, {show_decorations = true} is set, causing `full_link()` in [[Module:links]] to appropriately display the decorations when showing the item or subitem. If you handle this display yourself, set {no_show_decorations = true} to prevent double display of decorations. 3. Fields related to language prefixes: * `parse_lang_prefix`: If true, allow and parse off a language code prefix attached to items followed by a colon, such as {la:minūtia} or {grc:[[σκῶρ|σκατός]]}. Etymology-only languages are allowed. Inline modifiers can be attached to such items. The exact syntax allowed is as specified in the `parse_term_with_lang()` function in [[Module:parse utilities]]. If `allow_multiple_lang_prefixes` is given, a {{cd|+}}-sign-separated list of language prefixes can be attached to an item. The resulting language object is stored into the `termlang` field, and also into the `lang` field (or in the case of `allow_multiple_lang_prefixes`, the list of language objects is stored into the `termlangs` field, and the first specified object is stored in the `lang` field). * `allow_multiple_lang_prefixes`: If given in conjunction with `parse_lang_prefix`, multiple language code prefixes can be given, separated by a {{cd|+}} sign. See `parse_lang_prefix` above. * `allow_bad_lang_prefix`: If given in conjunction with `parse_lang_prefix`, unrecognized language prefixes do not trigger an error, but are simply ignored (and not stripped off the item). Note that, regardless of whether this is given, prefixes before a colon do not trigger an error if they do not have the form of a language prefix or if a space follows the colon. It is not recommended that this be given because typos in language prefixes will not trigger an error and will tend to remain unfixed. 4. Fields related to multiple subitems in the term: * `splitchar`: A Lua pattern. If specified, the user-specified argument can consist of multiple delimiter-separated subitems, each of which may be followed by inline modifiers. In this case, the first returned value is no longer an object describing the item, but instead an object with a `terms` field, whose value is a list describing the subitems (whose format is the same as the normal format of the item when `splitchar` is not specified). Each subitem object will have a `delimiter` field holding the actual delimiter occurring before the subitem, which is useful in the case where `splitchar` matches multiple possible characters. In this case, it is possible to specify that a given modifier can only occur after the last subitem and effectively modifies the whole collection of subitems by setting `overall = true` on the modifier. In this case, the modifier's value will be stored in the top-level object (the object with the `terms` field specifying the subitems). Note that splitting on delimiters will not happen in certain protected sequences (by default comma+whitespace; see below). In addition, the algorithm to split on delimiters is sensitive to inline modifier syntax and will not be confused by delimiters inside of inline modifiers or inside of square brackets, which do not trigger splitting (whether or not contained within protected sequences). * `escape_fun` and `unescape_fun`: As in `split_escaping()` and `split_alternating_runs_escaping()` in [[Module:parse utilities]]. They control the protected sequences that won't be split when `splitchar` is specified (see previous item). By default, `escape_comma_whitespace` and `unescape_comma_whitespace` are used, so that comma+whitespace sequences won't be split. * `subitem_param_handling`: How to handle separate parameters that are specified in the presence of multiple subitems. The possible values are {"only"} (only allow separate parameters if there aren't any subitems, otherwise throw an error), {"first"} (store the separate parameters in the first subitem) and {"last"} (store the separate parameters in the last subitem). The default is {"only"}. As a special case, an {{para|scN}} separate parameter will be stored into all subitems. * `subitem_separator_map`: Table mapping user-specified delimiters to displayed separators, stored in the `separator` field of the subitem. If not specified, it defaults to `default_subitem_separator_map`. Note that the presence of an item in this table does not mean that it can be used as a delimiter; only the delimiters specified using `splitchar` are recognized. Delimiters not in this map display as-is. Two values are returned, an object describing the item (or subitems) and the processed `args` structure. In the returned item, there will be one field set for each specified property (either through inline modifiers or separate parameters). If subitems are not allowed, the item directly has fields set on it for the specified properties. If subitems ''are'' allowed, the item contains a `terms` field, which is a list of subitem objects, each of which has fields set on it for the specified properties of that subitem. In addition, the following fields may be set on the item or each subitem: * `term`: The term portion of the item (minus inline modifiers and language prefixes). {nil} if no term was given. * `termlang`: If there is a language prefix, the corresponding language object is stored here (only if `parse_lang_prefix` is set and `allow_multiple_lang_prefixes` is not set). * `termlangs`: If there is are language prefixes and both `parse_lang_prefix` and `allow_multiple_lang_prefixes` are set, the list of corresponding language objects is stored here. * `lang`: The language object of the item. This is set when either (a) there is a language prefix parsed off (if multiple prefixes are allowed, this corresponds to the first one); (b) the `lang` property is allowed and specified; (c) neither (a) nor (b) apply and the `lang` field of the overall `data` object is set, providing a default value. * `sc`: The script object of the item. This is set when either (a) the `sc` property is allowed and specified; (b) `sc` isn't otherwise set and the `sc` field of the overall `data` object is set, providing a default value. * `delimiter`: If subitems are allowed, this specifies the delimiter used prior to the given subitem (e.g. {","}). * `separator`: If subitems are allowed, this specifies the displayed form of the delimiter to be shown before a given subitem. The mapping from user-specified delimiters to displayed separators is handled by `subitem_separator_map`; see above. The first subitem always has a blank string in the `separator` field. * `show_decorations`: If the item or subitem has any decorations (i.e. qualifiers, labels or references) specified, {show_decorations = true} is normally set on the item, so that these decorations are displayed when `full_link()` is called. Use {no_show_decorations = true} to prevent this. ]==] function export.parse_term_with_inline_modifiers_and_separate_params(data) validate_argument_related_fields(data) local raw_args, termarg, param_mods, args = data.raw_args, data.termarg, data.param_mods if raw_args then local params = data.params local termarg_spec = params[termarg] if type(termarg_spec) == "table" and termarg_spec.list then internal_error("Term spec in `data.params` must not have `list` set", termarg_spec) end export.augment_params_with_modifiers(params, param_mods, "always") if data.make_separate_g_into_list then -- HACK: g= is a list for compatibility, but sublist as an inline parameter. params.g = {list = true, item_dest = "genders", type = "genders", flatten = true} end local adjust_params_before_arg_processing = data.adjust_params_before_arg_processing if adjust_params_before_arg_processing then adjust_params_before_arg_processing(params) end args = process_params(raw_args, params) else args = data.processed_args end local process_args_before_parsing = data.process_args_before_parsing if process_args_before_parsing then process_args_before_parsing(args) end local term, lang_cache = args[termarg], data.lang_cache local lang = fetch_argument(args, data.lang) if lang and lang_cache then lang_cache[lang:getCode()] = lang end local sc = fetch_argument(args, data.sc) local term_dest = data.term_dest or "term" if not term then track("missing-term", data.track_module) end local termobj, splitchar = {}, data.splitchar if term then local function generate_obj(term, parse_err) return export.generate_obj_maybe_parsing_lang_prefix { term = term, termobj = splitchar and {} or termobj, term_dest = term_dest, paramname = termarg, parse_lang_prefix = data.parse_lang_prefix, parse_err = parse_err, allow_bad_lang_prefix = data.allow_bad_lang_prefix, allow_multiple_lang_prefixes = data.allow_multiple_lang_prefixes, lang_cache = lang_cache, } end parse_inline_modifiers(term, { paramname = termarg, param_mods = param_mods, generate_obj = generate_obj, splitchar = splitchar, preserve_splitchar = true, escape_fun = data.escape_fun, unescape_fun = data.unescape_fun, outer_container = splitchar and termobj or nil, pre_normalize_modifiers = data.pre_normalize_modifiers, }) end -- FIXME: Make into an error, then remove after a month. if data.no_show_qualifiers then track("no_show_qualifiers") end copy_separate_params_to_termobj_and_postprocess { args = args, param_mods = param_mods, termobj = termobj, has_subitems = not not splitchar, lang = lang, sc = sc, subitem_param_handling = data.subitem_param_handling, subitem_separator_map = data.subitem_separator_map or export.default_subitem_separator_map, allow_conflicting_inline_mods_and_separate_params = data.allow_conflicting_inline_mods_and_separate_params, no_show_decorations = data.no_show_decorations or data.no_show_qualifiers, } if splitchar and termobj.terms[2] then track("parse-term-multiple-subitems", data.track_module) track("parse-term-multiple-subitems") end return termobj, args end return export 0ocovy5h7vivua56um7mx5b9e7pm8uc accelerate 0 140217 239037 227285 2026-11-15T04:17:06Z Lee 19 ශුද්ධ පවිත්‍ර කිරීම 239037 wikitext text/x-wiki == ඉංග්‍රීසි == === නිරුක්තිය === {{root|en|ine-pro|*kel-}} First attested in the 1520s. Either from {{lbor|en|la|accelerātus|notext=1}}, {{glossary|perfect}} {{glossary|passive}} {{glossary|participle}} of {{m|la|accelerō||to accelerate, hasten}} (see {{af|en|-ate|id1=verb|pos1=verb-forming suffix}} and {{af|en|-ate|id1=adjective|pos1=adjective-forming suffix}}), formed from {{m|la|ad}} + {{m|la|celerō||to hasten}}, which is from {{m|la|celer||quick}} (see [[celerity]]), or {{back-form|en|acceleration|nocap=1}}.<ref>{{R:CDOE|page=6}}</ref> === උච්චාරණය === * {{IPA|en|/əkˈsɛl.əˌɹeɪt/|/ækˈsɛl.əˌɹeɪt/|/ɪkˈsɛl.əˌɹeɪt/|a=RP}} * {{IPA|en|/ɪkˈsɛl.əˌɹeɪt/|a=GA}} ** {{IPA|en|/əkˈsɛl.əˌɹeɪt/|a=weak vowel}} * {{audio|en|en-us-accelerate.ogg|a=US}} === ක්‍රියා පදය === {{en-verb}} # {{lb|en|transitive}} To cause to move [[faster]]; to [[quicken]] the motion of; to add to the [[speed]] of. # {{lb|en|transitive}} To quicken the natural or ordinary [[progression]] or [[process]] of. #: {{co|en|to '''accelerate''' the growth of a plant, the increase of wealth, etc.}} #: {{ux|en|The company plans to '''accelerate''' its growth with new marketing strategies.}} #: {{ux|en|She had to '''accelerate''' her work pace to meet the deadline.}} #* {{quote-journal|en|year=2013|month=September-October|author=[http://www.americanscientist.org/authors/detail/michael-sivak Michael Sivak] |magazine=w:American Scientist|title=[http://www.americanscientist.org/issues/pub/2013/5/will-ac-put-a-chill-on-the-global-energy-supply Will AC Put a Chill on the Global Energy Supply?] |passage=Nevertheless, it is clear that the global energy demand for air-conditioning will grow substantially as nations become more affluent, with the consequences of climate change potentially '''accelerating''' the demand.}} # {{lb|en|transitive|physics}} To cause a change of [[velocity]]. # {{lb|en|transitive}} To [[hasten]], as the occurrence of an event. #: {{co|en|to '''accelerate''' our departure}} # {{lb|en|transitive|education}} To enable a [[student]] to finish a course of study in less than normal time. # {{lb|en|intransitive}} To become faster; to begin to move more quickly. #: {{ux|en|The car began to '''accelerate''' as soon as the light turned green.}} # {{lb|en|intransitive}} [[grow|Grow]]; [[increase]]. #: {{rfex|en}} ==== සමාන පද ==== * {{sense|to cause to move faster}} {{l|en|hasten}}, {{l|en|quicken}}, {{l|en|speed up}}; see also [[Thesaurus:speed up]] * {{sense|to quicken progress}} {{l|en|expedite}}, {{l|en|further}}, * {{sense|to hasten the occurrence of an event}} {{l|en|advance}}, {{l|en|forward}} ==== විරුද්ධ පද ==== * {{l|en|decelerate}} * {{l|en|retard}} * {{l|en|unaccelerate}} ==== ව්‍යුත්පන්න යෙදුම් ==== {{col|en|acceleratable|deaccelerate|outaccelerate|overaccelerate|reaccelerate|accelerated motion|accelerating force|accelerative|accelerator|post-accelerate|accelerated ageing|accelerated aging|accelerated critical illness|accelerated depreciation|accelerated erosion|accelerated graphics port|accelerated motion|accelerating universe|acceleratingly|nonaccelerating|unaccelerating}} ==== ආශ්‍රිත යෙදුම් ==== {{col3|en|accelerando|accelerant|acceleration|accelerograph|accelerometer}} === නාම විශේෂණ පදය === {{en-adj|-}} # {{lb|en|archaic}} [[accelerated|Accelerated]]; [[quickened]]; [[hastened]]; [[hurried]]. #* {{quote-text|en|year=1662|author=Thomas Salusbury|title=Galileo's Dialogue Concerning the Two Chief World Systems|section=Dialogue 2 |passage=''... a general knowledg of the definition of motion, and of the distinction of natural and violent, even and '''accelerate''', and the like, sufficing.''}} === මූලාශ්‍ර === <references/> * {{R:OED2}} {{cln|en|ergative verbs}} {{C|en|Acceleration|Mechanics}} == ඉතාලි == === නිරුක්තිය 1 === ==== නාම විශේෂණ පදය ==== {{head|it|adjective form|g=f-p}} # {{adj form of|it|accelerato||f|p}} ====Participle==== {{head|it|past participle form|g=f-p}} # {{feminine plural of|it|accelerato}} === නිරුක්තිය 2 === ==== ක්‍රියා පදය ==== {{head|it|verb form}} # {{inflection of|it|accelerare||2|p|pres|indc|;|2|p|impr}} == ලතින් == === ක්‍රියා පදය === {{head|la|verb form|head=accelerāte}} # {{inflection of|la|accelerō||2|p|pres|actv|impr}} andh35sz6eojaf4l2ehxg4y3nthq5x1 accelero 0 140219 239035 227283 2026-11-15T04:15:44Z Lee 19 ශුද්ධ පවිත්‍ර කිරීම 239035 wikitext text/x-wiki {{also|accelerò}} ==Catalan== === ක්‍රියා පදය === {{head|ca|verb form}} # {{ca-verb form of|accelerar}} == ඉතාලි == === ක්‍රියා පදය === {{head|it|verb form}} # {{inflection of|it|accelerare||1|s|pres|indc}} ===Anagrams=== * {{anagrams|it|a=acceelor|cocleare}} == ලතින් == === වෙනත් ආකාර === * {{l|la|adcelerō}} === නිරුක්තිය === From {{af|la|ad-<t:to, towards, at>|celerō<t:to quicken, accelerate>}}. === උච්චාරණය === * {{la-IPA|accelerō}} === ක්‍රියා පදය === {{la-verb|1+|accelerō}} # {{lb|la|transitive}} to [[quicken]], [[hasten]], [[speed up]], [[accelerate]] # {{lb|la|intransitive}} to be [[quick]], [[make haste]], hasten ====Conjugation==== {{la-conj|1+|accelerō}} ==== සමාන පද ==== * {{sense|hasten, accelerate}} {{l|la|approperō}}, {{l|la|celerō}} * {{sense|make haste}} {{l|la|celerō}} ==== ව්‍යුත්පන්න යෙදුම් ==== * {{l|la|accelerātiō}} * {{l|la|accelerātus}} ==== ආශ්‍රිත යෙදුම් ==== * {{l|la|praecelerō}} ====Descendants==== {{top2}} * {{desc|ca|accelerar}} * {{desc|en|accelerate|bor=1}} * {{desc|fr|accélérer}} * {{desc|gl|acelerar}} * {{desc|it|accelerare}} * {{desc|lmo|acelerà|accelerà}} * {{desc|pt|acelerar}} * {{desc|ro|accelera}} * {{desc|es|acelerar}} {{bottom}} === මූලාශ්‍ර === * {{R:la:L&S}} * {{R:la:Gaffiot}} * {{R:la:M&A}} hepy82s5ck0r2h01o002d021yf1q367 239036 239035 2026-11-15T04:16:07Z Lee 19 ශුද්ධ පවිත්‍ර කිරීම 239036 wikitext text/x-wiki {{also|accelerò}} ==Catalan== === ක්‍රියා පදය === {{head|ca|verb form}} # {{ca-verb form of|accelerar}} == ඉතාලි == === ක්‍රියා පදය === {{head|it|verb form}} # {{inflection of|it|accelerare||1|s|pres|indc}} == ලතින් == === වෙනත් ආකාර === * {{l|la|adcelerō}} === නිරුක්තිය === From {{af|la|ad-<t:to, towards, at>|celerō<t:to quicken, accelerate>}}. === උච්චාරණය === * {{la-IPA|accelerō}} === ක්‍රියා පදය === {{la-verb|1+|accelerō}} # {{lb|la|transitive}} to [[quicken]], [[hasten]], [[speed up]], [[accelerate]] # {{lb|la|intransitive}} to be [[quick]], [[make haste]], hasten ====Conjugation==== {{la-conj|1+|accelerō}} ==== සමාන පද ==== * {{sense|hasten, accelerate}} {{l|la|approperō}}, {{l|la|celerō}} * {{sense|make haste}} {{l|la|celerō}} ==== ව්‍යුත්පන්න යෙදුම් ==== * {{l|la|accelerātiō}} * {{l|la|accelerātus}} ==== ආශ්‍රිත යෙදුම් ==== * {{l|la|praecelerō}} ====Descendants==== {{top2}} * {{desc|ca|accelerar}} * {{desc|en|accelerate|bor=1}} * {{desc|fr|accélérer}} * {{desc|gl|acelerar}} * {{desc|it|accelerare}} * {{desc|lmo|acelerà|accelerà}} * {{desc|pt|acelerar}} * {{desc|ro|accelera}} * {{desc|es|acelerar}} {{bottom}} === මූලාශ්‍ර === * {{R:la:L&S}} * {{R:la:Gaffiot}} * {{R:la:M&A}} rpcl1x45rgk5gecw8qh4lpr06tmo8c8 Module:category tree/fam/zhx 828 140971 239011 233704 2026-07-26T06:06:29Z en>Benwing 0 Changed protection settings for "[[Module:category tree/fam/zhx]]": per existence of [[WT:CLTR]]; changes to these modules should go through a vetting process ([Edit=Allow only autopatrollers] (indefinite) [Move=Allow only autopatrollers] (indefinite)) 239011 Scribunto text/plain local labels = {} local handlers = {} labels["hanzi"] = { topright = "{{wp|Chinese characters}}", description = "{{{langname}}} symbols of the Han logographic script, which can represent sounds or convey meanings directly.", umbrella = "Han characters", parents = "logograms", } labels["chengyu"] = { topright = "{{wp|Chengyu}}", description = "{{{langname}}} traditional idiomatic expressions, usually consisting of four [[hanzi]]; typically derived from [[Classical Chinese]].", additional = "Compare Japanese {{w|yojijukugo}} and Korean {{w|sajaseong-eo}}.", parents = "idioms", } labels["terms with uncreated forms"] = { description = "{{{langname}}} terms that use a hanzi box template (such as {{temp|zh-forms}}) with a form not having a page of its own, or a {{temp|zh-see}} template linking to a page without a Chinese section or a nonexistent page", additional = "If the redlink in the hanzi box is a variant or simplified form, the page may be created with {{temp|subst:zh-new}}.", parents = {"redlinks", "entry maintenance"}, } for _, source in ipairs { "Mencius", "the Analects", "the Book of Documents", "the Book of Rites", "the Classic of Poetry", "the Han Feizi", "the I Ching", "the Zhuangzi", "the Zuo Zhuan", } do local book = source:match("^the (.*)$") local sort_key = book or source local italicized = book and "the ''" .. book .. "''" or source labels["terms derived from " .. source] = { displaytitle = book and "{{{langname}}} terms derived from " .. italicized or nil, parents = {{name = "terms attributed to a specific source", sort = sort_key}}, description = "{{{langname}}} terms derived from " .. italicized .. ".", breadcrumb = italicized, } labels["chengyu derived from " .. source] = { displaytitle = book and "{{{langname}}} chengyu derived from " .. italicized or nil, parents = {{name = "chengyu", sort = sort_key}, "terms derived from " .. source}, description = "{{{langname}}} [[chengyu]] derived from " .. italicized .. ".", breadcrumb = "derived from " .. italicized, } end return {LABELS = labels, HANDLERS = handlers} rm746jovo6y2tar6jekijha49gudmt4 239012 239011 2026-11-15T03:41:39Z Lee 19 [[:en:Module:category_tree/fam/zhx]] වෙතින් එක් සංශෝධනයක් 239011 Scribunto text/plain local labels = {} local handlers = {} labels["hanzi"] = { topright = "{{wp|Chinese characters}}", description = "{{{langname}}} symbols of the Han logographic script, which can represent sounds or convey meanings directly.", umbrella = "Han characters", parents = "logograms", } labels["chengyu"] = { topright = "{{wp|Chengyu}}", description = "{{{langname}}} traditional idiomatic expressions, usually consisting of four [[hanzi]]; typically derived from [[Classical Chinese]].", additional = "Compare Japanese {{w|yojijukugo}} and Korean {{w|sajaseong-eo}}.", parents = "idioms", } labels["terms with uncreated forms"] = { description = "{{{langname}}} terms that use a hanzi box template (such as {{temp|zh-forms}}) with a form not having a page of its own, or a {{temp|zh-see}} template linking to a page without a Chinese section or a nonexistent page", additional = "If the redlink in the hanzi box is a variant or simplified form, the page may be created with {{temp|subst:zh-new}}.", parents = {"redlinks", "entry maintenance"}, } for _, source in ipairs { "Mencius", "the Analects", "the Book of Documents", "the Book of Rites", "the Classic of Poetry", "the Han Feizi", "the I Ching", "the Zhuangzi", "the Zuo Zhuan", } do local book = source:match("^the (.*)$") local sort_key = book or source local italicized = book and "the ''" .. book .. "''" or source labels["terms derived from " .. source] = { displaytitle = book and "{{{langname}}} terms derived from " .. italicized or nil, parents = {{name = "terms attributed to a specific source", sort = sort_key}}, description = "{{{langname}}} terms derived from " .. italicized .. ".", breadcrumb = italicized, } labels["chengyu derived from " .. source] = { displaytitle = book and "{{{langname}}} chengyu derived from " .. italicized or nil, parents = {{name = "chengyu", sort = sort_key}, "terms derived from " .. source}, description = "{{{langname}}} [[chengyu]] derived from " .. italicized .. ".", breadcrumb = "derived from " .. italicized, } end return {LABELS = labels, HANDLERS = handlers} rm746jovo6y2tar6jekijha49gudmt4 239013 239012 2026-11-15T03:42:15Z Lee 19 පැරණි සංස්කරණයකින් ගත් කොටස්... 239013 Scribunto text/plain local labels = {} local handlers = {} labels["hanzi"] = { topright = "{{wp|Chinese characters}}", description = "{{{langname}}} symbols of the Han logographic script, which can represent sounds or convey meanings directly.", umbrella = "Han characters", parents = "logograms", } labels["chengyu"] = { topright = "{{wp|Chengyu}}", description = "{{{langname}}} traditional idiomatic expressions, usually consisting of four [[hanzi]]; typically derived from [[Classical Chinese]].", additional = "Compare Japanese {{w|yojijukugo}} and Korean {{w|sajaseong-eo}}.", parents = "idioms", } labels["terms with uncreated forms"] = { description = "{{{langname}}} terms that use a hanzi box template (such as {{temp|zh-forms}}) with a form not having a page of its own, or a {{temp|zh-see}} template linking to a page without a Chinese section or a nonexistent page", additional = "If the redlink in the hanzi box is a variant or simplified form, the page may be created with {{temp|subst:zh-new}}.", parents = {"රතු සබැඳි", "ප්‍රවේශ නඩත්තුව"}, } for _, source in ipairs { "Mencius", "the Analects", "the Book of Documents", "the Book of Rites", "the Classic of Poetry", "the Han Feizi", "the I Ching", "the Zhuangzi", "the Zuo Zhuan", } do local book = source:match("^the (.*)$") local sort_key = book or source local italicized = book and "the ''" .. book .. "''" or source labels["terms derived from " .. source] = { displaytitle = book and "{{{langname}}} terms derived from " .. italicized or nil, parents = {{name = "terms attributed to a specific source", sort = sort_key}}, description = "{{{langname}}} terms derived from " .. italicized .. ".", breadcrumb = italicized, } labels["chengyu derived from " .. source] = { displaytitle = book and "{{{langname}}} chengyu derived from " .. italicized or nil, parents = {{name = "chengyu", sort = sort_key}, "terms derived from " .. source}, description = "{{{langname}}} [[chengyu]] derived from " .. italicized .. ".", breadcrumb = "derived from " .. italicized, } end return {LABELS = labels, HANDLERS = handlers} 69158piccvryx7wi223dj9kbp7drih6 239014 239013 2026-11-15T03:43:44Z Lee 19 "hanzi" සිට "හන්සු" වෙතට 239014 Scribunto text/plain local labels = {} local handlers = {} labels["හන්සු"] = { topright = "{{wp|Chinese characters}}", description = "{{{langname}}} symbols of the Han logographic script, which can represent sounds or convey meanings directly.", umbrella = "Han characters", parents = "logograms", } labels["chengyu"] = { topright = "{{wp|Chengyu}}", description = "{{{langname}}} traditional idiomatic expressions, usually consisting of four [[hanzi]]; typically derived from [[Classical Chinese]].", additional = "Compare Japanese {{w|yojijukugo}} and Korean {{w|sajaseong-eo}}.", parents = "idioms", } labels["terms with uncreated forms"] = { description = "{{{langname}}} terms that use a hanzi box template (such as {{temp|zh-forms}}) with a form not having a page of its own, or a {{temp|zh-see}} template linking to a page without a Chinese section or a nonexistent page", additional = "If the redlink in the hanzi box is a variant or simplified form, the page may be created with {{temp|subst:zh-new}}.", parents = {"රතු සබැඳි", "ප්‍රවේශ නඩත්තුව"}, } for _, source in ipairs { "Mencius", "the Analects", "the Book of Documents", "the Book of Rites", "the Classic of Poetry", "the Han Feizi", "the I Ching", "the Zhuangzi", "the Zuo Zhuan", } do local book = source:match("^the (.*)$") local sort_key = book or source local italicized = book and "the ''" .. book .. "''" or source labels["terms derived from " .. source] = { displaytitle = book and "{{{langname}}} terms derived from " .. italicized or nil, parents = {{name = "terms attributed to a specific source", sort = sort_key}}, description = "{{{langname}}} terms derived from " .. italicized .. ".", breadcrumb = italicized, } labels["chengyu derived from " .. source] = { displaytitle = book and "{{{langname}}} chengyu derived from " .. italicized or nil, parents = {{name = "chengyu", sort = sort_key}, "terms derived from " .. source}, description = "{{{langname}}} [[chengyu]] derived from " .. italicized .. ".", breadcrumb = "derived from " .. italicized, } end return {LABELS = labels, HANDLERS = handlers} 8kqzignl0fxhevgm8591rv9up883t9w 239015 239014 2026-11-15T03:44:15Z Lee 19 "logograms" සිට "ලෝගෝග්‍රෑම" වෙතට 239015 Scribunto text/plain local labels = {} local handlers = {} labels["හන්සු"] = { topright = "{{wp|Chinese characters}}", description = "{{{langname}}} symbols of the Han logographic script, which can represent sounds or convey meanings directly.", umbrella = "Han characters", parents = "ලෝගෝග්‍රෑම", } labels["chengyu"] = { topright = "{{wp|Chengyu}}", description = "{{{langname}}} traditional idiomatic expressions, usually consisting of four [[hanzi]]; typically derived from [[Classical Chinese]].", additional = "Compare Japanese {{w|yojijukugo}} and Korean {{w|sajaseong-eo}}.", parents = "idioms", } labels["terms with uncreated forms"] = { description = "{{{langname}}} terms that use a hanzi box template (such as {{temp|zh-forms}}) with a form not having a page of its own, or a {{temp|zh-see}} template linking to a page without a Chinese section or a nonexistent page", additional = "If the redlink in the hanzi box is a variant or simplified form, the page may be created with {{temp|subst:zh-new}}.", parents = {"රතු සබැඳි", "ප්‍රවේශ නඩත්තුව"}, } for _, source in ipairs { "Mencius", "the Analects", "the Book of Documents", "the Book of Rites", "the Classic of Poetry", "the Han Feizi", "the I Ching", "the Zhuangzi", "the Zuo Zhuan", } do local book = source:match("^the (.*)$") local sort_key = book or source local italicized = book and "the ''" .. book .. "''" or source labels["terms derived from " .. source] = { displaytitle = book and "{{{langname}}} terms derived from " .. italicized or nil, parents = {{name = "terms attributed to a specific source", sort = sort_key}}, description = "{{{langname}}} terms derived from " .. italicized .. ".", breadcrumb = italicized, } labels["chengyu derived from " .. source] = { displaytitle = book and "{{{langname}}} chengyu derived from " .. italicized or nil, parents = {{name = "chengyu", sort = sort_key}, "terms derived from " .. source}, description = "{{{langname}}} [[chengyu]] derived from " .. italicized .. ".", breadcrumb = "derived from " .. italicized, } end return {LABELS = labels, HANDLERS = handlers} chgihk3p3gmem1dtpt31n94cm8w905q 239016 239015 2026-11-15T03:46:53Z Lee 19 "Han characters" සිට "හන් අනුලක්ෂණ" වෙතට 239016 Scribunto text/plain local labels = {} local handlers = {} labels["හන්සු"] = { topright = "{{wp|Chinese characters}}", description = "{{{langname}}} symbols of the Han logographic script, which can represent sounds or convey meanings directly.", umbrella = "හන් අනුලක්ෂණ", parents = "ලෝගෝග්‍රෑම", } labels["chengyu"] = { topright = "{{wp|Chengyu}}", description = "{{{langname}}} traditional idiomatic expressions, usually consisting of four [[hanzi]]; typically derived from [[Classical Chinese]].", additional = "Compare Japanese {{w|yojijukugo}} and Korean {{w|sajaseong-eo}}.", parents = "idioms", } labels["terms with uncreated forms"] = { description = "{{{langname}}} terms that use a hanzi box template (such as {{temp|zh-forms}}) with a form not having a page of its own, or a {{temp|zh-see}} template linking to a page without a Chinese section or a nonexistent page", additional = "If the redlink in the hanzi box is a variant or simplified form, the page may be created with {{temp|subst:zh-new}}.", parents = {"රතු සබැඳි", "ප්‍රවේශ නඩත්තුව"}, } for _, source in ipairs { "Mencius", "the Analects", "the Book of Documents", "the Book of Rites", "the Classic of Poetry", "the Han Feizi", "the I Ching", "the Zhuangzi", "the Zuo Zhuan", } do local book = source:match("^the (.*)$") local sort_key = book or source local italicized = book and "the ''" .. book .. "''" or source labels["terms derived from " .. source] = { displaytitle = book and "{{{langname}}} terms derived from " .. italicized or nil, parents = {{name = "terms attributed to a specific source", sort = sort_key}}, description = "{{{langname}}} terms derived from " .. italicized .. ".", breadcrumb = italicized, } labels["chengyu derived from " .. source] = { displaytitle = book and "{{{langname}}} chengyu derived from " .. italicized or nil, parents = {{name = "chengyu", sort = sort_key}, "terms derived from " .. source}, description = "{{{langname}}} [[chengyu]] derived from " .. italicized .. ".", breadcrumb = "derived from " .. italicized, } end return {LABELS = labels, HANDLERS = handlers} aqlwdbtmzqxvrnfzoegfw1fwbeaaavc ප්‍රවර්ගය:Belarusian terms with non-redundant manual transliterations 14 145818 238997 2026-11-15T03:21:27Z Lee 19 Lee විසින් [[ප්‍රවර්ගය:Belarusian terms with non-redundant manual transliterations]] සිට [[ප්‍රවර්ගය:බෙලරුසියානු terms with non-redundant manual transliterations]] වෙත පිටුව ගෙන යන ලදී 238997 wikitext text/x-wiki #යළියොමුව [[:ප්‍රවර්ගය:බෙලරුසියානු terms with non-redundant manual transliterations]] blqjhwrdo1btuwf9pjmyjbsovkwj9b3 239038 238997 2026-11-15T04:19:30Z Pinthura 2424 රොබෝ: යළියොමුව, මෘදු ප්‍රවර්ග යළියොමුවක් බවට හැරවීම 239038 wikitext text/x-wiki {{category redirect|බෙලරුසියානු terms with non-redundant manual transliterations}} 3lj0uxzxsboizo840nuswpe7j30mar3 ප්‍රවර්ග සාකච්ඡාව:Belarusian terms with non-redundant manual transliterations 15 145819 238999 2026-11-15T03:21:27Z Lee 19 Lee විසින් [[ප්‍රවර්ග සාකච්ඡාව:Belarusian terms with non-redundant manual transliterations]] සිට [[ප්‍රවර්ග සාකච්ඡාව:බෙලරුසියානු terms with non-redundant manual transliterations]] වෙත පිටුව ගෙන යන ලදී 238999 wikitext text/x-wiki #යළියොමුව [[ප්‍රවර්ග සාකච්ඡාව:බෙලරුසියානු terms with non-redundant manual transliterations]] avmuh2clvclk9kko1lv3j7hvth9wmu5 ප්‍රවර්ගය:Demotic මොඩියුල 14 145820 239001 2026-11-15T03:22:52Z Lee 19 Lee විසින් [[ප්‍රවර්ගය:Demotic මොඩියුල]] සිට [[ප්‍රවර්ගය:Demotic Egyptian මොඩියුල]] වෙත පිටුව ගෙන යන ලදී 239001 wikitext text/x-wiki #යළියොමුව [[:ප්‍රවර්ගය:Demotic Egyptian මොඩියුල]] 2rnl6fdn8yaeocc744x0ytf18uelm9r 239039 239001 2026-11-15T04:19:40Z Pinthura 2424 රොබෝ: යළියොමුව, මෘදු ප්‍රවර්ග යළියොමුවක් බවට හැරවීම 239039 wikitext text/x-wiki {{category redirect|Demotic Egyptian මොඩියුල}} tsjafrj5vw1kr1iiaflbq2t1fgk1d2l ප්‍රවර්ග සාකච්ඡාව:Demotic මොඩියුල 15 145821 239003 2026-11-15T03:22:53Z Lee 19 Lee විසින් [[ප්‍රවර්ග සාකච්ඡාව:Demotic මොඩියුල]] සිට [[ප්‍රවර්ග සාකච්ඡාව:Demotic Egyptian මොඩියුල]] වෙත පිටුව ගෙන යන ලදී 239003 wikitext text/x-wiki #යළියොමුව [[ප්‍රවර්ග සාකච්ඡාව:Demotic Egyptian මොඩියුල]] apqfqk68vykdps70247rrbe7duciz8s ප්‍රවර්ගය:Demotic සැකිලි 14 145822 239005 2026-11-15T03:23:24Z Lee 19 Lee විසින් [[ප්‍රවර්ගය:Demotic සැකිලි]] සිට [[ප්‍රවර්ගය:Demotic Egyptian සැකිලි]] වෙත පිටුව ගෙන යන ලදී 239005 wikitext text/x-wiki #යළියොමුව [[:ප්‍රවර්ගය:Demotic Egyptian සැකිලි]] sdenefywdq6a1p1i7ev7w9a774rbdc8 239040 239005 2026-11-15T04:19:50Z Pinthura 2424 රොබෝ: යළියොමුව, මෘදු ප්‍රවර්ග යළියොමුවක් බවට හැරවීම 239040 wikitext text/x-wiki {{category redirect|Demotic Egyptian සැකිලි}} 4ltxku1j53csieoass4odbi3o4jstau ප්‍රවර්ග සාකච්ඡාව:Demotic සැකිලි 15 145823 239007 2026-11-15T03:23:24Z Lee 19 Lee විසින් [[ප්‍රවර්ග සාකච්ඡාව:Demotic සැකිලි]] සිට [[ප්‍රවර්ග සාකච්ඡාව:Demotic Egyptian සැකිලි]] වෙත පිටුව ගෙන යන ලදී 239007 wikitext text/x-wiki #යළියොමුව [[ප්‍රවර්ග සාකච්ඡාව:Demotic Egyptian සැකිලි]] 58tqednzi6lilf60k5g2qr4i7mk1sm5