Module:LineJoiner

文档图示 模块文档[创建]
local p = {}

-- Check if a line is special (e.g., empty, header, HTML tag)
function p.isSpecialLine(line)
    return line:match("^%s*$") or line:match("^=.+=$") or line:match("^__.*__$") or line:match("^<[^>]+>$")
end

function p.joinLines(frame)
    -- Ensure frame.args exists
    if not frame.args then
        return "Error: No arguments provided."
    end

    -- 使用第一个参数作为分隔符
    local sep = frame.args[1] or ""
    local text = frame.args.text or ""

    -- Split the text into lines, keeping empty lines
    local lines = mw.text.split(text, "\n")

    local result = {}
    local wasLastLineNormal = false

    for i, line in ipairs(lines) do
        -- Determine if the current line is special
        local isSpecial = p.isSpecialLine(line)

        -- Handle the line based on its type
        if isSpecial then
            if i > 1 then
                table.insert(result, "\n")  -- Insert a newline before special lines
            end
            wasLastLineNormal = false
        else
            if wasLastLineNormal then
                table.insert(result, sep)  -- Add separator between normal lines
            elseif i > 1 then
                table.insert(result, "\n")  -- Insert a newline before the first normal line
            end
            wasLastLineNormal = true
        end

        table.insert(result, line)  -- Always add the line
    end

    return table.concat(result)
end

return p