/* Transform normal links and images into references and definitions,
replaces the current node, and adds a definition if needed.
351860
function factory(root, definitions, existing) {
  var id = 0

  return one

  /* Transform a normal link/image based on bound
   * `definitions`. */
  function one(node, index, parent) {
    var url = node.url
    var title = node.title
    var replacement
    var identifier
    var titles
    var definition

    if (own.call(definitions, url)) {
      titles = definitions[url]
    } else {
      titles = {}
      definitions[url] = titles
    }

    if (own.call(titles, title)) {
      identifier = titles[title].identifier
    } else {
      do {
        identifier = String(++id)
      } while (existing.indexOf(identifier) !== -1)

      definition = {
        type: 'definition',
        identifier: identifier,
        title: title,
        url: url
      }

      titles[title] = definition

      root.children.push(definition)
    }

    replacement = {
      type: node.type + 'Reference',
      identifier: identifier,
      referenceType: 'full'
    }

    if (node.type === 'image') {
      replacement.alt = node.alt
    } else {
      replacement.children = node.children
    }

    parent.children[index] = replacement
  }
}
1228169
function renameNodes(nodes, sourcePath, opts, mappings) {
  return nodes.map(function(node) {
    // Process CSS node
    if (node.type === 'class') {
      // Process "class" node
      var orgValue = node.value,
          newValue = renameClassNode(node.value, sourcePath, opts);
      // Edit node and store mapping of classname renaming
      node.value = mappings[orgValue] = newValue;
    } else if (node.type === 'pseudo' && node.value === ':not') {
      // Process ":not([selector])" pseudo node
      renameNodes(node.nodes, sourcePath, opts, mappings);
    } else if (node.type === 'selector') {
      // Rename selector nodes
      renameNodes(node.nodes, sourcePath, opts, mappings)
    }
  });
}
8429
function replace(oldNode, newNode){
    return oldNode[PARENT_NODE] ? oldNode[PARENT_NODE].replaceChild(newNode, oldNode) : oldNode;
  }
1115556
def replace_references(self, node):
        
        href = node.getAttribute('href')
        if href is None:
            return
        id = href.getValue()
        ref = self.catalog.get(id)
        if ref is None:
            log.error('soap multiref: %s, not-resolved', id)
            return
        node.append(ref.children)
        node.setText(ref.getText())
        for a in ref.attributes:
            if a.name != 'id':
                node.append(a)
        node.remove(href)
1318135
function replaceWithMultiple(nodes) {
  this.resync();

  nodes = this._verifyNodeList(nodes);
  t.inheritLeadingComments(nodes[0], this.node);
  t.inheritTrailingComments(nodes[nodes.length - 1], this.node);
  this.node = this.container[this.key] = null;
  this.insertAfter(nodes);
  if (!this.node) this.dangerouslyRemove();
}
121516
function replace(node, parent, scope, remaps) {
  var remap = remaps[node.name];
  if (!remap) return;

  var ownBinding = scope.getBindingIdentifier(node.name);
  if (ownBinding === remap.binding) {
    node.name = remap.uid;
  } else {
    // scope already has it's own binding that doesn't
    // match the one we have a stored replacement for
    if (this) this.skip();
  }
}
755442
function fixAnchors (hook) {

  hook.afterEach(function (html, next) {

    // find all headings and replace them
    html = html.replace(/<(h\d).+?<\/\1>/g, function (html) {

      // create temp node
      var div = document.createElement('div')
      div.innerHTML = html

      // get anchor
      var link = div.querySelector('a[href*="?id"]')

      if (!link) {
        return html
      }

      // work out id
      var text = link.innerText
      var id = text
        .split('(')
        .shift()
        .toLowerCase()
        .replace(/\W+/g, '-')
        .replace(/^-+|-+$/g, '')
      var href = link.getAttribute('href')
        .replace(/\?id=.+/, '?id=' + id)

      // update dom
      link.setAttribute('href', href)
      link.setAttribute('data-id', id)
      link.parentElement.setAttribute('id', id)

      // return html
      return div.innerHTML
    })

    // continue
    next(html)
  })
}
770500
function transformMedia(media, customMedias) {
	const transpiledMedias = [];

	for (const index in media.nodes) {
		const { value, nodes } = media.nodes[index];
		const key = value.replace(customPseudoRegExp, '$1');

		if (key in customMedias) {
			for (const replacementMedia of customMedias[key].nodes) {
				// use the first available modifier unless they cancel each other out
				const modifier = media.modifier !== replacementMedia.modifier
					? media.modifier || replacementMedia.modifier
				: '';
				const mediaClone = media.clone({
					modifier,
					// conditionally use the raws from the first available modifier
					raws: !modifier || media.modifier
						? { ...media.raws }
					: { ...replacementMedia.raws },
					type: media.type || replacementMedia.type,
				});

				// conditionally include more replacement raws when the type is present
				if (mediaClone.type === replacementMedia.type) {
					Object.assign(mediaClone.raws, {
						and: replacementMedia.raws.and,
						beforeAnd: replacementMedia.raws.beforeAnd,
						beforeExpression: replacementMedia.raws.beforeExpression
					});
				}

				mediaClone.nodes.splice(index, 1, ...replacementMedia.clone().nodes.map(node => {
					// use raws and spacing from the current usage
					if (media.nodes[index].raws.and) {
						node.raws = { ...media.nodes[index].raws };
					}

					node.spaces = { ...media.nodes[index].spaces };

					return node;
				}));

				// remove the currently transformed key to prevent recursion
				const nextCustomMedia = getCustomMediasWithoutKey(customMedias, key);
				const retranspiledMedias = transformMedia(mediaClone, nextCustomMedia);

				if (retranspiledMedias.length) {
					transpiledMedias.push(...retranspiledMedias);
				} else {
					transpiledMedias.push(mediaClone);
				}
			}

			return transpiledMedias;
		} else if (nodes && nodes.length) {
			transformMediaList(media.nodes[index], customMedias);
		}
	}

	return transpiledMedias;
}
644143
function reference(node) {
  var definition = this.definitions(node.identifier)
  return link.call(this, node, definition ? definition.url : null)
}
783271
function (node) {

			// Does this node have a body? If so we can replace its contents.
			if (node.body && node.body.length) {
				node.body =
					[].slice.call(node.body, 0)
					.reduce(function(body, node) {

						if (!~allowedPrepend.indexOf(node.type))
							return body.concat(node);

						id++;
						sourceMapAdd(id, node, true);

						return body.concat(
							expressionStatement(
								callExpression(filetag, id)
							),
							node
						);

					}, []);
			}

			if (node.noReplace)
				return;

			// If we're allowed to replace the node,
			// replace it with a Call Expression.

			if (~allowedReplacements.indexOf(node.type))
				return (
					id ++,
					sourceMapAdd(id, node, false),
					callExpression(filetag, id, node)
				);
		}
310736
def add_alias(ref)
      node = Nokogiri::XML::Node.new 'alias', document
      node.ref = (Entry === ref) ? ref.id : ref.to_s

      add_child node
    end
50949
function reference(node, clone)
			{
				clone.originalNode = node;
				
				node = node.firstChild;
				var child = clone.firstChild;
				
				while (node != null && child != null)
				{
					reference(node, child);
					node = node.nextSibling;
					child = child.nextSibling;
				}
				
				return clone;
			}
747298
protected String transformMardownLinks(String content, ReferenceContext references) {
		if (!isMarkdownToHtmlReferenceTransformation()) {
			return content;
		}

		// Prepare replacement data structures
		final Map<BasedSequence, String> replacements = new TreeMap<>((cmp1, cmp2) -> {
			final int cmp = Integer.compare(cmp2.getStartOffset(), cmp1.getStartOffset());
			if (cmp != 0) {
				return cmp;
			}
			return Integer.compare(cmp2.getEndOffset(), cmp1.getEndOffset());
		});

		// Visit the links and record the transformations
		final MutableDataSet options = new MutableDataSet();
		final Parser parser = Parser.builder(options).build();
		final Node document = parser.parse(content);
		final NodeVisitor visitor = new NodeVisitor(
				new VisitHandler<>(Link.class, it -> {
					URL url = FileSystem.convertStringToURL(it.getUrl().toString(), true);
					url = transformURL(url, references);
					if (url != null) {
						replacements.put(it.getUrl(), convertURLToString(url));
					}
				}));
		visitor.visitChildren(document);

		// Apply the replacements
		if (!replacements.isEmpty()) {
			final StringBuilder buffer = new StringBuilder(content);
			for (final Entry<BasedSequence, String> entry : replacements.entrySet()) {
				final BasedSequence seq = entry.getKey();
				buffer.replace(seq.getStartOffset(), seq.getEndOffset(), entry.getValue());
			}
			return buffer.toString();
		}
		return content;
	}
241131
function mapLocalReference (node) {
    if ((node === undefined) || (node === null)) return undefined;
    var ref = _getFirstChildNS(node, 'Ref');
    if ((ref === undefined) || (ref === null)) return undefined;
    return getAttrValue(ref, 'id');
  }
618850
function replaceNodeWith(node, newNode) {
    let done = false;
    const parent = node.$parent;
    const keys = Object.keys(parent);
    keys.forEach(function(key) {
        if (parent[key] === node) {
            parent[key] = newNode;
            done = true;
        }
    });

    if (done) {
        return;
    }

    // second pass, now check arrays
    keys.forEach(function(key) {
        if (Array.isArray(parent[key])) {
            const arr = parent[key];
            for (let i = 0; i < arr.length; i++) {
                if (arr[i] === node) {
                    arr[i] = newNode;
                    done = true;
                }
            }
        }
    });

    assert(done);
}
1032419
function normalizePage(sections, options) {
    options = _.defaults(options || {}, {
        // Current book
        book: null,

        // Do we need to convert svg?
        convertImages: false,

        // Current file path
        input: '.',

        // Navigation to use to transform path
        navigation: {},

        // Directory parent of the file currently in rendering process
        base: './',

        // Directory parent from the html output
        output: './',

        // Glossary terms
        glossary: []
    });

    // List of images to convert
    var toConvert = [];

    sections = _.map(sections, function(section) {
        if (section.type != 'normal') return section;

        var out = normalizeHtml(section.content, options);

        toConvert = toConvert.concat(out.images);
        section.content = out.html;
        return section;
    });

    return Q()
    .then(function() {
        toConvert = _.uniq(toConvert, 'source');
        return convertImages(toConvert, options);
    })
    .thenResolve(sections);
}
1332429
function normalizeRelatedNodes(node, options) {
	'use strict';
	['any', 'all', 'none'].forEach(type => {
		if (!Array.isArray(node[type])) {
			return;
		}
		node[type]
			.filter(checkRes => Array.isArray(checkRes.relatedNodes))
			.forEach(checkRes => {
				checkRes.relatedNodes = checkRes.relatedNodes.map(relatedNode => {
					var res = {
						html: relatedNode.source
					};
					if (options.elementRef && !relatedNode.fromFrame) {
						res.element = relatedNode.element;
					}
					if (options.selectors !== false || relatedNode.fromFrame) {
						res.target = relatedNode.selector;
					}
					if (options.xpath) {
						res.xpath = relatedNode.xpath;
					}
					return res;
				});
			});
	});
}