
# API

shikiphp은 두 가지 진입점을 제공합니다. 일반적인 경우를 위한 정적 `Shikiphp` 파사드와 그 외 모든 기능(HAST 출력, 사용자 지정 문법 및 테마, 테마 변형, 번들 검사)을 위한 `Highlighter` 인스턴스입니다.

## `Shikiphp` 파사드

`Shikiphp\Shikiphp`은 지연 생성되고 캐시되는 번들 하이라이터를 감싼 얇은 정적 파사드입니다.

### `Shikiphp::codeToHtml`

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

`$code`을 토큰화하고 완전한 `<pre class="shiki …">` HTML 블록을 렌더링합니다. 옵션 배열에는 항상 `lang`이 포함되며, `theme` 또는 `themes` 맵 중 하나와 렌더링 [옵션](https://shikiphp.inline0.dev/ko/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
```

HTML 대신 `Shikiphp\Render\ThemedToken` 객체의 기본 2D 토큰 그리드(줄마다 내부 목록 하나)를 반환합니다.

```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/ko/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`에는 전체 API가 포함됩니다. 공유 번들 인스턴스는 `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/ko/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/ko/docs/languages) 및 [테마](https://shikiphp.inline0.dev/ko/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;
}
```
