
# API

shikiphpには2つの入口があります。一般的な用途向けの静的`Shikiphp`ファサードと、それ以外のすべてに対応する`Highlighter`インスタンスです（HAST出力、カスタム文法とテーマ、テーマバリアント、バンドルの詳細調査など）。

## `Shikiphp`ファサード

`Shikiphp\Shikiphp`は、遅延作成されキャッシュされるバンドル済みハイライターを覆う薄い静的ファサードです。

### `Shikiphp::codeToHtml`

```php
public static function codeToHtml(string $code, array $options): string
```

`$code`をトークン化し、完全な`<pre class="shiki …">`HTMLブロックをレンダリングします。options配列には必ず`lang`と、`theme`または`themes`マップのいずれかを指定し、レンダリングの[オプション](https://shikiphp.inline0.dev/ja/docs/options)も指定できます。

```php
use Shikiphp\Shikiphp;

echo Shikiphp::codeToHtml($code, ['lang' => 'php', 'theme' => 'github-dark']);
```

### `Shikiphp::codeToTokens`

```php
/** @return list<list<ThemedToken>> */
public static function codeToTokens(string $code, array $options): array
```

`Shikiphp\Render\ThemedToken`オブジェクトで構成される、行ごとに内側のリストが分かれた2Dトークングリッドを返します。HTMLは返しません。

```php
use Shikiphp\Shikiphp;

$lines = Shikiphp::codeToTokens($code, ['lang' => 'js', 'theme' => 'nord']);

foreach ($lines as $line) {
    foreach ($line as $token) {
        // $token->content, $token->color, $token->fontStyle,
        // $token->bgColor, $token->htmlStyle, $token->offset
    }
}
```

### `Shikiphp::codeToTokensBase`

```php
/** @return list<list<ThemedToken>> */
public static function codeToTokensBase(string $code, array $options): array
```

Shikiの`codeToTokensBase`という名前に合わせた、`codeToTokens`の別名です。

### `Shikiphp::codeToTokensResult`

```php
public static function codeToTokensResult(string $code, array $options): TokensResult
```

Shikiのトップレベル`codeToTokens`に対応する詳細な結果を返します。トークングリッドに加え、解決済みの色、テーマ名、デュアルテーマのルートスタイル、最終的な文法状態を含みます。以下の[`TokensResult`](#tokensresult)を参照してください。

```php
use Shikiphp\Shikiphp;

$result = Shikiphp::codeToTokensResult($code, [
    'lang'  => 'php',
    'theme' => 'github-dark',
]);

$result->tokens;       // list<list<ThemedToken>>
$result->fg;           // "#e1e4e8"
$result->bg;           // "#24292e"
$result->themeName;    // "github-dark"
$result->grammarState; // GrammarState
```

### `Shikiphp::getLastGrammarState`

```php
public static function getLastGrammarState(string $code, array $options): GrammarState
```

`$code`をトークン化し、末尾に到達した文法状態（Shikiの`getLastGrammarState`）を返します。同じ状態から後続の断片のトークン化を再開するには、[`grammarState`](https://shikiphp.inline0.dev/ja/docs/options)オプションに渡します。インクリメンタルなハイライトに便利です。`lang`が`'ansi'`の場合は例外をスローします（ANSIには文法状態がありません）。

```php
use Shikiphp\Shikiphp;

$state = Shikiphp::getLastGrammarState("/* unterminated comment", [
    'lang'  => 'js',
    'theme' => 'nord',
]);

$html = Shikiphp::codeToHtml("still inside the comment */", [
    'lang'         => 'js',
    'theme'        => 'nord',
    'grammarState' => $state,
]);
```

### `Shikiphp::highlighter`

```php
public static function highlighter(): Highlighter
```

共有のバンドル済み`Highlighter`を返し、初回利用時には作成します。下記のインスタンスメソッドを使う際に利用してください。

### `Shikiphp::use`と`Shikiphp::reset`

```php
public static function use(Highlighter $highlighter): void
public static function reset(): void
```

`use`はカスタム`Highlighter`に切り替え、ファサードからそのオブジェクトに処理を委譲します（カスタム文法やテーマを読み込ませたものなど）。`reset`はキャッシュ済みインスタンスをクリアし、次の呼び出しでデフォルトのバンドル済みハイライターを再構築します。

## `Highlighter`

`Shikiphp\Highlighter`はすべての機能を備えています。共有のバンドル済みインスタンスは`Shikiphp::highlighter()`で取得するか、明示的に作成します。

```php
use Shikiphp\Highlighter;

$highlighter = Highlighter::createBundled();
```

ファサードと同じシグネチャで`codeToHtml`、`codeToTokens`、`codeToTokensBase`、`codeToTokensResult`、`getLastGrammarState`を実装し、さらに以下の機能を備えます。

### `Highlighter::codeToHast`

```php
public function codeToHast(string $code, array $options): \Shikiphp\Hast\Element
```

Shikiが構築する`pre.shiki > code > (span.line > span)*`HASTツリーを作成します。自身で走査、変更、シリアライズできます。`codeToHtml`が内部でシリアライズするのもこのツリーです。

```php
use Shikiphp\Shikiphp;

$hast = Shikiphp::highlighter()->codeToHast($code, [
    'lang'  => 'rust',
    'theme' => 'nord',
]);
```

### `Highlighter::codeToTokensWithThemes`

```php
/** @return list<list<ThemedTokenWithVariants>> */
public function codeToTokensWithThemes(string $code, array $options): array
```

テーマごとに一度だけトークン化し、テーマキーを使って結果をトークンごとの`variants`に統合します。Shikiの`codeToTokensWithThemes`に対応しています。`themes`マップが必要です。

```php
use Shikiphp\Shikiphp;

$lines = Shikiphp::highlighter()->codeToTokensWithThemes($code, [
    'lang'   => 'ts',
    'themes' => ['light' => 'github-light', 'dark' => 'github-dark'],
]);

$lines[0][0]->content;            // token text
$lines[0][0]->variants['light'];  // ThemedTokenStyle for the light theme
$lines[0][0]->variants['dark'];   // ThemedTokenStyle for the dark theme
```

### `Highlighter::loadGrammar`と`Highlighter::loadTheme`

```php
public function loadGrammar(
    array $rawTmLanguage,
    ?string $langId = null,
    array $aliases = [],
    array $embedded = [],
): void

public function loadTheme(array $rawTheme): void
```

デコード済みのJSONからカスタムTextMate文法またはVS Codeテーマを登録します。[カスタム言語とテーマ](https://shikiphp.inline0.dev/ja/docs/custom-languages-themes)を参照してください。

### バンドルの詳細調査

```php
/** @return list<string> */ public function loadedLanguages(): array
/** @return list<string> */ public function loadedThemes(): array
/** @return list<string> */ public function bundledLanguages(): array
/** @return list<string> */ public function bundledThemes(): array
```

`loadedLanguages`/`loadedThemes`は現在利用可能なすべてのID（バンドル済みと登録済みのカスタム項目）を報告します。`bundledLanguages`/`bundledThemes`は同梱されているIDのみを報告します。[言語](https://shikiphp.inline0.dev/ja/docs/languages)と[テーマ](https://shikiphp.inline0.dev/ja/docs/themes)を参照してください。

## 値オブジェクト

### `ThemedToken`

`Shikiphp\Render\ThemedToken`は、スタイルが適用されたテキストのひとまとまりです。

```php
final class ThemedToken
{
    public readonly string $content;
    public readonly ?string $color;
    public readonly int $fontStyle;      // FontStyle bitmask
    public readonly ?string $bgColor;
    public readonly ?string $htmlStyle;  // pre-built inline style (dual themes / ANSI)
    public readonly int $offset;         // UTF-16 code-unit offset into the source
}
```

`fontStyle`は`Shikiphp\Theme\FontStyle`から作られたビットマスクです（`NONE`、`ITALIC`、`BOLD`、`UNDERLINE`、`STRIKETHROUGH`）。

### `TokensResult`

`Shikiphp\TokensResult`は`codeToTokensResult`の戻り値です。

```php
final class TokensResult
{
    public readonly array $tokens;             // list<list<ThemedToken>>
    public readonly ?string $fg;               // resolved foreground
    public readonly ?string $bg;               // resolved background
    public readonly ?string $themeName;        // single id, or "shiki-themes …"
    public readonly string|false|null $rootStyle; // dual-theme root style (or null)
    public readonly ?GrammarState $grammarState;
}
```

### `GrammarState`

`Shikiphp\GrammarState`はトークナイザーのルールスタックをテーマ名で管理し、中間地点からハイライトを再開できるようにします。

```php
final class GrammarState
{
    public readonly string $lang;

    public function theme(): string;          // first theme name
    public function themes(): array;          // list<string>
    public function getScopes(?string $theme = null): array; // scopes in effect, innermost first
    public function withTheme(string $theme): self;
}
```
