gptel-transient: Commands to act on region

gptel.el (gptel): When calling `gptel' with a selected region, insert it
into a new session.

gptel-transient.el (gptel--suffix-send-existing,
gptel--suffix-send-new): Transient suffixes available when a region is
selected.  These send the text as a prompt in a existing or new gptel
session.
This commit is contained in:
Karthik Chikmagalur 2023-03-09 22:58:54 -08:00
parent 39376aa3f4
commit 9f8fc0e519
2 changed files with 38 additions and 5 deletions

View file

@ -25,6 +25,7 @@
;;
;;; Code:
(eval-when-compile (require 'cl-lib))
(require 'gptel)
(require 'transient)
@ -163,8 +164,35 @@ will get progressively longer!"
(read-from-minibuffer "Set temperature (0.0-2.0, leave empty for default): "
(number-to-string gptel--temperature))))
(transient-define-suffix gptel--suffix-send-existing ()
"Send query in existing chat session."
:if (lambda () (use-region-p))
:key "E"
:description "Send in existing session"
(interactive)
(when-let* ((this (buffer-name))
(prompt (buffer-substring (region-beginning)
(region-end)))
(buf
(completing-read
"Send query in buffer: " (mapcar #'buffer-name (buffer-list))
(lambda (buf) (and (buffer-local-value 'gptel-mode (get-buffer buf))
(not (equal this buf)))))))
(with-current-buffer buf
(goto-char (point-max))
(insert prompt)
(pop-to-buffer buf))))
(transient-define-suffix gptel--suffix-send-new ()
"Send query in new session."
:if (lambda () (use-region-p))
:description "Send in new session"
:key "N"
(interactive)
(let ((current-prefix-arg t)) (call-interactively #'gptel)))
(transient-define-suffix gptel--suffix-system-message ()
"Set Establishing message sent to ChatGPT."
"Set directives sent to ChatGPT."
:transient nil
:description "Set custom directives"
:key "h"

View file

@ -286,18 +286,23 @@ Return the message received."
map))
;;;###autoload
(defun gptel (name &optional api-key)
(defun gptel (name &optional api-key initial)
"Switch to or start ChatGPT session with NAME.
With a prefix arg, query for a (new) session name.
Ask for API-KEY if `gptel-api-key' is unset."
Ask for API-KEY if `gptel-api-key' is unset.
If region is active, use it as the INITIAL prompt."
(interactive (list (if current-prefix-arg
(read-string "Session name: " (generate-new-buffer-name gptel-default-session))
gptel-default-session)
(or gptel-api-key
(setq gptel-api-key
(read-passwd "OpenAI API key: ")))))
(read-passwd "OpenAI API key: ")))
(and (use-region-p)
(buffer-substring (region-beginning)
(region-end)))))
(unless api-key
(user-error "No API key available"))
(with-current-buffer (get-buffer-create name)
@ -308,7 +313,7 @@ Ask for API-KEY if `gptel-api-key' is unset."
(visual-line-mode 1))
(t (funcall gptel-default-mode)))
(unless gptel-mode (gptel-mode 1))
(if (bobp) (insert gptel-prompt-string))
(if (bobp) (insert (or initial gptel-prompt-string)))
(pop-to-buffer (current-buffer))
(goto-char (point-max))
(skip-chars-backward "\t\r\n")