R提示中有问题的ANSI转义序列 [英] buggy ANSI escape sequences in R prompt

查看:138
本文介绍了R提示中有问题的ANSI转义序列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当R在支持颜色的终端中交互运行时,可以使用ANSI转义序列以将颜色放入提示中,例如

When R is run interactively in a terminal which supports colors, it is possible to use ANSI escape sequences in order to put colors in the prompt, such as

options(prompt = "\033[0;31mThis is red\033[0m> ")

不幸的是,出了一些问题,因为对于较长的命令行来说,行连续覆盖提示,而不是写在下一行中。

使用几种颜色时,问题变得更加严重,因为在命令行中,每个转义序列都会以某种方式占用一些空间,直到提示的结尾可能会覆盖开头的点。在我的配置中,这会发生在例如

Unfortunately, something goes wrong because for long command lines, the line continuation override the prompt instead of being written in the next line. The problem gets worse when using several colors, because somehow each escape sequence "takes up some space" in the command line, up to the point that the end of the prompt might overwrite the beginning. On my configuration this happens with for instance

options(prompt = paste("\033[0;31m With \033[0;32m multiple",
                   "\033[0;33m colors \033[0;34m this",
                   "\033[0;35m gets \033[0;36m really",
                   "\033[0;37m wrong! \033[0m"))

为什么会这样?有解决方法吗?

Why is it so? Is there a workaround?

PS:这篇相当老的帖子似乎与 http://r.789695.n4.nabble.com/Xterm-escape-sequences-in-Prompt-td906375.html

PS: This rather old post seems related http://r.789695.n4.nabble.com/Xterm-escape-sequences-in-Prompt-td906375.html

update:以及R版本3.6.0和readline 8.0(不知道在这里重要),上述大部分问题都消失了,但是仍然存在一些奇怪的行为。

update: with R version 3.6.0 and readline 8.0 (don't know which matters here), most of the above described problem disappeared, but some strange behaviors remain. Accepted answer below resolves everything.

推荐答案

您需要用特殊的标记将每个不可见颜色代码括起来: \001 \002

you need to surround each «invisible» color code with special «marks»: \001 and \002:

options(prompt = "\001\033[0;31m\002This is red\001\033[0m\002> ")






有关说明,请参见 $信息阅读专线(或这个简短答案)。

这篇关于R提示中有问题的ANSI转义序列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆