-
Notifications
You must be signed in to change notification settings - Fork 2
/
pptext.go
4066 lines (3608 loc) · 124 KB
/
pptext.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
/*
filename: pptext.go
author: Roger Frank
license: GPL
*/
/*
2019.04.10a "show word in context" incorporates Verbose flag
adds "-----" separator in edit distance checks
2019.04.10b case-insensitive Mr/Mr. (&c.) checks
2019.04.11 hyphenation and spaced pair check boundary code
2019.04.12 hyp/non hyp blocked in edit distance checks
2019.04.14a bugfix: tcHypSpaceConsistency needed FindAllStringSubmatch
2019.04.16 adds timing and expensive check flag (borrowing -x)
2019.04.18 add minor divider in hyphenation and non-hyphenated check
2019.04.21 adds ability to skip spell-check (which also kills edit-distance)
2019.04.21a curly quote check itemize suspects; ditto special situation checks
2019.04.29 add minor divider in hyphenation and spaced pair check
2019.05.02 add debug code for memory usage
2019.05.03 add file encoding report to header lines
2019.05.05 complete rewrite hyp-space consistency for memory optimization
2019.05.07 incorrectly split paragraph to work within a block quote
2019.05.14 hook for skipping hyphenation checks (filename start with "%")
corrections to parsing for Dr, etc.
2019.05.16 user can choose selected tests. default is "a" (all)
tests are
q: smart quote scan
s: spellcheck
e: edit distance
t: text checks
1: tcHypConsistency subtest
2: tcHypSpaceConsistency2 subtest
j: jeebies
2019.05.19 corrected good word list count calculation
2019.05.26 use \P{L} for word boundary in (2) text checks
2019.05.31 verbose flag honored in text-check
2019.06.06 off-by-one in dash check adjusted
2019.07.10 scanno check now case insensitive
2019.07.12 numeric scannos checked once
2019.07.15 added para ends with comma
2019.08.15 changed handling of hyphenated words in lookup; added "am./a. m." checks
2019.09.02 spacing in book-level checks
2020.02.27 added compass direction consistency checks
2020.07.05 character checks bug on same line as &c fixed
*/
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"sort"
"strconv"
"strings"
"time"
"unicode"
"unicode/utf8"
)
var (
gitHash string // git hash when the exec was built
buildTime string // time when when the exec was built
)
const SHOWTIMING bool = false
var sw []string // suspect words list
var rs []string // array of strings for local aggregation
var pptr []string // pptext report
var puncStyle string // punctuation style American or British
// scanno list. all lower case. curly apostrophes
var scannoWordlist []string // scanno word list
// good word list. may have straight or curly apostrophes, mixed case
var goodWordlist []string // good word list specified by user
// mixed case ok words in text
var okwords []string // ok words in text
// the lwl is a slice of slices of strings, one per line. order maintained
// lwl[31] contains a slice of strings containing the words on line "31"
var lwl []([]string)
// wordListMapCount has all words in the book and their frequency of occurence
// wordListMapCount["chocolate"] -> 3 means that word occurred three times
var wordListMapCount map[string]int
// wordListMapLines has all words in the book and their frequency of occurence
// wordListMapLines["chocolate"] -> 415,1892,2295 means that word occurred on those three lines
var wordListMapLines map[string]string
// paragraph buffer
var pbuf []string
// working buffer
var wbuf []string
// heMap and beMap maps map word sequences to relative frequency of occurence
// higher values mean more frequently seen
var heMap map[string]int
var beMap map[string]int
// debug messages
var dbuf []string
/* ********************************************************************** */
/* */
/* utility functions */
/* */
/* ********************************************************************** */
// word is entirely numeric or entirely consistent case Roman numerals
var re2a *regexp.Regexp = regexp.MustCompile(`[0123456789]+`)
var re2b *regexp.Regexp = regexp.MustCompile(`[ivxlc]+`)
var re2c *regexp.Regexp = regexp.MustCompile(`[IVXLC]+`)
//re2a := regexp.MustCompile(`[0123456789]+`)
//re2b := regexp.MustCompile(`[ivxlc]+`)
//re2c := regexp.MustCompile(`[IVXLC]+`)
func isRomOrNum(s string) bool {
t1 := re2a.ReplaceAllString(s, "")
t2 := re2b.ReplaceAllString(s, "")
t3 := re2c.ReplaceAllString(s, "")
return (t1 == "" || t2 == "" || t3 == "")
}
// return true if slice contains string
//
func contains(s []string, e string) bool {
for _, a := range s {
if a == e {
return true
}
}
return false
}
// protect <, >
func pt(line string) string {
line = strings.Replace(line, "<", "<", -1)
line = strings.Replace(line, ">", ">", -1)
return line
}
// return true if both straight and curly quotes detected
//
func straightCurly(lpb []string) bool {
curly := false
straight := false
for _, line := range lpb {
if strings.ContainsAny(line, "\"'") {
straight = true
}
if strings.ContainsAny(line, "“”‘’") {
curly = true
}
if straight && curly {
break
}
}
return straight && curly
}
// text-wrap string into string with embedded newlines
// with leader 9 spaces after first
//
// avoid very short lines
// if final newline is within 8 characters of end, use a space
func wraptext9(s string) string {
s2 := ""
runecount := 0
totalrunes := utf8.RuneCountInString(s)
// rc := utf8.RuneCountInString(s)
for len(s) > 0 {
r, size := utf8.DecodeRuneInString(s) // first
runecount++
// replace space with newline (break on space)
if runecount >= 70 && runecount < totalrunes-8 && r == ' ' {
s2 += "\n "
runecount = 0
} else {
s2 += string(r) // append single rune to string
}
s = s[size:] // chop off rune
}
return s2
}
// text-wrap string into string with embedded newlines
// left indent 2 spaces
//
func wraptext2(s string) string {
re := regexp.MustCompile(`\s+`)
s = re.ReplaceAllString(s, " ")
s2 := " " // start with indent
runecount := 0
for utf8.RuneCountInString(s) > 0 {
r, size := utf8.DecodeRuneInString(s) // first rune
runecount++ // how many we have collected
// first space after rune #68 becomes newline
if runecount >= 68 && r == ' ' {
s2 += "\n "
runecount = 0
} else {
s2 += string(r) // append single rune to string
}
s = s[size:] // chop off rune
}
return s2
}
/* ********************************************************************** */
/* */
/* parameters */
/* */
/* ********************************************************************** */
type params struct {
Infile string
Outdir string // target directory
Wlang string
Alang string
GWFilename string
Experimental bool
Verbose bool
Revision bool
Debug bool
SelectedTests string // a=all, b-z0-9=selected tests
}
var p params
/* ********************************************************************** */
/* */
/* file operations */
/* */
/* ********************************************************************** */
var BOM = string([]byte{239, 187, 191}) // UTF-8 Byte Order Mark
// readLn returns a single line (without the ending \n)
// from the input buffered reader.
// An error is returned if there is an error with the
// buffered reader.
func readLn(r *bufio.Reader) (string, error) {
var (
isPrefix bool = true
err error = nil
line, ln []byte
)
for isPrefix && err == nil {
line, isPrefix, err = r.ReadLine()
ln = append(ln, line...)
}
return string(ln), err
}
func readText(infile string) []string {
wb := []string{}
f, err := os.Open(infile)
if err != nil {
s := fmt.Sprintf("error opening file: %v\n", err)
pptr = append(pptr, s)
} else {
r := bufio.NewReader(f)
s, e := readLn(r) // read first line
for e == nil { // continue as long as there are no errors reported
wb = append(wb, s)
s, e = readLn(r)
}
}
// successfully read. remove BOM if present
if len(wb) > 0 {
wb[0] = strings.TrimPrefix(wb[0], BOM)
}
return wb
}
var HHEAD = []string{
"<html>",
"<head>",
"<meta charset=\"utf-8\">",
"<meta name=viewport content=\"width=device-width, initial-scale=1\">",
"<title>pptext report</title>",
"<style type=\"text/css\">",
"body { margin-left: 1em;}",
".red { color:red; background-color: #FFFFAA; }",
".green { color:green; background-color: #FFFFAA; }",
".black { color:black; }",
".dim { color:#999999; }",
"</style>",
"</head>",
"<body>",
"<pre>"}
var HFOOT = []string{
"</pre>",
"</body>",
"</html>"}
// saves HTML report to report.html
//
func saveHtml(a []string, outdir string) {
f2, err := os.Create(outdir + "/report.html") // specified report file for text output
if err != nil {
log.Fatal(err)
}
defer f2.Close()
for _, line := range HHEAD {
s := strings.Replace(line, "\n", "\r\n", -1)
fmt.Fprintf(f2, "%s\r\n", s)
}
// as I emit the HTML, look for predefined tokens that generate spans
// or other info.
// ☰ <span class='red'>
// ☱ <span class='green'>
// ☲ <span class='dim'>
// ☳ <span class='black'>
// ☷ </span>
// ◨ <i>
// ◧ </i>
for _, line := range a {
s := strings.Replace(line, "\n", "\r\n", -1)
// there should not be any HTML tags in the report
// unless they are specifically marked
if !strings.ContainsAny(s, "☳") {
s = strings.Replace(s, "<", "<span class='green'>❬", -1)
s = strings.Replace(s, ">", "❭</span>", -1)
}
s = strings.Replace(s, "☰", "<span class='red'>", -1)
s = strings.Replace(s, "☱", "<span class='green'>", -1)
s = strings.Replace(s, "☲", "<span class='dim'>", -1)
s = strings.Replace(s, "☳", "<span class='black'>", -1)
s = strings.Replace(s, "◨", "<i>", -1)
s = strings.Replace(s, "◧", "</i>", -1)
s = strings.Replace(s, "☷", "</span>", -1)
s = strings.Replace(s, "☳", "", -1) // HTML-only line flag
fmt.Fprintf(f2, "%s\r\n", s)
}
for _, line := range HFOOT {
s := strings.Replace(line, "\n", "\r\n", -1)
fmt.Fprintf(f2, "%s\r\n", s)
}
}
// create an empty stack to hold punctuation events
type puncEvent struct {
punc string
lnum int
}
type stack []puncEvent
// stack methods
func (s stack) Push(v puncEvent) stack {
s = append(s, v) // put event on stack
return s // return the stack
}
// returns the stack and the puncEvent
// if pop returns -1 for a puncEvent line number,
// we tried to pop from an empty stack
func (s stack) Pop() (stack, puncEvent) {
l := len(s)
rval := puncEvent{"", -1} // default to return if empty stack
if len(s) > 0 { // have something to return
rval = s[l-1] // get last element
if l > 1 {
s = s[:l-1] // pop that off stack
} else {
s = []puncEvent{} // now empty
}
}
return s, rval // return stack and event
}
func (s stack) Peek() (stack, puncEvent) {
l := len(s)
rval := puncEvent{"", -1} // default to return if empty stack
if len(s) > 0 { // have something to return
rval = s[l-1] // get last element
}
return s, rval
}
func (s stack) Dump() (stack, string) {
t := ""
for _, pevent := range s {
t += pevent.punc
}
return s, t
}
/* tokens use in text
▿ certain apostrophe
▾ very probably apostrophe
ⴵ apostrophe on "-ing" word
▵ aspell reported apostrophe
⸢ open single quote
⸣ close single quote
*/
type xpuncEvent struct {
punc string // punctuation mark
lnum int // line number
lpos int // position on line
}
var pstack []xpuncEvent
func Push(v xpuncEvent) {
pstack = append(pstack, v) // put event on stack
}
func Pop() xpuncEvent {
t := xpuncEvent{"", -1, -1} // default (empty) value
if len(pstack) > 0 {
t = pstack[len(pstack)-1] // get last event on stack
pstack = pstack[:len(pstack)-1] // remove it
}
return t
}
func Peek() xpuncEvent {
t := xpuncEvent{"", -1, -1} // default (empty) value
if len(pstack) > 0 {
t = pstack[len(pstack)-1] // get last event on stack
}
return t
}
// aspell qualify words in map
// return map of only those recognized by aspell
func asqual(m map[string]int) map[string]int {
// build a slice from the map
words := make([]string, 0, len(m))
for word := range m {
words = append(words, word)
}
words = runAspell(words, "")
if len(words) > 0 {
// some derived words not cleared by aspell
for _, s := range words {
delete(m, s) // remove from map
}
}
return m
}
// puts output in scanreport.txt in same folder as results.html
func puncScan() []string {
rs := []string{} // returned and displayed in pptext report
prs := []string{} // saved to scanreport.txt
if puncStyle == "British" {
rs = append(rs, "Smart Quote Checks skipped (British-style punctuation)")
return rs
}
rs = append(rs, "☳<a name='sqs'></a>")
rs = append(rs, "☳"+strings.Repeat("*", 80))
rs = append(rs, fmt.Sprintf("* %-76s *", fmt.Sprintf("SMART QUOTE SCAN")))
rs = append(rs, strings.Repeat("*", 80))
rs = append(rs, "")
// here we can run a curly quote scan
// build the header
prs = append(prs, BOM+"SMART QUOTE CHECKS (overlay format)")
prs = append(prs, "suspect punctuation marked with '@' character")
prs = append(prs, "-------------------------------------------------------------------")
prs = append(prs, "")
// local working buffer to obfuscate
lwbuf := make([]string, len(wbuf))
copy(lwbuf, wbuf) // FIXME throws off sentinel
lwbuf = append(lwbuf, "")
// another copy to annotate and provide to user
dwbuf := make([]string, len(wbuf))
copy(dwbuf, wbuf)
// classify apostrophes/CSQ: mid-word contractions, lists
//
re81 := regexp.MustCompile(`(\p{L})’(\p{L})`) // mid-word contraction
// traililng apostrophe common word list
re72 := regexp.MustCompile(`(?i)(^|\P{L})(wher|ther|o|an|ha|t)’($|\P{L})`)
// leading apostrophe common word list
re73 := regexp.MustCompile(`(?i)(^|\P{L})’(way|twas|twill|twould|twere|uns|fore|most|em|ud|cos|cept|ll|less|\d+)($|\P{L})`)
for i, _ := range lwbuf {
lwbuf[i] = re81.ReplaceAllString(lwbuf[i], "$1▿$2")
lwbuf[i] = re81.ReplaceAllString(lwbuf[i], "$1▿$2") // for multiple internal quotes
lwbuf[i] = re72.ReplaceAllString(lwbuf[i], "$1$2▿$3")
lwbuf[i] = re73.ReplaceAllString(lwbuf[i], "$1▿$2$3")
}
awords := make(map[string]int) // apostrophe words
// accept contractions in good word list
for _, word := range goodWordlist {
if strings.Contains(word, "’") {
rword := strings.Replace(word, "’", "▿", -1)
re51 := regexp.MustCompile(`(?i)(?P<1W>^|\P{L})` + word + `(?P<2W>$|\P{L})`)
for i, _ := range lwbuf {
lwbuf[i] = re51.ReplaceAllString(lwbuf[i], "${1W}"+rword+"${2W}")
}
}
}
/*
// detect all words/count using trailing apostrophes in the file
re37 := regexp.MustCompile(`(^|\P{L})(\p{L}+’)(\P{L}|$)`) // ending in "’"
for _, line := range lwbuf {
t := re37.FindAllStringSubmatch(line, -1)
for _,u := range t {
awords[u[2]] += 1
}
}
*/
// detect all words/count using leading apostrophes in the file
re38 := regexp.MustCompile(`(^|\P{L})(’\p{L}+)(\P{L}|$)`) // starting with "’"
for _, line := range lwbuf {
t := re38.FindAllStringSubmatch(line, -1)
for _, u := range t {
awords[u[2]] += 1
}
}
// if word with apostrophe occurs more than once, mark the apostrophe as ▾
for key, value := range awords {
if value > 1 {
rkey := strings.Replace(key, "’", "▾", -1)
for j, _ := range lwbuf {
lwbuf[j] = strings.Replace(lwbuf[j], key, rkey, -1)
}
}
}
// find all phrases that occur at least twice
// mark ends as quote pairs.
re29 := regexp.MustCompile(`(?P<1W>‘)(?P<2W>[^’]+)(?P<3W>’)`)
i := 0
for ; i < len(lwbuf)-1; i++ {
// temp join two lines
ccl1 := len(lwbuf[i])
s := lwbuf[i] + " " + lwbuf[i+1]
s = re29.ReplaceAllString(s, "⸢${2W}⸣")
// now split and put it back
lwbuf[i] = s[:ccl1]
lwbuf[i+1] = s[ccl1+1:]
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// thinkin’ ?= thinking processing
// if a word ends in in’ change it to -ing and see if that's a valid word
// if it is, protect it
re51 := regexp.MustCompile(`(?P<a1>^|\P{L})(?P<a2>\p{L}+?in)’(?P<a3>\P{L}|$)`) // ending in "in’"
cwords := make(map[string]int)
for i, _ := range lwbuf {
t := re51.FindAllStringSubmatch(lwbuf[i], -1)
for _, u := range t {
cwords[u[2]+"g"] = 1
}
}
// reduce map of candidate words to only those ok by aspell
cwords = asqual(cwords)
// cloak the ok ones with ▵ replacing "’"
for k, _ := range cwords {
tword := k[:len(k)-1] + "’"
pword := k[:len(k)-1] + "▵"
for i, _ := range lwbuf {
lwbuf[i] = strings.Replace(lwbuf[i], tword, pword, -1)
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// ’ouse ?= house processing
// if a word startsd with ’, change ’ to "h" and see if that's a valid word
// if it is, protect it
re52 := regexp.MustCompile(`(?P<a1>^|\P{L})’(?P<a2>\p{L}+)(?P<a3>\P{L}|$)`) // start with "’"
cwords = make(map[string]int)
for i, _ := range lwbuf {
t := re52.FindAllStringSubmatch(lwbuf[i], -1)
for _, u := range t {
cwords["h"+u[2]] = 1
}
}
// reduce map of candidate words to only those ok by aspell
cwords = asqual(cwords)
// cloak the ok ones with ▵ replacing "’"
for k, _ := range cwords {
tword := "’" + k[1:]
pword := "▵" + k[1:]
for i, _ := range lwbuf {
lwbuf[i] = strings.Replace(lwbuf[i], tword, pword, -1)
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
/*
perhaps should be disabled: fails too readily by not being able to distinguish:
The dogs’ barking could be heard for miles. (as an apostrophe)
The place has ‘gone to the dogs’ very quickly. (as a close single quote)
*/
// minutes’ ?= minutes processing
// minutes’ -> minute | valid ? protect it : leave it
re53 := regexp.MustCompile(`(?P<a1>^|\P{L})(?P<a2>\p{L}+)s’(?P<a3>\P{L}|$)`) // end in "s’"
cwords = make(map[string]int)
for i, _ := range lwbuf {
t := re53.FindAllStringSubmatch(lwbuf[i], -1)
for _, u := range t {
cwords[u[2]] = 1
}
}
// reduce map of candidate words to only those ok by aspell
cwords = asqual(cwords)
// cloak the ok ones with ▵ replacing "’"
for k, _ := range cwords {
tword := k + "s’"
pword := k + "s▵"
for i, _ := range lwbuf {
lwbuf[i] = strings.Replace(lwbuf[i], tword, pword, -1)
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// lwbuf is fully munged. scan for possible errors
re80 := regexp.MustCompile(`[“”‘’]`)
sqreport := false
dqreport := false
anyreport := false
for i := 0; i < len(lwbuf); i++ {
parabreak := false
if strings.TrimSpace(lwbuf[i]) == "" {
parabreak = true
}
if parabreak {
// paragraph break.
// we are sitting on a blank line between paragraphs or
// at the EOF one past the last line.
// process what we have and reset
// anything on stack at this point is an error
if len(pstack) > 0 {
stacklst := ""
for _, t61 := range pstack {
stacklst = stacklst + " " + t61.punc
}
stacklst = strings.TrimSpace(stacklst)
anyreport = true
dwbuf[i-1] += fmt.Sprintf("[@NESK %s]", stacklst) // non-empty stack at paragraph end
}
pstack = []xpuncEvent{}
sqreport = false
dqreport = false
continue
}
m := re80.FindAllStringSubmatchIndex(lwbuf[i], -1)
for _, t := range m {
rune, _ := utf8.DecodeRuneInString(lwbuf[i][t[0]:])
r := string(rune)
// if we hit an ODQ, check if it follows another ODQ
// always push
if r == "“" {
r2 := Peek()
if !dqreport && r2.punc == "“" {
// consecutive ODQ
anyreport = true
dqreport = true
dwbuf[i] = dwbuf[i][:t[0]] + "[@CODQ]" + dwbuf[i][t[0]:]
}
Push(xpuncEvent{r, i, t[0]})
}
// close double quote should be paired with an open double quote on the stack
// if so, remove the ODQ on the stack
// pop only if expected, else leave stack intact
if r == "”" {
r2 := Peek()
if r2.punc == "“" { // expected
_ = Pop()
} else {
anyreport = true
dwbuf[i] = dwbuf[i][:t[0]] + "[@UCDQ]" + dwbuf[i][t[0]:]
}
}
// open single quote, check if it follows another OSQ
// always push
if r == "‘" {
r2 := Peek()
if !sqreport && r2.punc == "‘" {
// consecutive OSQ
anyreport = true
sqreport = true
dwbuf[i] = dwbuf[i][:t[0]] + "[@COSQ]" + dwbuf[i][t[0]:]
}
Push(xpuncEvent{r, i, t[0]})
}
// close single quote should be paired with an open single quote on the stack
// if so, remove the OSQ on the stack
// pop only if expected, else leave stack intact
if r == "’" {
r2 := Peek()
if r2.punc == "‘" { // expected
_ = Pop()
} else {
anyreport = true
dwbuf[i] = dwbuf[i][:t[0]] + "[@UCSQ]" + dwbuf[i][t[0]:]
}
}
}
}
if !anyreport {
prs = append(prs, "no punctuation scan suspects reported")
rs = append(rs, "Smart Quote Scan: no suspects reported")
} else {
f2, err := os.Create(p.Outdir + "/scanreport.txt")
if err != nil {
log.Fatal(err)
}
for _, u := range prs {
fmt.Fprintf(f2, "%s\n", u)
}
for _, u := range dwbuf {
fmt.Fprintf(f2, "%s\n", u)
}
f2.Close()
rs = append(rs, "Smart Quote Scan: report generated in scanreport.txt")
}
return rs
}
/* ********************************************************************** */
/* */
/* spellcheck based on aspell */
/* */
/* ********************************************************************** */
func Intersection(a, b []string) (c []string) {
m := make(map[string]bool)
for _, item := range a {
m[item] = true
}
for _, item := range b {
if _, ok := m[item]; ok {
c = append(c, item)
}
}
return
}
// $ aspell --help shows installed languages
// # apt install aspell installs aspell and language "en"
// # apt install aspell-es installs addtl. language
func aspellCheck() ([]string, []string, []string) {
var sw []string // suspect words
okwords := make(map[string]int, len(wordListMapCount))
okslice := []string{}
rs := []string{} // empty rs to start aggregation
rs = append(rs, "☳<a name='spell'></a>")
rs = append(rs, "☳"+strings.Repeat("*", 80))
rs = append(rs, fmt.Sprintf("* %-76s *", fmt.Sprintf("SPELLCHECK SUSPECT WORDS (%s)", p.Alang)))
rs = append(rs, strings.Repeat("*", 80))
rs = append(rs, "")
// previously, the wordListMapCount was populated with all words and how
// often they occured. That map is the starting point for a list of good
// words in the book. Start with all words, subtract suspects -> result
// are good words that will be used later, as in the Levenshtein distance
// checks of each suspect word against all good words.
for k, v := range wordListMapCount {
okwords[k] = v
}
// any words in the good word list need to be pulled out of the text *before* running
// aspell because aspell will split it. Example: avec-trollop will be flagged for "avec"
// this will replace the entire "avec-trollop" with "▷000000◁" which will not flag aspell.
lwbuf := make([]string, len(wbuf))
copy(lwbuf, wbuf)
for i, line := range lwbuf {
for n, word := range goodWordlist {
// use the index to generate a token
if strings.Contains(line, word) {
lwbuf[i] = strings.Replace(lwbuf[i], word, fmt.Sprintf("▷%06d◁", n), -1)
}
}
}
// any hyphenated words will be evaluated by parts. either part or both can flag a report.
//
// begin successive aspell runs for each language
// process with each language specified by user
uselangs := strings.Split(p.Alang, ",")
for _, rl := range uselangs {
lwbuf = runAspell(lwbuf, rl)
}
suspect_words := lwbuf
// into slice
if len(suspect_words) > 0 {
suspect_words = suspect_words[:len(suspect_words)-1]
}
// reduce suspect using various rules
i := 0
for ; i < len(suspect_words); i++ {
t := suspect_words[i]
// if word occurs 5 or more times, accept it
if wordListMapCount[strings.ToLower(t)]+
wordListMapCount[strings.Title(strings.ToLower(t))]+
wordListMapCount[strings.ToUpper(t)]+
wordListMapCount[t] >= 5 {
suspect_words = append(suspect_words[:i], suspect_words[i+1:]...)
i--
continue
}
// danger: this could hide a " th " type by accepting "4th"
if t == "th" || t == "st" || t == "nd" {
suspect_words = append(suspect_words[:i], suspect_words[i+1:]...)
i--
continue
}
}
// sort the list of suspect words for report order
sort.Slice(suspect_words, func(i, j int) bool {
return strings.ToLower(suspect_words[i]) < strings.ToLower(suspect_words[j])
})
// show each word in context
// lcreported := make(map[string]int) // map to hold downcased words reported
// rs = append(rs, fmt.Sprintf("Suspect words:"))
re4 := regexp.MustCompile(`☰`)
for _, word := range suspect_words {
/*
// if I've reported the word in any case, don't report it again
lcword := strings.ToLower(word)
if _, ok := lcreported[lcword]; ok { // if it is there already, skip
continue
} else {
lcreported[lcword] = 1
}
*/
sw = append(sw, word) // simple slice of only the word
rs = append(rs, fmt.Sprintf("%s", word)) // word we will show in context
re := regexp.MustCompile(`(^|\P{L})(` + word + `)(\P{L}|$)`)
// make sure there is an entry for this word in the line map
if _, ok := wordListMapLines[word]; ok {
theLines := strings.Split(wordListMapLines[word], ",")
reported := 0
for _, theline := range theLines {
where, _ := strconv.Atoi(theline)
line := wbuf[where-1] // 1-based in map
if re.MatchString(line) {
reported++
line = re.ReplaceAllString(line, `$1☰$2☷$3`)
loc := re4.FindStringIndex(line) // the start of highlighted word
line = getParaSegment(line, loc[0])
rs = append(rs, fmt.Sprintf(" %6d: %s", where, pt(line))) // 1-based
}
if !p.Verbose && reported > 1 && len(theLines) > 2 {
rs = append(rs, fmt.Sprintf(" ...%6d more", len(theLines)-2))
break
}
}
} else {
// in line map word is burst by hyphens
// sésame-ouvre-toi not found in map
// but the individual words are:
// sésame 2806
// ouvre 1507,1658,2533,2806
// toi 1333,1371,2806,3196,3697
// find a line number that's in all three (2806)
// and report that line
pcs := strings.Split(word, "-")
// find all lines with first word
t55 := []string{}
for n, t34 := range pcs {
if n == 0 {
t55 = strings.Split(wordListMapLines[pcs[0]], ",")
} else {
t55 = Intersection(t55, strings.Split(wordListMapLines[t34], ","))
}
}
// if many matches, it probably should not be reported at all.
if len(t55) == 0 {
rs = rs[:len(rs)-2] // back this one off rs
break
}
if lnum, err := strconv.Atoi(t55[0]); err == nil {
rs = append(rs, fmt.Sprintf(" %6s: %s", t55[0], pt(wbuf[lnum-1])))
} else {
rs = rs[:len(rs)-2] // back this one off rs
}
}
rs = append(rs, "")
}
haveReport := false
// remove all suspect words from allwords map
for _, s := range sw {
delete(okwords, s)
haveReport = true
}
// convert to slice and return
for s, _ := range okwords {
okslice = append(okslice, s)
}
if !haveReport {
rs = append(rs, "no spellcheck suspect words")
rs[1] = "☲" + string([]rune(rs[1])[1:]) // switch to dim
}
rs = append(rs, "☷") // and close out dim or black if reports
return sw, okslice, rs
}
/* ********************************************************************** */
/* */
/* utilities */
/* */
/* ********************************************************************** */
// compare the good word list to the submitted word
// allow variations, i.e. "Rose-Ann" in GWL will match "Rose-Ann’s"
func inGoodWordList(s string) bool {
for _, word := range goodWordlist {
if strings.Contains(s, word) {
return true
}
}
return false
}
type rp struct {
rpr rune
rpp int