---
title: "code"
description: "Translate the prose comments of code blocks and leave the code alone."
canonical_url: "https://diglot.sh/adapters/code"
---
# code

> Translate the prose comments of code blocks and leave the code alone.

`@diglot/code` finds the prose comments in a code block with a per-language tokenizer, turns each comment line into a `code-comment` segment, and replaces only the comment text when applying a translation. The comark and mdast adapters use it for fenced code blocks, and you can use it on its own.

<package-info directory="packages/code" install="pnpm add @diglot/code @diglot/core" name="@diglot/code">



</package-info>

## Usage

```ts
import { applyCode, extractCode } from '@diglot/code'

const { segments } = extractCode(code, 'ts')
const { code: translated, report } = applyCode(code, 'ts', translations)
```

## Building blocks for adapters

<table>
<thead>
  <tr>
    <th>
      Function
    </th>
    
    <th>
      Description
    </th>
  </tr>
</thead>

<tbody>
  <tr>
    <td>
      <code>
        findComments(code, language)
      </code>
    </td>
    
    <td>
      Returns <code>
        { line, start, end, text }
      </code>
      
       for each prose comment line, where <code>
        [start, end)
      </code>
      
       are offsets of the text in the code
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        commentDraft(comment, language, context)
      </code>
    </td>
    
    <td>
      Converts a comment to a segment draft. Inline code and URLs become placeholders
    </td>
  </tr>
  
  <tr>
    <td>
      <code>
        replaceComments(code, replacements)
      </code>
    </td>
    
    <td>
      Substitutes comment texts. Each replacement must be a single line without comment terminators
    </td>
  </tr>
</tbody>
</table>

## Supported languages

- JavaScript and TypeScript: `js`, `ts`, `jsx`, `tsx`, `mjs`, `cjs`
- Vue and HTML, including `<script>` and `<style>` blocks
- CSS, SCSS and Less
- Shell: `bash`, `sh`, `zsh`
- dotenv and ini
- YAML
- TOML
- JSON5 and JSONC

## What is not extracted

A comment is extracted only when it reads as prose. These are left alone:

- Twoslash directives such as `// ^?`, `// @errors` and `// ---cut---`.
- Shiki notations such as `// [!code ++]`.
- Tool pragmas such as `eslint-disable`, `@ts-expect-error` and `#region`.
- Commented-out code.
- Comments with fewer than two words.

Comment segments are plain segments: one line, with no markup. A translation of a comment can't contain a comment terminator such as `*/` or `-->`, which would end the comment early.


## Sitemap

See the full [sitemap](https://diglot.sh/sitemap.md) for all pages.
