Colored output with crayon

Vignette Author

2018-11-16

The crayon package can be used in conjunction with glue to easily color text output. Simple place the color in between braces {red} and put a {reset} when you want to reset the color. This behavior is currently only in the devel version of crayon.

library(crayon)
glue::glue("
  { sample.int(10, 1) } roses are {red}red{reset}
  { sample.int(10, 1) } violets are {blue}blue{reset}
  ")
#> 10 roses are red
#> 10 violets are blue

You can also create new objects as combinations of colors.

library(crayon)
error <- red $ bold
warn <- magenta $ underline
note <- cyan

subscript <- 2
glue("{error}Error: subscript '{subscript}' out of bounds!{reset}")
#> Error: subscript '2' out of bounds!

arg <- "y"
glue("{warn}Warning: shorter argument '{arg}' was recycled.{reset}")
#> Warning: shorter argument 'y' was recycled.

dir <- 'pkg/R'
glue("{note}Note: no such directory '{dir}'.{reset}")
#> Note: no such directory 'pkg/R'.

And calling glue functions directly within {} works as well

glue("
Crayon example:
  {
    green(
    'I am a green line ' %+%
    blue$underline$bold('with a blue substring') %+%
    ' that becomes green again!')
  }
  ")
#> Crayon example:
#>   I am a green line with a blue substring that becomes green again!