| Title: | Helpers for Developing Command Line Interfaces |
| Version: | 3.6.5 |
| Description: | A suite of tools to build attractive command line interfaces ('CLIs'), from semantic elements: headings, lists, alerts, paragraphs, etc. Supports custom themes via a 'CSS'-like language. It also contains a number of lower level 'CLI' elements: rules, boxes, trees, and 'Unicode' symbols with 'ASCII' alternatives. It support ANSI colors and text styles as well. |
| License: | MIT + file LICENSE |
| URL: | https://cli.r-lib.org,https://github.com/r-lib/cli |
| BugReports: | https://github.com/r-lib/cli/issues |
| Depends: | R (≥ 3.4) |
| Imports: | utils |
| Suggests: | callr, covr, crayon, digest, glue (≥ 1.6.0), grDevices,htmltools, htmlwidgets, knitr, methods, processx, ps (≥1.3.4.9000), rlang (≥ 1.0.2.9003), rmarkdown, rprojroot,rstudioapi, testthat (≥ 3.2.0), tibble, whoami, withr |
| Config/Needs/website: | r-lib/asciicast, bench, brio, cpp11, decor, desc,fansi, prettyunits, sessioninfo, tidyverse/tidytemplate,usethis, vctrs |
| Config/testthat/edition: | 3 |
| Encoding: | UTF-8 |
| RoxygenNote: | 7.3.2 |
| NeedsCompilation: | yes |
| Packaged: | 2025-04-22 12:00:18 UTC; gaborcsardi |
| Author: | Gábor Csárdi [aut, cre], Hadley Wickham [ctb], Kirill Müller [ctb], Salim Brüggemann |
| Maintainer: | Gábor Csárdi <gabor@posit.co> |
| Repository: | CRAN |
| Date/Publication: | 2025-04-23 13:50:02 UTC |
cli: Helpers for Developing Command Line Interfaces
Description
A suite of tools to build attractive command line interfaces ('CLIs'), from semantic elements: headings, lists, alerts, paragraphs, etc. Supports custom themes via a 'CSS'-like language. It also contains a number of lower level 'CLI' elements: rules, boxes, trees, and 'Unicode' symbols with 'ASCII' alternatives. It support ANSI colors and text styles as well.
Author(s)
Maintainer: Gábor Csárdigabor@posit.co
Other contributors:
Hadley Wickham [contributor]
Kirill Müller [contributor]
Salim Brüggemannsalim-b@pm.me (ORCID) [contributor]
Posit Software, PBC [copyright holder, funder]
See Also
Useful links:
ANSI colored text
Description
cli has a number of functions to color and style text at the commandline. They provide a more modern interface than the crayon package.
Usage
bg_black(...)bg_blue(...)bg_cyan(...)bg_green(...)bg_magenta(...)bg_red(...)bg_white(...)bg_yellow(...)bg_none(...)bg_br_black(...)bg_br_blue(...)bg_br_cyan(...)bg_br_green(...)bg_br_magenta(...)bg_br_red(...)bg_br_white(...)bg_br_yellow(...)col_black(...)col_blue(...)col_cyan(...)col_green(...)col_magenta(...)col_red(...)col_white(...)col_yellow(...)col_grey(...)col_silver(...)col_none(...)col_br_black(...)col_br_blue(...)col_br_cyan(...)col_br_green(...)col_br_magenta(...)col_br_red(...)col_br_white(...)col_br_yellow(...)style_dim(...)style_blurred(...)style_bold(...)style_hidden(...)style_inverse(...)style_italic(...)style_reset(...)style_strikethrough(...)style_underline(...)style_no_bold(...)style_no_blurred(...)style_no_dim(...)style_no_italic(...)style_no_underline(...)style_no_inverse(...)style_no_hidden(...)style_no_strikethrough(...)style_no_color(...)style_no_bg_color(...)Arguments
... | Character strings, they will be pasted together with |
Details
Thecol_* functions change the (foreground) color to the text.These are the eight original ANSI colors. Note that in some terminals,they might actually look differently, as terminals have their ownsettings for how to show them.col_none() is the default color, thisis useful in a substring of a colored string.
Thecol_br_* functions are bright versions of the eight ANSI colors.Note that on some terminal configurations and themes they might be thesame as the non-bright colors.
Thebg_* functions change the background color of the text.These are the eight original ANSI background colors. These, too, canvary in appearance, depending on terminal settings.bg_none() thethe default background color, this is useful in a substring of abackground-colored string.
Thebg_br_* functions are the bright versions of the eight ANSIbackground colors. Note that on some terminal configurations and themesthey might be the same as the non-bright colors.
Thestyle_* functions apply other styling to the text. The currentlysupported styling functions are:
style_reset()to remove any style, including color,style_bold()for boldface / strong text, although some terminalsshow a bright, high intensity text instead,style_dim()(orstyle_blurred()reduced intensity text.style_italic()(not widely supported).style_underline(),style_inverse(),style_hidden(),style_strikethrough()(not widely supported).
The style functions take any number of character vectors as arguments,and they concatenate them usingpaste0() before adding the style.
Styles can also be nested, and then inner style takes precedence, seeexamples below.
Sometimes you want to revert back to the default text color, in themiddle of colored text, or you want to have a normal font in the middleof italic text. You can use thestyle_no_* functions for this. Everystyle_*() function has astyle_no_*() pair, which defends itsargument from taking on the style. See examples below.
Value
An ANSI string (classcli_ansi_string), that contains ANSIsequences, if the current platform supports them. You can simplyusecat() to print them to the terminal.
See Also
Other ANSI styling:combine_ansi_styles(),make_ansi_style(),num_ansi_colors()
Examples
col_blue("Hello ", "world!")cat(col_blue("Hello ", "world!"))cat("... to highlight the", col_red("search term"), "in a block of text\n")## Style stack properlycat(col_green( "I am a green line ", col_blue(style_underline(style_bold("with a blue substring"))), " that becomes green again!"))error <- combine_ansi_styles("red", "bold")warn <- combine_ansi_styles("magenta", "underline")note <- col_cyancat(error("Error: subscript out of bounds!\n"))cat(warn("Warning: shorter argument was recycled.\n"))cat(note("Note: no such directory.\n"))# style_no_* functions, note that the color is not removedstyle_italic(col_green(paste0( "italic before, ", style_no_italic("normal here, "), "italic after")))# avoiding color for substringstyle_italic(col_red(paste( "red before", col_none("not red between"), "red after")))Align an ANSI colored string
Description
Align an ANSI colored string
Usage
ansi_align( text, width = console_width(), align = c("left", "center", "right"), type = "width")Arguments
text | The character vector to align. |
width | Width of the field to align in. |
align | Whether to align |
type | Passed on to |
Details
str <- c( col_red("This is red"), style_bold("This is bold"))astr <- ansi_align(str, width = 30)boxx(astr)#> ┌────────────────────────────────────┐ #> │ │ #> │This is red │ #> │This is bold │ #> │ │ #> └────────────────────────────────────┘
str <- c( col_red("This is red"), style_bold("This is bold"))astr <- ansi_align(str, align = "center", width = 30)boxx(astr)#> ┌────────────────────────────────────┐ #> │ │ #> │This is red │ #> │This is bold │ #> │ │ #> └────────────────────────────────────┘
str <- c( col_red("This is red"), style_bold("This is bold"))astr <- ansi_align(str, align = "right", width = 30)boxx(astr)#> ┌────────────────────────────────────┐ #> │ │ #> │This is red │ #> │This is bold │ #> │ │ #> └────────────────────────────────────┘
Value
The aligned character vector.
See Also
Other ANSI string operations:ansi_columns(),ansi_nchar(),ansi_strsplit(),ansi_strtrim(),ansi_strwrap(),ansi_substr(),ansi_substring(),ansi_toupper(),ansi_trimws()
Collapse a vector into a string scalar
Description
Features:
custom separator (
sep),custom separator for length-two input (
sep2),custom last separator (
last),adds ellipsis to truncated strings,
uses Unicode ellipsis character on UTF-8 console,
can collapse "from both ends", with
style = "both-ends",can consider a limit for the display width of the result, in characters,
handles ANSI control sequences correctly when measuring display width.
Usage
ansi_collapse( x, sep = ", ", sep2 = sub("^,", "", last), last = ", and ", trunc = Inf, width = Inf, ellipsis = symbol$ellipsis, style = c("both-ends", "head"))Arguments
x | Character vector, or an object with an |
sep | Separator. A character string. |
sep2 | Separator for the special case that |
last | Last separator, if there is no truncation. E.g. use |
trunc | Maximum number of elements to show. For |
width | Limit for the display width of the result, in characters.This is a hard limit, and the output will never exceed it.This argument is not implemented for the |
ellipsis | Character string to use at the place of the truncation.By default, the Unicode ellipsis character is used if the console isUTF-8, and three dots otherwise. |
style | Truncation style:
|
Value
Character scalar. It isNA_character_ if any elements inxareNA.
See Also
glue_collapse in the glue package inspired this function.
Examples
ansi_collapse(letters)# truncateansi_collapse(letters, trunc = 5)# head styleansi_collapse(letters, trunc = 5, style = "head")Format a character vector in multiple columns
Description
This function helps with multi-column output of ANSI styles strings.It works well together withboxx(), see the example below.
Usage
ansi_columns( text, width = console_width(), sep = " ", fill = c("rows", "cols"), max_cols = 4, align = c("left", "center", "right"), type = "width", ellipsis = symbol$ellipsis)Arguments
text | Character vector to format. Each element will formattedas a cell of a table. |
width | Width of the screen. |
sep | Separator between the columns. It may have ANSI styles. |
fill | Whether to fill the columns row-wise or column-wise. |
max_cols | Maximum number of columns to use. Will not use more,even if there is space for it. |
align | Alignment within the columns. |
type | Passed to |
ellipsis | The string to append to truncated strings. Supply anempty string if you don't want a marker. |
Details
If a string does not fit into the specifiedwidth, it will betruncated usingansi_strtrim().
fmt <- ansi_columns( paste(col_red("foo"), 1:10), width = 50, fill = "rows", max_cols=10, align = "center", sep = " ")boxx(fmt, padding = c(0,1,0,1), header = col_cyan("Columns"))#> ┌Columns ───────────────────────────────────────────┐ #> │foo 1foo 2foo 3foo 4foo 5 │ #> │foo 6foo 7foo 8foo 9foo 10 │ #> └────────────────────────────────────────────────────┘
Value
ANSI string vector.
See Also
Other ANSI string operations:ansi_align(),ansi_nchar(),ansi_strsplit(),ansi_strtrim(),ansi_strwrap(),ansi_substr(),ansi_substring(),ansi_toupper(),ansi_trimws()
Likebase::grep() andbase::grepl(), but for ANSI strings
Description
First ANSI sequences will be stripped withansi_strip(), both
Usage
ansi_grep(pattern, x, ignore.case = FALSE, perl = FALSE, value = FALSE, ...)ansi_grepl(pattern, x, ...)Arguments
pattern | Character scalar, regular expression or fixed string(if |
x | Character vector to search in. Other objects will be coercedusing |
ignore.case,perl,value | Passed to |
... | Extra arguments are passed to |
Details
Note that these functions work on code points (or bytes ifuseBytes = TRUE), and not graphemes.
Unlikebase::grep() andbase::grepl() these functions do not specialcase factors.
Bothpattern andx are converted to UTF-8.
Value
The same asbase::grep() andbase::grepl(), respectively.
Examples
red_needle <- col_red("needle")haystack <- c("foo", "needle", "foo")green_haystack <- col_green(haystack)ansi_grepl(red_needle, haystack)ansi_grepl(red_needle, green_haystack)Check if a string has some ANSI styling
Description
Check if a string has some ANSI styling
Usage
ansi_has_any(string, sgr = TRUE, csi = TRUE, link = TRUE)Arguments
string | The string to check. It can also be a charactervector. |
sgr | Whether to look for SGR (styling) control sequences. |
csi | Whether to look for non-SGR control sequences. |
link | Whether to look for ANSI hyperlinks. |
Value
Logical vector,TRUE for the strings that have someANSI styling.
See Also
Other low level ANSI functions:ansi_hide_cursor(),ansi_regex(),ansi_string(),ansi_strip()
Examples
## The second one has style if ANSI colors are supportedansi_has_any("foobar")ansi_has_any(col_red("foobar"))Hide/show cursor in a terminal
Description
This only works in terminal emulators. In other environments, itdoes nothing.
Usage
ansi_hide_cursor(stream = "auto")ansi_show_cursor(stream = "auto")ansi_with_hidden_cursor(expr, stream = "auto")Arguments
stream | The stream to inspect or manipulate, an R connectionobject. It can also be a string, one of |
expr | R expression to evaluate. |
Details
ansi_hide_cursor() hides the cursor.
ansi_show_cursor() shows the cursor.
ansi_with_hidden_cursor() temporarily hides the cursor forevaluating an expression.
See Also
Other terminal capabilities:is_ansi_tty(),is_dynamic_tty()
Other low level ANSI functions:ansi_has_any(),ansi_regex(),ansi_string(),ansi_strip()
Convert ANSI styled text to HTML
Description
Convert ANSI styled text to HTML
Usage
ansi_html(x, escape_reserved = TRUE, csi = c("drop", "keep"))Arguments
x | Input character vector. |
escape_reserved | Whether to escape characters that are reservedin HTML ( |
csi | What to do with non-SGR ANSI sequences, either |
Value
Character vector of HTML.
See Also
Other ANSI to HTML conversion:ansi_html_style()
Examples
## Syntax highlight the source code of an R function with ANSI tags,## and export it to a HTML file.code <- withr::with_options( list(ansi.num_colors = 256), code_highlight(format(ansi_html)))hcode <- paste(ansi_html(code), collapse = "\n")css <- paste(format(ansi_html_style()), collapse= "\n")page <- htmltools::tagList( htmltools::tags$head(htmltools::tags$style(css)), htmltools::tags$pre(htmltools::HTML(hcode)))if (interactive()) htmltools::html_print(page)CSS styles for the output ofansi_html()
Description
CSS styles for the output ofansi_html()
Usage
ansi_html_style( colors = TRUE, palette = c("vscode", "dichro", "vga", "winxp", "win10", "macos", "putty", "mirc", "xterm", "ubuntu", "eclipse", "iterm", "iterm-pastel", "iterm-smoooooth", "iterm-snazzy", "iterm-solarized", "iterm-tango"))Arguments
colors | Whether or not to include colors. |
palette | Character scalar, palette to use for the first eight colorsplus their bright variants. Terminals define these colors differently,and cli includes a couple of examples. Sources of palettes:
|
Value
Named list of CSS declaration blocks, where the names areCSS selectors. It has aformat() andprint() methods, which youcan use to write the output to a CSS or HTML file.
See Also
Other ANSI to HTML conversion:ansi_html()
Examples
ansi_html_style(colors = FALSE)ansi_html_style(colors = 8, palette = "iterm-snazzy")Count number of characters in an ANSI colored string
Description
This is a color-aware counterpart ofutf8_nchar(). By default itcounts Unicode grapheme clusters, instead of code points.
Usage
ansi_nchar(x, type = c("chars", "bytes", "width", "graphemes", "codepoints"))Arguments
x | Character vector, potentially ANSI styled, or a vector to becoerced to character. If it converted to UTF-8. |
type | Whether to count graphemes (characters), code points,bytes, or calculate the display width of the string. |
Value
Numeric vector, the length of the strings in the charactervector.
See Also
Other ANSI string operations:ansi_align(),ansi_columns(),ansi_strsplit(),ansi_strtrim(),ansi_strwrap(),ansi_substr(),ansi_substring(),ansi_toupper(),ansi_trimws()
Examples
str <- paste( col_red("red"), "default", col_green("green"))cat(str, "\n")nchar(str)ansi_nchar(str)nchar(ansi_strip(str))Likebase::nzchar(), but for ANSI strings
Description
Likebase::nzchar(), but for ANSI strings
Usage
ansi_nzchar(x, ...)Arguments
x | Charcater vector. Other objects are coarced using |
... | Passed to |
Examples
ansi_nzchar("")ansi_nzchar(col_red(""))Perl compatible regular expression that matches ANSI escapesequences
Description
Don't forget to useperl = TRUE when using this withgrepl() andfriends.
Usage
ansi_regex()Value
String scalar, the regular expression.
See Also
Other low level ANSI functions:ansi_has_any(),ansi_hide_cursor(),ansi_string(),ansi_strip()
Simplify ANSI styling tags
Description
It creates an equivalent, but possibly shorter ANSI styled string, byremoving duplicate and empty tags.
Usage
ansi_simplify(x, csi = c("keep", "drop"))Arguments
x | Input string |
csi | What to do with non-SGR ANSI sequences, either |
Value
Simplifiedcli_ansi_string vector.
Labels a character vector as containing ANSI control codes.
Description
This function sets the class of its argument, activatingANSI-string-specific methods such as for printing.
Usage
ansi_string(x)Arguments
x | A character vector or something that can becoerced into one. |
Value
Acli_ansi_string object, a subclass ofcharacter, with the same length and contentsasx.
See Also
Other low level ANSI functions:ansi_has_any(),ansi_hide_cursor(),ansi_regex(),ansi_strip()
Remove ANSI escape sequences from a string
Description
The input may be of classcli_ansi_string class, this is also droppedfrom the result.
Usage
ansi_strip(string, sgr = TRUE, csi = TRUE, link = TRUE)Arguments
string | The input string. |
sgr | Whether to remove for SGR (styling) control sequences. |
csi | Whether to remove for non-SGR control sequences. |
link | Whether to remove ANSI hyperlinks. |
Value
The cleaned up string. Note thatansi_strip() always dropsthecli_ansi_string class, even ifsgr and sciareFALSE'.
See Also
Other low level ANSI functions:ansi_has_any(),ansi_hide_cursor(),ansi_regex(),ansi_string()
Examples
ansi_strip(col_red("foobar")) == "foobar"Split an ANSI colored string
Description
This is the color-aware counterpart ofbase::strsplit().It works almost exactly like the original, but keeps the colors in thesubstrings.
Usage
ansi_strsplit(x, split, ...)Arguments
x | Character vector, potentially ANSI styled, or a vector tocoerced to character. |
split | Character vector of length 1 (or object which can be coerced tosuch) containing regular expression(s) (unless |
... | Extra arguments are passed to |
Value
A list of the same length asx, thei-th element ofwhich contains the vector of splits ofx[i]. ANSI styles areretained.
See Also
Other ANSI string operations:ansi_align(),ansi_columns(),ansi_nchar(),ansi_strtrim(),ansi_strwrap(),ansi_substr(),ansi_substring(),ansi_toupper(),ansi_trimws()
Examples
str <- paste0( col_red("I am red---"), col_green("and I am green-"), style_underline("I underlined"))cat(str, "\n")# split at dashes, keep colorcat(ansi_strsplit(str, "[-]+")[[1]], sep = "\n")strsplit(ansi_strip(str), "[-]+")# split to characters, keep colorcat(ansi_strsplit(str, "")[[1]], "\n", sep = " ")strsplit(ansi_strip(str), "")Truncate an ANSI string
Description
This function is similar tobase::strtrim(), but works correctly withANSI styled strings. It also adds... (or the corresponding Unicodecharacter if Unicode characters are allowed) to the end of truncatedstrings.
Usage
ansi_strtrim(x, width = console_width(), ellipsis = symbol$ellipsis)Arguments
x | Character vector of ANSI strings. |
width | The width to truncate to. |
ellipsis | The string to append to truncated strings. Supply anempty string if you don't want a marker. |
Details
Note:ansi_strtrim() does not support NA values currently.
See Also
Other ANSI string operations:ansi_align(),ansi_columns(),ansi_nchar(),ansi_strsplit(),ansi_strwrap(),ansi_substr(),ansi_substring(),ansi_toupper(),ansi_trimws()
Examples
text <- cli::col_red(cli:::lorem_ipsum())ansi_strtrim(c(text, "foobar"), 40)Wrap an ANSI styled string to a certain width
Description
This function is similar tobase::strwrap(), but works on ANSIstyled strings, and leaves the styling intact.
Usage
ansi_strwrap( x, width = console_width(), indent = 0, exdent = 0, simplify = TRUE)Arguments
x | ANSI string. |
width | Width to wrap to. |
indent | Indentation of the first line of each paragraph. |
exdent | Indentation of the subsequent lines of each paragraph. |
simplify | Whether to return all wrapped strings in a singlecharacter vector, or wrap each element of |
Value
Ifsimplify isFALSE, then a list of character vectors,each an ANSI string. Otherwise a single ANSI string vector.
See Also
Other ANSI string operations:ansi_align(),ansi_columns(),ansi_nchar(),ansi_strsplit(),ansi_strtrim(),ansi_substr(),ansi_substring(),ansi_toupper(),ansi_trimws()
Examples
text <- cli:::lorem_ipsum()# Highlight some words, that start with 's'rexp <- gregexpr("\\b([sS][a-zA-Z]+)\\b", text)regmatches(text, rexp) <- lapply(regmatches(text, rexp), col_red)cat(text)wrp <- ansi_strwrap(text, width = 40)cat(wrp, sep = "\n")Substring(s) of an ANSI colored string
Description
This is a color-aware counterpart ofbase::substr().It works exactly like the original, but keeps the colorsin the substrings. The ANSI escape sequences are ignored whencalculating the positions within the string.
Usage
ansi_substr(x, start, stop)Arguments
x | Character vector, potentially ANSI styled, or a vector tocoerced to character. |
start | Starting index or indices, recycled to match the lengthof |
stop | Ending index or indices, recycled to match the lengthof |
Value
Character vector of the same length asx, containingthe requested substrings. ANSI styles are retained.
See Also
Other ANSI string operations:ansi_align(),ansi_columns(),ansi_nchar(),ansi_strsplit(),ansi_strtrim(),ansi_strwrap(),ansi_substring(),ansi_toupper(),ansi_trimws()
Examples
str <- paste( col_red("red"), "default", col_green("green"))cat(str, "\n")cat(ansi_substr(str, 1, 5), "\n")cat(ansi_substr(str, 1, 15), "\n")cat(ansi_substr(str, 3, 7), "\n")substr(ansi_strip(str), 1, 5)substr(ansi_strip(str), 1, 15)substr(ansi_strip(str), 3, 7)str2 <- paste( "another", col_red("multi-", style_underline("style")), "text")cat(str2, "\n")cat(ansi_substr(c(str, str2), c(3,5), c(7, 18)), sep = "\n")substr(ansi_strip(c(str, str2)), c(3,5), c(7, 18))Substring(s) of an ANSI colored string
Description
This is the color-aware counterpart ofbase::substring().It works exactly like the original, but keeps the colors in thesubstrings. The ANSI escape sequences are ignored whencalculating the positions within the string.
Usage
ansi_substring(text, first, last = 1000000L)Arguments
text | Character vector, potentially ANSI styled, or a vector tocoerced to character. It is recycled to the longest of |
first | Starting index or indices, recycled to match the lengthof |
last | Ending index or indices, recycled to match the lengthof |
Value
Character vector of the same length asx, containingthe requested substrings. ANSI styles are retained.
See Also
Other ANSI string operations:ansi_align(),ansi_columns(),ansi_nchar(),ansi_strsplit(),ansi_strtrim(),ansi_strwrap(),ansi_substr(),ansi_toupper(),ansi_trimws()
Examples
str <- paste( col_red("red"), "default", col_green("green"))cat(str, "\n")cat(ansi_substring(str, 1, 5), "\n")cat(ansi_substring(str, 1, 15), "\n")cat(ansi_substring(str, 3, 7), "\n")substring(ansi_strip(str), 1, 5)substring(ansi_strip(str), 1, 15)substring(ansi_strip(str), 3, 7)str2 <- paste( "another", col_red("multi-", style_underline("style")), "text")cat(str2, "\n")cat(ansi_substring(str2, c(3,5), c(7, 18)), sep = "\n")substring(ansi_strip(str2), c(3,5), c(7, 18))ANSI character translation and case folding
Description
There functions are similar totoupper(),tolower() andchartr(), but they keep the ANSI colors of the string.
Usage
ansi_toupper(x)ansi_tolower(x)ansi_chartr(old, new, x)Arguments
x | Input string. May have ANSI colors and styles. |
old | a character string specifying the characters to betranslated. If a character vector of length 2 or more is supplied,the first element is used with a warning. |
new | a character string specifying the translations. If acharacter vector of length 2 or more is supplied, the first elementis used with a warning. |
Value
Character vector of the same length asx, containingthe translated strings. ANSI styles are retained.
See Also
Other ANSI string operations:ansi_align(),ansi_columns(),ansi_nchar(),ansi_strsplit(),ansi_strtrim(),ansi_strwrap(),ansi_substr(),ansi_substring(),ansi_trimws()
Other ANSI string operations:ansi_align(),ansi_columns(),ansi_nchar(),ansi_strsplit(),ansi_strtrim(),ansi_strwrap(),ansi_substr(),ansi_substring(),ansi_trimws()
Other ANSI string operations:ansi_align(),ansi_columns(),ansi_nchar(),ansi_strsplit(),ansi_strtrim(),ansi_strwrap(),ansi_substr(),ansi_substring(),ansi_trimws()
Examples
ansi_toupper(col_red("Uppercase"))ansi_tolower(col_red("LowerCase"))x <- paste0(col_green("MiXeD"), col_red(" cAsE 123"))ansi_chartr("iXs", "why", x)Remove leading and/or trailing whitespace from an ANSI string
Description
This function is similar tobase::trimws() but works on ANSI strings,and keeps color and other styling.
Usage
ansi_trimws(x, which = c("both", "left", "right"))Arguments
x | ANSI string vector. |
which | Whether to remove leading or trailing whitespace or both. |
Value
ANSI string, with the whitespace removed.
See Also
Other ANSI string operations:ansi_align(),ansi_columns(),ansi_nchar(),ansi_strsplit(),ansi_strtrim(),ansi_strwrap(),ansi_substr(),ansi_substring(),ansi_toupper()
Examples
trimws(paste0(" ", col_red("I am red"), " "))ansi_trimws(paste0(" ", col_red("I am red"), " "))trimws(col_red(" I am red "))ansi_trimws(col_red(" I am red "))The built-in CLI theme
Description
This theme is always active, and it is at the bottom of the themestack. Seethemes.
Usage
builtin_theme(dark = getOption("cli.theme_dark", "auto"))Arguments
dark | Whether to use a dark theme. The |
Value
A named list, a CLI theme.
Showcase
cli_h1("Heading 1")cli_h2("Heading 2")cli_h3("Heading 3")cli_par()cli_alert_danger("Danger alert")cli_alert_warning("Warning alert")cli_alert_info("Info alert")cli_alert_success("Success alert")cli_alert("Alert for starting a process or computation", class = "alert-start")cli_end()cli_text("Packages and versions: {.pkg cli} {.version 1.0.0}.")cli_text("Time intervals: {.timestamp 3.4s}")cli_text("{.emph Emphasis} and {.strong strong emphasis}")cli_text("This is a piece of code: {.code sum(x) / length(x)}")cli_text("Function names: {.fn cli::simple_theme}")cli_text("Files: {.file /usr/bin/env}")cli_text("URLs: {.url https://r-project.org}")cli_h2("Longer code chunk")cli_par(class = "code R")cli_verbatim( '# window functions are useful for grouped mutates', 'mtcars %>%', ' group_by(cyl) %>%', ' mutate(rank = min_rank(desc(mpg)))')#>──Heading 1───────────────────────────────────────────────────────── #> #> ──Heading 2 ── #> #> ── Heading 3 #>✖ Danger alert #>! Warning alert #>ℹ Info alert #>✔ Success alert #> → Alert for starting a process or computation #> #> Packages and versions:cli 1.0.0. #> Time intervals:[3.4s] #>Emphasis andstrong emphasis #> This is a piece of code: `sum(x) / length(x)` #> Function names: `cli::simple_theme()` #> Files:/usr/bin/env #> URLs:<https://r-project.org> #> #> ──Longer code chunk ── #> #># window functions are useful for grouped mutates #> mtcars%>% #>group_by(cyl)%>% #>mutate(rank =min_rank(desc(mpg)))
See Also
cat() helpers
Description
These helpers provide useful wrappers aroundcat(): most importantlythey all setsep = "", andcat_line() automatically adds a newline.
Usage
cat_line(..., col = NULL, background_col = NULL, file = stdout())cat_bullet( ..., col = NULL, background_col = NULL, bullet = "bullet", bullet_col = NULL, file = stdout())cat_boxx(..., file = stdout())cat_rule(..., file = stdout())cat_print(x, file = "")Arguments
... | For |
col,background_col,bullet_col | Colors for text, background, andbullets respectively. |
file | Output destination. Defaults to standard output. |
bullet | Name of bullet character. Indexes intosymbol |
x | An object to print. |
Examples
cat_line("This is ", "a ", "line of text.", col = "red")cat_bullet(letters[1:5])cat_bullet(letters[1:5], bullet = "tick", bullet_col = "green")cat_rule()Compose multiple cli functions
Description
cli() will record allcli_* calls inexpr, and emit them togetherin a single message. This is useful if you want to built a largerpiece of output from multiplecli_* calls.
Usage
cli(expr)Arguments
expr | Expression that contains |
Details
Use this function to build a more complex piece of CLI that would notmake sense to show in pieces.
cli({ cli_h1("Title") cli_h2("Subtitle") cli_ul(c("this", "that", "end"))})#> #>──Title───────────────────────────────────────────────────────────── #> #> ──Subtitle ── #> #> • this #> • that #> • end
Value
Nothing.
cli environment variables and options
Description
cli environment variables and options
User facing configuration
These are environment variables and options that users may set, to modifythe behavior of cli.
Hyperlinks
cli uses ANSI escape sequences to create hyperlinks.Specifically, cli createsOSC 8 hyperlinks that have this syntax:
OSC 8 ; {OPTIONAL PARAMS } ; {URI} ST {LINK TEXT} OSC 8 ; ; STUnder the hood,style_hyperlink() is the helper that forms these links, but it is more common to request them indirectly via inline markup (documented inhelp("links")).
R_CLI_HYPERLINK_MODE
Set toposix to force generating POSIX compatible ANSI hyperlinks.This is about the specific operating system command (OSC) and string terminator (ST) used in hyperlinks.
If not set, then RStudio compatible links are generated. This is atemporary crutch until RStudio handles POSIX hyperlinks correctly, andafter that it will be removed.
cli.hyperlink option andR_CLI_HYPERLINKS env var
Set this option or env var totrue,TRUE orTrue to tell cli that the terminal supports ANSI hyperlinks.Leave this configuration unset (or set to anything else) when there is no hyperlink support.Specifically, this configuration indicates the support for URL and file hyperlinks, requested via markup like{.href url} or{.file path/file}.(Below we describe the configuration that indicates support for even more specialized types of hyperlinks.)
The optioncli.hyperlink takes precedence over theR_CLI_HYPERLINKS env var.
cli.hyperlink_* options andR_CLI_HYPERLINK_* env vars
cli supports a few special types of hyperlink that go beyond pointing to, e.g., a webpage or a file.These specialized hyperlinks cause R-specific actions to happen, such as executing a bit of R code or opening specific documentation.
Set the relevant option or env var totrue,TRUE, orTrue to tell cli that the terminal is capable of implementing these specialized behaviours.Leave this configuration unset (or set to anything else) when there is no support for a specific type of hyperlink.
| Action | Example inline markup | Option | Env var |
| Run R code | {.run testthat::snapshot_review()} | cli.hyperlink_run | R_CLI_HYPERLINK_RUN |
| Open a help topic | {.fun stats::lm}{.topic tibble::tibble_options}{.help [{.fun lm}](stats::lm)} | cli.hyperlink_help | R_CLI_HYPERLINK_HELP |
| Open a vignette | {.vignette tibble::types} | cli.hyperlink_vignette | R_CLI_HYPERLINK_VIGNETTE |
In all cases, the option takes priority over the corresponding env var.
cli.hyperlink_*_url_format options andR_CLI_HYPERLINK_*_URL_FORMAT env vars
Recall the overall structure of cli's hyperlinks:
OSC 8 ; {OPTIONAL PARAMS } ; {URI} ST {LINK TEXT} OSC 8 ; ; STTheURI part has a default format for each type of hyperlink, but it is possible to provide a custom format via an option or an env var.If defined, the option takes priority over the env var.
| Action | Default URI format | Customize via option | Customize via env var |
| Open a file | (see below) | cli.hyperlink_file_url_format | R_CLI_HYPERLINK_FILE_URL_FORMAT |
| Run R code | x-r-run:{code} | cli.hyperlink_run_url_format | R_CLI_HYPERLINK_RUN_URL_FORMAT |
| Open a help topic | x-r-help:{topic} | cli.hyperlink_help_url_format | R_CLI_HYPERLINK_HELP_URL_FORMAT |
| Open a vignette | x-r-vignette:{vignette} | cli.hyperlink_vignette_url_format | R_CLI_HYPERLINK_VIGNETTE_URL_FORMAT |
A format must be a glue-like template with the relevant placeholder in curly braces (code,topic orvignette).
Here's an example of a custom URI format for runnable code, which is useful in an integrated Positron terminal:
positron://positron.positron-r/cli?command=x-r-run:{code}(For backwards compatibility with older versions of RStudio, in some contexts, a legacy format is used, e.g.ide:run:{code}.)
The default handling for file hyperlinks is geared towards the expectations of RStudio and can't really be expressed as a URI format, but it's approximatelyfile://{path}, plus possibly passingline andcol (yes, it really iscol, notcolumn) in theOPTIONAL PARAMS part of the OSC 8 hyperlink.
A custom format can be provided for file hyperlinks and the relevant placeholders arepath,line, andcolumn.Examples of custom file hyperlink formats:
positron://file{path}:{line}:{column}vscode://file{path}:{line}:{column}txmt://open?url=file://{path}&line={line}&column={column}It's OK if the format includes onlypath.
User facing environment variables
NO_COLOR
Set to a nonempty value to turn off ANSI colors.Seenum_ansi_colors().
ESS_BACKGROUND_MODE
Set this environment variable tolight ordark to indicate dark modein Emacs. Once https://github.com/emacs-ess/ESS/pull/1178 is merged, ESSwill set this automatically.
R_CLI_DYNAMIC
Set totrue,TRUE orTrue to assume a dynamic terminal, that supports\r.Set to anything else to assume a non-dynamic terminal.Seeis_dynamic_tty().
R_CLI_NUM_COLORS
Set to a positive integer to assume a given number of colors.Seenum_ansi_colors().
User facing options
cli.ansi
Set totrue,TRUE orTrue to assume a terminal that supports ANSIcontrol sequences.Set to anything else to assume a non-ANSI terminal.Seeis_ansi_tty().
cli.condition_unicode_bullets
TRUE orFALSE to force turn on or off the Unicode symbols when printingconditions. E.g. informat_error(),format_warning(),format_message() andalso incli_abort(),cli_warn() andcli_inform().
cli.condition_width
Integer scalar (orInf) to set the console width when cli is formattingerrors, warnings or messages informat_error(),format_warning() andformat_message(). When formatting conditions this option takes precedenceovercli.width.
cli.default_handler
General handler function for all cli conditions.Seehttps://cli.r-lib.org/articles/semantic-cli.html#cli-messages-1
cli.default_num_colors
Default number of ANSI colors. This value is used if the number of colorsis not already set by
the
cli.num_colorsoption,the
R_CLI_NUM_COLORSenvironment variable,the
crayon.enabledandcrayon.colorsoptions,the
NO_COLORenvironment variable,the
knitr.in.progressoption,a
sink()call for the stream.
You can also use this option if color support is detected correctly, butyou want to adjust the number of colors. E.g.
if
crayon.enabledisTRUE, butcrayon.colorsis not,in Emacs on Windows,
in terminals.
Seenum_ansi_colors(). See also thecli.num_colors option.
cli.dynamic
Set toTRUE to assume a dynamic terminal, that supports\r.Set to anything else to assume a non-dynamic terminal.Seeis_dynamic_tty().
cli.hide_cursor
Whether the cli status bar should try to hide the cursor on terminals.Set theFALSE if the hidden cursor causes issues.
cli.ignore_unknown_rstudio_theme
Set toTRUE to omit a warning for an unknown RStudio theme incode_highlight().
cli.num_colors
Number of ANSI colors. Seenum_ansi_colors(). See also thecli.default_num_colors option.
cli.message_class
Character vector of classes to add to cli's conditions.
cli.progress_bar_style
Progress bar style.Seecli_progress_styles().
cli.progress_bar_style_ascii
Progress bar style on ASCII consoles.Seecli_progress_styles().
cli.progress_bar_style_unicode
Progress bar style on Unicode (UTF-8) consoles;Seecli_progress_styles().
cli.progress_clear
Whether to clear terminated progress bar from the screen on dynamic terminals.Seecli_progress_bar().
cli.progress_demo_live
Whethercli_progress_demo() should show a live demo, or just record theprogress bar frames.
cli.progress_format_download
Default format string fordownload progress bars.
cli.progress_format_download_nototal
Default format string fordownload progress bars with unknown totals.
cli.progress_format_iterator
Default format string foriterator progress bars.
cli.progress_format_iterator_nototal
Default format string foriterator progress bars with unknown total numberof progress units.
cli.progress_format_tasks
Default format string fortasks progress bars.
cli.progress_format_tasks_nototal
Default format string fortasks progress bars with unknown totals.
cli.progress_handlers
Progress handlers to try.Seecli_progress_builtin_handlers().
cli.progress_handlers_force
Progress handlers that will always be used, even if another handlerwas already selected.Seecli_progress_builtin_handlers().
cli.progress_handlers_only
Progress handlers to force, ignoring handlers set incli.progress_handlers andcli.progress_handlers_force.Seecli_progress_builtin_handlers().
cli.progress_say_args
Command line arguments for thesay progress handlers.Seecli_progress_builtin_handlers().
cli.progress_say_command
External command to use in thesay progress handler.Seecli_progress_builtin_handlers().
cli.progress_say_frequency
Minimum delay betweensay calls in thesay progress handler.say ignores very frequent updates, to keep the speech comprehensible.Seecli_progress_builtin_handlers().
cli.progress_show_after
Delay before showing a progress bar, in seconds.Progress bars that finish before this delay are not shown at all.cli also shows progress bars that have more than 50% to go after half ofthis delay has passed.
cli.spinner
Default spinner to use, seeget_spinner().
cli.spinner_ascii
Default spinner to use on ASCII terminals, seeget_spinner().
cli.spinner_unicode
Default spinner to use on Unicode terminals, seeget_spinner().
cli.theme
Default cli theme, in addition to the built-in theme.This option in intended for the package developers.Seethemes andstart_app().
cli.theme_dark
Whether cli should assume a dark theme for the builtin theme.Seebuiltin_theme().
cli.unicode
Whether to assume a Unicode terminal.If not set, then it is auto-detected.Seeis_utf8_output().
cli.user_theme
cli user theme.This option is intended for end users.Seethemes.
cli.warn_inline_newlines
Whether to emit a warning when cli replaces newline characters withspaces within a{.class } inline style.Defaults toFALSE.
cli.width
Terminal width to assume.If not set, then it is auto-detected.Seeconsole_width().
rlib_interactive
Whether to assume an interactive R session.If not set, then it is auto-detected.
width
Terminal width.This is used on some platforms, ifcli.width is not set.
Internal configuration
These environment variables and options are for cli developers. Usersshould not rely on them as they may change between cli releases.
Internal environment variables
ASCIICAST
Used to detect an asciicast sub-process in RStudio.
ANSICON
Used to detect ANSICON when detecting the number of ANSI colors.
CI
Used to detect if the code is running on a CI.If yes, we avoid ANSI hyperlinks.
CLI_DEBUG_BAD_END
Whether to warn aboutcli_end() calls when there is no container to close.
CLI_NO_BUILTIN_THEME
Set it totrue to omit the builtin theme.
CLI_SPEED_TIME
Can be used to speed up cli's timer.It is a factor, e.g. setting it to 2 makes cli's time go twice as fast.
CLI_TICK_TIME
How often the cli timer should alert, in milliseconds.
CMDER_ROOT
Used to detect cmder when detecting the number of ANSI colors.
COLORTERM
Used when detecting ANSI color support.
ConEmuANSI
Used to detect ConEmu when detecting the number of ANSI colors.
EMACS
Used to detect Emacs.
INSIDE_EMACS
Used to detect Emacs.
NOT_CRAN
Set totrue to run tests / examples / checks, that do not run on CRAN.
_R_CHECK_PACKAGE_NAME_
Used to detectR CMD check.
R_BROWSER
Used to detect the RStudio build pane.
R_GUI_APP_VERSION
Used to detect R.app on macOS, to decide if the console has ANSI controlsequences.
R_PACKAGE_DIR
Used to detect if the code is running underR CMD INSTALL.
R_PDFVIEWER
Used to detect the RStudio build pane.
R_PROGRESS_NO_EXAMPLES
Set totrue to avoid running examples, outside ofR CMD check.
RSTUDIO
Used to detect RStudio, in various functions.
RSTUDIO_CONSOLE_COLOR
Used to detect the number of colors in RStudio.Seenum_ansi_colors().
RSTUDIO_CONSOLE_WIDTH
Used to auto-detect console width in RStudio.
RSTUDIO_TERM
Used to detect the RStudio build pane.
TEAMCITY_VERSION
Used to detect the TeamCity CI, to turn off ANSI hyperlinks.
TERM
Used to detect if the console has ANSI control sequences, in a terminal.
TERM_PROGRAM
Used to detect iTerm for the dark theme detection and the ANSI hyperlinksupport detection.
TERM_PROGRAM_VERSION
Used to detect a suitable iTerm version for ANSI hyperlink support.
TESTTHAT
Used to detect running in testthat tests.
VTE_VERSION
Used to detect a suitable VTE version for ANSI hyperlinks.
Internal options
cli__pb
This option is set to the progress bar that is being updated, wheninterpolating the format string.
cli.record
Internal option to mark the state that cli is recording messages.
crayon.colors
Deprecated option for the number of ANSI colors, that is still supportedby cli, when the new options are not set.Seenum_ansi_colors().
crayon.enabled
Deprecated option to turn ANSI colors on/off.This is still supported by cli when the new options are not set.Seenum_ansi_colors().
crayon.hyperlink
Whether to assume ANSI hyperlink support.Seeansi_has_hyperlink_support().
knitr.in.progress
Used to detect knitr when detecting interactive sessions and ANSI colorsupport.
rstudio.notebook.executing
Used to detect knitr when detecting interactive sessions.
Signal an error, warning or message with a cli formattedmessage
Description
These functions let you create error, warning or diagnosticmessages with cli formatting, including inline styling,pluralization and glue substitutions.
Usage
cli_abort( message, ..., call = .envir, .envir = parent.frame(), .frame = .envir)cli_warn(message, ..., .envir = parent.frame())cli_inform(message, ..., .envir = parent.frame())Arguments
message | It is formatted via a call to |
... | Passed to |
call | The execution environment of a currently runningfunction, e.g. You only need to supply Can also be For more information about error calls, seeIncluding function calls in error messages. |
.envir | Environment to evaluate the glue expressions in. |
.frame | The throwing context. Used as default for |
Details
n <- "boo"cli_abort(c( "{.var n} must be a numeric vector", "x" = "You've supplied a {.cls {class(n)}} vector."))#>Error: #>! `n` must be a numeric vector #>✖ You've supplied a<character> vector. #>Run `rlang::last_trace()` to see where the error occurred.
len <- 26idx <- 100cli_abort(c( "Must index an existing element:", "i" = "There {?is/are} {len} element{?s}.", "x" = "You've tried to subset element {idx}."))#>Error: #>! Must index an existing element: #>ℹ There are 26 elements. #>✖ You've tried to subset element 100. #>Run `rlang::last_trace()` to see where the error occurred.
See Also
These functions supportinline markup.
Other functions supporting inline markup:cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
CLI alerts
Description
Alerts are typically short status messages.
Usage
cli_alert(text, id = NULL, class = NULL, wrap = FALSE, .envir = parent.frame())cli_alert_success( text, id = NULL, class = NULL, wrap = FALSE, .envir = parent.frame())cli_alert_danger( text, id = NULL, class = NULL, wrap = FALSE, .envir = parent.frame())cli_alert_warning( text, id = NULL, class = NULL, wrap = FALSE, .envir = parent.frame())cli_alert_info( text, id = NULL, class = NULL, wrap = FALSE, .envir = parent.frame())Arguments
text | Text of the alert. |
id | Id of the alert element. Can be used in themes. |
class | Class of the alert element. Can be used in themes. |
wrap | Whether to auto-wrap the text of the alert. |
.envir | Environment to evaluate the glue expressions in. |
Details
Success
nbld <- 11tbld <- prettyunits::pretty_sec(5.6)cli_alert_success("Built {.emph {nbld}} status report{?s} in {tbld}.")#>✔ Built11 status reports in 5.6s.
Info
cfl <- "~/.cache/files/latest.cache"cli_alert_info("Updating cache file {.path {cfl}}.")#>ℹ Updating cache file~/.cache/files/latest.cache.
Warning
cfl <- "~/.cache/files/latest.cache"cli_alert_warning("Failed to update cache file {.path {cfl}}.")#>! Failed to update cache file~/.cache/files/latest.cache.
Danger
cfl <- "~/.config/report.yaml"cli_alert_danger("Cannot validate config file at {.path {cfl}}.")#>✖ Cannot validate config file at~/.config/report.yaml.
Text wrapping
Alerts are printed without wrapping, unless you setwrap = TRUE:
cli_alert_info("Data columns: {.val {names(mtcars)}}.")cli_alert_info("Data columns: {.val {names(mtcars)}}.", wrap = TRUE)#>ℹ Data columns:"mpg","cyl","disp","hp","drat","wt","qsec","vs","am","g#>ear", and"carb". #>ℹ Data columns:"mpg","cyl","disp","hp","drat","wt","qsec", #>"vs","am","gear", and"carb".
See Also
These functions supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
CLI block quote
Description
A section that is quoted from another source. It is typically indented.
Usage
cli_blockquote( quote, citation = NULL, id = NULL, class = NULL, .envir = parent.frame())Arguments
quote | Text of the quotation. |
citation | Source of the quotation, typically a link or the nameof a person. |
id | Element id, a string. If |
class | Class name, sting. Can be used in themes. |
.envir | Environment to evaluate the glue expressions in. It isalso used to auto-close the container if |
Details
evil <- paste( "The real problem is that programmers have spent far too much time", "worrying about efficiency in the wrong places and at the wrong", "times; premature optimization is the root of all evil (or at least", "most of it) in programming.")cli_blockquote(evil, citation = "Donald Ervin Knuth")
#> #>“The real problem is that programmers have spent far #>too much time worrying about efficiency in the wrong #>places and at the wrong times; premature optimization #>is the root of all evil (or at least most of it) in #>programming.” #>— Donald Ervin Knuth #>
See Also
This function supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
List of items
Description
It is often useful to print out a list of items, tasks a function orpackage performs, or a list of notes.
Usage
cli_bullets(text, id = NULL, class = NULL, .envir = parent.frame())Arguments
text | Character vector of items. See details below on how namesare interpreted. |
id | Optional id of the |
class | Optional additional class(es) for the |
.envir | Environment to evaluate the glue expressions in. |
Details
Items may be formatted differently, e.g. they can have a prefix symbol.Formatting is specified by the names oftext, and can be themed.cli creates adiv element of classbullets for the whole bullet list.Each item is anotherdiv element of classbullet-<name>, where<name> is the name of the entry intext. Entries intext withouta name create adiv element of classbullet-empty, and if thename is a single space character, the class isbullet-space.
The built-in theme defines the following item types:
No name: Item without a prefix.
: Indented item.*: Item with a bullet.>: Item with an arrow or pointer.v: Item with a green "tick" symbol, likecli_alert_success().x: Item with a ref cross, likecli_alert_danger().!: Item with a yellow exclamation mark, likecli_alert_warning().i: Info item, likecli_alert_info().
You can define new item type by simply defining theming for thecorrespondingbullet-<name> classes.
cli_bullets(c( "noindent", " " = "indent", "*" = "bullet", ">" = "arrow", "v" = "success", "x" = "danger", "!" = "warning", "i" = "info"))
#> noindent #> indent #>• bullet #> → arrow #>✔ success #>✖ danger #>! warning #>ℹ info
See Also
This function supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
List of verbatim items
Description
cli_format_bullets_raw() is similar tocli_bullets(), but it doesnot perform any inline styling or glue substitutions in the input.
Usage
cli_bullets_raw(text, id = NULL, class = NULL)format_bullets_raw(text, id = NULL, class = NULL)Arguments
text | Character vector of items. See details below on how namesare interpreted. |
id | Optional id of the |
class | Optional additional class(es) for the |
Details
format_bullets_raw() returns the output instead of printing it.
See Also
These functions supportinline markup.
Seecli_bullets() for examples.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
A block of code
Description
A helper function that creates adiv with classcode and then callscli_verbatim() to output code lines. The builtin theme formats thesecontainers specially. In particular, it adds syntax highlighting tovalid R code.
Usage
cli_code( lines = NULL, ..., language = "R", .auto_close = TRUE, .envir = environment())Arguments
lines | Character vector, each line will be a line of code, andnewline characters also create new lines. Note thatno gluesubstitution is performed on the code. |
... | More character vectors, they are appended to |
language | Programming language. This is also added as a class,in addition to |
.auto_close | Passed to |
.envir | Passed to |
Details
myfun <- function() { message("Just an example function") graphics::pairs(iris, col = 1:4)}cli_code(format(myfun))#>function() #>{ #>message("Just an example function") #> graphics::pairs(iris, col =1:4) #>}
Value
The id of the container that contains the code.
Debug cli internals
Description
Return the current state of a cli app. It includes the currentlyopen tags, their ids, classes and their computed styles.
Usage
cli_debug_doc(app = default_app() %||% start_app())Arguments
app | The cli app to debug. Defaults to the current app.if there is no app, then it creates one by calling |
Details
The returned data frame has a print method, and if you want to createa plain data frame from it, index it with an empty bracket:cli_debug_doc()[].
To see all currently active themes, useapp$themes, e.g. for thedefault app:default_app()$themes.
Value
Data frame with columns:tag,id,class (space separated),theme (id of the theme the element added),styles (computed stylesfor the element).
See Also
cli_sitrep(). To debug containers, you can set theCLI-DEBUG_BAD_END environment variable totrue, and then cli willwarn when it cannot find the specified container to close (or anycontained at all).
Examples
## Not run: cli_debug_doc()olid <- cli_ol()cli_li()cli_debug_doc()cli_debug_doc()[]cli_end(olid)cli_debug_doc()## End(Not run)Generic CLI container
Description
Seecontainers. Acli_div container is special, because it mayadd new themes, that are valid within the container.
Usage
cli_div( id = NULL, class = NULL, theme = NULL, .auto_close = TRUE, .envir = parent.frame())Arguments
id | Element id, a string. If |
class | Class name, sting. Can be used in themes. |
theme | A custom theme for the container. Seethemes. |
.auto_close | Whether to close the container, when the callingfunction finishes (or |
.envir | Environment to evaluate the glue expressions in. It isalso used to auto-close the container if |
Details
Custom themes
d <- cli_div(theme = list(h1 = list(color = "cyan", "font-weight" = "bold")))cli_h1("Custom title")cli_end(d)#> #>Custom titleAuto-closing
By default acli_div() is closed automatically when the callingframe exits.
div <- function() { cli_div(class = "tmp", theme = list(.tmp = list(color = "yellow"))) cli_text("This is yellow")}div()cli_text("This is not yellow any more")#>This is yellow #> This is not yellow any moreValue
The id of the new container element, invisibly.
Definition list
Description
A definition list is a container, seecontainers.
Usage
cli_dl( items = NULL, labels = names(items), id = NULL, class = NULL, .close = TRUE, .auto_close = TRUE, .envir = parent.frame())Arguments
items | Named character vector, or |
labels | Item labels. Defaults the names in |
id | Id of the list container. Can be used for closing it with |
class | Class of the list container. Can be used in themes. |
.close | Whether to close the list container if the |
.auto_close | Whether to close the container, when the callingfunction finishes (or |
.envir | Environment to evaluate the glue expressions in. It isalso used to auto-close the container if |
Details
All items at once
fun <- function() { cli_dl(c(foo = "one", bar = "two", baz = "three"))}fun()#> foo: one #> bar: two #> baz: three
Items one by one
fun <- function() { cli_dl() cli_li(c(foo = "{.emph one}")) cli_li(c(bar = "two")) cli_li(c(baz = "three"))}fun()#> foo:one #> bar: two #> baz: threeValue
The id of the new container element, invisibly.
See Also
This function supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
Close a CLI container
Description
Containers aut0-close by default, but sometimes you need to explicitlyclose them. Closing a container also closes all of its nestedcontainers.
Usage
cli_end(id = NULL)Arguments
id | Id of the container to close. If missing, the currentcontainer is closed, if any. |
Details
Explicit closing
cnt <- cli_par()cli_text("First paragraph.")cli_end(cnt)cnt <- cli_par()cli_text("Second paragraph.")cli_end(cnt)#> First paragraph. #> #> Second paragraph. #>
Closing a stack of containers
list <- cli_ul()cli_li("Item one:")cli_li("Item two:")cli_par()cli_text("Still item two.")cli_end(list)cli_text("Not in the list any more")#> • Item one: #> • Item two: #> Still item two. #> #> Not in the list any more
Omittingid
Ifid is omitted, the container that was opened last will be closed.
cli_par()cli_text("First paragraph")cli_end()cli_par()cli_text("Second paragraph")cli_end()#> First paragraph #> #> Second paragraph #>
Debugging containers
You can use the internalcli:::cli_debug_doc() function to see thecurrently open containers.
fun <- function() { cli_div(id = "mydiv") cli_par(class = "myclass") cli:::cli_debug_doc()}fun()#> <cli document> #> <body> #> <div> +theme #> <par>
Capture the output of cli functions instead of printing it
Description
Capture the output of cli functions instead of printing it
Usage
cli_fmt(expr, collapse = FALSE, strip_newline = FALSE)Arguments
expr | Expression to evaluate, containing |
collapse | Whether to collapse the output into a single characterscalar, or return a character vector with one element for each line. |
strip_newline | Whether to strip the trailing newline. |
Examples
cli_fmt({ cli_alert_info("Loading data file") cli_alert_success("Loaded data file")})Format a value for printing
Description
This function can be used directly, or via the{.val ...} inlinestyle.{.val {expr}} callscli_format() automatically on the valueofexpr, before styling and collapsing it.
Usage
cli_format(x, style = NULL, ...)## Default S3 method:cli_format(x, style = NULL, ...)## S3 method for class 'character'cli_format(x, style = NULL, ...)## S3 method for class 'numeric'cli_format(x, style = NULL, ...)Arguments
x | The object to format. |
style | List of formatting options, see the individual methodsfor the style options they support. |
... | Additional arguments for methods. |
Details
Default style
months <- month.name[1:3]cli_text("{.val {months}}")#>"January","February", and"March"
nums <- 1:5 / 7cli_text("{.val {nums}}")#>0.142857142857143,0.285714285714286,0.428571428571429, #>0.571428571428571, and0.714285714285714
Styling with themes
nums <- 1:5 / 7divid <- cli_div(theme = list(.val = list(digits = 3)))cli_text("{.val {nums}}")cli_end(divid)#>0.143,0.286,0.429,0.571, and0.714
It is possible to define new S3 methods forcli_format and thenthese will be used automatically for{.val ...} expressions.
cli_format.month <- function(x, style = NULL, ...) { x <- encodeString(substr(x, 1, 3), quote = "\"") NextMethod("cli_format")}registerS3method("cli_format", "month", cli_format.month)months <- structure(month.name[1:3], class = "month")cli_text("{.val {months}}")#>"Jan","Feb", and"Mar"
See Also
Create a format method for an object using cli tools
Description
This method can be typically used informat() S3 methods. Then theprint() method of the class can be easily defined in terms of such aformat() method. See examples below.
Usage
cli_format_method(expr, theme = getOption("cli.theme"))Arguments
expr | Expression that calls |
theme | Theme to use for the formatting. |
Value
Character vector, one element for each line of the printout.
Examples
# Let's create format and print methods for a new S3 class that# represents the an installed R package: `r_package`# An `r_package` will contain the DESCRIPTION metadata of the package# and also its installation path.new_r_package <- function(pkg) { tryCatch( desc <- packageDescription(pkg), warning = function(e) stop("Cannot find R package `", pkg, "`") ) file <- dirname(attr(desc, "file")) if (basename(file) != pkg) file <- dirname(file) structure( list(desc = unclass(desc), lib = dirname(file)), class = "r_package" )}format.r_package <- function(x, ...) { cli_format_method({ cli_h1("{.pkg {x$desc$Package}} {cli::symbol$line} {x$desc$Title}") cli_text("{x$desc$Description}") cli_ul(c( "Version: {x$desc$Version}", if (!is.null(x$desc$Maintainer)) "Maintainer: {x$desc$Maintainer}", "License: {x$desc$License}" )) if (!is.na(x$desc$URL)) cli_text("See more at {.url {x$desc$URL}}") })}# Now the print method is easy:print.r_package <- function(x, ...) { cat(format(x, ...), sep = "\n")}# Try it outnew_r_package("cli")# The formatting of the output depends on the current theme:opt <- options(cli.theme = simple_theme())print(new_r_package("cli"))options(opt) # <- restore themeCLI headings
Description
cli has three levels of headings.
Usage
cli_h1(text, id = NULL, class = NULL, .envir = parent.frame())cli_h2(text, id = NULL, class = NULL, .envir = parent.frame())cli_h3(text, id = NULL, class = NULL, .envir = parent.frame())Arguments
text | Text of the heading. It can contain inline markup. |
id | Id of the heading element, string. It can be used in themes. |
class | Class of the heading element, string. It can be used inthemes. |
.envir | Environment to evaluate the glue expressions in. |
Details
This is how the headings look with the default builtin theme.
cli_h1("Header {.emph 1}")cli_h2("Header {.emph 2}")cli_h3("Header {.emph 3}")#> #>──Header1────────────────────────────────────────────────────────── #> #> ──Header2 ── #> #> ── Header3
See Also
These functions supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
CLI list item(s)
Description
A list item is a container, seecontainers.
Usage
cli_li( items = NULL, labels = names(items), id = NULL, class = NULL, .auto_close = TRUE, .envir = parent.frame())Arguments
items | Character vector of items, or |
labels | For definition lists the item labels. |
id | Id of the new container. Can be used for closing it with |
class | Class of the item container. Can be used in themes. |
.auto_close | Whether to close the container, when the callingfunction finishes (or |
.envir | Environment to evaluate the glue expressions in. It isalso used to auto-close the container if |
Details
Nested lists
fun <- function() { ul <- cli_ul() cli_li("one:") cli_ol(letters[1:3]) cli_li("two:") cli_li("three") cli_end(ul)}fun()#> • one: #> 1. a #> 2. b #> 3. c #> • two: #> • three
Value
The id of the new container element, invisibly.
See Also
This function supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
List the currently active themes
Description
If there is no active app, then it callsstart_app().
Usage
cli_list_themes()Value
A list of data frames with the active themes.Each data frame row is a style that applies to selected CLI tree nodes.Each data frame has columns:
selector: The original CSS-like selector string. Seethemes.parsed: The parsed selector, as used by cli for matching to nodes.style: The original style.cnt: The id of the container the style is currently applied to, orNAif the style is not used.
See Also
Ordered CLI list
Description
An ordered list is a container, seecontainers.
Usage
cli_ol( items = NULL, id = NULL, class = NULL, .close = TRUE, .auto_close = TRUE, .envir = parent.frame())Arguments
items | If not |
id | Id of the list container. Can be used for closing it with |
class | Class of the list container. Can be used in themes. |
.close | Whether to close the list container if the |
.auto_close | Whether to close the container, when the callingfunction finishes (or |
.envir | Environment to evaluate the glue expressions in. It isalso used to auto-close the container if |
Details
Adding all items at once
fun <- function() { cli_ol(c("one", "two", "three"))}fun()#> 1. one #> 2. two #> 3. three
Adding items one by one
## Adding items one by onefun <- function() { cli_ol() cli_li("{.emph one}") cli_li("{.emph two}") cli_li("{.emph three}") cli_end()}fun()#> 1.one #> 2.two #> 3.three
Nested lists
fun <- function() { cli_div(theme = list(ol = list("margin-left" = 2))) cli_ul() cli_li("one") cli_ol(c("foo", "bar", "foobar")) cli_li("two") cli_end() cli_end()}fun()#> • one #> 1. foo #> 2. bar #> 3. foobar #> • two
Value
The id of the new container element, invisibly.
See Also
This function supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
The connection option that cli would use
Description
Note that this only refers to the current R process. If the outputis produced in another process, then it is not relevant.
Usage
cli_output_connection()Details
In interactive sessions the standard output is chosen, otherwise thestandard error is used. This is to avoid painting output messages redin the R GUIs.
Value
Connection object.
CLI paragraph
Description
The builtin theme leaves an empty line between paragraphs.See alsocontainers.
Usage
cli_par(id = NULL, class = NULL, .auto_close = TRUE, .envir = parent.frame())Arguments
id | Element id, a string. If |
class | Class name, sting. Can be used in themes. |
.auto_close | Whether to close the container, when the callingfunction finishes (or |
.envir | Environment to evaluate the glue expressions in. It isalso used to auto-close the container if |
Details
clifun <- function() { cli_par() cli_text(cli:::lorem_ipsum())}clifun()clifun()#> Sunt anim ullamco Lorem qui mollit anim est in deserunt adipisicing. #> Enim deserunt laborum ad qui qui. Anim esse non anim magna Lorem #> consequat dolore labore cupidatat magna et. Esse nulla eiusmod Lorem #> exercitation cupidatat velit enim exercitation excepteur non officia #> incididunt. Id laborum dolore commodo Lorem esse ea sint proident. #> #> Fugiat mollit in Lorem velit qui exercitation ipsum consectetur ad #> nisi ut eu do ullamco. Mollit officia reprehenderit culpa Lorem est #> reprehenderit excepteur enim magna incididunt ea. Irure nisi ad #> exercitation deserunt enim anim excepteur quis minim laboris veniam #> nulla pariatur. Enim irure aute nulla irure qui non. Minim velit #> proident sunt sint. Proident sit occaecat ex aute. #>
Value
The id of the new container element, invisibly.
Indicate the start and termination of some computation in the status bar(superseded)
Description
Thecli_process_*() functions are superseded bythecli_progress_message() andcli_progress_step() functions,because they have a better default behavior.
Typically you callcli_process_start() to start the process, and thencli_process_done() when it is done. If an error happens beforecli_process_done() is called, then cli automatically shows the messagefor unsuccessful termination.
Usage
cli_process_start( msg, msg_done = paste(msg, "... done"), msg_failed = paste(msg, "... failed"), on_exit = c("auto", "failed", "done"), msg_class = "alert-info", done_class = "alert-success", failed_class = "alert-danger", .auto_close = TRUE, .envir = parent.frame())cli_process_done( id = NULL, msg_done = NULL, .envir = parent.frame(), done_class = "alert-success")cli_process_failed( id = NULL, msg = NULL, msg_failed = NULL, .envir = parent.frame(), failed_class = "alert-danger")Arguments
msg | The message to show to indicate the start of the process orcomputation. It will be collapsed into a single string, and the firstline is kept and cut to |
msg_done | The message to use for successful termination. |
msg_failed | The message to use for unsuccessful termination. |
on_exit | Whether this process should fail or terminatesuccessfully when the calling function (or the environment in |
msg_class | The style class to add to the message. Use an emptystring to suppress styling. |
done_class | The style class to add to the successful terminationmessage. Use an empty string to suppress styling.a |
failed_class | The style class to add to the unsuccessfultermination message. Use an empty string to suppress styling.a |
.auto_close | Whether to clear the status bar when the callingfunction finishes (or |
.envir | Environment to evaluate the glue expressions in. It isalso used to auto-clear the status bar if |
id | Id of the status bar container to clear. If |
Details
If you handle the errors of the process or computation, then you can dothe opposite: callcli_process_start() withon_exit = "done", andin the error handler callcli_process_failed(). cli will automaticallycallcli_process_done() on successful termination, when the callingfunction finishes.
See examples below.
Value
Id of the status bar container.
See Also
This function supportsinline markup.
Thecli_progress_message() andcli_progress_step()functions, for a superior API.
Other status bar:cli_status(),cli_status_clear(),cli_status_update()
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
Examples
## Failure by defaultfun <- function() { cli_process_start("Calculating") if (interactive()) Sys.sleep(1) if (runif(1) < 0.5) stop("Failed") cli_process_done()}tryCatch(fun(), error = function(err) err)## Success by defaultfun2 <- function() { cli_process_start("Calculating", on_exit = "done") tryCatch({ if (interactive()) Sys.sleep(1) if (runif(1) < 0.5) stop("Failed") }, error = function(err) cli_process_failed())}fun2()Add a progress bar to a mapping function or for loop
Description
Note that this function is currently experimental!
Usecli_progress_along() in a mapping function or in a for loop, to add aprogress bar. It usescli_progress_bar() internally.
Usage
cli_progress_along( x, name = NULL, total = length(x), ..., .envir = parent.frame())Arguments
x | Sequence to add the progress bar to. |
name | Name of the progress bar, a label, passed to |
total | Passed to |
... | Passed to |
.envir | Passed to |
Details
for loop
Afor loop withcli_progress_along() looks like this:
for (i in cli_progress_along(seq)) { ...}A complete example:
clifun <- function() { for (i in cli_progress_along(1:100, "Downloading")) { Sys.sleep(4/100) }}clifun()lapply() and other mapping functions
They will look like this:
lapply(cli_progress_along(X), function(i) ...)
A complete example:
res <- lapply(cli_progress_along(1:100, "Downloading"), function(i) { Sys.sleep(4/100)})Custom format string
clifun <- function() { for (i in cli_progress_along(1:100, format = "Downloading data file {cli::pb_current}")) { Sys.sleep(4/100) }}clifun()Breaking out of loops
Note that if you usebreak in thefor loop, you probably want toterminate the progress bar explicitly when breaking out of the loop,or right after the loop:
for (i in cli_progress_along(seq)) { ... if (cond) cli_progress_done() && break ...}Value
An index vector from 1 tolength(x) that triggers progressupdates as you iterate over it.
See Also
This function supportsinline markup.
cli_progress_bar() and the traditional progress bar API.
Other progress bar functions:cli_progress_bar(),cli_progress_builtin_handlers(),cli_progress_message(),cli_progress_num(),cli_progress_output(),cli_progress_step(),cli_progress_styles(),progress-variables
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
cli progress bars
Description
This is the reference manual of the three functions that create,update and terminate progress bars. For a tutorial see thecli progress bars.
cli_progress_bar() creates a new progress bar.
cli_progress_update() updates the state of a progress bar, andpotentially the display as well.
cli_progress_done() terminates a progress bar.
Usage
cli_progress_bar( name = NULL, status = NULL, type = c("iterator", "tasks", "download", "custom"), total = NA, format = NULL, format_done = NULL, format_failed = NULL, clear = getOption("cli.progress_clear", TRUE), current = TRUE, auto_terminate = type != "download", extra = NULL, .auto_close = TRUE, .envir = parent.frame())cli_progress_update( inc = NULL, set = NULL, total = NULL, status = NULL, extra = NULL, id = NULL, force = FALSE, .envir = parent.frame())cli_progress_done(id = NULL, .envir = parent.frame(), result = "done")Arguments
name | This is typically used as a label, and should be short,at most 20 characters. |
status | New status string of the progress bar, if not |
type | Type of the progress bar. It is used to select a defaultdisplay if
|
total | Total number of progress units, or |
format | Format string. It has to be specified for custom progressbars, otherwise it is optional, and a default display is selectedbased on the progress bat type and whether the number of total unitsis known. Format strings may contain glue substitution, the supportpluralization and cli styling. Seeprogress-variables for specialvariables that you can use in the custom format. |
format_done | Format string for successful termination. By defaultthe same as |
format_failed | Format string for unsuccessful termination. Bydefault the same as |
clear | Whether to remove the progress bar from the screen afterit has terminated. Defaults to the |
current | Whether to use this progress bar as the current progressbar of the calling function. See more at 'The current progress bar'below. |
auto_terminate | Whether to terminate the progress bar if thenumber of current units reaches the number of total units. |
extra | Extra data to add to the progress bar. This can beused in custom format strings for example. It should be a named list. |
.auto_close | Whether to terminate the progress bar when thecalling function (or the one with execution environment in |
.envir | The environment to use for auto-termination and for gluesubstitution. It is also used to find and set the current progress bar. |
inc | Increment in progress units. This is ignored if |
set | Set the current number of progress units to this value.Ignored if |
id | Progress bar to update or terminate. If |
force | Whether to force a display update, even if no update isdue. |
result | String to select successful or unsuccessful termination.It is only used if the progress bar is not cleared from the screen.It can be one of |
Details
Basic usage
cli_progress_bar() creates a progress bar,cli_progress_update()updates an existing progress bar, andcli_progress_done() terminatesit.
It is good practice to always set thename argument, to make theprogress bar more informative.
clean <- function() { cli_progress_bar("Cleaning data", total = 100) for (i in 1:100) { Sys.sleep(5/100) cli_progress_update() } cli_progress_done()}clean()Progress bar types
There are three builtin types of progress bars, and a custom type.
tasks <- function() { cli_progress_bar("Tasks", total = 3, type = "tasks") for (i in 1:3) { Sys.sleep(1) cli_progress_update() } cli_progress_done()}tasks()Unknowntotal
Iftotal is not known, then cli shows a different progress bar.Note that you can also settotal incli_progress_update(), if itnot known when the progress bar is created, but you learn it later.
nototal <- function() { cli_progress_bar("Parameter tuning") for (i in 1:100) { Sys.sleep(3/100) cli_progress_update() } cli_progress_done()}nototal()Clearing the progress bar
By default cli removes terminated progress bars from the screen, ifthe terminal supports this. If you want to change this, use theclear argument ofcli_progress_bar(), or thecli.progress_clearglobal option (seecli-config) to change this.
(In the cli documentation we usually setcli.progress_clear toFALSE,so users can see how finished progress bars look.)
In this example the first progress bar is cleared, the second is not.
fun <- function() { cli_progress_bar("Data cleaning", total = 100, clear = TRUE) for (i in 1:100) { Sys.sleep(3/100) cli_progress_update() } cli_progress_bar("Parameter tuning", total = 100, clear = FALSE) for (i in 1:100) { Sys.sleep(3/100) cli_progress_update() }}fun()Initial delay
Updating a progress bar on the screen is costly, so cli tries to avoidit for quick loops. By default a progress bar is only shown after twoseconds, or after half of that if less than 50% of the iterations arecomplete. You can change the two second default with thecli.progress_show_after global option (seecli-config).
(In the cli documentation we usually setcli.progress_show_after to0 (zero seconds), so progress bars are shown immediately.)
In this example we only show the progress bar after one second, becausemore than 50% of the iterations remain after one second.
fun <- function() { cli_alert("Starting now, at {Sys.time()}") cli_progress_bar( total = 100, format = "{cli::pb_bar} {pb_percent} @ {Sys.time()}" ) for (i in 1:100) { Sys.sleep(4/100) cli_progress_update() }}options(cli.progress_show_after = 2)fun()Thecurrent progress bar
By default cli sets the new progress bar as thecurrent progress barof the calling function. The current progress bar is the default onein cli progress bar operations. E.g. if no progress bar id is suppliedincli_progress_update(), then the current progress bar is updated.
Every function can only have a singlecurrent progress bar, and if anew one is created, then the previous one (if any) is automaticallyterminated. The current progress bar is also terminated when the functionthat created it exits. Thanks to these rules, most often you don't needto explicitly deal with progress bar ids, and you don't need toexplicitly callcli_progress_done():
fun <- function() { cli_progress_bar("First step ", total = 100) for (i in 1:100) { Sys.sleep(2/100) cli_progress_update() } cli_progress_bar("Second step", total = 100) for (i in 1:100) { Sys.sleep(2/100) cli_progress_update() }}fun()cli output while the progress bar is active
cli allows emitting regular cli output (alerts, headers, lists, etc.)while a progress bar is active. On terminals that support this, cliwill remove the progress bar temporarily, emit the output, and thenrestores the progress bar.
fun <- function() { cli_alert_info("Before the progress bar") cli_progress_bar("Calculating", total = 100) for (i in 1:50) { Sys.sleep(4/100) cli_progress_update() } cli_alert_info("Already half way!") for (i in 1:50) { Sys.sleep(4/100) cli_progress_update() } cli_alert_info("All done")}fun()See alsocli_progress_output(), which sends text for the currentprogress handler. E.g. in a Shiny app it will send the output to theShiny progress bar, as opposed to thecli_alert() etc. cli functionswhich will print the text to the console.
Custom formats
In addition to the builtin types, you can also specify a customformat string. In this caseprogress variablesare probably useful to avoid calculating some progress bar quantitieslike the elapsed time, of the ETA manually. You can also use your ownvariables in the calling function:
fun <- function(urls) { cli_progress_bar( format = paste0( "{pb_spin} Downloading {.path {basename(url)}} ", "[{pb_current}/{pb_total}] ETA:{pb_eta}" ), format_done = paste0( "{col_green(symbol$tick)} Downloaded {pb_total} files ", "in {pb_elapsed}." ),, total = length(urls) ) for (url in urls) { cli_progress_update() Sys.sleep(5/10) }}fun(paste0("https://acme.com/data-", 1:10, ".zip"))Value
cli_progress_bar() returns the id of the new progress bar.The id is a string constant.
cli_progress_update() returns the id of the progress bar,invisibly.
cli_progress_done() returnsTRUE, invisibly, always.
See Also
These functions supportinline markup.
cli_progress_message() andcli_progress_step() for simplerprogress messages.
Other progress bar functions:cli_progress_along(),cli_progress_builtin_handlers(),cli_progress_message(),cli_progress_num(),cli_progress_output(),cli_progress_step(),cli_progress_styles(),progress-variables
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
cli progress handlers
Description
The progress handler(s) to use can be selected with global options.
Usage
cli_progress_builtin_handlers()Details
There are three options that specify which handlers will be selected,but most of the time you only need to use one of them. You can set theseoptions to a character vector, the names of the built-in cli handlers youwant to use:
If
cli.progress_handlers_onlyis set, then these handlers are used,without considering others and without checking if they are able tohandle a progress bar. This option is mainly intended for testingpurposes.The handlers named in
cli.progress_handlersare checked if they areable to handle the progress bar, and from the ones that are, the firstone is selected. This is usually the option that the end use would wantto set.The handlers named in
cli.progress_handlers_forceare always appendedto the ones selected viacli.progress_handlers. This option is usefulto add an additional handler, e.g. a logger that writes to a file.
Value
cli_progress_builtin_handlers() returns the names of thecurrently supported progress handlers.
The built-in progress handlers
cli
Use cli's internal status bar, the last line of the screen, to show theprogress bar. This handler is always able to handle all progress bars.
logger
Log progress updates to the screen, with one line for each update and withtime stamps. This handler is always able to handle all progress bars.
progressr
Use the progressr package to createprogress bars. This handler is always able to handle all progress bars.(The progressr package needs to be installed.)
rstudio
UseRStudio's job panelto show the progress bars. This handler is available at the RStudio console,in recent versions of RStudio.
say
Use the macOSsay command to announce progress events in speech (typeman say on a terminal for more info). Set thecli.progress_say_frequencyoption to set the minimum delay betweensay invocations, the default isthree seconds. This handler is available on macOS, if thesay command ison the path.
The external command and its arguments can be configured with options:
cli_progress_say_args: command line arguments, e.g. you can use thisto select a voice on macOS,cli_progress_say_command: external command to run,cli_progress_say_frequency: wait at least this many seconds betweencalling the external command.
shiny
Useshiny's progress bars.This handler is available if a shiny app is running.
See Also
Other progress bar functions:cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_num(),cli_progress_output(),cli_progress_step(),cli_progress_styles(),progress-variables
cli progress bar demo
Description
Useful for experimenting with format strings and for documentation.It creates a progress bar, iterates it until it terminates and saves theprogress updates.
Usage
cli_progress_demo( name = NULL, status = NULL, type = c("iterator", "tasks", "download", "custom"), total = NA, .envir = parent.frame(), ..., at = if (is_interactive()) NULL else 50, show_after = 0, live = NULL, delay = 0, start = as.difftime(5, units = "secs"))Arguments
name | Passed to |
status | Passed to |
type | Passed to |
total | Passed to |
.envir | Passed to |
... | Passed to |
at | The number of progress units to show and capture the progressbar at. If |
show_after | Delay to show the progress bar. Overrides the |
live | Whether to show the progress bat on the screen, or justreturn the recorded updates. Defaults to the value of the |
delay | Delay between progress bar updates. |
start | Time to subtract from the start time, to simulate aprogress bar that takes longer to run. |
Value
List with classcli_progress_demo, which has a print and aformat method for pretty printing. Thelines entry contains theoutput lines, each corresponding to one update.
Simplified cli progress messages
Description
This is a simplified progress bar, a single (dynamic)message, without progress units.
Usage
cli_progress_message( msg, current = TRUE, .auto_close = TRUE, .envir = parent.frame(), ...)Arguments
msg | Message to show. It may contain glue substitution and clistyling. It can be updated via |
current | Passed to |
.auto_close | Passed to |
.envir | Passed to |
... | Passed to |
Details
cli_progress_message() always shows the message, even if noupdate is due. When the progress message is terminated, it is removedfrom the screen by default.
Note that the message can be dynamic: if you update it withcli_progress_update(), then cli uses the current values in the stringsubstitutions.
fun <- function() { cli_progress_message("Task one is running...") Sys.sleep(2) cli_progress_message("Task two is running...") Sys.sleep(2) step <- 1L cli_progress_message("Task three is underway: step {step}") for (step in 1:5) { Sys.sleep(0.5) cli_progress_update() }}fun()Value
The id of the new progress bar.
See Also
This function supportsinline markup.
cli_progress_bar() for the complete progress bar API.cli_progress_step() for a similar display that is styled by default.
Other progress bar functions:cli_progress_along(),cli_progress_bar(),cli_progress_builtin_handlers(),cli_progress_num(),cli_progress_output(),cli_progress_step(),cli_progress_styles(),progress-variables
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
Progress bar utility functions.
Description
Progress bar utility functions.
Usage
cli_progress_num()cli_progress_cleanup()Details
cli_progress_num() returns the number of currentlyactive progress bars. (These do not currently include the progressbars created in C/C++ code.)
cli_progress_cleanup() terminates all active progress bars.(It currently ignores progress bars created in the C/C++ code.)
Value
cli_progress_num() returns an integer scalar.
'cli_progress_cleanup() does not return anything.
See Also
Other progress bar functions:cli_progress_along(),cli_progress_bar(),cli_progress_builtin_handlers(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_progress_styles(),progress-variables
Add text output to a progress bar
Description
The text is calculated viacli_text(), so all cli features can beused here, including progress variables.
Usage
cli_progress_output(text, id = NULL, .envir = parent.frame())Arguments
text | Text to output. It is formatted via |
id | Progress bar id. The default is the current progress bar. |
.envir | Environment to use for glue interpolation of |
Details
The text is passed to the progress handler(s), that may or may not beable to print it.
fun <- function() { cli_alert_info("Before the progress bar") cli_progress_bar("Calculating", total = 100) for (i in 1:50) { Sys.sleep(4/100) cli_progress_update() } cli_progress_output("Already half way!") for (i in 1:50) { Sys.sleep(4/100) cli_progress_update() } cli_alert_info("All done")}fun()Value
TRUE, always.
See Also
This function supportsinline markup.
Other progress bar functions:cli_progress_along(),cli_progress_bar(),cli_progress_builtin_handlers(),cli_progress_message(),cli_progress_num(),cli_progress_step(),cli_progress_styles(),progress-variables
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
Simplified cli progress messages, with styling
Description
This is a simplified progress bar, a single (dynamic)message, without progress units.
Usage
cli_progress_step( msg, msg_done = msg, msg_failed = msg, spinner = FALSE, class = if (!spinner) ".alert-info", current = TRUE, .auto_close = TRUE, .envir = parent.frame(), ...)Arguments
msg | Message to show. It may contain glue substitution and clistyling. It can be updated via |
msg_done | Message to show on successful termination. By defaultthis it is the same as |
msg_failed | Message to show on unsuccessful termination. Bydefault it is the same as |
spinner | Whether to show a spinner at the beginning of the line.To make the spinner spin, you'll need to call |
class | cli class to add to the message. By default there is noclass for steps with a spinner. |
current | Passed to |
.auto_close | Passed to |
.envir | Passed to |
... | Passed to |
Details
cli_progress_step() always shows the progress message,even if no update is due.
Basic use
f <- function() { cli_progress_step("Downloading data") Sys.sleep(2) cli_progress_step("Importing data") Sys.sleep(1) cli_progress_step("Cleaning data") Sys.sleep(2) cli_progress_step("Fitting model") Sys.sleep(3)}f()Spinner
You can add a spinner to some or all steps withspinner = TRUE,but note that this will only work if you callcli_progress_update()regularly.
f <- function() { cli_progress_step("Downloading data", spinner = TRUE) for (i in 1:100) { Sys.sleep(2/100); cli_progress_update() } cli_progress_step("Importing data") Sys.sleep(1) cli_progress_step("Cleaning data") Sys.sleep(2) cli_progress_step("Fitting model", spinner = TRUE) for (i in 1:100) { Sys.sleep(3/100); cli_progress_update() }}f()Dynamic messages
You can make the step messages dynamic, using glue templates.Sincecli_progress_step() show that message immediately, we needto initializemsg first.
f <- function() { msg <- "" cli_progress_step("Downloading data{msg}", spinner = TRUE) for (i in 1:100) { Sys.sleep(2/100) msg <- glue::glue(", got file {i}/100") cli_progress_update() } cli_progress_step("Importing data") Sys.sleep(1) cli_progress_step("Cleaning data") Sys.sleep(2) cli_progress_step("Fitting model", spinner = TRUE) for (i in 1:100) { Sys.sleep(3/100); cli_progress_update() }}f()Termination messages
You can specify a different message for successful and/orunsuccessful termination:
f <- function() { size <- 0L cli_progress_step( "Downloading data.", msg_done = "Downloaded {prettyunits::pretty_bytes(size)}.", spinner = TRUE ) for (i in 1:100) { Sys.sleep(3/100) size <- size + 8192 cli_progress_update() }}f()See Also
This function supportsinline markup.
Other progress bar functions:cli_progress_along(),cli_progress_bar(),cli_progress_builtin_handlers(),cli_progress_message(),cli_progress_num(),cli_progress_output(),cli_progress_styles(),progress-variables
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
List of built-in cli progress styles
Description
The following options are used to select a style:
cli_progress_bar_stylecli_progress_bar_style_asciicli_progress_bar_style_unicode
Usage
cli_progress_styles()Details
On Unicode terminals (ifis_utf8_output() isTRUE), thecli_progress_bar_style_unicode andcli_progress_bar_styleoptions are used.
On ASCII terminals (ifis_utf8_output() isFALSE), thecli_pgoress_bar_style_ascii andcli_progress_bar_style optionsare are used.
for (style in names(cli_progress_styles())) { options(cli.progress_bar_style = style) label <- ansi_align(paste0("Style '", style, "'"), 20) print(cli_progress_demo(label, live = FALSE, at = 66, total = 100))}options(cli.progress_var_style = NULL)#> Style 'classic'##################### 66% | ETA: 3s #> Style 'squares'■■■■■■■■■■■■■■■■■■■■■ 66% | ETA: 3s #> Style 'dot'────────────────────●────────── 66% | ETA: 3s #> Style 'fillsquares'■■■■■■■■■■■■■■■■■■■■■□□□□□□□□□□ 66% | ETA: 3s #> Style 'bar'███████████████████████████████ 66% | ETA: 3s
Value
A named list with sublists containing elementscomplete,incomplete and potentiallycurrent.
See Also
Other progress bar functions:cli_progress_along(),cli_progress_bar(),cli_progress_builtin_handlers(),cli_progress_message(),cli_progress_num(),cli_progress_output(),cli_progress_step(),progress-variables
CLI horizontal rule
Description
It can be used to separate parts of the output.
Usage
cli_rule( left = "", center = "", right = "", id = NULL, .envir = parent.frame())Arguments
left | Label to show on the left. It interferes with the |
center | Label to show at the center. It interferes with the |
right | Label to show on the right. It interferes with the |
id | Element id, a string. If |
.envir | Environment to evaluate the glue expressions in. |
Details
Inline styling and interpolation
pkg <- "mypackage"cli_rule(left = "{.pkg {pkg}} results")#> ──mypackage results ─────────────────────────────────────────────────Theming
The line style of the rule can be changed via the theline-typeproperty. Possible values are:
"single": (same as1), a single line,"double": (same as2), a double line,"bar1","bar2","bar3", etc.,"bar8"uses varying height bars.
Colors and background colors can similarly changed via a theme.
d <- cli_div(theme = list(rule = list( color = "cyan", "line-type" = "double")))cli_rule("Summary", right = "{.pkg mypackage}")cli_end(d)#>══ Summary ══════════════════════════════════════════════mypackage ══
See Also
This function supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
cli situation report
Description
Contains currently:
cli_unicode_option: whether thecli.unicodeoption is set and itsvalue. Seeis_utf8_output().symbol_charset: the selected character set forsymbol, UTF-8,Windows, or ASCII.console_utf8: whether the console supports UTF-8. Seebase::l10n_info().latex_active: whether we are inside knitr, creating a LaTeXdocument.num_colors: number of ANSI colors. Seenum_ansi_colors().console_with: detected console width.
Usage
cli_sitrep()Value
Named list with entries listed above. It has acli_sitrepclass, with aprint() andformat() method.
Examples
cli_sitrep()Update the status bar (superseded)
Description
Thecli_status_*() functions are superseded bythecli_progress_message() andcli_progress_step() functions,because they have a better default behavior.
The status bar is the last line of the terminal. cli apps can use thisto show status information, progress bars, etc. The status bar is keptintact by all semantic cli output.
Usage
cli_status( msg, msg_done = paste(msg, "... done"), msg_failed = paste(msg, "... failed"), .keep = FALSE, .auto_close = TRUE, .envir = parent.frame(), .auto_result = c("clear", "done", "failed", "auto"))Arguments
msg | The text to show, a character vector. It will becollapsed into a single string, and the first line is kept and cut to |
msg_done | The message to use when the message is cleared, whenthe calculation finishes successfully. If |
msg_failed | The message to use when the message is cleared, whenthe calculation finishes unsuccessfully. If |
.keep | What to do when this status bar is cleared. If |
.auto_close | Whether to clear the status bar when the callingfunction finishes (or |
.envir | Environment to evaluate the glue expressions in. It isalso used to auto-clear the status bar if |
.auto_result | What to do when auto-closing the status bar. |
Details
Usecli_status_clear() to clear the status bar.
Often status messages are associated with processes. E.g. the app startsdownloading a large file, so it sets the status bar accordingly. Once thedownload is done (or has failed), the app typically updates the status baragain. cli automates much of this, via themsg_done,msg_failed, and.auto_result arguments. See examples below.
Value
The id of the new status bar container element, invisibly.
See Also
Status bars supportinline markup.
Thecli_progress_message() andcli_progress_step()functions, for a superior API.
Other status bar:cli_process_start(),cli_status_clear(),cli_status_update()
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status_update(),cli_text(),cli_ul(),format_error(),format_inline()
Clear the status bar (superseded)
Description
Thecli_status_*() functions are superseded bythecli_progress_message() andcli_progress_step() functions,because they have a better default behavior.
Clear the status bar
Usage
cli_status_clear( id = NULL, result = c("clear", "done", "failed"), msg_done = NULL, msg_failed = NULL, .envir = parent.frame())Arguments
id | Id of the status bar container to clear. If |
result | Whether to show a message for success or failure or justclear the status bar. |
msg_done | If not |
msg_failed | If not |
.envir | Environment to evaluate the glue expressions in. It isalso used to auto-clear the status bar if |
See Also
Thecli_progress_message() andcli_progress_step()functions, for a superior API.
Other status bar:cli_process_start(),cli_status(),cli_status_update()
Update the status bar (superseded)
Description
Thecli_status_*() functions are superseded bythecli_progress_message() andcli_progress_step() functions,because they have a better default behavior.
Update the status bar
Usage
cli_status_update( id = NULL, msg = NULL, msg_done = NULL, msg_failed = NULL, .envir = parent.frame())Arguments
id | Id of the status bar to update. Defaults to the currentstatus bar container. |
msg | Text to update the status bar with. |
msg_done | Updated "done" message. |
msg_failed | Updated "failed" message. |
.envir | Environment to evaluate the glue expressions in. |
Value
Id of the status bar container.
See Also
This function supportsinline markup.
Thecli_progress_message() andcli_progress_step()functions, for a superior API.
Other status bar:cli_process_start(),cli_status(),cli_status_clear()
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_text(),cli_ul(),format_error(),format_inline()
CLI text
Description
Write some text to the screen. This function is most appropriate forlonger paragraphs. Seecli_alert() for shorter status messages.
Usage
cli_text(..., .envir = parent.frame())Arguments
... | The text to show, in character vectors. They will beconcatenated into a single string. Newlines arenot preserved. |
.envir | Environment to evaluate the glue expressions in. |
Details
Text wrapping
Text is wrapped to the console width, seeconsole_width().
cli_text(cli:::lorem_ipsum())
#> Lorem ad ipsum veniam esse nisi deserunt duis. Qui incididunt elit #> elit mollit sint nulla consectetur aute commodo do elit laboris minim #> et. Laboris ipsum mollit voluptate et non do incididunt eiusmod. Anim #> consectetur mollit laborum occaecat eiusmod excepteur. Ullamco non #> tempor esse anim tempor magna non.
New lines
Acli_text() call always appends a newline character to the end.
cli_text("First line.")cli_text("Second line.")#> First line. #> Second line.
Styling
You can useinline markup, as usual.
cli_text("The {.fn cli_text} function in the {.pkg cli} package.")#> The `cli_text()` function in thecli package.Interpolation
String interpolation via glue works as usual. Interpolated vectorsare collapsed.
pos <- c(5, 14, 25, 26)cli_text("We have {length(pos)} missing measurements: {pos}.")#> We have 4 missing measurements: 5, 14, 25, and 26.
Styling and interpolation
Use double braces to combine styling and string interpolation.
fun <- "cli-text"pkg <- "cli"cli_text("The {.fn {fun}} function in the {.pkg {pkg}} package.")#> The `cli-text()` function in thecli package.Multiple arguments
Arguments are concatenated.
cli_text(c("This ", "will ", "all "), "be ", "one ", "sentence.")#> This will all be one sentence.
Containers
You can usecli_text() within clicontainers.
ul <- cli_ul()cli_li("First item.")cli_text("Still the {.emph first} item")cli_li("Second item.")cli_text("Still the {.emph second} item")cli_end(ul)#> • First item. #> Still thefirst item #> • Second item. #> Still thesecond item
See Also
This function supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_ul(),format_error(),format_inline()
Unordered CLI list
Description
An unordered list is a container, seecontainers.
Usage
cli_ul( items = NULL, id = NULL, class = NULL, .close = TRUE, .auto_close = TRUE, .envir = parent.frame())Arguments
items | If not |
id | Id of the list container. Can be used for closing it with |
class | Class of the list container. Can be used in themes. |
.close | Whether to close the list container if the |
.auto_close | Whether to close the container, when the callingfunction finishes (or |
.envir | Environment to evaluate the glue expressions in. It isalso used to auto-close the container if |
Details
Adding all items at once
fun <- function() { cli_ul(c("one", "two", "three"))}fun()#> • one #> • two #> • three
Adding items one by one
fun <- function() { cli_ul() cli_li("{.emph one}") cli_li("{.emph two}") cli_li("{.emph three}") cli_end()}fun()#> •one #> •two #> •three
Value
The id of the new container element, invisibly.
See Also
This function supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),format_error(),format_inline()
Add custom cli style to a vector
Description
Add custom cli style to a vector
Usage
cli_vec(x, style = list())Arguments
x | Vector that will be collapsed by cli. |
style | Style to apply to the vector. It is used as a theme ona |
Details
You can use this function to change the default parameters ofcollapsing the vector into a string, see an example below.
The style is added as an attribute, so operations that removeattributes will remove the style as well.
Custom collapsing separator
v <- cli_vec( c("foo", "bar", "foobar"), style = list("vec-sep" = " & ", "vec-last" = " & "))cli_text("My list: {v}.")#> My list: foo & bar & foobar.
Custom truncation
x <- cli_vec(names(mtcars), list("vec-trunc" = 3))cli_text("Column names: {x}.")#> Column names: mpg, cyl, disp, …, gear, and carb.
See Also
CLI verbatim text
Description
It is not wrapped, but printed as is. Long lines will overflow.No glue substitution is performed on verbatim text.
Usage
cli_verbatim(..., .envir = parent.frame())Arguments
... | The text to show, in character vectors. Each element isprinted on a new line. |
.envir | Environment to evaluate the glue expressions in. |
Details
Line breaks
cli_verbatim("This has\nthree\nlines,")#> This has #> three #> lines,
Special characters
No glue substitution happens here.
cli_verbatim("No string {interpolation} or {.emph styling} here")#> No string {interpolation} or {.emph styling} hereSee Also
cli_code() for printing R or other source code.
Syntax highlight R code
Description
Syntax highlight R code
Usage
code_highlight(code, code_theme = NULL, envir = NULL)Arguments
code | Character vector, each element is one line of code. |
code_theme | Theme see |
envir | Environment to look up function calls for hyperlinks.If |
Details
Seecode_theme_list() for the default syntax highlighting theme andhow to change it.
Ifcode does not parse, then it is returned unchanged and acli_parse_failure condition is thrown. Note that this is not an error,and the condition is ignored, unless explicitly caught.
Value
Character vector, the highlighted code.
See Also
Other syntax highlighting:code_theme_list()
Examples
code_highlight(deparse(ls))cat(code_highlight(deparse(ls)), sep = "\n")Syntax highlighting themes
Description
code_theme_list() lists the built-in code themes.
Usage
code_theme_list()Value
Character vector of the built-in code theme names.
Code themes
A theme is a list of character vectors, except forbracket, see below.Each character vector must contain RGB colors (e.g."#a9a9a9"),and cli styles, e.g."bold". Entries in the list:
reserved: reserved wordsnumber: numeric literalsnull: theNULLconstantoperator: operators, including assignmentcall: function callsstring: character literalscomment: commentsbracket: brackets:(){}[]This is a list of character vectors,to create "rainbow" brackets. It is recycled for deeply nested lists.
The default code theme
In RStudio, it matches the current theme of the IDE.
You can use three options to customize the code theme:
If
cli.code_themeis set, it is used.Otherwise if R is running in RStudio and
cli.code_theme_rstudioisset, then it is used.Otherwise if T is not running in RStudio and
cli.code_theme_terminalis set, then it is used.
You can set these options to the name of a built-in theme, or to listthat specifies a custom theme. Seecode_theme_list() for the listof the built-in themes.
See Also
Other syntax highlighting:code_highlight()
Examples
code_theme_list()code_highlight(deparse(get), code_theme = "Solarized Dark")Combine two or more ANSI styles
Description
Combine two or more styles or style functions into a new style functionthat can be called on strings to style them.
Usage
combine_ansi_styles(...)Arguments
... | The styles to combine. For character strings, the |
Details
It does not usually make sense to combine two foregroundcolors (or two background colors), because only the first oneapplied will be used.
It does make sense to combine different kind of styles,e.g. background color, foreground color, bold font.
Value
The combined style function.
See Also
Other ANSI styling:ansi-styles,make_ansi_style(),num_ansi_colors()
Examples
## Use style namesalert <- combine_ansi_styles("bold", "red4")cat(alert("Warning!"), "\n")## Or style functionsalert <- combine_ansi_styles(style_bold, col_red, bg_cyan)cat(alert("Warning!"), "\n")## Combine a composite stylealert <- combine_ansi_styles( "bold", combine_ansi_styles("red", bg_cyan))cat(alert("Warning!"), "\n")Determine the width of the console
Description
It uses thecli.width option, if set. Otherwise it tries todetermine the size of the terminal or console window.
Usage
console_width()Details
These are the exact rules:
If the
cli.widthoption is set to a positive integer, it is used.If the
cli.widthoption is set, but it is not a positive integer,and error is thrown.
Then we try to determine the size of the terminal or console window:
If we are not in RStudio, or we are in an RStudio terminal,then we try to use the
tty_size()function to query theterminal size. This might fail if R is not running in a terminal,but failures are ignored.If we are in the RStudio build pane, then the
RSTUDIO_CONSOLE_WIDTHenvironment variable is used. If the build pane is resized, then thisenvironment variable is not accurate any more, and the output mightget garbled.We arenot using the
RSTUDIO_CONSOLE_WIDTHenvironment variableif we are in the RStudio console.
If we cannot determine the size of the terminal or console window, thenwe use thewidth option. If thewidth option is not set, thenwe return 80L.
Value
Integer scalar, the console with, in number of characters.
Examples
console_width()About cli containers
Description
Container elements may contain other elements. Currently the followingcommands create container elements:cli_div(),cli_par(), the listelements:cli_ul(),cli_ol(),cli_dl(), and list items arecontainers as well:cli_li().
Details
Themes
A container can add a new theme, which is removed when the containerexits.
d <- cli_div(theme = list(h1 = list(color = "blue", "font-weight" = "bold")))cli_h1("Custom title")cli_end(d)#> #>Custom titleAuto-closing
Container elements are closed withcli_end(). For convenience,by default they are closed automatically when the function that createdthem terminated (either regularly or with an error). The defaultbehavior can be changed with the.auto_close argument.
div <- function() { cli_div(class = "tmp", theme = list(.tmp = list(color = "yellow"))) cli_text("This is yellow")}div()cli_text("This is not yellow any more")#>This is yellow #> This is not yellow any moreDebugging
You can use the internalcli:::cli_debug_doc() function to see thecurrently open containers.
fun <- function() { cli_div(id = "mydiv") cli_par(class = "myclass") cli:::cli_debug_doc()}fun()#> #> <cli document> #> <body> #> <div> +theme #> <par>
Show a demo of some (by default all) spinners
Description
Each spinner is shown for about 2-3 seconds.
Usage
demo_spinners(which = NULL)Arguments
which | Character vector, which spinners to demo. |
Details
demo_spinners("clock")See Also
Other spinners:get_spinner(),list_spinners(),make_spinner()
Compare two character vectors elementwise
Description
Its printed output is similar to callingdiff -u at the commandline.
Usage
diff_chr(old, new, max_dist = Inf)Arguments
old | First character vector. |
new | Second character vector. |
max_dist | Maximum distance to consider, or |
Value
A list that is acli_diff_chr object, with aformat() and aprint() method. You can also access its members:
oldandneware the original inputs,lcsis a data frame of LCS edit that transformoldintonew.
Thelcs data frame has the following columns:
operation: one of"match","delete"or"insert".offset: offset inoldfor matches and deletions, offset innewfor insertions.length: length of the operation, i.e. number of matching, deletedor inserted elements.old_offset: offset inoldafter the operation.new_offset: offset innewafter the operation.
See Also
The diffobj package for a much more comprehensive set ofdiff-like tools.
Other diff functions in cli:diff_str()
Examples
letters2 <- c("P", "R", "E", letters, "P", "O", "S", "T")letters2[11:16] <- c("M", "I", "D", "D", "L", "E")diff_chr(letters, letters2)Compare two character strings, character by character
Description
Characters are defined by UTF-8 graphemes.
Usage
diff_str(old, new, max_dist = Inf)Arguments
old | First string, must not be |
new | Second string, must not be |
max_dist | Maximum distance to consider, or |
Value
A list that is acli_diff_str object and also acli_diff_chr object, seediff_str for the details about itsstructure.
See Also
The diffobj package for a much more comprehensive set ofdiff-like tools.
Other diff functions in cli:diff_chr()
Examples
str1 <- "abcdefghijklmnopqrstuvwxyz"str2 <- "PREabcdefgMIDDLEnopqrstuvwxyzPOST"diff_str(str1, str2)Frequently Asked Questions
Description
Frequently Asked Questions
Details
My platform supports ANSI colors, why does cli not use them?
It is probably a mistake in the ANSI support detection algorithm. Pleaseopen an issue athttps://github.com/r-lib/cli/issues and do not forgetto tell us the details of your platform and terminal or GUI.
How do I turn off ANSI colors and styles?
Set theNO_COLOR environment variable to a non-empty value. You can dothis in your.Renviron file (useusethis::edit_r_environ()).
If you want to do this for testthat tests, then consider using the 3rdedition on testthat, which does turn off ANSI styling automaticallyinsidetest_that().
cli does not show the output beforefile.choose()
Try callingflush.console() to flush the console, beforefile.choose(). If flushing does not work and you are in RStudio, thenit is probably this RStudio bug:https://github.com/rstudio/rstudio/issues/8040 See more details athttps://github.com/r-lib/cli/issues/151
Why are heading separators wider than my screen in RStudio?
The display width of some Unicode characters ambiguous in the Unicodestandard. Some software treats them as narrow (one column on thescreen), other as wide (two columns). In some terminal emulators (forexample iTerm2), you can configure the preferred behavior.
Unfortunately the box drawing characters that cli uses also haveambiguous width.
In RStudio the behavior depends on the font. In particular, Consolas,Courier and Inconsolata treats them as wide characters, so cli outputwill not look great with these. Some good, modern fonts that look goodinclude Menlo, Fira Code and Source Code Pro.
If you do not want to change your font, you can also turn off Unicodeoutput, by setting thecli.unicode option:
options(cli.unicode = FALSE)
A related issue:https://github.com/r-lib/cli/issues/320
Is there a suggested font to use with cli?
In modern terminals, cli output usually looks good.
If you see too wide heading separators in RStudio, then see the previousquestion: Why are heading separators wider than my screen in RStudio?.
If some output is garbled, then cli probably misdetected Unicode supportfor your terminal or font. You can try choosing a different font. In ourexperience output looks good with Menlo, Fira Code and Source Code Pro.Alternatively you can turn off Unicode output:
options(cli.unicode = FALSE)
If you think this is our fault, then please also file an issue athttps://github.com/r-lib/cli/issues
Format an error, warning or diagnostic message
Description
You can then throw this message withstop() orrlang::abort().
Usage
format_error(message, .envir = parent.frame())format_warning(message, .envir = parent.frame())format_message(message, .envir = parent.frame())Arguments
message | It is formatted via a call to |
.envir | Environment to evaluate the glue expressions in. |
Details
The messages can use inline styling, pluralization and gluesubstitutions.
n <- "boo"stop(format_error(c( "{.var n} must be a numeric vector", "x" = "You've supplied a {.cls {class(n)}} vector.")))#> Error: `n` must be a numeric vector #>✖ You've supplied a<character> vector.
len <- 26idx <- 100stop(format_error(c( "Must index an existing element:", "i" = "There {?is/are} {len} element{?s}.", "x" = "You've tried to subset element {idx}.")))#> Error: Must index an existing element: #>ℹ There are 26 elements. #>✖ You've tried to subset element 100.
See Also
These functions supportinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_inline()
Format and returns a line of text
Description
You can use this function to format a line of cli text, without emittingit to the screen. It usescli_text() internally.
Usage
format_inline( ..., .envir = parent.frame(), collapse = TRUE, keep_whitespace = TRUE)Arguments
... | Passed to |
.envir | Environment to evaluate the expressions in. |
collapse | Whether to collapse the result if it has multiplelines, e.g. because of |
keep_whitespace | Whether to keep all whitepace (spaces, newlinesand form feeds) as is in the input. |
Details
format_inline() performs no width-wrapping.
Value
Character scalar, the formatted string.
See Also
This function supportsinline markup.
Other functions supporting inline markup:cli_abort(),cli_alert(),cli_blockquote(),cli_bullets(),cli_bullets_raw(),cli_dl(),cli_h1(),cli_li(),cli_ol(),cli_process_start(),cli_progress_along(),cli_progress_bar(),cli_progress_message(),cli_progress_output(),cli_progress_step(),cli_rule,cli_status(),cli_status_update(),cli_text(),cli_ul(),format_error()
Examples
format_inline("A message for {.emph later}, thanks {.fn format_inline}.")Character vector to put a spinner on the screen
Description
cli contains many different spinners, you choose one according to yourtaste.
Usage
get_spinner(which = NULL)Arguments
which | The name of the chosen spinner. If |
Details
options(cli.spinner = "hearts")fun <- function() { cli_progress_bar("Spinning") for (i in 1:100) { Sys.sleep(4/100) cli_progress_update() }}fun()options(cli.spinner = NULL)Value
A list with entries:name,interval: the suggested updateinterval in milliseconds andframes: the character vector of thespinner's frames.
See Also
Other spinners:demo_spinners(),list_spinners(),make_spinner()
Check if the current platform/terminal supports readingsingle keys.
Description
Check if the current platform/terminal supports readingsingle keys.
Usage
has_keypress_support()Details
Supported platforms:
Terminals in Windows and Unix.
RStudio terminal.
Not supported:
RStudio (if not in the RStudio terminal).
R.app on macOS.
Rgui on Windows.
Emacs ESS.
Others.
Value
Whether there is support for waiting for individualkeypressses.
See Also
Other keypress function:keypress()
Examples
has_keypress_support()Adjective-animal hash
Description
Adjective-animal hash
Usage
hash_animal(x, n_adj = 2)hash_raw_animal(x, n_adj = 2)hash_obj_animal(x, n_adj = 2, serialize_version = 2)Arguments
x | Character vector. |
n_adj | Number of adjectives to use. It must be from 0 through 3. |
serialize_version | Workspace format version to use, see |
Details
It uses the first 13 hexadecimal characters (out of the 32) of the MD5hash of the input, and converts them into an adjective-animal form tocreate a human readable hash.
Number of possible hash values
hash_animal() uses 1748 animal names and8946 different adjectives. The number ofdifferent hashes you can get for different values ofn_adj:
n_adj | size of the hash table space |
| 0 | 1,748 |
| 1 | 15,637,608 |
| 2 | 139,894,041,168 |
| 3 | 1,251,492,092,288,928 |
Source
The list of adjectives and animals comes from the ids package,and in turn fromhttps://github.com/a-type/adjective-adjective-animal, andfromhttps://gfycat.com (now gone).
hash_raw_animal() calculates the adjective-animal hash ofthe bytes of a raw vector.
hash_obj_animal() calculates the adjective-animal hash ofan R object. The object is serialized into a binary vector first.
Value
A data frame with columns
hash: the hash value, a string.words: list column with the adjectives and the animal name in acharacter vector.
hash_raw_animal() andhash_obj_animal() return a listwith entries:
hash: the hash value, a string,'words: the adjectives and the animal name in a character vector.
See Also
the ids package for generating random adjective-animal ids
Other hash functions:hash_emoji(),hash_md5(),hash_sha1(),hash_sha256(),hash_xxhash()
Examples
hash_animal(c("foo", "bar"))# if you increase `n_adj`, the shorter hash is a suffix of the longer:hash_animal("cli package", 0)$hashhash_animal("cli package", 1)$hashhash_animal("cli package", 2)$hashhash_animal("cli package", 3)$hashEmoji hash
Description
Emoji hash
Usage
hash_emoji(x, size = 3)hash_raw_emoji(x, size = 3)hash_obj_emoji(x, size = 3, serialize_version = 2)Arguments
x | Character vector. |
size | Number of emojis to use in a hash. Currently it has tobe from 1 through 4. |
serialize_version | Workspace format version to use, see |
Details
It uses the first 13 hexadecimal characters (out of the 32) of the MD5hash of the input, and converts them into an emoji representation.It uses a manually selected subset of all emojis, that tend to bedisplayed correctly.
Number of possible hash values
cli uses 2280 possible emojis. This is the number ofdifferent hashes you can get for different values ofsize:
size | size of hash table space |
| 1 | 2,280 |
| 2 | 5,198,400 |
| 3 | 11,852,352,000 |
| 4 | 27,023,362,560,000 |
hash_raw_emoji() calculates the emoji hash of the bytesof a raw vector.
hash_obj_emoji() calculates the emoji hash of an Robject. The object is serialized into a binary vector first.
Value
hash_emoji() returns a data frame with columns
hash: the emoji hash, a string of the requested size.emojis: list column with the emoji characters in charactervectors. Note that an emoji might have multiple code points.text: text representation ofhash, comma separated.names: list column with the text representations ofemojis, incharacter vectors.
hash_raw_emoji() andhash_obj_emoji() return a list withentries:
hash: the emoji hash, a string of requested size,emojis: the individual emoji characters in a character vector,text: text representation ofhash, comma separated,names: names of the emojis, in a character vector.
See Also
the emoji package for a comprehensive list of emojis
Other hash functions:hash_animal(),hash_md5(),hash_sha1(),hash_sha256(),hash_xxhash()
Examples
hash_emoji(c("foo", NA, "bar", ""))$text# if you increase `size`, the shorter hash is a prefix of the longer:hash_emoji("foobar", 1)$texthash_emoji("foobar", 2)$texthash_emoji("foobar", 3)$texthash_emoji("foobar", 4)$textMD5 hash
Description
Calculate the MD5 hash of each element of a character vector.
Usage
hash_md5(x)hash_raw_md5(x)hash_obj_md5(x, serialize_version = 2)hash_file_md5(paths)Arguments
x | Character vector. If not a character vector, then |
serialize_version | Workspace format version to use, see |
paths | Character vector of file names. |
Details
hash_raw_md5() calculates the MD5 hash of the bytesof a raw vector.
hash_obj_md5() calculates the MD5 hash of an Robject. The object is serialized into a binary vector first.
hash_file_md5() calculates the MD5 hash of one or morefiles.
Value
hash_md5() returns a character vector of hexadecimal MD5hashes.
hash_raw_md5() returns a character scalar.
hash_obj_md5() returns a character scalar.
See Also
tools::md5sum() for a base R MD5 function that works onfiles.
Other hash functions:hash_animal(),hash_emoji(),hash_sha1(),hash_sha256(),hash_xxhash()
Examples
hash_md5(c("foo", NA, "bar", ""))SHA-1 hash
Description
Calculate the SHA-1 hash of each element of a character vector.
Usage
hash_sha1(x)hash_raw_sha1(x)hash_obj_sha1(x, serialize_version = 2)hash_file_sha1(paths)Arguments
x | Character vector. If not a character vector, then |
serialize_version | Workspace format version to use, see |
paths | Character vector of file names. |
Details
hash_raw_sha1() calculates the SHA-1 hash of the bytesof a raw vector.
hash_obj_sha1() calculates the SHA-1 hash of an Robject. The object is serialized into a binary vector first.
hash_file_sha1() calculates the SHA-1 hash of one ormore files.
Value
hash_sha1() returns a character vector of hexadecimalSHA-1 hashes.
hash_raw_sha1() returns a character scalar.
hash_obj_sha1() returns a character scalar.
hash_file_sha1() returns a character vector of SHA-1hashes.
See Also
Other hash functions:hash_animal(),hash_emoji(),hash_md5(),hash_sha256(),hash_xxhash()
Examples
hash_sha1(c("foo", NA, "bar", ""))SHA-256 hash
Description
Calculate the SHA-256 hash of each element of a character vector.
Usage
hash_sha256(x)hash_raw_sha256(x)hash_obj_sha256(x, serialize_version = 2)hash_file_sha256(paths)Arguments
x | Character vector. If not a character vector, then |
serialize_version | Workspace format version to use, see |
paths | Character vector of file names. |
Details
hash_raw_sha256() calculates the SHA-256 hash of the bytesof a raw vector.
hash_obj_sha256() calculates the SHA-256 hash of an Robject. The object is serialized into a binary vector first.
hash_file_sha256() calculates the SHA-256 hash of one ormore files.
Value
hash_sha256() returns a character vector of hexadecimalSHA-256 hashes.
hash_raw_sha256() returns a character scalar.
hash_obj_sha256() returns a character scalar.
hash_file_sha256() returns a character vector of SHA-256hashes.
See Also
Other hash functions:hash_animal(),hash_emoji(),hash_md5(),hash_sha1(),hash_xxhash()
Examples
hash_sha256(c("foo", NA, "bar", ""))xxHash
Description
Extremely fast hash algorithm.
Usage
hash_xxhash(x)hash_raw_xxhash(x)hash_obj_xxhash(x, serialize_version = 2)hash_file_xxhash(paths)hash_xxhash64(x)hash_raw_xxhash64(x)hash_obj_xxhash64(x, serialize_version = 2)hash_file_xxhash64(paths)Arguments
x | Character vector. If not a character vector, then |
serialize_version | Workspace format version to use, see |
paths | Character vector of file names. |
Details
hash_raw_xxhash() calculates the xxHash hash of the bytesof a raw vector.
hash_obj_xxhash() calculates the xxHash hash of an Robject. The object is serialized into a binary vector first.
hash_file_xxhash() calculates the xxHash hash of one ormore files.
The64 functions caculate the 64 bit variantof xxHash. Otherwise they work the same.
Value
hash_xxhash() returns a character vector of hexadecimalxxHash hashes.
hash_raw_xxhash() returns a character scalar.
hash_obj_xxhash() returns a character scalar.
hash_file_xxhash() returns a character vector of xxHashhashes.
See Also
Other hash functions:hash_animal(),hash_emoji(),hash_md5(),hash_sha1(),hash_sha256()
Examples
hash_xxhash(c("foo", NA, "bar", ""))About inline markup in the semantic cli
Description
To learn how to use cli’s semantic markup, start with the ‘Buildinga semantic CLI’ article athttps://cli.r-lib.org.
Command substitution
All text emitted by cli supports glue interpolation. Expressionsenclosed by braces will be evaluated as R code. Seeglue::glue() fordetails.
In addition to regular glue interpolation, cli can also add classesto parts of the text, and these classes can be used in themes. Forexample
cli_text("This is {.emph important}.")#> This isimportant.adds a class to the "important" word, class"emph". Note that in thiscase the string within the braces is usually not a valid R expression.If you want to mix classes with interpolation, add another pair ofbraces:
adjective <- "great"cli_text("This is {.emph {adjective}}.")#> This isgreat.An inline class will always create aspan element internally. So inthemes, you can use thespan.emph CSS selector to change how inlinetext is emphasized:
cli_div(theme = list(span.emph = list(color = "red")))adjective <- "nice and red"cli_text("This is {.emph {adjective}}.")#> This isnice and red.Classes
The default theme defines the following inline classes:
argfor a function argument.clsfor an S3, S4, R6 or other class name.codefor a piece of code.dtis used for the terms in a definition list (cli_dl()).ddis used for the descriptions in a definition list (cli_dl()).emailfor an email address.If the terminal supports ANSI hyperlinks (e.g. RStudio, iTerm2, etc.),then cli creates a clickable link.Seelinks for more information about cli hyperlinks.emphfor emphasized text.envvarfor the name of an environment variable.fieldfor a generic field, e.g. in a named list.filefor a file name. If the terminal supports ANSI hyperlinks (e.g.RStudio, iTerm2, etc.), then cli creates a clickable link that opensthe file in RStudio or with the default app for the file type.Seelinks for more information about cli hyperlinks.fnfor a function name. If it is in thepackage::function_nameform, and the terminal supports ANSI hyperlinks (e.g. RStudio,iTerm2, etc.), then cli creates a clickable link.Seelinks for more information about cli hyperlinks.funsame asfn.helpis a help page of afunction.If the terminal supports ANSI hyperlinks to help pages (e.g. RStudio),then cli creates a clickable link. It supports link text.Seelinks for more information about cli hyperlinks.hrefcreates a hyperlink, potentially with a link text.If the terminal supports ANSI hyperlinks (e.g. RStudio, iTerm2, etc.),then cli creates a clickable link.Seelinks for more information about cli hyperlinks.kbdfor a keyboard key.keysame askbd.obj_type_friendlyformats the type of an R object in a readable way,and it should be used with{}, see an example below.orchanges the string that separates the last two elements ofcollapsed vectors (see below) from "and" to "or".pathfor a path (the same asfilein the default theme).pkgfor a package name.runis an R expression, that is potentially clickable if the terminalsupports ANSI hyperlinks to runnable code (e.g. RStudio).It supports link text. Seelinks for more information about cli hyperlinks.strfor a double quoted string escaped bybase::encodeString().strongfor strong importance.topicis a help page of atopic.If the terminal supports ANSI hyperlinks to help pages (e.g. RStudio),then cli creates a clickable link. It supports link text.Seelinks for more information about cli hyperlinks.typeformats the type of an R object in a readable way, and itshould be used with{}, see an example below.urlfor a URL. If the terminal supports ANSI hyperlinks (e.g.RStudio, iTerm2, etc.), then cli creates a clickable link.Seelinks for more information about cli hyperlinks.varfor a variable name.valfor a generic "value".vignetteis a vignette.If the terminal supports ANSI hyperlinks to help pages (e.g. RStudio),then cli creates a clickable link. It supports link text.Seelinks for more information about cli hyperlinks.
ul <- cli_ul()cli_li("{.emph Emphasized} text.")cli_li("{.strong Strong} importance.")cli_li("A piece of code: {.code sum(a) / length(a)}.")cli_li("A package name: {.pkg cli}.")cli_li("A function name: {.fn cli_text}.")cli_li("A keyboard key: press {.kbd ENTER}.")cli_li("A file name: {.file /usr/bin/env}.")cli_li("An email address: {.email bugs.bunny@acme.com}.")cli_li("A URL: {.url https://example.com}.")cli_li("An environment variable: {.envvar R_LIBS}.")cli_li("`mtcars` is {.obj_type_friendly {mtcars}}")cli_end(ul)#> •Emphasized text. #> •Strong importance. #> • A piece of code: `sum(a) / length(a)`. #> • A package name:cli. #> • A function name: `cli_text()`. #> • A keyboard key: press[ENTER]. #> • A file name:/usr/bin/env. #> • An email address:bugs.bunny@acme.com. #> • A URL:<https://example.com>. #> • An environment variable: `R_LIBS`. #> • `mtcars` is a data frame
You can add new classes by defining them in the theme, and then usingthem.
cli_div(theme = list( span.myclass = list(color = "lightgrey"), "span.myclass" = list(before = "<<"), "span.myclass" = list(after = ">>")))cli_text("This is {.myclass in angle brackets}.")cli_end()#> This is<<in angle brackets>>.Highlighting weird-looking values
Often it is useful to highlight a weird file or path name, e.g. onethat starts or ends with space characters. The built-in theme does thisfor.file,.path and.email by default. You can highlightany string inline by adding the.q class to it.
The current highlighting algorithm
adds single quotes to the string if it does not start or end with analphanumeric character, underscore, dot or forward slash.
Highlights the background colors of leading and trailing spaces onterminals that support ANSI colors.
Collapsing inline vectors
When cli performs inline text formatting, it automatically collapsesglue substitutions, after formatting. This is handy to create lists offiles, packages, etc.
pkgs <- c("pkg1", "pkg2", "pkg3")cli_text("Packages: {pkgs}.")cli_text("Packages: {.pkg {pkgs}}.")#> Packages: pkg1, pkg2, and pkg3. #> Packages:pkg1,pkg2, andpkg3.
Class names are collapsed differently by default
x <- Sys.time()cli_text("Hey, {.var x} has class {.cls {class(x)}}.")#> Hey, `x` has class<POSIXct/POSIXt>.By default cli truncates long vectors. The truncation limit is by defaulttwenty elements, but you can change it with thevec-trunc style.
nms <- cli_vec(names(mtcars), list("vec-trunc" = 5))cli_text("Column names: {nms}.")#> Column names: mpg, cyl, disp, …, gear, and carb.
Formatting values
Theval inline class formats values. By default (c.f. the built-intheme), it calls thecli_format() generic function, with the currentstyle as the argument. Seecli_format() for examples.
str is for formatting strings, it usesbase::encodeString() withdouble quotes.
Escaping{ and}
It might happen that you want to pass a string tocli_* functions,and you donot want command substitution in that string, because itmight contain{ and} characters. The simplest solution for this isto refer to the string from a template:
msg <- "Error in if (ncol(dat$y)) {: argument is of length zero"cli_alert_warning("{msg}")#>! Error in if (ncol(dat$y)) {: argument is of length zeroIf you want to explicitly escape{ and} characters, just doublethem:
cli_alert_warning("A warning with {{ braces }}.")#>! A warning with { braces }.See also examples below.
Pluralization
All cli commands that emit text support pluralization. Some examples:
ndirs <- 1nfiles <- 13pkgs <- c("pkg1", "pkg2", "pkg3")cli_alert_info("Found {ndirs} director{?y/ies} and {nfiles} file{?s}.")cli_text("Will install {length(pkgs)} package{?s}: {.pkg {pkgs}}")#>ℹ Found 1 directory and 13 files. #> Will install 3 packages:pkg1,pkg2, andpkg3
Seepluralization for details.
Wrapping
Most cli containers wrap the text to width the container's width,while observing margins requested by the theme.
To avoid a line break, you can use the UTF_8 non-breaking spacecharacter:\u00a0. cli will not break a line here.
To force a line break, insert a form feed character:\f or\u000c. cli will insert a line break there.
Detect if a stream support ANSI escape characters
Description
We check that all of the following hold:
The stream is a terminal.
The platform is Unix.
R is not running inside R.app (the macOS GUI).
R is not running inside RStudio.
R is not running inside Emacs.
The terminal is not "dumb".
streamis either the standard output or the standard error stream.
Usage
is_ansi_tty(stream = "auto")Arguments
stream | The stream to inspect or manipulate, an R connectionobject. It can also be a string, one of |
Value
TRUE orFALSE.
See Also
Other terminal capabilities:ansi_hide_cursor(),is_dynamic_tty()
Examples
is_ansi_tty()Detect whether a stream supports\\r (Carriage return)
Description
In a terminal,\\r moves the cursor to the first position of thesame line. It is also supported by most R IDEs.\\r is typicallyused to achieve a more dynamic, less cluttered user interface, e.g.to create progress bars.
Usage
is_dynamic_tty(stream = "auto")Arguments
stream | The stream to inspect or manipulate, an R connectionobject. It can also be a string, one of |
Details
If the output is directed to a file, then\\r characters are typicallyunwanted. This function detects if\\r can be used for the givenstream or not.
The detection mechanism is as follows:
If the
cli.dynamicoption is set toTRUE,TRUEis returned.If the
cli.dynamicoption is set to anything else,FALSEisreturned.If the
R_CLI_DYNAMICenvironment variable is not empty and set tothe string"true","TRUE"or"True",TRUEis returned.If
R_CLI_DYNAMICis not empty and set to anything else,FALSEisreturned.If the stream is a terminal, then
TRUEis returned.If the stream is the standard output or error within RStudio,the macOS R app, or RKWard IDE,
TRUEis returned.Otherwise
FALSEis returned.
See Also
Other terminal capabilities:ansi_hide_cursor(),is_ansi_tty()
Examples
is_dynamic_tty()is_dynamic_tty(stdout())Whether cli is emitting UTF-8 characters
Description
UTF-8 cli characters can be turned on by setting thecli.unicodeoption toTRUE. They can be turned off by setting if toFALSE.If this option is not set, thenbase::l10n_info() is used to detectUTF-8 support.
Usage
is_utf8_output()Value
Flag, whether cli uses UTF-8 characters.
Read a single keypress at the terminal
Description
It currently only works at Linux/Unix and OSX terminals,and at the Windows command line. seehas_keypress_support.
Usage
keypress(block = TRUE)Arguments
block | Whether to wait for a key press, if there is noneavailable now. |
Details
The following special keys are supported:
Arrow keys: 'up', 'down', 'right', 'left'.
Function keys: from 'f1' to 'f12'.
Others: 'home', 'end', 'insert', 'delete', 'pageup', 'pagedown','tab', 'enter', 'backspace' (same as 'delete' on OSX keyboards),'escape'.
Control with one of the following keys: 'a', 'b', 'c', 'd', 'e', 'f','h', 'k', 'l', 'n', 'p', 't', 'u', 'w'.
Value
The key pressed, a character scalar. For non-blocking readsNA is returned if no keys are available.
See Also
Other keypress function:has_keypress_support()
Examples
x <- keypress()cat("You pressed key", x, "\n")cli hyperlinks
Description
Certain cli styles create clickable links, if your IDE or terminalsupports them.
Note: hyperlinks are currently experimental
The details of the styles that create hyperlinks will prrobably changein the near future, based on user feedback.
About the links in this manual page
The hyperlinks that are included in this manual are demonstrativeonly, except for thehttps: links. They look like a hyperlink, andyou can click on them, but they do nothing. I.e. a.run link willnot run the linked expression if you click on it.
Hyperlink Support
As of today, the latest release of RStudio (version v2022.07.0+548)supports all hyperlink types discussed here. Certain terminals, e.g.iTerm on macOS, Linux terminals based on VTE (GNOME terminal) support.href,.email and.file links.
You can useansi_has_hyperlink_support() to check if your terminal orIDE has hyperlink support in general, andansi_hyperlink_types() tocheck if various types of hyperlinks are supported.
If your hyperlink support is not detected properly in your IDE orterminal, please open a cli issue athttps://github.com/r-lib/cli/issues.
Link text
Before we delve into the various types of hyperlinks, a general commentabout link texts. Some link styles support a custom link text:
.href.help.topic.vignette.run
Others, i.e..email,.file,.fun and.url do not support customlink text.
The generic syntax for link text is the same as for Markdown hyperlinks:
{.style [link text](url)}Vectorization
Note that it is not possible to add link text to a vector of URLs. E.g.this will create a list of three URLs, all clickable:
urls <- paste0("https://httpbin.org/status/", c(200, 403, 404))cli::cli_text("Some httpbin URLs: {.url {urls}}.")#> Some httpbin URLs:<https://httpbin.org/status/200>, #><https://httpbin.org/status/403>, and #><https://httpbin.org/status/404>.
What if hyperlinks are not available?
If ANSI hyperlinks are not available, then the link text for of thesestyles outputs both the link text and the URL in a (hopefully) helpfulway. See examples below.
URLs
There are two cli styles to link to generic URLs..url does notallow custom link text, but\href does.
cli_text( "See the cli homepage at {.url https://cli.r-lib.org} for details.")#> See the cli homepage at<https://cli.r-lib.org> for details.
cli_text( "See the {.href [cli homepage](https://cli.r-lib.org)} for details.")#> See thecli homepage for details.
Without hyperlink support
This is how these links look without hyperlink support:
local({ withr::local_options(cli.hyperlink = FALSE) cli_text( "See the cli homepage at {.url https://cli.r-lib.org} for details." ) cli_text( "See the {.href [cli homepage](https://cli.r-lib.org)} for details." )})#> See the cli homepage at<https://cli.r-lib.org> for details. #> See the cli homepage (<https://cli.r-lib.org>) for details.
URL encoding
Note that cli does not encode the url, so you might need to callutils::URLencode() on it, especially, if it is substituted invia{}.
weirdurl <- utils::URLencode("https://example.com/has some spaces")cli_text("See more at {.url {weirdurl}}.")#> See more at<https://example.com/has%20some%20spaces>.
Files
The.file style now automatically creates afile: hyperlink.Becausefile: hyperlinks must contain an absolute path, cli tries toconvert relative paths, and paths starting with~ to aboslute path.
cli_text("... edit your {.file ~/.Rprofile} file.")#> ... edit your~/.Rprofile file.Link text
.file cannot use a custom link text. If you custom link text, thenyou can use.href with afile: URL.
prof <- path.expand("~/.Rprofile")cli_text("... edit your {.href [R profile](file://{prof})}.")#> ... edit yourR profile.
Line and column numbers
You may add a line number to a file name, separated by:. Handlerstypically place the cursor at that line after opening the file.You may also add a column number, after the line number, separated byanother:.
cli_text("... see line 5 in {.file ~/.Rprofile:5}.")#> ... see line 5 in~/.Rprofile:5.Default handler
In RStudiofile: URLs open within RStudio. If you click on a filelink outside of RStudio, typically the operating system is consultedfor the application to open it.
Without hyperlink support
One issue with using.href file files is that it does not look greatif hyperlinks are not available. This will be improved in the future:
local({ withr::local_options(cli.hyperlink = FALSE) prof <- path.expand("~/.Rprofile") cli_text("... edit your {.href [R profile](file://{prof})}.")})#> ... edit your R profile (<file:///Users/gaborcsardi/.Rprofile>).Links to the manual
.fun automatically creates links to the manual page of the function,provided the function name is in thepackagename::functionname form:
cli::cli_text("... see {.fun stats::lm} to learn more.")#> ... see `stats::lm()` to learn more.
Link text
For a custom link text, use.help instead of.fun.
cli::cli_text("... see {.help [{.fun lm}](stats::lm)} to learn more.")#> ... see`lm()` to learn more.
Without hyperlink support
The same message without hyperlink support looks like this:
local({ withr::local_options(cli.hyperlink = FALSE) cli::cli_text("... see {.help [{.fun lm}](stats::lm)} to learn more.")})#> ... see `lm()` (`?stats::lm()`) to learn more.
Topics
To link to a help topic that is not a function, use.topic:
cli::cli_text("... the tibble options at {.topic tibble::tibble_options}.")#> ... the tibble options attibble::tibble_options.
.topic support link text.
Vignettes
To link to a vignette, use.vignette:
cli::cli_text("... see the {.vignette tibble::types} vignette.")#> ... see thetibble::types vignette.
Click to run code
RStudio also supports a special link type that runs R code in thecurrent R session upon clicking.
You can create these links with.run:
cli::cli_text("Run {.run testthat::snapshot_review()} to review")#> Runtestthat::snapshot_review() to review
Link text
Sometimes you want to show a slightly different expression in the link,than the one that is evaluated. E.g. the evaluated expression probablyneeds to qualify packages with::, but you might not want to show this:
cli::cli_text( "Run {.run [snapshot_review()](testthat::snapshot_review())} to review")#> Runsnapshot_review() to review
Security considerations
To make.run hyperlinks more secure, RStudio will not run code
that is not in the
pkg::fun(args)form,if
argscontains(,)or;,if it calls a core package (base, stats, etc.),
if it calls a package that is not loaded, and it is not one oftestthat, devtools, usethis, rlang, pkgload, or pkgdown which are explicitly allowed.
When RStudio does not run a.run hyperlink, then it shows the codeand the user can copy and paste it to the console, if they considerit safe to run.
Note that depending on your version of RStudio, the behavior can change.
Draw a banner-like box in the console
Description
Draw a banner-like box in the console
Usage
list_border_styles()boxx( label, header = "", footer = "", border_style = "single", padding = 1, margin = 0, float = c("left", "center", "right"), col = NULL, background_col = NULL, border_col = col, align = c("left", "center", "right"), width = console_width())Arguments
label | Label to show, a character vector. Each element will bein a new line. You can color it using the |
header | Text to show on top border of the box. If too long,it will be cut. |
footer | Text to show on the bottom border of the box. If too long,it will be cut. |
border_style | String that specifies the border style. |
padding | Padding within the box. Either an integer vector offour numbers (bottom, left, top, right), or a single number |
margin | Margin around the box. Either an integer vector of fournumbers (bottom, left, top, right), or a single number |
float | Whether to display the box on the |
col | Color of text, and default border color. Either a stylefunction (seeANSI styles) or a color name that ispassed to |
background_col | Background color of the inside of the box.Either a style function (seeANSI styles), or a colorname which will be used in |
border_col | Color of the border. Either a style function(seeANSI styles) or a color name that is passed to |
align | Alignment of the label within the box: |
width | Width of the screen, defaults to |
Details
Defaults
boxx("Hello there!")#> ┌──────────────────┐ #> │ │ #> │ Hello there! │ #> │ │ #> └──────────────────┘
Change border style
boxx("Hello there!", border_style = "double")#> ╔══════════════════╗ #> ║ ║ #> ║ Hello there! ║ #> ║ ║ #> ╚══════════════════╝
Multiple lines
boxx(c("Hello", "there!"), padding = 1)#> ┌────────────┐ #> │ │ #> │ Hello │ #> │ there! │ #> │ │ #> └────────────┘
Padding
boxx("Hello there!", padding = 1)boxx("Hello there!", padding = c(1, 5, 1, 5))#> ┌──────────────────┐ #> │ │ #> │ Hello there! │ #> │ │ #> └──────────────────┘ #> ┌──────────────────────┐ #> │ │ #> │ Hello there! │ #> │ │ #> └──────────────────────┘
Floating
boxx("Hello there!", padding = 1, float = "center")boxx("Hello there!", padding = 1, float = "right")#> ┌──────────────────┐ #> │ │ #> │ Hello there! │ #> │ │ #> └──────────────────┘ #> ┌──────────────────┐ #> │ │ #> │ Hello there! │ #> │ │ #> └──────────────────┘
Text color
boxx(col_cyan("Hello there!"), padding = 1, float = "center")#> ┌──────────────────┐ #> │ │ #> │Hello there! │ #> │ │ #> └──────────────────┘Background color
boxx("Hello there!", padding = 1, background_col = "brown")boxx("Hello there!", padding = 1, background_col = bg_red)#> ┌──────────────────┐ #> ││ #> │ Hello there!│ #> ││ #> └──────────────────┘ #> ┌──────────────────┐ #> ││ #> │ Hello there!│ #> ││ #> └──────────────────┘
Border color
boxx("Hello there!", padding = 1, border_col = "green")boxx("Hello there!", padding = 1, border_col = col_red)#>┌──────────────────┐ #>││ #>│ Hello there!│ #>││ #>└──────────────────┘ #>┌──────────────────┐ #>││ #>│ Hello there!│ #>││ #>└──────────────────┘
Label alignment
boxx(c("Hi", "there", "you!"), padding = 1, align = "left")boxx(c("Hi", "there", "you!"), padding = 1, align = "center")boxx(c("Hi", "there", "you!"), padding = 1, align = "right")#> ┌───────────┐ #> │ │ #> │ Hi │ #> │ there │ #> │ you! │ #> │ │ #> └───────────┘ #> ┌───────────┐ #> │ │ #> │ Hi │ #> │ there │ #> │ you! │ #> │ │ #> └───────────┘ #> ┌───────────┐ #> │ │ #> │ Hi │ #> │ there │ #> │ you! │ #> │ │ #> └───────────┘
A very customized box
star <- symbol$starlabel <- c(paste(star, "Hello", star), " there!")boxx( col_white(label), border_style="round", padding = 1, float = "center", border_col = "tomato3", background_col="darkolivegreen")
#> ╭───────────────╮ #>││ #>│★ Hello ★│ #>│ there!│ #>││ #> ╰───────────────╯
About fonts and terminal settings
The boxes might or might not look great in your terminal, dependingon the box style you use and the font the terminal uses. We found thatthe Menlo font looks nice in most terminals an also in Emacs.
RStudio currently has a line height greater than one for console output,which makes the boxes ugly.
List all available spinners
Description
List all available spinners
Usage
list_spinners()Value
Character vector of all available spinner names.
See Also
Other spinners:demo_spinners(),get_spinner(),make_spinner()
Examples
list_spinners()get_spinner(list_spinners()[1])Create a new ANSI style
Description
Create a function that can be used to add ANSI styles to text.
Usage
make_ansi_style(..., bg = FALSE, grey = FALSE, colors = num_ansi_colors())Arguments
... | The style to create. See details and examples below. |
bg | Whether the color applies to the background. |
grey | Whether to specifically create a grey color.This flag is included, because ANSI 256 has a finer color scalefor greys, then the usual 0:5 scale for red, green and blue components.It is only used for RGB color specifications (either numericallyor via a hexadecimal string), and it is ignored on eight color ANSIterminals. |
colors | Number of colors, detected automaticallyby default. |
Details
The... style argument can be any of the following:
A cli ANSI style function of class
cli_ansi_style. This is returnedas is, without looking at the other arguments.An R color name, see
grDevices::colors().A 6- or 8-digit hexadecimal color string, e.g.
#ff0000meansred. Transparency (alpha channel) values are ignored.A one-column matrix with three rows for the red, greenand blue channels, as returned by
grDevices::col2rgb().
make_ansi_style() detects the number of colors to useautomatically (this can be overridden using thecolorsargument). If the number of colors is less than 256 (detected or given),then it falls back to the color in the ANSI eight color mode thatis closest to the specified (RGB or R) color.
Value
A function that can be used to color (style) strings.
See Also
Other ANSI styling:ansi-styles,combine_ansi_styles(),num_ansi_colors()
Examples
make_ansi_style("orange")make_ansi_style("#123456")make_ansi_style("orange", bg = TRUE)orange <- make_ansi_style("orange")orange("foobar")cat(orange("foobar"))Create a spinner
Description
Create a spinner
Usage
make_spinner( which = NULL, stream = "auto", template = "{spin}", static = c("dots", "print", "print_line", "silent"))Arguments
which | The name of the chosen spinner. If |
stream | The stream to use for the spinner. Typically this isstandard error, or maybe the standard output stream.It can also be a string, one of |
template | A template string, that will contain the spinner. Thespinner itself will be substituted for |
static | What to do if the terminal does not support dynamicdisplays:
|
Value
Acli_spinner object, which is a list of functions. Seeits methods below.
cli_spinner methods:
$spin(): output the next frame of the spinner.$finish(): terminate the spinner. Depending on terminal capabilitiesthis removes the spinner from the screen. Spinners can be reused,you can start calling the$spin()method again.
All methods return the spinner object itself, invisibly.
The spinner is automatically throttled to its ideal update frequency.
Examples
Default spinner
sp1 <- make_spinner()fun_with_spinner <- function() { lapply(1:100, function(x) { sp1$spin(); Sys.sleep(0.05) }) sp1$finish()}ansi_with_hidden_cursor(fun_with_spinner())Spinner with a template
sp2 <- make_spinner(template = "Computing {spin}")fun_with_spinner2 <- function() { lapply(1:100, function(x) { sp2$spin(); Sys.sleep(0.05) }) sp2$finish()}ansi_with_hidden_cursor(fun_with_spinner2())Custom spinner
sp3 <- make_spinner("simpleDotsScrolling", template = "Downloading {spin}")fun_with_spinner3 <- function() { lapply(1:100, function(x) { sp3$spin(); Sys.sleep(0.05) }) sp3$finish()}ansi_with_hidden_cursor(fun_with_spinner3())See Also
Other spinners:demo_spinners(),get_spinner(),list_spinners()
Match a selector to a container stack
Description
Match a selector to a container stack
Usage
match_selector(sels, cnts)Arguments
sels | A list of selector nodes. |
cnts | A list of container nodes. The last selector in the list must match the last container, so wedo the matching from the back. This is because we use this functionto calculate the style of newly encountered containers. |
Match a selector node to a container
Description
Match a selector node to a container
Usage
match_selector_node(node, cnt)Arguments
node | Selector node, as parsed by |
cnt | Container node, has elements The selector node matches the container, if all these hold:
|
Pluralization helper functions
Description
Pluralization helper functions
Usage
no(expr)qty(expr)Arguments
expr | For |
See Also
Other pluralization:pluralization,pluralize()
Examples
nfile <- 0; cli_text("Found {no(nfile)} file{?s}.")#> Found no files.nfile <- 1; cli_text("Found {no(nfile)} file{?s}.")#> Found 1 file.nfile <- 2; cli_text("Found {no(nfile)} file{?s}.")#> Found 2 files.Detect the number of ANSI colors to use
Description
Certain Unix and Windows terminals, and also certain R GUIs, e.g.RStudio, support styling terminal output using special controlsequences (ANSI sequences).
num_ansi_colors() detects if the current R session supports ANSIsequences, and if it does how many colors are supported.
Usage
num_ansi_colors(stream = "auto")detect_tty_colors()Arguments
stream | The stream that will be used for output, an R connectionobject. It can also be a string, one of |
Details
The detection mechanism is quite involved and it is designed to workout of the box on most systems. If it does not work on your system,please report a bug. Setting options and environment variables to turnon ANSI support is error prone, because they are inherited in otherenvironments, e.g. knitr, that might not have ANSI support.
If you want toturn off ANSI colors, set theNO_COLOR environmentvariable to a non-empty value.
The exact detection mechanism is as follows:
If the
cli.num_colorsoptions is set, that is returned.If the
R_CLI_NUM_COLORSenvironment variable is set to anon-empty value, then it is used.If the
crayon.enabledoption is set toFALSE, 1L is returned.(This is for compatibility with code that uses the crayon package.)If the
crayon.enabledoption is set toTRUEand thecrayon.colorsoption is not set, then the value of thecli.default_num_colorsoption, or if it is unset, then 8L isreturned.If the
crayon.enabledoption is set toTRUEand thecrayon.colorsoption is also set, then the latter is returned.(This is for compatibility with code that uses the crayon package.)If the
NO_COLORenvironment variable is set, then 1L is returned.If we are in knitr, then 1L is returned, to turn off colors in
.Rmdchunks.If
streamis"auto"(the default) and there is an activesink (either for"output"or"message"), then we return 1L.(In theory we would only need to check the stream that will bebe actually used, but there is no easy way to tell that.)If
streamis not"auto", but it isstderr()and there is anactive sink for it, then 1L is returned.(If a sink is active for "output", then R changes thestdout()stream, so this check is not needed.)If the
cli.default_num_colorsoption is set, then we use that.If R is running inside RGui on Windows, or R.app on macOS, then wereturn 1L.
If R is running inside RStudio, with color support, then theappropriate number of colors is returned, usually 256L.
If R is running on Windows, inside an Emacs version that is recentenough to support ANSI colors, then the value of the
cli.default_num_colorsoption, or if unset 8L is returned.(On Windows, Emacs hasisatty(stdout()) == FALSE, so we need tocheck for this here before dealing with terminals.)If
streamis not the standard output or standard error in aterminal, then 1L is returned.Otherwise we use and cache the result of the terminal colordetection (see below).
The terminal color detection algorithm:
If the
COLORTERMenvironment variable is set totruecoloror24bit, then we return 16 million colors.If the
COLORTERMenvironment variable is set to anything else,then we return the value of thecli.num_default_colorsoption,8L if unset.If R is running on Unix, inside an Emacs version that is recentenough to support ANSI colors, then the value of the
cli.default_num_colorsoption is returned, or 8L if unset.If we are on Windows in an RStudio terminal, then apparentlywe only have eight colors, but the
cli.default_num_colorsoptioncan be used to override this.If we are in a recent enough Windows 10 terminal, then thereis either true color (from build 14931) or 256 color (frombuild 10586) support. You can also use the
cli.default_num_colorsoption to override these.If we are on Windows, under ConEmu or cmder, or ANSICON is loaded,then the value of
cli.default_num_colors, or 8L if unset, isreturned.Otherwise if we are on Windows, return 1L.
Otherwise we are on Unix and try to run
tput colorsto determinethe number of colors. If this succeeds, we return its return value.If theTERMenvironment variable isxtermandtputreturned 8L, we return 256L, because xterm compatible terminalstend to support 256 colors(https://github.com/r-lib/crayon/issues/17)You can override this with thecli.default_num_colorsoption.If
TERMis set todumb, we return 1L.If
TERMstarts withscreen,xterm, orvt100, we return 8L.If
TERMcontainscolor,ansi,cygwinorlinux, we return 8L.Otherwise we return 1L.
Value
Integer, the number of ANSI colors the current R sessionsupports forstream.
See Also
Other ANSI styling:ansi-styles,combine_ansi_styles(),make_ansi_style()
Examples
num_ansi_colors()Parse a CSS3-like selector
Description
This is the rather small subset of CSS3 that is supported:
Usage
parse_selector(x)Arguments
x | CSS3-like selector string. |
Details
Selectors:
Type selectors, e.g.
inputselects all<input>elements.Class selectors, e.g.
.indexselects any element that has a classof "index".ID selector.
#tocwill match the element that has the ID"toc".
Combinators:
Descendant combinator, i.e. the space, that combinator selects nodesthat are descendants of the first element. E.g.
div spanwill matchall<span>elements that are inside a<div>element.
About cli pluralization
Description
About cli pluralization
Introduction
cli has tools to create messages that are printed correctly in singularand plural forms. This usually requires minimal extra work, andincreases the quality of the messages greatly. In this document we firstshow some pluralization examples that you can use as guidelines.Hopefully these are intuitive enough, so that they can be used withoutknowing the exact cli pluralization rules.
If you need pluralization without the semantic cli functions, see thepluralize() function.
Examples
Pluralization markup
In the simplest case the message contains a single{} gluesubstitution, which specifies the quantity that is used to selectbetween the singular and plural forms. Pluralization uses markup that issimilar to glue, but uses the{? and} delimiters:
library(cli)nfile <- 0; cli_text("Found {nfile} file{?s}.")#> Found 0 files.
nfile <- 1; cli_text("Found {nfile} file{?s}.")#> Found 1 file.
nfile <- 2; cli_text("Found {nfile} file{?s}.")#> Found 2 files.
Here the value ofnfile is used to decide whether the singular orplural form offile is used. This is the most common case for Englishmessages.
Irregular plurals
If the plural form is more difficult than a simples suffix, then thesingular and plural forms can be given, separated with a forward slash:
ndir <- 1; cli_text("Found {ndir} director{?y/ies}.")#> Found 1 directory.
ndir <- 5; cli_text("Found {ndir} director{?y/ies}.")#> Found 5 directories.
Use"no" instead of zero
For readability, it is better to use theno() helper function toinclude a count in a message.no() prints the word"no" if the countis zero, and prints the numeric count otherwise:
nfile <- 0; cli_text("Found {no(nfile)} file{?s}.")#> Found no files.
nfile <- 1; cli_text("Found {no(nfile)} file{?s}.")#> Found 1 file.
nfile <- 2; cli_text("Found {no(nfile)} file{?s}.")#> Found 2 files.
Use the length of character vectors
With the auto-collapsing feature of cli it is easy to include a list ofobjects in a message. When cli interprets a character vector as apluralization quantity, it takes the length of the vector:
pkgs <- "pkg1"cli_text("Will remove the {.pkg {pkgs}} package{?s}.")#> Will remove the pkg1 package.
pkgs <- c("pkg1", "pkg2", "pkg3")cli_text("Will remove the {.pkg {pkgs}} package{?s}.")#> Will remove the pkg1, pkg2, and pkg3 packages.
Note that the length is only used for non-numeric vectors (whenis.numeric(x) returnFALSE). If you want to use the length of anumeric vector, convert it to character viaas.character().
You can combine collapsed vectors with"no", like this:
pkgs <- character()cli_text("Will remove {?no/the/the} {.pkg {pkgs}} package{?s}.")#> Will remove no packages.
pkgs <- c("pkg1", "pkg2", "pkg3")cli_text("Will remove {?no/the/the} {.pkg {pkgs}} package{?s}.")#> Will remove the pkg1, pkg2, and pkg3 packages.
When the pluralization markup contains three alternatives, like above,the first one is used for zero, the second for one, and the third onefor larger quantities.
Choosing the right quantity
When the text contains multiple glue{} substitutions, the one rightbefore the pluralization markup is used. For example:
nfiles <- 3; ndirs <- 1cli_text("Found {nfiles} file{?s} and {ndirs} director{?y/ies}")#> Found 3 files and 1 directory
This is sometimes not the the correct one. You can explicitly specifythe correct quantity using theqty() function. This sets that quantitywithout printing anything:
nupd <- 3; ntotal <- 10cli_text("{nupd}/{ntotal} {qty(nupd)} file{?s} {?needs/need} updates")#> 3/10 files need updates
Note that if the message only contains a single{} substitution, thenthis may appear before or after the pluralization markup. If the messagecontains multiple{} substitutionsafter pluralization markup, anerror is thrown.
Similarly, if the message contains no{} substitutions at all, but haspluralization markup, an error is thrown.
Rules
The exact rules of cli pluralization. There are two sets of rules. Thefirst set specifies how a quantity is associated with a{?}pluralization markup. The second set describes how the{?} is parsedand interpreted.
Quantities
{}substitutions define quantities. If the value of a{}substitution is numeric (whenis.numeric(x)holds), then it has tohave length one to define a quantity. This is only enforced if the{}substitution is used for pluralization. The quantity is definedas the value of{}then, rounded withas.integer(). If the valueof{}is not numeric, then its quantity is defined as its length.If a message has
{?}markup but no{}substitution, an error isthrown.If a message has exactly one
{}substitution, its value is used asthe pluralization quantity for all{?}markup in the message.If a message has multiple
{}substitutions, then for each{?}markup cli uses the quantity of the{}substitution that precedesit.If a message has multiple
{}substitutions and has pluralizationmarkup without a preceding{}substitution, an error is thrown.
Pluralization markup
Pluralization markup starts with
{?and ends with}. It may notcontain{and}characters, so it may not contain{}substitutions either.Alternative words or suffixes are separated by
/.If there is a single alternative, thennothing is used if
quantity == 1and this single alternative is used ifquantity != 1.If there are two alternatives, the first one is used for
quantity == 1, the second one forquantity != 1(including'quantity == 0).If there are three alternatives, the first one is used for
quantity == 0, the second one forquantity == 1, and the thirdone otherwise.
See Also
Other pluralization:no(),pluralize()
String templating with pluralization
Description
pluralize() is similar toglue::glue(), with two differences:
It supports cli'spluralization syntax, using
{?}markers.It collapses substituted vectors into a comma separated string.
Usage
pluralize( ..., .envir = parent.frame(), .transformer = glue::identity_transformer)Arguments
...,.envir,.transformer | All arguments are passed to |
Details
Seepluralization and some examples below.
You need to install the glue package to use this function.
See Also
Other pluralization:no(),pluralization
Examples
# Regular pluralsnfile <- 0; pluralize("Found {nfile} file{?s}.")nfile <- 1; pluralize("Found {nfile} file{?s}.")nfile <- 2; pluralize("Found {nfile} file{?s}.")# Irregular pluralsndir <- 1; pluralize("Found {ndir} director{?y/ies}.")ndir <- 5; pluralize("Found {ndir} director{?y/ies}.")# Use 'no' instead of zeronfile <- 0; pluralize("Found {no(nfile)} file{?s}.")nfile <- 1; pluralize("Found {no(nfile)} file{?s}.")nfile <- 2; pluralize("Found {no(nfile)} file{?s}.")# Use the length of character vectorspkgs <- "pkg1"pluralize("Will remove the {pkgs} package{?s}.")pkgs <- c("pkg1", "pkg2", "pkg3")pluralize("Will remove the {pkgs} package{?s}.")pkgs <- character()pluralize("Will remove {?no/the/the} {pkgs} package{?s}.")pkgs <- c("pkg1", "pkg2", "pkg3")pluralize("Will remove {?no/the/the} {pkgs} package{?s}.")# Multiple quantitiesnfiles <- 3; ndirs <- 1pluralize("Found {nfiles} file{?s} and {ndirs} director{?y/ies}")# Explicit quantitiesnupd <- 3; ntotal <- 10cli_text("{nupd}/{ntotal} {qty(nupd)} file{?s} {?needs/need} updates")Turn on pretty-printing functions at the R console
Description
Defines a print method for functions, in the current session, that supportssyntax highlighting.
Usage
pretty_print_code()Details
The new print method takes priority over the built-in one. Usebase::suppressMessages() to suppress the alert message.
The cli progress C API
Description
The cli progress C API
The cli progress C API
CLI_SHOULD_TICK
A macro that evaluates to (int) 1 if a cli progress bar update is due,and to (int) 0 otherwise. If the timer hasn't been initialized in thiscompilation unit yet, then it is always 0. To initialize the timer,callcli_progress_init_timer() or create a progress bar withcli_progress_bar().
cli_progress_add()
void cli_progress_add(SEXP bar, double inc);
Add a number of progress units to the progress bar. It will alsotrigger an update if an update is due.
bar: progress bar object.inc: progress increment.
cli_progress_bar()
SEXP cli_progress_bar(double total, SEXP config);
Create a new progress bar object. The returned progress bar objectmust bePROTECT()-ed.
total: Total number of progress units. UseNA_REALif it is notknown.config: R named list object of additional parameters. May beNULL(the CNULL~) or R_NilValue(the RNULL') for the defaults.
config may contain the following entries:
name: progress bar name.status: (initial) progress bar status.type: progress bar type.total: total number of progress units.show_after: show the progress bar after the specified number ofseconds. This overrides the globalshow_afteroption.format: format string, must be specified for custom progress bars.format_done: format string for successful termination.format_failed: format string for unsuccessful termination.clear: whether to remove the progress bar from the screen aftertermination.auto_terminate: whether to terminate the progress bar when thenumber of current units equals the number of total progress units.
Example
#include <cli/progress.h>SEXP progress_test1() { int i; SEXP bar = PROTECT(cli_progress_bar(1000, NULL)); for (i = 0; i < 1000; i++) { cli_progress_sleep(0, 4 * 1000 * 1000); if (CLI_SHOULD_TICK) cli_progress_set(bar, i); } cli_progress_done(bar); UNPROTECT(1); return Rf_ScalarInteger(i);}cli_progress_done()
void cli_progress_done(SEXP bar);
Terminate the progress bar.
bar: progress bar object.
cli_progress_init_timer()
void cli_progress_init_timer();
Initialize the cli timer without creating a progress bar.
cli_progress_num()
int cli_progress_num();
Returns the number of currently active progress bars.
cli_progress_set()
void cli_progress_set(SEXP bar, double set);
Set the progress bar to the specified number of progress units.
bar: progress bar object.set: number of current progress progress units.
cli_progress_set_clear()
void cli_progress_set_clear(SEXP bar, int clear);
Set whether to remove the progress bar from the screen. You can callthis any time beforecli_progress_done() is called.
bar: progress bar object.clear: whether to remove the progress bar from the screen, zero orone.
cli_progress_set_format()
void cli_progress_set_format(SEXP bar, const char *format, ...);
Set a custom format string for the progress bar. This call does nottry to update the progress bar. If you want to request an update,callcli_progress_add(),cli_progress_set() orcli_progress_update().
bar: progress bar object.format: format string....: values to substitute intoformat.
format and... are passed tovsnprintf() to create a formatstring.
Format strings may contain glue substitutions, referring toprogress variables, pluralization, and clistyling.
cli_progress_set_name()
void cli_progress_set_name(SEXP bar, const char *name);
Set the name of the progress bar.
bar; progress bar object.name: progress bar name.
cli_progress_set_status()
void cli_progress_set_status(SEXP bar, const char *status);
Set the status of the progress bar.
bar: progress bar object.status: progress bar status.
cli_progress_set_type()
void cli_progress_set_type(SEXP bar, const char *type);
Set the progress bar type. Call this function right after creatingthe progress bar withcli_progress_bar(). Otherwise the behavior isundefined.
bar: progress bar object.type: progress bar type. Possible progress bar types:iterator,tasks,downloadandcustom.
cli_progress_update()
void cli_progress_update(SEXP bar, double set, double inc, int force);
Update the progress bar. Unlike the simplercli_progress_add() andcli_progress_set() function, it can force an update ifforce isset to 1.
bar: progress bar object.set: the number of current progress units. It is ignored ifnegative.inc: increment to add to the current number of progress units.It is ignored ifsetis not negative.force: whether to force an update, even if no update is due.
To force an update without changing the current number of progress units,supplyset = -1,inc = 0 andforce = 1.
Progress bar variables
Description
Progress bar variables
Details
These variables can be used in cli progress bar formatstrings. They are calculated on demand. To use a variable, e.g.pb_barin a package, you either need to to importpb_bar from cli, or usethe qualified form in the format string:cli::pb_bar.
Similarly, in R scripts, you can usepb_bar afterlibrary(cli),orcli::pb_bar if you do not attach the cli package.
pb_bar
Creates a visual progress bar. If the number of total unitsis unknown, then it will return an empty string.
cli_progress_bar( total = 100, format = "Fitting model {cli::pb_bar} {cli::pb_percent}")#> Fitting model███████████████████████████████ 66%
pb_current
The number of current progress units.
cli_progress_bar( total = 100, format = "{cli::pb_spin} Reading file {cli::pb_current}/{cli::pb_total}")#> ⠙ Reading file 66/100
pb_current_bytes
The number of current progress units formatted as bytes.The output has a constant width of six characters.
cli_progress_bar( format = "Got {cli::pb_current_bytes} in {cli::pb_elapsed}")#> Got 524 kB in 5s
pb_elapsed
The elapsed time since the start of the progress bar. The time ismeasured since the progress bar was created withcli_progress_bar()or similar.
cli_progress_bar( total = 100, format = "{cli::pb_bar} {cli::pb_percent} [{cli::pb_elapsed}]")#>███████████████████████████████ 66% [5s]
pb_elapsed_clock
The elapsed time, inhh::mm::ss format.
cli_progress_bar( total = 100, format = "{cli::pb_bar} {cli::pb_percent} [{cli::pb_elapsed_clock}]")#>███████████████████████████████ 66% [00:00:05]
pb_elapsed_raw
The number of seconds since the start of the progress bar.
cli_progress_bar( total = 100, format = "{cli::pb_bar} {cli::pb_percent} [{round(cli::pb_elapsed_raw)}s]")#>███████████████████████████████ 66% [5s]
pb_eta
The estimated time until the end of the progress bar,in human readable form.
cli_progress_bar( total = 100, format = "{cli::pb_bar} {cli::pb_percent} | ETA: {cli::pb_eta}")#>███████████████████████████████ 66% | ETA: 3s
pb_eta_raw
The estimated time until the end of the progressbar, in seconds. This is useful if you want to adjust the defaultpb_eta display.
cli_progress_bar( total = 100, format = "{cli::pb_bar} {cli::pb_percent} | ETA: {round(cli::pb_eta_raw)}s")#>███████████████████████████████ 66% | ETA: 3s
pb_eta_str
The estimated time until the end of the progress bar.It includes the"ETA:" prefix. It is only shown if the time can beestimated, otherwise it is the empty string.
cli_progress_bar( total = 100, format = "{cli::pb_bar} {cli::pb_percent} | {cli::pb_eta_str}")#>███████████████████████████████ 66% | ETA: 3s
pb_extra
pb_extra can be used to access extra data, see theextra argumentofcli_progress_bar() andcli_progress_update().
cli_progress_bar( total = 100, extra = list(user = whoami::username()), format = "Cleaning cache for user '{cli::pb_extra$user}': {cli::pb_current_bytes}")#> Cleaning cache for user 'gaborcsardi': 161 MB
pb_id
The id of the progress bar. The id has the formatcli-<pid>-<counter> where<pid> is the process id, and<counter> is an integer counter that is incremented every timecli needs a new unique id.
This is useful for debugging progress bars.
cli_progress_bar( format = "Progress bar '{cli::pb_id}' is at {cli::pb_current}")#> Progress bar 'cli-40403-1860' is at 64
pb_name
The name of the progress bar. This is supplied by thedeveloper, and it is by default the empty string. A space characteris added to non-empty names.
cli_progress_bar( name = "Loading training data", total = 100, format = "{cli::pb_name} {cli::pb_bar} {cli::pb_percent}")#> Loading training data███████████████████████████████ 66%
pb_percent
The percentage of the progress bar, always formattedin three characters plus the percentage sign. If the total number ofunits is unknown, then it is" NA%".
cli_progress_bar( total = 100, format = "{cli::pb_bar} {cli::pb_percent}")#>███████████████████████████████ 66%
pb_pid
The integer process id of the progress bar. This is useful if you areaggregating logging output or progress results from multiple processes.
pb_rate
The progress rate, in number of units per second, formatted in a string.
cli_progress_bar( total = 156, format = "Reading input files {pb_current}/{pb_total} [{pb_rate}]")#> Reading input files 68/156 [14/s]
pb_rate_raw
The raw progress rate, in number of units per second.
cli_progress_bar( total = 156, format = "Reading input files {pb_current}/{pb_total} [{round(pb_rate_raw)}/s]")#> Reading input files 68/156 [14/s]
pb_rate_bytes
The progress rate, formatted as bytes per second, in human readable form.
cli_progress_bar( total = 256 * 1024 * 1014, format = paste0( "Reading data {pb_current_bytes}/{pb_total_bytes} ", "[{ansi_trimws(pb_rate_bytes)}]" )#> Reading data 70 MB/266 MB [14 MB/s]
pb_spin
A spinner. The default spinner is selected via aget_spinner() call.
cli_progress_bar( total = 100, format = "{cli::pb_spin} Reading file {cli::pb_current}/{cli::pb_total}")#> ⠙ Reading file 66/100
pb_status
The status string of the progress bar. By default this is an emptystring, but it is possible to set it incli_progress_bar()and 'cli_progress_update()].
cli_progress_bar(status = "Connecting...")
#> ⠙ Connecting... 0 done (0/s) | 1s
pb_timestamp
A time stamp for the current time in ISO 8601 format.
cli_progress_bar( "Loading training data files", format = "{pb_timestamp} {pb_current} ({pb_rate})"#> 2025-04-22T12:27:16+00:00 125 (25/s)
pb_total
The total number of progress units, orNA if the number of units isunknown.
cli_progress_bar( total = 100, format = "{cli::pb_spin} Reading file {cli::pb_current}/{cli::pb_total}")#> ⠙ Reading file 66/100
pb_total_bytes
The total number of progress units, formatted asbytes, in a human readable format.
cli_progress_bar( total = 256 * 1024 * 1014, format = paste0( "Reading data {pb_current_bytes}/{pb_total_bytes} ", "[{ansi_trimws(pb_rate_bytes)}]" )#> Reading data 70 MB/266 MB [14 MB/s]
See Also
Other progress bar functions:cli_progress_along(),cli_progress_bar(),cli_progress_builtin_handlers(),cli_progress_message(),cli_progress_num(),cli_progress_output(),cli_progress_step(),cli_progress_styles()
Make a rule with one or two text labels
Description
The rule can include either a centered text label, or labels on theleft and right side.
To color the labels, use the functionscol_*,bg_* andstyle_*functions, seeANSI styles, and the examples below.To color the line, either these functions directly, or theline_coloption.
Usage
rule( left = "", center = "", right = "", line = 1, col = NULL, line_col = col, background_col = NULL, width = console_width())Arguments
left | Label to show on the left. It interferes with the |
center | Label to show at the center. It interferes with the |
right | Label to show on the right. It interferes with the |
line | The character or string that is used to draw the line.It can also |
col | Color of text, and default line color. Either an ANSI stylefunction (seeANSI styles), or a color name that ispassed to |
line_col,background_col | Either a color name (used in |
width | Width of the rule. Defaults to the |
Details
Simple rule
rule()
#> ──────────────────────────────────────────────────────────────────────
Line styles
Some strings for theline argument are interpreted specially:
"single": (same as1), a single line,"double": (same as2), a double line,"bar1","bar2","bar3", etc.,"bar8"uses varying height bars.
Double rule
rule(line = 2)
#> ══════════════════════════════════════════════════════════════════════
Bars
rule(line = "bar2")rule(line = "bar5")
#> ▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂ #> ▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅▅
Custom lines
rule(center = "TITLE", line = "~")
#> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TITLE ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
rule(center = "TITLE", line = col_blue("~-"))#>~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~- TITLE~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~
rule(center = bg_red(" ", symbol$star, "TITLE", symbol$star, " "), line = "\u2582", line_col = "orange")#>▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂ ★TITLE★▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂▂
Left label
rule(left = "Results")
#> ── Results ───────────────────────────────────────────────────────────
Centered label
rule(center = " * RESULTS * ")
#> ──────────────────────────── * RESULTS * ───────────────────────────
Colored labels
rule(center = col_red(" * RESULTS * "))#> ──────────────────────────── * RESULTS * ───────────────────────────Colored line
rule(center = col_red(" * RESULTS * "), line_col = "red")#>──────────────────────────── * RESULTS *───────────────────────────
Value
Character scalar, the rule.
Print the helpful ruler to the screen
Description
Print the helpful ruler to the screen
Usage
ruler(width = console_width())Arguments
width | Ruler width. |
Examples
ruler()A simple CLI theme
Description
To use this theme, you can set it as thecli.theme option.Note that this is in addition to the builtin theme, which is still ineffect.
Usage
simple_theme(dark = getOption("cli.theme_dark", "auto"))Arguments
dark | Whether the theme should be optimized for a darkbackground. If |
Details
options(cli.theme = cli::simple_theme())
and then CLI apps started after this will use it as the default theme.You can also use it temporarily, in a div element:
cli_div(theme = cli::simple_theme())
Showcase
show <- cli_div(theme = cli::simple_theme())cli_h1("Heading 1")cli_h2("Heading 2")cli_h3("Heading 3")cli_par()cli_alert_danger("Danger alert")cli_alert_warning("Warning alert")cli_alert_info("Info alert")cli_alert_success("Success alert")cli_alert("Alert for starting a process or computation", class = "alert-start")cli_end()cli_text("Packages and versions: {.pkg cli} {.version 1.0.0}.")cli_text("Time intervals: {.timestamp 3.4s}")cli_text("{.emph Emphasis} and {.strong strong emphasis}")cli_text("This is a piece of code: {.code sum(x) / length(x)}")cli_text("Function names: {.fn cli::simple_theme}")cli_text("Files: {.file /usr/bin/env}")cli_text("URLs: {.url https://r-project.org}")cli_h2("Longer code chunk")cli_par(class = "code R")cli_verbatim( '# window functions are useful for grouped mutates', 'mtcars %>%', ' group_by(cyl) %>%', ' mutate(rank = min_rank(desc(mpg)))')cli_end(show)#> #>──Heading 1───────────────────────────────────────────────────────── #> #> ─Heading 2 ── #> #>Heading 3 #>✖ Danger alert #>! Warning alert #>ℹ Info alert #>✔ Success alert #> → Alert for starting a process or computation #> #> Packages and versions:cli1.0.0. #> Time intervals:[3.4s] #>Emphasis andstrong emphasis #> This is a piece of code: `sum(x) / length(x)` #> Function names:`cli::simple_theme()`() #> Files:/usr/bin/env #> URLs:<https://r-project.org> #> #> ─Longer code chunk ── #># window functions are useful for grouped mutates #> mtcars%>% #>group_by(cyl)%>% #>mutate(rank =min_rank(desc(mpg))) #>
See Also
Draw a sparkline bar graph with unicode block characters
Description
Rendered usingblock elements.In most common fixed width fonts these are rendered wider than regularcharacters which means they are not suitable if you need precise alignment.
You might want to avoid sparklines on non-UTF-8 systems, because theydo not look good. You can useis_utf8_output() to test for supportfor them.
Usage
spark_bar(x)Arguments
x | A numeric vector between 0 and 1 |
Details
x <- seq(0, 1, length = 6)spark_bar(x)
#> ▁▂▄▅▇█
x <- seq(0, 1, length = 6)spark_bar(sample(x))
#> ▅▁█▄▇▂
spark_bar(seq(0, 1, length = 8))
#> ▁▂▃▄▅▆▇█
NAs are left out:
spark_bar(c(0, NA, 0.5, NA, 1))
#> ▁ ▄ █
See Also
Draw a sparkline line graph with Braille characters.
Description
You might want to avoid sparklines on non-UTF-8 systems, because theydo not look good. You can useis_utf8_output() to test for supportfor them.
Usage
spark_line(x)Arguments
x | A numeric vector between 0 and 1 |
Details
x <- seq(0, 1, length = 10)spark_line(x)
#> ⣀⡠⠔⠊⠉
See Also
Start, stop, query the default cli application
Description
start_app creates an app, and places it on the top of the app stack.
Usage
start_app( theme = getOption("cli.theme"), output = c("auto", "message", "stdout", "stderr"), .auto_close = TRUE, .envir = parent.frame())stop_app(app = NULL)default_app()Arguments
theme | Theme to use. |
output | How to print the output. |
.auto_close | Whether to stop the app, when the calling frameis destroyed. |
.envir | The environment to use, instead of the calling frame,to trigger the stop of the app. |
app | App to stop. If |
Details
stop_app removes the top app, or multiple apps from the app stack.
default_app returns the default app, the one on the top of the stack.
Value
start_app returns the new app,default_app returns the default app.stop_app does not return anything.
Terminal Hyperlinks
Description
ansi_hyperlink() creates an ANSI hyperlink.
Usage
style_hyperlink(text, url, params = NULL)ansi_has_hyperlink_support()ansi_hyperlink_types()Arguments
text | Text to show. |
url | URL to link to. |
params | A named character vector of additional parameters, or |
Details
This function is currently experimental. In particular, many of theansi_*() functions do not support it properly.
ansi_has_hyperlink_support() checks if the currentstdout()supports hyperlinks.
See alsohttps://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda.
ansi_hyperlink_types() checks if currentstdout() supports varioustypes of hyperlinks. It returns a list with entrieshref,run,help andvignettes.
Value
Styledcli_ansi_string forstyle_hyperlink().Logical scalar foransi_has_hyperlink_support().
Examples
cat("This is an", style_hyperlink("R", "https://r-project.org"), "link.\n")ansi_has_hyperlink_support()Various handy symbols to use in a command line UI
Description
Various handy symbols to use in a command line UI
Usage
symbollist_symbols()Format
A named list, seenames(symbol) for all sign names.
Details
On Windows they have a fallback to less fancy symbols.
list_symbols() prints a table with all symbols to the screen.
Examples
cat(symbol$tick, " SUCCESS\n", symbol$cross, " FAILURE\n", sep = "")## All symbolscat(paste(format(names(symbol), width = 20), unlist(symbol)), sep = "\n")Test cli output with testthat
Description
Use this function in your testthat test files, to test cli output.It requires testthat edition 3, and works best with snapshot tests.
Usage
test_that_cli( desc, code, configs = c("plain", "ansi", "unicode", "fancy"), links = NULL)Arguments
desc | Test description, passed to |
code | Test code, it is modified to set up the cli config, andthen passed to |
configs | cli configurations to test |
links | Whether to run the code with various hyperlinks allowed.If
|
Details
test_that_cli() callstestthat::test_that() multiple times, withdifferent cli configurations. This makes it simple to test cli outputwith and without ANSI colors, with and without Unicode characters.
Currently available configurations:
plain: no ANSI colors, ASCII characters only.ansi: ANSI colors, ASCII characters only.unicode: no ANSI colors, Unicode characters.fancy; ANSI colors, Unicode characters.
See examples below and in cli's own tests, e.g. inhttps://github.com/r-lib/cli/tree/main/tests/testthatand the corresponding snapshots athttps://github.com/r-lib/cli/tree/main/tests/testthat/_snaps
Important note regarding Windows
Because of base R's limitation to record Unicode characters on Windows,we suggest that you record your snapshots on Unix, or you restrictyour tests to ASCII configurations.
Unicode tests on Windows are automatically skipped by testthatcurrently.
Examples
# testthat cannot record or compare snapshots when you run these# examples interactively, so you might want to copy them into a test# file# Default configurationscli::test_that_cli("success", { testthat::local_edition(3) testthat::expect_snapshot({ cli::cli_alert_success("wow") })})# Only use two configurations, because this output does not have colorscli::test_that_cli(configs = c("plain", "unicode"), "cat_bullet", { testthat::local_edition(3) testthat::expect_snapshot({ cli::cat_bullet(letters[1:5]) })})# You often need to evaluate all cli calls of a test case in the same# environment. Use `local()` to do that:cli::test_that_cli("theming", { testthat::local_edition(3) testthat::expect_snapshot(local({ cli::cli_div(theme = list(".alert" = list(before = "!!! "))) cli::cli_alert("wow") }))})About cli themes
Description
CLI elements can be styled via a CSS-like language of selectors andproperties. Only a small subset of CSS3 is supported, anda lot visual properties cannot be implemented on a terminal, so thesewill be ignored as well.
Adding themes
The style of an element is calculated from themes from four sources.These form a stack, and the themes on the top of the stack takeprecedence, over themes in the bottom.
The cli package has a built-in theme. This is always active.See
builtin_theme().When an app object is created via
start_app(), the caller canspecify a theme, that is added to theme stack. If no theme isspecified forstart_app(), the content of thecli.themeoptionis used. Removed when the corresponding app stops.The user may specify a theme in the
cli.user_themeoption. Thisis added to the stackafter the app's theme (step 2.), so it canoverride its settings. Removed when the app that added it stops.Themes specified explicitly in
cli_div()elements. These areremoved from the theme stack, when the correspondingcli_div()elements are closed.
Writing themes
A theme is a named list of lists. The name of each entry is a CSSselector. Only a subset of CSS is supported:
Type selectors, e.g.
inputselects all<input>elements.Class selectors, e.g.
.indexselects any element that has a classof "index".ID selector.
#tocwill match the element that has the ID "toc".The descendant combinator, i.e. the space, that selects nodesthat are descendants of the first element. E.g.
div spanwill matchall<span>elements that are inside a<div>element.
The content of a theme list entry is another named list, where thenames are CSS properties, e.g.color, orfont-weight ormargin-left, and the list entries themselves define the values ofthe properties. Seebuiltin_theme() andsimple_theme() for examples.
Formatter callbacks
For flexibility, themes may also define formatter functions, withproperty namefmt. These will be called once the other styles areapplied to an element. They are only called on elements that produceoutput, i.e.not on container elements.
Supported properties
Right now only a limited set of properties are supported. These includeleft, right, top and bottom margins, background and foreground colors,bold and italic fonts, underlined text. Thebefore andafterproperties are supported to insert text before and after thecontent of the element.
The current list of properties:
after: A string literal to insert after the element. It can also bea function that returns a string literal. Supported by all inlineelements, list items, alerts and rules.background-color: An R color name, or HTML hexadecimal color.It can be applied to most elements (inline elements, rules, text,etc.), but the background of containers is not colored properlycurrently.before: A string literal to insert before the element. It can also bea function that returns a string literal. Supported by all inlineelements, list items, alerts and rules.class-map: Its value can be a named list, and it specifies howR (S3) class names are mapped to cli class names. E.g.list(fs_path = "file")specifies thatfs_pathobjects (from the fspackage) should always print as.fileobjects in cli.color: Text color, an R color name or a HTML hexadecimal color. Itcan be applied to most elements that are printed.collapse: Specifies how to collapse a vector, before applyingstyling. If a character string, then that is used as the separator.If a function, then it is called, with the vector as the onlyargument.digits: Number of digits after the decimal point for numeric inlineelement of class.val.fmt: Generic formatter function that takes an input text and returnsformatted text. Can be applied to most elements. If colors are in use,the input text provided tofmtalready includes ANSI sequences.font-style: If"italic"then the text is printed as cursive.font-weight: If"bold", then the text is printed in boldface.line-type: Line type forcli_rule().list-style-type: String literal or functions that returns a stringliteral, to be used as a list item marker in un-ordered lists.margin-bottom,margin-left,margin-right,margin-top: Margins.padding-left,padding-right: This is currently used the same wayas the margins, but this might change later.start: Integer number, the first element in an ordered list.string-quote: Quoting character for inline elements of class.val.text-decoration: If"underline", then underlined text is created.text-exdent: Amount of indentation from the second line of wrappedtext.transform: A function to call on glue substitutions, beforecollapsing them. Note thattransformis applied prior toimplementing color via ANSI sequences.vec-last: The last separator when collapsing vectors.vec-sep: The separator to use when collapsing vectors.vec-sep2: The separator to use for two elements when collapsingvectors. If not set, thenvec-sepis used for these as well.vec-trunc: Vectors longer than this will be truncated. Defaults to100.vec-trunc-style: Select between two ways of collapsing vectors:"both-ends"is the current default and it shows the beginning andthe end of the vector."head"only shows the beginning of the vector.
More properties might be added later. If you think that a property isnot applied properly to an element, please open an issue about it inthe cli issue tracker.
Examples
Color of headings, that are only active in paragraphs with an'output' class:
list( "par.output h1" = list("background-color" = "red", color = "#e0e0e0"), "par.output h2" = list("background-color" = "orange", color = "#e0e0e0"), "par.output h3" = list("background-color" = "blue", color = "#e0e0e0"))Create a custom alert type:
list( ".alert-start" = list(before = symbol$play), ".alert-stop" = list(before = symbol$stop))
Draw a tree
Description
Draw a tree using box drawing characters. Unicode characters areused if available. (Set thecli.unicode option if auto-detectionfails.)
Usage
tree( data, root = data[[1]][[1]], style = NULL, width = console_width(), trim = FALSE)Arguments
data | Data frame that contains the tree structure.The first column is an id, and the second column is a list column,that contains the ids of the child nodes. The optional third columnmay contain the text to print to annotate the node. |
root | The name of the root node. |
style | Optional box style list. |
width | Maximum width of the output. Defaults to the |
trim | Whether to avoid traversing the same nodes multiple times.If |
Details
A node might appear multiple times in the tree, or might not appearat all.
data <- data.frame( stringsAsFactors = FALSE, package = c("processx", "backports", "assertthat", "Matrix", "magrittr", "rprojroot", "clisymbols", "prettyunits", "withr", "desc", "igraph", "R6", "crayon", "debugme", "digest", "irlba", "rcmdcheck", "callr", "pkgconfig", "lattice"), dependencies = I(list( c("assertthat", "crayon", "debugme", "R6"), character(0), character(0), "lattice", character(0), "backports", character(0), c("magrittr", "assertthat"), character(0), c("assertthat", "R6", "crayon", "rprojroot"), c("irlba", "magrittr", "Matrix", "pkgconfig"), character(0), character(0), "crayon", character(0), "Matrix", c("callr", "clisymbols", "crayon", "desc", "digest", "prettyunits", "R6", "rprojroot", "withr"), c("processx", "R6"), character(0), character(0) )))tree(data)#> processx #> ├─assertthat #> ├─crayon #> ├─debugme #> │ └─crayon #> └─R6
tree(data, root = "rcmdcheck")
#> rcmdcheck #> ├─callr #> │ ├─processx #> │ │ ├─assertthat #> │ │ ├─crayon #> │ │ ├─debugme #> │ │ │ └─crayon #> │ │ └─R6 #> │ └─R6 #> ├─clisymbols #> ├─crayon #> ├─desc #> │ ├─assertthat #> │ ├─R6 #> │ ├─crayon #> │ └─rprojroot #> │ └─backports #> ├─digest #> ├─prettyunits #> │ ├─magrittr #> │ └─assertthat #> ├─R6 #> ├─rprojroot #> │ └─backports #> └─withr
Colored nodes
data$label <- paste(data$package, style_dim(paste0("(", c("2.0.0.1", "1.1.1", "0.2.0", "1.2-11", "1.5", "1.2", "1.2.0", "1.0.2", "2.0.0", "1.1.1.9000", "1.1.2", "2.2.2", "1.3.4", "1.0.2", "0.6.12", "2.2.1", "1.2.1.9002", "1.0.0.9000", "2.0.1", "0.20-35"), ")")) )roots <- ! data$package %in% unlist(data$dependencies)data$label[roots] <- col_cyan(style_italic(data$label[roots]))tree(data, root = "rcmdcheck")#>rcmdcheck (1.2.1.9002) #> ├─callr (1.0.0.9000) #> │ ├─processx (2.0.0.1) #> │ │ ├─assertthat (0.2.0) #> │ │ ├─crayon (1.3.4) #> │ │ ├─debugme (1.0.2) #> │ │ │ └─crayon (1.3.4) #> │ │ └─R6 (2.2.2) #> │ └─R6 (2.2.2) #> ├─clisymbols (1.2.0) #> ├─crayon (1.3.4) #> ├─desc (1.1.1.9000) #> │ ├─assertthat (0.2.0) #> │ ├─R6 (2.2.2) #> │ ├─crayon (1.3.4) #> │ └─rprojroot (1.2) #> │ └─backports (1.1.1) #> ├─digest (0.6.12) #> ├─prettyunits (1.0.2) #> │ ├─magrittr (1.5) #> │ └─assertthat (0.2.0) #> ├─R6 (2.2.2) #> ├─rprojroot (1.2) #> │ └─backports (1.1.1) #> └─withr (2.0.0)Trimming
pkgdeps <- list( "dplyr@0.8.3" = c("assertthat@0.2.1", "glue@1.3.1", "magrittr@1.5", "R6@2.4.0", "Rcpp@1.0.2", "rlang@0.4.0", "tibble@2.1.3", "tidyselect@0.2.5"), "assertthat@0.2.1" = character(), "glue@1.3.1" = character(), "magrittr@1.5" = character(), "pkgconfig@2.0.3" = character(), "R6@2.4.0" = character(), "Rcpp@1.0.2" = character(), "rlang@0.4.0" = character(), "tibble@2.1.3" = c("cli@1.1.0", "crayon@1.3.4", "fansi@0.4.0", "pillar@1.4.2", "pkgconfig@2.0.3", "rlang@0.4.0"), "cli@1.1.0" = c("assertthat@0.2.1", "crayon@1.3.4"), "crayon@1.3.4" = character(), "fansi@0.4.0" = character(), "pillar@1.4.2" = c("cli@1.1.0", "crayon@1.3.4", "fansi@0.4.0", "rlang@0.4.0", "utf8@1.1.4", "vctrs@0.2.0"), "utf8@1.1.4" = character(), "vctrs@0.2.0" = c("backports@1.1.5", "ellipsis@0.3.0", "digest@0.6.21", "glue@1.3.1", "rlang@0.4.0", "zeallot@0.1.0"), "backports@1.1.5" = character(), "ellipsis@0.3.0" = c("rlang@0.4.0"), "digest@0.6.21" = character(), "glue@1.3.1" = character(), "zeallot@0.1.0" = character(), "tidyselect@0.2.5" = c("glue@1.3.1", "purrr@1.3.1", "rlang@0.4.0", "Rcpp@1.0.2"), "purrr@0.3.3" = c("magrittr@1.5", "rlang@0.4.0"))pkgs <- data.frame( stringsAsFactors = FALSE, name = names(pkgdeps), deps = I(unname(pkgdeps)))tree(pkgs, trim = TRUE)#> dplyr@0.8.3 #> ├─assertthat@0.2.1 #> ├─glue@1.3.1 #> ├─magrittr@1.5 #> ├─R6@2.4.0 #> ├─Rcpp@1.0.2 #> ├─rlang@0.4.0 #> ├─tibble@2.1.3 #> │ ├─cli@1.1.0 #> │ │ ├─assertthat@0.2.1 #> │ │ └─crayon@1.3.4 #> │ ├─crayon@1.3.4 #> │ ├─fansi@0.4.0 #> │ ├─pillar@1.4.2 #> │ │ ├─cli@1.1.0 #> │ │ ├─crayon@1.3.4 #> │ │ ├─fansi@0.4.0 #> │ │ ├─rlang@0.4.0 #> │ │ ├─utf8@1.1.4 #> │ │ └─vctrs@0.2.0 #> │ │ ├─backports@1.1.5 #> │ │ ├─ellipsis@0.3.0 #> │ │ │ └─rlang@0.4.0 #> │ │ ├─digest@0.6.21 #> │ │ ├─glue@1.3.1 #> │ │ ├─rlang@0.4.0 #> │ │ └─zeallot@0.1.0 #> │ ├─pkgconfig@2.0.3 #> │ └─rlang@0.4.0 #> └─tidyselect@0.2.5 #> ├─glue@1.3.1 #> ├─rlang@0.4.0 #> └─Rcpp@1.0.2
# Mark the trimmed nodespkgs$label <- pkgs$namepkgs$trimmed <- paste(pkgs$name, " (trimmed)")tree(pkgs, trim = TRUE)
#> dplyr@0.8.3 #> ├─assertthat@0.2.1 #> ├─glue@1.3.1 #> ├─magrittr@1.5 #> ├─R6@2.4.0 #> ├─Rcpp@1.0.2 #> ├─rlang@0.4.0 #> ├─tibble@2.1.3 #> │ ├─cli@1.1.0 #> │ │ ├─assertthat@0.2.1 (trimmed) #> │ │ └─crayon@1.3.4 #> │ ├─crayon@1.3.4 (trimmed) #> │ ├─fansi@0.4.0 #> │ ├─pillar@1.4.2 #> │ │ ├─cli@1.1.0 (trimmed) #> │ │ ├─crayon@1.3.4 (trimmed) #> │ │ ├─fansi@0.4.0 (trimmed) #> │ │ ├─rlang@0.4.0 (trimmed) #> │ │ ├─utf8@1.1.4 #> │ │ └─vctrs@0.2.0 #> │ │ ├─backports@1.1.5 #> │ │ ├─ellipsis@0.3.0 #> │ │ │ └─rlang@0.4.0 (trimmed) #> │ │ ├─digest@0.6.21 #> │ │ ├─glue@1.3.1 (trimmed) #> │ │ ├─rlang@0.4.0 (trimmed) #> │ │ └─zeallot@0.1.0 #> │ ├─pkgconfig@2.0.3 #> │ └─rlang@0.4.0 (trimmed) #> └─tidyselect@0.2.5 #> ├─glue@1.3.1 (trimmed) #> ├─rlang@0.4.0 (trimmed) #> └─Rcpp@1.0.2 (trimmed)
Value
Character vector, the lines of the tree drawing.
ANSI colors palettes
Description
If your platform supports at least 256 colors, then you can configurethe colors that cli uses for the eight base and the eight bright colors.(I.e. the colors ofcol_black(),col_red(), andcol_br_black(),col_br_red(), etc.
Usage
truecoloransi_palettesansi_palette_show(palette = NULL, colors = num_ansi_colors(), rows = 4)Arguments
palette | The palette to show, in the same format as for the |
colors | Number of ANSI colors to use the show the palette. If theplatform does not have sufficient support, the output might havea lower color resolution. Without color support it will have no colorat all. |
rows | The number of colored rows to print. |
Format
truecolor is an integer scalar.
ansi_palettes is a data frame with one row for each palette,and one column for each base ANSI color.attr(ansi_palettes, "info")contains a list with information about each palette.
Details
truecolor is an integer constant for the number of 24 bit ANSI colors.
To customize the default palette, set thecli.palette option to thename of a built-in palette (seeansi_palettes()), or the list of16 colors. Colors can be specified with RGB colors strings:#rrggbb or R color names (see the output ofgrDevices::colors()).
For example, you can put this in your R profile:
options(cli.palette = "vscode")
It is currently not possible to configure the background colorsseparately, these will be always the same as the foreground colors.
If your platform only has 256 colors, then the colors specified in thepalette have to be interpolated. On true color platforms they RGBvalues are used as-is.
ansi_palettes is a data frame of the built-in palettes, each rowis one palette.
ansi_palette_show() shows the colors of an ANSI palette on the screen.
Value
ansi_palette_show returns a character vector, the rows thatare printed to the screen, invisibly.
Examples
ansi_palettesansi_palette_show("dichro", colors = truecolor)Working around the bad Unicode character widths
Description
R 3.6.2 and also the coming 3.6.3 and 4.0.0 versions use the Unicode 8standard to calculate the display width of Unicode characters.Unfortunately the widths of most emojis are incorrect in this standard,and width 1 is reported instead of the correct 2 value.
Details
cli implements a workaround for this. The package contains a table thatcontains all Unicode ranges that have wide characters (display width 2).
On first use of one of the workaround wrappers (inansi_nchar(), etc.)we check what the current version of R thinks about the width of thesecharacters, and then create a regex that matches the ones that Ris wrong about (re_bad_char_width).
Then we use this regex to duplicate all of the problematic charactersin the input string to the wrapper function, before calling the realstring manipulation function (nchar(),strwrap()) etc. At end weundo the duplication before we return the result.
This workaround is fine fornchar() andstrwrap(), and consequentlyansi_align() andansi_strtrim() as well.
The rest of theansi_*() functions work on characters, and do notdeal with character width.
Break an UTF-8 character vector into grapheme clusters
Description
Break an UTF-8 character vector into grapheme clusters
Usage
utf8_graphemes(x)Arguments
x | Character vector. |
Value
List of characters vectors, the grapheme clusters of the inputstring.
See Also
Other UTF-8 string manipulation:utf8_nchar(),utf8_substr()
Examples
# Five grapheme clustersstr <- paste0( "\U0001f477\U0001f3ff\u200d\u2640\ufe0f", "\U0001f477\U0001f3ff", "\U0001f477\u200d\u2640\ufe0f", "\U0001f477\U0001f3fb", "\U0001f477\U0001f3ff")cat(str, "\n")chrs <- utf8_graphemes(str)Count the number of characters in a character vector
Description
By default it counts Unicode grapheme clusters, instead of code points.
Usage
utf8_nchar(x, type = c("chars", "bytes", "width", "graphemes", "codepoints"))Arguments
x | Character vector, it is converted to UTF-8. |
type | Whether to count graphemes (characters), code points,bytes, or calculate the display width of the string. |
Value
Numeric vector, the length of the strings in the charactervector.
See Also
Other UTF-8 string manipulation:utf8_graphemes(),utf8_substr()
Examples
# Grapheme example, emoji with combining characters. This is a single# grapheme, consisting of five Unicode code points:# * `\U0001f477` is the construction worker emoji# * `\U0001f3fb` is emoji modifier that changes the skin color# * `\u200d` is the zero width joiner# * `\u2640` is the female sign# * `\ufe0f` is variation selector 16, requesting an emoji style glyphemo <- "\U0001f477\U0001f3fb\u200d\u2640\ufe0f"cat(emo)utf8_nchar(emo, "chars") # = graphemesutf8_nchar(emo, "bytes")utf8_nchar(emo, "width")utf8_nchar(emo, "codepoints")# For comparision, the output for width depends on the R version used:nchar(emo, "chars")nchar(emo, "bytes")nchar(emo, "width")Substring of an UTF-8 string
Description
This function uses grapheme clusters instead of Unicode code points inUTF-8 strings.
Usage
utf8_substr(x, start, stop)Arguments
x | Character vector. |
start | Starting index or indices, recycled to match the lengthof |
stop | Ending index or indices, recycled to match the length of |
Value
Character vector of the same length asx, containingthe requested substrings.
See Also
Other UTF-8 string manipulation:utf8_graphemes(),utf8_nchar()
Examples
# Five grapheme clusters, select the middle threestr <- paste0( "\U0001f477\U0001f3ff\u200d\u2640\ufe0f", "\U0001f477\U0001f3ff", "\U0001f477\u200d\u2640\ufe0f", "\U0001f477\U0001f3fb", "\U0001f477\U0001f3ff")cat(str)str24 <- utf8_substr(str, 2, 4)cat(str24)Simulate (a subset of) a VT-5xx ANSI terminal
Description
This is utility function that calculates the state of a VT-5xx screenafter a certain set of output.
Usage
vt_output(output, width = 80L, height = 25L)Arguments
output | Character vector or raw vector. Character vectors arecollapsed (without a separater), and converted to a raw vector using |
width | Terminal width. |
height | Terminal height. |
Details
Currently it supports:
configurable terminal width and height
ASCII printable characters.
\n,\r.ANSI SGR colors, 8 color mode, 256 color mode and true color mode.
Other ANSI SGR features: bold, italic, underline, strikethrough,blink, inverse.
It doesnot currently supports other features, mode notably:
Other ANSI control sequences and features. Other control sequencesare silently ignored.
Wide Unicode characters. Their width is not taken into accountcorrectly.
Unicode graphemes.
Value
Data frame with columnslineno,segmentno,segment,attributes.
Note
This function is experimental, and the virtual temrinal API willlikely change in future versions of cli.