5 from librarian import dcparser, RDFNS
6 from librarian.util import get_translation
9 class WLElement(etree.ElementBase):
22 text_substitutions = [
32 def meta_object(self):
33 if not hasattr(self, '_meta_object'):
34 elem = self.find(RDFNS('RDF'))
36 self._meta_object = dcparser.BookInfo.from_element(elem)
38 self._meta_object = None
39 return self._meta_object
43 if self.meta_object is not None:
44 return self.meta_object
46 if self.getparent() is not None:
47 return self.getparent().meta
49 return self.document.base_meta
53 return get_translation(self.meta.language).gettext
55 def normalize_text(self, text):
57 for e, s in self.text_substitutions:
58 text = text.replace(e, s)
59 text = re.sub(r'\s+', ' ', text)
62 def _build_inner(self, builder, build_method):
63 child_count = len(self)
64 if self.CAN_HAVE_TEXT and self.text:
65 text = self.normalize_text(self.text)
70 builder.push_text(text)
71 for i, child in enumerate(self):
72 if isinstance(child, WLElement):
73 getattr(child, build_method)(builder)
74 if self.CAN_HAVE_TEXT and child.tail:
75 text = self.normalize_text(child.tail)
76 if self.STRIP and i == child_count - 1:
78 builder.push_text(text)
80 def _txt_build_inner(self, builder):
81 self._build_inner(builder, 'txt_build')
83 def txt_build(self, builder):
84 if hasattr(self, 'TXT_LEGACY_TOP_MARGIN'):
85 builder.push_legacy_margin(self.TXT_LEGACY_TOP_MARGIN)
87 builder.push_margin(self.TXT_TOP_MARGIN)
88 builder.push_text(self.TXT_PREFIX, True)
89 self._txt_build_inner(builder)
90 builder.push_text(self.TXT_SUFFIX, True)
91 if hasattr(self, 'TXT_LEGACY_BOTTOM_MARGIN'):
92 builder.push_legacy_margin(self.TXT_LEGACY_BOTTOM_MARGIN)
94 builder.push_margin(self.TXT_BOTTOM_MARGIN)
96 def _html_build_inner(self, builder):
97 self._build_inner(builder, 'html_build')
99 def get_html_attr(self, builder):
100 attr = self.HTML_ATTR.copy()
102 attr['class'] = self.HTML_CLASS
103 # always copy the id attribute (?)
104 if self.attrib.get('id'):
105 attr['id'] = self.attrib['id']
106 elif '_compat_section_id' in self.attrib:
107 attr['id'] = self.attrib['_compat_section_id']
110 def html_build(self, builder):
112 builder.start_element(
114 self.get_html_attr(builder),
117 self._html_build_inner(builder)
119 builder.end_element()
122 # TODO: Remove insanity here.
124 if isinstance(e, WLElement):