示例#1
0
def title(request, title):
    query = request.GET.get('q')
    if query:
        title, content, result = search(request, query)['query'], search(
            request, query)['content'], search(request, query)['result']
        markdowner = Markdown()
        body = markdowner.convert(content)
        content = body
        return render(request, "encyclopedia/title.html", {
            "title": title,
            "content": content,
            "result": result
        })
    else:
        content = util.get_entry(title)
        if util.get_entry(title) == None:
            return render(request, "encyclopedia/error.html")
        else:
            markdowner = Markdown()
            body = markdowner.convert(content)
            content = body
            request.session['page'] = title
            page = request.session['page']
            return render(request, "encyclopedia/title.html", {
                "title": title,
                "content": content
            })
示例#2
0
文件: genny.py 项目: yelo/genny
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
示例#3
0
def new_note(request):
    if request.method == 'POST' and 'b2' in request.POST :
        form = NewNote(request.POST)
        if form.is_valid():
            new = Note()
            new.owner = request.session['username']
            new.head = form.cleaned_data["heading"]
            new.content = form.cleaned_data["content"]
            con = Markdown()
            new.md = con.convert(new.content)
            new.save()
            return HttpResponseRedirect("./")
    if request.method == 'POST' and 'b1' in request.POST :
        form = NewNote(request.POST)
        if form.is_valid():
            con=Markdown()
            request.session['temp'] = con.convert(form.cleaned_data['content'])

            return HttpResponseRedirect('preview')
    data = [i for i in Note.objects.all() if i.owner == request.session['username']]

    context = dict()
    context['data'] = data
    context['form'] = NewNote()
    context['username'] = request.session['username']
    temp = loader.get_template('notes/newnote.html')
    return HttpResponse(temp.render(context, request))
示例#4
0
def savecounty(request, countyname):
    markdowner = Markdown()
    if request.user.is_anonymous:
        return render(request, "county/login.html",
                      {"message": "Please log in before saving any counties."})
    else:
        user = request.user
        content = util.get_entry(countyname)
        CountyListentry = CountyListEntry.objects.create(user=user,
                                                         countyname=countyname,
                                                         content=content)
        CountyListentry.save()
        SavedAlready = bool('Saved')
        return render(
            request, "county/countyinformation.html", {
                "county": markdowner.convert(content),
                'countyname': countyname,
                "message": "County Saved!",
                "SavedAlready": SavedAlready
            })
    return render(
        request, "county/countyinformation.html", {
            "county": markdowner.convert(content),
            'countyname': countyname,
            "SavedAlready": SavedAlready
        })
示例#5
0
文件: views.py 项目: Elias-Cz/wiki
def entry(request, name):
    markdowner = Markdown()
    edit = name
    title = name
    name = util.get_entry(name)
    try:
        name = markdowner.convert(name)
    except:
        return render(request, "encyclopedia/index.html",
                      {"msg": 'Error: The requested page does not exist'})
    if request.method == "POST" and request.POST.get('ser') == 'ser':
        name = request.POST.get('q')
        title = name
        markdowner = Markdown()
        name = util.get_entry(title)
        stuff = util.list_entries()
        try:
            name = markdowner.convert(name)
            return redirect('/wiki/' + title)
        except:
            for text in stuff:
                if title in text:
                    print("Partial match")
                    print(text)
                    return render(request, "encyclopedia/results.html",
                                  {"text": text})

    elif request.method == "POST" and request.POST.get('edit') == 'edit':
        return redirect('/wiki/' + edit + '/edit/')

    return render(request, "encyclopedia/entry.html", {
        "name": name,
        "title": title
    })
示例#6
0
def query(request):
    if request.method == "GET":
        form = NewSearchForm(request.GET)
        if form.is_valid():
            markdown = Markdown()
            query = form.cleaned_data["q"]
            entry = util.get_entry( query )
            list_of_entries = util.list_entries()
            if entry:
                return render(request, "encyclopedia/entry.html", {
                    "query": query,
                    "entry": markdown.convert(f"{entry}"),
                    "search_form": NewSearchForm()
                })
            else:
                search_results = []
                for entry in list_of_entries:
                    if query.lower() in entry.lower():
                        search_results.append(entry)
                return render(request, "encyclopedia/query.html", {
                    "query": query,
                    "entry": markdown.convert(f"{entry}"),
                    "search_form": NewSearchForm(),
                    "search_results": search_results
                })
示例#7
0
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>')
示例#8
0
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
                            )
示例#9
0
def entry(request, title):
    content = util.get_entry(title)
    entrylist = util.list_entries()
    EmptyForm = NewSearchForm()
    randomEntry = random.choice(entrylist)
    markdowner = Markdown()

    if content is not None:
        content = markdowner.convert(content)
        return render(
            request, "encyclopedia/entry.html", {
                "entryTitle": title,
                "entryContent": content,
                "form": EmptyForm,
                "randomEntry": randomEntry
            })
    else:
        return render(
            request, "encyclopedia/error.html", {
                "title": title,
                "form": EmptyForm,
                "errorMessage":
                f" Your search: <b><u>{ title }</b></u>, did not yield any result. Please try another search input.",
                "randomEntry": randomEntry
            })
示例#10
0
def random_entry(request):
    li = util.list_entries()
    random_v = random.choice(li)
    markdown = Markdown()
    content = util.get_entry(random_v)
    html = markdown.convert(content)
    return HttpResponse(html)
示例#11
0
def main():
    chapter_folders = [
        d for d in PROJECT_ROOT_DIR.iterdir()
        if d.is_dir() and d.name.lower().startswith('chapter')
    ]
    chapter_folders.sort()
    csstyle = '<link rel="stylesheet" type="text/css" href="genpdf/assets/css/pdf.css">'
    pretag = '\n<p style="page-break-before: always" >\n'
    endtag = '\n</p>\n'
    markdowner = Markdown(extras=['fenced-code-blocks'])
    cover = get_cover_image()
    all_html = [cover] if cover else []
    all_html.append(csstyle)
    for fold in chapter_folders:
        md = next(fold.glob('*.md'))
        with open(md, 'r', encoding='utf-8') as f:
            content = f.read()
            html = markdowner.convert(content)
            html = replace_images(html)
            all_html.append(pretag + html + endtag)

    all_html = '<script></script>'.join(all_html)
    HTML(string=all_html).write_pdf(OUTPUT_FILENAME,
                                    stylesheets=[CSS_FILENAME])
    print("Successfully cooked the book!")
示例#12
0
class MarkdownTool():
        
    WCLASS = "localLink"
    WPRE = "/"
    WPOST = ""

    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.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):
        return re.sub(WIKILINKPATTERN, self.wikilinkReplace, source)
        
    def wikilinkReplace(self,match):
        wpre = self.wpre
        t = match.group(1)
        return '<a class="%s" href="%s%s%s">%s</a>' % (MarkdownTool.WCLASS,MarkdownTool.WPRE,t,MarkdownTool.WPOST,t)
        
    @staticmethod
    def setWikilinkCssClass(c):
        MarkdownTool.WCLASS = "localLink"
        
    @staticmethod
    def setWikilinkPrePath(p):
        MarkdownTool.WPRE = "/"
        
    @staticmethod
    def setWikilinkCPostPath(p):
        MarkdownTool.WPOST = ""
示例#13
0
    def send(self):
        sg = sendgrid.SendGridAPIClient(api_key=self.context.sendgrid_api_key)
        markdowner = Markdown(extras=["tables"])

        from_email = sendgrid.Email(self.context.from_email)
        body = []
        for a in self.analyses:
            stale_days = (datetime.datetime.now(tz=a.last_change.tzinfo) - a.last_change).days if a.last_change else "Never updated"
            body.append(line_item_template.format(file_path=a.doc_name, file_link=a.file_link,
                                                  changed_by=a.changed_by_email, stale_days=stale_days))

        plain_text = body_template.format(item_list="\n".join(body),
                                          github_repo=self.context.github_repo,
                                          github_repo_root=self.context.github_repo_path,
                                          max_stale_days=self.context.doc_is_stale_after_days)
        html_text = markdowner.convert(plain_text)

        content_text = sendgrid.Content("text/plain", plain_text)
        content_html = sendgrid.Content("text/html", html_text + "\n" + css)

        recipients = list(map(lambda x: sendgrid.To(x), self.recipients))
        mail = sendgrid.Mail(from_email, recipients, self.subject(), plain_text_content=content_text,
                             html_content=content_html)
        response = sg.client.mail.send.post(request_body=mail.get())

        if 300 > response.status_code >= 200:
            success(f"Successfully sent email to {', '.join(self.recipients)} regarding {len(self.analyses)} files", 2)
        else:
            error(
                f"Failed to send email to {', '.join(self.recipients)} regarding {len(self.analyses)} files: "
                f"{response.status_code} - {response.body}", 2)
示例#14
0
class RendererMiscPages(Renderer):
    def __init__(self, *args, **kwargs):
        self.basectx = {
            "rr": "..",
        }

        super().__init__(*args, **kwargs, nonl10n=True)

        self.markdowner = Markdown(extras=["tables"])

    def render(self):
        env = self.env

        os.mkdir(self.getpath("misc"))

        context = self.new_context()
        context["noindex"] = True

        for dirpath, dirnames, filenames in \
                os.walk(os.path.join(self.fctx.args.data_dir_prefix, "misc-pages")):
            for ofn in filenames:
                fn = os.path.splitext(ofn)[0]

                print(f"  => {dirpath} {fn}")

                with open(os.path.join(dirpath, ofn)) as of:
                    with open(self.getpath("misc", fn + ".html"), "w") as tf:
                        context["content"] = self.markdowner.convert(of.read())
                        tf.write(
                            self.env.get_template("simple_md.html").render(
                                context))
示例#15
0
def wiki_add(request):
    if request.method == 'POST':
        form = NewEntryForm(request.POST)
        if form.is_valid():
            entries = util.list_entries()
            title = form.cleaned_data['title']
            if title not in entries:
                # handle save
                content = form.cleaned_data['content']
                markdowner = Markdown()
                content_html = markdowner.convert(content)
                util.save_entry(title,content)
                return render(request, "encyclopedia/content.html", {
                    "page": title,
                    "content": content_html
                })
            else:
                # print error
                error = "The {} entry has already existed!"
                return render(request,"encyclopedia/add.html",{
                    "form": form,
                    "error": error.format(title)
                })
    return render(request,"encyclopedia/add.html", {
        "form": NewEntryForm()
    })
示例#16
0
def entry(request, title=None):

    if title == 'random_entry':
        title = randomEntries()

    if title == 'search':
        print(f'SEARCH SECTION: {request.META["QUERY_STRING"] }')
        matching_idx, match_exact = search(request.META["QUERY_STRING"])
        list_entries = util.list_entries()
        if not match_exact:
            return render(
                request, "encyclopedia/search.html", {
                    "searches": list(
                        map(lambda x: list_entries[x], matching_idx)),
                    "title": title,
                })
        else:
            title = list_entries[matching_idx]
    elif title not in util.list_entries():
        print('NOT IN SEARCH')
        return render(request, "encyclopedia/error.html", {
            "title": title,
        })
    print(f'OUTSIDE OF SEARCH {title}')
    markdowner = Markdown()
    page = markdowner.convert(util.get_entry(title))
    # html = markdown.markdown(util.get_entry(title), output_format = "html5")
    # with open("encyclopedia/templates/encyclopedia/css_1.html", "w", encoding="utf-8", errors="xmlcharrefreplace") as output_file:
    #     output_file.write(html)
    # with open("encyclopedia/templates/encyclopedia/css_1.html", "r", encoding="utf-8") as input_file:
    #     text = input_file.read()
    return render(request, "encyclopedia/entry.html", {
        "page": page,
        "title": title,
    })
示例#17
0
def faq(request):
    help_file = open("help/faq.md", "r")
    faq = help_file.read()
    markdowner = Markdown()

    return render(request, "magicjourney/faq.html",
                  {"faq": markdowner.convert(faq)})
示例#18
0
def search(request):
    if request.method == "POST":
        ibcm = request.POST
        query = ibcm['query']
        #make everything lowercase for comparisons
        entries = util.list_entries()
        #find all matches
        matches = []
        for entry in entries:
            if not ((entry.lower()).find(query.lower()) == -1):
                matches.append(entry)
        #render matches
        if (len(matches) == 0):
            return HttpResponse("No matches found for " + query + ".<br>" +
                                "<a href=" + "/" + ">Home</a>")
        elif (matches[0].lower() == query.lower()):
            markdowner = Markdown()
            mdpage = util.get_entry(matches[0])
            body = markdowner.convert(mdpage)
            return redirect("/wiki/" + matches[0])
        else:
            return render(request, "encyclopedia/index.html", {
                "title": "Results for '" + query + "'",
                "entries": matches
            })
示例#19
0
def search(request):
    '''
    Search
    '''
    x.printx('*** search')
    title = request.GET.get('q', '')

    # Try and catch
    try:
        entry = util.get_entry(title=title)
    except FileNotFoundError:
        x.printx(ERROR)
        titles = []
        titles = util.is_subtring(query=title, x_list=util.list_entries())
        if titles:
            return render(request, "encyclopedia/warning.html", {
                "entries": titles,
                "message": 'It might be here.'
            })
        else:
            return render(request, "encyclopedia/error.html", {
                "message": PAGE_NOT_FOUND,
            })
    else:
        x.printx(SUCCESS)
        markdowner = Markdown()
        html = markdowner.convert(entry)
        return render(request, "encyclopedia/wiki.html", {
            "html": html,
            "page": title,
        })
示例#20
0
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),
        )
示例#21
0
def random(request):
	if request.method=='GET':
		entry=choice(util.list_entries())
		md=Markdown()	
		content=util.get_entry(entry)
		html=md.convert(content)
		return HttpResponseRedirect(reverse("display_cont",args=(entry,)))
示例#22
0
def entry(request, title):
    entry = util.get_entry(title)
    if not entry:
        return HttpResponse('404 Error, Page Not Found!')
    markdowner = Markdown()
    text = markdowner.convert(entry)
    return render(request, "encyclopedia/entry.html", {"title": title, "text": text})
示例#23
0
def convert_markdown_to_html(text):
    if not text or len(text) == 0:
        return ""

    markdown = Markdown()

    html = re.sub(
        r"youtube:([-_a-zA-Z0-9]+)",
        r"<iframe width='800' height='550' src='https://www.youtube.com/embed/\1?controls=1'></iframe>\n",
        text)
    html = re.sub(
        r"panopto:([a-zA-Z0-9\.]+.panopto.com)\/([-_a-z0-9]+)",
        r"<p style='text-align: left;'>\n<iframe id='panopto_iframe' style='border: 1px solid #464646;' title='embedded content' src='https://\1/Panopto/Pages/Embed.aspx?id=\2&amp;autoplay=false&amp;offerviewer=true&amp;showtitle=false&amp;showbrand=false&amp;captions=false&amp;interactivity=none' width='100%' height='450' allowfullscreen='allowfullscreen' allow='autoplay'></iframe>\n</p>\n",
        html)
    html = re.sub(r'```(.+?)```', r"<code>\1</code>",
                  html)  # Formats single line code chunks
    html = re.sub(r'```([\s\S]*?)```', r"<pre><code>\1</code></pre>",
                  html)  # Formats multiline code blocks
    html = re.sub(r'<pre><code>\n', r"<pre><code>",
                  html)  # Removes extra newline, if present
    html = markdown.convert(html)
    html = re.sub(r"<a href=\"([^\"]+)\">",
                  r"<a href='\1' target='_blank' rel='noopener noreferrer'>",
                  html)

    return html
示例#24
0
def convert(entry):
    try:
        markdowner = Markdown()
        entry = markdowner.convert(entry)
        return entry
    except FileNotFoundError:
        return None
示例#25
0
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)
示例#26
0
def add(request):
    if request.method == "POST":
        form = NewPageForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            content = form.cleaned_data['textarea']
            exist = util.get_entry(title)
            if exist == None:
                util.save_entry(title, content)
                print(f"anadido, lo guardo {title}, {content}")
                markdowner = Markdown()
                body = markdowner.convert(content)
                content = body
                return render(request, "encyclopedia/title.html", {
                    "title": title,
                    "content": content
                })
            else:
                print("Existe ya")
                return render(request, "encyclopedia/error.html")

        else:
            form = NewPageForm()
            return render(request, "encyclopedia/add.html", {"form": form})

    return render(request, "encyclopedia/add.html", {"form": NewPageForm()})
示例#27
0
 def onInputChange(self, event):
     self.inputeditor.edit_modified(0)
     md2html = Markdown()
     # self.outputbox.set_html(md2html.convert(self.inputeditor.get("1.0" , END)))
     markdownText = self.inputeditor.get("1.0", END)
     html = md2html.convert(markdownText)
     self.outputbox.set_html(html)
示例#28
0
    def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
        if self.review and not self.pk:
            markdown = Markdown()
            # Replace redundant characters from pattern @[text](href:link) to correspond markdown2 format [text](link)
            self.review = markdown.convert(conditional_escape(self.review.replace('@[', '[').replace('(href:', '(')))

        super().save(force_insert, force_update, using, update_fields)
示例#29
0
def convert_to_html(text_with_markdown):
    # Convert markdown to html, then parse text using BeautifulSoup
    # Use code-friendly extra syntax to avoid problem with strings such as factory_girl_rails changed into factory<em>girl</em>rails
    # and subsequently factorygirlrails after HTML tag removal
    markdowner = Markdown(extras=["code-friendly"])
    converted_md = markdowner.convert(text_with_markdown)
    return converted_md
示例#30
0
    def realize(self, mfac):
        if self.fmt == "plain":
            self.html = escape(self.text).replace("\n", "<br>")
        elif self.fmt == "markdown":
            # FIXME: hardcode `../..` is not good
            #        we should embed a HTMLImage object into markdown
            # FIXME: should not use the src property, webp condation will be dropped.
            markdowner = Markdown(
                extras={
                    "strike": None,
                    "target-blank-links": None,
                    "x-FGI-min-header-level": 2
                },
                inline_image_uri_filter=lambda uri: mfac.uri_to_html_image(
                    uri, self.game.id).with_rr("../..").src)
            self.html = markdowner.convert(self.text)
            self.text = BeautifulSoup(self.html,
                                      features="html.parser").get_text()
        else:
            raise ValueError(f"description format invaild: {fmt}")

        if not self.brief:
            # FIXME: split by words, not characters.
            self.brief = self.text[:480] + (self.text[480:] and "...")
            self.brief = self.brief.replace("\n", " ")

        self.brief = self.brief.rstrip(" \n")

        self.brief_sl = self.brief.replace("\n", " ")
        self.brief_html = escape(self.brief).replace("\n", "<br />")
示例#31
0
 def formated_content(self):
     md = Markdown()
     try:
         return md.convert(self.content)
     except Exception:
         pass
     return self.content
示例#32
0
def entry(request, title):

    entry = util.get_entry(title)

    markdowner = Markdown()

    entry = markdowner.convert(entry)

    # ryan = Person('ryan', 20)

    # ryan.get_info()

    # Person = {
    #     name : string,
    #     age : integer,

    #     def get_info:
    #         print('My name is ', name, ' and i am ', age, ' years old.')
    # }

    if entry:
        context = {"title": title, "entry": entry}
        return render(request, "encyclopedia/entry.html", context)
    else:
        return render(request, "encyclopedia/error.html")
示例#33
0
def wiki(request, title):
    # util.py :)
    # Get a list of all articles
    _, filenames = default_storage.listdir("entries")
    titleList = list(
        sorted(
            re.sub(r"\.md$", "", filename) for filename in filenames
            if filename.endswith(".md")))
    # Variable for title
    textTitle = None
    # Go through the entire list and compare the title
    for t in titleList:
        if t.upper() == title.upper():
            textTitle = t
    # Get text from file
    pageMd = util.get_entry(title)
    # If the file is not found, then we report an error
    if pageMd is None:
        return render(request, "encyclopedia/error.html", {
            "msg": "Page not found",
            "form": SearchForm()
        })
    # https://github.com/trentm/python-markdown2#quick-usage
    md = Markdown()
    pageHtml = md.convert(pageMd)
    # Go to article page
    return render(request, "encyclopedia/page.html", {
        "title": textTitle,
        "text": pageHtml,
        "form": SearchForm()
    })
示例#34
0
def search(request):
    query = request.GET['q']
    possible_entry = util.get_entry(query)

    if possible_entry:
        markdowner = Markdown()
        entry_html = markdowner.convert(possible_entry)
        return render(request, "encyclopedia/entry.html", {
            "title": query,
            "body": entry_html,
        })

    else:
        stored_entries = util.list_entries()
        suggested_entries = []

        print(stored_entries)
        for entry in stored_entries:
            if query.lower() in entry.lower():
                suggested_entries.append(entry)
        print(suggested_entries)
        return render(request, "encyclopedia/index.html", {
            "entries": suggested_entries,
            "query": query,
        })
示例#35
0
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 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()
示例#37
0
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.")
示例#38
0
	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)
示例#39
0
 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)
示例#40
0
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()
示例#42
0
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)
示例#43
0
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)
示例#44
0
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
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}
示例#46
0
	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
    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
示例#48
0
def convert_markdown(_dict):
    _md = Markdown()
    ans = {}
    for key, item in _dict.items():
        ans[key] = _md.convert(item)
    return ans
示例#49
0
文件: models.py 项目: wjdp/nt-tickets
 def long_markdown(self):
     md = Markdown()
     return md.convert(self.long_description)
示例#50
0
def do_markdown( msg):
    """docstring for do_markdown"""
    from markdown2 import Markdown
    markdowner = Markdown()
    msg.html = markdowner.convert(msg.body)
    return msg
示例#51
0
def remade(data):
    md = Markdown()
    html = data
    html = re.sub('<br />','\n', data)
    html = md.convert(html)
    return html
示例#52
0
def render_markdown(readme):
    readme_file = open(readme, 'r')
    md = Markdown()
    header = md.convert(readme_file.read())
    return header
示例#53
0
文件: meta.py 项目: igorgue/osqa
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))
示例#54
0
def convert_markdown(md):
    from markdown2 import Markdown
    markdowner = Markdown()
    return markdowner.convert(md)
 def to_html(self):
     formatter = Markdown()
     return formatter.convert(self.content)
示例#56
0
文件: pusto.py 项目: pyapple/pusto
def markdown(text):
    from markdown2 import Markdown

    md = Markdown(extras=['footnotes', 'code-friendly', 'code-color'])
    return md.convert(text)
示例#57
0
 def parse_markdown(self):
     """Parses Markdown into HTML."""
     markdowner = Markdown()
     self.html = markdowner.convert(self.raw)
示例#58
0
def markdown(text):
    """Template filter that renders Markdown as HTML."""
    markdowner = Markdown()
    return markdowner.convert(text)
示例#59
0
#!/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)