Jump to content

Module:CodeToText: Difference between revisions

No edit summary
No edit summary
Line 4: Line 4:


function p.showSnippet(frame)
function p.showSnippet(frame)
    -- Get the page to load, defaulting to "Module:Sandbox" if none is specified
     local pageName = frame.args.page or 'Module:Sandbox'
     local pageName = frame.args.page or 'Module:Sandbox'
     local fromLine = tonumber(frame.args.from) or 1
     local fromLine = tonumber(frame.args.from) or 1
Line 19: Line 18:
     end
     end


    -- Split by line
     local lines = {}
     local lines = {}
     for line in content:gmatch('[^\r\n]+') do
     for line in content:gmatch('[^\r\n]+') do
Line 25: Line 23:
     end
     end


    -- Extract only the requested line range
     local snippet = {}
     local snippet = {}
     for i = fromLine, math.min(toLine, #lines) do
     for i = fromLine, math.min(toLine, #lines) do
         table.insert(snippet, lines[i])
         table.insert(snippet, lines[i])
    end
    -- If a removal argument is provided, remove its occurrences from the snippet
    if frame.args.remove then
        local removeToken = frame.args.remove
        for i, line in ipairs(snippet) do
              snippet[i] = line:gsub(removeToken, "")
        end
     end
     end



Revision as of 04:26, 10 February 2025

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

-- Extracts and returns a snippet of lines from a specified page, allowing for selective display of content within a defined range

local p = {}

function p.showSnippet(frame)
    local pageName = frame.args.page or 'Module:Sandbox'
    local fromLine = tonumber(frame.args.from) or 1
    local toLine   = tonumber(frame.args.to)   or fromLine

    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

    local lines = {}
    for line in content:gmatch('[^\r\n]+') do
        table.insert(lines, line)
    end

    local snippet = {}
    for i = fromLine, math.min(toLine, #lines) do
        table.insert(snippet, lines[i])
    end

    -- If a removal argument is provided, remove its occurrences from the snippet
    if frame.args.remove then
         local removeToken = frame.args.remove
         for i, line in ipairs(snippet) do
              snippet[i] = line:gsub(removeToken, "")
         end
    end

    return table.concat(snippet, '\n')
end

return p