Jump to content

Module:Escape

Permanently protected module
From Wikipedia, the free encyclopedia
This is an old revision of this page, as edited by Codehydro (talk | contribs) at 13:37, 14 January 2015 (unnecessary dependency on module arguments). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

escape = {
	char = function(self, char, args)
		args = args or {}
		local safe = {
			args.front or string.char(24),
			args.back or string.char(27)
		}
		char = tostring(char)
		self[1] = ('%s%%s%s'):format(
			('%s%s%s'):format(safe[1], ('%x'):format(char:byte()), safe[1]),
			('%s%s'):format(safe[2], ('%x'):format(char:byte()))
		)
		if not self[self[1]] then
			self[self[1]] = {
				char = char,
				text = ('%s(.)'):format(char),
				undo = self[1]:format'(%d+)'
			}
		end
		return args.text and self:text(args.text)
			or args.undo and self:undo(args.undo, char)
			or args.kill and self:kill(args.kill)
			or self
	end,
	exec = function(self, text, mode, newEscape)
		local target, v = self[self[1]]
		repeat v = text:match(target[mode])
			text = v and
				text:gsub(
					mode == 'text' and
						('%s%s'):format(target.char, v)
						or self[1]:format(v),
					mode == 'text' and
						self[1]:format(v:byte())
						or (newEscape or '') .. v:char()
				)
				or text
		until not v
		return text
	end,
	text = function(self, text)
		return self:exec(type(text) == 'table' and text[1] or text, 'text')
	end,
	undo = function(self, text, newEscape)
		if type(text) == 'table' then
			text, newEscape = text[1], text[2] or newEscape
		end
		return self:exec(text, 'undo', newEscape)
	end,
	kill = function(self, text, chars, newEscape)
		if type(text) == 'table' then
			text, chars, newEscape = text[1], text[2] or chars, text[3] or newEscape
		end
		return self:undo(self:text(text):gsub(chars, ''), newEscape)
	end
}

function escape.main(frame)
	local args = frame.args
	return escape[args.mode](escape:char(args.char or '\\'), args)
end

return escape:char('\\')