scripture-guide 1.0.82 → 1.0.84

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -213,8 +213,20 @@ const raw_regex_orig = {
213
213
  const raw_lang = {
214
214
  ko:{
215
215
  spacing: ["", " "],
216
- books:{ "창세기": ["창"], "출애굽기": ["출", "탈출기"], "레위기": ["레"], "민수기": ["민"], "신명기": ["신"], "여호수아": ["수"], "사사기": ["삿", "판관기"], "룻기": ["룻"], "사무엘상": ["삼상"], "사무엘하": ["삼하"], "열왕기상": ["왕상"], "열왕기하": ["왕하"], "역대상": ["대상", "역대기 *상"], "역대하": ["대하", "역대기 *하"], "에스라": ["스", "에즈라"], "느헤미야": ["느"], "에스더": ["에", "에스텔"], "욥기": ["욥"], "시편": ["시"], "잠언": ["잠"], "전도서": ["전", "코헬렛"], "아가": ["아"], "이사야": ["사", "이사야서"], "예레미야": ["렘", "예레미야서"], "예레미야애가": ["애"], "에스겔": ["겔", "에제키엘"], "다니엘": ["단", "다니엘서"], "호세아": ["호", "호세아서"], "요엘": ["욜", "요엘서"], "아모스": ["암", "아모스서"], "오바댜": ["옵", "오바댜서", "오바디야"], "요나": ["욘", "요나서"], "미가": ["미", "미가서"], "나훔": ["나", "나훔서"], "하박국": ["합", "[하합]박[꾹국]서*"], "스바냐": ["습", "스바니야"], "학개": ["학", "하깨"], "스가랴": ["슥", "즈가리야"], "말라기": ["말", "말라기서"], "마태복음": ["마", "마태", "마태오 복음서", "마태오의 복음서"], "마가복음": ["막", "마가", "마르코 복음서"], "누가복음": ["눅","[루누][가카]","[루누][가카] *복음서*"], "요한복음": ["요", "요한", "요한 *복음서*"], "사도행전": ["사*도*행전*","악"], "로마서": ["롬", "로마인들에게 보낸 편지"], "고린도전서": ["고전", "코린토1서"], "고린도후서": ["고후", "코린토2서"], "갈라디아서": ["갈"], "에베소서": ["엡", "에페소인들에게 보낸 편지"], "빌립보서": ["빌", "필리피서"], "골로새서": ["골", "콜로새서"], "데살로니가전서": ["살전", "테살로니카1서"], "데살로니가후서": ["살후", "테살로니카2서"], "디모데전서": ["딤전", "티모테오1서"], "디모데후서": ["딤후", "티모테오2서", "티모테후서"], "디도서": ["딛", "티토서"], "빌레몬서": ["몬", "필레몬서"], "히브리서": ["히"], "야고보서": ["약"], "베드로전서": ["베드로 전서","벧전", "베드로1서"], "베드로후서": ["베드로 후서", "벧후", "베드로2서"], "요한일서": ["요1", "요(일|1)", "(일|1)요"], "요한이서": ["요2", "요(이|2)", "(이|2)요"], "요한삼서": ["요3", "요(삼|3)", "(삼|3)요"], "유다서": ["유다*", "유다의 편지"], "요한 계시록": ["계시*록*", "요한 *[묵계]시록"], "니파이전서": ["니전"], "니파이후서": ["니후"], "야곱서": ["야곱"], "이노스서": ["이노", "이노스서"], "예이롬서": ["예이", "예이롬"], "옴나이서": ["옴", "옴나이"], "몰몬의 말씀": ["몰말", "몰몬말씀"], "모사이야서": ["모사", "모사이야"], "앨마서": ["앨", "앨마"], "힐라맨서": ["힐", "힐라맨"], "제3니파이": ["3니", "제* *3 *니파이서*"], "제4니파이": ["4니", "제* *4 *니파이서*"], "몰몬서": ["몰", "몰몬"], "이더서": ["이더"], "모로나이서": ["모로", "모로나이"], "교리와 성약": ["교성", "교리성약"], "모세서": ["모세"], "아브라함서": ["아브", "아브라함"], "조셉 스미스—마태복음": ["조마", "조셉 스미스—마태"], "조셉 스미스—역사": ["조역", "조셉 스미스—역사"], "신앙개조": ["신개"] },
216
+ books:{ "창세기": ["창"], "출애굽기": ["출", "탈출기"], "레위기": ["레"], "민수기": ["민"], "신명기": ["신"], "여호수아": ["수"], "사사기": ["삿", "판관기"], "룻기": ["룻"], "사무엘상": ["삼상"], "사무엘하": ["삼하"], "열왕기상": ["왕상"], "열왕기하": ["왕하"], "역대상": ["대상", "역대기 *상"], "역대하": ["대하", "역대기 *하"], "에스라": ["스", "에즈라"], "느헤미야": ["느"], "에스더": ["에", "에스텔"], "욥기": ["욥"], "시편": ["시"], "잠언": ["잠"], "전도서": ["전", "코헬렛"], "아가": ["아"], "이사야": ["사", "이사야서"], "예레미야": ["렘", "예레미야서"], "예레미야애가": ["애"], "에스겔": ["겔", "에제키엘"], "다니엘": ["단", "다니엘서"], "호세아": ["호", "호세아서"], "요엘": ["욜", "요엘서"], "아모스": ["암", "아모스서"], "오바댜": ["옵", "오바댜서", "오바디야"], "요나": ["욘", "요나서"], "미가": ["미", "미가서"], "나훔": ["나", "나훔서"], "하박국": ["합", "[하합]박[꾹국]서*"], "스바냐": ["습", "스바니야"], "학개": ["학", "하깨"], "스가랴": ["슥", "즈가리야"], "말라기": ["말", "말라기서"], "마태복음": ["마", "마태", "마태오 복음서", "마태오의 복음서"], "마가복음": ["막", "마가", "마르코 복음서"], "누가복음": ["눅","[루누][가카]","[루누][가카] *복음서*"], "요한복음": ["요", "요한", "요한 *복음서*"], "사도행전": ["사*도*행전*","악"], "로마서": ["롬", "로마인들에게 보낸 편지"], "고린도전서": ["고전", "코린토1서"], "고린도후서": ["고후", "코린토2서"], "갈라디아서": ["갈"], "에베소서": ["엡", "에페소인들에게 보낸 편지"], "빌립보서": ["빌", "필리피서"], "골로새서": ["골", "콜로새서"], "데살로니가전서": ["살전", "테살로니카1서"], "데살로니가후서": ["살후", "테살로니카2서"], "디모데전서": ["딤전", "티모테오1서"], "디모데후서": ["딤후", "티모테오2서", "티모테후서"], "디도서": ["딛", "티토서"], "빌레몬서": ["몬", "필레몬서"], "히브리서": ["히"], "야고보서": ["약"], "베드로전서": ["베드로 전서","벧전", "베드로1서"], "베드로후서": ["베드로 후서", "벧후", "베드로2서"], "요한일서": ["요1", "요(일|1)", "(일|1)요"], "요한이서": ["요2", "요(이|2)", "(이|2)요"], "요한삼서": ["요3", "요(삼|3)", "(삼|3)요"], "유다서": ["유다*", "유다의 편지"], "요한 계시록": ["계시*록*", "요한 *[묵계]시록"], "니파이전서": ["니전"], "니파이후서": ["니후"], "야곱서": ["야곱"], "이노스서": ["이노", "이노스서"], "예이롬서": ["예이", "예이롬"], "옴나이서": ["옴", "옴나이"], "몰몬의 말씀": ["몰말", "몰몬말씀"], "모사이야서": ["모사", "모사이야"], "앨마서": ["앨", "앨마"], "힐라맨서": ["힐", "힐라맨"], "제3니파이": ["3니", "제* *3 *니파이서*"], "제4니파이": ["4니", "제* *4 *니파이서*"], "몰몬서": ["몰", "몰몬"], "이더서": ["이더"], "모로나이서": ["모로", "모로나이"], "교리와 성약": ["교성", "교리성약", "교리와성약"], "모세서": ["모세"], "아브라함서": ["아브", "아브라함"], "조셉 스미스—마태복음": ["조마", "조셉 스미스—마태"], "조셉 스미스—역사": ["조역", "조셉 스미스—역사"], "신앙개조": ["신개"] },
217
217
  pre_rules: [
218
+ // Handle 편 (section) suffix - MUST be first to catch all cases
219
+ ["교리와\\s*성약\\s*(\\d+)\\s*편", "교리성약 $1"], // "교리와 성약 76편" -> "교리성약 76"
220
+ ["교성\\s*(\\d+)\\s*편", "교성 $1"], // "교성 76편" -> "교성 76"
221
+ ["(\\d+)\\s*편", "$1"], // General "76편" -> "76"
222
+
223
+ // Handle spaced forms
224
+ ["교리와\\s*성약", "교리성약"], // Convert spaced form to non-spaced form
225
+
226
+ // Handle parenthetical verses
227
+ ["\\((\\d+~\\d+)절\\)", " $1절"], // Handle "(20~24절)" -> " 20~24절"
228
+ ["\\((\\d+)절\\)", " $1절"], // Handle "(20절)" -> " 20절"
229
+
218
230
  //handle 1장 2절-3절
219
231
  //turn 30 장 10 절 into 30장 10절
220
232
  ["부터", "-"],
@@ -245,10 +257,10 @@ const raw_lang = {
245
257
  ],
246
258
  matchRules:{
247
259
  book: "(제[0-9]+)*",
248
- chapter:"([장절과와및0-9:;,~\\s—–-]|부터|그리고|또는*)*[0-9장절]+",
260
+ chapter:"([장절편과와및0-9:;,~\\s—–-]|부터|그리고|또는*)*[0-9장절편]+",
249
261
  verse:"절",
250
262
  joiners: ["^[;, ]*(또는*|그리고|비교|과|와)*$"],
251
- tail: "[^장절0-9]+$"
263
+ tail: "[^장절편0-9]+$"
252
264
  },
253
265
  },
254
266
  de:{
@@ -646,27 +658,213 @@ const raw_lang = {
646
658
  }
647
659
  }
648
660
  ;
649
- const findMatchingBooks = (content,books) => {
650
- const matchingBooks = books.filter(book => {
651
- try {
652
- // For Vietnamese and other languages, handle more flexible matching
653
- let pattern = book;
654
-
655
- // Replace * with optional space/separator patterns
656
- pattern = pattern.replace(/\*/g, '');
657
-
658
- // Make separators very flexible - handle spaces, hyphens, dots, etc.
659
- pattern = pattern.replace(/[\s\-–—\.]+/g, '[\\s\\-–—\\.]*');
661
+ // Shared utility functions
662
+ /**
663
+ * Shared utilities for scripture reference matching and processing
664
+ * Contains common logic used across detection modules
665
+ */
666
+
667
+ /**
668
+ * Check if two ranges overlap
669
+ * @param {Array} range1 - [start, end] tuple
670
+ * @param {Array} range2 - [start, end] tuple
671
+ * @returns {boolean} True if ranges overlap
672
+ */
673
+ const rangesOverlap = (range1, range2) => {
674
+ return range1[0] < range2[1] && range2[0] < range1[1];
675
+ };
676
+
677
+ /**
678
+ * Remove overlapping matches, with configurable preference logic
679
+ * @param {Array} matches - Array of match tuples
680
+ * @param {string} content - Original content (for debugging)
681
+ * @param {Function} preferenceResolver - Function to choose between overlapping matches
682
+ * @returns {Array} Non-overlapping matches
683
+ */
684
+ const removeOverlaps = (matches, content, preferenceResolver = null) => {
685
+ if (matches.length <= 1) return matches;
686
+
687
+ const result = [];
688
+
689
+ for (let i = 0; i < matches.length; i++) {
690
+ const current = matches[i];
691
+ let shouldInclude = true;
692
+
693
+ // Check for overlaps with already included matches
694
+ for (const included of result) {
695
+ if (rangesOverlap(current, included)) {
696
+ shouldInclude = false;
697
+ break;
698
+ }
699
+ }
700
+
701
+ if (shouldInclude) {
702
+ // Check for overlaps with remaining matches
703
+ for (let j = i + 1; j < matches.length; j++) {
704
+ const next = matches[j];
705
+ if (rangesOverlap(current, next)) {
706
+ // Use preference resolver or default to longer match
707
+ if (preferenceResolver) {
708
+ const preferred = preferenceResolver(current, next, content);
709
+ if (preferred !== current) {
710
+ shouldInclude = false;
711
+ break;
712
+ }
713
+ } else {
714
+ // Default: prefer longer match
715
+ const currentLength = current[1] - current[0];
716
+ const nextLength = next[1] - next[0];
717
+
718
+ if (nextLength > currentLength) {
719
+ shouldInclude = false;
720
+ break;
721
+ }
722
+ }
723
+ }
724
+ }
725
+ }
726
+
727
+ if (shouldInclude) {
728
+ result.push(current);
729
+ }
730
+ }
731
+
732
+ return result;
733
+ };
734
+
735
+ /**
736
+ * Calculate gaps between consecutive matches
737
+ * @param {Array} matches - Array of [start, end] tuples
738
+ * @returns {Array} Array of gap [start, end] tuples
739
+ */
740
+ const calculateGaps = (matches) => {
741
+ return matches.reduce((prev, current, index) => {
742
+ if (index === 0) return prev;
743
+ const lastPair = matches[index - 1];
744
+ const gap = [lastPair[1], current[0]];
745
+ return [...prev, gap];
746
+ }, []);
747
+ };
748
+
749
+ /**
750
+ * Calculate negative space (gaps) for final output construction
751
+ * @param {Array} matches - Array of [start, end] tuples
752
+ * @param {number} contentLength - Total length of content
753
+ * @returns {Array} Array of negative space [start, end] tuples
754
+ */
755
+ const calculateNegativeSpace = (matches, contentLength) => {
756
+ const negativeSpace = matches.reduce((prev, current, index, array) => {
757
+ if (index !== 0) {
758
+ const prevIndex = array[index - 1];
759
+ const gap = [prevIndex[1], current[0]];
760
+ prev.push(gap);
761
+ }
762
+ return prev;
763
+ }, []);
764
+
765
+ if (matches[0][0] !== 0) {
766
+ negativeSpace.unshift([0, matches[0][0]]);
767
+ }
768
+
769
+ if (matches[matches.length - 1][1] !== contentLength) {
770
+ negativeSpace.push([matches[matches.length - 1][1], contentLength]);
771
+ }
772
+
773
+ return negativeSpace;
774
+ };
775
+
776
+ /**
777
+ * Merge adjacent matches based on joiner patterns
778
+ * @param {Array} matches - Array of match tuples
779
+ * @param {Array} gapMergeFlags - Boolean array indicating which gaps can be merged
780
+ * @param {Function} compatibilityCheck - Optional function to check if matches can be merged
781
+ * @returns {Array} Merged matches
782
+ */
783
+ const mergeAdjacentMatches = (matches, gapMergeFlags, compatibilityCheck = null) => {
784
+ return matches.reduce((prev, current, index) => {
785
+ if (index === 0) {
786
+ return [current];
787
+ } else {
788
+ const prevIndex = prev[prev.length - 1];
789
+ const shouldMerge = gapMergeFlags[index - 1];
660
790
 
661
- const regex = new RegExp(pattern, "ig");
662
- const result = regex.test(content);
791
+ // Check compatibility if function provided
792
+ if (shouldMerge && compatibilityCheck) {
793
+ const isCompatible = compatibilityCheck(prevIndex, current);
794
+ if (!isCompatible) {
795
+ prev.push(current);
796
+ return prev;
797
+ }
798
+ }
663
799
 
664
- return result;
665
- } catch (e) {
666
- // Fallback to original logic if regex fails
667
- return (new RegExp(book,"ig")).test(content);
800
+ if (shouldMerge) {
801
+ // Merge logic - keep first position, extend to second end, combine text and verse IDs
802
+ if (prevIndex.length > 2 && current.length > 2) {
803
+ // Extended format: [start, end, text, verseIds]
804
+ const startPos = prevIndex[0];
805
+ const endPos = current[1];
806
+ const combinedText = prevIndex[2] + ";" + current[2]; // Combine with semicolon
807
+ const combinedVerseIds = [...(prevIndex[3] || []), ...(current[3] || [])]; // Merge verse ID arrays
808
+ const merged = [startPos, endPos, combinedText, combinedVerseIds];
809
+ prev[prev.length - 1] = merged;
810
+ } else {
811
+ // Basic format: [start, end]
812
+ const merged = [prevIndex[0], current[1], ...(prevIndex.slice(2))];
813
+ prev[prev.length - 1] = merged;
814
+ }
815
+ } else {
816
+ prev.push(current);
817
+ }
818
+ return prev;
668
819
  }
669
- });
820
+ }, []);
821
+ };
822
+
823
+ /**
824
+ * Build final output by alternating between cut items and negative space
825
+ * @param {Array} cutItems - Processed match content
826
+ * @param {Array} negativeItems - Unprocessed content between matches
827
+ * @param {boolean} firstReferenceIsAtStart - Whether first match starts at position 0
828
+ * @returns {string} Final merged output
829
+ */
830
+ const buildFinalOutput = (cutItems, negativeItems, firstReferenceIsAtStart) => {
831
+ const maxCount = Math.max(cutItems.length, negativeItems.length);
832
+ const merged = [];
833
+
834
+ for (let i = 0; i < maxCount; i++) {
835
+ const firstItem = firstReferenceIsAtStart ? cutItems[i] : negativeItems[i];
836
+ const secondItem = firstReferenceIsAtStart ? negativeItems[i] : cutItems[i];
837
+ if (firstItem) merged.push(firstItem);
838
+ if (secondItem) merged.push(secondItem);
839
+ }
840
+
841
+ return merged.join("");
842
+ };
843
+
844
+ /**
845
+ * Default tie-breaker for scriptdetect.mjs overlap resolution
846
+ * @param {Array} pair1 - First match tuple
847
+ * @param {Array} pair2 - Second match tuple
848
+ * @param {string} content - Original content
849
+ * @returns {Array} Preferred match tuple
850
+ */
851
+ const defaultTieBreaker = (pair1, pair2, content) => {
852
+ const string1 = content.substring(pair1[0], pair1[1]);
853
+ const string2 = content.substring(pair2[0], pair2[1]);
854
+
855
+ // If one pair is all lower case, return the other one
856
+ if(/[^A-Z]/.test(string1) && !/[^A-Z]/.test(string2)) return pair2;
857
+ if(/[^A-Z]/.test(string2) && !/[^A-Z]/.test(string1)) return pair1;
858
+
859
+ if(string1.length > string2.length) return pair1;
860
+ if(string2.length > string1.length) return pair2;
861
+
862
+ return pair1;
863
+ };
864
+
865
+ // Script detection functions
866
+ const findMatchingBooks = (content,books) => {
867
+ const matchingBooks = books.filter(i=>(new RegExp(i,"ig")).test(content));
670
868
  return matchingBooks;
671
869
  }
672
870
 
@@ -675,10 +873,10 @@ const findMatches = (content,books,lang_extra) => {
675
873
  const htmlEntityMap = {
676
874
  '&ndash;': '–',
677
875
  '&mdash;': '—',
678
- '&minus;': '–', // Treat minus as en dash for scripture ranges
876
+ '&minus;': '−',
679
877
  '&#8211;': '–',
680
878
  '&#8212;': '—',
681
- '&#8722;': '–' // Treat minus as en dash for scripture ranges
879
+ '&#8722;': '−'
682
880
  };
683
881
 
684
882
  let normalizedContent = content;
@@ -757,7 +955,7 @@ const findMatches = (content,books,lang_extra) => {
757
955
  if(prev.includes(current)) return prev;
758
956
  return [...prev,current]
759
957
  },[]).filter(i=>!!i);
760
- return {matches, normalizedContent};
958
+ return matches;
761
959
  }
762
960
 
763
961
 
@@ -797,43 +995,10 @@ function findMatchIndexes(content, matches,lookupReference, lang_extra) {
797
995
 
798
996
  if(!indexes.length) return false;
799
997
 
800
-
801
- const tieBreaker = (pair1,pair2)=>{
802
- const string1 = content.substring(pair1[0],pair1[1]);
803
- const string2 = content.substring(pair2[0],pair2[1]);
804
-
805
- // if one pair is all lower case, return the other one
806
- if(/[^A-Z]/.test(string1) && !/[^A-Z]/.test(string2)) return pair2;
807
- if(/[^A-Z]/.test(string2) && !/[^A-Z]/.test(string1)) return pair1;
808
-
809
- if(string1.length > string2.length) return pair1;
810
- if(string2.length > string1.length) return pair2;
811
-
812
- return pair1;
813
- }
814
-
815
-
816
- const nonOverlappingIndeces = indexes.reduce((prev, current) => {
817
- if (prev.length === 0) {
818
- return [current];
819
- }
820
- const lastPair = prev[prev.length - 1];
821
- if (current[0] < lastPair[1]) { // They overlap
822
- const chosenPair = tieBreaker(lastPair, current);
823
- if (chosenPair === lastPair) {
824
- // Keep the last pair, discard the current one
825
- return prev;
826
- } else {
827
- // Replace the last pair with the current one
828
- prev.pop();
829
- return [...prev, current];
830
- }
831
- } else {
832
- // They don't overlap, add the current pair
833
- return [...prev, current];
834
- }
835
- }, []).filter(([start,end])=>start!==end);
836
-
998
+ // Use shared overlap removal with custom tie-breaker
999
+ const preferenceResolver = (pair1, pair2, content) => defaultTieBreaker(pair1, pair2, content);
1000
+ const nonOverlappingIndeces = removeOverlaps(indexes, content, preferenceResolver)
1001
+ .filter(([start,end])=>start!==end);
837
1002
 
838
1003
  return nonOverlappingIndeces;
839
1004
 
@@ -849,16 +1014,12 @@ const processReferenceDetection = (content,books,lang_extra,lookupReference,call
849
1014
  {
850
1015
  try{
851
1016
  lang_extra = lang_extra || {};
852
- const {matches, normalizedContent} = findMatches(content,books,lang_extra);
853
- const matchIndeces = findMatchIndexes(normalizedContent,matches,lookupReference,lang_extra);
1017
+ const matches = findMatches(content,books,lang_extra);
1018
+ const matchIndeces = findMatchIndexes(content,matches,lookupReference,lang_extra);
854
1019
  if(!matchIndeces) return content;
855
- const gapsBetweenIndeces = matchIndeces.reduce((prev,current,index)=>{
856
- if(index === 0) return prev;
857
- const lastPair = matchIndeces[index-1];
858
- const gap = [lastPair[1],current[0]];
859
- return [...prev,gap];
860
- },[]);
861
- const gapStrings = gapsBetweenIndeces.map(([start,end])=>normalizedContent.substring(start,end).trim());
1020
+
1021
+ const gapsBetweenIndeces = calculateGaps(matchIndeces);
1022
+ const gapStrings = gapsBetweenIndeces.map(([start,end])=>content.substring(start,end).trim());
862
1023
  //console.log({matches,matchIndeces,gapsBetweenIndeces,gapStrings});
863
1024
  const joiners = lang_extra.joiners || ["^[;, ]*(and|c\\.*f\\.*)*$"];
864
1025
  const gapThatMayBeMerged = gapsBetweenIndeces.map(([start,end],i)=>{
@@ -869,65 +1030,249 @@ const processReferenceDetection = (content,books,lang_extra,lookupReference,call
869
1030
  return canBeMerged;
870
1031
  });
871
1032
 
1033
+ // Use shared merge logic
1034
+ const mergedIndeces = mergeAdjacentMatches(matchIndeces, gapThatMayBeMerged);
872
1035
 
873
- // new incexes
874
- const mergedIndeces = matchIndeces.reduce((prev, current, index) => {
875
- if (index === 0) {
876
- return [current];
877
- } else {
878
- const prevIndex = prev[prev.length - 1];
879
- if (gapThatMayBeMerged[index - 1]) {
880
- const merged = [prevIndex[0], current[1]];
881
- prev[prev.length - 1] = merged;
882
- } else {
883
- prev.push(current);
884
- }
885
- return prev;
886
- }
887
- }, []);
888
-
889
- //get the gaps and the front/end bumpers if any
890
- const negativeSpace = mergedIndeces.reduce((prev, current, index, array) => {
891
- if (index !== 0) {
892
- const prevIndex = array[index - 1];
893
- const gap = [prevIndex[1], current[0]];
894
- prev.push(gap);
895
- }
896
- return prev;
897
- }, []);
898
-
899
- if (mergedIndeces[0][0] !== 0) {
900
- negativeSpace.unshift([0, mergedIndeces[0][0]]);
901
- }
902
-
903
- if (mergedIndeces[mergedIndeces.length - 1][1] !== content.length) {
904
- negativeSpace.push([mergedIndeces[mergedIndeces.length - 1][1], content.length]);
905
- }
906
-
1036
+ // Use shared negative space calculation
1037
+ const negativeSpace = calculateNegativeSpace(mergedIndeces, content.length);
907
1038
 
908
1039
  //check content between matches. If puctuation only (or 'and'), then merge
909
1040
  const cutItems = mergedIndeces.map(([start,end])=>{
910
- const string = normalizedContent.substring(start,end);
911
- return lookupReference(string).query
912
- }).map(callback);
1041
+ const string = content.substring(start,end);
1042
+ const lookupResult = lookupReference(string);
1043
+ return callback(lookupResult.query, lookupResult.verse_ids);
1044
+ });
913
1045
 
914
- const negativeItems = negativeSpace.map(([start,end])=>normalizedContent.substring(start,end));
1046
+ const negativeItems = negativeSpace.map(([start,end])=>content.substring(start,end));
915
1047
  const firstReferenceIsAtStart = mergedIndeces[0][0] === 0;
916
- const maxCount = Math.max(cutItems.length,negativeItems.length);
917
- //merge by alternating cutItems and negativeItems. run the callback on the cut items
918
- const merged = [];
919
- for(let i=0;i<maxCount;i++){
920
- const firstItem = firstReferenceIsAtStart ? cutItems[i] : negativeItems[i];
921
- const secondItem = firstReferenceIsAtStart ? negativeItems[i] : cutItems[i];
922
- if(firstItem) merged.push(firstItem);
923
- if(secondItem) merged.push(secondItem);
924
- }
925
-
926
- return merged.join("");
1048
+
1049
+ return buildFinalOutput(cutItems, negativeItems, firstReferenceIsAtStart);
927
1050
  }catch(e){
928
1051
  return content;
929
1052
  }
930
1053
  }
1054
+ // Context detection functions
1055
+ /**
1056
+ * Enhanced contextual scripture reference detection module
1057
+ * Handles detection of implied references using context from explicit references
1058
+ */
1059
+ // Enhanced reference detection with contextual processing
1060
+ const detectReferencesWithContext = (content, books, lang_extra, lookupReference, callback, options, generateReference = null) => {
1061
+ try {
1062
+ // Step 1: Find explicit references using existing logic
1063
+ const explicitMatches = findMatches(content, books, lang_extra);
1064
+ const explicitIndices = findMatchIndexes(content, explicitMatches, lookupReference, lang_extra);
1065
+
1066
+ // Step 2: Find implied references using context
1067
+ const impliedMatches = findImpliedReferences(content, explicitMatches, explicitIndices, lookupReference, options);
1068
+
1069
+ // Step 3: Merge and sort all matches - store both original text and verse IDs
1070
+ const explicitMatchesWithRefs = (explicitIndices || []).map(([start, end]) => {
1071
+ const originalText = content.substring(start, end);
1072
+ const verification = lookupReference(originalText);
1073
+ return [start, end, originalText, verification.verse_ids];
1074
+ });
1075
+
1076
+ // Convert implied matches to include verse IDs
1077
+ const impliedMatchesWithVerseIds = impliedMatches.map(([start, end, resolvedRef]) => {
1078
+ const originalText = content.substring(start, end);
1079
+ const verification = lookupReference(resolvedRef);
1080
+ return [start, end, originalText, verification.verse_ids];
1081
+ });
1082
+
1083
+ const allMatches = [...explicitMatchesWithRefs, ...impliedMatchesWithVerseIds];
1084
+ allMatches.sort((a, b) => a[0] - b[0]);
1085
+
1086
+ // Step 4: Remove overlaps, preferring explicit matches
1087
+ const nonOverlappingMatches = removeOverlaps(allMatches, content);
1088
+
1089
+ if (!nonOverlappingMatches || nonOverlappingMatches.length === 0) {
1090
+ return content;
1091
+ }
1092
+
1093
+ // Step 5: Apply the same gap merging logic as original
1094
+ const gapsBetweenIndices = calculateGaps(nonOverlappingMatches);
1095
+
1096
+ const joiners = lang_extra.joiners || ["^[;]*(and|cf\\.)*$", "^\\s*[;,]\\s*$"]; // More restrictive joiners
1097
+ const gapThatMayBeMerged = gapsBetweenIndices.map(([start, end]) => {
1098
+ const gapString = content.substring(start, end).trim();
1099
+ return joiners.some(joiner => (new RegExp(joiner, "ig")).test(gapString));
1100
+ });
1101
+
1102
+ // Compatibility check for merging references
1103
+ const compatibilityCheck = (prevIndex, current) => {
1104
+ // Always allow merging for explicit references separated by joiners
1105
+ // The user's intention is clear when they list references like "Isa 45.22;Morm 3.18;Moro 10.24"
1106
+ return true;
1107
+ };
1108
+
1109
+ // Merge adjacent matches if gaps are joiners and references are compatible
1110
+ const mergedIndices = mergeAdjacentMatches(nonOverlappingMatches, gapThatMayBeMerged, compatibilityCheck);
1111
+
1112
+ // Step 6: Build final output
1113
+ const negativeSpace = calculateNegativeSpace(mergedIndices, content.length);
1114
+
1115
+ // Use the stored reference and verse IDs
1116
+ const cutItems = mergedIndices.map(([start, end, originalText, verseIds]) => {
1117
+ // Pass verseIds to callback for compatibility with expected signature
1118
+ return callback(originalText, verseIds);
1119
+ });
1120
+
1121
+ const negativeItems = negativeSpace.map(([start, end]) => content.substring(start, end));
1122
+ const firstReferenceIsAtStart = mergedIndices[0][0] === 0;
1123
+
1124
+ const result = buildFinalOutput(cutItems, negativeItems, firstReferenceIsAtStart);
1125
+ return result;
1126
+ } catch (e) {
1127
+ console.warn('Enhanced reference detection failed, falling back to basic detection:', e);
1128
+ return processReferenceDetection(content, books, lang_extra, lookupReference, callback);
1129
+ }
1130
+ };
1131
+
1132
+ /**
1133
+ * Find all book contexts from explicit references
1134
+ * @param {string} content - The text content
1135
+ * @param {Array} explicitMatches - Array of explicit reference strings
1136
+ * @param {Array} explicitIndices - Array of [start, end] positions for explicit matches
1137
+ * @param {Function} lookupReference - Function to validate references
1138
+ * @returns {Array} Array of context objects with book, chapter, and position info
1139
+ */
1140
+ const findBookContexts = (content, explicitMatches, explicitIndices, lookupReference) => {
1141
+ const contexts = [];
1142
+
1143
+ // Use the already found explicit matches and their positions
1144
+ if (explicitMatches && explicitIndices) {
1145
+ for (let i = 0; i < explicitMatches.length; i++) {
1146
+ const match = explicitMatches[i];
1147
+ const [start, end] = explicitIndices[i];
1148
+
1149
+ const verification = lookupReference(match);
1150
+
1151
+ if (verification.verse_ids && verification.verse_ids.length > 0) {
1152
+ // Extract book and chapter from the verified reference
1153
+ // Handle both "Book Chapter:Verse" and "Book Chapter" (like D&C 76) patterns
1154
+ let refParts = verification.ref.match(/^(.+?)\s+(\d+):/);
1155
+ if (!refParts) {
1156
+ // Try pattern for section-only references like "Doctrine and Covenants 76"
1157
+ refParts = verification.ref.match(/^(.+?)\s+(\d+)$/);
1158
+ }
1159
+
1160
+ if (refParts) {
1161
+ const cleanBook = refParts[1];
1162
+ const chapter = parseInt(refParts[2]);
1163
+
1164
+ contexts.push({
1165
+ position: start,
1166
+ book: cleanBook,
1167
+ chapter: chapter,
1168
+ endPosition: end
1169
+ });
1170
+ }
1171
+ }
1172
+ }
1173
+ }
1174
+
1175
+ const result = contexts.sort((a, b) => a.position - b.position);
1176
+ return result;
1177
+ };
1178
+
1179
+ /**
1180
+ * Get the nearest book context for a given position
1181
+ * @param {number} position - Character position in the text
1182
+ * @param {Array} bookContexts - Array of context objects from findBookContexts
1183
+ * @param {number} maxDistance - Maximum distance to look for context
1184
+ * @returns {Object|null} The nearest context object or null if none found
1185
+ */
1186
+ const getNearestBookContext = (position, bookContexts, maxDistance) => {
1187
+ if (!bookContexts.length) return null;
1188
+
1189
+ // Find the most recent context before this position
1190
+ let bestContext = null;
1191
+ let bestDistance = Infinity;
1192
+
1193
+ for (const context of bookContexts) {
1194
+ if (context.position <= position) {
1195
+ const distance = position - context.endPosition;
1196
+ if (distance <= maxDistance && distance < bestDistance) {
1197
+ bestContext = context;
1198
+ bestDistance = distance;
1199
+ }
1200
+ }
1201
+ }
1202
+
1203
+ return bestContext;
1204
+ };
1205
+
1206
+ /**
1207
+ * Find implied references using context from explicit references
1208
+ * @param {string} content - The text content
1209
+ * @param {Array} explicitMatches - Array of explicit reference strings
1210
+ * @param {Array} explicitIndices - Array of [start, end] positions for explicit matches
1211
+ * @param {Function} lookupReference - Function to validate references
1212
+ * @param {Object} options - Detection options including maxContextDistance
1213
+ * @returns {Array} Array of [start, end, resolvedReference] tuples for implied references
1214
+ */
1215
+ const findImpliedReferences = (content, explicitMatches, explicitIndices, lookupReference, options) => {
1216
+ const matches = [];
1217
+
1218
+ // Find all explicit book references to establish context
1219
+ const bookContexts = findBookContexts(content, explicitMatches, explicitIndices, lookupReference);
1220
+
1221
+ // Simple pattern to match "vv. X, Y, Z:A, B:C" - treat it as one unit
1222
+ const verseGroupPattern = /\b(?:vv?\.?\s*|vs\.?\s*|verses?\s+)([\d:,\s–—-]+?)(?=\s*[).;\n]|$)/gi;
1223
+
1224
+ let match;
1225
+ while ((match = verseGroupPattern.exec(content)) !== null) {
1226
+ const fullMatch = match[0];
1227
+ const verseSpec = match[1].trim();
1228
+ const position = match.index;
1229
+
1230
+ // Find the nearest book context
1231
+ const context = getNearestBookContext(position, bookContexts, options.maxContextDistance);
1232
+ if (context) {
1233
+ // Replace the "vv." with the actual book and chapter
1234
+ const impliedRef = `${context.book} ${context.chapter}:${verseSpec}`;
1235
+ const verification = lookupReference(impliedRef);
1236
+
1237
+ if (verification.verse_ids && verification.verse_ids.length > 0) {
1238
+ matches.push([position, position + fullMatch.length, impliedRef]);
1239
+ }
1240
+ }
1241
+ }
1242
+
1243
+ // Also handle standalone chapter:verse patterns
1244
+ const chapterVersePattern = /\b(\d+):(\d+(?:[–—-]\d+)?(?:\s*,\s*\d+(?:[–—-]\d+)?)*)/g;
1245
+ while ((match = chapterVersePattern.exec(content)) !== null) {
1246
+ const fullMatch = match[0];
1247
+ const chapter = match[1];
1248
+ const verses = match[2];
1249
+ const position = match.index;
1250
+
1251
+ // Skip if this is part of an explicit reference we already found
1252
+ const isPartOfExplicit = explicitIndices && explicitIndices.some(([start, end]) =>
1253
+ position >= start && position < end
1254
+ );
1255
+
1256
+ if (isPartOfExplicit) {
1257
+ continue;
1258
+ }
1259
+
1260
+ // Find the nearest book context
1261
+ const context = getNearestBookContext(position, bookContexts, options.maxContextDistance);
1262
+ if (context) {
1263
+ const impliedRef = `${context.book} ${chapter}:${verses}`;
1264
+ const verification = lookupReference(impliedRef);
1265
+
1266
+ if (verification.verse_ids && verification.verse_ids.length > 0) {
1267
+ matches.push([position, position + fullMatch.length, impliedRef]);
1268
+ }
1269
+ }
1270
+ }
1271
+
1272
+ return matches;
1273
+ };
1274
+
1275
+ ;
931
1276
  // Browser localStorage key for language preference
932
1277
  const LANGUAGE_STORAGE_KEY = 'scriptureGuideUtils_language';
933
1278
 
@@ -1494,18 +1839,39 @@ const loadMaxVerse = function(book, chapter, config) {
1494
1839
  return config.raw_index[book][parseInt(chapter) - 1]
1495
1840
  }
1496
1841
 
1497
-
1498
-
1499
- const detectReferences = (content, callBack, language = null) => {
1500
-
1842
+ const detectReferences = (content, callBack, options = null) => {
1843
+ // Handle legacy API: (content, callback, language)
1844
+ if (typeof options === 'string' || options === null) {
1845
+ const language = options;
1846
+ options = { language };
1847
+ }
1848
+
1849
+ // Default options
1850
+ const defaultOptions = {
1851
+ language: null,
1852
+ contextAware: true,
1853
+ contextScope: 'sentence',
1854
+ maxContextDistance: 500,
1855
+ enableImpliedBooks: true,
1856
+ enableVerseAbbrev: true
1857
+ };
1858
+
1859
+ const finalOptions = { ...defaultOptions, ...options };
1501
1860
  callBack = callBack ? callBack : (i)=>{return `[${i}]`};
1502
- const effectiveLanguage = getEffectiveLanguage(language);
1861
+
1862
+ const effectiveLanguage = getEffectiveLanguage(finalOptions.language);
1503
1863
  const config = getLanguageConfig(effectiveLanguage);
1504
1864
  const src = config.raw_regex.books.map(i => i[0]);
1505
1865
  const dst = [...new Set(config.raw_regex.books.map(i => i[1]))];
1506
1866
  const books = [...dst, ...src];
1867
+
1868
+ // Use enhanced processing if context-aware mode is enabled
1869
+ if (finalOptions.contextAware) {
1870
+ return detectReferencesWithContext(content, books, config.lang_extra, (query) => lookupReference(query, effectiveLanguage), callBack, finalOptions, generateReference);
1871
+ }
1872
+
1873
+ // Fallback to original processing
1507
1874
  return processReferenceDetection(content, books, config.lang_extra, (query) => lookupReference(query, effectiveLanguage), callBack);
1508
-
1509
1875
  }
1510
1876
 
1511
1877
  const getLanguageConfig = function(language) {