close method

List<Node>? close(
  1. InlineParser parser,
  2. Match? endMatch
)

Pops this tag off the stack, completes it, and adds it to the output.

Will discard any unmatched tags that happen to be above it on the stack. If this is the last node in the stack, returns its children.

Implementation

List<Node>? close(InlineParser parser, Match? endMatch) {
  // If there are unclosed tags on top of this one when it's closed, that
  // means they are mismatched. Mismatched tags are treated as plain text in
  // markdown. So for each tag above this one, we write its start tag as text
  // and then adds its children to this one's children.
  final index = parser._stack.indexOf(this);

  // Remove the unmatched children.
  final unmatchedTags = parser._stack.sublist(index + 1);
  parser._stack.removeRange(index + 1, parser._stack.length);

  // Flatten them out onto this tag.
  for (final unmatched in unmatchedTags) {
    // Write the start tag as text.
    parser.writeTextRange(unmatched.startPos, unmatched.endPos);

    // Bequeath its children unto this tag.
    children.addAll(unmatched.children);
  }

  // Pop this off the stack.
  parser.writeText();
  parser._stack.removeLast();

  // If the stack is empty now, this is the special "results" node.
  if (parser._stack.isEmpty) {
    return children;
  }
  final endMatchIndex = parser.pos;

  // We are still parsing, so add this to its parent's children.
  if (syntax!.onMatchEnd(parser, endMatch!, this)) {
    parser.consume(endMatch[0]!.length);
  } else {
    // Didn't close correctly so revert to text.
    parser
      ..writeTextRange(startPos, endPos)
      .._stack.last.children.addAll(children)
      ..pos = endMatchIndex
      ..advanceBy(endMatch[0]!.length);
  }

  return null;
}