From f975137253613712c48ea4e25cc067d5d7577841 Mon Sep 17 00:00:00 2001 From: Romain Francois Date: Sat, 24 Feb 2024 18:59:31 +0100 Subject: [PATCH] link::auto() --- DESCRIPTION | 4 +++- NAMESPACE | 1 + R/auto.R | 41 +++++++++++++++++++++++++++++++++++++++++ man/auto.Rd | 11 +++++++++++ 4 files changed, 56 insertions(+), 1 deletion(-) create mode 100644 R/auto.R create mode 100644 man/auto.Rd diff --git a/DESCRIPTION b/DESCRIPTION index ce0ab14..d074e7a 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -12,6 +12,8 @@ Imports: cli, downlit, glue, - rlang + knitr, + rlang, + stringr URL: https://github.com/tadascience/link, http://tada.science/link/ BugReports: https://github.com/tadascience/link/issues diff --git a/NAMESPACE b/NAMESPACE index 5d98da8..5b87ae7 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -1,5 +1,6 @@ # Generated by roxygen2: do not edit by hand +export(auto) export(to) importFrom(cli,cli_abort) importFrom(rlang,enexpr) diff --git a/R/auto.R b/R/auto.R new file mode 100644 index 0000000..af4825a --- /dev/null +++ b/R/auto.R @@ -0,0 +1,41 @@ +rx_valid_pkg <- "[a-zA-Z][a-zA-Z0-9.]*[a-zA-Z0-9]" +rx_valid_fun <- "([a-zA-Z]\\w*|\\.\\w+)" + +autolink_pkg <- function(x) { + rx_pkg <- glue::glue("[{{]({rx_valid_pkg})[}}]") + stringr::str_replace_all( + x, rx_pkg, + function(pkg) { + to(package = stringr::str_extract(pkg, rx_pkg, group = 1)) + } + ) +} + +autolink_call <- function(x) { + rx_call <- glue::glue("[{{]({rx_valid_pkg})::({rx_valid_fun})[(][)][}}]") + stringr::str_replace_all( + x, rx_call, + function(call){ + to( + package = stringr::str_extract(call, rx_call, group = 1), + topic = stringr::str_extract(call, rx_call, group = 2) + ) + } + ) + +} + +#' Setup automatic linking +#' +#' @export +auto <- function() { + default_text_hook <- knitr::knit_hooks$get("text") + knitr::knit_hooks$set(text = function(x) { + + x <- autolink_pkg(x) + x <- autolink_call(x) + + default_text_hook(x) + }) + +} diff --git a/man/auto.Rd b/man/auto.Rd new file mode 100644 index 0000000..7ed3275 --- /dev/null +++ b/man/auto.Rd @@ -0,0 +1,11 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/auto.R +\name{auto} +\alias{auto} +\title{Setup automatic linking} +\usage{ +auto() +} +\description{ +Setup automatic linking +}