generated from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 63
/
main.ts
1159 lines (1034 loc) · 30.4 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
/* eslint-disable @typescript-eslint/no-var-requires */
import {
App,
Editor,
MarkdownView,
Plugin,
PluginSettingTab,
Setting,
requestUrl,
TFile,
Notice,
SuggestModal,
TFolder,
Platform,
} from "obsidian";
import { StreamManager } from "./stream";
import {
unfinishedCodeBlock,
writeInferredTitleToEditor,
createFolderModal,
} from "helpers";
interface ChatGPT_MDSettings {
apiKey: string;
defaultChatFrontmatter: string;
stream: boolean;
chatTemplateFolder: string;
chatFolder: string;
generateAtCursor: boolean;
autoInferTitle: boolean;
dateFormat: string;
headingLevel: number;
inferTitleLanguage: string;
}
const DEFAULT_SETTINGS: ChatGPT_MDSettings = {
apiKey: "default",
defaultChatFrontmatter:
"---\nsystem_commands: ['I am a helpful assistant.']\ntemperature: 0\ntop_p: 1\nmax_tokens: 512\npresence_penalty: 1\nfrequency_penalty: 1\nstream: true\nstop: null\nn: 1\nmodel: gpt-3.5-turbo\n---",
stream: true,
chatTemplateFolder: "ChatGPT_MD/templates",
chatFolder: "ChatGPT_MD/chats",
generateAtCursor: false,
autoInferTitle: false,
dateFormat: "YYYYMMDDhhmmss",
headingLevel: 0,
inferTitleLanguage: "English",
};
const DEFAULT_URL = `https://api.openai.com/v1/chat/completions`;
interface Chat_MD_FrontMatter {
temperature: number;
top_p: number;
presence_penalty: number;
frequency_penalty: number;
model: string;
max_tokens: number;
stream: boolean;
stop: string[] | null;
n: number;
logit_bias: any | null;
user: string | null;
system_commands: string[] | null;
url: string;
}
export default class ChatGPT_MD extends Plugin {
settings: ChatGPT_MDSettings;
async callOpenAIAPI(
streamManager: StreamManager,
editor: Editor,
messages: { role: string; content: string }[],
model = "gpt-3.5-turbo",
max_tokens = 250,
temperature = 0.3,
top_p = 1,
presence_penalty = 0.5,
frequency_penalty = 0.5,
stream = true,
stop: string[] | null = null,
n = 1,
logit_bias: any | null = null,
user: string | null = null,
url = DEFAULT_URL
) {
try {
console.log("calling openai api");
if (stream) {
const options = {
model: model,
messages: messages,
max_tokens: max_tokens,
temperature: temperature,
top_p: top_p,
presence_penalty: presence_penalty,
frequency_penalty: frequency_penalty,
stream: stream,
stop: stop,
n: n,
// logit_bias: logit_bias, // not yet supported
// user: user, // not yet supported
};
const response = await streamManager.streamSSE(
editor,
this.settings.apiKey,
url,
options,
this.settings.generateAtCursor,
this.getHeadingPrefix()
);
console.log("response from stream", response);
return { fullstr: response, mode: "streaming" };
} else {
const responseUrl = await requestUrl({
url: url,
method: "POST",
headers: {
Authorization: `Bearer ${this.settings.apiKey}`,
"Content-Type": "application/json",
},
contentType: "application/json",
body: JSON.stringify({
model: model,
messages: messages,
max_tokens: max_tokens,
temperature: temperature,
top_p: top_p,
presence_penalty: presence_penalty,
frequency_penalty: frequency_penalty,
stream: stream,
stop: stop,
n: n,
// logit_bias: logit_bias, // not yet supported
// user: user, // not yet supported
}),
throw: false,
});
try {
const json = responseUrl.json;
if (json && json.error) {
new Notice(
`[ChatGPT MD] Stream = False Error :: ${json.error.message}`
);
throw new Error(JSON.stringify(json.error));
}
} catch (err) {
// continue we got a valid str back
if (err instanceof SyntaxError) {
// continue
} else {
throw new Error(err);
}
}
const response = responseUrl.text;
const responseJSON = JSON.parse(response);
return responseJSON.choices[0].message.content;
}
} catch (err) {
if (err instanceof Object) {
if (err.error) {
new Notice(`[ChatGPT MD] Error :: ${err.error.message}`);
throw new Error(JSON.stringify(err.error));
} else {
if (url !== DEFAULT_URL) {
new Notice(
"[ChatGPT MD] Issue calling specified url: " + url
);
throw new Error(
"[ChatGPT MD] Issue calling specified url: " + url
);
} else {
new Notice(
`[ChatGPT MD] Error :: ${JSON.stringify(err)}`
);
throw new Error(JSON.stringify(err));
}
}
}
new Notice(
"issue calling OpenAI API, see console for more details"
);
throw new Error(
"issue calling OpenAI API, see error for more details: " + err
);
}
}
addHR(editor: Editor, role: string) {
const newLine = `\n\n<hr class="__chatgpt_plugin">\n\n${this.getHeadingPrefix()}role::${role}\n\n`;
editor.replaceRange(newLine, editor.getCursor());
// move cursor to end of file
const cursor = editor.getCursor();
const newCursor = {
line: cursor.line,
ch: cursor.ch + newLine.length,
};
editor.setCursor(newCursor);
}
getFrontmatter(view: MarkdownView): Chat_MD_FrontMatter {
try {
// get frontmatter
const noteFile = app.workspace.getActiveFile();
if (!noteFile) {
throw new Error("no active file");
}
const metaMatter =
app.metadataCache.getFileCache(noteFile)?.frontmatter;
const shouldStream =
metaMatter?.stream !== undefined
? metaMatter.stream // If defined in frontmatter, use its value.
: this.settings.stream !== undefined
? this.settings.stream // If not defined in frontmatter but exists globally, use its value.
: true; // Otherwise fallback on true.
const temperature =
metaMatter?.temperature !== undefined
? metaMatter.temperature
: 0.3;
const frontmatter = {
title: metaMatter?.title || view.file.basename,
tags: metaMatter?.tags || [],
model: metaMatter?.model || "gpt-3.5-turbo",
temperature: temperature,
top_p: metaMatter?.top_p || 1,
presence_penalty: metaMatter?.presence_penalty || 0,
frequency_penalty: metaMatter?.frequency_penalty || 0,
stream: shouldStream,
max_tokens: metaMatter?.max_tokens || 512,
stop: metaMatter?.stop || null,
n: metaMatter?.n || 1,
logit_bias: metaMatter?.logit_bias || null,
user: metaMatter?.user || null,
system_commands: metaMatter?.system_commands || null,
url: metaMatter?.url || DEFAULT_URL,
};
return frontmatter;
} catch (err) {
throw new Error("Error getting frontmatter");
}
}
splitMessages(text: string) {
try {
// <hr class="__chatgpt_plugin">
const messages = text.split('<hr class="__chatgpt_plugin">');
return messages;
} catch (err) {
throw new Error("Error splitting messages" + err);
}
}
clearConversationExceptFrontmatter(editor: Editor) {
try {
// get frontmatter
const YAMLFrontMatter = /---\s*[\s\S]*?\s*---/g;
const frontmatter = editor.getValue().match(YAMLFrontMatter);
if (!frontmatter) {
throw new Error("no frontmatter found");
}
// clear editor
editor.setValue("");
// add frontmatter
editor.replaceRange(frontmatter[0], editor.getCursor());
// get length of file
const length = editor.lastLine();
// move cursor to end of file https://davidwalsh.name/codemirror-set-focus-line
const newCursor = {
line: length + 1,
ch: 0,
};
editor.setCursor(newCursor);
return newCursor;
} catch (err) {
throw new Error("Error clearing conversation" + err);
}
}
moveCursorToEndOfFile(editor: Editor) {
try {
// get length of file
const length = editor.lastLine();
// move cursor to end of file https://davidwalsh.name/codemirror-set-focus-line
const newCursor = {
line: length + 1,
ch: 0,
};
editor.setCursor(newCursor);
return newCursor;
} catch (err) {
throw new Error("Error moving cursor to end of file" + err);
}
}
removeYMLFromMessage(message: string) {
try {
const YAMLFrontMatter = /---\s*[\s\S]*?\s*---/g;
const newMessage = message.replace(YAMLFrontMatter, "");
return newMessage;
} catch (err) {
throw new Error("Error removing YML from message" + err);
}
}
extractRoleAndMessage(message: string) {
try {
if (message.includes("role::")) {
const role = message.split("role::")[1].split("\n")[0].trim();
const content = message
.split("role::")[1]
.split("\n")
.slice(1)
.join("\n")
.trim();
return { role, content };
} else {
return { role: "user", content: message };
}
} catch (err) {
throw new Error("Error extracting role and message" + err);
}
}
getHeadingPrefix() {
const headingLevel = this.settings.headingLevel;
if (headingLevel === 0) {
return "";
} else if (headingLevel > 6) {
return "#".repeat(6) + " ";
}
return "#".repeat(headingLevel) + " ";
}
appendMessage(editor: Editor, role: string, message: string) {
/*
append to bottom of editor file:
const newLine = `<hr class="__chatgpt_plugin">\n${this.getHeadingPrefix()}role::${role}\n\n${message}`;
*/
const newLine = `\n\n<hr class="__chatgpt_plugin">\n\n${this.getHeadingPrefix()}role::${role}\n\n${message}\n\n<hr class="__chatgpt_plugin">\n\n${this.getHeadingPrefix()}role::user\n\n`;
editor.replaceRange(newLine, editor.getCursor());
}
removeCommentsFromMessages(message: string) {
try {
// comment block in form of =begin-chatgpt-md-comment and =end-chatgpt-md-comment
const commentBlock =
/=begin-chatgpt-md-comment[\s\S]*?=end-chatgpt-md-comment/g;
// remove comment block
const newMessage = message.replace(commentBlock, "");
return newMessage;
} catch (err) {
throw new Error("Error removing comments from messages" + err);
}
}
async inferTitleFromMessages(messages: string[]) {
console.log("[ChtGPT MD] Inferring Title");
new Notice("[ChatGPT] Inferring title from messages...");
try {
if (messages.length < 2) {
new Notice(
"Not enough messages to infer title. Minimum 2 messages."
);
return;
}
const prompt = `Infer title from the summary of the content of these messages. The title **cannot** contain any of the following characters: colon, back slash or forward slash. Just return the title. Write the title in ${
this.settings.inferTitleLanguage
}. \nMessages:\n\n${JSON.stringify(messages)}`;
const titleMessage = [
{
role: "user",
content: prompt,
},
];
const responseUrl = await requestUrl({
url: `https://api.openai.com/v1/chat/completions`,
method: "POST",
headers: {
Authorization: `Bearer ${this.settings.apiKey}`,
"Content-Type": "application/json",
},
contentType: "application/json",
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: titleMessage,
max_tokens: 50,
temperature: 0.0,
}),
throw: false,
});
const response = responseUrl.text;
const responseJSON = JSON.parse(response);
return responseJSON.choices[0].message.content
.replace(/[:/\\]/g, "")
.replace("Title", "")
.replace("title", "")
.trim();
} catch (err) {
new Notice("[ChatGPT MD] Error inferring title from messages");
throw new Error(
"[ChatGPT MD] Error inferring title from messages" + err
);
}
}
// only proceed to infer title if the title is in timestamp format
isTitleTimestampFormat(title: string) {
try {
const format = this.settings.dateFormat;
const pattern = this.generateDatePattern(format);
return title.length == format.length && pattern.test(title);
} catch (err) {
throw new Error(
"Error checking if title is in timestamp format" + err
);
}
}
generateDatePattern(format: string) {
const pattern = format
.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&") // Escape any special characters
.replace("YYYY", "\\d{4}") // Match exactly four digits for the year
.replace("MM", "\\d{2}") // Match exactly two digits for the month
.replace("DD", "\\d{2}") // Match exactly two digits for the day
.replace("hh", "\\d{2}") // Match exactly two digits for the hour
.replace("mm", "\\d{2}") // Match exactly two digits for the minute
.replace("ss", "\\d{2}"); // Match exactly two digits for the second
return new RegExp(`^${pattern}$`);
}
// get date from format
getDate(date: Date, format = "YYYYMMDDhhmmss") {
const year = date.getFullYear();
const month = date.getMonth() + 1;
const day = date.getDate();
const hour = date.getHours();
const minute = date.getMinutes();
const second = date.getSeconds();
const paddedMonth = month.toString().padStart(2, "0");
const paddedDay = day.toString().padStart(2, "0");
const paddedHour = hour.toString().padStart(2, "0");
const paddedMinute = minute.toString().padStart(2, "0");
const paddedSecond = second.toString().padStart(2, "0");
return format
.replace("YYYY", year.toString())
.replace("MM", paddedMonth)
.replace("DD", paddedDay)
.replace("hh", paddedHour)
.replace("mm", paddedMinute)
.replace("ss", paddedSecond);
}
async onload() {
const statusBarItemEl = this.addStatusBarItem();
await this.loadSettings();
const streamManager = new StreamManager();
// This adds an editor command that can perform some operation on the current editor instance
this.addCommand({
id: "call-chatgpt-api",
name: "Chat",
icon: "message-circle",
editorCallback: (editor: Editor, view: MarkdownView) => {
// This adds a status bar item to the bottom of the app. Does not work on mobile apps.
statusBarItemEl.setText("[ChatGPT MD] Calling API...");
// get frontmatter
const frontmatter = this.getFrontmatter(view);
// get messages
const bodyWithoutYML = this.removeYMLFromMessage(
editor.getValue()
);
let messages = this.splitMessages(bodyWithoutYML);
messages = messages.map((message) => {
return this.removeCommentsFromMessages(message);
});
const messagesWithRoleAndMessage = messages.map((message) => {
return this.extractRoleAndMessage(message);
});
if (frontmatter.system_commands) {
const systemCommands = frontmatter.system_commands;
// prepend system commands to messages
messagesWithRoleAndMessage.unshift(
...systemCommands.map((command) => {
return {
role: "system",
content: command,
};
})
);
}
// move cursor to end of file if generateAtCursor is false
if (!this.settings.generateAtCursor) {
this.moveCursorToEndOfFile(editor);
}
if (Platform.isMobile) {
new Notice("[ChatGPT MD] Calling API");
}
this.callOpenAIAPI(
streamManager,
editor,
messagesWithRoleAndMessage,
frontmatter.model,
frontmatter.max_tokens,
frontmatter.temperature,
frontmatter.top_p,
frontmatter.presence_penalty,
frontmatter.frequency_penalty,
frontmatter.stream,
frontmatter.stop,
frontmatter.n,
frontmatter.logit_bias,
frontmatter.user,
frontmatter.url
)
.then((response) => {
let responseStr = response;
if (response.mode === "streaming") {
responseStr = response.fullstr;
// append \n\n<hr class="__chatgpt_plugin">\n\n${this.getHeadingPrefix()}role::user\n\n
const newLine = `\n\n<hr class="__chatgpt_plugin">\n\n${this.getHeadingPrefix()}role::user\n\n`;
editor.replaceRange(newLine, editor.getCursor());
// move cursor to end of completion
const cursor = editor.getCursor();
const newCursor = {
line: cursor.line,
ch: cursor.ch + newLine.length,
};
editor.setCursor(newCursor);
} else {
if (unfinishedCodeBlock(responseStr)) {
responseStr = responseStr + "\n```";
}
this.appendMessage(
editor,
"assistant",
responseStr
);
}
if (this.settings.autoInferTitle) {
const title = view.file.basename;
let messagesWithResponse = messages.concat(responseStr);
messagesWithResponse = messagesWithResponse.map((message) => {
return this.removeCommentsFromMessages(message);
});
if (
this.isTitleTimestampFormat(title) &&
messagesWithResponse.length >= 4
) {
console.log(
"[ChatGPT MD] auto inferring title from messages"
);
statusBarItemEl.setText(
"[ChatGPT MD] Calling API..."
);
this.inferTitleFromMessages(
messagesWithResponse
)
.then(async (title) => {
if (title) {
console.log(
`[ChatGPT MD] automatically inferred title: ${title}. Changing file name...`
);
statusBarItemEl.setText("");
await writeInferredTitleToEditor(
this.app.vault,
view,
this.app.fileManager,
this.settings.chatFolder,
title
);
} else {
new Notice(
"[ChatGPT MD] Could not infer title",
5000
);
}
})
.catch((err) => {
console.log(err);
statusBarItemEl.setText("");
if (Platform.isMobile) {
new Notice(
"[ChatGPT MD] Error inferring title. " +
err,
5000
);
}
});
}
}
statusBarItemEl.setText("");
})
.catch((err) => {
if (Platform.isMobile) {
new Notice(
"[ChatGPT MD Mobile] Full Error calling API. " +
err,
9000
);
}
statusBarItemEl.setText("");
console.log(err);
});
},
});
this.addCommand({
id: "add-hr",
name: "Add divider",
icon: "minus",
editorCallback: (editor: Editor, view: MarkdownView) => {
this.addHR(editor, "user");
},
});
this.addCommand({
id: "add-comment-block",
name: "Add comment block",
icon: "comment",
editorCallback: (editor: Editor, view: MarkdownView) => {
// add a comment block at cursor in format: =begin-chatgpt-md-comment and =end-chatgpt-md-comment
const cursor = editor.getCursor();
const line = cursor.line;
const ch = cursor.ch;
const commentBlock = `=begin-chatgpt-md-comment\n\n=end-chatgpt-md-comment`;
editor.replaceRange(commentBlock, cursor);
// move cursor to middle of comment block
const newCursor = {
line: line + 1,
ch: ch,
};
editor.setCursor(newCursor);
},
});
this.addCommand({
id: "stop-streaming",
name: "Stop streaming",
icon: "octagon",
editorCallback: (editor: Editor, view: MarkdownView) => {
streamManager.stopStreaming();
},
});
this.addCommand({
id: "infer-title",
name: "Infer title",
icon: "subtitles",
editorCallback: async (editor: Editor, view: MarkdownView) => {
// get messages
const bodyWithoutYML = this.removeYMLFromMessage(
editor.getValue()
);
let messages = this.splitMessages(bodyWithoutYML);
messages = messages.map((message) => {
return this.removeCommentsFromMessages(message);
});
statusBarItemEl.setText("[ChatGPT MD] Calling API...");
const title = await this.inferTitleFromMessages(messages);
statusBarItemEl.setText("");
if (title) {
await writeInferredTitleToEditor(
this.app.vault,
view,
this.app.fileManager,
this.settings.chatFolder,
title
);
}
},
});
// grab highlighted text and move to new file in default chat format
this.addCommand({
id: "move-to-chat",
name: "Create new chat with highlighted text",
icon: "highlighter",
editorCallback: async (editor: Editor, view: MarkdownView) => {
try {
const selectedText = editor.getSelection();
if (
!this.settings.chatFolder ||
this.settings.chatFolder.trim() === ""
) {
new Notice(
`[ChatGPT MD] No chat folder value found. Please set one in settings.`
);
return;
}
if (
!(await this.app.vault.adapter.exists(
this.settings.chatFolder
))
) {
const result = await createFolderModal(
this.app,
this.app.vault,
"chatFolder",
this.settings.chatFolder
);
if (!result) {
new Notice(
`[ChatGPT MD] No chat folder found. One must be created to use plugin. Set one in settings and make sure it exists.`
);
return;
}
}
const newFile = await this.app.vault.create(
`${this.settings.chatFolder}/${this.getDate(
new Date(),
this.settings.dateFormat
)}.md`,
`${this.settings.defaultChatFrontmatter}\n\n${selectedText}`
);
// open new file
await this.app.workspace.openLinkText(
newFile.basename,
"",
true,
{ state: { mode: "source" } }
);
const activeView =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (!activeView) {
new Notice("No active markdown editor found.");
return;
}
activeView.editor.focus();
this.moveCursorToEndOfFile(activeView.editor);
} catch (err) {
console.error(
`[ChatGPT MD] Error in Create new chat with highlighted text`,
err
);
new Notice(
`[ChatGPT MD] Error in Create new chat with highlighted text, check console`
);
}
},
});
this.addCommand({
id: "choose-chat-template",
name: "Create new chat from template",
icon: "layout-template",
editorCallback: async (editor: Editor, view: MarkdownView) => {
if (
!this.settings.chatFolder ||
this.settings.chatFolder.trim() === ""
) {
new Notice(
`[ChatGPT MD] No chat folder value found. Please set one in settings.`
);
return;
}
if (
!(await this.app.vault.adapter.exists(
this.settings.chatFolder
))
) {
const result = await createFolderModal(
this.app,
this.app.vault,
"chatFolder",
this.settings.chatFolder
);
if (!result) {
new Notice(
`[ChatGPT MD] No chat folder found. One must be created to use plugin. Set one in settings and make sure it exists.`
);
return;
}
}
if (
!this.settings.chatTemplateFolder ||
this.settings.chatTemplateFolder.trim() === ""
) {
new Notice(
`[ChatGPT MD] No chat template folder value found. Please set one in settings.`
);
return;
}
if (
!(await this.app.vault.adapter.exists(
this.settings.chatTemplateFolder
))
) {
const result = await createFolderModal(
this.app,
this.app.vault,
"chatTemplateFolder",
this.settings.chatTemplateFolder
);
if (!result) {
new Notice(
`[ChatGPT MD] No chat template folder found. One must be created to use plugin. Set one in settings and make sure it exists.`
);
return;
}
}
new ChatTemplates(
this.app,
this.settings,
this.getDate(new Date(), this.settings.dateFormat)
).open();
},
});
this.addCommand({
id: "clear-chat",
name: "Clear chat (except frontmatter)",
icon: "trash",
editorCallback: async (editor: Editor, view: MarkdownView) => {
this.clearConversationExceptFrontmatter(editor);
},
});
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new ChatGPT_MDSettingsTab(this.app, this));
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
async saveSettings() {
await this.saveData(this.settings);
}
}
interface ChatTemplate {
title: string;
file: TFile;
}
export class ChatTemplates extends SuggestModal<ChatTemplate> {
settings: ChatGPT_MDSettings;
titleDate: string;
constructor(app: App, settings: ChatGPT_MDSettings, titleDate: string) {
super(app);
this.settings = settings;
this.titleDate = titleDate;
}
getFilesInChatFolder(): TFile[] {
const folder = this.app.vault.getAbstractFileByPath(
this.settings.chatTemplateFolder
) as TFolder;
if (folder != null) {
return folder.children as TFile[];
} else {
new Notice(
`Error getting folder: ${this.settings.chatTemplateFolder}`
);
throw new Error(
`Error getting folder: ${this.settings.chatTemplateFolder}`
);
}
}
// Returns all available suggestions.
getSuggestions(query: string): ChatTemplate[] {
const chatTemplateFiles = this.getFilesInChatFolder();
if (query == "") {
return chatTemplateFiles.map((file) => {
return {
title: file.basename,
file: file,
};
});
}
return chatTemplateFiles
.filter((file) => {
return file.basename
.toLowerCase()
.includes(query.toLowerCase());
})
.map((file) => {
return {
title: file.basename,
file: file,
};
});
}
// Renders each suggestion item.
renderSuggestion(template: ChatTemplate, el: HTMLElement) {
el.createEl("div", { text: template.title });
}
// Perform action on the selected suggestion.
async onChooseSuggestion(
template: ChatTemplate,
evt: MouseEvent | KeyboardEvent
) {
new Notice(`Selected ${template.title}`);
const templateText = await this.app.vault.read(template.file);
// use template text to create new file in chat folder
const file = await this.app.vault.create(
`${this.settings.chatFolder}/${this.titleDate}.md`,
templateText
);
// open new file
this.app.workspace.openLinkText(file.basename, "", true);
}
}
class ChatGPT_MDSettingsTab extends PluginSettingTab {
plugin: ChatGPT_MD;
constructor(app: App, plugin: ChatGPT_MD) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl("h2", {
text: "Settings for ChatGPT MD: Keep tokens in mind! You can see if your text is longer than the token limit (4096) here:",
});