Highlight code blocks with league/commonmark and Shiki

Overview

Highlight code blocks with league/commonmark and Shiki

Latest Version on Packagist Tests GitHub Code Style Action Status Total Downloads

This package contains a block renderer for league/commonmark to highlight code blocks using Shiki PHP.

This package also ships with the following extra languages, on top of the 100+ that Shiki supports out of the box:

  • Antlers
  • Blade

If you're using Laravel, make sure to look at our spatie/laravel-markdown package which offers easy integration with Shiki in laravel projects.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/commonmark-shiki-highlighter

In your project, you should have the JavaScript package shiki installed. You can install it via npm

npm install shiki

or Yarn

yarn add shiki

Usage

Here's how we can create a function that can convert markdown to HTML with all code snippets highlighted. Inside the function will create a new CommonMarkConverter that uses the HighlightCodeExtension provided by this package.

use League\CommonMark\CommonMarkConverter;
use League\CommonMark\Environment;
use Spatie\CommonMarkShikiHighlighter\HighlightCodeExtension;

function convertToHtml(string $markdown, string $theme): string
{
    $environment = Environment::createCommonMarkEnvironment()
        ->addExtension(new HighlightCodeExtension($theme));

    $commonMarkConverter = new CommonMarkConverter(environment: $environment);

    return $commonMarkConverter->convertToHtml($markdown);
}

Using themes

The $theme argument on HighlightCodeExtension expects the name of one of the many themes that Shiki supports.

Alternatively, you can use a custom theme. Shiki supports any VSCode themes. You can load a theme simply by passing an absolute path of a theme file to the $theme argument.

Marking lines as highlighted, added, deleted and focus

You can mark lines using the Markdown info tag as highlighted or focused. You can prefix lines with + or - to mark them as added or deleted. In the first pair of brackets, you can specify line numbers that should be highlighted. In an optional second pair you can specify which lines should be focused on.

```php{1,2}{3}
<?php
echo "We're highlighting line 1 and 2";
echo "And focusing line 3";
```php
<?php
+ echo "This line is marked as added";
- echo "This line is marked as deleted";

More syntax examples for highlighting & focusing

Line numbers start at 1.

```php - Don't highlight any lines

```php{4} - Highlight just line 4
```php{4-6} - Highlight the range of lines from 4 to 6 (inclusive)
```php{1,5} - Highlight just lines 1 and 5 on their own
```php{1-3,5} - Highlight 1 through 3 and then 5 on its own
```php{5,7,2-3} - The order of lines don't matter. However, specifying 3-2 will not work.

```php{}{4} - Focus just line 4 ```php{}{4-6} - Focus the range of lines from 4 to 6 (inclusive)
```php{}{1,5} - Focus just lines 1 and 5 on their own
```php{}{1-3,5} - Focus 1 through 3 and then 5 on its own
```php{}{5,7,2-3} - The order of lines don't matter. However, specifying 3-2 will not work.

Styling highlighted lines

When you mark lines as highlighted, added, deleted or focused, Shiki will apply some classes to those lines. You should add some CSS to your page to style those lines. Here's a bit of example CSS to get you started.

.shiki .highlight {
    background-color: hsl(197, 88%, 94%);
    padding: 3px 0;
}

.shiki .add {
    background-color: hsl(136, 100%, 96%);
    padding: 3px 0;
}

.shiki .del {
    background-color: hsl(354, 100%, 96%);
    padding: 3px 0;
}

.shiki.focus .line:not(.focus) {
    transition: all 250ms;
    filter: blur(2px);
}

.shiki.focus:hover .line {
    transition: all 250ms;
    filter: blur(0);
}

A word on performance

Highlighting with Shiki is a resource intensive process. We highly recommend using some form of caching.

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security Vulnerabilities

Please review our security policy on how to report security vulnerabilities.

Credits

Alternatives

If you don't want to install and handle Shiki yourself, take a look at Torchlight, which can highlight your code with minimal setup.

License

The MIT License (MIT). Please see License File for more information.

You might also like...
Magento 2 Module to add simple image resizing capabilities in all blocks and .phtml templates
Magento 2 Module to add simple image resizing capabilities in all blocks and .phtml templates

Magento 2 Image Resizer Magento 2 Module to add simple image resizing capabilities in all blocks and .phtml templates Installation $ composer require

Silverstripe module allowing editors to create newsletters using elemental blocks and export them to a sendy instance

Silverstripe Sendy Silverstripe module allowing editors to create newsletters using elemental blocks and export them to a sendy instance. Introduction

A virion for PocketMine-MP to create and manage fake blocks

🧊 fakeblocks Create and manage fakeblocks Description: A virion for PocketMine-MP to create and manage fake blocks. This virion indicates to the clie

A plugin to add more blocks to PocketMine

This plugin aims to add all blocks not included in PocketMine. As of right now the ExtendedBlocks plugin is required to add blocks with IDs above 255.

Provide blocks which allow positioning content within them in layouts.

Mini layouts Provide blocks which allow positioning content within them in layouts. Backdrop Installation Install and enable the module as usual. Go t

A quick naked theme to demonstrate how easy it is to support Gutenberg using ACF blocks

ACF Gutenberg Demo Theme A quick naked theme to demonstrate how easy it is to support Gutenberg using ACF blocks demo.mp4 Files I have found a useful

PocketMine-MP Plugin for converting items & blocks name to your language.
PocketMine-MP Plugin for converting items & blocks name to your language.

ConvertName PocketMine-MP Plugin for converting items & blocks name to your language. Usage Due to license issue, I don't put the language files direc

PocketMine-MP plugin that adds new blocks to the server!

CustomBlockLoader PocketMine-MP plugin that adds new blocks to the server! Reference This plugin is experimental. We are not responsible for any probl

⚗️ Adds code analysis to Laravel improving developer productivity and code quality.
⚗️ Adds code analysis to Laravel improving developer productivity and code quality.

⚗️ About Larastan Larastan was created by Can Vural and Nuno Maduro, got artwork designed by @Caneco, is maintained by Can Vural, Nuno Maduro, and Vik

Comments
  • Update README.md

    Update README.md

    Description

    When #5 was merged, I forgot to update the README file to replace the old CommonMarkConverter with the new MarkdownConverter. This PR fixes this small oversight.

    Changes

    • Replace CommonMarkConverter with MarkdownConverter in Usage section
    • Rename variable to be more in line with the class name

    I apologize for the inconvenience.

    opened by alexanderglueck 1
  • Update to Commonmark v2

    Update to Commonmark v2

    Description

    This pull request makes commonmark-shiki-highlighter compatible with league/commonmark v2. By upgrading to v2, support for v1 is dropped. This is a breaking change, and therefor I marked the release in the changelog as 2.0.

    Notes

    I need to push on my branch again to trigger Github Actions. Locally tests don't pass, but I think this is due to Windows \r\n instead of expected \n. EDIT: It seems like the tests pass on Github 😄

    Changes:

    • Added a changelog entry. This is now a new major version.
    • Updated composer.json to be in line with the new commonmark requirements
    • Updated the tests to use the new namespaces
    • Updated the readme to show an updated code sample

    Closing

    Would you like me to not commit the yarn.lock file? Let me know if there is anything else you need.

    opened by alexanderglueck 1
  • Add commonmark-extension package type

    Add commonmark-extension package type

    We encourage third-party extensions to use this type to make them more easily findable on Packagist: https://packagist.org/packages/league/commonmark?type=commonmark-extension

    (Great work on the extension BTW, I might have to use this myself sometime!)

    opened by colinodell 1
Releases(2.1.1)
Owner
Spatie
We create products and courses for the developer community
Spatie
Highlight PHP code in terminal

PHP Console Highlighter This repository is abandoned. Suggested alternative: https://github.com/php-parallel-lint/PHP-Console-Highlighter Highlight PH

Jakub Onderka 6.2k Dec 22, 2022
Highlight PHP code in terminal

PHP Console Highlighter Highlight PHP code in console (terminal). Example Install Just run the following command to install it: composer require --dev

PHP Parallel lint 74 Dec 12, 2022
Converts any PocketMine-MP 3.0 extended blocks into PM4 native blocks!

ExtendedBlocksConverter Converts any PocketMine-MP 3.0 extended blocks into PM4 native blocks! Yes, you heard right, this plugin can convert any lefto

Covered123 6 Jun 4, 2022
This library is an implementation of League\Event for Slim Framework

Slim Event Dispatcher This library is an implementation of League\Event for Slim Framework. This works with the latest version of Slim (V3). Installat

Aneek Mukhopadhyay 7 Aug 23, 2022
A minimal library that defines primitive building blocks of PHP code.

Jungi Common A minimal library that defines primitive building blocks of PHP code. It combines the advantages of functional and object-oriented progra

Piotr Kugla 28 Jul 15, 2022
A minimal library that defines primitive building blocks of PHP code.

A minimal library that defines primitive building blocks of PHP code. It combines the advantages of functional and object-oriented programming. All of this makes code easier to understand and less prone to errors.

Jungi 28 Jul 15, 2022
A Magento 2 module that allows admins to duplicate CMS blocks and pages from their respective grids and en masse.

element119 | CMS Duplicator ?? Features ✔️ Allows merchants to duplicate CMS blocks and pages from the Action column in the admin grid ✔️ Allows merch

Kiel Pykett 13 Oct 13, 2022
Allow SVG images to be used in Magento CMS blocks and pages via the TinyMCE Wysiwyg Editor.

Hyvä Themes - SVG support for the Magento CMS Wysiwyg Editor Allow SVG images to be used in CMS blocks and pages via the TinyMCE Wysiwyg Editor. hyva-

Hyvä 14 Dec 15, 2022
This plugin adds 95% of 1.16 blocks & items and their functionality

INether This plugin adds 95% of 1.16 blocks & items and their functionality Implemented blocks Ancient Debris All types of Basalt Crimson & Warped Fun

null 34 Dec 7, 2022