Pergi ke kandungan

Modul:etymon/text

Daripada Wikikamus


local export = {}

local loader = require("Module:module loader")

local M = loader.init({
	require = {
		en_utilities = "Module:en-utilities",
		references = "Module:references",
		senseno = "Module:senseno",
	},
	loadData = {
		data = "Module:etymon/data",
	},
})

function export.render(opts)
	opts = opts or {}
	local data_tree = opts.data_tree
	local format_term_func = opts.format_term_func
	local max_depth = opts.max_depth
	local stop_at_blue_link = opts.stop_at_blue_link
	local curr_page = opts.curr_page
	local nodot = opts.nodot and opts.nodot ~= "" and opts.nodot ~= "0"

	local function explicit_dot_override()
		if opts.dot == nil or opts.dot == false then
			return nil
		end
		local d = mw.text.trim(tostring(opts.dot))
		if d == "" or d == "." then
			return nil
		end
		return d
	end

	local dot_override = explicit_dot_override()

	local function find_deepest_last_part(tree)
		if not tree or not tree.container_parts or #tree.container_parts == 0 then
			return nil
		end
		local last_part = tree.container_parts[#tree.container_parts]
		if last_part.continuation then
			return find_deepest_last_part(last_part.continuation)
		end
		return last_part
	end

	local function apply_final_punctuation_override(tree, punct)
		if not tree or punct == nil then
			return
		end
		local last_part = find_deepest_last_part(tree)
		if last_part then
			last_part.punctuation = punct
		end
	end

	local function apply_closing_punctuation_override(tree, is_last_segment)
		if not is_last_segment then
			return
		end
		local punct
		if nodot then
			punct = ""
		elseif dot_override ~= nil then
			punct = dot_override
		else
			return
		end
		apply_final_punctuation_override(tree, punct)
	end

	local function has_supplements()
		return data_tree.supplements and #data_tree.supplements > 0
	end

	local stop_at_lang = opts.stop_at_lang
	local stop_at_lang_or_bluelink = opts.stop_at_lang_or_bluelink
	local lang_matches_stop_code = opts.lang_matches_stop_code

	local stop_lang_reached = false

	local function term_matches_stop_code(term_lang, stop_code)
		if lang_matches_stop_code then
			return lang_matches_stop_code(term_lang, stop_code)
		end
		return term_lang and term_lang:getCode() == stop_code
	end

	local children = data_tree.children

	local function has_text_supplements()
		if not data_tree.supplements then
			return false
		end
		for _, supplement in ipairs(data_tree.supplements) do
			if supplement.type == "doublet" and supplement.terms and #supplement.terms > 0 then
				return true
			end
			if supplement.type == "etydate" and supplement.etydate_text and supplement.etydate_text ~= "" then
				return true
			end
		end
		return false
	end

	if (not children or #children == 0) and not has_text_supplements() then
		if stop_at_lang then
			return "", { stop_lang_reached = false }
		end
		return ""
	end

	local entry_lang = data_tree.lang

	local function lowercase_glossary_link_display(wikitext)
		return wikitext:gsub("(%[%[Lampiran:Glosari#[^|]+|)([^%]])([^%]]*)%]%]", function(prefix, first, rest)
			return prefix .. mw.ustring.lower(first) .. rest .. "]]"
		end)
	end

	local function format_sl_senseid_intro(senseid, keyword_text, keyword_phrase, capitalize_senseno, is_uncertain)
		local senseids = mw.text.split(senseid, "!!", true)
		local senseno_parts = {}
		for i, id in ipairs(senseids) do
			id = mw.text.trim(id)
			if id ~= "" then
				table.insert(senseno_parts, M.senseno.link_text(entry_lang:getCode(), { id }, {
					title = curr_page,
					uc = (i == 1 and capitalize_senseno) or nil,
				}))
			end
		end
		if #senseno_parts == 0 then
			return keyword_text, keyword_phrase
		end

		local senseno_text = mw.text.listToText(senseno_parts)
		local glossary_link = (keyword_text or ""):gsub(" from$", "")
		local glossary_lower = lowercase_glossary_link_display(glossary_link)

		if #senseno_parts > 1 then
			local plural_link = glossary_lower:gsub("|semantic loan%]%]", "|semantic loans]]")
			if is_uncertain then
				return senseno_text .. " are possibly " .. plural_link .. " from",
					senseno_text .. " are possibly semantic loans from"
			end
			return senseno_text .. " are " .. plural_link .. " from",
				senseno_text .. " are semantic loans from"
		end

		if is_uncertain then
			return senseno_text .. " is possibly a " .. glossary_lower .. " from",
				senseno_text .. " is possibly a semantic loan from"
		end
		return senseno_text .. " is a " .. glossary_lower .. " from",
			senseno_text .. " is a semantic loan from"
	end

	local function get_term_refs(term, defined_here)
		if defined_here and term.refs and next(term.refs) then
			return M.references.format_references(term.refs)
		end
		return ""
	end

	-- Build a text part for a single term
	local function build_term_part(term, current_lang, defined_here)
		local text = ""
		local new_lang = current_lang
		local lang_changed = term.lang:getCanonicalName() ~= current_lang:getCanonicalName()

		-- Use centralized format_term (handles suppress_term, unknown_term, and regular terms)
		local term_text = format_term_func(term)

		if lang_changed then
			new_lang = term.lang
			if term_text then
				text = term.lang:makeWikipediaLink() .. " " .. term_text
			elseif term.is_family then
				text = M.en_utilities.add_indefinite_article(term.lang:makeWikipediaLink() .. " language", false)
			else
				-- suppress_term with language change: show only language
				text = term.lang:makeWikipediaLink()
			end
		else
			text = term_text or ""
		end

		return {
			type = "term",
			text = text,
			refs = get_term_refs(term, defined_here),
			lang = new_lang,
			is_uncertain = term.is_uncertain or false,
		}
	end

	-- Build text parts for a container
	local function build_container_part(container, node, depth, allow_continuation, fallback_to_bluelink)
		local keyword_info = container.keyword_info
		local keyword_modifiers = container.keyword_modifiers or {}
		local terms = container.terms or {}

		if not keyword_info or #terms == 0 then
			return nil
		end
		-- Skip building text part when invisible in text ("all", "text", or true)
		local inv = keyword_info.invisible
		if inv == "all" or inv == true or inv == "text" then
			return nil
		end

		local is_group = keyword_info.is_group
		local keyword_uncertain = keyword_modifiers.unc or false

		-- Determine text and phrase (allowing for overrides)
		local intro_text = keyword_info.text
		local phrase = keyword_info.phrase
		local new_sentence = keyword_info.new_sentence or false

		if keyword_modifiers.text then
			-- User-provided override: assumed to be lowercase
			phrase = keyword_modifiers.text
			-- Auto-capitalize for intro text (e.g., "derived from" -> "Derived from")
			intro_text = mw.ustring.upper(phrase:sub(1, 1)) .. phrase:sub(2)
		end

		local defined_here = (node.page_of or curr_page) == curr_page

		-- Get keyword references
		local keyword_refs = ""
		if defined_here and keyword_modifiers.refs and next(keyword_modifiers.refs) then
			keyword_refs = M.references.format_references(keyword_modifiers.refs)
		end

		-- Build term parts
		local term_parts = {}
		local current_lang = node.lang

		for _, term in ipairs(terms) do
			local term_part = build_term_part(term, current_lang, defined_here)
			if term_part.text ~= "" then
				table.insert(term_parts, term_part)
				current_lang = term_part.lang
			end
		end

		-- Check uncertainty distribution
		local uncertain_count = 0
		for _, term_part in ipairs(term_parts) do
			if term_part.is_uncertain then
				uncertain_count = uncertain_count + 1
			end
		end

		-- If keyword itself is uncertain, treat all terms as uncertain
		local all_uncertain = keyword_uncertain or (uncertain_count == #term_parts and #term_parts > 0)
		if is_group and uncertain_count > 0 then
			all_uncertain = true
		end
		local has_mixed_uncertainty = not all_uncertain and uncertain_count > 0

		-- Check if there are more steps (only if continuation is allowed)
		local has_more_steps = false
		local next_node = nil
		local first_term = terms[1]

		-- Check if we should stop at this language
		local reached_stop_lang = false
		if stop_at_lang then
			for _, term in ipairs(terms) do
				if term.lang and term_matches_stop_code(term.lang, stop_at_lang) then
					reached_stop_lang = true
					stop_lang_reached = true
					break
				end
			end
		elseif stop_at_lang_or_bluelink then
			-- Check if we should stop at this language, or at the first bluelink if it's a redlink
			for _, term in ipairs(terms) do
				if term.lang and term_matches_stop_code(term.lang, stop_at_lang_or_bluelink) then
					if first_term.status == M.data.STATUS.OK then
						reached_stop_lang = true
					else
						fallback_to_bluelink = true
					end
					break
				end
			end
			if fallback_to_bluelink and first_term.status == M.data.STATUS.OK then
				reached_stop_lang = true
			end
		end

		if allow_continuation and not is_group and #terms == 1 and not reached_stop_lang then
			local first_term_children = first_term.children
			if first_term_children and #first_term_children > 0 and (not max_depth or depth < max_depth) then
				local next_container = first_term_children[1]
				local next_keyword_info = next_container and next_container.keyword_info
				if not (next_keyword_info and next_keyword_info.invisible) then
					if stop_at_blue_link then
						if first_term.status ~= M.data.STATUS.OK then
							has_more_steps = true
							next_node = first_term
						end
					else
						has_more_steps = true
						next_node = first_term
					end
				end
			end
		end

		return {
			type = "container",
			intro_text = intro_text,
			phrase = phrase,
			senseid = keyword_modifiers.senseid,
			sl_keyword_text = keyword_modifiers.senseid and keyword_info.text or nil,
			is_uncertain = all_uncertain,
			has_mixed_uncertainty = has_mixed_uncertainty,
			term_parts = term_parts,
			is_group = is_group,
			has_more_steps = has_more_steps,
			next_node = next_node,
			new_sentence = new_sentence,
			separate_clause = keyword_info.separate_clause or false,
			conj = keyword_modifiers.conj or keyword_info.default_conj, -- custom conjunction: "and", "or", "and/or", etc.
			lit = keyword_modifiers.lit,
			keyword_refs = keyword_refs,
			fallback_to_bluelink = fallback_to_bluelink,
		}
	end

	-- Build the full tree of text parts
	local function build_text_tree(node, depth, allow_continuation, fallback_to_bluelink)
		local containers = node.children
		if not containers or #containers == 0 then
			return nil
		end

		local container_parts = {}

		-- Count containers that get a text part (invisible in text = "all", "text", or true)
		local visible_container_count = 0
		for _, container in ipairs(containers) do
			local keyword_info = container.keyword_info
			local inv = keyword_info and keyword_info.invisible
			if not (inv == "all" or inv == true or inv == "text") then
				visible_container_count = visible_container_count + 1
			end
		end

		-- If there are multiple visible containers at this level, don't allow continuation for any
		local has_multiple_containers = visible_container_count > 1
		local should_allow_continuation = allow_continuation and not has_multiple_containers

		for _, container in ipairs(containers) do
			local part = build_container_part(container, node, depth, should_allow_continuation, fallback_to_bluelink)
			if part then
				-- Recursively build children if there are more steps
				if part.has_more_steps and part.next_node then
					part.continuation = build_text_tree(part.next_node, depth + 1, true, part.fallback_to_bluelink)
				end
				table.insert(container_parts, part)
			end
		end

		if #container_parts == 0 then
			return nil
		end

		return {
			type = "tree",
			container_parts = container_parts,
			depth = depth,
		}
	end

	-- Check if tree has mixed joining types
	local function container_join_kind(part)
		if part.type == "etydate" then
			return nil
		end
		if part.new_sentence or part.separate_clause then
			return "supplement"
		end
		return "or_join"
	end

	local function check_complexity(tree)
		if not tree then return nil end

		local parts = tree.container_parts
		if #parts <= 1 then
			-- Single container
			if parts[1] and parts[1].continuation then
				return check_complexity(parts[1].continuation)
			end
			return nil
		end

		-- Or-join containers must precede any supplemental (calque-like / influence) containers.
		local seen_supplement = false
		for _, part in ipairs(parts) do
			local kind = container_join_kind(part)
			if kind == "supplement" then
				seen_supplement = true
			elseif kind == "or_join" and seen_supplement then
				error(
					"Cannot generate etymology text: a main derivation step cannot follow a calque, semantic loan, or influence clause in the same list.")
			end
		end

		for _, part in ipairs(parts) do
			if part.continuation then
				check_complexity(part.continuation)
			end
		end

		return nil
	end

	-- Analyze tree and assign punctuation
	local function analyze_punctuation(tree, is_toplevel)
		if not tree then return end

		local parts = tree.container_parts
		local num_parts = #parts

		for i, part in ipairs(parts) do
			local is_first = (i == 1)
			local is_last = (i == num_parts)
			local next_part = parts[i + 1]

			-- Analyze term punctuation within container
			if part.term_parts then
				-- Terms use Oxford comma style: "A, B, or C"
				-- Custom conjunction can be specified via conj modifier (e.g., "and/or", "and")
				local num_terms = #part.term_parts
				local term_conj = part.conj or "or" -- default to "or"
				for j, term_part in ipairs(part.term_parts) do
					local is_last_term = (j == num_terms)

					if part.is_group then
						-- Group: terms joined with " + "
						term_part.joiner = is_last_term and "" or " + "
					elseif num_terms > 1 then
						-- Multiple terms not in a group: Oxford comma style
						if is_last_term then
							term_part.joiner = ""
						elseif j == num_terms - 1 then
							-- Second to last term
							if num_terms == 2 then
								term_part.joiner = " " .. term_conj .. " "
							else
								term_part.joiner = ", " .. term_conj .. " "
							end
						else
							term_part.joiner = ", "
						end
					else
						-- Single term
						term_part.joiner = ""
					end
				end
			end

			-- Determine container punctuation based on what comes next
			if part.continuation then
				-- Has continuation
				part.punctuation = ","
				-- Recursively analyze continuation
				analyze_punctuation(part.continuation, false)
			elseif is_last then
				-- Last container at this level (may still continue in part.continuation)
				part.punctuation = "."
			elseif next_part and next_part.new_sentence then
				-- Next container starts a new sentence
				part.punctuation = "."
			elseif next_part and next_part.separate_clause then
				-- Next container is a separate clause
				part.punctuation = ","
			else
				-- Not last, next is joined with "or"
				-- Containers use repeated "or" style: "A, or B, or C"
				part.punctuation = ","
			end

			-- Determine joiner to next part
			-- Containers use repeated "or" style: ", or" between each
			-- Custom conjunction can be specified via conj modifier
			local container_conj = part.conj or "or" -- default to "or"
			if not is_last then
				if next_part and next_part.new_sentence then
					-- New sentence
					part.joiner = " "
				elseif next_part and next_part.separate_clause then
					-- Separate clause
					part.joiner = " "
				else
					-- Same sentence: use custom conjunction or default "or"
					part.joiner = " " .. container_conj .. " "
				end
			else
				part.joiner = ""
			end

			-- Determine intro formatting
			-- Capitalize if first at top level, OR if this container starts a new sentence
			if (is_first and is_toplevel) or part.new_sentence then
				part.intro_capitalized = true
				part.use_full_intro = true
			else
				part.intro_capitalized = false
				part.use_full_intro = false
			end
		end
	end

	-- Assemble text from analyzed tree
	local function assemble_text(tree)
		if not tree then return "" end

		local result = ""

		for i, part in ipairs(tree.container_parts) do
			if part.type == "etydate" then
				result = result .. part.etydate_text
				if part.punctuation and part.punctuation ~= "" then
					result = result .. part.punctuation
				end
				if part.etydate_refs and next(part.etydate_refs) then
					result = result .. M.references.format_references(part.etydate_refs)
				end
				if part.joiner and part.joiner ~= "" then
					result = result .. part.joiner
				end
			else
				-- Build intro
				local intro_text = part.intro_text
				local phrase = part.phrase
				if part.senseid then
					intro_text, phrase = format_sl_senseid_intro(
						part.senseid,
						part.sl_keyword_text,
						part.phrase,
						part.intro_capitalized,
						part.is_uncertain
					)
				end

				local intro
				if part.use_full_intro then
					if part.is_uncertain and not part.senseid then
						intro = "Possibly " .. phrase
					else
						intro = intro_text
					end
				else
					if part.is_uncertain and not part.senseid then
						intro = "possibly " .. phrase
					else
						intro = phrase
					end
				end

			result = result .. intro

			-- Build terms
			if #part.term_parts > 0 then
				result = result .. " "

				for j, term_part in ipairs(part.term_parts) do
					-- Add "possibly" prefix for uncertain terms when there's mixed uncertainty
					if part.has_mixed_uncertainty and term_part.is_uncertain then
						result = result .. "possibly "
					end

					result = result .. term_part.text

					-- Add joiner between terms
					if term_part.joiner ~= "" then
						-- Check if joiner contains comma (punctuation)
						local comma_pos = term_part.joiner:find(",")
						if comma_pos then
							-- Add up to and including comma
							result = result .. term_part.joiner:sub(1, comma_pos)
							-- Add refs after comma
							if term_part.refs ~= "" then
								result = result .. term_part.refs
							end
							-- Add rest of joiner
							result = result .. term_part.joiner:sub(comma_pos + 1)
						else
							-- No comma, add refs before joiner
							if term_part.refs ~= "" then
								result = result .. term_part.refs
							end
							result = result .. term_part.joiner
						end
					end
				end

				-- For the last term, add punctuation then refs
				local last_term = part.term_parts[#part.term_parts]
				if last_term and last_term.joiner == "" then
					if part.punctuation ~= "" then
						-- If we have literal text, punctuation goes AFTER it
						if part.lit then
							-- Add refs first (attached to term)
							if last_term.refs ~= "" then
								result = result .. last_term.refs
							end
							-- Add keyword refs
							if part.keyword_refs and part.keyword_refs ~= "" then
								result = result .. part.keyword_refs
							end
							-- Add literal text
							result = result .. ", literally “" .. part.lit .. "”"
							-- Add punctuation
							result = result .. part.punctuation
						else
							-- Normal behavior: punctuation then refs
							result = result .. part.punctuation
							if last_term.refs ~= "" then
								result = result .. last_term.refs
							end
							-- Add keyword refs after term refs
							if part.keyword_refs and part.keyword_refs ~= "" then
								result = result .. part.keyword_refs
							end
						end
					else
						-- No punctuation
						if last_term.refs ~= "" then
							result = result .. last_term.refs
						end
						-- Add keyword refs
						if part.keyword_refs and part.keyword_refs ~= "" then
							result = result .. part.keyword_refs
						end
						-- Add literal text if present (even without punctuation)
						if part.lit then
							result = result .. ", literally “" .. part.lit .. "”"
						end
					end
				end
			else
				-- No terms, just add punctuation and keyword refs
				if part.punctuation ~= "" then
					result = result .. part.punctuation
				end
				-- Add keyword refs even when there are no terms
				if part.keyword_refs and part.keyword_refs ~= "" then
					result = result .. part.keyword_refs
				end
			end

			-- Add continuation
			if part.continuation then
				result = result .. " " .. assemble_text(part.continuation)
			end

			-- Add joiner to next container
			if part.joiner ~= "" then
				result = result .. part.joiner
			end
		end
	end

		return result
	end

	local text_tree = build_text_tree(data_tree, 1, true, false)

	-- Supplements (doublets, etydate, …) are rendered outside the main derivation text tree.
	local function assemble_supplements()
		if not data_tree.supplements then
			return ""
		end

		local chunks = {}
		local pending_trees = {}

		local function flush_pending_trees()
			local num = #pending_trees
			for i, supplement_tree in ipairs(pending_trees) do
				analyze_punctuation(supplement_tree, true)
				apply_closing_punctuation_override(supplement_tree, i == num)
				local chunk = assemble_text(supplement_tree)
				if chunk ~= "" then
					table.insert(chunks, chunk)
				end
			end
			pending_trees = {}
		end

		for _, supplement in ipairs(data_tree.supplements) do
			local supplement_tree

			if supplement.type == "doublet" and supplement.config
				and supplement.terms and #supplement.terms > 0 then
				local config = supplement.config
				local term_parts = {}
				for _, term in ipairs(supplement.terms) do
					local term_part = build_term_part(term, entry_lang, true)
					if term_part.text ~= "" then
						table.insert(term_parts, term_part)
					end
				end
				if #term_parts == 0 then
					supplement_tree = nil
				else
					supplement_tree = {
						type = "tree",
						container_parts = {
							{
								type = "doublet",
								intro_text = config.text,
								phrase = config.phrase,
								term_parts = term_parts,
								conj = config.default_conj or "and",
								new_sentence = true,
							},
						},
						depth = 1,
					}
				end
			elseif supplement.type == "etydate" and supplement.etydate_text and supplement.etydate_text ~= "" then
				supplement_tree = {
					type = "tree",
					container_parts = {
						{
							type = "etydate",
							etydate_text = supplement.etydate_text,
							etydate_refs = supplement.etydate_refs,
							new_sentence = true,
						},
					},
					depth = 1,
				}
			end

			if supplement_tree then
				table.insert(pending_trees, supplement_tree)
			end
		end

		flush_pending_trees()

		return table.concat(chunks, " ")
	end

	if not text_tree then
		local supplement_text = assemble_supplements()
		if supplement_text == "" then
			if stop_at_lang then
				return "", { stop_lang_reached = false }
			end
			return ""
		end
		if stop_at_lang then
			return supplement_text, { stop_lang_reached = false }
		end
		return supplement_text
	end

	local rendered = ""
	if text_tree then
		check_complexity(text_tree)
		analyze_punctuation(text_tree, true)
		apply_closing_punctuation_override(text_tree, not has_supplements())
		rendered = assemble_text(text_tree)
	end

	local supplement_text = assemble_supplements()
	if supplement_text ~= "" then
		if rendered ~= "" then
			rendered = rendered .. " " .. supplement_text
		else
			rendered = supplement_text
		end
	end

	if stop_at_lang then
		return rendered, { stop_lang_reached = stop_lang_reached }
	end
	return rendered
end

return export