Python markdown.markdown() Examples
The following are 30
code examples of markdown.markdown().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
markdown
, or try the search function
.
Example #1
Source File: helpers.py From daf-recipes with GNU General Public License v3.0 | 6 votes |
def render_markdown(data, auto_link=True, allow_html=False): ''' Returns the data as rendered markdown :param auto_link: Should ckan specific links be created e.g. `group:xxx` :type auto_link: bool :param allow_html: If True then html entities in the markdown data. This is dangerous if users have added malicious content. If False all html tags are removed. :type allow_html: bool ''' if not data: return '' if allow_html: data = markdown(data.strip()) else: data = RE_MD_HTML_TAGS.sub('', data.strip()) data = clean_html( markdown(data), strip=True, tags=MARKDOWN_TAGS, attributes=MARKDOWN_ATTRIBUTES) # tags can be added by tag:... or tag:"...." and a link will be made # from it if auto_link: data = html_auto_link(data) return literal(data)
Example #2
Source File: markdown_to_html.py From tools with MIT License | 6 votes |
def convert_markdown(in_fn): input_md = open(in_fn, mode="r", encoding="utf-8").read() html = markdown.markdown( "[TOC]\n" + input_md, extensions = [ 'pymdownx.extra', 'pymdownx.b64', 'pymdownx.highlight', 'pymdownx.emoji', 'pymdownx.tilde', 'toc' ], extension_configs = { 'pymdownx.b64': { 'base_path': os.path.dirname(in_fn) }, 'pymdownx.highlight': { 'noclasses': True }, 'toc': { 'title': 'Table of Contents' } } ) return html
Example #3
Source File: __init__.py From bioforum with MIT License | 6 votes |
def markdown(text, *args, **kwargs): """Convert a Markdown string to HTML and return HTML as a Unicode string. This is a shortcut function for `Markdown` class to cover the most basic use case. It initializes an instance of Markdown, loads the necessary extensions and runs the parser on the given text. Keyword arguments: * text: Markdown formatted text as Unicode or ASCII string. * Any arguments accepted by the Markdown class. Returns: An HTML document as a string. """ md = Markdown(*args, **kwargs) return md.convert(text)
Example #4
Source File: __init__.py From lambda-packs with MIT License | 6 votes |
def registerExtensions(self, extensions, configs): """ 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. """ for ext in extensions: if isinstance(ext, str): ext = self.build_extension(ext, configs.get(ext, [])) if isinstance(ext, Extension): # might raise NotImplementedError, but that's the extension author's problem ext.extendMarkdown(self, globals()) elif ext is not None: raise ValueError('Extension "%s.%s" must be of type: "markdown.Extension".' \ % (ext.__class__.__module__, ext.__class__.__name__)) return self
Example #5
Source File: botlistapi.py From BotListBot with MIT License | 6 votes |
def md2html(text): text = str(text) import textwrap res = Markup(markdown.markdown( textwrap.dedent(text), [ 'markdown.extensions.codehilite', 'markdown.extensions.nl2br', 'markdown.extensions.extra', 'markdown.extensions.admonition' ], extension_configs={ 'markdown.extensions.codehilite': { 'noclasses': True, 'pygments_style': 'colorful' } })) return res
Example #6
Source File: markdown.py From karrot-backend with GNU Affero General Public License v3.0 | 6 votes |
def render(text, truncate_words=None): html = markdown.markdown( text, extensions=[ EmojiExtension(emoji_index=twemoji), SuperFencesCodeExtension(), MagiclinkExtension(), DeleteSubExtension(subscript=False), Nl2BrExtension(), ] ) markdown_attrs['img'].append('class') markdown_tags.append('pre') clean_html = bleach.clean(html, markdown_tags, markdown_attrs) if truncate_words: clean_html = Truncator(clean_html).words(num=truncate_words, html=True) return clean_html
Example #7
Source File: __init__.py From lambda-packs with MIT License | 6 votes |
def markdown(text, *args, **kwargs): """Convert a markdown string to HTML and return HTML as a unicode string. This is a shortcut function for `Markdown` class to cover the most basic use case. It initializes an instance of Markdown, loads the necessary extensions and runs the parser on the given text. Keyword arguments: * text: Markdown formatted text as Unicode or ASCII string. * Any arguments accepted by the Markdown class. Returns: An HTML document as a string. """ md = Markdown(*args, **kwargs) return md.convert(text)
Example #8
Source File: docs.py From cascade-server with Apache License 2.0 | 6 votes |
def serve_document(filebase): if "\\" in filebase or "/" in filebase or "." in filebase: return Response(status=404) try: with open("docs/{}.md".format(filebase), "r") as f: html = markdown.markdown(f.read(), output_format="html5") except IOError: return Response(status=404) for open_tag, title, close_tag in re.findall("<(h[0-9])>(.*?)</(h[0-9])>", html): if open_tag != close_tag: continue chunk = "<{tag}>{contents}</{tag}>".format(tag=open_tag, contents=title) section_id = title.replace(" ", "-").lower() new_chunk = '<{tag} id="{id}">{contents}</{tag}>'.format(tag=open_tag, id=section_id, contents=title) html = html.replace(chunk, new_chunk) html = '<div class="documentation container">{}</div'.format(html) return Response(html, 200)
Example #9
Source File: helpers.py From daf-recipes with GNU General Public License v3.0 | 6 votes |
def markdown_extract(text, extract_length=190): ''' return the plain text representation of markdown encoded text. That is the texted without any html tags. If extract_length is 0 then it will not be truncated.''' if not text: return '' plain = RE_MD_HTML_TAGS.sub('', markdown(text)) if not extract_length or len(plain) < extract_length: return literal(plain) return literal( unicode( whtext.truncate( plain, length=extract_length, indicator='...', whole_word=True ) ) )
Example #10
Source File: GarbageInlineProcessors.py From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License | 6 votes |
def spotPatch(self, soup): # Replace <pre> tags on wattpad. # wp_div = soup.find_all('div', class_="panel-reading") # for item in wp_div: # Fukkit, just nuke them in general for pre in soup.find_all("pre"): pre.name = "div" contentstr = pre.encode_contents().decode("utf-8") formatted = markdown.markdown(contentstr, extensions=["mdx_linkify"]) formatted = WebRequest.as_soup(formatted) if formatted.find("html"): formatted.html.unwrap() formatted.body.unwrap() pre.replace_with(formatted) # print(pre) return soup
Example #11
Source File: abbr.py From lambda-packs with MIT License | 6 votes |
def run(self, lines): ''' Find and remove all Abbreviation references from the text. Each reference is set as a new AbbrPattern in the markdown instance. ''' new_text = [] for line in lines: m = ABBR_REF_RE.match(line) if m: abbr = m.group('abbr').strip() title = m.group('title').strip() self.markdown.inlinePatterns['abbr-%s'%abbr] = \ AbbrPattern(self._generate_pattern(abbr), title) else: new_text.append(line) return new_text
Example #12
Source File: RemarkableWindow.py From Remarkable with MIT License | 6 votes |
def on_menuitem_export_pdf_activate(self, widget): self.window.set_sensitive(False) start, end = self.text_buffer.get_bounds() text = self.text_buffer.get_text(start, end, False) text = self.text_buffer.get_text(self.text_buffer.get_start_iter(), self.text_buffer.get_end_iter(), False) dirname = os.path.dirname(self.name) text = re.sub(r'(\!\[.*?\]\()([^/][^:]*?\))', lambda m, dirname=dirname: m.group(1) + os.path.join(dirname, m.group(2)), text) try: html_middle = markdown.markdown(text, self.default_extensions) except: try: html_middle = markdown.markdown(text, self.safe_extensions) except: html_middle = markdown.markdown(text) html = self.default_html_start + html_middle + self.default_html_end self.save_pdf(html)
Example #13
Source File: tests.py From html2markdown with MIT License | 6 votes |
def test_inline_tag_content(self): """content of inline-type tags should be converted""" emptyElements = self.emptyElements for tag in html2markdown._inlineTags: if tag in emptyElements: continue testStr = '<%s style="text-decoration:line-through;">strike <strong>through</strong> some text</%s> here' % (tag, tag) expectedStr = '<%s style="text-decoration:line-through;">strike __through__ some text</%s> here' % (tag, tag) mdStr = html2markdown.convert(testStr) self.assertEqual(mdStr, expectedStr, 'Tag: {}'.format(tag)) bs = bs4.BeautifulSoup(markdown.markdown(mdStr), 'html.parser') self.assertEqual( len(bs.find_all('strong')), 1 if tag != 'strong' else 2, 'Tag: {}. Conversion: {}'.format(tag, mdStr) )
Example #14
Source File: _markdown.py From webviz-config with MIT License | 6 votes |
def __init__(self, markdown_file: Path): super().__init__() self.markdown_file = markdown_file self.html = bleach.clean( markdown.markdown( get_path(self.markdown_file).read_text(), extensions=[ "tables", "sane_lists", _WebvizMarkdownExtension(base_path=markdown_file.parent), ], ), tags=Markdown.ALLOWED_TAGS, attributes=Markdown.ALLOWED_ATTRIBUTES, styles=Markdown.ALLOWED_STYLES, ) # Workaround for upstream issue https://github.com/plotly/dash-core-components/issues/746, # where we convert void html tags from <tag> to <tag/>. self.html = re.sub("<img (.*?[^/])>", r"<img \1/>", self.html) self.html = self.html.replace("<br>", "<br/>").replace("<hr>", "<hr/>")
Example #15
Source File: app.py From MegaQC with GNU General Public License v3.0 | 6 votes |
def register_extensions(app): """ Register Flask extensions. """ cache.init_app(app) db.init_app(app) csrf_protect.init_app(app) login_manager.init_app(app) debug_toolbar.init_app(app) ma.init_app(app) json_api.init_app(app) migrate.init_app(app, db) @app.context_processor def inject_debug(): """ Make the debug variable available to templates. """ return dict(debug=app.debug, version=version) @app.template_filter() def safe_markdown(text): return jinja2.Markup(markdown.markdown(text)) return None
Example #16
Source File: common.py From PyOne with Mozilla Public License 2.0 | 6 votes |
def GetReadMe(path): # README ext='Markdown' readme,_,i=has_item(path,'README.md') if readme==False: readme,_,i=has_item(path,'readme.md') if readme==False: ext='Text' readme,_,i=has_item(path,'readme.txt') if readme==False: ext='Text' readme,_,i=has_item(path,'README.txt') if readme!=False: readme=markdown.markdown(readme, extensions=['tables','codehilite']) return readme,ext # @cache.memoize(timeout=60*5)
Example #17
Source File: text_plugin.py From lambda-packs with MIT License | 6 votes |
def markdown_and_sanitize(markdown_string): """Takes a markdown string and converts it into sanitized html. It uses the table extension; while that's not a part of standard markdown, it is sure to be useful for TensorBoard users. The sanitizer uses the allowed_tags and attributes specified above. Mostly, we ensure that our standard use cases like tables and links are supported. Args: markdown_string: Markdown string to sanitize Returns: a string containing sanitized html for input markdown """ # Convert to utf-8 whenever we have a binary input. if isinstance(markdown_string, six.binary_type): markdown_string = markdown_string.decode('utf-8') string_html = markdown.markdown( markdown_string, extensions=['markdown.extensions.tables']) string_sanitized = bleach.clean( string_html, tags=ALLOWED_TAGS, attributes=ALLOWED_ATTRIBUTES) return string_sanitized
Example #18
Source File: RemarkableWindow.py From Remarkable with MIT License | 6 votes |
def on_menuitem_preview_browser_activate(self, widget): # Create a temporary HTML file tf = tempfile.NamedTemporaryFile(delete = False) self.temp_file_list.append(tf) tf_name = tf.name text = self.text_buffer.get_text(self.text_buffer.get_start_iter(), self.text_buffer.get_end_iter(), False) dirname = os.path.dirname(self.name) text = re.sub(r'(\!\[.*?\]\()([^/][^:]*?\))', lambda m, dirname=dirname: m.group(1) + os.path.join(dirname, m.group(2)), text) try: html_middle = markdown.markdown(text, self.default_extensions) except: try: html_middle = markdown.markdown(text, extensions =self.safe_extensions) except: html_middle = markdown.markdown(text) html = self.default_html_start + html_middle + self.default_html_end tf.write(html.encode()) tf.flush() # Load the temporary HTML file in the user's default browser webbrowser.open_new_tab(tf_name)
Example #19
Source File: RemarkableWindow.py From Remarkable with MIT License | 5 votes |
def on_menuitem_export_pdf_plain_activate(self, widget): self.window.set_sensitive(False) start, end = self.text_buffer.get_bounds() text = self.text_buffer.get_text(start, end, False) text = self.text_buffer.get_text(self.text_buffer.get_start_iter(), self.text_buffer.get_end_iter(), False) try: html_middle = markdown.markdown(text, self.default_extensions) except: try: html_middle = markdown.markdown(text, self.safe_extensions) except: html_middle = markdown.markdown(text) html = html_middle self.save_pdf(html)
Example #20
Source File: RemarkableWindow.py From Remarkable with MIT License | 5 votes |
def on_menuitem_export_html_plain_activate(self, widget): # This can be re-factored. A lot of duplicated code. Migrate some functions to external .py files self.window.set_sensitive(False) start, end = self.text_buffer.get_bounds() text = self.text_buffer.get_text(start, end, False) text = self.text_buffer.get_text(self.text_buffer.get_start_iter(), self.text_buffer.get_end_iter(), False) try: html_middle = markdown.markdown(text, self.default_extensions) except: try: html_middle = markdown.markdown(text, extensions =self.safe_extensions) except: html_middle = markdown.markdown(text) html = html_middle self.save_html(html)
Example #21
Source File: helpers.py From peering-manager with Apache License 2.0 | 5 votes |
def markdown(value): """ Render text as Markdown. """ # Strip HTML tags and render Markdown html = md(strip_tags(value), extensions=["fenced_code", "tables"]) return mark_safe(html)
Example #22
Source File: __init__.py From bioforum with MIT License | 5 votes |
def markdownFromFile(*args, **kwargs): """Read markdown code from a file and write it to a file or a stream. This is a shortcut function which initializes an instance of Markdown, and calls the convertFile method rather than convert. Keyword arguments: * input: a file name or readable object. * output: a file name or writable object. * encoding: Encoding of input and output. * Any arguments accepted by the Markdown class. """ # For backward compatibility loop through positional args pos = ['input', 'output', 'extensions', 'encoding'] c = 0 for arg in args: if pos[c] not in kwargs: kwargs[pos[c]] = arg c += 1 if c == len(pos): break if len(args): warnings.warn('Positional arguments are depreacted in ' 'Markdown and will raise an error in version 2.7. ' 'Use keyword arguments only.', DeprecationWarning) md = Markdown(**kwargs) md.convertFile(kwargs.get('input', None), kwargs.get('output', None), kwargs.get('encoding', None))
Example #23
Source File: __init__.py From bioforum with MIT License | 5 votes |
def registerExtensions(self, extensions, configs): """ 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. """ for ext in extensions: if isinstance(ext, util.string_type): ext = self.build_extension(ext, configs.get(ext, {})) if isinstance(ext, Extension): ext.extendMarkdown(self, globals()) logger.debug( 'Successfully loaded extension "%s.%s".' % (ext.__class__.__module__, ext.__class__.__name__) ) elif ext is not None: raise TypeError( 'Extension "%s.%s" must be of type: "markdown.Extension"' % (ext.__class__.__module__, ext.__class__.__name__)) return self
Example #24
Source File: url_checker_async.py From msticpy with MIT License | 5 votes |
def _get_doc_links(doc_path: Path) -> Set[str]: """ Check links in an HTML or Markdown document. Parameters ---------- doc_path : str Path to the document Returns ------- Set[str] Set of links """ html_content = None try: html_content = doc_path.read_text(encoding="utf-8") except UnicodeDecodeError: html_content = doc_path.read_text(encoding="mbcs") if doc_path.suffix.casefold() == ".md": html_content = markdown.markdown(html_content) soup = BeautifulSoup(html_content, "html.parser") links = soup.find_all("a") links = {link.get("href") for link in links} links = {link for link in links if link.casefold().startswith("http")} return links
Example #25
Source File: url_checker.py From msticpy with MIT License | 5 votes |
def check_md_document(doc_path: str) -> Dict[str, UrlResult]: """ Check links in Markdown document. Parameters ---------- doc_path : str Path to the document Returns ------- Dict[str, UrlResult] Dictionary of checked links """ with open(doc_path, "r") as doc_file: body_markdown = doc_file.read() md_content = markdown.markdown(body_markdown) soup = BeautifulSoup(md_content, "html.parser") links = soup.find_all("a") page_links = {link.get("href") for link in links} checked_links: Dict[str, UrlResult] = {} print("Checking page...") for url_link in page_links: if url_link[0:4] == "http": if url_link in checked_links: print("_", end="") continue print("a", end="") result = check_url(url_link) checked_links[url_link] = result else: print("_", end="") print( f"visited_links = {len(checked_links)}", f"{len(page_links)} links in current page", ) _print_url_results(list(checked_links.values())) return checked_links
Example #26
Source File: md2conf.py From md_to_conf with MIT License | 5 votes |
def convert_comment_block(html): """ Convert markdown code bloc to Confluence hidden comment :param html: string :return: modified html string """ open_tag = '<ac:placeholder>' close_tag = '</ac:placeholder>' html = html.replace('<!--', open_tag).replace('-->', close_tag) return html
Example #27
Source File: context.py From mkdocs_macros_plugin with MIT License | 5 votes |
def format_value(value): "Properly format the value, to make it descriptive" # those classes will be processed as "dictionary type" # NOTE: using the name does nto force us to import them LISTED_CLASSES = 'Config', 'File', 'Section' # those types will be printed without question SHORT_TYPES = int, float, str, list if callable(value): # for functions docstring = get_first_para(value.__doc__) # we interpret the markdown in the docstring, # since both jinja2 and ourselves use markdown, # and we need to produce a HTML table: docstring = markdown(docstring) try: varnames = ', '.join(value.__code__.co_varnames) return "(<i>%s</i>)<br/> %s" % (varnames, docstring) except AttributeError: # code not available return docstring elif (isinstance(value, dict) or type(value).__name__ in LISTED_CLASSES): # print("Processing:", type(value).__name__, isinstance(value, SHORT_TYPES)) r_list = [] for key, value in list_items(value): if isinstance(value, SHORT_TYPES): r_list.append("%s = %s" % (key, repr(value))) else: # object or dict: write minimal info: r_list.append("<b>%s</b> [<i>%s</i>]" % (key, type(value).__name__)) return ', '.join(r_list) else: return repr(value)
Example #28
Source File: _markdown.py From webviz-config with MIT License | 5 votes |
def __init__(self, image_link_re: str, md: markdown.core.Markdown, base_path: Path): self.base_path = base_path super(_MarkdownImageProcessor, self).__init__(image_link_re, md)
Example #29
Source File: _markdown.py From webviz-config with MIT License | 5 votes |
def extendMarkdown(self, md: markdown.core.Markdown) -> None: md.inlinePatterns.register( item=_MarkdownImageProcessor(IMAGE_LINK_RE, md, self.base_path), name="image_link", priority=50, )
Example #30
Source File: fenced_code.py From lambda-packs with MIT License | 5 votes |
def run(self, lines): """ Match and store Fenced Code Blocks in the HtmlStash. """ # Check for code hilite extension if not self.checked_for_codehilite: for ext in self.markdown.registeredExtensions: if isinstance(ext, CodeHiliteExtension): self.codehilite_conf = ext.config break self.checked_for_codehilite = True text = "\n".join(lines) while 1: m = FENCED_BLOCK_RE.search(text) if m: lang = '' if m.group('lang'): lang = LANG_TAG % m.group('lang') # If config is not empty, then the codehighlite extension # is enabled, so we call it to highlite the code if self.codehilite_conf: highliter = CodeHilite(m.group('code'), linenos=self.codehilite_conf['force_linenos'][0], guess_lang=self.codehilite_conf['guess_lang'][0], css_class=self.codehilite_conf['css_class'][0], style=self.codehilite_conf['pygments_style'][0], lang=(m.group('lang') or None), noclasses=self.codehilite_conf['noclasses'][0]) code = highliter.hilite() else: code = CODE_WRAP % (lang, self._escape(m.group('code'))) placeholder = self.markdown.htmlStash.store(code, safe=True) text = '%s\n%s\n%s'% (text[:m.start()], placeholder, text[m.end():]) else: break return text.split("\n")