generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.ts
3295 lines (2945 loc) · 86.8 KB
/
main.ts
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
import {
App,
Modal,
Notice,
Plugin,
PluginSettingTab,
Setting,
FuzzySuggestModal,
TFile,
normalizePath,
requestUrl,
MarkdownRenderer,
} from 'obsidian'
import { E_CANCELED, Mutex } from 'async-mutex'
import { randomInt } from 'crypto'
import { BBCodeTag, legacy, parse_mybible } from 'mybible_parser'
import { mb } from 'api'
const BUILD_END_TOAST = "Bible build finished!";
const SELECTED_TRANSLATION_OPTION = "<Selected reading translation, {0}>"
const SELECTED_TRANSLATION_OPTION_KEY = "default"
// Remember to rename these classes and interfaces!
class Version {
major:number = 1
minor:number = 0
patch:number = 0
constructor(ma:number, mi:number, pa:number) {
this.major = ma
this.minor = mi
this.patch = pa
}
static fromString(version:string):Version {
let parts = version.split(".")
return new Version(
Number(parts[0]),
Number(parts[1]),
Number(parts[2]),
)
}
}
class MyBibleSettings {
translation: string
reading_translation: string
bible_folder: string
store_locally: boolean
padded_order: boolean
book_folders_enabled: boolean
book_name_format: string
book_name_delimiter: string
book_name_capitalization: string
book_name_abbreviated: boolean
padded_chapter: boolean
book_ordering: string
chapter_name_format: string
chapter_body_format: string
build_with_dynamic_verses: boolean
verse_body_format: string
index_enabled: boolean
index_name_format: string
index_format: string
index_link_format: string
chapter_index_enabled: boolean
chapter_index_name_format: string
chapter_index_format: string
chapter_index_link_format: string
enable_javascript_execution:boolean
_built_translation: string;
_last_opened_version: Version|undefined
_plugin:MyBible
constructor() {}
async set_translation(val: string) {
if (val === SELECTED_TRANSLATION_OPTION_KEY) {
this.translation = val
return
}
let has_translation = false;
let translations = (await this._plugin.bible_api.get_translations());
if (!(val in translations)) {
this.translation = await this._plugin.bible_api.get_default_translation();
} else {
this.translation = val;
}
}
async setLastOpenedVersion(version:Version) {
this._last_opened_version = version
this._plugin.saveSettings()
}
}
const DEFAULT_SETTINGS: MyBibleSettings = {
translation: SELECTED_TRANSLATION_OPTION_KEY,
reading_translation: "WEB",
bible_folder: "/My Bible/",
book_folders_enabled: true,
book_name_format: "{order} {book}",
book_name_delimiter: " ",
chapter_name_format: "{book} {chapter}",
book_name_capitalization: "name_case",
book_name_abbreviated: false,
padded_order: true,
padded_chapter: false,
book_ordering: "christian",
build_with_dynamic_verses: true,
verse_body_format: "###### {verse}\n"
+ "{verse_text}"
,
chapter_body_format: "\n"
+ "##### "
+ "**[[{last_chapter_name}|⏪ {last_chapter_name}]] | [[{chapter_index}|Chapters]] | [[{next_chapter_name}|{next_chapter_name} ⏩]]**<br>"
+ "**[[{first_chapter_name}|First ({first_chapter})]] | [[{final_chapter_name}|Last ({final_chapter})]]**<br><br>\n"
+ "\n"
+ "{verses}\n"
+ "\n"
+ "##### "
+ "**[[{last_chapter_name}|⏪ {last_chapter_name}]] | [[{chapter_index}|Chapters]] | [[{next_chapter_name}|{next_chapter_name} ⏩]]**<br>"
+ "**[[{first_chapter_name}|First ({first_chapter})]] | [[{final_chapter_name}|Last ({final_chapter})]]**\n"
,
index_enabled: true,
index_name_format: "-- Bible --",
index_link_format: "- [[{chapter_index}|{book}]]",
index_format: ""
+ "### Old testament\n"
+ "{old_testament}\n"
+ "### New testament\n"
+ "{new_testament}\n"
+ "### Apocrypha\n"
+ "{apocrypha}"
,
chapter_index_enabled: true,
chapter_index_name_format: "-- {book} --",
chapter_index_link_format: "- [[{chapter_name}|{chapter}]]",
chapter_index_format: ""
+ "##### *[[{index}|Books]]*\n"
+ "\n"
+ "### Chapters\n"
+ "{chapters}\n"
,
store_locally: false,
enable_javascript_execution: false,
_built_translation: "",
_last_opened_version: undefined,
} as MyBibleSettings
export function getPlugin():MyBible {
return MyBible.plugin
}
export function httpGet(theUrl: string): Promise<string> {
try {
return new Promise(async (ok, err) => {
ok(await requestUrl(theUrl).text);
});
} catch (e) {
let err = new Error(e.message)
err.name = "NetworkError:"
err.stack = e.stack
throw err
}
}
export function is_alpha(string: string): boolean {
for (let char_str of string) {
let char = char_str.charCodeAt(0);
if ((char > 64 && char < 91) || (char > 96 && char < 123) || (char > 39 && char < 42)) {
// Character is a capital or lowercase letter, continue
continue;
}
// Character is not a capital or lowercase letter, return false
return false;
}
// All characters were uppercase or lowercase letters, return true
return true;
}
export function is_alphanumeric(string: string): boolean {
for (let char_str of string) {
let char = char_str.charCodeAt(0);
if ((char > 64 && char < 91) || (char > 96 && char < 123) || (char > 47 && char < 58)) {
// Character is a capital or lowercase letter, continue
continue;
}
// Character is not a capital or lowercase letter, return false
return false;
}
// All characters were uppercase or lowercase letters, return true
return true;
}
export function is_numeric(string: string): boolean {
for (let char_str of string) {
let char = char_str.charCodeAt(0);
if (char > 47 && char < 58) {
// Character is a number, continue
continue;
}
// Character is not number, return false
return false;
}
// All characters were numbers, return true
return true;
}
export async function save_file(path: string, content: string) {
let file_path = normalizePath(path);
let file = this.app.vault.getAbstractFileByPath(file_path)
if (file instanceof TFile) {
await this.app.vault.modify(file, content)
} else if (file === null) {
await this.app.vault.create(
file_path,
content,
)
}
}
export function translation_to_display_name(translation:Translation):string {
if (translation.language === "") {
return translation.display_name
}
return "{0} - {1} - {2}"
.format(translation.language, translation.abbreviated_name, translation.display_name)
;
}
export function cyrb128(str:string): number {
let h1 = 1779033703, h2 = 3144134277,
h3 = 1013904242, h4 = 2773480762;
for (let i = 0, k; i < str.length; i++) {
k = str.charCodeAt(i);
h1 = h2 ^ Math.imul(h1 ^ k, 597399067);
h2 = h3 ^ Math.imul(h2 ^ k, 2869860233);
h3 = h4 ^ Math.imul(h3 ^ k, 951274213);
h4 = h1 ^ Math.imul(h4 ^ k, 2716044179);
}
h1 = Math.imul(h3 ^ (h1 >>> 18), 597399067);
h2 = Math.imul(h4 ^ (h2 >>> 22), 2869860233);
h3 = Math.imul(h1 ^ (h3 >>> 17), 951274213);
h4 = Math.imul(h2 ^ (h4 >>> 19), 2716044179);
h1 ^= (h2 ^ h3 ^ h4), h2 ^= h1, h3 ^= h1, h4 ^= h1;
return h1 >>> 0
}
export function wait(seconds:number):Promise<void> {
return new Promise(function(resolve) {
setTimeout(resolve, seconds);
});
}
export default class MyBible extends Plugin {
bible_api: BibleAPI
settings: MyBibleSettings
progress_notice: Notice | null
legacyParser: legacy.VerseParser
depricationTimer: Promise<void>|undefined = undefined
static plugin:MyBible
async onload() {
MyBible.plugin = this
// @ts-ignore
globalThis["mb"] = mb
this.legacyParser = new legacy.VerseParser()
this.bible_api = new BollsLifeBibleAPI();
this.bible_api.plugin = this;
await this.loadSettings()
this.settings._plugin = this
this.settings.setLastOpenedVersion(
Version.fromString(this.manifest.version)
)
await this.settings.set_translation(this.settings.translation)
// This adds a simple command that can be triggered anywhere
this.addCommand({
id: 'create_bible_files',
name: 'Build Bible',
callback: async () => {
new BuilderModal(this.app, this).open()
}
});
this.addCommand({
id: 'quick_change_translation',
name: 'Change translation',
callback: async () => {
let modal = new QuickChangeTranslationeModal(this)
modal.translations = await this.bible_api.get_translations()
modal.onChose = async translation => {
this.settings.reading_translation = translation.abbreviated_name
await getPlugin().saveSettings()
}
modal.open()
}
});
this.addCommand({
id: 'clear_cache',
name: 'Clear local files',
callback: async () => {
new ClearLocalFilesModal(this.app, this).open();
}
});
this.addCommand({
id: 'download_bible',
name: 'Download translation',
callback: async () => {
let modal = new QuickChangeTranslationeModal(this)
modal.translations = await this.bible_api.get_translations()
modal.onChose = async translation => {
await this.bible_api.user_download_translation(
translation.abbreviated_name
)
}
modal.open()
}
});
this.registerMarkdownCodeBlockProcessor("verse", async (source, el, ctx) =>{
const DEPRICATE_VERSE_BLOCK = false
if (DEPRICATE_VERSE_BLOCK && this.depricationTimer === undefined) {
MarkdownRenderer.render(
this.app,
"> [!WARNING] `verse` codeblocks are depricated\n"
+ "> Rebuilding your Bible should resolve this issue. If you created this block yourself then use the `mybible` codeblock instead. For more information visit [the wiki]({0})."
.format("https://gslogimaker.github.io/my-bible-obsidian-plugin/documents/Code_Blocks.html#md:verse-1"),
el,
"",
this,
)
this.depricationTimer = (async () => {
await wait(3)
this.depricationTimer = undefined
return
})()
}
await this.legacyParser.parse(source, el)
});
this.registerMarkdownCodeBlockProcessor("mybible", async (source, el, ctx) => {
let code_context = {
file: this.app.vault.getAbstractFileByPath(ctx.sourcePath)
}
let parsed = parse_mybible(source)
if (parsed instanceof Error) {
MarkdownRenderer.render(
this.app,
"> [!ERROR] {0}\n> ```\n> {1}\n> ```".format(
parsed.name,
parsed.message
.replace(/\n/g, "\n> ")
.replace(/```/g, "")
),
el,
"",
this,
)
return
}
let text = ""
for (const X of parsed) {
if (X instanceof BBCodeTag) {
text += await X.toText(code_context)
} else {
text += X
}
}
MarkdownRenderer.render(this.app, text, el, "", this)
});
this.addSettingTab(new SettingsTab(this.app, this));
}
onunload() {
}
async build_bible() {
let bible_path = normalizePath(this.settings.bible_folder);
let bible_folder = this.app.vault.getAbstractFileByPath(bible_path);
if (bible_folder instanceof TFile) {
// Can't handle if bible path is a file. Abort
new ErrorModal(
this.app,
this,
"Failed to build bible",
"The bible folder defined in settings, \"{0}\", was expected to point to a folder, but it points to a file. Try changing the path to point to a folder, or change the file to a folder."
.format(this.settings.bible_folder),
).open();
return;
} else if (bible_folder === null) {
// Bible path doesn't exist. Create it
this.app.vault.adapter.mkdir(bible_path);
} else {
// Bible path is already a valid folder. No action needed
}
let folders_and_files = await this.app.vault.adapter.list(bible_path);
if (folders_and_files.files.length + folders_and_files.folders.length != 0) {
new ClearOldBibleFilesModal(this.app, this).open()
} else {
await this._build_bible(bible_path);
}
}
async _build_bible(bible_path: string) {
this.show_toast_progress(0, null)
try {
let translation = ""
if (this.settings.translation == SELECTED_TRANSLATION_OPTION_KEY) {
translation = this.settings.reading_translation
} else {
translation = this.settings.translation
}
// TODO: Build bibles according to translation in settings
this.settings._built_translation = translation;
await this.saveSettings();
let ctx = new BuildContext
ctx.plugin = this
ctx.translation = translation
ctx.set_books(await this.bible_api.get_books_data(ctx.translation))
ctx.verse_counts = await this.bible_api.get_verse_count(ctx.translation)
// Get translation texts
ctx.translation_texts = await this.bible_api
.get_translation(ctx.translation);
// Remove empty chapters from books (HACK: This should be done in a better place, but this is where all the needed information is)
if (ctx.translation_texts !== undefined) {
for (const BOOK_ID of Object.keys(ctx.books) as unknown as number[]) {
let book = ctx.books[BOOK_ID]
let to_remove = []
for (let i = 1; i != book.chapters.length+1; i++) {
let chapter_texts = ctx.translation_texts.books[book.id]
let verses = chapter_texts[i] || {}
if (Object.keys(verses).length === 0) {
to_remove.push(i)
}
}
for (const i of to_remove.reverse()) {
book.chapters.remove(i)
}
}
}
// Notify progress
let built_chapter_count = 0
let total_chapter_count = 0
for (const i in ctx.books) {
total_chapter_count += ctx.books[i].chapters.length
}
this.show_toast_progress(0, total_chapter_count)
// Index
if (this.settings.index_enabled) {
await save_file(
"{0}/{1}.md".format(bible_path, ctx.format_index_name()),
ctx.format_index(),
)
}
let file_promises: Array<Promise<any>> = [];
for (const BOOK_ID of Object.keys(ctx.books) as unknown as number[]) {
let book = ctx.books[BOOK_ID]
ctx.set_book_and_chapter(book, book.chapters[0])
let texts_of_book = ctx.translation_texts.books[book.id]
// Book path
let book_path = bible_path
if (this.settings.book_folders_enabled) {
book_path += "/" + ctx.format_book_name(ctx.book);
this.app.vault.adapter.mkdir(normalizePath(book_path));
}
// Chapter index
if (this.settings.chapter_index_enabled) {
file_promises.push(save_file(
"{0}/{1}.md".format(book_path, ctx.format_chapter_index_name(ctx.book)),
ctx.format_chapter_index(ctx.book),
))
}
for (const chapter of ctx.book.chapters) {
file_promises.push(new Promise(async () => {
ctx.set_chapter(chapter);
let texts_of_chapter = texts_of_book[chapter]
// Assemble verses
ctx.verses_text = ""
let added_verse_count = 0
for (const verse_key of Object.keys(texts_of_chapter)) {
const verse = Number(verse_key)
while (added_verse_count < verse) {
ctx.verse = added_verse_count + 1
let text = ctx.format_verse_body()
if (text.length === 0) {
added_verse_count += 1
continue
}
ctx.verses_text += text
if (
!(text.length === 0 && !this.settings.build_with_dynamic_verses)
&& verse_key !== Object.keys(texts_of_chapter).last())
{
ctx.verses_text += "\n";
}
added_verse_count += 1
}
}
// Chapter name
let chapter_note_name = ctx.format_chapter_name();
// Chapter body
let note_body = ctx.format_chapter_body();
// Save file
let file_path = book_path + "/" + chapter_note_name + ".md"
await save_file(file_path, note_body)
built_chapter_count += 1
this.show_toast_progress(
built_chapter_count,
total_chapter_count,
)
}))
}
}
await Promise.all(file_promises);
} catch (e) {
this.show_toast_error(String(e))
throw e
}
}
show_toast_error(error:string) {
if (this.progress_notice !== null) {
this.progress_notice?.hide()
this.progress_notice = null
}
new Notice("Error building bible: " + error, 0)
}
show_toast_progress(progress: number, finish: number|null) {
if (progress === finish && finish != null) {
this.progress_notice?.hide()
this.progress_notice = null
new Notice(BUILD_END_TOAST)
return
}
if (this.progress_notice == null) {
this.progress_notice = new Notice("", 0)
}
let msg = ""
if (finish == null) {
msg = "Building bible..."
} else {
msg = "Building bible... ({0}/{1})"
.format(String(progress), String(finish))
}
this.progress_notice.setMessage(msg)
}
async loadSettings() {
this.settings = Object.assign(
new MyBibleSettings,
DEFAULT_SETTINGS,
await this.loadData(),
)
}
async saveSettings() {
let saving:Record<string, any> = {}
Object.assign(saving, this.settings)
for (const key in saving) {
let value:any = (DEFAULT_SETTINGS as Record<string, any>)[key]
if (saving[key] === value) {
delete saving[key]
}
}
delete saving["_plugin"]
await this.saveData(saving)
}
async runJS(code:string, context?:any):Promise<any> {
if (!this.settings.enable_javascript_execution) {
throw new Error(
"Can't execute javascript because `Enable Javascript excecution` is not enabled. Enable in MyBible settings."
)
}
let call_result = await async function() {
return eval("(async () => { {0} })()".format(code))
}.call(context)
return call_result
}
}
class MBGeneralError extends Error {
toString():string {
let msg = "\n> [!ERROR] {0}\n".format(this.name)
if (this.message.length !== 0) {
msg += "> " + this.message + "\n"
}
return msg
}
}
class MBTagError extends MBGeneralError {}
class MBValueParseError extends MBTagError {
parsing_value:string
constructor(parsing_value:string) {
super("Parsing value: `{0}`".format(parsing_value))
parsing_value = parsing_value
this.name = "Failed to parse value"
}
}
class MBArgValueParseError extends MBTagError {
constructor(arg_name:string, err:MBValueParseError|undefined=undefined) {
let msg = ""
if (arg_name.length !== 0) {
msg += "Parsing argument: `{0}`".format(arg_name)
}
if (err !== undefined) {
msg += "\n> {0}".format(err.message)
}
super(msg)
this.name = "Failed to parse value for argument"
}
}
class BuildContext {
translation: string = ""
translation_texts: TranslationData
books: Record<BookId, BookData> = {}
/// List of book IDs sorted by their ordering as specified in the build settings
sorted_book_ids: BookId[]
/// Book of the current chapter
book: BookData
/// Book of previous chapter
prev_book: BookData
/// Book of next chapter
next_book: BookData
chapter: number = 1
prev_chapter: number = 0
next_chapter: number = 0
chapters: ChapterData
last_chapters: ChapterData
next_chapters: ChapterData
chapter_verse_count: number = 0
verses_text: string = ""
verse: number = 0
verse_counts: VerseCounts
plugin: MyBible
/// Find index of book by ID
find_book(book_id:BookId):number {
return book_id
}
abbreviate_book_name(name:string, delimeter:string): string {
return name.replace(delimeter, "").slice(0,3);
}
format_book_name(book:BookData|undefined=undefined): string {
if (book === undefined) {
book = this.book
}
let delim = this.plugin.settings.book_name_delimiter
let book_name = this.to_case(
book.name,
this.plugin.settings.book_name_capitalization,
delim
)
if (this.plugin.settings.book_name_abbreviated) {
book_name = this.abbreviate_book_name(book_name, delim)
}
return this.plugin.settings.book_name_format
.replace(/{translation}/g, String(this.translation))
.replace(/{book}/g, book_name)
.replace(
/{order}/g,
String(this.book_order(book))
.padStart(2 * Number(this.plugin.settings.padded_order), "0")
)
}
format_book_name_without_order(
book:BookData|undefined=undefined,
casing:string|undefined=undefined,
): string {
if (book === undefined) {
book = this.book
}
if (casing === undefined) {
casing = this.plugin.settings.book_name_capitalization
}
let delim = this.plugin.settings.book_name_delimiter
let book_name = this.to_case(
book.name,
casing,
delim
)
if (this.plugin.settings.book_name_abbreviated) {
book_name = this.abbreviate_book_name(book_name, delim)
}
return book_name
}
format_chapter_body(): string {
return this.plugin.settings.chapter_body_format
.replace(/{translation}/g, String(this.translation))
.replace(/{book}/g, this.format_book_name_without_order(this.book))
.replace(
/{order}/g,
String(this.book_order(this.book))
.padStart(2 * Number(this.plugin.settings.padded_order), "0")
)
.replace(/{chapter}/g, String(this.chapter))
.replace(/{chapter_name}/g, this.format_chapter_name())
.replace(/{chapter_index}/g, this.format_chapter_index_name(this.book))
.replace(/{last_chapter}/g, String(this.prev_chapter))
.replace(/{last_chapter_name}/g, this.format_chapter_name("last"))
.replace(/{last_chapter_book}/g, this.format_book_name_without_order(this.prev_book))
.replace(/{next_chapter}/g, String(this.next_chapter))
.replace(/{next_chapter_name}/g, this.format_chapter_name("next"))
.replace(/{next_chapter_book}/g, this.format_book_name_without_order(this.next_book))
.replace(/{first_chapter}/g, String(this.book.chapters.first()))
.replace(/{first_chapter_name}/g, this.format_chapter_name("first"))
.replace(/{final_chapter}/g, String(this.book.chapters.last()))
.replace(/{final_chapter_name}/g, this.format_chapter_name("final"))
.replace(/{verses}/g, this.verses_text)
}
format_chapter_name(tense:string="current", custom_chapter:number|null = null): string {
let format = this.plugin.settings.chapter_name_format;
if (format.length == 0) {
format = DEFAULT_SETTINGS.chapter_name_format;
}
let presentBook = this.book
let book_name = "";
let id = -1;
let chapter = custom_chapter
switch (tense) {
case "current": {
presentBook = this.book
book_name = this.format_book_name_without_order(this.book);
id = this.book.id
chapter = this.chapter
break;
}
case "last": {
presentBook = this.prev_book
book_name = this.format_book_name_without_order(this.prev_book);
id = this.prev_book.id
chapter = this.prev_chapter
break;
}
case "next": {
presentBook = this.next_book
book_name = this.format_book_name_without_order(this.next_book);
id = this.next_book.id
chapter = this.next_chapter
break;
}
case "first": {
presentBook = this.book
book_name = this.format_book_name_without_order(this.book);
id = this.book.id
chapter = this.book.chapters.first() || 1
break;
}
case "final": {
presentBook = this.book
book_name = this.format_book_name_without_order(this.book);
id = this.book.id
chapter = this.book.chapters.last() || 1
break;
}
case "custom": {
book_name = this.format_book_name_without_order(this.book);
id = this.book.id
chapter = custom_chapter;
break;
}
default: throw new Error("Unmatched switch case at tense '{0}'".format(tense));
}
if (chapter == null) {
throw new Error("Chapter is null");
}
let chapter_pad_by = 1
if (presentBook.chapters.length > 99) {
chapter_pad_by = 3
} else if (presentBook.chapters.length > 9) {
chapter_pad_by = 2
}
return format
.replace(/{translation}/g, String(this.translation))
.replace(/{book}/g, book_name)
.replace(
/{order}/g,
String(this.book_order(id))
.padStart(2 * Number(this.plugin.settings.padded_order), "0")
)
.replace(
/{chapter}/g,
String(chapter)
.padStart(chapter_pad_by * Number(this.plugin.settings.padded_chapter), "0"),
)
}
format_verse_body(
custom_text:string|undefined=undefined,
): string {
let book_name = this.format_book_name_without_order(
this.book,
"name_case",
);
let verse_text = ""
if (custom_text !== undefined) {
verse_text = custom_text
} else if (this.plugin.settings.build_with_dynamic_verses) {
verse_text = "``` verse\n"
+ "{0} {1}:{2}\n".format(
String(this.book.id),
String(this.chapter),
String(this.verse),
)
+ "```"
} else {
verse_text = this.plugin.bible_api.parse_html(
this.translation_texts.books[this.book.id][this.chapter][this.verse] ?? ""
)
if (verse_text === undefined) {
return ""
}
}
if (verse_text === "") {
return ""
}
return this.plugin.settings.verse_body_format
.replace(/{translation}/g, String(this.translation))
.replace(/{book}/g, book_name)
.replace(/{book_id}/g, String(this.book.id))
.replace(
/{order}/g,
String(this.book_order(this.book))
.padStart(2 * Number(this.plugin.settings.padded_order), "0")
)
.replace(/{chapter}/g, String(this.chapter))
.replace(/{chapter_name}/g, this.format_chapter_name())
.replace(/{verse_text}/g, verse_text)
.replace(/{verse}/g, String(this.verse))
}
format_chapter_index(book: BookData): string {
let book_name = this.format_book_name_without_order(book)
let chapter_links = ""
// Format chapter links
for (let i = 0; i != book.chapters.length; i++) {
let chapter = book.get_chapter_number(i);
let link = this.format_chapter_index_element(book, book_name, chapter)
if (i != book.chapters.length-1) {
link += "\n"
}
chapter_links += link
}
return this.plugin.settings.chapter_index_format
.replace(/{translation}/g, String(this.translation))
.replace(/{book}/g, book_name)
.replace(/{order}/g, String(this.book_order(book)).padStart(2 * Number(this.plugin.settings.padded_order), "0"))
.replace(/{index}/g, this.format_index_name())
.replace(/{chapters}/g, chapter_links)
.replace(/{chapter_index}/g, this.format_chapter_index_name(book))
;
}
format_chapter_index_element(
book:BookData|undefined=undefined,
book_name: string|undefined=undefined,
chapter: number|undefined=undefined,
): string {
if (book === undefined) {
book = this.book
}
if (book_name === undefined) {
book_name = this.format_book_name_without_order(book)
}
if (chapter === undefined) {
chapter = this.chapter
}
return this.plugin.settings.chapter_index_link_format
.replace(/{translation}/g, String(this.translation))
.replace(/{book}/g, book_name)
.replace(/{order}/g, String(this.book_order(book)).padStart(2 * Number(this.plugin.settings.padded_order), "0"))
.replace(/{chapter}/g, String(chapter))
.replace(/{chapter_name}/g, this.format_chapter_name("custom", chapter))
}
format_chapter_index_name(book: BookData|undefined=undefined): string {
if (book === undefined) {
book = this.book
}
let book_name = this.format_book_name_without_order(book)
return this.plugin.settings.chapter_index_name_format
.replace(/{order}/g, String(this.book_order(book)).padStart(2 * Number(this.plugin.settings.padded_order), "0"))
.replace(/{book}/g, book_name)
.replace(/{translation}/g, String(this.translation))
}
format_index_element(book:BookData|BookId|undefined=undefined) {
let id = 0
if (book === undefined) {
id = this.book.id
} else if (book instanceof BookData) {
id = book.id
} else {
id = book
}
let book_name = this.format_book_name_without_order(this.books[id])
let link = this.plugin.settings.index_link_format
.replace(/{translation}/g, String(this.translation))
.replace(/{book}/g, book_name)
.replace(/{order}/g, String(this.book_order(Number(id))).padStart(2 * Number(this.plugin.settings.padded_order), "0"))
.replace(/{chapter_index}/g, this.format_chapter_index_name(this.books[id]))
+ '\n'
return link
}
format_index_name(): string {
return this.plugin.settings.index_name_format
.replace(/{translation}/g, this.translation)
}
format_index(): string {
let old_t_links = ""
let new_t_links = ""
let apocr_links = ""
// Format all book links
for (const ID_ in this.books) {
const ID = Number(ID_)
let link = this.format_index_element(ID)
if (this.books[ID].id < 40) {
old_t_links += link
} else if (this.books[ID].id < 67) {
new_t_links += link
} else {
apocr_links += link
}
}