-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopilot-diff.el
More file actions
523 lines (459 loc) · 20.3 KB
/
Copy pathcopilot-diff.el
File metadata and controls
523 lines (459 loc) · 20.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
;;; copilot-diff.el --- Diff preview mode for Copilot Emacs AI OS -*- lexical-binding: t; -*-
;; Copyright (C) 2026 Contributors
;; SPDX-License-Identifier: MIT
;;; Commentary:
;; Provides a diff preview step for Copilot agent edits. When enabled,
;; buffer edits proposed by the agent are shown in a side-window diff
;; buffer instead of being applied directly. The user can then accept,
;; reject, or manually edit the change.
;;
;; Entry points:
;; `copilot-diff-show' — preview a single edit
;; `copilot-diff-show-multi' — preview multiple hunks at once
;; `copilot-diff-wrap-edit' — drop-in wrapper for `copilot-emacs-tools--buffer-edit'
;;
;; Enable with:
;; (setq copilot-diff-preview-enabled t) ; default
;;
;; Keybindings in the diff buffer:
;; C-c C-c / a — accept the proposed change
;; C-c C-k / r — reject (discard) the change
;; e — open target buffer at the change location
;; n / p — next / previous hunk (multi-hunk)
;; q — same as reject
;;; Code:
(require 'cl-lib)
(require 'copilot-sdk-tools)
;;; ============================================================
;;; Customization
;;; ============================================================
(defgroup copilot-diff nil
"Diff preview for Copilot agent edits."
:group 'copilot
:prefix "copilot-diff-")
(defcustom copilot-diff-preview-enabled t
"When non-nil, buffer edits go through a diff preview before applying."
:type 'boolean
:group 'copilot-diff)
(defcustom copilot-diff-auto-accept-timeout nil
"Seconds before auto-accepting a proposed change.
When nil, changes wait indefinitely for user action."
:type '(choice (const :tag "Disabled" nil)
(number :tag "Seconds"))
:group 'copilot-diff)
(defcustom copilot-diff-context-lines 3
"Number of context lines to show around the changed region."
:type 'natnum
:group 'copilot-diff)
;;; ============================================================
;;; Faces
;;; ============================================================
(defface copilot-diff-added
'((((class color) (background dark))
:background "#1a3a1a" :extend t)
(((class color) (background light))
:background "#ccffcc" :extend t)
(t :underline t))
"Face for added (new) text in the diff preview."
:group 'copilot-diff)
(defface copilot-diff-removed
'((((class color) (background dark))
:background "#3a1a1a" :extend t)
(((class color) (background light))
:background "#ffcccc" :extend t)
(t :strike-through t))
"Face for removed (old) text in the diff preview."
:group 'copilot-diff)
(defface copilot-diff-context
'((((class color) (background dark))
:foreground "#888888" :extend t)
(((class color) (background light))
:foreground "#666666" :extend t)
(t :italic t))
"Face for context lines surrounding the change."
:group 'copilot-diff)
(defface copilot-diff-header
'((t :weight bold :height 1.1))
"Face for the diff header section."
:group 'copilot-diff)
;;; ============================================================
;;; Buffer-local state
;;; ============================================================
(defvar-local copilot-diff--buffer-name nil
"Name of the target buffer for the current diff.")
(defvar-local copilot-diff--on-accept nil
"Callback (0-arg) invoked when the user accepts the change.")
(defvar-local copilot-diff--on-reject nil
"Callback (0-arg) invoked when the user rejects the change.")
(defvar-local copilot-diff--hunks nil
"List of hunk plists for multi-hunk diffs.
Each hunk is (:buffer-name NAME :old-text OLD :new-text NEW :accepted nil).")
(defvar-local copilot-diff--on-accept-all nil
"Callback for accepting all hunks in a multi-hunk diff.")
(defvar-local copilot-diff--on-reject-all nil
"Callback for rejecting all hunks in a multi-hunk diff.")
(defvar-local copilot-diff--auto-timer nil
"Timer for auto-accept timeout, if any.")
(defvar-local copilot-diff--change-position nil
"Position (marker) of the old text in the target buffer.")
;;; ============================================================
;;; Keymap
;;; ============================================================
(defvar copilot-diff-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "C-c C-c") #'copilot-diff-accept)
(define-key map (kbd "a") #'copilot-diff-accept)
(define-key map (kbd "C-c C-k") #'copilot-diff-reject)
(define-key map (kbd "r") #'copilot-diff-reject)
(define-key map (kbd "e") #'copilot-diff-edit)
(define-key map (kbd "n") #'copilot-diff-next-hunk)
(define-key map (kbd "p") #'copilot-diff-prev-hunk)
(define-key map (kbd "q") #'copilot-diff-reject)
map)
"Keymap for `copilot-diff-mode'.")
;;; ============================================================
;;; Major mode
;;; ============================================================
(define-derived-mode copilot-diff-mode special-mode "Copilot-Diff"
"Major mode for reviewing proposed Copilot edits.
\\<copilot-diff-mode-map>
\\[copilot-diff-accept]\tAccept the proposed change.
\\[copilot-diff-reject]\tReject (discard) the proposed change.
\\[copilot-diff-edit]\tOpen the target buffer at the change location.
\\[copilot-diff-next-hunk]\tMove to the next hunk.
\\[copilot-diff-prev-hunk]\tMove to the previous hunk."
:group 'copilot-diff
(setq buffer-read-only t)
(setq truncate-lines t))
;;; ============================================================
;;; Internal helpers
;;; ============================================================
(defun copilot-diff--make-buffer-name (target-name)
"Return the diff buffer name for TARGET-NAME."
(format "*Copilot Diff: %s*" target-name))
(defun copilot-diff--separator ()
"Return a heavy separator line."
(make-string 55 ?═))
(defun copilot-diff--thin-separator (label)
"Return a thin separator with LABEL."
(concat "── " label " " (make-string (max 0 (- 50 (length label))) ?─)))
(defun copilot-diff--extract-context (buf text n-lines)
"Extract N-LINES of context around TEXT in BUF.
Returns (BEFORE-LINES . AFTER-LINES) as strings, or (nil . nil)
if the text is not found."
(if (not (buffer-live-p buf))
(cons nil nil)
(with-current-buffer buf
(save-excursion
(goto-char (point-min))
(if (not (search-forward text nil t))
(cons nil nil)
(let* ((match-start (match-beginning 0))
(match-end (match-end 0))
;; Before context
(before-start (save-excursion
(goto-char match-start)
(forward-line (- n-lines))
(point)))
(before-text (buffer-substring-no-properties
before-start match-start))
;; After context
(after-end (save-excursion
(goto-char match-end)
(forward-line n-lines)
(line-end-position)))
(after-text (buffer-substring-no-properties
match-end after-end)))
(cons (if (string-empty-p before-text) nil before-text)
(if (string-empty-p after-text) nil after-text))))))))
(defun copilot-diff--insert-propertized (text face)
"Insert TEXT with FACE applied to the entire region."
(let ((start (point)))
(insert text)
;; Ensure trailing newline
(unless (string-suffix-p "\n" text)
(insert "\n"))
(put-text-property start (point) 'face face)))
(defun copilot-diff--render-single (_buffer-name old-text new-text target-buf)
"Render a single hunk for BUFFER-NAME showing OLD-TEXT → NEW-TEXT.
TARGET-BUF is the live target buffer (or nil). Point is at the
insertion location in the diff buffer."
(let* ((ctx (if target-buf
(copilot-diff--extract-context
target-buf old-text copilot-diff-context-lines)
(cons nil nil)))
(before-ctx (car ctx))
(after-ctx (cdr ctx))
(inhibit-read-only t))
;; Removed section
(insert "\n")
(copilot-diff--insert-propertized
(copilot-diff--thin-separator "Removed") 'copilot-diff-header)
(copilot-diff--insert-propertized (concat " " old-text) 'copilot-diff-removed)
(insert "\n")
;; Added section
(copilot-diff--insert-propertized
(copilot-diff--thin-separator "Added") 'copilot-diff-header)
(copilot-diff--insert-propertized (concat " " new-text) 'copilot-diff-added)
(insert "\n")
;; Context section
(when (or before-ctx after-ctx)
(copilot-diff--insert-propertized
(copilot-diff--thin-separator "Context") 'copilot-diff-header)
(when before-ctx
(copilot-diff--insert-propertized
(concat " " (string-trim-right before-ctx)) 'copilot-diff-context)
(insert "\n"))
(copilot-diff--insert-propertized " <<<change>>>" 'copilot-diff-context)
(when after-ctx
(copilot-diff--insert-propertized
(concat " " (string-trim-left after-ctx)) 'copilot-diff-context)))
(insert "\n")))
(defun copilot-diff--set-mode-line (filename)
"Set the mode line to show diff info for FILENAME."
(setq mode-line-format
(list " "
(propertize
(format "[Diff: %s — C-c C-c accept, C-c C-k reject]" filename)
'face 'copilot-diff-header))))
(defun copilot-diff--record-change-position (target-buf old-text)
"Record the position of OLD-TEXT in TARGET-BUF as a marker."
(when (buffer-live-p target-buf)
(with-current-buffer target-buf
(save-excursion
(goto-char (point-min))
(when (search-forward old-text nil t)
(let ((m (copy-marker (match-beginning 0))))
m))))))
(defun copilot-diff--start-auto-timer ()
"Start the auto-accept timer if `copilot-diff-auto-accept-timeout' is set."
(when (and copilot-diff-auto-accept-timeout
(numberp copilot-diff-auto-accept-timeout)
(> copilot-diff-auto-accept-timeout 0))
(setq copilot-diff--auto-timer
(run-with-timer copilot-diff-auto-accept-timeout nil
(let ((buf (current-buffer)))
(lambda ()
(when (buffer-live-p buf)
(with-current-buffer buf
(copilot-diff-accept)))))))))
(defun copilot-diff--cancel-auto-timer ()
"Cancel the auto-accept timer if running."
(when copilot-diff--auto-timer
(cancel-timer copilot-diff--auto-timer)
(setq copilot-diff--auto-timer nil)))
(defun copilot-diff--cleanup ()
"Cancel timers and kill the current diff buffer."
(copilot-diff--cancel-auto-timer)
(let ((buf (current-buffer))
(win (get-buffer-window (current-buffer))))
(when (and win (window-live-p win))
(quit-window t win))
(when (buffer-live-p buf)
(kill-buffer buf))))
;;; ============================================================
;;; Hunk navigation
;;; ============================================================
(defun copilot-diff--hunk-positions ()
"Return a sorted list of hunk header positions in the current buffer."
(let (positions)
(save-excursion
(goto-char (point-min))
(while (re-search-forward "^── Removed ─" nil t)
(push (match-beginning 0) positions)))
(nreverse positions)))
(defun copilot-diff-next-hunk ()
"Move point to the next hunk header."
(interactive)
(let ((positions (copilot-diff--hunk-positions))
(here (point))
target)
(setq target (cl-find-if (lambda (p) (> p here)) positions))
(if target
(goto-char target)
(message "No more hunks."))))
(defun copilot-diff-prev-hunk ()
"Move point to the previous hunk header."
(interactive)
(let ((positions (copilot-diff--hunk-positions))
(here (point))
target)
(setq target (cl-find-if (lambda (p) (< p here)) (reverse positions)))
(if target
(goto-char target)
(message "No previous hunks."))))
;;; ============================================================
;;; Core public API — single hunk
;;; ============================================================
(defun copilot-diff-show (buffer-name old-text new-text on-accept on-reject)
"Show a diff preview for a proposed edit.
BUFFER-NAME is the name of the target buffer.
OLD-TEXT is the text to be replaced.
NEW-TEXT is the replacement text.
ON-ACCEPT is a 0-arg callback invoked when the user accepts.
ON-REJECT is a 0-arg callback invoked when the user rejects.
The diff is displayed in a side window at the bottom of the frame."
(let* ((diff-name (copilot-diff--make-buffer-name buffer-name))
(target-buf (get-buffer buffer-name))
(diff-buf (get-buffer-create diff-name))
(change-pos (copilot-diff--record-change-position target-buf old-text)))
(with-current-buffer diff-buf
(let ((inhibit-read-only t))
(erase-buffer)
;; Header
(copilot-diff--insert-propertized (copilot-diff--separator) 'copilot-diff-header)
(copilot-diff--insert-propertized
(format " Proposed Change: %s" buffer-name) 'copilot-diff-header)
(copilot-diff--insert-propertized
" C-c C-c to accept │ C-c C-k to reject │ e to edit"
'copilot-diff-header)
(copilot-diff--insert-propertized (copilot-diff--separator) 'copilot-diff-header)
;; Body
(copilot-diff--render-single buffer-name old-text new-text target-buf))
;; Activate mode and set state
(copilot-diff-mode)
(setq copilot-diff--buffer-name buffer-name)
(setq copilot-diff--on-accept on-accept)
(setq copilot-diff--on-reject on-reject)
(setq copilot-diff--change-position change-pos)
(copilot-diff--set-mode-line buffer-name)
(goto-char (point-min))
(copilot-diff--start-auto-timer))
;; Display in side window
(display-buffer-in-side-window diff-buf
'((side . bottom)
(slot . 0)
(window-height . 0.35)
(preserve-size . (nil . t))))
diff-buf))
;;; ============================================================
;;; Core public API — multi hunk
;;; ============================================================
(defun copilot-diff-show-multi (hunks on-accept-all on-reject-all)
"Show a multi-hunk diff preview.
HUNKS is a list of plists, each with keys:
:buffer-name — target buffer name
:old-text — text to replace
:new-text — replacement text
ON-ACCEPT-ALL is a 0-arg callback invoked when the user accepts all.
ON-REJECT-ALL is a 0-arg callback invoked when the user rejects all."
(let* ((first-name (or (plist-get (car hunks) :buffer-name) "multiple"))
(diff-name (format "*Copilot Diff: %s (+%d)*" first-name (length hunks)))
(diff-buf (get-buffer-create diff-name)))
(with-current-buffer diff-buf
(let ((inhibit-read-only t))
(erase-buffer)
;; Header
(copilot-diff--insert-propertized (copilot-diff--separator) 'copilot-diff-header)
(copilot-diff--insert-propertized
(format " Proposed Changes: %d hunks" (length hunks))
'copilot-diff-header)
(copilot-diff--insert-propertized
" C-c C-c accept all │ C-c C-k reject all │ n/p navigate hunks"
'copilot-diff-header)
(copilot-diff--insert-propertized (copilot-diff--separator) 'copilot-diff-header)
;; Render each hunk
(let ((idx 0))
(dolist (hunk hunks)
(cl-incf idx)
(let* ((bname (plist-get hunk :buffer-name))
(old (plist-get hunk :old-text))
(new (plist-get hunk :new-text))
(tbuf (get-buffer bname)))
(insert "\n")
(copilot-diff--insert-propertized
(format "━━━ Hunk %d/%d: %s ━━━" idx (length hunks) bname)
'copilot-diff-header)
(copilot-diff--render-single bname old new tbuf)))))
;; Activate mode (kills locals), then set state
(copilot-diff-mode)
(setq copilot-diff--buffer-name first-name)
(setq copilot-diff--hunks hunks)
(setq copilot-diff--on-accept-all on-accept-all)
(setq copilot-diff--on-reject-all on-reject-all)
(setq copilot-diff--on-accept on-accept-all)
(setq copilot-diff--on-reject on-reject-all)
(copilot-diff--set-mode-line (format "%s (+%d)" first-name (length hunks)))
(goto-char (point-min))
(copilot-diff--start-auto-timer))
;; Display in side window
(display-buffer-in-side-window diff-buf
'((side . bottom)
(slot . 0)
(window-height . 0.4)
(preserve-size . (nil . t))))
diff-buf))
;;; ============================================================
;;; Interactive commands
;;; ============================================================
(defun copilot-diff-accept ()
"Accept the proposed change and apply it.
Calls the on-accept callback, then kills the diff buffer."
(interactive)
(unless (derived-mode-p 'copilot-diff-mode)
(user-error "Not in a Copilot diff buffer"))
(let ((callback (or copilot-diff--on-accept-all
copilot-diff--on-accept)))
(copilot-diff--cleanup)
(when callback
(funcall callback))
(message "Change accepted.")))
(defun copilot-diff-reject ()
"Reject the proposed change.
Calls the on-reject callback, then kills the diff buffer."
(interactive)
(unless (derived-mode-p 'copilot-diff-mode)
(user-error "Not in a Copilot diff buffer"))
(let ((callback (or copilot-diff--on-reject-all
copilot-diff--on-reject)))
(copilot-diff--cleanup)
(when callback
(funcall callback))
(message "Change rejected.")))
(defun copilot-diff-edit ()
"Open the target buffer at the change location and discard the diff."
(interactive)
(unless (derived-mode-p 'copilot-diff-mode)
(user-error "Not in a Copilot diff buffer"))
(let ((target-name copilot-diff--buffer-name)
(pos copilot-diff--change-position))
(copilot-diff--cleanup)
(let ((buf (get-buffer target-name)))
(if buf
(progn
(pop-to-buffer buf)
(when (and pos (marker-buffer pos))
(goto-char pos))
(message "Editing %s — diff discarded." target-name))
(message "Target buffer %s no longer exists." target-name)))))
;;; ============================================================
;;; Integration hook
;;; ============================================================
(defun copilot-diff-wrap-edit (args)
"Wrap `copilot-emacs-tools--buffer-edit' with diff preview.
ARGS is the tool arguments alist (bufferName, oldText, newText).
When `copilot-diff-preview-enabled' is non-nil and Emacs is running
interactively, the edit is shown in a diff preview buffer instead of
being applied directly. The on-accept callback applies the original
edit.
When preview is disabled or in batch mode, falls through to the
original `copilot-emacs-tools--buffer-edit'."
(if (or (not copilot-diff-preview-enabled)
noninteractive)
;; Bypass: apply directly
(copilot-emacs-tools--buffer-edit args)
;; Preview path
(let* ((buffer-name (alist-get 'bufferName args))
(old-text (alist-get 'oldText args))
(new-text (alist-get 'newText args)))
(copilot-diff-show
buffer-name old-text new-text
;; on-accept: apply the edit
(lambda ()
(copilot-emacs-tools--buffer-edit args))
;; on-reject: no-op
(lambda ()
(message "Edit to %s rejected by user." buffer-name)))
(format "Change proposed — waiting for user review in diff buffer"))))
(provide 'copilot-diff)
;;; copilot-diff.el ends here