有一个程序通过重复覆盖stderr
中的最后一行文本来与用户进行交互。具体做法如下:
- There is a state monad that remembers the length of the last line printed.
When It wants to overwrite a line
s
with another lines'
, It padss'
with spaces until it is at least as long ass
and prepends it with "carriage return" character:n <- gets lastLineLength let s'Padded | 0 < n = '\r': s' ++ replicate (n - length s') ' ' | otherwise = s' hPutStr stderr s'Padded
这个程序完全有效。(虽然我个人只在通常的Linux终端环境下进行了测试。)
我改进了这个程序,通过从ansi-wl-pprint
中使用Doc
类型替换普通的String
,以便我可以像最近版本的GHC一样用颜色来渲染文本。像这样的库可能过于复杂,因为我只需要一次输出几行,而且没有缩进,但是我想尝试一下其抽象着色功能。但是,我不认为这个库(或任何漂亮的打印库)会具有旨在擦除先前打印的Doc
的函数。
我心目中的一个解决方案是将Doc
呈现为String
并测量其长度。但是,我必须排除颜色代码;此外,这总体上是对库提供的抽象的干扰:特别是,我必须依赖于手动完成的渲染与hPutDoc
隐式完成的渲染相匹配的假设。
我应该完全放弃库并继续使用String
,手动添加ANSI转义序列和回车吗?是否有更好的方式来覆盖先前的输出?我欢迎任何建议。