Skip to content

Commit 61b35ef

Browse files
borzovunnamedd
andauthored
Script for convert Markdown formatting to Telegram format (raycast#936)
* Script for convert Markdown formatting to Telegram format, excluding processing inside code blocks or quotes (ver. 1.0) * Update commands/conversions/markdown-to-telegram.py Co-authored-by: Thiago Holanda <[email protected]> * Update commands/conversions/markdown-to-telegram.py Co-authored-by: Thiago Holanda <[email protected]> * Update commands/conversions/markdown-to-telegram.py Co-authored-by: Thiago Holanda <[email protected]> * Update commands/conversions/markdown-to-telegram.py Co-authored-by: Thiago Holanda <[email protected]> * Update commands/conversions/markdown-to-telegram.py Co-authored-by: Thiago Holanda <[email protected]> * Update commands/conversions/markdown-to-telegram.py Co-authored-by: Thiago Holanda <[email protected]> * Add comments to improve code readability • Add comments to explain the purpose of functions and variables • Describe the main stages of the conversion process • Clarify the formatting logic for different Markdown elements • Preserve the existing functionality and logic of the script The added comments aim to enhance the code's readability and maintainability without altering its behavior. This will make it easier for developers to understand and modify the script in the future. --------- Co-authored-by: Thiago Holanda <[email protected]>
1 parent 88fe21f commit 61b35ef

File tree

1 file changed

+100
-0
lines changed

1 file changed

+100
-0
lines changed
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
#!/usr/bin/env python3
2+
3+
# Required parameters:
4+
# @raycast.schemaVersion 1
5+
# @raycast.title Convert Markdown to Telegram Format
6+
# @raycast.mode silent
7+
8+
# Optional parameters:
9+
# @raycast.icon 🔄
10+
# @raycast.packageName Conversions
11+
# @raycast.description Convert Markdown formatting to Telegram format, excluding processing inside code blocks or quotes
12+
13+
# Documentation:
14+
# @raycast.author Maxim Borzov
15+
# @raycast.authorURL https://github.com/borzov
16+
17+
import re
18+
import subprocess
19+
20+
# Set environment variables and encoding
21+
env_vars = {'LANG': 'en_US.UTF-8'}
22+
encoding = 'utf-8'
23+
24+
def paste():
25+
"""Read text from the clipboard."""
26+
return subprocess.check_output('pbpaste', env=env_vars).decode(encoding)
27+
28+
def copy(text):
29+
"""Write text to the clipboard."""
30+
process = subprocess.Popen('pbcopy', env=env_vars, stdin=subprocess.PIPE)
31+
process.communicate(text.encode(encoding))
32+
33+
def convert_markdown(text):
34+
"""Convert Markdown formatting to Telegram format."""
35+
lines = text.split('\n')
36+
converted_lines = []
37+
in_code_block = False
38+
39+
for line in lines:
40+
# Check if the line is a code block delimiter
41+
if line.startswith('```'):
42+
in_code_block = not in_code_block
43+
converted_lines.append(line)
44+
continue
45+
46+
# Skip quotes and only format if not in a code block
47+
if not in_code_block and not line.startswith('>'):
48+
# Format headers with emojis and bold text
49+
if line.startswith('# '):
50+
line = f"⚫️ **{line[2:].strip()}**\n"
51+
elif line.startswith('## '):
52+
line = f"◾️ **{line[3:].strip()}**\n"
53+
elif line.startswith('### '):
54+
line = f"▪️ **{line[4:].strip()}**\n"
55+
elif line.startswith('#### '):
56+
line = f"🔹 **{line[5:].strip()}**\n"
57+
elif line.startswith('##### '):
58+
line = f"📌 **{line[6:].strip()}**\n"
59+
elif line.startswith('###### '):
60+
line = f"🔰 **{line[7:].strip()}**\n"
61+
else:
62+
# Format bold text
63+
line = re.sub(r'(?<!\\)\*{2}(.*?)\*{2}', r'**\1**', line)
64+
line = re.sub(r'(?<!\\)_{2}(.*?)_{2}', r'**\1**', line)
65+
# Format italic text
66+
line = re.sub(r'(?<!\\|\*)\*(?!\*)(.+?)(?<!\*)\*(?![\*_])', r'__\1__', line)
67+
line = re.sub(r'(?<!\\|_)_(?!_)(.+?)(?<!_)_(?![\*_])', r'__\1__', line)
68+
# Format strikethrough text
69+
line = re.sub(r'(?<!\\)~{2}(.*?)~{2}', r'~~\1~~', line)
70+
# Format spoilers
71+
line = re.sub(r'(?<!\\)\|\|(.*?)\|\|', r'||\1||', line)
72+
# Format underline text
73+
line = re.sub(r'(?<!\\)-{2}(.*?)-{2}', r'--\1--', line)
74+
# Format links
75+
line = re.sub(r'(?<!\\)\[(.*?)\]\((.*?)\)', r'[\1](\2)', line)
76+
# Format inline code
77+
line = re.sub(r'(?<!\\)`(.*?)`', r'`\1`', line)
78+
79+
converted_lines.append(line)
80+
81+
# Add empty lines between paragraphs
82+
result = []
83+
for i in range(len(converted_lines)):
84+
result.append(converted_lines[i])
85+
if i < len(converted_lines) - 1:
86+
cur = converted_lines[i].strip()
87+
next = converted_lines[i+1].strip()
88+
if cur and next and not cur.startswith(('*', '-', '```', '|', '>')) and not next.startswith(('*', '-', '```', '|', '>')):
89+
result.append('')
90+
91+
return '\n'.join(result)
92+
93+
if __name__ == "__main__":
94+
try:
95+
markdown_text = paste()
96+
converted_text = convert_markdown(markdown_text)
97+
copy(converted_text)
98+
print("✅ Markdown converted and copied to clipboard")
99+
except Exception as e:
100+
print(f"❌ Error during conversion: {str(e)}")

0 commit comments

Comments
 (0)