'Encode special characters in ``text`` and return it.
If attval is true, preserve as much as possible verbatim (used
in attribute value encoding).  If attval is \'width\' or
\'height\', `text` is interpreted as a length value.'

def encode(self, text, attval=None):

    if (attval in ('width', 'height')):
        match = re.match('([0-9.]+)(\\S*)$', text)
        assert match, ('%s="%s"    must    be    a    length' % (attval, text))
        (value, unit) = match.groups()
        if (unit == '%'):
            value = str((float(value) / 100))
            unit = '\\DECrelativeunit'
        elif (unit in ('', 'px')):
            value = str((float(value) * 0.75))
            unit = '\\DECpixelunit'
        return ('%s%s' % (value, unit))
    if attval:
        get = self.att_map.get
    else:
        get = self.character_map.get
    text = ''.join([get(c, c) for c in text])
    if ((self.literal_block or self.inline_literal) and (not attval)):
        text = text.replace('\r\n', '\n')
        if self.literal_block:
            text = text.replace('\n', '\\mbox{}\\\\{}')
            replace_fn = self.encode_replace_for_literal_block_spaces
        else:
            replace_fn = self.encode_replace_for_inline_literal_spaces
        text = re.sub('\\s+', replace_fn, text)
        text = text.replace('-', '\\mbox{-}')
        text = text.replace("'", '{\\DECtextliteralsinglequote}')
        return text
    elif (not attval):
        text = re.sub('\\s+', '{    }', text)
        L = []
        for part in text.split(self.character_map['"']):
            if L:
                L.append(((self.left_quote and '{\\DECtextleftdblquote}') or '{\\DECtextrightdblquote}'))
                self.left_quote = (not self.left_quote)
            L.append(part)
        return ''.join(L)
    else:
        return text
