Debian Codegraph @

renderer/markdown.go

raw
1 package renderer
2
3 import (
4 "io"
5 "strings"
6
7 "github.com/olekukonko/ll"
8 "github.com/olekukonko/tablewriter/pkg/twwidth"
9
10 "github.com/olekukonko/tablewriter/tw"
11 )
12
13 // Markdown renders tables in Markdown format with customizable settings.
14 type Markdown struct {
15 config tw.Rendition // Rendering configuration
16 logger *ll.Logger // Debug trace messages
17 headerAlignment tw.Alignment // Cached header alignments
18 bodyAlignment tw.Alignment // Cached body alignments
19 bodyResolved bool // Whether body alignment has been resolved from actual row data
20 w io.Writer
21 // Deferred separator rendering
22 pendingSeparator bool
23 pendingSepCtx tw.Formatting
24 }
25
26 // NewMarkdown initializes a Markdown renderer with defaults tailored for Markdown.
27 func NewMarkdown(configs ...tw.Rendition) *Markdown {
28 cfg := defaultBlueprint()
29 cfg.Symbols = tw.NewSymbols(tw.StyleMarkdown)
30 cfg.Borders = tw.Border{Left: tw.On, Right: tw.On, Top: tw.Off, Bottom: tw.Off}
31 cfg.Settings.Separators.BetweenColumns = tw.On
32 cfg.Settings.Separators.BetweenRows = tw.Off
33 cfg.Settings.Lines.ShowHeaderLine = tw.On
34 cfg.Settings.Lines.ShowTop = tw.Off
35 cfg.Settings.Lines.ShowBottom = tw.Off
36 cfg.Settings.Lines.ShowFooterLine = tw.Off
37
38 if len(configs) > 0 {
39 cfg = mergeMarkdownConfig(cfg, configs[0])
40 }
41 return &Markdown{config: cfg, logger: ll.New("markdown").Disable()}
42 }
43
44 // mergeMarkdownConfig combines user-provided config with Markdown defaults, enforcing Markdown-specific settings.
45 func mergeMarkdownConfig(defaults, overrides tw.Rendition) tw.Rendition {
46 if overrides.Borders.Left != 0 {
47 defaults.Borders.Left = overrides.Borders.Left
48 }
49 if overrides.Borders.Right != 0 {
50 defaults.Borders.Right = overrides.Borders.Right
51 }
52 if overrides.Symbols != nil {
53 defaults.Symbols = overrides.Symbols
54 }
55 defaults.Settings = mergeSettings(defaults.Settings, overrides.Settings)
56 // Enforce Markdown requirements
57 defaults.Settings.Lines.ShowHeaderLine = tw.On
58 defaults.Settings.Separators.BetweenColumns = tw.On
59 return defaults
60 }
61
62 func (m *Markdown) Logger(logger *ll.Logger) {
63 m.logger = logger.Namespace("markdown")
64 }
65
66 // Config returns the renderer's current configuration.
67 func (m *Markdown) Config() tw.Rendition {
68 return m.config
69 }
70
71 func (m *Markdown) Rendition(config tw.Rendition) {
72 m.config = mergeRendition(m.config, config)
73 m.Reset()
74 }
75
76 // Header renders the Markdown table header. Separator is deferred until body alignment is known.
77 func (m *Markdown) Header(headers [][]string, ctx tw.Formatting) {
78 m.resolveHeaderAlignment(ctx)
79 if len(headers) == 0 || len(headers[0]) == 0 {
80 m.logger.Debug("Header: No headers to render")
81 return
82 }
83 m.logger.Debugf("Rendering header with %d lines, widths=%v, current=%v, next=%v",
84 len(headers), ctx.Row.Widths, ctx.Row.Current, ctx.Row.Next)
85
86 // Render header content immediately
87 m.renderMarkdownLine(headers[0], ctx, false)
88
89 // Defer separator rendering until we know the body alignment
90 if m.config.Settings.Lines.ShowHeaderLine.Enabled() {
91 m.pendingSeparator = true
92 m.pendingSepCtx = ctx
93 m.logger.Debug("Header: Deferred separator rendering until body alignment is known")
94 }
95 }
96
97 // Row renders a Markdown table data row. First row triggers deferred separator if pending.
98 func (m *Markdown) Row(row []string, ctx tw.Formatting) {
99 m.resolveBodyAlignment(ctx)
100
101 // Render deferred separator if pending and body alignment is now known
102 if m.pendingSeparator && m.bodyResolved {
103 m.renderDeferredSeparator()
104 }
105
106 m.logger.Debugf("Rendering row with data=%v, widths=%v, previous=%v, current=%v, next=%v",
107 row, ctx.Row.Widths, ctx.Row.Previous, ctx.Row.Current, ctx.Row.Next)
108 m.renderMarkdownLine(row, ctx, false)
109 }
110
111 // Footer renders the Markdown table footer.
112 func (m *Markdown) Footer(footers [][]string, ctx tw.Formatting) {
113 m.resolveBodyAlignment(ctx)
114
115 // Render deferred separator if still pending (no rows to trigger it)
116 if m.pendingSeparator && m.bodyResolved {
117 m.renderDeferredSeparator()
118 }
119
120 if len(footers) == 0 || len(footers[0]) == 0 {
121 m.logger.Debug("Footer: No footers to render")
122 return
123 }
124 m.logger.Debugf("Rendering footer with %d lines, widths=%v, previous=%v, current=%v, next=%v",
125 len(footers), ctx.Row.Widths, ctx.Row.Previous, ctx.Row.Current, ctx.Row.Next)
126 m.renderMarkdownLine(footers[0], ctx, false)
127 }
128
129 // renderDeferredSeparator renders the separator line now that body alignment is known.
130 func (m *Markdown) renderDeferredSeparator() {
131 m.logger.Debug("Rendering deferred separator with known body alignment: %s", m.bodyAlignment)
132
133 sepCtx := m.pendingSepCtx
134 sepCtx.Row.Widths = m.pendingSepCtx.Row.Widths
135 sepCtx.Row.Previous = m.pendingSepCtx.Row.Current
136 sepCtx.IsSubRow = true
137 sepCtx.Row.Current = m.pendingSepCtx.Row.Current // Use header context for separator rendering
138
139 m.renderMarkdownLine(nil, sepCtx, true)
140 m.pendingSeparator = false
141 }
142
143 func (m *Markdown) Line(ctx tw.Formatting) {
144 m.logger.Debugf("Line: Generic Line call received (pos: %s, loc: %s). Markdown ignores these.",
145 ctx.Row.Position, ctx.Row.Location)
146 }
147
148 // Reset clears the renderer's internal state, including debug traces.
149 func (m *Markdown) Reset() {
150 m.headerAlignment = nil
151 m.bodyAlignment = nil
152 m.bodyResolved = false
153 m.pendingSeparator = false
154 m.logger.Info("Reset: Cleared alignment caches")
155 }
156
157 func (m *Markdown) Start(w io.Writer) error {
158 m.w = w
159 m.logger.Warn("Markdown.Start() called (no-op).")
160 return nil
161 }
162
163 func (m *Markdown) Close() error {
164 if !m.pendingSeparator {
165 return nil
166 }
167
168 // If we have a deferred separator but body alignment was never resolved,
169 // fall back to header alignment so the separator still renders.
170 if !m.bodyResolved && len(m.headerAlignment) > 0 {
171 m.bodyResolved = true
172 m.bodyAlignment = make(tw.Alignment, len(m.headerAlignment))
173 copy(m.bodyAlignment, m.headerAlignment)
174 }
175
176 if m.bodyResolved {
177 m.renderDeferredSeparator()
178 }
179
180 return nil
181 }
182
183 func (m *Markdown) resolveHeaderAlignment(ctx tw.Formatting) tw.Alignment {
184 if len(m.headerAlignment) != 0 {
185 return m.headerAlignment
186 }
187 total := len(ctx.Row.Current)
188 for i := 0; i < total; i++ {
189 m.headerAlignment = append(m.headerAlignment, tw.AlignNone)
190 }
191 for i := 0; i < total; i++ {
192 m.headerAlignment[i] = ctx.Row.Current[i].Align
193 }
194 m.logger.Debugf(" → Header Align Resolved %s", m.headerAlignment)
195 return m.headerAlignment
196 }
197
198 func (m *Markdown) resolveBodyAlignment(ctx tw.Formatting) tw.Alignment {
199 // Only resolve from actual row data once
200 if m.bodyResolved {
201 return m.bodyAlignment
202 }
203
204 total := len(ctx.Row.Current)
205 if total == 0 {
206 return m.bodyAlignment
207 }
208
209 // Initialize if needed
210 if len(m.bodyAlignment) == 0 {
211 for i := 0; i < total; i++ {
212 m.bodyAlignment = append(m.bodyAlignment, tw.AlignNone)
213 }
214 }
215
216 // Only update from row context if position is Row or Footer (not Header/separator)
217 if ctx.Row.Position == tw.Row || ctx.Row.Position == tw.Footer {
218 for i := 0; i < total && i < len(m.bodyAlignment); i++ {
219 m.bodyAlignment[i] = ctx.Row.Current[i].Align
220 }
221 m.bodyResolved = true
222 m.logger.Debugf(" → Body Align Resolved from %s: %s", ctx.Row.Position, m.bodyAlignment)
223 }
224
225 return m.bodyAlignment
226 }
227
228 // resolveAlignmentRule applies the Deliberate Rules:
229 // Rule 1: No explicit alignment → Center (backward compatible)
230 // Rule 2 & 3: Body has explicit alignment → Body wins
231 // Rule 4: Only header has explicit alignment → Header wins
232 func (m *Markdown) resolveAlignmentRule(headerAlign, bodyAlign tw.Align) tw.Align {
233 headerExplicit := headerAlign != tw.AlignNone && headerAlign != tw.Empty && headerAlign != tw.Skip
234 bodyExplicit := bodyAlign != tw.AlignNone && bodyAlign != tw.Empty && bodyAlign != tw.Skip
235
236 if bodyExplicit {
237 return bodyAlign
238 } else if headerExplicit {
239 return headerAlign
240 }
241 return tw.AlignCenter
242 }
243
244 // formatCell formats a Markdown cell's content with padding and alignment, ensuring at least 3 characters wide.
245 func (m *Markdown) formatCell(content string, width int, align tw.Align, padding tw.Padding) string {
246 contentVisualWidth := twwidth.Width(content)
247 padLeftChar := padding.Left
248 if padLeftChar == tw.Empty {
249 padLeftChar = tw.Space
250 }
251 padRightChar := padding.Right
252 if padRightChar == tw.Empty {
253 padRightChar = tw.Space
254 }
255 padLeftCharWidth := twwidth.Width(padLeftChar)
256 padRightCharWidth := twwidth.Width(padRightChar)
257 minWidth := tw.Max(3, contentVisualWidth+padLeftCharWidth+padRightCharWidth)
258 targetWidth := tw.Max(width, minWidth)
259
260 totalPaddingNeeded := max(targetWidth-contentVisualWidth, 0)
261
262 var leftPadStr, rightPadStr string
263 switch align {
264 case tw.AlignRight:
265 leftPadCount := tw.Max(0, totalPaddingNeeded-padRightCharWidth)
266 rightPadCount := totalPaddingNeeded - leftPadCount
267 leftPadStr = strings.Repeat(padLeftChar, leftPadCount)
268 rightPadStr = strings.Repeat(padRightChar, rightPadCount)
269 case tw.AlignCenter:
270 leftPadCount := totalPaddingNeeded / 2
271 rightPadCount := totalPaddingNeeded - leftPadCount
272 if leftPadCount < padLeftCharWidth && totalPaddingNeeded >= padLeftCharWidth+padRightCharWidth {
273 leftPadCount = padLeftCharWidth
274 rightPadCount = totalPaddingNeeded - leftPadCount
275 }
276 if rightPadCount < padRightCharWidth && totalPaddingNeeded >= padLeftCharWidth+padRightCharWidth {
277 rightPadCount = padRightCharWidth
278 leftPadCount = totalPaddingNeeded - rightPadCount
279 }
280 leftPadStr = strings.Repeat(padLeftChar, leftPadCount)
281 rightPadStr = strings.Repeat(padRightChar, rightPadCount)
282 default: // AlignLeft
283 rightPadCount := tw.Max(0, totalPaddingNeeded-padLeftCharWidth)
284 leftPadCount := totalPaddingNeeded - rightPadCount
285 leftPadStr = strings.Repeat(padLeftChar, leftPadCount)
286 rightPadStr = strings.Repeat(padRightChar, rightPadCount)
287 }
288
289 result := leftPadStr + content + rightPadStr
290 finalWidth := twwidth.Width(result)
291 if finalWidth != targetWidth {
292 m.logger.Debugf("Markdown formatCell MISMATCH: content='%s', target_w=%d, paddingL='%s', paddingR='%s', align=%s -> result='%s', result_w=%d",
293 content, targetWidth, padding.Left, padding.Right, align, result, finalWidth)
294 adjNeeded := targetWidth - finalWidth
295 if adjNeeded > 0 {
296 adjStr := strings.Repeat(tw.Space, adjNeeded)
297 switch align {
298 case tw.AlignRight:
299 result = adjStr + result
300 case tw.AlignCenter:
301 leftAdj := adjNeeded / 2
302 rightAdj := adjNeeded - leftAdj
303 result = strings.Repeat(tw.Space, leftAdj) + result + strings.Repeat(tw.Space, rightAdj)
304 default:
305 result += adjStr
306 }
307 } else {
308 result = twwidth.Truncate(result, targetWidth)
309 }
310 m.logger.Debugf("Markdown formatCell Corrected: target_w=%d, result='%s', new_w=%d", targetWidth, result, twwidth.Width(result))
311 }
312
313 m.logger.Debugf("Markdown formatCell: content='%s', width=%d, align=%s, paddingL='%s', paddingR='%s' -> '%s' (target %d)",
314 content, width, align, padding.Left, padding.Right, result, targetWidth)
315 return result
316 }
317
318 func (m *Markdown) formatSeparator(width int, align tw.Align) string {
319 targetWidth := tw.Max(3, width)
320 var sb strings.Builder
321
322 switch align {
323 case tw.AlignLeft:
324 sb.WriteRune(':')
325 sb.WriteString(strings.Repeat("-", targetWidth-1))
326 case tw.AlignRight:
327 sb.WriteString(strings.Repeat("-", targetWidth-1))
328 sb.WriteRune(':')
329 case tw.AlignCenter:
330 sb.WriteRune(':')
331 sb.WriteString(strings.Repeat("-", targetWidth-2))
332 sb.WriteRune(':')
333 default:
334 sb.WriteRune(':')
335 sb.WriteString(strings.Repeat("-", targetWidth-2))
336 sb.WriteRune(':')
337 }
338
339 result := sb.String()
340 currentLen := twwidth.Width(result)
341 if currentLen < targetWidth {
342 result += strings.Repeat("-", targetWidth-currentLen)
343 } else if currentLen > targetWidth {
344 result = twwidth.Truncate(result, targetWidth)
345 }
346
347 m.logger.Debugf("Markdown formatSeparator: width=%d, align=%s -> '%s'", width, align, result)
348 return result
349 }
350
351 // renderMarkdownLine renders a single Markdown line (header, row, footer, or separator) with pipes and alignment.
352 func (m *Markdown) renderMarkdownLine(line []string, ctx tw.Formatting, isHeaderSep bool) {
353 numCols := 0
354 if len(ctx.Row.Widths) > 0 {
355 maxKey := -1
356 for k := range ctx.Row.Widths {
357 if k > maxKey {
358 maxKey = k
359 }
360 }
361 numCols = maxKey + 1
362 } else if len(ctx.Row.Current) > 0 {
363 maxKey := -1
364 for k := range ctx.Row.Current {
365 if k > maxKey {
366 maxKey = k
367 }
368 }
369 numCols = maxKey + 1
370 } else if len(line) > 0 && !isHeaderSep {
371 numCols = len(line)
372 }
373
374 if numCols == 0 && !isHeaderSep {
375 m.logger.Debug("renderMarkdownLine: Skipping line with zero columns.")
376 return
377 }
378
379 var output strings.Builder
380 prefix := m.config.Symbols.Column()
381 if m.config.Borders.Left == tw.Off {
382 prefix = tw.Empty
383 }
384 suffix := m.config.Symbols.Column()
385 if m.config.Borders.Right == tw.Off {
386 suffix = tw.Empty
387 }
388 separator := m.config.Symbols.Column()
389 output.WriteString(prefix)
390
391 colIndex := 0
392 separatorWidth := twwidth.Width(separator)
393
394 for colIndex < numCols {
395 cellCtx, ok := ctx.Row.Current[colIndex]
396 defaultPadding := tw.Padding{Left: tw.Space, Right: tw.Space}
397 if !ok {
398 cellCtx = tw.CellContext{
399 Data: tw.Empty, Align: tw.AlignNone, Padding: defaultPadding,
400 Width: ctx.Row.Widths.Get(colIndex), Merge: tw.MergeState{},
401 }
402 } else if !cellCtx.Padding.Paddable() {
403 cellCtx.Padding = defaultPadding
404 }
405
406 isContinuation := ok && cellCtx.Merge.Horizontal.Present && !cellCtx.Merge.Horizontal.Start
407 if colIndex > 0 && !isContinuation {
408 output.WriteString(separator)
409 m.logger.Debugf("renderMarkdownLine: Added separator '%s' before col %d", separator, colIndex)
410 }
411
412 span := 1
413 visualWidth := 0
414 isHMergeStart := ok && cellCtx.Merge.Horizontal.Present && cellCtx.Merge.Horizontal.Start
415 if isHMergeStart {
416 span = cellCtx.Merge.Horizontal.Span
417 totalWidth := 0
418 for k := 0; k < span && colIndex+k < numCols; k++ {
419 colWidth := max(ctx.NormalizedWidths.Get(colIndex+k), 0)
420 totalWidth += colWidth
421 if k > 0 && separatorWidth > 0 {
422 totalWidth += separatorWidth
423 }
424 }
425 visualWidth = totalWidth
426 m.logger.Debugf("renderMarkdownLine: HMerge col %d, span %d, visualWidth %d", colIndex, span, visualWidth)
427 } else {
428 visualWidth = ctx.Row.Widths.Get(colIndex)
429 m.logger.Debugf("renderMarkdownLine: Regular col %d, visualWidth %d", colIndex, visualWidth)
430 }
431 if visualWidth < 0 {
432 visualWidth = 0
433 }
434
435 if isContinuation {
436 m.logger.Debugf("renderMarkdownLine: Skipping col %d (HMerge continuation)", colIndex)
437 colIndex += span
438 continue
439 }
440
441 var formattedSegment string
442 if isHeaderSep {
443 // Separator: use body alignment (if resolved) else header alignment
444 headerAlign := tw.AlignNone
445 if colIndex < len(m.headerAlignment) {
446 headerAlign = m.headerAlignment[colIndex]
447 }
448 bodyAlign := tw.AlignNone
449 if m.bodyResolved && colIndex < len(m.bodyAlignment) {
450 bodyAlign = m.bodyAlignment[colIndex]
451 }
452 sepAlign := m.resolveAlignmentRule(headerAlign, bodyAlign)
453 formattedSegment = m.formatSeparator(visualWidth, sepAlign)
454 m.logger.Debugf("renderMarkdownLine: Separator col %d - headerAlign=%s, bodyAlign=%s, final=%s",
455 colIndex, headerAlign, bodyAlign, sepAlign)
456 } else {
457 content := ""
458 if colIndex < len(line) {
459 content = line[colIndex]
460 }
461 if ctx.Row.Position == tw.Header {
462 // Header content uses its own alignment
463 headerAlign := tw.AlignNone
464 if colIndex < len(m.headerAlignment) {
465 headerAlign = m.headerAlignment[colIndex]
466 }
467 if headerAlign == tw.AlignNone || headerAlign == tw.Empty || headerAlign == tw.Skip {
468 headerAlign = tw.AlignCenter
469 }
470 formattedSegment = m.formatCell(content, visualWidth, headerAlign, cellCtx.Padding)
471 m.logger.Debugf("renderMarkdownLine: Header col %d - align=%s", colIndex, headerAlign)
472 } else {
473 // Body/footer: apply rules
474 headerAlign := tw.AlignNone
475 if colIndex < len(m.headerAlignment) {
476 headerAlign = m.headerAlignment[colIndex]
477 }
478 bodyAlign := tw.AlignNone
479 if m.bodyResolved && colIndex < len(m.bodyAlignment) {
480 bodyAlign = m.bodyAlignment[colIndex]
481 }
482 rowAlign := m.resolveAlignmentRule(headerAlign, bodyAlign)
483 formattedSegment = m.formatCell(content, visualWidth, rowAlign, cellCtx.Padding)
484 m.logger.Debugf("renderMarkdownLine: Row col %d - headerAlign=%s, bodyAlign=%s, final=%s",
485 colIndex, headerAlign, bodyAlign, rowAlign)
486 }
487 }
488 output.WriteString(formattedSegment)
489 m.logger.Debugf("renderMarkdownLine: Wrote col %d (span %d, width %d): '%s'",
490 colIndex, span, visualWidth, formattedSegment)
491 colIndex += span
492 }
493
494 output.WriteString(suffix)
495 output.WriteString(tw.NewLine)
496 m.w.Write([]byte(output.String()))
497 m.logger.Debugf("renderMarkdownLine: Final line: %s", strings.TrimSuffix(output.String(), tw.NewLine))
498 }
499
500 var _ tw.Renditioning = (*Markdown)(nil)