Enclose ANSI/SGR escape sequences with ANSI_START and ANSI_END.
966559
def EncloseAnsiText(text):
  """"""
  return sgr_re.sub(lambda x: ANSI_START + x.group(1) + ANSI_END, text)
276526
def _sequence(self, i):
        """"""

        result = ['[']
        end_range = 0
        escape_hyphen = -1
        removed = False
        last_posix = False

        c = next(i)
        if c in ('!', '^'):
            # Handle negate char
            result.append('^')
            c = next(i)
        if c == '[':
            last_posix = self._handle_posix(i, result, 0)
            if not last_posix:
                result.append(re.escape(c))
            c = next(i)
        elif c in ('-', ']'):
            result.append(re.escape(c))
            c = next(i)

        while c != ']':
            if c == '-':
                if last_posix:
                    result.append('\\' + c)
                    last_posix = False
                elif i.index - 1 > escape_hyphen:
                    # Found a range delimiter.
                    # Mark the next two characters as needing to be escaped if hyphens.
                    # The next character would be the end char range (s-e),
                    # and the one after that would be the potential start char range
                    # of a new range (s-es-e), so neither can be legitimate range delimiters.
                    result.append(c)
                    escape_hyphen = i.index + 1
                    end_range = i.index
                elif end_range and i.index - 1 >= end_range:
                    if self._sequence_range_check(result, '\\' + c):
                        removed = True
                    end_range = 0
                else:
                    result.append('\\' + c)
                c = next(i)
                continue
            last_posix = False

            if c == '[':
                last_posix = self._handle_posix(i, result, end_range)
                if last_posix:
                    c = next(i)
                    continue

            if c == '\\':
                # Handle escapes
                subindex = i.index
                try:
                    value = self._references(i, True)
                except PathNameException:
                    raise StopIteration
                except StopIteration:
                    i.rewind(i.index - subindex)
                    value = r'\\'
            elif c == '/':
                if self.pathname:
                    raise StopIteration
                value = c
            elif c in SET_OPERATORS:
                # Escape &, |, and ~ to avoid &&, ||, and ~~
                value = '\\' + c
            else:
                # Anything else
                value = c

            if end_range and i.index - 1 >= end_range:
                if self._sequence_range_check(result, value):
                    removed = True
                end_range = 0
            else:
                result.append(value)

            c = next(i)

        result.append(']')
        # Bad range removed.
        if removed:
            value = "".join(result)
            if value == '[]':
                # We specified some ranges, but they are all
                # out of reach.  Create an impossible sequence to match.
                result = ['[^%s]' % ('\x00-\xff' if self.is_bytes else uniprops.UNICODE_RANGE)]
            elif value == '[^]':
                # We specified some range, but hey are all
                # out of reach. Since this is exclusive
                # that means we can match *anything*.
                result = ['[%s]' % ('\x00-\xff' if self.is_bytes else uniprops.UNICODE_RANGE)]
            else:
                result = [value]

        if self.pathname or self.after_start:
            return self._restrict_sequence() + ''.join(result)

        return ''.join(result)
1128136
def ansi(string, *args):
	

	ansi = ''

	for arg in args:
		arg = str(arg)
		if not re.match(ANSI_PATTERN, arg):
			raise ValueError('Additional arguments must be ansi strings')

		ansi += arg
	
	return ansi + string + colorama.Style.RESET_ALL
669727
function escapeCharacters(text, charsToEscape, afterBackslash) {

        var regexString = "([" + charsToEscape.replace(/([\[\]\\])/g,"\\$1") + "])";

        if(afterBackslash) {
            regexString = "\\\\" + regexString;
        }

        var regex = new RegExp(regexString,"g");

        text = text.replace(regex,escapeCharacters_callback);

        return text;
    }
935457
def shell_escape(s):
    
    """
    if isinstance(s, PosixPath):
        s = unicode_(s)
    elif isinstance(s, bytes):
        s = s.decode('utf-8')
    if not s or any(c not in safe_shell_chars for c in s):
        return '"%s"' % (s.replace('\\', '\\\\')
                          .replace('"', '\\"')
                          .replace('`', '\\`')
                          .replace('$', '\\$'))
    else:
        return s
209883
def trim(sequences, start, end):
    
    logging.info("Trimming from %d to %d", start, end)
    return (sequence[start:end] for sequence in sequences)
1245316
def _end_escape_sequence(self, char):
        

        num = ord(char)
        if num in self.sequence:
            self.dispatch(self.sequence[num], *self.params)
        self.state = "stream"
        self.current_param = ""
        self.params = []
527250
def supports_ansi_escape_codes(fd):
    

    if os.isatty(fd):
        return True

    if not is_win:
        return False

    # Check for cygwin/msys terminal
    handle = winapi._get_osfhandle(fd)
    if handle == winapi.INVALID_HANDLE_VALUE:
        return False

    if winapi.GetFileType(handle) != winapi.FILE_TYPE_PIPE:
        return False

    file_name = _get_file_name_for_handle(handle)
    match = re.match(
        "^\\\\(cygwin|msys)-[a-z0-9]+-pty[0-9]+-(from|to)-master$", file_name)
    return match is not None
1069779
function maskString(srcStr, mask, start, length) {
      var str = String(srcStr), ptn = /[^\u4e00-\u9fa5]/mg, ptn_ = /[\u4e00-\u9fa5]/mg;
      if (isNum(mask)) {
        length = start, start = mask, mask = '*';
      } else if (!isStr(mask)) {
        mask = '*';
      }
      var maskStr = str.substr(start, length).replace(ptn, mask).replace(ptn_, mask + mask);
      return str.substr(0, start) + maskStr + (isUdf(length) ? '' : str.substr(start + length));
    }
255419
def split_escape(string, sep, maxsplit=None, escape_char="\\"):
    

    assert len(sep) == 1
    assert len(escape_char) == 1

    if isinstance(string, bytes):
        if isinstance(escape_char, text_type):
            escape_char = escape_char.encode("ascii")
        iter_ = iterbytes
    else:
        iter_ = iter

    if maxsplit is None:
        maxsplit = len(string)

    empty = string[:0]
    result = []
    current = empty
    escaped = False
    for char in iter_(string):
        if escaped:
            if char != escape_char and char != sep:
                current += escape_char
            current += char
            escaped = False
        else:
            if char == escape_char:
                escaped = True
            elif char == sep and len(result) < maxsplit:
                result.append(current)
                current = empty
            else:
                current += char
    result.append(current)
    return result
753203
def _preprocess_sgm(line, is_sgm):
  """"""
  if not is_sgm:
    return line
  # In SGM files, remove <srcset ...>, <p>, <doc ...> lines.
  if line.startswith("<srcset") or line.startswith("</srcset"):
    return ""
  if line.startswith("<doc") or line.startswith("</doc"):
    return ""
  if line.startswith("<p>") or line.startswith("</p>"):
    return ""
  # Strip <seg> tags.
  line = line.strip()
  if line.startswith("<seg") and line.endswith("</seg>"):
    i = line.index(">")
    return line[i + 1:-6]
1358970
def add_regex_start_end(pattern_function):
    """"""

    @wraps(pattern_function)
    def func_wrapper(*args, **kwargs):
        return r'^{}$'.format(pattern_function(*args, **kwargs))
    return func_wrapper
742192
public void escape(Pointer _src, int len) {
        byte[] bsrc = _src.buffer;
        int src = _src.start;
        for(int i=0; i<len; i++) {
            int curr = (int)bsrc[src+i]&0xFF;

            if(curr < 0x20 || (0x7E < curr)) {
                write(BACKSLASH, 1);
                if(curr == 0) {
                    write(ZERO, 1);
                } else {
                    write(X, 1);
                    write(hex_table.withStart((curr & 0xF0) >> 4), 1);
                    write(hex_table.withStart(curr & 0x0F), 1);
                }
            } else {
                write(_src.withStart(src+i), 1);
                if(curr == '\\') {
                    write(BACKSLASH, 1);
                }
            }
        }
    }
148202
def escape_grouped_arguments(s):
    
    if s is None:
        return None

    # Additional escaping for windows paths
    if os.name == "nt":
        s = "{}".format(s.replace("\\", "\\\\"))
    return '"' + s.replace("'", "'\\''") + '"'
1225653
def ansi_split(text, _re=re.compile(u"(\x1b\\[(\\d*;?)*\\S)")):
    """"""

    for part in _re.split(text):
        if part:
            yield (bool(_re.match(part)), part)
699400
private String delRemChars(String pstrSrc)
    {
        int    intPos = 0;

        if (pstrSrc == null) return null;
        while ((intPos = pstrSrc.indexOf(";")) >= 0)
        {
            if (intPos == 0)
                pstrSrc = pstrSrc.substring(intPos + 1);
            else if (intPos > 0)
                pstrSrc = pstrSrc.substring(0, intPos) + pstrSrc.substring(intPos + 1);
        }
        return pstrSrc;
    }
125434
def _escape(self, s):
        
        for ch, r_ch in self.ESCAPE_SETS:
            s = s.replace(ch, r_ch)
        return s