5 from librarian import dcparser, RDFNS
8 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
51 def normalize_text(self, text):
53 for e, s in self.text_substitutions:
54 text = text.replace(e, s)
55 text = re.sub(r'\s+', ' ', text)
58 def _build_inner(self, builder, build_method):
59 child_count = len(self)
60 if self.CAN_HAVE_TEXT and self.text:
61 text = self.normalize_text(self.text)
66 builder.push_text(text)
67 for i, child in enumerate(self):
68 if isinstance(child, WLElement):
69 getattr(child, build_method)(builder)
70 if self.CAN_HAVE_TEXT and child.tail:
71 text = self.normalize_text(child.tail)
72 if self.STRIP and i == child_count - 1:
74 builder.push_text(text)
76 def _txt_build_inner(self, builder):
77 self._build_inner(builder, 'txt_build')
79 def txt_build(self, builder):
80 if hasattr(self, 'TXT_LEGACY_TOP_MARGIN'):
81 builder.push_legacy_margin(self.TXT_LEGACY_TOP_MARGIN)
83 builder.push_margin(self.TXT_TOP_MARGIN)
84 builder.push_text(self.TXT_PREFIX, True)
85 self._txt_build_inner(builder)
86 builder.push_text(self.TXT_SUFFIX, True)
87 if hasattr(self, 'TXT_LEGACY_BOTTOM_MARGIN'):
88 builder.push_legacy_margin(self.TXT_LEGACY_BOTTOM_MARGIN)
90 builder.push_margin(self.TXT_BOTTOM_MARGIN)
92 def _html_build_inner(self, builder):
93 self._build_inner(builder, 'html_build')
95 def get_html_attr(self, builder):
96 attr = self.HTML_ATTR.copy()
98 attr['class'] = self.HTML_CLASS
99 # always copy the id attribute (?)
100 if self.attrib.get('id'):
101 attr['id'] = self.attrib['id']
104 def html_build(self, builder):
105 if self.HTML_SECTION:
106 builder.start_element(
107 'a', {"name": "f18", "class": "target"}
109 builder.push_text(" ")
110 builder.end_element()
112 builder.start_element(
113 "a", {"href": "#f18", "class": "anchor"}
115 builder.push_text("18")
116 builder.end_element()
120 builder.start_element(
122 self.get_html_attr(builder),
125 if self.HTML_SECTION:
126 builder.start_element(
127 "a", {"name": "sec34"}
129 builder.end_element()
131 self._html_build_inner(builder)
133 builder.end_element()
136 # TODO: Remove insanity here.
138 if isinstance(e, WLElement):