Module:CodeToText
Appearance
Documentation for this module may be created at Module:CodeToText/doc
-- Module:TranscludeModuleCode
-- Extracts a snippet of lines from a specified page using either:
-- 1. A defined line range (from/to parameters)
-- 2. Hook markers like emojis (startHook/endHook parameters)
-- 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 startHook = frame.args.startHook
local endHook = frame.args.endHook
local includeHook = frame.args.includeHook == 'true'
-- Fallback to line numbers if hooks aren't provided
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 = {}
-- If hooks are provided, use them to extract the snippet
if startHook then
local startIndex, endIndex = nil, nil
-- Find the start hook
for i, line in ipairs(lines) do
if line:find(startHook, 1, true) then
startIndex = i
break
end
end
-- Find the end hook if provided
if endHook and startIndex then
for i = startIndex + 1, #lines do
if lines[i]:find(endHook, 1, true) then
endIndex = i
break
end
end
end
-- Extract the snippet based on hooks
if startIndex then
local snippetStart = includeHook and startIndex or startIndex + 1
local snippetEnd = endIndex
if not endIndex then
-- If no end hook is found or provided, include all lines after the start hook
snippetEnd = #lines
elseif not includeHook then
snippetEnd = endIndex - 1
end
for i = snippetStart, snippetEnd do
table.insert(snippet, lines[i])
end
else
return "Start hook '" .. startHook .. "' not found in '" .. pageName .. "'"
end
else
-- Fallback to line number-based extraction
for i = fromLine, math.min(toLine, #lines) do
table.insert(snippet, lines[i])
end
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