@latex-kit/escape 0.0.0-stage → 0.2.0
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/LICENSE +23 -0
- package/README.md +87 -2
- package/esm/index.d.ts +48 -0
- package/esm/index.js +128 -0
- package/index.d.ts +48 -0
- package/index.js +136 -0
- package/package.json +41 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dan Lynch <pyramation@gmail.com>
|
|
4
|
+
Copyright (c) 2026 Constructive <developers@constructive.io>
|
|
5
|
+
Copyright (c) 2020-present, Interweb, Inc.
|
|
6
|
+
|
|
7
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
8
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
9
|
+
in the Software without restriction, including without limitation the rights
|
|
10
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
12
|
+
furnished to do so, subject to the following conditions:
|
|
13
|
+
|
|
14
|
+
The above copyright notice and this permission notice shall be included in all
|
|
15
|
+
copies or substantial portions of the Software.
|
|
16
|
+
|
|
17
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
18
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
19
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
20
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
21
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
22
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
23
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,88 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @latex-kit/escape
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p align="center" width="100%">
|
|
4
|
+
<img height="250" src="https://raw.githubusercontent.com/constructive-io/constructive/refs/heads/main/assets/outline-logo.svg" />
|
|
5
|
+
</p>
|
|
6
|
+
|
|
7
|
+
<p align="center" width="100%">
|
|
8
|
+
<a href="https://github.com/constructive-io/latex-kit/actions/workflows/ci.yml">
|
|
9
|
+
<img height="20" src="https://github.com/constructive-io/latex-kit/actions/workflows/ci.yml/badge.svg" />
|
|
10
|
+
</a>
|
|
11
|
+
<a href="https://github.com/constructive-io/latex-kit/blob/main/LICENSE">
|
|
12
|
+
<img height="20" src="https://img.shields.io/badge/license-MIT-blue.svg"/>
|
|
13
|
+
</a>
|
|
14
|
+
<a href="https://www.npmjs.com/package/@latex-kit/escape">
|
|
15
|
+
<img height="20" src="https://img.shields.io/npm/v/@latex-kit/escape.svg"/>
|
|
16
|
+
</a>
|
|
17
|
+
</p>
|
|
18
|
+
|
|
19
|
+
<p align="center">Escape strings so they print exactly as written in LaTeX.</p>
|
|
20
|
+
|
|
21
|
+
A value like `R&D (50%) user_name` breaks a LaTeX document or silently
|
|
22
|
+
changes it: `&` is a table separator, `%` starts a comment and `_` is a
|
|
23
|
+
subscript. `@latex-kit/escape` turns any plain string into LaTeX that prints
|
|
24
|
+
the same characters, and refuses input it can't make safe. It has no
|
|
25
|
+
dependencies.
|
|
26
|
+
|
|
27
|
+
## Installation
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
npm install @latex-kit/escape
|
|
31
|
+
```
|
|
32
|
+
|
|
33
|
+
## Usage
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
import { escapeLatex, raw, tex } from '@latex-kit/escape';
|
|
37
|
+
|
|
38
|
+
escapeLatex('Smith & Jones, 50% off #3');
|
|
39
|
+
// => 'Smith \& Jones, 50\% off \#3'
|
|
40
|
+
|
|
41
|
+
// tagged template: literal parts are LaTeX, every value is escaped
|
|
42
|
+
const doc = tex`\textbf{${company}} owes \$${amount}.`;
|
|
43
|
+
doc.value; // string
|
|
44
|
+
|
|
45
|
+
// opt out for LaTeX you trust
|
|
46
|
+
tex`Signed: ${raw('\\rule{4cm}{0.4pt}')}`;
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`tex` throws on `undefined`, `null`, booleans, `NaN` and objects, so a
|
|
50
|
+
missing value can never print as the word "undefined".
|
|
51
|
+
|
|
52
|
+
### What it escapes
|
|
53
|
+
|
|
54
|
+
| Input | Output |
|
|
55
|
+
|---|---|
|
|
56
|
+
| `\` | `\textbackslash{}` |
|
|
57
|
+
| `{` `}` `$` `&` `#` `%` `_` | `\{` `\}` `\$` `\&` `\#` `\%` `\_` |
|
|
58
|
+
| `^` `~` | `\textasciicircum{}` `\textasciitilde{}` |
|
|
59
|
+
| `<` `>` `\|` | `\textless{}` `\textgreater{}` `\textbar{}` |
|
|
60
|
+
| `[` `]` | `{[}` `{]}`, so they are never read as an optional argument |
|
|
61
|
+
| `--`, `---` | `-\kern0pt-`, `-\kern0pt-\kern0pt-`: literal hyphens, not dashes, in every engine |
|
|
62
|
+
|
|
63
|
+
Unicode passes through unchanged. Output assumes LuaLaTeX or XeLaTeX, or
|
|
64
|
+
pdfLaTeX with `\usepackage[T1]{fontenc}`.
|
|
65
|
+
|
|
66
|
+
### Options
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
escapeLatex(text, {
|
|
70
|
+
newlines: 'space', // 'space' | 'linebreak' | 'paragraph' | 'error'
|
|
71
|
+
controlChars: 'error', // 'error' | 'strip'
|
|
72
|
+
});
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
- `newlines`: `space` (default) joins lines; `linebreak` emits
|
|
76
|
+
`\newline{}`; `paragraph` turns blank lines into paragraph breaks.
|
|
77
|
+
- `controlChars`: ASCII control characters (other than tab and line
|
|
78
|
+
breaks) throw by default rather than being dropped silently.
|
|
79
|
+
|
|
80
|
+
## Credits
|
|
81
|
+
|
|
82
|
+
**🛠 Built by the [Constructive](https://constructive.io) team — creators of modular Postgres tooling for secure, composable backends. If you like our work, contribute on [GitHub](https://github.com/constructive-io).**
|
|
83
|
+
|
|
84
|
+
## Disclaimer
|
|
85
|
+
|
|
86
|
+
AS DESCRIBED IN THE LICENSES, THE SOFTWARE IS PROVIDED "AS IS", AT YOUR OWN RISK, AND WITHOUT WARRANTIES OF ANY KIND.
|
|
87
|
+
|
|
88
|
+
No developer or entity involved in creating this software will be liable for any claims or damages whatsoever associated with your use, inability to use, or your interaction with other users of the code, including any direct, indirect, incidental, special, exemplary, punitive or consequential damages, or loss of profits, cryptocurrencies, tokens, or anything else of value.
|
package/esm/index.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Escape plain text so it can be placed inside a LaTeX document and print
|
|
3
|
+
* exactly as written.
|
|
4
|
+
*
|
|
5
|
+
* Output assumes a Unicode engine (LuaLaTeX or XeLaTeX, `TU` encoding) or
|
|
6
|
+
* pdfLaTeX with `\usepackage[T1]{fontenc}`. Non-ASCII characters pass through
|
|
7
|
+
* unchanged; the engine and fonts are responsible for them.
|
|
8
|
+
*/
|
|
9
|
+
export type NewlineMode = 'space' | 'linebreak' | 'paragraph' | 'error';
|
|
10
|
+
export type ControlCharMode = 'error' | 'strip';
|
|
11
|
+
export interface EscapeOptions {
|
|
12
|
+
/**
|
|
13
|
+
* What to do with line breaks in the input.
|
|
14
|
+
* - `space` (default): each run of line breaks becomes one space
|
|
15
|
+
* - `linebreak`: `\newline{}` (forced line break inside a paragraph)
|
|
16
|
+
* - `paragraph`: a blank line becomes a paragraph break, a single line
|
|
17
|
+
* break becomes `\newline{}`
|
|
18
|
+
* - `error`: throw
|
|
19
|
+
*/
|
|
20
|
+
newlines?: NewlineMode;
|
|
21
|
+
/**
|
|
22
|
+
* What to do with ASCII control characters other than tab and line breaks.
|
|
23
|
+
* Default `error`, so bad input is never changed silently.
|
|
24
|
+
*/
|
|
25
|
+
controlChars?: ControlCharMode;
|
|
26
|
+
}
|
|
27
|
+
export declare class LatexEscapeError extends Error {
|
|
28
|
+
constructor(message: string);
|
|
29
|
+
}
|
|
30
|
+
/** Escape a plain-text value for LaTeX. */
|
|
31
|
+
export declare function escapeLatex(input: string, options?: EscapeOptions): string;
|
|
32
|
+
/** LaTeX that is inserted as-is by {@link tex}. Use sparingly. */
|
|
33
|
+
export declare class RawLatex {
|
|
34
|
+
readonly value: string;
|
|
35
|
+
constructor(value: string);
|
|
36
|
+
toString(): string;
|
|
37
|
+
}
|
|
38
|
+
/** Mark a string as trusted LaTeX so {@link tex} does not escape it. */
|
|
39
|
+
export declare function raw(value: string): RawLatex;
|
|
40
|
+
export type TexValue = string | number | bigint | RawLatex;
|
|
41
|
+
/**
|
|
42
|
+
* Tagged template: the literal parts are LaTeX, every interpolated value is
|
|
43
|
+
* escaped unless wrapped in {@link raw}. `null`, `undefined`, booleans and
|
|
44
|
+
* objects throw, so a missing value can never print as "undefined".
|
|
45
|
+
*
|
|
46
|
+
* tex`Dear ${name},\\[1em] Total: ${raw('\\textbf{')}${total}${raw('}')}`
|
|
47
|
+
*/
|
|
48
|
+
export declare function tex(strings: TemplateStringsArray, ...values: TexValue[]): RawLatex;
|
package/esm/index.js
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Escape plain text so it can be placed inside a LaTeX document and print
|
|
3
|
+
* exactly as written.
|
|
4
|
+
*
|
|
5
|
+
* Output assumes a Unicode engine (LuaLaTeX or XeLaTeX, `TU` encoding) or
|
|
6
|
+
* pdfLaTeX with `\usepackage[T1]{fontenc}`. Non-ASCII characters pass through
|
|
7
|
+
* unchanged; the engine and fonts are responsible for them.
|
|
8
|
+
*/
|
|
9
|
+
export class LatexEscapeError extends Error {
|
|
10
|
+
constructor(message) {
|
|
11
|
+
super(message);
|
|
12
|
+
this.name = 'LatexEscapeError';
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
const SPECIALS = {
|
|
16
|
+
'\\': '\\textbackslash{}',
|
|
17
|
+
'{': '\\{',
|
|
18
|
+
'}': '\\}',
|
|
19
|
+
$: '\\$',
|
|
20
|
+
'&': '\\&',
|
|
21
|
+
'#': '\\#',
|
|
22
|
+
'%': '\\%',
|
|
23
|
+
_: '\\_',
|
|
24
|
+
'^': '\\textasciicircum{}',
|
|
25
|
+
'~': '\\textasciitilde{}',
|
|
26
|
+
'<': '\\textless{}',
|
|
27
|
+
'>': '\\textgreater{}',
|
|
28
|
+
'|': '\\textbar{}',
|
|
29
|
+
// a bracket right after \\ or an optional-argument macro would be read as
|
|
30
|
+
// an argument; grouping it makes it plain text everywhere
|
|
31
|
+
'[': '{[}',
|
|
32
|
+
']': '{]}',
|
|
33
|
+
};
|
|
34
|
+
// `-(?=-)` splits the -- and --- ligatures so "A--B" stays two hyphens. An
|
|
35
|
+
// empty group (`-{}-`) is not enough under LuaLaTeX, where the font's TeX
|
|
36
|
+
// ligatures still join the hyphens; a zero kern stops them in every engine.
|
|
37
|
+
const SPECIAL_RE = /[\\{}$&#%_^~<>|[\]]|-(?=-)/g;
|
|
38
|
+
const CONTROL_CHARS = '[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]';
|
|
39
|
+
const CONTROL_ONE = new RegExp(CONTROL_CHARS);
|
|
40
|
+
const CONTROL_ALL = new RegExp(CONTROL_CHARS, 'g');
|
|
41
|
+
function escapeLine(line) {
|
|
42
|
+
return line.replace(SPECIAL_RE, (ch) => (ch === '-' ? '-\\kern0pt' : SPECIALS[ch]));
|
|
43
|
+
}
|
|
44
|
+
/** Escape a plain-text value for LaTeX. */
|
|
45
|
+
export function escapeLatex(input, options = {}) {
|
|
46
|
+
if (typeof input !== 'string') {
|
|
47
|
+
throw new LatexEscapeError(`escapeLatex expects a string, got ${typeof input}`);
|
|
48
|
+
}
|
|
49
|
+
const newlines = options.newlines ?? 'space';
|
|
50
|
+
const controlChars = options.controlChars ?? 'error';
|
|
51
|
+
let text = input.replace(/\r\n?/g, '\n').replace(/\t/g, ' ');
|
|
52
|
+
const control = CONTROL_ONE.exec(text);
|
|
53
|
+
if (control) {
|
|
54
|
+
if (controlChars === 'error') {
|
|
55
|
+
const code = control[0].charCodeAt(0);
|
|
56
|
+
throw new LatexEscapeError(`control character U+${code.toString(16).toUpperCase().padStart(4, '0')} in input`);
|
|
57
|
+
}
|
|
58
|
+
text = text.replace(CONTROL_ALL, '');
|
|
59
|
+
}
|
|
60
|
+
if (!text.includes('\n'))
|
|
61
|
+
return escapeLine(text);
|
|
62
|
+
switch (newlines) {
|
|
63
|
+
case 'error':
|
|
64
|
+
throw new LatexEscapeError('line break in input (newlines: "error")');
|
|
65
|
+
case 'space':
|
|
66
|
+
return escapeLine(text.replace(/\s*\n\s*/g, ' '));
|
|
67
|
+
case 'linebreak':
|
|
68
|
+
return text
|
|
69
|
+
.split(/\n+/)
|
|
70
|
+
.map((l) => escapeLine(l.trim()))
|
|
71
|
+
.filter((l) => l.length > 0)
|
|
72
|
+
.join('\\newline{}');
|
|
73
|
+
case 'paragraph':
|
|
74
|
+
return text
|
|
75
|
+
.split(/\n\s*\n/)
|
|
76
|
+
.map((para) => para
|
|
77
|
+
.split('\n')
|
|
78
|
+
.map((l) => escapeLine(l.trim()))
|
|
79
|
+
.filter((l) => l.length > 0)
|
|
80
|
+
.join('\\newline{}'))
|
|
81
|
+
.filter((p) => p.length > 0)
|
|
82
|
+
.join('\n\n');
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
/** LaTeX that is inserted as-is by {@link tex}. Use sparingly. */
|
|
86
|
+
export class RawLatex {
|
|
87
|
+
value;
|
|
88
|
+
constructor(value) {
|
|
89
|
+
this.value = value;
|
|
90
|
+
}
|
|
91
|
+
toString() {
|
|
92
|
+
return this.value;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
/** Mark a string as trusted LaTeX so {@link tex} does not escape it. */
|
|
96
|
+
export function raw(value) {
|
|
97
|
+
return new RawLatex(value);
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Tagged template: the literal parts are LaTeX, every interpolated value is
|
|
101
|
+
* escaped unless wrapped in {@link raw}. `null`, `undefined`, booleans and
|
|
102
|
+
* objects throw, so a missing value can never print as "undefined".
|
|
103
|
+
*
|
|
104
|
+
* tex`Dear ${name},\\[1em] Total: ${raw('\\textbf{')}${total}${raw('}')}`
|
|
105
|
+
*/
|
|
106
|
+
export function tex(strings, ...values) {
|
|
107
|
+
let out = strings[0];
|
|
108
|
+
values.forEach((value, i) => {
|
|
109
|
+
out += interpolate(value, i) + strings[i + 1];
|
|
110
|
+
});
|
|
111
|
+
return new RawLatex(out);
|
|
112
|
+
}
|
|
113
|
+
function interpolate(value, index) {
|
|
114
|
+
if (value instanceof RawLatex)
|
|
115
|
+
return value.value;
|
|
116
|
+
if (typeof value === 'string')
|
|
117
|
+
return escapeLatex(value);
|
|
118
|
+
if (typeof value === 'number') {
|
|
119
|
+
if (!Number.isFinite(value)) {
|
|
120
|
+
throw new LatexEscapeError(`tex value #${index} is ${value}`);
|
|
121
|
+
}
|
|
122
|
+
return escapeLatex(String(value));
|
|
123
|
+
}
|
|
124
|
+
if (typeof value === 'bigint')
|
|
125
|
+
return String(value);
|
|
126
|
+
const kind = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
|
|
127
|
+
throw new LatexEscapeError(`tex value #${index} is ${kind}; pass a string, number or raw()`);
|
|
128
|
+
}
|
package/index.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Escape plain text so it can be placed inside a LaTeX document and print
|
|
3
|
+
* exactly as written.
|
|
4
|
+
*
|
|
5
|
+
* Output assumes a Unicode engine (LuaLaTeX or XeLaTeX, `TU` encoding) or
|
|
6
|
+
* pdfLaTeX with `\usepackage[T1]{fontenc}`. Non-ASCII characters pass through
|
|
7
|
+
* unchanged; the engine and fonts are responsible for them.
|
|
8
|
+
*/
|
|
9
|
+
export type NewlineMode = 'space' | 'linebreak' | 'paragraph' | 'error';
|
|
10
|
+
export type ControlCharMode = 'error' | 'strip';
|
|
11
|
+
export interface EscapeOptions {
|
|
12
|
+
/**
|
|
13
|
+
* What to do with line breaks in the input.
|
|
14
|
+
* - `space` (default): each run of line breaks becomes one space
|
|
15
|
+
* - `linebreak`: `\newline{}` (forced line break inside a paragraph)
|
|
16
|
+
* - `paragraph`: a blank line becomes a paragraph break, a single line
|
|
17
|
+
* break becomes `\newline{}`
|
|
18
|
+
* - `error`: throw
|
|
19
|
+
*/
|
|
20
|
+
newlines?: NewlineMode;
|
|
21
|
+
/**
|
|
22
|
+
* What to do with ASCII control characters other than tab and line breaks.
|
|
23
|
+
* Default `error`, so bad input is never changed silently.
|
|
24
|
+
*/
|
|
25
|
+
controlChars?: ControlCharMode;
|
|
26
|
+
}
|
|
27
|
+
export declare class LatexEscapeError extends Error {
|
|
28
|
+
constructor(message: string);
|
|
29
|
+
}
|
|
30
|
+
/** Escape a plain-text value for LaTeX. */
|
|
31
|
+
export declare function escapeLatex(input: string, options?: EscapeOptions): string;
|
|
32
|
+
/** LaTeX that is inserted as-is by {@link tex}. Use sparingly. */
|
|
33
|
+
export declare class RawLatex {
|
|
34
|
+
readonly value: string;
|
|
35
|
+
constructor(value: string);
|
|
36
|
+
toString(): string;
|
|
37
|
+
}
|
|
38
|
+
/** Mark a string as trusted LaTeX so {@link tex} does not escape it. */
|
|
39
|
+
export declare function raw(value: string): RawLatex;
|
|
40
|
+
export type TexValue = string | number | bigint | RawLatex;
|
|
41
|
+
/**
|
|
42
|
+
* Tagged template: the literal parts are LaTeX, every interpolated value is
|
|
43
|
+
* escaped unless wrapped in {@link raw}. `null`, `undefined`, booleans and
|
|
44
|
+
* objects throw, so a missing value can never print as "undefined".
|
|
45
|
+
*
|
|
46
|
+
* tex`Dear ${name},\\[1em] Total: ${raw('\\textbf{')}${total}${raw('}')}`
|
|
47
|
+
*/
|
|
48
|
+
export declare function tex(strings: TemplateStringsArray, ...values: TexValue[]): RawLatex;
|
package/index.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* Escape plain text so it can be placed inside a LaTeX document and print
|
|
4
|
+
* exactly as written.
|
|
5
|
+
*
|
|
6
|
+
* Output assumes a Unicode engine (LuaLaTeX or XeLaTeX, `TU` encoding) or
|
|
7
|
+
* pdfLaTeX with `\usepackage[T1]{fontenc}`. Non-ASCII characters pass through
|
|
8
|
+
* unchanged; the engine and fonts are responsible for them.
|
|
9
|
+
*/
|
|
10
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
11
|
+
exports.RawLatex = exports.LatexEscapeError = void 0;
|
|
12
|
+
exports.escapeLatex = escapeLatex;
|
|
13
|
+
exports.raw = raw;
|
|
14
|
+
exports.tex = tex;
|
|
15
|
+
class LatexEscapeError extends Error {
|
|
16
|
+
constructor(message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'LatexEscapeError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
exports.LatexEscapeError = LatexEscapeError;
|
|
22
|
+
const SPECIALS = {
|
|
23
|
+
'\\': '\\textbackslash{}',
|
|
24
|
+
'{': '\\{',
|
|
25
|
+
'}': '\\}',
|
|
26
|
+
$: '\\$',
|
|
27
|
+
'&': '\\&',
|
|
28
|
+
'#': '\\#',
|
|
29
|
+
'%': '\\%',
|
|
30
|
+
_: '\\_',
|
|
31
|
+
'^': '\\textasciicircum{}',
|
|
32
|
+
'~': '\\textasciitilde{}',
|
|
33
|
+
'<': '\\textless{}',
|
|
34
|
+
'>': '\\textgreater{}',
|
|
35
|
+
'|': '\\textbar{}',
|
|
36
|
+
// a bracket right after \\ or an optional-argument macro would be read as
|
|
37
|
+
// an argument; grouping it makes it plain text everywhere
|
|
38
|
+
'[': '{[}',
|
|
39
|
+
']': '{]}',
|
|
40
|
+
};
|
|
41
|
+
// `-(?=-)` splits the -- and --- ligatures so "A--B" stays two hyphens. An
|
|
42
|
+
// empty group (`-{}-`) is not enough under LuaLaTeX, where the font's TeX
|
|
43
|
+
// ligatures still join the hyphens; a zero kern stops them in every engine.
|
|
44
|
+
const SPECIAL_RE = /[\\{}$&#%_^~<>|[\]]|-(?=-)/g;
|
|
45
|
+
const CONTROL_CHARS = '[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F]';
|
|
46
|
+
const CONTROL_ONE = new RegExp(CONTROL_CHARS);
|
|
47
|
+
const CONTROL_ALL = new RegExp(CONTROL_CHARS, 'g');
|
|
48
|
+
function escapeLine(line) {
|
|
49
|
+
return line.replace(SPECIAL_RE, (ch) => (ch === '-' ? '-\\kern0pt' : SPECIALS[ch]));
|
|
50
|
+
}
|
|
51
|
+
/** Escape a plain-text value for LaTeX. */
|
|
52
|
+
function escapeLatex(input, options = {}) {
|
|
53
|
+
if (typeof input !== 'string') {
|
|
54
|
+
throw new LatexEscapeError(`escapeLatex expects a string, got ${typeof input}`);
|
|
55
|
+
}
|
|
56
|
+
const newlines = options.newlines ?? 'space';
|
|
57
|
+
const controlChars = options.controlChars ?? 'error';
|
|
58
|
+
let text = input.replace(/\r\n?/g, '\n').replace(/\t/g, ' ');
|
|
59
|
+
const control = CONTROL_ONE.exec(text);
|
|
60
|
+
if (control) {
|
|
61
|
+
if (controlChars === 'error') {
|
|
62
|
+
const code = control[0].charCodeAt(0);
|
|
63
|
+
throw new LatexEscapeError(`control character U+${code.toString(16).toUpperCase().padStart(4, '0')} in input`);
|
|
64
|
+
}
|
|
65
|
+
text = text.replace(CONTROL_ALL, '');
|
|
66
|
+
}
|
|
67
|
+
if (!text.includes('\n'))
|
|
68
|
+
return escapeLine(text);
|
|
69
|
+
switch (newlines) {
|
|
70
|
+
case 'error':
|
|
71
|
+
throw new LatexEscapeError('line break in input (newlines: "error")');
|
|
72
|
+
case 'space':
|
|
73
|
+
return escapeLine(text.replace(/\s*\n\s*/g, ' '));
|
|
74
|
+
case 'linebreak':
|
|
75
|
+
return text
|
|
76
|
+
.split(/\n+/)
|
|
77
|
+
.map((l) => escapeLine(l.trim()))
|
|
78
|
+
.filter((l) => l.length > 0)
|
|
79
|
+
.join('\\newline{}');
|
|
80
|
+
case 'paragraph':
|
|
81
|
+
return text
|
|
82
|
+
.split(/\n\s*\n/)
|
|
83
|
+
.map((para) => para
|
|
84
|
+
.split('\n')
|
|
85
|
+
.map((l) => escapeLine(l.trim()))
|
|
86
|
+
.filter((l) => l.length > 0)
|
|
87
|
+
.join('\\newline{}'))
|
|
88
|
+
.filter((p) => p.length > 0)
|
|
89
|
+
.join('\n\n');
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** LaTeX that is inserted as-is by {@link tex}. Use sparingly. */
|
|
93
|
+
class RawLatex {
|
|
94
|
+
value;
|
|
95
|
+
constructor(value) {
|
|
96
|
+
this.value = value;
|
|
97
|
+
}
|
|
98
|
+
toString() {
|
|
99
|
+
return this.value;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
exports.RawLatex = RawLatex;
|
|
103
|
+
/** Mark a string as trusted LaTeX so {@link tex} does not escape it. */
|
|
104
|
+
function raw(value) {
|
|
105
|
+
return new RawLatex(value);
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Tagged template: the literal parts are LaTeX, every interpolated value is
|
|
109
|
+
* escaped unless wrapped in {@link raw}. `null`, `undefined`, booleans and
|
|
110
|
+
* objects throw, so a missing value can never print as "undefined".
|
|
111
|
+
*
|
|
112
|
+
* tex`Dear ${name},\\[1em] Total: ${raw('\\textbf{')}${total}${raw('}')}`
|
|
113
|
+
*/
|
|
114
|
+
function tex(strings, ...values) {
|
|
115
|
+
let out = strings[0];
|
|
116
|
+
values.forEach((value, i) => {
|
|
117
|
+
out += interpolate(value, i) + strings[i + 1];
|
|
118
|
+
});
|
|
119
|
+
return new RawLatex(out);
|
|
120
|
+
}
|
|
121
|
+
function interpolate(value, index) {
|
|
122
|
+
if (value instanceof RawLatex)
|
|
123
|
+
return value.value;
|
|
124
|
+
if (typeof value === 'string')
|
|
125
|
+
return escapeLatex(value);
|
|
126
|
+
if (typeof value === 'number') {
|
|
127
|
+
if (!Number.isFinite(value)) {
|
|
128
|
+
throw new LatexEscapeError(`tex value #${index} is ${value}`);
|
|
129
|
+
}
|
|
130
|
+
return escapeLatex(String(value));
|
|
131
|
+
}
|
|
132
|
+
if (typeof value === 'bigint')
|
|
133
|
+
return String(value);
|
|
134
|
+
const kind = value === null ? 'null' : Array.isArray(value) ? 'array' : typeof value;
|
|
135
|
+
throw new LatexEscapeError(`tex value #${index} is ${kind}; pass a string, number or raw()`);
|
|
136
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,43 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@latex-kit/escape",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Escape strings for safe interpolation into LaTeX documents",
|
|
5
|
+
"author": "Constructive <developers@constructive.io>",
|
|
6
|
+
"main": "index.js",
|
|
7
|
+
"module": "esm/index.js",
|
|
8
|
+
"types": "index.d.ts",
|
|
9
|
+
"homepage": "https://github.com/constructive-io/latex-kit",
|
|
10
|
+
"license": "MIT",
|
|
11
|
+
"publishConfig": {
|
|
12
|
+
"access": "public",
|
|
13
|
+
"directory": "dist"
|
|
14
|
+
},
|
|
15
|
+
"repository": {
|
|
16
|
+
"type": "git",
|
|
17
|
+
"url": "https://github.com/constructive-io/latex-kit"
|
|
18
|
+
},
|
|
19
|
+
"bugs": {
|
|
20
|
+
"url": "https://github.com/constructive-io/latex-kit/issues"
|
|
21
|
+
},
|
|
22
|
+
"scripts": {
|
|
23
|
+
"copy": "makage assets",
|
|
24
|
+
"clean": "makage clean",
|
|
25
|
+
"prepublishOnly": "npm run build",
|
|
26
|
+
"build": "makage build",
|
|
27
|
+
"build:dev": "makage build --dev",
|
|
28
|
+
"lint": "eslint . --fix",
|
|
29
|
+
"test": "jest",
|
|
30
|
+
"test:watch": "jest --watch"
|
|
31
|
+
},
|
|
32
|
+
"devDependencies": {
|
|
33
|
+
"makage": "^0.8.0"
|
|
34
|
+
},
|
|
35
|
+
"keywords": [
|
|
36
|
+
"latex",
|
|
37
|
+
"tex",
|
|
38
|
+
"escape",
|
|
39
|
+
"sanitize",
|
|
40
|
+
"template"
|
|
41
|
+
],
|
|
42
|
+
"gitHead": "b88becdf229a9f5689fcc3b8ff087f718e04f216"
|
|
43
|
+
}
|