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:
parent
2ee5430c45
commit
420037796f
@ -457,23 +457,34 @@ PROMPT is an optional custom confirmation message."
|
||||
(if (get-buffer buffer)
|
||||
(with-current-buffer buffer
|
||||
(save-excursion
|
||||
(goto-char (point-min))
|
||||
(let ((count 0)
|
||||
(start-pos (point-min)))
|
||||
(while (search-forward original nil t)
|
||||
(setq count (1+ count))
|
||||
(when (= count 1)
|
||||
(setq start-pos (match-beginning 0))))
|
||||
(cond
|
||||
((= count 0)
|
||||
(format "Error: Could not find the original text in buffer %s" buffer))
|
||||
((> count 1)
|
||||
(format "Error: Found %d instances of the text in buffer %s" count buffer))
|
||||
(t
|
||||
(goto-char start-pos)
|
||||
(delete-region start-pos (+ start-pos (length original)))
|
||||
(insert replacement)
|
||||
(format "Successfully edited buffer %s" buffer))))))
|
||||
(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))
|
||||
(let ((count 0)
|
||||
(start-pos (point-min)))
|
||||
(while (search-forward original nil t)
|
||||
(setq count (1+ count))
|
||||
(when (= count 1)
|
||||
(setq start-pos (match-beginning 0))))
|
||||
(cond
|
||||
((= count 0)
|
||||
(format "Error: Could not find the original text in buffer %s" buffer))
|
||||
((> count 1)
|
||||
(format "Error: Found %d instances of the text in buffer %s" count buffer))
|
||||
(t
|
||||
(goto-char start-pos)
|
||||
(delete-region start-pos (+ start-pos (length original)))
|
||||
(insert replacement)
|
||||
(format "Successfully edited buffer %s" buffer))))))))
|
||||
(format "Error: Buffer %s does not exist" buffer)))
|
||||
:description "Replace specific text in a buffer with new text"
|
||||
: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
|
||||
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.
|
||||
|
||||
Respond concisely.
|
||||
|
Loading…
Reference in New Issue
Block a user