Returns: a converted tagged string
           param: string (contains html tags)

           Don't replace characters inside tags
336770
def convert(self, string):
        
        (string, tags) = self.detag_string(string)
        string = self.inner_convert_string(string)
        string = self.retag_string(string, tags)
        return string
1343578
def _label_to_tag(self, name, labels, scraper_config, tag_name=None):
        
        value = labels.get(name)
        if value:
            return self._format_tag(tag_name or name, value, scraper_config)
        else:
            return None
851122
def cleanup_string(string, strip: true)
      return '' if string.nil?
      raise ArgumentError, 'Expected a string or an object that implements #to_str' unless string.respond_to?(:to_str)

      strip_tags(string.to_str).tap do |s|
        s.gsub!(/\s+/, ' ')
        s.strip! if strip
      end
    end
1350288
def markdown_to_safe_html(markdown_string):
  
  warning = ''
  # Convert to utf-8 whenever we have a binary input.
  if isinstance(markdown_string, six.binary_type):
    markdown_string_decoded = markdown_string.decode('utf-8')
    # Remove null bytes and warn if there were any, since it probably means
    # we were given a bad encoding.
    markdown_string = markdown_string_decoded.replace(u'\x00', u'')
    num_null_bytes = len(markdown_string_decoded) - len(markdown_string)
    if num_null_bytes:
      warning = ('<!-- WARNING: discarded %d null bytes in markdown string '
                 'after UTF-8 decoding -->\n') % num_null_bytes

  string_html = markdown.markdown(
      markdown_string, extensions=['markdown.extensions.tables'])
  string_sanitized = bleach.clean(
      string_html, tags=_ALLOWED_TAGS, attributes=_ALLOWED_ATTRIBUTES)
  return warning + string_sanitized
480859
def _fix_tagging(value, params):
    

    _tag_type_to_explicit_implicit(params)

    retag = False
    if 'implicit' not in params:
        if value.implicit is not False:
            retag = True
    else:
        if isinstance(params['implicit'], tuple):
            class_, tag = params['implicit']
        else:
            tag = params['implicit']
            class_ = 'context'
        if value.implicit is False:
            retag = True
        elif value.class_ != CLASS_NAME_TO_NUM_MAP[class_] or value.tag != tag:
            retag = True

    if params.get('explicit') != value.explicit:
        retag = True

    if retag:
        return value.retag(params)
    return value
312744
def remove_tag(tag_name, string):
    
    if not string:
        return string
    pattern = re.compile('</?' + tag_name + '.*?>')
    string = pattern.sub('', string)
    return string
291175
def html_encode(text):
    
    text = text.replace('&', '&amp;')
    text = text.replace('<', '&lt;')
    text = text.replace('>', '&gt;')
    text = text.replace('"', '&quot;')
    return text
646295
def strip_tags(string)
      if defined?(Loofah)
        # Instead of strip_tags we will use Loofah to strip tags from now on
        Loofah.fragment(string).text(encode_special_chars: false)
      else
        helpers.strip_tags(string)
      end
    end
282949
def format_html(format_string, *args, **kwargs):
    
    args_safe = map(conditional_escape, args)
    kwargs_safe = dict([(k, conditional_escape(v)) for (k, v) in
                        six.iteritems(kwargs)])
    return mark_safe(format_string.format(*args_safe, **kwargs_safe))
842273
def selection_text=(str)
      from = [@text_input.selection_start, @text_input.caret_pos].min
      to = [@text_input.selection_start, @text_input.caret_pos].max
      new_length = str.length

      full_text = text
      tags_length_before = (0...from).inject(0) {|m, i| m + @tags[i].length }
      tags_length_inside = (from...to).inject(0) {|m, i| m + @tags[i].length }
      range = (selection_range.first + tags_length_before)...(selection_range.last + tags_length_before + tags_length_inside)
      full_text[range] = str.encode('UTF-8', undef: :replace)
      @text_input.text = full_text

      @text_input.selection_start = @text_input.caret_pos = from + new_length

      recalc # This may roll back the text if it is too long!

      publish :changed, self.text

      str
    end
329119
def safe_tag(self, tag, errors='strict'):
        
        if tag is not None:
            try:
                # handle unicode characters and url encode tag value
                tag = quote(self.s(tag, errors=errors), safe='~')[:128]
            except KeyError as e:
                warn = 'Failed converting tag to safetag ({})'.format(e)
                self.log.warning(warn)
        return tag
697640
def raw_tag(name, value):
    """"""
    return name.encode('utf-8') + \
        len(value).to_bytes(4, byteorder='big') + \
        value
47173
def replace_simple_tags(s, from_tag='italic', to_tag='i', to_open_tag=None):
    
    if to_open_tag:
        s = s.replace('<' + from_tag + '>', to_open_tag)
    elif to_tag:
        s = s.replace('<' + from_tag + '>', '<' + to_tag + '>')
        s = s.replace('<' + from_tag + '/>', '<' + to_tag + '/>')
    else:
        s = s.replace('<' + from_tag + '>', '')
        s = s.replace('<' + from_tag + '/>', '')

    if to_tag:
        s = s.replace('</' + from_tag + '>', '</' + to_tag + '>')
    else:
        s = s.replace('</' + from_tag + '>', '')

    return s
601055
def _from_docstring_md(doc):
    

    def format_fn(line, status):
        """ format function """

        def fix_tags(line):
            # In markdown we need to escape < > and & for display
            # but we don't want to do this is the value is quoted
            # by backticks ``

            def fn(match):
                # swap matched chars
                found = match.group(1)
                if found == "<":
                    return "&lt;"
                if found == ">":
                    return "&gt;"
                if found == "&":
                    return "&amp;"
                return match.group(0)

            return re_from_tag.sub(fn, line)

        if re_from_data.match(line):
            line = re_from_data.sub(r"**\1** ", line)
            status["add_line"] = True
        line = re_from_defaults.sub(r"*\1*", line)
        if status["listing"]:
            # parameters
            if re_from_param.match(line):
                m = re_from_param.match(line)
                line = "  - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
            # status items
            elif re_from_status.match(line):
                m = re_from_status.match(line)
                line = "  - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
            # bullets
            elif re_from_item.match(line):
                line = re_from_item.sub(r"  -", fix_tags(line))
            # is continuation line
            else:
                line = fix_tags(line)
                line = " " * 4 + line.lstrip()
        else:
            line = fix_tags(line)
        return line

    return _reformat_docstring(doc, format_fn, code_newline="\n")
873860
def to_raw
      tag_data = tags.map do |tag|
        case tag
        when Tags::OverloadTag
          tag_text = "@#{tag.tag_name} #{tag.signature}\n"
          unless tag.docstring.blank?
            tag_text += "\n  " + tag.docstring.all.gsub(/\r?\n/, "\n  ")
          end
        when Tags::OptionTag
          tag_text = "@#{tag.tag_name} #{tag.name}"
          tag_text += ' [' + tag.pair.types.join(', ') + ']' if tag.pair.types
          tag_text += ' ' + tag.pair.name.to_s if tag.pair.name
          tag_text += "\n " if tag.name && tag.text
          tag_text += ' (' + tag.pair.defaults.join(', ') + ')' if tag.pair.defaults
          tag_text += " " + tag.pair.text.strip.gsub(/\n/, "\n  ") if tag.pair.text
        else
          tag_text = '@' + tag.tag_name
          tag_text += ' [' + tag.types.join(', ') + ']' if tag.types
          tag_text += ' ' + tag.name.to_s if tag.name
          tag_text += "\n " if tag.name && tag.text
          tag_text += ' ' + tag.text.strip.gsub(/\n/, "\n  ") if tag.text
        end
        tag_text
      end
      [strip, tag_data.join("\n")].reject(&:empty?).compact.join("\n")
    end
764128
def encoding(self) -> _Encoding:
        
        if self._encoding:
            return self._encoding

        # Scan meta tags for charset.
        if self._html:
            self._encoding = html_to_unicode(self.default_encoding, self._html)[0]
            # Fall back to requests' detected encoding if decode fails.
            try:
                self.raw_html.decode(self.encoding, errors='replace')
            except UnicodeDecodeError:
                self._encoding = self.default_encoding


        return self._encoding if self._encoding else self.default_encoding
1132913
def replace_tags(string, from_tag='i', to_tag='italic'):
    
    string = string.replace('<' + from_tag + '>', '<' + to_tag + '>')
    string = string.replace('</' + from_tag + '>', '</' + to_tag + '>')
    return string