Module:CodeToText: Difference between revisions
Appearance
No edit summary |
No edit summary |
||
| Line 1: | Line 1: | ||
-- Extracts | -- Extracts a snippet of lines from a specified page using a defined line range. Optionally removes a given token (like a leading comment --) from each line. | ||
local p = {} | local p = {} | ||
Revision as of 04:32, 10 February 2025
Documentation for this module may be created at Module:CodeToText/doc
-- Extracts a snippet of lines from a specified page using a defined line range. Optionally removes a given token (like a leading comment --) from each line.
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