cli

repository·main·Indexed 20 days ago

https://github.com/r-lib/cli

A suite of tools for building attractive, semantic command line interfaces in R. It provides high-level elements such as headings (cli_h1, cli_h2, cli_h3), lists (cli_ul, cli_ol, cli_dl), alerts, and progress bars. The package supports theming via a CSS-like language, string interpolation using glue syntax, automatic pluralization, and the ability to compose multiple messages into atomic blocks using the cli() function.

Tokens
3.3K
Snippets
22
Records
22
Agent score
72%

What's inside cli

  1. Use command substitution with glue syntax

    main

    All cli text supports interpreted string literals via the glue package. You can embed R expressions directly into your messages using curly braces {}.

    size <- 123143123
    dt <- 1.3454
    cli_alert_info(c(
      "Downloaded {prettyunits::pretty_bytes(size)} in ",
      "{prettyunits::pretty_sec(dt)}"))
  2. Install the cli package

    main

    You can install the stable version of cli from CRAN or the development version from GitHub using pak.

    # Install stable version from CRAN
    install.packages("cli")
    
    # Install development version from GitHub
    pak::pak("r-lib/cli")
  3. Apply themes using a CSS-like language

    main

    You can style CLI elements by wrapping them in a cli_div() and providing a theme list. This allows you to override specific semantic styles, such as span.emph, within that scope.

    fun <- function() {
      cli_div(theme = list(span.emph = list(color = "orange")))
      cli_text("This is very {.emph important}")
      cli_end()
      cli_text("Back to the {.emph previous theme}")
    }
    fun()
  4. Implement pluralization in messages

    main

    Use the {?s} or {?y/ies} syntax within string literals to handle pluralization automatically based on the value of a variable.

    nfiles <- 3
    ndirs <- 1
    cli_alert_info("Found {nfiles} file{?s} and {ndirs} director{?y/ies}.")
  5. Use alert messages to inform or warn users

    main

    Use specialized alert functions to provide semantic, color-coded feedback in the terminal. These functions support string interpolation via glue syntax (e.g., {variable}).

    # Success alert
    cli_alert_success("Downloaded {length(pkgs)} packages.")
    
    # Info alert with URL interpolation
    db_url <- "example.com:port"
    cli_alert_info("Reopened database {.url {db_url}}.")
    
    # Warning alert
    cli_alert_warning("Cannot reach GitHub, using local database cache.")
    
    # Danger alert
    cli_alert_danger("Failed to connect to database.")
    
    # Generic alert
    cli_alert("A generic alert")
  6. Create ordered, unordered, and description lists

    main

    Lists can be nested. Use cli_ol() for ordered lists, cli_ul() for unordered lists, and cli_li() for list items. Always close a list scope using cli_end().

    fun <- function() {
      cli_ol()
      cli_li("Item 1")
      ulid <- cli_ul()
      cli_li("Subitem 1")
      cli_li("Subitem 2")
      cli_end(ulid)
      cli_li("Item 2")
      cli_end()
    }
    fun()
  7. Display progress bars

    main

    Use cli_progress_bar() to initialize a progress bar and cli_progress_update() to advance it during loops or long-running processes.

    clean <- function() {
      cli_progress_bar("Cleaning data", total = 100)
      for (i in 1:100) {
        Sys.sleep(5/100)
        cli_progress_update()
      }
    }
    clean()
  8. Capture cli output with cli_fmt()

    main

    If you need to capture the formatted output of cli_* functions as a character string instead of printing them to the console, use cli_fmt().

    • collapse: If TRUE, the output is collapsed into a single character scalar. If FALSE, it returns a character vector where each element represents a line.
    • strip_newline: If TRUE, the trailing newline is removed.
    cli_fmt({
      cli_alert_info("Loading data file")
      cli_alert_success("Loaded data file")
    })
  9. Manage CLI containers with cli_div() and cli_end()

    main

    Containers allow you to group elements and apply specific themes or classes to a block of output.

    • cli_div(id = NULL, class = NULL, theme = NULL, .auto_close = TRUE, .envir = parent.frame()): Creates a generic container. If a theme is provided, it applies to all elements within this container.
    • cli_end(id = NULL): Explicitly closes a container. If id is omitted, it closes the most recently opened container.

    Auto-closing: By default, cli_div() containers close automatically when the calling function exits. To prevent this, set .auto_close = FALSE or provide a specific .envir.

    # Custom theme in a div
    d <- cli_div(theme = list(h1 = list(color = "cyan", "font-weight" = "bold")))
    cli_h1("Custom title")
    cli_end(d)
    
    # Explicit closing
    cnt <- cli_div()
    cli_text("Inside container")
    cli_end(cnt)
  10. Display code blocks with cli_code()

    main

    The cli_code() function creates a specialized container (class code) that wraps cli_verbatim() calls. The built-in theme provides syntax highlighting for valid R code within these containers.

    • lines: A character vector where each element is a line of code.
    • language: The programming language (defaults to "R"). This is added as a class to the container.
    • .auto_close: Whether the container closes automatically after the code is emitted.
    myfun <- function() {
      message("Just an example function")
      graphics::pairs(iris, col = 1:5)
    }
    cli_code(format(myfun))
  11. Display alerts with cli_alert_*()

    main

    Alerts are short status messages used to convey different levels of importance. They are printed without wrapping unless wrap = TRUE is specified.

    Available alert types:

    • cli_alert_success(text, ...): For successful operations.
    • cli_alert_info(text, ...): For informational messages.
    • cli_alert_warning(text, ...): For warnings.
    • cli_alert_danger(text, ...): For critical errors or dangers.
    • cli_alert(text, ...): Generic alert.

    All functions support id, class, and wrap arguments.

    cli_alert_success("Built {.emph report} in 5 seconds.")
    cli_alert_info("Updating cache file.")
    cli_alert_warning("Failed to update cache.")
    cli_alert_danger("Cannot validate config file.")