summaryrefslogtreecommitdiff
path: root/library/src/math/style.rs
blob: 14f97ae8ad381c07cd7baf1c24343caf2508c4ce (plain) (blame)
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
use super::*;

/// # Upright
/// Upright (non-italic) font style in math.
///
/// ## Example
/// ```
/// $ upright(A) != A $
/// ```
///
/// ## Parameters
/// - body: Content (positional, required)
///   The piece of formula to style.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct UprightNode(pub Content);

#[node]
impl UprightNode {
    fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
        Ok(Self(args.expect("body")?).pack())
    }
}

impl LayoutMath for UprightNode {
    fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
        ctx.style(ctx.style.with_italic(false));
        self.0.layout_math(ctx)?;
        ctx.unstyle();
        Ok(())
    }
}

/// # Bold
/// Bold font style in math.
///
/// ## Example
/// ```
/// $ bold(A) := B^+ $
/// ```
///
/// ## Parameters
/// - body: Content (positional, required)
///   The piece of formula to style.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct BoldNode(pub Content);

#[node]
impl BoldNode {
    fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
        Ok(Self(args.expect("body")?).pack())
    }
}

impl LayoutMath for BoldNode {
    fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
        ctx.style(ctx.style.with_bold(true));
        self.0.layout_math(ctx)?;
        ctx.unstyle();
        Ok(())
    }
}

/// # Italic
/// Italic font style in math.
///
/// This is already the default.
///
/// ## Parameters
/// - body: Content (positional, required)
///   The piece of formula to style.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct ItalicNode(pub Content);

#[node]
impl ItalicNode {
    fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
        Ok(Self(args.expect("body")?).pack())
    }
}

impl LayoutMath for ItalicNode {
    fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
        ctx.style(ctx.style.with_italic(true));
        self.0.layout_math(ctx)?;
        ctx.unstyle();
        Ok(())
    }
}

/// # Serif
/// Serif (roman) font style in math.
///
/// This is already the default.
///
/// ## Parameters
/// - body: Content (positional, required)
///   The piece of formula to style.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct SerifNode(pub Content);

#[node]
impl SerifNode {
    fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
        Ok(Self(args.expect("body")?).pack())
    }
}

impl LayoutMath for SerifNode {
    fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
        ctx.style(ctx.style.with_variant(MathVariant::Serif));
        self.0.layout_math(ctx)?;
        ctx.unstyle();
        Ok(())
    }
}

/// # Sans-serif
/// Sans-serif font style in math.
///
/// ## Example
/// ```
/// $ sans(A B C) $
/// ```
///
/// ## Parameters
/// - body: Content (positional, required)
///   The piece of formula to style.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct SansNode(pub Content);

#[node]
impl SansNode {
    fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
        Ok(Self(args.expect("body")?).pack())
    }
}

impl LayoutMath for SansNode {
    fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
        ctx.style(ctx.style.with_variant(MathVariant::Sans));
        self.0.layout_math(ctx)?;
        ctx.unstyle();
        Ok(())
    }
}

/// # Calligraphic
/// Calligraphic font style in math.
///
/// ## Example
/// ```
/// Let $cal(P)$ be the set of ...
/// ```
///
/// ## Parameters
/// - body: Content (positional, required)
///   The piece of formula to style.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct CalNode(pub Content);

#[node]
impl CalNode {
    fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
        Ok(Self(args.expect("body")?).pack())
    }
}

impl LayoutMath for CalNode {
    fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
        ctx.style(ctx.style.with_variant(MathVariant::Cal));
        self.0.layout_math(ctx)?;
        ctx.unstyle();
        Ok(())
    }
}

/// # Fraktur
/// Fraktur font style in math.
///
/// ## Example
/// ```
/// $ frak(P) $
/// ```
///
/// ## Parameters
/// - body: Content (positional, required)
///   The piece of formula to style.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct FrakNode(pub Content);

#[node]
impl FrakNode {
    fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
        Ok(Self(args.expect("body")?).pack())
    }
}

impl LayoutMath for FrakNode {
    fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
        ctx.style(ctx.style.with_variant(MathVariant::Frak));
        self.0.layout_math(ctx)?;
        ctx.unstyle();
        Ok(())
    }
}

/// # Monospace
/// Monospace font style in math.
///
/// ## Example
/// ```
/// $ mono(x + y = z) $
/// ```
///
/// ## Parameters
/// - body: Content (positional, required)
///   The piece of formula to style.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct MonoNode(pub Content);

#[node]
impl MonoNode {
    fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
        Ok(Self(args.expect("body")?).pack())
    }
}

impl LayoutMath for MonoNode {
    fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
        ctx.style(ctx.style.with_variant(MathVariant::Mono));
        self.0.layout_math(ctx)?;
        ctx.unstyle();
        Ok(())
    }
}

/// # Blackboard Bold
/// Blackboard bold (double-struck) font style in math.
///
/// For uppercase latin letters, blackboard bold is additionally available
/// through [symbols](/docs/reference/math/) of the form `NN` and `RR`.
///
/// ## Example
/// ```
/// $ bb(b) $
/// $ bb(N) = NN $
/// $ f: NN -> RR $
/// ```
///
/// ## Parameters
/// - body: Content (positional, required) The piece of formula to style.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct BbNode(pub Content);

#[node]
impl BbNode {
    fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
        Ok(Self(args.expect("body")?).pack())
    }
}

impl LayoutMath for BbNode {
    fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
        ctx.style(ctx.style.with_variant(MathVariant::Bb));
        self.0.layout_math(ctx)?;
        ctx.unstyle();
        Ok(())
    }
}

/// The style in a formula.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct MathStyle {
    /// The style variant to select.
    pub variant: MathVariant,
    /// The size of the glyphs.
    pub size: MathSize,
    /// Affects the height of exponents.
    pub cramped: bool,
    /// Whether to use bold glyphs.
    pub bold: bool,
    /// Whether to use italic glyphs.
    pub italic: Smart<bool>,
}

impl MathStyle {
    /// This style, with the given `variant`.
    pub fn with_variant(self, variant: MathVariant) -> Self {
        Self { variant, ..self }
    }

    /// This style, with the given `size`.
    pub fn with_size(self, size: MathSize) -> Self {
        Self { size, ..self }
    }

    /// This style, with `cramped` set to the given value.
    pub fn with_cramped(self, cramped: bool) -> Self {
        Self { cramped, ..self }
    }

    /// This style, with `bold` set to the given value.
    pub fn with_bold(self, bold: bool) -> Self {
        Self { bold, ..self }
    }

    /// This style, with `italic` set to the given value.
    pub fn with_italic(self, italic: bool) -> Self {
        Self { italic: Smart::Custom(italic), ..self }
    }

    /// The style for subscripts in the current style.
    pub fn for_subscript(self) -> Self {
        self.for_superscript().with_cramped(true)
    }

    /// The style for superscripts in the current style.
    pub fn for_superscript(self) -> Self {
        self.with_size(match self.size {
            MathSize::Display | MathSize::Text => MathSize::Script,
            MathSize::Script | MathSize::ScriptScript => MathSize::ScriptScript,
        })
    }

    /// The style for numerators in the current style.
    pub fn for_numerator(self) -> Self {
        self.with_size(match self.size {
            MathSize::Display => MathSize::Text,
            MathSize::Text => MathSize::Script,
            MathSize::Script | MathSize::ScriptScript => MathSize::ScriptScript,
        })
    }

    /// The style for denominators in the current style.
    pub fn for_denominator(self) -> Self {
        self.for_numerator().with_cramped(true)
    }

    /// Apply the style to a character.
    pub fn styled_char(self, c: char) -> char {
        styled_char(self, c)
    }
}

/// The size of elements in a formula.
///
/// See the TeXbook p. 141.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum MathSize {
    /// Second-level sub- and superscripts.
    ScriptScript,
    /// Sub- and superscripts.
    Script,
    /// Math in text.
    Text,
    /// Math on its own line.
    Display,
}

impl MathSize {
    pub(super) fn factor(self, ctx: &MathContext) -> f64 {
        match self {
            Self::Display | Self::Text => 1.0,
            Self::Script => percent!(ctx, script_percent_scale_down),
            Self::ScriptScript => percent!(ctx, script_script_percent_scale_down),
        }
    }
}

/// A mathematical style variant, as defined by Unicode.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum MathVariant {
    Serif,
    Sans,
    Cal,
    Frak,
    Mono,
    Bb,
}

impl Default for MathVariant {
    fn default() -> Self {
        Self::Serif
    }
}

/// Select the correct styled math letter.
///
/// https://www.w3.org/TR/mathml-core/#new-text-transform-mappings
/// https://en.wikipedia.org/wiki/Mathematical_Alphanumeric_Symbols
pub(super) fn styled_char(style: MathStyle, c: char) -> char {
    use MathVariant::*;

    let (base, default_italic) = match c {
        'a'..='z' => ('a', true),
        'A'..='Z' => ('A', true),
        'α'..='ω' => ('α', false),
        'Α'..='Ω' => ('Α', false),
        '0'..='9' => ('0', false),
        '-' => return '−',
        _ => return c,
    };

    let tuple = (style.variant, style.bold, style.italic.unwrap_or(default_italic));
    let start = match c {
        // Latin upper.
        'A'..='Z' => match tuple {
            (Serif, false, false) => 0x0041,
            (Serif, true, false) => 0x1D400,
            (Serif, false, true) => 0x1D434,
            (Serif, true, true) => 0x1D468,
            (Sans, false, false) => 0x1D5A0,
            (Sans, true, false) => 0x1D5D4,
            (Sans, false, true) => 0x1D608,
            (Sans, true, true) => 0x1D63C,
            (Cal, false, _) => 0x1D49C,
            (Cal, true, _) => 0x1D4D0,
            (Frak, false, _) => 0x1D504,
            (Frak, true, _) => 0x1D56C,
            (Mono, _, _) => 0x1D670,
            (Bb, _, _) => 0x1D538,
        },

        // Latin lower.
        'a'..='z' => match tuple {
            (Serif, false, false) => 0x0061,
            (Serif, true, false) => 0x1D41A,
            (Serif, false, true) => 0x1D44E,
            (Serif, true, true) => 0x1D482,
            (Sans, false, false) => 0x1D5BA,
            (Sans, true, false) => 0x1D5EE,
            (Sans, false, true) => 0x1D622,
            (Sans, true, true) => 0x1D656,
            (Cal, false, _) => 0x1D4B6,
            (Cal, true, _) => 0x1D4EA,
            (Frak, false, _) => 0x1D51E,
            (Frak, true, _) => 0x1D586,
            (Mono, _, _) => 0x1D68A,
            (Bb, _, _) => 0x1D552,
        },

        // Greek upper.
        'Α'..='Ω' => match tuple {
            (Serif, false, false) => 0x0391,
            (Serif, true, false) => 0x1D6A8,
            (Serif, false, true) => 0x1D6E2,
            (Serif, true, true) => 0x1D71C,
            (Sans, _, false) => 0x1D756,
            (Sans, _, true) => 0x1D790,
            (Cal | Frak | Mono | Bb, _, _) => return c,
        },

        // Greek lower.
        'α'..='ω' => match tuple {
            (Serif, false, false) => 0x03B1,
            (Serif, true, false) => 0x1D6C2,
            (Serif, false, true) => 0x1D6FC,
            (Serif, true, true) => 0x1D736,
            (Sans, _, false) => 0x1D770,
            (Sans, _, true) => 0x1D7AA,
            (Cal | Frak | Mono | Bb, _, _) => return c,
        },

        // Numbers.
        '0'..='9' => match tuple {
            (Serif, false, _) => 0x0030,
            (Serif, true, _) => 0x1D7CE,
            (Bb, _, _) => 0x1D7D8,
            (Sans, false, _) => 0x1D7E2,
            (Sans, true, _) => 0x1D7EC,
            (Mono, _, _) => 0x1D7F6,
            (Cal | Frak, _, _) => return c,
        },

        _ => return c,
    };

    // Map and fix up codepoints that are defined in previous Unicode Blocks.
    let code = start + (c as u32 - base as u32);
    match code {
        0x1D455 => '\u{210E}',
        0x1D49D => '\u{212C}',
        0x1D4A0 => '\u{2130}',
        0x1D4A1 => '\u{2131}',
        0x1D4A3 => '\u{210B}',
        0x1D4A4 => '\u{2110}',
        0x1D4A7 => '\u{2112}',
        0x1D4A8 => '\u{2133}',
        0x1D4AD => '\u{211B}',
        0x1D4BA => '\u{212F}',
        0x1D4BC => '\u{210A}',
        0x1D4C4 => '\u{2134}',
        0x1D506 => '\u{212D}',
        0x1D50B => '\u{210C}',
        0x1D50C => '\u{2111}',
        0x1D515 => '\u{211C}',
        0x1D51D => '\u{2128}',
        0x1D53A => '\u{2102}',
        0x1D53F => '\u{210D}',
        0x1D545 => '\u{2115}',
        0x1D547 => '\u{2119}',
        0x1D548 => '\u{211A}',
        0x1D549 => '\u{211D}',
        0x1D551 => '\u{2124}',
        code => std::char::from_u32(code).unwrap(),
    }
}