visitText method

  1. @override
void visitText(
  1. Text text
)

Called when a Text node has been reached.

Implementation

@override
void visitText(md.Text text) {
  // Don't allow text directly under the root.
  if (_blocks.last.tag == null) {
    return;
  }

  _addParentInlineIfNeeded(_blocks.last.tag);

  // Define trim text function to remove spaces from text elements in
  // accordance with Markdown specifications.
  String trimText(String text) {
    // The leading spaces pattern is used to identify spaces
    // at the beginning of a line of text.
    final RegExp _leadingSpacesPattern = RegExp(r'^ *');

    // The soft line break pattern is used to identify the spaces at the end of a
    // line of text and the leading spaces in the immediately following the line
    // of text. These spaces are removed in accordance with the Markdown
    // specification on soft line breaks when lines of text are joined.
    final RegExp _softLineBreakPattern = RegExp(r' ?\n *');

    // Leading spaces following a hard line break are ignored.
    // https://github.github.com/gfm/#example-657
    if (_lastTag == 'br') {
      text = text.replaceAll(_leadingSpacesPattern, '');
    }

    // Spaces at end of the line and beginning of the next line are removed.
    // https://github.github.com/gfm/#example-670
    return text.replaceAll(_softLineBreakPattern, ' ');
  }

  Widget? child;
  if (_blocks.isNotEmpty && builders.containsKey(_blocks.last.tag)) {
    child = builders[_blocks.last.tag!]!
        .visitText(text, styleSheet.styles[_blocks.last.tag!]);
  } else if (_blocks.last.tag == 'pre') {
    child = Scrollbar(
      child: SingleChildScrollView(
        scrollDirection: Axis.horizontal,
        padding: styleSheet.codeblockPadding,
        child: _buildRichText(delegate.formatText(styleSheet, text.text)),
      ),
    );
  } else {
    child = _buildRichText(
      TextSpan(
        style: _isInBlockquote
            ? styleSheet.blockquote!.merge(_inlines.last.style)
            : _inlines.last.style,
        text: _isInBlockquote ? text.text : trimText(text.text),
        recognizer: _linkHandlers.isNotEmpty ? _linkHandlers.last : null,
      ),
      textAlign: _textAlignForBlockTag(_currentBlockTag),
    );
  }
  if (child != null) {
    _inlines.last.children.add(child);
  }
}