Modul:lt-common
Penampilan
- Laman modul ini kekurangan sublaman pendokumenan. Minta tolong ciptakan laman pendokumenan tersebut.
- Pautan berguna: senarai sublaman • pautan • transklusi • kes ujian • kotak pasir
local export = {}
local m_str_utils = require("Module:string utilities")
local put = require("Module:parse utilities")
local u = m_str_utils.char
local ugsub = m_str_utils.gsub
local ulower = m_str_utils.lower
local uupper = m_str_utils.upper
local ufind = m_str_utils.find
local ulen = m_str_utils.len
local ucodepoint = m_str_utils.codepoint
-- Keep native Unicode normalization functions (no replacement available)
local toNFC = mw.ustring.toNFC
local toNFD = mw.ustring.toNFD
-- =============================================================================
-- Unicode constants
-- =============================================================================
local GRAVE = u(0x0300) -- combining grave accent
local ACUTE = u(0x0301) -- combining acute accent
local TILDE = u(0x0303) -- combining tilde
local MACRON = u(0x0304) -- combining macron
local DOTABOVE = u(0x0307) -- combining dot above
local CARON = u(0x030C) -- combining caron
local OGONEK = u(0x0328) -- combining ogonek
local ANY_ACCENT = "[" .. GRAVE .. ACUTE .. TILDE .. "]"
-- Legacy aliases for backward compatibility
local grave = GRAVE
local acute = ACUTE
local tilde = TILDE
local macron = MACRON
local dotabove = DOTABOVE
local caron = CARON
local ogonek = OGONEK
local accents = ANY_ACCENT
-- Export accent constants for use by other Lithuanian modules
-- (lt-pron, lt-verb, lt-noun, etc.) to avoid duplicating these values.
export.GRAVE = GRAVE
export.ACUTE = ACUTE
export.TILDE = TILDE
export.MACRON = MACRON
export.DOTABOVE = DOTABOVE
export.CARON = CARON
export.OGONEK = OGONEK
export.ANY_ACCENT = ANY_ACCENT
-- =============================================================================
-- Private Use Area (PUA) replacement hints
-- =============================================================================
-- Maps PUA codepoints (U+E000–U+E022) to their suggested standard Unicode
-- replacements. Used by reject_pua to give actionable error messages when
-- editors paste in pre-composed glyphs from old Lithuanian-specific encodings.
local INVALID_CHARS = {
[0xE000] = "Ą́", [0xE001] = "ą́", [0xE002] = "Ą̃", [0xE003] = "ą̃",
[0xE004] = "Ę́", [0xE005] = "ę́", [0xE006] = "Ę̃", [0xE007] = "ę̃",
[0xE008] = "Ė́", [0xE009] = "ė́", [0xE00A] = "Ė̃", [0xE00B] = "ė̃",
[0xE00C] = "i̇̀", [0xE00D] = "i̇́", [0xE00E] = "i̇̃",
[0xE00F] = "Į̇́", [0xE010] = "į̇́", [0xE011] = "Į̇̃", [0xE012] = "į̇̃",
[0xE013] = "J̃", [0xE014] = "j̇̃",
[0xE015] = "L̃", [0xE016] = "l̃",
[0xE017] = "M̃", [0xE018] = "m̃",
[0xE019] = "R̃", [0xE01A] = "r̃",
[0xE01B] = "Ų́", [0xE01C] = "ų́", [0xE01D] = "Ų̃", [0xE01E] = "ų̃",
[0xE01F] = "Ū́", [0xE020] = "ū́", [0xE021] = "Ū̃", [0xE022] = "ū̃",
}
export.INVALID_CHARS = INVALID_CHARS
-- =============================================================================
-- Internal helper functions
-- =============================================================================
local dotless_to_dotted = {
["ı"] = "i",
["ȷ"] = "j",
}
local function char_to_dotted_form(base, below)
return (dotless_to_dotted[base] or base) .. below
end
local function normalize_dotted_chars(text)
-- Remove any dots above, and convert dotless forms to dotted.
-- On entry, text must be in NFD form.
return ugsub(text, "([iıjȷ])(" .. ogonek .. "?)" .. dotabove, char_to_dotted_form)
end
local function char_to_accent_form(base, below)
-- Add a 'dot above' after the base.
if base == "i" or base == "j" then
return base .. below .. dotabove
end
-- Convert any dotless chars combining with accents to the dotted form,
-- so that they normalize properly. This shouldn't happen, but just in case.
return char_to_dotted_form(base, below)
end
local function stripped_text_form(text)
-- Remove accents.
text = ugsub(toNFD(text), accents .. "+", "")
-- Normalize dotless characters and dot-above diacritics.
return normalize_dotted_chars(text)
end
-- =============================================================================
-- Input validation
-- =============================================================================
-- Reject Private Use Area characters (U+E000–U+F8FF). When the character is
-- a known non-standard Lithuanian glyph, the error message includes the
-- recommended standard Unicode replacement (see INVALID_CHARS above).
function export.reject_pua(s)
if not s then return end
for i = 1, ulen(s) do
local cp = ucodepoint(s, i)
if cp >= 0xE000 and cp <= 0xF8FF then
local replacement = INVALID_CHARS[cp]
if replacement then
error(string.format(
"lt-common: private use area character U+%04X \"%s\" detected. " ..
"Please use \"%s\" instead.", cp, u(cp), replacement))
else
error(string.format(
"lt-common: private use area character U+%04X detected in \"%s\". " ..
"Please use a standard Unicode character instead.", cp, s))
end
end
end
end
-- =============================================================================
-- Input normalization
-- =============================================================================
-- Detect nonstandard encoding patterns in the input.
-- Returns: dotless_flag (found ı/ȷ), precomp_i_flag (found precomposed í/ì/ĩ)
function export.detect_nonstandard(s)
if not s then return false, false end
local nfd_s = toNFD(s)
local dotless_flag = ufind(nfd_s, "[ıȷ]") ~= nil
local precomp_i_flag = ufind(nfd_s, "[íìĩ]") ~= nil
return dotless_flag, precomp_i_flag
end
-- Normalize input to clean canonical NFC.
-- Handles dotless i/j (ı, ȷ) and stray dot-above combinations.
function export.canonicalize_input(s)
if not s then return s end
s = toNFD(s)
-- Remove stray dot-above after i/j (with or without ogonek)
s = ugsub(s, "([iıjȷ])(" .. OGONEK .. "?)" .. DOTABOVE, function(base, below)
base = (base == "ı") and "i" or (base == "ȷ") and "j" or base
return base .. below
end)
-- Convert any remaining dotless i/j to standard forms
s = ugsub(s, "ı", "i")
s = ugsub(s, "ȷ", "j")
return toNFC(s)
end
-- =============================================================================
-- Partial NFD conversion (stem_ac representation)
-- =============================================================================
-- Convert canonical NFC to partial NFD (stem_ac).
-- Applies full NFD, then recomposes non-accent diacritics.
-- Only grave/acute/tilde remain as combining characters.
function export.to_stem_ac(s)
if not s then return s end
s = toNFD(s)
-- Recompose ogonek vowels
s = ugsub(s, "a" .. OGONEK, "ą")
s = ugsub(s, "e" .. OGONEK, "ę")
s = ugsub(s, "i" .. OGONEK, "į")
s = ugsub(s, "u" .. OGONEK, "ų")
-- Recompose macron vowel
s = ugsub(s, "u" .. MACRON, "ū")
-- Recompose dot-above e
s = ugsub(s, "e" .. DOTABOVE, "ė")
-- Recompose caron consonants
s = ugsub(s, "c" .. CARON, "č")
s = ugsub(s, "s" .. CARON, "š")
s = ugsub(s, "z" .. CARON, "ž")
return s
end
-- =============================================================================
-- Accent manipulation
-- =============================================================================
-- Strip all accent marks (grave/acute/tilde) from partial NFD text.
function export.to_stem_bare(stem_ac)
if not stem_ac then return stem_ac end
return ugsub(stem_ac, ANY_ACCENT, "")
end
-- Check if partial NFD text contains any accent marks.
function export.has_accent(stem_ac)
return ufind(stem_ac, ANY_ACCENT) ~= nil
end
-- =============================================================================
-- Complete input pipeline
-- =============================================================================
-- Process raw user input through the complete normalization pipeline.
-- Returns: stem_bare, stem_ac, dotless_flag, precomp_flag
function export.process_input(raw)
if not raw then return raw, raw, false, false end
export.reject_pua(raw)
local dotless_flag, precomp_flag = export.detect_nonstandard(raw)
local canon = export.canonicalize_input(raw)
local stem_ac = export.to_stem_ac(canon)
local stem_bare = export.to_stem_bare(stem_ac)
return stem_bare, stem_ac, dotless_flag, precomp_flag
end
-- =============================================================================
-- Display and text processing
-- =============================================================================
function export.makeDisplayText(text, lang, sc)
if not text then return text end
-- Normalize dotless characters and dot-above diacritics (while retaining accents).
text = normalize_dotted_chars(toNFD(text))
-- Add a 'dot above' between "i" or "j" and an accent.
text = ugsub(text, "([iıjȷ])(" .. ogonek .. "?)%f" .. accents, char_to_accent_form)
return toNFC(text)
end
-- Called from [[Module:languages]] since [[Module:lt-common]] is set as the stripDiacritics handler in
-- [[Module:languages/data/2]].
function export.stripDiacritics(text, lang, sc)
if not text then return text end
return toNFC(stripped_text_form(text))
end
local sortkey_substitutes = {
[ogonek] = u(0xF000),
[caron] = u(0xF001),
[macron] = u(0xF002),
[dotabove] = u(0xF003),
["y"] = "i" .. u(0xF004),
}
function export.makeSortKey(text, lang, sc)
if not text then return text end
-- Normalize to the stripped-text form and convert diacritics to Private Use
-- Area characters so they sort after all other characters.
text = stripped_text_form(ulower(text))
:gsub(".[\128-\191]*", sortkey_substitutes)
return toNFC(uupper(text))
end
-- =============================================================================
-- Footnote / multi-value spec parsing
-- =============================================================================
--
-- Shared by lt-noun (and eventually lt-verb/lt-adjective) to parse a single
-- "field" of a declension pattern (lemma, AP, genitive, a slot-override
-- value) that may hold multiple colon-separated variants, each optionally
-- followed by one or more bracketed footnotes: `VAL1[note1]:VAL2[note2]`.
--
-- Ported from [[Module:de-common]]'s fetch_specs/fetch_footnotes, which is
-- the mechanism [[Module:de-noun]] uses for exactly this purpose. The caller
-- is responsible for first isolating `[...]` runs from the raw field text
-- with `put.parse_balanced_segment_run(text, "[", "]")` (so that a "." or
-- ":" inside a footnote is never mistaken for a delimiter) before any
-- comma/dot/colon splitting; `fetch_specs` operates on the result of that
-- isolation (optionally after a further split, since split_alternating_runs
-- preserves the same alternating-runs shape).
-- Given one delimiter-separated "run" (a list alternating between plain text
-- and "[...]" bracket runs, as produced by parse_balanced_segment_run /
-- split_alternating_runs), return the list of bracketed footnote strings
-- (each including its own brackets, e.g. "[archaic]"), or nil if there are
-- none. Errors if non-bracket text follows a footnote (e.g. "val[note]x").
function export.fetch_footnotes(separated_group, parse_err)
local footnotes
for j = 2, #separated_group - 1, 2 do
if separated_group[j + 1] ~= "" then
parse_err("Extraneous text after bracketed footnotes: '" .. table.concat(separated_group) .. "'")
end
if not footnotes then
footnotes = {}
end
table.insert(footnotes, separated_group[j])
end
return footnotes
end
-- Given a bracket-isolated run and a sub-delimiter (e.g. ":"), split it into
-- one or more {form=VALUE, footnotes={...}} specs. `spectype` is used only
-- in error messages. If `allow_blank` is given, a wholly-blank run (no forms
-- at all) returns nil instead of erroring, for optional fields like the
-- genitive parameter.
function export.fetch_specs(segments, separator, spectype, allow_blank, parse_err)
local separated_groups = put.split_alternating_runs_and_strip_spaces(segments, separator)
if allow_blank and #separated_groups == 1 and #separated_groups[1] == 1 and
separated_groups[1][1] == "" then
return nil
end
local specs = {}
for _, separated_group in ipairs(separated_groups) do
local form = separated_group[1]
if form == "" then
parse_err("Blank form not allowed here, but saw '" .. table.concat(segments) .. "'")
end
local new_spec = {form = form, footnotes = export.fetch_footnotes(separated_group, parse_err)}
for _, existing_spec in ipairs(specs) do
if existing_spec.form == new_spec.form then
parse_err("Duplicate " .. spectype .. " spec '" .. table.concat(separated_group) .. "'")
end
end
table.insert(specs, new_spec)
end
return specs
end
-- =============================================================================
-- Headword scraping
-- =============================================================================
-- Lazy-load Module:template parser (only needed when scraping is triggered).
local function find_templates(...)
find_templates = require("Module:template parser").find_templates
return find_templates(...)
end
-- Scan the wikitext of `pagename` for calls to `{{infltemp}}` (e.g. "lt-ndecl")
-- and return the inflection spec (first positional argument) of the matching call.
-- `infltemp` is one template name or a list of interchangeable names (e.g.
-- {"lt-conj", "lt-conj+"} while the new conjugation template sits on a
-- temporary "+" name); calls to any of them are treated as the same template.
-- If `inflid` is given, match only the call whose id= equals `inflid`.
-- Returns (infl_string, nil) on success, (nil, error_string) on failure.
function export.find_lt_inflection(pagename, infltemp, inflid)
local wanted_names = {}
if type(infltemp) == "table" then
for _, name in ipairs(infltemp) do wanted_names[name] = true end
infltemp = table.concat(infltemp, "}}/{{") -- display name for messages
else
wanted_names[infltemp] = true
end
local title = mw.title.new(pagename)
if not title then
return nil, ("Bad pagename '%s': couldn't create title object"):format(pagename)
end
local content = title:getContent()
if not content then
return nil, ("Couldn't fetch page content for '[[%s]]'; page may not exist"):format(pagename)
end
local sets_by_id = {} -- id string → infl string
local sets_no_id = {} -- list of infl strings (templates without id=)
for template in find_templates(content) do
if wanted_names[template:get_name()] then
local targs = template:get_arguments()
local infl = targs[1]
if not infl or infl == "" then
return nil, ("Found {{%s}} on '[[%s]]' but it has no inflection spec in 1="):
format(infltemp, pagename)
end
if targs.id then
if sets_by_id[targs.id] then
return nil, ("Found duplicate id='%s' for {{%s}} on '[[%s]]'"):
format(targs.id, infltemp, pagename)
end
sets_by_id[targs.id] = infl
else
table.insert(sets_no_id, infl)
end
end
end
local has_id = next(sets_by_id) ~= nil
local has_no_id = #sets_no_id > 0
-- Nothing found at all.
if not has_id and not has_no_id then
return nil, ("No {{%s}} found on '[[%s]]'"):format(infltemp, pagename)
end
-- Inconsistent: some calls have id= and some don't.
if has_id and has_no_id then
return nil, ("On '[[%s]]', some {{%s}} calls have id= and some don't; " ..
"all must be consistent"):format(pagename, infltemp)
end
-- Multiple calls, all without id=: caller must add id= params.
if not has_id and #sets_no_id > 1 then
return nil, ("On '[[%s]]', found %d {{%s}} calls without id=; " ..
"add id= to each and specify id= in {{lt-noun}} to disambiguate"):
format(pagename, #sets_no_id, infltemp)
end
-- From here, either exactly one no-id call, or all calls have id=.
-- Caller specified an id: find the matching call.
if inflid then
if not has_id then
-- Only one no-id call exists; id= mismatch is suspicious but unambiguous — return it.
return sets_no_id[1], nil
end
local match = sets_by_id[inflid]
if match then
return match, nil
end
local available = {}
for k in pairs(sets_by_id) do table.insert(available, "'" .. k .. "'") end
table.sort(available)
return nil, ("On '[[%s]]', no {{%s}} with id='%s' found; available: %s"):
format(pagename, infltemp, inflid, table.concat(available, ", "))
end
-- No id specified by caller.
if not has_id then
-- Exactly one no-id call (multiple case already caught above).
return sets_no_id[1], nil
end
-- All calls have id= but caller didn't specify one.
local keys = {}
for k in pairs(sets_by_id) do table.insert(keys, k) end
table.sort(keys)
if #keys == 1 then
-- Unambiguous single id= call: return it.
return sets_by_id[keys[1]], nil
end
local quoted = {}
for _, k in ipairs(keys) do table.insert(quoted, "'" .. k .. "'") end
return nil, ("On '[[%s]]', found multiple {{%s}} calls with id= (%s); " ..
"specify id= in {{lt-noun}} to disambiguate"):
format(pagename, infltemp, table.concat(quoted, ", "))
end
return export