-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlsp-copilot.el
2653 lines (2409 loc) · 119 KB
/
lsp-copilot.el
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
;;; lsp-copilot.el --- Description -*- lexical-binding: t; -*-
;;
;; Copyright (C) 2023 JadeStrong
;;
;; Author: JadeStrong <jadestrong@163.com>
;; Maintainer: JadeStrong <jadestrong@163.com>
;; Created: December 15, 2023
;; Modified: December 15, 2023
;; Version: 0.0.1
;; Keywords: abbrev bib c calendar comm convenience data docs emulations extensions faces files frames games hardware help hypermedia i18n internal languages lisp local maint mail matching mouse multimedia news outlines processes terminals tex tools unix vc wp
;; Homepage: https://github.com/bytedance/lsp-copilot
;; Package-Requires: ((emacs "29.1") (s "1.13.1") (ht "2.4") (posframe "1.4.4") (dash "2.19.1") (f "0.21.0") (yasnippet "0.14.1"))
;;
;; This file is not part of GNU Emacs.
;;
;;; Commentary:
;; Description
;;
;;; Code:
(require 'cl-lib)
(require 'json)
(require 'jsonrpc)
(require 'xref)
(require 'compile)
(require 'seq)
(require 'url-util)
(require 'project)
(require 's)
(require 'f)
(require 'ht)
(require 'dash)
(require 'posframe)
(require 'yasnippet)
(declare-function projectile-project-root "ext:projectile")
(declare-function yas-expand-snippet "ext:yasnippet")
(declare-function flycheck-buffer "ext:flycheck")
(declare-function flycheck-mode "ext:flycheck")
(declare-function flycheck-define-generic-checker
"ext:flycheck" (symbol docstring &rest properties))
(declare-function flycheck-error-new "ext:flycheck" t t)
(declare-function flycheck-error-message "ext:flycheck" (err) t)
(declare-function flycheck-define-error-level "ext:flycheck" (level &rest properties))
(declare-function flycheck-valid-checker-p "ext:flycheck")
(declare-function flycheck-stop "ext:flycheck")
(declare-function flycheck-checker-supports-major-mode-p "ext:flycheck")
(declare-function flycheck-add-mode "ext:flycheck")
(defvar flycheck-mode)
(defvar flycheck-check-syntax-automatically)
(defvar flycheck-checker)
(defvar flycheck-checkers)
(defgroup lsp-copilot nil
"Interaction with Lsp Copilot Server."
:prefix "lsp-copilot-"
:group 'tools)
(defcustom lsp-copilot-user-languages-config (expand-file-name (concat user-emacs-directory (file-name-as-directory "lsp-copilot") "languages.toml"))
"The user config file to store custom language config."
:type 'string
:group 'lsp-copilot)
(defcustom lsp-copilot-log-file-directory temporary-file-directory
"The directory for `lsp-copilot` server to generate log file."
:type 'string
:group 'lsp-copilot)
(defcustom lsp-copilot-log-max 0
"Max size of events buffer. 0 disables, nil means infinite.
Enabling event logging may slightly affect performance."
:group 'lsp-copilot
:type 'integer)
(defcustom lsp-copilot-log-buffer-max message-log-max
"Maximum number of lines to keep in th elog buffer.
If nil, disable message logging. If t, log messages but don’t truncate
the buffer when it becomes large."
:group 'lsp-copilot
:type '(choice (const :tag "Disable" nil)
(integer :tag "lines")
(const :tag "Unlimited" t)))
(defcustom lsp-copilot--send-changes-idle-time 0
"Don't tell server of changes before Emacs's been idle for this many seconds."
:group 'lsp-copilot
:type 'number)
(defcustom lsp-copilot-idle-delay 0.500
"Debounce interval for `after-change-functions'."
:type 'number
:group 'lsp-copilot)
(defcustom lsp-copilot-on-idle-hook nil
"Hooks to run after `lsp-copilot-idle-delay'."
:type 'hook
:group 'lsp-copilot)
(defcustom lsp-copilot-hover-buffer "*lsp-copilot-help*"
"Buffer for display hover info."
:type 'string
:group 'lsp-copilot)
(defcustom lsp-copilot-diagnostics-buffer "*lsp-copilot-diagnostics*"
"Buffer for display diagnostics."
:type 'string
:group 'lsp-copilot)
(defcustom lsp-copilot-signature-buffer " *lsp-copilot-signature*"
"Buffer for display signature help info."
:type 'string
:group 'lsp-copilot)
(defcustom lsp-copilot-signature-auto-active nil
"If auto active signature help."
:type 'boolean
:group 'lsp-copilot)
(defcustom lsp-copilot-trim-trailing-whitespace t
"Trim trailing whitespace on a line."
:group 'lsp-copilot
:type 'boolean)
(defcustom lsp-copilot-insert-final-newline t
"Insert a newline character at the end of the file if one does not exist."
:group 'lsp-copilot
:type 'boolean)
(defcustom lsp-copilot-trim-final-newlines t
"Trim all newlines after the final newline at the end of the file."
:group 'lsp-copilot
:type 'boolean)
(defcustom lsp-copilot-log-level 1
"A number indicating the log level. Defaults to 1."
:type '(choice (const :tag "Warn" 0)
(const :tag "Info" 1)
(const :tag "Debug" 2)
(const :tag "Trace" 3))
:group 'lsp-copilot)
(defface lsp-copilot-hover-posframe
'((t :inherit tooltip))
"Background and foreground for `lsp-copilot-hover-posframe'."
:group 'lsp-copilot)
(defcustom lsp-copilot-signature-retrigger-keys '(return)
"Character strings used to retrigger a new textDocument/signatureHelp request."
:type 'list
:group 'lsp-copilot-mode)
(defcustom lsp-copilot-diagnostics-provider :auto
"The checker backend provider."
:type
'(choice
(const :tag "Pick flycheck if present and fallback to flymake" :auto)
(const :tag "Pick flycheck" :flycheck)
(const :tag "Pick flymake" :flymake)
(const :tag "Use neither flymake nor lsp" :none)
(const :tag "Prefer flymake" t)
(const :tag "Prefer flycheck" nil))
:group 'lsp-copilot)
(defvar lsp-copilot--exec-file (expand-file-name (if (eq system-type 'windows-nt)
"./lsp-copilot.exe"
"./lsp-copilot")
(if load-file-name
(file-name-directory load-file-name)
default-directory)))
(defvar-local lsp-copilot--on-idle-timer nil)
(defvar lsp-copilot--log-file nil
"The log file name.")
(defvar lsp-copilot--connection nil
"Lsp Copilot agent jsonrcp connection instnace.")
(defvar lsp-copilot--opened-buffers nil
"List of buffers that have been opened in Lsp Copilot.")
(defvar-local lsp-copilot--doc-version 0
"The document version of the current buffer. Incremented after each change.")
(defvar-local lsp-copilot--recent-changes nil
"Recent buffer changes as collected by `lsp-copilot--before-change'.")
(defvar-local lsp-copilot--change-idle-timer nil
"Idle timer for didChange signals.")
(defvar-local lsp-copilot--completion-trigger-characters nil
"Completion trigger characters.")
(defvar-local lsp-copilot--signature-trigger-characters nil
"Signature trigger characters.")
(defvar-local lsp-copilot-enable-relative-indentation nil
"Enable relative indentation when insert texts, snippets ...
from language server.")
(defvar-local lsp-copilot-diagnostics--flycheck-enabled nil
"True when lsp-copilot diagnostics flycheck integration
has been enabled in this buffer.")
(defvar-local lsp-copilot-diagnostics--flymake-enabled nil
"True when lsp-copilot diagnostics flymake integration
has been enabled in this buffer.")
(defvar-local lsp-copilot-diagnostics--flycheck-checker nil
"The value of flycheck-checker before lsp-copilot diagnostics was activated.")
(defvar-local lsp-copilot--signature-last nil)
(defvar-local lsp-copilot--signature-last-index nil)
(defvar lsp-copilot--signature-last-buffer nil)
(defvar-local lsp-copilot--support-inlay-hints nil
"Is there any server associated with this buffer that support `textDocument/inlayHint' request.")
(defvar lsp-copilot--show-message t
"If non-nil, show debug message from `lsp-copilot-mode'.")
(defvar lsp-copilot--formatting-indent-alist
;; Taken from `dtrt-indent-mode'
'(
(ada-mode . ada-indent) ; Ada
(c++-mode . c-basic-offset) ; C++
(c++-ts-mode . c-ts-mode-indent-offset)
(c-mode . c-basic-offset) ; C
(c-ts-mode . c-ts-mode-indent-offset)
(cperl-mode . cperl-indent-level) ; Perl
(crystal-mode . crystal-indent-level) ; Crystal (Ruby)
(csharp-mode . c-basic-offset) ; C#
(csharp-tree-sitter-mode . csharp-tree-sitter-indent-offset) ; C#
(csharp-ts-mode . csharp-ts-mode-indent-offset) ; C# (tree-sitter, Emacs29)
(css-mode . css-indent-offset) ; CSS
(d-mode . c-basic-offset) ; D
(enh-ruby-mode . enh-ruby-indent-level) ; Ruby
(erlang-mode . erlang-indent-level) ; Erlang
(ess-mode . ess-indent-offset) ; ESS (R)
(go-ts-mode . go-ts-mode-indent-offset)
(hack-mode . hack-indent-offset) ; Hack
(java-mode . c-basic-offset) ; Java
(java-ts-mode . java-ts-mode-indent-offset)
(jde-mode . c-basic-offset) ; Java (JDE)
(js-mode . js-indent-level) ; JavaScript
(js2-mode . js2-basic-offset) ; JavaScript-IDE
(js3-mode . js3-indent-level) ; JavaScript-IDE
(json-mode . js-indent-level) ; JSON
(json-ts-mode . json-ts-mode-indent-offset)
(lua-mode . lua-indent-level) ; Lua
(nxml-mode . nxml-child-indent) ; XML
(objc-mode . c-basic-offset) ; Objective C
(pascal-mode . pascal-indent-level) ; Pascal
(perl-mode . perl-indent-level) ; Perl
(php-mode . c-basic-offset) ; PHP
(powershell-mode . powershell-indent) ; PowerShell
(raku-mode . raku-indent-offset) ; Perl6/Raku
(ruby-mode . ruby-indent-level) ; Ruby
(rust-mode . rust-indent-offset) ; Rust
(rust-ts-mode . rust-ts-mode-indent-offset)
(rustic-mode . rustic-indent-offset) ; Rust
(scala-mode . scala-indent:step) ; Scala
(sgml-mode . sgml-basic-offset) ; SGML
(sh-mode . sh-basic-offset) ; Shell Script
(toml-ts-mode . toml-ts-mode-indent-offset)
(typescript-mode . typescript-indent-level) ; Typescript
(typescript-ts-mode . typescript-ts-mode-indent-offset) ; Typescript (tree-sitter, Emacs29)
(yaml-mode . yaml-indent-offset) ; YAML
(default . standard-indent)) ; default fallback
"A mapping from `major-mode' to its indent variable.")
(defconst lsp-copilot--kind->symbol
'((1 . text)
(2 . method)
(3 . function)
(4 . constructor)
(5 . field)
(6 . variable)
(7 . class)
(8 . interface)
(9 . module)
(10 . property)
(11 . unit)
(12 . value)
(13 . enum)
(14 . keyword)
(15 . snippet)
(16 . color)
(17 . file)
(18 . reference)
(19 . folder)
(20 . enum-member)
(21 . constant)
(22 . struct)
(23 . event)
(24 . operator)
(25 . type-parameter)))
(defconst lsp-copilot--message-type-face
`((1 . ,compilation-error-face)
(2 . ,compilation-warning-face)
(3 . ,compilation-message-face)
(4 . ,compilation-info-face)))
;; progress token map
(defvar lsp-copilot--project-hashmap (make-hash-table :test 'equal))
(defun lsp-copilot--add-project (project-root-path project-map)
(puthash project-root-path (make-hash-table :test 'equal) project-map))
(defun lsp-copilot--remove-project (project-root-path project-map)
(if project-root-path
(remhash project-root-path project-map)))
(defun lsp-copilot--get-or-create-project (project-root-path project-map)
(or (gethash project-root-path project-map)
(lsp-copilot--add-project project-root-path project-map)
(gethash project-root-path project-map)))
(defun lsp-copilot--set-work-done-token (project-root-path token value)
(let ((project (lsp-copilot--get-or-create-project project-root-path lsp-copilot--project-hashmap)))
(if project
(puthash token value project)
(error "Project not found: %s" project-root-path))))
(defun lsp-copilot--rem-work-done-token (project-root-path token)
(let ((project (gethash project-root-path lsp-copilot--project-hashmap)))
(if project
(remhash token project)
(error "Project not found: %s" project-root-path))))
;; diagnostics map
(defvar lsp-copilot--diagnostics-map (make-hash-table :test 'equal))
;;
;; schedule
;;
(defun lsp-copilot--idle-reschedule (buffer)
"LSP copilot idle schedule on current BUFFER."
(when lsp-copilot--on-idle-timer
(cancel-timer lsp-copilot--on-idle-timer))
(setq-local lsp-copilot--on-idle-timer (run-with-idle-timer
lsp-copilot-idle-delay
nil
#'lsp-copilot--on-idle
buffer)))
(defun lsp-copilot--on-idle (buffer)
"Start post command loop on current BUFFER."
(when (and (buffer-live-p buffer)
(equal buffer (current-buffer))
lsp-copilot-mode)
(run-hooks 'lsp-copilot-on-idle-hook)))
;; log message
(defun lsp-copilot--message (format &rest args)
"Wrapper for `message'
We `inhibit-message' the message when the cursor is in the
minibuffer and when emacs version is before emacs 27 due to the
fact that we often use `lsp--info', `lsp--warn' and `lsp--error'
in async context and the call to these function is removing the
minibuffer prompt. The issue with async messages is already fixed
in emacs 27.
See #2049"
(when lsp-copilot--show-message
(let ((inhibit-message (or inhibit-message
(and (minibufferp)
(version< emacs-version "27.0")))))
(apply #'message format args))))
(defun lsp-copilot--info (format &rest args)
"Display lsp info message with FORMAT with ARGS."
(lsp-copilot--message "%s :: %s" (propertize "LSP-COPILOT" 'face 'success) (apply #'format format args)))
(defun lsp-copilot--warn (format &rest args)
"Display lsp warn message with FORMAT with ARGS."
(lsp-copilot--message "%s :: %s" (propertize "LSP-COPILOT" 'face 'warning) (apply #'format format args)))
(defun lsp-copilot--error (format &rest args)
"Display lsp error message with FORMAT with ARGS."
(lsp-copilot--message "%s :: %s" (propertize "LSP-COPILOT" 'face 'error) (apply #'format format args)))
(defun lsp-copilot--propertize (str type)
"Propertize STR as per TYPE."
(propertize str 'face (alist-get type lsp-copilot--message-type-face)))
;; Buffer local variable for storing number of lines.
(defvar lsp-copilot--log-lines)
(defun lsp-copilot-log (format &rest args)
"Log message to the *lsp-copilot-log* buffer.
FORMAT and ARGS is the same as for `messsage'."
(when lsp-copilot-log-buffer-max
(let ((log-buffer (get-buffer "*lsp-copilot-log*"))
(inhibit-read-only t))
(unless log-buffer
(setq log-buffer (get-buffer-create "*lsp-copilot-log*"))
(with-current-buffer log-buffer
(buffer-disable-undo)
(view-mode 1)
(set (make-local-variable 'lsp-copilot--log-lines) 0)))
(with-current-buffer log-buffer
(save-excursion
(let* ((message (apply 'format format args))
;; Count newlines in message.
(newlines (1+ (cl-loop with start = 0
for count from 0
while (string-match "\n" message start)
do (setq start (match-end 0))
finally return count))))
(goto-char (point-max))
;; in case the buffer is not empty insert before last \n to preserve
;; the point position(in case it is in the end)
(if (eq (point) (point-min))
(progn
(insert "\n")
(backward-char))
(backward-char)
(insert "\n"))
(insert message)
(setq lsp-copilot--log-lines (+ lsp-copilot--log-lines newlines))
(when (and (integerp lsp-copilot-log-buffer-max) (> lsp-copilot--log-lines lsp-copilot-log-buffer-max))
(let ((to-delete (- lsp-copilot--log-lines lsp-copilot-log-buffer-max)))
(goto-char (point-min))
(forward-line to-delete)
(delete-region (point-min) (point))
(setq lsp-copilot--log-lines lsp-copilot-log-buffer-max)))))))))
;; project root
(defvar-local lsp-copilot--cur-project-root nil)
(defun lsp-copilot-project-root ()
"Return the project root of current project."
(if lsp-copilot--cur-project-root
lsp-copilot--cur-project-root
;; TODO make an customizable option
(let* ((root (or (and (fboundp 'projectile-project-root) (projectile-project-root))
(project-root (project-current))))
(root-path (and root (directory-file-name root))))
(setq lsp-copilot--cur-project-root root-path)
root-path)))
;;
;; utils
;;
(eval-and-compile
(defun lsp-copilot--transform-pattern (pattern)
"Transform PATTERN to (&plist PATTERN) recursively."
(cons '&plist
(mapcar (lambda (p)
(if (listp p)
(lsp-copilot--transform-pattern p)
p))
pattern))))
(defmacro lsp-copilot--dbind (pattern source &rest body)
"Destructure SOURCE against plist PATTERN and eval BODY."
(declare (indent 2))
`(-let ((,(lsp-copilot--transform-pattern pattern) ,source))
,@body))
(defvar lsp-copilot--already-widened nil)
(defmacro lsp-copilot--save-restriction-and-excursion (&rest form)
(declare (indent 0) (debug t))
`(if lsp-copilot--already-widened
(save-excursion ,@form)
(let* ((lsp-copilot--already-widened t))
(save-restriction
(widen)
(save-excursion ,@form)))))
(cl-defmacro lsp-copilot--when-live-buffer (buf &rest body)
"Check BUF live, then do BODY in it." (declare (indent 1) (debug t))
(let ((b (cl-gensym)))
`(let ((,b ,buf)) (if (buffer-live-p ,b) (with-current-buffer ,b ,@body)))))
(cl-defmacro lsp-copilot--when-buffer-window (buf &body body)
"Check BUF showing somewhere, then do BODY in it." (declare (indent 1) (debug t))
(let ((b (cl-gensym)))
`(let ((,b ,buf))
;;notice the exception when testing with `ert'
(when (or (get-buffer-window ,b) (ert-running-test))
(with-current-buffer ,b ,@body)))))
(defun lsp-copilot--calculate-column ()
"Calculate character offset of cursor in current line."
(/ (- (length
(encode-coding-region
(line-beginning-position)
(min (point) (point-max)) 'utf-16 t))
2)
2))
(defun lsp-copilot--get-uri ()
"Get URI of current buffer."
(cond
((not buffer-file-name)
(concat "buffer://" (url-encode-url (buffer-name (current-buffer)))))
((and (eq system-type 'windows-nt)
(not (s-starts-with-p "/" buffer-file-name)))
(concat "file:///" (url-encode-url buffer-file-name)))
(t
(concat "file://" (url-encode-url buffer-file-name)))))
(declare-function w32-long-file-name "w32proc.c" (fn))
(defun lsp-copilot--uri-to-path (uri)
"Convert URI to file path."
(when (keywordp uri) (setq uri (substring (symbol-name uri) 1)))
(let* ((remote-prefix (and lsp-copilot--cur-project-root (file-remote-p lsp-copilot--cur-project-root)))
(url (url-generic-parse-url uri)))
;; Only parse file:// URIs, leave other URI untouched as
;; `file-name-handler-alist' should know how to handle them
;; (bug#58790).
(if (string= "file" (url-type url))
(let* ((retval (url-unhex-string (url-filename url)))
(normalized (if (and (not remote-prefix)
(eq system-type 'windows-nt)
(cl-plusp (length retval)))
(w32-long-file-name (substring retval 1))
retval)))
(concat remote-prefix normalized))
uri)))
(defun lsp-copilot--get-source ()
"Get source code from current buffer."
(buffer-substring-no-properties (point-min) (point-max)))
(defun lsp-copilot--position ()
(list :line (1- (line-number-at-pos)) :character (lsp-copilot--calculate-column)))
(defun lsp-copilot--point-position (point)
"Get position of the POINT."
(lsp-copilot--save-restriction-and-excursion
(goto-char point)
(lsp-copilot--position)))
(defun lsp-copilot--position-point (pos)
"Convert `Position' object POS to a point"
(let* ((line (plist-get pos :line))
(character (plist-get pos :character)))
(lsp-copilot--line-character-to-point line character)))
(defun lsp-copilot--line-character-to-point (line character)
"Return the point for character CHARACTER on line LINE."
(let ((inhibit-field-text-motion t))
(lsp-copilot--save-restriction-and-excursion
(goto-char (point-min))
(forward-line line)
;; server may send character position beyond the current line and we
;; sould fallback to line end.
(let* ((line-end (line-end-position)))
(if (> character (- line-end (point)))
line-end
(forward-char character)
(point))))))
(defun lsp-copilot--position-equal (pos-a pos-b)
"Return whether POS-A and POS-B positions are equal."
(and (= (plist-get pos-a :line) (plist-get pos-b :line))
(= (plist-get pos-a :character) (plist-get pos-b :character))))
(defun lsp-copilot--position-compare (pos-a pos-b)
"Return t if POS-A if greater thatn POS-B."
(let* ((line-a (plist-get pos-a :line))
(line-b (plist-get pos-b :line)))
(if (= line-a line-b)
(> (plist-get pos-a :character) (plist-get pos-b :character))
(> line-a line-b))))
;; TODO fix point if the line or charactor is -1
(defun lsp-copilot--range-region (range)
"Return region (BEG . END) that represents LSP RANGE.
If optional MARKERS, make markers."
(let ((beg (lsp-copilot--position-point (plist-get range :start)))
(end (lsp-copilot--position-point (plist-get range :end))))
(cons beg end)))
(defun lsp-copilot--region-range (start end)
"Make Range object for the current region."
(list :start (lsp-copilot--point-position start)
:end (lsp-copilot--point-position end)))
(defun lsp-copilot--region-or-line ()
"The active region or the current line."
(if (use-region-p)
(lsp-copilot--region-range (region-beginning) (region-end))
(lsp-copilot--region-range (line-beginning-position) (line-end-position))))
(defun lsp-copilot--format-markup (markup)
"Format MARKUP according to LSP's spec."
(pcase-let ((`(,string ,mode)
(if (stringp markup) (list markup 'gfm-view-mode)
(list (plist-get markup :value)
(pcase (plist-get markup :kind)
("markdown" 'gfm-view-mode)
("plaintext" 'text-mode)
(_ major-mode))))))
(with-temp-buffer
(setq-local markdown-fontify-code-blocks-natively t)
(insert string)
(let ((inhibit-message t)
(message-log-max nil))
(ignore-errors (delay-mode-hooks (funcall mode))))
(font-lock-ensure)
(string-trim (buffer-string)))))
(defun lsp-copilot--markdown-render ()
(when (fboundp 'gfm-view-mode)
(let ((inhibit-message t))
(setq-local markdown-fontify-code-blocks-natively t)
(set-face-background 'markdown-code-face (face-attribute 'lsp-copilot-hover-posframe :background nil t))
;; (set-face-attribute 'markdown-code-face nil :height 230)
(gfm-view-mode)))
(read-only-mode 0)
(prettify-symbols-mode 1)
(display-line-numbers-mode -1)
(font-lock-ensure)
(setq-local mode-line-format nil))
(defun lsp-copilot--expand-snippet (snippet &optional start end expand-env)
"Wrapper of `yas-expand-snippet' with all of it arguments.
The snippet will be convert to LSP style and indent according to
LSP server according to
LSP server result."
(let* ((inhibit-field-text-motion t)
(yas-wrap-around-region nil)
(yas-indent-line 'none)
(yas-also-auto-indent-first-line nil))
(yas-expand-snippet snippet start end expand-env)))
(defun lsp-copilot--indent-lines (start end &optional insert-text-mode?)
"Indent from START to END based on INSERT-TEXT-MODE? value.
- When INSERT-TEXT-MODE? is provided
- if it's `lsp/insert-text-mode-as-it', do no editor indentation.
- if it's `lsp/insert-text-mode-adjust-indentation', adjust leading
whitespaces to match the line where text is inserted.
- When it's not provided, using `indent-line-function' for each line."
(save-excursion
(goto-char end)
(let* ((end-line (line-number-at-pos))
(offset (save-excursion
(goto-char start)
(current-indentation)))
(indent-line-function
(cond ((eql insert-text-mode? 1)
#'ignore)
((or (equal insert-text-mode? 2)
lsp-copilot-enable-relative-indentation
;; Indenting snippets is extremely slow in `org-mode' buffers
;; since it has to calculate indentation based on SRC block
;; position. Thus we use relative indentation as default.
(derived-mode-p 'org-mode))
(lambda () (save-excursion
(beginning-of-line)
(indent-to-column offset))))
(t indent-line-function))))
(goto-char start)
(forward-line)
(while (and (not (eobp))
(<= (line-number-at-pos) end-line))
(funcall indent-line-function)
(forward-line)))))
(defun lsp-copilot--get-file-contents-from-list (paths)
"Get all file content of PATHS list."
(apply #'vector
(mapcar
(lambda (path)
(let ((buffer (find-file-noselect path)))
(with-current-buffer buffer
(list :path path :content (buffer-substring-no-properties (point-min) (point-max)))))) paths)))
(defun lsp-copilot--TextDocumentIdentifier ()
"Make a TextDocumentIdentifier object."
`(:textDocument
(:uri ,(lsp-copilot--get-uri))))
(defun lsp-copilot--TextDocumentPosition ()
"Make a TextDocumentPosition object."
(append `(:position ,(lsp-copilot--position))
(lsp-copilot--TextDocumentIdentifier)))
(defun lsp-copilot--request-or-notify-params (params &rest args)
"Wrap request or notify params base PARAMS and add extra ARGS."
(let ((rest (apply 'append args)))
(append (list :uri (lsp-copilot--get-uri) :params params) rest)))
(defun lsp-copilot--advice-json-parse (old-fn &rest args)
"Try to parse bytecode instead of json."
(or
(when (equal (following-char) ?#)
(let ((bytecode (read (current-buffer))))
(when (byte-code-function-p bytecode)
(funcall bytecode))))
(apply old-fn args)))
(advice-add (if (progn (require 'json)
(fboundp 'json-parse-buffer))
'json-parse-buffer
'json-read)
:around
#'lsp-copilot--advice-json-parse)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; xref integration ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun lsp-copilot--xref-backend () "lsp-copilot xref backend." 'xref-lsp-copilot)
(cl-defmethod xref-backend-identifier-at-point ((_backend (eql xref-lsp-copilot)))
(propertize (or (thing-at-point 'symbol) "")
'identifier-at-point t))
(cl-defmethod xref-backend-identifier-completion-table ((_backend (eql xref-lsp-copilot)))
(list (propertize (or (thing-at-point 'symbol) "")
'identifier-at-point t)))
(cl-defmethod xref-backend-definitions ((_backend (eql xref-lsp-copilot)) _identifier)
(save-excursion
(lsp-copilot-find-definition)))
(cl-defmethod xref-backend-references ((_backend (eql xref-lsp-copilot)) _identifier)
(save-excursion
(lsp-copilot-find-references)))
(cl-defmethod xref-backend-implementations ((_backend (eql xref-lsp-copilot)) _identifier)
(save-excursion
(lsp-copilot-find-implementations)))
(cl-defmethod xref-backend-type-definitions ((_backend (eql xref-lsp-copilot)) _identifier)
(save-excursion
(lsp-copilot-find-type-definition)))
(defcustom lsp-copilot-xref-force-references nil
"If non-nil threat everything as references(e. g. jump if only one item.)"
:group 'lsp-copilot
:type 'boolean)
(defcustom lsp-copilot-progress-prefix "⌛ "
"Progress prefix."
:group 'lsp-copilot-mode
:type 'string)
(defun lsp-copilot-show-xrefs (xrefs display-action references?)
(unless (region-active-p) (push-mark nil t))
(if (boundp 'xref-show-definitions-function)
(with-no-warnings
(xref-push-marker-stack)
(funcall (if (and references? (not lsp-xref-force-references))
xref-show-xrefs-function
xref-show-definitions-function)
(-const xrefs)
`((window . ,(selected-window))
(display-action . ,display-action)
,(if (and references? (not lsp-xref-force-references))
`(auto-jump . ,xref-auto-jump-to-first-xref)
`(auto-jump . ,xref-auto-jump-to-first-definition)))))
(xref--show-xrefs xrefs display-action)))
(defun lsp-copilot--process-locations (locations)
"Process LOCATIONS and show xrefs."
(if (seq-empty-p locations)
(lsp-copilot--error "Not found for: %s" (or (thing-at-point 'symbol t) ""))
(when-let* ((locs (cl-mapcar (lambda (it)
(let* ((uri (plist-get it :uri))
(filepath (lsp-copilot--uri-to-path uri))
(visiting (find-buffer-visiting filepath))
(range (plist-get it :range))
(start (plist-get range :start))
(end (plist-get range :end))
(start-line (plist-get start :line))
(start-column (plist-get start :character))
(_end-line (plist-get end :line))
(_end-column (plist-get end :character))
(collect (lambda ()
(save-excursion
(save-restriction
(widen)
(let* ((beg (lsp-copilot--position-point start))
(end (lsp-copilot--position-point end))
(bol (progn (goto-char beg) (line-beginning-position)))
(summary (buffer-substring bol (line-end-position)))
(hi-beg (- beg bol))
(hi-end (- (min (line-end-position) end) bol)))
(when summary
(add-face-text-property hi-beg hi-end 'xref-match t summary))
(xref-make summary
(xref-make-file-location filepath (1+ start-line) start-column))))))))
(cond
(visiting (with-current-buffer visiting (funcall collect)))
((file-readable-p filepath)
(with-temp-buffer
(insert-file-contents-literally filepath)
(funcall collect)))
(t (lsp-copilot--warn "Failed to process xref entry for file %s" filepath)))))
(if (vectorp locations) locations (vector locations)))))
(lsp-copilot-show-xrefs locs nil nil))))
;;
;; text-edit
;;
(defun lsp-copilot--apply-text-document-edit (change)
"Apply CHANGE."
(let* ((kind (gethash "kind" change))
(options (gethash "options" change))
uri
filename
new-uri new-filename
overwrite ignoreIfExists recursive ignoreIfNotExists)
(cond
((equal kind "create")
(setq uri (gethash "uri" change))
(setq filename (lsp-copilot--uri-to-path uri))
(when options
(setq overwrite (gethash "overwrite" options)
ignoreIfExists (gethash "ignoreIfExists" options)))
(if (file-exists-p filename)
(if (or overwrite
(not ignoreIfExists))
(progn
(when (find-buffer-visiting filename)
(with-current-buffer (find-buffer-visiting filename)
(save-buffer)
(kill-buffer)))
(delete-file filename t)
(with-current-buffer (find-file-noselect filename)
(save-buffer)))
(lsp-copilot--warn "Cannot create file %s." filename))
(when (find-buffer-visiting filename)
(with-current-buffer (find-buffer-visiting filename)
(save-buffer)
(kill-buffer)))
(delete-file filename t)
(with-current-buffer (find-file-noselect new-filename)
(save-buffer))))
((equal kind "rename")
(setq uri (gethash "oldUri" change))
(setq filename (lsp-copilot--uri-to-path uri))
(setq new-uri (gethash "newUri" change))
(setq new-filename (lsp-copilot--uri-to-path new-uri))
(when options
(setq overwrite (gethash "overwrite" options)
ignoreIfExists (gethash "ignoreIfExists" options)))
(if (file-exists-p new-filename)
(if (or overwrite
(not ignoreIfExists))
(progn
(when (find-buffer-visiting filename)
(with-current-buffer (find-buffer-visiting filename)
(save-buffer)
(kill-buffer)))
(when (find-buffer-visiting new-filename)
(with-current-buffer (find-buffer-visiting new-filename)
(save-buffer)
(kill-buffer)))
(rename-file filename new-filename t))
(lsp-copilot--warn "Cannot rename %s to %s" filename new-filename))
(if (find-buffer-visiting filename) ;; new filename not existing
(progn
(with-current-buffer (find-buffer-visiting filename)
(save-buffer)
(kill-buffer))
(rename-file filename new-filename t)
(find-file new-filename))
(rename-file filename new-filename t))))
((equal kind "delete")
(setq uri (gethash "uri" change))
(setq filename (lsp-copilot--uri-to-path uri))
(when options
(setq recursive (gethash "recursive" options)
ignoreIfNotExists (gethash "ignoreIfNotExists" options)))
(when (file-exists-p filename)
(if (file-directory-p filename)
(progn
(if recursive
(progn
(dolist (buf (buffer-list))
(with-current-buffer buf
(when (and buffer-file-name
(f-parent-of-p filename buffer-file-name))
(save-buffer)
(kill-buffer))))
(delete-directory filename t t))
(lsp-copilot--warn "Cannot delete directory %s" filename)))
(if (find-buffer-visiting filename)
(with-current-buffer (find-buffer-visiting filename)
(save-buffer)
(kill-buffer)))
(delete-file filename t)))))))
(defun lsp-copilot--sort-edits (edits)
(sort edits #'(lambda (edit-a edit-b)
(let* ((range-a (plist-get edit-a :range))
(range-b (plist-get edit-b :range))
(start-a (plist-get range-a :start))
(start-b (plist-get range-b :start))
(end-a (plist-get range-a :end))
(end-b (plist-get range-a :end)))
(if (lsp-copilot--position-equal start-a start-b)
(lsp-copilot--position-compare end-a end-b)
(lsp-copilot--position-compare start-a start-b))))))
(defun lsp-copilot--apply-text-edit (edit)
"Apply the edits ddescribed in the TextEdit objet in TEXT-EDIT."
(let* ((start (lsp-copilot--position-point (plist-get (plist-get edit :range) :start)))
(end (lsp-copilot--position-point (plist-get (plist-get edit :range) :end)))
(new-text (plist-get edit :newText)))
(setq new-text (s-replace "\r" "" (or new-text "")))
(plist-put edit :newText new-text)
(goto-char start)
(delete-region start end)
(insert new-text)))
(defun lsp-copilot--apply-text-edit-replace-buffer-contents (edit)
"Apply the edits described in the TextEdit object in TEXT-EDIT.
The method uses `replace-buffer-contents'."
(let* (
(source (current-buffer))
(new-text (plist-get edit :newText))
(region (lsp-copilot--range-region (plist-get edit :range)))
(beg (car region))
(end (cdr region))
;; ((beg . end) (lsp--range-to-region (lsp-make-range :start (lsp--fix-point start)
;; :end (lsp--fix-point end))))
)
(setq new-text (s-replace "\r" "" (or new-text "")))
(plist-put edit :newText new-text)
(with-temp-buffer
(insert new-text)
(let ((temp (current-buffer)))
(with-current-buffer source
(save-excursion
(save-restriction
(narrow-to-region beg end)
;; On emacs versions < 26.2,
;; `replace-buffer-contents' is buggy - it calls
;; change functions with invalid arguments - so we
;; manually call the change functions here.
;;
;; See emacs bugs #32237, #32278:
;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=32237
;; https://debbugs.gnu.org/cgi/bugreport.cgi?bug=32278
(let ((inhibit-modification-hooks t)
(length (- end beg)))
(run-hook-with-args 'before-change-functions
beg end)
(replace-buffer-contents temp)
(run-hook-with-args 'after-change-functions
beg (+ beg (length new-text))
length)))))))))
(defun lsp-copilot--apply-text-edits (edits &optional version)
"Apply the EDITS of VERSION described in the TextEdit[] object."
(unless (seq-empty-p edits)
(atomic-change-group
(let* ((change-group (prepare-change-group))
(howmany (length edits))
(message (format "Applying %s edits to `%s' ..." howmany (current-buffer)))
(_ (message message))
(reporter (make-progress-reporter message 0 howmany))
(done 0))
(unwind-protect
(mapc (lambda (edit)
(progress-reporter-update reporter (cl-incf done))
(lsp-copilot--apply-text-edit-replace-buffer-contents edit)
(when-let* ((insert-text-format (plist-get edit :insertTextFormat))
(start (lsp-copilot--position-point (plist-get (plist-get edit :range) :start)))
(new-text (plist-get edit :newText)))
(when (eq insert-text-format 2)
;; No `save-excursion' needed since expand snippet will change point anyway
(goto-char (+ start (length new-text)))
(lsp-copilot--indent-lines start (point))
(lsp-copilot--expand-snippet new-text start (point))))) (reverse edits))
(undo-amalgamate-change-group change-group)
(progress-reporter-done reporter))))))
(defun lsp-copilot--create-apply-text-edits-handlers ()
"Create (handler cleanup-fn) for applying text edits in async request.
Only works when mode is `tick or `alive."
(let* (first-edited
(func (lambda (start &rest _)
(setq first-edited (if first-edited
(min start first-edited)
start)))))
(add-hook 'before-change-functions func nil t)
(list
(lambda (edits)
(if (and first-edited
(seq-find (lambda (edit) (let* ((range (plist-get edit :range))
(end (plist-get range :end))
(end-point (lsp-copilot--position-point end)))
(message "range %s end %s" range end)
(> end-point first-edited)))
edits))
(lsp-copilot--warn "%s" "TextEdits will not be applied since document has been modified before of them.")