Repository navigation
Expand file tree
/
Copy pathaidermacs.el
More file actions
1500 lines (1366 loc) · 68.1 KB
/
Copy pathaidermacs.el
File metadata and controls
1500 lines (1366 loc) · 68.1 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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; aidermacs.el --- AI pair programming with Aider -*- lexical-binding: t; -*-
;; Author: Mingde (Matthew) Zeng <matthewzmd@posteo.net>
;; Version: 1.13
;; Package-Requires: ((emacs "26.1") (transient "0.3.0") (compat "30.0.2.0") (markdown-mode "2.7"))
;; Keywords: ai emacs llm aider ai-pair-programming tools
;; URL: https://github.com/MatthewZMD/aidermacs
;; SPDX-License-Identifier: Apache-2.0
;; This file is not part of GNU Emacs.
;;; Commentary:
;; Aidermacs integrates with Aider (https://aider.chat/) for AI-assisted code
;; modification in Emacs. Aider lets you pair program with LLMs to edit code
;; in your local git repository. It works with both new projects and existing
;; code bases, supporting Claude, DeepSeek, ChatGPT, and can connect to almost
;; any LLM including local models. Think of it as having a helpful coding
;; partner that can understand your code, suggest improvements, fix bugs, and
;; even write new code for you. Whether you're working on a new feature,
;; debugging, or just need help understanding some code, Aidermacs provides an
;; intuitive way to collaborate with AI while staying in your familiar Emacs
;; environment.
;; Originally forked from Kang Tu <tninja@gmail.com>'s Aider.el.
;;; Code:
(require 'compat)
(require 'comint)
(require 'dired)
(require 'project)
(require 'transient)
(require 'vc-git)
(require 'which-func)
(require 'ansi-color)
(require 'cl-lib)
(require 'tramp)
(require 'find-dired)
(require 'aidermacs-backends)
(require 'aidermacs-models)
(require 'aidermacs-output)
(declare-function magit-show-commit "magit-diff")
(declare-function notifications-notify "notifications")
(defgroup aidermacs nil
"AI pair programming with Aider."
:group 'aidermacs)
(defcustom aidermacs-program '("aider-ce" "aider")
"The name or path of the Aider program.
If it is a list, Aidermacs will try each program in order."
:type '(choice string (repeat :tag "Program fallbacks" string)))
(defvar aidermacs--resolved-programs (make-hash-table :test 'equal)
"Hash table of cached resolved Aider program paths keyed by workspace.")
(defvar aidermacs--cached-versions (make-hash-table :test 'equal)
"Hash table of cached aider versions keyed by workspace.")
(defcustom aidermacs-enable-notifications t
"When non-nil, send system notification when aider command completes.
This is useful when aider takes a long time to process and the user
has switched to another application."
:type 'boolean)
(defcustom aidermacs-notify-after-seconds 120
"Minimum seconds elapsed before sending notification on command completion.
Only applies when `aidermacs-enable-notifications' is non-nil."
:type 'integer)
(defvar-local aidermacs--command-start-time nil
"Timestamp when the current command was sent to aider.
Used to determine if notification should be sent when command completes.")
(defun aidermacs--get-cache-key ()
"Generate a unique cache key based on current workspace context.
Returns a string combining the remote connection (if any) and project root."
(let ((remote-prefix (file-remote-p default-directory))
(root (aidermacs-project-root)))
(concat (or remote-prefix "local") "::" root)))
(defun aidermacs-get-program ()
"Resolve and return the path to the Aider program.
The value is cached per-workspace in `aidermacs--resolved-programs`.
It respects `aidermacs-program` which can be a string or a list of strings."
(let* ((key (aidermacs--get-cache-key))
(cached (gethash key aidermacs--resolved-programs)))
(or cached
(let* ((programs (if (listp aidermacs-program) aidermacs-program (list aidermacs-program)))
(finder-fn (if (file-remote-p default-directory)
(lambda (prog) (executable-find prog t))
#'executable-find))
(program (cl-some finder-fn programs)))
(unless program
(error "Aider executable not found. Checked: %s" programs))
(puthash key program aidermacs--resolved-programs)
program))))
(defvar-local aidermacs--current-mode nil
"Buffer-local variable to track the current aidermacs mode.
Possible values: `code', `ask', `architect', `help'.")
(defvar-local aidermacs--ready nil
"Non-nil when aider is ready to accept new commands.")
(defcustom aidermacs-default-chat-mode nil
"Chat mode used when an Aidermacs session starts.
nil or `code' starts code mode (no --chat-mode arg).
`ask' starts ask/chat mode (--chat-mode ask).
`architect' starts architect mode (--chat-mode architect + model flags).
`help' starts help mode (--chat-mode help)."
:type '(choice (const :tag "Code (default)" nil)
(const :tag "Code" code)
(const :tag "Ask" ask)
(const :tag "Architect" architect)
(const :tag "Help" help)))
;; DEPRECATED – will disappear in a future release
(defcustom aidermacs-use-architect-mode nil
"OBSOLETE. Non-nil means start Aidermacs in Architect mode.
Instead, set `aidermacs-default-chat-mode' to the symbol `architect'."
:type 'boolean
:group 'aidermacs)
(make-obsolete-variable 'aidermacs-use-architect-mode
'aidermacs-default-chat-mode
"1.5")
(defcustom aidermacs-config-file nil
"Path to aider configuration file.
When set, Aidermacs will pass this to aider via --config flag,
ignoring other configuration settings except `aidermacs-extra-args'
and `aidermacs-subtree-only' (see its documentation for details)."
:type '(choice (const :tag "None" nil)
(file :tag "Config file")))
(define-obsolete-variable-alias 'aidermacs-args 'aidermacs-extra-args "0.5.0"
"Old name for `aidermacs-extra-args', please update your config.")
(defcustom aidermacs-extra-args '()
"Additional arguments to pass to the aidermacs command."
:type '(repeat string))
(defcustom aidermacs-global-read-only-files '()
"List of read-only files to add to the aidermacs session.
These paths are project-agnostic, i.e. not relative to the project root."
:type '(repeat string))
(defcustom aidermacs-project-read-only-files '()
"List of read-only files to add to the aidermacs session.
These paths are relative to the project root."
:type '(repeat string))
(defcustom aidermacs-subtree-only nil
"When non-nil, run aider with --subtree-only in the current directory.
This is useful for working in monorepos where you want to limit aider's scope.
Unlike other configuration settings, this flag is applied even when
`aidermacs-config-file' is set. However, if subtree-only is already set to
true in that configuration file, it will take precedence, because aider does
not support --no-subtree-only on the command line. For this reason, avoid
setting subtree-only in the configuration file; instead, choose the desired
behavior by invoking `aidermacs-run', `aidermacs-run-in-current-dir', or
`aidermacs-run-in-directory' as appropriate."
:type 'boolean)
(defcustom aidermacs-auto-commits nil
"When non-nil, enable auto-commits of LLM changes.
When nil, disable auto-commits requiring manual git commits."
:type 'boolean)
(defcustom aidermacs-watch-files nil
"When non-nil, enable watching files for AI coding instructions.
When enabled, aider will watch all files in your repo and look for
any AI coding instructions you add using your favorite IDE or text editor."
:type 'boolean)
(defcustom aidermacs-auto-accept-architect nil
"When non-nil, automatically accept architect mode changes.
When nil, require explicit confirmation before applying changes."
:type 'boolean)
(defcustom aidermacs-exit-kills-buffer nil
"When non-nil, `aidermacs-exit' will also kill the Aider buffer."
:type 'boolean)
(defvar aidermacs--read-string-history nil
"History list for aidermacs read string inputs.")
(defcustom aidermacs-common-prompts
'("What does this code do? Explain the logic step by step"
"Explain the overall architecture of this codebase"
"Simplify this code while preserving functionality"
"Extract this logic into separate helper functions"
"Optimize this code for better performance"
"Are there any edge cases not handled in this code?"
"Refactor to reduce complexity and improve readability"
"How could we make this code more maintainable?")
"List of common prompts to use with aidermacs.
These will be available for selection when using aidermacs commands."
:type '(repeat string))
(defvar aidermacs--cached-version nil
"Cached aider version to avoid repeated version checks.")
(defun aidermacs-aider-version ()
"Check the installed aider version.
Returns a version string like \"0.77.0\" or nil if version can't be determined.
Uses cached version per-workspace if available to avoid repeated process calls."
(interactive)
(let* ((path exec-path)
(key (aidermacs--get-cache-key))
(cached (gethash key aidermacs--cached-versions)))
(unless cached
(let ((version
(with-temp-buffer
(setq-local exec-path path)
(when (= 0 (process-file (aidermacs-get-program) nil t nil "--version"))
(goto-char (point-min))
(when (re-search-forward
"\\([0-9]+\\.[0-9]+\\.[0-9]+\\)" nil t)
(match-string 0))))))
(puthash key version aidermacs--cached-versions)
(setq cached version)))
(message "Aider version %s" (or cached "unknown"))
cached))
(defun aidermacs-clear-aider-version-cache (&optional all)
"Clear the cached aider version.
With prefix argument ALL, clear all cached versions.
Without prefix, clear only the cache for the current workspace.
Call this after upgrading aider to ensure the correct version is detected."
(interactive "P")
(if all
(progn
(clrhash aidermacs--cached-versions)
(message "Aider version cache cleared for all workspaces."))
(remhash (aidermacs--get-cache-key) aidermacs--cached-versions)
(message "Aider version cache cleared for current workspace.")))
(defun aidermacs--send-notification (title message)
"Send system notification with TITLE and MESSAGE.
Uses `notifications' library if available, otherwise falls back to
system-specific commands."
(when aidermacs-enable-notifications
(condition-case err
(cond
((featurep 'notifications)
(notifications-notify
:title title
:body message
:app-name "Aidermacs"
:timeout 0))
((eq system-type 'darwin)
(cond
((executable-find "alerter")
(let* ((output-buffer "")
(caller-buffer (current-buffer))
(bufs (match-buffers #'aidermacs--is-aidermacs-buffer-p))
(target-buffer (cond
((aidermacs--is-aidermacs-buffer-p caller-buffer)
(buffer-name caller-buffer))
((= 1 (length bufs))
(buffer-name (car bufs)))
((> (length bufs) 1)
(let* ((current-root (file-truename (aidermacs-project-root)))
(matching (cl-find-if
(lambda (buf)
(string-match-p (regexp-quote current-root) (buffer-name buf)))
bufs)))
(buffer-name (or matching (car bufs)))))))
(display-message (if target-buffer
(format "%s [%s]" message target-buffer)
message)))
(make-process
:name "aidermacs-alerter"
:command (list "alerter"
"--title" title
"--message" display-message
"--sound" "default"
"--actions" "Open Emacs"
"--group" "aidermacs"
"--json"
"--timeout" "0")
:filter (lambda (_proc output)
(setq output-buffer (concat output-buffer output)))
:sentinel (lambda (_proc event)
(when (string-match-p "finished" event)
(condition-case err
(let* ((json-object-type 'hash-table)
(json-key-type 'string)
(data (json-read-from-string output-buffer))
(activation-type (gethash "activationType" data))
(activation-value (gethash "activationValue" data)))
(when (and (string= activation-type "actionClicked")
(string= activation-value "Open Emacs"))
(unless (= 0 (call-process "open" nil nil nil "-b" "org.gnu.Emacs"))
(call-process "open" nil nil nil "-a" "Emacs"))
(when (and target-buffer (get-buffer target-buffer))
(run-with-timer 0.1 nil #'aidermacs-switch-to-buffer target-buffer))))
(error
(message "Alerter JSON parse error: %s" err)))))
:noquery t
:connection-type 'pipe)))
(t
(call-process "osascript" nil nil nil
"-e" (format "display notification \"%s\" with title \"%s\" sound name \"default\""
message title)))))
((eq system-type 'gnu/linux)
(call-process "notify-send" nil nil nil
title message
"-t" "0"))
((eq system-type 'windows-nt)
(call-process "powershell" nil nil nil
"-Command"
(format "[System.Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms'); [System.Windows.Forms.MessageBox]::Show('%s', '%s', [System.Windows.Forms.MessageBoxButtons]::OK, [System.Windows.Forms.MessageBoxIcon]::Information)"
message title)))
(t
nil))
(error
(message "Failed to send notification: %s" err)))))
(defun aidermacs-project-root ()
"Get the project root using VC-git, or fallback to file directory.
This function tries multiple methods to determine the project root."
(or (vc-git-root default-directory)
(when buffer-file-name
(file-name-directory buffer-file-name))
default-directory))
(defcustom aidermacs-prompt-file-name ".aider.prompt.org"
"File name that will automatically enable `aidermacs-minor-mode' when opened.
This is the file name without path."
:type 'string)
;;;###autoload (autoload 'aidermacs-transient-menu "aidermacs" nil t)
(transient-define-prefix aidermacs-transient-menu ()
"AI Pair Programming Interface."
["Aidermacs: AI Pair Programming"
["Core"
("a" (lambda ()
(if (aidermacs--live-p (aidermacs-get-buffer-name))
(concat "Open Session " (propertize "(RUNNING)" 'face 'success))
(concat "Start Session " (propertize "(NOT RUNNING)" 'face 'warning))))
aidermacs-run)
("." "Start in Current Dir" aidermacs-run-in-current-dir)
(":" "Start in Chosen Dir" aidermacs-run-in-directory)
("l" "Clear Chat History" aidermacs-clear-chat-history)
("s" "Reset Session" aidermacs-reset)
("x" "Exit Session" aidermacs-exit)]
["Persistent Modes"
("1" "Code Mode" aidermacs-switch-to-code-mode)
("2" "Chat/Ask Mode" aidermacs-switch-to-ask-mode)
("3" "Architect Mode" aidermacs-switch-to-architect-mode)
("4" "Help Mode" aidermacs-switch-to-help-mode)]
["Utilities"
("^" "Show Last Commit" aidermacs-magit-show-last-commit
:if (lambda () aidermacs-auto-commits))
("u" "Undo Last Commit" aidermacs-undo-last-commit
:if (lambda () aidermacs-auto-commits))
("C" "Auto-commit Changes" aidermacs-commit-with-auto-message)
("R" "Refresh Repo Map" aidermacs-refresh-repo-map)
("h" "Session History" aidermacs-show-output-history)
("o" "Switch Model (C-u: weak-model)" aidermacs-change-model)
("v" "Send Voice" aidermacs-send-voice)
("W" "Fetch Web Content" aidermacs-web)
("?" "Aider Meta-level Help" aidermacs-help)]]
["File Actions"
["Add Files (C-u: read-only)"
("f" "Add File" aidermacs-add-file)
("p" "Add Project File" aidermacs-add-project-file)
("F" "Add Current File" aidermacs-add-current-file)
("d" "Add From Directory (same type)" aidermacs-add-same-type-files-under-dir)
("w" "Add From Window" aidermacs-add-files-in-current-window)
("m" "Add From Dired (marked)" aidermacs-batch-add-dired-marked-files)]
["Drop Files"
("j" "Drop File" aidermacs-drop-file)
("J" "Drop Current File" aidermacs-drop-current-file)
("k" "Drop From Dired (marked)" aidermacs-batch-drop-dired-marked-files)
("K" "Drop All Files" aidermacs-drop-all-files)]
["Others"
("S" "Create Session Scratchpad" aidermacs-create-session-scratchpad)
("G" "Add File to Session" aidermacs-add-file-to-session)
("A" "List Added Files" aidermacs-list-added-files)]]
["Code Actions"
["Code"
("c" "Code Change" aidermacs-direct-change)
("e" "Question Code" aidermacs-question-code)
("r" "Architect Change" aidermacs-architect-this-code)]
["Question"
("q" "General Question" aidermacs-question-general)
("*" "Question This Symbol" aidermacs-question-this-symbol)
("g" "Accept Proposed Changes" aidermacs-accept-change)]
["Others"
("i" "Implement TODO" aidermacs-implement-todo)
("t" "Write Test" aidermacs-write-unit-test)
("T" "Fix Test" aidermacs-fix-failing-test-under-cursor)
("!" "Debug Exception" aidermacs-debug-exception)]])
(defun aidermacs-select-buffer-name ()
"Select an existing aidermacs session buffer.
If there is only one aidermacs buffer, return its name.
If there are multiple, prompt to select one interactively.
Returns nil if no aidermacs buffers exist.
This is used when you want to target an existing session."
(let* ((buffers (match-buffers #'aidermacs--is-aidermacs-buffer-p))
(buffer-names (mapcar #'buffer-name buffers)))
(pcase buffers
(`() nil)
(`(,name) (buffer-name name))
(_ (completing-read "Select aidermacs session: " buffer-names nil t)))))
(defun aidermacs-get-buffer-name (&optional use-existing suffix)
"Generate the aidermacs buffer name based on project root or current directory.
When USE-EXISTING is non-nil, return an existing session buffer name.
Otherwise, reuse an existing session whose directory contains the current
directory and is not a strict ancestor of the current git repository
\(if inside a git repo); otherwise create a new buffer name based on
`aidermacs-subtree-only' or the project root.
If supplied, SUFFIX is appended to the buffer name within the earmuffs."
(if use-existing
(aidermacs-select-buffer-name)
(let* ((root (aidermacs-project-root))
(current-dir-truename (file-truename default-directory)) ; Use truename for consistent comparisons
(aidermacs-buffers (match-buffers #'aidermacs--is-aidermacs-buffer-p))
;; Extract truename paths from existing *aidermacs:PATH* buffers (base sessions)
(existing-session-paths
(delq nil
(mapcar (lambda (buf)
(when (string-match "^\\*aidermacs:\\([^\\*]+\\)\\*$" (buffer-name buf)) ; Match base session names
(let ((path-str (match-string 1 (buffer-name buf))))
(when (file-directory-p path-str) ; Ensure it's a directory
(file-truename path-str)))))
aidermacs-buffers)))
;; Determine the display-root for the buffer name
(display-root
(let* ((git-root (vc-git-root default-directory))
(git-root-truename (and git-root (file-truename git-root)))
(sessions-containing-current-dir ;; Sessions whose paths contain current-dir-truename
(sort (cl-remove-if-not
(lambda (session-path)
(and (file-in-directory-p current-dir-truename session-path)
;; When inside a git repo, don't reuse sessions
;; that belong to a parent (enclosing) git repo.
(or (null git-root-truename)
(not (and (file-in-directory-p git-root-truename session-path)
(not (string= git-root-truename session-path)))))))
existing-session-paths)
;; Sort by length (deeper paths are more specific)
(lambda (a b) (> (length a) (length b)))))
(closest-session-containing-current-dir (car sessions-containing-current-dir)))
(cond
;; 1. Current directory is INSIDE an existing session's directory.
(closest-session-containing-current-dir
closest-session-containing-current-dir)
;; 2. Fallback logic: use current directory if subtree-only, else project root.
(aidermacs-subtree-only current-dir-truename)
(t (file-truename root)))))) ; Ensure root is also truename for consistency
(format "*aidermacs:%s%s*"
display-root
(or suffix "")))))
(defun aidermacs--live-p (buffer-name)
"Return t if BUFFER-NAME exists and its aider process is running."
(and (get-buffer buffer-name)
(process-live-p (get-buffer-process (or buffer-name (aidermacs-get-buffer-name))))))
;;;###autoload
(defun aidermacs-run ()
"Run aidermacs process using the selected backend.
This function sets up the appropriate arguments and launches the process."
(interactive)
;; Legacy boolean ⇒ new symbol
(when (and aidermacs-use-architect-mode
(null aidermacs-default-chat-mode))
(setq aidermacs-default-chat-mode 'architect)
(display-warning
'aidermacs
"`aidermacs-use-architect-mode' is obsolete – \
set `aidermacs-default-chat-mode' to 'architect' instead."
:warning))
;; Set up necessary hooks when aidermacs is actually run
(aidermacs--setup-ediff-cleanup-hooks)
(aidermacs--setup-cleanup-hooks)
(aidermacs-setup-minor-mode)
(let* ((buffer-name (aidermacs-get-buffer-name))
;; Split each string on whitespace for member comparison later
(flat-extra-args
(cl-mapcan (lambda (s)
(if (stringp s)
(split-string s "[[:space:]]+" t)
(list s)))
aidermacs-extra-args))
(has-model-arg (cl-some (lambda (x) (member x flat-extra-args))
'("--model" "--opus" "--sonnet" "--haiku"
"--4" "--4o" "--mini" "--4-turbo" "--35turbo"
"--deepseek" "--o1-mini" "--o1-preview")))
(has-config-arg (or (cl-some (lambda (dir)
(let ((conf (expand-file-name ".aider.conf.yml" dir)))
(when (file-exists-p conf)
dir)))
(list (expand-file-name "~")
(aidermacs-project-root)
default-directory))
aidermacs-config-file
(cl-some (lambda (x) (member x flat-extra-args))
'("--config" "-c"))))
;; Check aider version for auto-accept-architect support
(aider-version (aidermacs-aider-version))
;; New code: determine startup mode and warnings
(startup-mode (or aidermacs-default-chat-mode 'code))
(needs-chat-flag (and startup-mode (not (eq startup-mode 'code))))
(architect? (eq startup-mode 'architect)))
(let* ((backend-args
(if has-config-arg
;; Only need to add aidermacs-config-file manually
(when aidermacs-config-file
(list "--config" aidermacs-config-file))
(append
;; --chat-mode when required (ask/help/architect)
(when needs-chat-flag
(list "--chat-mode" (symbol-name startup-mode)))
;; extra model flags for architect
(when architect?
(list "--model" (aidermacs-get-architect-model)
"--editor-model" (aidermacs-get-editor-model)))
;; default --model when we’re still in plain code mode and user
;; didn’t supply one
(when (and (not needs-chat-flag) (not has-model-arg))
(list "--model" aidermacs-default-model))
;; existing flags that follow (no change)
(unless aidermacs-auto-commits
'("--no-auto-commits"))
;; Only add --no-auto-accept-architect if:
;; 1. User has disabled auto-accept (aidermacs-auto-accept-architect is nil)
;; 2. Aider version supports this flag (>= 0.77.0)
(when (and (not aidermacs-auto-accept-architect)
(version<= "0.77.0" aider-version))
'("--no-auto-accept-architect"))
;; Add watch-files if enabled
(when aidermacs-watch-files
'("--watch-files"))
;; Add weak model if specified
(when aidermacs-weak-model
(list "--weak-model" aidermacs-weak-model))
;; Aider-CE Only Option
(when (let ((prog (gethash (aidermacs--get-cache-key) aidermacs--resolved-programs)))
(and prog (string-match-p "aider-ce" prog)))
'("--linear-output"))
(when aidermacs-global-read-only-files
(apply #'append
(mapcar (lambda (file) (list "--read" file))
aidermacs-global-read-only-files)))
(when aidermacs-project-read-only-files
(apply #'append
(mapcar (lambda (file) (list "--read"
(expand-file-name file (aidermacs-project-root))))
aidermacs-project-read-only-files))))))
;; Take the original aidermacs-extra-args instead of the flat ones
(final-args (append backend-args
(when aidermacs-subtree-only
'("--subtree-only"))
aidermacs-extra-args)))
(if (aidermacs--live-p buffer-name)
(aidermacs-switch-to-buffer buffer-name)
(let ((default-directory (if aidermacs-subtree-only
default-directory
(or (aidermacs-project-root) default-directory))))
(aidermacs-run-backend (aidermacs-get-program) final-args buffer-name))
(with-current-buffer buffer-name
;; Set initial mode based on startup configuration
(setq-local aidermacs--current-mode startup-mode))
(aidermacs-switch-to-buffer buffer-name)))))
(defun aidermacs-run-in-current-dir ()
"Run aidermacs in the current directory with --subtree-only flag.
This is useful for working in monorepos where you want to limit aider's scope."
(interactive)
(let ((aidermacs-subtree-only t))
(aidermacs-run)))
(defun aidermacs-run-in-directory (directory)
"Run aidermacs in DIRECTORY with the --subtree-only flag.
This is useful for working in complex monorepos with nested subprojects."
(interactive
(list (read-file-name "Choose a directory: " nil nil t nil 'file-directory-p)))
(let ((aidermacs-subtree-only t)
(default-directory directory))
(aidermacs-run)))
(defun aidermacs--command-may-edit-files (command)
"Check if COMMAND may result in file edits.
Returns t if the command is likely to modify files, nil otherwise.
In code/architect mode, commands without prefixes may edit.
Commands containing /code or /architect always may edit."
(and (stringp command)
(or (and (memq aidermacs--current-mode '(code architect))
(not (string-match-p "^/" command)))
(string-match-p "/code" command)
(string-match-p "/architect" command))))
(defun aidermacs--send-command (command &optional no-switch-to-buffer use-existing redirect callback)
"Send command to the corresponding aidermacs process.
COMMAND is the text to send.
If NO-SWITCH-TO-BUFFER is non-nil, don't switch to the aidermacs buffer.
If USE-EXISTING is non-nil, use an existing buffer instead of creating new.
If REDIRECT is non-nil it redirects the output (hidden) for comint backend.
If CALLBACK is non-nil it will be called after the command finishes."
(let* ((buffer-name (aidermacs-get-buffer-name use-existing))
(buffer (if (aidermacs--live-p buffer-name)
(get-buffer buffer-name)
(when (get-buffer buffer-name)
(kill-buffer buffer-name))
(aidermacs-run)
(sit-for 1)
(get-buffer buffer-name)))
(processed-command (aidermacs--process-message-if-multi-line command)))
;; Check if command may edit files and prepare accordingly
(with-current-buffer buffer
;; Attempt to wait out transient commands or server lag for max 3s
(let ((max-wait-count 30))
(while (and (not aidermacs--ready) (> max-wait-count 0))
(sit-for 0.1)
(setq max-wait-count (1- max-wait-count))))
(if (not aidermacs--ready)
(progn (aidermacs-switch-to-buffer buffer-name)
(message "Aider process is not currently accepting commands"))
;; Reset current output before sending new command
(setq aidermacs--current-output "")
(setq aidermacs--current-callback callback)
(setq aidermacs--last-command processed-command)
(aidermacs--cleanup-temp-buffers)
(aidermacs--ensure-current-file-tracked)
(when (aidermacs--command-may-edit-files command)
(aidermacs--prepare-for-code-edit))
(aidermacs--send-command-backend buffer processed-command redirect)))
(when (and (not no-switch-to-buffer)
(not (string= (buffer-name) buffer-name)))
(aidermacs-switch-to-buffer buffer-name))))
;;;###autoload
(defun aidermacs-switch-to-buffer (&optional buffer-name)
"Switch to the aidermacs buffer.
If BUFFER-NAME is provided, switch to that buffer.
If not, try to get a buffer using `aidermacs-get-buffer-name`.
If that fails, try an existing buffer with `aidermacs-select-buffer-name`.
If the buffer is already visible in a window, switch to that window.
If the current buffer is already the aidermacs buffer, do nothing."
(interactive)
(let* ((target-buffer-name (or buffer-name
(aidermacs-get-buffer-name t)
(aidermacs-select-buffer-name)))
(buffer (and target-buffer-name (get-buffer target-buffer-name))))
(cond
((and target-buffer-name (string= (buffer-name) target-buffer-name)) t)
((and buffer (get-buffer-window buffer))
(select-window (get-buffer-window buffer))) ;; Switch to existing window
(buffer
(pop-to-buffer buffer))
(t
(error "No aidermacs buffer exists")))))
(defun aidermacs-clear-chat-history ()
"Send the command \"/clear\" to the aidermacs buffer."
(interactive)
(aidermacs--send-command "/clear"))
(defun aidermacs-reset ()
"Send the command \"/reset\" to the aidermacs buffer."
(interactive)
(setq aidermacs--tracked-files nil)
(aidermacs--send-command "/reset"))
(defun aidermacs-exit ()
"Send the command \"/exit\" to the aidermacs buffer.
If `aidermacs-exit-kills-buffer' is non-nil, also kill the buffer."
(interactive)
(let ((buffer-name (aidermacs-get-buffer-name)))
(when (get-buffer buffer-name)
(aidermacs--cleanup-temp-buffers)
(when (aidermacs--live-p buffer-name)
(aidermacs--send-command "/exit" t))
(when aidermacs-exit-kills-buffer
(sit-for 1)
(kill-buffer buffer-name)))))
(defun aidermacs--process-message-if-multi-line (str)
"Process multi-line chat messages for proper formatting.
STR is the message to process. If STR contains newlines and isn't already
wrapped in {aidermacs...aidermacs}, wrap it.
Otherwise return STR unchanged. See documentation at:
https://aidermacs.chat/docs/usage/commands.html#entering-multi-line-chat-messages"
(if (and (string-match-p "\n" str)
(not (string-match-p "^{aidermacs\n.*\naidermacs}$" str)))
(format "{aidermacs\n%s\naidermacs}" str)
str))
(defun aidermacs-drop-current-file ()
"Drop the current file from aidermacs session."
(interactive)
(if (not buffer-file-name)
(message "Current buffer is not associated with a file.")
(let* ((file-path (aidermacs--localize-tramp-path buffer-file-name))
(formatted-path (if (string-match-p " " file-path)
(format "\"%s\"" file-path)
file-path))
(command (format "/drop %s" formatted-path)))
(aidermacs--send-command command))))
(defun aidermacs--parse-ls-output (output)
"Parse the /ls command output to extract files in chat.
OUTPUT is the text returned by the /ls command. After the \"Files in chat:\"
header, each subsequent line that begins with whitespace is processed.
The first non-whitespace token is taken as the file name. Relative paths are
resolved using the repository root (if available) or `default-directory`.
Only files that exist on disk are included in the result.
Returns a deduplicated list of such file names."
(when output
(with-temp-buffer
(insert output)
(goto-char (point-min))
(let* ((files '())
(base (aidermacs-project-root))
(is-remote (file-remote-p base)))
;; Parse read-only files section
(when (search-forward "Read-only files:" nil t)
(forward-line 1)
(while (and (not (eobp))
(string-match-p "^[[:space:]]" (thing-at-point 'line t)))
(let* ((line (string-trim (thing-at-point 'line t)))
(file (car (split-string line))))
;; Skip empty file names
(when (and file (not (string-empty-p file)))
;; For remote files, we don't try to verify existence or convert paths
(if is-remote
(push (concat file " (read-only)") files)
;; For local files, verify existence and convert to relative path
(when (file-exists-p (expand-file-name file base))
(push (concat (file-relative-name (expand-file-name file base) base)
" (read-only)")
files)))))
(forward-line 1)))
;; Parse files in chat section
(when (search-forward "Files in chat:" nil t)
(forward-line 1)
(while (and (not (eobp))
(string-match-p "^[[:space:]]" (thing-at-point 'line t)))
(let* ((line (string-trim (thing-at-point 'line t)))
(file (car (split-string line))))
;; Skip empty file names
(when (and file (not (string-empty-p file)))
;; For remote files, we don't try to verify existence or convert paths
(if is-remote
(push file files)
;; For local files, verify existence and convert to relative path
(when (file-exists-p (expand-file-name file base))
(push (file-relative-name (expand-file-name file base) base) files)))))
(forward-line 1)))
;; Remove duplicates and return
(setq aidermacs--tracked-files (delete-dups (nreverse files)))
aidermacs--tracked-files))))
(defun aidermacs--get-files-in-session (callback)
"Get list of files in current session and call CALLBACK with the result."
(aidermacs--send-command
"/ls" nil nil t
(lambda ()
(let ((files (aidermacs--parse-ls-output aidermacs--current-output)))
(funcall callback files)))))
(defun aidermacs-list-added-files ()
"List all files currently added to the chat session.
Sends the \"/ls\" command and displays the results in a Dired buffer."
(interactive)
(aidermacs--get-files-in-session
(lambda (files)
(setq aidermacs--tracked-files files)
(let ((buf-name (aidermacs-get-buffer-name nil " Files")))
;; Unfortunately find-dired-with-command doesn't allow us to specify the
;; buffer name, so we manually rename it after the fact and recreate it
;; on each call.
(when (get-buffer buf-name)
(kill-buffer buf-name))
(if files
(let* ((root (aidermacs-project-root))
(files-arg (mapconcat #'shell-quote-argument files " "))
(cmd (format "find %s %s" files-arg (car find-ls-option))))
(find-dired-with-command root cmd)
(let ((buf (get-buffer "*Find*")))
(when buf
(with-current-buffer buf
(rename-buffer buf-name)
(save-excursion
;; The executed command is on the 2nd line; it can get
;; quite long, so we delete it to avoid cluttering the
;; buffer.
(goto-char (point-min))
(forward-line 1) ;; Move to the 2nd line
(when (looking-at "^ *find " t)
(let ((inhibit-read-only t))
(delete-region (line-beginning-position) (line-end-position)))))
(setq revert-buffer-function
(lambda (&rest _) (aidermacs-list-added-files)))))))
(message "No files added to the chat session"))))))
(defun aidermacs-drop-file ()
"Drop a file from the chat session by selecting from currently added files."
(interactive)
(aidermacs--get-files-in-session
(lambda (files)
(if-let* ((file (completing-read "Select file to drop: " files nil t))
(clean-file (replace-regexp-in-string " (read-only)$" "" file)))
(let ((command (aidermacs--prepare-file-paths-for-command "/drop" (list clean-file))))
(aidermacs--send-command command))
(message "No files available to drop")))))
(defun aidermacs-drop-all-files ()
"Drop all files from the current chat session."
(interactive)
(setq aidermacs--tracked-files nil)
(aidermacs--send-command "/drop"))
(defun aidermacs-batch-drop-dired-marked-files ()
"Drop Dired marked files from the aidermacs session."
(interactive)
(unless (derived-mode-p 'dired-mode)
(user-error "This command can only be used in Dired mode"))
(let ((files (dired-get-marked-files))
(is-aidermacs-files-buffer (string= (buffer-name)
(aidermacs-get-buffer-name nil " Files"))))
(aidermacs--drop-files-helper files)
;; If we're in the special aidermacs files buffer, kill it after dropping files
(when is-aidermacs-files-buffer
(message "Closing aidermacs file buffer after dropping files")
(kill-buffer (aidermacs-get-buffer-name nil " Files")))))
(defun aidermacs--form-prompt (command &optional prompt-prefix guide ignore-context)
"Get command based on context with COMMAND and PROMPT-PREFIX.
COMMAND is the text to prepend. PROMPT-PREFIX is the text to add after COMMAND.
GUIDE is displayed in the prompt but not included in the final command.
Use highlighted region as context unless IGNORE-CONTEXT is set to non-nil."
(let* ((region-text (when (and (use-region-p) (not ignore-context))
(buffer-substring-no-properties (region-beginning) (region-end))))
(context (when region-text
(format " in %s regarding this section:\n```\n%s\n```\n" (buffer-name) region-text)))
;; Read user input
(user-command
(read-string
(concat command " " prompt-prefix context
(when guide (format " (%s)" guide)) ": ")
nil 'aidermacs--read-string-history nil nil)))
;; Add to history if not already there, removing any duplicates
(setq aidermacs--read-string-history
(delete-dups (cons user-command aidermacs--read-string-history)))
(concat command
" "
prompt-prefix
context
(unless (string-empty-p user-command)
(concat ": " user-command)))))
(defun aidermacs--detect-code-change-region ()
"Select the underlying region based on paragraph boundaries.
Return a cons cell (START . END) of the detected region, or nil if none found."
(save-excursion
(let ((start (point))
(end (point)))
(backward-paragraph)
(setq start (point))
(forward-paragraph)
(setq end (point))
(cons start end))))
(defun aidermacs--set-code-change-region ()
"Set the region based on detected code change boundaries if no region is active."
(unless (use-region-p)
(when-let ((region (aidermacs--detect-code-change-region)))
(goto-char (car region))
(set-mark (cdr region)))))
(defun aidermacs-direct-change ()
"Prompt the user for an input and send it to aidermacs prefixed with \"/code \".
If no region is active, automatically detect and select a relevant region."
(interactive)
(aidermacs--set-code-change-region)
(when-let* ((command (aidermacs--form-prompt "/code" "Make this change" "will edit file")))
(aidermacs--ensure-current-file-tracked)
(aidermacs--send-command command)))
(defun aidermacs-question-code ()
"Ask a question about the code at point or region.
If a region is active, include the region text in the question.
If cursor is inside a function, include the function name as context.
If called from the aidermacs buffer, use general question instead."
(interactive)
(aidermacs--set-code-change-region)
(when-let* ((command (aidermacs--form-prompt "/ask" "Propose a solution" "won't edit file")))
(aidermacs--ensure-current-file-tracked)
(aidermacs--send-command command)))
(defun aidermacs-architect-this-code ()
"Architect code at point or region.
If region is active, inspect that region.
If point is in a function, inspect that function."
(interactive)
(aidermacs--set-code-change-region)
(when-let* ((command (aidermacs--form-prompt "/architect" "Design a solution" "confirm before edit")))
(aidermacs--ensure-current-file-tracked)
(aidermacs--send-command command)))
(defun aidermacs-question-general ()
"Prompt the user for a general question without code context."
(interactive)
(when-let* ((command (aidermacs--form-prompt "/ask" nil "empty for ask mode" t)))
(aidermacs--send-command command)))
(defun aidermacs-help ()
"Prompt the user for an input prefixed with \"/help \"."
(interactive)
(when-let* ((command (aidermacs--form-prompt "/help" nil "question how to use aider, empty for all commands" t)))
(aidermacs--send-command command)))
(defun aidermacs-debug-exception ()
"Prompt the user for an input and send it to aidermacs prefixed with \"/debug \"."
(interactive)
(when-let* ((command (aidermacs--form-prompt "/ask" "Debug exception")))
(aidermacs--send-command command)))
(defun aidermacs-accept-change ()
"Send the command \"go ahead\" to the aidermacs."
(interactive)
(aidermacs--send-command "/code ok"))
(defun aidermacs-magit-show-last-commit ()
"Show the last commit message using Magit.
If Magit is not installed, report that it is required."
(interactive)
(if (require 'magit nil 'noerror)
(magit-show-commit "HEAD")
(message "Magit is required to show the last commit.")))
(defun aidermacs-undo-last-commit ()
"Undo the last change made by aidermacs."
(interactive)
(aidermacs--send-command "/undo"))
(defun aidermacs-commit-with-auto-message ()
"Commit edits to the repo with an automatically generated commit message.
Uses aider's /commit command without arguments to generate a descriptive
commit message automatically based on the changes made."
(interactive)
(aidermacs--send-command "/commit"))
(defun aidermacs-question-this-symbol ()
"Ask aidermacs to explain symbol under point."
(interactive)
(let* ((symbol (thing-at-point 'symbol))
(line (string-trim-right (thing-at-point 'line)))
(prompt (format "/ask Please explain what '%s' means in the context of this code line: %s"
symbol line)))
(unless symbol
(error "No symbol under point!"))
(aidermacs--ensure-current-file-tracked)
(aidermacs--send-command prompt)))
(defun aidermacs-send-command-with-prefix (prefix command)
"Send COMMAND to the aidermacs buffer with PREFIX.
PREFIX is the text to prepend. COMMAND is the text to send."
(aidermacs--ensure-current-file-tracked)
(aidermacs--send-command (concat prefix command)))
(defun aidermacs--localize-tramp-path (file)
"If FILE is a TRAMP path, extract the local part of the path.
Otherwise, return FILE unchanged."
(if (and (fboundp 'tramp-tramp-file-p) (tramp-tramp-file-p file))
(let ((local-name (tramp-file-name-localname (tramp-dissect-file-name file))))
local-name)
file))
(defun aidermacs--prepare-file-paths-for-command (command files)
"Prepare FILES for use with COMMAND in aider.
Handles TRAMP paths by extracting local parts and formats the command string,
but wrapping them with double quotes that aider understands."
(let* ((localized-files (mapcar #'aidermacs--localize-tramp-path (delq nil files)))
(quoted-files (mapcar (lambda (path) (format "\"%s\"" path)) localized-files)))