Repository navigation
Expand file tree
/
Copy pathminuet.el
More file actions
1540 lines (1385 loc) · 65.8 KB
/
Copy pathminuet.el
File metadata and controls
1540 lines (1385 loc) · 65.8 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
;;; minuet.el --- Code completion using LLM -*- lexical-binding: t; -*-
;; Copyright (C) 2025 Free Software Foundation, Inc.
;; Author: Milan Glacier <dev@milanglacier.com>
;; Maintainer: Milan Glacier <dev@milanglacier.com>
;; Version: 0.10.0
;; URL: https://github.com/milanglacier/minuet-ai.el
;; Package-Requires: ((emacs "29") (plz "0.9") (dash "2.19.1"))
;; This file is part of GNU Emacs
;; This program is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program; see the file COPYING. If not, write to
;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth
;; Floor, Boston, MA 02110-1301, USA.
;;; Commentary:
;; LLM-powered code completion with dual modes:
;;
;; - Specialized prompts and various enhancements for chat-based LLMs
;; on code completion tasks.
;; - Fill-in-the-middle (FIM) completion for compatible models
;; (DeepSeek, Codestral, and some Ollama models).
;;
;; Minuet supports multiple LLM providers (OpenAI, Claude, Gemini,
;; Codestral, Ollama, Llama.cpp, and OpenAI-compatible providers)
;;
;; You can use it with overlay-based ghost text via
;; `minuet-show-suggestion' or selecting the candidates via
;; `minuet-complete-with-minibuffer'. You can toggle automatic
;; suggestion popup with `minuet-auto-suggestion-mode'.
;;; Code:
(require 'plz)
(require 'dash)
(require 'cl-lib)
(defgroup minuet nil
"Minuet group."
:group 'applications)
(declare-function evil-emacs-state-p "evil-states")
(declare-function evil-insert-state-p "evil-states")
(declare-function consult--read "consult")
(declare-function consult--insertion-preview "consult")
(defcustom minuet-auto-suggestion-debounce-delay 0.4
"Debounce delay in seconds for auto-suggestions."
:type 'number)
(define-obsolete-variable-alias 'minuet-auto-suggestion-block-functions
'minuet-auto-suggestion-block-predicates "0.7.1")
(defcustom minuet-auto-suggestion-block-predicates '(minuet-evil-not-insert-state-p)
"List of functions to determine whether auto-suggestions should be blocked.
Each functions should return non-nil if auto-suggestions should be
blocked. If any function in this list returns non-nil,
auto-suggestions will not be shown."
:type '(repeat function))
(defcustom minuet-auto-suggestion-throttle-delay 1.0
"Minimum time in seconds between auto-suggestions."
:type 'number)
(defface minuet-suggestion-face
'((t :inherit shadow))
"Face used for displaying inline suggestions.")
(defvar-local minuet--current-overlay nil
"Overlay used for displaying the current suggestion.")
(defvar-local minuet--last-synced-point nil
"Last point where typed text was synced with the suggestion overlay.")
(defvar-local minuet--last-point nil
"Last known cursor position for suggestion overlay.")
(defvar-local minuet--auto-last-point nil
"Last known cursor position for auto-suggestion.")
(defvar-local minuet--current-suggestions nil
"List of current completion suggestions.")
(defvar-local minuet--current-suggestion-index 0
"Index of currently displayed suggestion.")
(defvar-local minuet--current-requests nil
"List of current active request processes for this buffer.")
(defvar-local minuet--last-auto-suggestion-time nil
"Timestamp of last auto-suggestion.")
(defvar-local minuet--debounce-timer nil
"Timer for debouncing auto-suggestions.")
(defvar minuet-buffer-name "*minuet*" "The basename for minuet buffers.")
(defcustom minuet-provider 'openai-fim-compatible
"The provider to use for code completion.
Must be one of the supported providers: codestral, openai, claude, etc."
:type '(choice (const :tag "Codestral" codestral)
(const :tag "OpenAI" openai)
(const :tag "Claude" claude)
(const :tag "OpenAI Compatible" openai-compatible)
(const :tag "OpenAI FIM Compatible" openai-fim-compatible)
(const :tag "Gemini" gemini)))
(defcustom minuet-context-window 16000
"The maximum total characters of the context before and after cursor.
This limits how much surrounding code is sent to the LLM for context.
The default is 16000 characters which would roughly equate 4000
tokens."
:type 'integer)
(defcustom minuet-context-ratio 0.75
"Ratio of context before cursor vs after cursor.
When the total characters exceed the context window, this ratio
determines how much context to keep before vs after the cursor. A
larger ratio means more context before the cursor will be used."
:type 'float)
(defcustom minuet-request-timeout 3
"Maximum timeout in seconds for sending completion requests."
:type 'integer)
(defcustom minuet-add-single-line-entry t
"Whether to create additional single-line completion items.
When non-nil and a completion item has multiple lines, create another
completion item containing only its first line."
:type 'boolean)
(defcustom minuet-show-error-message-on-minibuffer nil
"Whether to show the error messages in minibuffer.
When non-nil, if a request fails or times out without generating even
a single token, the error message will be shown in the minibuffer.
Note that you can always inspect `minuet-buffer-name' to view the
complete error log."
:type 'boolean)
(defun minuet--default-after-cursor-filter-length-function ()
"Return the default after-cursor filter length for the current provider."
(if (memq minuet-provider '(codestral openai-fim-compatible)) 0 15))
(defcustom minuet-after-cursor-filter-length
#'minuet--default-after-cursor-filter-length-function
"Length of context after cursor used to filter completion text.
This setting helps prevent the language model from generating
redundant text. When filtering completions, the system compares the
suffix of a completion candidate with the text immediately following
the cursor.
The value may be either an integer or a function called with no
arguments that returns an integer.
If the length of the longest common substring between the end of the
candidate and the beginning of the post-cursor context exceeds this
value, that common portion is trimmed from the candidate.
For example, if the value is 15, and a completion candidate ends with
a 20-character string that exactly matches the 20 characters following
the cursor, the candidate will be truncated by those 20 characters
before being delivered."
:type '(choice integer function))
(defun minuet--default-before-cursor-filter-length-function ()
"Return the default before-cursor filter length for the current provider."
(if (memq minuet-provider '(codestral openai-fim-compatible)) 0 2))
(defcustom minuet-before-cursor-filter-length
#'minuet--default-before-cursor-filter-length-function
"Length of context before cursor used to filter completion text.
This setting helps prevent the language model from generating
redundant text at the beginning of completion. When filtering
completions, the system compares the prefix of a completion candidate
with the text immediately before the cursor.
The value may be either an integer or a function called with no
arguments that returns an integer.
If the length of the longest common substring between the beginning of
the candidate and the end of the pre-cursor context exceeds this
value, that common portion is trimmed from the candidate.
For example, if the value is 3, and a completion candidate starts with
a 10-character string where the last 3 characters exactly match the 3
characters before the cursor, the candidate will be truncated by those
3 characters before being delivered."
:type '(choice integer function))
(defcustom minuet-n-completions 3
"Number of completion items.
For FIM model, this is the number of requests to send. For chat LLM ,
this is the number of completions encoded as part of the prompt. Note
that when `minuet-add-single-line-entry` is true, the actual number of
returned items may exceed this value. Additionally, the LLM cannot
guarantee the exact number of completion items specified, as this
parameter serves only as a prompt guideline. The default is `3`."
:type 'integer)
(defvar minuet-default-prompt-prefix-first
"You are an AI code completion engine. Provide contextually appropriate completions:
- Code completions in code context
- Comment/documentation text in comments
- String content in string literals
- Prose in markdown/documentation files
Input markers:
- `<contextAfterCursor>`: Context after cursor
- `<cursorPosition>`: Current cursor location
- `<contextBeforeCursor>`: Context before cursor
"
"The default prefix-first style prompt for minuet completion.")
(defvar minuet-default-prompt
(concat minuet-default-prompt-prefix-first
"
Note that the user input will be provided in **reverse** order: first the
context after cursor, followed by the context before cursor.
") "The default prompt for minuet completion.")
(defvar minuet-default-guidelines
"Guidelines:
1. Offer completions after the `<cursorPosition>` marker.
2. Make sure you have maintained the user's existing whitespace and indentation.
This is REALLY IMPORTANT!
3. Provide multiple completion options when possible.
4. Return completions separated by the marker <endCompletion>.
5. The returned message will be further parsed and processed. DO NOT include
additional comments or markdown code block fences. Return the result directly.
6. Keep each completion option concise, limiting it to a single line or a few lines.
7. Create entirely new code completion that DO NOT REPEAT OR COPY any user's existing code around <cursorPosition>."
"The default guidelines for minuet completion.")
(defvar minuet-default-n-completion-template
"8. Provide at most %d completion items."
"The default prompt for minuet for number of completions request.")
(defvar minuet-default-system-template
"{{{:prompt}}}\n{{{:guidelines}}}\n{{{:n-completions-template}}}"
"The default template for minuet system template.")
(defvar minuet-default-chat-input-template
"{{{:language-and-tab}}}
<contextAfterCursor>
{{{:context-after-cursor}}}
<contextBeforeCursor>
{{{:context-before-cursor}}}<cursorPosition>"
"The default template for minuet chat input.")
(defvar minuet-default-chat-input-template-prefix-first
"{{{:language-and-tab}}}
<contextBeforeCursor>
{{{:context-before-cursor}}}<cursorPosition>
<contextAfterCursor>
{{{:context-after-cursor}}}"
"The default prefix-first style template for minuet chat input.")
(defvar minuet-default-fewshots
`((:role "user"
:content "# language: javascript
<contextAfterCursor>
return result;
}
const processedData = transformData(rawData, {
uppercase: true,
removeSpaces: false
});
<contextBeforeCursor>
function transformData(data, options) {
const result = [];
for (let item of data) {
<cursorPosition>")
(:role "assistant"
:content "let processed = item;
if (options.uppercase) {
processed = processed.toUpperCase();
}
if (options.removeSpaces) {
processed = processed.replace(/\s+/g, '');
}
result.push(processed);
}
<endCompletion>
if (typeof item === 'string') {
let processed = item;
if (options.uppercase) {
processed = processed.toUpperCase();
}
if (options.removeSpaces) {
processed = processed.replace(/\s+/g, '');
}
result.push(processed);
} else {
result.push(item);
}
}
<endCompletion>
")))
(defvar minuet-default-fewshots-prefix-first
`((:role "user"
:content "# language: javascript
<contextBeforeCursor>
function transformData(data, options) {
const result = [];
for (let item of data) {
<cursorPosition>
<contextAfterCursor>
return result;
}
const processedData = transformData(rawData, {
uppercase: true,
removeSpaces: false
});")
,(cadr minuet-default-fewshots)))
(defvar minuet-claude-options
`(:model "claude-haiku-5-5"
:end-point "https://api.anthropic.com/v1/messages"
:max_tokens 256
:api-key "ANTHROPIC_API_KEY"
:system
(:template minuet-default-system-template
:prompt minuet-default-prompt
:guidelines minuet-default-guidelines
:n-completions-template minuet-default-n-completion-template)
:fewshots minuet-default-fewshots
:chat-input
(:template minuet-default-chat-input-template
:language-and-tab minuet--default-chat-input-language-and-tab-function
:context-before-cursor minuet--default-chat-input-before-cursor-function
:context-after-cursor minuet--default-chat-input-after-cursor-function)
:transform ()
:optional nil)
"Config options for Minuet Claude provider.")
(defvar minuet-openai-options
`(:model "gpt-5.6-luna"
:api-key "OPENAI_API_KEY"
:end-point "https://api.openai.com/v1/chat/completions"
:system
(:template minuet-default-system-template
:prompt minuet-default-prompt-prefix-first
:guidelines minuet-default-guidelines
:n-completions-template minuet-default-n-completion-template)
:fewshots minuet-default-fewshots-prefix-first
:chat-input
(:template minuet-default-chat-input-template-prefix-first
:language-and-tab minuet--default-chat-input-language-and-tab-function
:context-before-cursor minuet--default-chat-input-before-cursor-function
:context-after-cursor minuet--default-chat-input-after-cursor-function)
:transform ()
:optional nil)
"Config options for Minuet OpenAI provider.")
(defvar minuet-codestral-options
'(:model "codestral-latest"
:name "Codestral"
:end-point "https://codestral.mistral.ai/v1/fim/completions"
:api-key "CODESTRAL_API_KEY"
:template (:prompt minuet--default-fim-prompt-function
:suffix minuet--default-fim-suffix-function)
;; a list of functions to transform the end-point, headers, and body
:transform ()
;; function to extract LLM-generated text from JSON output
:get-text-fn minuet--openai-get-text-fn
:optional nil)
"Config options for Minuet Codestral provider.")
(defvar minuet-openai-compatible-options
`(:end-point "https://openrouter.ai/api/v1/chat/completions"
:api-key "OPENROUTER_API_KEY"
:model "deepseek/deepseek-v4-flash"
:system
(:template minuet-default-system-template
:prompt minuet-default-prompt-prefix-first
:guidelines minuet-default-guidelines
:n-completions-template minuet-default-n-completion-template)
:fewshots minuet-default-fewshots-prefix-first
:chat-input
(:template minuet-default-chat-input-template-prefix-first
:language-and-tab minuet--default-chat-input-language-and-tab-function
:context-before-cursor minuet--default-chat-input-before-cursor-function
:context-after-cursor minuet--default-chat-input-after-cursor-function)
:transform ()
:optional nil)
"Config options for Minuet OpenAI compatible provider.")
(defvar minuet-openai-fim-compatible-options
'(:model "deepseek-v4-flash"
:end-point "https://api.deepseek.com/beta/completions"
:api-key "DEEPSEEK_API_KEY"
:name "Deepseek"
:template (:prompt minuet--default-fim-prompt-function
:suffix minuet--default-fim-suffix-function)
;; a list of functions to transform the end-point, headers, and body
:transform ()
;; function to extract LLM-generated text from JSON output
:get-text-fn minuet--openai-fim-get-text-fn
:optional nil)
"Config options for Minuet OpenAI FIM compatible provider.")
(defvar minuet-gemini-options
`(:model "gemini-2.0-flash"
:end-point "https://generativelanguage.googleapis.com/v1beta/models"
:api-key "GEMINI_API_KEY"
:system
(:template minuet-default-system-template
:prompt minuet-default-prompt-prefix-first
:guidelines minuet-default-guidelines
:n-completions-template minuet-default-n-completion-template)
:fewshots minuet-default-fewshots-prefix-first
:chat-input
(:template minuet-default-chat-input-template-prefix-first
:language-and-tab minuet--default-chat-input-language-and-tab-function
:context-before-cursor minuet--default-chat-input-before-cursor-function
:context-after-cursor minuet--default-chat-input-after-cursor-function)
:transform ()
:optional nil)
"Config options for Minuet Gemini provider.")
(defun minuet-evil-not-insert-state-p ()
"Return non-nil if evil is loaded and not in insert or Emacs state."
(and (bound-and-true-p evil-local-mode)
(not (or (evil-insert-state-p)
(evil-emacs-state-p)))))
(defmacro minuet-set-nested-plist (plist val &rest attributes)
"Set or delete a PLIST's nested ATTRIBUTES.
PLIST is the plist to set. If VAL is non-nil, set the nested
attribute to VAL. If VAL is nil, delete the final attribute from its
parent plist.
Example usage:
\(minuet-set-nested-plist `minuet-openai-options' 256 :optional :max-tokens)
;; delete :max-tokens field
\(minuet-set-nested-plist `minuet-openai-options' nil :optional :max-tokens)"
(if (null attributes)
(error "Minuet-set-nested-plist requires at least one attribute key"))
(if val
(let ((access-form plist))
(dolist (attr attributes)
(setq access-form `(plist-get ,access-form ,attr)))
`(setf ,access-form ,val))
;; If val is nil, delete the key from its parent plist.
(let* ((all-but-last-attributes (butlast attributes))
(last-attribute (car (last attributes)))
(parent-plist-accessor plist))
(dolist (attr all-but-last-attributes)
(setq parent-plist-accessor `(plist-get ,parent-plist-accessor ,attr)))
`(setf ,parent-plist-accessor (map-delete ,parent-plist-accessor ,last-attribute)))))
(defun minuet-set-optional-options (options key val &optional parent-key)
"Set the value of KEY in the PARENT-KEY of OPTIONS to VAL.
If PARENT-KEY is not provided, it defaults to :optional. If VAL is nil,
then remove KEY from OPTIONS. This helper function simplifies setting
values in a two-level nested plist structure."
(let ((parent-key (or parent-key :optional)))
(minuet-set-nested-plist options val parent-key key)))
(defun minuet--eval-value (value)
"Eval a VALUE for minuet.
If value is a function (either lambda or a callable symbol), eval the
function (with no argument) and return the result. Else if value is a
symbol, return its value. Else return itself."
(cond ((functionp value) (funcall value))
((and (symbolp value) (boundp value)) (symbol-value value))
(t value)))
(defun minuet--expand-template (template lookup)
"Expand each {{{KEY}}} placeholder in TEMPLATE using LOOKUP.
TEMPLATE must be a string; any other value raises an error. LOOKUP
is called with the interned KEY symbol \(e.g. `:prompt' for
{{{:prompt}}}) and must return the replacement string, or nil to drop
the placeholder; any other return value raises an error. The
template is walked once using literal string matching."
(let ((pos 0)
(parts nil))
(while-let ((open (string-search "{{{" template pos))
(close (string-search "}}}" template (+ open 3))))
(push (substring template pos open) parts)
(when-let* ((key (intern (substring template (+ open 3) close)))
(value (funcall lookup key)))
(unless (stringp value)
(signal 'wrong-type-argument (list 'stringp value key)))
(push value parts))
(setq pos (+ close 3)))
(push (substring template pos) parts)
(apply #'concat (nreverse parts))))
(defun minuet--cancel-requests ()
"Cancel all current minuet requests for this buffer."
(when minuet--current-requests
(dolist (proc minuet--current-requests)
(when (process-live-p proc)
(minuet--log (format "%s process terminated" (prin1-to-string proc)))
(signal-process proc 'SIGTERM)))
(setq minuet--current-requests nil)))
(defun minuet--cleanup-suggestion (&optional no-cancel)
"Remove the current suggestion overlay.
Also cancel any pending requests unless NO-CANCEL is t."
(unless no-cancel
(minuet--cancel-requests))
(when minuet--current-overlay
(delete-overlay minuet--current-overlay)
(setq minuet--current-overlay nil)
(minuet-active-mode -1))
(remove-hook 'post-command-hook #'minuet--on-cursor-moved t)
(setq minuet--last-point nil))
(defun minuet--cursor-moved-p ()
"Check if cursor moved from last suggestion position."
(and minuet--last-point
(not (eq minuet--last-point (point)))))
(defun minuet--sync-suggestion-with-typed-text ()
"Update the suggestion when the typed text matches its prefix.
Return non-nil when the completion was preserved or updated."
(if-let* ((suggestions minuet--current-suggestions)
(has-overlay minuet--current-overlay)
(last-point minuet--last-point)
(cursor-moved-forward (> (point) last-point))
(index (or minuet--current-suggestion-index 0))
(current-suggestion (nth index suggestions))
(typed (buffer-substring-no-properties last-point (point)))
(current-suggestion-matches-typed
(and (string-prefix-p typed current-suggestion)
(length> current-suggestion (length typed))))
(matched-suggestions
(cl-loop for suggestion in suggestions
for i from 0
when (string-prefix-p typed suggestion)
collect (cons i (substring suggestion (length typed)))))
(new-index (or (cl-position index matched-suggestions :key #'car) 0))
(new-suggestions (mapcar #'cdr matched-suggestions)))
(progn
(minuet--cleanup-suggestion)
(minuet--display-suggestion new-suggestions new-index)
(setq minuet--last-synced-point (point))
t)
(setq minuet--last-synced-point nil)))
(defun minuet--on-cursor-moved ()
"Minuet event on cursor moved."
(when (minuet--cursor-moved-p)
(unless (minuet--sync-suggestion-with-typed-text)
(minuet--cleanup-suggestion))))
(defun minuet--display-suggestion (suggestions &optional index)
"Display suggestion from SUGGESTIONS at INDEX using an overlay at point."
;; we only cancel requests when cursor is moved. Because the
;; completion items may be accumulated during multiple concurrent
;; curl requests.
(minuet--cleanup-suggestion t)
(add-hook 'post-command-hook #'minuet--on-cursor-moved nil t)
(when-let* ((suggestions suggestions)
(cursor-not-moved (not (minuet--cursor-moved-p)))
(total (length suggestions))
(index (mod (or index 0) total))
(suggestion (nth index suggestions))
;; Adjust the suggestion text displayed in the overlay
;; by replacing empty lines with a space. This ensures
;; that when the current line is empty, the overlay text
;; is correctly positioned after the cursor rather than
;; before it.
(overlay-text (replace-regexp-in-string "^$" " " suggestion))
(overlay-text (propertize
(format "%s%s"
overlay-text
(if (= total minuet-n-completions 1) ""
(format " (%d/%d)" (1+ index) total)))
'face 'minuet-suggestion-face))
;; 'Display' is used when not at the end-of-line to
;; ensure proper overlay positioning. Other methods,
;; such as `after-string' or `before-string', fail to
;; correctly position the cursor (which should precede
;; the overlay) and the overlay itself.
(ov-method (if (eolp) 'after-string 'display))
(ov-start (point))
(ov-end (if (eq ov-method 'display) (1+ ov-start) ov-start))
;; When using 'display', we include the character next
;; to the current point into the overlay to ensure its
;; visibility, as the overlay otherwise conceals it.
(offset-char (if (eq ov-method 'after-string)
""
(buffer-substring ov-start ov-end)))
(ov (make-overlay ov-start ov-end)))
(setq minuet--current-suggestions suggestions
minuet--current-suggestion-index index
minuet--last-point ov-start)
;; HACK: Adapted from copilot.el We add a 'cursor text property to the
;; first character of the suggestion to simulate the visual effect of
;; placing the overlay after the cursor
(put-text-property 0 1 'cursor t overlay-text)
(overlay-put ov ov-method
(concat overlay-text offset-char))
(overlay-put ov 'minuet t)
(setq minuet--current-overlay ov)
(minuet-active-mode 1)))
;;;###autoload
(defun minuet-next-suggestion ()
"Cycle to next suggestion."
(interactive)
(if-let* ((suggestions minuet--current-suggestions)
(_ minuet--current-overlay)
(next-index (mod (1+ minuet--current-suggestion-index)
(length suggestions))))
(minuet--display-suggestion suggestions next-index)
(minuet-show-suggestion)))
;;;###autoload
(defun minuet-previous-suggestion ()
"Cycle to previous suggestion."
(interactive)
(if-let* ((suggestions minuet--current-suggestions)
(_ minuet--current-overlay)
(prev-index (mod (1- minuet--current-suggestion-index)
(length suggestions))))
(minuet--display-suggestion suggestions prev-index)
(minuet-show-suggestion)))
;;;###autoload
(defun minuet-show-suggestion ()
"Show code suggestion using overlay at point."
(interactive)
(minuet--cleanup-suggestion)
(setq minuet--last-point (point))
(let ((current-buffer (current-buffer))
(available-p-fn (intern (format "minuet--%s-available-p" minuet-provider)))
(complete-fn (intern (format "minuet--%s-complete" minuet-provider)))
(context (minuet--get-context))
(is-first-completion t))
(unless (funcall available-p-fn)
(minuet--log (format "Minuet provider %s is not available" minuet-provider))
(error "Minuet provider %s is not available" minuet-provider))
(funcall complete-fn
context
(lambda (items)
(setq items (seq-uniq items))
(with-current-buffer current-buffer
(when (and items (not (minuet--cursor-moved-p)))
(minuet--display-suggestion
items (if is-first-completion 0 minuet--current-suggestion-index))))
(setq is-first-completion nil)))))
(defun minuet--log (message &optional message-p)
"Log minuet messages into `minuet-buffer-name'.
Also print the MESSAGE when MESSAGE-P is t."
(with-current-buffer (get-buffer-create minuet-buffer-name)
(goto-char (point-max))
(insert (format "%s %s\n" message (format-time-string "%Y-%02m-%02d %02H:%02M:%02S")))
(when message-p (message "%s" message))
;; make sure this function returns nil
nil))
(defun minuet--wrap-in-comment (text)
"Return TEXT as a comment line for the current major mode.
Use \"#\" when the mode has no comment syntax. Return an empty
string outside of `prog-mode', `text-mode' and `conf-mode'."
(if (derived-mode-p 'prog-mode 'text-mode 'conf-mode)
(concat (or comment-start "#") " " text (or comment-end ""))
""))
(defun minuet--add-tab-comment ()
"Add comment string for tab use into the prompt."
(minuet--wrap-in-comment
(if indent-tabs-mode
"indentation: use \t for a tab"
(format "indentation: use %d spaces for a tab" tab-width))))
(defun minuet--add-language-comment ()
"Add comment string for language use into the prompt."
(let* ((mode (symbol-name major-mode))
(mode (replace-regexp-in-string "-ts-mode" "" mode))
(mode (replace-regexp-in-string "-mode" "" mode)))
(minuet--wrap-in-comment (concat "language: " mode))))
(defun minuet--add-single-line-entry (data)
"Add single line entry into the DATA."
(cl-loop
for item in data
when (stringp item)
append (list (car (split-string item "\n"))
item)))
(defun minuet--remove-spaces (items)
"Remove trailing and leading spaces in each item in ITEMS."
;; Emacs use \\` and \\' to match the beginning/end of the string,
;; ^ and $ are used to match bol or eol
(setq items (mapcar (lambda (x)
(if (or (equal x "")
(string-match "\\`[\s\t\n]+\\'" x))
nil
(string-trim x)))
items)
items (seq-filter #'identity items)))
(defun minuet--remove-blank-items (items)
"Remove empty or whitespace-only strings from ITEMS."
(seq-filter (lambda (item)
(and (stringp item)
(not (string-match "\\`[\s\t\n]*\\'" item))))
items))
(defun minuet--get-context ()
"Get the context for minuet completion."
(let* ((point (point))
;; Count accessible characters, including when the buffer is narrowed.
(n-chars-before (- point (point-min)))
(point-max (point-max))
(n-chars-after (- point-max point))
(before-start (point-min))
(after-end point-max)
(is-incomplete-before nil)
(is-incomplete-after nil))
;; Calculate context window boundaries before extracting text
(when (>= (+ n-chars-before n-chars-after) minuet-context-window)
(cond ((< n-chars-before (* minuet-context-ratio minuet-context-window))
;; If context before cursor does not exceed context-window,
;; only limit after-cursor content
(setq after-end (+ point (- minuet-context-window n-chars-before))
is-incomplete-after t))
((< n-chars-after (* (- 1 minuet-context-ratio) minuet-context-window))
;; If context after cursor does not exceed context-window,
;; limit before-cursor content
(setq before-start (- point (- minuet-context-window n-chars-after))
is-incomplete-before t))
(t
;; At middle of file, use ratio to determine both boundaries
(setq is-incomplete-before t
is-incomplete-after t
after-end (+ point (floor (* minuet-context-window (- 1 minuet-context-ratio))))
before-start (+ (point-min)
(max 0 (- n-chars-before
(floor (* minuet-context-window minuet-context-ratio)))))))))
`(:before-cursor ,(buffer-substring-no-properties before-start point)
:after-cursor ,(buffer-substring-no-properties point after-end)
:language-and-tab ,(format "%s\n%s" (minuet--add-language-comment) (minuet--add-tab-comment))
:is-incomplete-before ,is-incomplete-before
:is-incomplete-after ,is-incomplete-after)))
(defun minuet--make-chat-llm-shot (context options)
"Build the final chat input for chat llm.
The CONTEXT is read from the current buffer content. OPTIONS should
be specified as a plist of provider settings. The return value will a
list of strings. It will then be converted into a multi-turn
conversation with alternating `user` and `assistant` roles by
`minuet--create-chat-messages-from-list'"
(let* ((chat-input (plist-get options :chat-input))
(templates (minuet--eval-value (plist-get chat-input :template)))
(templates (if (stringp templates) (list templates) templates))
(lookup (lambda (key)
(when-let* (((not (eq key :template)))
(repl-fn (plist-get chat-input key)))
(funcall repl-fn context)))))
(mapcar (lambda (template) (minuet--expand-template template lookup))
templates)))
(cl-defun minuet--filter-text (item context)
"Filter ITEM based on CONTEXT using `minuet-find-longest-match'.
ITEM is a completion candidate string.
CONTEXT is a plist with :before-cursor and :after-cursor fields.
Returns the filtered item after trimming overlapping parts."
(when (null item)
(cl-return-from minuet--filter-text nil))
(when (null context)
(cl-return-from minuet--filter-text item))
(let* ((before-cursor (plist-get context :before-cursor))
(after-cursor (plist-get context :after-cursor))
(before-filter-length
(minuet--eval-value minuet-before-cursor-filter-length))
(after-filter-length
(minuet--eval-value minuet-after-cursor-filter-length))
(filtered-item item))
(when (and (<= before-filter-length 0)
(<= after-filter-length 0))
(cl-return-from minuet--filter-text item))
(setq filtered-item (string-trim filtered-item))
;; Filter against before-cursor context (trim from prefix)
(when-let* ((before-cursor before-cursor)
(should-filter (> before-filter-length 0))
(before-cursor (string-trim before-cursor))
(match (minuet-find-longest-match filtered-item before-cursor))
(should-filter (and (not (string-empty-p match))
(>= (length match) before-filter-length))))
(setq filtered-item (substring filtered-item (length match))))
;; Filter against after-cursor context (trim from suffix)
(when-let* ((after-cursor after-cursor)
(should-filter (> after-filter-length 0))
(after-cursor (string-trim after-cursor))
(match (minuet-find-longest-match after-cursor filtered-item))
(should-filter (and (not (string-empty-p match))
(>= (length match) after-filter-length))))
(setq filtered-item (substring filtered-item 0 (- (length filtered-item) (length match)))))
filtered-item))
(cl-defun minuet-find-longest-match (a b)
"Find the longest string that is a prefix of A and a suffix of B.
The function iterates from the longest possible match length downwards
for efficiency. If A or B are not strings, it returns an empty
string."
(unless (and (stringp a) (stringp b))
(cl-return-from minuet-find-longest-match ""))
(let* ((len-a (length a))
(len-b (length b))
(max-len (min len-a len-b)))
(cl-loop for i from max-len downto 1
for prefix-a = (substring a 0 i)
for suffix-b = (substring b (- i))
when (string= prefix-a suffix-b)
do (cl-return-from minuet-find-longest-match prefix-a))
""))
(defun minuet--filter-context-sequence-in-items (items context)
"Apply the filter sequence in each item in ITEMS.
The filter sequence is obtained from CONTEXT."
(cl-loop for item in items
for filtered-item = (minuet--filter-text item context)
when (and filtered-item
(not (string= filtered-item "")))
collect filtered-item))
(defun minuet--stream-decode (response get-text-fn)
"Decode the RESPONSE using GET-TEXT-FN."
(setq response (split-string response "[\r]?\n"))
(let (result)
(dolist (line response)
(when-let* ((json (ignore-errors
(json-parse-string
(replace-regexp-in-string "^data: " "" line)
:object-type 'plist :array-type 'list)))
(text (ignore-errors
(funcall get-text-fn json)))
(text-not-empty (and (stringp text)
(not (string= text "")))))
(push text result)))
(setq result (apply #'concat (nreverse result)))
(if (equal result "")
(progn
(minuet--log "Minuet: Stream decoding failed for response:"
minuet-show-error-message-on-minibuffer)
(minuet--log response))
result)))
(defmacro minuet--make-process-stream-filter (response)
"Store the data into RESPONSE which should hold a plain list."
(declare (debug (gv-place)))
`(lambda (proc text)
(funcall #'internal-default-process-filter proc text)
;; (setq ,response (append ,response (list text)))
(push text ,response)))
(defun minuet--stream-decode-raw (response get-text-fn)
"Decode the raw stream used by minuet.
RESPONSE will be stored in the temp variable create by
`minuet--make-process-stream-filter' parsed by GET-TEXT-FN."
(if-let* ((response (nreverse response))
(response (apply #'concat response)))
(minuet--stream-decode response get-text-fn)
(minuet--log "Minuet: Empty stream response - no data received"
minuet-show-error-message-on-minibuffer)))
(defun minuet--handle-chat-completion-timeout (context err response get-text-fn name callback)
"Handle the timeout error for chat completion.
This function will decode and send the partial complete response to
the callback, and log the error. CONTEXT, ERR, RESPONSE, GET-TEXT-FN,
NAME, CALLBACK are used to deliver partial completion items and log
the errors."
(if (equal (car (plz-error-curl-error err)) 28)
(progn
(minuet--log (format "%s Request timeout" name))
(when-let* ((result (minuet--stream-decode-raw response get-text-fn))
(completion-items (minuet--parse-completion-itmes-default result))
(completion-items (minuet--filter-context-sequence-in-items
completion-items
context))
(completion-items (minuet--remove-spaces completion-items)))
(funcall callback completion-items)))
(minuet--log (format "An error occured when sending request to %s" name)
minuet-show-error-message-on-minibuffer)
(minuet--log err)))
(defmacro minuet--with-temp-response (&rest body)
"Execute BODY with a temporary response collection.
This macro creates a local variable `--response--' that can be used to
collect process output within the BODY. It's designed to work in
conjunction with `minuet--make-process-stream-filter'. The
`--response--' variable is initialized as an empty list and can be
used to accumulate text output from a process. After execution,
`--response--' will contain the collected responses in reverse order."
(declare (debug t) (indent 0))
`(let (--response--) ,@body))
;;;###autoload
(defun minuet-accept-suggestion ()
"Accept the current overlay suggestion."
(interactive)
(when-let* ((suggestions minuet--current-suggestions)
(_ minuet--current-overlay)
(suggestion (nth minuet--current-suggestion-index suggestions)))
(minuet--cleanup-suggestion)
(insert suggestion)))
;;;###autoload
(defun minuet-dismiss-suggestion ()
"Dismiss the current overlay suggestion."
(interactive)
(minuet--cleanup-suggestion))
;;;###autoload
(defun minuet-accept-suggestion-line (&optional n)
"Accept N lines of the current suggestion.
When called interactively with a numeric prefix argument, accept that
many lines. Without a prefix argument, accept only the first line."
(interactive "p")
(when (and minuet--current-suggestions
minuet--current-overlay)
(let* ((suggestion (nth minuet--current-suggestion-index
minuet--current-suggestions))
(lines (split-string suggestion "\n"))
(n (or n 1))
(selected-lines (seq-take lines n))
(remaining-lines (seq-drop lines n))
(remaining-suggestion (when remaining-lines
(string-join remaining-lines "\n"))))
(minuet--cleanup-suggestion)
(insert (string-join selected-lines "\n"))
(when remaining-suggestion
(insert "\n") ;; There is a remaining suggestion, so move to the next line.
;; NOTE: We do not need to worry about Minuet
;; automatically triggering the next suggestion upon
;; continuous acceptance. Minuet only attempts
;; auto-suggestion when the last command was not a Minuet
;; command. Since we have just accepted partial lines, the
;; last command is indeed a Minuet command.
(minuet--display-suggestion (list remaining-suggestion) 0)))))
;;;###autoload
(defun minuet-accept-suggestion-word (&optional n)
"Accept N words of the current suggestion.
When called interactively with a numeric prefix argument, accept that
many words. Without a prefix argument, accept only the first word."
(interactive "p")
(when-let* ((suggestions minuet--current-suggestions)
(_ minuet--current-overlay)
(suggestion (nth minuet--current-suggestion-index suggestions))
(n (or n 1))
(syntax (syntax-table))
(accepted
(with-temp-buffer
(set-syntax-table syntax)
(insert suggestion)
(goto-char (point-min))
(forward-word n)
(buffer-substring (point-min) (point))))
(remaining (substring suggestion (length accepted))))
(minuet--cleanup-suggestion)
(insert accepted)
(unless (string-empty-p remaining)
;; See the NOTE in `minuet-accept-suggestion-line' about why this
;; does not retrigger auto-suggestion.
(minuet--display-suggestion (list remaining) 0))))
;;;###autoload
(defun minuet-complete-with-minibuffer ()
"Complete using minibuffer interface."
(interactive)
(let ((current-buffer (current-buffer))
(available-p-fn (intern (format "minuet--%s-available-p" minuet-provider)))
(complete-fn (intern (format "minuet--%s-complete" minuet-provider)))
(context (minuet--get-context))