- Bouton « Publier » dans l'en-tête (droit creer_sujet) ; /nouveau redirige vers /publier.
- /publier en pleine largeur : titre, station liée facultative, photos, « Me prévenir des
réponses » (enregistré seulement), emplacement « Catégorie » marqué bientôt.
- markdown_sur.py : convertisseur maison (HTML échappé d'abord, liens http(s) seulement,
titres, gras, italique, listes, code, paragraphes, tableaux pipe).
- posts.format ('texte' par défaut, 'md' depuis /publier) ; topics.station_liee et prevenir.
- Brouillons privés (table brouillons) : enregistrement auto ~1 s après la frappe
(apercu.js), bouton sans JS, page « Mes brouillons », suppression à la publication.
- Tests : tests/test_publier.py ; tests existants mis à jour pour /publier.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
113 lignes
4.2 KiB
Python
113 lignes
4.2 KiB
Python
"""Convertisseur Markdown maison, volontairement réduit et sûr (aucune bibliothèque externe).
|
|
|
|
Tout le texte est d'abord échappé (html.escape) : aucune balise de l'auteur ne passe.
|
|
On reconnaît ensuite : titres (#, ##, ###), gras (**x**), italique (*x* ou _x_), listes (- * ou 1.),
|
|
liens [texte](http(s)://…) seulement, code en ligne (`x`), paragraphes et tableaux (syntaxe pipe).
|
|
"""
|
|
import html
|
|
import re
|
|
|
|
CODE = re.compile(r"`([^`\n]+)`")
|
|
LIEN = re.compile(r"\[([^\]\n]+)\]\(([^)\s]+)\)")
|
|
URL_OK = re.compile(r"^https?://[^\s\x00]+$", re.I)
|
|
GRAS = re.compile(r"\*\*(?=\S)(.+?)(?<=\S)\*\*")
|
|
ITALIQUE = re.compile(r"(?<![\w*])\*(?=\S)(.+?)(?<=\S)\*(?![\w*])|(?<![\w])_(?=\S)(.+?)(?<=\S)_(?![\w])")
|
|
TITRE = re.compile(r"^(#{1,3})\s+(.+?)\s*#*\s*$")
|
|
PUCE = re.compile(r"^\s*[-*+]\s+(.*)$")
|
|
NUMERO = re.compile(r"^\s*\d{1,3}[.)]\s+(.*)$")
|
|
SEPARATEUR = re.compile(r"^\s*\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$")
|
|
|
|
|
|
def _en_ligne(t):
|
|
"""Texte déjà échappé -> HTML en ligne (le code est protégé des autres règles)."""
|
|
codes = []
|
|
|
|
def garder(m):
|
|
codes.append("<code>%s</code>" % m.group(1))
|
|
return "\x00%d\x00" % (len(codes) - 1)
|
|
|
|
t = CODE.sub(garder, t)
|
|
|
|
def lien(m):
|
|
texte, url = m.group(1), html.unescape(m.group(2))
|
|
if not URL_OK.match(url):
|
|
return m.group(0) # javascript:, data:, relatif… : laissé en texte
|
|
return "<a href='%s' rel='nofollow noopener noreferrer'>%s</a>" % (html.escape(url, quote=True), texte)
|
|
|
|
t = LIEN.sub(lien, t)
|
|
t = GRAS.sub(r"<strong>\1</strong>", t)
|
|
t = ITALIQUE.sub(lambda m: "<em>%s</em>" % (m.group(1) or m.group(2)), t)
|
|
return re.sub("\x00(\\d+)\x00", lambda m: codes[int(m.group(1))], t)
|
|
|
|
|
|
def _cellules(ligne):
|
|
ligne = ligne.strip()
|
|
if ligne.startswith("|"):
|
|
ligne = ligne[1:]
|
|
if ligne.endswith("|"):
|
|
ligne = ligne[:-1]
|
|
return [c.strip() for c in ligne.split("|")]
|
|
|
|
|
|
def _alignements(sep):
|
|
out = []
|
|
for c in _cellules(sep):
|
|
g, d = c.startswith(":"), c.endswith(":")
|
|
out.append(" class='centre'" if g and d else " class='droite'" if d else "")
|
|
return out
|
|
|
|
|
|
def rendu(texte):
|
|
"""Markdown -> HTML sûr."""
|
|
lignes = html.escape((texte or "").replace("\r\n", "\n").replace("\r", "\n"), quote=True).split("\n")
|
|
out, para, i = [], [], 0
|
|
|
|
def fermer_para():
|
|
if para:
|
|
out.append("<p>%s</p>" % "<br>".join(_en_ligne(x) for x in para))
|
|
para.clear()
|
|
|
|
while i < len(lignes):
|
|
l = lignes[i]
|
|
if not l.strip():
|
|
fermer_para()
|
|
i += 1
|
|
continue
|
|
m = TITRE.match(l)
|
|
if m:
|
|
fermer_para()
|
|
n = len(m.group(1)) + 1 # # -> h2 (le h1 est le titre du sujet)
|
|
out.append("<h%d>%s</h%d>" % (n, _en_ligne(m.group(2)), n))
|
|
i += 1
|
|
continue
|
|
if "|" in l and i + 1 < len(lignes) and SEPARATEUR.match(lignes[i + 1]) and "|" in lignes[i + 1]:
|
|
fermer_para()
|
|
tete, al = _cellules(l), _alignements(lignes[i + 1])
|
|
larg = len(tete)
|
|
al = (al + [""] * larg)[:larg]
|
|
h = ["<div class='tableau'><table><thead><tr>"]
|
|
h += ["<th%s>%s</th>" % (al[k], _en_ligne(c)) for k, c in enumerate(tete)]
|
|
h.append("</tr></thead><tbody>")
|
|
i += 2
|
|
while i < len(lignes) and lignes[i].strip() and "|" in lignes[i]:
|
|
cs = (_cellules(lignes[i]) + [""] * larg)[:larg]
|
|
h.append("<tr>%s</tr>" % "".join("<td%s>%s</td>" % (al[k], _en_ligne(c)) for k, c in enumerate(cs)))
|
|
i += 1
|
|
h.append("</tbody></table></div>")
|
|
out.append("".join(h))
|
|
continue
|
|
for motif, balise in ((PUCE, "ul"), (NUMERO, "ol")):
|
|
if motif.match(l):
|
|
fermer_para()
|
|
items = []
|
|
while i < len(lignes) and motif.match(lignes[i]):
|
|
items.append("<li>%s</li>" % _en_ligne(motif.match(lignes[i]).group(1)))
|
|
i += 1
|
|
out.append("<%s>%s</%s>" % (balise, "".join(items), balise))
|
|
break
|
|
else:
|
|
para.append(l.strip())
|
|
i += 1
|
|
fermer_para()
|
|
return "\n".join(out)
|