What is code-excerpt?
The code-excerpt npm package is designed to extract and highlight excerpts from code snippets. It is particularly useful for creating documentation, tutorials, or any content that requires displaying code with specific lines highlighted.
What are code-excerpt's main functionalities?
Extracting Code Excerpts
This feature allows you to extract a specific range of lines from a code snippet. The `start` and `end` options specify the range of lines to be extracted.
const codeExcerpt = require('code-excerpt');
const code = `
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
`;
const excerpt = codeExcerpt(code, { start: 2, end: 4 });
console.log(excerpt);
// Output:
// {
// value: ' return a + b;\n}\n\nconsole.log(add(2, 3));\n',
// start: 2,
// end: 4
// }
Highlighting Specific Lines
This feature allows you to highlight specific lines within the extracted code excerpt. The `highlight` option takes an array of line numbers to be highlighted.
const codeExcerpt = require('code-excerpt');
const code = `
function add(a, b) {
return a + b;
}
console.log(add(2, 3));
`;
const excerpt = codeExcerpt(code, { start: 2, end: 4, highlight: [3] });
console.log(excerpt);
// Output:
// {
// value: ' return a + b;\n}\n\nconsole.log(add(2, 3));\n',
// start: 2,
// end: 4,
// highlight: [3]
// }
Other packages similar to code-excerpt
highlight.js
highlight.js is a popular library for syntax highlighting of code snippets. Unlike code-excerpt, which focuses on extracting and highlighting specific lines, highlight.js is designed to apply syntax highlighting to entire code blocks. It supports a wide range of programming languages and is highly customizable.
prismjs
Prism is a lightweight, extensible syntax highlighter. It is similar to highlight.js in that it focuses on syntax highlighting for entire code blocks. Prism is known for its performance and ease of use, and it also supports a wide range of languages and plugins for additional functionality.
codemirror
CodeMirror is a versatile text editor implemented in JavaScript for the browser. It is more than just a syntax highlighter; it provides a full-featured code editor with features like autocompletion, linting, and more. While it can be used to highlight code, its primary use case is as an in-browser code editor.
code-excerpt
Extract code excerpts
Install
$ npm install --save code-excerpt
Usage
import codeExcerpt from 'code-excerpt';
const source = `
'use strict';
function someFunc() {}
module.exports = () => {
const a = 1;
const b = 2;
const c = 3;
someFunc();
};
`.trim();
const excerpt = codeExcerpt(source, 5);
API
codeExcerpt(source, line, [options])
source
Type: string
Source code.
line
Type: number
Line number to extract excerpt for.
options
around
Type: number
Default: 3
Number of surrounding lines to extract.