Diferencia entre revisiones de «Módulo:Excerpt»

De Hispanopedia
imported>Leoncastro
m ops
 
imported>Sophivorus
Actualizo a la última versión
Línea 1: Línea 1:
-- Copied from https://en.wikipedia.org/wiki/Module:Excerpt.
local Transcluder = require('Module:Transcluder')
-- This module is rated as alpha.
 
local yesno = require('Module:Yesno')
 
local ok, config = pcall(require, 'Module:Excerpt/config')
if not ok then config = {} end


local p = {}
local p = {}
local mRedirect = require('Module:Redirección')


-- Entry point for Lua callers
-- Helper function to get arguments
-- Returns a string value: text of the lead of a page
local args
function p._lead(pagenames, options)
function getArg(key, default)
if not pagenames or #pagenames < 1 then return "" end -- Return blank text rather than an error splurge
value = args[key]
local pagename = pagenames[1]
if value and mw.text.trim(value) ~= '' then
if #pagenames > 1 then -- we could do this even with one page, but it would be inefficient
return value
math.randomseed(os.time())
end
pagename = pagenames[math.random(#pagenames)] --pick a random title
return default
end
 
-- Helper function to handle errors
function getError(message, value)
if type(message) == 'string' then
message = Transcluder.getError(message, value)
end
if config.categories and config.categories.errors and mw.title.getCurrentTitle().isContentPage then
message:node('[[Category:' .. config.categories.errors .. ']]')
end
end
pagename = mw.ustring.match(pagename, "%[%[%s*(.-)[]|#]") or pagename -- "[[Foo|Bar]]" → "Foo"
return message
pagename = mw.ustring.match(pagename, "%S.*%S") -- strip leading and trailing white space
end
 
-- Helper function to get localized messages
function getMessage(key)
local ok, TNT = pcall(require, 'Module:TNT')
if not ok then return key end
return TNT.format('I18n/Module:Excerpt.tab', key)
end
 
function p.main(frame)
args = Transcluder.parseArgs(frame)
 
-- Make sure the requested page exists
local page = getArg(1)
if not page then return getError('no-page') end
local title = mw.title.new(page)
if not title then return getError('no-page') end
if title.isRedirect then title = title.redirectTarget end
if not title.exists then return getError('page-not-found', page) end
page = title.prefixedText


local title = mw.title.new(pagename) -- Find the lead section of the named page
-- Set variables
if not title then return "" end
local fragment = getArg('fragment')
local redir = mRedirect.getTarget(title)
local section = fragment or getArg(2, getArg('section', mw.ustring.match(getArg(1), '[^#]+#([^#]+)') ) )
if redir then title = mw.title.new(redir) end
local hat = yesno( getArg('hat', true) )
local edit = yesno( getArg('edit', true) )
local this = getArg('this')
local only = getArg('only')
local files = getArg('files', getArg('file', ( only == 'file' and 1 ) ) )
local lists = getArg('lists', getArg('list', ( only == 'list' and 1 ) ) )
local tables = getArg('tables', getArg('table', ( only == 'table' and 1 ) ) )
local templates = getArg('templates', getArg('template', ( only == 'template' and 1 ) ) )
local paragraphs = getArg('paragraphs', getArg('paragraph', ( only == 'paragraph' and 1 ) ) )
local references = getArg('references', getArg('reference', ( only == 'reference' and 1 ) ) )
local sections = not yesno( getArg('sections') )
local noBold = not yesno( getArg('bold') )
local inline = yesno( getArg('inline') )
local quote = yesno( getArg('quote') )
local more = yesno( getArg('more') )
local class = getArg('class')
local blacklist = table.concat((config.templates or {}), ',')


local text = title:getContent() or ""
-- Build the hatnote
text = mw.ustring.gsub(text, "%c%s*==.*","") -- remove first heading and everything after it
if hat and not inline then
text = mw.ustring.gsub(text, "<noinclude>.-</noinclude>", "") -- remove noinclude bits
if this then
if not options.refs or options.refs == "false" then
hat = this
text = mw.ustring.gsub(text, "<[Rr][Ee][Ff][^>]-/>", "") -- remove refs cited elsewhere
elseif quote then
text = mw.ustring.gsub(text, "<[Rr][Ee][Ff].->.-</[Rr][Ee][Ff]%s*>", "") -- remove refs
hat = getMessage('this')
for _, t in pairs {"[Hh]arvnp", "[Rr]efn", "[Ss]fnm?", "#[Tt][Aa][Gg]:%s*[Rr][Ee][Ff]"} do
elseif only then
text = mw.ustring.gsub(text, "{{%s*" .. t .. "%s*|.-}}", "") -- remove ref and footnote templates
hat = getMessage(only)
else
hat = getMessage('section')
end
hat = hat .. ' ' .. getMessage('excerpt') .. ' '
if section and not fragment then
hat = hat .. '[[:' .. page .. '#' .. mw.uri.anchorEncode(section) .. '|' .. page
.. ' § ' .. mw.ustring.gsub(section, '%[%[([^]|]+)|?[^]]*%]%]', '%1') .. ']]' -- remove nested links
else
hat = hat .. '[[:' .. page .. '|' .. page .. ']]'
end
if edit then
hat = hat .. "''" .. '<span class="mw-editsection-like plainlinks"><span class="mw-editsection-bracket">[</span>['
hat = hat .. title:fullUrl('action=edit') .. ' ' .. mw.message.new('editsection'):plain()
hat = hat .. ']<span class="mw-editsection-bracket">]</span></span>' .. "''"
end
if config.hat then
hat = config.hat .. hat .. '}}'
hat = frame:preprocess(hat)
end
end
hat = mw.html.create('div'):addClass('dablink excerpt-hat'):wikitext(hat)
else
hat = nil
end
-- Build the "Read more" link
if more and not inline then
more = "'''[[" .. page .. '#' .. (section or '') .. "|" .. getMessage('more') .. "]]'''"
more = mw.html.create('div'):addClass('noprint excerpt-more'):wikitext(more)
else
more = nil
end
end
text = mw.ustring.gsub(text, "%s*{{%s*([Cc]ontenido|[Tt](?:ocright|OC(?:001| ?derecha| ?limit))).-}}", "") -- remove most common tables of contents


local allparas = true -- keep all paragraphs?
-- Build the options for Module:Transcluder out of the template arguments and the desired defaults
if options.paraflags then
local options = {
for _, v in pairs(options.paraflags) do
files = files,
if v then allparas = false end -- if any para specifically requested, don't keep all
lists = lists,
end
tables = tables,
paragraphs = paragraphs,
templates = templates or '-' .. blacklist,
sections = sections,
categories = 0,
references = references,
only = only and mw.text.trim(only, 's') .. 's',
noBold = noBold,
noSelfLinks = true,
noNonFreeFiles = true,
noBehaviorSwitches = true,
fixReferences = true,
linkBold = true,
}
 
-- Get the excerpt itself
local title = page .. '#' .. (section or '')
local ok, excerpt = pcall(Transcluder.get, title, options)
if not ok then return getError(excerpt) end
if mw.text.trim(excerpt) == '' then
if section then return getError('section-empty', section) else return getError('lead-empty') end
end
end


-- a basic parser to trim down the lead
-- Add a line break in case the excerpt starts with a table or list
local inlead = false -- have we found some text yet?
excerpt = '\n' .. excerpt
local t = "" -- the stripped down output text
local files = 0 -- how many [[Image: or [[File: so far
local paras = 0 -- how many paragraphs so far


text = mw.ustring.gsub(text,"^%s*","") -- remove initial white space
-- If no file was found, try to excerpt one from the removed infoboxes
repeat -- loop around parsing a comment, template, image or paragraph
local fileNamespaces = Transcluder.getNamespaces('File')
local token = mw.ustring.match(text, "^%s*<!%-%-.-%-%->%s*") -- <!--HTML comment-->
if not only and (files ~= '0' or not files) and not Transcluder.matchAny(excerpt, '%[%[', fileNamespaces, ':') and config.captions then
or mw.ustring.match(text, "^%b{}%s*") or false -- or {{Template}}
local templates = Transcluder.get(title, { only = 'templates', templates = blacklist, fixReferences = true } )
if token then
local parameters = Transcluder.getParameters(templates)
if inlead then t = t .. token end -- keep comments and templates only within text body
local file, captions, caption
else
for _, pair in pairs(config.captions) do
token = mw.ustring.match(text, "^%[%[%s*([Aa]rchivo|[Ff]ile|[Ii]mage)%s*:") -- [[File: ...
file = pair[1]
if token then
file = parameters[file]
token = mw.ustring.match(text, "^%b[]%s*") -- match [[...]] to handle nesting
if file and Transcluder.matchAny(file, '^.*%.', {'[Jj][Pp][Ee]?[Gg]','[Pp][Nn][Gg]','[Gg][Ii][Ff]','[Ss][Vv][Gg]'}, '.*') then
files = files + 1
file = mw.ustring.match(file, '%[?%[?.-:([^{|]+)%]?%]?') or file -- [[File:Example.jpg{{!}}upright=1.5]] to Example.jpg
if options.fileflags and options.fileflags[files] then t = t .. token end
captions = pair[2]
else -- got a paragraph, which ends at a file, image, blank line or end of text
for _, p in pairs(captions) do
local afterend = mw.ustring.len(text) + 1
if parameters[p] then caption = parameters[p] break end
local blankpos = mw.ustring.find(text, "\n%s*\n") or afterend
local endpos = math.min(
mw.ustring.find(text, "%[%[%s*([Aa]rchivo|[Ff]ile|[Ii]mage)%s*:") or afterend,
mw.ustring.find(text, "%[%[%s*([Aa]rchivo|[Ff]ile|[Ii]mage)%s*:") or afterend,
blankpos)
token = mw.ustring.sub(text, 1, endpos-1)
if blankpos < afterend and blankpos == endpos then -- paragraph ends with a blank line
token = token .. mw.ustring.match(text, "\n%s*\n", blankpos)
end
end
inlead = true
excerpt = '[[File:' .. file .. '|thumb|' .. (caption or '') .. ']]' .. excerpt
paras = paras + 1
excerpt = Transcluder.removeNonFreeFiles(excerpt)
if allparas or (options.paraflags and options.paraflags[paras]) then t = t .. token end
break
end
end
end
end
end


if token then text = mw.ustring.sub(text, mw.ustring.len(token)+1) end
-- Remove nested categories
until not text or text == "" or not token or token == ""
excerpt = frame:preprocess(excerpt)
local categories, excerpt = Transcluder.getCategories(excerpt, options.categories)


text = mw.ustring.gsub(t, "\n+$", "") -- remove  trailing line feeds, so "{{Transclude text excerpt|Foo}} more" flows on one line
-- Add tracking categories
 
if config.categories then
if options.more then text = text .. " '''[[" .. pagename .. "|" .. options.more .. "]]'''" end
local contentCategory = config.categories.content
return text
if contentCategory and mw.title.getCurrentTitle().isContentPage then
end
excerpt = excerpt .. '[[Category:' .. contentCategory .. ']]'
 
end
-- Convert a comma-separated list of numbers or min-max ranges into a list of booleans, e.g. "1,3-5" → {1=true,2=false,3=true,4=true,5=true}
local namespaceCategory = config.categories[ mw.title.getCurrentTitle().namespace ]
function p.numberflags(str)
if namespaceCategory then
local ranges = mw.text.split(str, ",") -- parse ranges, e.g. "1,3-5" → {"1","3-5"}
excerpt = excerpt .. '[[Category:' .. namespaceCategory .. ']]'
local flags = {}
for _, r in pairs(ranges) do
local min, max = mw.ustring.match(r, "^%s*(%d+)%s*%-%s*(%d+)%s*$") -- "3-5" → min=3 max=5
if not max then min, max = mw.ustring.match(r, "^%s*((%d+))%s*$") end -- "1" → min=1 max=1
if max then
for p = min, max do flags[p] = true end
end
end
end
end
return flags
end


-- Entry point for template callers using #invoke:
-- Load the styles
function p.lead(frame)
local styles
-- args = { 1 = page name, paragraphs = list e.g. "1,3-5", files = list, more = text}
if config.styles then
local args = frame.args -- from calling module
styles = frame:extensionTag( 'templatestyles', '', { src = config.styles } )
local pargs = frame:getParent().args -- from template
end


-- Accept any number of page names.  If more than one, we'll pick one randomly
-- Combine and return the elements
local pagenames = {}
local tag1 = 'div'
for i, p in pairs(args) do
local tag2 = 'div'
if p and type(i) == 'number' then table.insert(pagenames, p) end
if inline then
end
tag1 = 'span'
for i, p in pairs(pargs) do
tag2 = 'span'
if p and type(i) == 'number' and not args[i] then table.insert(pagenames, p) end
elseif quote then
tag2 = 'blockquote'
end
end
 
excerpt = mw.html.create(tag1):addClass('excerpt'):wikitext(excerpt)
local options = {}
local block = mw.html.create(tag2):addClass('excerpt-block'):addClass(class)
options.paraflags = p.numberflags(args["paragraphs"] or pargs["paragraphs"] or "") -- parse paragraphs, e.g. "1,3-5" → {"1","3-5"}
return block:node(styles):node(hat):node(excerpt):node(more)
options.fileflags = p.numberflags(args["files"] or pargs["files"] or "") -- parse file numbers
options.refs = args["refs"] or pargs["refs"]
options.more = args["more"] or pargs["more"]
if options.more and options.more == "" then options.more = "Read more..." end -- more= is short for this default text
 
local text = p._lead(pagenames, options)
return frame:preprocess(text)
end
end


-- Function lead is just function random picking from a list of one article,
-- Entry points for backwards compatibility
-- but we advertise different entry points in case they should differ in future
function p.lead(frame) return p.main(frame) end
function p.random(frame)
function p.excerpt(frame) return p.main(frame) end
return p.lead(frame)
end


return p
return p

Revisión del 15:31 8 oct 2020

La documentación para este módulo puede ser creada en Módulo:Excerpt/doc

local Transcluder = require('Module:Transcluder')

local yesno = require('Module:Yesno')

local ok, config = pcall(require, 'Module:Excerpt/config')
if not ok then config = {} end

local p = {}

-- Helper function to get arguments
local args
function getArg(key, default)
	value = args[key]
	if value and mw.text.trim(value) ~= '' then
		return value
	end
	return default
end

-- Helper function to handle errors
function getError(message, value)
	if type(message) == 'string' then
		message = Transcluder.getError(message, value)
	end
	if config.categories and config.categories.errors and mw.title.getCurrentTitle().isContentPage then
		message:node('[[Category:' .. config.categories.errors .. ']]')
	end
	return message
end

-- Helper function to get localized messages
function getMessage(key)
	local ok, TNT = pcall(require, 'Module:TNT')
	if not ok then return key end
	return TNT.format('I18n/Module:Excerpt.tab', key)
end

function p.main(frame)
	args = Transcluder.parseArgs(frame)

	-- Make sure the requested page exists
	local page = getArg(1)
	if not page then return getError('no-page') end
	local title = mw.title.new(page)
	if not title then return getError('no-page') end
	if title.isRedirect then title = title.redirectTarget end
	if not title.exists then return getError('page-not-found', page) end
	page = title.prefixedText

	-- Set variables
	local fragment = getArg('fragment')
	local section = fragment or getArg(2, getArg('section', mw.ustring.match(getArg(1), '[^#]+#([^#]+)') ) )
	local hat = yesno( getArg('hat', true) )
	local edit = yesno( getArg('edit', true) )
	local this = getArg('this')
	local only = getArg('only')
	local files = getArg('files', getArg('file', ( only == 'file' and 1 ) ) )
	local lists = getArg('lists', getArg('list', ( only == 'list' and 1 ) ) )
	local tables = getArg('tables', getArg('table', ( only == 'table' and 1 ) ) )
	local templates = getArg('templates', getArg('template', ( only == 'template' and 1 ) ) )
	local paragraphs = getArg('paragraphs', getArg('paragraph', ( only == 'paragraph' and 1 ) ) )
	local references = getArg('references', getArg('reference', ( only == 'reference' and 1 ) ) )
	local sections = not yesno( getArg('sections') )
	local noBold = not yesno( getArg('bold') )
	local inline = yesno( getArg('inline') )
	local quote = yesno( getArg('quote') )
	local more = yesno( getArg('more') )
	local class = getArg('class')
	local blacklist = table.concat((config.templates or {}), ',')

	-- Build the hatnote
	if hat and not inline then
		if this then
			hat = this
		elseif quote then
			hat = getMessage('this')
		elseif only then
			hat = getMessage(only)
		else
			hat = getMessage('section')
		end
		hat = hat .. ' ' .. getMessage('excerpt') .. ' '
		if section and not fragment then
			hat = hat .. '[[:' .. page .. '#' .. mw.uri.anchorEncode(section) .. '|' .. page
				.. ' § ' .. mw.ustring.gsub(section, '%[%[([^]|]+)|?[^]]*%]%]', '%1') .. ']]' -- remove nested links
		else
			hat = hat .. '[[:' .. page .. '|' .. page .. ']]'
		end
		if edit then
			hat = hat .. "''" .. '<span class="mw-editsection-like plainlinks"><span class="mw-editsection-bracket">[</span>['
			hat = hat .. title:fullUrl('action=edit') .. ' ' .. mw.message.new('editsection'):plain()
			hat = hat .. ']<span class="mw-editsection-bracket">]</span></span>' .. "''"
		end
		if config.hat then
			hat = config.hat .. hat .. '}}'
			hat = frame:preprocess(hat)
		end
		hat = mw.html.create('div'):addClass('dablink excerpt-hat'):wikitext(hat)
	else
		hat = nil
	end

	-- Build the "Read more" link
	if more and not inline then
		more = "'''[[" .. page .. '#' .. (section or '') .. "|" .. getMessage('more') .. "]]'''"
		more = mw.html.create('div'):addClass('noprint excerpt-more'):wikitext(more)
	else
		more = nil
	end

	-- Build the options for Module:Transcluder out of the template arguments and the desired defaults
	local options = {
		files = files,
		lists = lists,
		tables = tables,
		paragraphs = paragraphs,
		templates = templates or '-' .. blacklist,
		sections = sections,
		categories = 0,
		references = references,
		only = only and mw.text.trim(only, 's') .. 's',
		noBold = noBold,
		noSelfLinks = true,
		noNonFreeFiles = true,
		noBehaviorSwitches = true,
		fixReferences = true,
		linkBold = true,
	}

	-- Get the excerpt itself
	local title = page .. '#' .. (section or '')
	local ok, excerpt = pcall(Transcluder.get, title, options)
	if not ok then return getError(excerpt) end
	if mw.text.trim(excerpt) == '' then
		if section then return getError('section-empty', section) else return getError('lead-empty') end
	end

	-- Add a line break in case the excerpt starts with a table or list
	excerpt = '\n' .. excerpt

	-- If no file was found, try to excerpt one from the removed infoboxes
	local fileNamespaces = Transcluder.getNamespaces('File')
	if not only and (files ~= '0' or not files) and not Transcluder.matchAny(excerpt, '%[%[', fileNamespaces, ':') and config.captions then
		local templates = Transcluder.get(title, { only = 'templates', templates = blacklist, fixReferences = true } )
		local parameters = Transcluder.getParameters(templates)
		local file, captions, caption
		for _, pair in pairs(config.captions) do
			file = pair[1]
			file = parameters[file]
			if file and Transcluder.matchAny(file, '^.*%.', {'[Jj][Pp][Ee]?[Gg]','[Pp][Nn][Gg]','[Gg][Ii][Ff]','[Ss][Vv][Gg]'}, '.*') then
				file = mw.ustring.match(file, '%[?%[?.-:([^{|]+)%]?%]?') or file -- [[File:Example.jpg{{!}}upright=1.5]] to Example.jpg
				captions = pair[2]
				for _, p in pairs(captions) do
					if parameters[p] then caption = parameters[p] break end
				end
				excerpt = '[[File:' .. file .. '|thumb|' .. (caption or '') .. ']]' .. excerpt
				excerpt = Transcluder.removeNonFreeFiles(excerpt)
				break
			end
		end
	end

	-- Remove nested categories
	excerpt = frame:preprocess(excerpt)
	local categories, excerpt = Transcluder.getCategories(excerpt, options.categories)

	-- Add tracking categories
	if config.categories then
		local contentCategory = config.categories.content
		if contentCategory and mw.title.getCurrentTitle().isContentPage then
			excerpt = excerpt .. '[[Category:' .. contentCategory .. ']]'
		end
		local namespaceCategory = config.categories[ mw.title.getCurrentTitle().namespace ]
		if namespaceCategory then
			excerpt = excerpt .. '[[Category:' .. namespaceCategory .. ']]'
		end
	end

	-- Load the styles
	local styles
	if config.styles then
		styles = frame:extensionTag( 'templatestyles', '', { src = config.styles } )
	end

	-- Combine and return the elements
	local tag1 = 'div'
	local tag2 = 'div'
	if inline then
		tag1 = 'span'
		tag2 = 'span'
	elseif quote then
		tag2 = 'blockquote'
	end
	excerpt = mw.html.create(tag1):addClass('excerpt'):wikitext(excerpt)
	local block = mw.html.create(tag2):addClass('excerpt-block'):addClass(class)
	return block:node(styles):node(hat):node(excerpt):node(more)
end

-- Entry points for backwards compatibility
function p.lead(frame) return p.main(frame) end
function p.excerpt(frame) return p.main(frame) end

return p