Module:CodeToText: Difference between revisions
Appearance
No edit summary |
No edit summary |
||
| Line 19: | Line 19: | ||
local lines = {} | local lines = {} | ||
for line in content:gmatch( | 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 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( | snippet[i] = line:gsub(pattern, "") | ||
end | end | ||
end | end | ||
return table.concat(snippet, | 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