Module:Demo: Difference between revisions

From NvWiki
Jump to navigation Jump to search
Repair breakage. This is one of the reasons why I dislike the entire concept of lint errors
Undid revision 1240199590 by BrandonXLF (talk)
Line 1: Line 1:
==demo_kill_categories alias nocat==
local p = {}
{{moved from|Module talk:Demo|[[User:Pppery|* Pppery *]] [[User talk:Pppery|<sub style="color:#800000">has returned</sub>]] 00:45, 22 April 2019 (UTC)}}
I've did [[Special:Diff/841233019/856477054|this change]], but it doesn't seem to work.  Can somebody with more Lua knowledge take a look?
See example here: [[User:Andrybak/sandbox/demonocat]] -- note, that page is added to [[:Category:Wikipedians in Russia]], but shouldn't be. —&#8288;[[User:Andrybak|andrybak]] ([[User talk:Andrybak|talk]]) 11:15, 29 August 2018 (UTC)
:
: {{Resolved|[[Wikipedia_talk:Lua/Archive_7#Template:Demo_demo_kill_categories_alias_nocat]] —&#8288;[[User:Andrybak|andrybak]] ([[User talk:Andrybak|talk]]) 14:52, 3 September 2018 (UTC)}}


== Template-protected edit request on 22 March 2019 ==
--creates a frame object that cannot access any of the parent's args
--unless a table containing a list keys of not to inherit is provided
function disinherit(frame, onlyTheseKeys)
local parent = frame:getParent() or frame
local orphan = parent:newChild{}
orphan.getParent = parent.getParent --returns nil
orphan.args = {}
if onlyTheseKeys then
local family = {parent, frame}
for f = 1, 2 do
for k, v in pairs(family[f] and family[f].args or {}) do
orphan.args[k] = orphan.args[k] or v
end
end
parent.args = mw.clone(orphan.args)
setmetatable(orphan.args, nil)
for _, k in ipairs(onlyTheseKeys) do
rawset(orphan.args, k, nil)
end
end
return orphan, parent
end


{{edit template-protected|Template:Demo|answered=yes}}
function getSeparator(args, default)
Please '''remove''' the line <code><nowiki><noinclude>{{pp-template|small=yes}}</noinclude></nowiki></code> - protection templates are automatically handled by the documentation page. Thanks, --[[User:DannyS712|DannyS712]] ([[User talk:DannyS712|talk]]) 06:39, 22 March 2019 (UTC)
local br = tonumber(args.br) and ('<br>'):rep(args.br) or args.br
:[[File:Yes check.svg|20px|link=|alt=]] '''Done'''<!-- Template:ETp --> —&thinsp;[[User:JJMC89|JJMC89]]&thinsp;<small>([[User talk:JJMC89|T]]'''·'''[[Special:Contributions/JJMC89|C]])</small> 06:54, 22 March 2019 (UTC)
local sep = args.sep or br or default
return #sep > 0 and ' ' .. sep .. ' ' or sep
end


== Syntax highlighting ==
function p.get(frame, arg, passArgs)
Please incorporate a parameter to enable syntax highlighting of the preformatted text with <nowiki><syntaxhighlight lang="{wikitext|html|etc.}"></nowiki>. I've attempted to develop this in the sandbox, without success. —[[User:Swpb|<u>swpb</u>]]<sup>[[User talk:Swpb|T]]&#8201;•&#8201;[[WP:BEYOND|beyond]]&#8201;&#8201;[[WP:MUTUAL|mutual]]</sup> 13:55, 11 May 2023 (UTC)
local orphan, frame = disinherit(frame, passArgs and {arg or 1})
:I believe the syntax should be highlighted by default. Why not? <code>wikitext</code> is a good default that would work with HTML as well. BTW, do we even need <code>html</code> as a parameter? [[User:JWBTH|Jack who built the house]] ([[User:JWBTH|talk]]) 08:40, 20 July 2023 (UTC)
local code = frame.args[arg or 1] or ''
:So, I've managed to get the code in the sandbox to work. The resulting look is a bit different from {{tag|pre}}: you can't set <code>display: inline</code> to {{tag|syntaxhighlight}}, as suggested in [[Template:Demo]]. Also, if used without {{tag|nowiki}}, the templates are replaced with their code, but the code is still treated as code. Compare {{#tag:syntaxhighlight|{{fail}}|lang=wikitext}} and <pre>{{fail}}</pre>. This result is kind of better than with {{tag|pre}}: when there are no templates inside, {{tag|nowiki}} can be omitted (but people might forget that they haven't used {{tag|nowiki}} and use a template which will expand). [[User:JWBTH|Jack who built the house]] ([[User:JWBTH|talk]]) 19:52, 20 July 2023 (UTC)
if code:match'UNIQ%-%-nowiki' then
{{editProtected|answered=yes}}
code = mw.text.unstripNoWiki(code)
:Please update [[Module:Demo]] from [[Module:Demo/sandbox]]. Test cases: [[Template:Demo/testcases]]. Ping the OP: @[[User:Swpb|Swpb]]. [[User:JWBTH|Jack who built the house]] ([[User:JWBTH|talk]]) 15:07, 21 July 2023 (UTC)
:gsub('&lt;', '<')
:: {{done}} Sidenote to {{u|JWBTH}}, your signature is messed up and should be fixed. [[User:Pppery|* Pppery *]] [[User talk:Pppery|<sub style="color:#800000">it has begun...</sub>]] 21:09, 22 July 2023 (UTC)
:gsub('&gt;', '>')
:::Haha, thanks! Forgot to check a checkbox. I don't even see my signature due to a [[c:User:JWBTH/CD|script]], and the author username was displayed correctly :) [[User:JWBTH|Jack who built the house]] ([[User:JWBTH|talk]]) 00:18, 23 July 2023 (UTC)
:gsub('&quot;', '"')
-- Replace `&#125;%-` with `}-` because of some server quirk leading to
-- =mw.text.unstripNoWiki(mw.getCurrentFrame():preprocess('<nowiki>}-</nowiki>'))
-- outputting `&#125;-` instead of `}-`, while it's ok with `<nowiki>} -</nowiki>`
:gsub('&#125;%-', '}-')
-- The same with `-&#123;`
:gsub('%-&#123;', '-{')
end
local kill_categories = frame.args.demo_kill_categories or frame.args.nocat
return {
source = code,
output = orphan:preprocess(code):gsub(kill_categories and '%[%[Category.-%]%]' or '', ''),
frame = frame
}
end


== Changes announcement ==
function p.main(frame, demoTable)
local show = demoTable or p.get(frame)
local args = show.frame.args
if show[args.result_arg] then
return show[args.result_arg]
end
local yesno = require('Module:Yesno')
args.reverse = yesno(args.reverse, false)
args.sep = getSeparator(args, '')
local source = frame:extensionTag{
name = 'syntaxhighlight',
args = {
lang = 'wikitext',
style = args.style
},
content = show.source
}
return args.reverse and
show.output .. args.sep .. source or
source .. args.sep .. show.output
end


I'm to make an edit to the module with several notable changes that you can see [https://en.wikipedia.org/w/index.php?title=Module:Demo/sandbox&diff=1166998268&oldid=1166318175 here] or in the [[Template:Demo/testcases|test cases]]:
-- Alternate function to return an inline result
* HTML tags in the code snippet will work (they don't now). So, the template will be able to be used to show demonstrations of any code, not necessarily of templates.
function p.inline(frame, demoTable)
* Markup that must be at the start of the line (like <code>*</code>, <code>{|</code>) will work. It doesn't work for the first line now.
local show = demoTable or p.get(frame)
* There will be {{para|reverse|1}} parameter to show the code snippet and the result in reverse order.
local args = show.frame.args
* There will be no {{tag|br|o}} after the code snippet by default, because it creates nonfunctional empty space. Many [https://en.wikipedia.org/w/index.php?search=hastemplate%3Ademo+insource%3A%2F%5C%7B%5C%7B%5BdD%5Demo%2F+insource%3A%2Fbr+%2A%3D+%2A%5B0%7C%5D%2F+prefix%3Atemplate%3A&title=Special:Search&profile=advanced&fulltext=1&ns0=1 usages] of the template try to remove that space. I haven't witnessed cases where it was justified.
if show[args.result_arg] then
* {{para|br}} will be renamed to {{para|sep}}, from "separator" ({{para|br}} will still work) because the more popular usage of the parameter is to add some meaningful text between the snippet and the result, not just line breaks.
return show[args.result_arg]
[[User:JWBTH|Jack who built the house]] ([[User:JWBTH|talk]]) 22:11, 26 July 2023 (UTC)
end
local yesno = require('Module:Yesno')
args.reverse = yesno(args.reverse, false)
args.sep = getSeparator(args, args.reverse and '←' or '→')
local source =  frame:extensionTag{
name = 'syntaxhighlight',
args = {
lang = 'wikitext',
inline = true,
style = args.style
},
content = show.source
}
return args.reverse and
show.output .. args.sep .. source or
source .. args.sep .. show.output
end
 
--passing of args into other module without preprocessing
function p.module(frame)
local orphan, frame = disinherit(frame, {
'demo_template',
'demo_module',
'demo_module_func',
'demo_main',
'demo_sep',
'demo_br',
'demo_result_arg',
'demo_kill_categories',
'nocat'
})
local template = frame.args.demo_template and 'Template:'..frame.args.demo_template
local demoFunc = frame.args.demo_module_func or 'main\n'
local demoModule = require('Module:' .. frame.args.demo_module)[demoFunc:match('^%s*(.-)%s*$')]
frame.args.br, frame.args.result_arg = frame.args.demo_sep or frame.args.demo_br, frame.args.demo_result_arg
local kill_categories = frame.args.demo_kill_categories or frame.args.nocat
if demoModule then
local named = {insert = function(self, ...) table.insert(self, ...) return self end}
local source = {insert = named.insert, '{{', frame.args.demo_template or frame.args.demo_module, '\n'}
if not template then
source:insert(2, '#invoke:'):insert(4, '|'):insert(5, demoFunc)
end
local insertNamed = #source + 1
for k, v in pairs(orphan.args) do
local nan, insert = type(k) ~= 'number', {v}
local target = nan and named or source
target:insert'|'
if nan then
target:insert(k):insert'=':insert'\n'
table.insert(insert, 1, #target)
end
target:insert(unpack(insert))
local nowiki = v:match('nowiki')
if nowiki or v:match('{{.-}}') then
orphan.args[k] = frame:preprocess(nowiki and mw.text.unstripNoWiki(v) or v)
end
end
source:insert'}}'
table.insert(source, insertNamed, table.concat(named))
return p.main(orphan, {
source = table.concat(source), "<>'|=~",
output = tostring(demoModule(orphan)):gsub(kill_categories and '%[%[Category.-%]%]' or '', ''),
frame = frame
})
else
return "ERROR: Invalid module function: "..demoFunc
end
end
 
return p

Revision as of 02:31, 14 August 2024

Template:Module rating

Usage

Usage via templates

This module supports Template:T

{{#invoke:Demo|main}}

and Template:T

{{#invoke:Demo|inline}}

The input must be wrapped in Template:Xtag tags or else it may be processed before the module can read it.

Usage in a module

If you want to use this in another module (such as to make the output prettier), you can get values like so:

require('Module:demo').get(frame)

Function Template:Code returns a table containing:

  • source = the source code (without Template:Xtag wrappers, characters substituted with html entities)
  • output = the execution result of the source.
  • frame = the frame from which this template took the parameter.

By default, Template:Code takes the first parameter of frame. If the frame uses a different parameter name for the nowiki-wrapped source, then place that name (as a string) as the second parameter, like so Template:Code

Example:

local p = {}

function p.main(frame)
	local parts = require('Module:demo').get(frame)
	return '…Pretty HTML… <pre>' .. parts.source .. '</pre> …More pretty HTML… ' .. parts.output .. ' …Even more pretty HTML…'
end

return p

See also



local p = {}

--creates a frame object that cannot access any of the parent's args
--unless a table containing a list keys of not to inherit is provided
function disinherit(frame, onlyTheseKeys)
	local parent = frame:getParent() or frame
	local orphan = parent:newChild{}
	orphan.getParent = parent.getParent --returns nil
	orphan.args = {}
	if onlyTheseKeys then
		local family = {parent, frame}
		for f = 1, 2 do
			for k, v in pairs(family[f] and family[f].args or {}) do
				orphan.args[k] = orphan.args[k] or v
			end
		end
		parent.args = mw.clone(orphan.args)
		setmetatable(orphan.args, nil)
		for _, k in ipairs(onlyTheseKeys) do
			rawset(orphan.args, k, nil)
		end
	end
	return orphan, parent
end

function getSeparator(args, default)
	local br = tonumber(args.br) and ('<br>'):rep(args.br) or args.br
	local sep = args.sep or br or default
	return #sep > 0 and ' ' .. sep .. ' ' or sep
end

function p.get(frame, arg, passArgs)
	local orphan, frame = disinherit(frame, passArgs and {arg or 1})
	local code = frame.args[arg or 1] or ''
	if code:match'UNIQ%-%-nowiki' then
		code = mw.text.unstripNoWiki(code)
			:gsub('&lt;', '<')
			:gsub('&gt;', '>')
			:gsub('&quot;', '"')
			-- Replace `&#125;%-` with `}-` because of some server quirk leading to
			-- =mw.text.unstripNoWiki(mw.getCurrentFrame():preprocess('<nowiki>}-</nowiki>'))
			-- outputting `&#125;-` instead of `}-`, while it's ok with `<nowiki>} -</nowiki>`
			:gsub('&#125;%-', '}-')
			-- The same with `-&#123;`
			:gsub('%-&#123;', '-{')
	end
	local kill_categories = frame.args.demo_kill_categories or frame.args.nocat
	return {
		source = code,
		output = orphan:preprocess(code):gsub(kill_categories and '%[%[Category.-%]%]' or '', ''),
		frame = frame
	}
end

function p.main(frame, demoTable)
	local show = demoTable or p.get(frame)
	local args = show.frame.args
	if show[args.result_arg] then
		return show[args.result_arg]
	end
	local yesno = require('Module:Yesno')
	args.reverse = yesno(args.reverse, false)
	args.sep = getSeparator(args, '')
	local source = frame:extensionTag{
		name = 'syntaxhighlight',
		args = {
			lang = 'wikitext',
			style = args.style
		},
		content = show.source
	}
	return args.reverse and
		show.output .. args.sep .. source or
		source .. args.sep .. show.output
end

-- Alternate function to return an inline result
function p.inline(frame, demoTable)
	local show = demoTable or p.get(frame)
	local args = show.frame.args
	if show[args.result_arg] then
		return show[args.result_arg]
	end
	local yesno = require('Module:Yesno')
	args.reverse = yesno(args.reverse, false)
	args.sep = getSeparator(args, args.reverse and '←' or '→')
	local source =  frame:extensionTag{
		name = 'syntaxhighlight',
		args = {
			lang = 'wikitext',
			inline = true,
			style = args.style
		},
		content = show.source
	}
	return args.reverse and
		show.output .. args.sep .. source or
		source .. args.sep .. show.output
end

--passing of args into other module without preprocessing
function p.module(frame)
	local orphan, frame = disinherit(frame, {
		'demo_template',
		'demo_module',
		'demo_module_func',
		'demo_main',
		'demo_sep',
		'demo_br',
		'demo_result_arg',
		'demo_kill_categories',
		'nocat'
	})
	local template = frame.args.demo_template and 'Template:'..frame.args.demo_template
	local demoFunc = frame.args.demo_module_func or 'main\n'
	local demoModule = require('Module:' .. frame.args.demo_module)[demoFunc:match('^%s*(.-)%s*$')]
	frame.args.br, frame.args.result_arg = frame.args.demo_sep or frame.args.demo_br, frame.args.demo_result_arg
	local kill_categories = frame.args.demo_kill_categories or frame.args.nocat
	if demoModule then
		local named = {insert = function(self, ...) table.insert(self, ...) return self end}
		local source = {insert = named.insert, '{{', frame.args.demo_template or frame.args.demo_module, '\n'}
		if not template then
			source:insert(2, '#invoke:'):insert(4, '|'):insert(5, demoFunc)
		end
		local insertNamed = #source + 1
		for k, v in pairs(orphan.args) do
			local nan, insert = type(k) ~= 'number', {v}
			local target = nan and named or source
			target:insert'|'
			if nan then
				target:insert(k):insert'=':insert'\n'
				table.insert(insert, 1, #target)
			end
			target:insert(unpack(insert))
			local nowiki = v:match('nowiki')
			if nowiki or v:match('{{.-}}') then
				orphan.args[k] = frame:preprocess(nowiki and mw.text.unstripNoWiki(v) or v)
			end
		end
		source:insert'}}'
		table.insert(source, insertNamed, table.concat(named))
		return p.main(orphan, {
			source = table.concat(source), "<>'|=~",
			output = tostring(demoModule(orphan)):gsub(kill_categories and '%[%[Category.-%]%]' or '', ''),
			frame = frame
		})
	else
		return "ERROR: Invalid module function: "..demoFunc
	end
end

return p