or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

core-highlighting.mdindex.mdlanguage-system.mdplugin-system.mdtoken-system.mdutilities.md

core-highlighting.mddocs/

0

# Core Highlighting

1

2

The core highlighting functionality provides both automatic and manual syntax highlighting capabilities. These functions form the primary API for highlighting code in web pages and applications.

3

4

## Capabilities

5

6

### Automatic Highlighting

7

8

#### highlightAll

9

10

Automatically highlights all code elements on the page that have language-specific CSS classes.

11

12

```javascript { .api }

13

/**

14

* Highlight all code elements on the page automatically

15

* @param {boolean} [async=false] - Whether to use Web Workers for highlighting

16

* @param {function} [callback] - Callback function invoked after each element is highlighted

17

*/

18

Prism.highlightAll(async, callback);

19

```

20

21

**Usage Examples:**

22

23

```javascript

24

// Basic automatic highlighting

25

Prism.highlightAll();

26

27

// Asynchronous highlighting with callback

28

Prism.highlightAll(true, function(element) {

29

console.log('Highlighted:', element);

30

});

31

```

32

33

**HTML Setup:**

34

35

```html

36

<pre><code class="language-javascript">

37

const message = "Hello, World!";

38

console.log(message);

39

</code></pre>

40

41

<script>

42

// Call after DOM is loaded

43

Prism.highlightAll();

44

</script>

45

```

46

47

#### highlightAllUnder

48

49

Highlights all code elements under a specific container element.

50

51

```javascript { .api }

52

/**

53

* Highlight all descendants of container that have language-* classes

54

* @param {Element} container - Root element to search under

55

* @param {boolean} [async=false] - Whether to use Web Workers

56

* @param {function} [callback] - Callback function invoked after each element

57

*/

58

Prism.highlightAllUnder(container, async, callback);

59

```

60

61

**Usage Examples:**

62

63

```javascript

64

// Highlight only within a specific container

65

const codeContainer = document.getElementById('code-examples');

66

Prism.highlightAllUnder(codeContainer);

67

68

// With async and callback

69

Prism.highlightAllUnder(container, true, (element) => {

70

element.classList.add('highlighted');

71

});

72

```

73

74

### Element Highlighting

75

76

#### highlightElement

77

78

Highlights code inside a single element with fine-grained control.

79

80

```javascript { .api }

81

/**

82

* Highlight code inside a single element

83

* @param {Element} element - Element containing code with language-* class

84

* @param {boolean} [async=false] - Whether to use Web Workers for highlighting

85

* @param {function} [callback] - Optional callback function after highlighting

86

*/

87

Prism.highlightElement(element, async, callback);

88

```

89

90

**Usage Examples:**

91

92

```javascript

93

// Highlight single element

94

const codeBlock = document.querySelector('code.language-python');

95

Prism.highlightElement(codeBlock);

96

97

// With callback for post-processing

98

Prism.highlightElement(codeBlock, false, function(element) {

99

// Add line numbers or other enhancements

100

console.log('Element highlighted:', element);

101

});

102

103

// Asynchronous highlighting

104

Prism.highlightElement(codeBlock, true);

105

```

106

107

**Requirements:**

108

- Element must have `language-*` class (e.g., `language-javascript`)

109

- Element should contain text content to highlight

110

- Language grammar must be loaded

111

112

### Manual String Highlighting

113

114

#### highlight

115

116

Low-level function for highlighting code strings directly without DOM manipulation.

117

118

```javascript { .api }

119

/**

120

* Highlight a code string using specified grammar

121

* @param {string} text - Code string to highlight

122

* @param {object} grammar - Language grammar object from Prism.languages

123

* @param {string} language - Language identifier for CSS classes

124

* @returns {string} HTML string with syntax highlighting markup

125

*/

126

Prism.highlight(text, grammar, language);

127

```

128

129

**Usage Examples:**

130

131

```javascript

132

// Basic string highlighting

133

const code = 'const greeting = "Hello, World!";';

134

const grammar = Prism.languages.javascript;

135

const highlighted = Prism.highlight(code, grammar, 'javascript');

136

console.log(highlighted);

137

// Output: '<span class="token keyword">const</span> greeting <span class="token operator">=</span> <span class="token string">"Hello, World!"</span><span class="token punctuation">;</span>'

138

139

// Dynamic highlighting with different languages

140

function highlightCode(code, lang) {

141

if (Prism.languages[lang]) {

142

return Prism.highlight(code, Prism.languages[lang], lang);

143

} else {

144

throw new Error(`Language "${lang}" not loaded`);

145

}

146

}

147

148

const pythonCode = 'print("Hello, Python!")';

149

const highlighted = highlightCode(pythonCode, 'python');

150

document.getElementById('output').innerHTML = highlighted;

151

```

152

153

#### tokenize

154

155

Core tokenization function that parses code into structured token objects.

156

157

```javascript { .api }

158

/**

159

* Tokenize code string into structured token stream

160

* @param {string} text - Code string to tokenize

161

* @param {object} grammar - Language grammar object from Prism.languages

162

* @returns {Array} Array of strings and Token objects (TokenStream)

163

*/

164

Prism.tokenize(text, grammar);

165

```

166

167

**Usage Examples:**

168

169

```javascript

170

// Basic tokenization

171

const code = 'let count = 42;';

172

const tokens = Prism.tokenize(code, Prism.languages.javascript);

173

174

// Analyze tokens

175

tokens.forEach(token => {

176

if (token instanceof Prism.Token) {

177

console.log(`Token: ${token.type} = "${token.content}"`);

178

} else {

179

console.log(`Text: "${token}"`);

180

}

181

});

182

183

// Advanced token processing

184

function extractIdentifiers(code, language) {

185

const tokens = Prism.tokenize(code, Prism.languages[language]);

186

const identifiers = [];

187

188

function processTokens(tokens) {

189

tokens.forEach(token => {

190

if (token instanceof Prism.Token) {

191

if (token.type === 'function' || token.type === 'variable') {

192

identifiers.push(token.content);

193

}

194

if (Array.isArray(token.content)) {

195

processTokens(token.content);

196

}

197

}

198

});

199

}

200

201

processTokens(tokens);

202

return identifiers;

203

}

204

```

205

206

## Hooks Integration

207

208

The highlighting process integrates with the hook system to allow plugins to modify behavior:

209

210

```javascript

211

// Available hooks during highlighting

212

Prism.hooks.add('before-highlightall', function(env) {

213

// Modify elements before highlighting starts

214

console.log('Starting to highlight:', env.selector);

215

});

216

217

Prism.hooks.add('before-sanity-check', function(env) {

218

// Modify element/code before processing

219

console.log('Processing element:', env.element);

220

});

221

222

Prism.hooks.add('before-highlight', function(env) {

223

// Modify code/grammar before highlighting

224

env.code = env.code.trim(); // Remove whitespace

225

});

226

227

Prism.hooks.add('after-highlight', function(env) {

228

// Modify highlighted HTML

229

console.log('Highlighted code:', env.highlightedCode);

230

});

231

232

Prism.hooks.add('complete', function(env) {

233

// Final processing after DOM insertion

234

console.log('Highlighting complete:', env.element);

235

});

236

```

237

238

## Error Handling

239

240

```javascript

241

// Check if language is available

242

function safeHighlight(code, language) {

243

if (!Prism.languages[language]) {

244

console.warn(`Language "${language}" not loaded`);

245

return code; // Return original code

246

}

247

248

try {

249

return Prism.highlight(code, Prism.languages[language], language);

250

} catch (error) {

251

console.error('Highlighting failed:', error);

252

return code; // Fallback to original

253

}

254

}

255

256

// Error handling with element highlighting

257

function highlightWithFallback(element) {

258

try {

259

Prism.highlightElement(element);

260

} catch (error) {

261

console.error('Failed to highlight element:', error);

262

// Element remains unhighlighted but functional

263

}

264

}

265

```

266

267

## Web Worker Support

268

269

PrismJS supports asynchronous highlighting using Web Workers to prevent blocking the main thread:

270

271

```javascript

272

// Enable async highlighting

273

Prism.highlightAll(true);

274

275

// Web Workers require all language definitions in main prism.js

276

// Components loaded separately won't be available in workers

277

278

// Check worker support

279

if (typeof Worker !== 'undefined') {

280

console.log('Web Workers supported');

281

} else {

282

console.log('Falling back to synchronous highlighting');

283

}

284

```

285

286

## Performance Considerations

287

288

```javascript

289

// For large code blocks, use async highlighting

290

const largeCodeBlock = document.querySelector('.large-code');

291

if (largeCodeBlock.textContent.length > 10000) {

292

Prism.highlightElement(largeCodeBlock, true);

293

}

294

295

// Batch highlighting for better performance

296

const codeBlocks = document.querySelectorAll('code[class*="language-"]');

297

if (codeBlocks.length > 50) {

298

// Use async for many elements

299

Prism.highlightAll(true);

300

} else {

301

// Sync is fine for few elements

302

Prism.highlightAll(false);

303

}

304

```