---
title: "`string_magic`'s sepcial operations"
author: "Laurent R. Berge"
date: "`r Sys.Date()`"
output:
  html_document:
    theme: journal
    highlight: haddock
    number_sections: yes
    toc: yes
    toc_depth: 3
    toc_float:
      collapsed: yes
      smooth_scroll: no
  pdf_document:
    toc: yes
    toc_depth: 3
vignette: >
  %\VignetteIndexEntry{ref_string_magic_special_ops}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

library(stringmagic)
```

This vingette presents advanced operations included in `string_magic`. There are four parts:

- [group-wise operations](#sec_group_wise)
- [conditional operations](#sec_conditional)
- [compact if-else operator](#sec_ifelse)
- [pluralization](#sec_pluralization)

By default the function `string_magic` returns a plain character vector. In this 
vignette it is sometimes nicer to apply the function `base::cat` to display 
`string_magic` results containing newlines. Ths function `cat_magic` does exactly 
that and we will use it from time to time.

# Group-wise operations {#sec_group_wise}

In `string_magic`, the operations `split` and `extract` keep a memory of the strings 
that were split (i.e. they provide multiple results for each initial string element). 

Use the tilde operator, of the form `~(op1, op2)`, to apply operations
group-wise, to each of the split strings. Better with an example.

```{r}
x = c("Oreste, Hermione", "Hermione, Pyrrhus", "Pyrrhus, Andromaque")
string_magic("Troubles ahead: {', 'split, ~(' loves 'collapse), enum ? x}.")
```

Almost all operations can be applied group-wise (although only operations changing the order or 
the length of the strings really matter, see the [dedicated section](https://lrberge.github.io/stringmagic/articles/ref_operations.html#sec_op_length)).

# Conditional operations {#sec_conditional}

There are two operators to apply operations conditionally: `if` and `vif`, the latter
standing for *verbatim if*.

## *if* statement

The syntax of `if` is `if(cond ; ops_true ; ops_false)` with `cond` a
condition (i.e. logical operation) on the value being interpolated, `ops_true` a comma-separated
sequence of operations if the condition is `TRUE` and `ops_false` an *optional* a sequence of
operations if the condition is `FALSE`.

The condition `cond` accepts the following special values: 

- `.` (the dot): refers to the current vector
- `.nchar` or `.C`: represent the number of characters of the current vector (equivalent to `nchar(.)`)
- `.len` or `.N`.: represent the length of the current vector (equivalent to `length(.)`)

Ex.1: Let's take a sentence, delete words of less than 4 characters, and trim 
words of 7+ characters. 
```{r}
x = "Songe Céphise à cette nuit cruelle qui fut pour tout un peuple une nuit éternelle"
string_magic("{' 'split, if(.nchar<=4 ; nuke ; 7 shorten), collapse ? x}")
```

Let's break it down. First the sentence is split w.r.t. spaces (command `' 'split`), leading to a vector
of words. Then we use the special variable `.nchar` in `if`'s condition to refer 
to the number of characters of the current vector (the words). The words with 
less than 4 characters are nuked (i.e. removed), and the other words are
trimmed at 7 characters (`7 Shorten`). Finally the modified vector of words is collapsed with 
the command `collapse`, leading to the result.

In Ex.1 the condition led to a vector of length greater than 1 (length = number of words), 
triggerring element-wise operations. 

If a condition leads to a result of length 1, then the operations are applied to 
the full string vector. 
Contrary to element-wise conditions
for which operations modifying the length of the vectors are **forbidden** (apart from nuking),
such operations are fine in full-string conditions.

Ex.2: we write the sum of several elements, if the vector is longer than 4, we replace all
remaining elements with an ellispsis.
```{r}
# same expression for two values of x give different results
x_short = string_magic("x{1:4}")
# the false statement is missing: it means that nothing is done is .N<=4
string_magic("y = {if(.N>4 ; 3 first, '...'insert.right), ' + 'c ? x_short}")

x_long = string_magic("x{1:10}")
string_magic("y = {if(.N>4 ; 3 first, '...'insert.right), ' + 'c ? x_long}")
```

In this example, the operations applied are:

- short vector: `string_magic("y = {' + 'c ? x_short}")`
- long vector: `string_magic("y = {3 first, '...'insert.right, ' + 'c ? x_long}")`

## *Verbatim if* statement

For `vif`, the syntax is `vif(cond ; verb_true ; verb_false)` with `verb_true`
a verbatim value with which the vector will be replaced if the condition is `TRUE`. 
This is similar for `verb_false`. The condition works as in `if`.

As for the if operator, you can use the special values `"."`, `.len`, `.N`, `.nchar` 
and `.C` in the condition.
On top of this, you can use `'.'` to refer to the current value in `verb_true` 
and `verb_false`, as illustrated by the following example.

Ex.3: we want to replace all values lower than 10 by the the string "<10", and then
create an enumeration.
```{r}
pval = c(1e-20, 0.15, 0.5)
cat_magic("pvalues: {vif(.<1e-16 ; <1e-16 ; {%05f ? .}), align.right ? pval}", 
          .sep = "\n")
```

In this example, the condition is of the same length as the vector, so an element-wise 
operation is triggered. Note that we use `'.'` to refer to `pval` in the condition.
Elements lower than 1e-16 are replaced with the string `"<1e-16"`.
Other elements are replaced with `{%05f?.}`. This string contains the interpolation delimiters,
interpolation applies. The dot, `'.'`, now refers to the values of `pval` respecting the condition.
And `sprintf` formatting is applied (`%05f`). After this, we right align the results.

Conditions of length 1 apply the replacement 
to the full vector. Knowing this, let's redo Ex.2 differently:
```{r}
x = string_magic("x{1:10}")
string_magic("y = {vif(.N>4 ; {first?x} + ... + {last?x} ; {' + 'c ? x}) ? x}")
```

Let's break it down. If the length of the vector is greater than 4 (here it's 10), then
the full string is replaced with `"{first?x} + ... + {last?x}"`. Since this string 
contains curly brackets, interpolation applies. 
Hence we obtain the string `"x1 + ... + x10"`. Finally, this is collated to `"y = "` 
leading to the result. 

If the vector were of length lower than 4, it would have been replaced with `"{' + 'collapse?x}"`,
which will be interpolated.

# Special interpolation: if-else {#sec_ifelse}

Using an ampersand (`"&"`) as the first character of an interpolation leads to an *if-else* operation.
Using two ampersands (`"&&"`) leads to a slightly different operation 
described at the end of this section.

## Regular if-else: "&"

The syntax is as follows: `{&cond ; verb_true ; verb_false}` with `cond` a
condition (i.e. logical operation), `verb_true`
a verbatim value with which the vector will be replaced if the condition is `TRUE` and 
`verb_false` an *optional* verbatim value with which the vector will be replaced 
if the condition is `FALSE`. 
If not provided, `verb_false` is considered to be the *empty string* unless the operator is 
the double ampersand described (`&&`) at the end of this section.

Note that in `cond`, you can use the function `len`, an alias to `length`.

Ex.1: we take a vector and compose a message depending on its length. If its length is
lower than 10 then we write the message `"x is short"`, otherwise we write `"x is long"`,
and insert `"very"` depending on the number of digits.
```{r}
x = 1:5
string_magic("x is {&len(x)<10 ; short ; {`log10(.N)-1`times, ''c ! very }long}")

x = 1:50
string_magic("x is {&len(x)<10 ; short ; {`log10(.N)-1`times, ''c ! very }long}")

x = 1:5000
string_magic("x is {&len(x)<10 ; short ; {`log10(.N)-1`times, ''c ! very }long}")
```

If a condition leads to a result of length 1, the full string is replaced by the verbatim 
expression. Further, this expression will be interpolated if requested. This was the case
in Ex.1 where `verb_false` was interpolated.

If the condition uses a variable, in later interpolations you can refer to the 
first variable present in the condition with '.', and use '.len' or '.N' to refer
to its length.

If the condition's length is greater than 1, then each logical values equal to `TRUE` is replaced
by `verb_true`, and `FALSE` values are replaced with `verb_false`. There can be interpolation
on the values `verb_true` and `verb_false`. In that case the interpolation must
result into a vector of either length 1 or a length equal to the condition. Then element-wise
replacements are made, a la `base::ifelse`.

Ex.2: illustration of element-wise replacements.
```{r}
x = 1:4
y = letters[1:4]
string_magic("{&x %% 2 ; odd ; {y}}")
```

In that example, when x is odd, it is replaced with `"odd"`, and when even it is
replaced with the elements of y.

## *if-else* with automatic filling

Using the two ampersands operator (`&&`) is like the simple ampersand version but the 
default for `verb_false` is the variable used in the condition itself. So the syntax is
`{&&cond ; verb_true}` and *it does not accept* `verb_false`.

Ex.3: let's write the integer `i` in letters when equal to 3 only.
```{r}
i = 3 
string_magic("i = {&&i == 3 ; three}")

i = 5
string_magic("i = {&&i == 3 ; three}")
```

When the condition is of length 1: the full vector is replaced. When the condition is 
of the length of the vector, an element-wise replacement is triggered, like in example 3.

# Special interpolation: Pluralization {#sec_pluralization}

There is advanced support for pluralization which greatly facilitates the writing of messages 
in natural language.

## Pluralization: Principles

There are two ways to pluralize: over length or over value. To trigger a "pluralization" interpolation
use as first character:

- `#` to pluralize over the value of a variable (see Ex.1)
- `$` to pluralize over the length of a variable (see Ex.2)

Ex.1: we add an ending 's' based on a number.
```{r}
x = 5
string_magic("I bought {N?x} book{#s}.")

x = 1
string_magic("I bought {N?x} book{#s}.")
```

The syntax is `{#plural_ops ? variable}` or `{#plural_ops}` where `plural_ops` are
specific pluralization operations which will be described below. 
The pluralization is perfomed *always* with respect to the value of a variable. 

You can either add the variable explicitly (`{#plural_ops ? variable}`) or refer
to it implicitly (`{#plural_ops}`). If implicit, then the algorithm will look at the 
previous variable that was interpolated and pluralize over it. This is exaclty what happens in
Ex.1 where `x` was interpolated in `{N?x}` and the plural operation `s` (in `{#s}`) applies to 
`x`. It would have been equivalent to have `{#s ? x}`. If a variable wasn't interpolated before, then
the next interpolated variable will be used (see Ex.2). If no variable is interpolated
at all, an error is thrown.

Ex.2: we add an ending 's' and conjugate the verb 'be' based on the length of a vector.
```{r}
x = c("J.", "M.")
string_magic("My BFF{$s, are} {enum?x}!")

x = "J."
string_magic("My BFF{$s, are} {enum?x}!")
```

As you can notice in Ex.2, you can chain operations (here `'s'` and `'are'`). 
In that case a whitespace is automatically added between them.

Now let's come to the specific pluralization operations, which are different 
from regular operations.

## Pluralization: Regular operations

### s, es

Adds an `"s"` (or `"es"`) if it is plural (> 1), nothing otherwise. Accepts the option `0` or `zero` which 
treats a 0-length or a 0-value as plural.

```{r}
nfiles = 1
string_magic("We've found {#n.no ? nfiles} file{#s}.")

nfiles = 0
string_magic("We've found {#n.no ? nfiles} file{#s}.")

nfiles = 0
string_magic("We've found {#n.no ? nfiles} file{#s.0}.")

nfiles = 4
string_magic("We've found {#n.no ? nfiles} file{#s.0}.")
```

### y or ies

Adds an 'y' if singular and 'ies' if plural (>1). Accepts the option `0` or `zero` which 
treats a 0-length or a 0-value as plural.

```{r}
ndir = 1
string_magic("We've found {ndir} director{#y}.")

ndir = 5
string_magic("We've found {ndir} director{#y}.")

ndir = 1
string_magic("We've found {ndir} director{#ies}.")
```

### enum

Enumerates the elements (see help for the [regular operation `enum`](https://lrberge.github.io/stringmagic/articles/ref_operations.html#create-an-enumeration-enum)).

```{r}
fruits = c("apples", "oranges")
string_magic("The fruit{$s ? fruits} I love {$are, enum}.")

fruits = "apples"
string_magic("The fruit{$s ? fruits} I love {$are, enum}.")
```

### n, N, len, Len

Add the number of elements (`"len"`) or the value (`"n"`) of the variable as a formatted number or 
in letters (upper case versions). Accepts the options `letter` (to write in letter) 
and `upper` (to uppercase the first letter).

You can also pass the options `no` or `No`, which replace the 0 values with "no"/"No". Alternatively, 
pass a free-form argument to be used in lieu of 0 values.

```{r}
nfiles = 5
string_magic("{#N.upper.No ? nfiles} file{#s, are} compromised.")

nfiles = 1
string_magic("{#N.upper.No ? nfiles} file{#s, are} compromised.")

nfiles = 0
string_magic("{#N.upper.No ? nfiles} file{#s, are} compromised.")

# Using free-form arguments
nfiles = 5
string_magic("{#'Absolutely no'N.upper ? nfiles} file{#s, are} compromised.")

nfiles = 0
string_magic("{#'Absolutely no'N.upper ? nfiles} file{#s, are} compromised.")
```

### nth, ntimes

Writes the value of the variable as an order (nth) or a frequence (ntimes). Accepts the option `letter`
to write the numbers in letters (uppercase version of the operator does the same).

```{r}
n = 2
string_magic("Writing the same sentence {#Ntimes ? n} is unnecessary.")
```

### is, or any verb

Conjugates any English verb appropriately depending on context. Any command that
is not recognized as one of the commands previously described is treated as a verb.

Simply add an upper case first to upper case the conjugated verb.

Multiple verbs are illustrated in the example below. It also anticipaed the 
conditional statements described in the next section.

Ex.3: multiple verbs and conditional statements.
```{r}
pple = c("Francis", "Henry")
cat_magic("{$enum, is, (a;) ? pple} tall guy{$s}.",
        "{$(He;They), like} to eat donuts.",
        "When happy, at the pub {$(he;they), goes}!",
        "{$Don't, (he;they)} have wit, {$(he;they)} who {$try}?", .sep = "\n")

pple = "Francis"
cat_magic("{$enum, is, (a;) ? pple} tall guy{$s}.",
        "{$(He;They), like} to eat donuts.",
        "When happy, at the pub {$(he;they), goes}!",
        "{$Don't, (he;they)} have wit, {$(he;they)} who {$try}?", .sep = "\n")

```

## Pluralization: Conditional statements

On top of the previous operations, there is a special operation allowing to add 
verbatim text depending on the situation. The syntax is as follows:

- `(s1;s2)`: adds verbatim 's1' if singular and 's2' if plural (>1)
- `(s1;s2;s3)`: adds verbatim 's1' if zero, 's2' if singular (=1) and 's3' if plural
- `(s1;;s3)`: adds verbatim 's1' if zero, 's3' if singular or plural (i.e. >=1)

These case-dependent verbatim values **are interpolated** (if appropriate). In these interpolations
you need not refer explicitly to the variable for pluralization interpolations.

```{r}
x = 0
string_magic("{#(Sorry, nothing found.;;{#N.upper} match{#es, were} found.)?x}")

x = 1
string_magic("{#(Sorry, nothing found.;;{#N.upper} match{#es, were} found.)?x}")

x = 3
string_magic("{#(Sorry, nothing found.;;{#N.upper} match{#es, were} found.)?x}")
```


# Direct access to the current time and a timer facility {#sec_timer}

### Current date and time

You can refer to the current date or the current time with the special variables 
.date and .now:

- `.date` is equivalent to `Sys.date()`
- `.now` is equivalent to `Sys.time()`

Here is an example where we display the day:
```{r}
string_magic("This message has been written on {.date}.")
```

On top of this, you can use `.now` as a function whose sole argument
provides the format of the time. The format follows 
`base::strptime` (see `?strptime`).
In the following example, we display the day, month and the hour:

```{r}
string_magic("This message has been written on {.now('%A %B at %Hh%M')}.")
```

### Timer

Timers can be very useful inside code to find choke points and debug. `stringmagic` offers
a simple system:

- first set the timer anywhere with `timer_magic()`
- within `*_magic` functions, display the elapsed time in three possible special variables:
  - `.timer`: displays the elapsed time and resets the timer
  - `.timer_lap`: displays the elapsed time and *does not* reset the timer
  - `.timer_total`: displays the elapsed time since the `timer_magic()` call

Here is an example where we time a few computations within a function:

```{r}
rnorm_crossprod = function(n, mean = 0, sd = 1){
  # we set the timer
  timer_magic()
  # we compute some stuff
  x = rnorm(n, mean, sd)
  # we can report the time with .timer
  message_magic("{10 align ! Generation}: {.timer}")
  
  res = x %*% x
  message_magic("{10 align ! Product}: {.timer}",
                "{10 align ! Total}: {.timer_total}", .sep = "\n")
  res
}

rnorm_crossprod(1e5)
```

Note that timer is precise at +/- 1ms (this is due to its very simple interface), 
and hence should not be used to time code chunks with very short execution times.

We could refine by trigerring the messages only when debugging. We can do that by
using the argument `.trigger`:

```{r}
rnorm_crossprod = function(n, mean = 0, sd = 1, debug = FALSE){
  # we set the timer
  timer_magic()
  # we compute some stuff
  x = rnorm(n, mean, sd)
  # we can report the time with .timer
  message_magic("{10 align ! Generation}: {.timer}", .trigger = debug)
  
  res = x %*% x
  message_magic("{10 align ! Product}: {.timer}",
                "{10 align ! Total}: {.timer_total}", 
                .sep = "\n", .trigger = debug)
                
  res
}

# timer not shown
rnorm_crossprod(1e5)

# timers shown thanks to the argument
rnorm_crossprod(1e5, debug = TRUE)
```




