Manages a collection of rules used to convert HTML to Markdown
490939
function Rules (options) {
  this.options = options;
  this._keep = [];
  this._remove = [];

  this.blankRule = {
    replacement: options.blankReplacement
  };

  this.keepReplacement = options.keepReplacement;

  this.defaultRule = {
    replacement: options.defaultReplacement
  };

  this.array = [];
  for (var key in options.rules) this.array.push(options.rules[key]);
}
567860
function regexize (rulesToRemove) {
  var rulesRegexes = []
  for (var i = 0, l = rulesToRemove.length; i < l; i++) {
    if (typeof rulesToRemove[i] === 'string') {
      rulesRegexes.push(new RegExp('^\\s*' + escapeRegExp(rulesToRemove[i]) + '\\s*$'))
    } else {
      rulesRegexes.push(rulesToRemove[i])
    }
  }
  return rulesRegexes
}
194964
def compile_rules(environment):
    """"""
    e = re.escape
    rules = [
        (len(environment.comment_start_string), 'comment',
         e(environment.comment_start_string)),
        (len(environment.block_start_string), 'block',
         e(environment.block_start_string)),
        (len(environment.variable_start_string), 'variable',
         e(environment.variable_start_string))
    ]

    if environment.line_statement_prefix is not None:
        rules.append((len(environment.line_statement_prefix), 'linestatement',
                      r'^\s*' + e(environment.line_statement_prefix)))
    if environment.line_comment_prefix is not None:
        rules.append((len(environment.line_comment_prefix), 'linecomment',
                      r'(?:^|(?<=\S))[^\S\r\n]*' +
                      e(environment.line_comment_prefix)))

    return [x[1:] for x in sorted(rules, reverse=True)]
759820
function gulpHtmlLint(options) {
	let htmlLintOptions = {},
		issueFileCount = 0,
		issueCount = 0;

	options = options || {};
	options.htmllintrc = options.htmllintrc || '.htmllintrc';
	options.useHtmllintrc = options.useHtmllintrc !== false;
	options.plugins = options.plugins || [];
	options.limitFiles = options.limitFiles || (options.bail ? 1 : Number.MAX_VALUE);
	options.limitIssuesPerFile = options.limitIssuesPerFile || Number.MAX_VALUE;
	options.limitIssues = options.limitIssues || Number.MAX_VALUE;

	// load htmllint rules
	if (options.useHtmllintrc && fs.existsSync(options.htmllintrc)) {
		htmlLintOptions = JSON.parse(fs.readFileSync(options.htmllintrc, 'utf8'));
	}
	if (options.rules && typeof options.rules === 'object') {
		Object.keys(options.rules).forEach((prop) => {
			htmlLintOptions[prop] = options.rules[prop];
		});
	}

	// use plugins
	htmllint.use(options.plugins);

	return transform((file, enc, cb) => {
		if (file.isNull()) return cb(null, file);
		if (file.isStream()) return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
		if (issueFileCount >= options.limitFiles ||
			issueCount >= options.limitIssues) return cb(null, file);
		const relativeFilePath = path.relative(process.cwd(), file.path);
		htmllint(file.contents.toString(), htmlLintOptions)
			.then((issues) => {
				if (issues && issues.length) {
					let errorCount = 0,
						warningCount = 0;
					issueFileCount++;
					issueCount += issues.length;
					issues.forEach((issue) => {
						if (issue.code.indexOf('E') === 0) {
							issue.error = true;
							errorCount++;
						} else {
							issue.error = false;
							warningCount++;
						}
						issue.warning = !issue.error;
						issue.message = issue.message || htmllint.messages.renderIssue(issue);
					});
					file.htmlLint = {
						filePath: file.path,
						issues: issues.splice(0, Math.min(issues.length, options.limitIssuesPerFile)),
						relativeFilePath,
						errorCount,
						warningCount
					};
				}
				cb(null, file);
			}, () => {
				return cb(new gutil.PluginError(PLUGIN_NAME, `Could not lint html file: ${relativeFilePath}`));
			});
	});
}
409464
function processVars (markdownContent, config) {
  if (config.variables && Array.isArray(config.variables)) {
    config.variables.forEach((v) => {
      markdownContent = markdownContent.replace(new RegExp('%' + v.name + '%', 'g'), v.content);
    });
  }
  if (config.base_url) {
    markdownContent = markdownContent.replace(/%base_url%/g, config.base_url);
  }
  if (config.image_url) {
    markdownContent = markdownContent.replace(/%image_url%/g, config.image_url);
  }
  return markdownContent;
}
1123734
function getHtmlFromMarkedMarkdown(srcStr) {
	var result = parseSource(srcStr);
	var html = md.render(result);
	return html;
}
1198221
function toTableRow(rule) {
    const mark = `${rule.recommended ? "🌟" : ""}${rule.fixable ? "✒️" : ""}`
    const link = `[eslint-comments/<wbr>${rule.name}](./${rule.name}.html)`
    const description = rule.description || "(no description)"
    return `| ${link} | ${description} | ${mark} |`
}
62153
function stripMeta (markdownContent) {
  switch (true) {
    case _metaRegex.test(markdownContent):
      return markdownContent.replace(_metaRegex, '').trim();
    case _metaRegexYaml.test(markdownContent):
      return markdownContent.replace(_metaRegexYaml, '').trim();
    default:
      return markdownContent.trim();
  }
}
979311
def _filter_markdown(source, filters):
    """"""
    lines = source.splitlines()
    # Filters is a list of 'hN' strings where 1 <= N <= 6.
    headers = [_replace_header_filter(filter) for filter in filters]
    lines = [line for line in lines if line.startswith(tuple(headers))]
    return '\n'.join(lines)
737450
function(markup, targetdoc) {
		var elm, doc = this._document ||
			(this._document = document.implementation.createHTMLDocument(""));
		return gui.Guide.suspend(function() {
			doc.body.innerHTML = this._unsanitize(markup);
			elm = doc.querySelector("." + this._classname) || doc.body;
			return Array.map(elm.childNodes, function(node) {
				return (targetdoc || document).importNode(node, true);
			});
		}, this);
	}
1037412
function createCssRule(selector, ...rules) {
    let styles = document.getElementById(styleId);

    if (!styles) {
        styles = document.createElement('style');
        styles.type = 'text/css';
        styles.id = styleId;
        document.getElementsByTagName('head')[0].appendChild(styles);
    }

    const sheet = styles.sheet;

    // add each rule via 'insertRule' if that rule doesn't already exist
    // (needed due to storybook / webpack hot reloading)
    for (let i = 0; i < rules.length; i++) {
        const rule = rules[i];
        const cssText = `${selector} { ${rule}; }`;
        let found = false;

        for (let j = 0; j < sheet.cssRules.length; j++) {
            const existingRule = sheet.cssRules[j];
            if (cssText === existingRule.cssText) {
                found = true;
                break;
            }
        }

        if (!found) {
            // insertRule won't allow semicolons
            sheet.insertRule(cssText.replace(';', ''), 0);
        }
    }
}
1012954
function(rules) {
      var normalizedRules = {};
      _.each(rules, function(rule) {
        _.each(rule.apiGroups, function(apiGroup) {
          if (!normalizedRules[apiGroup]) {
            normalizedRules[apiGroup] = {};
          }
          _.each(rule.resources, function(resource) {
            normalizedRules[apiGroup][resource] = rule.verbs;
          });
        });
      });
      return normalizedRules;
    }
141673
def handle_markdown(value):
    md = markdown(
        value,
        extensions=[
            'markdown.extensions.fenced_code',
            'codehilite',
        ]
    )
    
    open_tag = '<p>'
    close_tag = '</p>'
    if md.startswith(open_tag) and md.endswith(close_tag):
        md = md[len(open_tag):-len(close_tag)]
    return mark_safe(md)
2896
function applyRules(_string, _ruleSet, _skip) {

      if(_skip.indexOf(_string.toLowerCase()) === -1) {
        var i = 0, rule;
        while(rule = _ruleSet[i++]) {
          if(_string.match(rule[0])) {
            return _string.replace(rule[0], rule[1]);
          }
        }
      }

      return _string;
    }
316087
def clean_markdown(text):
    
    result = text

    if isinstance(text, str):
        result = ''.join(
            BeautifulSoup(markdown(text), 'lxml').findAll(text=True))

    return result
295137
function mdAstToHtml(ast, lines) {
    if (lines == undefined)
        lines = [];

    // Adds each element of the array as markdown 
    function addArray(ast) {
        for (let child of ast)
            mdAstToHtml(child, lines);
        return lines;
    }

    // Adds tagged content 
    function addTag(tag, ast, newLine) {
        lines.push(startTag(tag));
        if (ast instanceof Array)
            addArray(ast); 
        else
            mdAstToHtml(ast, lines);
        lines.push(endTag(tag));
        if (newLine)
            lines.push('\r\n');
        return lines;
    }

    function addLink(url, astOrText) {
        lines.push(startTag('a', { href:url }));
        if (astOrText) {
            if (astOrText.children)
                addArray(astOrText.children);
            else
               lines.push(astOrText);
        }        
        
        lines.push(endTag('a')) ;
        return lines;
    }

    function addImg(url) {
        lines.push(startTag('img', { src:url }));
        lines.push(endTag('img')) ;
        return lines;
    }

    switch (ast.name)
    {
        case "heading": 
            {
                let headingLevel = ast.children[0];
                let restOfLine = ast.children[1];
                let h = headingLevel.allText.length;
                switch (h)
                {
                    case 1: return addTag("h1", restOfLine, true); 
                    case 2: return addTag("h2", restOfLine, true); 
                    case 3: return addTag("h3", restOfLine, true); 
                    case 4: return addTag("h4", restOfLine, true); 
                    case 5: return addTag("h5", restOfLine, true); 
                    case 6: return addTag("h6", restOfLine, true); 
                    default: throw "Heading level must be from 1 to 6"
                }
            }
        case "paragraph":   
            return addTag("p", ast.children, true);
        case "unorderedList":
            return addTag("ul", ast.children, true);
        case "orderedList":
            return addTag("ol", ast.children, true);
        case "unorderedListItem":
            return addTag("li", ast.children, true);
        case "orderedListItem":
            return addTag("li", ast.children, true);
        case "inlineUrl":
            return addLink(ast.allText, ast.allText);
        case "bold":
            return addTag("b", ast.children);
        case "italic":
            return addTag("i", ast.children);
        case "code":
            return addTag("code", ast.children);
        case "codeBlock":
            return addTag("pre", ast.children);
        case "quote":
            return addTag("blockquote", ast.children, true);
        case "link":
            return addLink(ast.children[1].allText, ast.children[0]);
        case "image":
            return addImg(ast.children[0]);
        default:
            if (ast.isLeaf)
                lines.push(ast.allText);
            else 
                ast.children.forEach(function(c) { mdAstToHtml(c, lines); });
    }
    return lines;
}
715385
def markdownify(input)
      @context.registers[:site].find_converter_instance(
        Jekyll::Converters::Markdown
      ).convert(input.to_s)
    end