-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmakeWebBook.go
1475 lines (1332 loc) · 56.5 KB
/
makeWebBook.go
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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 DLR-SR. All rights reserved.
// Use of this source code is governed by the
// Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License
// (http://creativecommons.org/licenses/by-nc-sa/4.0/).
/*
Author:
Martin Otter, DLR-SR
(http://www.robotic.dlr.de/sr/en/staff/martin.otter/)
Package makeWebBook updates HTML files to generate a web or local book
organized via several files. It is assumed that all files are present
in one directory, such as:
/bookDirectory
/resources // directory
/media // directory of media files (e.g. images)
/styles // directory of style and javascript files
configuration.json // required file describing the book structure
index.html // cover file
preface.html
tableofcontents.html
chapter_01.html // section file 1 (defined in configuration.json)
chapter_02.html // section file 2
chapter_03.html // section file 3
chapter_A.html // appendix
references.html // references
With the command
makeWebBook bookDirectory
the actions described below are performed, provided a corresponding
<h1> element starts with the text "Chapter" or "Appendix".
(otherwise the <h1> section is not modified; this is useful for a
preface or a literature chapter)
- Specific html elements get a number. In particular:
<h1>, <h2>, <h3>, <h4> elements are updated with section numbers
Examples:
<h1>: Chapter 3 - Operators and Expressions
Appendix B - Concrete Syntax
<h2>: 3.2 Array Operators
<h3>: 3.2.3 Array Multiplication
<h4>: 3.2.3.5 Matrix Multiplication
<caption> elements are updated with a caption number, e.g.
"Table 3-4: This is a table"
<figcaption> elements are updated with a figcaption number, e.g.
"Figure 3-7: This is a figure"
Equations marked by
<div class="equation"> $$ ... $$ </div>
are updated with an equation number (note, it is important that
exactly the string `<div class="equation"` is used with exactly one
space between "div" and "class"). Example:
<div class="equation"> $$ (2.1) \;\;\; ax^2 + bx + c = 0$$ </div>
If a number is not present, it is introduced (with exception of <h1>
element, where a number is only introduced if the text starts with
"Chapter" or with "Appendix").
If it is present and correct, nothing is changed.
Otherwise, the number is updated.
- A navigation bar is introduced in all files with links to the
"table of contents" file, the previous, and the next file.
- The "table of contents" file is updated with the actual document
structure. The "table of contents" file must be defined by the user.
The text within the html comment
<!-- BeginTableOfContents -->
...
<!-- EndTableOfContents -->
is removed and replaced by the actual document structure
- If a section file needs no update, it is not changed.
If a file is changed, it is first moved in a backup directory
(defined in the configuration.json file), and then the file
is newly generated with the updated information.
*/
package main
import (
"encoding/json"
"fmt"
"github.com/PuerkitoBio/goquery"
"io/ioutil"
"log"
"math/rand"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
// "net/http"
)
type ConfigurationType struct {
BackupDirectory string `json:"BackupDirectory"`
CoverFileName string `json:"CoverFileName"`
TocFileName string `json:"TableOfContentsFileName"`
SectionsFileNames []string `json:"SectionsFileNames"`
}
// Structure of one book section (h1, h2, ...), used to generate the "table of contents"
type SectionType struct {
FileName string // File where section is present
ID string // <hx id=ID>
Label string // Label of section (e.g. "Chapter 1", "Preface", "References")
Text string // <hx id=ID>Text</hx>
Modified bool // = true, if Text was modified (section/caption/equation number); = false, if it was not modified
Sections []SectionType // subsections in this section
Captions []CaptionType // captions and figcaptions in this section before any of the subsections
Equations []EquationType // equations in this section before any of the subsections
}
// Table "caption" or figure "figcaption" information
type CaptionType struct {
FileName string
ID string // <caption id=ID> or <figcaption id=ID>
Text string // <caption id=ID>Text</caption> or <figcaption id=ID>Text</figcaption>
Modified bool // = true, if Text was modified (section/caption number); = false, if it was not modified
Figcaption bool // = true, if figcaption, otherwise caption
}
// Equation information
type EquationType struct {
FileName string
ID string // <div class="equation" id=ID>
Text string // <div class="equation" id=ID>Text</div>
Modified bool // = true, if Text was modified; = false, if it was not modified
}
// Information of one found element, used to update the file
type ElementType struct {
StartTag string // Start-tag of element, without closing ">" and without attributes (e.g. "<h1")
EndTag string // End-tag of element (e.g. "</h1>")
Text string // Text of element
Href string // If StartTag == "<a" then (if Href != "" then internal link: <a href="Href">..</a> else external link) else Href="" (dummy)
NewText string // If Modified = true, the modified text, otherwise Text (If StartTag=="<a" then target file name: <a href="TargetFileName#TargetID" title="Tooltip">Text</a>)
Tooltip string // If StartTag == "<a then tooltip; otherwise Tooltip="" (dummy)
Modified bool // = true, if Text was modified (e.g. section or caption number)
ID string // id attribute of element or targetID if startTag = "<a"
NewID bool // = true, if a new ID was generated, because no ID was present
}
// Information about the modified data on a file
type SectionFileType struct {
FileName string // Name of the file
NavList []string // The elements of the nav element. Empty array if no nav is present (NewNav=false)
NewNav bool // = true, if no nav was present in the file and a new one needs to be generated
UpdateNav bool // If NewNav = false (otherwise dummy): If UpdateNav=true, the existing nav needs to be updated, otherwise no update needed
H1Index int // The information in this file is a subsection of <h1> in BookStructure.SectionFiles[H1Index]
Modified bool // = true, if at least one element in Elements needs to be modified
Elements []ElementType
}
// Information about a bookmark. All bookmarks are collected
// in a map where the "id" attribute is used as key
// see section <a href="chapter_02.html#sec_operators>2.3.1</a>
// Key : "sec_operators"
// FileName: "chapter_02.html"
// Ref : "2.3.1"
type BookmarkType struct {
FileName string // File name of bookmark
Label string // Reference label, such as "Chapter 2", "2.3", "Figure 3-2"
Tooltip string // Text to be used as tooltip
}
/*
// Information about a Link
type LinkType struct {
FileName string // File in which link is present
TargetFileName string // Target file name
TargetID string // Target ID
Label string // Link text (should be a label like "Chapter 2" or "2.3"
}
*/
// Complete book structure
type BookStructureType struct {
CoverFileName string
TocFileName string
SectionFiles []SectionFileType // Files in which the sections are present
Sections []SectionType // h1 sections
}
// Counters
type CountersType struct {
iFigCaption int
iCaption int
iEquation int
ih1_digit int
ih1_letter int
last_h1_type string // = "Chapter" or "Appendix" or ""
}
// Global variable holding the complete structure of the document
var Configuration ConfigurationType
var BookStructure BookStructureType
var Bookmarks = make(map[string]BookmarkType)
var ReqNav = make([]string, 0, 10) // Required nav element
// Global variable holding the full path to the actual backup directory
var BackupPath string
// Global variable holding all counters
var Counters CountersType
// Compiled regular expressions as global variables
var validSection1 = regexp.MustCompile(`^Chapter [1-9][0-9]* `) // e.g. "Chapter 4 "
var validSection2 = regexp.MustCompile(`^[1-9][0-9]*[.][1-9][0-9]* `) // e.g. "4.2 "
var validSection3 = regexp.MustCompile(`^[1-9][0-9]*[.][1-9][0-9]*[.][1-9][0-9]* `) // e.g. "4.2.3 "
var validSection4 = regexp.MustCompile(`^[1-9][0-9]*[.][1-9][0-9]*[.][1-9][0-9]*[.][1-9][0-9]* `) // e.g. "4.2.3.5 "
var validSection1_Appendix = regexp.MustCompile(`^Appendix [A-Z] `) // e.g. "Appendix B "
var validSection2_Appendix = regexp.MustCompile(`^[A-Z][.][1-9][0-9]* `) // e.g. "B.2 "
var validSection3_Appendix = regexp.MustCompile(`^[A-Z][.][1-9][0-9]*[.][1-9][0-9]* `) // e.g. "B.2.3 "
var validSection4_Appendix = regexp.MustCompile(`^[A-Z][.][1-9][0-9]*[.][1-9][0-9]*[.][1-9][0-9]* `) // e.g. "B.2.3.5 "
var validCaption = regexp.MustCompile(`^Table [1-9][0-9]*[-][1-9][0-9]*: `) // e.g. "Table 3-2: "
var validFigCaption = regexp.MustCompile(`^Figure [1-9][0-9]*[-][1-9][0-9]*: `) // e.g. "Figure 3-2: "
var validCaption_Appendix = regexp.MustCompile(`^Table [A-Z][-][1-9][0-9]*: `) // e.g. "Table B-2: "
var validFigCaption_Appendix = regexp.MustCompile(`^Figure [A-Z][-][1-9][0-9]*: `) // e.g. "Figure B-2: "
var validEquation = regexp.MustCompile(`\s*[$][$]\s*[(][1-9][0-9]*[.][1-9][0-9]*[)]`) // e.g. "$$ (2.3)"
var validEquation_Appendix = regexp.MustCompile(`\s*[$][$]\s*[(][A-Z][.][1-9][0-9]*[)]`) // e.g. "$$ (B.3)"
var withEquationNumber = regexp.MustCompile(`\s*[$][$]\s*[(]`) // e.g. "$$ ("
var equationStart = regexp.MustCompile(`\s*[$][$]`) // e.g. "$$"
// Constants
const beginTableOfContents = "<!-- BeginTableOfContents -->"
const endTableOfContents = "<!-- EndTableOfContents -->"
const beginNavBar = "<nav>"
const endNavBar = "</nav>"
const beginBody = "<body>"
const letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
const maxDisplayCharacters = 40 // Maximum number of characters to be showed for captions in Table-of-Contents
func main() {
// One input argument required: Directory in which book files are present
// Configuration file must be here: "<arg>/resources/configuration.json"
nArgs := len(os.Args)
if nArgs < 2 {
fmt.Println("Error: No directory name given as input argument for makeWebBook.exe")
os.Exit(1)
} else if nArgs > 2 {
fmt.Println("Error: 2 or more arguments given to makeWebBook.exe, but only one argument is allowed")
}
bookDirectory := os.Args[1]
// Change directory to the place where the configuration file is present
err := os.Chdir(bookDirectory)
if err != nil {
log.Fatal(err)
}
bookPath, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
fmt.Println("... Book directory that shall be processed:", bookPath)
// Read configuration file
fullConfigurationFileName := filepath.Join(bookPath, "resources", "configuration.json")
fmt.Println("Configuration file:", fullConfigurationFileName)
getConfiguration(fullConfigurationFileName)
// Generate and log backup directory
BackupPath = makeBackupDirectory(Configuration.BackupDirectory)
// Get document structure (store in global variable BookStructure)
getDocumentStructure()
// Update section documents (changed section or caption numbers, introducing ids, etc.)
updateSectionDocuments()
// Generate Table-of-Contents file
movedContentsFileName := filepath.Join(BackupPath, BookStructure.TocFileName)
err = os.Rename(BookStructure.TocFileName, movedContentsFileName)
if os.IsNotExist(err) {
// No contents file exists; generate a new one
writeContentsFile("", BookStructure.TocFileName)
} else if err != nil {
log.Fatal(err)
} else {
// BookStructure file exists and was moved
writeContentsFile(movedContentsFileName, BookStructure.TocFileName)
}
}
// Get actual time as string so that the string can be used as directory name (":" is replaced by "-")
func getActualTimeAsString() string {
actualTime := time.Now()
str1 := actualTime.Format(time.RFC3339)
str2 := strings.Replace(str1, ":", "-", -1)
return str2
}
// Make backup directory: input: directory to place backup directory; output: full path name of backup directory
func makeBackupDirectory(directoryName string) string {
if os.Mkdir(directoryName, 0700) != nil {
// Mkdir failed: Check that the existing file is a directory
fileInfo, err := os.Stat(directoryName)
if err != nil {
log.Fatal(err)
}
if !fileInfo.IsDir() {
log.Fatalf("Backup directory name \"%s\" is not a directory\n", directoryName)
}
}
actualTime := getActualTimeAsString()
workingDirectory, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
err = os.Chdir(directoryName)
if err != nil {
log.Fatal(err)
}
err = os.Mkdir(actualTime, 0700)
if err != nil {
log.Fatal(err)
}
err = os.Chdir(actualTime)
if err != nil {
log.Fatal(err)
}
backupPath, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
err = os.Chdir(workingDirectory)
if err != nil {
log.Fatal(err)
}
fmt.Println("Backup directory:", backupPath)
return backupPath
}
func getConfiguration(fileName string) {
raw, err := ioutil.ReadFile(fileName)
if err != nil {
fmt.Println("... Could not read configuration file:", err.Error())
os.Exit(1)
}
err = json.Unmarshal(raw, &Configuration)
if err != nil {
fmt.Println("... Error in json configuration file \"", fileName, "\": ", err.Error())
os.Exit(2)
}
return
}
// Determine document structure and store results in gobal variable BookStructure
func getDocumentStructure() {
BookStructure = BookStructureType{
CoverFileName: Configuration.CoverFileName,
TocFileName: Configuration.TocFileName,
SectionFiles: make([]SectionFileType, 0, 10),
Sections: make([]SectionType, 0, 10)}
// Initialize new random number generator (in order to generator random id's, if no ones are present)
r := rand.New(rand.NewSource(time.Now().UnixNano()))
// Determine structure of every section file
fmt.Println("Determine document structure:")
H1Index_old := -1
for iFile, file := range Configuration.SectionsFileNames {
getStructureOfOneFile(file, iFile, r, &H1Index_old)
}
// Build required navigation bar (with exception of Previous and Next)
ReqNav = append(ReqNav, Configuration.TocFileName)
ReqNav = append(ReqNav, "") // Previous
ReqNav = append(ReqNav, "") // Next
ReqNav = append(ReqNav, Configuration.CoverFileName)
for _, section := range BookStructure.Sections {
ReqNav = append(ReqNav, section.FileName+"#"+section.ID)
}
// Determine whether navigation bars need to be updated
fmt.Println("\nDetermine whether nav elements need to be updated:")
for iFile, sectionFile := range BookStructure.SectionFiles {
checkNavigationBarOfOneFile(iFile, sectionFile)
}
}
func checkNavigationBarOfOneFile(iFile int, sectionFile SectionFileType) {
fileName := BookStructure.SectionFiles[iFile].FileName
// Check whether a nav element is not present
if BookStructure.SectionFiles[iFile].NewNav {
fmt.Printf(" %s (nav will be added)\n", fileName)
return
}
// Build required "Previous" and "Next" file references
last := false
// Previous
if iFile > 0 {
ReqNav[1] = Configuration.SectionsFileNames[iFile-1]
} else {
ReqNav[1] = Configuration.CoverFileName
}
// Next
if iFile < len(Configuration.SectionsFileNames)-1 {
ReqNav[2] = Configuration.SectionsFileNames[iFile+1]
} else {
last = true
ReqNav[2] = ""
}
// Check whether number of references agree
lenReqNav := len(ReqNav)
lenNav := len(sectionFile.NavList)
if last && lenReqNav-1 != lenNav || !last && lenReqNav != lenNav {
// Wrong number of references in nav element: nav element needs to be newly generated
BookStructure.SectionFiles[iFile].UpdateNav = true
fmt.Printf(" %s (nav will be updated)\n", fileName)
return
}
// Check navigation
j := 0
for i := 0; i < lenNav; i++ {
if last && i > 1 {
j = i + 1
} else {
j = i
}
if sectionFile.NavList[i] != ReqNav[j] {
BookStructure.SectionFiles[iFile].UpdateNav = true
fmt.Printf(" %s (nav will be updated)\n", fileName)
return
}
}
BookStructure.SectionFiles[iFile].UpdateNav = false
return
}
func getStructureOfOneFile(fileName string, iFile int, r *rand.Rand, H1Index_old *int) {
fmt.Println(" ", fileName)
// Store file name and default section/caption structure
BookStructure.SectionFiles = append(BookStructure.SectionFiles,
SectionFileType{fileName, make([]string, 0, 10), true, false, -1, false, make([]ElementType, 0, 10)})
iSectionFile := len(BookStructure.SectionFiles) - 1
// Open file
file, err1 := os.Open(fileName)
if err1 != nil {
log.Fatal(err1)
}
defer file.Close()
// Query section structure present in file
doc, err := goquery.NewDocumentFromReader(file)
if err != nil {
log.Fatal(err)
}
element := false
iNav := 0
doc.Find("h1,h2,h3,h4,caption,figcaption,a,nav,div.equation,ul.references").Each(func(i int, s *goquery.Selection) {
// Inquire whether nav element is present
if s.Is("nav") {
// Check that nav is before any other element
if element {
fmt.Println("Error: <nav> present after a section/caption/figcaption element on file:", fileName)
fmt.Println(" This is not supported.")
os.Exit(1)
}
// Mark that navigation bar is already present in file.
BookStructure.SectionFiles[iSectionFile].NewNav = false
// Inquire file references in navigation bar
s.Find("a").Each(func(i int, ss *goquery.Selection) {
// Save a new nav file reference
BookStructure.SectionFiles[iSectionFile].NavList = append(BookStructure.SectionFiles[iSectionFile].NavList, ss.AttrOr("href", "???"))
iNav++
})
return
} else {
element = true
}
if s.Is("a") { // Link detected
// Check if link is pointing into the book
if iNav > 0 {
// Link from the navigation bar (ignore it)
iNav--
return
}
href, exists := s.Attr("href")
if !exists {
fmt.Printf("Warning: link <a> without href attribute is ignored in file %s\n", fileName)
BookStructure.SectionFiles[iFile].Elements = append(BookStructure.SectionFiles[iFile].Elements,
ElementType{"<a", "</a>", "", "", "", "", false, "", false})
return
}
if strings.Index(href, "/") == -1 {
// No "/", so link internal to the book
var targetFileName string
var targetID string
tooltip := s.AttrOr("title", "")
IDstart := strings.Index(href, "#")
if IDstart == -1 {
// No "#"
targetFileName = href
targetID = ""
} else if IDstart == 0 {
// "#xxx", so no file name
if len(href) <= 1 {
fmt.Printf("Error: Wrong link '<a href=\"#\">' in file %s\n", fileName)
os.Exit(1)
}
targetFileName = fileName
targetID = href[IDstart+1:]
} else {
// "xxx#yyy"
if IDstart+1 >= len(href) {
targetFileName = href[0:IDstart]
targetID = ""
} else {
targetFileName = href[0:IDstart]
targetID = href[IDstart+1:]
}
}
BookStructure.SectionFiles[iFile].Elements = append(BookStructure.SectionFiles[iFile].Elements,
ElementType{"<a", "</a>", s.Text(), href, targetFileName, tooltip, false, targetID, false})
} else {
BookStructure.SectionFiles[iFile].Elements = append(BookStructure.SectionFiles[iFile].Elements,
ElementType{"<a", "</a>", "", "", "", "", false, "", false})
/*
// External link, check whether it exists
_, err := http.Get(href);
if err != nil {
fmt.Printf("Error when opening link %s\n", href)
*/
}
return
}
// Store id's of references
if s.Is("ul.references") { // references detected
s.Find("li").Each(func(i int, s2 *goquery.Selection) {
id, exists := s2.Attr("id")
if !exists || id == "" || id == "#" {
// No id is present, ignore this list item
return
} else {
// Find text between <strong> ... </strong>
tooltip := ""
s2.Find("strong").Each(func(i int, s3 *goquery.Selection) {
tooltip = s3.Text()
})
// Store id as bookmark
title, exists := s2.Attr("title")
if exists && title != "" {
addBookmark(id, fileName, title, tooltip)
} else {
addBookmark(id, fileName, "", tooltip)
}
}
})
return
}
// Inquire element id and content (= text + label)
var label string
newID := false
id, exists := s.Attr("id")
if !exists || id == "" || id == "#" {
// If no id present, introduce a random value for id
id = strconv.Itoa(int(r.Int31()))
newID = true
}
// text := s.Text()
text, _ := s.Html()
modified := false // = true, if text is modified
var newText string
// Actual index of SectionFiles
iFile := len(BookStructure.SectionFiles) - 1
// Store information
if s.Is("h1") {
Counters.iFigCaption = 0
Counters.iCaption = 0
Counters.iEquation = 0
// Determine chapter number
isec := minInt(len("Chapter"), len(text))
if text[0:isec] == "Chapter" {
// Increment chapter number
Counters.ih1_digit++
Counters.last_h1_type = "Chapter"
} else {
isec = minInt(len("Appendix"), len(text))
if text[0:isec] == "Appendix" {
// Increment appendix number
Counters.ih1_letter++
Counters.last_h1_type = "Appendix"
} else {
Counters.last_h1_type = ""
}
}
// Update h1 section number if necessary and make a new h1 entry in BookStructure
newText, modified, label = updateSectionText(text, 1, 0, 0, 0)
BookStructure.Sections = append(BookStructure.Sections,
SectionType{fileName, id, label, newText, modified,
make([]SectionType, 0, 5),
make([]CaptionType, 0, 5),
make([]EquationType, 0, 5)})
BookStructure.SectionFiles[iFile].Elements = append(BookStructure.SectionFiles[iFile].Elements,
ElementType{"<h1", "</h1>", text, "", newText, "", modified, id, newID})
BookStructure.SectionFiles[iFile].H1Index = len(BookStructure.Sections) - 1
*H1Index_old = len(BookStructure.Sections) - 1
} else if s.Is("h2") {
i1 := len(BookStructure.Sections) - 1
if i1 < 0 {
fmt.Println("h2 defined before h1 in file:", fileName)
os.Exit(1)
}
i2 := len(BookStructure.Sections[i1].Sections)
newText, modified, label = updateSectionText(text, 2, i2+1, 0, 0)
BookStructure.Sections[i1].Sections =
append(BookStructure.Sections[i1].Sections,
SectionType{fileName, id, label, newText, modified,
make([]SectionType, 0, 5),
make([]CaptionType, 0, 5),
make([]EquationType, 0, 5)})
BookStructure.SectionFiles[iFile].Elements = append(BookStructure.SectionFiles[iFile].Elements,
ElementType{"<h2", "</h2>", text, "", newText, "", modified, id, newID})
BookStructure.SectionFiles[iFile].H1Index = *H1Index_old
} else if s.Is("h3") {
i1 := len(BookStructure.Sections) - 1
if i1 < 0 {
fmt.Println("h2 defined before h1 in file:", fileName)
os.Exit(1)
}
i2 := len(BookStructure.Sections[i1].Sections) - 1
if i2 < 0 {
fmt.Println("h3 defined before h2 in file:", fileName)
os.Exit(1)
}
i3 := len(BookStructure.Sections[i1].Sections[i2].Sections)
newText, modified, label = updateSectionText(text, 3, i2+1, i3+1, 0)
BookStructure.Sections[i1].Sections[i2].Sections =
append(BookStructure.Sections[i1].Sections[i2].Sections,
SectionType{fileName, id, label, newText, modified,
make([]SectionType, 0, 5),
make([]CaptionType, 0, 5),
make([]EquationType, 0, 5)})
BookStructure.SectionFiles[iFile].Elements = append(BookStructure.SectionFiles[iFile].Elements,
ElementType{"<h3", "</h3>", text, "", newText, "", modified, id, newID})
BookStructure.SectionFiles[iFile].H1Index = *H1Index_old
} else if s.Is("h4") {
i1 := len(BookStructure.Sections) - 1
if i1 < 0 {
fmt.Println("h2 defined before h1 in file:", fileName)
os.Exit(1)
}
i2 := len(BookStructure.Sections[i1].Sections) - 1
if i2 < 0 {
fmt.Println("h3 defined before h2 in file:", fileName)
os.Exit(1)
}
i3 := len(BookStructure.Sections[i1].Sections[i2].Sections) - 1
if i3 < 0 {
fmt.Println("h4 defined before h3 in file:", fileName)
os.Exit(1)
}
i4 := len(BookStructure.Sections[i1].Sections[i2].Sections[i3].Sections)
newText, modified, label = updateSectionText(text, 4, i2+1, i3+1, i4+1)
BookStructure.Sections[i1].Sections[i2].Sections[i3].Sections =
append(BookStructure.Sections[i1].Sections[i2].Sections[i3].Sections,
SectionType{fileName, id, label, newText, modified,
make([]SectionType, 0, 1),
make([]CaptionType, 0, 1),
make([]EquationType, 0, 5)})
BookStructure.SectionFiles[iFile].Elements = append(BookStructure.SectionFiles[iFile].Elements,
ElementType{"<h4", "</h4>", text, "", newText, "", modified, id, newID})
BookStructure.SectionFiles[iFile].H1Index = *H1Index_old
} else if s.Is("caption") || s.Is("figcaption") {
var fig bool
var iCap int
if s.Is("caption") {
fig = false
Counters.iCaption++
iCap = Counters.iCaption
} else {
fig = true
Counters.iFigCaption++
iCap = Counters.iFigCaption
}
i1 := len(BookStructure.Sections) - 1
if i1 < 0 {
fmt.Printf("caption/figcaption in file \"%s\" defined before first h1 defined in book", fileName)
os.Exit(1)
}
newText, modified, label = updateCaptionText(text, fig, iCap)
i2 := len(BookStructure.Sections[i1].Sections) - 1
if i2 < 0 {
BookStructure.Sections[i1].Captions =
append(BookStructure.Sections[i1].Captions, CaptionType{fileName, id, newText, modified, fig})
} else {
i3 := len(BookStructure.Sections[i1].Sections[i2].Sections) - 1
if i3 < 0 {
BookStructure.Sections[i1].Sections[i2].Captions =
append(BookStructure.Sections[i1].Sections[i2].Captions,
CaptionType{fileName, id, newText, modified, fig})
} else {
i4 := len(BookStructure.Sections[i1].Sections[i2].Sections[i3].Sections) - 1
if i4 < 0 {
BookStructure.Sections[i1].Sections[i2].Sections[i3].Captions =
append(BookStructure.Sections[i1].Sections[i2].Sections[i3].Captions,
CaptionType{fileName, id, newText, modified, fig})
} else {
BookStructure.Sections[i1].Sections[i2].Sections[i3].Sections[i4].Captions =
append(BookStructure.Sections[i1].Sections[i2].Sections[i3].Sections[i4].Captions,
CaptionType{fileName, id, newText, modified, fig})
}
}
}
if fig {
BookStructure.SectionFiles[iFile].Elements = append(BookStructure.SectionFiles[iFile].Elements,
ElementType{"<figcaption", "</figcaption>", text, "", newText, "", modified, id, newID})
} else {
BookStructure.SectionFiles[iFile].Elements = append(BookStructure.SectionFiles[iFile].Elements,
ElementType{"<caption", "</caption>", text, "", newText, "", modified, id, newID})
}
} else if s.Is("div.equation") {
Counters.iEquation++
i1 := len(BookStructure.Sections) - 1
if i1 < 0 {
fmt.Printf("<div class=\"equation\"> in file \"%s\" defined before first h1 defined in book", fileName)
os.Exit(1)
}
newText, modified, label = updateEquationText(text)
i2 := len(BookStructure.Sections[i1].Sections) - 1
if i2 < 0 {
BookStructure.Sections[i1].Equations =
append(BookStructure.Sections[i1].Equations, EquationType{fileName, id, newText, modified})
} else {
i3 := len(BookStructure.Sections[i1].Sections[i2].Sections) - 1
if i3 < 0 {
BookStructure.Sections[i1].Sections[i2].Equations =
append(BookStructure.Sections[i1].Sections[i2].Equations,
EquationType{fileName, id, newText, modified})
} else {
i4 := len(BookStructure.Sections[i1].Sections[i2].Sections[i3].Sections) - 1
if i4 < 0 {
BookStructure.Sections[i1].Sections[i2].Sections[i3].Equations =
append(BookStructure.Sections[i1].Sections[i2].Sections[i3].Equations,
EquationType{fileName, id, newText, modified})
} else {
BookStructure.Sections[i1].Sections[i2].Sections[i3].Sections[i4].Equations =
append(BookStructure.Sections[i1].Sections[i2].Sections[i3].Sections[i4].Equations,
EquationType{fileName, id, newText, modified})
}
}
}
BookStructure.SectionFiles[iFile].Elements = append(BookStructure.SectionFiles[iFile].Elements,
ElementType{"<div class=\"equation\"", "</div>", text, "", newText, "", modified, id, newID})
}
if modified || newID {
BookStructure.SectionFiles[iFile].Modified = true
}
if newID {
// Print information about introduced ID
iElem := len(BookStructure.SectionFiles[iFile].Elements) - 1
elem := BookStructure.SectionFiles[iFile].Elements[iElem]
fmt.Printf(" Element id introduced: %s id=\"%s\">%s%s\n",
elem.StartTag, id, newText, elem.EndTag)
}
// Store bookmark
if s.Is("div.equation") {
addBookmark(id, fileName, label, "") // no tool tip for a link to an equation
} else {
addBookmark(id, fileName, label, newText)
}
})
}
func addBookmark(id string, fileName string, label string, tooltip string) {
key, present := Bookmarks[id]
if present {
fmt.Printf("ERROR: Bookmark with id = \"%s\" present twice:\n", id)
fmt.Printf(" First location: FileName = \"%s\", Label = \"%s\", Tooltip =\"%s\"\n", key.FileName, key.Label, key.Tooltip)
fmt.Printf(" Second location: FileName = \"%s\", Label = \"%s\", Tooltip =\"%s\"\n", fileName, label, tooltip)
} else {
Bookmarks[id] = BookmarkType{fileName, label, tooltip}
}
}
// Integer minimum
func minInt(a, b int) int {
if a <= b {
return a
} else {
return b
}
}
// Update text with correct section number
func updateSectionText(text string, level, nr2, nr3, nr4 int) (newText string, modified bool, label string) {
// If section needs not to be numbered, return
if Counters.last_h1_type == "" {
newText = text
modified = false
label = text
return
}
// Section number needs to be numbered
var secStr string // Required section number as string
// Determine required section number
if Counters.last_h1_type == "Chapter" {
switch level {
case 1:
secStr = fmt.Sprintf("Chapter %d ", Counters.ih1_digit)
case 2:
secStr = fmt.Sprintf("%d.%d ", Counters.ih1_digit, nr2)
case 3:
secStr = fmt.Sprintf("%d.%d.%d ", Counters.ih1_digit, nr2, nr3)
case 4:
secStr = fmt.Sprintf("%d.%d.%d.%d ", Counters.ih1_digit, nr2, nr3, nr4)
default:
fmt.Printf("Wrong argument level (= %d) when calling function updateText.\nMust be 1,2,3 or 4\n", level)
os.Exit(1)
}
} else {
h1_letter := string(letters[Counters.ih1_letter-1])
switch level {
case 1:
secStr = fmt.Sprintf("Appendix %s ", h1_letter)
case 2:
secStr = fmt.Sprintf("%s.%d ", h1_letter, nr2)
case 3:
secStr = fmt.Sprintf("%s.%d.%d ", h1_letter, nr2, nr3)
case 4:
secStr = fmt.Sprintf("%s.%d.%d.%d ", h1_letter, nr2, nr3, nr4)
default:
fmt.Printf("Wrong argument level (= %d) when calling function updateText.\nMust be 1,2,3 or 4\n", level)
os.Exit(1)
}
}
label = secStr[0 : len(secStr)-1]
// Has text the required section number?
isec := minInt(len(secStr), len(text))
if text[0:isec] == secStr {
// text has the required section number
newText = text
modified = false
} else {
// text has no or wrong section number -> correct section number
var index []int
byteText := []byte(text)
if Counters.last_h1_type == "Chapter" {
switch level {
case 1:
index = validSection1.FindIndex(byteText)
case 2:
index = validSection2.FindIndex(byteText)
case 3:
index = validSection3.FindIndex(byteText)
case 4:
index = validSection4.FindIndex(byteText)
}
} else {
switch level {
case 1:
index = validSection1_Appendix.FindIndex(byteText)
case 2:
index = validSection2_Appendix.FindIndex(byteText)
case 3:
index = validSection3_Appendix.FindIndex(byteText)
case 4:
index = validSection4_Appendix.FindIndex(byteText)
}
}
if index == nil {
// no Section number was present
newText = secStr + text
fmt.Println(" Section number added:", newText)
} else {
// Section number was present: replace it with correct one
newText = secStr + string(byteText[index[1]:])
fmt.Println(" Section number updated:", newText)
}
modified = true
}
return
}
// Update text with correct caption number
func updateCaptionText(text string, fig bool, nrCap int) (newText string, modified bool, label string) {
// If caption needs not to be numbered, return
if Counters.last_h1_type == "" {
newText = text
modified = false
label = text
return
}
// Caption number needs to be numbered
var capStr string // Required caption number as string
// Determine required caption number
if Counters.last_h1_type == "Chapter" {
if fig {
capStr = fmt.Sprintf("Figure %d-%d: ", Counters.ih1_digit, nrCap)
} else {
capStr = fmt.Sprintf("Table %d-%d: ", Counters.ih1_digit, nrCap)
}
} else {
h1_letter := string(letters[Counters.ih1_letter-1])
if fig {
capStr = fmt.Sprintf("Figure %s-%d: ", h1_letter, nrCap)
} else {
capStr = fmt.Sprintf("Table %s-%d: ", h1_letter, nrCap)
}
}
label = capStr[0 : len(capStr)-2]
// Has text the required caption number?
icap := minInt(len(capStr), len(text))
if text[0:icap] == capStr {
// text has the required caption number
newText = text
modified = false
} else {
// text has no or wrong caption number -> correct caption number
var index []int
byteText := []byte(text)
if Counters.last_h1_type == "Chapter" {
if fig {
index = validFigCaption.FindIndex(byteText)
} else {
index = validCaption.FindIndex(byteText)
}
} else {
if fig {
index = validFigCaption_Appendix.FindIndex(byteText)
} else {
index = validCaption_Appendix.FindIndex(byteText)
}
}
if index == nil {
// no caption number was present
newText = capStr + text
fmt.Println(" Caption number added:", newText)
} else {
// Caption number was present: replace it with correct one
newText = capStr + string(byteText[index[1]:])
fmt.Println(" Caption number updated:", newText)
}
modified = true
}
return
}
// Update text with correct equation number
func updateEquationText(text string) (newText string, modified bool, label string) {
// If section needs not to be numbered, return
if Counters.last_h1_type == "" {
newText = text
modified = false
label = ""
return
}