def genny_markdown(section): """Read and convert markdown data to html""" md = Markdown() src_dir = "./markdown/" if section == "index": src = src_dir + "index/" file_list = os.listdir(src) output = "" for item in reversed(file_list): markdown = open(src+item, "r") text = markdown.read() markdown.close() output += text + "\n" text = genny_swap(output) html = md.convert(text) elif section == "about": src = src_dir + "about.md" markdown = open(src, "r") text = markdown.read() markdown.close() text = genny_swap(text) html = md.convert(text) else: print "You have to specify wich part to throw through Genny!" return html
class MarkdownFormatter(PostFormatter): """ Post formatter which uses Markdown to format posts. """ QUICK_HELP_TEMPLATE = 'forum/help/markdown_formatting_quick.html' FULL_HELP_TEMPLATE = 'forum/help/markdown_formatting.html' def __init__(self, *args, **kwargs): super(MarkdownFormatter, self).__init__(*args, **kwargs) from markdown2 import Markdown self.md = Markdown(safe_mode='escape') def format_post_body(self, body): """ Formats the given raw post body as HTML using Markdown formatting. """ self.md.reset() return self.md.convert(body).strip() def quote_post(self, post): """ Returns a raw post body which quotes the given Post using Markdown syntax. """ return u'**%s** [wrote](%s "View quoted post"):\n\n%s\n\n' % ( escape(post.user.username), post.get_absolute_url(), quote_post_re.sub('> ', post.body), )
def index(): readme = "" with open('README.md', 'r') as f: readme = f.read() markdowner= Markdown() content = markdowner.convert(readme) return render_template('index.html', content=content)
def submit_edit(request): marked_content = request.POST['entry'] title = request.POST['title'] util.save_entry(title, marked_content) markdowner = Markdown() return render(request, "encyclopedia/entry.html", { "title": title, "content": markdowner.convert(util.get_entry(title)) })
def job_descriptions(jobID): job = Job.query.filter_by(github_issues_number=jobID).first() if not job: return 'Job not found !' markdowner = Markdown() return render_template('job_descriptions.html', title='Job descriptions', job=job, content=markdowner.convert(job.content))
def parse_markdown(value): """ Parses a value into markdown syntax, using the pygments preprocessor and smartypants """ md = Markdown() md.textPreprocessors.insert(0, SmartyPantsPreprocessor()) md.textPreprocessors.insert(1, CodeBlockPreprocessor()) return md.convert(value)
def findentry(request, name): markdowner = Markdown() content = util.get_entry(name) # markdowner.convert(content) return render( request, "encyclopedia/findentry.html", { "entries": markdowner.convert(content), "title": name, "noentry": util.get_entry(name) == None })
def __init__(self): import markdown2 from markdown2 import Markdown #from markdown.extensions.wikilinks import WikiLinkExtension #self._md = markdown2.Markdown(extensions=[WikiLinkExtension(base_url='/', end_url='', html_class='localLink')]) self._md = Markdown() self.wclass = "localLink" self.wpre = "/" self.wpost = "" self.parselock = threading.Lock()
def generate_post(source, destination): fobj_read = open(source) fobj_write = open(destination, 'w') markdown_object = Markdown() html_converted = markdown_object.convert(fobj_read.read()) fobj_write.write(html_converted) fobj_read.close() fobj_write.close()
def random_page(request): entries = util.list_entries() entry = random.choice(entries) page = util.get_entry(entry) markdowner = Markdown() hello = markdowner.convert(page) # world='<form><input type="text"><form>' # return render(request, "encyclopedia/display.html",{'hello': hello+world.encode("utf-8")}) return HttpResponse( markdowner.convert(page) + '<a href="edit/' + entry + '">EDIT</a>')
def random_page(request): title = random.choice(util.list_entries()) title_data = util.get_entry(title) markdowner = Markdown() return render(request, "encyclopedia/title.html", { "title": title, "content": markdowner.convert(title_data) })
def wiki(request, name): if util.get_entry(name): entry = util.get_entry(name) markdowner = Markdown() return render(request, "encyclopedia/wiki.html", { "title": name, "entry": markdowner.convert("%s" % entry) }) else: return render(request, "encyclopedia/error.html")
def pageShow(request, entry): content = util.get_entry(entry) if content is None: raise Http404 (f'<h2>Page not found: "wiki/{entry}"</h2>') # The message is useful only for debug mk = Markdown() return render(request, "encyclopedia/pageshow.html", { "entry": entry, "content": mk.convert(content) })
def title(request, title): title_data = util.get_entry(title) if not title_data: return render(request, "encyclopedia/appology.html", {"error": "Wiki title does not exit"}) markdowner = Markdown() return render(request, "encyclopedia/title.html", { "title": title, "content": markdowner.convert(title_data), })
def entry(request, name): markDown = Markdown() entryName = util.get_entry(name) if entryName is None: return render(request, "encyclopedia/notFound.html", {"entry": name}) else: return render(request, "encyclopedia/entry.html", { "entry": markDown.convert(entryName), "title": name })
def entry(request, entry): markdowner = Markdown() formatted = markdowner.convert(util.get_entry(entry)) if util.get_entry(entry): return render(request, "encyclopedia/entry.html", { "entry": formatted, "title": entry.capitalize() }) else: return render(request, "encyclopedia/no-entry.html")
def randomPage(request): entries = util.list_entries() title = random.choice(entries) page = util.get_entry(f"{title}") markdown = Markdown() contenido = markdown.convert(page) return render(request, "encyclopedia/entryPage.html", { "contenido": contenido, "title": title })
def random_search(request): entries = util.list_entries() random_entry_title = random.choice(entries) random_entry = util.get_entry(random_entry_title) markdowner = Markdown() entry_html = markdowner.convert(random_entry) return render(request, "encyclopedia/entry.html", { "title": random_entry_title, "body": entry_html, })
def entry(request, title): if request.method == "GET": page = util.get_entry(title) if not page: return render(request, "encyclopedia/dne.html") markdowner = Markdown() return render(request, "encyclopedia/entry.html", { "page": markdowner.convert(page), "title": title })
def title(request, name): entry = util.get_entry(name) if entry: markdowner = Markdown() return render(request, "encyclopedia/subject.html", { "subj": markdowner.convert(entry), "heading": name }) else: return render(request, "encyclopedia/error.html", {"heading": name})
def entry(request, title): content = util.get_entry(title) if not content: content = f"#{title}\n Wiki doesn't have article with this exact name." md_converter = Markdown() content = md_converter.convert(content) return render(request, "encyclopedia/entry.html", { "title": title, "content": content })
def get_desc(rr, game, language): desc = get(game, language, "description") if "description-format" not in game: return escape(desc).replace("\n", "<br>") elif game["description-format"] == "markdown": markdowner = Markdown(extras=["strike", "target-blank-links"], inline_image_uri_filter = lambda uri: image.uri(rr, uri, game["id"])) return markdowner.convert(desc) else: raise ValueError("description format invaild")
def display_cont(request,title): md=Markdown() all_entries=util.list_entries() if title.title() in all_entries or title.upper() in all_entries: content=util.get_entry(title) html=md.convert(content) content={"content":html,"search":Search(),"title":title} return render(request,"encyclopedia/display_content.html",content) else: return render(request,"encyclopedia/display_content.html",{"message":"Entry Not Found!!","search":Search()})
def random_entry(request): markdowner = Markdown() list = util.list_entries() rand = random.randint(0, len(list)) title = list[rand - 1] context = { "title": title, "entry": markdowner.convert(util.get_entry(title)) } return render(request, "encyclopedia/random.html", context)
def entry(request, title): try: md = Markdown() entry = md.convert(util.get_entry(title)) except TypeError: raise Http404("The requested page was not found") return render(request, "encyclopedia/entry.html", { "title": title, "entry": entry })
def reqTitle(request, requestedTitle): tobeDisplayed = util.get_entry(requestedTitle) if tobeDisplayed is None: tobeDisplayed = "Error: the requested page could not be found" markdownRead = Markdown() tobeDisplayed = markdownRead.convert(tobeDisplayed) return render(request, "encyclopedia/entry.html", { "entry": TextAreaOnly(initial={"description": tobeDisplayed}) #"entry": tobeDisplayed })
def entry(request, entry): markDownPage = Markdown() entryPage = util.get_entry(entry) if entryPage is None: return render(request, "encyclopedia/entryNotFound.html") else: return render(request, "encyclopedia/entry.html", { "entry": markDownPage.convert(entryPage), "entryTitle": entry })
def detail(request, name): markdowner = Markdown() if util.get_entry(name): entry = util.get_entry(name) context = {"title": name, "entry": markdowner.convert(entry)} else: return render(request, "encyclopedia/not_Exist_error.html", {'title': name}) return render(request, "encyclopedia/detail.html", context)
def bbs_topic(id): options = {"id": id} page = request.args.get('page', 0, type=int) topic = Topic.query.get(id) if not topic: return render_template("topic_not_found.html") count, num_pages, replies = get_page_query(Reply.query.replies_at_topic(topic.id), page, page_size=DEFAULT_PAGE_REPLIES) def pager_url(p, options): return generate_url(".bbs_topic", page=p, **options) if current_user.is_anonymous(): form = None else: form = ReplyForm(request.form) if request.method == "POST": if current_user.is_anonymous(): return redirect(url_for("auth.login", next=request.path) or "/") if form.validate(): reply = Reply(section=topic.section, node=topic.node, user=current_user, topic=topic, content=form.data["content"], created=datetime.now(), floor=topic.reply_count+1) topic.last_reply_by = current_user.username topic.last_reply_at = datetime.now() topic.reply_count += 1 current_user.profile.replies += 1 node = topic.node node.reply_count += 1 section = topic.section section.reply_count += 1 db.session.add_all([reply, topic, current_user.profile, node, section]) db.session.commit() return redirect(pager_url((reply.floor-1)/DEFAULT_PAGE_REPLIES, options)) return render_template("topic.html", topic=topic, options=options, count=count, pager_url=pager_url, num_pages=num_pages, page=page, replies=replies, form=form) topic.hits += 1 db.session.commit() markdowner = Markdown() topic.content = markdowner.convert(topic.content) for r in replies: r.content = markdowner.convert(r.content) return render_template("topic.html", topic=topic, options=options, count=count, pager_url=pager_url, num_pages=num_pages, page=page, replies=replies, form=form )
def entry(request, entry): markdowner = Markdown() entryPage = util.get_entry(entry) if entryPage is None: return render(request, "encyclopedia/nonExistingEntry.html", {"entryTitle": entry}) else: return render(request, "encyclopedia/entry.html", { "entry": markdowner.convert(entryPage), "entryTitle": entry })
def entry(request, entry): markdowner = Markdown() entryTitle = entry get = util.get_entry(entry) if get is None: return render(request, 'encyclopedia/404.html', {'title': entryTitle}) else: return render(request, 'encyclopedia/entry.html', { 'entry': markdowner.convert(get), 'title': entryTitle })
def entry(request, entry): mark = Markdown() page = util.get_entry(entry) if page != None: return render(request, "encyclopedia/entry.html", { "entryTitle": entry, "entry": mark.convert(page) }) else: return render(request, "encyclopedia/noEntry.html", {"entryTitle": entry})
def render_literal(s): """ Presume the string is serialised as markdown and convert it to HTML. :param s: The string to be converted. :type s: str :return: HTML string. :rtype: str """ markdowner = Markdown() return markdowner.convert(s)
def convert(request): if request.body.strip() : markdownConverter = Markdown() print("md: ", request.body) html = markdownConverter.convert(request.body) print("html: ", html) response = HttpResponse(html) response['Access-Control-Allow-Origin'] = '*' return response else: return HttpResponse("Empty request.")
def serialize_data(s): if isinstance(s, rdflib.Literal): markdowner = Markdown() return markdowner.convert(s) elif isinstance(s, rdflib.URIRef): # check if it's a URI or an email if is_email(s): s = f'<a href="mailto:{s}">{s}</a>' elif is_url(s): s = f'<a href="{s}">{s}</a>' return s
def entry_page(request, name): if util.get_entry(name) != None : request.session["title"] = name markdowner = Markdown() html = markdowner.convert(util.get_entry(name)) else: html = None return render(request, "encyclopedia/entry_page.html",{ "html": html, "title": name })
def page(request, entry): markdowner = Markdown() mdpage = util.get_entry(entry) if (mdpage == None): return HttpResponse("No matches found for " + entry + ".<br>" + "<a href=" + "/" + ">Home</a>") body = markdowner.convert(mdpage) return render(request, "encyclopedia/entry.html", { "text": body, "title": entry })
def get(self): parameter = {} markdowner = Markdown(extras=['wiki-tables','fenced-code-blocks']) parameter['username'] = self.current_user article_id = self.get_argument('id') sql = "select * from pycoder_post where id=%s" % article_id article_info = self.db.query(sql)[0] parameter['title'] = article_info['title'] parameter['content'] = markdowner.convert(article_info['html']) times = time.localtime(int(article_info['timestamp'])) parameter['edit_time'] = time.strftime("%Y-%m-%d %H:%M:%S", times) self.render('article.html', parameter)
def extract_content(self, text, full=True): self.is_full = full if not self.is_full: text = text.split('\n\n')[0] # Extract the metadata, then 'demote' the text to an unicode # object. Without the demotion, it won't serialize properly. markdowner = Markdown(extras=['metadata', 'fenced-code-blocks']) attributed_html = markdowner.convert(text) for key, value in attributed_html.metadata.iteritems(): setattr(self, key, value) self.html = unicode(attributed_html)
def markdown(value): try: from markdown2 import Markdown md = Markdown( extras={'footnotes': None, 'code-friendly': None, 'demote-headers': 1}) except ImportError: try: from markdown import Markdown md = Markdown(extensions=['footnotes']) except ImportError: raise jinja2.TemplateError('Markdown is not installed!') return md.convert(value)
def convert_all_md(source, destination): markdown_object = Markdown() i = 1 for fil in listdir(source): if fil.endswith('.md'): fobj_read = open(source+fil) html_converted = markdown_object.convert(fobj_read.read()) fobj_write = open(destination+"markdown_converted_%d.html" % i , 'w') fobj_write.write(html_converted) i+=1 fobj_read.close() fobj_write.close()
def __init__(self, parent=None): super(ControlMainWindow, self).__init__(parent) self.markdown = Markdown() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.txtInput.textChanged.connect(self.text_changed) self.wire_keys()
def send_email(title, content, fromaddress = None, toaddresses = None, contentformat = ContentFormat.Text, ccaddresses = None, bccaddresses = None, charset = None): print(fromaddress, toaddresses) toaddresses = list(map(lambda address:(address.strip()), toaddresses.split(','))) if ccaddresses is not None: ccaddresses = list(map(lambda address:(address.strip()), ccaddresses.split(','))) if bccaddresses is not None: bccaddresses = list(map(lambda address:(address.strip()), bccaddresses.split(','))) destination = { 'ToAddresses' : toaddresses } if ccaddresses is not None: destination['CcAddresses'] = ccaddresses if bccaddresses is not None: destination['BccAddresses'] = bccaddresses message = { 'Subject': { 'Data': title }, 'Body': { } } htmlformat = True ; if contentformat == ContentFormat.Text : htmlformat = False if contentformat == ContentFormat.Markdown : markdowner = Markdown() content = markdowner.convert(content) if htmlformat : message['Body']['Html'] = { 'Data': content } else : message['Body']['Text'] = { 'Data': content } client = boto3.client('ses', region_name='us-west-2') response = client.send_email( Source = fromaddress, Destination = destination, Message = message ) print(response)
def __init__ (self): #from markdown.extensions.wikilinks import WikiLinkExtension #self._md = markdown2.Markdown(extensions=[WikiLinkExtension(base_url='/', end_url='', html_class='localLink')]) self._md = Markdown() self.wclass = "localLink" self.wpre = "/" self.wpost = "" self.parselock = threading.Lock()
def get_html_content (local_file_path): """Converts a local markdown-formatted file to HTML""" if not local_file_path: raise TypeError('local_file_path not provided.') if not path.exists(local_file_path): raise TypeError('local_file_path does not exist!') with open(local_file_path, mode='r', encoding='utf-8') as markdown_file: file_content=markdown_file.read() markdown_file.close() markdowner = Markdown() # first textual line is considered as title title = file_content.strip().split('\n')[0] # the full thing will be converted to HTML file_content = markdowner.convert(file_content) return file_content, title
def convert(self): mdowner = Markdown(extras=[ 'toc', 'header-ids', 'fenced-code-blocks', 'metadata', 'pyshell' ]) md_text = self.__markdown.read() md_inst = mdowner.convert(md_text) title, description, tags = self._regulate_metadata(md_inst.metadata) toc, toc_html = self._generate_toc_data( md_inst._toc, md_inst, bool(mdowner.urls) ) sources_html = self._generate_sources_html(mdowner.urls) _content = self.kindcls(self.__markdown, title, description, tags, toc) _content.table_of_contents = toc_html _content.body = md_inst _content.sources = sources_html return _content
class MarkdownTool(): def __init__ (self): #from markdown.extensions.wikilinks import WikiLinkExtension #self._md = markdown2.Markdown(extensions=[WikiLinkExtension(base_url='/', end_url='', html_class='localLink')]) self._md = Markdown() self.wclass = "localLink" self.wpre = "/" self.wpost = "" self.parselock = threading.Lock() def setPre(self,pre="./"): self.wpre = pre def setPost(self,post=""): self.wpost = post def parse(self,source,preservePara=False,wpre=None): if not source or len(source) == 0: return "" source = source.strip() source = source.replace("\\n","\n") try: self.parselock.acquire() ret = self._md.convert(source) finally: self.parselock.release() if not preservePara: #Remove wrapping <p> </p>\n that Markdown2 adds by default if len(ret) > 7 and ret.startswith("<p>") and ret.endswith("</p>\n"): ret = ret[3:len(ret)-5] ret = ret.replace("<p>","") ret = ret.replace("</p>","<br/><br/>") if ret.endswith("<br/><br/>"): ret = ret[:len(ret)-10] return self.parseWiklinks(ret,wpre=wpre) def parseWiklinks(self,source,wpre=None): sdoutil.setAppVar("MKDOWNWPRE",wpre) return re.sub(WIKILINKPATTERN, self.wikilinkReplace, source) def wikilinkReplace(self,match): wpre = sdoutil.getAppVar("MKDOWNWPRE") if not wpre: wpre = self.wpre t = match.group(1) return '<a class="%s" href="%s%s%s">%s</a>' % (self.wclass,wpre,t,self.wpost,t)
def getMessage(self): msgAsMarkdown = "" subject = "" # for each line in file # set the first line to message # put the rest into a long string f = open(self.templatePath,"r") lines = f.readlines() firstLineOfMessage = 0 for line in lines: firstLineOfMessage = firstLineOfMessage + 1 if line == '\n': break for i in range(firstLineOfMessage,len(lines)): msgAsMarkdown = msgAsMarkdown + lines[i] markdowner = Markdown() message = markdowner.convert(msgAsMarkdown) f.close() return message
class ControlMainWindow(gui.QMainWindow): """ This is the main window class. Called as the first window shown. Creates and runs UI_MainWindow from the autogenerated editor modules """ def __init__(self, parent=None): super(ControlMainWindow, self).__init__(parent) self.markdown = Markdown() self.ui = Ui_MainWindow() self.ui.setupUi(self) self.ui.txtInput.textChanged.connect(self.text_changed) self.wire_keys() def text_changed(self): raw = self.ui.txtInput.toPlainText() md = self.markdown.convert(raw) self.ui.txtOutput.setHtml(md) def keyPressEvent(self, ev): if ev.modifiers() & core.Qt.ControlModifier and ev.key() in self.ctrl_keys: return self.ctrl_keys[ev.key()](ev) if ev.modifiers() & core.Qt.AltModifier and ev.key() in self.mod_keys: return self.mod_keys[ev.key()](ev) if ev.key() in self.keys: return self.keys[ev.key()](ev) def _help(self, ev): print "showing help" def _save(self, ev): print "saving file" def _open(self, ev): print "opening file" def wire_keys(self): self.ctrl_keys = {core.Qt.Key_S: self._save, core.Qt.Key_O: self._open} self.mod_keys = {} self.keys = {core.Qt.Key_F1: self._help}
def markdown(text): """Template filter that renders Markdown as HTML.""" markdowner = Markdown() return markdowner.convert(text)
def do_markdown( msg): """docstring for do_markdown""" from markdown2 import Markdown markdowner = Markdown() msg.html = markdowner.convert(msg.body) return msg
def remade(data): md = Markdown() html = data html = re.sub('<br />','\n', data) html = md.convert(html) return html
def render_markdown(readme): readme_file = open(readme, 'r') md = Markdown() header = md.convert(readme_file.read()) return header
def __init__(self, *args, **kwargs): super(MarkdownFormatter, self).__init__(*args, **kwargs) from markdown2 import Markdown self.md = Markdown(safe_mode='escape')
def to_html(self): formatter = Markdown() return formatter.convert(self.content)
def convert_markdown(md): from markdown2 import Markdown markdowner = Markdown() return markdowner.convert(md)
def markdown(text): from markdown2 import Markdown md = Markdown(extras=['footnotes', 'code-friendly', 'code-color']) return md.convert(text)
def about(request): markdowner = Markdown(html4tags=True) text = markdowner.convert(settings.ABOUT_PAGE_TEXT.value) return render_to_response('about.html', {'text': text }, context_instance=RequestContext(request))
def _table_sub(self, *args, **kwargs): result = Markdown._table_sub(self, *args, **kwargs) return '<div style="overflow-y: scroll">\n{}\n</div>'.format(result)
#!/usr/bin/env python from codecs import open from markdown2 import Markdown markdown_options = { 'code-color':{'classprefix':'cc'}, 'footnotes':'', 'toc':'toc' } template = """ // GENERATED FILE! // Look at package-info.md in project root, and gen-package-info.py /** %s */ package stormpot; """ with open("package-info.md", "r", "utf-8") as f: md = f.read() markdown = Markdown(extras=markdown_options) html = markdown.convert(md) java = template % html.replace(u'{toc}', html.toc_html) with open("src/main/java/stormpot/package-info.java", "w", "utf-8") as f: f.write(java)