Fix edit_buffer handling of empty buffers/strings

Handle special case when editing an empty buffer or replacing an empty string in a non-empty buffer to avoid invalid replacements.
This commit is contained in:
Jeremy Dormitzer 2025-04-01 18:57:39 +00:00
parent 2ee5430c45
commit 420037796f

View File

@ -457,6 +457,17 @@ PROMPT is an optional custom confirmation message."
(if (get-buffer buffer) (if (get-buffer buffer)
(with-current-buffer buffer (with-current-buffer buffer
(save-excursion (save-excursion
(cond
;; Special case: empty buffer and empty original string
((and (string= original "")
(= (buffer-size) 0))
(insert replacement)
(format "Successfully edited buffer %s" buffer))
;; Error case: empty original string but non-empty buffer
((string= original "")
(format "Error: Cannot replace empty string in non-empty buffer %s" buffer))
;; Normal case: non-empty original string
(t
(goto-char (point-min)) (goto-char (point-min))
(let ((count 0) (let ((count 0)
(start-pos (point-min))) (start-pos (point-min)))
@ -473,7 +484,7 @@ PROMPT is an optional custom confirmation message."
(goto-char start-pos) (goto-char start-pos)
(delete-region start-pos (+ start-pos (length original))) (delete-region start-pos (+ start-pos (length original)))
(insert replacement) (insert replacement)
(format "Successfully edited buffer %s" buffer)))))) (format "Successfully edited buffer %s" buffer))))))))
(format "Error: Buffer %s does not exist" buffer))) (format "Error: Buffer %s does not exist" buffer)))
:description "Replace specific text in a buffer with new text" :description "Replace specific text in a buffer with new text"
:args (list '(:name "buffer" :args (list '(:name "buffer"
@ -709,6 +720,8 @@ The core workflow for making code changes is as follows:
3. Verify the buffer contents with read_buffer, then make the changes using edit_buffer 3. Verify the buffer contents with read_buffer, then make the changes using edit_buffer
4. Write the changes back to the file using write_buffer 4. Write the changes back to the file using write_buffer
ALWAYS CHECK THE BUFFER CONTENTS BEFORE MAKING CHANGES. Otherwise you may call the edit_buffer tool with invalid arguments.
Remember to always let the user review changes before you make them, and provide a summary of any changes made afterwards. Remember to always let the user review changes before you make them, and provide a summary of any changes made afterwards.
Respond concisely. Respond concisely.