retex-engine 1.3.0

The TeX typesetting engine for retex
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! xcolor's colour expressions and colour definitions (xcolor.sty v3.02),
//! for the models `rgb`, `gray` and `cmyk`: `\XC@split` of
//! `<name>!<pct>!<name>!<pct>…` (mixing, as `\@xcolor@` and `\@xcolor@@`
//! do it with TeX dimensions: `\XC@mix`, `\rrshift`, `\strip@pt`), the
//! conversion from `gray` (`\XC@cnv@gray`), and what `\XC@definec@lor`
//! stores (`\XC@coremodel`'s normalization `\XC@calcN` and the driver
//! text of `luatex.def`'s `\color@rgb`, `\color@gray`, `\color@cmyk`).
//!
//! Everything works on the strings xcolor works on. Anything else
//! (complements, functions, model lists, postfix series, conversions other
//! than from gray, other models, components outside `[0,1]` where the
//! driver checks them) is `None`: the caller declines.

use super::deps;
use super::pgfdim as d;
use crate::Engine;
use crate::cmd::Cmd;
use crate::hash::CsId;
use crate::token::Token;

/// A colour model of the subset.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Model {
    Rgb,
    Gray,
    Cmyk,
}

impl Model {
    fn from_name(s: &[u8]) -> Option<Model> {
        Some(match s {
            b"rgb" => Model::Rgb,
            b"gray" => Model::Gray,
            b"cmyk" => Model::Cmyk,
            _ => return None,
        })
    }

    pub fn name(self) -> &'static [u8] {
        match self {
            Model::Rgb => b"rgb",
            Model::Gray => b"gray",
            Model::Cmyk => b"cmyk",
        }
    }

    fn arity(self) -> usize {
        match self {
            Model::Rgb => 3,
            Model::Gray => 1,
            Model::Cmyk => 4,
        }
    }
}

/// A colour: its model and the component strings.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Spec {
    pub model: Model,
    pub comps: Vec<Vec<u8>>,
}

/// Whether `s` is a decimal number xcolor's macros read as one (an
/// optional `-`, digits and at most one point, something).
fn number(s: &[u8]) -> bool {
    let s = s.strip_prefix(b"-").unwrap_or(s);
    let digits = s.iter().filter(|c| c.is_ascii_digit()).count();
    let points = s.iter().filter(|&&c| c == b'.').count();
    digits > 0 && points <= 1 && digits + points == s.len() && s.last() != Some(&b'.')
}

/// Parses `a,b,c` for `model` (xcolor's `\XC@clean` leaves such lists
/// unchanged).
fn components(model: Model, s: &[u8]) -> Option<Vec<Vec<u8>>> {
    let comps: Vec<Vec<u8>> = s.split(|&c| c == b',').map(<[u8]>::to_vec).collect();
    (comps.len() == model.arity() && comps.iter().all(|c| number(c))).then_some(comps)
}

/// The tokens of a braced group at `toks[*i]`.
fn group<'a>(toks: &'a [Token], i: &mut usize) -> Option<&'a [Token]> {
    let t = *toks.get(*i)?;
    if t.is_cs() || t.cmd_code() != Cmd::LeftBrace as u32 {
        return None;
    }
    let start = *i + 1;
    let mut depth = 0;
    loop {
        let k = *toks.get(*i)?;
        if !k.is_cs() {
            if k.cmd_code() == Cmd::LeftBrace as u32 {
                depth += 1;
            } else if k.cmd_code() == Cmd::RightBrace as u32 {
                depth -= 1;
                if depth == 0 {
                    *i += 1;
                    return Some(&toks[start..*i - 1]);
                }
            }
        }
        *i += 1;
    }
}

/// The four arguments of `\xcolor@` in a colour macro's body
/// (`\xcolor@{<cls>}{<drv>}{<mod>}{<clr>}`).
pub fn xcolor_args(e: &Engine, cs: CsId) -> Option<[Vec<Token>; 4]> {
    let xcolor_at = e.hash.lookup(b"xcolor@")?;
    let body = deps::plain_body(e, cs)?;
    if e.eqtb.meaning(cs).cmd != Cmd::Call || body.first() != Some(&Token::cs(xcolor_at)) {
        return None;
    }
    let mut i = 1;
    let mut out: [Vec<Token>; 4] = Default::default();
    for slot in &mut out {
        *slot = group(body, &mut i)?.to_vec();
    }
    (i == body.len()).then_some(out)
}

/// The colour named `name` as `\@xcolor@` reads it: `\XC@sdef\@@mod{#3}`,
/// `\edef\@@clr{#4}`.
pub fn named_spec(e: &Engine, name: &[u8]) -> Option<Spec> {
    let mut cname = b"\\color@".to_vec();
    cname.extend_from_slice(name);
    let cs = e.hash.lookup(&cname)?;
    let [_, _, m, c] = xcolor_args(e, cs)?;
    let model = Model::from_name(&deps::sanitized(&deps::edef(e, &m)?)?)?;
    let clr = deps::sanitized(&deps::edef(e, &c)?)?;
    Some(Spec {
        model,
        comps: components(model, &clr)?,
    })
}

/// `\XC@clr@<mod>@<name>`: xcolor's shortcuts for mixing with `white`.
fn shortcut(e: &Engine, model: Model, name: &[u8]) -> Option<Option<Spec>> {
    let mut n = b"XC@clr@".to_vec();
    n.extend_from_slice(model.name());
    n.push(b'@');
    n.extend_from_slice(name);
    let Some(cs) = e.hash.lookup(&n) else {
        return Some(None);
    };
    let m = e.eqtb.meaning(cs);
    if m.cmd == Cmd::UndefinedCs {
        return Some(None);
    }
    let relax = e.hash.lookup(b"relax").map(|r| e.eqtb.meaning(r))?;
    if deps::absent(m, relax) {
        return Some(None);
    }
    let text = deps::sanitized(deps::plain_body(e, cs)?)?;
    Some(Some(Spec {
        model,
        comps: components(model, &text)?,
    }))
}

/// `\strip@pt`: `\the` of a dimension without `pt`, and without `.0`.
fn strip_pt(x: i32) -> Vec<u8> {
    let s = d::print(x);
    match s.strip_suffix(b".0") {
        Some(int) => int.to_vec(),
        None => s,
    }
}

/// `\rshift`: the point of `\the<dim>` moved one place to the left, read
/// again as a dimension.
fn rshift(x: i32) -> Option<i32> {
    let s = d::print(x);
    let (int, frac) = d::split_point(&s);
    let (&last, head) = int.split_last()?;
    let mut t = head.to_vec();
    t.push(b'.');
    t.push(last);
    t.extend_from_slice(frac);
    d::scan_pt(&t).ok()
}

/// `\XC@calcN`: clamped to `[0,1]`, five decimals (truncated), trailing
/// zeros removed.
pub fn calc_n(x: &[u8]) -> Vec<u8> {
    let (int, frac) = match x.iter().position(|&c| c == b'.') {
        Some(p) => (&x[..p], &x[p + 1..]),
        None => (x, &b"0"[..]),
    };
    // \ifnum#10>0: the integer part followed by a zero, as a number.
    let int_value = |extra: u8| -> i64 {
        let mut t = int.to_vec();
        t.push(extra);
        d::scan_int(&t).unwrap_or(0)
    };
    let r: Vec<u8> = if int_value(b'0') > 0 {
        b"1.00000".to_vec()
    } else if int_value(b'1') < 0 {
        b"0.00000".to_vec()
    } else {
        let mut f = frac.to_vec();
        f.extend_from_slice(b"00000");
        let mut r = b"0.".to_vec();
        r.extend_from_slice(&f[..5]);
        r
    };
    // \XC@c@lcN: the integer, and the decimals before the first `00000`.
    let (i, f) = r.split_at(1);
    let mut tail = f[1..].to_vec();
    tail.extend_from_slice(b"00000");
    let end = tail.windows(5).position(|w| w == b"00000").unwrap_or(0);
    let digits = &tail[..end];
    let mut out = i.to_vec();
    if digits.iter().any(|&c| c != b'0') {
        out.push(b'.');
        out.extend_from_slice(digits);
    }
    out
}

/// `\convertcolorspec` from `gray` (`\XC@cnv@gray`) to `to`.
fn from_gray(g: &[u8], to: Model) -> Option<Vec<Vec<u8>>> {
    match to {
        Model::Gray => Some(vec![g.to_vec()]),
        Model::Rgb => {
            let n = calc_n(g);
            Some(vec![n.clone(), n.clone(), n])
        }
        // `0,0,0,` and \XC@calcC: not needed so far.
        Model::Cmyk => None,
    }
}

/// `\XC@mix` of `cur` with `other` (same model), `p` the percentage of
/// `cur` as a dimension.
fn mix(cur: &[Vec<u8>], other: &[Vec<u8>], p: i32) -> Option<Vec<Vec<u8>>> {
    let tempdima = p;
    let tempdimb = d::adv(d::scan_pt(b"100").ok()?, -tempdima).ok()?;
    cur.iter()
        .zip(other)
        .map(|(c, m)| {
            let mut x = d::scan_factor(c, tempdima).ok()?;
            x = d::adv(x, d::scan_factor(m, tempdimb).ok()?).ok()?;
            x = rshift(rshift(x)?)?;
            Some(strip_pt(x))
        })
        .collect()
}

/// `\XC@split` of an expression (already `\XC@edef`ed): the colour it
/// denotes.
pub fn split(e: &Engine, expr: &[u8]) -> Option<Spec> {
    split_over(e, expr, None)
}

/// [`split`], with the colour `over.0` taken to be `over.1` (a colour the
/// caller is about to define).
pub fn split_over(e: &Engine, expr: &[u8], over: Option<(&[u8], &Spec)>) -> Option<Spec> {
    let named = |n: &[u8]| match over {
        Some((name, spec)) if name == n => Some(spec.clone()),
        _ => named_spec(e, n),
    };
    if expr.iter().any(|c| b">:-[]+/".contains(c)) {
        return None; // functions, model lists, complements, series
    }
    let mut parts = expr.split(|&c| c == b'!');
    let name = parts.next()?;
    let mut spec = named(name)?;
    let rest: Vec<&[u8]> = parts.collect();
    // `<pct>!<name>` pairs; a last `<pct>` mixes with white.
    let mut k = 0;
    while k < rest.len() {
        let pct = rest[k];
        let other = rest.get(k + 1).copied().unwrap_or(b"");
        k += 2;
        if pct.is_empty() || !number(pct) || pct.starts_with(b"-") {
            return None;
        }
        let one = d::scan_pt(b"1").ok()?;
        let p = d::scan_factor(pct, one).ok()?;
        if p <= 0 || p >= d::scan_factor(b"100", one).ok()? {
            return None; // \XC@postfix or a plain copy
        }
        let other = if other.is_empty() {
            &b"white"[..]
        } else {
            other
        };
        let other_spec = match shortcut(e, spec.model, other)? {
            Some(s) => s,
            None => {
                let o = named(other)?;
                if spec.model == Model::Gray {
                    // The current colour is converted to the other's model.
                    let g = spec.comps[0].clone();
                    spec = Spec {
                        model: o.model,
                        comps: from_gray(&g, o.model)?,
                    };
                    o
                } else if o.model == spec.model {
                    o
                } else if o.model == Model::Gray {
                    Spec {
                        model: spec.model,
                        comps: from_gray(&o.comps[0], spec.model)?,
                    }
                } else {
                    return None;
                }
            }
        };
        spec.comps = mix(&spec.comps, &other_spec.comps, p)?;
    }
    Some(spec)
}

/// `\XC@coremodel` for the subset: `\XC@calcN` on each component.
pub fn normalized(spec: &Spec) -> Spec {
    Spec {
        model: spec.model,
        comps: spec.comps.iter().map(|c| calc_n(c)).collect(),
    }
}

/// Whether the driver's `\c@lor@arg` accepts every component (in `[0,1]`).
pub fn in_range(spec: &Spec) -> bool {
    let one = 65536;
    spec.comps
        .iter()
        .all(|c| d::scan_pt(c).is_ok_and(|v| (0..=one).contains(&v)))
}

/// The value `\c@lor@arg` leaves in `\dimen@` for the last component it
/// checks (the driver checks gray's only component, rgb's in order, and
/// cmyk's black first, then cyan, magenta, yellow).
pub fn last_arg_dimen(spec: &Spec) -> Option<i32> {
    let last = match spec.model {
        Model::Cmyk => &spec.comps[2],
        _ => spec.comps.last()?,
    };
    let v = d::scan_factor(last, 65536).ok()?;
    Some(if v < 0 { 0o7777777777 } else { v })
}

/// The driver text (`luatex.def`'s `\color@<model>`): `r g b rg r g b RG`,
/// `g g g G`… as tokens.
pub fn driver_text(spec: &Spec) -> Vec<Token> {
    let mut out = Vec::new();
    let chars = |s: &[u8], out: &mut Vec<Token>| {
        out.extend(s.iter().map(|&c| Token::other(u32::from(c))));
    };
    let letters = |s: &[u8], out: &mut Vec<Token>| {
        out.extend(s.iter().map(|&c| Token::letter(u32::from(c))));
    };
    for op in [&b"rg"[..], b"RG"] {
        if !out.is_empty() {
            out.push(Token::SPACE);
        }
        for c in &spec.comps {
            chars(c, &mut out);
            out.push(Token::SPACE);
        }
        let op: &[u8] = match spec.model {
            Model::Rgb => op,
            Model::Gray => {
                if op == b"rg" {
                    b"g"
                } else {
                    b"G"
                }
            }
            Model::Cmyk => {
                if op == b"rg" {
                    b"k"
                } else {
                    b"K"
                }
            }
        };
        letters(op, &mut out);
    }
    out
}

/// The comma-separated components as tokens.
pub fn clr_tokens(spec: &Spec) -> Vec<Token> {
    let mut out = Vec::new();
    for (k, c) in spec.comps.iter().enumerate() {
        if k > 0 {
            out.push(Token::other(u32::from(b',')));
        }
        out.extend(c.iter().map(|&b| Token::other(u32::from(b))));
    }
    out
}

/// The body `\XC@definec@lor` gives a colour macro:
/// `\xcolor@{}{<drv>}{<mod>}{<clr>}` with the normalized spec.
pub fn definition(e: &Engine, spec: &Spec) -> Option<Vec<Token>> {
    let xcolor_at = e.hash.lookup(b"xcolor@")?;
    let n = normalized(spec);
    let mut out = vec![
        Token::END_MATCH,
        Token::cs(xcolor_at),
        Token::LEFT_BRACE,
        Token::RIGHT_BRACE,
        Token::LEFT_BRACE,
    ];
    out.extend(driver_text(&n));
    out.push(Token::RIGHT_BRACE);
    out.push(Token::LEFT_BRACE);
    out.extend(n.model.name().iter().map(|&c| Token::other(u32::from(c))));
    out.push(Token::RIGHT_BRACE);
    out.push(Token::LEFT_BRACE);
    out.extend(clr_tokens(&n));
    out.push(Token::RIGHT_BRACE);
    Some(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn calc_n_cases() {
        let n = |s: &str| String::from_utf8(calc_n(s.as_bytes())).unwrap();
        assert_eq!(n("1"), "1");
        assert_eq!(n("0"), "0");
        assert_eq!(n("0.5"), "0.5");
        assert_eq!(n(".3"), "0.3");
        assert_eq!(n("0.123456"), "0.12345");
        assert_eq!(n("0.10010"), "0.1001");
        assert_eq!(n("0.005"), "0.005");
        assert_eq!(n("1.5"), "1");
        assert_eq!(n("-0.5"), "0");
        assert_eq!(n("2"), "1");
    }

    #[test]
    fn mixing() {
        let p = d::scan_pt(b"50").unwrap();
        let c = vec![b"1".to_vec(), b"0".to_vec(), b"0".to_vec()];
        let w = vec![b"1".to_vec(), b"1".to_vec(), b"1".to_vec()];
        let m = mix(&c, &w, p).unwrap();
        assert_eq!(m, vec![b"1".to_vec(), b"0.5".to_vec(), b"0.5".to_vec()]);
    }
}