Tweaks to more properly align block elements

This commit is contained in:
diamondburned (Forefront) 2020-06-18 18:53:09 -07:00
parent c4a77a6582
commit 8b9b46317b
3 changed files with 36 additions and 1 deletions

View File

@ -13,6 +13,9 @@ var _ text.Quoteblocker = (*BlockquoteSegment)(nil)
func (r *TextRenderer) blockquote(n *ast.Blockquote, enter bool) ast.WalkStatus {
if enter {
r.startBlock()
defer r.endBlock()
// Create a segment.
var seg = BlockquoteSegment{start: r.i()}

View File

@ -14,6 +14,9 @@ var _ text.Codeblocker = (*CodeblockSegment)(nil)
func (r *TextRenderer) codeblock(n *ast.FencedCodeBlock, enter bool) ast.WalkStatus {
if enter {
r.startBlock()
defer r.endBlock()
// Create a segment.
seg := CodeblockSegment{
start: r.i(),

View File

@ -2,6 +2,7 @@ package segments
import (
"bytes"
"strings"
"github.com/diamondburned/arikawa/discord"
"github.com/diamondburned/arikawa/state"
@ -44,7 +45,7 @@ func RenderNode(source []byte, n ast.Node) text.Rich {
ast.Walk(n, r.renderNode)
return text.Rich{
Content: buf.String(),
Content: string(bytes.TrimSpace(buf.Bytes())),
Segments: r.segs,
}
}
@ -54,6 +55,34 @@ func (r *TextRenderer) i() int {
return r.buf.Len()
}
// startBlock guarantees enough indentation to start a new block.
func (r *TextRenderer) startBlock() {
var maxNewlines = 2
// Peek twice.
if r.peekLast(0) == '\n' {
maxNewlines--
}
if r.peekLast(1) == '\n' {
maxNewlines--
}
// Write the padding.
r.buf.WriteString(strings.Repeat("\n", maxNewlines))
}
func (r *TextRenderer) endBlock() {
// Do the same thing as starting a block.
r.startBlock()
}
func (r *TextRenderer) peekLast(offset int) byte {
if i := r.buf.Len() - offset - 1; i > 0 {
return r.buf.Bytes()[i]
}
return 0
}
func (r *TextRenderer) append(segs ...text.Segment) {
r.segs = append(r.segs, segs...)
}