### Install Phiki using Composer Source: https://github.com/phikiphp/phiki/blob/2.x/docs/installation.mdx Run this command in your project's root directory to install Phiki. It adds the latest stable version to your composer.json. ```sh composer require phiki/phiki:^2.0 ``` -------------------------------- ### Initialize CommonMark with Phiki Extension Source: https://github.com/phikiphp/phiki/blob/2.x/docs/commonmark.mdx Set up the CommonMark environment with the Phiki extension for code highlighting. Ensure you have the necessary League CommonMark and Phiki components installed. ```php use League\CommonMark\Environment\Environment; use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; use League\CommonMark\MarkdownConverter; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Theme\Theme; $environment = new Environment; $environment ->addExtension(new CommonMarkCoreExtension) ->addExtension(new PhikiExtension(Theme::GithubLight)); $converter = new MarkdownConverter($environment); $output = $converter->convert("My awesome blog post with code blocks..."); ``` -------------------------------- ### Install Phiki via Composer Source: https://github.com/phikiphp/phiki/blob/2.x/README.md Use this command to add the Phiki package to your PHP project dependencies. ```sh composer require phiki/phiki ``` -------------------------------- ### Gutter Diff Symbols Example Source: https://github.com/phikiphp/phiki/blob/2.x/docs/commonmark.mdx Demonstrates the setup for Phiki with a gutter enabled, which replaces line numbers with diff symbols (+ for insert, - for remove). ```php $environment = new Environment; $environment ->addExtension(new CommonMarkCoreExtension) ->addExtension(new PhikiExtension(Theme::GithubLight, withGutter: true)); ``` -------------------------------- ### Set starting line number Source: https://github.com/phikiphp/phiki/blob/2.x/docs/highlighting-code.mdx Configure the initial line number for the gutter using the startingLine method. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $html = (new Phiki) ->codeToHtml("withGutter() ->startingLine(5) ->toString(); ``` -------------------------------- ### CSS Styling with AddClassesTransformer Source: https://github.com/phikiphp/phiki/blob/2.x/docs/add-classes-transformer.mdx Example CSS to style elements based on the 'phiki-source.php' classes added by the transformer. ```css .token[class^="phiki-keyword"] { color: blue !important; } ``` -------------------------------- ### CSS for Highlighted Lines Source: https://github.com/phikiphp/phiki/blob/2.x/docs/commonmark.mdx Example CSS for styling highlighted lines using Phiki's generated CSS variables, including dark mode overrides. ```css @media (prefers-color-scheme: dark) { .phiki .line.highlight { background-color: var(--phiki-dark-line-highlight) !important; } } ``` -------------------------------- ### Adding line numbers with withGutter Source: https://context7.com/phikiphp/phiki/llms.txt Enables a line number gutter in the output, with support for custom starting line numbers. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $phiki = new Phiki(); $code = <<<'PHP' codeToHtml($code, Grammar::Php, Theme::GithubLight) ->withGutter() ->toString(); // Start line numbers at 42 $html = $phiki ->codeToHtml($code, Grammar::Php, Theme::GithubLight) ->withGutter() ->startingLine(42) ->toString(); ``` -------------------------------- ### Blade Component with Custom Starting Line Number Source: https://context7.com/phikiphp/phiki/llms.txt Set a custom starting line number for the gutter using the 'starting-line' attribute. ```blade // This starts at line 42 $result = calculate(); ``` -------------------------------- ### Create a new Phiki instance Source: https://github.com/phikiphp/phiki/blob/2.x/docs/quick-start-guide.mdx Instantiate the Phiki class to begin using its features. Ensure the Phiki namespace is imported. ```php use Phiki\Phiki; $phiki = new Phiki(); ``` -------------------------------- ### Use Multiple Themes with Phiki Extension Source: https://github.com/phikiphp/phiki/blob/2.x/docs/commonmark.mdx Initialize the Phiki extension with an array of themes to support multiple color schemes, such as light and dark modes. ```php use League\CommonMark\Environment\Environment; use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; use League\CommonMark\MarkdownConverter; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Theme\Theme; $environment = new Environment; $environment ->addExtension(new CommonMarkCoreExtension) ->addExtension(new PhikiExtension([ 'light' => Theme::GithubLight, 'dark' => Theme::GithubDark, ])); // [!code ++] ``` -------------------------------- ### Using a Custom Transformer in Phiki Source: https://github.com/phikiphp/phiki/blob/2.x/docs/transformers.mdx Demonstrates how to create a custom transformer by extending `AbstractTransformer` and applying it during code highlighting. Ensure all necessary classes are imported. ```php use Phiki\Phiki; use Phiki\Theme\Theme; use Phiki\Transformers\AbstractTransformer; class MyTransformer extends AbstractTransformer { // Implement the methods you need here... } $html = (new Phiki) ->codeToHtml("transformer(new MyTransformer) ->toString(); ``` -------------------------------- ### Load a local theme file Source: https://github.com/phikiphp/phiki/blob/2.x/docs/custom-themes.mdx Load a theme by providing a slug and the file path to the theme() method. ```php use Phiki\Phiki; $phiki = (new Phiki) ->theme('my-theme', '/path/to/my-theme.json'); ``` -------------------------------- ### Create a Reusable Extension in PHP Source: https://context7.com/phikiphp/phiki/llms.txt Bundle custom grammars, themes, and configurations into reusable extensions by implementing ExtensionInterface. This allows for shared and consistent configurations across projects. ```php use Phiki\Phiki; use Phiki\Contracts\ExtensionInterface; use Phiki\Environment; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; class MyCompanyExtension implements ExtensionInterface { public function register(Environment $environment): void { // Register custom grammars $environment->grammar('internal-dsl', __DIR__ . '/grammars/internal-dsl.json'); $environment->grammar('config-lang', __DIR__ . '/grammars/config-lang.json'); // Register company themes $environment->theme('company-light', __DIR__ . '/themes/company-light.json'); $environment->theme('company-dark', __DIR__ . '/themes/company-dark.json'); } } $phiki = new Phiki(); $phiki->extend(new MyCompanyExtension()); // Now use the custom grammars and themes $html = $phiki ->codeToHtml('DEFINE task: "build"', 'internal-dsl', 'company-light') ->toString(); ``` -------------------------------- ### Highlight PHP code to HTML Source: https://github.com/phikiphp/phiki/blob/2.x/docs/quick-start-guide.mdx Load a PHP file and use the Phiki instance to convert its content to HTML with syntax highlighting. Specify the grammar and theme for highlighting. ```php use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $code = file_get_contents('path/to/your/code.php'); $highlighted = $phiki->codeToHtml($code, Grammar::Php, Theme::GithubLight); echo $highlighted; ``` -------------------------------- ### Implement a custom extension class Source: https://github.com/phikiphp/phiki/blob/2.x/docs/custom-extensions.mdx Create a class implementing ExtensionInterface to register custom grammars and themes via the Environment object. ```php use Phiki\Contracts\ExtensionInterface; use Phiki\Environment; class MyExtension implements ExtensionInterface { public function register(Environment $environment): void { $environment ->grammar('my-language', __DIR__ . '/grammars/my-language.json') ->theme('my-theme', __DIR__ . '/themes/my-theme.json'); } } ``` -------------------------------- ### Laravel Facade Basic Usage Source: https://context7.com/phikiphp/phiki/llms.txt Perform basic code highlighting in Laravel applications using the Phiki facade. Specify the code, grammar, and theme directly. ```php use Phiki\Adapters\Laravel\Facades\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; // Basic highlighting with facade $html = Phiki::codeToHtml('toString(); ``` -------------------------------- ### Register custom grammars and themes Source: https://github.com/phikiphp/phiki/blob/2.x/docs/laravel.mdx Register custom grammars and themes in the boot method of a service provider. ```php use Phiki\Adapters\Laravel\Facades\Phiki; class AppServiceProvider extends ServiceProvider { public function boot(): void { Phiki::grammar('my-grammar', __DIR__ . '/path/to/grammar.json'); Phiki::theme('my-theme', __DIR__ . '/path/to/theme.json'); } } ``` -------------------------------- ### Load a local grammar file Source: https://github.com/phikiphp/phiki/blob/2.x/docs/custom-grammars.mdx Register a custom grammar by providing a slug and the file path to the grammar() method. ```php use Phiki\Phiki; $phiki = (new Phiki) ->grammar('my-language', '/path/to/my-language.json'); ``` -------------------------------- ### Registering Custom Themes Source: https://context7.com/phikiphp/phiki/llms.txt Add custom Visual Studio Code themes by registering theme JSON files or defining themes at runtime. ```APIDOC ## Registering Custom Themes ### Description Add custom Visual Studio Code themes by registering theme JSON files or defining themes at runtime. ### Method ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $phiki = new Phiki(); // Register from a local JSON file $phiki->theme('my-theme', '/path/to/my-theme.json'); // Register from an array definition at runtime $phiki->theme('custom-dark', Theme::parse([ 'name' => 'Custom Dark', 'colors' => [ 'editor.background' => '#1e1e1e', 'editor.foreground' => '#d4d4d4', ], 'tokenColors' => [ [ 'scope' => 'keyword', 'settings' => ['foreground' => '#569cd6'] ], [ 'scope' => 'string', 'settings' => ['foreground' => '#ce9178'] ], ] ])); // Use the custom theme $html = $phiki ->codeToHtml('const x = "hello";', Grammar::Javascript, 'custom-dark') ->toString(); ``` ``` -------------------------------- ### Basic CommonMark Integration with Phiki Source: https://context7.com/phikiphp/phiki/llms.txt Integrate Phiki with league/commonmark to highlight code blocks in Markdown. Requires setting up the CommonMark environment and adding the Phiki extension. ```php use League\CommonMark\Environment\Environment; use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; use League\CommonMark\MarkdownConverter; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Theme\Theme; // Basic setup $environment = new Environment(); $environment ->addExtension(new CommonMarkCoreExtension()) ->addExtension(new PhikiExtension(Theme::GithubLight)); $converter = new MarkdownConverter($environment); $markdown = <<<'MD' # My Document Here is some PHP code: ```php convert($markdown); ``` -------------------------------- ### Highlight code with Phiki facade Source: https://github.com/phikiphp/phiki/blob/2.x/docs/laravel.mdx Use the Phiki facade to manually highlight code in Laravel. ```php use Phiki\Adapters\Laravel\Facades\Phiki; $html = Phiki::codeToHtml("toString(); ``` -------------------------------- ### CommonMark Integration with Gutter Source: https://context7.com/phikiphp/phiki/llms.txt Enable line numbers (gutter) in highlighted code blocks by setting `withGutter` to true when initializing the Phiki extension. ```php // With gutter enabled $environment2 = new Environment(); $environment2 ->addExtension(new CommonMarkCoreExtension()) ->addExtension(new PhikiExtension(Theme::GithubLight, withGutter: true)); ``` -------------------------------- ### Enabling caching with PSR-16 Source: https://context7.com/phikiphp/phiki/llms.txt Improves performance by caching highlighting results using the PSR-16 SimpleCache interface. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; use Psr\SimpleCache\CacheInterface; // Example simple file-based cache implementation class FileCache implements CacheInterface { public function __construct(private string $cacheDir) {} public function get(string $key, mixed $default = null): mixed { $file = $this->cacheDir . '/' . md5($key); return file_exists($file) ? unserialize(file_get_contents($file)) : $default; } public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool { return file_put_contents($this->cacheDir . '/' . md5($key), serialize($value)) !== false; } public function has(string $key): bool { return file_exists($this->cacheDir . '/' . md5($key)); } // ... implement other CacheInterface methods } $phiki = new Phiki(); // Enable caching globally for all codeToHtml calls $phiki->cache(new FileCache('/tmp/phiki-cache')); $html = $phiki ->codeToHtml('echo "cached";', Grammar::Php, Theme::GithubLight) ->toString(); // Or cache individual snippets only $phiki2 = new Phiki(); $html = $phiki2 ->codeToHtml('echo "also cached";', Grammar::Php, Theme::GithubLight) ->cache(new FileCache('/tmp/phiki-cache')) ->toString(); ``` -------------------------------- ### Registering custom themes Source: https://context7.com/phikiphp/phiki/llms.txt Adds custom Visual Studio Code themes via JSON files or runtime array definitions. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $phiki = new Phiki(); // Register from a local JSON file $phiki->theme('my-theme', '/path/to/my-theme.json'); // Register from an array definition at runtime $phiki->theme('custom-dark', Theme::parse([ 'name' => 'Custom Dark', 'colors' => [ 'editor.background' => '#1e1e1e', 'editor.foreground' => '#d4d4d4', ], 'tokenColors' => [ [ 'scope' => 'keyword', 'settings' => ['foreground' => '#569cd6'] ], [ 'scope' => 'string', 'settings' => ['foreground' => '#ce9178'] ], ] ])); // Use the custom theme $html = $phiki ->codeToHtml('const x = "hello";', Grammar::Javascript, 'custom-dark') ->toString(); ``` -------------------------------- ### Define a grammar at runtime Source: https://github.com/phikiphp/phiki/blob/2.x/docs/custom-grammars.mdx Register a grammar by passing an associative array to Grammar::parse() instead of a file path. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; $phiki = (new Phiki) ->grammar('my-language', Grammar::parse([ 'name' => 'my-language', 'scopeName' => 'source.my-language', 'patterns' => [ // ... ], 'repository' => [ // ... ] ])); ``` -------------------------------- ### CommonMark Integration with Multiple Themes Source: https://context7.com/phikiphp/phiki/llms.txt Configure Phiki to support multiple themes for dark mode by passing an associative array of theme names to their respective `Theme` constants. ```php // With multiple themes for dark mode $environment3 = new Environment(); $environment3 ->addExtension(new CommonMarkCoreExtension()) ->addExtension(new PhikiExtension([ 'light' => Theme::GithubLight, 'dark' => Theme::GithubDark, ])); ``` -------------------------------- ### Enable Gutter in Phiki Extension Source: https://github.com/phikiphp/phiki/blob/2.x/docs/commonmark.mdx Configure the Phiki extension to display a gutter next to code blocks by setting the `withGutter` argument to `true` in the constructor. ```php use League\CommonMark\Environment\Environment; use League\CommonMark\Extension\CommonMark\CommonMarkCoreExtension; use League\CommonMark\MarkdownConverter; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Theme\Theme; $environment = new Environment; $environment ->addExtension(new CommonMarkCoreExtension) ->addExtension(new PhikiExtension(Theme::GithubLight, withGutter: true)); // [!code ++] ``` -------------------------------- ### Apply a custom theme Source: https://github.com/phikiphp/phiki/blob/2.x/docs/custom-themes.mdx Use a registered custom theme by passing its slug to the codeToHtml() method. ```php $html = (new Phiki) ->theme('my-theme', '/path/to/my-theme.json') ->codeToHtml('Your code here...', Grammar::Php, 'my-theme') ->toString(); ``` -------------------------------- ### Define a theme at runtime Source: https://github.com/phikiphp/phiki/blob/2.x/docs/custom-themes.mdx Define a theme dynamically by passing an associative array to Theme::parse(). ```php use Phiki\Phiki; use Phiki\Theme\Theme; $phiki = (new Phiki) ->theme('my-theme', Theme::parse([ 'name' => 'my-theme', 'colors' => [ // ... ], 'tokenColors' => [ // ... ] ])); ``` -------------------------------- ### Registering Custom Grammars Source: https://context7.com/phikiphp/phiki/llms.txt Add support for custom languages by registering TextMate grammar files. Grammars can be loaded from JSON files or defined as arrays at runtime. ```APIDOC ## Registering Custom Grammars ### Description Add support for custom languages by registering TextMate grammar files. Grammars can be loaded from JSON files or defined as arrays at runtime. ### Method ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $phiki = new Phiki(); // Register from a local JSON file $phiki->grammar('my-language', '/path/to/my-language.json'); // Register from an array definition at runtime $phiki->grammar('custom-lang', Grammar::parse([ 'name' => 'custom-lang', 'scopeName' => 'source.custom-lang', 'patterns' => [ [ 'name' => 'keyword.control.custom-lang', 'match' => '\\b(if|else|while|for|return)\\b' ], [ 'name' => 'string.quoted.double.custom-lang', 'begin' => '"', 'end' => '"' ], ], 'repository' => [] ])); // Use the custom grammar $html = $phiki ->codeToHtml('if (x) return "yes"', 'custom-lang', Theme::GithubLight) ->toString(); // Create an alias for an existing grammar $phiki->alias('my-php', Grammar::Php); $html = $phiki ->codeToHtml('toString(); ``` ``` -------------------------------- ### Sample CSS for Highlighted and Focused Lines Source: https://github.com/phikiphp/phiki/blob/2.x/docs/commonmark.mdx Provides CSS rules to style highlighted lines and to apply a blur effect to non-focused lines, with a hover effect to reveal all lines when focus is active. ```css pre.phiki code .line.highlight { background-color: hsl(197, 88%, 94%); } pre.phiki.focus .line:not(.focus) { transition: all 250ms; filter: blur(2px); } pre.phiki.focus:hover .line { transition: all 250ms; filter: blur(0); } ``` -------------------------------- ### codeToHtml Method Source: https://context7.com/phikiphp/phiki/llms.txt Generates syntax-highlighted HTML from a code string using specified grammar and theme. ```APIDOC ## codeToHtml ### Description Generates syntax highlighted HTML from code strings. Returns a PendingHtmlOutput object that can be further customized. ### Parameters - **code** (string) - Required - The source code to highlight. - **grammar** (string|Enum) - Required - The language grammar identifier. - **theme** (string|Enum|array) - Required - The theme identifier or an array of themes for light/dark mode support. ### Request Example $phiki->codeToHtml('toString(); ``` -------------------------------- ### Customize cache store Source: https://github.com/phikiphp/phiki/blob/2.x/docs/laravel.mdx Configure the cache store used by Phiki in the boot method of a service provider. ```php use Phiki\Adapters\Laravel\Facades\Phiki; use Illuminate\Support\Facades\Cache; class AppServiceProvider extends ServiceProvider { public function boot(): void { Phiki::cache(Cache::store('redis')); } } ``` -------------------------------- ### Configuring multiple themes for dark mode Source: https://context7.com/phikiphp/phiki/llms.txt Passes an array of themes to generate CSS variables, enabling theme toggling via media queries or CSS classes. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $phiki = new Phiki(); $html = $phiki ->codeToHtml('echo "Hello";', Grammar::Php, [ 'light' => Theme::GithubLight, 'dark' => Theme::GithubDark, ]) ->toString(); // The HTML includes CSS variables: --phiki-dark-color, --phiki-dark-background-color, etc. // CSS for query-based dark mode: /* @media (prefers-color-scheme: dark) { .phiki, .phiki span { color: var(--phiki-dark-color) !important; background-color: var(--phiki-dark-background-color) !important; font-style: var(--phiki-dark-font-style) !important; font-weight: var(--phiki-dark-font-weight) !important; text-decoration: var(--phiki-dark-text-decoration) !important; } } */ // CSS for class-based dark mode: /* html.dark .phiki, html.dark .phiki span { color: var(--phiki-dark-color) !important; background-color: var(--phiki-dark-background-color) !important; } */ ``` -------------------------------- ### Inline Line Highlighting with Ranges Source: https://github.com/phikiphp/phiki/blob/2.x/docs/commonmark.mdx Demonstrates using inline comments `// [code! highlight]` to mark lines for highlighting. Supports various range specifications like `highlight:2` (current line + 2 lines) or `highlight:-2` (current line + 2 previous lines). ```php echo "Hello, world!"; // [code! highlight] ``` ```php echo "Hello, world!"; // [code! hl] ``` ```php echo "Hello, world!"; // [code! ~~] ``` -------------------------------- ### Highlight Code with Multiple Themes Source: https://github.com/phikiphp/phiki/blob/2.x/docs/multi-themes.mdx Pass an array of theme names to `Phiki::codeToHtml()` to support multiple themes. The first theme is the default. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $html = (new Phiki) ->codeToHtml(" Theme::GithubLight, 'dark' => Theme::GithubDark, ]) ->toString(); ``` -------------------------------- ### Highlight Markdown code blocks Source: https://github.com/phikiphp/phiki/blob/2.x/docs/laravel.mdx Use the PhikiExtension with Str::markdown to highlight code blocks. ```php use Illuminate\Support\Str; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Phiki; use Phiki\Theme\Theme; Str::markdown($markdown, extensions: [ new PhikiExtension(Theme::GithubLight, resolve(Phiki::class)), ]); ``` ```php use Illuminate\Support\Str; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Theme\Theme; use Phiki\Phiki; Str::markdown($markdown, extensions: [ new PhikiExtension(Theme::GithubLight, resolve(Phiki::class), withGutter: true), ]); ``` ```php use Illuminate\Support\Str; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Phiki; use Phiki\Theme\Theme; Str::markdown($markdown, extensions: [ new PhikiExtension([ 'light' => Theme::GithubLight, 'dark' => Theme::GithubDark, ], resolve(Phiki::class)), ]); ``` ```php use Illuminate\Support\Str; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Theme\Theme; use Phiki\Phiki; Str::markdown($markdown, extensions: [ new PhikiExtension(Theme::GithubLight, resolve(Phiki::class)), ]); ``` -------------------------------- ### Register custom extensions in Service Provider Source: https://github.com/phikiphp/phiki/blob/2.x/docs/laravel.mdx Register custom extensions within the boot method of a service provider. ```php use Phiki\Adapters\Laravel\Facades\Phiki; use App\Phiki\MyCustomExtension; class AppServiceProvider extends ServiceProvider { public function boot(): void { Phiki::extend(new MyCustomExtension); } } ``` -------------------------------- ### Access Grammars and Themes Repositories in Phiki 2.0 Source: https://github.com/phikiphp/phiki/blob/2.x/docs/upgrade-2.0.mdx Access grammar and theme repositories directly via the `Phiki::$environment` property. These properties are readonly. ```php $phiki = new Phiki(); $phiki->environment->grammars->...; $phiki->environment->themes->...; ``` -------------------------------- ### Highlight code to HTML in PHP Source: https://github.com/phikiphp/phiki/blob/2.x/docs/highlighting-code.mdx Use the codeToHtml method to convert a code string into highlighted HTML output. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $html = (new Phiki) ->codeToHtml("toString(); ``` -------------------------------- ### Enable line numbers with a gutter Source: https://github.com/phikiphp/phiki/blob/2.x/docs/highlighting-code.mdx Add a line number gutter to the output by chaining the withGutter method. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $html = (new Phiki) ->codeToHtml("withGutter() ->toString(); ``` -------------------------------- ### Style code blocks with CSS Source: https://github.com/phikiphp/phiki/blob/2.x/docs/highlighting-code.mdx Apply basic styling to the generated pre element to improve readability. ```css pre { font-family: ui-monospace, SFMono-Regular, Consolas, "Liberation Mono", Menlo, Courier, monospace; font-size: 0.875rem; /* 14px */ padding: 1rem 1.5rem; /* 16px 24px */ border-radius: 0.375rem; /* 6px */ overflow-x: auto; } ``` -------------------------------- ### Registering custom grammars Source: https://context7.com/phikiphp/phiki/llms.txt Adds support for custom languages via JSON files or runtime array definitions. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $phiki = new Phiki(); // Register from a local JSON file $phiki->grammar('my-language', '/path/to/my-language.json'); // Register from an array definition at runtime $phiki->grammar('custom-lang', Grammar::parse([ 'name' => 'custom-lang', 'scopeName' => 'source.custom-lang', 'patterns' => [ [ 'name' => 'keyword.control.custom-lang', 'match' => '\\b(if|else|while|for|return)\\b' ], [ 'name' => 'string.quoted.double.custom-lang', 'begin' => '"', 'end' => '"' ], ], 'repository' => [] ])); // Use the custom grammar $html = $phiki ->codeToHtml('if (x) return "yes"', 'custom-lang', Theme::GithubLight) ->toString(); // Create an alias for an existing grammar $phiki->alias('my-php', Grammar::Php); $html = $phiki ->codeToHtml('toString(); ``` -------------------------------- ### withGutter Method Source: https://context7.com/phikiphp/phiki/llms.txt Enables line number gutters on the generated HTML output. ```APIDOC ## withGutter ### Description Adds a line number gutter to the left side of the code block. Can be chained with startingLine() to define the initial line number. ### Parameters - **startingLine** (int) - Optional - The number to start the line count from. ``` -------------------------------- ### Enable Global Caching in Phiki Source: https://github.com/phikiphp/phiki/blob/2.x/docs/caching.mdx Provide a PSR-16 compatible cache implementation to the Phiki::cache() method to enable caching for all subsequent code highlighting operations. This caches HTML output based on code, grammar, theme, gutter settings, and transformers. ```php class SimpleCache implements \Psr\SimpleCache\CacheInterface { // ... } $phiki = (new Phiki) ->cache(new SimpleCache); ``` -------------------------------- ### Register a custom extension Source: https://github.com/phikiphp/phiki/blob/2.x/docs/custom-extensions.mdx Apply the custom extension to a Phiki instance using the extend method. ```php use App\Phiki\MyExtension; $phiki = (new Phiki) ->extend(new MyExtension); ``` -------------------------------- ### Laravel Str::markdown Integration with Multiple Themes Source: https://context7.com/phikiphp/phiki/llms.txt Configure multiple themes for dark mode in Markdown code blocks by passing an array of themes to PhikiExtension. ```php use Illuminate\Support\Str; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Phiki; use Phiki\Theme\Theme; $markdown = <<<'MD' # Welcome Here's some code: ```php $greeting = "Hello, World!"; echo $greeting; ``` MD; // With multiple themes $html = Str::markdown($markdown, extensions: [ new PhikiExtension([ 'light' => Theme::GithubLight, 'dark' => Theme::GithubDark, ], resolve(Phiki::class)), ]); ``` -------------------------------- ### Highlighting code with codeToHtml Source: https://context7.com/phikiphp/phiki/llms.txt Generates syntax-highlighted HTML from code strings using either enum-based or string-based identifiers for languages and themes. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; // Basic usage - highlight PHP code with GitHub Light theme $phiki = new Phiki(); $html = $phiki ->codeToHtml('toString(); // Output:
...
// Using string identifiers instead of enums $html = $phiki ->codeToHtml('const x = 42;', 'javascript', 'dracula') ->toString(); // Highlight Python code with Monokai theme $pythonCode = <<<'PYTHON' def greet(name): return f"Hello, {name}!" print(greet("World")) PYTHON; $html = $phiki ->codeToHtml($pythonCode, Grammar::Python, Theme::Monokai) ->toString(); ``` -------------------------------- ### Enabling Caching with PSR-16 SimpleCache Source: https://context7.com/phikiphp/phiki/llms.txt Enable caching to improve performance for repeated highlighting operations. Phiki uses PSR-16 SimpleCache interface, compatible with any compliant cache implementation. ```APIDOC ## Enabling Caching with PSR-16 SimpleCache ### Description Enable caching to improve performance for repeated highlighting operations. Phiki uses PSR-16 SimpleCache interface, compatible with any compliant cache implementation. ### Method ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; use Psr\SimpleCache\CacheInterface; // Example simple file-based cache implementation class FileCache implements CacheInterface { public function __construct(private string $cacheDir) {} public function get(string $key, mixed $default = null): mixed { $file = $this->cacheDir . '/' . md5($key); return file_exists($file) ? unserialize(file_get_contents($file)) : $default; } public function set(string $key, mixed $value, null|int|\DateInterval $ttl = null): bool { return file_put_contents($this->cacheDir . '/' . md5($key), serialize($value)) !== false; } public function has(string $key): bool { return file_exists($this->cacheDir . '/' . md5($key)); } // ... implement other CacheInterface methods } $phiki = new Phiki(); // Enable caching globally for all codeToHtml calls $phiki->cache(new FileCache('/tmp/phiki-cache')); $html = $phiki ->codeToHtml('echo "cached";', Grammar::Php, Theme::GithubLight) ->toString(); // Or cache individual snippets only $phiki2 = new Phiki(); $html = $phiki2 ->codeToHtml('echo "also cached";', Grammar::Php, Theme::GithubLight) ->cache(new FileCache('/tmp/phiki-cache')) ->toString(); ``` ``` -------------------------------- ### Highlighted Tokens with codeToHighlightedTokens Source: https://context7.com/phikiphp/phiki/llms.txt Generate tokens with theme styling applied. Returns highlighted tokens containing both the raw token data and styling information from the theme. ```APIDOC ## Highlighted Tokens with codeToHighlightedTokens ### Description Generate tokens with theme styling applied. Returns highlighted tokens containing both the raw token data and styling information from the theme. ### Method ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $phiki = new Phiki(); $code = 'function hello() { return "Hi"; }'; // Get highlighted tokens with theme styles applied $highlightedTokens = $phiki->codeToHighlightedTokens( $code, Grammar::Javascript, Theme::OneDarkPro ); // Process highlighted tokens foreach ($highlightedTokens as $lineIndex => $lineTokens) { foreach ($lineTokens as $highlightedToken) { $text = $highlightedToken->token->text; $settings = $highlightedToken->settings['default'] ?? null; $color = $settings?->foreground; // Use token data for custom rendering... } } ``` ``` -------------------------------- ### Highlighting tokens with codeToHighlightedTokens Source: https://context7.com/phikiphp/phiki/llms.txt Generates tokens with theme styling applied for custom rendering. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; $phiki = new Phiki(); $code = 'function hello() { return "Hi"; }'; // Get highlighted tokens with theme styles applied $highlightedTokens = $phiki->codeToHighlightedTokens( $code, Grammar::Javascript, Theme::OneDarkPro ); // Process highlighted tokens foreach ($highlightedTokens as $lineIndex => $lineTokens) { foreach ($lineTokens as $highlightedToken) { $text = $highlightedToken->token->text; $settings = $highlightedToken->settings['default'] ?? null; $color = $settings?->foreground; // Use token data for custom rendering... } } ``` -------------------------------- ### Laravel Str::markdown Basic Integration Source: https://context7.com/phikiphp/phiki/llms.txt Integrate Phiki with Laravel's Str::markdown() to highlight code blocks within Markdown strings. Requires PhikiExtension. ```php use Illuminate\Support\Str; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Phiki; use Phiki\Theme\Theme; $markdown = <<<'MD' # Welcome Here's some code: ```php $greeting = "Hello, World!"; echo $greeting; ``` MD; // Basic usage $html = Str::markdown($markdown, extensions: [ new PhikiExtension(Theme::GithubLight, resolve(Phiki::class)), ]); ``` -------------------------------- ### Register Phiki Extension in Statamic Source: https://github.com/phikiphp/phiki/blob/2.x/docs/statamic.mdx Register the PhikiExtension within the boot method of a service provider to enable syntax highlighting in Statamic Markdown. ```php use Statamic\Facades\Markdown; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Theme\Theme; use Phiki\Phiki; class AppServiceProvider extends ServiceProvider { public function boot(): void { Markdown::addExtension(fn () => new PhikiExtension(Theme::GithubLight, resolve(Phiki::class))); } } ``` -------------------------------- ### codeToTokens Method Source: https://context7.com/phikiphp/phiki/llms.txt Converts code into raw token data without applying HTML formatting. ```APIDOC ## codeToTokens ### Description Parses code into an array of lines, where each line contains an array of tokens with text and scope information. ### Parameters - **code** (string) - Required - The source code to tokenize. - **grammar** (string|Enum) - Required - The language grammar identifier. ### Response - **tokens** (array) - An array of lines containing token objects with 'text' and 'scopes' properties. ``` -------------------------------- ### Use a custom grammar Source: https://github.com/phikiphp/phiki/blob/2.x/docs/custom-grammars.mdx Reference the registered slug when calling codeToHtml to apply the custom grammar. ```php $html = (new Phiki) ->grammar('my-language', '/path/to/my-language.json') ->codeToHtml('Your code here...', 'my-language', Theme::GithubLight) ->toString(); ``` -------------------------------- ### Laravel Str::markdown Integration with Gutter Source: https://context7.com/phikiphp/phiki/llms.txt Enable line numbers for code blocks in Markdown by setting 'withGutter' to true in PhikiExtension. ```php use Illuminate\Support\Str; use Phiki\Adapters\CommonMark\PhikiExtension; use Phiki\Phiki; use Phiki\Theme\Theme; $markdown = <<<'MD' # Welcome Here's some code: ```php $greeting = "Hello, World!"; echo $greeting; ``` MD; // With gutter $html = Str::markdown($markdown, extensions: [ new PhikiExtension(Theme::GithubLight, resolve(Phiki::class), withGutter: true), ]); ``` -------------------------------- ### Query-based Dark Mode CSS Source: https://github.com/phikiphp/phiki/blob/2.x/docs/multi-themes.mdx Apply dark theme styles using a media query for system preference. ```css @media (prefers-color-scheme: dark) { .phiki, .phiki span { color: var(--phiki-dark-color) !important; background-color: var(--phiki-dark-background-color) !important; font-style: var(--phiki-dark-font-style) !important; font-weight: var(--phiki-dark-font-weight) !important; text-decoration: var(--phiki-dark-text-decoration) !important; } } ``` -------------------------------- ### CSS for Diff Annotations Source: https://github.com/phikiphp/phiki/blob/2.x/docs/commonmark.mdx Illustrates how to use Phiki's CSS variables for diff annotations (insert/remove) to style the background and text colors, with dark mode support. ```css .phiki .line.insert { background-color: var(--phiki-diff-insert-bg); color: var(--phiki-diff-insert-fg); } .phiki .line.remove { background-color: var(--phiki-diff-remove-bg); color: var(--phiki-diff-remove-fg); } ``` ```css @media (prefers-color-scheme: dark) { .phiki .line.insert { background-color: var(--phiki-dark-diff-insert-bg) !important; color: var(--phiki-dark-diff-insert-fg) !important; } .phiki .line.remove { background-color: var(--phiki-dark-diff-remove-bg) !important; color: var(--phiki-dark-diff-remove-fg) !important; } } ``` -------------------------------- ### Basic Blade Component Usage Source: https://context7.com/phikiphp/phiki/llms.txt Use the Blade component to highlight code directly in your views. Specify the grammar and theme. ```blade ``` -------------------------------- ### Create a Custom Transformer in PHP Source: https://context7.com/phikiphp/phiki/llms.txt Extend AbstractTransformer to modify code at different stages: preprocess, pre, line, token, and postprocess. Use this to customize output, add attributes, or inject content. ```php use Phiki\Phiki; use Phiki\Grammar\Grammar; use Phiki\Theme\Theme; use Phiki\Transformers\AbstractTransformer; use Phiki\Phast\Element; use Phiki\Phast\Root; use Phiki\Token\HighlightedToken; class CustomTransformer extends AbstractTransformer { // Modify input code before tokenization public function preprocess(string $code): string { return str_replace("\t", ' ', $code); // Convert tabs to spaces } // Modify the
 element
    public function pre(Element $pre): Element
    {
        $pre->properties->set('data-filename', 'example.php');
        return $pre;
    }

    // Modify each line element
    public function line(Element $span, array $tokens, int $index): Element
    {
        $span->properties->set('data-line', (string)($index + 1));
        return $span;
    }

    // Modify individual token elements
    public function token(Element $span, HighlightedToken $token, int $index, int $line): Element
    {
        if (str_contains($token->token->text, 'TODO')) {
            $span->properties->get('class')->add('todo-highlight');
        }
        return $span;
    }

    // Modify final HTML output
    public function postprocess(string $html): string
    {
        return "\n" . $html;
    }
}

$phiki = new Phiki();
$html = $phiki
    ->codeToHtml('// TODO: fix this', Grammar::Php, Theme::GithubLight)
    ->transformer(new CustomTransformer())
    ->toString();

```

--------------------------------

### Register Custom Theme in Phiki 2.0

Source: https://github.com/phikiphp/phiki/blob/2.x/docs/upgrade-2.0.mdx

Use the `Phiki::theme()` method to register custom themes, following the removal of custom environment support.

```php
$phiki = (new Phiki)
    ->theme('my-custom-theme', '/path/to/theme.json');
```

--------------------------------

### Diff Annotation (Insert/Remove)

Source: https://github.com/phikiphp/phiki/blob/2.x/docs/commonmark.mdx

Employ `[code! insert]` or `[code! remove]` comments to denote line insertions or deletions. Shorthands `--` for insert and `++` for remove are available.

```php
$user = User::find(1); // [code! remove]
```

```php
$user = User::findOrFail(1); // [code! insert]
```

```php
$user = User::find(1); // [code! --]
```

```php
$user = User::findOrFail(1); // [code! ++]
```

--------------------------------

### Clear cache via Artisan

Source: https://github.com/phikiphp/phiki/blob/2.x/docs/laravel.mdx

Manually clear the application cache using the artisan command.

```sh
php artisan cache:clear
```

--------------------------------

### Use Blade component for code highlighting

Source: https://github.com/phikiphp/phiki/blob/2.x/docs/laravel.mdx

Highlight code directly in Blade views using the phiki::code component.

```blade

echo "Hello, world!";

```

```blade

echo "Hello, world!";

```

```blade

echo "Hello, world!";

```

--------------------------------

### Focus Line Annotation

Source: https://github.com/phikiphp/phiki/blob/2.x/docs/commonmark.mdx

Use a trailing comment with `[code! focus]` to highlight a specific line. Shorthands `f` or `**` can also be used.

```php
echo "Hello, world!"; // [code! focus]
```

```php
echo "Hello, world!"; // [code! f]
```

```php
echo "Hello, world!"; // [code! **]
```

--------------------------------

### Register Custom Extension in Phiki 2.0

Source: https://github.com/phikiphp/phiki/blob/2.x/docs/upgrade-2.0.mdx

Use the `Phiki::extend()` method to register custom extensions after custom environment support was removed.

```php
$phiki = (new Phiki)
    ->extend(new MyCustomExtension());
```

--------------------------------

### Laravel Facade Custom Extension Registration

Source: https://context7.com/phikiphp/phiki/llms.txt

Register custom grammars, themes, or extensions within a Laravel service provider using the Phiki facade. This allows for extended functionality and custom styling.

```php
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Register custom grammars
        Phiki::grammar('my-grammar', resource_path('grammars/my-grammar.json'));

        // Register custom themes
        Phiki::theme('my-theme', resource_path('themes/my-theme.json'));

        // Register custom extensions
        Phiki::extend(new MyCustomExtension());

        // Use a specific cache store (defaults to CACHE_STORE)
        Phiki::cache(Cache::store('redis'));
    }
}
```

--------------------------------

### Apply AddClassesTransformer to HTML

Source: https://github.com/phikiphp/phiki/blob/2.x/docs/add-classes-transformer.mdx

Use this transformer to automatically add scope-based CSS classes to HTML elements. Ensure Phiki and AddClassesTransformer are imported.

```php
use Phiki\Phiki;
use Phiki\Transformers\AddClassesTransformer;

$html = (new Phiki)
    ->codeToHtml("transformer(new AddClassesTransformer)
    ->toString();
```

--------------------------------

### Apply Custom CSS Classes with Decorations in PHP

Source: https://context7.com/phikiphp/phiki/llms.txt

Use Decorations like PreDecoration, CodeDecoration, LineDecoration, and GutterDecoration to apply custom CSS classes to specific elements. This is useful for targeted styling and highlighting.

```php
use Phiki\Phiki;
use Phiki\Grammar\Grammar;
use Phiki\Theme\Theme;
use Phiki\Transformers\Decorations\PreDecoration;
use Phiki\Transformers\Decorations\CodeDecoration;
use Phiki\Transformers\Decorations\LineDecoration;
use Phiki\Transformers\Decorations\GutterDecoration;

$phiki = new Phiki();
$code = <<<'PHP'
codeToHtml($code, Grammar::Php, Theme::GithubLight)
    ->withGutter()
    ->decoration(
        PreDecoration::make()->class('code-block'),
        CodeDecoration::make()->class('code-content'),
        LineDecoration::forLine(1)->class('highlight'),  // Highlight line 2 (0-indexed)
        LineDecoration::forLine(2)->class('focus'),      // Focus line 3
        GutterDecoration::make()->class('line-numbers'),
    )
    ->toString();

/*
.code-block { border: 1px solid #ccc; border-radius: 8px; }
.line.highlight { background-color: rgba(255, 255, 0, 0.2); }
.line.focus { background-color: rgba(0, 100, 255, 0.1); }
*/

```

--------------------------------

### Extracting raw tokens with codeToTokens

Source: https://context7.com/phikiphp/phiki/llms.txt

Provides access to raw tokenization data instead of generating HTML, useful for custom processing.

```php
use Phiki\Phiki;
use Phiki\Grammar\Grammar;

$phiki = new Phiki();
$code = 'codeToTokens($code, Grammar::Php);

// Each token contains: text, scopes
foreach ($tokens as $lineIndex => $lineTokens) {
    echo "Line $lineIndex:\n";
    foreach ($lineTokens as $token) {
        echo "  Text: '{$token->text}' | Scopes: " . implode(', ', $token->scopes) . "\n";
    }
}
```