--- Parses escape sequences into their fully qualified characters

function Util.ParseEscapeSequences(text)
	return text:gsub("\\(.)", {
		t = "\t";
		n = "\n";
	})
	:gsub("\\u(%x%x%x%x)", charCode)
	:gsub("\\x(%x%x)", charCode)
end

function Util.EncodeEscapedOperator(text, op)
	local first = op:sub(1, 1)
	local escapedOp = op:gsub(".", "%%%1")
	local escapedFirst = "%" .. first

	return text:gsub("(" .. escapedFirst .. "+)(" .. escapedOp .. ")", function(esc, op)
			return (esc:sub(1, #esc-1) .. op):gsub(".", function(char)
					return "\\u" .. string.format("%04x", string.byte(char), 16)
			end)
	end)
end

local OPERATORS = {"&&", "||", ";"}
function Util.EncodeEscapedOperators(text)
	for _, operator in ipairs(OPERATORS) do
		text = Util.EncodeEscapedOperator(text, operator)
	end

	return text
end

local function encodeControlChars(text)
	return (
		text
		:gsub("\\\\", "___!CMDR_ESCAPE!___")
		:gsub("\\\"", "___!CMDR_QUOTE!___")
		:gsub("\\'", "___!CMDR_SQUOTE!___")
		:gsub("\\\n", "___!CMDR_NL!___")
	)
end

local function decodeControlChars(text)
	return (
		text
		:gsub("___!CMDR_ESCAPE!___", "\\")
		:gsub("___!CMDR_QUOTE!___", "\"")
		:gsub("___!CMDR_NL!___", "\n")
	)
end
