0
# Copy-TeX Extension
1
2
Clipboard integration extension that enables copying rendered math expressions as TeX source code, preserving original LaTeX notation for easy sharing and editing.
3
4
## Import
5
6
```typescript
7
import "katex/contrib/copy-tex";
8
```
9
10
For CommonJS:
11
12
```javascript
13
require("katex/contrib/copy-tex");
14
```
15
16
## Capabilities
17
18
### Automatic Clipboard Enhancement
19
20
The copy-tex extension automatically enhances the clipboard behavior when copying math expressions rendered by KaTeX.
21
22
```typescript { .api }
23
// No explicit API - works automatically once imported
24
// Modifies global copy behavior for .katex elements
25
```
26
27
**Usage Example:**
28
29
```html
30
<script src="katex.js"></script>
31
<script src="katex/contrib/copy-tex.js"></script>
32
33
<div id="math-content">
34
<!-- Rendered math elements -->
35
</div>
36
37
<script>
38
// Render some math
39
katex.render("\\frac{1}{2}", document.getElementById("math-content"));
40
41
// Now when users copy the rendered math, they get:
42
// - HTML format: full rendered HTML for pasting into rich text editors
43
// - Plain text format: TeX source code (e.g., "\frac{1}{2}")
44
</script>
45
```
46
47
### Clipboard Behavior
48
49
When users copy rendered math expressions:
50
51
**Before copy-tex:**
52
- HTML format: Raw HTML spans and classes
53
- Plain text: Rendered text approximation (e.g., "1/2")
54
55
**After copy-tex:**
56
- HTML format: Complete rendered HTML with styling preserved
57
- Plain text: Original TeX source code (e.g., "\\frac{1}{2}")
58
59
### Copy Delimiter Configuration
60
61
The extension supports configurable delimiters for copied TeX code:
62
63
```typescript { .api }
64
interface CopyDelimiters {
65
/** Delimiters for inline math */
66
inline: [string, string];
67
/** Delimiters for display math */
68
display: [string, string];
69
}
70
71
const defaultCopyDelimiters: CopyDelimiters = {
72
inline: ['$', '$'],
73
display: ['$$', '$$']
74
};
75
76
/**
77
* Replace KaTeX elements with their TeX source
78
* @param fragment - Document fragment to process
79
* @param copyDelimiters - Delimiter configuration
80
* @returns Modified fragment with TeX source
81
*/
82
function katexReplaceWithTex(
83
fragment: DocumentFragment,
84
copyDelimiters?: CopyDelimiters
85
): DocumentFragment;
86
```
87
88
**Usage Example (Advanced):**
89
90
```typescript
91
import { katexReplaceWithTex, defaultCopyDelimiters } from "katex/contrib/copy-tex";
92
93
// Custom copy handler with LaTeX-style delimiters
94
const customDelimiters = {
95
inline: ['\\(', '\\)'],
96
display: ['\\[', '\\]']
97
};
98
99
// Manual processing for custom copy behavior
100
document.addEventListener('copy', function(event) {
101
const selection = window.getSelection();
102
const range = selection.getRangeAt(0);
103
const fragment = range.cloneContents();
104
105
// Replace KaTeX elements with TeX source
106
const processed = katexReplaceWithTex(fragment, customDelimiters);
107
108
event.clipboardData.setData('text/plain', processed.textContent);
109
event.preventDefault();
110
});
111
```
112
113
### Selection Expansion
114
115
The extension automatically expands selections to include complete math expressions:
116
117
- **Partial Selection**: When users start selecting within a math expression, the selection expands to include the entire formula
118
- **Cross-Expression Selection**: Handles selections that span multiple math expressions
119
- **Mixed Content**: Properly handles selections containing both math and regular text
120
121
**Behavior Example:**
122
123
```html
124
<p>The equation <span class="katex">E = mc²</span> shows energy equivalence.</p>
125
126
<!-- If user selects part of "mc²", the extension expands selection to include entire "E = mc²" -->
127
<!-- Copy result:
128
HTML: Full rendered equation HTML
129
Text: "E = mc^2" (original TeX)
130
-->
131
```
132
133
### Integration with Frameworks
134
135
The copy-tex extension works automatically with any rendering approach:
136
137
```typescript
138
// React component
139
useEffect(() => {
140
import("katex/contrib/copy-tex"); // Enable copy-tex for all rendered math
141
}, []);
142
143
// Vue component
144
mounted() {
145
require("katex/contrib/copy-tex");
146
}
147
148
// Angular component
149
ngOnInit() {
150
import("katex/contrib/copy-tex");
151
}
152
```
153
154
### Browser Compatibility
155
156
Copy-tex extension requires:
157
158
- **Modern browsers** with Clipboard API support
159
- **Selection API** for range manipulation
160
- **Event handling** for copy event interception
161
162
**Fallback for older browsers:**
163
164
```javascript
165
// Check for required APIs
166
if (window.getSelection && document.createRange && window.ClipboardEvent) {
167
import("katex/contrib/copy-tex");
168
} else {
169
console.warn("Copy-tex extension requires modern browser APIs");
170
}
171
```
172
173
### Usage with Auto-Render
174
175
Copy-tex works seamlessly with auto-rendered content:
176
177
```html
178
<div id="content">
179
<p>Display math: $$\int_0^\infty e^{-x^2} dx = \frac{\sqrt{\pi}}{2}$$</p>
180
<p>Inline math: The formula \(x = \frac{-b \pm \sqrt{b^2-4ac}}{2a}\) solves quadratics.</p>
181
</div>
182
183
<script>
184
import renderMathInElement from "katex/contrib/auto-render";
185
import "katex/contrib/copy-tex";
186
187
// First render the math
188
renderMathInElement(document.getElementById("content"));
189
190
// Copy-tex automatically enhances all rendered expressions
191
// Users can now copy any math and get TeX source in plain text
192
</script>
193
```
194
195
### Security Considerations
196
197
The copy-tex extension:
198
199
- **Does not modify** the original document structure
200
- **Only affects** copy operations on KaTeX-rendered content
201
- **Preserves** all security settings from KaTeX rendering
202
- **Does not access** external resources or make network requests
203
204
### Troubleshooting
205
206
**Math not copying as TeX:**
207
- Ensure copy-tex is imported after KaTeX
208
- Verify math was rendered with MathML output (default)
209
- Check for JavaScript errors in console
210
211
**Wrong delimiters in copied text:**
212
- Copy-tex uses default `$` delimiters
213
- Use `katexReplaceWithTex` with custom delimiters for different formats
214
- Verify the TeX source is preserved in MathML annotations
215
216
**Selection not expanding properly:**
217
- Extension only works with elements having `.katex` class
218
- Ensure math was rendered by KaTeX (not other libraries)
219
- Check for CSS or JavaScript that might interfere with selection APIs