...
1 package table
2
3 import (
4 "fmt"
5 "strings"
6 )
7
8
9
10
11
12
13
14
15 func (t *Table) RenderMarkdown() string {
16 t.initForRender()
17
18 var out strings.Builder
19 if t.numColumns > 0 {
20 t.markdownRenderTitle(&out)
21 t.markdownRenderRowsHeader(&out)
22 t.markdownRenderRows(&out, t.rows, renderHint{})
23 t.markdownRenderRowsFooter(&out)
24 t.markdownRenderCaption(&out)
25 }
26 return t.render(&out)
27 }
28
29 func (t *Table) markdownRenderCaption(out *strings.Builder) {
30 if t.caption != "" {
31 out.WriteRune('\n')
32 out.WriteRune('_')
33 out.WriteString(t.caption)
34 out.WriteRune('_')
35 }
36 }
37
38 func (t *Table) markdownRenderRow(out *strings.Builder, row rowStr, hint renderHint) {
39
40 if out.Len() > 0 {
41 out.WriteRune('\n')
42 }
43
44
45 out.WriteRune('|')
46 for colIdx := 0; colIdx < t.numColumns; colIdx++ {
47 t.markdownRenderRowAutoIndex(out, colIdx, hint)
48
49 if hint.isSeparatorRow {
50 out.WriteString(t.getAlign(colIdx, hint).MarkdownProperty())
51 } else {
52 var colStr string
53 if colIdx < len(row) {
54 colStr = row[colIdx]
55 }
56 out.WriteRune(' ')
57 if strings.Contains(colStr, "|") {
58 colStr = strings.Replace(colStr, "|", "\\|", -1)
59 }
60 if strings.Contains(colStr, "\n") {
61 colStr = strings.Replace(colStr, "\n", "<br/>", -1)
62 }
63 out.WriteString(colStr)
64 out.WriteRune(' ')
65 }
66 out.WriteRune('|')
67 }
68 }
69
70 func (t *Table) markdownRenderRowAutoIndex(out *strings.Builder, colIdx int, hint renderHint) {
71 if colIdx == 0 && t.autoIndex {
72 out.WriteRune(' ')
73 if hint.isSeparatorRow {
74 out.WriteString("---:")
75 } else if hint.isRegularRow() {
76 out.WriteString(fmt.Sprintf("%d ", hint.rowNumber))
77 }
78 out.WriteRune('|')
79 }
80 }
81
82 func (t *Table) markdownRenderRows(out *strings.Builder, rows []rowStr, hint renderHint) {
83 if len(rows) > 0 {
84 for idx, row := range rows {
85 hint.rowNumber = idx + 1
86 t.markdownRenderRow(out, row, hint)
87
88 if idx == len(rows)-1 && hint.isHeaderRow {
89 t.markdownRenderRow(out, t.rowSeparator, renderHint{isSeparatorRow: true})
90 }
91 }
92 }
93 }
94
95 func (t *Table) markdownRenderRowsFooter(out *strings.Builder) {
96 t.markdownRenderRows(out, t.rowsFooter, renderHint{isFooterRow: true})
97
98 }
99
100 func (t *Table) markdownRenderRowsHeader(out *strings.Builder) {
101 if len(t.rowsHeader) > 0 {
102 t.markdownRenderRows(out, t.rowsHeader, renderHint{isHeaderRow: true})
103 } else if t.autoIndex {
104 t.markdownRenderRows(out, []rowStr{t.getAutoIndexColumnIDs()}, renderHint{isAutoIndexRow: true, isHeaderRow: true})
105 }
106 }
107
108 func (t *Table) markdownRenderTitle(out *strings.Builder) {
109 if t.title != "" {
110 out.WriteString("# ")
111 out.WriteString(t.title)
112 }
113 }
114
View as plain text