-
Notifications
You must be signed in to change notification settings - Fork 74
/
chatgpt-shell.el
3711 lines (3366 loc) · 151 KB
/
chatgpt-shell.el
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
;;; chatgpt-shell.el --- ChatGPT shell + buffer insert commands -*- lexical-binding: t -*-
;; Copyright (C) 2023 Alvaro Ramirez
;; Author: Alvaro Ramirez https://xenodium.com
;; URL: https://github.com/xenodium/chatgpt-shell
;; Version: 1.24.1
;; Package-Requires: ((emacs "28.1") (shell-maker "0.62.1"))
(defconst chatgpt-shell--version "1.24.1")
;; This package is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; This package is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; `chatgpt-shell' is a comint-based ChatGPT shell for Emacs.
;;
;; You must set `chatgpt-shell-openai-key' to your key before using.
;;
;; Run `chatgpt-shell' to get a ChatGPT shell.
;;
;; Note: This is young package still. Please report issues or send
;; patches to https://github.com/xenodium/chatgpt-shell
;;
;; Support the work https://github.com/sponsors/xenodium
;;; Code:
(require 'cl-lib)
(require 'dired)
(require 'esh-mode)
(require 'em-prompt)
(require 'eshell)
(require 'find-func)
(require 'flymake)
(require 'ielm)
(require 'shell-maker)
(require 'smerge-mode)
(require 'ob-core)
(require 'color)
(require 'chatgpt-shell-openai)
(defcustom chatgpt-shell-request-timeout 600
"How long to wait for a request to time out in seconds."
:type 'integer
:group 'chatgpt-shell)
(defcustom chatgpt-shell-default-prompts
'("Write a unit test for the following code:"
"Refactor the following code so that "
"Summarize the output of the following command:"
"What's wrong with this command?"
"Explain what the following code does:")
"List of default prompts to choose from."
:type '(repeat string)
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-describe-code
"What does the following code do?"
"Prompt header of `describe-code`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-write-git-commit
"Please help me write a git commit message for the following commit:"
"Prompt header of `git-commit`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-refactor-code
"Please help me refactor the following code.
Please reply with the refactoring explanation in English, refactored code, and diff between two versions.
Please ignore the comments and strings in the code during the refactoring.
If the code remains unchanged after refactoring, please say 'No need to refactor'."
"Prompt header of `refactor-code`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-generate-unit-test
"Please help me generate unit-test following function:"
"Prompt header of `generate-unit-test`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-proofread-region
"Please help me proofread the following English text and only reply with fixed text:"
"Prompt header used by `chatgpt-shell-proofread-region`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-whats-wrong-with-last-command
"What's wrong with this command execution?"
"Prompt header of `whats-wrong-with-last-command`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-eshell-summarize-last-command-output
"Summarize the output of the following command:"
"Prompt header of `eshell-summarize-last-command-output`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-query-response-style 'other-buffer
"Determines the prompt style when invoking from other buffers.
`'inline' inserts responses into current buffer.
`'other-buffer' inserts responses into a transient buffer.
`'shell' inserts responses and focuses the shell
Note: in all cases responses are written to the shell to keep context."
:type '(choice (const :tag "Inline" inline)
(const :tag "Other Buffer" other-buffer)
(const :tag "Shell" shell))
:group 'chatgpt)
(defcustom chatgpt-shell-after-command-functions nil
"Abnormal hook (i.e. with parameters) invoked after each command.
This is useful if you'd like to automatically handle or suggest things
post execution.
For example:
\(add-hook `chatgpt-shell-after-command-functions'
(lambda (command output success)
(message \"Command: %s\" command)
(message \"Output: %s\" output)))"
:type 'hook
:group 'shell-maker)
(defvaralias 'chatgpt-shell-display-function 'shell-maker-display-function)
(defvaralias 'chatgpt-shell-read-string-function 'shell-maker-read-string-function)
(defvaralias 'chatgpt-shell-logging 'shell-maker-logging)
(defvaralias 'chatgpt-shell-root-path 'shell-maker-root-path)
(defalias 'chatgpt-shell-save-session-transcript #'shell-maker-save-session-transcript)
(defvar chatgpt-shell--prompt-history nil)
(defcustom chatgpt-shell-language-mapping '(("elisp" . "emacs-lisp")
("objective-c" . "objc")
("objectivec" . "objc")
("cpp" . "c++"))
"Maps external language names to Emacs names.
Use only lower-case names.
For example:
lowercase Emacs mode (without -mode)
Objective-C -> (\"objective-c\" . \"objc\")"
:type '(alist :key-type (string :tag "Language Name/Alias")
:value-type (string :tag "Mode Name (without -mode)"))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-babel-headers '(("dot" . ((:file . "<temp-file>.png")))
("plantuml" . ((:file . "<temp-file>.png")))
("ditaa" . ((:file . "<temp-file>.png")))
("objc" . ((:results . "output")))
("python" . ((:python . "python3")))
("swiftui" . ((:results . "file")))
("c++" . ((:results . "raw")))
("c" . ((:results . "raw"))))
"Additional headers to make babel blocks work.
Entries are of the form (language . headers). Headers should
conform to the types of `org-babel-default-header-args', which
see.
Please submit contributions so more things work out of the box."
:type '(alist :key-type (string :tag "Language")
:value-type (alist :key-type (restricted-sexp :match-alternatives (keywordp) :tag "Argument Name")
:value-type (string :tag "Value")))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-source-block-actions
nil
"Block actions for known languages.
Can be used compile or run source block at point."
:type '(alist :key-type (string :tag "Language")
:value-type (list (cons (const primary-action-confirmation) (string :tag "Confirmation Prompt:"))
(cons (const primary-action) (function :tag "Action:"))))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-model-versions
'("chatgpt-4o-latest"
"o1-preview"
"o1-mini"
"gpt-4o"
"gpt-4-0125-preview"
"gpt-4-turbo-preview"
"gpt-4-1106-preview"
"gpt-4-0613"
"gpt-4"
"gpt-3.5-turbo-16k-0613"
"gpt-3.5-turbo-16k"
"gpt-3.5-turbo-0613"
"gpt-3.5-turbo")
"The list of ChatGPT OpenAI models to swap from.
The list of models supported by /v1/chat/completions endpoint is
documented at
https://platform.openai.com/docs/models/model-endpoint-compatibility."
:type '(repeat string)
:group 'chatgpt-shell)
(defcustom chatgpt-shell-model-version 0
"The active ChatGPT OpenAI model index.
See `chatgpt-shell-model-versions' for available model versions.
Swap using `chatgpt-shell-swap-model-version'.
The list of models supported by /v1/chat/completions endpoint is
documented at
https://platform.openai.com/docs/models/model-endpoint-compatibility."
:type '(choice (string :tag "String")
(integer :tag "Integer")
(const :tag "Nil" nil))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-model-temperature nil
"What sampling temperature to use, between 0 and 2, or nil.
Higher values like 0.8 will make the output more random, while
lower values like 0.2 will make it more focused and
deterministic. Value of nil will not pass this configuration to
the model.
See
https://platform.openai.com/docs/api-reference/completions\
/create#completions/create-temperature
for details."
:type '(choice (float :tag "Float")
(const :tag "Nil" nil))
:group 'chatgpt-shell)
(defun chatgpt-shell--append-system-info (text)
"Append system info to TEXT."
(cl-labels ((chatgpt-shell--get-system-info-command
()
(cond ((eq system-type 'darwin) "sw_vers")
((or (eq system-type 'gnu/linux)
(eq system-type 'gnu/kfreebsd)) "uname -a")
((eq system-type 'windows-nt) "ver")
(t (format "%s" system-type)))))
(let ((system-info (string-trim
(shell-command-to-string
(chatgpt-shell--get-system-info-command)))))
(concat text
"\n# System info\n"
"\n## OS details\n"
system-info
"\n## Editor\n"
(emacs-version)))))
(defcustom chatgpt-shell-system-prompts
`(("tl;dr" . "Be as succint but informative as possible and respond in tl;dr form to my queries")
("General" . "You use markdown liberally to structure responses. Always show code snippets in markdown blocks with language labels.")
;; Based on https://github.com/benjamin-asdf/dotfiles/blob/8fd18ff6bd2a1ed2379e53e26282f01dcc397e44/mememacs/.emacs-mememacs.d/init.el#L768
("Programming" . ,(chatgpt-shell--append-system-info
"The user is a programmer with very limited time.
You treat their time as precious. You do not repeat obvious things, including their query.
You are as concise as possible in responses.
You never apologize for confusions because it would waste their time.
You use markdown liberally to structure responses.
Always show code snippets in markdown blocks with language labels.
Don't explain code snippets.
Whenever you output updated code for the user, only show diffs, instead of entire snippets."))
("Positive Programming" . ,(chatgpt-shell--append-system-info
"Your goal is to help the user become an amazing computer programmer.
You are positive and encouraging.
You love see them learn.
You do not repeat obvious things, including their query.
You are as concise in responses. You always guide the user go one level deeper and help them see patterns.
You never apologize for confusions because it would waste their time.
You use markdown liberally to structure responses. Always show code snippets in markdown blocks with language labels.
Don't explain code snippets. Whenever you output updated code for the user, only show diffs, instead of entire snippets."))
("Japanese" . ,(chatgpt-shell--append-system-info
"The user is a beginner Japanese language learner with very limited time.
You treat their time as precious. You do not repeat obvious things, including their query.
You are as concise as possible in responses.
You never apologize for confusions because it would waste their time.
You use markdown liberally to structure responses.")))
"List of system prompts to choose from.
If prompt is a cons, its car will be used as a title to display.
For example:
\(\"Translating\" . \"You are a helpful English to Spanish assistant.\")\"
\(\"Programming\" . \"The user is a programmer with very limited time...\")"
:type '(alist :key-type (string :tag "Title")
:value-type (string :tag "Prompt value"))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-system-prompt 1 ;; Concise
"The system prompt `chatgpt-shell-system-prompts' index.
Or nil if none."
:type '(choice (string :tag "String")
(integer :tag "Integer")
(const :tag "No Prompt" nil))
:group 'chatgpt-shell)
(defun chatgpt-shell-model-version ()
"Return active model version."
(cond ((stringp chatgpt-shell-model-version)
chatgpt-shell-model-version)
((integerp chatgpt-shell-model-version)
(nth chatgpt-shell-model-version
chatgpt-shell-model-versions))
(t
nil)))
(defun chatgpt-shell-system-prompt ()
"Return active system prompt."
(cond ((stringp chatgpt-shell-system-prompt)
chatgpt-shell-system-prompt)
((integerp chatgpt-shell-system-prompt)
(let ((prompt (nth chatgpt-shell-system-prompt
chatgpt-shell-system-prompts)))
(if (consp prompt)
(cdr prompt)
prompt)))
(t
nil)))
(defun chatgpt-shell-duplicate-map-keys (map)
"Return duplicate keys in MAP."
(let ((keys (map-keys map))
(seen '())
(duplicates '()))
(dolist (key keys)
(if (member key seen)
(push key duplicates)
(push key seen)))
duplicates))
;;;###autoload
(defun chatgpt-shell-swap-system-prompt ()
"Swap system prompt from `chatgpt-shell-system-prompts'."
(interactive)
(unless (derived-mode-p 'chatgpt-shell-mode)
(user-error "Not in a shell"))
(when-let ((duplicates (chatgpt-shell-duplicate-map-keys chatgpt-shell-system-prompts)))
(user-error "Duplicate prompt names found %s. Please remove" duplicates))
(let* ((choices (append (list "None")
(map-keys chatgpt-shell-system-prompts)))
(choice (completing-read "System prompt: " choices))
(choice-pos (seq-position choices choice)))
(if (or (string-equal choice "None")
(string-empty-p (string-trim choice))
(not choice-pos))
(setq-local chatgpt-shell-system-prompt nil)
(setq-local chatgpt-shell-system-prompt
;; -1 to disregard None
(1- (seq-position choices choice)))))
(chatgpt-shell--update-prompt t)
(chatgpt-shell-interrupt nil)
(chatgpt-shell--save-variables))
(declare-function pcsv-parse-file "pcsv" (file &optional coding-system))
;;;###autoload
(defun chatgpt-shell-load-awesome-prompts ()
"Load `chatgpt-shell-system-prompts' from awesome-chatgpt-prompts.
Downloaded from https://github.com/f/awesome-chatgpt-prompts."
(interactive)
(unless (fboundp 'pcsv-parse-file)
(user-error "Please install pcsv"))
(require 'pcsv)
(let ((csv-path (concat (temporary-file-directory) "awesome-chatgpt-prompts.csv")))
(url-copy-file "https://raw.githubusercontent.com/f/awesome-chatgpt-prompts/main/prompts.csv"
csv-path t)
(setq chatgpt-shell-system-prompts
(map-merge 'list
chatgpt-shell-system-prompts
;; Based on Daniel Gomez's parsing code from
;; https://github.com/xenodium/chatgpt-shell/issues/104
(seq-sort (lambda (rhs lhs)
(string-lessp (car rhs)
(car lhs)))
(cdr
(mapcar
(lambda (row)
(cons (car row)
(cadr row)))
(pcsv-parse-file csv-path))))))
(message "Loaded awesome-chatgpt-prompts")
(setq chatgpt-shell-system-prompt nil)
(chatgpt-shell--update-prompt t)
(chatgpt-shell-interrupt nil)
(chatgpt-shell-swap-system-prompt)))
;;;###autoload
(defun chatgpt-shell-version ()
"Show `chatgpt-shell' mode version."
(interactive)
(message "chatgpt-shell v%s" chatgpt-shell--version))
(defun chatgpt-shell-swap-model-version ()
"Swap model version from `chatgpt-shell-model-versions'."
(interactive)
(unless (derived-mode-p 'chatgpt-shell-mode)
(user-error "Not in a shell"))
(setq-local chatgpt-shell-model-version
(completing-read "Model version: "
(if (> (length chatgpt-shell-model-versions) 1)
(seq-remove
(lambda (item)
(string-equal item (chatgpt-shell-model-version)))
chatgpt-shell-model-versions)
chatgpt-shell-model-versions) nil t))
(chatgpt-shell--update-prompt t)
(chatgpt-shell-interrupt nil))
(defcustom chatgpt-shell-streaming t
"Whether or not to stream ChatGPT responses (show chunks as they arrive)."
:type 'boolean
:group 'chatgpt-shell)
(defcustom chatgpt-shell-highlight-blocks t
"Whether or not to highlight source blocks."
:type 'boolean
:group 'chatgpt-shell)
(defcustom chatgpt-shell-insert-dividers nil
"Whether or not to display a divider between requests and responses."
:type 'boolean
:group 'chatgpt-shell)
(defcustom chatgpt-shell-transmitted-context-length
#'chatgpt-shell--approximate-context-length
"Controls the amount of context provided to chatGPT.
This context needs to be transmitted to the API on every request.
ChatGPT reads the provided context on every request, which will
consume more and more prompt tokens as your conversation grows.
Models do have a maximum token limit, however.
A value of nil will send full chat history (the full contents of
the comint buffer), to ChatGPT.
A value of 0 will not provide any context. This is the cheapest
option, but ChatGPT can't look back on your conversation.
A value of 1 will send only the latest prompt-completion pair as
context.
A Value > 1 will send that amount of prompt-completion pairs to
ChatGPT.
A function `(lambda (tokens-per-message tokens-per-name messages))'
returning length. Can use custom logic to enable a shifting context
window."
:type '(choice (integer :tag "Integer")
(const :tag "Not set" nil)
(function :tag "Function"))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-welcome-function #'shell-maker-welcome-message
"Function returning welcome message or nil for no message.
See `shell-maker-welcome-message' as an example."
:type 'function
:group 'chatgpt-shell)
(defvar chatgpt-shell--config
(make-shell-maker-config
:name "ChatGPT"
:validate-command
(lambda (_command)
(unless chatgpt-shell-openai-key
"Variable `chatgpt-shell-openai-key' needs to be set to your key.
Try M-x set-variable chatgpt-shell-openai-key
or
(setq chatgpt-shell-openai-key \"my-key\")"))
:execute-command
(lambda (command shell)
(shell-maker-make-http-request
:async t
:url (chatgpt-shell--chatgpt-api-url)
:data (chatgpt-shell--make-chatgpt-payload
:prompt command
:context (map-elt shell :history)
:streaming chatgpt-shell-streaming
:temperature chatgpt-shell-model-temperature)
:headers (list "Content-Type: application/json; charset=utf-8"
(funcall chatgpt-shell-auth-header))
:filter #'chatgpt-shell-filter-chatgpt-output
:shell shell))
:on-command-finished
(lambda (command output success)
(chatgpt-shell--put-source-block-overlays)
(run-hook-with-args 'chatgpt-shell-after-command-functions
command output success))
:redact-log-output
(lambda (output)
(if (chatgpt-shell-openai-key)
(replace-regexp-in-string (regexp-quote (chatgpt-shell-openai-key))
"SK-REDACTED-OPENAI-KEY"
output)
output))))
(defalias 'chatgpt-shell-explain-code #'chatgpt-shell-describe-code)
;; Aliasing enables editing as text in babel.
(defalias 'chatgpt-shell-mode #'text-mode)
(shell-maker-define-major-mode chatgpt-shell--config)
;;;###autoload
(defun chatgpt-shell (&optional new-session)
"Start a ChatGPT shell interactive command.
With NEW-SESSION, start a new session."
(interactive "P")
(chatgpt-shell-start nil new-session))
(defvar chatgpt-shell-mode-map (make-sparse-keymap)
"Keymap for `chatgpt-shell-mode'.")
(defun chatgpt-shell-start (&optional no-focus new-session ignore-as-primary model-version system-prompt)
"Start a ChatGPT shell programmatically.
Set NO-FOCUS to start in background.
Set NEW-SESSION to start a separate new session.
Set IGNORE-AS-PRIMARY to avoid making new buffer the primary one.
Set MODEL-VERSION to override variable `chatgpt-shell-model-version'.
Set SYSTEM-PROMPT to override variable `chatgpt-shell-system-prompt'"
(let* ((chatgpt-shell--config
(let ((config (copy-sequence chatgpt-shell--config))
(chatgpt-shell-model-version (or model-version chatgpt-shell-model-version))
(chatgpt-shell-system-prompt (or system-prompt chatgpt-shell-system-prompt)))
(setf (shell-maker-config-prompt config)
(car (chatgpt-shell--prompt-pair)))
(setf (shell-maker-config-prompt-regexp config)
(cdr (chatgpt-shell--prompt-pair)))
config))
(shell-buffer
(shell-maker-start chatgpt-shell--config
no-focus
chatgpt-shell-welcome-function
new-session
(if (and (chatgpt-shell--primary-buffer)
(not ignore-as-primary))
(buffer-name (chatgpt-shell--primary-buffer))
(chatgpt-shell--make-buffer-name)))))
(when (and (not ignore-as-primary)
(not (chatgpt-shell--primary-buffer)))
(chatgpt-shell--set-primary-buffer shell-buffer))
(unless model-version
(setq model-version chatgpt-shell-model-version))
(unless system-prompt
(setq system-prompt chatgpt-shell-system-prompt))
(with-current-buffer shell-buffer
(setq-local chatgpt-shell-model-version model-version)
(setq-local chatgpt-shell-system-prompt system-prompt)
(chatgpt-shell--update-prompt t)
(chatgpt-shell--add-menus))
(define-key chatgpt-shell-mode-map (kbd "C-M-h")
#'chatgpt-shell-mark-at-point-dwim)
(define-key chatgpt-shell-mode-map (kbd "C-c C-c")
#'chatgpt-shell-ctrl-c-ctrl-c)
(define-key chatgpt-shell-mode-map (kbd "C-c C-v")
#'chatgpt-shell-swap-model-version)
(define-key chatgpt-shell-mode-map (kbd "C-c C-s")
#'chatgpt-shell-swap-system-prompt)
(define-key chatgpt-shell-mode-map (kbd "C-c C-p")
#'chatgpt-shell-previous-item)
(define-key chatgpt-shell-mode-map (kbd "C-c C-n")
#'chatgpt-shell-next-item)
(define-key chatgpt-shell-mode-map (kbd "C-c C-e")
#'chatgpt-shell-prompt-compose)
shell-buffer))
(defun chatgpt-shell--shrink-model-version (model-version)
"Shrink MODEL-VERSION. gpt-3.5-turbo -> 3.5t."
(replace-regexp-in-string
"-turbo" "t"
(string-remove-prefix
"gpt-" (string-trim model-version))))
(defun chatgpt-shell--shrink-system-prompt (prompt)
"Shrink PROMPT."
(if (consp prompt)
(chatgpt-shell--shrink-system-prompt (car prompt))
(if (> (length (string-trim prompt)) 15)
(format "%s..."
(substring (string-trim prompt) 0 12))
(string-trim prompt))))
(defun chatgpt-shell--shell-info ()
"Generate shell info for display."
(concat
(chatgpt-shell--shrink-model-version
(chatgpt-shell-model-version))
(cond ((and (integerp chatgpt-shell-system-prompt)
(nth chatgpt-shell-system-prompt
chatgpt-shell-system-prompts))
(concat "/" (chatgpt-shell--shrink-system-prompt (nth chatgpt-shell-system-prompt
chatgpt-shell-system-prompts))))
((stringp chatgpt-shell-system-prompt)
(concat "/" (chatgpt-shell--shrink-system-prompt chatgpt-shell-system-prompt)))
(t
""))))
(defun chatgpt-shell--prompt-pair ()
"Return a pair with prompt and prompt-regexp."
(cons
(format "ChatGPT(%s)> " (chatgpt-shell--shell-info))
(rx (seq bol "ChatGPT" (one-or-more (not (any "\n"))) ">" (or space "\n")))))
(defun chatgpt-shell--shell-buffers ()
"Return a list of all shell buffers."
(seq-filter
(lambda (buffer)
(eq (buffer-local-value 'major-mode buffer)
'chatgpt-shell-mode))
(buffer-list)))
(defun chatgpt-shell-set-as-primary-shell ()
"Set as primary shell when there are multiple sessions."
(interactive)
(unless (derived-mode-p 'chatgpt-shell-mode)
(user-error "Not in a shell"))
(chatgpt-shell--set-primary-buffer (current-buffer)))
(defvar-local chatgpt-shell--is-primary-p nil
"Non-nil if shell buffer is considered primary.")
(defun chatgpt-shell--set-primary-buffer (primary-shell-buffer)
"Set PRIMARY-SHELL-BUFFER as primary buffer."
(unless primary-shell-buffer
(error "No primary shell available"))
(mapc (lambda (shell-buffer)
(with-current-buffer shell-buffer
(setq chatgpt-shell--is-primary-p nil)))
(chatgpt-shell--shell-buffers))
(with-current-buffer primary-shell-buffer
(setq chatgpt-shell--is-primary-p t)))
(defun chatgpt-shell--primary-buffer ()
"Return the primary shell buffer.
This is used for sending a prompt to in the background."
(let* ((shell-buffers (chatgpt-shell--shell-buffers))
(primary-shell-buffer (seq-find
(lambda (shell-buffer)
(with-current-buffer shell-buffer
chatgpt-shell--is-primary-p))
shell-buffers)))
(unless primary-shell-buffer
(setq primary-shell-buffer
(or (seq-first shell-buffers)
(shell-maker-start chatgpt-shell--config
t
chatgpt-shell-welcome-function
t
(chatgpt-shell--make-buffer-name))))
(chatgpt-shell--set-primary-buffer primary-shell-buffer))
primary-shell-buffer))
(defun chatgpt-shell--make-buffer-name ()
"Generate a buffer name using current shell config info."
(format "%s %s"
(shell-maker-buffer-default-name
(shell-maker-config-name chatgpt-shell--config))
(chatgpt-shell--shell-info)))
(defun chatgpt-shell--add-menus ()
"Add ChatGPT shell menu items."
(unless (derived-mode-p 'chatgpt-shell-mode)
(user-error "Not in a shell"))
(when-let ((duplicates (chatgpt-shell-duplicate-map-keys chatgpt-shell-system-prompts)))
(user-error "Duplicate prompt names found %s. Please remove.?" duplicates))
(easy-menu-define chatgpt-shell-system-prompts-menu (current-local-map) "ChatGPT"
`("ChatGPT"
("Versions"
,@(mapcar (lambda (version)
`[,version
(lambda ()
(interactive)
(setq-local chatgpt-shell-model-version
(seq-position chatgpt-shell-model-versions ,version))
(chatgpt-shell--update-prompt t)
(chatgpt-shell-interrupt nil))])
chatgpt-shell-model-versions))
("Prompts"
,@(mapcar (lambda (prompt)
`[,(car prompt)
(lambda ()
(interactive)
(setq-local chatgpt-shell-system-prompt
(seq-position (map-keys chatgpt-shell-system-prompts) ,(car prompt)))
(chatgpt-shell--save-variables)
(chatgpt-shell--update-prompt t)
(chatgpt-shell-interrupt nil))])
chatgpt-shell-system-prompts))))
(easy-menu-add chatgpt-shell-system-prompts-menu))
(defun chatgpt-shell--update-prompt (rename-buffer)
"Update prompt and prompt regexp from `chatgpt-shell-model-versions'.
Set RENAME-BUFFER to also rename the buffer accordingly."
(unless (derived-mode-p 'chatgpt-shell-mode)
(user-error "Not in a shell"))
(shell-maker-set-prompt
(car (chatgpt-shell--prompt-pair))
(cdr (chatgpt-shell--prompt-pair)))
(when rename-buffer
(shell-maker-set-buffer-name
(current-buffer)
(chatgpt-shell--make-buffer-name))))
(defun chatgpt-shell-interrupt (ignore-item)
"Interrupt `chatgpt-shell' from any buffer.
With prefix IGNORE-ITEM, do not mark as failed."
(interactive "P")
(with-current-buffer
(cond
((derived-mode-p 'chatgpt-shell-mode)
(current-buffer))
(t
(shell-maker-buffer-name chatgpt-shell--config)))
(shell-maker-interrupt ignore-item)))
(defun chatgpt-shell-ctrl-c-ctrl-c (ignore-item)
"If point in source block, execute it. Otherwise interrupt.
With prefix IGNORE-ITEM, do not use interrupted item in context."
(interactive "P")
(cond ((chatgpt-shell-block-action-at-point)
(chatgpt-shell-execute-block-action-at-point))
((chatgpt-shell-markdown-block-at-point)
(user-error "No action available"))
((and shell-maker--busy
(eq (line-number-at-pos (point-max))
(line-number-at-pos (point))))
(shell-maker-interrupt ignore-item))
(t
(shell-maker-interrupt ignore-item))))
(defun chatgpt-shell-mark-at-point-dwim ()
"Mark source block if at point. Mark all output otherwise."
(interactive)
(if-let ((block (chatgpt-shell-markdown-block-at-point)))
(progn
(set-mark (map-elt block 'end))
(goto-char (map-elt block 'start)))
(shell-maker-mark-output)))
(defun chatgpt-shell-markdown-block-language (text)
"Get the language label of a Markdown TEXT code block."
(when (string-match (rx bol "```" (0+ space) (group (+ (not (any "\n"))))) text)
(match-string 1 text)))
(defun chatgpt-shell-markdown-block-at-point ()
"Markdown start/end cons if point at block. nil otherwise."
(save-excursion
(save-restriction
(when (derived-mode-p 'chatgpt-shell-mode)
(shell-maker-narrow-to-prompt))
(let* ((language)
(language-start)
(language-end)
(start (save-excursion
(when (re-search-backward "^```" nil t)
(setq language (chatgpt-shell-markdown-block-language (thing-at-point 'line)))
(save-excursion
(forward-char 3) ; ```
(setq language-start (point))
(end-of-line)
(setq language-end (point)))
language-end)))
(end (save-excursion
(when (re-search-forward "^```" nil t)
(forward-line 0)
(point)))))
(when (and start end
(>= (point) start)
(< (point) end))
(list (cons 'language language)
(cons 'language-start language-start)
(cons 'language-end language-end)
(cons 'start start)
(cons 'end end)))))))
;; TODO: Move to shell-maker.
(defun chatgpt-shell--markdown-headers (&optional avoid-ranges)
"Extract markdown headers with AVOID-RANGES."
(let ((headers '())
(case-fold-search nil))
(save-excursion
(goto-char (point-min))
(while (re-search-forward
(rx bol (group (one-or-more "#"))
(one-or-more space)
(group (one-or-more (not (any "\n")))) eol)
nil t)
(when-let ((begin (match-beginning 0))
(end (match-end 0)))
(unless (seq-find (lambda (avoided)
(and (>= begin (car avoided))
(<= end (cdr avoided))))
avoid-ranges)
(push
(list
'start begin
'end end
'level (cons (match-beginning 1) (match-end 1))
'title (cons (match-beginning 2) (match-end 2)))
headers)))))
(nreverse headers)))
;; TODO: Move to shell-maker.
(defun chatgpt-shell--markdown-links (&optional avoid-ranges)
"Extract markdown links with AVOID-RANGES."
(let ((links '())
(case-fold-search nil))
(save-excursion
(goto-char (point-min))
(while (re-search-forward
(rx (seq "["
(group (one-or-more (not (any "]"))))
"]"
"("
(group (one-or-more (not (any ")"))))
")"))
nil t)
(when-let ((begin (match-beginning 0))
(end (match-end 0)))
(unless (seq-find (lambda (avoided)
(and (>= begin (car avoided))
(<= end (cdr avoided))))
avoid-ranges)
(push
(list
'start begin
'end end
'title (cons (match-beginning 1) (match-end 1))
'url (cons (match-beginning 2) (match-end 2)))
links)))))
(nreverse links)))
;; TODO: Move to shell-maker.
(defun chatgpt-shell--markdown-bolds (&optional avoid-ranges)
"Extract markdown bolds with AVOID-RANGES."
(let ((bolds '())
(case-fold-search nil))
(save-excursion
(goto-char (point-min))
(while (re-search-forward
(rx (or (group "**" (group (one-or-more (not (any "\n*")))) "**")
(group "__" (group (one-or-more (not (any "\n_")))) "__")))
nil t)
(when-let ((begin (match-beginning 0))
(end (match-end 0)))
(unless (seq-find (lambda (avoided)
(and (>= begin (car avoided))
(<= end (cdr avoided))))
avoid-ranges)
(push
(list
'start begin
'end end
'text (cons (or (match-beginning 2)
(match-beginning 4))
(or (match-end 2)
(match-end 4))))
bolds)))))
(nreverse bolds)))
;; TODO: Move to shell-maker.
(defun chatgpt-shell--markdown-strikethroughs (&optional avoid-ranges)
"Extract markdown strikethroughs with AVOID-RANGES."
(let ((strikethroughs '())
(case-fold-search nil))
(save-excursion
(goto-char (point-min))
(while (re-search-forward
(rx "~~" (group (one-or-more (not (any "\n~")))) "~~")
nil t)
(when-let ((begin (match-beginning 0))
(end (match-end 0)))
(unless (seq-find (lambda (avoided)
(and (>= begin (car avoided))
(<= end (cdr avoided))))
avoid-ranges)
(push
(list
'start begin
'end end
'text (cons (match-beginning 1)
(match-end 1)))
strikethroughs)))))
(nreverse strikethroughs)))
;; TODO: Move to shell-maker.
(defun chatgpt-shell--markdown-italics (&optional avoid-ranges)
"Extract markdown italics with AVOID-RANGES."
(let ((italics '())
(case-fold-search nil))
(save-excursion
(goto-char (point-min))
(while (re-search-forward
(rx (or (group (or bol (one-or-more (any "\n \t")))
(group "*")
(group (one-or-more (not (any "\n*")))) "*")
(group (or bol (one-or-more (any "\n \t")))
(group "_")
(group (one-or-more (not (any "\n_")))) "_")))
nil t)
(when-let ((begin (match-beginning 0))
(end (match-end 0)))
(unless (seq-find (lambda (avoided)
(and (>= begin (car avoided))
(<= end (cdr avoided))))
avoid-ranges)
(push
(list
'start (or (match-beginning 2)
(match-beginning 5))
'end end
'text (cons (or (match-beginning 3)
(match-beginning 6))
(or (match-end 3)
(match-end 6))))
italics)))))
(nreverse italics)))
;; TODO: Move to shell-maker.
(defun chatgpt-shell--markdown-inline-codes (&optional avoid-ranges)
"Get a list of all inline markdown code in buffer with AVOID-RANGES."
(let ((codes '())
(case-fold-search nil))
(save-excursion
(goto-char (point-min))
(while (re-search-forward
"`\\([^`\n]+\\)`"
nil t)
(when-let ((begin (match-beginning 0))
(end (match-end 0)))
(unless (seq-find (lambda (avoided)
(and (>= begin (car avoided))
(<= end (cdr avoided))))
avoid-ranges)
(push
(list
'body (cons (match-beginning 1) (match-end 1))) codes)))))
(nreverse codes)))
;; TODO: Move to shell-maker.
(defvar chatgpt-shell--source-block-regexp
(rx bol (zero-or-more whitespace) (group "```") (zero-or-more whitespace) ;; ```
(group (zero-or-more (or alphanumeric "-" "+" "#"))) ;; languages like: emacs-lisp C++ C#
(zero-or-more whitespace)
(one-or-more "\n")
(group (*? anychar)) ;; body
(one-or-more "\n")
(group "```") (or "\n" eol)))
(defun chatgpt-shell-next-source-block ()
"Move point to previous source block."
(interactive)
(when-let
((next-block
(save-excursion
(when-let ((current (chatgpt-shell-markdown-block-at-point)))
(goto-char (map-elt current 'end))
(end-of-line))
(when (re-search-forward chatgpt-shell--source-block-regexp nil t)
(chatgpt-shell--match-source-block)))))
(goto-char (car (map-elt next-block 'body)))))