示例#1
0
    def handle(self, *args, **options):
        names = os.listdir("docs/other")
        paths = [os.path.join("docs/other", x) for x in names]
        paths += ["README.md"]

        mkdir_p("docs/static/docs/img")

        for path in paths:
            text = "".join(open(path, "r").readlines())

            if path.endswith("_plain.md"):
                c = Context({
                    "docs": misaka.html(text),
                    "STATIC_URL": settings.STATIC_URL,
                })
                t = loader.get_template("docs/content.html")
                page = os.path.split(path)[1].replace("_plain.md", ".html")
            else:
                tree = misaka.html(text, render_flags=misaka.HTML_TOC_TREE)
                body = misaka.html(text, render_flags=misaka.HTML_TOC)

                c = Context({
                    "toc": postprocess_toc(tree, "#"),
                    "docs": postprocess_toc(body, 'id="'),
                    "STATIC_URL": settings.STATIC_URL,
                })
                t = loader.get_template("docs/index.html")
                page = os.path.split(path)[1].replace(".md", ".html")

            page = page.replace("README", "technical")

            with open(os.path.join("docs/static/docs", page), "w") as f:
                rendered = t.render(c)
                new_rendered = self.get_and_replace_images(rendered)
                f.write(new_rendered)
示例#2
0
 def postRead(args=dict()):
     getPostList = post.getPostList(boardname=args.get('board'))
     if(getPostList is None):
         viewPost = {'postSrl': 'getPost.postSrl', 'postTitle': 'getPost.title', 'postText': 'getPost.text', 'postWriter': 'getPost.writer', 'postWriten': 'getPost.writeTime', 'files': 'getPost.files'}
     else:
         postList = list()
         for getPost in getPostList:
             t = time.localtime(getPost.writeTime)
             writen = str(t[1])+'월'+str(t[2])+'일 '+str(t[3])+':'+str(t[4])
             rendered = misaka.html(getPost.text)
             commentList = comment.getComment(getPost.postSrl)
             comments = list()
             for commentTemp in commentList:
                 ct = time.localtime(commentTemp.writeTime)
                 commentWriten = str(ct[1])+'월'+str(ct[2])+'일 '+str(ct[3])+':'+str(ct[4])
                 commentR = misaka.html(commentTemp.comment)
                 temp = {'commentWriter': commentTemp.writer, 'commentWriten': commentWriten, 'comment': commentR, 'commentSrl': commentTemp.commentSrl}
                 comments.append(temp)
             fileDict = fileUploader.serving(getPost.files)
             viewPost = {'postSrl': getPost.postSrl, 'postTitle': getPost.title, 'postText': rendered,\
                 'postWriter': getPost.writer, 'postWriten': writen,\
                 'board': getPost.board, 'commentCount': getPost.commentCount,\
                 'comments': comments, 'fileList': fileDict}
             postList.append(viewPost)
         postList.reverse()
         return render_template('postView.jinja', postList=postList, isBoard=True, getBoard=args.get('board'))
示例#3
0
文件: models.py 项目: LeIggy/gswd
 def save(self, *args, **kwargs):
     self.intro_html = mi.html(self.intro,
         extensions=mi.EXT_NO_INTRA_EMPHASIS | mi.EXT_FENCED_CODE | mi.HTML_HARD_WRAP)
     self.body_html = mi.html(self.body,
         extensions=mi.EXT_NO_INTRA_EMPHASIS | mi.EXT_FENCED_CODE | mi.HTML_HARD_WRAP)
     self.transcript_html = mi.html(self.transcript,
         extensions=mi.EXT_NO_INTRA_EMPHASIS | mi.EXT_FENCED_CODE | mi.HTML_HARD_WRAP)
     super(Translation, self).save(*args, **kwargs)
示例#4
0
	def post(self):
		timeLimit 	= int(self.get_argument("timeLimit", ""))*1000
		stars		= int(self.get_argument("stars", ""))
		title 		= self.get_argument("title", "")
		proDes 		= misaka.html( self.get_argument("proDes", "") )
		inputDes	= misaka.html( self.get_argument("inputDes", "") )
		outputDes	= misaka.html( self.get_argument("outputDes", "") )
		sapInput	= self.get_argument("sapInput", "")
		sapOutput	= self.get_argument("sapOutput", "")
		author		= self.get_argument("author", "")
		recommend	= misaka.html( self.get_argument("recommend", "") )
		testInput	= self.request.files["inputfile"][0]["body"].replace("\r\n", "\n")
		testOutput	= self.request.files["outputfile"][0]["body"].request("\r\n", "\n")

		print testInput

		if timeLimit != "" and stars != "" \
		   and title != "" and proDes != "" \
		   and inputDes != "" and outputDes != "" \
		   and sapInput != "" and sapOutput != "" \
		   and author != "" \
		   and testInput != None and testOutput != None:

			print "Adding Problem:", \
				"\ntimeLimit:\n", timeLimit, \
				"\nstarts:\n", stars, \
				"\ntitle:\n", title, \
				"\nproDes:\n", proDes, \
				"\ninputDes:\n", inputDes, \
				"\noutputDes:\n", outputDes, \
				"\nsapInput:\n", sapInput, \
				"\nsapOutput:\n", sapOutput, \
				"\nauthor:\n", author, \
				"\nrecommend:\n", recommend, "\n"
		
			proID = self.application.problemCnt + 1001
			self.application.problemCnt += 1

			self.application.problemSet.addProblemItem(proID, title, stars, proDes,\
											   inputDes, outputDes, sapInput, sapOutput,\
											   recommend, author, timeLimit)

			dirName = "./judgefile/%s" % proID
			if os.path.exists(dirName) == False:
				os.makedirs(dirName)
			finput = open("%s/%s.in" % (dirName, proID), "w")
			foutput = open("%s/%s.out" % (dirName, proID), "w")
			finput.write(str(testInput))
			foutput.write(str(testOutput))
			print testOutput
			finput.close()
			foutput.close()


			self.render('addProblem.html', addOK=True)
			return

		self.render('addProblem.html', addOK=False)
示例#5
0
    def save(self, *args, **kwargs):
        if not self.pk:
            self.created_at = timezone.now()

        if self.excerpt:
            self.excerpt_html = misaka.html(self.excerpt)
        self.content_html = misaka.html(self.content)

        super(Post, self).save(*args, **kwargs)
示例#6
0
 def test_misaka(self):
     import misaka
     extensions = (
         'no-intra-emphasis',
         'fenced=code',
         'autolink',
         'tables',
         'strikethrough',
     )
     misaka.html(self.text, extensions)
示例#7
0
def benchmark_misaka(text):
    import misaka as m
    # mistune has all these features
    extensions = (
        m.EXT_NO_INTRA_EMPHASIS | m.EXT_FENCED_CODE | m.EXT_AUTOLINK |
        m.EXT_TABLES | m.EXT_STRIKETHROUGH
    )
    # md = m.Markdown(m.HtmlRenderer(), extensions=extensions)
    # md.render(text)

    m.html(text, extensions)
示例#8
0
文件: Text.py 项目: Andais/jasy
def markdownToHtml(markdownStr):
    """
    Converts Markdown to HTML. Supports GitHub's fenced code blocks, 
    auto linking and typographic features by SmartyPants.
    """

    return misaka.html(markdownStr, misakaExt, misakaRender)
示例#9
0
文件: pygwi.py 项目: kosystem/PyGWi
def contentView(name):
    import datetime
    pageList = pagelist()
    updateList = commitList()
    if os.path.splitext(name)[1] != '.ico':
        try:
            fullpath = os.path.join(path, name+'.md')
            f = codecs.open(
                fullpath,
                'r',
                encoding='utf-8')
            pageTitle = f.readline()
            pageTitle = pageTitle.replace('#', '')
            text = f.read()
            rndr = BleepRenderer(flags=misaka_flags)
            md = misaka.Markdown(rndr, extensions=misaka_ext)
            content = md.render(text)
            toc = misaka.html(text, misaka_ext, misaka.HTML_TOC_TREE)

            st_time = os.lstat(fullpath).st_mtime
            date_time = datetime.datetime.fromtimestamp(st_time)
            updateTime = date_time.strftime('%Y/%m/%d %H:%M')
            return render_template('content.html', **locals())
        except:
            # TODO: page not found message in flash
            return redirect(url_for('newView', pageName=name))
    else:
        return 0
示例#10
0
    def form_valid(self, form):
        rsvps = form.cleaned_data.get('rsvps')
        event = self.get_context_data().get('event')
        selected_rsvps = event.rsvps.all()
        if rsvps == 'yes':
            selected_rsvps = event.rsvps.yes()
        elif rsvps == 'no':
            selected_rsvps = event.rsvps.no()
        elif rsvps == 'maybe':
            selected_rsvps = event.rsvps.maybe()
        elif rsvps == 'possible':
            selected_rsvps = event.rsvps.possible()

        to_emails = ['{0.name} <{0.email}>'.format(rsvp.user) for
                     rsvp in selected_rsvps]
        host_email = event.host.email if form.cleaned_data.get(
            'include_email_address') else None

        email = generate_email(
            'events/email/message_from_host',
            self.request,
            {
                'subject': form.cleaned_data.get('subject'),
                'body': form.cleaned_data.get('body'),
                'body_html': misaka.html(form.cleaned_data.get('body')),
                'host_email': host_email,
                'event': event,
                'domain': Site.objects.get_current().domain
            },
            to=to_emails
        )
        email.send(fail_silently=True)
        return super(EmailRSVPs, self).form_valid(form)
示例#11
0
def render(filename, template, edit=False):
  filename = filename.replace('.', '') # remove periods
  filename = filename.replace(' ', '-')
  filename = filename.replace('/', '-')
  filepath = os.path.join(NOTES_PATH, '%s.md' % (filename, ))

  if not os.path.exists(filepath):
    if edit:
      note = ''
    else:
      bottle.redirect('/edit/%s' % (filename, ))
  else:
    with codecs.open(filepath, 'r', 'utf8') as file_obj:
      note = file_obj.read()

  def replacement(match):
     match_str =  match.groups()[0]
     replace_match = match_str.replace(' ', '-')
     replace_match = match_str.replace('/', '-')

     replace_match = replace_match.replace('.', '')
     return "<a href='/notes/%s'>%s</a>" % (replace_match, match_str)

  if not edit:
   note = re.sub(
      r'\[\[([A-Z \/\.a-z0-9@]+)\]\]',
      replacement,
      m.html(note)
    )

  return pystache.render(loader.load_name(template), {
    'title': ' '.join(x.capitalize() for x in filename.split('-')),
    'filename': filename,
    'content': note
  })
示例#12
0
文件: home.py 项目: HevLfreis/Seed
def resume():
    logger.info('(' + get_addr(request) + ')')
    db.counter.update_one({'counter': 'resume'}, {'$inc': {'value': 1}})
    with codecs.open(app.static_folder + '/files/md/resume.md', 'r', encoding='utf8') as f:
        text = f.read()
    res = m.html(text)
    return render_template('blank.html', html=res, title='Resume')
示例#13
0
 def clean_body(body):
     # Cross-board links: >>>(/)?boardname/id
     body = re.sub(r'>>>/?([a-zA-Z]{1,6})/(\d+)\b', r'<a class="ref" href="/\1/#\2">&gt;&gt;&gt;/\1/\2</a>', body)
     # Same-board links: >>id
     body = re.sub(r'>>(\d+)\b', r'<a class="ref" href="#\1">&gt;&gt;\1</a>', body)
     body = clean_html(html(body).strip())
     return body
示例#14
0
文件: tnote.py 项目: tom5760/tnote
    def note(self, name=None, title=None, raw=None, tags=None):
        cherrypy.response.headers['Content-Type'] = 'text/html'
        vals = {}
        if cherrypy.request.method == 'GET':
            if name is not None:
                vals['title'] = name
                try:
                    vals['raw'] = self.load_note(name)
                except IOError:
                    pass
        elif cherrypy.request.method == 'POST':
            if name is not None and name != title:
                self.rename_note(name, title, raw, tags)
            else:
                self.save_note(title, raw, tags)
            vals['title'] = title
            vals['raw'] = raw

        if 'raw' in vals:
            vals['body'] = misaka.html(vals['raw'], self.markdown_extensions)

        if 'title' in vals:
            vals['tags'] = self.get_tags(vals['title'])

        return bytes(self.template_env.get_template('note.html')
                     .render(vals), 'utf-8')
示例#15
0
def home():
    """Serve the home page."""
    global _body_html
    if _body_html is None:
        with open('README.md') as f:
            _body_html = misaka.html(f.read())
    return render_template('index.html', body=_body_html)
示例#16
0
    def _parse_meta(self, header, body):
        header = m.html(to_unicode(header))
        titles = re.findall(r'<h1>(.*)</h1>', header)
        if not titles:
            logging.error('There is no title')
            title = None
        else:
            title = titles[0]

        meta = {'title': title}
        items = re.findall(r'<li>(.*?)</li>', header, re.S)
        for item in items:
            index = item.find(':')
            key = item[:index].rstrip()
            value = item[index + 1:].lstrip()
            meta[key] = value

        desc = re.findall(r'<p>(.*?)</p>', header, re.S)
        if desc:
            meta['description'] = '\n\n'.join(desc)

        #: keep body in meta data as source text
        meta['source_text'] = body
        _toc = m.Markdown(m.HtmlTocRenderer(), 0)
        meta['toc'] = _toc.render(body)
        return meta
示例#17
0
  def getRevealMarkdown(self):

    # Remove non-ASCII characters from markdown, these appear when reading from the wiki
    # (http://stackoverflow.com/questions/8689795/python-remove-non-ascii-characters-but-leave-periods-and-spaces)
    self.markdown = filter(lambda x: x in string.printable, self.markdown)

    # Convert the markdown to HTML using misaka which is a python wrapper utilizing the same
    # parser as GitHub
    # (https://gist.github.com/fyears/5097469)
    html = misaka.html(self.markdown,
                       extensions = misaka.EXT_NO_INTRA_EMPHASIS | misaka.EXT_FENCED_CODE |
                       misaka.EXT_AUTOLINK |
                       misaka.EXT_TABLES,
                       render_flags =  misaka.HTML_USE_XHTML | misaka.HTML_HARD_WRAP)

    # Convert the Remark.js style blocks to spans
    html = re.sub(r'<p>\.(.*?)\[</p>', self._startSpan, html)
    html = re.sub(r'<p>\]</p>', '</span>', html)

    # Create the html output suitable for Reveal.js
    output = ''
    output +=  ' '*10 + '<section id="' + self.name() + '">\n'
    output += html
    output +=  ' '*10 + '</section>\n'
    return output
示例#18
0
def markdown(text, **options):
    """
    Parses the provided Markdown-formatted text into valid HTML, and returns
    it as a :class:`flask.Markup` instance.
    """
    ext, rndr = make_flags(**options)
    return Markup(misaka.html(text, extensions=ext, render_flags=rndr))
示例#19
0
文件: test.py 项目: MistShi/the-gist
def show(name):
    name = name.replace("..", "", -1).replace(" ", " ", -1)
    file_path = os.path.join("./f", name)
    if not (os.path.exists(file_path) or os.path.isfile(file_path)):
        abort(404, u"不存在这个文件哈")

    content = open(file_path).read().decode("utf8")

    if name.endswith(".md") or name.endswith(".markdown"):
        html = misaka.html(content, extensions=\
                misaka.EXT_AUTOLINK|misaka.EXT_LAX_HTML_BLOCKS|misaka.EXT_SPACE_HEADERS|\
                misaka.EXT_SUPERSCRIPT|misaka.EXT_FENCED_CODE|misaka.EXT_NO_INTRA_EMPHASIS|\
                misaka.EXT_STRIKETHROUGH|misaka.EXT_TABLES)
        def _r(m):
            try:
                lexer_name = m.group(1)
                code = m.group(2)
                lexer = get_lexer_by_name(lexer_name)
                code = HTMLParser.HTMLParser().unescape(code)
                return highlight(code, lexer, HtmlFormatter())
            except pygments.util.ClassNotFound:
                return m.group()

        p = re.compile(r'''<pre><code class="([0-9a-zA-Z._-]+)">(.+?)</code></pre>''', re.DOTALL)
        html = p.sub(lambda m: _r(m), html)

    else:
        try:
            lexer = guess_lexer_for_filename(file_path, content)
        except pygments.util.ClassNotFound:
            lexer = get_lexer_by_name("python")
        html = highlight(content, lexer,  HtmlFormatter())

    return render_template("gfm.html", **locals())
示例#20
0
 def on_modified(self, event):
     if all([event.is_directory, event.event_type == 'modified',
        event.src_path == target_path]):
         with file(target) as f:
             html = misaka.html(f.read())
             with sockets_lock:
                 for socket in sockets:
                     socket.write_message(html)
示例#21
0
    def highlight(self, code_string, **kwargs):
        import misaka

        return mark_safe(
            misaka.html(
                code_string, extensions=self.extensions, render_flags=self.render_flags
            )
        )
示例#22
0
文件: idea.py 项目: burtn/idea.py
def addIdea():
	text = m.html(h.escape_js(request.form['text']), extensions=m.EXT_AUTOLINK | m.EXT_SPACE_HEADERS | m.HTML_SKIP_HTML | m.HTML_SAFELINK | m.HTML_HARD_WRAP)
	try:
		g.db.execute("insert into ideas(userID, title, text, rating) values(?,?,?,?)", (session['ID'], request.form['title'], text, 1)) 
		g.db.commit()
	except KeyError:
		return render_template('error.html'), 500
	return redirect(url_for('Ideas', user_ID=session['ID']))
示例#23
0
    def test_one_ext_one_render(self, html):
        ext, flags = EXT_NO_INTRA_EMPHASIS, HTML_SKIP_HTML

        result = markdown(TEST_MD, no_intra_emphasis=True, no_html=True)

        html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags)
        self.assertIsInstance(result, Markup)
        self.assertEqual(result, misaka.html(TEST_MD,
            extensions=ext, render_flags=flags))
示例#24
0
    def test_defaults(self, html):
        ext, flags = 0, 0

        result = markdown(TEST_MD)

        html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags)
        self.assertIsInstance(result, Markup)
        self.assertEqual(result, misaka.html(TEST_MD,
            extensions=ext, render_flags=flags))
示例#25
0
 def build_list_operation(self, method='get'):
     return {
         'summary': self.get_operation_summary(detail=False, method=method),
         'httpMethod': method.upper(),
         'parameters': self.build_parameters_for_list(method=method),
         'responseClass': 'ListView' if method.upper() == 'GET' else self.resource_name,
         'nickname': '%s-list' % self.resource_name,
         'notes': markdownrender.html(inspect.getdoc(self.resource)),
     }
示例#26
0
    def test_undefined_option(self, html):
        ext, flags = 0, 0

        result = markdown(TEST_MD, fireworks=True)

        html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags)
        self.assertIsInstance(result, Markup)
        self.assertEqual(result, misaka.html(TEST_MD,
            extensions=ext, render_flags=flags))
示例#27
0
    def test_defined_and_undefined_options(self, html):
        ext, flags = 0, HTML_HARD_WRAP

        result = markdown(TEST_MD, hard_wrap=True, stupid_hard_wrap=False)

        html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags)
        self.assertIsInstance(result, Markup)
        self.assertEqual(result, misaka.html(TEST_MD,
            extensions=ext, render_flags=flags))
示例#28
0
    def test_inverse_render(self, html):
        ext, flags = 0, HTML_SKIP_HTML

        result = markdown(TEST_MD, no_html=True)

        html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags)
        self.assertIsInstance(result, Markup)
        self.assertEqual(result, misaka.html(TEST_MD,
            extensions=ext, render_flags=flags))
示例#29
0
    def test_inverse_ext(self, html):
        ext, flags = EXT_NO_INTRA_EMPHASIS, 0

        result = markdown(TEST_MD, intra_emphasis=False)

        html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags)
        self.assertIsInstance(result, Markup)
        self.assertEqual(result, misaka.html(TEST_MD,
            extensions=ext, render_flags=flags))
示例#30
0
    def test_two_render(self, html):
        ext, flags = 0, HTML_HARD_WRAP | HTML_ESCAPE

        result = markdown(TEST_MD, wrap=True, escape=True)

        html.assert_called_with(TEST_MD, extensions=ext, render_flags=flags)
        self.assertIsInstance(result, Markup)
        self.assertEqual(result, misaka.html(TEST_MD,
            extensions=ext, render_flags=flags))
示例#31
0
 def save(self, *args, **kwargs):
     self.message_html = misaka.html(self.message)  # saves the html version
     super().save(*args, **kwargs)
示例#32
0
 def save(self, *args, **kwargs):
     self.slug = slugify(self.name)
     self.description = m.html(self.description)
     print(f'----------group description_html is {self.description}-------')
     super().save(args, kwargs)
示例#33
0
 def save(self,*args,**kwargs):
     self.message_html = misaka.html(self.message)
     ## ^ means that if somebody puts a link in their
     ## post, it looks normal.
     super().save(*args,**kwargs)
示例#34
0
 def save(self, *args, **kwargs):
     self.message_html = misaka.html(self.message)
     super().save(*args, **kwargs)
示例#35
0
 def save(self, *args, **kwargs):
     self.slug = slugify(self.name)
     self.description_html = misaka.html(self.description)
     super().save(*args, **kwargs)