r-lib / cli

Tools for making beautiful & useful command line interfaces
https://cli.r-lib.org/
Other
625 stars 66 forks source link

Fix formatting for call objects #679

Closed jameslairdsmith closed 3 months ago

jameslairdsmith commented 3 months ago

Looks like call objects are being cast to character vectors and so getting that kind of formatting.

library(cli)
my_call <- call("paste0", "foo", "bar")
my_call
#> paste0("foo", "bar")
cli_text("{.code {my_call}}")
#> `paste0`, `foo`, and `bar`

Using capture.output() makes it look more like what I would expect.

cli_text("{.code {capture.output(my_call)}}")
#> `paste0("foo", "bar")`

Created on 2024-03-15 with reprex v2.1.0

gaborcsardi commented 3 months ago

cli calls as.character() on the result of {...} substitutions, because it needs to output a character scalar.

If as.character() does not behave the way you want for an object, you need to format it manually. E.g. for calls you could call format(). Or capture.output() like you did.

FWIW glue::glue() and paste() which are similar functions, behave the same way:

❯ glue::glue("{my_call}")
paste0
foo
bar
❯ paste(my_call, collapse = " ")
[1] "paste0 foo bar"
jameslairdsmith commented 3 months ago

Thanks for the explanation. I thought there might be some formatting inheritance going on, which it might be easy to plug the call class into. But if it's just as.character() then it makes sense that people opt into the formatting by calling format() directly.

I see there is also cli_format() that does inline formatting. Might that also be a way someone could do it themselves? By creating the S3 method and using .val?

gaborcsardi commented 3 months ago

Yep, whichever is working for you.