How to use extendMarkdown method in Best

Best JavaScript code snippet using best

markdown.py

Source:markdown.py Github

copy

Full Screen

...13from markdown.util import etree14from ..models import Comment15register = template.Library()16class EscapeHtml(Extension):17 def extendMarkdown(self, md, md_globals):18 del md.preprocessors['html_block']19 del md.inlinePatterns['html']20class RestrictImageHosts(Extension):21 class ImageHostFilter(Treeprocessor):22 def __init__(self, md, patterns):23 super(RestrictImageHosts.ImageHostFilter, self).__init__(md)24 self.patterns = patterns25 def run(self, root):26 for image in root.findall('.//img'):27 link = image.get('src')28 if not any((pattern.match(link) for pattern in self.patterns)) and\29 'smiley' not in image.get('class', []):30 image.tag = 'a'31 image.attrib.pop('src')32 image.attrib.pop('alt')33 image.text = link34 image.set('href', link)35 def __init__(self, allowed_hosts_list):36 self.patterns = [re.compile(pattern) for pattern in allowed_hosts_list]37 super(RestrictImageHosts, self).__init__()38 def extendMarkdown(self, md, md_globals):39 md.treeprocessors.add('imagefilter', self.ImageHostFilter(md, self.patterns), '_end')40class Smileys(Extension):41 class SmileysPattern(Pattern):42 def __init__(self):43 Pattern.__init__(self, '')44 def getCompiledRegExp(self):45 self.smileys = cache.get('smiley_list')46 return re.compile(r'^(.*?):(?P<smiley>' + '|'.join(self.smileys.keys()) + '):(.*?)$')47 def handleMatch(self, m):48 smiley_name = m.group('smiley')49 el = etree.Element('img', src=self.smileys[smiley_name])50 el.set('class', 'smiley')51 return el52 def extendMarkdown(self, md, md_globals):53 md.inlinePatterns.add('smileys', self.SmileysPattern(), '_end')54 md.ESCAPED_CHARS.append(':')55class Spoilers(Extension):56 class SpoilerPattern(Pattern):57 def __init__(self):58 Pattern.__init__(self, r'(%{2})(?P<contents>.+?)\2')59 def handleMatch(self, m):60 el = etree.Element('span')61 el.set('class', 'spoiler')62 el.text = m.group('contents')63 return el64 def extendMarkdown(self, md, md_globals):65 md.inlinePatterns.add('spoilers', self.SpoilerPattern(), '_end')66 md.ESCAPED_CHARS.append('%')67class CommentRefs(Extension):68 class CommentRefPattern(Pattern):69 def __init__(self):70 Pattern.__init__(self, r'(>{2})(?P<comment_id>\d+)')71 def handleMatch(self, m):72 comment_id = int(m.group('comment_id'))73 try:74 comment = Comment.objects.get(pk=comment_id)75 el = etree.Element('a')76 el.set('href', '{}#{}'.format(77 reverse('onechan:show_post', kwargs={78 'post_id': comment.post_id79 }),80 comment_id81 ))82 el.set('class', 'comment-ref')83 el.set('data-comment-url',84 reverse('onechan:get_comment', kwargs={'comment_id': comment_id})85 )86 el.text = '>>{}'.format(comment_id)87 return el88 except Exception:89 return '>>{}'.format(comment_id)90 def extendMarkdown(self, md, md_globals):91 md.inlinePatterns.add('comment_refs', self.CommentRefPattern(), '_end')92class Autolinks(Extension):93 class LinkPreprocessor(Preprocessor):94 LINK_RE = re.compile(r'(https?://\S+)')95 def run(self, lines):96 return [self.LINK_RE.sub(r'[\1](\1)', line) for line in lines]97 def extendMarkdown(self, md, md_globals):98 md.preprocessors.add('autolinks', self.LinkPreprocessor(), '_end')99class YoutubeEmbedder(Extension):100 class YoutubeProcessor(Treeprocessor):101 YOUTUBE_RE = re.compile(r'''102 https?://(?:www\.)? # scheme and optional www prefix103 (?: # then either104 youtube\.com/watch\?.*v= # traditional url with any query args before v=<id>105 | # or106 youtu\.be/ # new 'share' url107 )108 (?P<id>[^&]+).* # finally, capture the video id and ignore irrelevant shit109 ''',110 re.VERBOSE111 )112 def run(self, root):113 for link in root.findall('.//a'):114 href = link.get('href')115 match = self.YOUTUBE_RE.match(href)116 if match:117 link.tag = 'div'118 link.attrib.pop('href')119 link.set('class', 'youtube-container')120 link.set('data-video-id', match.group('id'))121 link.text = ''122 img = etree.Element('img',123 src='https://img.youtube.com/vi/{}/mqdefault.jpg'.format(match.group('id')))124 link.append(img)125 def extendMarkdown(self, md, md_globals):126 md.treeprocessors.add('youtube', self.YoutubeProcessor(), '_end')127md = Markdown(extensions=[128 EscapeHtml(),129 RestrictImageHosts(settings.ALLOWED_IMAGE_PATTERNS),130 Smileys(),131 Spoilers(),132 CommentRefs(),133 Autolinks(),134 YoutubeEmbedder(),135])136# sorry mommy i am a dirty monkey patcher137md.parser.blockprocessors['quote'].RE = re.compile(r'(^|\n)[ ]{0,3}>(?!\>\d)[ ]?(.*)')138@register.filter139@stringfilter...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

...53 # it's a dict54 items = items.items()55 for key, value in items:56 self.setConfig(key, value)57 def _extendMarkdown(self, *args):58 """ Private wrapper around extendMarkdown. """59 md = args[0]60 try:61 self.extendMarkdown(md)62 except TypeError as e:63 if "missing 1 required positional argument" in str(e):64 # Must be a 2.x extension. Pass in a dumby md_globals.65 self.extendMarkdown(md, {})66 warnings.warn(67 "The 'md_globals' parameter of '{}.{}.extendMarkdown' is "68 "deprecated.".format(self.__class__.__module__, self.__class__.__name__),69 category=DeprecationWarning,70 stacklevel=271 )72 else:73 raise74 def extendMarkdown(self, md):75 """76 Add the various proccesors and patterns to the Markdown Instance.77 This method must be overriden by every extension.78 Keyword arguments:79 * md: The Markdown instance.80 * md_globals: Global variables in the markdown module namespace.81 """82 raise NotImplementedError(83 'Extension "%s.%s" must define an "extendMarkdown"'84 'method.' % (self.__class__.__module__, self.__class__.__name__)...

Full Screen

Full Screen

CacheLoader.js

Source:CacheLoader.js Github

copy

Full Screen

1'use strict'2/**3 * Module dependencies.4 */5const {6 path, toAbsolutePath, chalk, logger,7 datatypes: { isString, isBoolean }8} = require('@vuepress/shared-utils')9/**10 * Get cache directory and cache identifier via config.11 * @param {object} siteConfig12 * @param {object} options13 */14exports.getCacheLoaderOptions = function (siteConfig, options, cwd, isProd) {15 const defaultCacheDirectory = path.resolve(__dirname, '../../node_modules/.cache/vuepress')16 let cache = options.cache || siteConfig.cache || defaultCacheDirectory17 if (isBoolean(cache)) {18 if (cache === true) {19 cache = defaultCacheDirectory20 }21 } else if (!isString(cache)) {22 throw new Error(`expected cache option to be string or boolean, but got ${typeof cache}`)23 }24 const cacheDirectory = toAbsolutePath(cache, cwd)25 const cacheIdentifier = JSON.stringify({26 vuepress: require('../../package.json').version,27 'cache-loader': require('cache-loader/package.json').version,28 'vue-loader': require('cache-loader/package.json').version,29 isProd,30 config: (31 (32 siteConfig.markdown33 ? JSON.stringify(siteConfig.markdown)34 : ''35 )36 + (37 siteConfig.markdown && siteConfig.markdown.extendMarkdown38 ? siteConfig.markdown.extendMarkdown.toString()39 : ''40 )41 + (42 siteConfig.extendMarkdown43 ? siteConfig.extendMarkdown.toString()44 : ''45 )46 + (siteConfig.chainWebpack || '').toString()47 + (siteConfig.configureWebpack || '').toString()48 )49 })50 logger.debug('Cache directory: ' + chalk.gray(cacheDirectory))51 logger.debug('Cache identifier : ' + chalk.gray(cacheIdentifier))52 return { cacheDirectory, cacheIdentifier }...

Full Screen

Full Screen

createMarkdown.js

Source:createMarkdown.js Github

copy

Full Screen

...13 chainMarkdown && chainMarkdown(config)14 ctx.pluginAPI.applySyncOption('chainMarkdown', config)15 }16 const afterInstantiate = md => {17 extendMarkdown && extendMarkdown(md)18 ctx.pluginAPI.applySyncOption('extendMarkdown', md)19 }20 return createMarkdown(21 Object.assign(markdownConfig, {22 beforeInstantiate,23 afterInstantiate24 })25 )...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = function (eleventyConfig) {2 eleventyConfig.addPlugin(require("@11ty/eleventy-navigation"));3 eleventyConfig.addPassthroughCopy("src/css");4 eleventyConfig.addPassthroughCopy("src/img");5 eleventyConfig.addPassthroughCopy("src/js");6 eleventyConfig.addFilter("dateDisplay", require("./src/filters/dates.js"));7 eleventyConfig.addCollection("posts", function (collectionApi) {8 return collectionApi.getFilteredByGlob("./src/posts/*.md");9 });10 eleventyConfig.addCollection("tagList", require("./src/utils/getTagList.js"));11 eleventyConfig.addFilter("tagList", require("./src/utils/getTagList.js"));12 eleventyConfig.addFilter("getTags", function (item) {13 return (item.data.tags || []).filter(function (item) {14 switch (item) {15 return false;16 }17 return true;18 });19 });20 eleventyConfig.addFilter("getPosts", function (item) {21 return (item.data.posts || []).filter(function (item) {22 switch (item) {23 return false;24 }25 return true;26 });27 });28 eleventyConfig.addShortcode("readableDate", require("./src/shortcodes/readableDate.js"));29 eleventyConfig.addShortcode("postDate", require("./src/shortcodes/postDate.js"));30 eleventyConfig.addShortcode("postTime", require("./src/shortcodes/postTime.js"));31 eleventyConfig.addShortcode("postAuthor", require("./src/shortcodes/postAuthor.js"));32 eleventyConfig.addShortcode("postTags", require("./src/shortcodes/postTags.js"));33 eleventyConfig.addShortcode("postImage", require("./src/shortcodes/postImage.js"));34 eleventyConfig.addFilter("htmlDateString", (dateObj) => {35 return new Date(dateObj).toISOString().split("T")[

Full Screen

Using AI Code Generation

copy

Full Screen

1const BestMarked = require('bestmarked');2const marked = require('marked');3const renderer = new marked.Renderer();4const bestMarked = new BestMarked({5 {6 extendMarkdown: function (md) {7 return md.replace(/\[TEST\]\((.*?)\)/g, '<a href="$1">TEST</a>');8 }9 }10});11const BestMarked = require('bestmarked');12const marked = require('marked');13const renderer = new marked.Renderer();14const bestMarked = new BestMarked({15 {16 extendMarkdown: function (md) {17 return md.replace(/\[TEST\]\((.*?)\)/g, '<a href="$1">TEST</a>');18 }19 }20});21const BestMarked = require('bestmarked');22const marked = require('marked');23const renderer = new marked.Renderer();24const bestMarked = new BestMarked({25 {26 extendMarkdown: function (md) {27 return md.replace(/\[TEST\]\((.*?)\)/g, '<a href="$1">TEST</a>');28 }29 }30});31const BestMarked = require('bestmarked');32const marked = require('marked');33const renderer = new marked.Renderer();34const bestMarked = new BestMarked({35 {36 extendMarkdown: function (md) {37 return md.replace(/\[TEST\]\((.*?)\)/g, '<a href="$1">TEST</a>');38 }39 }40});

Full Screen

Using AI Code Generation

copy

Full Screen

1const BestMark = require('bestmark');2const md = new BestMark();3md.extendMarkdown(md => {4 md.use(require('markdown-it-emoji'));5});6BestMark is a [Markdown-it](

Full Screen

Using AI Code Generation

copy

Full Screen

1const BestMark = require('bestmark');2const bestmark = new BestMark({3 extendMarkdown: md => {4 md.use(require('markdown-it-attrs'));5 }6});7Extend the [markdown-it](

Full Screen

Using AI Code Generation

copy

Full Screen

1const Bestiary = require('./bestiary');2const bestiary = new Bestiary();3bestiary.extendMarkdown = function (md) {4 console.log('extendMarkdown');5};6bestiary.init();

Full Screen

Using AI Code Generation

copy

Full Screen

1const BestMark = require('bestmark');2const md = BestMark({3});4md.use(require('markdown-it-spoiler'));5md.use(require('markdown-it-container'), 'spoiler', {6 render: function (tokens, idx) {7 var m = tokens[idx].info.trim().match(/^spoiler\s+(.*)$/);8 if (tokens[idx].nesting === 1) {9 return '<details><summary>' + md.utils.escapeHtml(m[1]) + '</summary>\n';10 } else {11 return '</details>\n';12 }13 }14});15md.use(require('markdown-it-container'), 'note', {16 render: function (tokens, idx) {17 var m = tokens[idx].info.trim().match(/^note\s+(.*)$/);18 if (tokens[idx].nesting === 1) {19 return '<div class="note"><span class="note-title">' + md.utils.escapeHtml(m[1]) + '</span>\n';20 } else {21 return '</div>\n';22 }23 }24});25md.use(require('markdown-it-container'), 'tip', {26 render: function (tokens, idx) {27 var m = tokens[idx].info.trim().match(/^tip\s+(.*)$/);28 if (tokens[idx].nesting === 1) {29 return '<div class="tip"><span class="tip-title">' + md.utils.escapeHtml(m[1]) + '</span>\n';30 } else {31 return '</div>\n';32 }33 }34});35md.use(require('markdown-it-container'), 'warning', {36 render: function (tokens, idx) {37 var m = tokens[idx].info.trim().match(/^warning\s+(.*)$/);38 if (tokens[idx].nesting === 1) {39 return '<div class="warning"><span class="warning-title">' + md.utils.escapeHtml(m[1]) + '</span>\n';40 } else {41 return '</div>\n';42 }43 }44});

Full Screen

Using AI Code Generation

copy

Full Screen

1var BestMarked = require('bestmarked');2var marked = new BestMarked();3marked.extendMarkdown(function (md) {4 var renderer = new marked.Renderer();5 renderer.link = function (href, title, text) {6 return '<a target="_blank" href="' + href + '" title="' + title + '">' + text + '</a>';7 };8 var linkRenderer = renderer.link;9 var googleLinkRenderer = function (href, title, text) {10 if (text === 'Google') {11 }12 return linkRenderer(href, title, text);13 };14 md.renderer.link = googleLinkRenderer;15});16 if (err) {17 return console.log(err);18 }19 console.log(content);20});21var BestMarked = require('bestmarked');22var marked = new BestMarked();23marked.extendRenderer(function (renderer) {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Best automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful