ExGram.Markdown (ex_gram v0.64.0)

Copy Markdown View Source

Converts CommonMark/GFM Markdown into a {plain_text, [MessageEntity]} tuple for the Telegram Bot API.

Uses MDEx (backed by Rust's comrak) for spec-compliant parsing, then walks the AST to produce plain text annotated with ExGram.Model.MessageEntity structs whose offset and length fields are measured in UTF-16 code units (as required by Telegram).

Options

  • :skip_blockquotes - when true, blockquote nodes are rendered as indented plain text instead of a blockquote entity. Useful when the output will itself be wrapped in an expandable blockquote, since Telegram forbids nested blockquotes.

Fallback

If MDEx fails to parse, the raw markdown is returned as plain text with no entities.

Example

iex> ExGram.Markdown.to_entities("**bold** and *italic*")
{"bold and italic",
 [
   %ExGram.Model.MessageEntity{type: "bold", offset: 0, length: 4},
   %ExGram.Model.MessageEntity{type: "italic", offset: 9, length: 6}
 ]}

Summary

Functions

from_entities(arg, format \\ :markdown)

@spec from_entities(ExGram.Dsl.MessageEntityBuilder.t(), :markdown | :markdown_v2) ::
  String.t()

Converts a ExGram.Dsl.MessageEntityBuilder.t/0 back into a markdown string.

Warning

The conversion from markdown <-> entities is not 1 on 1, since entities is a limited subset of markdown.

Formats

  • :markdown - CommonMark output (via MDEx AST)
  • :markdown_v2 - Telegram MarkdownV2 output with proper escaping

Example

iex> alias ExGram.Model.MessageEntity
iex> entities = [%MessageEntity{type: "bold", offset: 0, length: 4}]
iex> ExGram.Markdown.from_entities({"bold text", entities}, :markdown)
"**bold** text"
iex> ExGram.Markdown.from_entities({"bold text", entities}, :markdown_v2)
"*bold* text"

to_entities(markdown, opts \\ [])

@spec to_entities(
  String.t(),
  keyword()
) :: ExGram.Dsl.MessageEntityBuilder.t()

Converts a Markdown string into a ExGram.Dsl.MessageEntityBuilder.t/0 ready to be used.