| 112 | |
| 113 | |
| 114 | class AttrListTreeprocessor(Treeprocessor): |
| 115 | |
| 116 | BASE_RE = r'\{\:?[ ]*([^\}\n ][^\n]*)\}' |
| 117 | HEADER_RE = re.compile(r'[ ]+{}[ ]*$'.format(BASE_RE)) |
| 118 | BLOCK_RE = re.compile(r'\n[ ]*{}[ ]*$'.format(BASE_RE)) |
| 119 | INLINE_RE = re.compile(r'^{}'.format(BASE_RE)) |
| 120 | NAME_RE = NAME_RE |
| 121 | |
| 122 | def run(self, doc: Element) -> None: |
| 123 | for elem in doc.iter(): |
| 124 | if self.md.is_block_level(elem.tag): |
| 125 | # Block level: check for `attrs` on last line of text |
| 126 | RE = self.BLOCK_RE |
| 127 | if isheader(elem) or elem.tag in ['dt', 'td', 'th']: |
| 128 | # header, def-term, or table cell: check for attributes at end of element |
| 129 | RE = self.HEADER_RE |
| 130 | if len(elem) and elem.tag == 'li': |
| 131 | # special case list items. children may include a `ul` or `ol`. |
| 132 | pos = None |
| 133 | # find the `ul` or `ol` position |
| 134 | for i, child in enumerate(elem): |
| 135 | if child.tag in ['ul', 'ol']: |
| 136 | pos = i |
| 137 | break |
| 138 | if pos is None and elem[-1].tail: |
| 139 | # use tail of last child. no `ul` or `ol`. |
| 140 | m = RE.search(elem[-1].tail) |
| 141 | if m: |
| 142 | if not self.assign_attrs(elem, m.group(1), strict=True): |
| 143 | elem[-1].tail = elem[-1].tail[:m.start()] |
| 144 | elif pos is not None and pos > 0 and elem[pos-1].tail: |
| 145 | # use tail of last child before `ul` or `ol` |
| 146 | m = RE.search(elem[pos-1].tail) |
| 147 | if m: |
| 148 | if not self.assign_attrs(elem, m.group(1), strict=True): |
| 149 | elem[pos-1].tail = elem[pos-1].tail[:m.start()] |
| 150 | elif elem.text: |
| 151 | # use text. `ul` is first child. |
| 152 | m = RE.search(elem.text) |
| 153 | if m: |
| 154 | if not self.assign_attrs(elem, m.group(1), strict=True): |
| 155 | elem.text = elem.text[:m.start()] |
| 156 | elif len(elem) and elem[-1].tail: |
| 157 | # has children. Get from tail of last child |
| 158 | m = RE.search(elem[-1].tail) |
| 159 | if m: |
| 160 | if not self.assign_attrs(elem, m.group(1), strict=True): |
| 161 | elem[-1].tail = elem[-1].tail[:m.start()] |
| 162 | if isheader(elem): |
| 163 | # clean up trailing #s |
| 164 | elem[-1].tail = elem[-1].tail.rstrip('#').rstrip() |
| 165 | elif elem.text: |
| 166 | # no children. Get from text. |
| 167 | m = RE.search(elem.text) |
| 168 | if m: |
| 169 | if not self.assign_attrs(elem, m.group(1), strict=True): |
| 170 | elem.text = elem.text[:m.start()] |
| 171 | if isheader(elem): |