J'ai pu le faire. Je ne suis pas entièrement satisfait de ma solution mais elle est assez décente. Attendre que quelqu'un d'autre apporte une meilleure solution.
Le processus suit. Convertissez le markdown en html et joignez-le au message. Transformez cette pièce jointe en inline
pièce jointe. Mais maintenant, j'ai deux pièces jointes, la première est en démarque et la seconde en html. Remplacez le contenu de démarque par une chaîne vide afin que seul le html soit envoyé.
J'ai ajouté la ligne suivante au ~/.muttrc
fichier.
macro compose B ":set editor=text2mime-markdown.py<enter>E:set editor=email-editor<enter>Da/tmp/html-markdown-alternative.html<enter>^Du"
Voici email-editor
ce qui est emprunté au lien affiché en question.
#!/bin/sh
if grep -q In-Reply-To $1; then
# Jump to first line of message
exec vim -c 'norm }j' $1
else
# Enter insert mode on the To: line
exec vim $1
fi
Et le fichier python principal qui est appelé suit. Ceci est inspiré du script perl du lien en question.
#!/usr/bin/env python
import os
import sys
from formatter import *
version = "0.1"
file = sys.argv[1]
new_file = "/tmp/html-markdown-alternative.html"
with open(file, "r") as f:
text = f.read()
lines = text.split('\n')
header = []
body = []
headerStart = True
for l in lines:
if headerStart:
m = re.search(r'^[\w\-]+\:', l)
if m:
header.append(l)
else:
headerStart = False
body.append(l)
else:
body.append(l)
header = '\n'.join(header)
body = '\n'.join(body)
htmlBody = markdownToHtml(body);
html = []
html.append('<html>')
html.append('<head>')
html.append('<meta name=\"generator\" content=\"text2mime-markdown{}\">'.format(version))
html.append('<style>')
html.append("code { font-family: 'Andale Mono', 'Lucida Console', \
'Bitstream Vera Sans Mono', 'Courier New', monospace; }")
html.append('pre { border-left: 20px solid #ddd; margin-left: 10px; \
padding-left: 5px; }')
html.append('</style>')
html.append('</head>')
html.append('<body>')
html.append('{0}'.format(body))
html.append('</body>')
html.append('</html>')
html = '\n'.join(html)
with open(new_file, "w") as newF:
newF.write(html)
with open(file, 'w') as f:
f.write(header)
Cela dépend d'un autre fichier python appelé formatter.py
qui utilise pandoc
pour formater mon courrier mais s'il pandoc
n'est pas disponible, il peut utiliser le python-markdown2
package. Ce script suit.
import subprocess
import re
import os
import sys
import html2text
import collections
# check if pandoc exists
panDoc = True
try:
subprocess.call(["pandoc", '--version']
, stdout=subprocess.PIPE
, stdin=subprocess.PIPE
)
except OSError:
panDoc = False
if not panDoc:
import text.html2text as html2text
import markdown
def decodeText(text):
return text.decode('utf-8')
def markdownToHtml(content, convertor='pandoc'):
global panDoc
if panDoc:
cmd = ["pandoc", "-f", "markdown", "-t", "html"]
p = subprocess.Popen(cmd
, stdin = subprocess.PIPE
, stdout = subprocess.PIPE
)
p.stdin.write(content)
content = p.communicate()[0]
return decodeText(content)
else:
return markdown.markdown(decodeText(content))
def htmlToMarkdown(content, convertor='pandoc'):
global panDoc
if panDoc and convertor == 'pandoc':
cmd = ["pandoc", "-t", "markdown", "-f", "html"]
p = subprocess.Popen(cmd
, stdin = subprocess.PIPE
, stdout = subprocess.PIPE
)
p.stdin.write(content)
content = p.communicate()[0]
return decodeText(content)
# Use markdown package to convert markdown to html
else:
h = html2text.HTML2Text()
content = h.handle(decodeText(content))
return content
def titleToBlogDir(title):
if title is None:
return ''
if len(title.strip()) == 0:
return ''
blogDir = title.replace(" ","_").replace(':', '-').replace('(', '')
blogDir = blogDir.replace('/', '').replace('\\', '').replace('`', '')
blogDir = blogDir.replace(')', '').replace("'", '').replace('"', '')
return blogDir
def titleToFilePath(title, blogDir):
if len(blogDir.strip()) == 0:
return ''
fileName = os.path.join(blogDir, titleToBlogDir(title))
return fileName
def htmlToHtml(html):
return decodeText(html)
def metadataDict(txt):
mdict = collections.defaultdict(list)
md = getMetadata(txt)
for c in ["title", 'type', "layout", "status", "id", "published", "category", "tag"]:
pat = re.compile(r'{0}\:\s*(?P<name>.+)'.format(c), re.IGNORECASE)
m = pat.findall(txt)
for i in m:
mdict[c].append(i)
return mdict
def getMetadata(txt):
"""
Get metadata out of a txt
"""
if not "---" in txt:
print txt
sys.exit(1)
pat = re.compile(r'\-\-\-+(?P<metadata>.+?)\-\-\-+', re.DOTALL)
m = pat.search(txt)
if m:
return m.group('metadata')
else:
sys.exit(0)
def getContent(txt):
"""
Return only text of the post.
"""
pat = re.compile(r'\-\-\-+(?P<metadata>.+?)\-\-\-+', re.DOTALL)
return re.sub(pat, "", txt)
def readInputFile(fileName):
"""
read file and return its format. html or markdown
"""
assert fileName
if not os.path.exists(fileName):
raise IOError, "File %s does not exists" % fileName
# Check the fmt of file.
fmt = os.path.splitext(fileName)[1].lower()
if fmt in ["htm", "html", "xhtml"]:
fmt = "html"
elif fmt in ["md", "markdown"]:
fmt = "markdown"
else:
fmt = "markdown"
txt = open(fileName, 'r').read()
return (fmt, txt)
def formatContent(txt, fmt):
"""
Format the content as per fmt.
"""
content = getContent(txt)
if fmt == "html":
content = htmlToHtml(content)
elif fmt == "markdown":
content = markdownToHtml(content)
else:
content = markdownToHtml(content)
return content
Ces fichiers sont également disponibles ici https://github.com/dilawar/mutt
sendmail
?