Robovojtik/markdown_parser.py

63 lines
2.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
Module: markdown_parser.py
----------------------------
Jednoduchý Markdown parser pro curses.
Rozpozná základní znaèky:
- **tuènì** curses.A_BOLD
- *kurzíva* curses.A_UNDERLINE
- `kód` curses.A_REVERSE (pro zvýraznìní kódu)
Vrací seznam segmentù ve tvaru (text, atribut), které lze postupnì vypsat pomocí curses.
"""
import re
import curses
def parse_markdown(text):
"""
Rozparsuje zadaný text obsahující jednoduché Markdown znaèky a vrátí seznam
dvojic (segment_text, attribute). Nepodporuje vnoøené znaèky.
Podporované znaèky:
**text** tuènì (A_BOLD)
*text* kurzíva (A_UNDERLINE)
`text` kód (A_REVERSE)
Pokud se znaèky nepárují, vrací zbytek textu s atributem 0.
"""
segments = []
pos = 0
pattern = re.compile(r'(\*\*.*?\*\*|\*.*?\*|`.*?`)')
for match in pattern.finditer(text):
start, end = match.span()
# Normalní text pøed znaèkou
if start > pos:
segments.append((text[pos:start], 0))
token = match.group(0)
# Rozpoznání typu tokenu
if token.startswith("**") and token.endswith("**"):
# Bold odstraníme dvojité hvìzdièky
content = token[2:-2]
segments.append((content, curses.A_BOLD))
elif token.startswith("*") and token.endswith("*"):
# Italic odstraníme hvìzdièky
content = token[1:-1]
segments.append((content, curses.A_UNDERLINE))
elif token.startswith("`") and token.endswith("`"):
# Inline kód odstraníme zpìtné apostrofy a použijeme reverzní barvu
content = token[1:-1]
segments.append((content, curses.A_REVERSE))
else:
segments.append((token, 0))
pos = end
# Zbytek textu
if pos < len(text):
segments.append((text[pos:], 0))
return segments
if __name__ == "__main__":
# Jednoduchý test
sample = "Toto je **tuèný text**, toto je *kurzíva* a toto je `kód`."
segments = parse_markdown(sample)
for seg, attr in segments:
print(f"Segment: '{seg}', Attr: {attr}")