Ejemplo n.º 1
0
 def html_bodies(self):
     if (self._pid):
         return markdown(self._body)
     else:
         self._html_bodies = []
         for body in self._bodies:
             self._html_bodies.append(markdown(body))
         return self._html_bodies
Ejemplo n.º 2
0
	def html_bodies(self):
		if (self._pid):
			return markdown(self._body)
		else:
			self._html_bodies = []
			for body in self._bodies:
				self._html_bodies.append(markdown(body))
			return self._html_bodies
Ejemplo n.º 3
0
 def html_titles(self):
     if (self._pid):
         return markdown(self._title)
     else:
         self._html_titles = []
         for title in self._titles:
             self._html_titles.append(markdown(title))
         return self._html_titles
Ejemplo n.º 4
0
	def html_titles(self):
		if (self._pid):
			return markdown(self._title)
		else:
			self._html_titles = []
			for title in self._titles:
				self._html_titles.append(markdown(title))
			return self._html_titles
Ejemplo n.º 5
0
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.setWindowIcon(QIcon('.computerhousekeeper\\img\\about.png'))
        print(markdown(open('README.md', encoding='utf-8').read()))
        self.textEdit.setHtml(markdown(open('README.md', encoding='utf-8').read()))

        logging.info(f'初始化{type(self).__name__}窗口')
Ejemplo n.º 6
0
 def html_list(self):
     if (self._pid):
         self._list = [
             self._pid,
             markdown(self._title),
             markdown(self._body)
         ]
         return self._list
     else:
         return None
Ejemplo n.º 7
0
 def on_changed_body(target, value, oldvalue, initiator):
     allowed_tags = ['a', 'abbr', 'acronym', 'b', 'blockquote', 'code',
                     'em', 'i', 'li', 'ol', 'pre', 'strong', 'ul',
                     'h1', 'h2', 'h3', 'p']
     target.body_html = bleach.linkify(bleach.clean(
         markdown(value, output_format='html'),
         tags=allowed_tags, strip=True))
Ejemplo n.º 8
0
def load_film(film_id, markdown=False):
    cursor=mysql.connection.cursor(named_tuple=True)
    cursor.execute('SELECT * FROM film_description WHERE id=%s;',(film_id,))
    film= cursor.fetchone()
    if markdown:
        film = film.mrk(description=markdown(film.description))
    cursor.close()
    return film
Ejemplo n.º 9
0
 def parser(self, value, type=None):
     if type == 'rst':
         convert = restructuredtext(value)
     elif type == 'markdown':
         convert = markdown(value)
     elif type == 'textile':
         convert = textile(value)
     return convert
Ejemplo n.º 10
0
 def _render_markdown(self, caller=None):
     """
     Calls the markdown filter to transform the output.
     """
     if not caller:
         return ''
     output = caller().strip()
     return markdown(self.environment, output)
Ejemplo n.º 11
0
 def on_changed_body(target, value, oldvalue, initiator):
     allowed_tags = [
         'a', 'abbr', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li',
         'ol', 'pre', 'strong', 'ul', 'h1', 'h2', 'h3', 'p'
     ]
     target.body_html = bleach.linkify(
         bleach.clean(markdown(value, output_format='html'),
                      tags=allowed_tags,
                      strip=True))
Ejemplo n.º 12
0
 def render_basic(self, value):
     md = markdown(
         value,
         [
             'markdown.extensions.fenced_code',
             'codehilite',
         ],
     )
     return mark_safe(md)
Ejemplo n.º 13
0
 def post(self, request, format=None):
     serializer = serializers.MarkdownToHTMLSerializer(data=request.data, context={**request.data})
     if not serializer.is_valid():
         return Response(serializer.errors, status=rest_framework.status.HTTP_400_BAD_REQUEST)
     return Response(
         markdown(
             serializer.data["md"],
             extensions=['markdown.extensions.fenced_code'],
         )
     )
Ejemplo n.º 14
0
    def header(self):
        from markdown import markdown

        html = markdown(self.readme)
        soup = bs4.BeautifulSoup(html, 'html.parser')
        links = soup.find_all('img')
        links = [fix_image_url(l['src'], self.repo) for l in links]
        if links:
            return links[0]
        else:
            return ''
Ejemplo n.º 15
0
    def readme_html(self):
        from markdown import markdown

        html = markdown(self.readme)
        soup = bs4.BeautifulSoup(html, 'html.parser')
        links = soup.find_all('img')
        links = [(l['src'], fix_image_url(l['src'], self.repo)) for l in links]

        for original, new in links:
            html = html.replace(original, new)
        return Markup(html)
Ejemplo n.º 16
0
def test_markdownify_template():
    current_dir = pathlib.Path(__file__).parent.absolute()

    template = my_ssg.get_markdownify_template(current_dir)
    markdown_content = open(os.path.join(current_dir, "content.md"),
                            "r").read()
    rendered = template.render(content=markdown_content)

    from markdown import markdown
    expected = markdown(markdown_content)

    eq_(rendered, expected)
Ejemplo n.º 17
0
def docs(path=None):
  # Find the active page.
  page = find_page(path)
  if not page: abort(404)

  filename = os.path.join(basedir, page['file'])
  with open(filename, 'r') as fp:
    md = markdown()
    content = md.convert(fp.read())

  return render_template('registry/docs.html',
    content=content, toc=md.toc, pages=pages, active_page=path, page=page)
Ejemplo n.º 18
0
 def _render_include_text(self, caller=None):
     """
     Runs markdown and if available, typogrigy on the
     content returned by the include node.
     """
     if not caller:
         return ''
     output = caller().strip()
     output = markdown(self.environment, output)
     if 'typogrify' in self.environment.filters:
         typo = self.environment.filters['typogrify']
         output = typo(output)
     return output
Ejemplo n.º 19
0
def htmlasf(event=None):
    filet = asksaveasfile(mode='w',defaultextension=".html")
    markdowntxt = markdowncode_box.get("1.0", END)
    htmltext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/transitional.dtd"><html><head></head><body>'
    htmltext += markdown(markdowntxt, extensions=['extra', 'toc', 'smarty', 'legacy_attrs', 'meta'])
    htmltext += "</body></html>"
    htmltext = htmltext.replace("<table>",'<table border="2" >')
    htmltext = htmltext.replace("<code>",'<code bgcolor="#DCDCDC" >')
    # print(htmltext)
    try:
        filet.write(htmltext)
        filet.close()
    except:
        showerror("File error", "File error.")
Ejemplo n.º 20
0
def html_format(value):
    """
    Returns the value formatted in HTML,
    depends on MARKUP_LANGUAGE setting.
    """
    if not value:
        return ''
    elif MARKUP_LANGUAGE == 'markdown':
        return markdown(value)
    elif MARKUP_LANGUAGE == 'textile':
        return textile(value)
    elif MARKUP_LANGUAGE == 'restructuredtext':
        return restructuredtext(value)
    elif '</p>' not in value:
        return linebreaks(value)
    return value
Ejemplo n.º 21
0
def html_format(value):
    """
    Returns the value formatted in HTML,
    depends on MARKUP_LANGUAGE setting.
    """
    if not value:
        return ''
    elif MARKUP_LANGUAGE == 'markdown':
        return markdown(value)
    elif MARKUP_LANGUAGE == 'textile':
        return textile(value)
    elif MARKUP_LANGUAGE == 'restructuredtext':
        return restructuredtext(value)
    elif '</p>' not in value:
        return linebreaks(value)
    return value
Ejemplo n.º 22
0
def refresh():
    global event_r
    global saved
    sleep(0.1)
    markdowntxt = markdowncode_box.get("1.0", END)
    htmltext = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/transitional.dtd"><html><head></head><body>'
    htmltext += markdown(markdowntxt, extensions=['extra', 'toc', 'smarty', 'legacy_attrs', 'meta'])
    htmltext += "</body></html>"
    htmltext = htmltext.replace("<table>",'<table border="2" >')
    htmltext = htmltext.replace("<code>",'<code bgcolor="#DCDCDC" >')
    # print(htmltext)
    preview.set_content(htmltext)
    print(event_r.keysym)
    if "Control" not in event_r.keysym:
        print("Control is not pressed.")
        saved = 0
        refreshtitle()
Ejemplo n.º 23
0
def format_post(message, ip, parentid, parent_timestamp=0):
    """
  Formats posts using the specified format
  """
    board = Settings._.BOARD
    using_markdown = False

    # Escape any HTML if user is not using Markdown or HTML
    if not Settings.USE_HTML:
        message = cgi.escape(message)

    # Strip text
    message = message.rstrip()[0:8000]

    # Treat HTML
    if Settings.USE_MARKDOWN:
        message = markdown(message)
        using_markdown = True
    if Settings.USE_HTML:
        message = onlyAllowedHTML(message)

    # [code] tag
    if board["dir"] == "tech":
        message = re.compile(r"\[code\](.+)\[/code\]",
                             re.DOTALL | re.IGNORECASE).sub(
                                 r"<pre><code>\1</code></pre>", message)

    if Settings.VIDEO_THUMBS:
        (message, affected) = videoThumbs(message)
        if affected:
            message = close_html(message)

    message = clickableURLs(message)
    message = checkRefLinks(message, parentid, parent_timestamp)
    message = checkWordfilters(message, ip, board["dir"])

    # If user is not using markdown quotes must be created and \n changed for HTML line breaks
    if not using_markdown:
        message = checkQuotes(message)
        message = message.replace("\n", "<br />")

    return message
Ejemplo n.º 24
0
def format_post(message, ip, parentid, parent_timestamp=0):
  """
  Formats posts using the specified format
  """
  board = Settings._.BOARD
  using_markdown = False
  
  # Escape any HTML if user is not using Markdown or HTML
  if not Settings.USE_HTML:
    message = cgi.escape(message)
  
  # Strip text
  message = message.rstrip()[0:8000]
  
  # Treat HTML
  if Settings.USE_MARKDOWN:
    message = markdown(message)
    using_markdown = True
  if Settings.USE_HTML:
    message = onlyAllowedHTML(message)

  # [code] tag
  if board["dir"] == "tech":
    message = re.compile(r"\[code\](.+)\[/code\]", re.DOTALL | re.IGNORECASE).sub(r"<pre><code>\1</code></pre>", message)

  if Settings.VIDEO_THUMBS:
    (message, affected) = videoThumbs(message)
    if affected:
      message = close_html(message)
    
  message = clickableURLs(message)
  message = checkRefLinks(message, parentid, parent_timestamp)
  message = checkWordfilters(message, ip, board["dir"])
  
  # If user is not using markdown quotes must be created and \n changed for HTML line breaks
  if not using_markdown:
    message = checkQuotes(message)
    message = message.replace("\n", "<br />")

  return message
Ejemplo n.º 25
0
def do_wl_markdown(value, *args, **keyw):
    """Apply wl specific things, like smileys or colored links."""

    beautify = keyw.pop('beautify', True)
    html = markdown(value, extensions=md_extensions)

    # Sanitize posts from potencial untrusted users (Forum/Wiki/Maps)
    if 'bleachit' in args:
        html = mark_safe(
            bleach.clean(html,
                         tags=settings.BLEACH_ALLOWED_TAGS,
                         attributes=settings.BLEACH_ALLOWED_ATTRIBUTES))

    # Prepare the html and apply smileys and classes.
    # BeautifulSoup objects are all references, so changing a variable
    # derived from the soup will take effect on the soup itself.
    # Because of that the called functions will modify the soup directly.
    soup = BeautifulSoup(html, features='lxml')
    if len(soup.contents) == 0:
        # well, empty soup. Return it
        return str(soup)

    if beautify:
        # Insert smileys
        smiley_text = soup.find_all(string=find_smiley_Strings)
        for text in smiley_text:
            _insert_smileys(text)

        # Classify links
        for tag in soup.find_all('a'):
            _classify_link(tag)

        # All external images gets clickable
        # This applies only in forum
        for tag in soup.find_all('img'):
            _make_clickable_images(tag)

    return str(soup)
Ejemplo n.º 26
0
    def readme_html(self):
        from jinja2 import Markup
        from markdown import markdown
        '''
        def process(url):
            from urllib.parse import urlparse
            o = urlparse(url)

            def parse_find_string(string):
                def parse(data):
                    print(data, string)
                    result = data.find(string)
                    return result >= 0, result + len(string)
                return parse

            master = parse_find_string('/blob/master/')
            result = master(o.path.decode('utf8'))
            if result[0]:
                path = o.path[:result[1]]
                return f"https://raw.githubusercontent.com/{self.repo}/{path}"

            if url.netloc == '':
                return f"https://raw.githubusercontent.com/{self.repo}/{o.path}"
            return 
        '''

        html = markdown(self.readme)
        soup = bs4.BeautifulSoup(html, 'html.parser')
        links = soup.find_all('img')
        links = [(l['src'], fix_image_url(l['src'], self.repo)) for l in links]
        '''
        print(links)
        '''
        for original, new in links:
            html = html.replace(original, new)
        return Markup(html)
Ejemplo n.º 27
0
def markdown(value):
    renderer = HighlightRenderer()
    markdown = mistune.Markdown(renderer=renderer)
    return markdown(value)
Ejemplo n.º 28
0
 def pre_save(self, model_instance, add):
     value = getattr(model_instance, self.attname)
     html = markdown(value, ['extra'], safe_mode=self._markdown_safe)
     setattr(model_instance, self._html_field, html)
     return value
Ejemplo n.º 29
0
#!/usr/bin/evn python

###########################################################################
# Script Name: md2pdf.py
# Create Date: 11/18/2018
# Description: python script to convert markdown files to pdf files using user inputs of filenames
# Author: Mr. Machine
# Tags: python, md, pdf, productivity
########################################################################### 

# Library imports
import markdown
import pdfkit

input_filename = 'todolist.md'
output_filename ='todolist.pdf'

with open(input_filename, 'r') as f:
    html_text = markdown(f.read(), output_format='html4')

pdfkit.from_string(html_text, output_filename)
Ejemplo n.º 30
0
	def html_list(self):
		if (self._pid):
			self._list = [ self._pid, markdown(self._title), markdown(self._body) ]
			return self._list
		else:
			return None
Ejemplo n.º 31
0
 def __init__(self, title, body):
     self.title = title
     self.body = body
     self.timestamp = datetime.utcnow()
     #创建时得到Markdown的HTML代码缓存到数据库这个列中。
     self.body_html = markdown(self.body, output_format='html')
Ejemplo n.º 32
0
def markweg(value):
    """Markdown rendering that does not wrap text into a paragraph."""
    return markdown(value)[3:][:-4]

#234567891123456789212345678931234567894123456789512345678961234567897123456789
Ejemplo n.º 33
0
def htmlasf():
    filet = asksaveasfile(mode='w', defaultextension=".html")
    htmltext = markdown(markdowncode_box.get(1.0, END))
    filet.write(htmltext)
Ejemplo n.º 34
0
def refresh(event):
    markdowntxt = markdowncode_box.get("1.0", END)
    htmltext = markdown(markdowntxt)
    preview.set_content(htmltext)
    saved.set(0)
Ejemplo n.º 35
0
 def render(self, text, **kwargs):
     from markdown import markdown
     return markdown(text,
                     extensions=['diskurs.markdown.giffer:GifferMarkdown'],
                     **kwargs)
Ejemplo n.º 36
0
Archivo: tools.py Proyecto: Peiiii/sun2
def mdToHTML(md):
    md=markdown(md)
    return md
Ejemplo n.º 37
0
	def save(self, *args, **kwargs):
		"""When saving the content, render via markdown and save to self.rendered"""
		self.rendered = markdown(urlize(self.description))
		super(Idea, self).save(*args, **kwargs)
Ejemplo n.º 38
0
def markweg(value):
    """Markdown rendering that does not wrap text into a paragraph."""
    return markdown(value)[3:][:-4]


#234567891123456789212345678931234567894123456789512345678961234567897123456789
Ejemplo n.º 39
0
def markdown_to_html(value):
    markdown = mistune.Markdown()
    return mark_safe(markdown(value))
Ejemplo n.º 40
0
  result = utils.url_for('static', filename=fn)
  if app.debug and dbg_force_reload:
    result += '?v=' + str(time.time())
  return result

# Initialize the Jinja environment globals and filters..
app.jinja_env.globals.update({
  'VERSION': str(manifest.parse(os.path.join(__directory__, '../package.json')).version),
  'PY_VERSION': sys.implementation.name + ' ' + '.'.join(map(str, sys.version_info)),
  'FLASK_VERSION': flask.__version__,
  'active': lambda v, x: jinja2.Markup('class="active"') if v == x else '',
  'User': models.User,
  'Package': models.Package,
  'PackageVersion': models.PackageVersion,
  'resources': resources,
  'config': config,
  'jsonfmt': json.dumps,
  'urlparse': urllib.parse.urlparse,
  'url_for': utils.url_for,
  'active': utils.active,
  'static': static
})

app.jinja_env.filters.update({
  'markdown': lambda x: markupsafe.Markup(markdown().convert(x)),
  'sizeof_fmt': utils.sizeof_fmt,
  'pygmentize': utils.pygmentize
})

exports = app
Ejemplo n.º 41
0
def get_post():
    today = datetime.utcnow()
    todate = today.date()
    weekday = todate.weekday()
    if weekday == 4:
        weekday = 5
    weekssincestart = str(
        abs((date(2018, 2, 19) - date.today()).days/7)).split('.')[0]
    post = template['post']
    dailytheme = post[str(weekday)]
    title = dailytheme['title']+" - Weekly Round-Up #"+weekssincestart
    tag = dailytheme['tag']
    tags = ["hive-184437", "travel", "fundition-81n9hwooj", "palnet", tag,
            "travelfeeddaily", "neoxian"]
    app = post['app']
    country_codes = dailytheme.get('country_codes', None)
    featured_posts = query_db(country_codes, tag, post['database_connection'])
    authorlist = []
    featured_post_text = ""
    selected_featured_posts = []
    count = 0
    authorcandidateslist = []
    for fp in featured_posts:
        try:
            data = json.loads(fp[7])
            if data['app'].split('/')[0] == 'travelfeed' and fp[0] not in authorcandidateslist and count < 3:
                authorcandidateslist += [fp[0]]
                count += 1
                selected_featured_posts += [fp]
        except Exception as e:
            print(e)
            continue
    for fp in selected_featured_posts:
        fp_author = fp[0]
        authorlist += [fp_author]
        fp_permlink = fp[1]
        fp_title = fp[2]
        fp_title = re.sub(r'\'', '’', fp_title)
        fp_title = re.sub(r'\"', '”', fp_title)
        caption_regex = r'<h.>.*</h.>'
        link_regex = r'/(?:https?|ftp):\/\/[\n\S]+/g'
        image_regex = r'''(https?:\/\/(?:[-a-zA-Z0-9._]*[-a-zA-Z0-9])(?::\d{2,5})?(?:[/?#](?:[^\s\"'<>\][()]*[^\s\"'<>\][().,])?(?:(?:\.(?:tiff?|jpe?g|png|svg|ico)|ipfs\/[a-z\d]{40,}))))'''
        fp_preview = re.sub(caption_regex, '', markdown(fp[3]))
        fp_preview = BeautifulSoup(
            fp_preview, features="html.parser").get_text()
        fp_preview = re.sub(r'\'', '’', fp_preview)
        fp_preview = re.sub(r'\"', '”', fp_preview)
        fp_preview = re.sub(r'\n', '', fp_preview)
        fp_preview = re.sub(link_regex, '', fp_preview)
        fp_preview = re.sub(image_regex, '', fp_preview)
        fp_preview = fp_preview[:350]+"[...]"
        fp_img_url = fp[4]
        fp_location = ""
        if weekday != 2 and weekday != 5:
            fp_country = pycountry.countries.get(alpha_2=fp[5].upper()).name
            fp_subdivision = fp[6]
            fp_location = '<p>📍<em>'+fp_country + \
                '</em></p>'
            if fp_subdivision != None:
                fp_location = '<p>📍<em>'+fp_subdivision+', '+fp_country + \
                    '</em></p>'
        featured_post_text += '''<div json='{"type": "linkTool", "data": {"link": "https://travelfeed.io/@'''+fp_author+'''/'''+fp_permlink+'''", "meta": {"title": "'''+fp_title+'''", "description": "'''+fp_preview+'''", "image": "'''+fp_img_url+'''", "author": "'''+fp_author+'''", "permlink": "'''+fp_permlink+'''"}}}'><center><h4>''' + \
            fp_title+''' <em> by <a href="https://travelfeed.io/@'''+fp_author+'''">@'''+fp_author+'''</a></em></h4>'''+fp_location+'''</center><blockquote><p>'''+fp_preview + \
            '''</p></blockquote><center><a href="https://travelfeed.io/@''' + fp_author+'''/''' + \
            fp_permlink+'''"><img src="'''+fp_img_url + '''" /></a></center></div><hr/>'''
    permlink = dailytheme['title'].lower().replace(
        ', ', '-').replace(' & ', '-').replace(' ', '-')+"-weekly-round-up-"+weekssincestart
    body = '<a href="https://travelfeed.io/@travelfeed/{}"><center><h3>Read "{}" on TravelFeed.io for the best experience</h3></center></a><hr />\n\n'.format(permlink, title)+post['header'].format(dailytheme['title']) + dailytheme['body'] + \
        post['subheader'].format(dailytheme['title']) + \
        featured_post_text + post['postsfooter'] + post['footer'] + \
        '\n\n---\n\nView this post [on TravelFeed](https://travelfeed.io/@travelfeed/{}) for the best experience.'.format(
        permlink)
    if selected_featured_posts == []:
        body = post['header'].format(dailytheme['title'])+post['nopoststext'].format(
            dailytheme['title'], dailytheme['title']) + post['footer']
        logger.debug("No posts for topic")
    beneficiaries = []
    # remove duplicates, oder alphabetically
    authorlist = sorted(list(dict.fromkeys(authorlist)))
    for a in authorlist:
        beneficiaries += {'account': a, 'weight': 1300},
    # logger.info("title: "+title)
    # logger.info("tags: "+str(tags))
    # logger.info("body: "+body)
    # logger.info("beneficiaries:"+str(beneficiaries))
    post_to_steem(title,
                  body, permlink, app, tags, beneficiaries)
    post_to_hive(title,
                 body, permlink, app, tags, beneficiaries)
Ejemplo n.º 42
0
def render(value):
    """Renders a data entry according to its encoding."""
    if value.is_rest:
        return restructuredtext(value.text)
    else:
        return markdown(value.text)
Ejemplo n.º 43
0
def markdown(value):
    renderer = HightLightRenderer()
    markdown = mistune.Markdown(renderer=renderer)
    return markdown(value)
Ejemplo n.º 44
0
def render(value):
    """Renders a data entry according to its encoding."""
    if value.is_rest:
        return restructuredtext(value.text)
    else:
        return markdown(value.text)
Ejemplo n.º 45
0
def markdown_filter(data):
    from flask import Markup
    from markdown import markdown
    return Markup(markdown(data))