# m ask 支持 markdown 流式渲染了 (December 5, 2024)

发现原来 rich 有可以用来实现流式 markdown 渲染的工具，于是就集成了一下，下面是个例子，在命令行中直接对 ruff 的一条 lint 规则进行提问

![](/nlark/yuque/0/2024/png/26070246/1733365529567-3775961f-30ef-48a6-a721-7a000972e0f4.png)

但是超出高度会闪烁，于是手动实现了下 truncate 的策略

```python
class TruncatedMarkdown(Markdown):
    def __rich_console__(self, console, options):
        results = list(super().__rich_console__(console, options))
        height = console.height
        count = 0
        buffer = []
        for segment in reversed(results):
            count += segment.text.count("\n")  # type: ignore
            if count > height:
                break
            buffer.append(segment)

        yield from reversed(buffer)
```

其实 `rich.live` 的用法还是昨晚从 pydantic-ai 学到的：

[Stream markdown - PydanticAI](https://ai.pydantic.dev/examples/stream-markdown/?h=rich.live)