@mlightcad/mtext-parser 1.5.1 → 1.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/parser.ts CHANGED
@@ -1,2116 +1,2167 @@
1
- /**
2
- * Token types used in MText parsing
3
- */
4
- export enum TokenType {
5
- /** No token */
6
- NONE = 0,
7
- /** Word token with string data */
8
- WORD = 1,
9
- /** Stack token with [numerator, denominator, type] data */
10
- STACK = 2,
11
- /** Space token with no data */
12
- SPACE = 3,
13
- /** Non-breaking space token with no data */
14
- NBSP = 4,
15
- /** Tab token with no data */
16
- TABULATOR = 5,
17
- /** New paragraph token with no data */
18
- NEW_PARAGRAPH = 6,
19
- /** New column token with no data */
20
- NEW_COLUMN = 7,
21
- /** Wrap at dimension line token with no data */
22
- WRAP_AT_DIMLINE = 8,
23
- /** Properties changed token with string data (full command) */
24
- PROPERTIES_CHANGED = 9,
25
- /** AutoCAD percent-sign symbol code (`%%c`, `%%d`, `%%p`, `%%ddd`, `%%%`) */
26
- PERCENT_SYMBOL = 10,
27
- }
28
-
29
- /**
30
- * AutoCAD percent-sign symbol emitted when {@link MTextParserOptions.yieldPercentSymbols}
31
- * is enabled.
32
- */
33
- export type PercentSymbolData =
34
- | {
35
- kind: 'named';
36
- /** Percent code letter: `%%c`, `%%d`, or `%%p`. */
37
- code: 'c' | 'd' | 'p';
38
- /** Unicode expansion used for display (e.g. `%%c` → `Ø`). */
39
- char: string;
40
- }
41
- | {
42
- kind: 'numeric';
43
- /** Decimal code from `%%ddd` (0–255). */
44
- charCode: number;
45
- /** `String.fromCharCode(charCode)`. */
46
- char: string;
47
- }
48
- | {
49
- kind: 'literal';
50
- /** Literal percent from `%%%`. */
51
- char: '%';
52
- };
53
-
54
- /**
55
- * Represents a factor value that can be either absolute or relative.
56
- * Used for properties like height, width, and character tracking in MText formatting.
57
- */
58
- export interface FactorValue {
59
- /** The numeric value of the factor */
60
- value: number;
61
- /** Whether the value is relative (true) or absolute (false) */
62
- isRelative: boolean;
63
- }
64
-
65
- /**
66
- * Format properties of MText word tokens.
67
- * This interface defines all the formatting properties that can be applied to MText content,
68
- * including text styling, colors, alignment, font properties, and paragraph formatting.
69
- */
70
- export interface Properties {
71
- /** Whether text is underlined */
72
- underline?: boolean;
73
- /** Whether text has an overline */
74
- overline?: boolean;
75
- /** Whether text has strike-through */
76
- strikeThrough?: boolean;
77
- /** AutoCAD Color Index (ACI) color value (0-256), or null if not set */
78
- aci?: number | null;
79
- /** RGB color tuple [r, g, b], or null if not set */
80
- rgb?: RGB | null;
81
- /** Line alignment for the text */
82
- align?: MTextLineAlignment;
83
- /** Font face properties including family, style, and weight */
84
- fontFace?: FontFace;
85
- /** Capital letter height factor (can be relative or absolute) */
86
- capHeight?: FactorValue;
87
- /** Character width factor (can be relative or absolute) */
88
- widthFactor?: FactorValue;
89
- /** Character tracking factor for spacing between characters (can be relative or absolute) */
90
- charTrackingFactor?: FactorValue;
91
- /** Oblique angle in degrees for text slant */
92
- oblique?: number;
93
- /** Paragraph formatting properties (partial to allow selective updates) */
94
- paragraph?: Partial<ParagraphProperties>;
95
- }
96
-
97
- /**
98
- * Represents a change in MText properties, including the command, the changed properties, and the context depth.
99
- */
100
- export interface ChangedProperties {
101
- /**
102
- * The property command that triggered the change (e.g., 'L', 'C', 'f').
103
- * The command will be undefined if it is to restore context.
104
- */
105
- command: string | undefined;
106
- /**
107
- * The set of properties that have changed as a result of the command.
108
- */
109
- changes: Properties;
110
- /**
111
- * The current context stack depth when the property change occurs.
112
- * - 0: The change is global (applies outside of any `{}` block).
113
- * - >0: The change is local (applies within one or more nested `{}` blocks).
114
- */
115
- depth: number; // 0 = global, >0 = local
116
- }
117
-
118
- /**
119
- * Type for token data based on token type
120
- */
121
- export type TokenData = {
122
- [TokenType.NONE]: null;
123
- [TokenType.WORD]: string;
124
- [TokenType.STACK]: [string, string, string];
125
- [TokenType.SPACE]: null;
126
- [TokenType.NBSP]: null;
127
- [TokenType.TABULATOR]: null;
128
- [TokenType.NEW_PARAGRAPH]: null;
129
- [TokenType.NEW_COLUMN]: null;
130
- [TokenType.WRAP_AT_DIMLINE]: null;
131
- [TokenType.PROPERTIES_CHANGED]: ChangedProperties;
132
- [TokenType.PERCENT_SYMBOL]: PercentSymbolData;
133
- };
134
-
135
- /**
136
- * Line alignment options for MText
137
- */
138
- export enum MTextLineAlignment {
139
- /** Align text to bottom */
140
- BOTTOM = 0,
141
- /** Align text to middle */
142
- MIDDLE = 1,
143
- /** Align text to top */
144
- TOP = 2,
145
- }
146
-
147
- /**
148
- * Paragraph alignment options for MText
149
- */
150
- export enum MTextParagraphAlignment {
151
- /** Default alignment */
152
- DEFAULT = 0,
153
- /** Left alignment */
154
- LEFT = 1,
155
- /** Right alignment */
156
- RIGHT = 2,
157
- /** Center alignment */
158
- CENTER = 3,
159
- /** Justified alignment */
160
- JUSTIFIED = 4,
161
- /** Distributed alignment */
162
- DISTRIBUTED = 5,
163
- }
164
-
165
- /**
166
- * Text stroke options for MText
167
- */
168
- export enum MTextStroke {
169
- /** No stroke */
170
- NONE = 0,
171
- /** Underline stroke */
172
- UNDERLINE = 1,
173
- /** Overline stroke */
174
- OVERLINE = 2,
175
- /** Strike-through stroke */
176
- STRIKE_THROUGH = 4,
177
- }
178
-
179
- /**
180
- * RGB color tuple
181
- */
182
- export type RGB = [number, number, number];
183
-
184
- /**
185
- * Font style type
186
- */
187
- export type FontStyle = 'Regular' | 'Italic';
188
-
189
- /**
190
- * Font face properties
191
- */
192
- export interface FontFace {
193
- /** Font family name */
194
- family: string;
195
- /** Font style (e.g., 'Regular', 'Italic') */
196
- style: FontStyle;
197
- /** Font weight (e.g., 400 for normal, 700 for bold) */
198
- weight: number;
199
- }
200
-
201
- /**
202
- * Paragraph properties
203
- */
204
- export interface ParagraphProperties {
205
- /** Indentation value */
206
- indent: number;
207
- /** Left margin value */
208
- left: number;
209
- /** Right margin value */
210
- right: number;
211
- /** Paragraph alignment */
212
- align: MTextParagraphAlignment;
213
- /** Tab stop positions and types */
214
- tabs: (number | string)[];
215
- }
216
-
217
- /**
218
- * Special character encoding mapping
219
- */
220
- const SPECIAL_CHAR_ENCODING: Record<string, string> = {
221
- c: 'Ø',
222
- d: '°',
223
- p: '±',
224
- '%': '%',
225
- };
226
-
227
- /**
228
- * Character to paragraph alignment mapping
229
- */
230
- const CHAR_TO_ALIGN: Record<string, MTextParagraphAlignment> = {
231
- l: MTextParagraphAlignment.LEFT,
232
- r: MTextParagraphAlignment.RIGHT,
233
- c: MTextParagraphAlignment.CENTER,
234
- j: MTextParagraphAlignment.JUSTIFIED,
235
- d: MTextParagraphAlignment.DISTRIBUTED,
236
- };
237
-
238
- /**
239
- * Convert RGB tuple to integer color value
240
- * @param rgb - RGB color tuple
241
- * @returns Integer color value
242
- */
243
- export function rgb2int(rgb: RGB): number {
244
- const [r, g, b] = rgb;
245
- return (r << 16) | (g << 8) | b;
246
- }
247
-
248
- /**
249
- * Convert integer color value to RGB tuple
250
- * @param value - Integer color value
251
- * @returns RGB color tuple
252
- */
253
- export function int2rgb(value: number): RGB {
254
- const r = (value >> 16) & 0xff;
255
- const g = (value >> 8) & 0xff;
256
- const b = value & 0xff;
257
- return [r, g, b];
258
- }
259
-
260
- function clampColorChannel(value: number): number {
261
- return Math.max(0, Math.min(255, Math.round(value)));
262
- }
263
-
264
- function normalizeColorNumber(color: number): number {
265
- return Math.max(0, Math.min(0xffffff, Math.round(color)));
266
- }
267
-
268
- function colorNumberToHex(color: number | null): string | null {
269
- if (color === null) return null;
270
- return `#${normalizeColorNumber(color).toString(16).padStart(6, '0')}`;
271
- }
272
-
273
- function normalizeHexColor(value: string | null | undefined): string | null {
274
- if (!value) return null;
275
- const normalized = value.trim().toLowerCase();
276
- if (/^#[0-9a-f]{6}$/.test(normalized)) return normalized;
277
- if (/^[0-9a-f]{6}$/.test(normalized)) return `#${normalized}`;
278
- if (/^#[0-9a-f]{3}$/.test(normalized)) {
279
- const r = normalized[1];
280
- const g = normalized[2];
281
- const b = normalized[3];
282
- return `#${r}${r}${g}${g}${b}${b}`;
283
- }
284
- if (/^[0-9a-f]{3}$/.test(normalized)) {
285
- const r = normalized[0];
286
- const g = normalized[1];
287
- const b = normalized[2];
288
- return `#${r}${r}${g}${g}${b}${b}`;
289
- }
290
- return null;
291
- }
292
-
293
- function cssColorToRgbValue(value: string | null | undefined): number | null {
294
- if (!value) return null;
295
- const raw = value.trim().toLowerCase();
296
- if (raw === 'transparent') return null;
297
-
298
- const hex = normalizeHexColor(raw);
299
- if (hex) {
300
- return normalizeColorNumber(Number.parseInt(hex.slice(1), 16));
301
- }
302
-
303
- const fnMatch = raw.match(/^rgba?\((.*)\)$/);
304
- if (!fnMatch) return null;
305
-
306
- const parts = fnMatch[1]
307
- .replace(/\s*\/\s*/g, ' ')
308
- .split(/[,\s]+/)
309
- .map(p => p.trim())
310
- .filter(Boolean);
311
-
312
- if (parts.length < 3) return null;
313
-
314
- const toChannel = (token: string): number => {
315
- if (token.endsWith('%')) {
316
- const percent = Number.parseFloat(token.slice(0, -1));
317
- return clampColorChannel((percent / 100) * 255);
318
- }
319
- const num = Number.parseFloat(token);
320
- return clampColorChannel(num);
321
- };
322
-
323
- const r = toChannel(parts[0]);
324
- const g = toChannel(parts[1]);
325
- const b = toChannel(parts[2]);
326
- return rgb2int([r, g, b]);
327
- }
328
-
329
- /**
330
- * Escape DXF line endings
331
- * @param text - Text to escape
332
- * @returns Escaped text
333
- */
334
- export function escapeDxfLineEndings(text: string): string {
335
- return text.replace(/\r\n|\r|\n/g, '\\P');
336
- }
337
-
338
- /**
339
- * Check if text contains inline formatting codes
340
- * @param text - Text to check
341
- * @returns True if text contains formatting codes
342
- */
343
- export function hasInlineFormattingCodes(text: string): boolean {
344
- return text.replace(/\\P/g, '').replace(/\\~/g, '').includes('\\');
345
- }
346
-
347
- /**
348
- * Extracts all unique font names used in an MText string.
349
- * This function searches for font commands in the format \f{fontname}| or \f{fontname}; and returns a set of unique font names.
350
- * Font names are converted to lowercase to ensure case-insensitive uniqueness.
351
- *
352
- * @param mtext - The MText string to analyze for font names
353
- * @param removeExtension - Whether to remove font file extensions (e.g., .ttf, .shx) from font names. Defaults to false.
354
- * @returns A Set containing all unique font names found in the MText string, converted to lowercase
355
- * @example
356
- * ```ts
357
- * const mtext = "\\fArial.ttf|Hello\\fTimes New Roman.otf|World";
358
- * const fonts = getFonts(mtext, true);
359
- * // Returns: Set(2) { "arial", "times new roman" }
360
- * ```
361
- */
362
- export function getFonts(mtext: string, removeExtension: boolean = false) {
363
- const fonts: Set<string> = new Set();
364
- const regex = /\\[fF](.*?)[;|]/g;
365
-
366
- [...mtext.matchAll(regex)].forEach(match => {
367
- let fontName = match[1].toLowerCase();
368
- if (removeExtension) {
369
- fontName = fontName.replace(/\.(ttf|otf|woff|shx)$/, '');
370
- }
371
- fonts.add(fontName);
372
- });
373
-
374
- return fonts;
375
- }
376
-
377
- /**
378
- * ContextStack manages a stack of MTextContext objects for character-level formatting.
379
- *
380
- * - Character-level formatting (underline, color, font, etc.) is scoped to `{}` blocks and managed by the stack.
381
- * - Paragraph-level formatting (\p) is not scoped, but when a block ends, any paragraph property changes are merged into the parent context.
382
- * - On pop, paragraph properties from the popped context are always merged into the new top context.
383
- */
384
- class ContextStack {
385
- private stack: MTextContext[] = [];
386
-
387
- /**
388
- * Creates a new ContextStack with an initial context.
389
- * @param initial The initial MTextContext to use as the base of the stack.
390
- */
391
- constructor(initial: MTextContext) {
392
- this.stack.push(initial);
393
- }
394
-
395
- /**
396
- * Pushes a copy of the given context onto the stack.
397
- * @param ctx The MTextContext to push (copied).
398
- */
399
- push(ctx: MTextContext) {
400
- this.stack.push(ctx);
401
- }
402
-
403
- /**
404
- * Pops the top context from the stack and merges its paragraph properties into the new top context.
405
- * If only one context remains, nothing is popped.
406
- * @returns The popped MTextContext, or undefined if the stack has only one context.
407
- */
408
- pop(): MTextContext | undefined {
409
- if (this.stack.length <= 1) return undefined;
410
- const popped = this.stack.pop()!;
411
- // Merge paragraph properties into the new top context
412
- const top = this.stack[this.stack.length - 1];
413
- if (JSON.stringify(top.paragraph) !== JSON.stringify(popped.paragraph)) {
414
- top.paragraph = { ...popped.paragraph };
415
- }
416
- return popped;
417
- }
418
-
419
- /**
420
- * Returns the current (top) context on the stack.
421
- */
422
- get current(): MTextContext {
423
- return this.stack[this.stack.length - 1];
424
- }
425
-
426
- /**
427
- * Returns the current stack depth (number of nested blocks), not counting the root context.
428
- */
429
- get depth(): number {
430
- return this.stack.length - 1;
431
- }
432
-
433
- /**
434
- * Returns the root (bottom) context, which represents the global formatting state.
435
- * Used for paragraph property application.
436
- */
437
- get root(): MTextContext {
438
- return this.stack[0];
439
- }
440
-
441
- /**
442
- * Replaces the current (top) context with the given context.
443
- * @param ctx The new context to set as the current context.
444
- */
445
- setCurrent(ctx: MTextContext) {
446
- this.stack[this.stack.length - 1] = ctx;
447
- }
448
- }
449
-
450
- /**
451
- * Configuration options for the MText parser.
452
- * These options control how the parser behaves during tokenization and property handling.
453
- */
454
- export interface MTextParserOptions {
455
- /**
456
- * Whether to yield PROPERTIES_CHANGED tokens when formatting properties change.
457
- * When true, the parser will emit tokens whenever properties like color, font, or alignment change.
458
- * When false, property changes are applied silently to the context without generating tokens.
459
- * @default false
460
- */
461
- yieldPropertyCommands?: boolean;
462
- /**
463
- * Whether to reset paragraph parameters when encountering a new paragraph token.
464
- * When true, paragraph properties (indent, margins, alignment, tab stops) are reset to defaults
465
- * at the start of each new paragraph.
466
- * @default false
467
- */
468
- resetParagraphParameters?: boolean;
469
- /**
470
- * Whether to emit {@link TokenType.PERCENT_SYMBOL} tokens for AutoCAD `%%` symbol
471
- * codes instead of expanding them into {@link TokenType.WORD} characters.
472
- * @default false
473
- */
474
- yieldPercentSymbols?: boolean;
475
- /**
476
- * Custom decoder function for MIF (Multibyte Interchange Format) codes.
477
- * If provided, this function will be used instead of the default decodeMultiByteChar.
478
- * The function receives the hex code string and should return the decoded character.
479
- * @param hex - Hex code string (e.g., "C4E3" or "1A2B3")
480
- * @returns Decoded character or empty square (▯) if invalid
481
- * @default undefined (uses default decoder)
482
- */
483
- mifDecoder?: (hex: string) => string;
484
- /**
485
- * The length of MIF hex codes to parse. MIF codes in AutoCAD can vary in length
486
- * depending on the specific SHX big font used (typically 4 or 5 digits).
487
- * If not specified, the parser will try to auto-detect the length by attempting
488
- * to match 4 digits first, then 5 digits if needed.
489
- * @default undefined (auto-detect)
490
- */
491
- mifCodeLength?: 4 | 5 | 'auto';
492
- }
493
-
494
- /**
495
- * Main parser class for MText content
496
- */
497
- export class MTextParser {
498
- private scanner: TextScanner;
499
- private ctxStack: ContextStack;
500
- private continueStroke: boolean = false;
501
- private yieldPropertyCommands: boolean;
502
- private resetParagraphParameters: boolean;
503
- private yieldPercentSymbols: boolean;
504
- private inStackContext: boolean = false;
505
- private mifDecoder: (hex: string) => string;
506
- private mifCodeLength: 4 | 5 | 'auto';
507
-
508
- /**
509
- * Creates a new MTextParser instance
510
- * @param content - The MText content to parse
511
- * @param ctx - Optional initial MText context
512
- * @param options - Parser options
513
- */
514
- constructor(content: string, ctx?: MTextContext, options: MTextParserOptions = {}) {
515
- this.scanner = new TextScanner(content);
516
- const initialCtx = ctx ?? new MTextContext();
517
- this.ctxStack = new ContextStack(initialCtx);
518
- this.yieldPropertyCommands = options.yieldPropertyCommands ?? false;
519
- this.resetParagraphParameters = options.resetParagraphParameters ?? false;
520
- this.yieldPercentSymbols = options.yieldPercentSymbols ?? false;
521
- this.mifDecoder = options.mifDecoder ?? this.decodeMultiByteChar.bind(this);
522
- this.mifCodeLength = options.mifCodeLength ?? 'auto';
523
- }
524
-
525
- /**
526
- * Decode multi-byte character from hex code
527
- * @param hex - Hex code string (e.g. "C4E3" or "1A2B3")
528
- * @returns Decoded character or empty square if invalid
529
- */
530
- private decodeMultiByteChar(hex: string): string {
531
- try {
532
- // For 5-digit codes, return placeholder directly
533
- if (hex.length === 5) {
534
- const prefix = hex[0];
535
-
536
- // Notes:
537
- // I know AutoCAD uses prefix 1 for Shift-JIS, 2 for big5, and 5 for gbk.
538
- // But I don't know whether there are other prefixes and their meanings.
539
- let encoding = 'gbk';
540
- if (prefix === '1') {
541
- encoding = 'shift-jis';
542
- } else if (prefix === '2') {
543
- encoding = 'big5';
544
- }
545
- const bytes = new Uint8Array([
546
- parseInt(hex.substr(1, 2), 16),
547
- parseInt(hex.substr(3, 2), 16),
548
- ]);
549
- const decoder = new TextDecoder(encoding);
550
- const result = decoder.decode(bytes);
551
- return result;
552
- } else if (hex.length === 4) {
553
- // For 4-digit hex codes, decode as 2-byte character
554
- const bytes = new Uint8Array([
555
- parseInt(hex.substr(0, 2), 16),
556
- parseInt(hex.substr(2, 2), 16),
557
- ]);
558
-
559
- // Try GBK first
560
- const gbkDecoder = new TextDecoder('gbk');
561
- const gbkResult = gbkDecoder.decode(bytes);
562
- if (gbkResult !== '▯') {
563
- return gbkResult;
564
- }
565
-
566
- // Try BIG5 if GBK fails
567
- const big5Decoder = new TextDecoder('big5');
568
- const big5Result = big5Decoder.decode(bytes);
569
- if (big5Result !== '▯') {
570
- return big5Result;
571
- }
572
- }
573
-
574
- return '▯';
575
- } catch {
576
- return '▯';
577
- }
578
- }
579
-
580
- /**
581
- * Extract MIF hex code from scanner
582
- * @param length - The length of the hex code to extract (4 or 5), or 'auto' to detect
583
- * @returns The extracted hex code, or null if not found
584
- */
585
- private extractMifCode(length: 4 | 5 | 'auto'): string | null {
586
- if (length === 'auto') {
587
- // Try 5 digits first if available, then fall back to 4 digits
588
- const code5 = this.scanner.tail.match(/^[0-9A-Fa-f]{5}/)?.[0];
589
- if (code5) {
590
- return code5;
591
- }
592
- const code4 = this.scanner.tail.match(/^[0-9A-Fa-f]{4}/)?.[0];
593
- if (code4) {
594
- return code4;
595
- }
596
- return null;
597
- } else {
598
- const code = this.scanner.tail.match(new RegExp(`^[0-9A-Fa-f]{${length}}`))?.[0];
599
- return code ?? null;
600
- }
601
- }
602
-
603
- /**
604
- * Parse an AutoCAD `\U+nnnn` escape after the leading `U` has been consumed.
605
- *
606
- * @remarks
607
- * Exactly four hexadecimal digits are read. A high surrogate followed by
608
- * another `\U+nnnn` low surrogate is combined into one supplementary-plane
609
- * character (AutoCAD's encoding for code points above U+FFFF).
610
- *
611
- * @returns The decoded character, or `null` if the escape is incomplete
612
- */
613
- private parseUnicodeEscape(): string | null {
614
- if (this.scanner.peek() !== '+') {
615
- return null;
616
- }
617
-
618
- this.scanner.consume(1); // Consume the '+'
619
- const hexMatch = this.scanner.tail.match(/^[0-9A-Fa-f]{4}/);
620
- if (!hexMatch) {
621
- this.scanner.consume(-1); // Rewind '+'
622
- return null;
623
- }
624
-
625
- const codeUnit = parseInt(hexMatch[0], 16);
626
- this.scanner.consume(hexMatch[0].length);
627
-
628
- // High surrogate: combine with a following \U+ low-surrogate escape
629
- if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {
630
- const pairMatch = this.scanner.tail.match(/^\\U\+([0-9A-Fa-f]{4})/);
631
- if (pairMatch) {
632
- const lowUnit = parseInt(pairMatch[1], 16);
633
- if (lowUnit >= 0xdc00 && lowUnit <= 0xdfff) {
634
- this.scanner.consume(pairMatch[0].length);
635
- const codePoint =
636
- ((codeUnit - 0xd800) << 10) + (lowUnit - 0xdc00) + 0x10000;
637
- try {
638
- return String.fromCodePoint(codePoint);
639
- } catch {
640
- return '▯';
641
- }
642
- }
643
- }
644
- }
645
-
646
- // BMP code unit, or an unpaired surrogate kept as a UTF-16 unit
647
- return String.fromCharCode(codeUnit);
648
- }
649
-
650
- /**
651
- * Push current context onto the stack
652
- */
653
- private pushCtx(): void {
654
- this.ctxStack.push(this.ctxStack.current);
655
- }
656
-
657
- /**
658
- * Pop context from the stack
659
- */
660
- private popCtx(): void {
661
- this.ctxStack.pop();
662
- }
663
-
664
- /**
665
- * Parse stacking expression (numerator/denominator)
666
- * @returns Tuple of [TokenType.STACK, [numerator, denominator, type]]
667
- */
668
- private parseStacking(): [TokenType, [string, string, string]] {
669
- const scanner = new TextScanner(this.extractExpression(true));
670
- let numerator = '';
671
- let denominator = '';
672
- let stackingType = '';
673
-
674
- const getNextChar = (): [string, boolean] => {
675
- let c = scanner.peek();
676
- let escape = false;
677
- if (c.charCodeAt(0) < 32) {
678
- c = ' ';
679
- }
680
- if (c === '\\') {
681
- escape = true;
682
- scanner.consume(1);
683
- c = scanner.peek();
684
- }
685
- scanner.consume(1);
686
- return [c, escape];
687
- };
688
-
689
- const parseNumerator = (): [string, string] => {
690
- let word = '';
691
- while (scanner.hasData) {
692
- const [c, escape] = getNextChar();
693
- // Check for stacking operators first
694
- if (!escape && (c === '/' || c === '#' || c === '^')) {
695
- return [word, c];
696
- }
697
- word += c;
698
- }
699
- return [word, ''];
700
- };
701
-
702
- const parseDenominator = (skipLeadingSpace: boolean): string => {
703
- let word = '';
704
- let skipping = skipLeadingSpace;
705
- while (scanner.hasData) {
706
- const [c, escape] = getNextChar();
707
- if (skipping && c === ' ') {
708
- continue;
709
- }
710
- skipping = false;
711
- // Stop at terminator unless escaped
712
- if (!escape && c === ';') {
713
- break;
714
- }
715
- word += c;
716
- }
717
- return word;
718
- };
719
-
720
- [numerator, stackingType] = parseNumerator();
721
- if (stackingType) {
722
- // Only skip leading space for caret divider
723
- denominator = parseDenominator(stackingType === '^');
724
- }
725
-
726
- // Special case for \S^!/^?;
727
- if (numerator === '' && denominator.includes('I/')) {
728
- return [TokenType.STACK, [' ', ' ', '/']];
729
- }
730
-
731
- // Handle caret as a stacking operator
732
- if (stackingType === '^') {
733
- return [TokenType.STACK, [numerator, denominator, '^']];
734
- }
735
-
736
- return [TokenType.STACK, [numerator, denominator, stackingType]];
737
- }
738
-
739
- /**
740
- * Parse MText properties
741
- * @param cmd - The property command to parse
742
- * @returns Property changes if yieldPropertyCommands is true and changes occurred
743
- */
744
- private parseProperties(cmd: string): TokenData[TokenType.PROPERTIES_CHANGED] | void {
745
- const prevCtx = this.ctxStack.current.copy();
746
- const newCtx = this.ctxStack.current.copy();
747
- switch (cmd) {
748
- case 'L':
749
- newCtx.underline = true;
750
- this.continueStroke = true;
751
- break;
752
- case 'l':
753
- newCtx.underline = false;
754
- if (!newCtx.hasAnyStroke) {
755
- this.continueStroke = false;
756
- }
757
- break;
758
- case 'O':
759
- newCtx.overline = true;
760
- this.continueStroke = true;
761
- break;
762
- case 'o':
763
- newCtx.overline = false;
764
- if (!newCtx.hasAnyStroke) {
765
- this.continueStroke = false;
766
- }
767
- break;
768
- case 'K':
769
- newCtx.strikeThrough = true;
770
- this.continueStroke = true;
771
- break;
772
- case 'k':
773
- newCtx.strikeThrough = false;
774
- if (!newCtx.hasAnyStroke) {
775
- this.continueStroke = false;
776
- }
777
- break;
778
- case 'A':
779
- this.parseAlign(newCtx);
780
- break;
781
- case 'C':
782
- this.parseAciColor(newCtx);
783
- break;
784
- case 'c':
785
- this.parseRgbColor(newCtx);
786
- break;
787
- case 'H':
788
- this.parseHeight(newCtx);
789
- break;
790
- case 'W':
791
- this.parseWidth(newCtx);
792
- break;
793
- case 'Q':
794
- this.parseOblique(newCtx);
795
- break;
796
- case 'T':
797
- this.parseCharTracking(newCtx);
798
- break;
799
- case 'p':
800
- this.parseParagraphProperties(newCtx);
801
- break;
802
- case 'f':
803
- case 'F':
804
- this.parseFontProperties(newCtx);
805
- break;
806
- default:
807
- throw new Error(`Unknown command: ${cmd}`);
808
- }
809
-
810
- // Update continueStroke based on current stroke state
811
- this.continueStroke = newCtx.hasAnyStroke;
812
- newCtx.continueStroke = this.continueStroke;
813
- // Use setCurrent to replace the current context
814
- this.ctxStack.setCurrent(newCtx);
815
-
816
- if (this.yieldPropertyCommands) {
817
- const changes = this.getPropertyChanges(prevCtx, newCtx);
818
- if (Object.keys(changes).length > 0) {
819
- return {
820
- command: cmd,
821
- changes,
822
- depth: this.ctxStack.depth,
823
- };
824
- }
825
- }
826
- }
827
-
828
- /**
829
- * Get property changes between two contexts
830
- * @param oldCtx - The old context
831
- * @param newCtx - The new context
832
- * @returns Object containing changed properties
833
- */
834
- private getPropertyChanges(
835
- oldCtx: MTextContext,
836
- newCtx: MTextContext
837
- ): TokenData[TokenType.PROPERTIES_CHANGED]['changes'] {
838
- const changes: TokenData[TokenType.PROPERTIES_CHANGED]['changes'] = {};
839
-
840
- if (oldCtx.underline !== newCtx.underline) {
841
- changes.underline = newCtx.underline;
842
- }
843
- if (oldCtx.overline !== newCtx.overline) {
844
- changes.overline = newCtx.overline;
845
- }
846
- if (oldCtx.strikeThrough !== newCtx.strikeThrough) {
847
- changes.strikeThrough = newCtx.strikeThrough;
848
- }
849
- if (oldCtx.color.aci !== newCtx.color.aci) {
850
- changes.aci = newCtx.color.aci;
851
- }
852
- if (oldCtx.color.rgbValue !== newCtx.color.rgbValue) {
853
- changes.rgb = newCtx.color.rgb;
854
- }
855
- if (oldCtx.align !== newCtx.align) {
856
- changes.align = newCtx.align;
857
- }
858
- if (JSON.stringify(oldCtx.fontFace) !== JSON.stringify(newCtx.fontFace)) {
859
- changes.fontFace = newCtx.fontFace;
860
- }
861
- if (
862
- oldCtx.capHeight.value !== newCtx.capHeight.value ||
863
- oldCtx.capHeight.isRelative !== newCtx.capHeight.isRelative
864
- ) {
865
- changes.capHeight = newCtx.capHeight;
866
- }
867
- if (
868
- oldCtx.widthFactor.value !== newCtx.widthFactor.value ||
869
- oldCtx.widthFactor.isRelative !== newCtx.widthFactor.isRelative
870
- ) {
871
- changes.widthFactor = newCtx.widthFactor;
872
- }
873
- if (
874
- oldCtx.charTrackingFactor.value !== newCtx.charTrackingFactor.value ||
875
- oldCtx.charTrackingFactor.isRelative !== newCtx.charTrackingFactor.isRelative
876
- ) {
877
- changes.charTrackingFactor = newCtx.charTrackingFactor;
878
- }
879
- if (oldCtx.oblique !== newCtx.oblique) {
880
- changes.oblique = newCtx.oblique;
881
- }
882
- if (JSON.stringify(oldCtx.paragraph) !== JSON.stringify(newCtx.paragraph)) {
883
- // Only include changed paragraph properties
884
- const changedProps: Partial<ParagraphProperties> = {};
885
- if (oldCtx.paragraph.indent !== newCtx.paragraph.indent) {
886
- changedProps.indent = newCtx.paragraph.indent;
887
- }
888
- if (oldCtx.paragraph.align !== newCtx.paragraph.align) {
889
- changedProps.align = newCtx.paragraph.align;
890
- }
891
- if (oldCtx.paragraph.left !== newCtx.paragraph.left) {
892
- changedProps.left = newCtx.paragraph.left;
893
- }
894
- if (oldCtx.paragraph.right !== newCtx.paragraph.right) {
895
- changedProps.right = newCtx.paragraph.right;
896
- }
897
- if (JSON.stringify(oldCtx.paragraph.tabs) !== JSON.stringify(newCtx.paragraph.tabs)) {
898
- changedProps.tabs = newCtx.paragraph.tabs;
899
- }
900
- if (Object.keys(changedProps).length > 0) {
901
- changes.paragraph = changedProps;
902
- }
903
- }
904
-
905
- return changes;
906
- }
907
-
908
- /**
909
- * Parse alignment property
910
- * @param ctx - The context to update
911
- */
912
- private parseAlign(ctx: MTextContext): void {
913
- const char = this.scanner.get();
914
- if ('012'.includes(char)) {
915
- ctx.align = parseInt(char) as MTextLineAlignment;
916
- } else {
917
- ctx.align = MTextLineAlignment.BOTTOM;
918
- }
919
- this.consumeOptionalTerminator();
920
- }
921
-
922
- /**
923
- * Parse height property
924
- * @param ctx - The context to update
925
- */
926
- private parseHeight(ctx: MTextContext): void {
927
- const expr = this.extractFloatExpression(true);
928
- if (expr) {
929
- try {
930
- if (expr.endsWith('x')) {
931
- // For height command, treat x suffix as relative value
932
- ctx.capHeight = {
933
- value: parseFloat(expr.slice(0, -1)),
934
- isRelative: true,
935
- };
936
- } else {
937
- ctx.capHeight = {
938
- value: parseFloat(expr),
939
- isRelative: false,
940
- };
941
- }
942
- } catch {
943
- // If parsing fails, treat the entire command as literal text
944
- this.scanner.consume(-expr.length); // Rewind to before the expression
945
- return;
946
- }
947
- }
948
- this.consumeOptionalTerminator();
949
- }
950
-
951
- /**
952
- * Parse width property
953
- * @param ctx - The context to update
954
- */
955
- private parseWidth(ctx: MTextContext): void {
956
- const expr = this.extractFloatExpression(true);
957
- if (expr) {
958
- try {
959
- if (expr.endsWith('x')) {
960
- // For width command, treat x suffix as relative value
961
- ctx.widthFactor = {
962
- value: parseFloat(expr.slice(0, -1)),
963
- isRelative: true,
964
- };
965
- } else {
966
- ctx.widthFactor = {
967
- value: parseFloat(expr),
968
- isRelative: false,
969
- };
970
- }
971
- } catch {
972
- // If parsing fails, treat the entire command as literal text
973
- this.scanner.consume(-expr.length); // Rewind to before the expression
974
- return;
975
- }
976
- }
977
- this.consumeOptionalTerminator();
978
- }
979
-
980
- /**
981
- * Parse character tracking property
982
- * @param ctx - The context to update
983
- */
984
- private parseCharTracking(ctx: MTextContext): void {
985
- const expr = this.extractFloatExpression(true);
986
- if (expr) {
987
- try {
988
- if (expr.endsWith('x')) {
989
- // For tracking command, treat x suffix as relative value
990
- ctx.charTrackingFactor = {
991
- value: Math.abs(parseFloat(expr.slice(0, -1))),
992
- isRelative: true,
993
- };
994
- } else {
995
- ctx.charTrackingFactor = {
996
- value: Math.abs(parseFloat(expr)),
997
- isRelative: false,
998
- };
999
- }
1000
- } catch {
1001
- // If parsing fails, treat the entire command as literal text
1002
- this.scanner.consume(-expr.length); // Rewind to before the expression
1003
- return;
1004
- }
1005
- }
1006
- this.consumeOptionalTerminator();
1007
- }
1008
-
1009
- /**
1010
- * Parse float value or factor
1011
- * @param value - Current value to apply factor to
1012
- * @returns New value
1013
- */
1014
- private parseFloatValueOrFactor(value: number): number {
1015
- const expr = this.extractFloatExpression(true);
1016
- if (expr) {
1017
- if (expr.endsWith('x')) {
1018
- const factor = parseFloat(expr.slice(0, -1));
1019
- value *= factor; // Allow negative factors
1020
- } else {
1021
- value = parseFloat(expr); // Allow negative values
1022
- }
1023
- }
1024
- return value;
1025
- }
1026
-
1027
- /**
1028
- * Parse oblique angle property
1029
- * @param ctx - The context to update
1030
- */
1031
- private parseOblique(ctx: MTextContext): void {
1032
- const obliqueExpr = this.extractFloatExpression(false);
1033
- if (obliqueExpr) {
1034
- ctx.oblique = parseFloat(obliqueExpr);
1035
- }
1036
- this.consumeOptionalTerminator();
1037
- }
1038
-
1039
- /**
1040
- * Parse ACI color property
1041
- * @param ctx - The context to update
1042
- */
1043
- private parseAciColor(ctx: MTextContext): void {
1044
- const aciExpr = this.extractIntExpression();
1045
- if (aciExpr) {
1046
- const aci = parseInt(aciExpr);
1047
- if (aci < 257) {
1048
- ctx.color.aci = aci;
1049
- }
1050
- }
1051
- this.consumeOptionalTerminator();
1052
- }
1053
-
1054
- /**
1055
- * Parse RGB color property
1056
- * @param ctx - The context to update
1057
- */
1058
- private parseRgbColor(ctx: MTextContext): void {
1059
- const rgbExpr = this.extractIntExpression();
1060
- if (rgbExpr) {
1061
- const value = parseInt(rgbExpr) & 0xffffff;
1062
- ctx.color.rgbValue = value;
1063
- }
1064
- this.consumeOptionalTerminator();
1065
- }
1066
-
1067
- /**
1068
- * Extract float expression from scanner
1069
- * @param relative - Whether to allow relative values (ending in 'x')
1070
- * @returns Extracted expression
1071
- */
1072
- private extractFloatExpression(relative: boolean = false): string {
1073
- const pattern = relative
1074
- ? /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?x?/
1075
- : /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/;
1076
- const match = this.scanner.tail.match(pattern);
1077
- if (match) {
1078
- const result = match[0];
1079
- this.scanner.consume(result.length);
1080
- return result;
1081
- }
1082
- return '';
1083
- }
1084
-
1085
- /**
1086
- * Extract integer expression from scanner
1087
- * @returns Extracted expression
1088
- */
1089
- private extractIntExpression(): string {
1090
- const match = this.scanner.tail.match(/^\d+/);
1091
- if (match) {
1092
- const result = match[0];
1093
- this.scanner.consume(result.length);
1094
- return result;
1095
- }
1096
- return '';
1097
- }
1098
-
1099
- /**
1100
- * Extract expression until semicolon or end
1101
- * @param escape - Whether to handle escaped semicolons
1102
- * @returns Extracted expression
1103
- */
1104
- private extractExpression(escape: boolean = false): string {
1105
- const stop = this.scanner.find(';', escape);
1106
- if (stop < 0) {
1107
- const expr = this.scanner.tail;
1108
- this.scanner.consume(expr.length);
1109
- return expr;
1110
- }
1111
- // Check if the semicolon is escaped by looking at the previous character
1112
- const prevChar = this.scanner.peek(stop - this.scanner.currentIndex - 1);
1113
- const isEscaped = prevChar === '\\';
1114
- const expr = this.scanner.tail.slice(0, stop - this.scanner.currentIndex + (isEscaped ? 1 : 0));
1115
- this.scanner.consume(expr.length + 1);
1116
- return expr;
1117
- }
1118
-
1119
- /**
1120
- * Parse font properties
1121
- * @param ctx - The context to update
1122
- */
1123
- private parseFontProperties(ctx: MTextContext): void {
1124
- const parts = this.extractExpression().split('|');
1125
- if (parts.length > 0 && parts[0]) {
1126
- const name = parts[0];
1127
- let style: FontStyle = 'Regular';
1128
- let weight = 400;
1129
-
1130
- for (const part of parts.slice(1)) {
1131
- if (part.startsWith('b1')) {
1132
- weight = 700;
1133
- } else if (part === 'i' || part.startsWith('i1')) {
1134
- style = 'Italic';
1135
- } else if (part === 'i0' || part.startsWith('i0')) {
1136
- style = 'Regular';
1137
- }
1138
- }
1139
-
1140
- ctx.fontFace = {
1141
- family: name,
1142
- style,
1143
- weight,
1144
- };
1145
- }
1146
- }
1147
-
1148
- /**
1149
- * Parse paragraph properties from the MText content
1150
- * Handles properties like indentation, alignment, and tab stops
1151
- * @param ctx - The context to update
1152
- */
1153
- private parseParagraphProperties(ctx: MTextContext): void {
1154
- const scanner = new TextScanner(this.extractExpression());
1155
- /** Current indentation value */
1156
- let indent = ctx.paragraph.indent;
1157
- /** Left margin value */
1158
- let left = ctx.paragraph.left;
1159
- /** Right margin value */
1160
- let right = ctx.paragraph.right;
1161
- /** Current paragraph alignment */
1162
- let align = ctx.paragraph.align;
1163
- /** Array of tab stop positions and types */
1164
- let tabStops: (number | string)[] = [];
1165
-
1166
- /**
1167
- * Parse a floating point number from the scanner's current position
1168
- * Handles optional sign, decimal point, and scientific notation
1169
- * @returns The parsed float value, or 0 if no valid number is found
1170
- */
1171
- const parseFloatValue = (): number => {
1172
- const match = scanner.tail.match(/^[+-]?\d+(?:\.\d*)?(?:[eE][+-]?\d+)?/);
1173
- if (match) {
1174
- const value = parseFloat(match[0]);
1175
- scanner.consume(match[0].length);
1176
- while (scanner.peek() === ',') {
1177
- scanner.consume(1);
1178
- }
1179
- return value;
1180
- }
1181
- return 0;
1182
- };
1183
-
1184
- while (scanner.hasData) {
1185
- const cmd = scanner.get();
1186
- switch (cmd) {
1187
- case 'i': // Indentation
1188
- indent = parseFloatValue();
1189
- break;
1190
- case 'l': // Left margin
1191
- left = parseFloatValue();
1192
- break;
1193
- case 'r': // Right margin
1194
- right = parseFloatValue();
1195
- break;
1196
- case 'x': // Skip
1197
- break;
1198
- case 'q': {
1199
- // Alignment
1200
- const adjustment = scanner.get();
1201
- align = CHAR_TO_ALIGN[adjustment] || MTextParagraphAlignment.DEFAULT;
1202
- while (scanner.peek() === ',') {
1203
- scanner.consume(1);
1204
- }
1205
- break;
1206
- }
1207
- case 't': // Tab stops
1208
- tabStops = [];
1209
- while (scanner.hasData) {
1210
- const type = scanner.peek();
1211
- if (type === 'r' || type === 'c') {
1212
- scanner.consume(1);
1213
- const value = parseFloatValue();
1214
- tabStops.push(type + value.toString());
1215
- } else {
1216
- const value = parseFloatValue();
1217
- if (!isNaN(value)) {
1218
- tabStops.push(value);
1219
- } else {
1220
- scanner.consume(1);
1221
- }
1222
- }
1223
- }
1224
- break;
1225
- }
1226
- }
1227
-
1228
- ctx.paragraph = {
1229
- indent,
1230
- left,
1231
- right,
1232
- align,
1233
- tabs: tabStops,
1234
- };
1235
- }
1236
-
1237
- /**
1238
- * Consume optional terminator (semicolon)
1239
- */
1240
- private consumeOptionalTerminator(): void {
1241
- if (this.scanner.peek() === ';') {
1242
- this.scanner.consume(1);
1243
- }
1244
- }
1245
-
1246
- /**
1247
- * Builds {@link PercentSymbolData} for a recognized `%%` code letter.
1248
- */
1249
- private buildPercentSymbolData(
1250
- code: string,
1251
- specialChar: string
1252
- ): PercentSymbolData | null {
1253
- if (code === 'c' || code === 'd' || code === 'p') {
1254
- return { kind: 'named', code, char: specialChar };
1255
- }
1256
- if (code === '%') {
1257
- return { kind: 'literal', char: '%' };
1258
- }
1259
- return null;
1260
- }
1261
-
1262
- /**
1263
- * Parse MText content into tokens
1264
- * @yields MTextToken objects
1265
- */
1266
- *parse(): Generator<MTextToken> {
1267
- const wordToken = TokenType.WORD;
1268
- const spaceToken = TokenType.SPACE;
1269
- let followupToken: TokenType | null = null;
1270
- let followupData: TokenData[TokenType] | undefined;
1271
-
1272
- function resetParagraph(ctx: MTextContext): Partial<ParagraphProperties> {
1273
- const prev = { ...ctx.paragraph };
1274
- ctx.paragraph = {
1275
- indent: 0,
1276
- left: 0,
1277
- right: 0,
1278
- align: MTextParagraphAlignment.DEFAULT,
1279
- tabs: [],
1280
- };
1281
- const changed: Partial<ParagraphProperties> = {};
1282
- if (prev.indent !== 0) changed.indent = 0;
1283
- if (prev.left !== 0) changed.left = 0;
1284
- if (prev.right !== 0) changed.right = 0;
1285
- if (prev.align !== MTextParagraphAlignment.DEFAULT)
1286
- changed.align = MTextParagraphAlignment.DEFAULT;
1287
- if (JSON.stringify(prev.tabs) !== JSON.stringify([])) changed.tabs = [];
1288
- return changed;
1289
- }
1290
-
1291
- const nextToken = (): [TokenType, TokenData[TokenType]] => {
1292
- let word = '';
1293
- while (this.scanner.hasData) {
1294
- let escape = false;
1295
- let letter = this.scanner.peek();
1296
- const cmdStartIndex = this.scanner.currentIndex;
1297
-
1298
- // Handle control characters first
1299
- if (letter.charCodeAt(0) < 32) {
1300
- this.scanner.consume(1); // Always consume the control character
1301
- if (letter === '\t') {
1302
- return [TokenType.TABULATOR, null];
1303
- }
1304
- if (letter === '\n') {
1305
- return [TokenType.NEW_PARAGRAPH, null];
1306
- }
1307
- letter = ' ';
1308
- }
1309
-
1310
- if (letter === '\\') {
1311
- if ('\\{}'.includes(this.scanner.peek(1))) {
1312
- escape = true;
1313
- this.scanner.consume(1);
1314
- letter = this.scanner.peek();
1315
- } else {
1316
- if (word) {
1317
- return [wordToken, word];
1318
- }
1319
- this.scanner.consume(1);
1320
- const cmd = this.scanner.get();
1321
- switch (cmd) {
1322
- case '~':
1323
- return [TokenType.NBSP, null];
1324
- case 'P':
1325
- return [TokenType.NEW_PARAGRAPH, null];
1326
- case 'N':
1327
- return [TokenType.NEW_COLUMN, null];
1328
- case 'X':
1329
- return [TokenType.WRAP_AT_DIMLINE, null];
1330
- case 'S': {
1331
- this.inStackContext = true;
1332
- const result = this.parseStacking();
1333
- this.inStackContext = false;
1334
- return result;
1335
- }
1336
- case 'm':
1337
- case 'M':
1338
- // Handle multi-byte character encoding (MIF)
1339
- if (this.scanner.peek() === '+') {
1340
- this.scanner.consume(1); // Consume the '+'
1341
- const hexCode = this.extractMifCode(this.mifCodeLength);
1342
- if (hexCode) {
1343
- this.scanner.consume(hexCode.length);
1344
- const decodedChar = this.mifDecoder(hexCode);
1345
- if (word) {
1346
- return [wordToken, word];
1347
- }
1348
- return [wordToken, decodedChar];
1349
- }
1350
- // If no valid hex code found, rewind the '+' character
1351
- this.scanner.consume(-1);
1352
- }
1353
- // If not a valid multi-byte code, treat as literal text
1354
- word += '\\M';
1355
- continue;
1356
- case 'U': {
1357
- // AutoCAD \U+nnnn uses exactly four hex digits. Characters
1358
- // outside the BMP are encoded as two consecutive \U+XXXX
1359
- // UTF-16 surrogate escapes.
1360
- const decodedChar = this.parseUnicodeEscape();
1361
- if (decodedChar !== null) {
1362
- if (word) {
1363
- return [wordToken, word];
1364
- }
1365
- return [wordToken, decodedChar];
1366
- }
1367
- // If not a valid Unicode code, treat as literal text
1368
- word += '\\U';
1369
- continue;
1370
- }
1371
- default:
1372
- if (cmd) {
1373
- try {
1374
- const propertyChanges = this.parseProperties(cmd);
1375
- if (this.yieldPropertyCommands && propertyChanges) {
1376
- return [TokenType.PROPERTIES_CHANGED, propertyChanges];
1377
- }
1378
- // After processing a property command, continue with normal parsing
1379
- continue;
1380
- } catch {
1381
- const commandText = this.scanner.tail.slice(
1382
- cmdStartIndex,
1383
- this.scanner.currentIndex
1384
- );
1385
- word += commandText;
1386
- }
1387
- }
1388
- }
1389
- continue;
1390
- }
1391
- }
1392
-
1393
- if (letter === '%' && this.scanner.peek(1) === '%') {
1394
- const code = this.scanner.peek(2).toLowerCase();
1395
- const specialChar = SPECIAL_CHAR_ENCODING[code];
1396
- if (specialChar) {
1397
- this.scanner.consume(3);
1398
- if (this.yieldPercentSymbols) {
1399
- const symbolData = this.buildPercentSymbolData(code, specialChar);
1400
- if (symbolData) {
1401
- if (word) {
1402
- followupToken = TokenType.PERCENT_SYMBOL;
1403
- followupData = symbolData;
1404
- return [wordToken, word];
1405
- }
1406
- return [TokenType.PERCENT_SYMBOL, symbolData];
1407
- }
1408
- }
1409
- word += specialChar;
1410
- continue;
1411
- } else {
1412
- /**
1413
- * Supports Control Codes: `%%ddd`, where ddd is a three-digit decimal number representing the ASCII code value of the character.
1414
- *
1415
- * Reference: https://help.autodesk.com/view/ACD/2026/ENU/?guid=GUID-968CBC1D-BA99-4519-ABDD-88419EB2BF92
1416
- */
1417
- const digits = [code, this.scanner.peek(3), this.scanner.peek(4)];
1418
-
1419
- if (digits.every(d => d >= '0' && d <= '9')) {
1420
- const charCode = Number.parseInt(digits.join(''), 10);
1421
- this.scanner.consume(5);
1422
- if (this.yieldPercentSymbols) {
1423
- const symbolData: PercentSymbolData = {
1424
- kind: 'numeric',
1425
- charCode,
1426
- char: String.fromCharCode(charCode),
1427
- };
1428
- if (word) {
1429
- followupToken = TokenType.PERCENT_SYMBOL;
1430
- followupData = symbolData;
1431
- return [wordToken, word];
1432
- }
1433
- return [TokenType.PERCENT_SYMBOL, symbolData];
1434
- }
1435
- word += String.fromCharCode(charCode);
1436
- } else {
1437
- // Skip invalid special character codes
1438
- this.scanner.consume(3);
1439
- }
1440
-
1441
- continue;
1442
- }
1443
- }
1444
-
1445
- if (letter === ' ') {
1446
- if (word) {
1447
- this.scanner.consume(1);
1448
- followupToken = spaceToken;
1449
- return [wordToken, word];
1450
- }
1451
- this.scanner.consume(1);
1452
- return [spaceToken, null];
1453
- }
1454
-
1455
- if (!escape) {
1456
- if (letter === '{') {
1457
- if (word) {
1458
- return [wordToken, word];
1459
- }
1460
- this.scanner.consume(1);
1461
- this.pushCtx();
1462
- continue;
1463
- } else if (letter === '}') {
1464
- if (word) {
1465
- return [wordToken, word];
1466
- }
1467
- this.scanner.consume(1);
1468
- // Context restoration with yieldPropertyCommands
1469
- if (this.yieldPropertyCommands) {
1470
- const prevCtx = this.ctxStack.current;
1471
- this.popCtx();
1472
- const changes = this.getPropertyChanges(prevCtx, this.ctxStack.current);
1473
- if (Object.keys(changes).length > 0) {
1474
- return [
1475
- TokenType.PROPERTIES_CHANGED,
1476
- { command: undefined, changes, depth: this.ctxStack.depth },
1477
- ];
1478
- }
1479
- } else {
1480
- this.popCtx();
1481
- }
1482
- continue;
1483
- }
1484
- }
1485
-
1486
- // Handle caret-encoded characters only when not in stack context
1487
- if (!this.inStackContext && letter === '^') {
1488
- const nextChar = this.scanner.peek(1);
1489
- if (nextChar) {
1490
- const code = nextChar.charCodeAt(0);
1491
- this.scanner.consume(2); // Consume both ^ and the next character
1492
- if (code === 32) {
1493
- // Space
1494
- word += '^';
1495
- } else if (code === 73) {
1496
- // Tab
1497
- if (word) {
1498
- return [wordToken, word];
1499
- }
1500
- return [TokenType.TABULATOR, null];
1501
- } else if (code === 74) {
1502
- // Line feed
1503
- if (word) {
1504
- return [wordToken, word];
1505
- }
1506
- return [TokenType.NEW_PARAGRAPH, null];
1507
- } else if (code === 77) {
1508
- // Carriage return
1509
- // Ignore carriage return
1510
- continue;
1511
- } else {
1512
- word += '▯';
1513
- }
1514
- continue;
1515
- }
1516
- }
1517
-
1518
- this.scanner.consume(1);
1519
- if (letter.charCodeAt(0) >= 32) {
1520
- word += letter;
1521
- }
1522
- }
1523
-
1524
- if (word) {
1525
- return [wordToken, word];
1526
- }
1527
- return [TokenType.NONE, null];
1528
- };
1529
-
1530
- while (true) {
1531
- const [type, data] = nextToken.call(this);
1532
- if (type) {
1533
- yield new MTextToken(type, this.ctxStack.current.copy(), data);
1534
- if (type === TokenType.NEW_PARAGRAPH && this.resetParagraphParameters) {
1535
- // Reset paragraph properties and emit PROPERTIES_CHANGED if needed
1536
- const ctx = this.ctxStack.current;
1537
- const changed = resetParagraph(ctx);
1538
- if (this.yieldPropertyCommands && Object.keys(changed).length > 0) {
1539
- yield new MTextToken(TokenType.PROPERTIES_CHANGED, ctx.copy(), {
1540
- command: undefined,
1541
- changes: { paragraph: changed },
1542
- depth: this.ctxStack.depth,
1543
- });
1544
- }
1545
- }
1546
- if (followupToken) {
1547
- yield new MTextToken(
1548
- followupToken,
1549
- this.ctxStack.current.copy(),
1550
- followupData ?? null
1551
- );
1552
- followupToken = null;
1553
- followupData = undefined;
1554
- }
1555
- } else {
1556
- break;
1557
- }
1558
- }
1559
- }
1560
- }
1561
-
1562
- /**
1563
- * Text scanner for parsing MText content
1564
- */
1565
- export class TextScanner {
1566
- private text: string;
1567
- private textLen: number;
1568
- private _index: number;
1569
-
1570
- /**
1571
- * Create a new text scanner
1572
- * @param text - The text to scan
1573
- */
1574
- constructor(text: string) {
1575
- this.text = text;
1576
- this.textLen = text.length;
1577
- this._index = 0;
1578
- }
1579
-
1580
- /**
1581
- * Get the current index in the text
1582
- */
1583
- get currentIndex(): number {
1584
- return this._index;
1585
- }
1586
-
1587
- /**
1588
- * Check if the scanner has reached the end of the text
1589
- */
1590
- get isEmpty(): boolean {
1591
- return this._index >= this.textLen;
1592
- }
1593
-
1594
- /**
1595
- * Check if there is more text to scan
1596
- */
1597
- get hasData(): boolean {
1598
- return this._index < this.textLen;
1599
- }
1600
-
1601
- /**
1602
- * Get the next character and advance the index
1603
- * @returns The next character, or empty string if at end
1604
- */
1605
- get(): string {
1606
- if (this.isEmpty) {
1607
- return '';
1608
- }
1609
- const char = this.text[this._index];
1610
- this._index++;
1611
- return char;
1612
- }
1613
-
1614
- /**
1615
- * Advance the index by the specified count
1616
- * @param count - Number of characters to advance
1617
- */
1618
- consume(count: number = 1): void {
1619
- this._index = Math.max(0, Math.min(this._index + count, this.textLen));
1620
- }
1621
-
1622
- /**
1623
- * Look at a character without advancing the index
1624
- * @param offset - Offset from current position
1625
- * @returns The character at the offset position, or empty string if out of bounds
1626
- */
1627
- peek(offset: number = 0): string {
1628
- const index = this._index + offset;
1629
- if (index >= this.textLen || index < 0) {
1630
- return '';
1631
- }
1632
- return this.text[index];
1633
- }
1634
-
1635
- /**
1636
- * Find the next occurrence of a character
1637
- * @param char - The character to find
1638
- * @param escape - Whether to handle escaped characters
1639
- * @returns Index of the character, or -1 if not found
1640
- */
1641
- find(char: string, escape: boolean = false): number {
1642
- let index = this._index;
1643
- while (index < this.textLen) {
1644
- if (escape && this.text[index] === '\\') {
1645
- if (index + 1 < this.textLen) {
1646
- if (this.text[index + 1] === char) {
1647
- return index + 1;
1648
- }
1649
- index += 2;
1650
- continue;
1651
- }
1652
- index++;
1653
- continue;
1654
- }
1655
- if (this.text[index] === char) {
1656
- return index;
1657
- }
1658
- index++;
1659
- }
1660
- return -1;
1661
- }
1662
-
1663
- /**
1664
- * Get the remaining text from the current position
1665
- */
1666
- get tail(): string {
1667
- return this.text.slice(this._index);
1668
- }
1669
-
1670
- /**
1671
- * Check if the next character is a space
1672
- */
1673
- isNextSpace(): boolean {
1674
- return this.peek() === ' ';
1675
- }
1676
-
1677
- /**
1678
- * Consume spaces until a non-space character is found
1679
- * @returns Number of spaces consumed
1680
- */
1681
- consumeSpaces(): number {
1682
- let count = 0;
1683
- while (this.isNextSpace()) {
1684
- this.consume();
1685
- count++;
1686
- }
1687
- return count;
1688
- }
1689
- }
1690
-
1691
- /**
1692
- * Class to handle ACI and RGB color logic for MText.
1693
- *
1694
- * This class encapsulates color state for MText, supporting both AutoCAD Color Index (ACI) and RGB color.
1695
- * Only one color mode is active at a time: setting an RGB color disables ACI, and vice versa.
1696
- * RGB is stored as a single 24-bit integer (0xRRGGBB) for efficient comparison and serialization.
1697
- *
1698
- * Example usage:
1699
- * ```ts
1700
- * const color1 = new MTextColor(1); // ACI color
1701
- * const color2 = new MTextColor([255, 0, 0]); // RGB color
1702
- * const color3 = new MTextColor(); // Default (ACI=256, "by layer")
1703
- * ```
1704
- */
1705
- export class MTextColor {
1706
- /**
1707
- * The AutoCAD Color Index (ACI) value. Only used if no RGB color is set.
1708
- * @default 256 ("by layer")
1709
- */
1710
- private _aci: number | null = 256;
1711
- /**
1712
- * The RGB color value as a single 24-bit integer (0xRRGGBB), or null if not set.
1713
- * @default null
1714
- */
1715
- private _rgbValue: number | null = null; // Store as 0xRRGGBB or null
1716
-
1717
- /**
1718
- * Create a new MTextColor instance.
1719
- * @param color The initial color: number for ACI, [r,g,b] for RGB, or null/undefined for default (ACI=256).
1720
- */
1721
- constructor(color?: number | RGB | null) {
1722
- if (Array.isArray(color)) {
1723
- this.rgb = color;
1724
- } else if (typeof color === 'number') {
1725
- this.aci = color;
1726
- } else {
1727
- this.aci = 256;
1728
- }
1729
- }
1730
-
1731
- /**
1732
- * Get the current ACI color value.
1733
- * @returns The ACI color (0-256), or null if using RGB.
1734
- */
1735
- get aci(): number | null {
1736
- return this._aci;
1737
- }
1738
-
1739
- /**
1740
- * Set the ACI color value. Setting this disables any RGB color.
1741
- * @param value The ACI color (0-256), or null to unset.
1742
- * @throws Error if value is out of range.
1743
- */
1744
- set aci(value: number | null) {
1745
- if (value === null) {
1746
- this._aci = null;
1747
- } else if (value >= 0 && value <= 256) {
1748
- this._aci = value;
1749
- this._rgbValue = null;
1750
- } else {
1751
- throw new Error('ACI not in range [0, 256]');
1752
- }
1753
- }
1754
-
1755
- /**
1756
- * Get the current RGB color as a tuple [r, g, b], or null if not set.
1757
- * @returns The RGB color tuple, or null if using ACI.
1758
- */
1759
- get rgb(): RGB | null {
1760
- if (this._rgbValue === null) return null;
1761
- // Extract R, G, B from 0xRRGGBB
1762
- const r = (this._rgbValue >> 16) & 0xff;
1763
- const g = (this._rgbValue >> 8) & 0xff;
1764
- const b = this._rgbValue & 0xff;
1765
- return [r, g, b];
1766
- }
1767
-
1768
- /**
1769
- * Set the RGB color. Setting this disables ACI color.
1770
- * @param value The RGB color tuple [r, g, b], or null to use ACI.
1771
- */
1772
- set rgb(value: RGB | null) {
1773
- if (value) {
1774
- const [r, g, b] = value;
1775
- this._rgbValue = ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
1776
- this._aci = null;
1777
- } else {
1778
- this._rgbValue = null;
1779
- }
1780
- }
1781
-
1782
- /**
1783
- * Returns true if the color is set by RGB, false if by ACI.
1784
- */
1785
- get isRgb(): boolean {
1786
- return this._rgbValue !== null;
1787
- }
1788
-
1789
- /**
1790
- * Returns true if the color is set by ACI, false if by RGB.
1791
- */
1792
- get isAci(): boolean {
1793
- return this._rgbValue === null && this._aci !== null;
1794
- }
1795
-
1796
- /**
1797
- * Get or set the internal RGB value as a number (0xRRGGBB), or null if not set.
1798
- * Setting this will switch to RGB mode and set ACI to null.
1799
- */
1800
- get rgbValue(): number | null {
1801
- return this._rgbValue;
1802
- }
1803
-
1804
- set rgbValue(val: number | null) {
1805
- if (val === null) {
1806
- this._rgbValue = null;
1807
- } else {
1808
- this._rgbValue = val & 0xffffff;
1809
- this._aci = null;
1810
- }
1811
- }
1812
-
1813
- /**
1814
- * Returns a deep copy of this color.
1815
- * @returns A new MTextColor instance with the same color state.
1816
- */
1817
- copy(): MTextColor {
1818
- const c = new MTextColor();
1819
- c._aci = this._aci;
1820
- c._rgbValue = this._rgbValue;
1821
- return c;
1822
- }
1823
-
1824
- /**
1825
- * Returns a plain object for serialization.
1826
- * @returns An object with aci, rgb (tuple), and rgbValue (number or null).
1827
- */
1828
- toObject(): { aci: number | null; rgb: RGB | null; rgbValue: number | null } {
1829
- return { aci: this._aci, rgb: this.rgb, rgbValue: this._rgbValue };
1830
- }
1831
-
1832
- /**
1833
- * Convert the current color to a CSS hex color string (#rrggbb).
1834
- * Returns null if the color is ACI-based and has no RGB value.
1835
- */
1836
- toCssColor(): string | null {
1837
- if (this._rgbValue !== null) {
1838
- return colorNumberToHex(this._rgbValue);
1839
- }
1840
- return null;
1841
- }
1842
-
1843
- /**
1844
- * Create an MTextColor from a CSS color string.
1845
- * Supports #rgb, #rrggbb, rgb(...), rgba(...). Returns null if invalid or transparent.
1846
- */
1847
- static fromCssColor(value: string | null | undefined): MTextColor | null {
1848
- const rgbValue = cssColorToRgbValue(value);
1849
- if (rgbValue === null) return null;
1850
- const color = new MTextColor();
1851
- color.rgbValue = rgbValue;
1852
- return color;
1853
- }
1854
-
1855
- /**
1856
- * Equality check for color.
1857
- * @param other The other MTextColor to compare.
1858
- * @returns True if both ACI and RGB values are equal.
1859
- */
1860
- equals(other: MTextColor): boolean {
1861
- return this._aci === other._aci && this._rgbValue === other._rgbValue;
1862
- }
1863
- }
1864
-
1865
- /**
1866
- * MText context class for managing text formatting state
1867
- */
1868
- export class MTextContext {
1869
- private _stroke: number = 0;
1870
- /** Whether to continue stroke formatting */
1871
- continueStroke: boolean = false;
1872
- /** Color (ACI or RGB) */
1873
- color: MTextColor = new MTextColor();
1874
- /** Line alignment */
1875
- align: MTextLineAlignment = MTextLineAlignment.BOTTOM;
1876
- /** Font face properties */
1877
- fontFace: FontFace = { family: '', style: 'Regular', weight: 400 };
1878
- /** Capital letter height */
1879
- private _capHeight: FactorValue = { value: 1.0, isRelative: false };
1880
- /** Character width factor */
1881
- private _widthFactor: FactorValue = { value: 1.0, isRelative: false };
1882
- /**
1883
- * Character tracking factor a multiplier applied to the default spacing between characters in the MText object.
1884
- * - Value = 1.0 → Normal spacing.
1885
- * - Value < 1.0 → Characters are closer together.
1886
- * - Value > 1.0 → Characters are spaced farther apart.
1887
- */
1888
- private _charTrackingFactor: FactorValue = { value: 1.0, isRelative: false };
1889
- /** Oblique angle */
1890
- oblique: number = 0.0;
1891
- /** Paragraph properties */
1892
- paragraph: ParagraphProperties = {
1893
- indent: 0,
1894
- left: 0,
1895
- right: 0,
1896
- align: MTextParagraphAlignment.DEFAULT,
1897
- tabs: [],
1898
- };
1899
-
1900
- /**
1901
- * Get the capital letter height
1902
- */
1903
- get capHeight(): FactorValue {
1904
- return this._capHeight;
1905
- }
1906
-
1907
- /**
1908
- * Set the capital letter height
1909
- * @param value - Height value
1910
- */
1911
- set capHeight(value: FactorValue) {
1912
- this._capHeight = {
1913
- value: Math.abs(value.value),
1914
- isRelative: value.isRelative,
1915
- };
1916
- }
1917
-
1918
- /**
1919
- * Get the character width factor
1920
- */
1921
- get widthFactor(): FactorValue {
1922
- return this._widthFactor;
1923
- }
1924
-
1925
- /**
1926
- * Set the character width factor
1927
- * @param value - Width factor value
1928
- */
1929
- set widthFactor(value: FactorValue) {
1930
- this._widthFactor = {
1931
- value: Math.abs(value.value),
1932
- isRelative: value.isRelative,
1933
- };
1934
- }
1935
-
1936
- /**
1937
- * Get the character tracking factor
1938
- */
1939
- get charTrackingFactor(): FactorValue {
1940
- return this._charTrackingFactor;
1941
- }
1942
-
1943
- /**
1944
- * Set the character tracking factor
1945
- * @param value - Tracking factor value
1946
- */
1947
- set charTrackingFactor(value: FactorValue) {
1948
- this._charTrackingFactor = {
1949
- value: Math.abs(value.value),
1950
- isRelative: value.isRelative,
1951
- };
1952
- }
1953
-
1954
- /**
1955
- * Get the ACI color value
1956
- */
1957
- get aci(): number | null {
1958
- return this.color.aci;
1959
- }
1960
-
1961
- /**
1962
- * Set the ACI color value
1963
- * @param value - ACI color value (0-256)
1964
- * @throws Error if value is out of range
1965
- */
1966
- set aci(value: number) {
1967
- this.color.aci = value;
1968
- }
1969
-
1970
- /**
1971
- * Get the RGB color value
1972
- */
1973
- get rgb(): RGB | null {
1974
- return this.color.rgb;
1975
- }
1976
-
1977
- /**
1978
- * Set the RGB color value
1979
- */
1980
- set rgb(value: RGB | null) {
1981
- this.color.rgb = value;
1982
- }
1983
-
1984
- /**
1985
- * Gets whether the current text should be rendered in italic style.
1986
- * @returns {boolean} True if the font style is 'Italic', otherwise false.
1987
- */
1988
- get italic(): boolean {
1989
- return this.fontFace.style === 'Italic';
1990
- }
1991
- /**
1992
- * Sets whether the current text should be rendered in italic style.
1993
- * @param value - If true, sets the font style to 'Italic'; if false, sets it to 'Regular'.
1994
- */
1995
- set italic(value: boolean) {
1996
- this.fontFace.style = value ? 'Italic' : 'Regular';
1997
- }
1998
-
1999
- /**
2000
- * Gets whether the current text should be rendered in bold style.
2001
- * This is primarily used for mesh fonts and affects font selection.
2002
- * @returns {boolean} True if the font weight is 700 or higher, otherwise false.
2003
- */
2004
- get bold(): boolean {
2005
- return (this.fontFace.weight || 400) >= 700;
2006
- }
2007
- /**
2008
- * Sets whether the current text should be rendered in bold style.
2009
- * This is primarily used for mesh fonts and affects font selection.
2010
- * @param value - If true, sets the font weight to 700; if false, sets it to 400.
2011
- */
2012
- set bold(value: boolean) {
2013
- this.fontFace.weight = value ? 700 : 400;
2014
- }
2015
-
2016
- /**
2017
- * Get whether text is underlined
2018
- */
2019
- get underline(): boolean {
2020
- return Boolean(this._stroke & MTextStroke.UNDERLINE);
2021
- }
2022
-
2023
- /**
2024
- * Set whether text is underlined
2025
- * @param value - Whether to underline
2026
- */
2027
- set underline(value: boolean) {
2028
- this._setStrokeState(MTextStroke.UNDERLINE, value);
2029
- }
2030
-
2031
- /**
2032
- * Get whether text has strike-through
2033
- */
2034
- get strikeThrough(): boolean {
2035
- return Boolean(this._stroke & MTextStroke.STRIKE_THROUGH);
2036
- }
2037
-
2038
- /**
2039
- * Set whether text has strike-through
2040
- * @param value - Whether to strike through
2041
- */
2042
- set strikeThrough(value: boolean) {
2043
- this._setStrokeState(MTextStroke.STRIKE_THROUGH, value);
2044
- }
2045
-
2046
- /**
2047
- * Get whether text has overline
2048
- */
2049
- get overline(): boolean {
2050
- return Boolean(this._stroke & MTextStroke.OVERLINE);
2051
- }
2052
-
2053
- /**
2054
- * Set whether text has overline
2055
- * @param value - Whether to overline
2056
- */
2057
- set overline(value: boolean) {
2058
- this._setStrokeState(MTextStroke.OVERLINE, value);
2059
- }
2060
-
2061
- /**
2062
- * Check if any stroke formatting is active
2063
- */
2064
- get hasAnyStroke(): boolean {
2065
- return Boolean(this._stroke);
2066
- }
2067
-
2068
- /**
2069
- * Set the state of a stroke type
2070
- * @param stroke - The stroke type to set
2071
- * @param state - Whether to enable or disable the stroke
2072
- */
2073
- private _setStrokeState(stroke: MTextStroke, state: boolean = true): void {
2074
- if (state) {
2075
- this._stroke |= stroke;
2076
- } else {
2077
- this._stroke &= ~stroke;
2078
- }
2079
- }
2080
-
2081
- /**
2082
- * Create a copy of this context
2083
- * @returns A new context with the same properties
2084
- */
2085
- copy(): MTextContext {
2086
- const ctx = new MTextContext();
2087
- ctx._stroke = this._stroke;
2088
- ctx.continueStroke = this.continueStroke;
2089
- ctx.color = this.color.copy();
2090
- ctx.align = this.align;
2091
- ctx.fontFace = { ...this.fontFace };
2092
- ctx._capHeight = { ...this._capHeight };
2093
- ctx._widthFactor = { ...this._widthFactor };
2094
- ctx._charTrackingFactor = { ...this._charTrackingFactor };
2095
- ctx.oblique = this.oblique;
2096
- ctx.paragraph = { ...this.paragraph };
2097
- return ctx;
2098
- }
2099
- }
2100
-
2101
- /**
2102
- * Token class for MText parsing
2103
- */
2104
- export class MTextToken {
2105
- /**
2106
- * Create a new MText token
2107
- * @param type - The token type
2108
- * @param ctx - The text context at this token
2109
- * @param data - Optional token data
2110
- */
2111
- constructor(
2112
- public type: TokenType,
2113
- public ctx: MTextContext,
2114
- public data: TokenData[TokenType]
2115
- ) {}
2116
- }
1
+ /**
2
+ * Token types used in MText parsing
3
+ */
4
+ export enum TokenType {
5
+ /** No token */
6
+ NONE = 0,
7
+ /** Word token with string data */
8
+ WORD = 1,
9
+ /** Stack token with [numerator, denominator, type] data */
10
+ STACK = 2,
11
+ /** Space token with no data */
12
+ SPACE = 3,
13
+ /** Non-breaking space token with no data */
14
+ NBSP = 4,
15
+ /** Tab token with no data */
16
+ TABULATOR = 5,
17
+ /** New paragraph token with no data */
18
+ NEW_PARAGRAPH = 6,
19
+ /** New column token with no data */
20
+ NEW_COLUMN = 7,
21
+ /** Wrap at dimension line token with no data */
22
+ WRAP_AT_DIMLINE = 8,
23
+ /** Properties changed token with string data (full command) */
24
+ PROPERTIES_CHANGED = 9,
25
+ /** AutoCAD percent-sign symbol code (`%%c`, `%%d`, `%%p`, `%%nnn`, `%%%`) */
26
+ PERCENT_SYMBOL = 10,
27
+ }
28
+
29
+ /**
30
+ * AutoCAD percent-sign symbol emitted when {@link MTextParserOptions.yieldPercentSymbols}
31
+ * is enabled.
32
+ */
33
+ export type PercentSymbolData =
34
+ | {
35
+ kind: 'named';
36
+ /** Percent code letter: `%%c`, `%%d`, or `%%p`. */
37
+ code: 'c' | 'd' | 'p';
38
+ /** Unicode expansion used for display (e.g. `%%c` → `Ø`). */
39
+ char: string;
40
+ }
41
+ | {
42
+ kind: 'numeric';
43
+ /**
44
+ * Decimal code from `%%nnn`, where `nnn` is 1–3 digits (Unicode/ASCII
45
+ * code point, e.g. `%%34` → `"`, `%%176` → `°`).
46
+ */
47
+ charCode: number;
48
+ /** `String.fromCharCode(charCode)`. */
49
+ char: string;
50
+ }
51
+ | {
52
+ kind: 'literal';
53
+ /** Literal percent from `%%%`. */
54
+ char: '%';
55
+ };
56
+
57
+ /**
58
+ * Represents a factor value that can be either absolute or relative.
59
+ * Used for properties like height, width, and character tracking in MText formatting.
60
+ */
61
+ export interface FactorValue {
62
+ /** The numeric value of the factor */
63
+ value: number;
64
+ /** Whether the value is relative (true) or absolute (false) */
65
+ isRelative: boolean;
66
+ }
67
+
68
+ /**
69
+ * Format properties of MText word tokens.
70
+ * This interface defines all the formatting properties that can be applied to MText content,
71
+ * including text styling, colors, alignment, font properties, and paragraph formatting.
72
+ */
73
+ export interface Properties {
74
+ /** Whether text is underlined */
75
+ underline?: boolean;
76
+ /** Whether text has an overline */
77
+ overline?: boolean;
78
+ /** Whether text has strike-through */
79
+ strikeThrough?: boolean;
80
+ /** AutoCAD Color Index (ACI) color value (0-256), or null if not set */
81
+ aci?: number | null;
82
+ /** RGB color tuple [r, g, b], or null if not set */
83
+ rgb?: RGB | null;
84
+ /** Line alignment for the text */
85
+ align?: MTextLineAlignment;
86
+ /** Font face properties including family, style, and weight */
87
+ fontFace?: FontFace;
88
+ /** Capital letter height factor (can be relative or absolute) */
89
+ capHeight?: FactorValue;
90
+ /** Character width factor (can be relative or absolute) */
91
+ widthFactor?: FactorValue;
92
+ /** Character tracking factor for spacing between characters (can be relative or absolute) */
93
+ charTrackingFactor?: FactorValue;
94
+ /** Oblique angle in degrees for text slant */
95
+ oblique?: number;
96
+ /** Paragraph formatting properties (partial to allow selective updates) */
97
+ paragraph?: Partial<ParagraphProperties>;
98
+ }
99
+
100
+ /**
101
+ * Represents a change in MText properties, including the command, the changed properties, and the context depth.
102
+ */
103
+ export interface ChangedProperties {
104
+ /**
105
+ * The property command that triggered the change (e.g., 'L', 'C', 'f').
106
+ * The command will be undefined if it is to restore context.
107
+ */
108
+ command: string | undefined;
109
+ /**
110
+ * The set of properties that have changed as a result of the command.
111
+ */
112
+ changes: Properties;
113
+ /**
114
+ * The current context stack depth when the property change occurs.
115
+ * - 0: The change is global (applies outside of any `{}` block).
116
+ * - >0: The change is local (applies within one or more nested `{}` blocks).
117
+ */
118
+ depth: number; // 0 = global, >0 = local
119
+ }
120
+
121
+ /**
122
+ * Type for token data based on token type
123
+ */
124
+ export type TokenData = {
125
+ [TokenType.NONE]: null;
126
+ [TokenType.WORD]: string;
127
+ [TokenType.STACK]: [string, string, string];
128
+ [TokenType.SPACE]: null;
129
+ [TokenType.NBSP]: null;
130
+ [TokenType.TABULATOR]: null;
131
+ [TokenType.NEW_PARAGRAPH]: null;
132
+ [TokenType.NEW_COLUMN]: null;
133
+ [TokenType.WRAP_AT_DIMLINE]: null;
134
+ [TokenType.PROPERTIES_CHANGED]: ChangedProperties;
135
+ [TokenType.PERCENT_SYMBOL]: PercentSymbolData;
136
+ };
137
+
138
+ /**
139
+ * Line alignment options for MText
140
+ */
141
+ export enum MTextLineAlignment {
142
+ /** Align text to bottom */
143
+ BOTTOM = 0,
144
+ /** Align text to middle */
145
+ MIDDLE = 1,
146
+ /** Align text to top */
147
+ TOP = 2,
148
+ }
149
+
150
+ /**
151
+ * Paragraph alignment options for MText
152
+ */
153
+ export enum MTextParagraphAlignment {
154
+ /** Default alignment */
155
+ DEFAULT = 0,
156
+ /** Left alignment */
157
+ LEFT = 1,
158
+ /** Right alignment */
159
+ RIGHT = 2,
160
+ /** Center alignment */
161
+ CENTER = 3,
162
+ /** Justified alignment */
163
+ JUSTIFIED = 4,
164
+ /** Distributed alignment */
165
+ DISTRIBUTED = 5,
166
+ }
167
+
168
+ /**
169
+ * Text stroke options for MText
170
+ */
171
+ export enum MTextStroke {
172
+ /** No stroke */
173
+ NONE = 0,
174
+ /** Underline stroke */
175
+ UNDERLINE = 1,
176
+ /** Overline stroke */
177
+ OVERLINE = 2,
178
+ /** Strike-through stroke */
179
+ STRIKE_THROUGH = 4,
180
+ }
181
+
182
+ /**
183
+ * RGB color tuple
184
+ */
185
+ export type RGB = [number, number, number];
186
+
187
+ /**
188
+ * Font style type
189
+ */
190
+ export type FontStyle = 'Regular' | 'Italic';
191
+
192
+ /**
193
+ * Font face properties
194
+ */
195
+ export interface FontFace {
196
+ /** Font family name */
197
+ family: string;
198
+ /** Font style (e.g., 'Regular', 'Italic') */
199
+ style: FontStyle;
200
+ /** Font weight (e.g., 400 for normal, 700 for bold) */
201
+ weight: number;
202
+ }
203
+
204
+ /**
205
+ * Paragraph properties
206
+ */
207
+ export interface ParagraphProperties {
208
+ /** Indentation value */
209
+ indent: number;
210
+ /** Left margin value */
211
+ left: number;
212
+ /** Right margin value */
213
+ right: number;
214
+ /** Paragraph alignment */
215
+ align: MTextParagraphAlignment;
216
+ /** Tab stop positions and types */
217
+ tabs: (number | string)[];
218
+ }
219
+
220
+ /**
221
+ * Special character encoding mapping
222
+ */
223
+ const SPECIAL_CHAR_ENCODING: Record<string, string> = {
224
+ c: 'Ø',
225
+ d: '°',
226
+ p: '±',
227
+ '%': '%',
228
+ };
229
+
230
+ /**
231
+ * Character to paragraph alignment mapping
232
+ */
233
+ const CHAR_TO_ALIGN: Record<string, MTextParagraphAlignment> = {
234
+ l: MTextParagraphAlignment.LEFT,
235
+ r: MTextParagraphAlignment.RIGHT,
236
+ c: MTextParagraphAlignment.CENTER,
237
+ j: MTextParagraphAlignment.JUSTIFIED,
238
+ d: MTextParagraphAlignment.DISTRIBUTED,
239
+ };
240
+
241
+ /**
242
+ * Convert RGB tuple to integer color value
243
+ * @param rgb - RGB color tuple
244
+ * @returns Integer color value
245
+ */
246
+ export function rgb2int(rgb: RGB): number {
247
+ const [r, g, b] = rgb;
248
+ return (r << 16) | (g << 8) | b;
249
+ }
250
+
251
+ /**
252
+ * Convert integer color value to RGB tuple
253
+ * @param value - Integer color value
254
+ * @returns RGB color tuple
255
+ */
256
+ export function int2rgb(value: number): RGB {
257
+ const r = (value >> 16) & 0xff;
258
+ const g = (value >> 8) & 0xff;
259
+ const b = value & 0xff;
260
+ return [r, g, b];
261
+ }
262
+
263
+ function clampColorChannel(value: number): number {
264
+ return Math.max(0, Math.min(255, Math.round(value)));
265
+ }
266
+
267
+ function normalizeColorNumber(color: number): number {
268
+ return Math.max(0, Math.min(0xffffff, Math.round(color)));
269
+ }
270
+
271
+ function colorNumberToHex(color: number | null): string | null {
272
+ if (color === null) return null;
273
+ return `#${normalizeColorNumber(color).toString(16).padStart(6, '0')}`;
274
+ }
275
+
276
+ function normalizeHexColor(value: string | null | undefined): string | null {
277
+ if (!value) return null;
278
+ const normalized = value.trim().toLowerCase();
279
+ if (/^#[0-9a-f]{6}$/.test(normalized)) return normalized;
280
+ if (/^[0-9a-f]{6}$/.test(normalized)) return `#${normalized}`;
281
+ if (/^#[0-9a-f]{3}$/.test(normalized)) {
282
+ const r = normalized[1];
283
+ const g = normalized[2];
284
+ const b = normalized[3];
285
+ return `#${r}${r}${g}${g}${b}${b}`;
286
+ }
287
+ if (/^[0-9a-f]{3}$/.test(normalized)) {
288
+ const r = normalized[0];
289
+ const g = normalized[1];
290
+ const b = normalized[2];
291
+ return `#${r}${r}${g}${g}${b}${b}`;
292
+ }
293
+ return null;
294
+ }
295
+
296
+ function cssColorToRgbValue(value: string | null | undefined): number | null {
297
+ if (!value) return null;
298
+ const raw = value.trim().toLowerCase();
299
+ if (raw === 'transparent') return null;
300
+
301
+ const hex = normalizeHexColor(raw);
302
+ if (hex) {
303
+ return normalizeColorNumber(Number.parseInt(hex.slice(1), 16));
304
+ }
305
+
306
+ const fnMatch = raw.match(/^rgba?\((.*)\)$/);
307
+ if (!fnMatch) return null;
308
+
309
+ const parts = fnMatch[1]
310
+ .replace(/\s*\/\s*/g, ' ')
311
+ .split(/[,\s]+/)
312
+ .map(p => p.trim())
313
+ .filter(Boolean);
314
+
315
+ if (parts.length < 3) return null;
316
+
317
+ const toChannel = (token: string): number => {
318
+ if (token.endsWith('%')) {
319
+ const percent = Number.parseFloat(token.slice(0, -1));
320
+ return clampColorChannel((percent / 100) * 255);
321
+ }
322
+ const num = Number.parseFloat(token);
323
+ return clampColorChannel(num);
324
+ };
325
+
326
+ const r = toChannel(parts[0]);
327
+ const g = toChannel(parts[1]);
328
+ const b = toChannel(parts[2]);
329
+ return rgb2int([r, g, b]);
330
+ }
331
+
332
+ /**
333
+ * Escape DXF line endings
334
+ * @param text - Text to escape
335
+ * @returns Escaped text
336
+ */
337
+ export function escapeDxfLineEndings(text: string): string {
338
+ return text.replace(/\r\n|\r|\n/g, '\\P');
339
+ }
340
+
341
+ /**
342
+ * Check if text contains inline formatting codes
343
+ * @param text - Text to check
344
+ * @returns True if text contains formatting codes
345
+ */
346
+ export function hasInlineFormattingCodes(text: string): boolean {
347
+ return text.replace(/\\P/g, '').replace(/\\~/g, '').includes('\\');
348
+ }
349
+
350
+ /**
351
+ * Extracts all unique font names used in an MText string.
352
+ * This function searches for font commands in the format \f{fontname}| or \f{fontname}; and returns a set of unique font names.
353
+ * Font names are converted to lowercase to ensure case-insensitive uniqueness.
354
+ *
355
+ * @param mtext - The MText string to analyze for font names
356
+ * @param removeExtension - Whether to remove font file extensions (e.g., .ttf, .shx) from font names. Defaults to false.
357
+ * @returns A Set containing all unique font names found in the MText string, converted to lowercase
358
+ * @example
359
+ * ```ts
360
+ * const mtext = "\\fArial.ttf|Hello\\fTimes New Roman.otf|World";
361
+ * const fonts = getFonts(mtext, true);
362
+ * // Returns: Set(2) { "arial", "times new roman" }
363
+ * ```
364
+ */
365
+ export function getFonts(mtext: string, removeExtension: boolean = false) {
366
+ const fonts: Set<string> = new Set();
367
+ const regex = /\\[fF](.*?)[;|]/g;
368
+
369
+ [...mtext.matchAll(regex)].forEach(match => {
370
+ let fontName = match[1].toLowerCase();
371
+ if (removeExtension) {
372
+ fontName = fontName.replace(/\.(ttf|otf|woff|shx)$/, '');
373
+ }
374
+ fonts.add(fontName);
375
+ });
376
+
377
+ return fonts;
378
+ }
379
+
380
+ /**
381
+ * ContextStack manages a stack of MTextContext objects for character-level formatting.
382
+ *
383
+ * - Character-level formatting (underline, color, font, etc.) is scoped to `{}` blocks and managed by the stack.
384
+ * - Paragraph-level formatting (\p) is not scoped, but when a block ends, any paragraph property changes are merged into the parent context.
385
+ * - On pop, paragraph properties from the popped context are always merged into the new top context.
386
+ */
387
+ class ContextStack {
388
+ private stack: MTextContext[] = [];
389
+
390
+ /**
391
+ * Creates a new ContextStack with an initial context.
392
+ * @param initial The initial MTextContext to use as the base of the stack.
393
+ */
394
+ constructor(initial: MTextContext) {
395
+ this.stack.push(initial);
396
+ }
397
+
398
+ /**
399
+ * Pushes a copy of the given context onto the stack.
400
+ * @param ctx The MTextContext to push (copied).
401
+ */
402
+ push(ctx: MTextContext) {
403
+ this.stack.push(ctx);
404
+ }
405
+
406
+ /**
407
+ * Pops the top context from the stack and merges its paragraph properties into the new top context.
408
+ * If only one context remains, nothing is popped.
409
+ * @returns The popped MTextContext, or undefined if the stack has only one context.
410
+ */
411
+ pop(): MTextContext | undefined {
412
+ if (this.stack.length <= 1) return undefined;
413
+ const popped = this.stack.pop()!;
414
+ // Merge paragraph properties into the new top context
415
+ const top = this.stack[this.stack.length - 1];
416
+ if (JSON.stringify(top.paragraph) !== JSON.stringify(popped.paragraph)) {
417
+ top.paragraph = { ...popped.paragraph };
418
+ }
419
+ return popped;
420
+ }
421
+
422
+ /**
423
+ * Returns the current (top) context on the stack.
424
+ */
425
+ get current(): MTextContext {
426
+ return this.stack[this.stack.length - 1];
427
+ }
428
+
429
+ /**
430
+ * Returns the current stack depth (number of nested blocks), not counting the root context.
431
+ */
432
+ get depth(): number {
433
+ return this.stack.length - 1;
434
+ }
435
+
436
+ /**
437
+ * Returns the root (bottom) context, which represents the global formatting state.
438
+ * Used for paragraph property application.
439
+ */
440
+ get root(): MTextContext {
441
+ return this.stack[0];
442
+ }
443
+
444
+ /**
445
+ * Replaces the current (top) context with the given context.
446
+ * @param ctx The new context to set as the current context.
447
+ */
448
+ setCurrent(ctx: MTextContext) {
449
+ this.stack[this.stack.length - 1] = ctx;
450
+ }
451
+ }
452
+
453
+ /**
454
+ * Configuration options for the MText parser.
455
+ * These options control how the parser behaves during tokenization and property handling.
456
+ */
457
+ export interface MTextParserOptions {
458
+ /**
459
+ * Whether to yield PROPERTIES_CHANGED tokens when formatting properties change.
460
+ * When true, the parser will emit tokens whenever properties like color, font, or alignment change.
461
+ * When false, property changes are applied silently to the context without generating tokens.
462
+ * @default false
463
+ */
464
+ yieldPropertyCommands?: boolean;
465
+ /**
466
+ * Whether to reset paragraph parameters when encountering a new paragraph token.
467
+ * When true, paragraph properties (indent, margins, alignment, tab stops) are reset to defaults
468
+ * at the start of each new paragraph.
469
+ * @default false
470
+ */
471
+ resetParagraphParameters?: boolean;
472
+ /**
473
+ * Whether to emit {@link TokenType.PERCENT_SYMBOL} tokens for AutoCAD `%%` symbol
474
+ * codes instead of expanding them into {@link TokenType.WORD} characters.
475
+ * @default false
476
+ */
477
+ yieldPercentSymbols?: boolean;
478
+ /**
479
+ * Custom decoder function for MIF (Multibyte Interchange Format) codes.
480
+ * If provided, this function will be used instead of the default decodeMultiByteChar.
481
+ * The function receives the hex code string and should return the decoded character.
482
+ * @param hex - Hex code string (e.g., "C4E3" or "1A2B3")
483
+ * @returns Decoded character or empty square (▯) if invalid
484
+ * @default undefined (uses default decoder)
485
+ */
486
+ mifDecoder?: (hex: string) => string;
487
+ /**
488
+ * The length of MIF hex codes to parse. MIF codes in AutoCAD can vary in length
489
+ * depending on the specific SHX big font used (typically 4 or 5 digits).
490
+ * If not specified, the parser will try to auto-detect the length by attempting
491
+ * to match 4 digits first, then 5 digits if needed.
492
+ * @default undefined (auto-detect)
493
+ */
494
+ mifCodeLength?: 4 | 5 | 'auto';
495
+ }
496
+
497
+ /**
498
+ * Main parser class for MText content
499
+ */
500
+ export class MTextParser {
501
+ private scanner: TextScanner;
502
+ private ctxStack: ContextStack;
503
+ private continueStroke: boolean = false;
504
+ private yieldPropertyCommands: boolean;
505
+ private resetParagraphParameters: boolean;
506
+ private yieldPercentSymbols: boolean;
507
+ private inStackContext: boolean = false;
508
+ private mifDecoder: (hex: string) => string;
509
+ private mifCodeLength: 4 | 5 | 'auto';
510
+
511
+ /**
512
+ * Creates a new MTextParser instance
513
+ * @param content - The MText content to parse
514
+ * @param ctx - Optional initial MText context
515
+ * @param options - Parser options
516
+ */
517
+ constructor(content: string, ctx?: MTextContext, options: MTextParserOptions = {}) {
518
+ this.scanner = new TextScanner(content);
519
+ const initialCtx = ctx ?? new MTextContext();
520
+ this.ctxStack = new ContextStack(initialCtx);
521
+ this.yieldPropertyCommands = options.yieldPropertyCommands ?? false;
522
+ this.resetParagraphParameters = options.resetParagraphParameters ?? false;
523
+ this.yieldPercentSymbols = options.yieldPercentSymbols ?? false;
524
+ this.mifDecoder = options.mifDecoder ?? this.decodeMultiByteChar.bind(this);
525
+ this.mifCodeLength = options.mifCodeLength ?? 'auto';
526
+ }
527
+
528
+ /**
529
+ * Decode multi-byte character from hex code
530
+ * @param hex - Hex code string (e.g. "C4E3" or "1A2B3")
531
+ * @returns Decoded character or empty square if invalid
532
+ */
533
+ private decodeMultiByteChar(hex: string): string {
534
+ try {
535
+ // For 5-digit codes, return placeholder directly
536
+ if (hex.length === 5) {
537
+ const prefix = hex[0];
538
+
539
+ // Notes:
540
+ // I know AutoCAD uses prefix 1 for Shift-JIS, 2 for big5, and 5 for gbk.
541
+ // But I don't know whether there are other prefixes and their meanings.
542
+ let encoding = 'gbk';
543
+ if (prefix === '1') {
544
+ encoding = 'shift-jis';
545
+ } else if (prefix === '2') {
546
+ encoding = 'big5';
547
+ }
548
+ const bytes = new Uint8Array([
549
+ parseInt(hex.substr(1, 2), 16),
550
+ parseInt(hex.substr(3, 2), 16),
551
+ ]);
552
+ const decoder = new TextDecoder(encoding);
553
+ const result = decoder.decode(bytes);
554
+ return result;
555
+ } else if (hex.length === 4) {
556
+ // For 4-digit hex codes, decode as 2-byte character
557
+ const bytes = new Uint8Array([
558
+ parseInt(hex.substr(0, 2), 16),
559
+ parseInt(hex.substr(2, 2), 16),
560
+ ]);
561
+
562
+ // Try GBK first
563
+ const gbkDecoder = new TextDecoder('gbk');
564
+ const gbkResult = gbkDecoder.decode(bytes);
565
+ if (gbkResult !== '▯') {
566
+ return gbkResult;
567
+ }
568
+
569
+ // Try BIG5 if GBK fails
570
+ const big5Decoder = new TextDecoder('big5');
571
+ const big5Result = big5Decoder.decode(bytes);
572
+ if (big5Result !== '▯') {
573
+ return big5Result;
574
+ }
575
+ }
576
+
577
+ return '▯';
578
+ } catch {
579
+ return '▯';
580
+ }
581
+ }
582
+
583
+ /**
584
+ * Extract MIF hex code from scanner
585
+ * @param length - The length of the hex code to extract (4 or 5), or 'auto' to detect
586
+ * @returns The extracted hex code, or null if not found
587
+ */
588
+ private extractMifCode(length: 4 | 5 | 'auto'): string | null {
589
+ if (length === 'auto') {
590
+ // Try 5 digits first if available, then fall back to 4 digits
591
+ const code5 = this.scanner.tail.match(/^[0-9A-Fa-f]{5}/)?.[0];
592
+ if (code5) {
593
+ return code5;
594
+ }
595
+ const code4 = this.scanner.tail.match(/^[0-9A-Fa-f]{4}/)?.[0];
596
+ if (code4) {
597
+ return code4;
598
+ }
599
+ return null;
600
+ } else {
601
+ const code = this.scanner.tail.match(new RegExp(`^[0-9A-Fa-f]{${length}}`))?.[0];
602
+ return code ?? null;
603
+ }
604
+ }
605
+
606
+ /**
607
+ * Parse an AutoCAD `\U+nnnn` escape after the leading `U` has been consumed.
608
+ *
609
+ * @remarks
610
+ * Exactly four hexadecimal digits are read. A high surrogate followed by
611
+ * another `\U+nnnn` low surrogate is combined into one supplementary-plane
612
+ * character (AutoCAD's encoding for code points above U+FFFF).
613
+ *
614
+ * @returns The decoded character, or `null` if the escape is incomplete
615
+ */
616
+ private parseUnicodeEscape(): string | null {
617
+ if (this.scanner.peek() !== '+') {
618
+ return null;
619
+ }
620
+
621
+ this.scanner.consume(1); // Consume the '+'
622
+ const hexMatch = this.scanner.tail.match(/^[0-9A-Fa-f]{4}/);
623
+ if (!hexMatch) {
624
+ this.scanner.consume(-1); // Rewind '+'
625
+ return null;
626
+ }
627
+
628
+ const codeUnit = parseInt(hexMatch[0], 16);
629
+ this.scanner.consume(hexMatch[0].length);
630
+
631
+ // High surrogate: combine with a following \U+ low-surrogate escape
632
+ if (codeUnit >= 0xd800 && codeUnit <= 0xdbff) {
633
+ const pairMatch = this.scanner.tail.match(/^\\U\+([0-9A-Fa-f]{4})/);
634
+ if (pairMatch) {
635
+ const lowUnit = parseInt(pairMatch[1], 16);
636
+ if (lowUnit >= 0xdc00 && lowUnit <= 0xdfff) {
637
+ this.scanner.consume(pairMatch[0].length);
638
+ const codePoint = ((codeUnit - 0xd800) << 10) + (lowUnit - 0xdc00) + 0x10000;
639
+ try {
640
+ return String.fromCodePoint(codePoint);
641
+ } catch {
642
+ return '▯';
643
+ }
644
+ }
645
+ }
646
+ }
647
+
648
+ // BMP code unit, or an unpaired surrogate kept as a UTF-16 unit
649
+ return String.fromCharCode(codeUnit);
650
+ }
651
+
652
+ /**
653
+ * Push current context onto the stack
654
+ */
655
+ private pushCtx(): void {
656
+ this.ctxStack.push(this.ctxStack.current);
657
+ }
658
+
659
+ /**
660
+ * Pop context from the stack
661
+ */
662
+ private popCtx(): void {
663
+ this.ctxStack.pop();
664
+ }
665
+
666
+ /**
667
+ * Parse stacking expression (numerator/denominator)
668
+ * @returns Tuple of [TokenType.STACK, [numerator, denominator, type]]
669
+ */
670
+ private parseStacking(): [TokenType, [string, string, string]] {
671
+ const scanner = new TextScanner(this.extractExpression(true));
672
+ let numerator = '';
673
+ let denominator = '';
674
+ let stackingType = '';
675
+
676
+ const getNextChar = (): [string, boolean] => {
677
+ let c = scanner.peek();
678
+ let escape = false;
679
+ if (c.charCodeAt(0) < 32) {
680
+ c = ' ';
681
+ }
682
+ if (c === '\\') {
683
+ escape = true;
684
+ scanner.consume(1);
685
+ c = scanner.peek();
686
+ }
687
+ scanner.consume(1);
688
+ return [c, escape];
689
+ };
690
+
691
+ const parseNumerator = (): [string, string] => {
692
+ let word = '';
693
+ while (scanner.hasData) {
694
+ const [c, escape] = getNextChar();
695
+ // Check for stacking operators first
696
+ if (!escape && (c === '/' || c === '#' || c === '^')) {
697
+ return [word, c];
698
+ }
699
+ word += c;
700
+ }
701
+ return [word, ''];
702
+ };
703
+
704
+ const parseDenominator = (skipLeadingSpace: boolean): string => {
705
+ let word = '';
706
+ let skipping = skipLeadingSpace;
707
+ while (scanner.hasData) {
708
+ const [c, escape] = getNextChar();
709
+ if (skipping && c === ' ') {
710
+ continue;
711
+ }
712
+ skipping = false;
713
+ // Stop at terminator unless escaped
714
+ if (!escape && c === ';') {
715
+ break;
716
+ }
717
+ word += c;
718
+ }
719
+ return word;
720
+ };
721
+
722
+ [numerator, stackingType] = parseNumerator();
723
+ if (stackingType) {
724
+ // Only skip leading space for caret divider
725
+ denominator = parseDenominator(stackingType === '^');
726
+ }
727
+
728
+ // Special case for \S^!/^?;
729
+ if (numerator === '' && denominator.includes('I/')) {
730
+ return [TokenType.STACK, [' ', ' ', '/']];
731
+ }
732
+
733
+ // Handle caret as a stacking operator
734
+ if (stackingType === '^') {
735
+ return [TokenType.STACK, [numerator, denominator, '^']];
736
+ }
737
+
738
+ return [TokenType.STACK, [numerator, denominator, stackingType]];
739
+ }
740
+
741
+ /**
742
+ * Parse MText properties
743
+ * @param cmd - The property command to parse
744
+ * @returns Property changes if yieldPropertyCommands is true and changes occurred
745
+ */
746
+ private parseProperties(cmd: string): TokenData[TokenType.PROPERTIES_CHANGED] | void {
747
+ const prevCtx = this.ctxStack.current.copy();
748
+ const newCtx = this.ctxStack.current.copy();
749
+ switch (cmd) {
750
+ case 'L':
751
+ newCtx.underline = true;
752
+ this.continueStroke = true;
753
+ break;
754
+ case 'l':
755
+ newCtx.underline = false;
756
+ if (!newCtx.hasAnyStroke) {
757
+ this.continueStroke = false;
758
+ }
759
+ break;
760
+ case 'O':
761
+ newCtx.overline = true;
762
+ this.continueStroke = true;
763
+ break;
764
+ case 'o':
765
+ newCtx.overline = false;
766
+ if (!newCtx.hasAnyStroke) {
767
+ this.continueStroke = false;
768
+ }
769
+ break;
770
+ case 'K':
771
+ newCtx.strikeThrough = true;
772
+ this.continueStroke = true;
773
+ break;
774
+ case 'k':
775
+ newCtx.strikeThrough = false;
776
+ if (!newCtx.hasAnyStroke) {
777
+ this.continueStroke = false;
778
+ }
779
+ break;
780
+ case 'A':
781
+ this.parseAlign(newCtx);
782
+ break;
783
+ case 'C':
784
+ this.parseAciColor(newCtx);
785
+ break;
786
+ case 'c':
787
+ this.parseRgbColor(newCtx);
788
+ break;
789
+ case 'H':
790
+ this.parseHeight(newCtx);
791
+ break;
792
+ case 'W':
793
+ this.parseWidth(newCtx);
794
+ break;
795
+ case 'Q':
796
+ this.parseOblique(newCtx);
797
+ break;
798
+ case 'T':
799
+ this.parseCharTracking(newCtx);
800
+ break;
801
+ case 'p':
802
+ this.parseParagraphProperties(newCtx);
803
+ break;
804
+ case 'f':
805
+ case 'F':
806
+ this.parseFontProperties(newCtx);
807
+ break;
808
+ default:
809
+ throw new Error(`Unknown command: ${cmd}`);
810
+ }
811
+
812
+ // Update continueStroke based on current stroke state
813
+ this.continueStroke = newCtx.hasAnyStroke;
814
+ newCtx.continueStroke = this.continueStroke;
815
+ // Use setCurrent to replace the current context
816
+ this.ctxStack.setCurrent(newCtx);
817
+
818
+ if (this.yieldPropertyCommands) {
819
+ const changes = this.getPropertyChanges(prevCtx, newCtx);
820
+ if (Object.keys(changes).length > 0) {
821
+ return {
822
+ command: cmd,
823
+ changes,
824
+ depth: this.ctxStack.depth,
825
+ };
826
+ }
827
+ }
828
+ }
829
+
830
+ /**
831
+ * Get property changes between two contexts
832
+ * @param oldCtx - The old context
833
+ * @param newCtx - The new context
834
+ * @returns Object containing changed properties
835
+ */
836
+ private getPropertyChanges(
837
+ oldCtx: MTextContext,
838
+ newCtx: MTextContext
839
+ ): TokenData[TokenType.PROPERTIES_CHANGED]['changes'] {
840
+ const changes: TokenData[TokenType.PROPERTIES_CHANGED]['changes'] = {};
841
+
842
+ if (oldCtx.underline !== newCtx.underline) {
843
+ changes.underline = newCtx.underline;
844
+ }
845
+ if (oldCtx.overline !== newCtx.overline) {
846
+ changes.overline = newCtx.overline;
847
+ }
848
+ if (oldCtx.strikeThrough !== newCtx.strikeThrough) {
849
+ changes.strikeThrough = newCtx.strikeThrough;
850
+ }
851
+ if (oldCtx.color.aci !== newCtx.color.aci) {
852
+ changes.aci = newCtx.color.aci;
853
+ }
854
+ if (oldCtx.color.rgbValue !== newCtx.color.rgbValue) {
855
+ changes.rgb = newCtx.color.rgb;
856
+ }
857
+ if (oldCtx.align !== newCtx.align) {
858
+ changes.align = newCtx.align;
859
+ }
860
+ if (JSON.stringify(oldCtx.fontFace) !== JSON.stringify(newCtx.fontFace)) {
861
+ changes.fontFace = newCtx.fontFace;
862
+ }
863
+ if (
864
+ oldCtx.capHeight.value !== newCtx.capHeight.value ||
865
+ oldCtx.capHeight.isRelative !== newCtx.capHeight.isRelative
866
+ ) {
867
+ changes.capHeight = newCtx.capHeight;
868
+ }
869
+ if (
870
+ oldCtx.widthFactor.value !== newCtx.widthFactor.value ||
871
+ oldCtx.widthFactor.isRelative !== newCtx.widthFactor.isRelative
872
+ ) {
873
+ changes.widthFactor = newCtx.widthFactor;
874
+ }
875
+ if (
876
+ oldCtx.charTrackingFactor.value !== newCtx.charTrackingFactor.value ||
877
+ oldCtx.charTrackingFactor.isRelative !== newCtx.charTrackingFactor.isRelative
878
+ ) {
879
+ changes.charTrackingFactor = newCtx.charTrackingFactor;
880
+ }
881
+ if (oldCtx.oblique !== newCtx.oblique) {
882
+ changes.oblique = newCtx.oblique;
883
+ }
884
+ if (JSON.stringify(oldCtx.paragraph) !== JSON.stringify(newCtx.paragraph)) {
885
+ // Only include changed paragraph properties
886
+ const changedProps: Partial<ParagraphProperties> = {};
887
+ if (oldCtx.paragraph.indent !== newCtx.paragraph.indent) {
888
+ changedProps.indent = newCtx.paragraph.indent;
889
+ }
890
+ if (oldCtx.paragraph.align !== newCtx.paragraph.align) {
891
+ changedProps.align = newCtx.paragraph.align;
892
+ }
893
+ if (oldCtx.paragraph.left !== newCtx.paragraph.left) {
894
+ changedProps.left = newCtx.paragraph.left;
895
+ }
896
+ if (oldCtx.paragraph.right !== newCtx.paragraph.right) {
897
+ changedProps.right = newCtx.paragraph.right;
898
+ }
899
+ if (JSON.stringify(oldCtx.paragraph.tabs) !== JSON.stringify(newCtx.paragraph.tabs)) {
900
+ changedProps.tabs = newCtx.paragraph.tabs;
901
+ }
902
+ if (Object.keys(changedProps).length > 0) {
903
+ changes.paragraph = changedProps;
904
+ }
905
+ }
906
+
907
+ return changes;
908
+ }
909
+
910
+ /**
911
+ * Parse alignment property
912
+ * @param ctx - The context to update
913
+ */
914
+ private parseAlign(ctx: MTextContext): void {
915
+ const char = this.scanner.get();
916
+ if ('012'.includes(char)) {
917
+ ctx.align = parseInt(char) as MTextLineAlignment;
918
+ } else {
919
+ ctx.align = MTextLineAlignment.BOTTOM;
920
+ }
921
+ this.consumeOptionalTerminator();
922
+ }
923
+
924
+ /**
925
+ * Parse height property
926
+ * @param ctx - The context to update
927
+ */
928
+ private parseHeight(ctx: MTextContext): void {
929
+ const expr = this.extractFloatExpression(true);
930
+ if (expr) {
931
+ try {
932
+ if (expr.endsWith('x')) {
933
+ // For height command, treat x suffix as relative value
934
+ ctx.capHeight = {
935
+ value: parseFloat(expr.slice(0, -1)),
936
+ isRelative: true,
937
+ };
938
+ } else {
939
+ ctx.capHeight = {
940
+ value: parseFloat(expr),
941
+ isRelative: false,
942
+ };
943
+ }
944
+ } catch {
945
+ // If parsing fails, treat the entire command as literal text
946
+ this.scanner.consume(-expr.length); // Rewind to before the expression
947
+ return;
948
+ }
949
+ }
950
+ this.consumeOptionalTerminator();
951
+ }
952
+
953
+ /**
954
+ * Parse width property
955
+ * @param ctx - The context to update
956
+ */
957
+ private parseWidth(ctx: MTextContext): void {
958
+ const expr = this.extractFloatExpression(true);
959
+ if (expr) {
960
+ try {
961
+ if (expr.endsWith('x')) {
962
+ // For width command, treat x suffix as relative value
963
+ ctx.widthFactor = {
964
+ value: parseFloat(expr.slice(0, -1)),
965
+ isRelative: true,
966
+ };
967
+ } else {
968
+ ctx.widthFactor = {
969
+ value: parseFloat(expr),
970
+ isRelative: false,
971
+ };
972
+ }
973
+ } catch {
974
+ // If parsing fails, treat the entire command as literal text
975
+ this.scanner.consume(-expr.length); // Rewind to before the expression
976
+ return;
977
+ }
978
+ }
979
+ this.consumeOptionalTerminator();
980
+ }
981
+
982
+ /**
983
+ * Parse character tracking property
984
+ * @param ctx - The context to update
985
+ */
986
+ private parseCharTracking(ctx: MTextContext): void {
987
+ const expr = this.extractFloatExpression(true);
988
+ if (expr) {
989
+ try {
990
+ if (expr.endsWith('x')) {
991
+ // For tracking command, treat x suffix as relative value
992
+ ctx.charTrackingFactor = {
993
+ value: Math.abs(parseFloat(expr.slice(0, -1))),
994
+ isRelative: true,
995
+ };
996
+ } else {
997
+ ctx.charTrackingFactor = {
998
+ value: Math.abs(parseFloat(expr)),
999
+ isRelative: false,
1000
+ };
1001
+ }
1002
+ } catch {
1003
+ // If parsing fails, treat the entire command as literal text
1004
+ this.scanner.consume(-expr.length); // Rewind to before the expression
1005
+ return;
1006
+ }
1007
+ }
1008
+ this.consumeOptionalTerminator();
1009
+ }
1010
+
1011
+ /**
1012
+ * Parse float value or factor
1013
+ * @param value - Current value to apply factor to
1014
+ * @returns New value
1015
+ */
1016
+ private parseFloatValueOrFactor(value: number): number {
1017
+ const expr = this.extractFloatExpression(true);
1018
+ if (expr) {
1019
+ if (expr.endsWith('x')) {
1020
+ const factor = parseFloat(expr.slice(0, -1));
1021
+ value *= factor; // Allow negative factors
1022
+ } else {
1023
+ value = parseFloat(expr); // Allow negative values
1024
+ }
1025
+ }
1026
+ return value;
1027
+ }
1028
+
1029
+ /**
1030
+ * Parse oblique angle property
1031
+ * @param ctx - The context to update
1032
+ */
1033
+ private parseOblique(ctx: MTextContext): void {
1034
+ const obliqueExpr = this.extractFloatExpression(false);
1035
+ if (obliqueExpr) {
1036
+ ctx.oblique = parseFloat(obliqueExpr);
1037
+ }
1038
+ this.consumeOptionalTerminator();
1039
+ }
1040
+
1041
+ /**
1042
+ * Parse ACI color property
1043
+ * @param ctx - The context to update
1044
+ */
1045
+ private parseAciColor(ctx: MTextContext): void {
1046
+ const aciExpr = this.extractIntExpression();
1047
+ if (aciExpr) {
1048
+ const aci = parseInt(aciExpr);
1049
+ if (aci < 257) {
1050
+ ctx.color.aci = aci;
1051
+ }
1052
+ }
1053
+ this.consumeOptionalTerminator();
1054
+ }
1055
+
1056
+ /**
1057
+ * Parse RGB color property
1058
+ * @param ctx - The context to update
1059
+ */
1060
+ private parseRgbColor(ctx: MTextContext): void {
1061
+ const rgbExpr = this.extractIntExpression();
1062
+ if (rgbExpr) {
1063
+ const value = parseInt(rgbExpr) & 0xffffff;
1064
+ ctx.color.rgbValue = value;
1065
+ }
1066
+ this.consumeOptionalTerminator();
1067
+ }
1068
+
1069
+ /**
1070
+ * Extract float expression from scanner
1071
+ * @param relative - Whether to allow relative values (ending in 'x')
1072
+ * @returns Extracted expression
1073
+ */
1074
+ private extractFloatExpression(relative: boolean = false): string {
1075
+ const pattern = relative
1076
+ ? /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?x?/
1077
+ : /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/;
1078
+ const match = this.scanner.tail.match(pattern);
1079
+ if (match) {
1080
+ const result = match[0];
1081
+ this.scanner.consume(result.length);
1082
+ return result;
1083
+ }
1084
+ return '';
1085
+ }
1086
+
1087
+ /**
1088
+ * Extract integer expression from scanner
1089
+ * @returns Extracted expression
1090
+ */
1091
+ private extractIntExpression(): string {
1092
+ const match = this.scanner.tail.match(/^\d+/);
1093
+ if (match) {
1094
+ const result = match[0];
1095
+ this.scanner.consume(result.length);
1096
+ return result;
1097
+ }
1098
+ return '';
1099
+ }
1100
+
1101
+ /**
1102
+ * Extract expression until semicolon or end
1103
+ * @param escape - Whether to handle escaped semicolons
1104
+ * @returns Extracted expression
1105
+ */
1106
+ private extractExpression(escape: boolean = false): string {
1107
+ const stop = this.scanner.find(';', escape);
1108
+ if (stop < 0) {
1109
+ const expr = this.scanner.tail;
1110
+ this.scanner.consume(expr.length);
1111
+ return expr;
1112
+ }
1113
+ // Check if the semicolon is escaped by looking at the previous character
1114
+ const prevChar = this.scanner.peek(stop - this.scanner.currentIndex - 1);
1115
+ const isEscaped = prevChar === '\\';
1116
+ const expr = this.scanner.tail.slice(0, stop - this.scanner.currentIndex + (isEscaped ? 1 : 0));
1117
+ this.scanner.consume(expr.length + 1);
1118
+ return expr;
1119
+ }
1120
+
1121
+ /**
1122
+ * Parse font properties
1123
+ * @param ctx - The context to update
1124
+ */
1125
+ private parseFontProperties(ctx: MTextContext): void {
1126
+ const parts = this.extractExpression().split('|');
1127
+ if (parts.length > 0 && parts[0]) {
1128
+ const name = parts[0];
1129
+ let style: FontStyle = 'Regular';
1130
+ let weight = 400;
1131
+
1132
+ for (const part of parts.slice(1)) {
1133
+ if (part.startsWith('b1')) {
1134
+ weight = 700;
1135
+ } else if (part === 'i' || part.startsWith('i1')) {
1136
+ style = 'Italic';
1137
+ } else if (part === 'i0' || part.startsWith('i0')) {
1138
+ style = 'Regular';
1139
+ }
1140
+ }
1141
+
1142
+ ctx.fontFace = {
1143
+ family: name,
1144
+ style,
1145
+ weight,
1146
+ };
1147
+ }
1148
+ }
1149
+
1150
+ /**
1151
+ * Parse paragraph properties from the MText content
1152
+ * Handles properties like indentation, alignment, and tab stops
1153
+ * @param ctx - The context to update
1154
+ */
1155
+ private parseParagraphProperties(ctx: MTextContext): void {
1156
+ const scanner = new TextScanner(this.extractExpression());
1157
+ /** Current indentation value */
1158
+ let indent = ctx.paragraph.indent;
1159
+ /** Left margin value */
1160
+ let left = ctx.paragraph.left;
1161
+ /** Right margin value */
1162
+ let right = ctx.paragraph.right;
1163
+ /** Current paragraph alignment */
1164
+ let align = ctx.paragraph.align;
1165
+ /** Array of tab stop positions and types */
1166
+ let tabStops: (number | string)[] = [];
1167
+
1168
+ /**
1169
+ * Parse a floating point number from the scanner's current position.
1170
+ * Accepts an optional sign, a leading decimal point, and scientific notation,
1171
+ * matching {@link extractFloatExpression}.
1172
+ * On a match, consumes the number and any immediately following commas.
1173
+ * @returns The parsed value, or 0 when the scanner is not on a number.
1174
+ * A miss consumes nothing, so looping callers must advance themselves.
1175
+ */
1176
+ const parseFloatValue = (): number => {
1177
+ const match = scanner.tail.match(/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/);
1178
+ if (match) {
1179
+ const value = parseFloat(match[0]);
1180
+ scanner.consume(match[0].length);
1181
+ while (scanner.peek() === ',') {
1182
+ scanner.consume(1);
1183
+ }
1184
+ return value;
1185
+ }
1186
+ return 0;
1187
+ };
1188
+
1189
+ while (scanner.hasData) {
1190
+ const cmd = scanner.get();
1191
+ switch (cmd) {
1192
+ case 'i': // Indentation
1193
+ indent = parseFloatValue();
1194
+ break;
1195
+ case 'l': // Left margin
1196
+ left = parseFloatValue();
1197
+ break;
1198
+ case 'r': // Right margin
1199
+ right = parseFloatValue();
1200
+ break;
1201
+ case 'x': // Skip
1202
+ break;
1203
+ case 'q': {
1204
+ // Alignment
1205
+ const adjustment = scanner.get();
1206
+ align = CHAR_TO_ALIGN[adjustment] || MTextParagraphAlignment.DEFAULT;
1207
+ while (scanner.peek() === ',') {
1208
+ scanner.consume(1);
1209
+ }
1210
+ break;
1211
+ }
1212
+ case 't': // Tab stops
1213
+ tabStops = [];
1214
+ while (scanner.hasData) {
1215
+ const indexBefore = scanner.currentIndex;
1216
+ const type = scanner.peek();
1217
+ if (type === 'r' || type === 'c') {
1218
+ scanner.consume(1);
1219
+ const valueIndex = scanner.currentIndex;
1220
+ const value = parseFloatValue();
1221
+ // 0 is also the miss result, so record a right/center stop only
1222
+ // when a number was consumed. Otherwise `\ptrz` becomes a fake
1223
+ // right tab at 0.
1224
+ if (scanner.currentIndex !== valueIndex) {
1225
+ tabStops.push(type + value.toString());
1226
+ }
1227
+ } else {
1228
+ const value = parseFloatValue();
1229
+ if (scanner.currentIndex !== indexBefore) {
1230
+ tabStops.push(value);
1231
+ }
1232
+ }
1233
+ // AutoCAD clears tab stops with `\pi0,l0,tz;`. `z` matches no
1234
+ // number and leaves the scanner in place; consume it or this
1235
+ // loop pushes zeros until it runs out of memory.
1236
+ if (scanner.currentIndex === indexBefore) {
1237
+ scanner.consume(1);
1238
+ }
1239
+ }
1240
+ break;
1241
+ }
1242
+ }
1243
+
1244
+ ctx.paragraph = {
1245
+ indent,
1246
+ left,
1247
+ right,
1248
+ align,
1249
+ tabs: tabStops,
1250
+ };
1251
+ }
1252
+
1253
+ /**
1254
+ * Consume optional terminator (semicolon)
1255
+ */
1256
+ private consumeOptionalTerminator(): void {
1257
+ if (this.scanner.peek() === ';') {
1258
+ this.scanner.consume(1);
1259
+ }
1260
+ }
1261
+
1262
+ /**
1263
+ * Builds {@link PercentSymbolData} for a recognized `%%` code letter.
1264
+ */
1265
+ private buildPercentSymbolData(code: string, specialChar: string): PercentSymbolData | null {
1266
+ if (code === 'c' || code === 'd' || code === 'p') {
1267
+ return { kind: 'named', code, char: specialChar };
1268
+ }
1269
+ if (code === '%') {
1270
+ return { kind: 'literal', char: '%' };
1271
+ }
1272
+ return null;
1273
+ }
1274
+
1275
+ /**
1276
+ * Parse MText content into tokens
1277
+ * @yields MTextToken objects
1278
+ */
1279
+ *parse(): Generator<MTextToken> {
1280
+ const wordToken = TokenType.WORD;
1281
+ const spaceToken = TokenType.SPACE;
1282
+ let followupToken: TokenType | null = null;
1283
+ let followupData: TokenData[TokenType] | undefined;
1284
+
1285
+ function resetParagraph(ctx: MTextContext): Partial<ParagraphProperties> {
1286
+ const prev = { ...ctx.paragraph };
1287
+ ctx.paragraph = {
1288
+ indent: 0,
1289
+ left: 0,
1290
+ right: 0,
1291
+ align: MTextParagraphAlignment.DEFAULT,
1292
+ tabs: [],
1293
+ };
1294
+ const changed: Partial<ParagraphProperties> = {};
1295
+ if (prev.indent !== 0) changed.indent = 0;
1296
+ if (prev.left !== 0) changed.left = 0;
1297
+ if (prev.right !== 0) changed.right = 0;
1298
+ if (prev.align !== MTextParagraphAlignment.DEFAULT)
1299
+ changed.align = MTextParagraphAlignment.DEFAULT;
1300
+ if (JSON.stringify(prev.tabs) !== JSON.stringify([])) changed.tabs = [];
1301
+ return changed;
1302
+ }
1303
+
1304
+ const nextToken = (): [TokenType, TokenData[TokenType]] => {
1305
+ let word = '';
1306
+ while (this.scanner.hasData) {
1307
+ let escape = false;
1308
+ let letter = this.scanner.peek();
1309
+ const cmdStartIndex = this.scanner.currentIndex;
1310
+
1311
+ // Handle control characters first. Flush any pending word before emitting
1312
+ // paragraph/tab tokens — the same pattern used for spaces and `\P` — so
1313
+ // LibreDWG/DXF converters that expand `\P` to raw `\n` do not drop text.
1314
+ if (letter.charCodeAt(0) < 32) {
1315
+ if (letter === '\t') {
1316
+ this.scanner.consume(1);
1317
+ if (word) {
1318
+ followupToken = TokenType.TABULATOR;
1319
+ followupData = null;
1320
+ return [wordToken, word];
1321
+ }
1322
+ return [TokenType.TABULATOR, null];
1323
+ }
1324
+ if (letter === '\n') {
1325
+ this.scanner.consume(1);
1326
+ if (word) {
1327
+ followupToken = TokenType.NEW_PARAGRAPH;
1328
+ followupData = null;
1329
+ return [wordToken, word];
1330
+ }
1331
+ return [TokenType.NEW_PARAGRAPH, null];
1332
+ }
1333
+ // Other C0 controls behave like a space delimiter.
1334
+ this.scanner.consume(1);
1335
+ if (word) {
1336
+ followupToken = spaceToken;
1337
+ return [wordToken, word];
1338
+ }
1339
+ return [spaceToken, null];
1340
+ }
1341
+
1342
+ if (letter === '\\') {
1343
+ if ('\\{}'.includes(this.scanner.peek(1))) {
1344
+ escape = true;
1345
+ this.scanner.consume(1);
1346
+ letter = this.scanner.peek();
1347
+ } else {
1348
+ if (word) {
1349
+ return [wordToken, word];
1350
+ }
1351
+ this.scanner.consume(1);
1352
+ const cmd = this.scanner.get();
1353
+ switch (cmd) {
1354
+ case '~':
1355
+ return [TokenType.NBSP, null];
1356
+ case 'P':
1357
+ return [TokenType.NEW_PARAGRAPH, null];
1358
+ case 'N':
1359
+ return [TokenType.NEW_COLUMN, null];
1360
+ case 'X':
1361
+ return [TokenType.WRAP_AT_DIMLINE, null];
1362
+ case 'S': {
1363
+ this.inStackContext = true;
1364
+ const result = this.parseStacking();
1365
+ this.inStackContext = false;
1366
+ return result;
1367
+ }
1368
+ case 'm':
1369
+ case 'M':
1370
+ // Handle multi-byte character encoding (MIF)
1371
+ if (this.scanner.peek() === '+') {
1372
+ this.scanner.consume(1); // Consume the '+'
1373
+ const hexCode = this.extractMifCode(this.mifCodeLength);
1374
+ if (hexCode) {
1375
+ this.scanner.consume(hexCode.length);
1376
+ const decodedChar = this.mifDecoder(hexCode);
1377
+ if (word) {
1378
+ return [wordToken, word];
1379
+ }
1380
+ return [wordToken, decodedChar];
1381
+ }
1382
+ // If no valid hex code found, rewind the '+' character
1383
+ this.scanner.consume(-1);
1384
+ }
1385
+ // If not a valid multi-byte code, treat as literal text
1386
+ word += '\\M';
1387
+ continue;
1388
+ case 'U': {
1389
+ // AutoCAD \U+nnnn uses exactly four hex digits. Characters
1390
+ // outside the BMP are encoded as two consecutive \U+XXXX
1391
+ // UTF-16 surrogate escapes.
1392
+ const decodedChar = this.parseUnicodeEscape();
1393
+ if (decodedChar !== null) {
1394
+ if (word) {
1395
+ return [wordToken, word];
1396
+ }
1397
+ return [wordToken, decodedChar];
1398
+ }
1399
+ // If not a valid Unicode code, treat as literal text
1400
+ word += '\\U';
1401
+ continue;
1402
+ }
1403
+ default:
1404
+ if (cmd) {
1405
+ try {
1406
+ const propertyChanges = this.parseProperties(cmd);
1407
+ if (this.yieldPropertyCommands && propertyChanges) {
1408
+ return [TokenType.PROPERTIES_CHANGED, propertyChanges];
1409
+ }
1410
+ // After processing a property command, continue with normal parsing
1411
+ continue;
1412
+ } catch {
1413
+ const commandText = this.scanner.tail.slice(
1414
+ cmdStartIndex,
1415
+ this.scanner.currentIndex
1416
+ );
1417
+ word += commandText;
1418
+ }
1419
+ }
1420
+ }
1421
+ continue;
1422
+ }
1423
+ }
1424
+
1425
+ if (letter === '%' && this.scanner.peek(1) === '%') {
1426
+ const code = this.scanner.peek(2).toLowerCase();
1427
+ const specialChar = SPECIAL_CHAR_ENCODING[code];
1428
+ if (specialChar) {
1429
+ this.scanner.consume(3);
1430
+ if (this.yieldPercentSymbols) {
1431
+ const symbolData = this.buildPercentSymbolData(code, specialChar);
1432
+ if (symbolData) {
1433
+ if (word) {
1434
+ followupToken = TokenType.PERCENT_SYMBOL;
1435
+ followupData = symbolData;
1436
+ return [wordToken, word];
1437
+ }
1438
+ return [TokenType.PERCENT_SYMBOL, symbolData];
1439
+ }
1440
+ }
1441
+ word += specialChar;
1442
+ continue;
1443
+ } else {
1444
+ /**
1445
+ * Supports Control Codes: `%%nnn`, where nnn is 1–3 decimal digits
1446
+ * for the character's Unicode/ASCII code point (e.g. `%%34` → `"`,
1447
+ * `%%176` → `°`). Digit count is not fixed at three.
1448
+ *
1449
+ * Reference: https://help.autodesk.com/view/ACD/2026/ENU/?guid=GUID-968CBC1D-BA99-4519-ABDD-88419EB2BF92
1450
+ */
1451
+ const digitChars: string[] = [];
1452
+ for (let i = 0; i < 3; i++) {
1453
+ const d = this.scanner.peek(2 + i);
1454
+ if (d >= '0' && d <= '9') {
1455
+ digitChars.push(d);
1456
+ } else {
1457
+ break;
1458
+ }
1459
+ }
1460
+
1461
+ if (digitChars.length > 0) {
1462
+ const charCode = Number.parseInt(digitChars.join(''), 10);
1463
+ this.scanner.consume(2 + digitChars.length);
1464
+ if (this.yieldPercentSymbols) {
1465
+ const symbolData: PercentSymbolData = {
1466
+ kind: 'numeric',
1467
+ charCode,
1468
+ char: String.fromCharCode(charCode),
1469
+ };
1470
+ if (word) {
1471
+ followupToken = TokenType.PERCENT_SYMBOL;
1472
+ followupData = symbolData;
1473
+ return [wordToken, word];
1474
+ }
1475
+ return [TokenType.PERCENT_SYMBOL, symbolData];
1476
+ }
1477
+ word += String.fromCharCode(charCode);
1478
+ } else {
1479
+ // Skip invalid special character codes (`%%` + non-digit)
1480
+ this.scanner.consume(3);
1481
+ }
1482
+
1483
+ continue;
1484
+ }
1485
+ }
1486
+
1487
+ if (letter === ' ') {
1488
+ if (word) {
1489
+ this.scanner.consume(1);
1490
+ followupToken = spaceToken;
1491
+ return [wordToken, word];
1492
+ }
1493
+ this.scanner.consume(1);
1494
+ return [spaceToken, null];
1495
+ }
1496
+
1497
+ if (!escape) {
1498
+ if (letter === '{') {
1499
+ if (word) {
1500
+ return [wordToken, word];
1501
+ }
1502
+ this.scanner.consume(1);
1503
+ this.pushCtx();
1504
+ continue;
1505
+ } else if (letter === '}') {
1506
+ if (word) {
1507
+ return [wordToken, word];
1508
+ }
1509
+ this.scanner.consume(1);
1510
+ // Context restoration with yieldPropertyCommands
1511
+ if (this.yieldPropertyCommands) {
1512
+ const prevCtx = this.ctxStack.current;
1513
+ this.popCtx();
1514
+ const changes = this.getPropertyChanges(prevCtx, this.ctxStack.current);
1515
+ if (Object.keys(changes).length > 0) {
1516
+ return [
1517
+ TokenType.PROPERTIES_CHANGED,
1518
+ { command: undefined, changes, depth: this.ctxStack.depth },
1519
+ ];
1520
+ }
1521
+ } else {
1522
+ this.popCtx();
1523
+ }
1524
+ continue;
1525
+ }
1526
+ }
1527
+
1528
+ // Handle caret-encoded characters only when not in stack context
1529
+ if (!this.inStackContext && letter === '^') {
1530
+ const nextChar = this.scanner.peek(1);
1531
+ if (nextChar) {
1532
+ const code = nextChar.charCodeAt(0);
1533
+ this.scanner.consume(2); // Consume both ^ and the next character
1534
+ if (code === 32) {
1535
+ // Space
1536
+ word += '^';
1537
+ } else if (code === 73) {
1538
+ // Tab
1539
+ if (word) {
1540
+ return [wordToken, word];
1541
+ }
1542
+ return [TokenType.TABULATOR, null];
1543
+ } else if (code === 74) {
1544
+ // Line feed
1545
+ if (word) {
1546
+ return [wordToken, word];
1547
+ }
1548
+ return [TokenType.NEW_PARAGRAPH, null];
1549
+ } else if (code === 77) {
1550
+ // Carriage return
1551
+ // Ignore carriage return
1552
+ continue;
1553
+ } else {
1554
+ word += '▯';
1555
+ }
1556
+ continue;
1557
+ }
1558
+ }
1559
+
1560
+ this.scanner.consume(1);
1561
+ if (letter.charCodeAt(0) >= 32) {
1562
+ word += letter;
1563
+ }
1564
+ }
1565
+
1566
+ if (word) {
1567
+ return [wordToken, word];
1568
+ }
1569
+ return [TokenType.NONE, null];
1570
+ };
1571
+
1572
+ const maybeResetAfterParagraph = (tokenType: TokenType) => {
1573
+ if (tokenType !== TokenType.NEW_PARAGRAPH || !this.resetParagraphParameters) {
1574
+ return;
1575
+ }
1576
+ // Reset paragraph properties and emit PROPERTIES_CHANGED if needed
1577
+ const ctx = this.ctxStack.current;
1578
+ const changed = resetParagraph(ctx);
1579
+ if (this.yieldPropertyCommands && Object.keys(changed).length > 0) {
1580
+ return new MTextToken(TokenType.PROPERTIES_CHANGED, ctx.copy(), {
1581
+ command: undefined,
1582
+ changes: { paragraph: changed },
1583
+ depth: this.ctxStack.depth,
1584
+ });
1585
+ }
1586
+ return;
1587
+ };
1588
+
1589
+ while (true) {
1590
+ const [type, data] = nextToken.call(this);
1591
+ if (type) {
1592
+ yield new MTextToken(type, this.ctxStack.current.copy(), data);
1593
+ const resetToken = maybeResetAfterParagraph(type);
1594
+ if (resetToken) {
1595
+ yield resetToken;
1596
+ }
1597
+ if (followupToken) {
1598
+ yield new MTextToken(followupToken, this.ctxStack.current.copy(), followupData ?? null);
1599
+ const followupResetToken = maybeResetAfterParagraph(followupToken);
1600
+ if (followupResetToken) {
1601
+ yield followupResetToken;
1602
+ }
1603
+ followupToken = null;
1604
+ followupData = undefined;
1605
+ }
1606
+ } else {
1607
+ break;
1608
+ }
1609
+ }
1610
+ }
1611
+ }
1612
+
1613
+ /**
1614
+ * Text scanner for parsing MText content
1615
+ */
1616
+ export class TextScanner {
1617
+ private text: string;
1618
+ private textLen: number;
1619
+ private _index: number;
1620
+
1621
+ /**
1622
+ * Create a new text scanner
1623
+ * @param text - The text to scan
1624
+ */
1625
+ constructor(text: string) {
1626
+ this.text = text;
1627
+ this.textLen = text.length;
1628
+ this._index = 0;
1629
+ }
1630
+
1631
+ /**
1632
+ * Get the current index in the text
1633
+ */
1634
+ get currentIndex(): number {
1635
+ return this._index;
1636
+ }
1637
+
1638
+ /**
1639
+ * Check if the scanner has reached the end of the text
1640
+ */
1641
+ get isEmpty(): boolean {
1642
+ return this._index >= this.textLen;
1643
+ }
1644
+
1645
+ /**
1646
+ * Check if there is more text to scan
1647
+ */
1648
+ get hasData(): boolean {
1649
+ return this._index < this.textLen;
1650
+ }
1651
+
1652
+ /**
1653
+ * Get the next character and advance the index
1654
+ * @returns The next character, or empty string if at end
1655
+ */
1656
+ get(): string {
1657
+ if (this.isEmpty) {
1658
+ return '';
1659
+ }
1660
+ const char = this.text[this._index];
1661
+ this._index++;
1662
+ return char;
1663
+ }
1664
+
1665
+ /**
1666
+ * Advance the index by the specified count
1667
+ * @param count - Number of characters to advance
1668
+ */
1669
+ consume(count: number = 1): void {
1670
+ this._index = Math.max(0, Math.min(this._index + count, this.textLen));
1671
+ }
1672
+
1673
+ /**
1674
+ * Look at a character without advancing the index
1675
+ * @param offset - Offset from current position
1676
+ * @returns The character at the offset position, or empty string if out of bounds
1677
+ */
1678
+ peek(offset: number = 0): string {
1679
+ const index = this._index + offset;
1680
+ if (index >= this.textLen || index < 0) {
1681
+ return '';
1682
+ }
1683
+ return this.text[index];
1684
+ }
1685
+
1686
+ /**
1687
+ * Find the next occurrence of a character
1688
+ * @param char - The character to find
1689
+ * @param escape - Whether to handle escaped characters
1690
+ * @returns Index of the character, or -1 if not found
1691
+ */
1692
+ find(char: string, escape: boolean = false): number {
1693
+ let index = this._index;
1694
+ while (index < this.textLen) {
1695
+ if (escape && this.text[index] === '\\') {
1696
+ if (index + 1 < this.textLen) {
1697
+ if (this.text[index + 1] === char) {
1698
+ return index + 1;
1699
+ }
1700
+ index += 2;
1701
+ continue;
1702
+ }
1703
+ index++;
1704
+ continue;
1705
+ }
1706
+ if (this.text[index] === char) {
1707
+ return index;
1708
+ }
1709
+ index++;
1710
+ }
1711
+ return -1;
1712
+ }
1713
+
1714
+ /**
1715
+ * Get the remaining text from the current position
1716
+ */
1717
+ get tail(): string {
1718
+ return this.text.slice(this._index);
1719
+ }
1720
+
1721
+ /**
1722
+ * Check if the next character is a space
1723
+ */
1724
+ isNextSpace(): boolean {
1725
+ return this.peek() === ' ';
1726
+ }
1727
+
1728
+ /**
1729
+ * Consume spaces until a non-space character is found
1730
+ * @returns Number of spaces consumed
1731
+ */
1732
+ consumeSpaces(): number {
1733
+ let count = 0;
1734
+ while (this.isNextSpace()) {
1735
+ this.consume();
1736
+ count++;
1737
+ }
1738
+ return count;
1739
+ }
1740
+ }
1741
+
1742
+ /**
1743
+ * Class to handle ACI and RGB color logic for MText.
1744
+ *
1745
+ * This class encapsulates color state for MText, supporting both AutoCAD Color Index (ACI) and RGB color.
1746
+ * Only one color mode is active at a time: setting an RGB color disables ACI, and vice versa.
1747
+ * RGB is stored as a single 24-bit integer (0xRRGGBB) for efficient comparison and serialization.
1748
+ *
1749
+ * Example usage:
1750
+ * ```ts
1751
+ * const color1 = new MTextColor(1); // ACI color
1752
+ * const color2 = new MTextColor([255, 0, 0]); // RGB color
1753
+ * const color3 = new MTextColor(); // Default (ACI=256, "by layer")
1754
+ * ```
1755
+ */
1756
+ export class MTextColor {
1757
+ /**
1758
+ * The AutoCAD Color Index (ACI) value. Only used if no RGB color is set.
1759
+ * @default 256 ("by layer")
1760
+ */
1761
+ private _aci: number | null = 256;
1762
+ /**
1763
+ * The RGB color value as a single 24-bit integer (0xRRGGBB), or null if not set.
1764
+ * @default null
1765
+ */
1766
+ private _rgbValue: number | null = null; // Store as 0xRRGGBB or null
1767
+
1768
+ /**
1769
+ * Create a new MTextColor instance.
1770
+ * @param color The initial color: number for ACI, [r,g,b] for RGB, or null/undefined for default (ACI=256).
1771
+ */
1772
+ constructor(color?: number | RGB | null) {
1773
+ if (Array.isArray(color)) {
1774
+ this.rgb = color;
1775
+ } else if (typeof color === 'number') {
1776
+ this.aci = color;
1777
+ } else {
1778
+ this.aci = 256;
1779
+ }
1780
+ }
1781
+
1782
+ /**
1783
+ * Get the current ACI color value.
1784
+ * @returns The ACI color (0-256), or null if using RGB.
1785
+ */
1786
+ get aci(): number | null {
1787
+ return this._aci;
1788
+ }
1789
+
1790
+ /**
1791
+ * Set the ACI color value. Setting this disables any RGB color.
1792
+ * @param value The ACI color (0-256), or null to unset.
1793
+ * @throws Error if value is out of range.
1794
+ */
1795
+ set aci(value: number | null) {
1796
+ if (value === null) {
1797
+ this._aci = null;
1798
+ } else if (value >= 0 && value <= 256) {
1799
+ this._aci = value;
1800
+ this._rgbValue = null;
1801
+ } else {
1802
+ throw new Error('ACI not in range [0, 256]');
1803
+ }
1804
+ }
1805
+
1806
+ /**
1807
+ * Get the current RGB color as a tuple [r, g, b], or null if not set.
1808
+ * @returns The RGB color tuple, or null if using ACI.
1809
+ */
1810
+ get rgb(): RGB | null {
1811
+ if (this._rgbValue === null) return null;
1812
+ // Extract R, G, B from 0xRRGGBB
1813
+ const r = (this._rgbValue >> 16) & 0xff;
1814
+ const g = (this._rgbValue >> 8) & 0xff;
1815
+ const b = this._rgbValue & 0xff;
1816
+ return [r, g, b];
1817
+ }
1818
+
1819
+ /**
1820
+ * Set the RGB color. Setting this disables ACI color.
1821
+ * @param value The RGB color tuple [r, g, b], or null to use ACI.
1822
+ */
1823
+ set rgb(value: RGB | null) {
1824
+ if (value) {
1825
+ const [r, g, b] = value;
1826
+ this._rgbValue = ((r & 0xff) << 16) | ((g & 0xff) << 8) | (b & 0xff);
1827
+ this._aci = null;
1828
+ } else {
1829
+ this._rgbValue = null;
1830
+ }
1831
+ }
1832
+
1833
+ /**
1834
+ * Returns true if the color is set by RGB, false if by ACI.
1835
+ */
1836
+ get isRgb(): boolean {
1837
+ return this._rgbValue !== null;
1838
+ }
1839
+
1840
+ /**
1841
+ * Returns true if the color is set by ACI, false if by RGB.
1842
+ */
1843
+ get isAci(): boolean {
1844
+ return this._rgbValue === null && this._aci !== null;
1845
+ }
1846
+
1847
+ /**
1848
+ * Get or set the internal RGB value as a number (0xRRGGBB), or null if not set.
1849
+ * Setting this will switch to RGB mode and set ACI to null.
1850
+ */
1851
+ get rgbValue(): number | null {
1852
+ return this._rgbValue;
1853
+ }
1854
+
1855
+ set rgbValue(val: number | null) {
1856
+ if (val === null) {
1857
+ this._rgbValue = null;
1858
+ } else {
1859
+ this._rgbValue = val & 0xffffff;
1860
+ this._aci = null;
1861
+ }
1862
+ }
1863
+
1864
+ /**
1865
+ * Returns a deep copy of this color.
1866
+ * @returns A new MTextColor instance with the same color state.
1867
+ */
1868
+ copy(): MTextColor {
1869
+ const c = new MTextColor();
1870
+ c._aci = this._aci;
1871
+ c._rgbValue = this._rgbValue;
1872
+ return c;
1873
+ }
1874
+
1875
+ /**
1876
+ * Returns a plain object for serialization.
1877
+ * @returns An object with aci, rgb (tuple), and rgbValue (number or null).
1878
+ */
1879
+ toObject(): { aci: number | null; rgb: RGB | null; rgbValue: number | null } {
1880
+ return { aci: this._aci, rgb: this.rgb, rgbValue: this._rgbValue };
1881
+ }
1882
+
1883
+ /**
1884
+ * Convert the current color to a CSS hex color string (#rrggbb).
1885
+ * Returns null if the color is ACI-based and has no RGB value.
1886
+ */
1887
+ toCssColor(): string | null {
1888
+ if (this._rgbValue !== null) {
1889
+ return colorNumberToHex(this._rgbValue);
1890
+ }
1891
+ return null;
1892
+ }
1893
+
1894
+ /**
1895
+ * Create an MTextColor from a CSS color string.
1896
+ * Supports #rgb, #rrggbb, rgb(...), rgba(...). Returns null if invalid or transparent.
1897
+ */
1898
+ static fromCssColor(value: string | null | undefined): MTextColor | null {
1899
+ const rgbValue = cssColorToRgbValue(value);
1900
+ if (rgbValue === null) return null;
1901
+ const color = new MTextColor();
1902
+ color.rgbValue = rgbValue;
1903
+ return color;
1904
+ }
1905
+
1906
+ /**
1907
+ * Equality check for color.
1908
+ * @param other The other MTextColor to compare.
1909
+ * @returns True if both ACI and RGB values are equal.
1910
+ */
1911
+ equals(other: MTextColor): boolean {
1912
+ return this._aci === other._aci && this._rgbValue === other._rgbValue;
1913
+ }
1914
+ }
1915
+
1916
+ /**
1917
+ * MText context class for managing text formatting state
1918
+ */
1919
+ export class MTextContext {
1920
+ private _stroke: number = 0;
1921
+ /** Whether to continue stroke formatting */
1922
+ continueStroke: boolean = false;
1923
+ /** Color (ACI or RGB) */
1924
+ color: MTextColor = new MTextColor();
1925
+ /** Line alignment */
1926
+ align: MTextLineAlignment = MTextLineAlignment.BOTTOM;
1927
+ /** Font face properties */
1928
+ fontFace: FontFace = { family: '', style: 'Regular', weight: 400 };
1929
+ /** Capital letter height */
1930
+ private _capHeight: FactorValue = { value: 1.0, isRelative: false };
1931
+ /** Character width factor */
1932
+ private _widthFactor: FactorValue = { value: 1.0, isRelative: false };
1933
+ /**
1934
+ * Character tracking factor a multiplier applied to the default spacing between characters in the MText object.
1935
+ * - Value = 1.0 → Normal spacing.
1936
+ * - Value < 1.0 → Characters are closer together.
1937
+ * - Value > 1.0 → Characters are spaced farther apart.
1938
+ */
1939
+ private _charTrackingFactor: FactorValue = { value: 1.0, isRelative: false };
1940
+ /** Oblique angle */
1941
+ oblique: number = 0.0;
1942
+ /** Paragraph properties */
1943
+ paragraph: ParagraphProperties = {
1944
+ indent: 0,
1945
+ left: 0,
1946
+ right: 0,
1947
+ align: MTextParagraphAlignment.DEFAULT,
1948
+ tabs: [],
1949
+ };
1950
+
1951
+ /**
1952
+ * Get the capital letter height
1953
+ */
1954
+ get capHeight(): FactorValue {
1955
+ return this._capHeight;
1956
+ }
1957
+
1958
+ /**
1959
+ * Set the capital letter height
1960
+ * @param value - Height value
1961
+ */
1962
+ set capHeight(value: FactorValue) {
1963
+ this._capHeight = {
1964
+ value: Math.abs(value.value),
1965
+ isRelative: value.isRelative,
1966
+ };
1967
+ }
1968
+
1969
+ /**
1970
+ * Get the character width factor
1971
+ */
1972
+ get widthFactor(): FactorValue {
1973
+ return this._widthFactor;
1974
+ }
1975
+
1976
+ /**
1977
+ * Set the character width factor
1978
+ * @param value - Width factor value
1979
+ */
1980
+ set widthFactor(value: FactorValue) {
1981
+ this._widthFactor = {
1982
+ value: Math.abs(value.value),
1983
+ isRelative: value.isRelative,
1984
+ };
1985
+ }
1986
+
1987
+ /**
1988
+ * Get the character tracking factor
1989
+ */
1990
+ get charTrackingFactor(): FactorValue {
1991
+ return this._charTrackingFactor;
1992
+ }
1993
+
1994
+ /**
1995
+ * Set the character tracking factor
1996
+ * @param value - Tracking factor value
1997
+ */
1998
+ set charTrackingFactor(value: FactorValue) {
1999
+ this._charTrackingFactor = {
2000
+ value: Math.abs(value.value),
2001
+ isRelative: value.isRelative,
2002
+ };
2003
+ }
2004
+
2005
+ /**
2006
+ * Get the ACI color value
2007
+ */
2008
+ get aci(): number | null {
2009
+ return this.color.aci;
2010
+ }
2011
+
2012
+ /**
2013
+ * Set the ACI color value
2014
+ * @param value - ACI color value (0-256)
2015
+ * @throws Error if value is out of range
2016
+ */
2017
+ set aci(value: number) {
2018
+ this.color.aci = value;
2019
+ }
2020
+
2021
+ /**
2022
+ * Get the RGB color value
2023
+ */
2024
+ get rgb(): RGB | null {
2025
+ return this.color.rgb;
2026
+ }
2027
+
2028
+ /**
2029
+ * Set the RGB color value
2030
+ */
2031
+ set rgb(value: RGB | null) {
2032
+ this.color.rgb = value;
2033
+ }
2034
+
2035
+ /**
2036
+ * Gets whether the current text should be rendered in italic style.
2037
+ * @returns {boolean} True if the font style is 'Italic', otherwise false.
2038
+ */
2039
+ get italic(): boolean {
2040
+ return this.fontFace.style === 'Italic';
2041
+ }
2042
+ /**
2043
+ * Sets whether the current text should be rendered in italic style.
2044
+ * @param value - If true, sets the font style to 'Italic'; if false, sets it to 'Regular'.
2045
+ */
2046
+ set italic(value: boolean) {
2047
+ this.fontFace.style = value ? 'Italic' : 'Regular';
2048
+ }
2049
+
2050
+ /**
2051
+ * Gets whether the current text should be rendered in bold style.
2052
+ * This is primarily used for mesh fonts and affects font selection.
2053
+ * @returns {boolean} True if the font weight is 700 or higher, otherwise false.
2054
+ */
2055
+ get bold(): boolean {
2056
+ return (this.fontFace.weight || 400) >= 700;
2057
+ }
2058
+ /**
2059
+ * Sets whether the current text should be rendered in bold style.
2060
+ * This is primarily used for mesh fonts and affects font selection.
2061
+ * @param value - If true, sets the font weight to 700; if false, sets it to 400.
2062
+ */
2063
+ set bold(value: boolean) {
2064
+ this.fontFace.weight = value ? 700 : 400;
2065
+ }
2066
+
2067
+ /**
2068
+ * Get whether text is underlined
2069
+ */
2070
+ get underline(): boolean {
2071
+ return Boolean(this._stroke & MTextStroke.UNDERLINE);
2072
+ }
2073
+
2074
+ /**
2075
+ * Set whether text is underlined
2076
+ * @param value - Whether to underline
2077
+ */
2078
+ set underline(value: boolean) {
2079
+ this._setStrokeState(MTextStroke.UNDERLINE, value);
2080
+ }
2081
+
2082
+ /**
2083
+ * Get whether text has strike-through
2084
+ */
2085
+ get strikeThrough(): boolean {
2086
+ return Boolean(this._stroke & MTextStroke.STRIKE_THROUGH);
2087
+ }
2088
+
2089
+ /**
2090
+ * Set whether text has strike-through
2091
+ * @param value - Whether to strike through
2092
+ */
2093
+ set strikeThrough(value: boolean) {
2094
+ this._setStrokeState(MTextStroke.STRIKE_THROUGH, value);
2095
+ }
2096
+
2097
+ /**
2098
+ * Get whether text has overline
2099
+ */
2100
+ get overline(): boolean {
2101
+ return Boolean(this._stroke & MTextStroke.OVERLINE);
2102
+ }
2103
+
2104
+ /**
2105
+ * Set whether text has overline
2106
+ * @param value - Whether to overline
2107
+ */
2108
+ set overline(value: boolean) {
2109
+ this._setStrokeState(MTextStroke.OVERLINE, value);
2110
+ }
2111
+
2112
+ /**
2113
+ * Check if any stroke formatting is active
2114
+ */
2115
+ get hasAnyStroke(): boolean {
2116
+ return Boolean(this._stroke);
2117
+ }
2118
+
2119
+ /**
2120
+ * Set the state of a stroke type
2121
+ * @param stroke - The stroke type to set
2122
+ * @param state - Whether to enable or disable the stroke
2123
+ */
2124
+ private _setStrokeState(stroke: MTextStroke, state: boolean = true): void {
2125
+ if (state) {
2126
+ this._stroke |= stroke;
2127
+ } else {
2128
+ this._stroke &= ~stroke;
2129
+ }
2130
+ }
2131
+
2132
+ /**
2133
+ * Create a copy of this context
2134
+ * @returns A new context with the same properties
2135
+ */
2136
+ copy(): MTextContext {
2137
+ const ctx = new MTextContext();
2138
+ ctx._stroke = this._stroke;
2139
+ ctx.continueStroke = this.continueStroke;
2140
+ ctx.color = this.color.copy();
2141
+ ctx.align = this.align;
2142
+ ctx.fontFace = { ...this.fontFace };
2143
+ ctx._capHeight = { ...this._capHeight };
2144
+ ctx._widthFactor = { ...this._widthFactor };
2145
+ ctx._charTrackingFactor = { ...this._charTrackingFactor };
2146
+ ctx.oblique = this.oblique;
2147
+ ctx.paragraph = { ...this.paragraph };
2148
+ return ctx;
2149
+ }
2150
+ }
2151
+
2152
+ /**
2153
+ * Token class for MText parsing
2154
+ */
2155
+ export class MTextToken {
2156
+ /**
2157
+ * Create a new MText token
2158
+ * @param type - The token type
2159
+ * @param ctx - The text context at this token
2160
+ * @param data - Optional token data
2161
+ */
2162
+ constructor(
2163
+ public type: TokenType,
2164
+ public ctx: MTextContext,
2165
+ public data: TokenData[TokenType]
2166
+ ) {}
2167
+ }