r-cli
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCLI for R Packages
面向 R 包的 CLI
When to Use What
何时使用什么
task: Display error with context and formatting
use: with inline markup and bullet lists
cli_abort()task: Show warning with formatting
use: with inline markup
cli_warn()task: Display informative message
use: with inline markup
cli_inform()task: Show progress for counted operations
use: with total count
cli_progress_bar()task: Show simple progress steps
use: with status messages
cli_progress_step()task: Format code or function names
use: or
{.code ...}{.fn package::function}task: Format file paths
use:
{.file path/to/file}task: Format package names
use:
{.pkg packagename}task: Format variable names
use:
{.var variable_name}task: Format values
use:
{.val value}task: Handle singular/plural text
use: or with pluralization
{?s}{?y/ies}task: Create headers
use: , ,
cli_h1()cli_h2()cli_h3()task: Create alerts
use: , , ,
cli_alert_success()cli_alert_danger()cli_alert_warning()cli_alert_info()task: Create lists
use: , , with
cli_ul()cli_ol()cli_dl()cli_li()任务:显示带有上下文和格式的错误
用法:使用带内联标记和项目符号列表的
cli_abort()任务:显示带有格式的警告
用法:使用带内联标记的
cli_warn()任务:显示信息性消息
用法:使用带内联标记的
cli_inform()任务:显示计数操作的进度
用法:使用带 total 计数器的
cli_progress_bar()任务:显示简单的进度步骤
用法:使用带状态消息的
cli_progress_step()任务:格式化代码或函数名
用法:使用 或
{.code ...}{.fn package::function}任务:格式化文件路径
用法:使用
{.file path/to/file}任务:格式化包名
用法:使用
{.pkg packagename}任务:格式化变量名
用法:使用
{.var variable_name}任务:格式化值
用法:使用
{.val value}任务:处理单复数文本
用法:使用 或 进行复数处理
{?s}{?y/ies}任务:创建标题
用法:使用 、、
cli_h1()cli_h2()cli_h3()任务:创建警告框
用法:使用 、、、
cli_alert_success()cli_alert_danger()cli_alert_warning()cli_alert_info()任务:创建列表
用法:使用 、、 配合
cli_ul()cli_ol()cli_dl()cli_li()Inline Markup Essentials
内联标记基础
Use inline markup with syntax to format text:
{.class content}r
undefined使用 语法通过内联标记格式化文本:
{.class content}r
undefinedBasic formatting
Basic formatting
cli_text("Function {.fn mean} calculates averages")
cli_text("Install package {.pkg dplyr}")
cli_text("See file {.file ~/.Rprofile}")
cli_text("{.var x} must be numeric, not {.obj_type_of {x}}")
cli_text("Got value {.val {x}}")
cli_text("Function {.fn mean} calculates averages")
cli_text("Install package {.pkg dplyr}")
cli_text("See file {.file ~/.Rprofile}")
cli_text("{.var x} must be numeric, not {.obj_type_of {x}}")
cli_text("Got value {.val {x}}")
Code formatting
Code formatting
cli_text("Use {.code sum(x, na.rm = TRUE)}")
cli_text("Use {.code sum(x, na.rm = TRUE)}")
Paths and arguments
Paths and arguments
cli_text("Reading from {.path /data/file.csv}")
cli_text("Set {.arg na.rm} to TRUE")
cli_text("Reading from {.path /data/file.csv}")
cli_text("Set {.arg na.rm} to TRUE")
Types and classes
Types and classes
cli_text("Object is {.cls data.frame}")
cli_text("Object is {.cls data.frame}")
Emphasis
Emphasis
cli_text("This is {.emph important}")
cli_text("This is {.strong critical}")
cli_text("This is {.emph important}")
cli_text("This is {.strong critical}")
Fields
Fields
cli_text("The {.field name} field is required")
undefinedcli_text("The {.field name} field is required")
undefinedVector Collapsing
向量折叠
Vectors are automatically collapsed with commas and "and":
r
pkgs <- c("dplyr", "tidyr", "ggplot2")
cli_text("Installing packages: {.pkg {pkgs}}")
#> Installing packages: dplyr, tidyr, and ggplot2
files <- c("data.csv", "script.R")
cli_text("Found {length(files)} file{?s}: {.file {files}}")
#> Found 2 files: data.csv and script.R向量会自动折叠,并使用逗号和“and”分隔:
r
pkgs <- c("dplyr", "tidyr", "ggplot2")
cli_text("Installing packages: {.pkg {pkgs}}")
#> Installing packages: dplyr, tidyr, and ggplot2
files <- c("data.csv", "script.R")
cli_text("Found {length(files)} file{?s}: {.file {files}}")
#> Found 2 files: data.csv and script.REscaping Braces
转义大括号
Use double braces and to escape literal braces:
{{}}r
cli_text("Use {{variable}} syntax in glue")
#> Use {variable} syntax in glueFor complete markup reference: See references/inline-markup.md for all 50+ inline classes, edge cases, nesting rules, and advanced patterns.
使用双大括号 和 转义字面量大括号:
{{}}r
cli_text("Use {{variable}} syntax in glue")
#> Use {variable} syntax in glue有关完整的内联标记参考:请参阅 references/inline-markup.md,了解全部 50 多种内联类、边缘情况、嵌套规则和高级模式。
Pluralization Basics
复数处理基础
Use for pluralization with three patterns:
{?}使用 处理复数,共有三种模式:
{?}Single Alternative
单一备选形式
r
nfile <- 1
cli_text("Found {nfile} file{?s}")
#> Found 1 file
nfile <- 3
cli_text("Found {nfile} file{?s}")
#> Found 3 filesr
nfile <- 1
cli_text("Found {nfile} file{?s}")
#> Found 1 file
nfile <- 3
cli_text("Found {nfile} file{?s}")
#> Found 3 filesTwo Alternatives
两种备选形式
r
ndir <- 1
cli_text("Found {ndir} director{?y/ies}")
#> Found 1 directory
ndir <- 5
cli_text("Found {ndir} director{?y/ies}")
#> Found 5 directoriesr
ndir <- 1
cli_text("Found {ndir} director{?y/ies}")
#> Found 1 directory
ndir <- 5
cli_text("Found {ndir} director{?y/ies}")
#> Found 5 directoriesThree Alternatives (zero/one/many)
三种备选形式(零/一/多)
r
nfile <- 0
cli_text("Found {nfile} file{?s}: {?no/the/the} file{?s}")
#> Found 0 files: no files
nfile <- 1
cli_text("Found {nfile} file{?s}: {?no/the/the} file{?s}")
#> Found 1 file: the file
nfile <- 3
cli_text("Found {nfile} file{?s}: {?no/the/the} file{?s}")
#> Found 3 files: the filesr
nfile <- 0
cli_text("Found {nfile} file{?s}: {?no/the/the} file{?s}")
#> Found 0 files: no files
nfile <- 1
cli_text("Found {nfile} file{?s}: {?no/the/the} file{?s}")
#> Found 1 files: the file
nfile <- 3
cli_text("Found {nfile} file{?s}: {?no/the/the} file{?s}")
#> Found 3 files: the filesHelpers: qty() and no()
辅助函数:qty() 和 no()
Use to display "no" instead of zero:
no()r
nfile <- 0
cli_text("Found {no(nfile)} file{?s}")
#> Found no filesUse to set quantity explicitly:
qty()r
nupd <- 3
ntotal <- 10
cli_text("{nupd}/{ntotal} {qty(nupd)} file{?s} {?needs/need} updates")
#> 3/10 files need updatesFor advanced pluralization: See references/inline-markup.md for edge cases and complex patterns.
使用 显示“no”而不是零:
no()r
nfile <- 0
cli_text("Found {no(nfile)} file{?s}")
#> Found no files使用 显式设置数量:
qty()r
nupd <- 3
ntotal <- 10
cli_text("{nupd}/{ntotal} {qty(nupd)} file{?s} {?needs/need} updates")
#> 3/10 files need updates有关高级复数处理:请参阅 references/inline-markup.md,了解边缘情况和复杂模式。
CLI Conditions: Core Patterns
CLI 条件:核心模式
Use cli conditions instead of base R for better formatting:
使用 cli 条件替代 base R,以获得更好的格式:
cli_abort() - Formatted Errors
cli_abort()——格式化错误
r
undefinedr
undefinedBefore (base R)
Before (base R)
stop("File not found: ", path)
stop("File not found: ", path)
After (cli)
After (cli)
cli_abort("File {.file {path}} not found")
cli_abort("File {.file {path}} not found")
With bullets for context
With bullets for context
check_file <- function(path) {
if (!file.exists(path)) {
cli_abort(c(
"File not found",
"x" = "Cannot read {.file {path}}",
"i" = "Check that the file exists"
))
}
}
undefinedcheck_file <- function(path) {
if (!file.exists(path)) {
cli_abort(c(
"File not found",
"x" = "Cannot read {.file {path}}",
"i" = "Check that the file exists"
))
}
}
undefinedcli_warn() - Formatted Warnings
cli_warn()——格式化警告
r
undefinedr
undefinedBefore (base R)
Before (base R)
warning("Column ", col, " has missing values")
warning("Column ", col, " has missing values")
After (cli)
After (cli)
cli_warn("Column {.field {col}} has missing values")
cli_warn("Column {.field {col}} has missing values")
With context
With context
cli_warn(c(
"Data quality issues detected",
"!" = "Column {.field {col}} has {n_missing} missing value{?s}",
"i" = "Consider using {.fn tidyr::drop_na}"
))
undefinedcli_warn(c(
"Data quality issues detected",
"!" = "Column {.field {col}} has {n_missing} missing value{?s}",
"i" = "Consider using {.fn tidyr::drop_na}"
))
undefinedcli_inform() - Formatted Messages
cli_inform()——格式化消息
r
undefinedr
undefinedBefore (base R)
Before (base R)
message("Processing ", n, " files")
message("Processing ", n, " files")
After (cli)
After (cli)
cli_inform("Processing {n} file{?s}")
cli_inform("Processing {n} file{?s}")
With structure
With structure
cli_inform(c(
"v" = "Successfully loaded {.pkg dplyr}",
"i" = "Version {packageVersion('dplyr')}"
))
undefinedcli_inform(c(
"v" = "Successfully loaded {.pkg dplyr}",
"i" = "Version {packageVersion('dplyr')}"
))
undefinedBullet Types
项目符号类型
- - Error/problem (red X)
"x" - - Warning (yellow !)
"!" - - Information (blue i)
"i" - - Success (green checkmark)
"v" - - Bullet point
"*" - - Arrow/pointer
">"
For advanced error design: See references/conditions.md for error design principles, rlang integration, testing strategies, and real-world patterns.
- - 错误/问题(红色 X)
"x" - - 警告(黄色 !)
"!" - - 信息(蓝色 i)
"i" - - 成功(绿色对勾)
"v" - - 项目符号
"*" - - 箭头/指针
">"
有关高级错误设计:请参阅 references/conditions.md,了解错误设计原则、rlang 集成、测试策略和真实场景模式。
Basic Progress Indicators
基础进度指示器
Simple Progress Steps
简单进度步骤
r
process_data <- function() {
cli_progress_step("Loading data")
data <- load_data()
cli_progress_step("Cleaning data")
clean <- clean_data(data)
cli_progress_step("Analyzing data")
analyze(clean)
}r
process_data <- function() {
cli_progress_step("Loading data")
data <- load_data()
cli_progress_step("Cleaning data")
clean <- clean_data(data)
cli_progress_step("Analyzing data")
analyze(clean)
}Basic Progress Bar
基础进度条
r
process_files <- function(files) {
cli_progress_bar("Processing files", total = length(files))
for (file in files) {
process_file(file)
cli_progress_update()
}
}r
process_files <- function(files) {
cli_progress_bar("Processing files", total = length(files))
for (file in files) {
process_file(file)
cli_progress_update()
}
}Auto-Cleanup
自动清理
Progress bars auto-close when the function exits:
r
process <- function() {
cli_progress_bar("Working", total = 100)
for (i in 1:100) {
Sys.sleep(0.01)
cli_progress_update()
}
# No need to call cli_progress_done() - auto-closes
}For advanced progress: See references/progress.md for nested progress, custom formats, parallel processing, all progress variables, and Shiny integration.
函数退出时进度条会自动关闭:
r
process <- function() {
cli_progress_bar("Working", total = 100)
for (i in 1:100) {
Sys.sleep(0.01)
cli_progress_update()
}
# No need to call cli_progress_done() - auto-closes
}有关高级进度:请参阅 references/progress.md,了解嵌套进度、自定义格式、并行处理、所有进度变量和 Shiny 集成。
Semantic CLI Elements
语义化 CLI 元素
Headers
标题
r
cli_h1("Main Section")
cli_h2("Subsection")
cli_h3("Detail")r
cli_h1("Main Section")
cli_h2("Subsection")
cli_h3("Detail")Alerts
警告框
r
cli_alert_success("Operation completed successfully")
cli_alert_danger("Critical error occurred")
cli_alert_warning("Potential issue detected")
cli_alert_info("Additional information available")r
cli_alert_success("Operation completed successfully")
cli_alert_danger("Critical error occurred")
cli_alert_warning("Potential issue detected")
cli_alert_info("Additional information available")Text and Code
文本与代码
r
undefinedr
undefinedRegular text with markup
Regular text with markup
cli_text("This is formatted text with {.emph emphasis}")
cli_text("This is formatted text with {.emph emphasis}")
Code blocks
Code blocks
cli_code(c(
"library(dplyr)",
"mtcars %>% filter(mpg > 20)"
))
cli_code(c(
"library(dplyr)",
"mtcars %>% filter(mpg > 20)"
))
Verbatim text (no formatting)
Verbatim text (no formatting)
cli_verbatim("This is displayed exactly as-is: {not interpolated}")
undefinedcli_verbatim("This is displayed exactly as-is: {not interpolated}")
undefinedLists
列表
r
undefinedr
undefinedUnordered list
Unordered list
cli_ul()
cli_li("First item")
cli_li("Second item")
cli_end()
cli_ul()
cli_li("First item")
cli_li("Second item")
cli_end()
Ordered list
Ordered list
cli_ol()
cli_li("First step")
cli_li("Second step")
cli_end()
cli_ol()
cli_li("First step")
cli_li("Second step")
cli_end()
Definition list
Definition list
cli_dl()
cli_li(c(name = "The name field"))
cli_li(c(email = "The email address"))
cli_end()
undefinedcli_dl()
cli_li(c(name = "The name field"))
cli_li(c(email = "The email address"))
cli_end()
undefinedCommon Workflows
常见工作流
Base R to CLI Migration
从 Base R 迁移到 CLI
r
undefinedr
undefinedBefore: Base R error handling
Before: Base R error handling
validate_input <- function(x, y) {
if (!is.numeric(x)) {
stop("x must be numeric")
}
if (length(y) == 0) {
stop("y cannot be empty")
}
if (length(x) != length(y)) {
stop("x and y must have the same length")
}
}
validate_input <- function(x, y) {
if (!is.numeric(x)) {
stop("x must be numeric")
}
if (length(y) == 0) {
stop("y cannot be empty")
}
if (length(x) != length(y)) {
stop("x and y must have the same length")
}
}
After: CLI error handling
After: CLI error handling
validate_input <- function(x, y) {
if (!is.numeric(x)) {
cli_abort(c(
"{.arg x} must be numeric",
"x" = "You supplied a {.cls {class(x)}} vector",
"i" = "Use {.fn as.numeric} to convert"
))
}
if (length(y) == 0) {
cli_abort(c(
"{.arg y} cannot be empty",
"i" = "Provide at least one element"
))
}
if (length(x) != length(y)) {
cli_abort(c(
"{.arg x} and {.arg y} must have the same length",
"x" = "{.arg x} has length {length(x)}",
"x" = "{.arg y} has length {length(y)}"
))
}
}
undefinedvalidate_input <- function(x, y) {
if (!is.numeric(x)) {
cli_abort(c(
"{.arg x} must be numeric",
"x" = "You supplied a {.cls {class(x)}} vector",
"i" = "Use {.fn as.numeric} to convert"
))
}
if (length(y) == 0) {
cli_abort(c(
"{.arg y} cannot be empty",
"i" = "Provide at least one element"
))
}
if (length(x) != length(y)) {
cli_abort(c(
"{.arg x} and {.arg y} must have the same length",
"x" = "{.arg x} has length {length(x)}",
"x" = "{.arg y} has length {length(y)}"
))
}
}
undefinedError Message with Rich Context
包含丰富上下文的错误消息
r
check_required_columns <- function(data, required_cols) {
actual_cols <- names(data)
missing_cols <- setdiff(required_cols, actual_cols)
if (length(missing_cols) > 0) {
cli_abort(c(
"Required column{?s} missing from data",
"x" = "Missing {length(missing_cols)} column{?s}: {.field {missing_cols}}",
"i" = "Data has {length(actual_cols)} column{?s}: {.field {actual_cols}}",
"i" = "Add the missing column{?s} or check for typos"
))
}
invisible(data)
}r
check_required_columns <- function(data, required_cols) {
actual_cols <- names(data)
missing_cols <- setdiff(required_cols, actual_cols)
if (length(missing_cols) > 0) {
cli_abort(c(
"Required column{?s} missing from data",
"x" = "Missing {length(missing_cols)} column{?s}: {.field {missing_cols}}",
"i" = "Data has {length(actual_cols)} column{?s}: {.field {actual_cols}}",
"i" = "Add the missing column{?s} or check for typos"
))
}
invisible(data)
}Function with Progress Bar
带进度条的函数
r
process_files <- function(files, verbose = TRUE) {
n <- length(files)
if (verbose) {
cli_progress_bar(
format = "Processing {cli::pb_bar} {cli::pb_current}/{cli::pb_total} [{cli::pb_eta}]",
total = n
)
}
results <- vector("list", n)
for (i in seq_along(files)) {
results[[i]] <- process_file(files[[i]])
if (verbose) {
cli_progress_update()
}
}
results
}r
process_files <- function(files, verbose = TRUE) {
n <- length(files)
if (verbose) {
cli_progress_bar(
format = "Processing {cli::pb_bar} {cli::pb_current}/{cli::pb_total} [{cli::pb_eta}]",
total = n
)
}
results <- vector("list", n)
for (i in seq_along(files)) {
results[[i]] <- process_file(files[[i]])
if (verbose) {
cli_progress_update()
}
}
results
}Resources & Advanced Topics
资源与高级主题
Reference Files
参考文件
-
references/inline-markup.md - Complete catalog of inline classes organized by category, advanced patterns, nesting rules, and real-world examples
-
references/conditions.md - Advanced error design patterns, rlang integration, testing with testthat snapshots, migration guide, and anti-patterns
-
references/progress.md - Nested progress bars, custom formats, all progress variables, parallel processing, Shiny integration, and debugging
-
references/themes.md - Complete theming system with CSS-like selectors, container functions, color palettes, custom themes, and accessibility
-
references/ansi-operations.md - ANSI string operations (align, columns, nchar, etc.), hyperlinks, color detection, testing CLI output, and troubleshooting
-
references/inline-markup.md - 按类别组织的完整内联类目录、高级模式、嵌套规则和真实场景示例
-
references/conditions.md - 高级错误设计模式、rlang 集成、使用 testthat 快照进行测试、迁移指南和反模式
-
references/progress.md - 嵌套进度条、自定义格式、所有进度变量、并行处理、Shiny 集成和调试
-
references/themes.md - 完整的 theming 系统,包含类似 CSS 的选择器、容器函数、颜色调色板、自定义主题和无障碍支持
-
references/ansi-operations.md - ANSI 字符串操作(对齐、列、nchar 等)、超链接、颜色检测、CLI 输出测试和故障排查
External Resources
外部资源
Related Packages
相关包
- rlang - Condition handling and error objects integrate with cli
- glue - String interpolation powers cli's syntax
{} - testthat - Snapshot testing for cli output
- rlang - 与 cli 集成的条件处理和错误对象
- glue - 为 cli 的 语法提供字符串插值支持
{} - testthat - 用于 CLI 输出的快照测试