diff --git a/telebot/formatting.py b/telebot/formatting.py index a27c746c0..fae8e05af 100644 --- a/telebot/formatting.py +++ b/telebot/formatting.py @@ -277,7 +277,9 @@ def mcode(content: str, language: str="", escape: Optional[bool]=True) -> str: :return: The formatted string. :rtype: :obj:`str` """ - return '```{}\n{}```'.format(language, escape_markdown(content) if escape else content) + if escape: + content = re.sub(r"([`\\])", r"\\\1", content) + return '```{}\n{}```'.format(language, content) def hcode(content: str, escape: Optional[bool]=True) -> str: diff --git a/tests/test_formatting.py b/tests/test_formatting.py index 7091e550f..99a19200f 100644 --- a/tests/test_formatting.py +++ b/tests/test_formatting.py @@ -4,8 +4,10 @@ from html.parser import HTMLParser +import pytest + from telebot import types -from telebot.formatting import apply_html_entities, hpre +from telebot.formatting import apply_html_entities, hpre, mcode class AttributeCollector(HTMLParser): @@ -87,3 +89,20 @@ def test_apply_html_entities_escapes_pre_language(): def test_apply_html_entities_still_escapes_content(): entity = types.MessageEntity(type="bold", offset=0, length=4) assert apply_html_entities("a c", [entity]) == "a<b> c" + + +@pytest.mark.parametrize('content, escaped', [ + (r'C:\code\_file.py', r'C:\\code\\_file.py'), + (r'\*', r'\\*'), + (r'\`', r'\\\`'), + ('`value`', r'\`value\`'), + ('trailing\\', 'trailing\\\\'), + ('plain text\nsecond line', 'plain text\nsecond line'), +]) +def test_mcode_escapes_code_content(content, escaped): + assert mcode(content, language='python') == '```python\n' + escaped + '```' + + +def test_mcode_can_disable_escaping(): + content = r'\* `value`' + assert mcode(content, escape=False) == '```\n' + content + '```'