Define a grammar for common HTML reserved chars. Those are characters like <, >, and & that should be be replaced by an HTML entity to be displayed correctly.
320633
function CreateHtmlReservedCharsGrammar(myna) 
{
    let m = myna;
    
    let g = new function() 
    {
        let escapeChars = '&<>"\'';        
        this.specialChar = m.char(escapeChars).ast;
        this.plainText = m.notChar(escapeChars).oneOrMore.ast;
        this.text = m.choice(this.specialChar, this.plainText).zeroOrMore;
    }

    // Register the grammar, providing a name and the default parse rule
    return m.registerGrammar('html_reserved_chars', g, g.text);
}
479623
def html_to_text(html, base_url='', bodywidth=CONFIG_DEFAULT):
    
    def _patched_handle_charref(c):
        self = h
        charref = self.charref(c)
        if self.code or self.pre:
            charref = cgi.escape(charref)
        self.o(charref, 1)

    def _patched_handle_entityref(c):
        self = h
        entityref = self.entityref(c)
        if self.code or self.pre:  # this expression was inversed.
            entityref = cgi.escape(entityref)
        self.o(entityref, 1)

    h = HTML2Text(baseurl=base_url, bodywidth=config.BODY_WIDTH if bodywidth is CONFIG_DEFAULT else bodywidth)
    h.handle_entityref = _patched_handle_entityref
    h.handle_charref = _patched_handle_charref
    return h.handle(html).rstrip()
179079
function encodeEntities(value) {
  return value.
    replace(/&/g, '&amp;').
    replace(NON_ALPHANUMERIC_REGEXP, function(value){
      return '&#' + value.charCodeAt(0) + ';';
    }).
    replace(/</g, '&lt;').
    replace(/>/g, '&gt;');
}
408454
@Override
    public void characters(char[] ch, int start, int length) throws SAXException {

        // <param-name>
        if (elements("web-app", "context-param", "param-name")) {
            currentName = String.valueOf(ch, start, length).trim();
        }

        // <param-value>
        if (elements("web-app", "context-param", "param-value")) {
            currentValue = String.valueOf(ch, start, length).trim();
        }

    }
1158489
public Response andCharset(String charset) {
        Objects.requireNonNull(charset, Required.CHARSET.toString());
        this.charset = charset;

        return this;
    }
1155366
def html_entity_decode_char(self, m, defs=htmlentities.entitydefs):
        
        try:
            char = defs[m.group(1)]
            return "&{char};".format(char=char)
        except ValueError:
            return m.group(0)
        except KeyError:
            return m.group(0)
932269
static String jsRegExpToJavaRegExp(String re) {
		re = re.replaceAll("\\[\\^\\\\\\d\\]", ".");
		re = re.replaceAll("\\[([^\\]]*)\\\\b([^\\]]*)\\]", "[$1\\\\cH$2]"); // [...\b...]
																				// ->
																				// [...\cH...]
		re = re.replaceAll("(?<!\\\\)\\[([^((?<!\\\\)\\[)\\]]*)\\[", "[$1\\\\["); // [...[...]
																					// ->
																					// [...\[...]

		// back reference in character classes are simply ignored by browsers
		re = re.replaceAll("(?<!\\\\)\\[([^\\]]*)(?<!\\\\)\\\\\\d", "[$1"); // [...ab\5cd...]
																			// ->
																			// [...abcd...]

		// characters escaped without need should be "un-escaped"
		re = re.replaceAll("(?<!\\\\)\\\\([ACE-RT-VX-Zaeg-mpqyz])", "$1");

		re = escapeJSCurly(re);
		return re;
	}
761590
function htmlParser(html, handler) {
  if (typeof html !== 'string') {
    if (html === null || typeof html === 'undefined') {
      html = '';
    } else {
      html = '' + html;
    }
  }
  var index, chars, match, stack = [],
    last = html,
    text;
  stack.last = function () {
    return stack[stack.length - 1];
  };

  while (html) {
    text = '';
    chars = true;

    // Make sure we're not in a script or style element
    if (!stack.last() || !specialElements[stack.last()]) {

      // Comment
      if (html.indexOf("<!--") === 0) {
        // comments containing -- are not allowed unless they terminate the comment
        index = html.indexOf("--", 4);

        if (index >= 0 && html.lastIndexOf("-->", index) === index) {
          if (handler.comment) handler.comment(html.substring(4, index));
          html = html.substring(index + 3);
          chars = false;
        }
        // DOCTYPE
      } else if (DOCTYPE_REGEXP.test(html)) {
        match = html.match(DOCTYPE_REGEXP);

        if (match) {
          html = html.replace(match[0], '');
          chars = false;
        }
        // end tag
      } else if (BEGING_END_TAGE_REGEXP.test(html)) {
        match = html.match(END_TAG_REGEXP);

        if (match) {
          html = html.substring(match[0].length);
          match[0].replace(END_TAG_REGEXP, parseEndTag);
          chars = false;
        }

        // start tag
      } else if (BEGIN_TAG_REGEXP.test(html)) {
        match = html.match(START_TAG_REGEXP);

        if (match) {
          // We only have a valid start-tag if there is a '>'.
          if (match[4]) {
            html = html.substring(match[0].length);
            match[0].replace(START_TAG_REGEXP, parseStartTag);
          }
          chars = false;
        } else {
          // no ending tag found --- this piece should be encoded as an entity.
          text += '<';
          html = html.substring(1);
        }
      }

      if (chars) {
        index = html.indexOf("<");

        text += index < 0 ? html : html.substring(0, index);
        html = index < 0 ? "" : html.substring(index);

        if (handler.chars) handler.chars(decodeEntities(text));
      }

    } else {
      // IE versions 9 and 10 do not understand the regex '[^]', so using a workaround with [\W\w].
      html = html.replace(new RegExp("([\\W\\w]*)<\\s*\\/\\s*" + stack.last() + "[^>]*>", 'i'),
        function (all, text) {
          text = text.replace(COMMENT_REGEXP, "$1").replace(CDATA_REGEXP, "$1");

          if (handler.chars) handler.chars(decodeEntities(text));

          return "";
        });

      parseEndTag("", stack.last());
    }

    if (html == last) {
      // benweet
      // throw $sanitizeMinErr('badparse', "The sanitizer was unable to parse the following block " +
      // 	"of html: {0}", html);
      stack.reverse();
      return stack.cl_each(function (tag) {
        buf.push('</');
        buf.push(tag);
        buf.push('>');
      });
    }
    last = html;
  }

  // Clean up any remaining tags
  parseEndTag();

  function parseStartTag(tag, tagName, rest, unary) {
    tagName = tagName && tagName.toLowerCase();
    if (blockElements[tagName]) {
      while (stack.last() && inlineElements[stack.last()]) {
        parseEndTag("", stack.last());
      }
    }

    if (optionalEndTagElements[tagName] && stack.last() == tagName) {
      parseEndTag("", tagName);
    }

    unary = voidElements[tagName] || !!unary;

    if (!unary) {
      stack.push(tagName);
    }

    var attrs = {};

    rest.replace(ATTR_REGEXP,
      function (match, name, doubleQuotedValue, singleQuotedValue, unquotedValue) {
        var value = doubleQuotedValue || singleQuotedValue || unquotedValue || '';

        attrs[name] = decodeEntities(value);
      });
    if (handler.start) handler.start(tagName, attrs, unary);
  }

  function parseEndTag(tag, tagName) {
    var pos = 0,
      i;
    tagName = tagName && tagName.toLowerCase();
    if (tagName) {
      // Find the closest opened tag of the same type
      for (pos = stack.length - 1; pos >= 0; pos--) {
        if (stack[pos] == tagName) break;
      }
    }

    if (pos >= 0) {
      // Close all the open elements, up the stack
      for (i = stack.length - 1; i >= pos; i--)
        if (handler.end) handler.end(stack[i]);

      // Remove the open elements from the stack
      stack.length = pos;
    }
  }
}
1338118
def characters(self, chars):
        
        self._finish_pending_start_element()
        if not is_valid_cdata_str(chars):
            raise ValueError("control characters are not allowed in "
                             "well-formed XML")
        self._write(xml.sax.saxutils.escape(
            chars,
            self._additional_escapes,
        ).encode("utf-8"))
892298
function parseCharset(charset /*:String*/) {
  charset=charset.split('');
  var chars=[],ranges=[],
      exclude = charset[0]==='^' && charset.length > 1 && charset.shift();
  charset.forEach(function (c) {
    if (chars[0]=='-' && chars.length>1) {//chars=['-','a'],c=='z'
      if (chars[1] > c ) // z-a  is invalid
        throw new Error('Charset range out of order:'+chars[1]+'-'+c+'!');
      ranges.push(chars[1]+c);
      chars.splice(0,2);
    } else chars.unshift(c);
  });
  ranges=ranges.concat(chars);
  //convert exclude to include
  return exclude?negate(ranges):classify(ranges).ranges;
}
872565
def escape_html(text):
    
    text = text.replace('&', '&amp;')
    text = text.replace('<', '&lt;')
    text = text.replace('>', '&gt;')
    text = text.replace('"', '&quot;')
    return text
403340
def _allowed_char(c):
    
    c = ord(c)
    if c < 0:
        return False
    if c < 128:
        return _ascii_allowed[c]
    # Genereally allow unicodes, TODO: check for unicode control characters
    # characters
    return True
885326
function () {
                    var str, j = i, e;

                    if (input.charAt(j) === '~') { j++, e = true } // Escaped strings
                    if (input.charAt(j) !== '`') { return }

                    e && $('~');

                    if (str = $(/^`([^`]*)`/)) {
                        return new(tree.JavaScript)(str[1], i, e);
                    }
                }
411112
def convert_reserved_characters(string)
    string.gsub!(/&quot;/, '\"')
    string.gsub!(/&apos;/, '\'')
    string.gsub!(/&amp;/,  '\&')
    string.gsub!(/&lt;/,   '\<')
    string.gsub!(/&lt;/,   '\>')
    string
  end
555285
private String escapeHtml(String html) {
    if (html == null) {
      return null;
    }
    return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(
        ">", "&gt;");
  }
87341
def replace_entities(self, html):
        
        def fixup(text):
            """replace the htmlentities in some text"""
            text = text.group(0)
            if text[:2] == "&#":
                # character reference
                try:
                    if text[:3] == "&#x":
                        return chr(int(text[3:-1], 16))
                    else:
                        return chr(int(text[2:-1]))
                except ValueError:
                    pass
            else:
                # named entity
                try:
                    text = chr(htmlentitydefs.name2codepoint[text[1:-1]])
                except KeyError:
                    pass
            return text  # leave as is
        return re.sub(r"&#?\w+;", fixup, html)
167142
def characters
      return non_excerpted_text if @charcount < @settings[:characters]
      html_count = char_count = 0
      tags_entities = /#{Regexp.union(/(<[a-z0-9]{1,}\b[^>]*>)/,/(<\/[a-z0-9]{1,}>)/,/(&[^\s]*;)/)}/io
      @body.split(tags_entities).each do |piece|
        if piece =~ tags_entities
          html_count += piece.length
        else
          chars_left = @settings[:characters] - char_count
          # NOTE Do I want to count spaces or not?
          piece.split(/\b/).each{|p|
            break if (char_count >= @settings[:characters])
            char_count += p.length
          }
        end
        break if (char_count >= @settings[:characters])
      end 
      text = clean(@body[0...(html_count+char_count)])
      close_tags(text)
    end