Traverse the whole document and replace <a>TYPENAME</a> with: <a href="../api/symbols/TYPENAME.html">TYPENAME</a> and <a>TYPENAME.MEMBERNAME</a> with: <a href="../api/symbols/TYPENAME.html#MEMBERNAME">TYPENAME.MEMBERNAME</a>
2913
function goDoc() {
  _traverseDOM(document);
  // add standard footer
  var ftr = document.createElement("div");
  ftr.className = "footer";
  var msg = "Copyright &copy; 1998-2015 by Northwoods Software Corporation.";
  if (go && go.version) {
    msg = "GoJS&reg; version " + go.version + ". " + msg;
  }
  ftr.innerHTML = msg;
  document.body.appendChild(ftr);
}
42758
def get_a(html, find=''):
    """"""
    links = []
    for a in html.find_all('a'):
        if a.get('href').find(find) != -1:
            links.append(a)
    return links
1157553
def _replace_docstring_header(paragraph):
    """"""

    # Replace Markdown headers in docstrings with light headers in bold.
    paragraph = re.sub(_docstring_header_pattern,
                       r'*\1*',
                       paragraph,
                       )

    paragraph = re.sub(_docstring_parameters_pattern,
                       r'\n* `\1` (\2)\n',
                       paragraph,
                       )

    return paragraph
936662
def serialize_link(ctx, document, elem, root):
    

    _a = etree.SubElement(root, 'a')

    for el in elem.elements:
        _ser = ctx.get_serializer(el)

        if _ser:
            _td = _ser(ctx, document, el, _a)
        else:
            if isinstance(el, doc.Text):
                children = list(_a)

                if len(children) == 0:
                    _text = _a.text or u''

                    _a.text = u'{}{}'.format(_text, el.value())
                else:
                    _text = children[-1].tail or u''

                    children[-1].tail = u'{}{}'.format(_text, el.value())
   
    if elem.rid in document.relationships[ctx.options['relationship']]:
        _a.set('href', document.relationships[ctx.options['relationship']][elem.rid].get('target', ''))

    fire_hooks(ctx, document, elem, _a, ctx.get_hook('a'))

    return root
1235413
def markup(str, remove_para=false)
      return '' unless str
      unless defined? @markup
        @markup = SM::SimpleMarkup.new

        # class names, variable names, or instance variables
        @markup.add_special(/(
                               \w+(::\w+)*[.\#]\w+(\([\.\w+\*\/\+\-\=\<\>]+\))?  # A::B.meth(**) (for operator in Fortran95)
                             | \#\w+(\([.\w\*\/\+\-\=\<\>]+\))?  #  meth(**) (for operator in Fortran95)
                             | \b([A-Z]\w*(::\w+)*[.\#]\w+)  #    A::B.meth
                             | \b([A-Z]\w+(::\w+)*)       #    A::B..
                             | \#\w+[!?=]?                #    #meth_name 
                             | \b\w+([_\/\.]+\w+)*[!?=]?  #    meth_name
                             )/x, 
                            :CROSSREF)

        # external hyperlinks
        @markup.add_special(/((link:|https?:|mailto:|ftp:|www\.)\S+\w)/, :HYPERLINK)

        # and links of the form  <text>[<url>]
        @markup.add_special(/(((\{.*?\})|\b\S+?)\[\S+?\.\S+?\])/, :TIDYLINK)
#        @markup.add_special(/\b(\S+?\[\S+?\.\S+?\])/, :TIDYLINK)

      end
      unless defined? @html_formatter
        @html_formatter = HyperlinkHtml.new(self.path, self)
      end

      # Convert leading comment markers to spaces, but only
      # if all non-blank lines have them

      if str =~ /^(?>\s*)[^\#]/
        content = str
      else
        content = str.gsub(/^\s*(#+)/)  { $1.tr('#',' ') }
      end

      res = @markup.convert(content, @html_formatter)
      if remove_para
        res.sub!(/^<p>/, '')
        res.sub!(/<\/p>$/, '')
      end
      res
    end
460755
def format_hyperlink( val, hlx, hxl, xhl ):
    
    if '<a href="' in str(val) and hlx != '<a href="':
        val = val.replace('<a href="', hlx).replace('">', hxl, 1).replace('</a>', xhl) 

    return val
356661
def anchor
      name, anchor_mark = @data.split(/,\s*/o, 2)
      anchor_mark = "_" if (anchor_mark.nil? or anchor_mark.empty?)
      HtmlElement.create("a", anchor_mark,
                         "name" => name,
                         "href" => "#" + name)
    end
1347590
function(articleContent) {
    var baseURI = this._doc.baseURI;
    var documentURI = this._doc.documentURI;
    function toAbsoluteURI(uri) {
      // Leave hash links alone if the base URI matches the document URI:
      if (baseURI == documentURI && uri.charAt(0) == "#") {
        return uri;
      }
      // Otherwise, resolve against base URI:
      try {
        return new URL(uri, baseURI).href;
      } catch (ex) {
        // Something went wrong, just return the original:
      }
      return uri;
    }

    var links = articleContent.getElementsByTagName("a");
    this._forEachNode(links, function(link) {
      var href = link.getAttribute("href");
      if (href) {
        // Replace links with javascript: URIs with text content, since
        // they won't work after scripts have been removed from the page.
        if (href.indexOf("javascript:") === 0) {
          var text = this._doc.createTextNode(link.textContent);
          link.parentNode.replaceChild(text, link);
        } else {
          link.setAttribute("href", toAbsoluteURI(href));
        }
      }
    });

    var imgs = articleContent.getElementsByTagName("img");
    this._forEachNode(imgs, function(img) {
      var src = img.getAttribute("src");
      if (src) {
        img.setAttribute("src", toAbsoluteURI(src));
      }
    });
  }
30657
def special_links_replace(text, urls):
    '''
    
    '''
    match_number = r'([A-Za-z0-9]+)' + r'(\+*)'
    reference_list = [(r'regulations:article:' + match_number, urls['regulations']),
                      (r'regulations:regulation:' + match_number, urls['regulations']),
                      (r'guidelines:article:' + match_number, urls['guidelines']),
                      (r'guidelines:guideline:' + match_number, urls['guidelines']),
                     ]
    anchor_list = [(r'regulations:contents', urls['regulations'] + r'#contents'),
                   (r'guidelines:contents', urls['guidelines'] + r'#contents'),
                   (r'regulations:top', urls['regulations'] + r'#'),
                   (r'guidelines:top', urls['guidelines'] + r'#'),
                   (r'link:pdf', urls['pdf'] + '.pdf'),
                  ]
    retval = text
    for match, repl in reference_list:
        retval = re.sub(match, repl + r'#\1\2', retval)
    for match, repl in anchor_list:
        retval = re.sub(match, repl, retval)
    return retval
259912
function getTOC(document) {
  var content = "";
  if (document.generateContentsCallback) {
    var callbackContent = document.generateContentsCallback(document.filesForTOC);
    content = markupFiles.getContents(document, callbackContent);
  } else {
    content = markupFiles.getContents(document);
  }
  return replacements(document, replacements(document, content));
}
791671
function fixLink (name, str) {
  /* In 6.x some API start with `xpack.` when in master they do not. We
   * can safely ignore that for link generation. */
  name = name.replace(/^xpack\./, '')
  const override = LINK_OVERRIDES[name]
  if (override) return override
  if (!str) return ''
  /* Replace references to the guide with the attribute {ref} because
   * the json files in the Elasticsearch repo are a bit of a mess. */
  str = str.replace(/^.+guide\/en\/elasticsearch\/reference\/[^/]+\/([^./]*\.html(?:#.+)?)$/, '{ref}/$1')
  str = str.replace(/frozen\.html/, 'freeze-index-api.html')
  str = str.replace(/ml-file-structure\.html/, 'ml-find-file-structure.html')
  str = str.replace(/security-api-get-user-privileges\.html/, 'security-api-get-privileges.html')

  return str
}
16301
static function convertWordFootnotes() {

		if ( ! current_user_can( 'edit_posts' ) || ! check_ajax_referer( 'pb-footnote-convert', false, false ) ) {
			static::ajaxFailure( __( 'Invalid permissions.', 'pressbooks' ) );
			return;
		}

		$html = urldecode( stripslashes( $_POST['content'] ) );

		/**
		 * Regular expression tip:
		 * (?: ), in contrast to ( ), is used to avoid capturing text.
		 *
		 * A $pattern must capture:
		 *  [0] => ... full capture ...
		 *  [1] => #_ftnref130
		 *  [2] => 130
		 *  [3] => ... the text we want to move ...
		 *
		 * Known MS Word variations:
		 *  href="#_ftn123" (-> #_ftnref123)
		 *  href="#_edn123" (-> #_ednref123)
		 *  href="/Users/foo/Documents/bar/9781426766497.doc#_ftn123" (-> .doc#_ftnref123)
		 *  href="/Users/foo/Documents/bar/9781426766497.docx#_edn123" (-> .docx#_ednref123)
		 *
		 * Known Libre Office variations:
		 *  href="#sdfootnote123sym" (-> #sdfootnote123anc)
		 */
		$patterns = [
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(#_ftnref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](#_ftnref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(#_ednref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](#_ednref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(#sdfootnote([0-9]+)anc)["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // Libre Office
		];

		/**
		 * A $replacer must be in the same position as a corresponding $pattern above,
		 * use __REPLACE_ME__ to substitute for what we don't know yet.
		 */
		$replacers = [
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(?:#_ftn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](?:#_ftn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(?:#_edn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](?:#_edn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(?:#sdfootnote__REPLACE_ME__sym)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // Libre Office
		];

		$footnotes = [];
		$find = [];
		$replace = [];

		foreach ( $patterns as $i => $pattern ) {

			preg_match_all( $pattern, $html, $footnotes, PREG_SET_ORDER );

			foreach ( $footnotes as $footnote ) {

				$tmp = wp_kses(
					$footnote[3], [
						'b' => [],
						'em' => [],
						'i' => [],
						'strong' => [],
					]
				);
				$tmp = \Pressbooks\Sanitize\remove_control_characters( $tmp );
				$tmp = trim( preg_replace( '/\s+/', ' ', $tmp ) ); // Normalize white spaces

				$find[] = str_replace( '__REPLACE_ME__', preg_quote( $footnote[2] ), $replacers[ $i ] );
				$replace[] = '[footnote]' . $tmp . '[/footnote]';
			}

			// Remove originals when done
			$find[] = $pattern;
			$replace[] = '&hellip;</div>';
		}

		// Twerk it
		$html = preg_replace( $find, $replace, $html );

		// Important, complex regular expressions have been known to, literally, crash PHP.
		// When testing, make sure this function exits as expected.

		// Send back JSON
		header( 'Content-Type: application/json' );
		$json = wp_json_encode(
			[
				'content' => $html,
			]
		);
		echo $json;

		wp_die();
	}
601055
def _from_docstring_md(doc):
    

    def format_fn(line, status):
        """ format function """

        def fix_tags(line):
            # In markdown we need to escape < > and & for display
            # but we don't want to do this is the value is quoted
            # by backticks ``

            def fn(match):
                # swap matched chars
                found = match.group(1)
                if found == "<":
                    return "&lt;"
                if found == ">":
                    return "&gt;"
                if found == "&":
                    return "&amp;"
                return match.group(0)

            return re_from_tag.sub(fn, line)

        if re_from_data.match(line):
            line = re_from_data.sub(r"**\1** ", line)
            status["add_line"] = True
        line = re_from_defaults.sub(r"*\1*", line)
        if status["listing"]:
            # parameters
            if re_from_param.match(line):
                m = re_from_param.match(line)
                line = "  - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
            # status items
            elif re_from_status.match(line):
                m = re_from_status.match(line)
                line = "  - `{}` {}".format(m.group(1), fix_tags(m.group(3)))
            # bullets
            elif re_from_item.match(line):
                line = re_from_item.sub(r"  -", fix_tags(line))
            # is continuation line
            else:
                line = fix_tags(line)
                line = " " * 4 + line.lstrip()
        else:
            line = fix_tags(line)
        return line

    return _reformat_docstring(doc, format_fn, code_newline="\n")
1324493
def pygmentify(value, **kwargs):
    """"""
    soup = BeautifulSoup(value, 'html.parser')
    for pre in soup.find_all('pre'):

        # Get code
        code = ''.join([to_string(item) for item in pre.contents])
        code = code.replace('&lt;', '<')
        code = code.replace('&gt;', '>')
        code = code.replace('&#39;', "'")
        code = code.replace('&quot;', '"')
        code = code.replace('&amp;', '&')

        # Get lexer by language
        class_list = pre.get('class', [])
        lexers = []
        options = {
            'stripall': True
        }

        # Collect all found lexers
        for c in class_list:
            try:
                lexers.append(get_lexer_by_name(c, **options))
            except ClassNotFound:
                pass

        # Get first lexer match or none
        try:
            lexer = lexers[0]
        except IndexError:
            lexer = None

        # If no lexer, try guessing
        if lexer is None:
            try:
                lexer = guess_lexer(pre.text, **options)
                class_list += [alias for alias in lexer.aliases]
            except ClassNotFound:
                pass

        if lexer is not None:

            # Get formatter
            formatter = HtmlFormatter(**kwargs)

            # Highlight code
            highlighted = highlight(code, lexer, formatter)
            class_string = ' '.join([c for c in class_list])
            highlighted = highlighted.replace(
                '<div class="%s"><pre>' % kwargs['cssclass'],
                '<div class="%s"><pre class="%s">' % (kwargs['cssclass'], class_string)
            )
            pre.replace_with(highlighted)

    return soup.decode(formatter=None).strip()
224218
def process_markdown_inside_elements(doc)
      # find span elements or elements with 'markdown' attribute
      elts = @fragment.css("[markdown]")

      d = @fragment.children.first
      if d && HTML_INLINE_ELEMS.include?(d.name)
        elts << d unless d.attribute('markdown')
        elts += span_descendents(d)
      end

      elts.each do |e|
        how = e['markdown']
        e.remove_attribute('markdown')

        next if "0" == how # user requests no markdown parsing inside
        parse_blocks = (how == 'block') || BLOCK_TAGS.include?(e.name)

        # Select all text children of e
        e.xpath("./text()").each do |original_text|
          s = MaRuKu::Out::HTML.escapeHTML(original_text.text)
          unless s.strip.empty?
            parsed = parse_blocks ? doc.parse_text_as_markdown(s) : doc.parse_span(s)

            # restore leading and trailing spaces
            padding = /\A(\s*).*?(\s*)\z/.match(s)
            parsed = [padding[1]] + parsed + [padding[2]] if padding

            el = doc.md_el(:dummy, parsed)

            # Nokogiri collapses consecutive Text nodes, so replace it by a dummy element
            guard = Nokogiri::XML::Element.new('guard', @fragment)
            original_text.replace(guard)
            el.children_to_html.each do |x|
              guard.before(x.to_s)
            end
            guard.remove
          end
        end
      end
    end
97928
function replaceLink(str, targets) {
  return str.replace(/\{@link\s+([^}]+)\}/g, function(full, link) {
    if (link in targets) {
      return util.format('[%s](%s)', link, targets[link]);
    } else if (link.match(/^(https?:)?\/\//)) {
      return util.format('[%s](%s)', link, link);
    }
    return link;
  });
}
777543
function replace(content, filename) {
    var dirname = nps.dirname(filename)

    return content.replace(
      new RegExp(
        '(^\\s*)' + prefix + '\\s*(.+?)\\s*' + suffix + '(\\s*\\n?)$',
        'gm'
      ),
      // /@\s*(.+?)\s*@/g,
      function(m, preappend, path, newlineOrNull) {
        var currLink = path.trim()
        var fullpath = ''

        // link::[why-need-require]../refs/why-need-require.md
        if (disableValue !== 'link' && currLink.startsWith('link::')) {
          var title = ''
          path = ''

          if (/^link::\[(.+?)\](.+)/.test(currLink)) {
            title = RegExp.$1
            path = RegExp.$2
            title = title && title.trim() ? title.trim() : path
          } else if (/^link::(.+)/.test(currLink)) {
            title = RegExp.$1
            path = RegExp.$1
          }

          fullpath = checkPath(path, dirname, selfFilename, true, alias)

          if (fullpath) {
            var link = findLink(filesMap, fullpath)
            if (link !== false) {
              return preappend + '[' + title + '](' + link + ')' + newlineOrNull
            }
          }
        }

        if (disableValue !== 'file-content') {
          fullpath = checkPath(currLink, dirname, filename, false, alias)
          if (fullpath) {
            var fileContent = fs.readFileSync(fullpath).toString()
            if (deep) {
              fileContent = replace(fileContent, fullpath)
            }

            return fileContent + newlineOrNull
          }
        }

        return m
      }
    )
  }