~shulhan/asciidoctor-go

ref: v0.1.0 asciidoctor-go/document.go -rw-r--r-- 9.4 KiB
4c1ded16Shulhan Release asciidoctor-go v0.1.0 (2021-03-06) 4 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
// Copyright 2020, Shulhan <ms@kilabit.info>. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package asciidoctor

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

const (
	defSectnumlevels  = 3
	defTOCLevel       = 2
	defTOCTitle       = "Table of Contents"
	defTitleSeparator = ':'
	defVersionPrefix  = "version "
)

//
// Document represent content of asciidoc that has been parsed.
//
type Document struct {
	Title       DocumentTitle
	Authors     []*Author
	Revision    Revision
	LastUpdated string
	Attributes  AttributeEntry
	TOCLevel    int

	rawAuthors   string
	rawRevision  string
	tocClasses   attributeClass
	tocPosition  string
	tocTitle     string
	tocIsEnabled bool

	file    string
	fpath   string
	classes attributeClass

	// anchors contains mapping between unique ID and its label.
	anchors map[string]*anchor
	// titleID is the reverse of anchors, it contains mapping of title and
	// its ID.
	titleID map[string]string

	sectnums  *sectionCounters
	sectLevel int

	header  *element
	content *element

	counterExample int
	counterImage   int
	counterTable   int

	isEmbedded bool
	isForToC   bool
}

func newDocument() *Document {
	return &Document{
		Title: DocumentTitle{
			sep: defTitleSeparator,
		},
		TOCLevel:   defTOCLevel,
		tocClasses: attributeClass{},
		tocTitle:   defTOCTitle,
		Attributes: newAttributeEntry(),
		classes:    attributeClass{},
		anchors:    make(map[string]*anchor),
		titleID:    make(map[string]string),
		sectnums:   &sectionCounters{},
		sectLevel:  defSectnumlevels,
		header: &element{
			kind: elKindDocHeader,
		},
		content: &element{
			kind: elKindDocContent,
		},
	}
}

//
// Open the ascidoc file and parse it.
//
func Open(file string) (doc *Document, err error) {
	fi, err := os.Stat(file)
	if err != nil {
		return nil, err
	}

	raw, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, fmt.Errorf("Open %s: %w", file, err)
	}

	wd, err := os.Getwd()
	if err != nil {
		return nil, fmt.Errorf("Open %s: %w", file, err)
	}

	doc = newDocument()
	doc.fpath = filepath.Join(wd, file)
	doc.file = file
	doc.LastUpdated = fi.ModTime().Round(time.Second).Format("2006-01-02 15:04:05 Z0700")

	parse(doc, raw)

	return doc, nil
}

//
// ToHTMLEmbedded convert the Document object into HTML with content only,
// without header and footer.
//
func (doc *Document) ToHTMLEmbedded(out io.Writer) (err error) {
	doc.isEmbedded = true
	doc.generateClasses()
	buf := &bytes.Buffer{}
	doc.toHTMLBody(buf, false)
	doc.isEmbedded = false
	_, err = out.Write(buf.Bytes())
	return err
}

//
// ToHTML convert the Document object into full HTML document.
//
func (doc *Document) ToHTML(out io.Writer) (err error) {
	doc.generateClasses()

	// Use *bytes.Buffer to minimize checking for error.
	buf := &bytes.Buffer{}

	fmt.Fprint(buf, _htmlBegin)

	metaValue := doc.Attributes[metaNameDescription]
	if len(metaValue) > 0 {
		fmt.Fprintf(buf, "\n<meta name=\"description\" content=%q>",
			metaValue)
	}

	metaValue = doc.Attributes[metaNameKeywords]
	if len(metaValue) > 0 {
		fmt.Fprintf(buf, "\n<meta name=\"keywords\" content=%q>", metaValue)
	}

	var metaAuthors strings.Builder
	for x, author := range doc.Authors {
		if x > 0 {
			metaAuthors.WriteString(", ")
		}
		metaAuthors.WriteString(author.FullName())
	}
	if metaAuthors.Len() > 0 {
		fmt.Fprintf(buf, "\n<meta name=%q content=%q>",
			attrValueAuthor, metaAuthors.String())
	}

	title := doc.Title.String()
	if len(title) > 0 {
		fmt.Fprintf(buf, "\n<title>%s</title>", title)
	}
	fmt.Fprint(buf, "\n<style>\n\n</style>")

	fmt.Fprintf(buf, "\n</head>\n<body class=%q>", doc.classes.String())

	isWithHeaderFooter := true
	_, ok := doc.Attributes[metaNameNoHeaderFooter]
	if ok {
		isWithHeaderFooter = false
	}
	doc.toHTMLBody(buf, isWithHeaderFooter)

	fmt.Fprint(buf, "\n</body>\n</html>")

	_, err = out.Write(buf.Bytes())

	return err
}

//
// ToHTMLBody convert the Document object into HTML with body only, this is
// including header, content, and footer.
//
func (doc *Document) ToHTMLBody(out io.Writer) (err error) {
	doc.generateClasses()
	buf := &bytes.Buffer{}
	doc.toHTMLBody(buf, true)
	_, err = out.Write(buf.Bytes())
	return err
}

func (doc *Document) generateClasses() {
	doc.classes.add(classNameArticle)
	doc.tocPosition, doc.tocIsEnabled = doc.Attributes[metaNameTOC]

	switch doc.tocPosition {
	case metaValueLeft:
		doc.classes.add(classNameToc2)
		doc.classes.add(classNameTocLeft)
		doc.tocClasses.add(classNameToc2)
	case metaValueRight:
		doc.classes.add(classNameToc2)
		doc.classes.add(classNameTocRight)
		doc.tocClasses.add(classNameToc2)
	default:
		doc.tocClasses.add(classNameToc)
	}
}

func (doc *Document) toHTMLBody(buf *bytes.Buffer, withHeaderFooter bool) {
	if withHeaderFooter {
		_, ok := doc.Attributes[metaNameNoHeader]
		if !ok {
			htmlWriteHeader(doc, buf)
		}
	}

	htmlWriteBody(doc, buf)

	if withHeaderFooter {
		_, ok := doc.Attributes[metaNameNoFooter]
		if !ok {
			htmlWriteFooter(doc, buf)
		}
	}
}

//
// postParseHeader re-check the document title, substract the authors, and
// revision number, date, and/or remark.
//
func (doc *Document) postParseHeader() {
	doc.unpackTitleSeparator()
	doc.unpackRawTitle()
	doc.unpackRawAuthor()
	doc.unpackRawRevision()
}

//
// registerAnchor register ID and its label.
// If the ID is already exist it will generate new ID with additional suffix
// "_x" added, where x is the counter of duplicate ID.
// The old or new ID will be returned to caller.
//
func (doc *Document) registerAnchor(id, label string) string {
	got, ok := doc.anchors[id]
	for ok {
		// The ID is duplicate
		got.counter++
		id = fmt.Sprintf("%s_%d", id, got.counter)
		got, ok = doc.anchors[id]
	}
	doc.anchors[id] = &anchor{
		label: label,
	}
	return id
}

//
// tocHTML write table of contents with HTML template into out.
//
func (doc *Document) tocHTML(out io.Writer) {
	v, ok := doc.Attributes[metaNameTOCLevels]
	if ok {
		doc.TOCLevel, _ = strconv.Atoi(v)
		if doc.TOCLevel <= 0 {
			doc.TOCLevel = defTOCLevel
		}
	}

	v, ok = doc.Attributes[metaNameTOCTitle]
	if ok && len(v) > 0 {
		doc.tocTitle = v
	}

	fmt.Fprintf(out, _htmlToCBegin, doc.tocClasses.String(), doc.tocTitle)
	htmlWriteToC(doc, doc.content, out, 0)
	fmt.Fprint(out, "\n</div>")
}

//
// unpackRawAuthor parse the authors field into one or more Author.
//
func (doc *Document) unpackRawAuthor() {
	if len(doc.rawAuthors) == 0 {
		v := doc.Attributes[metaNameAuthor]
		if len(v) > 0 {
			doc.rawAuthors = v
		}
		v = doc.Attributes[metaNameEmail]
		if len(v) > 0 {
			doc.rawAuthors += " <" + v + ">"
		}
		if len(doc.rawAuthors) == 0 {
			return
		}
	}

	rawAuthors := strings.Split(doc.rawAuthors, ";")
	for _, rawAuthor := range rawAuthors {
		if len(rawAuthor) > 0 {
			doc.Authors = append(doc.Authors, parseAuthor(rawAuthor))
		}
	}

	authorKey := metaNameAuthor
	emailKey := metaNameEmail
	initialsKey := metaNameAuthorInitials
	firstNameKey := metaNameFirstName
	middleNameKey := metaNameMiddleName
	lastNameKey := metaNameLastName
	for x, author := range doc.Authors {
		if x == 0 {
			doc.Attributes[authorKey] = author.FullName()
			doc.Attributes[emailKey] = author.Email
			doc.Attributes[initialsKey] = author.Initials
			doc.Attributes[firstNameKey] = author.FirstName
			doc.Attributes[middleNameKey] = author.MiddleName
			doc.Attributes[lastNameKey] = author.LastName
		}

		authorKey = fmt.Sprintf("%s_%d", metaNameAuthor, x+1)
		emailKey = fmt.Sprintf("%s_%d", metaNameEmail, x+1)
		initialsKey = fmt.Sprintf("%s_%d", metaNameAuthorInitials, x+1)
		firstNameKey = fmt.Sprintf("%s_%d", metaNameFirstName, x+1)
		middleNameKey = fmt.Sprintf("%s_%d", metaNameMiddleName, x+1)
		lastNameKey = fmt.Sprintf("%s_%d", metaNameLastName, x+1)

		doc.Attributes[authorKey] = author.FullName()
		doc.Attributes[emailKey] = author.Email
		doc.Attributes[initialsKey] = author.Initials
		doc.Attributes[firstNameKey] = author.FirstName
		doc.Attributes[middleNameKey] = author.MiddleName
		doc.Attributes[lastNameKey] = author.LastName
	}
}

func (doc *Document) unpackRawRevision() {
	if len(doc.rawRevision) > 0 {
		doc.Revision = parseRevision(doc.rawRevision)
		doc.Attributes[metaNameRevNumber] = doc.Revision.Number
		doc.Attributes[metaNameRevDate] = doc.Revision.Date
		doc.Attributes[metaNameRevRemark] = doc.Revision.Remark
		return
	}
	doc.Revision.Number = doc.Attributes[metaNameRevNumber]
	doc.Revision.Date = doc.Attributes[metaNameRevDate]
	doc.Revision.Remark = doc.Attributes[metaNameRevRemark]
}

func (doc *Document) unpackRawTitle() {
	var (
		title string
		prev  byte
	)

	if len(doc.Title.raw) == 0 {
		doc.Title.raw = doc.Attributes[metaNameDocTitle]
		if len(doc.Title.raw) == 0 {
			doc.Title.raw = doc.Attributes[metaNameTitle]
			if len(doc.Title.raw) == 0 {
				return
			}
		}
	}

	doc.Title.el = parseInlineMarkup(doc, []byte(doc.Title.raw))
	title = doc.Title.el.toText()
	doc.Attributes[metaNameDocTitle] = title

	for x := len(title) - 1; x > 0; x-- {
		if title[x] == doc.Title.sep {
			if prev == ' ' {
				doc.Title.Sub = string(title[x+2:])
				doc.Title.Main = string(title[:x])
				break
			}
		}
		prev = title[x]
	}
	if len(doc.Title.Main) == 0 {
		doc.Title.Main = title
	}
}

//
// unpackTitleSeparator set the Title separator using the first character in
// meta attribute "title-separator" value.
//
func (doc *Document) unpackTitleSeparator() {
	v, ok := doc.Attributes[metaNameTitleSeparator]
	if ok {
		v = strings.TrimSpace(v)
		if len(v) > 0 {
			doc.Title.sep = v[0]
		}
	}
}