def replace_linebreaks(self, text): lines = text.split('\n') if len(lines) > 1: wrapper = DOM.create_document_fragment() DOM.append_child(wrapper, DOM.create_text_node(lines[0])) for l in lines[1:]: DOM.append_child(wrapper, DOM.create_element('br')) DOM.append_child(wrapper, DOM.create_text_node(l)) else: wrapper = DOM.create_text_node(text) return wrapper
def create_nodes(self, text, block=None, entity_stack=None): if entity_stack: text_children = [DOM.create_text_node(text)] else: text_children = get_decorations(self.composite_decorators, text, block) if self.is_unstyled(): return list(text_children) else: tags = self.get_style_tags() node = DOM.create_element(tags[0]) child = node # Nest the tags. # Set the text and style attribute (if any) on the deepest node. for tag in tags[1:]: new_child = DOM.create_element(tag) DOM.append_child(child, new_child) child = new_child style_value = self.get_style_value() if style_value: DOM.set_attribute(child, 'style', style_value) for text_child in text_children: DOM.append_child(child, text_child) return [node]
def add_node(self, element, text): if self.is_unstyled(): child = DOM.create_text_node(text) DOM.append_child(element, child) else: tags = self.get_style_tags() child = element # Nest the tags. # Set the text and style attribute (if any) on the deepest node. for tag in tags: new_child = DOM.create_element(tag) DOM.append_child(child, new_child) child = new_child style_value = self.get_style_value() if style_value: DOM.set_attribute(child, 'style', style_value) class_value = self.get_class_value() if class_value: DOM.set_attribute(child, 'class', class_value) DOM.set_text_content(child, text) return child
def replace(self, match, block_type): protocol = match.group(1) url = match.group(2) href = protocol + url if block_type == BLOCK_TYPES.CODE: return DOM.create_text_node(href) text = cgi.escape(href) if href.startswith("www"): href = "http://" + href props = {'href': href} if self.new_window: props.update(target="_blank") return DOM.create_element('a', props, text)
def get_decorations(decorators, text, block=None): block_type = block.get('type') if block else None occupied = {} decorations = [] for deco in decorators: for match in deco.SEARCH_RE.finditer(text): begin, end = match.span() if not any(occupied.get(i) for i in xrange(begin, end)): for i in xrange(begin, end): occupied[i] = 1 decorations.append((begin, end, match, deco)) decorations.sort(key=itemgetter(0)) pointer = 0 for begin, end, match, deco in decorations: if pointer < begin: yield DOM.create_text_node(text[pointer:begin]) yield deco.replace(match, block_type) pointer = end if pointer < len(text): yield DOM.create_text_node(text[pointer:])
def test_create_text_node(self): self.assertEqual(DOM.get_tag_name(DOM.create_text_node('Test text')), 'textnode') self.assertEqual(DOM.get_text_content(DOM.create_text_node('Test text')), 'Test text')