A Prism.js plugin that adds code folding support for JSON objects and arrays. Demo
The algorithm should work for any C-like language. JSON/JavaScript/Java
are supported by default. You can add more languages by setting the PRISM_FOLD_HOOK_LANGUAGES
environment variable.
This plugin processes Prism tokens and wraps {}
and []
blocks in <details>
tags to enable folding functionality.
It implements two Prism hooks:
-
after-tokenize handler: Identifies punctuation tokens (
{
and[
), converting the flat token list into nested structures for folding -
wrap handler: Adds
<details>
and<summary>
tags before final HTML output
this implementation:
- Inspired by prism-js-fold, uses semantic HTML
<details>
without JavaScript event handlers - Leverages Prism's low-level
highlight
function through hook integration, therefore works transparently with direct calls toPrism.highlight()
- Processes tokens split by Prism's native parser instead of relying on regular expressions
Install via npm:
npm install prismjs-fold-json
Import after Prism:
const Prism = require('prismjs');
require('prismjs-fold-json');
// Example usage
const html = Prism.highlight(
JSON.stringify({ a: [1, 2] }, null, 4),
Prism.languages.json,
"json"
);
Note: For Vue/React projects, import CSS in your entry file:
import 'prismjs-fold-json/main.css';
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet"
href="https://unpkg.com/prismjs@1.29.0/themes/prism-coy.min.css">
<!-- Required CSS -->
<link rel="stylesheet"
href="https://unpkg.com/prismjs-fold-json@1.x.x/main.css">
</head>
<body>
<script src="https://unpkg.com/prismjs@1.29.0/components/prism-core.min.js"></script>
<script src="https://unpkg.com/prismjs@1.29.0/plugins/autoloader/prism-autoloader.min.js"></script>
<!-- Plugin script (load after Prism) -->
<script src="https://unpkg.com/prismjs-fold-json@1.x.x/index.js"></script>
</body>
</html>
Browser-specific <details>
tag behavior:
- Chromium ≥128: Creates new lines
- Other browsers: Adds extra indentation spaces
The implementation handles these differences through adaptive logic. If issues persist, try setting the PRISM_IN_CHROME_LIKE
environment variable with these values:
auto
(default) | new
| old
| none