Module: MTProto::Markdown
- Defined in:
- lib/mtproto/markdown.rb
Overview
Telegram-MarkdownV2-style formatting: text markup <-> (plain text, entities).
text, entities = MTProto::Markdown.parse("*bold* and _italic_ and ||spoiler||")
markup = MTProto::Markdown.render(text, entities)
Entity offsets/lengths are in UTF-16 code units (Telegram's unit), so the parser counts astral characters (emoji) as 2. Supported markup:
*bold* _italic_ __underline__ ~strikethrough~ ||spoiler||
`inline code` ```lang\npre block```
[label](http://url) -> text_url
[label](tg://user?id=123) -> mention (text-mention)
 -> custom emoji
>quoted line(s) -> blockquote
\x escapes any markup character x.
Malformed markup (an unclosed entity, a broken link) raises ParseError, matching Telegram's own "can't parse entities" rejection rather than sending garbage.
Known limitations (vs full Telegram MarkdownV2): expandable/collapsed blockquotes
are not produced; adjacent italic/underline runs (the _/__ adjacency, e.g.
___x___) are rejected as ambiguous; link labels are literal text (no nested
formatting inside [...]); auto-detected entities (url/mention/hashtag/email/…)
are left to Telegram's server-side detection and not emitted by parse.
Defined Under Namespace
Classes: ParseError, Parser, Renderer
Constant Summary collapse
- Entity =
MTProto::TL::MessageEntity
Class Method Summary collapse
- .parse(source) ⇒ Object
- .render(text, entities) ⇒ Object
- .utf16_size(char) ⇒ Object
-
.utf8(str) ⇒ Object
Treat input as UTF-8 text and reject invalid bytes with a clear error rather than letting a low-level ArgumentError/Encoding error escape from deep inside.
Class Method Details
.parse(source) ⇒ Object
36 37 38 |
# File 'lib/mtproto/markdown.rb', line 36 def parse(source) Parser.new(utf8(source)).parse end |
.render(text, entities) ⇒ Object
40 41 42 |
# File 'lib/mtproto/markdown.rb', line 40 def render(text, entities) Renderer.new(utf8(text), entities).render end |
.utf16_size(char) ⇒ Object
44 45 46 |
# File 'lib/mtproto/markdown.rb', line 44 def utf16_size(char) char.ord > 0xFFFF ? 2 : 1 end |
.utf8(str) ⇒ Object
Treat input as UTF-8 text and reject invalid bytes with a clear error rather than letting a low-level ArgumentError/Encoding error escape from deep inside.
50 51 52 53 54 55 56 |
# File 'lib/mtproto/markdown.rb', line 50 def utf8(str) s = str.to_s s = s.dup.force_encoding(Encoding::UTF_8) unless s.encoding == Encoding::UTF_8 raise ParseError, 'input is not valid UTF-8' unless s.valid_encoding? s end |