GNU source-highlight is a library to highlight source code in several different languages and output formats. This package provides Node.js bindings to the C++ library; currently, it requires you to have the library preinstalled.
npm install --save source-highlight
// Load the source code into a UTF-8 buffer
const input = Buffer.from(`
console.log('Hello world!');
`);
// Create the SourceHighlight instance. "esc.outlang" will output colored characters to the console. You can
// use "html.outlang" too.
const sourceHighlight = new SourceHighlight('esc.outlang');
// Highlight the source code.
const output = sourceHighlight.highlight(input, 'javascript.lang', '').toString();
console.log(output);
import { SourceHighlight } from 'source-highlight';
source-highlight@1.0.0 exports just the SourceHighlight
class. The API documentation for the GNU source-highlight
can be found here. The methods of SourceHighlight
provided
by this package are enlisted below.
constructor(outLangDef: string)
Create a SourceHighlight
instance that will output into the format specified, e.g. html.outlang
.
highlight(input: string, output: string, inputLang: string): void
Highlight the input file and write into the output file. inputLang
is the name of the language
definition file you want to use. (This cannot be a path, e.g. html.lang
is valid not /path/to/html.lang
)
highlight(input: Buffer, inputLang: string, inputFileName: string): Buffer
Highlight the source code in the UTF-8 buffer using the language definition file inputLang
(again only a
filename in the data directory, not a path). You can provide inputFileName
optionally OR pass a blank string.
checkLangDef(langFile: string): void
Check if the language definition file (in the data directory) is valid. It will throw an error if it is invalid.
checkOutLangDef(outLangFile: string): void
Check if the output format specification file (in the data directory) is valid. It will throw an error if it is invalid.
setDataDir(dataDir: string): void
Set the data directory. By default, this will be a directory with all the language definition files and output formats that ship with GNU source-highlight.
setStyleFile(styleFile: string): void
Set the style file.
setStyleCssFile(cssFile: string): void
Use a CSS style file.
setStyleDefaultFile(styleFile: string): void
Set the default style file.
setTitle(title: string): void
setInputLang(inputLang: string): void
Set the input language to use when it can't be inferred.
setCss(css: string): void
setHeaderFileName(headerFileName: string): void
Set the header file to be prepended to the output document.
setFooterFileName(footerFileName: string): void
Set the footer file to be appended to the output document.
setOutputDir(outputDir: string): void