From 57a70c23cb1e71dd32594692a060378a7d49d02f Mon Sep 17 00:00:00 2001 From: Karthik Chikmagalur Date: Tue, 7 Nov 2023 21:19:25 -0800 Subject: [PATCH] gptel: Skip to end of word before sending * gptel.el (gptel--at-word-end, gptel-send, gptel-request): Include the word the cursor is on in the prompt, and don't break it when inserting the response. This is primarily useful for evil-mode users who frequenty end up one char before the end of a word when they switch to normal-mode. * gptel-transient.el (gptel-send): Same. Also fix bug with selecting an existing buffer to send the response to. --- gptel-transient.el | 6 +++--- gptel.el | 10 ++++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/gptel-transient.el b/gptel-transient.el index 30496a8..ec18779 100644 --- a/gptel-transient.el +++ b/gptel-transient.el @@ -415,7 +415,7 @@ will get progressively longer!" 'gptel) t)) (point)) - (point)))))) + (gptel--at-word-end (point))))))) (with-current-buffer buffer (setq gptel-backend backend) (gptel--update-header-line " Waiting..." 'warning) @@ -423,7 +423,7 @@ will get progressively longer!" (setq output-to-other-buffer-p t)) ((setq gptel-buffer-name (cl-some (lambda (s) (and (string-prefix-p "e" s) - (substring s 2))) + (substring s 1))) args)) (setq buffer (get-buffer gptel-buffer-name)) (setq output-to-other-buffer-p t) @@ -440,7 +440,7 @@ will get progressively longer!" 'gptel) t)) (point)) - (point)))))) + (gptel--at-word-end (point))))))) (with-current-buffer buffer (goto-char (point-max)) (if (or buffer-read-only diff --git a/gptel.el b/gptel.el index c91db71..3d01906 100644 --- a/gptel.el +++ b/gptel.el @@ -387,6 +387,12 @@ and \"apikey\" as USER." "Ensure VAL is a number." (if (stringp val) (string-to-number val) val)) +(defmacro gptel--at-word-end (&rest body) + "Execute BODY at end of the current word or punctuation." + `(save-excursion + (skip-syntax-forward "w.") + ,@body)) + (defun gptel-prompt-string () (or (alist-get major-mode gptel-prompt-prefix-alist) "")) @@ -621,7 +627,7 @@ Model parameters can be let-bound around calls to this function." ((null position) (if (use-region-p) (set-marker (make-marker) (region-end)) - (point-marker))) + (gptel--at-word-end (point-marker)))) ((markerp position) position) ((integerp position) (set-marker (make-marker) position buffer)))) @@ -658,7 +664,7 @@ instead." (let* ((response-pt (if (use-region-p) (set-marker (make-marker) (region-end)) - (point-marker))) + (gptel--at-word-end (point-marker)))) (gptel-buffer (current-buffer)) (full-prompt (gptel--create-prompt response-pt))) (funcall