我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用markdown.Markdown()。
def parse_md_config(self, source): """ parse exts config from markdown file and update the markdown object exts source: https://pythonhosted.org/Markdown/extensions/ :return: """ md1 = markdown.Markdown(extensions=["markdown.extensions.meta"]) md1.convert(source) md_meta = getattr(md1, "Meta") # recreate an instance of Markdown object md2 = markdown.Markdown(extensions=self.ext_list) if self.to64: if not self.base_dir: raise ValueError( "base dir is required while convert from text and enable convert local image to base64") md2.inlinePatterns["image_link"] = ImageCheckPattern(self.base_dir, md2) return md2, md_meta
def __init__(self, markdown_file, templite_file="templates/article.html"): """ Class for storing and rendering markdown article in html template :param markdown_file: File storing markdown article :param templite_file: File storing templite template """ self.setting_access = Setting() tp_file = open(templite_file) # Get template content self.template = tp_file.read() tp_file.close() art_file = open("article/%s" % markdown_file) # Get markdown article content self.markdown = art_file.read() art_file.close() # Init markdown converter with configured extensions self.converter = markdown.Markdown(extensions=self.setting_access.get_markdown_plugin_list)
def run(): # pragma: no cover """Run Markdown from the command line.""" # Parse options and adjust logging level if necessary options, logging_level = parse_options() if not options: sys.exit(2) logger.setLevel(logging_level) console_handler = logging.StreamHandler() logger.addHandler(console_handler) if logging_level <= WARNING: # Ensure deprecation warnings get displayed warnings.filterwarnings('default') logging.captureWarnings(True) warn_logger = logging.getLogger('py.warnings') warn_logger.addHandler(console_handler) # Run markdown.markdownFromFile(**options)
def _get_user_css(): """Get user css.""" css = None user_css = _get_setting('mdpopups.user_css', DEFAULT_USER_CSS) try: css = clean_css(sublime.load_resource(user_css)) except Exception: css = clean_css(sublime.load_resource(DEFAULT_CSS)) return css if css else '' ############################## # Markdown parsing ##############################
def _get_user_css(): """Get user css.""" css = None user_css = _get_setting('mdpopups.user_css', DEFAULT_USER_CSS) try: css = clean_css(sublime.load_resource(user_css)) except Exception: pass return css if css else '' ############################## # Markdown parsing ##############################
def test_yaml_extension(self): md = Markdown( extensions=[MarkdownYamlMetaExtension()] ) html = md.convert(TEST_VALID_CONTENT1) self.assertEqual("<p>This is where the <strong>Markdown</strong> content will go.</p>", html.strip()) expected_meta = { 'some-variable': 'Value', 'other-variable': 'Another value', 'yet-another': ['this', 'is', 'a', 'list'] } self.assertEqual(expected_meta, md.meta) html = md.convert(TEST_VALID_CONTENT2) self.assertEqual("<p>This is just some plain old <strong>Markdown</strong> content, without metadata.</p>", html.strip()) # no metadata self.assertEqual({}, md.meta)
def test_permalink_extension(self): md = Markdown( extensions=[ MarkdownPermalinkExtension( permalink_text="¶", permalink_class="permalink", permalink_title="Permalink to this headline" ) ] ) html = "<html><body>"+md.convert(TEST_PERMALINK_CONTENT)+"</body></html>" tree = ET.fromstring(_str(html)) for tag_id in range(1, 7): heading = tree.findall('./body/h%d' % tag_id)[0] self.assertEqual('heading-%d' % tag_id, heading.get('id')) link = tree.findall('./body/h%d/a' % tag_id)[0] self.assertEqual('#heading-%d' % tag_id, link.get('href')) self.assertEqual('permalink', link.get('class')) self.assertEqual('Permalink to this headline', link.get('title'))
def test_lorem_ipsum_extension(self): md = Markdown( extensions=[ MarkdownYamlMetaExtension(), MarkdownLoremIpsumExtension() ] ) html = "<html>"+md.convert(TEST_LOREM_IPSUM_CONTENT)+"</html>" tree = ET.fromstring(_str(html)) p = tree.findall('./p')[0] self.assertEqual(100, lipsum.count_words(p.text)) p = tree.findall('./p')[1] self.assertEqual(5, lipsum.count_sentences(p.text)) self.assertEqual(3, len(tree.findall('./p')[2:])) html = "<html>"+md.convert(TEST_LOREM_IPSUM_SINGLE_INSTANCES)+"</html>" tree = ET.fromstring(_str(html)) p = tree.findall('./p')[0] self.assertEqual(1, lipsum.count_words(p.text)) p = tree.findall('./p')[1] self.assertEqual(1, lipsum.count_sentences(p.text)) self.assertEqual(1, len(tree.findall('./p')[2:]))
def _render_markdown(self, skip_headers=False, images_base64_encode=True, urlmappers=[]): """ Returns the `Markdown` instance as well as the rendered html output as a tuple: (`Markdown`, str). """ # Copy urlmappers locally so we can modify it without affecting global # state urlmappers = urlmappers[:] if images_base64_encode: urlmappers.insert(0, self.base64_encode_image_mapper) # proxy posts are assumed to be embeddable links if 'proxy' in self.kp.headers: return None, '<a href="{0}">Linked Post</a>\n<iframe width=100% height=800 src="{0}"></iframe>'.format(self.kp.headers['proxy'].strip()) html = '' if not skip_headers: html += self.render_headers() md = markdown.Markdown(extensions=MARKDOWN_EXTENSTIONS) html += md.convert(self.kp.read()) html = self.apply_url_remapping(html, urlmappers) return md, html
def __init__(self, markdown_file_lst, templite_file="templates/index.html"): """ Class for rendering article timeline from list of markdown document and template :param markdown_file_lst: List of markdown documents :param templite_file: File storing templite template """ self.setting_access = Setting() tp_file = open(templite_file) # Get template content self.template = tp_file.read() tp_file.close() self.markdown = [] # List containing all article content for markdown_file in markdown_file_lst: # Get all article content art_file = open("article/%s" % markdown_file) self.markdown.append(art_file.read()) art_file.close() # Init markdown converter with configured extensions self.converter = markdown.Markdown(extensions=self.setting_access.get_markdown_plugin_list)
def __parseMarkdown(path): """ This method is in charge to open, read and parse the file at `path`. It then return the parsed result (Markdown ? HTML) """ # Initialize the Markdown parser: md = markdown.Markdown(extensions=[ 'meta', 'markdown.extensions.tables', 'markdown.extensions.tables', 'markdown.extensions.extra', 'markdown.extensions.smarty', GithubFlavoredMarkdownExtension(), TocExtension(anchorlink=True, permalink=True), ]) # Open the file and read it, then parse: html = open(path, 'r').read() result = md.convert(html) # Return the Markdown in HTML format: return (result, md)
def registerExtensions(self, extensions, configs): # noqa """ Register extensions with this instance of Markdown. Keyword arguments: * extensions: A list of extensions, which can either be strings or objects. See the docstring on Markdown. * configs: A dictionary mapping module names to config options. """ from markdown import util from markdown.extensions import Extension for ext in extensions: try: if isinstance(ext, util.string_type): ext = self.build_extension(ext, configs.get(ext, {})) if isinstance(ext, Extension): ext.extendMarkdown(self, globals()) elif ext is not None: raise TypeError( 'Extension "%s.%s" must be of type: "markdown.Extension"' % (ext.__class__.__module__, ext.__class__.__name__) ) except Exception: # We want to gracefully continue even if an extension fails. _log('Failed to load markdown module!') _debug(traceback.format_exc(), ERROR) return self
def text_triggered(self): """Update text to markdown text simultaneously. Args: raw (String) : Recieves the string from entry every time an input is made ntxt (html string) : Converted html string """ raw = self.ui.center_widget.entry.journalEntry.toPlainText() md = markdown.Markdown() # raw = raw.encode('utf-8') ntxt = md.convert(raw) self.ui.center_widget.view.journalView.setHtml(ntxt)
def apply_markdown(text): """ Simple wrapper around :func:`markdown.markdown` to set the base level of '#' style headers to <h2>. """ extensions = [HEADERID_EXT_PATH] extension_configs = { HEADERID_EXT_PATH: { LEVEL_PARAM: '2' } } md = markdown.Markdown( extensions=extensions, extension_configs=extension_configs ) return md.convert(text)
def save(self, *args, **kwargs): # ???????MarkDown???????body??? ??html?? md = markdown.Markdown(extensions=[ 'markdown.extensions.extra', ]) # ??????body????54??? ????html??? self.body = md.convert(self.body) # ????save ?????????? super(Announcement, self).save(*args, **kwargs)
def render_page(path=''): if not path: path = 'index' with codecs.open(os.path.join(PAGES_DIR, path + '.md'), encoding='utf-8') as f: content = f.read() content = render_template_string(content) markdown = Markdown( extensions=['meta', 'tables', 'fenced_code'] ) html_content = markdown.convert(content) #misaka # html_content = markdown(content) meta = markdown.Meta meta = dict((k, v[0]) for k, v in meta.iteritems()) template = meta.get('template', 'page.html') return render_template(template, content=html_content, **meta) # Add macro
def run(): #pragma: no cover """Run Markdown from the command line.""" # Parse options and adjust logging level if necessary options, logging_level = parse_options() if not options: sys.exit(2) logger.setLevel(logging_level) logger.addHandler(logging.StreamHandler()) # Run markdown.markdownFromFile(**options)
def apply_markdown(text): """ Simple wrapper around :func:`markdown.markdown` to set the base level of '#' style headers to <h2>. """ extensions = [HEADERID_EXT_PATH] extension_configs = { HEADERID_EXT_PATH: { 'level': '2' } } md = markdown.Markdown( extensions=extensions, extension_configs=extension_configs ) return md.convert(text)
def main(): global VERBOSE VERBOSE = True parser = argparse.ArgumentParser(description='Generate data.json used by Roca-Web') parser.add_argument('--source', help='Source directory of the Markdown files', type=str, required=True) parser.add_argument('--target', help='Target directory to generate data.json in', default='.', type=str) parser.add_argument('--title', help='Project title', default='Documentation', type=str) args = parser.parse_args() root = os.path.abspath(args.source) target = os.path.abspath(args.target) build(root, target, args.title)
def matrix_to_gitter(msg): # Currently no fix needed, Markdown and emoji should go through fine return msg
def resolve_url(self, url): """ Resolve internal URLs. Returns None if the URL does not need changing, else returns the new URL. """ from markdown.util import AMP_SUBSTITUTE if not url: return None if url.startswith(AMP_SUBSTITUTE): # Possibly an overencoded mailto: link. # see https://bugs.debian.org/816218 # # Markdown then further escapes & with utils.AMP_SUBSTITUTE, so # we look for it here. return None parsed = urlparse(url) if parsed.scheme or parsed.netloc: return None if not parsed.path: return None dest = self.page.resolve_link(parsed.path) # Also allow .md extension in if dest is None and parsed.path.endswith(".md"): dirname, basename = os.path.split(parsed.path) if basename in ("index.md", "README.md"): dest = self.page.resolve_link(dirname) else: dest = self.page.resolve_link(parsed.path[:-3]) if dest is None: log.warn("%s: internal link %r does not resolve to any site page", self.page.src_relpath, url) return None return urlunparse( (parsed.scheme, parsed.netloc, dest.dst_link, parsed.params, parsed.query, parsed.fragment) )
def __init__(self, site): self.site = site self.md_staticsite = StaticSiteExtension() self.markdown = markdown.Markdown( extensions=[ "markdown.extensions.extra", "markdown.extensions.codehilite", "markdown.extensions.fenced_code", self.md_staticsite, ], output_format="html5", ) # Cached templates self._page_template = None self._redirect_template = None
def render_text(cls, post): md = markdown.Markdown(extensions=cls.all_extensions()) post["rendered_text"] = md.convert(post["text"]) post["meta"] = md.Meta
def render_post_tldr(post): if isinstance(post, KnowledgePost): return markdown.Markdown(extensions=MARKDOWN_EXTENSTIONS).convert(post.headers.get('tldr').strip()) else: return markdown.Markdown(extensions=MARKDOWN_EXTENSTIONS).convert(post.tldr.strip())
def render_comment(comment): return markdown.Markdown().convert(comment.text)
def run(self, lines): """ Parse Meta-Data and store in Markdown.Meta. """ cnt = 0 for i, line in enumerate(lines): if line.strip() == '---': cnt = cnt + 1 if cnt == 2: break return lines[i + 1:]
def extendMarkdown(self, md, md_globals): """ Add MetaPreprocessor to Markdown instance. """ md.preprocessors.add("knowledge_meta", KnowledgeMetaPreprocessor(md), ">normalize_whitespace")
def filter_markdown2html(text): if text is None: return '' md = markdown.Markdown() return md.convert(text)
def __call__(self, stream): from jinja2 import Markup from markdown import Markdown # Markdown is not thread safe markdown = Markdown(**self._markdown_options) return Markup(markdown.convert(stream))
def __init__(self, article, preview=False, *args, **kwargs): kwargs = settings.MARKDOWN_KWARGS kwargs['extensions'] = self.get_markdown_extensions() markdown.Markdown.__init__(self, *args, **kwargs) self.article = article self.preview = preview
def setUp(self): self.md = markdown.Markdown(extensions=[ 'extra', ResponsiveTableExtension() ]) self.md_without = markdown.Markdown(extensions=['extra'])
def load_posts(self, fpath=None): """\ - Load valid posts from source directory - Convert the text to extract the HTML data, metas and filenames - Returns a list of tuples that store the above information """ if fpath == None: fpath = self.ifpath if path.exists(fpath): posts = [] for f in [fpath] if path.isfile(fpath) \ else list(map(lambda x: path.join(fpath, x), listdir(fpath))): if path.splitext(f)[1] in self._md_exts: with codecs.open(f, 'r', encoding='utf-8') as fh: md = Markdown(extensions=self.pymd_exts) html = BeautifulSoup(md.convert(fh.read()), 'lxml') if html.html: # Remove html and body tags html.html.hidden = True html.body.hidden = True meta = md.Meta if not meta.get('type'): meta['type'] = [self.default_post_type] posts.append((html, meta, f)) if not posts: print('warning: Nothing to publish') return posts else: raise OSError(errno.ENOENT, strerror(errno.ENOENT), fpath)
def run(self, lines): HEADER_REGEX = re.compile('\{\{inline\(list\)::\n(.*?)\n\}\}', re.DOTALL) # maybe too much sensitive def replace(m): text = m.groups()[0] md = Markdown() table = md.convert(text).replace("\n", "") return table new_lines = HEADER_REGEX.sub(replace, "\n".join(lines)) return new_lines.split("\n")
def post(self): raw_text = self.request.body unicode_raw_text = unicode(raw_text, "utf-8") md = markdown.Markdown(extensions=MARKDOWN_EXT) html_text = md.reset().convert(unicode_raw_text) # ?????? def convert_checkbox1(match): return '<li><input type="checkbox" disabled>' if match.group('checked') == ' ' \ else '<li><input type="checkbox" disabled checked>' def convert_checkbox2(match): return '<li>\n<p><input type="checkbox" disabled>' if match.group('checked') == ' ' \ else '<li>\n<p><input type="checkbox" disabled checked>' # ??img out link def convert_src(match): return 'src="' + match.group('src') + '"' def filter_xss(match): return ' ' pattern_actions = {xss_pattern1: filter_xss, xss_pattern2: filter_xss, checked_pattern1: convert_checkbox1, checked_pattern2: convert_checkbox2, src_pattern: convert_src} for pattern, action in pattern_actions.items(): html_text = re.sub(pattern, action, html_text) self.write(html_text)
def pinyin_markdown(request): return Markdown(extensions=[request.param])
def pinyin_md_no_classes(): return Markdown(extensions=['pinyin_markdown(tone_class=,erhua_class=,apostrophe_class=)'])
def pinyin_md_entities(): return Markdown(extensions=['pinyin_markdown(entities=True)'])
def __init__(self): self._extensions = [ 'codehilite(css_class=highlight)', 'markdown.extensions.tables' ] self._parser = Markdown( extensions=self._extensions )
def convert_to_html(markdown_text): md = markdown.Markdown( extensions=[ 'pymdownx.github', 'markdown.extensions.toc', ], extension_configs={ 'markdown.extensions.toc': { 'title': '??', }, }, output_format="html5" ) return md.convert(markdown_text)