def highlight_placeables(text): """Wrap placeables to easily distinguish and manipulate them.""" output = u"" # Get a flat list of placeables and StringElem instances. flat_items = parse_placeables(text, PLACEABLE_PARSERS).flatten() for item in flat_items: if isinstance(item, BasePlaceable): # It is a placeable, so highlight it. class_name = item.__class__.__name__ placeable = unicode(item) # String representation for placeable. # CSS class used to highlight the placeable. css_class = { 'PootleEscapePlaceable': "highlight-escape", 'PootleSpacesPlaceable': "translation-space", 'PootleTabEscapePlaceable': "highlight-escape", 'NewlinePlaceable': "highlight-escape", }.get(class_name, "placeable") # Some placeables require changing the representation in order to # correctly display them on the translation editor. def replace_whitespace(string): fancy_space = ' ' if string.startswith(' '): return fancy_space * len(string) return string[0] + fancy_space * (len(string) - 1) content = { 'PootleEscapePlaceable': u'\\\\', 'PootleTabEscapePlaceable': u'\\t', 'PootleSpacesPlaceable': replace_whitespace(placeable), 'NewlinePlaceable': { u'\r\n': u'\\r\\n<br/>\n', u'\r': u'\\r<br/>\n', u'\n': u'\\n<br/>\n', }.get(placeable), 'XMLEntityPlaceable': placeable.replace('&', '&'), 'XMLTagPlaceable': placeable.replace('<', '<') \ .replace('>', '>'), }.get(class_name, placeable) # Provide a description for the placeable using a tooltip. description = PLACEABLE_DESCRIPTIONS.get(class_name, _("Unknown placeable")) output += (u'<span class="%s js-editor-copytext js-placeable" ' u'title="%s">%s</span>') % (css_class, description, content) else: # It is not a placeable, so just concatenate to output string. output += unicode(item) return mark_safe(output)
def apply_parsers(self, elems, parsers=None): """Apply all selected placeable parsers to the list of string elements given. @param elems: The list of C{StringElem}s to apply the parsers to.""" if not isinstance(elems, list) and isinstance(elems, StringElem): elems = [elems] if parsers is None: parsers = self.parsers for elem in elems: elem = elem parsed = parse_placeables(elem, parsers) if isinstance(elem, (str, unicode)) and parsed != StringElem(elem): parent = elem.get_parent_elem(elem) if parent is not None: parent.sub[parent.sub.index(elem)] = StringElem(parsed) return elems