forked from Freely-Given-org/BibleOrgSys
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BibleReferences.py
executable file
·2035 lines (1897 loc) · 131 KB
/
BibleReferences.py
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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# BibleReferences.py
#
# Module for handling Bible references including ranges
#
# Copyright (C) 2010-2018 Robert Hunt
# Author: Robert Hunt <Freely.Given.org@gmail.com>
# License: See gpl-3.0.txt
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
Module for creating and manipulating Bible references.
This module recognises and handles generic/international Bible references.
The expected/allowed format is controlled by the Bible organisational system,
which includes vernacular booknames, and particular punctuation systems (including allowedVerseSuffixes).
So in English 'Gen 1:26' or 'Jud 5' or '1 Jhn 3:1a' may be acceptable Bible references.
In other languages, the book abbreviations and punctuation will vary.
This module recognises and handles OSIS Bible references.
They are of the form bookAbbreviation.chapterNumber.verseNumber
e.g., Gen.1.1 or Exod.20.10 or 2Chr.7.6 or Jude.1.2
Note that the book abbreviation is not a constant length
and may also start with a digit
and that the same separator is repeated.
However, the native Bible reference string format in this system is more tightly defined
e.g., GEN_1:1 or EXO_20:10 or CH2_7:6 or JDE_1:2!b
We can see that
1/ The Bible book code is always 3-characters, starting with a letter
All letters are UPPERCASE
2/ We use an underline character as the book / chapter separator
3/ We use a colon as the chapter / verse separator
4/ We treat all chapter and verse "number" fields as strings
5/ Verse numbers can include a lowercase letter suffix a..d preceded by !
representing very approximate portions of a verse
a = first half of a verse
b = second half of a verse
c = final third of a verse
d = final quarter of a verse
6/ No spaces are ever allowed.
These are parsed in the VerseReferences module.
Internally, we represent it as a Bible reference tuple (BBB,C,V,S,) also called BCVS where
BBB is the three-character UPPERCASE reference abbreviation
C is the chapter number string (There are some examples of letters being used for chapter "numbers")
V is the verse number string
S is the suffix -- this can be:
a single lowercase letter a-d (see above)
W with a word number (first word is W1) or WxWy for an inclusive range (not including the surrounding spaces)
L with a letter number (first letter is L1) or LxLy for an inclusive range.
OSIS defines reference ranges with hyphens
e.g., Gen.1.1-Gen.1.2 or Gen.1.1-Gen.2.3 (inclusive)
Our ranges are slightly different (also inclusive)
e.g., Gen_1:1-Gen_1:2 but Gen_1:1–Gen_2:3
i.e., using a hyphen for a verse span but en-dash (–) for a span that crosses chapters or books.
OXES is different again using hyphens but tends to remove the second (redundant) book identifier
e.g., Gen.1.1-1.2 (if I remember correctly)
Technical note: Our Bible reference parsers use state machines rather than regular expressions.
Although this is longer and harder to debug, I believe it's able to give more informative error messages.
Also, I think it's easier to make it more generic/international this way.
If I'm wrong, please show me.
"""
from gettext import gettext as _
LastModifiedDate = '2018-12-12' # by RJH
ShortProgName = "BibleReferences"
ProgName = "Bible References handler"
ProgVersion = '0.35'
ProgNameVersion = '{} v{}'.format( ShortProgName, ProgVersion )
ProgNameVersionDate = '{} {} {}'.format( ProgNameVersion, _("last modified"), LastModifiedDate )
debuggingThisModule = False
import logging
import BibleOrgSysGlobals
from BibleOrganisationalSystems import BibleOrganisationalSystem
# This is a hack because it's language dependant :-(
ignoredSuffixes = (' (LXX)',) # A hack to cope with these suffixes in cross-references and footnotes :(
class BibleReferenceBase:
"""
Base class which provides some common functions for the others.
"""
def __init__( self, BOSObject, BibleObject ): # The BibleObject passed by the superclass may be None
"""
Initialize the object with necessary sub-systems.
A Bible Organisation system, e.g., BibleOrganisationalSystem( 'RSV' )
gives various things including:
a book order (useful for determining ranges that cross books)
a punctuation system
book names and deduced abbreviations
Optional Bible object is a loaded Bible (based on InternalBible).
We can use this to guess book names.
"""
assert BOSObject
self._BibleOrganisationalSystem = BOSObject
if BibleOrgSysGlobals.debugFlag:
print( "BibleReferenceBase: org={}".format( BOSObject.getOrganisationalSystemName() ) )
# Handle things differently if we don't know the punctuation system
punctuationSystemName = BOSObject.getOrganisationalSystemValue( 'punctuationSystem' )
#print( 'pSN', punctuationSystemName )
if punctuationSystemName and punctuationSystemName!='None' and punctuationSystemName!='Unknown': # default (if we know the punctuation system)
assert BibleObject is None
self.punctuationDict = self._BibleOrganisationalSystem.getPunctuationDict()
if BibleOrgSysGlobals.debugFlag: print( "BibleReferenceBase: punct={}".format( BOSObject.getPunctuationSystemName() ) )
else: # else use a very generic punctuation system
assert BibleObject is not None
self.punctuationDict = { 'spaceAllowedAfterBCS': 'E',
'booknameCase': 'ME',
'booknameLength': '3',
'punctuationAfterBookAbbreviation': '',
'allowedVerseSuffixes': 'ab',
'bookBridgeCharacter': '-–', 'chapterBridgeCharacter': '-–', 'verseBridgeCharacter': '-–',
'bookSeparator': ';', 'bookChapterSeparator': ' ', 'chapterSeparator': ';', 'chapterVerseSeparator': ':.', 'verseSeparator': ',',
'startQuoteLevel1': '“', 'startQuoteLevel2': '‘', 'startQuoteLevel3': '“', 'startQuoteLevel4': '',
'endQuoteLevel1': '”', 'endQuoteLevel2': '’', 'endQuoteLevel3': '”', 'endQuoteLevel4': '',
'sentenceCapitalisation': 'Y', 'properNounCapitalisation': 'Y',
'statementTerminator': '.', 'questionTerminator': '?', 'exclamationTerminator': '!',
'commaPauseCharacter': ',', }
# Handle things differently if we don't know the vernacular book names
booksNamesSystemName = BOSObject.getOrganisationalSystemValue( 'booksNamesSystem' )
#print( 'bNSN', booksNamesSystemName )
if booksNamesSystemName and booksNamesSystemName!='None' and booksNamesSystemName!='Unknown': # default (if we know the book names system)
#assert BibleObject is not None
self.getBookNameFunction = self._BibleOrganisationalSystem.getBookName
getBookAbbreviationFunction = self._BibleOrganisationalSystem.getBookAbbreviation
self.getBBBFromText = self._BibleOrganisationalSystem.getBBBFromText # This is the function that finds a book code from the vernacular name or abbreviation
if BibleOrgSysGlobals.debugFlag: print( "BibleReferenceBase: bns={}".format( BOSObject.getBooksNamesSystemName() ) )
else: # else use our local functions from our deduced book names
assert BibleObject is not None
self.getBookNameFunction = BibleObject.getAssumedBookName # from InternalBible (which gets it from InternalBibleBook)
getBookAbbreviationFunction = None
self.getBBBFromText = BibleObject.guessXRefBBB
# end of BibleReferenceBase:__init__
# end of class BibleReferenceBase
class BibleSingleReference( BibleReferenceBase ):
"""
Class for creating and manipulating single Bible reference objects (no range allowed).
Use this class only if a Bible reference must be just a single Bible verse.
Uses a state-machine (rather than regular expressions) because I think it can give better error and warning messages.
Not fully tested for all exceptional cases.
This class is not so generally useful. Use the BibleReferenceList class for most cases (beause it also handles lists and ranges).
Only use this class if you really want to enforce that it's only a reference to a single verse.
"""
def __init__( self, BOSObject, BibleObject=None ):
""" Initialize the object with necessary sub-systems. """
assert BOSObject
BibleReferenceBase.__init__( self, BOSObject, BibleObject ) # Initialise the base class
self.objectNameString = 'Bible single reference object'
self.objectTypeString = 'BibleSingleReference'
self.reference = ()
# end of BibleSingleReference:__init__
def __str__( self ):
"""
This method returns the string representation of a Bible object.
@return: the name of a Bible object formatted as a string
@rtype: string
"""
result = "Bible Single Reference object"
if self.reference: result += ('\n' if result else '') + " {}".format( str(self.reference) )
return result
# end of BibleSingleReference:__str__
def parseReferenceString( self, referenceString ):
"""
Returns a 6-tuple with True/False result, haveWarnings, BBB, C, V, S
"""
assert referenceString
haveWarnings, haveErrors = False, False
strippedReferenceString = referenceString.strip()
if strippedReferenceString != referenceString:
logging.warning( _("Reference string {!r} contains surrounding space(s)").format( referenceString ) )
haveWarnings = True
adjustedReferenceString = strippedReferenceString
for value in ignoredSuffixes:
adjustedReferenceString = adjustedReferenceString.replace( value, '' )
#statusList = {0:"gettingBookname", 1:"gettingBCSeparator", 2:"gettingChapter", 3:"gettingVerse", 4:"gotCV", 5:"done", 9:"finished"}
status, bookNameOrAbbreviation, BBB, C, V, S, spaceCount = 0, '', None, '', '', '', 0
for nn, char in enumerate(adjustedReferenceString):
nnn = referenceString.find( char, nn ) # Best guess of where this char might be in the original reference string (which we will display to users in error messages)
if nnn!=nn: # Well the character wasn't exactly where we expected it
assert adjustedReferenceString != referenceString # but this can happen if we messed with the string
#print( "nnn!=nn", nn, nnn, "'"+referenceString+"'", "'"+adjustedReferenceString+"'" )
#if referenceString.startswith('Num 22'):
#print( " BSR status: {}:{} -- got {!r}".format(status, statusList[status],char), haveErrors, haveWarnings )
if status == 0: # Getting bookname (with or without punctuation after book abbreviation)
if char.isalnum(): # doesn't include spaces
if char.isdigit() and bookNameOrAbbreviation: # Could this be the chapter number?
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None: # Don't seem to have a valid bookname yet
bookNameOrAbbreviation += char
continue
# else it seems we have a valid bookname -- let's assume this might be the chapter number
logging.error( _("It seems that the bookname might be joined onto the chapter number at position {} ({}) in Bible reference {!r}") \
.format( nnn, referenceString[nnn], referenceString ) )
status = 2 # Start getting the chapter number immediately (no "continue" here)
else:
bookNameOrAbbreviation += char
continue
elif bookNameOrAbbreviation and char == ' ': # Could be something like 1 Cor
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None: # Don't seem to have a valid bookname yet
bookNameOrAbbreviation += char
else: # we have a valid bookname
status = 2 # Start getting the chapter number
continue
elif 'punctuationAfterBookAbbreviation' in self.punctuationDict and char in self.punctuationDict['punctuationAfterBookAbbreviation']:
BBB = self.getBBBFromText( bookNameOrAbbreviation )
status = 1 # Default to getting BCS
if BBB is None:
logging.error( _("Invalid {!r} bookname at position {} in Bible reference {!r}").format( bookNameOrAbbreviation, nnn, referenceString ) )
haveErrors = True
else: # we found an unambiguous bookname
shortBookName = self.getBookNameFunction( BBB )
if shortBookName == bookNameOrAbbreviation: # they entered the full bookname -- we didn't really expect this punctuation
if char in self.punctuationDict['bookChapterSeparator']: # ok, they are the same character
status = 2 # Just accept this as the BCS and go get the chapter number
else:
logging.warning( _("Didn't expect {!r} punctuationAfterBookAbbreviation when the full book name was given at position {} in {!r}") \
.format(self.punctuationDict['punctuationAfterBookAbbreviation'],nnn,referenceString) )
haveWarnings = True
continue
elif char in self.punctuationDict['bookChapterSeparator'] or char=='_':
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None:
logging.error( _("Invalid {!r} bookname in Bible reference {!r}").format( bookNameOrAbbreviation, referenceString ) )
haveErrors = True
else: # we found an unambiguous bookname
shortBookName = self.getBookNameFunction( BBB )
if shortBookName != bookNameOrAbbreviation: # they didn't enter the full bookname -- we really expect the punctuationAfterBookAbbreviation
if 'punctuationAfterBookAbbreviation' in self.punctuationDict and self.punctuationDict['punctuationAfterBookAbbreviation']:
logging.warning( _("Missing {!r} punctuationAfterBookAbbreviation when the book name abbreviation was given at position {} ({}) in {!r}") \
.format( self.punctuationDict['punctuationAfterBookAbbreviation'], nnn, referenceString[nnn], referenceString ) )
haveWarnings = True
spaceCount = 1 if char==' ' else 0
status = 2 # getting chapter number
continue
else:
if ' ' in bookNameOrAbbreviation:
if bookNameOrAbbreviation.startswith('1 ') or bookNameOrAbbreviation.startswith('2 ') \
or bookNameOrAbbreviation.startswith('I ') or bookNameOrAbbreviation.startswith('II '):
logging.warning( "BibleSingleReference.parseReferenceString " + _("Unexpected space after book number when getting book name in Bible reference {!r}").format( referenceString ) )
haveWarnings = True
ixSP = bookNameOrAbbreviation.index( ' ' )
bookNameOrAbbreviation = bookNameOrAbbreviation[0] + bookNameOrAbbreviation[ixSP+1:] # Remove the space
if ' ' in bookNameOrAbbreviation:
logging.error( "BibleSingleReference.parseReferenceString " + _("Unable to deduce book name from {!r} in Bible reference {!r}").format( bookNameOrAbbreviation, referenceString ) )
haveErrors = True
else:
logging.error( _("Unexpected {!r} character when getting book name at position {} in Bible reference {!r}").format( char, nnn, referenceString ) )
haveErrors = True
if len(bookNameOrAbbreviation)>4: break # Best to break here I think since we've been unsuccessful at finding a book name
continue
if status == 1: # Getting book chapter separator
if char in self.punctuationDict['bookChapterSeparator']:
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None:
logging.error( _("Invalid {!r} bookname in Bible reference {!r}").format( bookNameOrAbbreviation, referenceString ) )
haveErrors = True
spaceCount = 1 if char==' ' else 0
status = 2
continue
elif char.isdigit(): # Must have missed the BCS
logging.warning( _("Missing {!r} book/chapter separator when the book name abbreviation was given in {!r}").format(self.punctuationDict['bookChapterSeparator'],referenceString) )
haveWarnings = True
status = 2 # Fall through below
else:
logging.error( _("Unexpected {!r} character in Bible reference {!r} when getting book/chapter separator").format( char, referenceString ) )
haveErrors = True
continue
if status == 2: # Getting chapter number (or could be the verse number of a one chapter book)
if char==' ' and not C:
spaceCount += 1
elif char.isdigit():
if self.punctuationDict['spaceAllowedAfterBCS']=='Y' and spaceCount<1:
logging.warning( _("Missing space after bookname in Bible reference {!r}").format( referenceString ) )
haveWarnings = True
elif self.punctuationDict['spaceAllowedAfterBCS']=='N' or spaceCount>1:
logging.warning( _("Extra space(s) after bookname in Bible reference {!r}").format( referenceString ) )
haveWarnings = True
C += char
elif char in self.punctuationDict['allowedVerseSuffixes'] and not S: # Could be like verse 5b
S = char
elif C and char in self.punctuationDict['chapterVerseSeparator']:
status = 3 # Start getting the verse number
else:
logging.error( _("Unexpected {!r} character when getting chapter number in {} Bible reference {!r}").format( char, BBB, referenceString ) )
haveErrors = True
continue
if status == 3: # Getting verse number
if char == ' ' and not V:
logging.warning( _("Extra space(s) after chapter in {} Bible reference {!r}").format( BBB, referenceString ) )
haveWarnings = True
elif char.isdigit():
V += char
elif char in self.punctuationDict['allowedVerseSuffixes'] and not S: # Could be like verse 5b
S = char
else:
logging.error( _("BSR: Unexpected {!r} character when getting verse number in {} {} Bible reference {!r}").format( char, BBB, C, referenceString ) )
haveErrors = True
if V: status = 4
else: break # Seems better to break on this one or else we get lots of errors (e.g., if a fr is left open in a footnote)
continue
if status == 3: # Got a C but still getting the V hopefully
if V: status = 4
if len(S) > 1:
logging.error( _("Unexpected long {!r} suffix in {} Bible reference {!r}").format( S, BBB, referenceString ) )
haveErrors = True
S = S[0] # Just take the first one
if BBB is not None:
if status==2 and C and self._BibleOrganisationalSystem.isSingleChapterBook( BBB ): # Have a single chapter book and what we were given is presumably the verse number
V = C
C = '1'
status = 4
if status>=4 and not haveErrors:
if self._BibleOrganisationalSystem.isValidBCVRef( (BBB, C, V, S), referenceString ):
status = 9
self.reference = (BBB, C, V, S,)
#print( "BSR final status: {}:{} -- got {!r}from {!r}\n".format(status,statusList[status],self.referenceList,referenceString) )
return status==9 and not haveErrors, haveWarnings, BBB, C, V, S
# end of BibleSingleReference:parseReferenceString
# end of class BibleSingleReference
class BibleSingleReferences( BibleReferenceBase ):
"""
Class for creating and manipulating a list of multiple Bible reference objects (no ranges allowed).
Use this class only if a Bible reference must be just a list of single Bible verses.
Uses a state-machine (rather than regular expressions) because I think it can give better error and warning messages.
Not fully tested for all exceptional cases.
This class is not so generally useful. Use the BibleReferenceList class for most cases (beause it also handles ranges).
Only use this class if you really want to enforce that it's only references to single verses.
"""
def __init__( self, BOSObject, BibleObject=None ):
""" Initialize the object with necessary sub-systems. """
assert BOSObject
BibleReferenceBase.__init__( self, BOSObject, BibleObject ) # Initialise the base class
self.objectNameString = 'Bible single references object'
self.objectTypeString = 'BibleSingleReferences'
self.referenceList = []
# end of BibleSingleReferences:__init__
def __str__( self ):
"""
This method returns the string representation of a Bible object.
@return: the name of a Bible object formatted as a string
@rtype: string
"""
result = "Bible Single References Object"
if self.referenceList: result += ('\n' if result else '') + " {}".format( self.referenceList )
return result
# end ofBibleSingleReferences: __str__
def parseReferenceString( self, referenceString ):
"""
Returns a tuple with True/False result, haveWarnings, list of (BBB, C, V, S) tuples
"""
def saveReference( BBB, C, V, S, refList ):
""" Checks the reference info then saves it as a referenceTuple in the refList. """
nonlocal haveErrors, haveWarnings
if len(S) > 1:
logging.error( _("Unexpected long {!r} suffix in {} Bible reference {!r}").format( S, BBB, referenceString ) )
haveErrors = True
S = S[0] # Just take the first one
refTuple = ( BBB, C, V, S, )
if refTuple in refList:
logging.warning( _("Reference {} is repeated in Bible reference {!r}").format( refTuple, referenceString ) )
haveWarnings = True
if BBB is None or not self._BibleOrganisationalSystem.isValidBCVRef( refTuple, referenceString ):
haveErrors = True
refList.append( refTuple )
# end of saveReference
#print( "Processing {!r}".format( referenceString ) )
assert referenceString
haveWarnings, haveErrors = False, False
strippedReferenceString = referenceString.strip()
if strippedReferenceString != referenceString:
logging.warning( _("Reference string {!r} contains surrounding space(s)").format( referenceString ) )
haveWarnings = True
adjustedReferenceString = strippedReferenceString
for value in ignoredSuffixes:
adjustedReferenceString = adjustedReferenceString.replace( value, '' )
#statusList = {0:"gettingBookname", 1:"gettingBCSeparator", 2:"gettingChapter", 3:"gettingVerse", 4:"gettingNextBorC", 5:"done", 9:"finished"}
status, bookNameOrAbbreviation, BBB, C, V, S, spaceCount, refList = 0, '', None, '', '', '', 0, []
for nn, char in enumerate(adjustedReferenceString):
nnn = referenceString.find( char, nn ) # Best guess of where this char might be in the original reference string (which we will display to users in error messages)
if nnn!=nn: # Well the character wasn't exactly where we expected it
assert adjustedReferenceString != referenceString # but this can happen if we messed with the string
#print( "nnn!=nn", nn, nnn, "'"+referenceString+"'", "'"+adjustedReferenceString+"'" )
#if referenceString.startswith('Num 22'):
#print( " BSRs status: {}:{} -- got {!r}".format(status, statusList[status],char), haveErrors, haveWarnings )
if status == 0: # Getting bookname (with or without punctuation after book abbreviation)
if char.isalnum(): # doesn't include spaces
if char.isdigit() and bookNameOrAbbreviation: # Could this be the chapter number?
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None: # Don't seem to have a valid bookname yet
bookNameOrAbbreviation += char
continue
# else it seems we have a valid bookname -- let's assume this might be the chapter number
logging.error( _("It seems that the bookname might be joined onto the chapter number at position {} in Bible reference {!r}").format(nnn, referenceString) )
status = 2 # Start getting the chapter number immediately (no "continue" here)
else:
bookNameOrAbbreviation += char
continue
elif bookNameOrAbbreviation and char == ' ': # Could be something like 1 Cor
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None: # Don't seem to have a valid bookname yet
bookNameOrAbbreviation += char
else: # we have a valid bookname
status = 2 # Start getting the chapter number
continue
elif 'punctuationAfterBookAbbreviation' in self.punctuationDict and char in self.punctuationDict['punctuationAfterBookAbbreviation']:
BBB = self.getBBBFromText( bookNameOrAbbreviation )
status = 1 # Default to getting BCS
if BBB is None:
logging.error( _("Invalid {!r} bookname at position {} in Bible reference {!r}").format( bookNameOrAbbreviation, nnn, referenceString ) )
haveErrors = True
else: # we found an unambiguous bookname
shortBookName = self.getBookNameFunction( BBB )
if shortBookName == bookNameOrAbbreviation: # they entered the full bookname -- we didn't really expect this punctuation
if char in self.punctuationDict['bookChapterSeparator']: # ok, they are the same character
status = 2 # Just accept this as the BCS and go get the chapter number
else:
logging.warning( _("Didn't expect {!r} punctuationAfterBookAbbreviation when the full book name was given at position {} in {!r}").format(self.punctuationDict['punctuationAfterBookAbbreviation'],nnn,referenceString) )
haveWarnings = True
continue
elif char in self.punctuationDict['bookChapterSeparator'] or char=='_':
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None:
logging.error( _("Invalid {!r} bookname in Bible reference {!r}").format( bookNameOrAbbreviation, referenceString ) )
haveErrors = True
else: # we found an unambiguous bookname
shortBookName = self.getBookNameFunction( BBB )
if shortBookName != bookNameOrAbbreviation: # they didn't enter the full bookname -- we really expect the punctuationAfterBookAbbreviation
if 'punctuationAfterBookAbbreviation' in self.punctuationDict and self.punctuationDict['punctuationAfterBookAbbreviation']:
logging.warning( _("Missing {!r} punctuationAfterBookAbbreviation when the book name abbreviation was given at position {} ({}) in {!r}") \
.format( self.punctuationDict['punctuationAfterBookAbbreviation'], nnn, referenceString[nnn], referenceString ) )
haveWarnings = True
spaceCount = 1 if char==' ' else 0
status = 2 # getting chapter number
continue
else:
if ' ' in bookNameOrAbbreviation:
if bookNameOrAbbreviation.startswith('1 ') or bookNameOrAbbreviation.startswith('2 ') \
or bookNameOrAbbreviation.startswith('I ') or bookNameOrAbbreviation.startswith('II '):
logging.warning( "BibleSingleReferences.parseReferenceString " + _("Unexpected space after book number when getting book name in Bible reference {!r}").format( referenceString ) )
haveWarnings = True
ixSP = bookNameOrAbbreviation.index( ' ' )
bookNameOrAbbreviation = bookNameOrAbbreviation[0] + bookNameOrAbbreviation[ixSP+1:] # Remove the space
if ' ' in bookNameOrAbbreviation:
logging.error( "BibleSingleReferences.parseReferenceString " + _("Unable to deduce book name from {!r} in Bible reference {!r}").format( bookNameOrAbbreviation, referenceString ) )
haveErrors = True
else:
logging.error( _("Unexpected {!r} character when getting book name at position {} in Bible reference {!r}").format( char, nnn, referenceString ) )
haveErrors = True
if len(bookNameOrAbbreviation)>4: break # Best to break here I think since we've been unsuccessful at finding a book name
continue
if status == 1: # Getting book chapter separator
if char in self.punctuationDict['bookChapterSeparator']:
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None:
logging.error( _("Invalid {!r} bookname in Bible reference {!r}").format( bookNameOrAbbreviation, referenceString ) )
haveErrors = True
spaceCount = 1 if char==' ' else 0
status = 2
continue
elif char.isdigit(): # Must have missed the BCS
logging.warning( _("Missing {!r} book/chapter separator when the book name abbreviation was given in {!r}").format(self.punctuationDict['bookChapterSeparator'],referenceString) )
haveWarnings = True
status = 2 # Fall through below
else:
logging.error( _("Unexpected {!r} character in Bible reference {!r} when getting book/chapter separator").format( char, referenceString ) )
haveErrors = True
continue
if status == 2: # Getting chapter number (or could be the verse number of a one chapter book)
if char==' ' and not C:
spaceCount += 1
elif char.isdigit():
if self.punctuationDict['spaceAllowedAfterBCS']=='Y' and spaceCount<1:
logging.warning( _("Missing space after bookname in Bible reference {!r}").format( referenceString ) )
haveWarnings = True
elif self.punctuationDict['spaceAllowedAfterBCS']=='N' or spaceCount>1:
logging.warning( _("Extra space(s) after bookname in Bible reference {!r}").format( referenceString ) )
haveWarnings = True
C += char
elif char in self.punctuationDict['allowedVerseSuffixes'] and not S: # Could be like verse 5b
S = char
elif C and char in self.punctuationDict['chapterVerseSeparator']:
status = 3 # Start getting the verse number
else:
logging.error( _("Unexpected {!r} character when getting chapter number in {} Bible reference {!r}").format( char, BBB, referenceString ) )
haveErrors = True
continue
if status == 3: # Getting verse number
if char == ' ' and not V:
logging.warning( _("Extra space(s) after chapter in {} Bible reference {!r}").format( BBB, referenceString ) )
haveWarnings = True
elif char.isdigit():
V += char
elif char in self.punctuationDict['allowedVerseSuffixes'] and not S: # Could be like verse 5b
S = char
elif V and char in self.punctuationDict['verseSeparator']:
saveReference( BBB, C, V, S, refList )
V, S = '', ''
elif V and (char in self.punctuationDict['chapterSeparator'] or char in self.punctuationDict['bookSeparator']):
saveReference( BBB, C, V, S, refList )
V, S = '', ''
if self.punctuationDict['chapterSeparator'] == self.punctuationDict['bookSeparator']:
temp, spaceCount = '', 0
status = 4 # We don't know what to expect next
elif char in self.punctuationDict['chapterSeparator']:
C = ''
status = 2 # Get the next chapter number
elif char in self.punctuationDict['bookSeparator']:
bookNameOrAbbreviation, BBB, C = '', None, ''
status = 0 # Get the next book name abbreviation
else:
logging.error( _("BSRs: Unexpected {!r} character when getting verse number in {} {} Bible reference {!r}").format( char, BBB, C, referenceString ) )
haveErrors = True
if V:
saveReference( BBB, C, V, S, refList )
V, S = '', ''
break # Seems better to break on this one or else we get lots of errors (e.g., if a fr is left open in a footnote)
continue
if status == 4: # Getting the next chapter number or book name (not sure which)
if char == ' ' and not temp:
if spaceCount:
logging.warning( _("Extra space(s) after chapter or book separator in {} Bible reference {!r}").format( BBB, referenceString ) )
haveWarnings = True
spaceCount += 1
elif char.isalnum():
temp += char
elif 'punctuationAfterBookAbbreviation' in self.punctuationDict and char in self.punctuationDict['punctuationAfterBookAbbreviation']:
bookNameOrAbbreviation = temp
BBB = self.getBBBFromText( bookNameOrAbbreviation )
C, status = '', 1 # Default to getting BCS
if BBB is None:
logging.error( _("Invalid {!r} bookname in Bible reference {!r}").format( bookNameOrAbbreviation, referenceString ) )
haveErrors = True
else: # we found an unambiguous bookname
shortBookName = self.getBookNameFunction( BBB )
if shortBookName == bookNameOrAbbreviation: # they entered the full bookname -- we didn't really expect this punctuation
if char in self.punctuationDict['bookChapterSeparator']: # ok, they are the same character
status = 2 # Just accept this as the BCS and go get the chapter number
else:
logging.warning( _("Didn't expect {!r} punctuationAfterBookAbbreviation when the full book name was given in {!r}").format(self.punctuationDict['punctuationAfterBookAbbreviation'],referenceString) )
haveWarnings = True
else:
#print( "Got {!r}".format( temp ) )
if char in self.punctuationDict['chapterVerseSeparator'] and temp and temp.isdigit(): # Assume it's a follow on chapter number
C = temp
status = 3 # Now get the verse number
elif char in self.punctuationDict['bookChapterSeparator']:
bookNameOrAbbreviation = temp
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None:
logging.error( _("Invalid {!r} bookname in Bible reference {!r}").format( bookNameOrAbbreviation, referenceString ) )
haveErrors = True
C, V, S = '', '', ''
spaceCount = 1 if char==' ' else 0
status = 2 # Start getting the chapter number
else:
logging.error( _("Unexpected {!r} character in Bible reference {!r} when getting book name").format( char, referenceString ) )
haveErrors = True
continue
if status==3: # Got a C but still getting the V hopefully
if V: status = 4
if BBB is not None:
if status==2 and C and self._BibleOrganisationalSystem.isSingleChapterBook( BBB ): # Have a single chapter book and what we were given is presumably the verse number
V = C
C = '1'
status = 4
if status>=4 and not haveErrors:
saveReference( BBB, C, V, S, refList )
status = 9
self.referenceList = refList
#print( "BSRs final status: {}:{} -- got {!r}from {!r}\n".format(status,statusList[status],self.referenceList,referenceString) )
return status==9 and not haveErrors, haveWarnings, self.referenceList
# end of BibleSingleReferences:parseReferenceString
# end of class BibleSingleReferences
class BibleReferenceList( BibleReferenceBase ):
"""
Class for creating and manipulating a list of multiple Bible reference objects including optional ranges.
Use this class unless a Bible reference must be just a single Bible verse or a list of single verses.
Uses a state-machine (rather than regular expressions) because I think it can give better error and warning messages.
Not fully tested yet for all exceptional cases.
__init__ creates the object
__str__ gives a brief prose description of the object
makeReferenceString makes a reference string out of a tuple
parseReferenceString makes a tuple out of a reference string
parseOSISReferenceString makes a tuple out of an OSIS reference string
getReferenceList returns our internal reference list of tuples, optionally expanded across ranges
getOSISRefList converts our internal reference list of tuples to an OSIS reference string
parseToOSIS attempts to convert a vernacular reference string to an OSIS reference string
containsReferenceTuple sees if the reference tuple is in our internal list
containsReference see if the BBB,C,V,S reference is in our internal list
"""
def __init__( self, BOSObject, BibleObject=None ):
""" Initialize the object with necessary sub-systems.
A Bible Organisation system, e.g., BibleOrganisationalSystem( 'RSV' )
gives various things including:
a book order (useful for determining ranges that cross books)
a punctuation system
book names and deduced abbreviations
Optional Bible object is a loaded Bible (based on InternalBible).
We can use this to guess book names.
"""
assert BOSObject
BibleReferenceBase.__init__( self, BOSObject, BibleObject ) # Initialise the base class
self.objectNameString = 'Bible reference list object'
self.objectTypeString = 'BibleReferenceList'
self.referenceList = []
# end of BibleReferenceList.__init__
def __str__( self ):
"""
This method returns- the string representation of a Bible Range References object.
@return: the name of a Bible object formatted as a string
@rtype: string
"""
result = "Bible Range References object"
if self.referenceList: result += ('\n' if result else '') + " {}".format( self.referenceList )
return result
# end of BibleReferenceList.__str__
def makeReferenceString( self, refTuple, location=None ):
"""
Makes a string out of a reference tuple
"""
assert refTuple
lenRef = len( refTuple )
if lenRef == 2: (BBB, C), V, S = refTuple, '', ''
elif lenRef == 3: (BBB, C, V), S = refTuple, ''
elif lenRef == 4: BBB, C, V, S = refTuple
else: logging.error( _("Unrecognized {} parameter to makeReferenceString").format( refTuple ) ); return None
BnC = self.punctuationDict['booknameCase'] if isinstance(self.punctuationDict['booknameCase'],str) else self.punctuationDict['booknameCase'][0]
BCS = self.punctuationDict['bookChapterSeparator'] if isinstance(self.punctuationDict['bookChapterSeparator'],str) else self.punctuationDict['bookChapterSeparator'][0]
CVS = self.punctuationDict['chapterVerseSeparator'] if isinstance(self.punctuationDict['chapterVerseSeparator'],str) else self.punctuationDict['chapterVerseSeparator'][0]
if BBB[0].isdigit(): # Have a book name like 1SA
assert "Should never happen I think" == BBB
BBBstr = BBB[0] + ( BBB[1:] if BnC=='U' else BBB[1:].lower() if BnC=='L' else BBB[1:].capitalize() )
else:
BBBstr = BBB if BnC=='U' else BBB.lower() if BnC=='L' else BBB.capitalize()
if self._BibleOrganisationalSystem.isSingleChapterBook( BBB ):
#print( "makeReferenceString-iSCB", refTuple, location )
if C!='1': logging.error( _("makeReferenceString: Expected chapter number to be 1 (not {!r}) for this {} single chapter book (from {} at {})").format( C, BBB, refTuple, location ) )
resultString = "{}{}{}{}".format( BBBstr, BCS, ' ' if self.punctuationDict['spaceAllowedAfterBCS']=='Y' else '', V )
else: # it's a book with multiple chapters
resultString = "{}{}{}{}{}{}".format( BBBstr, BCS, ' ' if self.punctuationDict['spaceAllowedAfterBCS']=='Y' else '', C, CVS, V )
return resultString
# end of BibleReferenceList.makeReferenceString
def parseReferenceString( self, referenceString, location=None ):
"""
A complex state machine that
returns a tuple with True/False result, haveWarnings, list of (BBB, C, V, S) tuples.
A range is expressed as a tuple containing a pair of (BBB, C, V, S) tuples.
All parsed references are checked for validity against the versification system.
The optional location is a string that helps in error/warning messages.
We could rewrite this using RegularExpressions, but would it be able to give such precise formatting error messages?
"""
def saveReference( BBB, C, V, S, refList ):
""" Checks the reference info then saves it as a referenceTuple in the refList. """
nonlocal haveErrors, haveWarnings, totalVerseList
if len(S) > 1:
logging.error( _("Unexpected long {!r} suffix in {} Bible reference {!r}").format( S, BBB, referenceString ) )
haveErrors = True
S = S[0] # Just take the first one
refTuple = ( BBB, C, V, S, )
if refTuple in refList:
logging.warning( _("Reference {} is repeated in Bible reference {!r}").format( refTuple, referenceString ) )
haveWarnings = True
if BBB is None or not self._BibleOrganisationalSystem.isValidBCVRef( refTuple, referenceString ):
haveErrors = True
refList.append( refTuple )
totalVerseList.append( refTuple )
# end of saveReference
def saveStartReference( BBB, C, V, S ):
""" Checks the reference info then saves it as a referenceTuple. """
nonlocal haveErrors, haveWarnings, startReferenceTuple
if len(S) > 1:
logging.error( _("Unexpected long {!r} suffix in {} Bible reference {!r}").format( S, BBB, referenceString ) )
haveErrors = True
S = S[0] # Just take the first one
startReferenceTuple = ( BBB, C, V, S, )
if BBB is None or not self._BibleOrganisationalSystem.isValidBCVRef( startReferenceTuple, referenceString ):
haveErrors = True
# end of saveStartReference
def saveReferenceRange( startTuple, BBB, C, V, S, refList ):
"""
Checks the reference info then saves it as a referenceTuple in the refList.
"""
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( "BibleReferences.saveReferenceRange:", "startTuple =", startTuple, "BBB =", BBB, "C =", C, "V =", V, "S = ", S, "refList =", refList )
if V and not S and V[-1] in ('a','b','c',): # Remove the suffix
S = V[-1]; V = V[:-1]
if V=='3O': V = '30' # Fix a bug in byr-w.usfm
if not BBB:
logging.error( _("saveReferenceRange: Missing BBB parameter from {} Bible reference {!r}").format( BBB, referenceString ) )
if not C:
logging.error( _("saveReferenceRange: Missing C parameter from {} Bible reference {!r}").format( BBB, referenceString ) )
elif C!='-1' and not C.isdigit():
logging.error( _("saveReferenceRange: Non-digit {} C parameter from {} Bible reference {!r}").format( repr(C), BBB, referenceString ) )
if not V:
logging.error( _("saveReferenceRange: Missing V parameter from {} Bible reference {!r}").format( BBB, referenceString ) )
elif not V.isdigit():
logging.error( _("saveReferenceRange: Non-digit {} V parameter from {} Bible reference {!r}").format( repr(V), BBB, referenceString ) )
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
assert BBB is None or len(BBB) == 3
assert not C or C.isdigit() # Should be no suffix on C (although it can be blank if the reference is for a whole book)
assert not V or V.isdigit() # Should be no suffix on V (although it can be blank if the reference is for a whole chapter)
assert not S or len(S)==1 and S.isalpha() # Suffix should be only one lower-case letter if anything
nonlocal haveErrors, haveWarnings, totalVerseList
if len(S) > 1:
logging.error( _("saveReferenceRange: Unexpected long {!r} suffix in {} Bible reference {!r}").format( S, BBB, referenceString ) )
haveErrors = True
S = S[0] # Just take the first one
finishTuple = ( BBB, C, V, S, )
if BBB is None or not self._BibleOrganisationalSystem.isValidBCVRef( finishTuple, referenceString ): # No error messages here because it will be caught at expandCVRange below
haveErrors = True # Just set this flag
rangeTuple = (startTuple, finishTuple,)
verseList = self._BibleOrganisationalSystem.expandCVRange( startTuple, finishTuple, referenceString, self._BibleOrganisationalSystem )
if verseList is not None: totalVerseList.extend( verseList )
if rangeTuple in refList:
logging.warning( _("saveReferenceRange: Reference range {} is repeated in Bible reference {!r}").format( rangeTuple, referenceString ) )
haveWarnings = True
refList.append( rangeTuple )
# end of saveReferenceRange
if location is None: location = '(unknown)'
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
print( "BibleReferences.parseReferenceString {!r} from {}".format( referenceString, location ) )
assert referenceString and isinstance( referenceString, str )
assert location and isinstance( location, str )
haveWarnings, haveErrors, totalVerseList = False, False, []
strippedReferenceString = referenceString.strip()
if strippedReferenceString != referenceString:
logging.warning( _("Reference string {!r} contains surrounding space(s)").format( referenceString ) )
haveWarnings = True
adjustedReferenceString = strippedReferenceString
for value in ignoredSuffixes:
adjustedReferenceString = adjustedReferenceString.replace( value, '' )
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
statusList = {0:"gettingBookname", 1:"gettingBCSeparator", 2:"gettingChapter", 3:"gettingVerse", 4:"gettingNextBorC", 5:"gettingBorCorVRange", 6:"gettingBRange", 7:"gettingCRange", 8:"gettingVRange", 9:"finished"}
status, bookNameOrAbbreviation, BBB, C, V, S, spaceCount, startReferenceTuple, self.referenceList = 0, '', None, '', '', '', 0, (), []
for nn, char in enumerate(adjustedReferenceString):
nnn = referenceString.find( char, nn ) # Best guess of where this char might be in the original reference string (which we will display to users in error messages)
if nnn!=nn: # Well the character wasn't exactly where we expected it
assert adjustedReferenceString != referenceString # but this can happen if we messed with the string
#print( "nnn!=nn", nn, nnn, "'"+referenceString+"'", "'"+adjustedReferenceString+"'" )
if BibleOrgSysGlobals.debugFlag and debuggingThisModule:
#if referenceString.startswith('Num 22'):
print( " BRL status: {}:{} -- got {!r}".format(status, statusList[status],char), haveErrors, haveWarnings, self.referenceList, BBB )
if status == 0: # Getting bookname (with or without punctuation after book abbreviation)
if char.isalnum(): # doesn't include spaces
if char.isdigit() and bookNameOrAbbreviation: # Could this be the chapter number?
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None: # Don't seem to have a valid bookname yet
bookNameOrAbbreviation += char
continue
# else it seems we have a valid bookname -- let's assume this might be the chapter number
logging.error( _("It seems that the bookname might be joined onto the chapter number at position {} in Bible reference {!r}").format(nnn, referenceString) )
status = 2 # Start getting the chapter number immediately (no "continue" here)
else:
bookNameOrAbbreviation += char
continue
elif bookNameOrAbbreviation and char == ' ': # Could be something like 1 Cor
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None: # Don't seem to have a valid bookname yet
bookNameOrAbbreviation += char
else: # we have a valid bookname
status = 2 # Start getting the chapter number
continue
elif 'punctuationAfterBookAbbreviation' in self.punctuationDict and char in self.punctuationDict['punctuationAfterBookAbbreviation']:
BBB = self.getBBBFromText( bookNameOrAbbreviation )
status = 1 # Default to getting BCS
if BBB is None:
logging.error( _("Invalid {!r} bookname at position {} in Bible reference {!r}").format( bookNameOrAbbreviation, nnn, referenceString ) )
haveErrors = True
else: # we found an unambiguous bookname
shortBookName = self.getBookNameFunction( BBB )
if shortBookName == bookNameOrAbbreviation: # they entered the full bookname -- we didn't really expect this punctuation
if char in self.punctuationDict['bookChapterSeparator']: # ok, they are the same character
status = 2 # Just accept this as the BCS and go get the chapter number
else:
logging.warning( _("Didn't expect {!r} punctuationAfterBookAbbreviation when the full book name was given at position {} in {!r}").format(self.punctuationDict['punctuationAfterBookAbbreviation'],nnn,referenceString) )
haveWarnings = True
continue
elif char in self.punctuationDict['bookChapterSeparator'] or char=='_':
if bookNameOrAbbreviation:
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None:
logging.error( _("Invalid {!r} bookname in Bible reference {!r}").format( bookNameOrAbbreviation, referenceString ) )
haveErrors = True
else: # we found an unambiguous bookname
shortBookName = self.getBookNameFunction( BBB )
if shortBookName != bookNameOrAbbreviation: # they didn't enter the full bookname -- we really expect the punctuationAfterBookAbbreviation
if 'punctuationAfterBookAbbreviation' in self.punctuationDict and self.punctuationDict['punctuationAfterBookAbbreviation']:
logging.warning( _("Missing {!r} punctuationAfterBookAbbreviation when the book name abbreviation was given at position {} ({}) in {!r}") \
.format( self.punctuationDict['punctuationAfterBookAbbreviation'], nnn, referenceString[nnn], referenceString ) )
haveWarnings = True
else:
logging.error( _("Missing bookname in Bible reference {!r}").format( referenceString ) )
haveErrors = True
spaceCount = 1 if char==' ' else 0
status = 2 # getting chapter number
continue
else:
if ' ' in bookNameOrAbbreviation:
if bookNameOrAbbreviation.startswith('1 ') or bookNameOrAbbreviation.startswith('2 ') \
or bookNameOrAbbreviation.startswith('I ') or bookNameOrAbbreviation.startswith('II '):
logging.warning( "BibleReferenceList.parseReferenceString " + _("Unexpected space after book number when getting book name in Bible reference {!r}").format( referenceString ) )
haveWarnings = True
ixSP = bookNameOrAbbreviation.index( ' ' )
bookNameOrAbbreviation = bookNameOrAbbreviation[0] + bookNameOrAbbreviation[ixSP+1:] # Remove the space
if ' ' in bookNameOrAbbreviation:
logging.error( "BibleReferenceList.parseReferenceString " + _("Unable to deduce book name from {!r} in Bible reference {!r}").format( bookNameOrAbbreviation, referenceString ) )
haveErrors = True
elif char == '.':
logging.warning( "BibleReferenceList.parseReferenceString " + _("Unexpected period when getting book name at position {} in Bible reference {!r}").format( nnn, referenceString ) )
haveWarnings = True
else:
logging.error( "BibleReferenceList.parseReferenceString " + _("Unexpected {!r} character when getting book name at position {} in Bible reference {!r}").format( char, nnn, referenceString ) )
haveErrors = True
if len(bookNameOrAbbreviation)>4: break # Best to break here I think since we've been unsuccessful at finding a book name
continue
if status == 1: # Getting book chapter separator
if char in self.punctuationDict['bookChapterSeparator'] or char=='_':
BBB = self.getBBBFromText( bookNameOrAbbreviation )
if BBB is None:
logging.error( _("Invalid {!r} bookname at position {} in Bible reference {!r}").format( bookNameOrAbbreviation, nnn, referenceString ) )
haveErrors = True
spaceCount = 1 if char==' ' else 0
status = 2
continue
elif char.isdigit(): # Must have missed the BCS
logging.warning( _("Missing {!r} book/chapter separator when the book name abbreviation was given at position {} ({}) in {!r}") \
.format( self.punctuationDict['bookChapterSeparator'], nnn, referenceString[nnn], referenceString ) )
haveWarnings = True
status = 2 # Fall through below
else:
logging.error( _("Unexpected {!r} character when getting book/chapter separator at position {} in Bible reference {!r}").format( char, nnn, referenceString ) )
haveErrors = True
continue
if status == 2: # Getting chapter number (or could be the verse number of a one chapter book)
if char==' ' and not C:
spaceCount += 1
elif char.isdigit():
if self.punctuationDict['spaceAllowedAfterBCS']=='Y' and spaceCount<1:
logging.warning( _("Missing space after bookname at position {} in Bible reference {!r}").format( nnn, referenceString ) )
haveWarnings = True
elif (self.punctuationDict['spaceAllowedAfterBCS']=='N' and spaceCount>0) or spaceCount>1:
logging.warning( _("Extra space(s) after bookname at position {} in Bible reference {!r}").format( nnn, referenceString ) )
haveWarnings = True
C += char
elif char in self.punctuationDict['allowedVerseSuffixes'] and not S: # Could be like verse 5b
S = char
elif C and char in self.punctuationDict['chapterVerseSeparator']:
status = 3 # Start getting the verse number
elif C and self._BibleOrganisationalSystem.isSingleChapterBook( BBB ):
V = C
C = '1'
if char in self.punctuationDict['verseSeparator']:
saveReference( BBB, C, V, S, self.referenceList )
status = 3 # Get the next verse number
elif char in self.punctuationDict['bookSeparator']:
saveReference( BBB, C, V, S, self.referenceList )
BBB, C = None, ''
status = 0
elif char in self.punctuationDict['verseBridgeCharacter']:
saveStartReference( BBB, C, V, S )
status = 8 # Getting verse range
else:
logging.error( _("Unexpected {!r} character when processing single chapter book {} at position {} in Bible reference {!r}").format( char, BBB, nnn, referenceString ) )
haveErrors = True
V, S = '', ''
elif C and char in self.punctuationDict['chapterBridgeCharacter']:
saveStartReference( BBB, C, V, S )
status, C, V, S = 7, '', '', '' # Getting chapter range
else:
logging.error( _("Unexpected {!r} character when getting chapter number at position {} in {} Bible reference {!r}").format( char, nnn, BBB, referenceString ) )
haveErrors = True
continue
if status == 3: # Getting verse number
if char == ' ' and not V:
logging.warning( _("Extra space(s) after chapter at position {} in {} Bible reference {!r}").format( nnn, BBB, referenceString ) )
haveWarnings = True
elif char.isdigit():
V += char
elif char in self.punctuationDict['allowedVerseSuffixes'] and not S: # Could be like verse 5a
S = char
elif V and char in self.punctuationDict['verseSeparator']:
saveReference( BBB, C, V, S, self.referenceList )
V, S = '', ''
elif V and (char in self.punctuationDict['chapterSeparator'] or char in self.punctuationDict['bookSeparator']):
saveReference( BBB, C, V, S, self.referenceList )
V = ''
if self.punctuationDict['chapterSeparator'] == self.punctuationDict['bookSeparator']:
temp, spaceCount = '', 0
status = 4 # We don't know what to expect next
elif char in self.punctuationDict['chapterSeparator']:
C = ''
status = 7
elif char in self.punctuationDict['bookSeparator']:
bookNameOrAbbreviation, BBB, C = '', None, ''
status = 0
elif char in self.punctuationDict['bookBridgeCharacter']:
saveStartReference( BBB, C, V, S )
V, S = '', ''
if char not in self.punctuationDict['chapterBridgeCharacter'] and char not in self.punctuationDict['verseBridgeCharacter']: # Must be a chapter bridge
status, BBB, C = 6, None, ''
else: # We don't know what kind of bridge this is
status, X = 5, ''
elif char in self.punctuationDict['chapterBridgeCharacter']:
saveStartReference( BBB, C, V, S )
V, S = '', ''
if char not in self.punctuationDict['verseBridgeCharacter']: # Must be a chapter bridge
status, C = 7, ''
else: # We don't know what kind of bridge this is
status, X = 5, ''
elif char in self.punctuationDict['verseBridgeCharacter']:
saveStartReference( BBB, C, V, S )
status, V, S = 8, '', ''
else:
logging.error( _("BRL1: Unexpected {!r} character when getting verse number at position {} in {} {} Bible reference {!r}").format( char, nnn, BBB, C, referenceString ) )
haveErrors = True
if V:
saveReference( BBB, C, V, S, self.referenceList )
V, S = '', ''
break # Seems better to break on this one or else we get lots of errors (e.g., if a fr is left open in a footnote)
continue
if status == 4: # Getting the next chapter number or book name (not sure which)
if char == ' ' and not temp:
if spaceCount:
logging.warning( _("Extra space(s) after chapter or book separator at position {} in {} Bible reference {!r}").format( nnn, BBB, referenceString ) )
haveWarnings = True
spaceCount += 1
elif char.isalnum():
temp += char