1

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> ")

enter image description here

Unfortunately, something goes wrong because for long command lines, the line continuation override the prompt instead of being written in the next line. enter image description here 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"))

enter image description here

Why is it so? Is there a workaround?

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

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.

Hugo Raguet
  • 418
  • 3
  • 11
  • To be clear, this is when your typing causes a new line, not when you break a long line and get a continuation prompt, usually "+" yeah? Screenshots might help (and are encouraged here, unlike on R-help!) – Spacedman Feb 07 '17 at 12:52
  • @Spacedman Exactly, this is when I type a long line. I added some screenshots. – Hugo Raguet Feb 07 '17 at 13:13

2 Answers2

2

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> ")

for explanation see $ info readline (or this short answer).

aleksandr barakin
  • 521
  • 1
  • 13
  • 42
  • Thanks for taking the time to answer that old question (currently with R version 3.6.0 and readline 8.0, do not know which matters, most of the above problems already disappeared, but your solution is really the way to go). – Hugo Raguet Jun 05 '19 at 09:32
0

Gábor Csárdi on the r-devel mailing list says that I cannot easily change this behavior (http://r.789695.n4.nabble.com/buggy-ANSI-escape-sequences-in-R-prompt-td4728671.html). The workaround he proposes is to use a two lines prompt, which suits me well enough.

Hugo Raguet
  • 418
  • 3
  • 11