_list.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. from typing import TYPE_CHECKING, Any, Dict, Iterable, cast
  2. from ..util import strip_end
  3. if TYPE_CHECKING:
  4. from ..core import BaseRenderer, BlockState
  5. def render_list(renderer: "BaseRenderer", token: Dict[str, Any], state: "BlockState") -> str:
  6. attrs = token["attrs"]
  7. if attrs["ordered"]:
  8. children = _render_ordered_list(renderer, token, state)
  9. else:
  10. children = _render_unordered_list(renderer, token, state)
  11. text = "".join(children)
  12. parent = token.get("parent")
  13. if parent:
  14. if parent["tight"]:
  15. return text
  16. return text + "\n"
  17. return strip_end(text) + "\n"
  18. def _render_list_item(
  19. renderer: "BaseRenderer",
  20. parent: Dict[str, Any],
  21. item: Dict[str, Any],
  22. state: "BlockState",
  23. ) -> str:
  24. leading = cast(str, parent["leading"])
  25. text = ""
  26. for tok in item["children"]:
  27. if tok["type"] == "list":
  28. tok["parent"] = parent
  29. elif tok["type"] == "blank_line":
  30. continue
  31. text += renderer.render_token(tok, state)
  32. lines = text.splitlines()
  33. text = (lines[0] if lines else "") + "\n"
  34. prefix = " " * len(leading)
  35. for line in lines[1:]:
  36. if line:
  37. text += prefix + line + "\n"
  38. else:
  39. text += "\n"
  40. return leading + text
  41. def _render_ordered_list(renderer: "BaseRenderer", token: Dict[str, Any], state: "BlockState") -> Iterable[str]:
  42. attrs = token["attrs"]
  43. start = attrs.get("start", 1)
  44. for item in token["children"]:
  45. leading = str(start) + token["bullet"] + " "
  46. parent = {
  47. "leading": leading,
  48. "tight": token["tight"],
  49. }
  50. yield _render_list_item(renderer, parent, item, state)
  51. start += 1
  52. def _render_unordered_list(renderer: "BaseRenderer", token: Dict[str, Any], state: "BlockState") -> Iterable[str]:
  53. parent = {
  54. "leading": token["bullet"] + " ",
  55. "tight": token["tight"],
  56. }
  57. for item in token["children"]:
  58. yield _render_list_item(renderer, parent, item, state)