|
| 1 | +from html.parser import HTMLParser |
| 2 | +from docutils import nodes |
| 3 | + |
| 4 | +from docutils.parsers.rst import directives |
| 5 | + |
| 6 | + |
| 7 | +class ExitImageParse(Exception): |
| 8 | + pass |
| 9 | + |
| 10 | + |
| 11 | +def align(argument): |
| 12 | + return directives.choice(argument, ("left", "center", "right")) |
| 13 | + |
| 14 | + |
| 15 | +def make_error(document, error_msg, text, line_number): |
| 16 | + return document.reporter.error( |
| 17 | + "<img> conversion: {}".format(error_msg), |
| 18 | + nodes.literal_block(text, text), |
| 19 | + line=line_number, |
| 20 | + ) |
| 21 | + |
| 22 | + |
| 23 | +class HTMLImgParser(HTMLParser): |
| 24 | + def handle_starttag(self, tag, attrs): |
| 25 | + if tag == "img": |
| 26 | + self._attrs = dict(attrs) |
| 27 | + raise ExitImageParse() |
| 28 | + |
| 29 | + def parse(self, text: str, document: nodes.document, line_number: int): |
| 30 | + self.reset() |
| 31 | + self._attrs = None |
| 32 | + try: |
| 33 | + self.feed(text) |
| 34 | + except ExitImageParse: |
| 35 | + pass |
| 36 | + if self._attrs is None: |
| 37 | + return |
| 38 | + |
| 39 | + # TODO check for preceding text? |
| 40 | + |
| 41 | + if "src" not in self._attrs: |
| 42 | + return make_error(document, "missing src attribute", text, line_number) |
| 43 | + |
| 44 | + options = {} |
| 45 | + for name, key, spec in [ |
| 46 | + ("src", "uri", directives.uri), |
| 47 | + ("class", "classes", directives.class_option), |
| 48 | + ("alt", "alt", directives.unchanged), |
| 49 | + ("height", "height", directives.length_or_unitless), |
| 50 | + ("width", "width", directives.length_or_percentage_or_unitless), |
| 51 | + ("align", "align", align) |
| 52 | + # note: docutils also has scale and target |
| 53 | + ]: |
| 54 | + if name in self._attrs: |
| 55 | + value = self._attrs[name] |
| 56 | + try: |
| 57 | + options[key] = spec(value) |
| 58 | + except (ValueError, TypeError) as error: |
| 59 | + error_msg = "Invalid attribute: (key: '{}'; value: {})\n{}".format( |
| 60 | + name, value, error |
| 61 | + ) |
| 62 | + return make_error(document, error_msg, text, line_number) |
| 63 | + |
| 64 | + node = nodes.image(text, **options) |
| 65 | + if "name" in self._attrs: |
| 66 | + name = nodes.fully_normalize_name(self._attrs["name"]) |
| 67 | + node["names"].append(name) |
| 68 | + document.note_explicit_target(node, node) |
| 69 | + |
| 70 | + return node |
0 commit comments