### Example: Default configurations for cli output testing Source: https://cli.r-lib.org/reference/test_that_cli This example demonstrates how to use `test_that_cli` with default configurations to test a success alert. Note that snapshot tests cannot be recorded or compared interactively; copy this code into a test file for actual use. ```r # Default configurations cli::test_that_cli("success", { testthat::local_edition(3) testthat::expect_snapshot({ cli::cli_alert_success("wow") }) }) ``` -------------------------------- ### Start, Stop, and Get Default CLI App Source: https://cli.r-lib.org/reference/start_app Use these functions to manage the cli application stack. `start_app` creates a new app, `stop_app` removes the top app or multiple apps, and `default_app` returns the current default app. ```r start_app( theme = getOption("cli.theme"), output = c("auto", "message", "stdout", "stderr"), .auto_close = TRUE, .envir = parent.frame() ) stop_app(app = NULL) default_app() ``` -------------------------------- ### start_app Source: https://cli.r-lib.org/reference/start_app Creates and starts a new CLI application, placing it at the top of the application stack. ```APIDOC ## start_app ### Description Creates an app, and places it on the top of the app stack. ### Arguments - theme (any) - Theme to use. - output (character) - How to print the output. Possible values are "auto", "message", "stdout", "stderr". - .auto_close (logical) - Whether to stop the app when the calling frame is destroyed. - .envir (environment) - The environment to use, instead of the calling frame, to trigger the stop of the app. ### Value Returns the new app that was started. ``` -------------------------------- ### Example of cli_format_method usage Source: https://cli.r-lib.org/reference/cli_format_method Demonstrates how to set a simple theme and use new_r_package to display package information. The theme is restored afterwards. ```r opt <- options(cli.theme = simple_theme()) print(new_r_package("cli")) #> #> ── cli ─ Helpers for Developing Command Line Interfaces ─────────────── #> 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. #> • Version: 3.6.6 #> • Maintainer: Gábor Csárdi #> • License: MIT + file LICENSE #> See more at options(opt) # <- restore theme ``` -------------------------------- ### Basic keypress() usage Source: https://cli.r-lib.org/reference/keypress Demonstrates how to capture a keypress and print it. This example is conditional and will not run unless `FALSE` is changed to `TRUE`. ```r if (FALSE) { x <- keypress() catalog("You pressed key", x, "\n") } ``` -------------------------------- ### boxx Function Examples Source: https://cli.r-lib.org/reference/boxx Demonstrates the usage of the boxx function with different parameters for customization. ```APIDOC ## boxx Function Usage ### Description Creates text boxes with various customization options. ### Parameters - `text` (character vector): The text content to display within the box. - `padding` (numeric): The amount of padding around the text. - `background_col` (character): The background color of the box. - `border_col` (character): The color of the box border. - `align` (character): The alignment of the text within the box ('left', 'center', 'right'). - `border_style` (character): The style of the border (e.g., 'round'). - `float` (character): The horizontal alignment of the box itself (e.g., 'center'). ### Examples #### Background Color ```R boxx("Hello there!", padding = 1, background_col = "brown") boxx("Hello there!", padding = 1, background_col = bg_red) ``` #### Border Color ```R boxx("Hello there!", padding = 1, border_col = "green") boxx("Hello there!", padding = 1, border_col = col_red) ``` #### Label Alignment ```R 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") ``` #### Customized Box ```R star <- symbol$star label <- c(paste(star, "Hello", star), " there!") boxx( col_white(label), border_style="round", padding = 1, float = "center", border_col = "tomato3", background_col="darkolivegreen" ) ``` ``` -------------------------------- ### Install cli Package Source: https://cli.r-lib.org/llms.txt Install the stable version of the cli package from CRAN. ```r install.packages("cli") ``` -------------------------------- ### cli_process_start Source: https://cli.r-lib.org/reference/cli_process_start Starts a process and displays a message in the status bar. It also sets up automatic handling for successful termination or failure upon exit. ```APIDOC ## cli_process_start ### Description Starts a process and displays a message in the status bar. It also sets up automatic handling for successful termination or failure upon exit. ### Usage ```r 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() ) ``` ### Arguments - msg (string): The message to show to indicate the start of the process or computation. It will be collapsed into a single string, and the first line is kept and cut to console_width(). - msg_done (string, optional): The message to use for successful termination. - msg_failed (string, optional): The message to use for unsuccessful termination. - on_exit (character, optional): Whether this process should fail or terminate successfully when the calling function (or the environment in `.envir`) exits. Defaults to "auto". - msg_class (string, optional): The style class to add to the message. Use an empty string to suppress styling. Defaults to "alert-info". - done_class (string, optional): The style class to add to the successful termination message. Use an empty string to suppress styling. Defaults to "alert-success". - failed_class (string, optional): The style class to add to the unsuccessful termination message. Use an empty string to suppress styling. Defaults to "alert-danger". - .auto_close (boolean, optional): Whether to clear the status bar when the calling function finishes (or `.envir` is removed from the stack, if specified). Defaults to TRUE. - .envir (environment, optional): Environment to evaluate the glue expressions in. It is also used to auto-clear the status bar if `.auto_close` is TRUE. Defaults to parent.frame(). ### Value Id of the status bar container. ``` -------------------------------- ### Install Development Version of cli Source: https://cli.r-lib.org/llms.txt Install the development version of the cli package from GitHub using the pak package manager. ```r pak::pak("r-lib/cli") ``` -------------------------------- ### Displaying Informational Messages with ui_info Source: https://cli.r-lib.org/articles/usethis-ui Example of using usethis::ui_info() to display a simple informational message. ```r ui_info("No labels need renaming") ``` -------------------------------- ### Example: Progress Bar with lapply and letters Source: https://cli.r-lib.org/articles/progress This example demonstrates how to use cli_progress_along with lapply to process the 'letters' vector, showing a progress bar during execution. Sys.sleep() is used to simulate work. ```r f <- function() { rawabc <- lapply( cli_progress_along(letters), function(i) { charToRaw(letters[i]) Sys.sleep(0.5) } ) } f() ``` -------------------------------- ### Traditional cli progress bar example Source: https://cli.r-lib.org/articles/progress Demonstrates the traditional three-step process for using cli progress bars: creating with `cli_progress_bar()`, updating with `cli_progress_update()`, and terminating with `cli_progress_done()`. ```r 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() ``` -------------------------------- ### Usage Examples Source: https://cli.r-lib.org/reference/ansi-styles Demonstrates how to use the ANSI styling functions for coloring text, combining styles, and creating styled messages. ```APIDOC ## Usage Examples ### Description Examples illustrating the use of ANSI styling functions for coloring text, combining different styles, and creating styled output. ### Examples ```r cat(col_blue("Hello ", "world!")) #> Hello world! cat("... to highlight the", col_red("search term"), "in a block of text\n") #> ... to highlight the search term in a block of text ## Style stack properly cat(col_green( "I am a green line ", col_blue(style_underline(style_bold("with a blue substring"))), " that becomes green again!" )) #> I am a green line with a blue substring that becomes green again! error <- combine_ansi_styles("red", "bold") warn <- combine_ansi_styles("magenta", "underline") note <- col_cyan cat(error("Error: subscript out of bounds!\n")) #> Error: subscript out of bounds! cat(warn("Warning: shorter argument was recycled.\n")) #> Warning: shorter argument was recycled. cat(note("Note: no such directory.\n")) #> Note: no such directory. ``` ``` -------------------------------- ### boxx Examples Source: https://cli.r-lib.org/reference/boxx Demonstrates various use cases of the `boxx` function, including default usage, changing border styles, handling multiple lines, adjusting padding, floating the box, and coloring text. ```APIDOC ### Details #### Defaults ```r boxx("Hello there!") ``` #### Change border style ```r boxx("Hello there!", border_style = "double") ``` #### Multiple lines ```r boxx(c("Hello", "there!"), padding = 1) ``` #### Padding ```r boxx("Hello there!", padding = 1) boxx("Hello there!", padding = c(1, 5, 1, 5)) ``` #### Floating ```r boxx("Hello there!", padding = 1, float = "center") boxx("Hello there!", padding = 1, float = "right") ``` #### Text color ```r boxx(col_cyan("Hello there!"), padding = 1, float = "center") ``` ``` -------------------------------- ### Info Alert Example Source: https://cli.r-lib.org/reference/cli_alert Displays an informational message, highlighting a file path using inline markup. ```r cfl <- "~/.cache/files/latest.cache" cli_alert_info("Updating cache file {.path {cfl}}.") #> ℹ Updating cache file ~/.cache/files/latest.cache. ``` -------------------------------- ### Basic Collapse Example Source: https://cli.r-lib.org/reference/ansi_collapse Demonstrates the default behavior of collapsing the `letters` vector into a string with standard separators. ```r ansi_collapse(letters) #> [1] "a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, and z" ``` -------------------------------- ### Background Color Examples Source: https://cli.r-lib.org/articles/semantic-cli Shows how to apply background colors to text using bg_* functions (e.g., bg_black, bg_blue). The results are displayed as an unordered list. ```r cli_ul(c( bg_black("black background"), bg_blue("blue background"), bg_cyan("cyan background"), bg_green("green background"), bg_magenta("magenta background"), bg_red("red background"), bg_white("white background"), bg_yellow("yellow background") )) ``` -------------------------------- ### Demonstrate Specific Spinner Source: https://cli.r-lib.org/reference/demo_spinners To demo a specific spinner, provide its name as a character vector to the 'which' argument. For example, to show only the 'clock' spinner. ```r demo_spinners("clock") ``` -------------------------------- ### Text Style Examples Source: https://cli.r-lib.org/articles/semantic-cli Demonstrates various text styling options like dim, bold, italic, and underline using style_* functions. The output is formatted as an unordered list. ```r cli_ul(c( style_dim("dim style"), style_blurred("blurred style"), style_bold("bold style"), style_hidden("hidden style"), style_inverse("inverse style"), style_italic("italic style"), style_reset("reset style"), style_strikethrough("strikethrough style"), style_underline("underline style") )) ``` -------------------------------- ### Run custom spinner with template Source: https://cli.r-lib.org/reference/make_spinner Demonstrates using a custom-named spinner with a custom template to show progress. This example highlights the flexibility in spinner selection and presentation. ```r 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()) ``` -------------------------------- ### List Active CLI Themes Source: https://cli.r-lib.org/reference/cli_list_themes Call this function to get a list of all currently active themes. If no app is active, it will first call `start_app()`. ```r cli_list_themes() ``` -------------------------------- ### Enable cli formatting globally with local_use_cli() Source: https://rlang.r-lib.org/reference/topic-condition-formatting.html Provides an example of how to enable cli formatting for all abort() calls within a package by calling local_use_cli() in the onLoad hook. This facilitates a progressive transition to cli::cli_abort(). ```R on_load(local_use_cli()) ``` -------------------------------- ### Example of cli_abort with formatted message parts Source: https://cli.r-lib.org/reference/cli_abort Demonstrates how to use cli_abort with a message that includes different parts, such as a main message and a specific error detail. It uses glue substitutions and conditional pluralization for dynamic output. ```r n <- "boo" cli_abort(c( "{.var n} must be a numeric vector", "x" = "You've supplied a {.cls {class(n)}} vector." )) ``` -------------------------------- ### Create a custom alert type Source: https://cli.r-lib.org/reference/themes Defines custom markers for the start and end of alert elements using the 'before' property. This example shows how to prepend a play symbol to the start of an alert and a stop symbol to its end, customizing the visual cues for alerts. ```R list( ".alert-start" = list(before = symbol$play), ".alert-stop" = list(before = symbol$stop) ) ``` -------------------------------- ### Display raw elapsed seconds with pb_elapsed_raw Source: https://cli.r-lib.org/reference/progress-variables Use `pb_elapsed_raw` to get the number of seconds since the start of the progress bar. This is useful for precise time calculations or custom formatting. ```r cli_progress_bar( total = 100, format = "{cli::pb_bar} {cli::pb_percent} [{round(cli::pb_elapsed_raw)}s]" ) ``` -------------------------------- ### Creating a definition list with items added one by one Source: https://cli.r-lib.org/reference/cli_dl This approach is useful for building a definition list incrementally. It demonstrates how to use cli_dl() to start the list and cli_li() to add individual items, including inline markup for formatting. ```r 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: three ``` -------------------------------- ### Adding items one by one with cli_ol and cli_li Source: https://cli.r-lib.org/reference/cli_ol Shows how to create an ordered list by first initializing an empty list with `cli_ol()` and then adding individual items using `cli_li()` and closing with `cli_end()`. ```r fun <- function() { cli_ol() cli_li("{.emph one}") cli_li("{.emph two}") cli_li("{.emph three}") cli_end() } fun() ``` -------------------------------- ### Get Console Width Source: https://cli.r-lib.org/reference/console_width Call `console_width()` to get the current console width. This function attempts to detect the terminal size automatically. ```r console_width() ``` ```r console_width() #> [1] 71 ``` -------------------------------- ### start_app(), stop_app(), default_app() Source: https://cli.r-lib.org/reference/index.html Functions to manage the default cli application. ```APIDOC ## start_app(), stop_app(), default_app() ### Description Start, stop, query the default cli application. ### Function Signatures start_app() stop_app() default_app() ``` -------------------------------- ### Example: Basic Progress Bar Usage Source: https://cli.r-lib.org/reference/progress-c Demonstrates the creation and updating of a progress bar within a loop. It uses `cli_progress_bar` to create the bar, `cli_progress_sleep` for simulated work, `CLI_SHOULD_TICK` to conditionally update, `cli_progress_set` to advance the bar, and `cli_progress_done` to finish. ```c #include 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); } ``` -------------------------------- ### Get CLI Situation Report Source: https://cli.r-lib.org/reference/cli_sitrep Call cli_sitrep() to get a named list containing information about the cli package's operating environment. This includes details on Unicode options, symbol character set, console UTF-8 support, LaTeX activity, number of ANSI colors, and console width. ```APIDOC ## cli_sitrep() ### Description Provides a situation report on the current state of the cli package, including Unicode settings, character sets, console capabilities, and color support. ### Usage ```r cli_sitrep() ``` ### Value Returns a named list with entries detailing the cli environment. The list has a `cli_sitrep` class, with associated `print()` and `format()` methods for display. ### Details - `cli_unicode_option`: Status of the `cli.unicode` option. - `symbol_charset`: Selected character set for symbols (UTF-8, Windows, or ASCII). - `console_utf8`: Indicates if the console supports UTF-8. - `latex_active`: Boolean indicating if inside knitr and creating a LaTeX document. - `num_colors`: Number of ANSI colors supported. - `console_width`: Detected console width. ### Examples ```r cli_sitrep() #> - cli_unicode_option : NULL #> - symbol_charset : UTF-8 #> - console_utf8 : TRUE #> - latex_active : FALSE #> - num_colors : 256 #> - console_width : 71 ``` ``` -------------------------------- ### cli_progress_demo Source: https://cli.r-lib.org/llms.txt Runs a demonstration of CLI progress bar functionality. ```APIDOC ## cli_progress_demo ### Description Executes a demonstration showcasing the features and usage of CLI progress bars. ### Usage cli_progress_demo() ``` -------------------------------- ### Create Definition List Source: https://cli.r-lib.org/articles/semantic-cli Use cli_dl() to create a definition list with terms and their descriptions. ```r cli_dl(c("item 1" = "description 1", "item 2" = "description 2", "item 3" = "description 3")) ``` -------------------------------- ### Displaying Error Messages with ui_oops Source: https://cli.r-lib.org/articles/usethis-ui Example of using usethis::ui_oops() to display an error message. ```r ui_oops("Can't validate token. Is the network reachable?") ``` -------------------------------- ### Warning Alert Example Source: https://cli.r-lib.org/reference/cli_alert Displays a warning message, indicating a potential issue with a file path. ```r cfl <- "~/.cache/files/latest.cache" cli_alert_warning("Failed to update cache file {.path {cfl}}.") #> ! Failed to update cache file ~/.cache/files/latest.cache. ``` -------------------------------- ### Basic Inline Markup Examples - cli package Source: https://cli.r-lib.org/reference/inline-markup Demonstrates the usage of various built-in inline markup classes for formatting text. These include emphasis, strong importance, code snippets, package names, function names, keyboard keys, file paths, email addresses, URLs, environment variables, and object types. Output is rendered with semantic styling and potential hyperlinks in compatible terminals. ```R 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) ``` -------------------------------- ### cli_process_start(), cli_process_done(), cli_process_failed() (Superseded) Source: https://cli.r-lib.org/reference/index.html Indicate the start and termination of some computation in the status bar (superseded). ```APIDOC ## cli_process_start(), cli_process_done(), cli_process_failed() (Superseded) ### Description Indicate the start and termination of some computation in the status bar (superseded). ### Function Signatures cli_process_start() cli_process_done() cli_process_failed() ``` -------------------------------- ### Adding all items at once with cli_ol Source: https://cli.r-lib.org/reference/cli_ol Demonstrates how to create an ordered list by providing all items as a character vector to the `items` argument. ```r fun <- function() { cli_ol(c("one", "two", "three")) } fun() ``` -------------------------------- ### Danger Alert Example Source: https://cli.r-lib.org/reference/cli_alert Displays a danger message, signaling a critical error related to a configuration file. ```r cfl <- "~/.config/report.yaml" cli_alert_danger("Cannot validate config file at {.path {cfl}}.") #> ✖ Cannot validate config file at ~/.config/report.yaml. ``` -------------------------------- ### Rendering CLI Headings Source: https://cli.r-lib.org/reference/cli_h1 Demonstrates how cli_h1, cli_h2, and cli_h3 render with the default builtin theme, including inline markup for emphasis. ```r cli_h1("Header {.emph 1}") cli_h2("Header {.emph 2}") cli_h3("Header {.emph 3}") ``` -------------------------------- ### Success Alert Example Source: https://cli.r-lib.org/reference/cli_alert Displays a success message with formatted text, including dynamic values and pluralization. ```r nbld <- 11 tbld <- prettyunits::pretty_sec(5.6) cli_alert_success("Built {.emph {nbld}} status report{?s} in {tbld}.") #> ✔ Built 11 status reports in 5.6s. ``` -------------------------------- ### Creating a definition list with all items at once Source: https://cli.r-lib.org/reference/cli_dl Use this method to create a definition list when all items and their labels are known beforehand. The output displays the labels and their corresponding values. ```r fun <- function() { cli_dl(c(foo = "one", bar = "two", baz = "three")) } fun() #> foo: one #> bar: two #> baz: three ``` -------------------------------- ### Demonstrate CLI progress bar styles Source: https://cli.r-lib.org/reference/cli_progress_styles Iterate through all available progress bar styles, set each as the active style using `options()`, and display a demo progress bar. This helps visualize how each style renders. ```r 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) ``` -------------------------------- ### List available CLI progress styles Source: https://cli.r-lib.org/reference/cli_progress_styles Call `cli_progress_styles()` to get a list of all available progress bar styles. ```r cli_progress_styles() ``` -------------------------------- ### Multiple quantities with pluralize() Source: https://cli.r-lib.org/reference/pluralize Example of using pluralize() to format strings with multiple quantities, like files and directories. ```r nfiles <- 3; ndirs <- 1 pluralize("Found {nfiles} file{?s} and {ndirs} director{?y/ies}") #> Found 3 files and 1 directory ``` -------------------------------- ### Formatting Paths with ui_path and cli_alert_success Source: https://cli.r-lib.org/articles/usethis-ui Shows how usethis::ui_path() formats paths and the equivalent using cli_alert_success() with {.file} markup for inline styling. ```r logo_path <- file.path("man", "figures", "logo.svg") img <- "/tmp/some-image.svg" ui_done("Copied {ui_path(img)} to {ui_path(logo_path)}") ``` ```r cli_alert_success("Copied {.file {img}} to {.file {logo_path}}") ``` -------------------------------- ### Custom truncation Source: https://cli.r-lib.org/reference/cli_vec Control the truncation of a vector when it is collapsed into a string. This example limits the displayed items and uses an ellipsis. ```r x <- cli_vec(names(mtcars), list("vec-trunc" = 3)) cli_text("Column names: {x}.") ``` -------------------------------- ### Basic usage of cli_progress_step() Source: https://cli.r-lib.org/reference/cli_progress_step Demonstrates sequential use of cli_progress_step() to indicate distinct stages of a process, with pauses between each step. ```r 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() ``` -------------------------------- ### Displaying Plain Text Lines with ui_line Source: https://cli.r-lib.org/articles/usethis-ui Example of using usethis::ui_line() to display a plain text message. ```r ui_line("No matching issues/PRs found.") ``` -------------------------------- ### Progress Bar with Initial Delay and Custom Format Source: https://cli.r-lib.org/reference/cli_progress_bar Illustrates how to set an initial delay before a progress bar appears using global options and how to customize the progress bar's format string. This example shows the bar appearing after a delay. ```R 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() ``` -------------------------------- ### List Built-in Code Themes Source: https://cli.r-lib.org/reference/code_theme_list Use `code_theme_list()` to get a character vector of all available built-in code theme names. ```r code_theme_list() ``` -------------------------------- ### Add items to an unordered list one by one Source: https://cli.r-lib.org/reference/cli_ul Demonstrates creating an unordered list and adding items sequentially using cli_li() and closing with cli_end(). ```r fun <- function() { cli_ul() cli_li("{.emph one}") cli_li("{.emph two}") cli_li("{.emph three}") cli_end() } fun() #> • one #> • two #> • three ``` -------------------------------- ### Get the number of active progress bars in C Source: https://cli.r-lib.org/articles/progress-advanced Retrieve the count of currently active progress bars using `cli_progress_num`. ```c int cli_progress_num(); ``` -------------------------------- ### Setting Multiple Fields with ui_done and cli_alert_success Source: https://cli.r-lib.org/articles/usethis-ui Demonstrates setting multiple fields using usethis::ui_done() and the equivalent cli_alert_success() with inline {.field} markup. cli collapses inline vectors before styling. ```r name <- c("Depends", "Imports", "Suggests") ui_done("Setting the {ui_field(name)} field(s) in DESCRIPTION") ``` ```r cli_alert_success("Setting the {.field {name}} field{?s} in DESCRIPTION") ``` -------------------------------- ### cli_progress_demo Source: https://cli.r-lib.org/reference/cli_progress_demo Creates a progress bar demo, iterating it until termination and saving the updates. Useful for experimenting with format strings and for documentation. ```APIDOC ## cli_progress_demo() ### Description Creates a progress bar demo, iterating it until termination and saving the updates. Useful for experimenting with format strings and for documentation. ### Arguments - `name` (any): Passed to `cli_progress_bar()`. - `status` (any): Passed to `cli_progress_bar()`. - `type` (character vector): Passed to `cli_progress_bar()`. Defaults to c("iterator", "tasks", "download", "custom"). - `total` (numeric): Passed to `cli_progress_bar()`. - `.envir` (environment): Passed to `cli_progress_bar()`. - `...` (any): Passed to `cli_progress_bar()`. - `at` (numeric): The number of progress units to show and capture the progress bar at. If `NULL`, then a sequence of states is generated to show the progress from beginning to end. - `show_after` (numeric): Delay to show the progress bar. Overrides the `cli.progress_show_after` option. - `live` (logical): Whether to show the progress bar on the screen, or just return the recorded updates. Defaults to the value of the `cli.progress_demo_live` options. If unset, then it is `TRUE` in interactive sessions. - `delay` (numeric): Delay between progress bar updates. - `start` (difftime): Time to subtract from the start time, to simulate a progress bar that takes longer to run. Defaults to as.difftime(5, units = "secs"). ### Value List with class `cli_progress_demo`, which has a print and a format method for pretty printing. The `lines` entry contains the output lines, each corresponding to one update. ``` -------------------------------- ### List Available Spinners Source: https://cli.r-lib.org/articles/semantic-cli Use `list_spinners()` to get a character vector of all available spinner names. This is useful for discovering which animations can be used. ```r list_spinners() ``` -------------------------------- ### Basic Tree Visualization with Trimming Source: https://cli.r-lib.org/reference/tree Demonstrates how to create a package dependency data frame and visualize it using the tree() function with the trim = TRUE option to simplify the output. ```R 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) ``` -------------------------------- ### usethis::ui_todo() Source: https://cli.r-lib.org/articles/usethis-ui Displays a to-do item to the user. It supports glue substitution and can be used with cli for similar formatting. ```APIDOC ## usethis::ui_todo() ### Description Displays a to-do item to the user, often used to indicate a task that needs to be done. ### Usage ```r usethis::ui_todo(x, .envir = parent.frame()) ``` ### Example ```r ui_todo("Redocument with {ui_code('devtools::document()')}") ``` ### With cli ```r cli_ul("Redocument with {.fun devtools::document}") ``` ``` -------------------------------- ### Stopping Execution with Errors using ui_stop Source: https://cli.r-lib.org/articles/usethis-ui Example of usethis::ui_stop() which performs glue substitution and then calls stop() to throw an error. ```r ui_stop("Could not copy {ui_path(img)} to {ui_path(logo_path)}, file already exists") ``` -------------------------------- ### Inspect cli app state with examples Source: https://cli.r-lib.org/reference/cli_debug_doc Demonstrates how to use cli_debug_doc() to inspect the cli app state at different points, including after opening and closing list elements. The output can be converted to a plain data frame by indexing with empty brackets. ```r if (FALSE) { # \dontrun{ cli_debug_doc() olid <- cli_ol() cli_li() cli_debug_doc() cli_debug_doc()[] cli_end(olid) cli_debug_doc() } # } ``` -------------------------------- ### Tree drawing from a specific root Source: https://cli.r-lib.org/reference/tree Shows how to draw a tree starting from a specified root node. This is useful for visualizing sub-trees or specific branches. ```r tree(data, root = "rcmdcheck") ``` -------------------------------- ### Load cli and usethis libraries Source: https://cli.r-lib.org/articles/usethis-ui Load the necessary libraries for using usethis and cli functions. ```r library(cli) library(usethis) ``` -------------------------------- ### demo_spinners Source: https://cli.r-lib.org/reference/demo_spinners Demonstrates the available spinner animations. By default, it shows all spinners. You can specify which spinners to demo using the `which` argument. ```APIDOC ## demo_spinners ### Description Shows a demo of some (by default all) spinners. Each spinner is shown for about 2-3 seconds. ### Usage ```r demo_spinners(which = NULL) ``` ### Arguments #### Parameters - **which** (Character vector) - Optional - Specifies which spinners to demo. If NULL, all spinners are shown. ### Details An example of how to demo a specific spinner: ```r demo_spinners("clock") ``` ![Spinner Demo](figures/demo-spinners.svg) ``` -------------------------------- ### Left label rule Source: https://cli.r-lib.org/reference/rule Creates a rule with a text label positioned on the left side. This is useful for indicating the start of a specific output section. ```r rule(left = "Results") #> ── Results ─────────────────────────────────────────────────────────── ``` -------------------------------- ### Create and end a paragraph Source: https://cli.r-lib.org/articles/semantic-cli Use `cli_par()` to start a new paragraph and `cli_end()` to close it. Paragraphs add spacing and handle text wrapping. ```r fun <- function() { cli_par() cli_text("This is some text.") cli_text("Some more text.") cli_end() cli_par() cli_text("Already a new paragraph.") cli_end() } fun() ``` -------------------------------- ### Demonstrate All Spinners Source: https://cli.r-lib.org/reference/demo_spinners Call demo_spinners() without arguments to show all available spinner animations. Each spinner is displayed for approximately 2-3 seconds. ```r demo_spinners(which = NULL) ``` -------------------------------- ### Basic Left Alignment Source: https://cli.r-lib.org/reference/ansi_align Demonstrates left alignment of ANSI colored strings within a specified width. Ensure the cli package is installed and loaded. ```r str <- c( col_red("This is red"), style_bold("This is bold") ) astr <- ansi_align(str, width = 30) boxx(astr) ``` -------------------------------- ### Custom collapsing separator Source: https://cli.r-lib.org/reference/cli_vec Apply custom separators to a vector when it's collapsed into a string. This example demonstrates changing the general, two-item, and last separators. ```r v <- cli_vec( c("foo", "bar", "foobar"), style = list("vec-sep" = " & ", "vec-last" = " & ") ) cli_text("My list: {v}.") ``` -------------------------------- ### C API for Progress Bar Creation and Updates Source: https://cli.r-lib.org/articles/progress-advanced Shows how to use the C API to create, update, and terminate a progress bar. Requires including 'cli/progress.h' and linking/importing the 'cli' package. ```cpp #include 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); } ``` -------------------------------- ### Boxx with different float options Source: https://cli.r-lib.org/reference/boxx Shows how to control the horizontal positioning of the box using the 'float' argument. Examples include 'center' and 'right' alignment. ```r boxx("Hello there!", padding = 1, float = "center") ``` ```r boxx("Hello there!", padding = 1, float = "right") ``` -------------------------------- ### Change border style to double Source: https://cli.r-lib.org/reference/boxx Shows how to change the border style of the box using the 'border_style' argument. This example uses the 'double' border style. ```r boxx("Hello there!", border_style = "double") ``` -------------------------------- ### Utilities and Configuration Source: https://cli.r-lib.org/reference/index.html Helper functions for printing output and managing cli package configuration. ```APIDOC ## Utilities and Configuration ### Description Helper functions for printing output and managing cli package configuration. ### Functions - `cat_line()`: Print a line of text. - `cat_bullet()`: Print a bulleted line of text. - `cat_boxx()`: Print text within a box. - `cat_rule()`: Print a rule. - `cat_print()`: Print text using cli formatting. - `cli-config`: Access cli environment variables and options. - `cli_debug_doc()`: Debug cli internals. - `cli_fmt()`: Capture the output of cli functions instead of printing it. - `cli_format_method()`: Create a format method for an object using cli tools. - `cli_output_connection()`: Specify the connection option for cli output. ``` -------------------------------- ### utf8_substr Source: https://cli.r-lib.org/reference/utf8_substr Extracts substrings from a character vector using grapheme clusters as units. The start and stop arguments define the range of grapheme clusters to extract. ```APIDOC ## utf8_substr ### Description This function uses grapheme clusters instead of Unicode code points in UTF-8 strings. ### Usage ```r utf8_substr(x, start, stop) ``` ### Arguments - x: Character vector. - start: Starting index or indices, recycled to match the length of `x`. - stop: Ending index or indices, recycled to match the length of `x`. ### Value Character vector of the same length as `x`, containing the requested substrings. ### Examples ```r # Five grapheme clusters, select the middle three str <- 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) #> 👷🏿👷‍♀️👷🏻 ``` ``` -------------------------------- ### Get Number of ANSI Colors Source: https://cli.r-lib.org/reference/num_ansi_colors Call `num_ansi_colors()` to determine the number of ANSI colors supported by your terminal. This function automatically detects the environment and returns an integer. ```r num_ansi_colors() #> [1] 256 ``` -------------------------------- ### Create a default spinner Source: https://cli.r-lib.org/reference/make_spinner Initializes a spinner with default settings. This is useful for basic progress indication. ```r sp1 <- make_spinner( which = NULL, stream = "auto", template = "{spin}", static = c("dots", "print", "print_line", "silent") ) ``` -------------------------------- ### Get default spinner configuration Source: https://cli.r-lib.org/reference/get_spinner Retrieves the default spinner configuration when no specific spinner is requested. The default can be customized via R options like cli.spinner. ```r get_spinner(which = NULL) ``` -------------------------------- ### Create Unordered List Source: https://cli.r-lib.org/articles/semantic-cli Use cli_ul() to create an unordered list with specified items. ```r cli_ul(c("item 1", "item 2", "item 3")) ``` -------------------------------- ### Showcase Simple Theme Elements Source: https://cli.r-lib.org/reference/simple_theme Demonstrates various formatting elements available with the simple theme, including headings, alerts, text styling, code, file paths, URLs, and verbatim code blocks. The output is captured within a cli_div context. ```r 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) ```