forked from xenodium/chatgpt-shell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chatgpt-shell.el
2048 lines (1851 loc) · 82.4 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: 0.40.1
;; Package-Requires: ((emacs "27.1") (shell-maker "0.25.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 'esh-mode)
(require 'eshell)
(require 'ielm)
(require 'shell-maker)
(defcustom chatgpt-shell-openai-key nil
"OpenAI key as a string or a function that loads and returns it."
:type '(choice (function :tag "Function")
(string :tag "String"))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-additional-curl-options nil
"Additional options for `curl' command."
:type '(repeat (string :tag "String"))
:group 'chatgpt-shell)
(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-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 text with English:"
"Promt header of `proofread-region`."
:type 'string
:group 'chatgpt-shell)
(defcustom chatgpt-shell-prompt-header-whats-wrong-with-last-command
"What's wrong with this command?"
"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)
(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-history-path 'shell-maker-history-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 '(repeat (cons string string))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-babel-headers '(("dot" . ((: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.
Please submit contributions so more things work out of the box."
:type '(repeat (cons string string))
: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 '(list (cons string
(list (cons 'primary-action-confirmation string)
(cons 'primary-action function))))
:group 'chatgpt-shell)
(defcustom chatgpt-shell-model-versions
'("gpt-3.5-turbo"
"gpt-3.5-turbo-0301"
"gpt-4"
"gpt-4-0314")
"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."
(cond ((eq system-type 'darwin)
(concat text
"\n# System info\n"
"\n## OS details\n"
(string-trim (shell-command-to-string "sw_vers"))
"\n## Editor\n"
(emacs-version)))
((or (eq system-type 'gnu/linux)
(eq system-type 'gnu/kfreebsd))
(concat text
"\n# System info\n"
"\n## OS details\n"
(string-trim (shell-command-to-string "uname -a"))
"\n## Editor\n"
(emacs-version)))
((eq system-type 'windows-nt)
(concat text
"\n# System info\n"
"\n## OS details\n"
(string-trim (shell-command-to-string "ver"))
"\n## Editor\n"
(emacs-version)))
(t
(concat text
"\n# System info\n"
"\n## OS details\n"
(format "%s" system-type)
"\n## Editor\n"
(emacs-version)))))
(defcustom chatgpt-shell-system-prompts
`(("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.")))
"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 '(repeat (choice (cons string string) string))
: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"))
: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-swap-system-prompt ()
"Swap system prompt from `chatgpt-shell-system-prompts'."
(interactive)
(let ((choice (completing-read
"System prompt: "
(append
(list "None")
(seq-map (lambda (item)
(if (consp item)
(concat
(car item)
(propertize (concat "<<prompt>>"
(cdr item))
'invisible t))
(truncate-string-to-width
(nth 0 (split-string item "\n"))
(window-body-width))))
chatgpt-shell-system-prompts)))))
(if (or (string-equal choice "None")
(string-empty-p (string-trim choice)))
(setq chatgpt-shell-system-prompt nil)
(setq chatgpt-shell-system-prompt
(or (seq-position chatgpt-shell-system-prompts choice
(lambda (item prefix)
;; Some items are of the form:
;; Programing<<prompt>>The user is a programmer.
(if-let ((parts (split-string choice "<<prompt>>"))
(prompt (when (> (length parts) 1)
(cons (nth 0 parts)
(nth 1 parts)))))
(equal item prompt)
(if (consp item)
nil ;; Different type / no matching.
(string-prefix-p prefix item)))))
choice))))
(chatgpt-shell--update-prompt)
(chatgpt-shell-interrupt nil))
(defun chatgpt-shell-load-awesome-prompts ()
"Load `chatgpt-shell-system-prompts' from https://github.com/f/awesome-chatgpt-prompts."
(interactive)
(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)
;; Based on Daniel Gomez's parsing code from
;; https://github.com/xenodium/chatgpt-shell/issues/104
(setq chatgpt-shell-system-prompts
(with-temp-buffer
(insert-file-contents csv-path)
(cdr
(mapcar
(lambda (row) (cons (car row) (cadr row)))
(mapcar
(lambda (line)
(mapcar
(lambda (s)
(replace-regexp-in-string "\"" "" s))
(split-string line ",")))
(split-string (buffer-string) "\n"))))))
(message "Loaded awesome-chatgpt-prompts")))
(defun chatgpt-shell-swap-model-version ()
"Swap model version from `chatgpt-shell-model-versions'."
(interactive)
(setq 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)
(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-transmitted-context-length nil
"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-api-url-base "https://api.openai.com"
"OpenAI API's base URL.
`chatgpt-shell--api-url' =
`chatgpt-shell--api-url-base' + `chatgpt-shell--api-url-path'
If you use ChatGPT through a proxy service, change the URL base."
:type 'string
:safe #'stringp
:group 'chatgpt-shell)
(defcustom chatgpt-shell-api-url-path "/v1/chat/completions"
"OpenAI API's URL path.
`chatgpt-shell--api-url' =
`chatgpt-shell--api-url-base' + `chatgpt-shell--api-url-path'"
:type 'string
:safe #'stringp
: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 history callback error-callback)
(shell-maker-async-shell-command
(chatgpt-shell--make-curl-request-command-list
(chatgpt-shell--make-payload history))
chatgpt-shell-streaming
#'chatgpt-shell--extract-chatgpt-response
callback
error-callback))
:on-command-finished
(lambda (command output)
(chatgpt-shell--put-source-block-overlays)
(run-hook-with-args 'chatgpt-shell-after-command-functions
command output))
: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-clear-buffer #'comint-clear-buffer)
(defalias 'chatgpt-shell-explain-code #'chatgpt-shell-describe-code)
;; Aliasing enables editing as text in babel.
(defalias 'chatgpt-shell-mode #'text-mode)
;;;###autoload
(defun chatgpt-shell (&optional no-focus)
"Start a ChatGPT shell.
With NO-FOCUS, start the shell without focus."
(interactive)
(setf (shell-maker-config-prompt chatgpt-shell--config)
(car (chatgpt-shell--prompt-pair)))
(setf (shell-maker-config-prompt-regexp chatgpt-shell--config)
(cdr (chatgpt-shell--prompt-pair)))
(shell-maker-start chatgpt-shell--config no-focus)
(chatgpt-shell--update-prompt)
;; Disabling advice for now. It gets in the way.
;; (advice-add 'keyboard-quit :around #'chatgpt-shell--adviced:keyboard-quit)
(define-key shell-maker-mode-map (kbd "C-M-h")
#'chatgpt-shell-mark-at-point-dwim)
(define-key shell-maker-mode-map (kbd "C-c C-c")
#'chatgpt-shell-ctrl-c-ctrl-c)
(define-key shell-maker-mode-map (kbd "C-c C-v")
#'chatgpt-shell-swap-model-version)
(define-key shell-maker-mode-map (kbd "C-c C-s")
#'chatgpt-shell-swap-system-prompt)
(define-key shell-maker-mode-map (kbd "C-c C-p")
#'chatgpt-shell-previous-item)
(define-key shell-maker-mode-map (kbd "C-c C-n")
#'chatgpt-shell-next-item))
(defun chatgpt-shell--prompt-pair ()
"Return a pair with prompt and prompt-regexp."
(cl-flet ((shrink-model-version (model-version) ;; gpt-3.5-turbo -> 3.5t
(replace-regexp-in-string
"-turbo" "t"
(string-remove-prefix
"gpt-" (string-trim model-version))))
(shrink-system-prompt (prompt)
(if (consp prompt)
(car prompt)
(if (> (length (string-trim prompt)) 6)
(format "%s..."
(substring (string-trim prompt) 0 15))
(string-trim prompt)))))
(cons
(format "ChatGPT(%s%s)> " (shrink-model-version
(chatgpt-shell-model-version))
(cond ((and (integerp chatgpt-shell-system-prompt)
(nth chatgpt-shell-system-prompt
chatgpt-shell-system-prompts))
(concat "/" (shrink-system-prompt (nth chatgpt-shell-system-prompt
chatgpt-shell-system-prompts))))
((stringp chatgpt-shell-system-prompt)
(concat "/" (shrink-system-prompt chatgpt-shell-system-prompt)))
(t
"")))
(rx (seq bol "ChatGPT" (one-or-more (not (any "\n"))) ">" (or space "\n"))))))
(defun chatgpt-shell--update-prompt ()
"Update prompt and prompt regexp from `chatgpt-shell-model-versions'."
(with-current-buffer (shell-maker-buffer chatgpt-shell--config)
(shell-maker-set-prompt
(car (chatgpt-shell--prompt-pair))
(cdr (chatgpt-shell--prompt-pair)))))
(defun chatgpt-shell--adviced:keyboard-quit (orig-fun &rest args)
"Advice around `keyboard-quit' interrupting active shell.
Applies ORIG-FUN and ARGS."
(chatgpt-shell-interrupt nil)
(apply orig-fun args))
(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
(shell-maker-buffer-name chatgpt-shell--config)
(shell-maker-interrupt ignore-item)))
(defun chatgpt-shell-ctrl-c-ctrl-c (ignore-item)
"Ctrl-C Ctrl-C DWIM binding.
If on a block with primary action, execute it.
Otherwise interrupt if busy.
With prefix IGNORE-ITEM, do not use interrupted item in context."
(interactive "P")
(cond ((chatgpt-shell-primary-block-action-at-point)
(chatgpt-shell-execute-primary-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
(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)))))))
(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)))
(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)))
(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)))
(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)))
(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)))
(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)))
(defvar chatgpt-shell--source-block-regexp
(rx bol (zero-or-more whitespace) (group "```") (zero-or-more whitespace) ;; ```
(group (zero-or-more (or alphanumeric "-" "+"))) ;; language
(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)))))
(defun chatgpt-shell-previous-item ()
"Go to previous item.
Could be a prompt or a source block."
(interactive)
(unless (eq major-mode 'shell-maker-mode)
(user-error "Not in a shell"))
(let ((prompt-pos (save-excursion
(when (comint-next-prompt (- 1))
(point))))
(block-pos (save-excursion
(when (chatgpt-shell-previous-source-block)
(point)))))
(cond ((and block-pos prompt-pos)
(goto-char (max prompt-pos
block-pos)))
(block-pos
(goto-char block-pos))
(prompt-pos
(goto-char prompt-pos)))))
(defun chatgpt-shell-next-item ()
"Go to next item.
Could be a prompt or a source block."
(interactive)
(unless (eq major-mode 'shell-maker-mode)
(user-error "Not in a shell"))
(let ((prompt-pos (save-excursion
(when (comint-next-prompt 1)
(point))))
(block-pos (save-excursion
(when (chatgpt-shell-next-source-block)
(point)))))
(cond ((and block-pos prompt-pos)
(goto-char (min prompt-pos
block-pos)))
(block-pos
(goto-char block-pos))
(prompt-pos
(goto-char prompt-pos)))))
(defun chatgpt-shell-previous-source-block ()
"Move point to previous source block."
(interactive)
(when-let
((previous-block
(save-excursion
(when-let ((current (chatgpt-shell-markdown-block-at-point)))
(goto-char (map-elt current 'start))
(forward-line 0))
(when (re-search-backward chatgpt-shell--source-block-regexp nil t)
(chatgpt-shell--match-source-block)))))
(goto-char (car (map-elt previous-block 'body)))))
(defun chatgpt-shell--match-source-block ()
"Return a matched source block by the previous search/regexp operation."
(list
'start (cons (match-beginning 1)
(match-end 1))
'end (cons (match-beginning 4)
(match-end 4))
'language (when (and (match-beginning 2)
(match-end 2))
(cons (match-beginning 2)
(match-end 2)))
'body (cons (match-beginning 3) (match-end 3))))
(defun chatgpt-shell--source-blocks ()
"Get a list of all source blocks in buffer."
(let ((markdown-blocks '())
(case-fold-search nil))
(save-excursion
(goto-char (point-min))
(while (re-search-forward
chatgpt-shell--source-block-regexp
nil t)
(when-let ((begin (match-beginning 0))
(end (match-end 0)))
(push (chatgpt-shell--match-source-block)
markdown-blocks))))
(nreverse markdown-blocks)))
(defun chatgpt-shell-prompt ()
"Make a ChatGPT request from the minibuffer.
If region is active, append to prompt."
(interactive)
(unless chatgpt-shell--prompt-history
(setq chatgpt-shell--prompt-history
chatgpt-shell-default-prompts))
(let ((overlay-blocks (derived-mode-p 'prog-mode))
(prompt (funcall shell-maker-read-string-function
(concat
(if (region-active-p)
"[appending region] "
"")
(shell-maker-prompt
chatgpt-shell--config))
'chatgpt-shell--prompt-history)))
(when (region-active-p)
(setq prompt (concat prompt "\n\n"
(if overlay-blocks
(format "``` %s\n"
(string-remove-suffix "-mode" (format "%s" major-mode)))
"")
(buffer-substring (region-beginning) (region-end))
(if overlay-blocks
"\n```"
""))))
(chatgpt-shell-send-to-buffer prompt nil)))
(defun chatgpt-shell-prompt-appending-kill-ring ()
"Make a ChatGPT request from the minibuffer appending kill ring."
(interactive)
(unless chatgpt-shell--prompt-history
(setq chatgpt-shell--prompt-history
chatgpt-shell-default-prompts))
(let ((prompt (funcall shell-maker-read-string-function
(concat
"[appending kill ring] "
(shell-maker-prompt
chatgpt-shell--config))
'chatgpt-shell--prompt-history)))
(chatgpt-shell-send-to-buffer
(concat prompt "\n\n"
(current-kill 0)) nil)))
(defun chatgpt-shell-describe-code ()
"Describe code from region using ChatGPT."
(interactive)
(unless (region-active-p)
(user-error "No region active"))
(let ((overlay-blocks (derived-mode-p 'prog-mode)))
(chatgpt-shell-send-to-buffer
(concat chatgpt-shell-prompt-header-describe-code
"\n\n"
(if overlay-blocks
(format "``` %s\n"
(string-remove-suffix "-mode" (format "%s" major-mode)))
"")
(buffer-substring (region-beginning) (region-end))
(if overlay-blocks
"\n```"
"")) nil)
(when overlay-blocks
(with-current-buffer
(shell-maker-buffer-name chatgpt-shell--config)
(chatgpt-shell--put-source-block-overlays)))))
(defun chatgpt-shell-send-region-with-header (header)
"Send text with HEADER from region using ChatGPT."
(unless (region-active-p)
(user-error "No region active"))
(chatgpt-shell-send-to-buffer
(concat header
"\n\n"
(buffer-substring (region-beginning) (region-end)))
nil))
(defun chatgpt-shell-refactor-code ()
"Refactor code from region using ChatGPT."
(interactive)
(chatgpt-shell-send-region-with-header chatgpt-shell-prompt-header-refactor-code))
(defun chatgpt-shell-generate-unit-test ()
"Generate unit-test for the code from region using ChatGPT."
(interactive)
(chatgpt-shell-send-region-with-header chatgpt-shell-prompt-header-generate-unit-test))
(defun chatgpt-shell-proofread-region ()
"Proofread English from region using ChatGPT."
(interactive)
(chatgpt-shell-send-region-with-header chatgpt-shell-prompt-header-proofread-region))
(defun chatgpt-shell-eshell-whats-wrong-with-last-command ()
"Ask ChatGPT what's wrong with the last eshell command."
(interactive)
(let ((chatgpt-shell-prompt-query-response-style 'other-buffer))
(chatgpt-shell-send-to-buffer
(concat chatgpt-shell-prompt-header-whats-wrong-with-last-command
"\n\n"
(buffer-substring-no-properties eshell-last-input-start eshell-last-input-end)
"\n\n"
(buffer-substring-no-properties (eshell-beginning-of-output) (eshell-end-of-output))))))
(defun chatgpt-shell-eshell-summarize-last-command-output ()
"Ask ChatGPT to summarize the last command output."
(interactive)
(let ((chatgpt-shell-prompt-query-response-style 'other-buffer))
(chatgpt-shell-send-to-buffer
(concat chatgpt-shell-prompt-header-eshell-summarize-last-command-output
"\n\n"
(buffer-substring-no-properties eshell-last-input-start eshell-last-input-end)
"\n\n"
(buffer-substring-no-properties (eshell-beginning-of-output) (eshell-end-of-output))))))
(defun chatgpt-shell-send-region (review)
"Send region to ChatGPT.
With prefix REVIEW prompt before sending to ChatGPT."