Skip to main content

toAnsi(md, options?): string

Converts a Markdown string to an ANSI-escaped terminal string suitable for printing in a terminal emulator.

Import​

import { toAnsi } from 'md-to-rich'
// or sub-path:
import { toAnsi } from 'md-to-rich/ansi'

Signature​

function toAnsi(md: string, options?: AnsiOptions): string

Options​

OptionTypeDefaultDescription
columnsnumberprocess.stdout.columns ?? 80Terminal column width for word-wrap and horizontal rules
hyperlinksbooleanfalseEmit OSC 8 hyperlink sequences (clickable links in supported terminals)
themePartial<AnsiTheme>built-inOverride individual ANSI styles — only specified keys are replaced
gfmbooleantrueEnable GitHub Flavored Markdown
remarkPluginsPlugin[][]Additional remark plugins applied before serialization

Examples​

Basic​

import { toAnsi } from 'md-to-rich'

const output = toAnsi('# Hello\n\n**bold** and *italic*', { columns: 80 })
process.stdout.write(output)
toAnsi('[Docs](https://example.com)', { hyperlinks: true })
// → OSC 8 ;; https://example.com \a Docs OSC 8 ;; \a

Supported in iTerm2, Kitty, WezTerm, and most modern terminal emulators.

Custom theme​

import type { AnsiTheme } from 'md-to-rich'

const theme: Partial<AnsiTheme> = {
h1: { open: '\x1b[1m', close: '\x1b[0m' },
listBullet: '→',
}

toAnsi('# Title\n\n- item', { theme })

Default Theme​

The built-in theme uses only inline ANSI constants — no external dependencies like chalk:

KeyEffect
h1Bold + underline + magenta
h2Bold + underline + cyan
h3Bold + cyan (also used for h4–h6)
boldBold
italicItalic
strikethroughStrikethrough
inlineCodeReverse video + yellow
codeBlockDark grey text inside a box-drawing border
blockquoteDark grey │ prefix
linkUnderline + blue
listBullet• character
hrChar─ character

See the ANSI Theme guide for full details and examples.

FAQ​

Can I use toAnsi() without colours?​

toAnsi() always emits escape codes and doesn't read NO_COLOR. To get plain text, strip the codes with Node's stripVTControlCharacters (see Respect NO_COLOR and piped output), or pass a theme whose styles all have empty open and close strings and leave hyperlinks off. Either way you keep the wrapping, bullets, code frames and table borders.

By default a link prints as its label in the link style followed by the URL in parentheses, such as Docs (https://example.com). With hyperlinks: true it becomes a clickable OSC 8 link that shows only the label. Images can't be drawn in a terminal, so toAnsi() prints [image: alt text] in their place, falling back to the URL when the alt text is empty. Links with unsafe URLs such as javascript: show only their label. Footnote references print as [1], with the notes listed at the end (2.1.0+).

Does toAnsi() syntax-highlight code blocks?​

No. toAnsi() draws a fenced code block inside a ┌─ code (ts) box-drawing frame, labelled with the language when there is one, and colours every line with the single codeBlock theme style.