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
|
use super::*;
const ROW_GAP: Em = Em::new(0.5);
const COL_GAP: Em = Em::new(0.75);
const VERTICAL_PADDING: Ratio = Ratio::new(0.1);
/// # Vector
/// A column vector.
///
/// ## Example
/// ```
/// $ vec(a, b, c) dot vec(1, 2, 3)
/// = a + 2b + 3c $
/// ```
///
/// ## Parameters
/// - elements: Content (positional, variadic)
/// The elements of the vector.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct VecNode(Vec<Content>);
#[node]
impl VecNode {
/// The delimiter to use.
///
/// # Example
/// ```
/// #set math.vec(delim: "[")
/// $ vec(1, 2) $
/// ```
pub const DELIM: Delimiter = Delimiter::Paren;
fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
Ok(Self(args.all()?).pack())
}
}
impl LayoutMath for VecNode {
fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
let delim = ctx.styles().get(Self::DELIM);
let frame = layout_vec_body(ctx, &self.0, Align::Center)?;
layout_delimiters(ctx, frame, Some(delim.open()), Some(delim.close()))
}
}
/// # Matrix
/// A matrix.
///
/// ## Example
/// ```
/// $ mat(1, 2; 3, 4) $
/// ```
///
/// ## Parameters
/// - rows: Array (positional, variadic)
/// An array of arrays with the rows of the matrix.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct MatNode(Vec<Vec<Content>>);
#[node]
impl MatNode {
/// The delimiter to use.
///
/// # Example
/// ```
/// #set math.mat(delim: "[")
/// $ mat(1, 2; 3, 4) $
/// ```
pub const DELIM: Delimiter = Delimiter::Paren;
fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
let mut rows = vec![];
let mut width = 0;
let values = args.all::<Spanned<Value>>()?;
if values.iter().all(|spanned| matches!(spanned.v, Value::Content(_))) {
rows = vec![values.into_iter().map(|spanned| spanned.v.display()).collect()];
} else {
for Spanned { v, span } in values {
let array = v.cast::<Array>().at(span)?;
let row: Vec<_> = array.into_iter().map(Value::display).collect();
width = width.max(row.len());
rows.push(row);
}
}
for row in &mut rows {
if row.len() < width {
row.resize(width, Content::empty());
}
}
Ok(Self(rows).pack())
}
}
impl LayoutMath for MatNode {
fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
let delim = ctx.styles().get(Self::DELIM);
let frame = layout_mat_body(ctx, &self.0)?;
layout_delimiters(ctx, frame, Some(delim.open()), Some(delim.close()))
}
}
/// # Cases
/// A case distinction.
///
/// ## Example
/// ```
/// $ f(x, y) := cases(
/// 1 "if" (x dot y)/2 <= 0,
/// 2 "if" x in NN,
/// 3 "if" x "is even",
/// 4 "else",
/// ) $
/// ```
///
/// ## Parameters
/// - branches: Content (positional, variadic)
/// The branches of the case distinction.
///
/// ## Category
/// math
#[func]
#[capable(LayoutMath)]
#[derive(Debug, Hash)]
pub struct CasesNode(Vec<Content>);
#[node]
impl CasesNode {
fn construct(_: &Vm, args: &mut Args) -> SourceResult<Content> {
Ok(Self(args.all()?).pack())
}
}
impl LayoutMath for CasesNode {
fn layout_math(&self, ctx: &mut MathContext) -> SourceResult<()> {
let frame = layout_vec_body(ctx, &self.0, Align::Left)?;
layout_delimiters(ctx, frame, Some('{'), None)
}
}
/// A vector / matrix delimiter.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Delimiter {
Paren,
Bracket,
Brace,
Bar,
DoubleBar,
}
impl Delimiter {
/// The delimiter's opening character.
fn open(self) -> char {
match self {
Self::Paren => '(',
Self::Bracket => '[',
Self::Brace => '{',
Self::Bar => '|',
Self::DoubleBar => '‖',
}
}
/// The delimiter's closing character.
fn close(self) -> char {
match self {
Self::Paren => ')',
Self::Bracket => ']',
Self::Brace => '}',
Self::Bar => '|',
Self::DoubleBar => '‖',
}
}
}
castable! {
Delimiter,
/// Delimit the vector with parentheses.
"(" => Self::Paren,
/// Delimit the vector with brackets.
"[" => Self::Bracket,
/// Delimit the vector with curly braces.
"{" => Self::Brace,
/// Delimit the vector with vertical bars.
"|" => Self::Bar,
/// Delimit the vector with double vertical bars.
"||" => Self::DoubleBar,
}
/// Layout the inner contents of a vector.
fn layout_vec_body(
ctx: &mut MathContext,
column: &[Content],
align: Align,
) -> SourceResult<Frame> {
let gap = ROW_GAP.scaled(ctx);
ctx.style(ctx.style.for_denominator());
let mut flat = vec![];
for element in column {
flat.push(ctx.layout_row(element)?);
}
ctx.unstyle();
Ok(stack(ctx, flat, align, gap, 0))
}
/// Layout the inner contents of a matrix.
fn layout_mat_body(ctx: &mut MathContext, rows: &[Vec<Content>]) -> SourceResult<Frame> {
let row_gap = ROW_GAP.scaled(ctx);
let col_gap = COL_GAP.scaled(ctx);
let ncols = rows.first().map_or(0, |row| row.len());
let nrows = rows.len();
if ncols == 0 || nrows == 0 {
return Ok(Frame::new(Size::zero()));
}
let mut rcols = vec![Abs::zero(); ncols];
let mut rrows = vec![Abs::zero(); nrows];
ctx.style(ctx.style.for_denominator());
let mut cols = vec![vec![]; ncols];
for (row, rrow) in rows.iter().zip(&mut rrows) {
for ((cell, rcol), col) in row.iter().zip(&mut rcols).zip(&mut cols) {
let cell = ctx.layout_row(cell)?;
rcol.set_max(cell.width());
rrow.set_max(cell.height());
col.push(cell);
}
}
ctx.unstyle();
let width = rcols.iter().sum::<Abs>() + col_gap * (ncols - 1) as f64;
let height = rrows.iter().sum::<Abs>() + row_gap * (nrows - 1) as f64;
let size = Size::new(width, height);
let mut frame = Frame::new(size);
let mut x = Abs::zero();
for (col, &rcol) in cols.into_iter().zip(&rcols) {
let points = alignments(&col);
let mut y = Abs::zero();
for (cell, &rrow) in col.into_iter().zip(&rrows) {
let cell = cell.to_aligned_frame(ctx, &points, Align::Center);
let pos = Point::new(
x + (rcol - cell.width()) / 2.0,
y + (rrow - cell.height()) / 2.0,
);
frame.push_frame(pos, cell);
y += rrow + row_gap;
}
x += rcol + col_gap;
}
Ok(frame)
}
/// Layout the outer wrapper around a vector's or matrices' body.
fn layout_delimiters(
ctx: &mut MathContext,
mut frame: Frame,
left: Option<char>,
right: Option<char>,
) -> SourceResult<()> {
let axis = scaled!(ctx, axis_height);
let short_fall = DELIM_SHORT_FALL.scaled(ctx);
let height = frame.height();
let target = height + VERTICAL_PADDING.of(height);
frame.set_baseline(height / 2.0 + axis);
if let Some(left) = left {
ctx.push(GlyphFragment::new(ctx, left).stretch_vertical(ctx, target, short_fall));
}
ctx.push(frame);
if let Some(right) = right {
ctx.push(
GlyphFragment::new(ctx, right).stretch_vertical(ctx, target, short_fall),
);
}
Ok(())
}
|