Support Edit / Rewrite code
To upvote this issue, give it a thumbs up. See this list for the most upvoted issues.
Some tools like Cursor support a feature where user select a part of the code and ask LLM to edit/improve/generate docs etc.
We should support this in the protocol
@ericdallo, how do you want to handle this?
This app does similar thing. https://github.com/theJayTea/WritingTools
In WritingTools just like MacOs writing tools
User select text, trigger the Writing-tools application via key binding (in my case Ctrl+` in linux) and ask LLM's to perform actions on it.
This application copies the selected code by virtually simulation Ctrl+c or command+c and passes the text to LLM with instructions.
I am trying to get it working on Wayland compositor and it is a pain, see -
https://github.com/theJayTea/WritingTools/pull/229
Since we also support multiple editor's/IDE's, I thought this would give you some context.
Let brainstorm here.
Or we just support it on the client(editors/ide's) end, which would be much easier.
Yeah, with ECA more stable now and chat being the core/most important feature, my idea for this feature is: user selects (or not) a text with cursor and call a ECA client command like eca-edit-cursor or something, then one of these happen:
- editor ask user what should do with that code, then client call a
edit/promptin eca protocol which server will pass to LLM and return to client, then client show the diff/change in the editor (harder) - editor just paste the code in a chat prompt then user can write whatver they want and see the change in the chat itself (easier)
WDYT? c/c @editor-code-assistant/maintainers
editor just paste the code in a chat prompt then user can write whatver they want and see the change in the chat itself (easier)
This would be much easier, User select the code and trigger a command eca-edit-selected, single-shot prompt instruction are captured via pop-window(vs-code/itellij) or mini-buffer(emacs/vim), we do not need to paste the code in chat-buffer/chat-window, just capture prompt with code and pass it on to the LLM with eca-edit-selected tool.
How does that sound?
the first hop UX looks good, but what about the LLM response? how we present the edit/preview the change? with chat we have all of that alredy, otherwise we will have to implement custom UX on each editor
at least on emacs end we do not need to send anything to the chat buffer, we can edit in place
see this -
https://github.com/karthink/gptel/blob/master/gptel-rewrite.el
transient-menu's can be to capture use input, see this demo - https://github.com/user-attachments/assets/cec11aec-52f6-412e-9e7a-9358e8b9b1bf
if you are OK with this approach at least in emacs, I can port the functionality over to eca-emacs .
transient-menu's can be to capture use input, see this demo - https://github.com/user-attachments/assets/cec11aec-52f6-412e-9e7a-9358e8b9b1bf
yeah, I very much would like to add this feature to ECA, let's start with that as the video, for that I believe we should have a edit/replace protocol request message in server which will receive the prompt, range and respond with text and range.
Let's discuss this API first so you can implement on eca-emacs side, which should have a eca-edit.el file for this whole feature. WDYT?
I still wonder, what if user didn't like the LLM result? they should just undo?
should have a eca-edit.el file for this whole feature. WDYT?
Yes this is what I envision too.
I still wonder, what if user didn't like the LLM result? they should just undo?
Yes we should have transient menu for , diff, accept, reject, re-try, re-try-with-new-prompt. Transient menu can be displaced with a key-binding, gptel-rewrite uses M-<return>.
I believe we should have a edit/replace protocol request message in server which will receive the prompt, range and respond with text and range.
Yes I believe so too, that would be more of a streamline approach but this can also be achieved in emacs by chat protocol, what I mean is, like we query llm with plan behaviour in the chat buffer and llm responds in the same buffer with responses. we can mimic that, we capture the the response from llm and replace the selected-region, since user already select's a region to perform LLM actions.
LMK what you think.
Ahh makes sense, we should handle streaming too, so I think the edit/replace could be a request if there is anything valuable to return, but the LLM response we process async in a edit/replaceReceived server notification multiple times
Hi @ericdallo ,
here is rough draft for emacs, haven't tested it yet but I want you to prof-read before I develop it any further.
;;; eca-rewrite.el --- ECA (Editor Code Assistant) rewrite -*- lexical-binding: t; -*-
;; Copyright (C) 2025 Eric Dallo
;;
;; SPDX-License-Identifier: Apache-2.0
;;
;;; Commentary:
;; Provides region-based text rewriting via ECA's LLM, all in one
;; smart command `eca-rewrite` (no separate region/point functions).
;;; Code:
(require 'cl-lib)
(require 'eca-util)
(require 'eca-api)
(declare-function diff-no-select "diff")
(declare-function ediff-setup-windows-plain "ediff-wind")
(declare-function smerge-mode "smerge-mode")
;; * User options
(defcustom eca-rewrite-default-action nil
"Action to take when rewriting a text region using ECA.
Choices: nil (wait for explicit), accept, merge, diff, ediff, dispatch, or custom function."
:group 'eca
:type '(choice
(const :tag "Wait" nil)
(const :tag "Accept rewrite" accept)
(const :tag "Merge with conflicts" merge)
(const :tag "Diff" diff)
(const :tag "Ediff" ediff)
(const :tag "Dispatch menu" dispatch)
(function :tag "Custom action")))
(defcustom eca-rewrite-directive
"You are an expert programmer and editor. Follow my instructions and improve or rewrite the text I provide. Generate ONLY the replacement text, without any explanation or Markdown fences."
"System prompt for rewrite operations."
:group 'eca
:type 'string)
(defface eca-rewrite-highlight-face
'((((class color) (min-colors 88) (background dark))
:background "#041714" :extend t)
(((class color) (min-colors 88) (background light))
:background "light goldenrod yellow" :extend t)
(t :inherit secondary-selection))
"Face to highlight pending rewrite regions."
:group 'eca)
;; * Internal variables
(defvar-keymap eca-rewrite-actions-map
:doc "Keymap for rewrite overlay actions."
"RET" #'eca-rewrite--dispatch
"<return>" #'eca-rewrite--dispatch
"C-c C-a" #'eca-rewrite--accept
"C-c C-k" #'eca-rewrite--reject
"C-c C-d" #'eca-rewrite--diff
"C-c C-e" #'eca-rewrite--ediff
"C-c C-m" #'eca-rewrite--merge
"C-c C-r" #'eca-rewrite ;; iterate with new instruction
"C-c C-t" #'eca-rewrite--retry
"C-c C-y" #'eca-rewrite--retry-with-derivative
"C-c C-n" #'eca-rewrite--next
"C-c C-p" #'eca-rewrite--previous)
(defvar-local eca-rewrite--overlays nil
"Active rewrite overlays in this buffer.")
(defvar-local eca-rewrite--message nil
"Last rewrite instruction used.")
(defvar-local eca-rewrite--original-text nil
"Original text before rewriting, for retry operations.")
;; * Helper functions
(defun eca-rewrite--move (search-func)
"Move to next/previous rewrite overlay using SEARCH-FUNC."
(let* ((ov (cdr (get-char-property-and-overlay (point) 'eca-rewrite)))
(pos (funcall search-func (if ov (overlay-start ov) (point))
'eca-rewrite)))
(if (get-char-property pos 'eca-rewrite)
(goto-char pos)
(user-error "No further rewrite regions"))))
(defun eca-rewrite--next () (interactive) (eca-rewrite--move #'next-single-char-property-change))
(defun eca-rewrite--previous () (interactive) (eca-rewrite--move #'previous-single-char-property-change))
(defun eca-rewrite--overlay-at (&optional pt)
"Return the rewrite overlay and its content at PT or point."
(pcase-let ((`(,content . ,ov)
(get-char-property-and-overlay (or pt (point)) 'eca-rewrite)))
(unless ov (user-error "No rewrite overlay here"))
(unless content (user-error "No LLM output for this overlay"))
ov))
(defun eca-rewrite--setup-overlay (start end content &optional original-text instruction)
"Create an overlay from START to END with CONTENT and return it.
ORIGINAL-TEXT and INSTRUCTION are stored for retry operations."
(let ((ov (make-overlay start end nil t)))
(overlay-put ov 'category 'eca-rewrite)
(overlay-put ov 'evaporate t)
(overlay-put ov 'eca-rewrite content)
(overlay-put ov 'eca-original (or original-text
(buffer-substring-no-properties start end)))
(overlay-put ov 'eca-instruction (or instruction eca-rewrite--message))
(overlay-put ov 'face 'eca-rewrite-highlight-face)
(overlay-put ov 'priority 2000)
(overlay-put ov 'keymap eca-rewrite-actions-map)
(overlay-put ov 'mouse-face 'highlight)
(overlay-put ov 'help-echo "ECA rewrite: RET for options")
(push ov eca-rewrite--overlays)
ov))
(defun eca-rewrite--move-cursor-back (start end)
"Move cursor back into the overlay region if at END."
(when (= (point) end) (backward-char 1))
(deactivate-mark))
(defun eca-rewrite--reject (&optional ovs)
"Delete overlays in OVS (or at point), clearing pending rewrites."
(interactive (list (eca-rewrite--overlay-at)))
(dolist (ov (ensure-list ovs))
(setq eca-rewrite--overlays (delq ov eca-rewrite--overlays))
(delete-overlay ov))
(message "Cleared rewrite overlay(s)"))
(defun eca-rewrite--accept (&optional ovs buf)
"Replace the original text with LLM CONTENT for overlays OVS.
If BUF is provided, apply there; otherwise use the overlay's buffer."
(interactive (list (eca-rewrite--overlay-at)))
(let ((ov-list (ensure-list ovs)))
(dolist (ov ov-list)
(let* ((content (overlay-get ov 'eca-rewrite))
(start (overlay-start ov))
(end (overlay-end ov))
(dst-buf (or buf (overlay-buffer ov))))
(with-current-buffer dst-buf
(goto-char start)
(delete-region start end)
(insert content)))
;; then remove overlay
(setq eca-rewrite--overlays (delq ov eca-rewrite--overlays))
(delete-overlay ov))
(message "Applied %d rewrite(s)" (length ov-list))))
(defun eca-rewrite--retry (&optional ovs)
"Retry the rewrite with the same instruction for overlays OVS."
(interactive (list (eca-rewrite--overlay-at)))
(let* ((ov (car (ensure-list ovs)))
(start (overlay-start ov))
(end (overlay-end ov))
(original-text (overlay-get ov 'eca-original))
(instruction (overlay-get ov 'eca-instruction)))
;; Remove current overlay
(eca-rewrite--reject ov)
;; Trigger new rewrite with same instruction
(eca-rewrite--send-request start end original-text instruction)
(message "Retrying rewrite with same instruction...")))
(defun eca-rewrite--retry-with-derivative (&optional ovs)
"Retry the rewrite with a derivative instruction for overlays OVS."
(interactive (list (eca-rewrite--overlay-at)))
(let* ((ov (car (ensure-list ovs)))
(start (overlay-start ov))
(end (overlay-end ov))
(original-text (overlay-get ov 'eca-original))
(old-instruction (overlay-get ov 'eca-instruction))
(new-instruction (read-string "New rewrite instruction: "
(format "Try a different approach: %s" old-instruction))))
;; Remove current overlay
(eca-rewrite--reject ov)
;; Trigger new rewrite with modified instruction
(eca-rewrite--send-request start end original-text new-instruction)
(setq eca-rewrite--message new-instruction)
(message "Retrying rewrite with new instruction...")))
(defun eca-rewrite--send-request (start end text instruction)
"Send rewrite request to ECA for TEXT with INSTRUCTION, creating overlay at START to END."
(let ((prompt (format "%s\n\nOriginal:\n%s\n\nInstructions: %s"
eca-rewrite-directive text instruction)))
(eca-api-request-async
(eca-session)
:method "chat/prompt"
:params (list :message prompt :chatId nil :contexts [])
:success-callback
(lambda (res)
(when-let ((content (plist-get res :content)))
(pulse-momentary-highlight-region start end)
(let ((ov (eca-rewrite--setup-overlay start end content text instruction)))
(if-let* ((sym eca-rewrite-default-action))
(if-let* ((action (intern (concat "eca-rewrite--" (symbol-name sym))))
((functionp action)))
(funcall action ov)
(funcall sym ov))
(message "ECA rewrite ready: RET for options")))))
:error-callback
(lambda (err) (message "ECA rewrite error: %s" err)))))
(defun eca-rewrite--diff (&optional ovs switches)
"Show unified diff between original and rewritten text for OVS."
(interactive (list (eca-rewrite--overlay-at)))
(let* ((ov (car (ensure-list ovs)))
(ov-buf (overlay-buffer ov))
(newbuf (eca-rewrite--prepare-buffer ovs))
(diff-buf (diff-no-select ov-buf newbuf switches)))
(with-current-buffer diff-buf
(setq-local diff-jump-to-old-file t))
(display-buffer diff-buf)))
(defun eca-rewrite--ediff (&optional ovs)
"Launch Ediff session between original and rewritten text for OVS."
(interactive (list (eca-rewrite--overlay-at)))
(let ((ov-buf (overlay-buffer (car (ensure-list ovs))))
(newbuf (eca-rewrite--prepare-buffer ovs))
(orig-win (current-window-configuration)))
(let ((ediff-window-setup-function #'ediff-setup-windows-plain)
(ediff-split-window-function #'split-window-horizontally))
(ediff-buffers ov-buf newbuf)
(add-hook 'ediff-quit-hook
(lambda ()
(set-window-configuration orig-win)
(remove-hook 'ediff-quit-hook #'this-function))
nil t))))
(defun eca-rewrite--dispatch (&optional ov _ci)
"Prompt user to choose action for overlay OV."
(interactive (list (eca-rewrite--overlay-at) t))
(let* ((choices '((?a "accept") (?k "reject")
(?d "diff") (?e "ediff")
(?m "merge") (?r "iterate")
(?t "retry") (?y "retry-derivative")))
(prompt "Action for rewrite: ")
(key (read-multiple-choice prompt choices)))
(pcase (cadr key)
("accept") (eca-rewrite--accept ov)
("reject") (eca-rewrite--reject ov)
("diff") (eca-rewrite--diff ov)
("ediff") (eca-rewrite--ediff ov)
("merge") (eca-rewrite--merge ov)
("iterate") (call-interactively #'eca-rewrite)
("retry") (eca-rewrite--retry ov)
("retry-derivative") (eca-rewrite--retry-with-derivative ov)
(_ (user-error "Unknown action")))))
(defun eca-rewrite--prepare-buffer (ovs &optional buf)
"Helper to copy BUF (or current) and apply accept to overlays OVS."
(setq buf (or buf (overlay-buffer (car (ensure-list ovs)))))
(with-current-buffer buf
(let ((min (point-min)) (max (point-max))
(pt (point))
(newb (get-buffer-create "*eca-rewrite-diff*")))
(save-restriction (widen)
(with-current-buffer newb
(erase-buffer)
(insert-buffer-substring buf)))
(with-current-buffer newb
(narrow-to-region min max)
(goto-char pt)
(eca-rewrite--accept ovs newb))
newb)))
(defun eca-rewrite--merge-simple (start end content)
"Insert simple conflict markers between START and END around CONTENT."
(goto-char end)
(insert "=======\n" content "\n>>>>>>> ECA-rewrite\n")
(goto-char start)
(insert "<<<<<<< original\n"))
(defun eca-rewrite--merge (&optional ovs)
"Insert merge conflict markers for overlays OVS."
(interactive (list (eca-rewrite--overlay-at)))
(dolist (ov (ensure-list ovs))
(let ((start (overlay-start ov))
(end (overlay-end ov))
(cont (overlay-get ov 'eca-rewrite)))
(setq eca-rewrite--overlays (delq ov eca-rewrite--overlays))
(delete-overlay ov)
(eca-rewrite--merge-simple start end cont)))
(when (fboundp 'smerge-mode) (smerge-mode 1)))
;;;###autoload
(defun eca-rewrite (instruction)
"Smart rewrite command:
• If on an existing rewrite overlay, re-iterate
• Else if region active, rewrite that region
• Else try to detect defun/paragraph boundaries
INSTRUCTION is the prompt for the LLM."
(interactive
(list (read-string "Rewrite instruction: "
(or eca-rewrite--message "Improve this text: "))))
(unless (eca-session) (user-error "ECA session not active"))
(let* ((existing (ignore-errors (eca-rewrite--overlay-at)))
(start (cond (existing (overlay-start existing))
((use-region-p) (region-beginning))
(t (or (car (bounds-of-thing-at-point 'defun))
(car (bounds-of-thing-at-point 'paragraph))
(user-error "No region and no overlay")))))
(end (cond (existing (overlay-end existing))
((use-region-p) (region-end))
(t (or (cdr (bounds-of-thing-at-point 'defun))
(cdr (bounds-of-thing-at-point 'paragraph))
start))))
(text (if existing
(overlay-get existing 'eca-original)
(buffer-substring-no-properties start end))))
(when existing (eca-rewrite--reject existing))
(eca-rewrite--send-request start end text instruction)
(eca-rewrite--move-cursor-back start end)
(setq eca-rewrite--message instruction)))
(provide 'eca-rewrite)
;;; eca-rewrite.el ends here
@CsBigDataHub nice!
Not sure I got how to use that, I tried, it sent sometimes the mesasge to the chat (others it doesn't send for some reason), and it didn't do anything with the LLM response, is that intended?
Please try this -
;;; eca-rewrite.el --- ECA (Editor Code Assistant) rewrite -*- lexical-binding: t; -*-
;; Copyright (C) 2025 Eric Dallo
;;
;; SPDX-License-Identifier: Apache-2.0
;;
;;; Commentary:
;; Provides region-based text rewriting via ECA's LLM, separate from chat.
;;; Code:
(require 'cl-lib)
(require 'eca-util)
(require 'eca-api)
(declare-function diff-no-select "diff")
(declare-function ediff-setup-windows-plain "ediff-wind")
(declare-function smerge-mode "smerge-mode")
;; * User options
(defcustom eca-rewrite-default-action nil
"Action to take when rewriting a text region using ECA.
Choices: nil (wait for explicit), accept, merge, diff, ediff, dispatch, or custom function."
:group 'eca
:type '(choice
(const :tag "Wait" nil)
(const :tag "Accept rewrite" accept)
(const :tag "Merge with conflicts" merge)
(const :tag "Diff" diff)
(const :tag "Ediff" ediff)
(const :tag "Dispatch menu" dispatch)
(function :tag "Custom action")))
(defcustom eca-rewrite-directive
"You are an expert programmer and editor. Follow my instructions and improve or rewrite the text I provide. Generate ONLY the replacement text, without any explanation or Markdown fences."
"System prompt for rewrite operations."
:group 'eca
:type 'string)
(defface eca-rewrite-highlight-face
'((((class color) (min-colors 88) (background dark))
:background "#041714" :extend t)
(((class color) (min-colors 88) (background light))
:background "light goldenrod yellow" :extend t)
(t :inherit secondary-selection))
"Face to highlight pending rewrite regions."
:group 'eca)
;; * Internal variables
(defvar-keymap eca-rewrite-actions-map
:doc "Keymap for rewrite overlay actions."
"RET" #'eca-rewrite--dispatch
"<return>" #'eca-rewrite--dispatch
"C-c C-a" #'eca-rewrite--accept
"C-c C-k" #'eca-rewrite--reject
"C-c C-d" #'eca-rewrite--diff
"C-c C-e" #'eca-rewrite--ediff
"C-c C-m" #'eca-rewrite--merge
"C-c C-r" #'eca-rewrite ;; iterate
"C-c C-t" #'eca-rewrite--retry
"C-c C-y" #'eca-rewrite--retry-with-derivative
"C-c C-n" #'eca-rewrite--next
"C-c C-p" #'eca-rewrite--previous)
(defvar-local eca-rewrite--overlays nil
"Active rewrite overlays in this buffer.")
(defvar-local eca-rewrite--message nil
"Last rewrite instruction used.")
(defvar-local eca-rewrite--temp-chat-id nil
"Temporary chat ID for rewrite operations.")
;; * Helper functions
(defun eca-rewrite--move (search-func)
"Move to next/previous rewrite overlay using SEARCH-FUNC."
(let* ((ov (cdr (get-char-property-and-overlay (point) 'eca-rewrite)))
(pos (funcall search-func (if ov (overlay-start ov) (point))
'eca-rewrite)))
(if (get-char-property pos 'eca-rewrite)
(goto-char pos)
(user-error "No further rewrite regions"))))
(defun eca-rewrite--next () (interactive) (eca-rewrite--move #'next-single-char-property-change))
(defun eca-rewrite--previous () (interactive) (eca-rewrite--move #'previous-single-char-property-change))
(defun eca-rewrite--overlay-at (&optional pt)
"Return the rewrite overlay and its content at PT or point."
(pcase-let ((`(,content . ,ov)
(get-char-property-and-overlay (or pt (point)) 'eca-rewrite)))
(unless ov (user-error "No rewrite overlay here"))
(unless content (user-error "No LLM output for this overlay"))
ov))
(defun eca-rewrite--setup-overlay (start end content &optional original-text instruction)
"Create an overlay from START to END with CONTENT and return it.
ORIGINAL-TEXT and INSTRUCTION are stored for retry operations."
(let ((ov (make-overlay start end nil t)))
(overlay-put ov 'category 'eca-rewrite)
(overlay-put ov 'evaporate t)
(overlay-put ov 'eca-rewrite content)
(overlay-put ov 'eca-original (or original-text
(buffer-substring-no-properties start end)))
(overlay-put ov 'eca-instruction (or instruction eca-rewrite--message))
(overlay-put ov 'face 'eca-rewrite-highlight-face)
(overlay-put ov 'priority 2000)
(overlay-put ov 'keymap eca-rewrite-actions-map)
(overlay-put ov 'mouse-face 'highlight)
(overlay-put ov 'help-echo "ECA rewrite: RET for options")
(push ov eca-rewrite--overlays)
ov))
(defun eca-rewrite--move-cursor-back (start end)
"Move cursor back into the overlay region if at END."
(when (= (point) end) (backward-char 1))
(deactivate-mark))
(defun eca-rewrite--reject (&optional ovs)
"Delete overlays in OVS (or at point), clearing pending rewrites."
(interactive (list (eca-rewrite--overlay-at)))
(dolist (ov (ensure-list ovs))
(setq eca-rewrite--overlays (delq ov eca-rewrite--overlays))
(delete-overlay ov))
(message "Cleared rewrite overlay(s)"))
(defun eca-rewrite--accept (&optional ovs buf)
"Replace the original text with LLM CONTENT for overlays OVS.
If BUF is provided, apply there; otherwise use the overlay's buffer."
(interactive (list (eca-rewrite--overlay-at)))
(let ((ov-list (ensure-list ovs)))
(dolist (ov ov-list)
(let* ((content (overlay-get ov 'eca-rewrite))
(start (overlay-start ov))
(end (overlay-end ov))
(dst-buf (or buf (overlay-buffer ov))))
(with-current-buffer dst-buf
(goto-char start)
(delete-region start end)
(insert content)))
;; then remove overlay
(setq eca-rewrite--overlays (delq ov eca-rewrite--overlays))
(delete-overlay ov))
(message "Applied %d rewrite(s)" (length ov-list))))
(defun eca-rewrite--retry (&optional ovs)
"Retry the rewrite with the same instruction for overlays OVS."
(interactive (list (eca-rewrite--overlay-at)))
(let* ((ov (car (ensure-list ovs)))
(start (overlay-start ov))
(end (overlay-end ov))
(original-text (overlay-get ov 'eca-original))
(instruction (overlay-get ov 'eca-instruction)))
;; Remove current overlay
(eca-rewrite--reject ov)
;; Trigger new rewrite with same instruction
(eca-rewrite--send-request start end original-text instruction)
(message "Retrying rewrite with same instruction...")))
(defun eca-rewrite--retry-with-derivative (&optional ovs)
"Retry the rewrite with a derivative instruction for overlays OVS."
(interactive (list (eca-rewrite--overlay-at)))
(let* ((ov (car (ensure-list ovs)))
(start (overlay-start ov))
(end (overlay-end ov))
(original-text (overlay-get ov 'eca-original))
(old-instruction (overlay-get ov 'eca-instruction))
(new-instruction (read-string "New rewrite instruction: "
(format "Try a different approach: %s" old-instruction))))
;; Remove current overlay
(eca-rewrite--reject ov)
;; Trigger new rewrite with modified instruction
(eca-rewrite--send-request start end original-text new-instruction)
(setq eca-rewrite--message new-instruction)
(message "Retrying rewrite with new instruction...")))
(defun eca-rewrite--create-temp-chat ()
"Create a temporary chat session for rewrite operations."
(unless eca-rewrite--temp-chat-id
;; Send a request to create a new temporary chat
(let ((response (eca-api-request-sync
(eca-session)
:method "chat/prompt"
:params (list :message "temp"
:chatId nil
:contexts []))))
(setq eca-rewrite--temp-chat-id (plist-get response :chatId))))
eca-rewrite--temp-chat-id)
(defun eca-rewrite--handle-content-received (session params buffer start end original-text instruction)
"Handle content received for rewrite operations."
(let* ((role (plist-get params :role))
(content (plist-get params :content))
(content-type (plist-get content :type))
(text (plist-get content :text)))
(when (and (string= role "assistant")
(string= content-type "text")
text
(buffer-live-p buffer))
(with-current-buffer buffer
(let ((ov (eca-rewrite--setup-overlay start end text original-text instruction)))
(pulse-momentary-highlight-region start end)
(if-let* ((sym eca-rewrite-default-action))
(if-let* ((action (intern (concat "eca-rewrite--" (symbol-name sym))))
((functionp action)))
(funcall action ov)
(funcall sym ov))
(message "ECA rewrite ready: RET for options")))))))
(defun eca-rewrite--send-request (start end text instruction)
"Send rewrite request to ECA for TEXT with INSTRUCTION, creating overlay at START to END."
(let* ((session (eca-session))
(buffer (current-buffer))
(prompt (format "%s\n\nOriginal text:\n%s\n\nInstructions: %s"
eca-rewrite-directive text instruction))
(chat-id (eca-rewrite--create-temp-chat)))
;; Set up a temporary content handler for this rewrite
(let ((original-handler (symbol-function 'eca-chat-content-received)))
(fset 'eca-chat-content-received
(lambda (session params)
(if (string= (plist-get params :chatId) chat-id)
;; This is our rewrite response
(eca-rewrite--handle-content-received session params buffer start end text instruction)
;; Pass through to original handler for regular chat
(funcall original-handler session params))))
;; Send the rewrite request
(eca-api-request-async
session
:method "chat/prompt"
:params (list :message prompt
:chatId chat-id
:contexts [])
:success-callback
(lambda (response)
;; The actual response will come via content-received
(message "ECA rewrite request sent..."))
:error-callback
(lambda (error)
;; Restore original handler on error
(fset 'eca-chat-content-received original-handler)
(message "ECA rewrite error: %s" error))))))
(defun eca-rewrite--diff (&optional ovs switches)
"Show unified diff between original and rewritten text for OVS."
(interactive (list (eca-rewrite--overlay-at)))
(let* ((ov (car (ensure-list ovs)))
(ov-buf (overlay-buffer ov))
(newbuf (eca-rewrite--prepare-buffer ovs))
(diff-buf (diff-no-select ov-buf newbuf switches)))
(with-current-buffer diff-buf
(setq-local diff-jump-to-old-file t))
(display-buffer diff-buf)))
(defun eca-rewrite--ediff (&optional ovs)
"Launch Ediff session between original and rewritten text for OVS."
(interactive (list (eca-rewrite--overlay-at)))
(let ((ov-buf (overlay-buffer (car (ensure-list ovs))))
(newbuf (eca-rewrite--prepare-buffer ovs))
(orig-win (current-window-configuration)))
(let ((ediff-window-setup-function #'ediff-setup-windows-plain)
(ediff-split-window-function #'split-window-horizontally))
(ediff-buffers ov-buf newbuf)
(add-hook 'ediff-quit-hook
(lambda ()
(set-window-configuration orig-win)
(remove-hook 'ediff-quit-hook #'this-function))
nil t))))
(defun eca-rewrite--dispatch (&optional ov _ci)
"Prompt user to choose action for overlay OV."
(interactive (list (eca-rewrite--overlay-at) t))
(let* ((choices '((?a "accept") (?k "reject")
(?d "diff") (?e "ediff")
(?m "merge") (?r "iterate")
(?t "retry") (?y "retry-derivative")))
(prompt "Action for rewrite: ")
(key (read-multiple-choice prompt choices)))
(pcase (cadr key)
("accept") (eca-rewrite--accept ov)
("reject") (eca-rewrite--reject ov)
("diff") (eca-rewrite--diff ov)
("ediff") (eca-rewrite--ediff ov)
("merge") (eca-rewrite--merge ov)
("iterate") (call-interactively #'eca-rewrite)
("retry") (eca-rewrite--retry ov)
("retry-derivative") (eca-rewrite--retry-with-derivative ov)
(_ (user-error "Unknown action")))))
(defun eca-rewrite--prepare-buffer (ovs &optional buf)
"Helper to copy BUF (or current) and apply accept to overlays OVS."
(setq buf (or buf (overlay-buffer (car (ensure-list ovs)))))
(with-current-buffer buf
(let ((min (point-min)) (max (point-max))
(pt (point))
(newb (get-buffer-create "*eca-rewrite-diff*")))
(save-restriction (widen)
(with-current-buffer newb
(erase-buffer)
(insert-buffer-substring buf)))
(with-current-buffer newb
(narrow-to-region min max)
(goto-char pt)
(eca-rewrite--accept ovs newb))
newb)))
(defun eca-rewrite--merge-simple (start end content)
"Insert simple conflict markers between START and END around CONTENT."
(goto-char end)
(insert "=======\n" content "\n>>>>>>> ECA-rewrite\n")
(goto-char start)
(insert "<<<<<<< original\n"))
(defun eca-rewrite--merge (&optional ovs)
"Insert merge conflict markers for overlays OVS."
(interactive (list (eca-rewrite--overlay-at)))
(dolist (ov (ensure-list ovs))
(let ((start (overlay-start ov))
(end (overlay-end ov))
(cont (overlay-get ov 'eca-rewrite)))
(setq eca-rewrite--overlays (delq ov eca-rewrite--overlays))
(delete-overlay ov)
(eca-rewrite--merge-simple start end cont)))
(when (fboundp 'smerge-mode) (smerge-mode 1)))
;;;###autoload
(defun eca-rewrite (instruction)
"Smart rewrite command:
• If on an existing rewrite overlay, re-iterate
• Else if region active, rewrite that region
• Else try to detect defun/paragraph boundaries
INSTRUCTION is the prompt for the LLM."
(interactive
(list (read-string "Rewrite instruction: "
(or eca-rewrite--message "Improve this text: "))))
(unless (eca-session)
(user-error "ECA session not active. Run `eca' first"))
(let* ((existing (ignore-errors (eca-rewrite--overlay-at)))
(start (cond (existing (overlay-start existing))
((use-region-p) (region-beginning))
(t (or (car (bounds-of-thing-at-point 'defun))
(car (bounds-of-thing-at-point 'paragraph))
(user-error "No region and no overlay")))))
(end (cond (existing (overlay-end existing))
((use-region-p) (region-end))
(t (or (cdr (bounds-of-thing-at-point 'defun))
(cdr (bounds-of-thing-at-point 'paragraph))
start))))
(text (if existing
(overlay-get existing 'eca-original)
(buffer-substring-no-properties start end))))
(when existing (eca-rewrite--reject existing))
(eca-rewrite--send-request start end text instruction)
(eca-rewrite--move-cursor-back start end)
(setq eca-rewrite--message instruction)))
(provide 'eca-rewrite)
;;; eca-rewrite.el ends here
How It Works Now:
- Creates Temporary Chat: Uses
eca-rewrite--create-temp-chat()to get a valid chat ID separate from main chat - Intercepts Content Stream: Temporarily hooks into
eca-chat-content-receivedto catch rewrite responses - Filters by Chat ID: Only processes content for the temporary rewrite chat, passes everything else to main chat
- Creates Overlays: When rewrite content arrives, creates overlay with the result
- Interactive Actions: RET brings up dispatch menu with accept/reject/diff/retry options
User Experience:
;; Select some code
(mark-defun) ; or any region
M-x eca-rewrite RET
"Make this more efficient" RET
;; No message appears in main chat
;; Overlay appears on selected region with rewritten code
;; RET on overlay shows: a)ccept, k)reject, d)iff, t)retry, etc.
Key Fixes:
- Proper ECA Integration: Now works with ECA's actual streaming API
- Isolated from Chat: Uses separate chat ID so rewrite requests don't pollute main chat
- Real-time Overlays: Creates overlays immediately when LLM responds
- Retry Support: Both same-instruction retry and derivative retry work correctly
you should now see proper overlay-based rewriting that doesn't interfere with their main ECA chat session!
@CsBigDataHub sorry for the delay, was focusing on other issues, some points:
- the overlay shows up but when choosing any of the options after pressing RET it does nothing.
- I can't cancel the overlay, maybe because of ☝🏻
- the overlay doesn't show the new code, tested with multiple functions or rewrites
- But now I have a overall idea of the user XP, I liked it so we can think how to support that with protocol messages, the arch right now is no good chainging into exising chat, we should not couple to chat feature IMO.
- Also, would be nice to look like gptel when writing the changes, I could not check that as the overlay apply is not working too.
@CsBigDataHub I started to implement this using your idea + gptel focusing on the best UX I can think and so far so good! Soon I should merge this rewrite branch, thanks for the help so far, helped a lot!
Done! 🎉 @CsBigDataHub I took some time to implement a protocol message for that, now it's smoother and extensible. I implemented in emacs and will work on other editors, but looks like this: