| Total Complexity | 9 |
| Total Lines | 91 |
| Duplicated Lines | 0 % |
| Changes | 0 | ||
| 1 | #!/usr/bin/env python |
||
| 2 | |||
| 3 | """ |
||
| 4 | Pandoc filter for adding complex figures. |
||
| 5 | """ |
||
| 6 | |||
| 7 | from panflute import ( # type: ignore |
||
| 8 | Caption, |
||
| 9 | Div, |
||
| 10 | Figure, |
||
| 11 | Plain, |
||
| 12 | convert_text, |
||
| 13 | debug, |
||
| 14 | run_filter, |
||
| 15 | ) |
||
| 16 | |||
| 17 | |||
| 18 | # pylint: disable=broad-exception-caught |
||
| 19 | def figure(elem, doc): |
||
| 20 | """ |
||
| 21 | Transform a div element into a figure element. |
||
| 22 | |||
| 23 | Arguments |
||
| 24 | --------- |
||
| 25 | elem |
||
| 26 | The pandoc element |
||
| 27 | doc |
||
| 28 | The pandoc document |
||
| 29 | |||
| 30 | Returns |
||
| 31 | ------- |
||
| 32 | Figure or None. |
||
| 33 | """ |
||
| 34 | if ( |
||
| 35 | doc.api_version >= (1, 23) |
||
| 36 | and isinstance(elem, Div) |
||
| 37 | and "figure" in elem.classes |
||
| 38 | and "caption" in elem.attributes |
||
| 39 | ): |
||
| 40 | try: |
||
| 41 | caption = convert_text(elem.attributes["caption"]) |
||
| 42 | del elem.attributes["caption"] |
||
| 43 | elem.classes.remove("figure") |
||
| 44 | return Figure( |
||
| 45 | *elem.content, |
||
| 46 | caption=Caption(Plain(*caption[0].content)), |
||
| 47 | identifier=elem.identifier, |
||
| 48 | classes=elem.classes, |
||
| 49 | attributes=elem.attributes, |
||
| 50 | ) |
||
| 51 | except Exception as error: # noqa: B902 |
||
| 52 | debug(f"[WARNING] pandoc-figure: {error}") |
||
| 53 | return None |
||
| 54 | |||
| 55 | |||
| 56 | def prepare(doc): |
||
| 57 | """ |
||
| 58 | Prepare the pandoc document. |
||
| 59 | |||
| 60 | Arguments |
||
| 61 | --------- |
||
| 62 | doc |
||
| 63 | The pandoc document |
||
| 64 | """ |
||
| 65 | if doc.api_version < (1, 23): |
||
| 66 | debug( |
||
| 67 | f"[WARNING] pandoc-figure: pandoc api version " |
||
| 68 | f"{'.'.join(str(value) for value in doc.api_version)} " |
||
| 69 | "is not compatible" |
||
| 70 | ) |
||
| 71 | |||
| 72 | |||
| 73 | def main(doc=None): |
||
| 74 | """ |
||
| 75 | Convert the pandoc document. |
||
| 76 | |||
| 77 | Arguments |
||
| 78 | --------- |
||
| 79 | doc |
||
| 80 | The pandoc document |
||
| 81 | |||
| 82 | Returns |
||
| 83 | ------- |
||
| 84 | The modified pandoc document |
||
| 85 | """ |
||
| 86 | return run_filter(figure, prepare=prepare, doc=doc) |
||
| 87 | |||
| 88 | |||
| 89 | if __name__ == "__main__": |
||
| 90 | main() |
||
| 91 |