Jump to content

Module:CodeToText

Documentation for this module may be created at Module:CodeToText/doc

-- Module:CodeToText
-- Extracts content snippets from a page using hook markers
-- 
-- Finds content between matching emoji hooks (e.g., đŸȘ, 📌, 🔖, ⭐) placed at the beginning and end of desired content.
-- 
-- Example:
--   {{#invoke:CodeToText|showSnippet|page=Module:Example|hook=⭐}}

local p = {}

function p.showSnippet(frame)
    local pageName = frame.args.page
    if not pageName then
        return "Error: 'page' parameter is required"
    end

    local hook = frame.args.hook
    if not hook then
        return "Error: 'hook' parameter is required"
    end

    local titleObj = mw.title.new(pageName)
    if not titleObj then
        return "Failed to create mw.title object for '" .. pageName .. "'"
    end

    local content = titleObj:getContent()
    if not content then
        return "No content for '" .. pageName .. "'"
    end

    -- Try inline hooks first
    local inlineSnippet = content:match(hook .. "(.-)" .. hook)
    if inlineSnippet then
        return inlineSnippet
    end

    -- Find block hooks
    local s, e = content:find(hook, 1, true)
    if not s then
        return "Error: Need at least 2 instances of hook '" .. hook .. "' in '" .. pageName .. "'"
    end

    local s2, e2 = content:find(hook, e + 1, true)
    if not s2 then
        return "Error: Need at least 2 instances of hook '" .. hook .. "' in '" .. pageName .. "'"
    end

    -- Extract text between the two hooks, excluding the hook lines
    local snippet = content:sub(e + 1, s2 - 1)

    -- Trim leading and trailing newlines
    if snippet:sub(1,1) == "\n" then
        snippet = snippet:sub(2)
    end
    if snippet:sub(-1) == "\n" then
        snippet = snippet:sub(1, -2)
    end

    return snippet
end

return p