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 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
    // Leading spaces in paragraph or list item are ignored
    // https://github.github.com/gfm/#example-192
    // https://github.github.com/gfm/#example-236
    if (const <String>['ul', 'ol', 'li', 'p', 'br']
        .contains(_lastVisitedTag)) {
      text = text.replaceAll(leadingSpacesPattern, '');
    }

    if (softLineBreak) {
      return text;
    }
    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(
      controller: _preScrollController,
      child: SingleChildScrollView(
        controller: _preScrollController,
        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);
  }

  _lastVisitedTag = null;
}