multipliedtwice / backticks-codeblocks

Tiny (~900 bytes) utility with no dependencies. Parses fenced code inside of text with backticks into code blocks and inline code. Parse and render text with highlighted code blocks
MIT License
1 stars 0 forks source link
codeblocks prismjs syntax-highlighting

npm version npm HitCount Coverage npm

Backticks-Codeblocks, syntax highlighting parser for fenced code

Backticks Codeblocks is a code fence library for parsing text and generating structures that can be rendered as code blocks or inline code using PrismJS.

Features

backticks-codeblocks

Package provides a simple and efficient way to parse strings containing backticks. It differentiates between inline code, marked by single backticks, and code blocks, surrounded by triple backticks, and returns them as structured data.

It's particularly useful for processing markdown text or any text that follows a similar convention for denoting code segments.

Installation

To install the package, use the following command:

npm install backticks-codeblocks

or if you use yarn

yarn add backticks-codeblocks

Usage

Import the processText function from the package and use it to parse a string with backticks:

import { processText } from 'backticks-codeblocks';

const result = processText('Some `inline code` and ```block code```');
console.log(result);

Ignore patterns

In some cases you can prevent backticks to be parsed as a block of code using second parameter.

const ignorePatterns: [RegExp, string][] = [
  [
    new RegExp('"```\\n"'.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'),
    'unique_string_as_a_name_identifier',
  ],
];
processText('Some `inline code` and ```block code```', ignorePatterns);

Input/Output Examples

The following table shows some example inputs and the corresponding output from the processText function:

Convert Block Code to Preformatted Text

Convert Inline and Block Code Correctly

Handles Consecutive Code Blocks

Handles Nested Backticks

Handles Interrupted Code Blocks

Handles Mixed Backticks

Handles Escaped Backticks

Handles Code Block at the Start

Handles Code Block at the End

Handles Empty Code Blocks

Handles Adjacent Code Blocks

Handles Unmatched Backticks Inside Code Blocks

Handles Code Blocks With New Lines

Performance

The processText function works fairly fast and is capable of handling large texts within reasonable time frames.

License

This project is open-sourced software licensed under the MIT license.

Credits: