-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlogos.py
More file actions
2398 lines (2168 loc) · 93.2 KB
/
Copy pathlogos.py
File metadata and controls
2398 lines (2168 loc) · 93.2 KB
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
# logos - a minimalist terminal Bible reader
"""
Built on public domain scripture texts. Zero dependencies beyond Python stdlib.
Works on Linux, BSD, macOS, and Windows.
"""
import curses
import curses.ascii
import json
import os
import sys
import textwrap
import platform
import subprocess
import configparser
from pathlib import Path
from typing import Optional
# VERSION & METADATA
VERSION = "1.2.0"
PROGRAM_NAME = "logos"
# OS DETECTION
# Centralised so debug menu can override it for testing.
def _detect_os() -> str:
"""Return a canonical OS string: 'windows', 'macos', 'linux', 'freebsd',
'openbsd', 'netbsd', or 'unknown'."""
s = platform.system().lower()
if s == "windows":
return "windows"
if s == "darwin":
return "macos"
if s == "linux":
return "linux"
if "bsd" in s:
return s # freebsd / openbsd / netbsd
return "unknown"
# Global that debug menu can override
_OS_OVERRIDE: Optional[str] = None
def get_os() -> str:
"""Return the effective OS string (may be overridden by debug menu)."""
return _OS_OVERRIDE if _OS_OVERRIDE else _detect_os()
# CONFIGURATION PATHS (XDG-compliant on Linux/BSD, native on macOS/Windows)
def get_config_dir() -> Path:
os_name = get_os()
if os_name == "windows":
base = Path(os.environ.get("APPDATA", Path.home()))
elif os_name == "macos":
base = Path.home() / "Library" / "Application Support"
else:
# Linux, FreeBSD, OpenBSD, NetBSD, unknown → XDG
base = Path(os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config"))
d = base / PROGRAM_NAME
d.mkdir(parents=True, exist_ok=True)
return d
def get_data_dir() -> Path:
os_name = get_os()
if os_name == "windows":
base = Path(os.environ.get("LOCALAPPDATA", Path.home()))
elif os_name == "macos":
base = Path.home() / "Library" / "Application Support"
else:
# Linux, BSD, unknown → XDG
base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share"))
d = base / PROGRAM_NAME
d.mkdir(parents=True, exist_ok=True)
return d
def get_default_save_dir() -> Path:
"""Platform-appropriate default directory for saved passages."""
os_name = get_os()
if os_name == "windows":
docs = Path(os.environ.get("USERPROFILE", Path.home())) / "Documents"
return docs / "logos_passages"
elif os_name == "macos":
return Path.home() / "Documents" / "logos_passages"
else:
return Path.home() / "logos_passages"
CONFIG_FILE = get_config_dir() / "config.ini"
DATA_DIR = get_data_dir()
# SCRIPTURE DATA
# The full KJV, WEB, and ASV are public domain. We ship them embedded.
# Deuterocanonical books (Catholic/Orthodox) come from public domain sources.
# Structure: BIBLE[translation][book_abbrev] = {name, chapters: {num: [verses]}}
# Book order definitions per canon
PROTESTANT_CANON = [
"Gen","Exod","Lev","Num","Deut","Josh","Judg","Ruth",
"1Sam","2Sam","1Kgs","2Kgs","1Chr","2Chr","Ezra","Neh",
"Esth","Job","Ps","Prov","Eccl","Song","Isa","Jer","Lam",
"Ezek","Dan","Hos","Joel","Amos","Obad","Jonah","Mic",
"Nah","Hab","Zeph","Hag","Zech","Mal",
"Matt","Mark","Luke","John","Acts","Rom","1Cor","2Cor",
"Gal","Eph","Phil","Col","1Thess","2Thess","1Tim","2Tim",
"Titus","Phlm","Heb","Jas","1Pet","2Pet","1John","2John",
"3John","Jude","Rev"
]
DEUTEROCANON = [
"Tob","Jdt","1Macc","2Macc","Wis","Sir","Bar","PrAzar",
"Sus","Bel","1Esd","PrMan","Ps151","3Macc","2Esd","4Macc"
]
CATHOLIC_CANON = (
PROTESTANT_CANON[:39] +
["Tob","Jdt","1Macc","2Macc","Wis","Sir","Bar"] +
PROTESTANT_CANON[39:]
)
ORTHODOX_CANON = (
PROTESTANT_CANON[:39] +
["Tob","Jdt","1Macc","2Macc","3Macc","4Macc","Wis","Sir","Bar",
"PrAzar","Sus","Bel","1Esd","PrMan","Ps151"] +
PROTESTANT_CANON[39:]
)
# Full human-readable book names
BOOK_NAMES = {
"Gen": "Genesis", "Exod": "Exodus",
"Lev": "Leviticus", "Num": "Numbers",
"Deut": "Deuteronomy", "Josh": "Joshua",
"Judg": "Judges", "Ruth": "Ruth",
"1Sam": "1 Samuel", "2Sam": "2 Samuel",
"1Kgs": "1 Kings", "2Kgs": "2 Kings",
"1Chr": "1 Chronicles", "2Chr": "2 Chronicles",
"Ezra": "Ezra", "Neh": "Nehemiah",
"Esth": "Esther", "Job": "Job",
"Ps": "Psalms", "Prov": "Proverbs",
"Eccl": "Ecclesiastes", "Song": "Song of Solomon",
"Isa": "Isaiah", "Jer": "Jeremiah",
"Lam": "Lamentations", "Ezek": "Ezekiel",
"Dan": "Daniel", "Hos": "Hosea",
"Joel": "Joel", "Amos": "Amos",
"Obad": "Obadiah", "Jonah": "Jonah",
"Mic": "Micah", "Nah": "Nahum",
"Hab": "Habakkuk", "Zeph": "Zephaniah",
"Hag": "Haggai", "Zech": "Zechariah",
"Mal": "Malachi",
"Matt": "Matthew", "Mark": "Mark",
"Luke": "Luke", "John": "John",
"Acts": "Acts", "Rom": "Romans",
"1Cor": "1 Corinthians", "2Cor": "2 Corinthians",
"Gal": "Galatians", "Eph": "Ephesians",
"Phil": "Philippians", "Col": "Colossians",
"1Thess": "1 Thessalonians", "2Thess": "2 Thessalonians",
"1Tim": "1 Timothy", "2Tim": "2 Timothy",
"Titus": "Titus", "Phlm": "Philemon",
"Heb": "Hebrews", "Jas": "James",
"1Pet": "1 Peter", "2Pet": "2 Peter",
"1John": "1 John", "2John": "2 John",
"3John": "3 John", "Jude": "Jude",
"Rev": "Revelation",
# Deuterocanon
"Tob": "Tobit", "Jdt": "Judith",
"1Macc": "1 Maccabees", "2Macc": "2 Maccabees",
"3Macc": "3 Maccabees", "4Macc": "4 Maccabees",
"Wis": "Wisdom", "Sir": "Sirach",
"Bar": "Baruch", "PrAzar": "Prayer of Azariah",
"Sus": "Susanna", "Bel": "Bel and the Dragon",
"1Esd": "1 Esdras", "PrMan": "Prayer of Manasseh",
"Ps151": "Psalm 151", "2Esd": "2 Esdras",
}
# Alternate search names → canonical abbreviations
BOOK_ALIASES = {
"genesis": "Gen", "gen": "Gen",
"exodus": "Exod", "exod": "Exod", "ex": "Exod",
"leviticus": "Lev", "lev": "Lev",
"numbers": "Num", "num": "Num",
"deuteronomy": "Deut", "deut": "Deut", "dt": "Deut",
"joshua": "Josh", "josh": "Josh",
"judges": "Judg", "judg": "Judg", "jdg": "Judg",
"ruth": "Ruth",
"1samuel": "1Sam", "1sam": "1Sam", "1s": "1Sam",
"2samuel": "2Sam", "2sam": "2Sam", "2s": "2Sam",
"1kings": "1Kgs", "1kgs": "1Kgs", "1k": "1Kgs",
"2kings": "2Kgs", "2kgs": "2Kgs", "2k": "2Kgs",
"1chronicles": "1Chr", "1chr": "1Chr", "1ch": "1Chr",
"2chronicles": "2Chr", "2chr": "2Chr", "2ch": "2Chr",
"ezra": "Ezra",
"nehemiah": "Neh", "neh": "Neh",
"esther": "Esth", "esth": "Esth", "est": "Esth",
"job": "Job",
"psalms": "Ps", "psalm": "Ps", "ps": "Ps",
"proverbs": "Prov", "prov": "Prov", "pr": "Prov",
"ecclesiastes": "Eccl", "eccl": "Eccl", "ecc": "Eccl",
"songofsongs": "Song", "song": "Song", "sos": "Song",
"isaiah": "Isa", "isa": "Isa",
"jeremiah": "Jer", "jer": "Jer",
"lamentations": "Lam", "lam": "Lam",
"ezekiel": "Ezek", "ezek": "Ezek", "ezk": "Ezek",
"daniel": "Dan", "dan": "Dan",
"hosea": "Hos", "hos": "Hos",
"joel": "Joel",
"amos": "Amos",
"obadiah": "Obad", "obad": "Obad", "ob": "Obad",
"jonah": "Jonah", "jon": "Jonah",
"micah": "Mic", "mic": "Mic",
"nahum": "Nah", "nah": "Nah",
"habakkuk": "Hab", "hab": "Hab",
"zephaniah": "Zeph", "zeph": "Zeph", "zep": "Zeph",
"haggai": "Hag", "hag": "Hag",
"zechariah": "Zech", "zech": "Zech", "zec": "Zech",
"malachi": "Mal", "mal": "Mal",
"matthew": "Matt", "matt": "Matt", "mt": "Matt",
"mark": "Mark", "mk": "Mark",
"luke": "Luke", "lk": "Luke",
"john": "John", "jn": "John",
"acts": "Acts",
"romans": "Rom", "rom": "Rom",
"1corinthians": "1Cor", "1cor": "1Cor",
"2corinthians": "2Cor", "2cor": "2Cor",
"galatians": "Gal", "gal": "Gal",
"ephesians": "Eph", "eph": "Eph",
"philippians": "Phil", "phil": "Phil",
"colossians": "Col", "col": "Col",
"1thessalonians": "1Thess", "1thess": "1Thess", "1th": "1Thess",
"2thessalonians": "2Thess", "2thess": "2Thess", "2th": "2Thess",
"1timothy": "1Tim", "1tim": "1Tim",
"2timothy": "2Tim", "2tim": "2Tim",
"titus": "Titus", "tit": "Titus",
"philemon": "Phlm", "phlm": "Phlm", "phm": "Phlm",
"hebrews": "Heb", "heb": "Heb",
"james": "Jas", "jas": "Jas",
"1peter": "1Pet", "1pet": "1Pet", "1pe": "1Pet",
"2peter": "2Pet", "2pet": "2Pet", "2pe": "2Pet",
"1john": "1John", "1jn": "1John",
"2john": "2John", "2jn": "2John",
"3john": "3John", "3jn": "3John",
"jude": "Jude", "jud": "Jude",
"revelation": "Rev", "rev": "Rev", "ap": "Rev",
# Deuterocanon aliases
"tobit": "Tob", "tob": "Tob",
"judith": "Jdt", "jdt": "Jdt",
"1maccabees": "1Macc", "1macc": "1Macc",
"2maccabees": "2Macc", "2macc": "2Macc",
"3maccabees": "3Macc", "3macc": "3Macc",
"4maccabees": "4Macc", "4macc": "4Macc",
"wisdom": "Wis", "wis": "Wis",
"sirach": "Sir", "sir": "Sir", "ecclesiasticus": "Sir",
"baruch": "Bar", "bar": "Bar",
}
# TRANSLATIONS & DENOMINATIONS
TRANSLATIONS = {
"KJV": {
"name": "King James Version (1769)",
"lang": "English",
"tradition": "Protestant / Anglican",
"canon": "protestant",
"file": "kjv.json",
},
"WEB": {
"name": "World English Bible",
"lang": "English",
"tradition": "Interdenominational",
"canon": "protestant",
"file": "web.json",
},
"ASV": {
"name": "American Standard Version (1901)",
"lang": "English",
"tradition": "Protestant",
"canon": "protestant",
"file": "asv.json",
},
"DOUAY": {
"name": "Douay-Rheims (Challoner 1899)",
"lang": "English",
"tradition": "Roman Catholic",
"canon": "catholic",
"file": "douay.json",
},
"RUS_SYNODAL": {
"name": "Synodal Bible (Russian, 1876)",
"lang": "Russian",
"tradition": "Russian / Serbian / Bulgarian / Georgian Orthodox",
"canon": "orthodox",
"file": "rus_synodal.json",
},
"UKR": {
"name": "Ogienko Bible (Ukrainian, 1962)",
"lang": "Ukrainian",
"tradition": "Ukrainian Orthodox / Protestant",
"canon": "orthodox",
"file": "ukr.json",
},
"ROM": {
"name": "Cornilescu Bible (Romanian, 1921)",
"lang": "Romanian",
"tradition": "Romanian Orthodox / Protestant",
"canon": "protestant",
"file": "rom.json",
},
"LXX": {
"name": "Brenton Septuagint in English (LXX, 1851)",
"lang": "English",
"tradition": "Eastern Orthodox Old Testament",
"canon": "orthodox",
"file": "lxx.json",
},
"CHURCH_SLAVONIC": {
"name": "Church Slavonic Bible (1900)",
"lang": "Church Slavonic",
"tradition": "Serbian / Bulgarian / Macedonian Orthodox",
"canon": "orthodox",
"file": "church_slavonic.json",
},
"GREEK_LXX": {
"name": "Septuagint in Greek (LXX)",
"lang": "Greek",
"tradition": "Eastern Orthodox (Greek)",
"canon": "orthodox",
"file": "greek_lxx.json",
},
"VULGATE": {
"name": "Clementine Vulgate (Latin)",
"lang": "Latin",
"tradition": "Roman Catholic / Orthodox",
"canon": "catholic",
"file": "vulgate.json",
},
"GERMAN": {
"name": "Luther Bible (German, 1912)",
"lang": "German",
"tradition": "Lutheran / Protestant",
"canon": "protestant",
"file": "german.json",
},
"FRENCH": {
"name": "Segond Bible (French, 1910)",
"lang": "French",
"tradition": "Protestant",
"canon": "protestant",
"file": "french.json",
},
"SPANISH": {
"name": "Reina-Valera (Spanish, 1909)",
"lang": "Spanish",
"tradition": "Protestant / Catholic",
"canon": "protestant",
"file": "spanish.json",
},
}
DENOMINATION_GROUPS = [
("English", [
("King James Version (KJV)", "KJV"),
("World English Bible (WEB)", "WEB"),
("American Standard (ASV, 1901)", "ASV"),
("Douay-Rheims (Roman Catholic)", "DOUAY"),
]),
("Orthodox", [
("Synodal - Russian / Serbian / Bulgarian / Georgian", "RUS_SYNODAL"),
("Church Slavonic (1900)", "CHURCH_SLAVONIC"),
("Brenton Septuagint in English (LXX)", "LXX"),
("Septuagint in Greek (LXX)", "GREEK_LXX"),
("Ukrainian - Ogienko (1962)", "UKR"),
("Romanian - Cornilescu (1921)", "ROM"),
]),
("Latin", [
("Clementine Vulgate", "VULGATE"),
]),
("Other languages", [
("Luther Bible (German)", "GERMAN"),
("Segond Bible (French)", "FRENCH"),
("Reina-Valera (Spanish)", "SPANISH"),
]),
]
DENOMINATIONS = [
("KJV - King James Version", "KJV"),
("WEB - World English Bible", "WEB"),
("ASV - American Standard (1901)", "ASV"),
("Douay-Rheims (Roman Catholic)", "DOUAY"),
("Synodal - Russian / Serbian / Bulgarian Orthodox","RUS_SYNODAL"),
("Church Slavonic (1900)", "CHURCH_SLAVONIC"),
("LXX - Brenton Septuagint (English)", "LXX"),
("Greek Septuagint (LXX, Greek)", "GREEK_LXX"),
("Ukrainian - Ogienko (1962)", "UKR"),
("Romanian - Cornilescu (1921)", "ROM"),
("Clementine Vulgate (Latin)", "VULGATE"),
("Luther Bible (German)", "GERMAN"),
("Segond Bible (French)", "FRENCH"),
("Reina-Valera (Spanish)", "SPANISH"),
]
# CONFIGURATION
DEFAULT_CONFIG = {
"translation": "KJV",
"verse_numbers": "true",
"wrap_width": "0", # 0 = auto (terminal width)
"theme": "default",
"setup_done": "false",
"last_book": "",
"last_chapter": "",
"last_scroll": "",
}
def load_config() -> dict:
cfg = configparser.ConfigParser()
if CONFIG_FILE.exists():
cfg.read(CONFIG_FILE)
result = dict(DEFAULT_CONFIG)
if "logos" in cfg:
result.update(dict(cfg["logos"]))
return result
def save_config(conf: dict):
cfg = configparser.ConfigParser()
cfg["logos"] = conf
with open(CONFIG_FILE, "w") as f:
cfg.write(f)
# BOOKMARKS — stored as JSON in data dir
BOOKMARKS_FILE = DATA_DIR / "bookmarks.json"
def load_bookmarks() -> list:
"""Returns list of {book, chapter, verse, label} dicts."""
if BOOKMARKS_FILE.exists():
try:
with open(BOOKMARKS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
except Exception:
pass
return []
def save_bookmarks(bmarks: list):
with open(BOOKMARKS_FILE, "w", encoding="utf-8") as f:
json.dump(bmarks, f, ensure_ascii=False, indent=2)
def add_bookmark(book: str, chapter: int, verse: Optional[int], label: str):
bmarks = load_bookmarks()
# Avoid exact duplicate
for b in bmarks:
if b["book"] == book and b["chapter"] == chapter and b.get("verse") == verse:
return
bmarks.insert(0, {"book": book, "chapter": chapter, "verse": verse, "label": label})
bmarks = bmarks[:50] # cap at 50
save_bookmarks(bmarks)
# DATA LOADING
# We use the Scrollmapper/bible-json public domain dataset format.
# Data files live alongside this script or in DATA_DIR.
_cache: dict = {}
def get_data_paths(filename: str) -> list[Path]:
"""Search order: script dir, data dir, current dir."""
script_dir = Path(__file__).parent
return [
script_dir / "data" / filename,
DATA_DIR / filename,
Path.cwd() / "data" / filename,
]
def load_translation(translation_key: str) -> Optional[dict]:
"""Load a translation JSON. Returns None if not found."""
if translation_key in _cache:
return _cache[translation_key]
info = TRANSLATIONS.get(translation_key)
if not info:
return None
for path in get_data_paths(info["file"]):
if path.exists():
with open(path, "r", encoding="utf-8") as f:
data = json.load(f)
_cache[translation_key] = data
return data
return None
def get_verse(translation_key: str, book: str, chapter: int, verse: int) -> Optional[str]:
data = load_translation(translation_key)
if not data:
return None
try:
return data[book][str(chapter)][str(verse)]
except (KeyError, TypeError):
return None
def get_chapter(translation_key: str, book: str, chapter: int) -> Optional[dict]:
data = load_translation(translation_key)
if not data:
return None
try:
return data[book][str(chapter)]
except (KeyError, TypeError):
return None
def get_passage(translation_key: str, book: str, chapter: int,
verse_start: int, verse_end: Optional[int] = None) -> list[tuple[int, str]]:
ch = get_chapter(translation_key, book, chapter)
if not ch:
return []
results = []
v = verse_start
max_v = max(int(k) for k in ch.keys()) if ch else 0
end = verse_end if verse_end else max_v
while v <= end:
text = ch.get(str(v))
if text:
results.append((v, text))
v += 1
return results
def get_book_chapters(translation_key: str, book: str) -> int:
data = load_translation(translation_key)
if not data or book not in data:
return 0
return len(data[book])
def get_chapter_verses(translation_key: str, book: str, chapter: int) -> int:
ch = get_chapter(translation_key, book, chapter)
return len(ch) if ch else 0
def available_books(translation_key: str) -> list[str]:
data = load_translation(translation_key)
if not data:
return []
canon = TRANSLATIONS[translation_key]["canon"]
if canon == "catholic":
order = CATHOLIC_CANON
elif canon == "orthodox":
order = ORTHODOX_CANON
else:
order = PROTESTANT_CANON
return [b for b in order if b in data]
# REFERENCE PARSING
# Accepts: "John 3:16", "Jn 3:16", "john 3:16-18", "Gen 1"
def parse_reference(ref: str) -> Optional[tuple]:
"""
Returns (book_abbrev, chapter, verse_start, verse_end) or None.
verse_start/verse_end are None if not specified.
"""
import re
ref = ref.strip()
# Match: Book [chapter[:verse[-verse_end]]]
pat = re.compile(
r'^([1-4]?\s*[A-Za-z]+(?:\s+[A-Za-z]+)?)' # book (with optional num prefix)
r'(?:\s+(\d+)' # chapter
r'(?::(\d+)' # :verse_start
r'(?:-(\d+))?)?)?$' # -verse_end
)
m = pat.match(ref)
if not m:
return None
book_raw, chap, vs, ve = m.groups()
# Normalize book
key = book_raw.strip().lower().replace(" ", "").replace(".", "")
abbrev = BOOK_ALIASES.get(key)
if not abbrev:
# Try fuzzy: first 3 chars
for alias, ab in BOOK_ALIASES.items():
if alias.startswith(key[:3]) or key.startswith(alias[:3]):
abbrev = ab
break
if not abbrev:
return None
chapter = int(chap) if chap else None
verse_start = int(vs) if vs else None
verse_end = int(ve) if ve else None
return (abbrev, chapter, verse_start, verse_end)
# COPY / SAVE UTILITIES (no external tools required)
def copy_to_clipboard(text: str) -> bool:
"""Try platform clipboard. Returns True on success."""
os_name = get_os()
try:
if os_name == "linux":
for cmd in [["xclip", "-selection", "clipboard"],
["xsel", "--clipboard", "--input"],
["wl-copy"]]:
try:
proc = subprocess.run(cmd, input=text.encode(),
capture_output=True, timeout=3)
if proc.returncode == 0:
return True
except (FileNotFoundError, subprocess.TimeoutExpired):
continue
elif os_name in ("freebsd", "openbsd", "netbsd"):
# xclip/xsel work on BSD under X11; xdotool also common
for cmd in [["xclip", "-selection", "clipboard"],
["xsel", "--clipboard", "--input"]]:
try:
proc = subprocess.run(cmd, input=text.encode(),
capture_output=True, timeout=3)
if proc.returncode == 0:
return True
except (FileNotFoundError, subprocess.TimeoutExpired):
continue
elif os_name == "macos":
proc = subprocess.run(["pbcopy"], input=text.encode(),
capture_output=True, timeout=3)
return proc.returncode == 0
elif os_name == "windows":
proc = subprocess.run(["clip"], input=text.encode("utf-16-le"),
capture_output=True, timeout=3)
return proc.returncode == 0
except Exception:
pass
return False
def save_passage_to_file(text: str, ref: str, out_dir: Optional[Path] = None) -> str:
"""Save text to out_dir (defaults to platform save dir) with a descriptive filename."""
if out_dir is None:
out_dir = get_default_save_dir()
try:
out_dir.mkdir(parents=True, exist_ok=True)
except OSError as e:
return f"[error creating dir: {e}]"
safe_ref = ref.replace(" ", "_").replace(":", "-").replace("/", "-")
filename = out_dir / f"{safe_ref}.txt"
i = 1
while filename.exists():
filename = out_dir / f"{safe_ref}_{i}.txt"
i += 1
try:
with open(filename, "w", encoding="utf-8") as f:
f.write(text)
return str(filename)
except OSError as e:
return f"[error writing file: {e}]"
def run_save_dir_input(stdscr, default_dir: Path) -> Optional[Path]:
"""Show a small dialog to let the user choose a save directory.
Returns a Path, or None to cancel (keep default)."""
curses.curs_set(1)
h, w = stdscr.getmaxyx()
tc = TermCompat
box_w = min(60, w - 6)
box_h = 6
box_y = h // 2 - box_h // 2
box_x = w // 2 - box_w // 2
input_str = str(default_dir)
error = ""
while True:
bg = curses.color_pair(3)
for i in range(box_h):
tc.safe_addstr(stdscr, box_y + i, box_x, " " * box_w, bg)
tc.safe_addstr(stdscr, box_y, box_x + 2, "Save to directory:", bg | curses.A_BOLD)
tc.safe_addstr(stdscr, box_y + 1, box_x + 2, "-" * (box_w - 4), bg)
# Show last (box_w-4) chars of path so it doesn't overflow
display = input_str[-(box_w - 5):] if len(input_str) > box_w - 5 else input_str
tc.safe_addstr(stdscr, box_y + 2, box_x + 2, display + "_", bg | curses.A_BOLD)
if error:
tc.safe_addstr(stdscr, box_y + 3, box_x + 2, error[:box_w - 4], bg)
else:
tc.safe_addstr(stdscr, box_y + 3, box_x + 2,
"Enter confirm Esc keep default Ctrl+U clear", bg)
tc.safe_addstr(stdscr, box_y + 4, box_x + 2,
"Tab = autocomplete first match", bg)
stdscr.refresh()
key = stdscr.getch()
if key in (curses.KEY_ENTER, ord('\n'), ord('\r'), 10, 13):
p = Path(os.path.expanduser(input_str.strip()))
curses.curs_set(0)
return p
elif key == 27:
curses.curs_set(0)
return None
elif key in (curses.KEY_BACKSPACE, 127, 8):
input_str = input_str[:-1]
error = ""
elif key == 21: # Ctrl+U — clear line
input_str = ""
error = ""
elif key == ord('\t'): # Tab — basic path autocomplete
partial = os.path.expanduser(input_str)
parent = os.path.dirname(partial) or "/"
base = os.path.basename(partial)
try:
matches = sorted([
os.path.join(parent, e)
for e in os.listdir(parent)
if e.startswith(base) and os.path.isdir(os.path.join(parent, e))
])
if matches:
input_str = matches[0]
error = ""
except OSError:
pass
elif 32 <= key <= 126:
input_str += chr(key)
error = ""
# TERMINAL COMPATIBILITY LAYER
# Handles differences between Linux/macOS/Windows terminals gracefully.
class TermCompat:
"""Safe wrappers around curses for cross-platform use."""
@staticmethod
def init_colors():
try:
curses.start_color()
curses.use_default_colors()
# Pair 1: header/title (white on dark blue or bold)
# Pair 2: verse numbers (dim/yellow)
# Pair 3: selected text (reverse)
# Pair 4: status bar (reverse)
# Pair 5: dim/comment (dim)
# Pair 6: highlight (bold)
if curses.can_change_color() and curses.COLORS >= 8:
curses.init_pair(1, curses.COLOR_CYAN, -1)
curses.init_pair(2, curses.COLOR_YELLOW, -1)
curses.init_pair(3, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.init_pair(4, curses.COLOR_BLACK, curses.COLOR_WHITE)
curses.init_pair(5, curses.COLOR_WHITE, -1)
curses.init_pair(6, curses.COLOR_WHITE, -1)
else:
for i in range(1, 7):
curses.init_pair(i, -1, -1)
except Exception:
pass
@staticmethod
def safe_addstr(win, y: int, x: int, text: str, attr: int = 0):
try:
h, w = win.getmaxyx()
if y < 0 or y >= h or x < 0:
return
available = w - x - 1
if available <= 0:
return
win.addstr(y, x, text[:available], attr)
except curses.error:
pass
@staticmethod
def safe_addch(win, y: int, x: int, ch: str, attr: int = 0):
try:
h, w = win.getmaxyx()
if 0 <= y < h and 0 <= x < w - 1:
win.addch(y, x, ch, attr)
except curses.error:
pass
@staticmethod
def hline(win, y: int, x: int, width: int, attr: int = 0):
try:
h, w = win.getmaxyx()
actual = min(width, w - x - 1)
if actual > 0 and 0 <= y < h:
win.addstr(y, x, "-" * actual, attr)
except curses.error:
try:
win.hline(y, x, curses.ACS_HLINE, min(width, win.getmaxyx()[1] - x - 1))
except curses.error:
pass
# SETUP WIZARD
def run_setup(stdscr, conf: dict) -> dict:
"""First-run setup wizard. Returns updated config."""
curses.curs_set(0)
h, w = stdscr.getmaxyx()
tc = TermCompat
stdscr.clear()
tc.safe_addstr(stdscr, 0, 0, " " * (w - 1), curses.color_pair(4))
tc.safe_addstr(stdscr, 0, 2, "logos - first run setup", curses.color_pair(4))
tc.hline(stdscr, 1, 0, w - 1)
tc.safe_addstr(stdscr, 3, 2, "Welcome. Choose your preferred translation.", 0)
tc.safe_addstr(stdscr, 4, 2, "Translations marked [run logos-fetch-data] need to be", curses.color_pair(5))
tc.safe_addstr(stdscr, 5, 2, "downloaded first. Press any key to continue.", curses.color_pair(5))
stdscr.refresh()
stdscr.getch()
conf = run_translation_picker(stdscr, conf)
if not conf.get("translation"):
conf["translation"] = "KJV"
conf["setup_done"] = "true"
save_config(conf)
return conf
# TRANSLATION SWITCHER
def run_translation_picker(stdscr, conf: dict) -> dict:
curses.curs_set(0)
h, w = stdscr.getmaxyx()
tc = TermCompat
current = conf.get("translation", "KJV")
# Build a flat selectable list, checking which files are present
# Items are (label, key_or_None) - None key means group header
def data_present(key):
info = TRANSLATIONS.get(key, {})
fname = info.get("file", "")
return any(p.exists() for p in get_data_paths(fname))
items = [] # (display_label, translation_key or None, is_header)
for group_name, entries in DENOMINATION_GROUPS:
items.append((group_name, None, True))
seen = set()
for label, key in entries:
if key in seen:
continue
seen.add(key)
present = data_present(key)
status = "" if present else " [run logos-fetch-data]"
items.append((label + status, key, False))
# Build selectable indices (non-headers only)
selectable = [i for i, (_, k, hdr) in enumerate(items) if not hdr]
# Start selection at current translation
cur_idx = next((selectable.index(i) for i, (_, k, hdr) in enumerate(items)
if k == current), 0)
sel = cur_idx # index into selectable list
scroll = 0
list_h = h - 5
while True:
stdscr.clear()
tc.safe_addstr(stdscr, 0, 0, " " * (w - 1), curses.color_pair(4))
tc.safe_addstr(stdscr, 0, 2, "Select Translation", curses.color_pair(4))
tc.hline(stdscr, 1, 0, w - 1)
for row in range(list_h):
li = scroll + row
if li >= len(items):
break
label, key, is_hdr = items[li]
y = 2 + row
if is_hdr:
tc.safe_addstr(stdscr, y, 2, label, curses.color_pair(1) | curses.A_BOLD)
else:
item_sel_idx = selectable.index(li) if li in selectable else -1
is_sel = (item_sel_idx == sel)
is_cur = (key == current)
prefix = " > " if is_sel else " "
attr = curses.A_BOLD if is_sel else (curses.color_pair(5) if not data_present(key) else 0)
suffix = " [active]" if is_cur else ""
tc.safe_addstr(stdscr, y, 2, prefix + label + suffix, attr)
tc.hline(stdscr, h - 2, 0, w - 1)
tc.safe_addstr(stdscr, h - 1, 2,
"j/k or arrows Enter select Esc cancel", curses.color_pair(5))
stdscr.refresh()
key_press = stdscr.getch()
if key_press in (curses.KEY_UP, ord('k')) and sel > 0:
sel -= 1
# Scroll up if needed
item_li = selectable[sel]
if item_li < scroll:
scroll = max(0, item_li)
elif key_press in (curses.KEY_DOWN, ord('j')) and sel < len(selectable) - 1:
sel += 1
item_li = selectable[sel]
if item_li >= scroll + list_h:
scroll = item_li - list_h + 1
elif key_press in (curses.KEY_ENTER, ord('\n'), ord('\r'), 10, 13):
chosen_li = selectable[sel]
chosen_key = items[chosen_li][1]
if chosen_key and data_present(chosen_key):
conf["translation"] = chosen_key
save_config(conf)
elif chosen_key:
# Show "not downloaded" briefly
tc.safe_addstr(stdscr, h - 1, 2,
"Not downloaded. Run: python logos-fetch-data.py " + chosen_key + " ",
curses.color_pair(5))
stdscr.refresh()
stdscr.getch()
continue
break
elif key_press in (27, ord('q')):
break
return conf
# BOOK BROWSER
def run_book_picker(stdscr, translation_key: str) -> Optional[str]:
"""Let user pick a book. Returns book abbrev or None."""
curses.curs_set(0)
h, w = stdscr.getmaxyx()
tc = TermCompat
books = available_books(translation_key)
if not books:
return None
sel = 0
scroll = 0
list_h = h - 6
search_str = ""
filtered = books[:]
def refilter():
nonlocal filtered, sel, scroll
if search_str:
q = search_str.lower()
filtered = [b for b in books if
q in BOOK_NAMES.get(b, b).lower() or
q in b.lower()]
else:
filtered = books[:]
sel = 0
scroll = 0
while True:
stdscr.clear()
tc.safe_addstr(stdscr, 0, 0, " " * (w - 1), curses.color_pair(4))
tc.safe_addstr(stdscr, 0, 2, f"Books: {TRANSLATIONS[translation_key]['name']}", curses.color_pair(4))
tc.hline(stdscr, 1, 0, w - 1)
# Search bar
tc.safe_addstr(stdscr, 2, 2, f"Search: {search_str}_", curses.color_pair(6) | curses.A_BOLD)
tc.hline(stdscr, 3, 0, w - 1)
# Book list
for row, i in enumerate(range(scroll, min(scroll + list_h, len(filtered)))):
b = filtered[i]
name = BOOK_NAMES.get(b, b)
y = 4 + row
prefix = " ▶ " if i == sel else " "
attr = curses.A_BOLD if i == sel else 0
tc.safe_addstr(stdscr, y, 2, f"{prefix}{name}", attr)
# Footer
tc.hline(stdscr, h - 2, 0, w - 1)
tc.safe_addstr(stdscr, h - 1, 2,
"↑/↓ move Enter select type to search Esc back",
curses.color_pair(5))
stdscr.refresh()
key = stdscr.getch()
if key in (curses.KEY_UP, ord('k')) and sel > 0:
sel -= 1
if sel < scroll:
scroll = sel
elif key in (curses.KEY_DOWN, ord('j')) and sel < len(filtered) - 1:
sel += 1
if sel >= scroll + list_h:
scroll = sel - list_h + 1
elif key in (curses.KEY_ENTER, ord('\n'), ord('\r'), 10, 13):
if filtered:
return filtered[sel]
elif key == 27: # Esc
return None
elif key in (curses.KEY_BACKSPACE, 127, 8):
if search_str:
search_str = search_str[:-1]
refilter()
elif 32 <= key <= 126:
search_str += chr(key)
refilter()
# CHAPTER PICKER
def run_chapter_picker(stdscr, translation_key: str, book: str) -> Optional[int]:
curses.curs_set(0)
h, w = stdscr.getmaxyx()
tc = TermCompat
total = get_book_chapters(translation_key, book)
if total == 0:
return None
book_name = BOOK_NAMES.get(book, book)
# Arrange chapters in columns
cols = max(1, (w - 6) // 5)
sel = 0
while True:
stdscr.clear()
tc.safe_addstr(stdscr, 0, 0, " " * (w - 1), curses.color_pair(4))
tc.safe_addstr(stdscr, 0, 2, f"{book_name}: Select Chapter", curses.color_pair(4))
tc.hline(stdscr, 1, 0, w - 1)
for i in range(total):
col = i % cols
row = i // cols
y = 3 + row
x = 3 + col * 5
if y < h - 3:
attr = curses.A_BOLD | curses.A_REVERSE if i == sel else 0
tc.safe_addstr(stdscr, y, x, f"{i + 1:3d} ", attr)
tc.hline(stdscr, h - 2, 0, w - 1)
tc.safe_addstr(stdscr, h - 1, 2,
"←/→/↑/↓ navigate Enter select Esc back",
curses.color_pair(5))
stdscr.refresh()
key = stdscr.getch()
if key in (curses.KEY_RIGHT, ord('l')):
if sel < total - 1:
sel += 1
elif key in (curses.KEY_LEFT, ord('h')):
if sel > 0: