Adapted from https://github.com/markdown-it/markdown-it/blob/fbc6b0fed563ba7c00557ab638fd19752f8e759d/docs/architecture.md
771102
function findFirstMatchingConfig (link, configs) {
  var i, config
  var href = link.attrs[link.attrIndex('href')][1]

  for (i = 0; i < configs.length; ++i) {
    config = configs[i]

    // if there is no pattern, config matches for all links
    // otherwise, only return config if href matches the pattern set
    if (!config.pattern || new RegExp(config.pattern).test(href)) {
      return config
    }
  }
}
874537
function emojiPlugin (md) {
  md.use(markdownitEmoji, {
    defs: customEmojis,
    shortcuts: shortcuts,
  });

  md.renderer.rules.emoji = function markdownEmojiRules (token, idx) {
    var src;
    var style;
    var emoji = token[idx].markup;

    emoji = parseEmoji(emoji);

    src = 'https://s3.amazonaws.com/habitica-assets/cdn/emoji/' + emoji + '.png';
    style = 'height: 1.5em; width: 1.5em';

    return '<img class="habitica-emoji" style="' + style + '" src="' + src + '" alt="' + emoji + '">';
  };
}
1051872
function(markup) {

        if (!markup) return undefined;

        var fragment = markup.fragment;
        if (!(markup.fragment instanceof DocumentFragment) || !markup.fragment.hasChildNodes()) throw new Error('dia.LinkView: invalid label markup.');

        var vNode;
        var childNodes = fragment.childNodes;

        if ((childNodes.length > 1) || childNodes[0].nodeName.toUpperCase() !== 'G') {
            // default markup fragment is not wrapped in <g />
            // add a <g /> container
            vNode = V('g').append(fragment);
        } else {
            vNode = V(childNodes[0]);
        }

        vNode.addClass('label');

        return { node: vNode.node, selectors: markup.selectors };
    }
1090248
function(markup) {
		markup = markup || "";
		return gui.Guide.suspend(function() {
			var doc = document.implementation.createHTMLDocument("");
			if (markup.toLowerCase().contains("<!doctype")) {
				try {
					doc.documentElement.innerHTML = markup;
				} catch (ie9exception) {
					doc = new ActiveXObject("htmlfile");
					doc.open();
					doc.write(markup);
					doc.close();
				}
			} else {
				doc.body.innerHTML = markup;
			}
			return doc;
		});
	}
133907
function Markdownify_Extra($linksAfterEachParagraph = MDFY_LINKS_EACH_PARAGRAPH, $bodyWidth = MDFY_BODYWIDTH, $keepHTML = MDFY_KEEPHTML) {
    parent::__construct($linksAfterEachParagraph, $bodyWidth, $keepHTML);

    ### new markdownable tags & attributes
    # header ids: # foo {bar}
    $this->isMarkdownable['h1']['id'] = 'optional';
    $this->isMarkdownable['h2']['id'] = 'optional';
    $this->isMarkdownable['h3']['id'] = 'optional';
    $this->isMarkdownable['h4']['id'] = 'optional';
    $this->isMarkdownable['h5']['id'] = 'optional';
    $this->isMarkdownable['h6']['id'] = 'optional';
    # tables
    $this->isMarkdownable['table'] = array();
    $this->isMarkdownable['th'] = array(
      'align' => 'optional',
    );
    $this->isMarkdownable['td'] = array(
      'align' => 'optional',
    );
    $this->isMarkdownable['tr'] = array();
    array_push($this->ignore, 'thead');
    array_push($this->ignore, 'tbody');
    array_push($this->ignore, 'tfoot');
    # definition lists
    $this->isMarkdownable['dl'] = array();
    $this->isMarkdownable['dd'] = array();
    $this->isMarkdownable['dt'] = array();
    # footnotes
    $this->isMarkdownable['fnref'] = array(
      'target' => 'required',
    );
    $this->isMarkdownable['footnotes'] = array();
    $this->isMarkdownable['fn'] = array(
      'name' => 'required',
    );
    $this->parser->blockElements['fnref'] = false;
    $this->parser->blockElements['fn'] = true;
    $this->parser->blockElements['footnotes'] = true;
    # abbr
    $this->isMarkdownable['abbr'] = array(
      'title' => 'required',
    );
    # build RegEx lookahead to decide wether table can pe parsed or not
    $inlineTags = array_keys($this->parser->blockElements, false);
    $colContents = '(?:[^<]|<(?:'.implode('|', $inlineTags).'|[^a-z]))+';
    $this->tableLookaheadHeader = '{
    ^\s*(?:<thead\s*>)?\s*                               # open optional thead
      <tr\s*>\s*(?:                                    # start required row with headers
        <th(?:\s+align=("|\')(?:left|center|right)\1)?\s*>   # header with optional align
        \s*'.$colContents.'\s*                       # contents
        </th>\s*                                     # close header
      )+</tr>                                          # close row with headers
    \s*(?:</thead>)?                                     # close optional thead
    }sxi';
    $this->tdSubstitute = '\s*'.$colContents.'\s*        # contents
          </td>\s*';
    $this->tableLookaheadBody = '{
      \s*(?:<tbody\s*>)?\s*                            # open optional tbody
        (?:<tr\s*>\s*                                # start row
          %s                                       # cols to be substituted
        </tr>)+                                      # close row
      \s*(?:</tbody>)?                                 # close optional tbody
    \s*</table>                                          # close table
    }sxi';
  }
1178120
def markdown_composer(method, options = {})
      render(partial:"admin/shared/forms/markdown_composer", locals: {
        f: self,
        method: method,
        options: options,
      })
    end
389027
function markdown(text, inline) {
    var r;

    if (text !== undefined)
      r = md_conrefs.replaceConref(text);

    else
      r = "";

    r = namp(r).html;

    // inline markdown means to strip enclosing tag, which in this case is <p>
    if (inline === true) {
        r = r.slice(3, -5);
    }

    // FIXME
    // desugar [[foo#bar]] tokens into local links
    // N.B. in order to not apply conversion in <code> blocks,
    // we first store replace code blocks with nonces
    var codes = {};
    r = r.replace(/(<code>[\s\S]*?<\/code>)/g, function (all, def) {
      var nonce = Math.random().toString().substring(2);
      codes[nonce] = def;
      return '@-=@=-@' + nonce + '@-=@=-@';
    });

    // convert [[link]] to links
    r = r.replace(/\[\[([\s\S]+?)\]\]/g, function (all, def) {
      def = def.split(/\s+/);
      id = def.shift();
      // invalid references don't produce links
      /*if (!list[id]) {// it's in a different file--list only refers to current page
          obj = fullList[id];

          if (obj === undefined) { // it might be global
              obj = {};
              obj.id = id;
          }
      }*/
      //else {
          obj = list[id];
      //}

      var obj = _.extend({name: def.join(' ') || id, globalId: id}, list[id]);
      obj.name = def.join(' ') || id;

      // lame, but I'm tired of writing stuff like [[child_process.fork `child_process.fork()`]]
      // If I didn't do this, it'd come out as an unstyled link
      if (def.length == 0) {
        if (obj.type === undefined && additionalObjsJSON[obj.name] === undefined && obj.name !== "Mixed") {
          console.error("Error".red + ": you tried to create a short link to an object that doesn't exist!");
          console.error(obj);
        } 

        if (additionalObjsJSON[obj.name] !== undefined)
          obj.name = "<code>" + obj.name + "</code>";
        else if (obj.type && obj.type !== "class" && obj.type.indexOf("property") < 0)
          obj.name = "<code>" + obj.name + "()</code>";
        else
          obj.name = "<code>" + obj.name + "</code>";
      }

      return link(obj, ['link-short'], true);
    });

    // restore code blocks, given previously stored nonces
    r = r.replace(/@-=@=-@(\d+)@-=@=-@/g, function (all, nonce) {
      return codes[nonce];
    });

    return r;
  }
490133
function generatePrismicDocuments(config) {
  return prismic.getAPI(config.apiEndpoint, { accessToken: config.accessToken })
    .then(api => (prismic.getEverything(api, null, ``, _.flatMap(config.collections, (val, key) => (`my.${key}.${val.sortBy}${val.reverse ? ` desc` : ``}`)))))
    .then(res => {
      util.log(util.colors.blue(`[prismic]`), `Fetched a total of ${res.results.length} documents`);
      if (res.results.length) res.results.forEach(doc => util.log(util.colors.blue(`[prismic]`), `Fetched document [${doc.type}]: ${doc.slug}`));
      const documents = prismic.reduce(res.results, false, config);

      // Populate config metadata with retrieved documents.
      if (!config.metadata) config.metadata = { $data: {} };
      _.merge(config.metadata.$data, documents);

      for (let docType in documents) {
        const c = _.get(config, `collections.${docType}`);

        if (c && c.permalink) {
          const subdir = `.prismic/${docType}`;
          const dir = path.join(path.join(config.base || ``, config.src || ``), subdir);
          c.pattern = path.join(subdir, `**/*`);

          documents[docType].forEach(doc => {
            const filename = `${doc.uid || _.kebabCase(doc.slug)}.html`;
            const frontMatter = yaml.stringify(_.omit(doc, [`next`, `prev`]));
            fs.mkdirsSync(dir);
            fs.writeFileSync(path.join(dir, filename), `---\n${frontMatter}---\n`);
          });
        }
      }

      return;
    });
}
391850
function() {
      var objects = this.getObjects();
      var markup = [
        '<g ',
          'width="', this.width, '" ',
          'height="', this.height, '" ',
          'style="', this.getSvgStyles(), '" ',
          'transform="', this.getSvgTransform(), '" ',
        '>'
      ];

      for (var i = 0, len = objects.length; i < len; i++) {
        markup.push(objects[i].toSVG());
      }
      markup.push('</g>');

      return markup.join('');
    }
600437
def html_from_markdown(markdown):
    

    if login:
        r = requests.get(gh_url+"/rate_limit", auth=login.auth())
        if r.status_code >= 400:
            if r.status_code != 401:
                err = RequestError('Bad HTTP Status Code: %s' % r.status_code)
                raise err
            if verbose:
                sys.stderr.write('Unauthorized. Proceeding without login...\n')
            login.devalue()

    headers = {'content-type': 'text/plain', 'charset': 'utf-8'}

    r = requests.post(gh_url + "/markdown/raw", data=markdown.encode('utf-8'),
                      auth=login.auth(), headers=headers)
    if r.status_code >= 400 and r.status_code != 403:
            err = RequestError('Bad HTTP Status Code: %s' % r.status_code)
            raise err

    if verbose:
        sys.stderr.write("%s requests remaining, resets in %d minutes\n"
                         % rate_limit_info())
    return r.text
1085657
def determine_markdown_renderer
      @markdown = if installed?('github/markdown')
        GitHubWrapper.new(@content)
      elsif installed?('redcarpet/compat')
        Markdown.new(@content, :fenced_code, :safelink, :autolink)
      elsif installed?('redcarpet')
        RedcarpetCompat.new(@content)
      elsif installed?('rdiscount')
        RDiscount.new(@content)
      elsif installed?('maruku')
        Maruku.new(@content)
      elsif installed?('kramdown')
        Kramdown::Document.new(@content)
      elsif installed?('bluecloth')
        BlueCloth.new(@content)
      end
    end
368072
@Override
    public MarkupDocBuilder apply(MarkupDocBuilder markupDocBuilder, PathsDocument.Parameters params) {
        Map<String, Path> paths = params.paths;
        if (MapUtils.isNotEmpty(paths)) {
            applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEFORE, markupDocBuilder));
            buildPathsTitle(markupDocBuilder);
            applyPathsDocumentExtension(new Context(Position.DOCUMENT_BEGIN, markupDocBuilder));
            buildsPathsSection(markupDocBuilder, paths);
            applyPathsDocumentExtension(new Context(Position.DOCUMENT_END, markupDocBuilder));
            applyPathsDocumentExtension(new Context(Position.DOCUMENT_AFTER, markupDocBuilder));
        }
        return markupDocBuilder;
    }
611023
function() {
  this.colon = false;
  HelpDocument.apply(this, arguments);
  this.format = fmt.MARKDOWN_FORMAT;
  this.vanilla = true;
  this.useCustom = true;
  // disable columns
  this.use = false;
  var format = '* `%s`: %s';
  var overrides = {
    synopsis: '```synopsis\n%s\n```'
  }
  this.markdown = {};
  var conf = this.conf.markdown || {}, i, key;
  var formats = conf.formats || {};
  for(i = 0;i < this.sections.length;i++) {
    key = this.sections[i];
    this.markdown[key] = formats[key] || overrides[key] || format;
  }
}
381877
def markdown2html(markdown_text):
    '''
    
    '''
    html = markdown.markdown(
        markdown_text,
        extensions=[
            WikiLinkExtension(base_url='/wiki/', end_url=''),
            'markdown.extensions.extra',
            'markdown.extensions.toc',
            'markdown.extensions.codehilite',
            'markdown.extensions.meta'
        ]
    )
    han_biaodians = ['。', '，', '；', '、', '！', '？']
    for han_biaodian in han_biaodians:
        html = html.replace(han_biaodian + '\n', han_biaodian)
    return tornado.escape.xhtml_escape(html)
314647
function (markdownString) {
                    var nonGreedyAllMatcherMultiLine = '(.|\r|\n)*?';
                    var matchIgnoredEmoji = new RegExp(
                        '<!--\\s*ignore:advanced-emoji:start\\s*-->' +
                        nonGreedyAllMatcherMultiLine +
                        '<!--\\s*ignore:advanced-emoji:end\\s*-->',
                        'g');
                    return markdownString.replace(matchIgnoredEmoji, function (match) {
                        namedEmoji.forEach(function(emojiCode) {
                            match = match.replace(new RegExp(':' + emojiCode + ':', 'g'), '::ignore-' + emojiCode.replace(/:/g, '') + '-ignore::');
                        });
                        return match;
                    });
                }
911538
function footnoteTokensToMeta(tokens, md) {
  return tokens
    .map((token, i) => { return token.type === 'footnote_open' ? i : -1; })
    .filter(i => i >= 0)
    .map((i) => {
      const inlineToken = tokens[i + 2];
      assert(inlineToken.type === 'inline');
      const anchorToken = tokens[i + 3];
      assert(anchorToken.type === 'footnote_anchor');

      const content = md.renderer.render([inlineToken], md.options, {});
      const id = anchorToken.meta.id + 1;
      const meta = Object.assign({}, anchorToken.meta, { id });
      return Object.assign({}, { content }, meta);
    });
}
426677
function getForwardedAttributes( section ) {

		var attributes = section.attributes;
		var result = [];

		for( var i = 0, len = attributes.length; i < len; i++ ) {
			var name = attributes[i].name,
				value = attributes[i].value;

			// disregard attributes that are used for markdown loading/parsing
			if( /data\-(markdown|separator|vertical|notes)/gi.test( name ) ) continue;

			if( value ) {
				result.push( name + '="' + value + '"' );
			}
			else {
				result.push( name );
			}
		}

		return result.join( ' ' );

	}