GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — GitHub - mlindsk/cli: Tools for making beautiful & useful command line interfaces

BranchesTags
Open more actions menu
 
 

Latest commit

 

History

223 Commits
223 Commits

Folders and files

NameName
Last commit message
Last commit date
R
R
 
 
inst
inst
 
 
man
man
 
 
tests
tests
 
 
tools
tools
 
 
.Rbuildignore
.Rbuildignore
 
 
.Rprofile
.Rprofile
 
 
.gitignore
.gitignore
 
 
.travis.yml
.travis.yml
 
 
DESCRIPTION
DESCRIPTION
 
 
LICENSE
LICENSE
 
 
Makefile
Makefile
 
 
NAMESPACE
NAMESPACE
 
 
NEWS.md
NEWS.md
 
 
README.Rmd
README.Rmd
 
 
README.md
README.md
 
 
appveyor.yml
appveyor.yml
 
 
cli.Rproj
cli.Rproj
 
 
header.md
header.md
 
 

Repository files navigation

cli

Helpers for Developing Command Line Interfaces

Linux Build Status Windows Build status CRAN RStudio mirror downloads Coverage Status

A suite of tools to build attractive command line interfaces (CLIs), from semantic elements: headers, lists, alerts, paragraphs, etc. Supports theming 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 integrates with the crayon package to support ANSI terminal colors.


  • Features
  • Installation
  • Building a command line interface
    • Alerts
    • Text
    • Paragraphs
    • Auto-closing containers
    • Headers
    • Interpolation
    • Inline text formatting
    • Lists
  • Theming
    • Tags, ids and classes
    • Generic containers
    • Theming inline markup
  • CLI messages
  • Subprocesses
  • Utility functions
    • ANSI colors
    • Console capabilities
  • Non-semantic CLI
    • Unicode characters
    • Rules
    • Boxes
    • Trees
    • Spinners
  • License

Features

  • Build a CLI using semantic elements: headers, lists, alerts, paragraphs.
  • Theming via a CSS-like language.
  • Terminal colors via the crayon package.
  • Create CLI elements in subprocesses, using the callr package.
  • All CLI text can contain interpreted string literals, via the glue package.

Installation

Install the stable version from CRAN:

install.packages("cli")

Building a command line interface

library(cli)

To start building a CLI, so can simply start using the cli_* functions to create various CLI elements. Their exact formatting depends on the current theme, see ‘Theming’ below.

Alerts

Alerts are typically short messages. cli has four types of alerts (success, info, warning, danger) and also a generic alert type:

cli_alert_success("Updated database.")

cli_alert_info("Reopened database.")

cli_alert_warning("Cannot reach GitHub, using local database cache.")

cli_alert_danger("Failed to connect to database.")

cli_alert("A generic alert")

Text

Text is automatically wrapped to the terminal width.

cli_text(cli:::lorem_ipsum())

Paragraphs

Paragraphs break the output. The default theme inserts an empty line before and after paragraphs, but only a single empty line is added between two paragraphs.

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()

cli_end() closes the latest open paragraph (or other open container).

Auto-closing containers

If a paragraph (or other container, see ‘Generic containers’ later), is opened within a function, cli automatically closes it at the end of the function, by default. So in the previous example the last cli_end() call is not needed. Use .auto_close = TRUE in cli_par() to leave the paragraph open after its calling function returns.

Headers

cli suppports three levels of headers. This is how they look in the default theme. The default theme adds an empty line before headers, and an empty line after cli_h1() and cli_h2().

cli_h1("Header 1")

cli_h2("Header 2")

cli_h3("Header 3")

Interpolation

All cli text is treated as a glue template, with special formatters available (see the ‘Inline text formatting’ Section):

size <- 123143123
dt <- 1.3454
cli_alert_info(c(
  "Downloaded {prettyunits::pretty_bytes(size)} in ",
  "{prettyunits::pretty_sec(dt)}"))

Inline text formatting

To define inline markup, you can use the regular glue braces, and immeadiately after the opening brace, supply the name of the markup formatter, e.g. for emphasised text, the formatter is called emph. Some examples are below, see ?"inline-markup" for details.

fun <- function() {
  cli_ul()
  cli_it("{emph Emphasized} text")
  cli_it("{strong Strong} importance")
  cli_it("A piece of code: {code sum(a) / length(a)}")
  cli_it("A package name: {pkg cli}")
  cli_it("A function name: {fun cli_text}")
  cli_it("A function argument: {arg text}")
  cli_it("A keyboard key: press {key ENTER}")
  cli_it("A file name: {file /usr/bin/env}")
  cli_it("An email address: {email [email protected]}")
  cli_it("A URL: {url https://acme.com}")
  cli_it("A variable name: {var mtcars}")
  cli_it("An environment variable: {envvar R_LIBS}")
}
fun()

To combine inline markup and string interpolation, you need to add another set of braces:

dlurl <- "https://httpbin.org/status/404"
cli_alert_danger("Failed to download {url {dlurl}}.")

Lists

cli has three types of list: ordered, unordered and definition lists, see cli_ol(), cli_ul() amd cli_dl():

cli_ol(c("item 1", "item 2", "item 3"))

cli_ul(c("item 1", "item 2", "item 3"))

cli_dl(c("item 1" = "description 1", "item 2" = "description 2",
         "item 3" = "description 3"))

Item text is wrapped to the terminal width:

cli_ul(c("item 1" = cli:::lorem_paragraph(1, 20),
         "item 2" = cli:::lorem_paragraph(1, 20)))

Adding list items iteratively

Items can be added one by one:

fun <- function() {
  lid <- cli_ul()
  cli_it("Item 1")
  cli_it("Item 2")
  cli_it("Item 3")
  cli_end(lid)
}
fun()

The cli_ul() call creates a list container, and because its items are not specified, it leaves the container open. Then items can be added one by one. (The last cli_end() is not necessary, because by default containers auto-close when their calling function exits.)

Adding text to an item iteratively

cli_it() creates a new container for the list item, within the list container. You can keep adding text to the item, until the container is closed via cli_end() or a new cli_it(), which closes the current item container, and creates another one for the new item:

fun <- function() {
  cli_ul()
  cli_it("First item")
  cli_text("This is still the first item")
  cli_it("This is the second item")
}
fun()

Nested lists

To create nested lists, open nested containers:

fun <- function() {
  cli_ol()
  cli_it("Item 1")
  ulid <- cli_ul()
  cli_it("Subitem 1")
  cli_it("Subitem 2")
  cli_end(ulid)
  cli_it("Item 2")
  cli_end()
}
fun()

In cli_end(olid), the olid is necessary, otherwise cli_end() would only close the container of the list item.

Theming

The looks of the various CLI elements can be changed via themes. The cli package comes with a simple built-in theme, and new themes can be added as well.

Tags, ids and classes

Similarly to HTML document, the elements of a CLI form a tree of nodes. Each node has exactly one tag, at most one id, and optionally a set of classes. E.g. cli_par() creates a node with a <p> tag, cli_ol() creates a node with an <ol> tag, etc. Here is an example CLI tree. It always starts with a <body> tag with id "body", this is created automatically.

<body id="body">
  <par>
    <ol>
      <it>
        <span class="pkg">

A cli theme is a named list, where the names are selectors based on tag names, ids and classes, and the elements of the list are style declarations. For example, the style of <h1> tags looks like this in the built-in theme:

builtin_theme()$h1

See also ?cli::themes for the reference and ?cli::simple_theme for an example theme.

Generic containers

cli_div() is a generic container, that does not produce any output, but it can add a new theme. This theme is removed when the <div> node is closed. (Like other containers, cli_div() auto-closes when the calling function exits.)

fun <- function() {
  cli_div(theme = list (.alert = list(color = "red")))
  cli_alert("This will be red")
  cli_end()
  cli_alert("Back to normal color")
}
fun()

Theming inline markup

The inline markup formatters always use a <span> tag, and add the name of the formatter as a class.

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()

CLI messages

All cli_*() functions are implemented using standard R conditions. For example a cli_alert() call emits an R condition with class cli_message. These messages can be caught, muffled, transfered from a subprocess to the main R process.

When a cli function is called:

  1. cli throws a cli_message condition.
  2. If this condition is caught and muffled (via the muffleMessage restart), then nothing else happens.
  3. Otherwise the cli.default_handler option is checked and if this is a function, then it is called with the message.
  4. If the cli.default_handler option is not set, or it is not a function, the default cli handler is called, which shows the text, alert, header, etc. on the screen, using the standard R message() function.
tryCatch(cli_h1("Header"), cli_message = function(x) x)
suppressMessages(cli_text("Not shown"))

Subprocesses

If cli_*() commands are invoked in a subprocess via callr::r_session (see https://callr.r-lib.org), then they are automatically copied to the main R process:

rs <- callr::r_session$new()
rs$run(function() {
  cli::cli_text("This is subprocess {emph {Sys.getpid()}} from {pkg callr}")
  Sys.getpid()
})
invisible(rs$close())

Utility functions

ANSI colors

cli defines wrapper functions to the crayon package, to create ANSI colored and styled output in the console. col_* functions change the foreground color, bg_* functions change the background color, and style_* functions change the style of the text in some way.

These functions concatenate their arguments using paste0(), and add the ansi_string class to their result:

cat(col_red("This ", "is ", "red."))

Foreground colors:

cli_ul(c(
  col_black("black"),
  col_blue("blue"),
  col_cyan("cyan"),
  col_green("green"),
  col_magenta("magenta"),
  col_red("red"),
  col_white("white"),
  col_yellow("yellow"),
  col_grey("grey")
))

Note that these might actually look different depending on your terminal theme. Background colors:

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")
))

Text styles:

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")
))

Not all style_* functions are supported by all terminals.

Colors, background colors and styles can be combined:

bg_white(style_bold(col_red("TITLE")))

make_ansi_style() can create custom colors, assuming your terminal supports them. combine_ansi_styles() combines several styles into a function:

col_warn <- combine_ansi_styles(make_ansi_style("pink"), style_bold)
col_warn("This is a warning in pink!")
cat(col_warn("This is a warning in pink!"))

Console capabilities

Query the console width:

console_width()

Query if the console supports ansi escapes:

is_ansi_tty()

Hide the cursor, if the console supports it (no-op otherwise):

ansi_hide_cursor()
ansi_show_cursor()

See also ansi_with_hidden_cursor().

Query if the console supports \r:

is_dynamic_tty()

Query if the console supports UTF-8 output:

is_utf8_output()

Non-semantic CLI

While the primary way of using cli is the cli_*() functions that generate semantic CLI elements, you can also use cli functions that create terminal output directly.

Unicode characters

The symbol variable includes some Unicode characters that are often useful in CLI messages. They automatically fall back to ASCII symbols if the platform does not support them. You can use these symbols both with the semantic cli_*() functions and directly.

options(asciicast_theme = list(font_family =
  c("Monaco", "'Fira Code'", "Consolas", "Menlo",
    "'Bitstream Vera Sans Mono'", "'Powerline Symbols'", "monospace")))

cli_text("{symbol$tick} no errors  |  {symbol$cross} 2 warnings")

Here is a list of all symbols:

list_symbols()

Most symbols were inspired by (and copied from) the awesome figures JavaScript project.

cli defines wrapper functions to

Rules

Simple rule, double rule, bars

rule()

rule(line = 2)

rule(line = "bar2")

rule(line = "bar5")

rule(center = "TITLE", line = "~")

Labels

rule(left = "Results")

rule(center = " * RESULTS * ")

Colors

rule(center = col_red(" * RESULTS * "))

rule(center = " * RESULTS * ", col = "red")

rule(center = " * RESULTS * ", line_col = "red")

rule(center = "TITLE", line = "~-", line_col = "blue")

rule(center = bg_red(" ", symbol$star, "TITLE", symbol$star, " "),
  line = "\u2582", line_col = "orange")

Boxes

boxx("Hello there!")

Change border style

boxx("Hello there!", border_style = "double")

Multiple lines of text

boxx(c("Hello", "there!"), padding = 1)

Padding and margin

boxx("Hello there!", padding = 1)

boxx("Hello there!", padding = c(1, 5, 1, 5))

boxx("Hello there!", margin = 1)

boxx("Hello there!", margin = c(1, 5, 1, 5))

Floating

boxx("Hello there!", padding = 1, float = "center")

boxx("Hello there!", padding = 1, float = "right")

Colors

boxx(col_cyan("Hello there!"), padding = 1, float = "center")

boxx("Hello there!", padding = 1, background_col = "brown")

boxx("Hello there!", padding = 1, background_col = bg_red)

boxx("Hello there!", padding = 1, border_col = "green")

boxx("Hello there!", padding = 1, border_col = col_red)

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")

A very customized box

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"
)

Trees

You can specify the tree with a two column data frame, containing the node ids/labels, and the list of their children.

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, root = "rcmdcheck")

An optional third column may contain custom labels. These can be colored as well:

data$label <- paste(data$package,
  col_grey(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")

Spinners

See list_spinners() and get_spinner(). From the awesome cli-spinners project.

list_spinners()

get_spinner("dots")

ansi_with_hidden_cursor(demo_spinners("dots"))

ansi_with_hidden_cursor(demo_spinners("clock"))

License

MIT © RStudio

About

Tools for making beautiful & useful command line interfaces

Resources

Readme
License
Activity

Stars

0 stars

Watchers

0 watching

Forks

0 forks
Report repository

Releases

Packages

Contributors

Languages

You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.