encoder.dart
9.95 KB
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
import 'dart:convert';
import 'package:collection/collection.dart';
import '../../ast/syntax_tree.dart';
import '../../ast/types.dart';
import '../../parser/tex/functions.dart';
import '../../parser/tex/settings.dart';
import '../../utils/alpha_numeric.dart';
import '../encoder.dart';
import 'functions.dart';
final texEncodingCache = Expando<EncodeResult>('Tex encoding results');
/// Encodes [GreenNode] into TeX
class TexEncoder extends Converter<GreenNode, String> {
@override
String convert(GreenNode input) => input.encodeTeX();
}
extension TexEncoderExt on GreenNode {
/// Encodes the node into TeX
String encodeTeX({TexEncodeConf conf = const TexEncodeConf()}) =>
encodeTex(this).stringify(conf);
}
extension ListTexEncoderExt on List<GreenNode> {
/// Encode the list of nodes into TeX
String encodeTex() =>
this.wrapWithEquationRow().encodeTeX(conf: TexEncodeConf().mathParam());
}
EncodeResult encodeTex(GreenNode node) {
final cachedRes = texEncodingCache[node];
if (cachedRes != null) return cachedRes;
final optimization = optimizationEntries
.firstWhereOrNull((entry) => entry.matcher.match(node));
if (optimization != null) {
optimization.optimize(node);
final cachedRes = texEncodingCache[node];
if (cachedRes != null) return cachedRes;
}
final type = node.runtimeType;
final encoderFunction = encoderFunctions[type];
if (encoderFunction == null) {
return NonStrictEncodeResult('unknown node type',
'Unrecognized node type $type encountered during encoding');
}
final encodeResult = encoderFunction(node);
texEncodingCache[node] = encodeResult;
return encodeResult;
}
class TexEncodeConf extends EncodeConf {
final Mode mode;
final bool removeRowBracket;
const TexEncodeConf({
this.mode = Mode.math,
this.removeRowBracket = false,
Strict strict = Strict.warn,
StrictFun? strictFun,
}) : super(strict: strict, strictFun: strictFun);
static const mathConf = TexEncodeConf();
static const mathParamConf = TexEncodeConf(removeRowBracket: true);
static const textConf = TexEncodeConf(mode: Mode.text);
static const textParamConf =
TexEncodeConf(mode: Mode.text, removeRowBracket: true);
TexEncodeConf math() {
if (mode == Mode.math && !removeRowBracket) return this;
return copyWith(mode: Mode.math, removeRowBracket: false);
}
TexEncodeConf mathParam() {
if (mode == Mode.math && removeRowBracket) return this;
return copyWith(mode: Mode.math, removeRowBracket: true);
}
TexEncodeConf text() {
if (mode == Mode.text && !removeRowBracket) return this;
return copyWith(mode: Mode.text, removeRowBracket: false);
}
TexEncodeConf textParam() {
if (mode == Mode.text && removeRowBracket) return this;
return copyWith(mode: Mode.text, removeRowBracket: true);
}
TexEncodeConf param() {
if (removeRowBracket) return this;
return copyWith(removeRowBracket: true);
}
TexEncodeConf ord() {
if (!removeRowBracket) return this;
return copyWith(removeRowBracket: false);
}
TexEncodeConf copyWith({
Mode? mode,
bool? removeRowBracket,
Strict? strict,
StrictFun? strictFun,
}) =>
TexEncodeConf(
mode: mode ?? this.mode,
removeRowBracket: removeRowBracket ?? this.removeRowBracket,
strict: strict ?? this.strict,
strictFun: strictFun ?? this.strictFun,
);
}
String _handleArg(dynamic arg, EncodeConf conf) {
if (arg == null) return '';
if (arg is EncodeResult) {
return arg.stringify(conf);
}
if (arg is GreenNode) {
return encodeTex(arg).stringify(conf);
}
if (arg is String) return arg;
return arg.toString();
}
String _handleAndWrapArg(dynamic arg, EncodeConf conf) {
final string = _handleArg(arg, conf);
return string.length == 1 || _isSingleSymbol(arg) ? string : '{$string}';
}
bool _isSingleSymbol(dynamic arg) {
while (true) {
if (arg is TransparentTexEncodeResult && arg.children.length == 1) {
arg = arg.children.first;
} else if (arg is EquationRowTexEncodeResult && arg.children.length == 1) {
arg = arg.children.first;
} else if (arg is EquationRowNode && arg.children.length == 1) {
arg = arg.children.first;
} else {
break;
}
}
if (arg is String) return true;
if (arg is StaticEncodeResult) return true;
return false;
}
class TexCommandEncodeResult extends EncodeResult {
final String command;
/// Accepted type: [Null], [String], [EncodeResult], [GreenNode]
final List<dynamic> args;
late final FunctionSpec spec = functions[command]!;
final int? _numArgs;
late final int numArgs = _numArgs ?? spec.numArgs;
final int? _numOptionalArgs;
late final int numOptionalArgs = _numOptionalArgs ?? spec.numOptionalArgs;
late final List<Mode?> argModes = spec.argModes ??
List.filled(numArgs + numOptionalArgs, null, growable: false);
TexCommandEncodeResult({
required this.command,
required this.args,
int? numArgs,
int? numOptionalArgs,
}) : _numArgs = numArgs,
_numOptionalArgs = numOptionalArgs;
@override
String stringify(TexEncodeConf conf) {
assert(this.numArgs >= this.numOptionalArgs);
if (!spec.allowedInMath && conf.mode == Mode.math) {
conf.reportNonstrict('command mode mismatch',
'Text-only command $command occured in math encoding enviroment');
}
if (!spec.allowedInText && conf.mode == Mode.text) {
conf.reportNonstrict('command mode mismatch',
'Math-only command $command occured in text encoding environment');
}
final argString = Iterable.generate(
numArgs + numOptionalArgs,
(index) {
final mode = argModes[index] ?? conf.mode;
final string = _handleArg(args[index],
mode == Mode.math ? conf.mathParam() : conf.textParam());
if (index < numOptionalArgs) {
return string.isEmpty ? '' : '[$string]';
} else {
return '{$string}'; // TODO optimize
}
},
).join();
if (argString.isNotEmpty && (argString[0] == '[' || argString[0] == '{')) {
return '$command$argString';
} else {
return '$command $argString';
}
}
}
extension TexEncoderJoinerExt on Iterable<String> {
String texJoin() {
final iterator = this.iterator..moveNext();
final length = this.length;
return Iterable.generate(length, (index) {
if (index == length - 1) return iterator.current;
final current = iterator.current;
final next = (iterator..moveNext()).current;
if (current.length == 1 ||
(next.isNotEmpty && !isAlphaNumericUnit(next[0]) && next[0] != '*') ||
(current.isNotEmpty && current[current.length - 1] == '\}')) {
return current;
}
return '$current ';
}).join();
}
}
class EquationRowTexEncodeResult extends EncodeResult {
final List<dynamic> children;
const EquationRowTexEncodeResult(this.children);
@override
String stringify(TexEncodeConf conf) {
final content = Iterable.generate(children.length, (index) {
final dynamic child = children[index];
if (index == children.length - 1 && child is TexModeCommandEncodeResult) {
return _handleArg(child, conf.param());
}
return _handleArg(child, conf.ord());
}).texJoin();
if (conf.removeRowBracket == true) {
return content;
} else {
return '{$content}';
}
}
}
class TransparentTexEncodeResult extends EncodeResult {
final List<dynamic> children;
const TransparentTexEncodeResult(this.children);
@override
String stringify(TexEncodeConf conf) =>
children.map((dynamic child) => _handleArg(child, conf.ord())).texJoin();
}
class ModeDependentEncodeResult extends EncodeResult {
final dynamic text;
final dynamic math;
const ModeDependentEncodeResult({this.text, this.math});
@override
String stringify(TexEncodeConf conf) =>
_handleArg(conf.mode == Mode.math ? math : text, conf);
static String _handleArg(dynamic arg, TexEncodeConf conf) {
if (arg == null) return '';
if (arg is GreenNode) return arg.encodeTeX(conf: conf);
if (arg is EncodeResult) return arg.stringify(conf);
return arg.toString();
}
}
class TexModeCommandEncodeResult extends EncodeResult {
final String command;
final List<dynamic> children;
const TexModeCommandEncodeResult(
{required this.command, required this.children});
@override
String stringify(TexEncodeConf conf) {
final content = Iterable.generate(children.length, (index) {
final dynamic child = children[index];
if (index == children.length - 1 && child is TexModeCommandEncodeResult) {
return _handleArg(child, conf.param());
}
return _handleArg(child, conf.ord());
}).texJoin();
if (conf.removeRowBracket == true) {
return '$command $content';
} else {
return '{$command $content}';
}
}
}
class TexMultiscriptEncodeResult extends EncodeResult {
final dynamic base;
final dynamic sub;
final dynamic sup;
final dynamic presub;
final dynamic presup;
const TexMultiscriptEncodeResult({
required this.base,
this.sub,
this.sup,
this.presub,
this.presup,
});
@override
String stringify(TexEncodeConf conf) {
if (conf.mode != Mode.math) {
conf.reportNonstrict('command mode mismatch',
'Sub/sup scripts occured in text encoding environment');
}
if (presub != null || presup != null) {
conf.reportNonstrict(
'imprecise encoding',
'Prescripts are not supported in vanilla KaTeX',
);
}
return [
if (presub != null || presup != null) '{}',
if (presub != null) ...[
'_',
_handleAndWrapArg(presub, conf.param()),
],
if (presup != null) ...[
'^',
_handleAndWrapArg(presup, conf.param()),
],
_handleAndWrapArg(base, conf.param()),
if (sub != null) ...[
'_',
_handleAndWrapArg(sub, conf.param()),
],
if (sup != null) ...[
'^',
_handleAndWrapArg(sup, conf.param()),
],
].texJoin();
}
}