r-lib / cli
1

2
#' Format a value for printing
3
#'
4
#' This function can be used directly, or via the `{.val ...}` inline
5
#' style. `{.val {expr}}` calls `cli_format()` automatically on the value
6
#' of `expr`, before styling and collapsing it.
7
#'
8
#' It is possible to define new S3 methods for `cli_format` and then
9
#' these will be used automatically for `{.cal ...}` expressions.
10
#'
11
#' @param x The object to format.
12
#' @param style List of formatting options, see the individual methods
13
#'   for the style options they support.
14
#' @param ... Additional arguments for methods.
15
#'
16
#' @export
17
#' @examples
18
#' things <- c(rep("this", 3), "that")
19
#' cli_format(things)
20
#' cli_text("{.val {things}}")
21
#'
22
#' nums <- 1:5 / 7
23
#' cli_format(nums, style = list(digits = 2))
24
#' cli_text("{.val {nums}}")
25
#' divid <- cli_div(theme = list(.val = list(digits = 3)))
26
#' cli_text("{.val {nums}}")
27
#' cli_end(divid)
28

29 0
cli_format <- function(x, style = list(), ...)
30 0
  UseMethod("cli_format")
31

32
#' @rdname cli_format
33
#' @export
34

35
cli_format.default <- function(x, style = list(), ...) {
36 0
  x
37
}
38

39
#' * Styles for character vectors:
40
#'   - `string_quote` is the quoting character for [encodeString()].
41
#'
42
#' @rdname cli_format
43
#' @export
44

45
cli_format.character <- function(x, style = list(), ...) {
46 0
  quote <- style$string_quote %||% "'"
47 0
  encodeString(x, quote = quote)
48
}
49

50
#' * Styles for numeric vectors:
51
#'   - `digits` is the number of digits to print after the decimal point.
52
#'
53
#' @rdname cli_format
54
#' @export
55

56
cli_format.numeric <- function(x, style = list(), ...) {
57 0
  digits <- style$digits
58 0
  if (!is.null(digits)) x <- round(x, digits)
59 0
  x
60
}

Read our documentation on viewing source code .

Loading