Jump to content

Module:CodeToText: Difference between revisions

No edit summary
No edit summary
Line 19: Line 19:


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


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


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


return p
return p

Revision as of 04:30, 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 frame.args.remove then
         local removeToken = frame.args.remove
         local escaped = removeToken:gsub("([^%w])", "%%%1")
         local pattern = "^" .. escaped .. "%s*"
         for i, line in ipairs(snippet) do
              snippet[i] = line:gsub(pattern, "")
         end
    end

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

return p