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 20:26, 13 January 2015 (a module for custom char escaping). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.
(diff) ← Previous revision | Latest revision (diff) | Newer revision → (diff)

escape = {
	init = 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 self
	end,
	exec = function(self, text, pattern, newEscape)
		local target, v = self[self[1]]
		repeat v = text:match(target[pattern])
			text = v and
				text:gsub(
					pattern == 'text' and
						('%s%s'):format(target.char, v)
						or self[1]:format(v),
					pattern == '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(text, 'text')
	end,
	undo = function(self, text, newEscape)
		return self:exec(text, 'undo', newEscape)
	end
}

return escape:init('\\')