-
Notifications
You must be signed in to change notification settings - Fork 90
/
lsp-java.el
2179 lines (1883 loc) · 94.2 KB
/
lsp-java.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-java.el --- Java support for lsp-mode -*- lexical-binding: t; -*-
;; Version: 3.0
;; Package-Requires: ((emacs "27.1") (lsp-mode "6.0") (markdown-mode "2.3") (dash "2.18.0") (f "0.20.0") (ht "2.0") (request "0.3.0") (treemacs "2.5") (dap-mode "0.5"))
;; Keywords: languague, tools
;; URL: https://github.com/emacs-lsp/lsp-java
;; 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 of the License, 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. If not, see <http://www.gnu.org/licenses/>.
;;; Commentary:
;; Java specific adapter for LSP mode
;;; Code:
(require 'cc-mode)
(require 'lsp-mode)
(require 'markdown-mode)
(require 'lsp-treemacs)
(require 'dash)
(require 'ht)
(require 'f)
(require 'request)
(require 'cl-lib)
;; Compiler pacifier
(defvar java-ts-mode-indent-offset)
(defgroup lsp-java nil
"JDT emacs frontend."
:prefix "lsp-java-"
:group 'applications
:link '(url-link :tag "GitHub" "https://github.com/emacs-lsp/lsp-java"))
(defcustom lsp-java-server-install-dir (f-join lsp-server-install-dir "eclipse.jdt.ls/")
"Install directory for eclipse.jdt.ls-server.
The slash is expected at the end."
:risky t
:type 'directory)
(defcustom lsp-java-jdt-ls-prefer-native-command nil
"Use native jdtls command provided by jdtls installation instead of
lsp's java -jar invocation."
:risky t
:type 'boolean)
(defcustom lsp-java-jdt-ls-command "jdtls"
"Native jdtls command provided by jdtls installation."
:risky t
:type 'string)
(defcustom lsp-java-jdt-download-url "https://www.eclipse.org/downloads/download.php?file=/jdtls/milestones/1.23.0/jdt-language-server-1.23.0-202304271346.tar.gz"
"JDT JS download url.
Use https://download.eclipse.org/jdtls/milestones/1.12.0/jdt-language-server-1.12.0-202206011637.tar.gz if you want to use older java version."
:type 'string)
(defcustom lsp-java-server-config-dir nil
"Path to your platform's configuration directory.
This path has to be writable. This configuration is specifically
created for systems like NixOS where the default configuration
directory inferred by lsp-java is not writable."
:group 'lsp-java
:risky t
:type 'directory)
(defcustom lsp-java-java-path "java"
"Path of the java executable."
:type 'string)
(defvar lsp-java-progress-string ""
"Java progress status as reported by the language server.")
(defface lsp-java-progress-face
'((t (:inherit success)))
"face for activity message"
:group 'lsp-java)
(defcustom lsp-java-workspace-dir (expand-file-name (locate-user-emacs-file "workspace/"))
"LSP java workspace directory."
:risky t
:type 'directory)
(defcustom lsp-java-workspace-cache-dir (expand-file-name ".cache/" lsp-java-workspace-dir)
"LSP java workspace cache directory."
:risky t
:type 'directory)
(defcustom lsp-java-themes-directory (f-join (f-dirname (or load-file-name buffer-file-name)) "icons")
"Directory containing themes."
:type 'directory
:group 'lsp-java)
(defcustom lsp-java-theme "vscode"
"Theme to use."
:type 'string
:group 'lsp-java)
(defcustom lsp-java-pop-buffer-function 'lsp-java-show-buffer
"The function which will be used for showing the helper windows."
:type 'function
:group 'lsp-java)
(defcustom lsp-java-vmargs '("-XX:+UseParallelGC" "-XX:GCTimeRatio=4" "-XX:AdaptiveSizePolicyWeight=90" "-Dsun.zip.disableMemoryMapping=true" "-Xmx1G" "-Xms100m")
"Specifies extra VM arguments used to launch the Java Language Server.
Eg. use `-noverify -Xmx1G -XX:+UseG1GC
-XX:+UseStringDeduplication` to bypass class
verification,increase the heap size to 1GB and enable String
deduplication with the G1 Garbage collector"
:risky t
:type '(repeat string))
(defcustom lsp-java-9-args '("--add-modules=ALL-SYSTEM" "--add-opens java.base/java.util=ALL-UNNAMED" "--add-opens java.base/java.lang=ALL-UNNAMED")
"Specifies arguments specific to java 9 and later."
:risky t
:type '(repeat string))
(lsp-defcustom lsp-java-errors-incomplete-classpath-severity "warning"
"Specifies the severity of the message when the classpath is
incomplete for a Java file"
:type '(choice (const "ignore")
(const "info")
(const "warning")
(const "error"))
:lsp-path "java.errors.incompleteClasspath.severity")
(lsp-defcustom lsp-java-dependency-package-representation "flat"
"Specifies the severity of the message when the classpath is
incomplete for a Java file"
:type '(choice (const "flat")
(const "hierarchical"))
:lsp-path "java.dependency.packagePresentation")
(lsp-defcustom lsp-java-configuration-check-project-settings-exclusions t
"Checks if the extension-generated project settings
files (.project, .classpath, .factorypath, .settings/) should be
excluded from the file explorer."
:type 'boolean
:lsp-path "java.configuration.checkProjectSettingsExclusions")
(lsp-defcustom lsp-java-configuration-update-build-configuration "automatic"
"Specifies how modifications on build files update the Java
classpath/configuration"
:type '(choice (const "disabled")
(const "interactive")
(const "automatic"))
:lsp-path "java.configuration.updateBuildConfiguration")
(lsp-defcustom lsp-java-trace-server "off"
"Traces the communication between VS Code and the Java language
server."
:type '(choice (const "off")
(const "messages")
(const "verbose"))
:lsp-path "java.trace.server")
(lsp-defcustom lsp-java-import-gradle-enabled t
"Enable/disable the Gradle importer."
:type 'boolean
:lsp-path "java.import.gradle.enabled")
(defcustom lsp-java-import-gradle-version nil
"Gradle version, used if the gradle wrapper is missing or disabled."
:type '(choice (string)
(const nil))
:group 'lsp-java)
(lsp-defcustom lsp-java-import-gradle-jvm-arguments nil
"JVM arguments to pass to Gradle.
If set manually, this variable has to be converted to a format
that `json-serialize' can understand. For instance, you cannot
pass a list, only a vector."
:type '(lsp-repeatable-vector string)
:lsp-path "java.import.gradle.jvmArguments")
(lsp-defcustom lsp-java-import-gradle-wrapper-enabled t
"Enable/disable using the Gradle wrapper distribution."
:type 'boolean
:lsp-path "java.import.gradle.wrapper.enabled")
(lsp-defcustom lsp-java-import-maven-enabled t
"Enable/disable the Maven importer."
:type 'boolean
:lsp-path "java.import.maven.enabled")
(lsp-defcustom lsp-java-maven-download-sources nil
"Enable/disable eager download of Maven source artifacts."
:type 'boolean
:lsp-path "java.maven.downloadSources")
(lsp-defcustom lsp-java-references-code-lens-enabled nil
"Enable/disable the references code lens."
:type 'boolean
:lsp-path "java.referencesCodeLens.enabled")
(lsp-defcustom lsp-java-signature-help-enabled t
"Enable/disable the signature help."
:type 'boolean
:lsp-path "java.signatureHelp.enabled")
(lsp-defcustom lsp-java-implementations-code-lens-enabled nil
"Enable/disable the implementations code lens."
:type 'boolean
:lsp-path "java.implementationsCodeLens.enabled")
(lsp-defcustom lsp-java-configuration-maven-user-settings nil
"Path to Maven's settings.xml"
:type '(choice (string)
(const nil))
:lsp-path "java.configuration.maven.userSettings")
(lsp-defcustom lsp-java-format-enabled t
"Enable/disable default Java formatter"
:type 'boolean
:lsp-path "java.format.enabled")
(lsp-defcustom lsp-java-save-actions-organize-imports nil
"Enable/disable auto organize imports on save action"
:type 'boolean
:lsp-path "java.saveActions.organizeImports")
(lsp-defcustom lsp-java-import-exclusions ["**/node_modules/**" "**/.metadata/**" "**/archetype-resources/**" "**/META-INF/maven/**"]
"Configure glob patterns for excluding folders when importing for the first time"
:type '(lsp-repeatable-vector string)
:lsp-path "java.import.exclusions")
(lsp-defcustom lsp-java-project-resource-filters ["node_modules" ".metadata" "archetype-resources" "META-INF/maven"]
"Configure glob patterns for excluding folders whenever workspace is refreshed"
:type '(lsp-repeatable-vector string)
:lsp-path "java.project.resourceFilters")
(lsp-defcustom lsp-java-content-provider-preferred nil
"Preferred content provider (a 3rd party decompiler id,
usually)"
:type '(choice (string)
(const nil))
:lsp-path "java.contentProvider.preferred")
(lsp-defcustom lsp-java-autobuild-enabled t
"Enable/disable the \"auto build\""
:type 'boolean
:lsp-path "java.autobuild.enabled")
(lsp-defcustom lsp-java-selection-enabled t
"Enable/disable the selection range"
:type 'boolean
:lsp-path "java.selectionRange.enabled")
(lsp-defcustom lsp-java-max-concurrent-builds 1
"Max simultaneous project builds"
:type 'number
:lsp-path "java.maxConcurrentBuilds")
(lsp-defcustom lsp-java-completion-enabled t
"Enable/disable code completion support"
:type 'boolean
:lsp-path "java.completion.enabled")
(lsp-defcustom lsp-java-completion-overwrite t
"When set to true, code completion overwrites the current text.
When set to false, code is simply added instead."
:type 'boolean
:lsp-path "java.completion.overwrite")
(lsp-defcustom lsp-java-completion-guess-method-arguments t
"When set to true, method arguments are guessed when a method
is selected from as list of code assist proposals."
:type 'boolean
:lsp-path "java.completion.guessMethodArguments")
(lsp-defcustom lsp-java-completion-favorite-static-members ["org.junit.Assert.*" "org.junit.Assume.*" "org.junit.jupiter.api.Assertions.*" "org.junit.jupiter.api.Assumptions.*" "org.junit.jupiter.api.DynamicContainer.*" "org.junit.jupiter.api.DynamicTest.*" "org.mockito.Mockito.*" "org.mockito.ArgumentMatchers.*" "org.mockito.Answers.*"]
"Defines a list of static members or types with static members.
Content assist will propose those static members even if the
import is missing."
:type '(lsp-repeatable-vector string)
:lsp-path "java.completion.favoriteStaticMembers")
(lsp-defcustom lsp-java-completion-import-order ["java" "javax" "com" "org"]
"Defines the sorting order of import statements.
A package or type name prefix (e.g. `org.eclipse') is a valid entry.
An import is always added to the most specific group."
:type '(lsp-repeatable-vector string)
:lsp-path "java.completion.importOrder")
(lsp-defcustom lsp-java-folding-range-enabled t
"Enable/disable smart folding range support.
If disabled, it will use the default indentation-based folding range provided by
VS Code."
:type 'boolean
:lsp-path "java.foldingRange.enabled")
(lsp-defcustom lsp-java-progress-reports-enabled t
"[Experimental] Enable/disable progress reports from background
processes on the server."
:type 'boolean
:lsp-path "java.progressReports.enabled")
(lsp-defcustom lsp-java-format-settings-url nil
"Specifies the url or file path to the [Eclipse formatter XML settings]
(https://github.com/redhat-developer/vscode-java/wiki/Formatter-settings)."
:type '(choice (string)
(const nil))
:lsp-path "java.format.settings.url")
(lsp-defcustom lsp-java-format-settings-profile nil
"Optional formatter profile name from the Eclipse formatter
settings."
:type '(choice (string)
(const nil))
:lsp-path "java.format.settings.profile")
(lsp-defcustom lsp-java-format-comments-enabled t
"Includes the comments during code formatting."
:type 'boolean
:lsp-path "java.format.comments.enabled")
(lsp-defcustom lsp-java-format-on-type-enabled t
"Enable/disable automatic block formatting when typing `;`,
`<enter>` or `}`"
:type 'boolean
:lsp-path "java.format.onType.enabled")
(defcustom lsp-java-bundles nil
"List of bundles that will be loaded in the JDT server."
:group 'lsp-java
:type '(repeat string))
(lsp-defcustom lsp-java-code-generation-hash-code-equals-use-java7objects nil
"Use Objects.hash and Objects.equals when generating the
hashCode and equals methods. This setting only applies to Java 7
and higher."
:type 'boolean
:lsp-path "java.codeGeneration.hashCodeEquals.useJava7Objects")
(lsp-defcustom lsp-java-code-generation-hash-code-equals-use-instanceof nil
"Use `instanceof' to compare types when generating the hashCode
and equals methods."
:type 'boolean
:lsp-path "java.codeGeneration.hashCodeEquals.useInstanceof")
(lsp-defcustom lsp-java-code-generation-use-blocks nil
"Use blocks in `if' statements when generating the methods."
:type 'boolean
:lsp-path "java.codeGeneration.useBlocks")
(lsp-defcustom lsp-java-code-generation-generate-comments nil
"Generate method comments when generating the methods."
:type 'boolean
:lsp-path "java.codeGeneration.generateComments")
(lsp-defcustom lsp-java-code-generation-to-string-template "${object.className} [${member.name()}=${member.value}, ${otherMembers}]"
"The template for generating the toString method."
:type 'string
:lsp-path "java.codeGeneration.toString.template")
(lsp-defcustom lsp-java-code-generation-to-string-code-style "STRING_CONCATENATION"
"The code style for generating the toString method."
:type '(choice (const "STRING_CONCATENATION")
(const "STRING_BUILDER")
(const "STRING_BUILDER_CHAINED")
(const "STRING_FORMAT"))
:lsp-path "java.codeGeneration.toString.codeStyle")
(lsp-defcustom
lsp-java-code-generation-to-string-skip-null-values nil
"Skip null values when generating the toString method."
:type 'boolean
:lsp-path "java.codeGeneration.toString.skipNullValues")
(lsp-defcustom lsp-java-code-generation-to-string-list-array-contents t
"List contents of arrays instead of using native toString()."
:type 'boolean
:lsp-path "java.codeGeneration.toString.listArrayContents")
(lsp-defcustom lsp-java-code-generation-to-string-limit-elements 0
"Limit number of items in arrays/collections/maps to list, if 0
then list all."
:type 'number
:lsp-path "java.codeGeneration.toString.limitElements")
(lsp-defcustom lsp-java-completion-filtered-types ["java.awt.*" "com.sun.*"]
"Defines the type filters. All types whose fully qualified name
matches the selected filter strings will be ignored in content
assist or quick fix proposals and when organizing imports. For
example `java.awt.*' will hide all types from the awt packages."
:type '(lsp-repeatable-vector string)
:lsp-path "java.completion.filteredTypes")
(lsp-defcustom lsp-java-format-tab-size (lambda () (if (equal major-mode 'java-ts-mode)
java-ts-mode-indent-offset
c-basic-offset))
"The basic offset"
:type 'function
:lsp-path "java.format.tabSize")
(lsp-defcustom lsp-java-format-insert-spaces (lambda () (not indent-tabs-mode))
"Returns whether tabs/spaces are used"
:type 'function
:lsp-path "java.format.insertSpaces")
(declare-function projectile-project-p "ext:projectile")
(declare-function projectile-project-root "ext:projectile")
(declare-function helm-make-source "ext:helm-source")
(defcustom lsp-java-inhibit-message t
"If non-nil, inhibit java messages echo via `inhibit-message'."
:type 'boolean
:group 'lsp-mode)
(lsp-defcustom lsp-java-import-gradle-home nil
"Use Gradle from the specified local installation directory or
GRADLE_HOME if the Gradle wrapper is missing or disabled and no
`java.import.gradle.version' is specified."
:type '(choice (string)
(const nil))
:lsp-path "java.import.gradle.home")
(lsp-defcustom lsp-java-import-gradle-java-home nil
"The location to the JVM used to run the Gradle daemon."
:type '(choice (string)
(const nil))
:lsp-path "java.import.gradle.java.home")
(lsp-defcustom lsp-java-import-gradle-offline-enabled nil
"Enable/disable the Gradle offline mode."
:type 'boolean
:lsp-path "java.import.gradle.offline.enabled")
(lsp-defcustom lsp-java-import-gradle-arguments nil
"Arguments to pass to Gradle."
:type '(choice (string)
(const nil))
:lsp-path "java.import.gradle.arguments")
(lsp-defcustom lsp-java-import-gradle-user-home nil
"Setting for GRADLE_USER_HOME."
:type '(choice (string)
(const nil))
:lsp-path "java.import.gradle.user.home")
(lsp-defcustom lsp-java-maven-update-snapshots nil
"Force update of Snapshots/Releases."
:type 'boolean
:lsp-path "java.maven.updateSnapshots")
(lsp-defcustom lsp-java-project-referenced-libraries ["lib/**/*.jar"]
"Configure glob patterns for referencing local libraries to a
Java project."
:type '(lsp-repeatable-vector string)
:lsp-path "java.project.referencedLibraries")
(lsp-defcustom lsp-java-completion-max-results 0
"Maximum number of completion results (not including
snippets).`0' (the default value) disables the limit, all results
are returned. In case of performance problems, consider setting a
sensible limit."
:type 'number
:lsp-path "java.completion.maxResults")
(lsp-defcustom lsp-java-selection-range-enabled t
"Enable/disable Smart Selection support for Java. Disabling
this option will not affect the VS Code built-in word-based and
bracket-based smart selection."
:type 'boolean
:lsp-path "java.selectionRange.enabled")
(lsp-defcustom lsp-java-show-build-status-on-start-enabled nil
"Automatically show build status on startup."
:type 'boolean
:lsp-path "java.showBuildStatusOnStart.enabled")
(lsp-defcustom lsp-java-configuration-runtimes nil
"Map Java Execution Environments to local JDKs."
:type '(lsp-repeatable-vector string)
:lsp-path "java.configuration.runtimes")
(lsp-defcustom lsp-java-server-launch-mode "Hybrid"
"The launch mode for the Java extension"
:type '(choice (const "Standard")
(const "LightWeight")
(const "Hybrid"))
:lsp-path "java.server.launchMode")
(lsp-defcustom lsp-java-sources-organize-imports-star-threshold 99
"Specifies the number of imports added before a star-import declaration is used."
:type 'number
:lsp-path "java.sources.organizeImports.starThreshold")
(lsp-defcustom lsp-java-sources-organize-imports-static-star-threshold 99
"Specifies the number of static imports added before a
star-import declaration is used."
:type 'number
:lsp-path "java.sources.organizeImports.staticStarThreshold")
(lsp-defcustom lsp-java-imports-gradle-wrapper-checksums []
"Defines allowed/disallowed SHA-256 checksums of Gradle Wrappers.
Sample value: [(:sha256 \"504b..\" :allowed t)]"
:type '(lsp-repeatable-vector
(plist :key-type (choice (const :tag "sha256" :sha256)
(const :tag "allowed" :allowed))
:value-type (choice string boolean)))
:lsp-path "java.imports.gradle.wrapper.checksums")
(lsp-defcustom lsp-java-project-import-on-first-time-startup "automatic"
"Specifies whether to import the Java projects, when opening
the folder in Hybrid mode for the first time."
:type '(choice (const "disabled")
(const "interactive")
(const "automatic"))
:lsp-path "java.project.importOnFirstTimeStartup")
(lsp-defcustom lsp-java-project-import-hint t
"Enable/disable the server-mode switch information, when Java
projects import is skipped on startup."
:type 'boolean
:lsp-path "java.project.importHint")
(defvar lsp-java--download-root "https://raw.githubusercontent.com/emacs-lsp/lsp-java/master/install/")
(defun lsp-java--json-bool (param)
"Return a PARAM for setting parsable by json.el for booleans."
(or param :json-false))
(defun lsp-java--list-or-empty (param)
"Return either PARAM or empty vector in case PARAM is nil."
(or param (vector)))
(defvar lsp-java-buffer-configurations
`(("*classpath*" . ((side . right) (slot . 10) (window-width . 0.20)))))
(defun lsp-java-show-buffer (buf)
"Show BUF according to defined rules."
(let ((win (display-buffer-in-side-window buf
(or (-> buf
buffer-name
(assoc lsp-java-buffer-configurations)
cl-rest)
'((side . right)
(slot . 1)
(window-width . 0.20))))))
(set-window-dedicated-p win t)
(select-window win)))
(defun lsp-java--locate-server-jar ()
"Return the jar file location of the language server.
The entry point of the language server is in the `lsp-java-server-install-dir'
+ /plugins/org.eclipse.equinox.launcher_`version'.jar."
(pcase (f-glob "org.eclipse.equinox.launcher_*.jar" (expand-file-name "plugins" lsp-java-server-install-dir))
(`(,single-entry) single-entry)
(`nil nil)
(server-jar-filenames
(error "Unable to find single point of entry %s" server-jar-filenames))))
(defun lsp-java--locate-server-command ()
"Return the jdtls command location of the language server.
The entry point of the language server is in the
`lsp-java-server-install-dir'/bin/jdtls[.bat]."
(let ((bin-path (expand-file-name "bin" lsp-java-server-install-dir)))
(locate-file lsp-java-jdt-ls-command `(,bin-path) exec-suffixes 1)))
(defun lsp-java--locate-server-config ()
"Return the server config based on OS."
(let ((config (cond
((string-equal system-type "windows-nt") ; Microsoft Windows
"config_win")
((string-equal system-type "darwin") ; Mac OS X
"config_mac")
(t "config_linux"))))
(let ((inhibit-message t))
(message (format "using config for %s" config)))
(expand-file-name config lsp-java-server-install-dir)))
(defun lsp-java--current-workspace-or-lose ()
"Look for the jdt-ls workspace."
(or lsp--cur-workspace
(lsp-find-workspace 'jdtls (buffer-file-name))
(error "Unable to find workspace")))
(defmacro lsp-java-with-jdtls (&rest body)
"Helper macro for invoking BODY against WORKSPACE context."
(declare (debug (form body))
(indent 0))
`(let ((lsp--cur-workspace (lsp-java--current-workspace-or-lose))) ,@body))
(defun lsp-java-build-project (&optional full)
"Perform project build action.
FULL specify whether full or incremental build will be performed."
(interactive "P" )
(lsp-java-with-jdtls
(setf (lsp--workspace-status-string (cl-first (lsp-workspaces)))
(propertize "Building project..."
'face 'success))
(force-mode-line-update)
(lsp-request-async
"java/buildWorkspace"
(lsp-json-bool full)
(lambda (result)
(setf (lsp--workspace-status-string (cl-first (lsp-workspaces))) nil)
(force-mode-line-update)
(pcase result
(1 (lsp--info "Successfully build project."))
(2 (lsp--error "Failed to build project."))))
:mode 'detached)))
(defun lsp-java-update-project-configuration ()
"Update project configuration."
(interactive)
(let ((file-name (file-name-nondirectory (buffer-file-name))))
(if (or (string= file-name "pom.xml") (string-match "\\.gradle" file-name))
(lsp-java-with-jdtls
(lsp-notify "java/projectConfigurationUpdate"
(lsp--text-document-identifier)))
(error "Update configuration could be called only from build file(pom.xml or gradle build file)"))))
(defun lsp-java--ensure-dir (path)
"Ensure that directory PATH exists."
(unless (file-directory-p path)
(make-directory path t)))
(lsp-defun lsp-java--show-references ((&Command :arguments? params))
;; (_server (_command (eql java.show.references)) params)
(if-let (refs (seq-elt params 2))
(lsp-show-xrefs (lsp--locations-to-xref-items refs) nil t)
(user-error "No references")))
(lsp-defun lsp-java--show-implementations ((&Command :arguments? params))
;; (_server (_command (eql java.show.implementations)) params)
(if-let (refs (seq-elt params 2))
(lsp-show-xrefs (lsp--locations-to-xref-items refs) nil nil)
(user-error "No implementations")))
(defun lsp-java--get-java-version ()
"Retrieve the java version from shell command."
(let* ((java-version-output (shell-command-to-string (concat lsp-java-java-path " -version")))
(version-string (nth 2 (split-string java-version-output))))
(string-to-number (replace-regexp-in-string "\"" "" version-string))))
(defun lsp-java--java-9-plus-p ()
"Check if java version is greater than or equal to 9."
(let ((java-version (lsp-java--get-java-version)))
(>= java-version 9)))
(defun lsp-java--get-gradle-version ()
"Return the gradle version to use if gradlew is disabled or absent."
(cond
;; if gradlew distribution is used, then the gradle version is irrelevant
(lsp-java-import-gradle-wrapper-enabled nil)
;; if the gradle version is set, then use it
(lsp-java-import-gradle-version lsp-java-import-gradle-version)
;; otherwise, get the version from gradlew at the project root, if any
;; this is also a workaround for when gradle-wrapper.properties is not at its default location
(t (let* ((project-gradlew (f-join (lsp-java--get-root) "gradlew -v"))
(gradle-version-output (shell-command-to-string project-gradlew)))
(when (string-match "Revision" gradle-version-output)
(nth 2 (split-string gradle-version-output)))))))
(defun lsp-java--ls-command ()
"LS startup command."
(let ((server-cmd (lsp-java--locate-server-command)))
(if (and lsp-java-jdt-ls-prefer-native-command
server-cmd)
`(,server-cmd
"--jvm-arg=-Dlog.protocol=true"
"--jvm-arg=-Dlog.level=ALL"
,@(mapcar (lambda (str) (concat "--jvm-arg=" str)) lsp-java-vmargs))
(let ((server-jar (lsp-file-local-name (lsp-java--locate-server-jar)))
(server-config (if lsp-java-server-config-dir
lsp-java-server-config-dir
(lsp-file-local-name (lsp-java--locate-server-config))))
(java-9-args (when (lsp-java--java-9-plus-p)
lsp-java-9-args)))
(lsp-java--ensure-dir lsp-java-workspace-dir)
`(,lsp-java-java-path
"-Declipse.application=org.eclipse.jdt.ls.core.id1"
"-Dosgi.bundles.defaultStartLevel=4"
"-Declipse.product=org.eclipse.jdt.ls.core.product"
"-Dlog.protocol=true"
"-Dlog.level=ALL"
,@lsp-java-vmargs
"-jar"
,server-jar
"-configuration"
,server-config
"-data"
,(lsp-file-local-name lsp-java-workspace-dir)
,@java-9-args)))))
(eval-and-compile
(lsp-interface
(java:Status (:message :type))
(java:Progress (:status :complete))
(java:ActionbleNotification (:commands))
(java:OrganizeImports (:candidates :range))
(java:Import (:fullyQualifiedName))
(java:ToString (:fields :exists))
(java:Equals (:fields :existingMethods))
(java:ConstructorsStatus (:fields :constructors))
(java:Constructor (:name :parameters))
(java:Field (:name :type))
(java:Destination (:displayName :path))
(java:OverridableMethod (:name :parameters :declaringClass))
(java:MoveDestinations (:destinations))
(java:ListOverridableMethods (:methods))
(java:MoveTypeInfo (:enclosingTypeName :displayName :projectName :supportedDestinationKinds))
(java:MoveContext (:textDocument))
(java:MoveResult nil (:edit :message :command))
(java:ResolveMethods (:fieldName))
(java:MoveInstanceResult (:destinations :errorMessage))
(java:MoveInstanceCommandInfo (:methodName))
(java:MoveDestination (:name :type :isField))
(java:FieldCommandInfo (:initializedScopes))
(java:MainClassInfo (:mainClass :projectName))
(java:RenameParams (:uri :offset :length))))
(defun lsp-java--get-root ()
"Retrieves the root directory of the java project root if available.
The current directory is assumed to be the java project’s root otherwise."
(cond
;; the cache directory root
((string= default-directory lsp-java-workspace-cache-dir) default-directory)
((and (featurep 'projectile) (projectile-project-p)) (projectile-project-root))
((vc-backend default-directory) (expand-file-name (vc-root-dir)))
(t (let ((project-types '("pom.xml" "build.gradle" ".project")))
(or (seq-some (lambda (file) (locate-dominating-file default-directory file)) project-types)
default-directory)))))
(lsp-defun lsp-java--language-status-callback (workspace (&java:Status :type :message))
"Callback for client initialized.
WORKSPACE is the currently active workspace.
PARAMS the parameters for language status notifications."
(let ((status type)
(current-status (lsp-workspace-get-metadata "status" workspace)))
;; process the status message only if there is no status or if the status is
;; starting (workaround for bug https://github.com/eclipse/eclipse.jdt.ls/issues/651)
(when (not (and (or (string= current-status "Error" )
(string= current-status "Started" ))
(string= "Starting" status)))
(let ((inhibit-message lsp-java-inhibit-message))
(lsp-log "%s[%s]" message type)))))
(lsp-defun lsp-java--apply-workspace-edit ((&Command :arguments?))
"Callback for java/applyWorkspaceEdit.
ACTION is the action to execute."
(lsp--apply-workspace-edit (lsp-seq-first arguments?)))
(lsp-defun lsp-java--actionable-notification-callback (_workspace (&java:Status :message))
"Handler for actionable notifications.
WORKSPACE is the currently active workspace.
PARAMS the parameters for actionable notifications."
(lsp--warn message))
(lsp-defun lsp-java--progress-report (_workspace (&java:Progress :complete :status))
"Progress report handling.
PARAMS progress report notification data."
(setq lsp-java-progress-string (propertize status 'face 'lsp-java-progress-face))
(when complete
(run-with-idle-timer 0.8 nil (lambda ()
(setq lsp-java-progress-string nil)))))
(put 'lsp-java-progress-string 'risky-local-variable t)
(defun lsp-java--render-string (str)
"Render STR with `java-mode and java-ts-mode' syntax highlight."
(condition-case nil
(with-temp-buffer
(delay-mode-hooks (java-mode))
(insert str)
(font-lock-ensure)
(buffer-string))
(error str)))
(defun lsp-java--prepare-mvnw ()
"Download mvnw and return the invocation command."
(let ((mvn-executable (if (string-equal system-type "windows-nt")
"mvnw.cmd"
"mvnw"))
(downloader ".mvn/wrapper/MavenWrapperDownloader.java")
(properties ".mvn/wrapper/maven-wrapper.properties"))
(mkdir ".mvn/wrapper/" t)
(url-copy-file (concat lsp-java--download-root mvn-executable)
mvn-executable
t)
(url-copy-file (concat lsp-java--download-root downloader) downloader t)
(url-copy-file (concat lsp-java--download-root properties) properties t)
(if (string= system-type "windows-nt")
(list mvn-executable)
(list "sh" mvn-executable))))
(defun lsp-java--bundles-dir ()
"Get default bundles dir."
(concat (lsp-file-local-name (file-name-as-directory lsp-java-server-install-dir)) "bundles"))
(defun lsp-java--ensure-server (_client callback error-callback _update?)
"Ensure that JDT server and the other configuration."
(f-delete lsp-java-server-install-dir t)
(f-delete lsp-java-workspace-cache-dir t)
(f-delete lsp-java-workspace-dir t)
(let* ((default-directory (make-temp-file "lsp-java-install" t))
(installed-mvn (executable-find "mvn"))
(mvn-command-and-options (if installed-mvn
(list installed-mvn)
(lsp-java--prepare-mvnw)))
(other-options
(list (format "-Djdt.js.server.root=%s"
(expand-file-name lsp-java-server-install-dir))
(format "-Djunit.runner.root=%s"
(expand-file-name
(if (boundp 'dap-java-test-runner)
(file-name-directory dap-java-test-runner)
(concat (file-name-directory lsp-java-server-install-dir)
"test-runner"))))
(format "-Djunit.runner.fileName=%s"
(if (boundp 'dap-java-test-runner)
(file-name-nondirectory (directory-file-name dap-java-test-runner))
"junit-platform-console-standalone.jar"))
(format "-Djava.debug.root=%s"
(expand-file-name (lsp-java--bundles-dir)))
"clean"
"package"
(format "-Djdt.download.url=%s" lsp-java-jdt-download-url))))
(url-copy-file (concat lsp-java--download-root "pom.xml") "pom.xml" t)
(apply #'lsp-async-start-process
callback
error-callback
(append mvn-command-and-options other-options))))
(defun lsp-java-update-server ()
(interactive)
(error "lsp-java-update-server is deprecated, use `C-u M-x lsp-install-server'"))
(defun lsp-java--workspace-notify (&rest _args)
"Workspace notify handler.")
(defun lsp-java--get-filename (url)
"Get the name of the buffer calculating it based on URL."
(or (save-match-data
(when (string-match "jdt://contents/\\(.*?\\)/\\(.*\\)\.class\\?" url)
(format "%s.java"
(replace-regexp-in-string "/" "." (match-string 2 url) t t))))
(-when-let ((_ file-name _ jar)
(s-match
"jdt://.*?/\\(.*?\\)\\?=\\(.*?\\)/.*/\\(.*\\)"
(url-unhex-string url)))
(format "%s(%s)" file-name
(->> jar
(s-replace "/" "")
(s-replace "\\" ""))))
(save-match-data
(when (string-match "chelib://\\(.*\\)" url)
(let ((matched (match-string 1 url)))
(replace-regexp-in-string (regexp-quote ".jar") "jar" matched t t))))
(error "Unable to match %s" url)))
(defun lsp-java--get-metadata-location (file-location)
"Given a FILE-LOCATION return the file containing the metadata for the file."
(format "%s.%s.metadata"
(file-name-directory file-location)
(file-name-base file-location)))
(defun lsp-java--resolve-uri (uri)
"Load a file corresponding to URI executing request to the jdt server."
(let* ((buffer-name (lsp-java--get-filename uri))
(file-location (concat lsp-java-workspace-cache-dir buffer-name)))
(unless (file-readable-p file-location)
(lsp-java--ensure-dir (file-name-directory file-location))
(with-lsp-workspace (lsp-find-workspace 'jdtls nil)
(let ((content (lsp-send-request (lsp-make-request
"java/classFileContents"
(list :uri uri)))))
(with-temp-file file-location
(insert content))
(with-temp-file (lsp-java--get-metadata-location file-location)
(insert uri)))))
file-location))
(defun lsp-java-execute-matching-action (regexp &optional not-found-message)
"Execute the code action which title match the REGEXP.
NOT-FOUND-MESSAGE will be used if there is no matching action."
(let ((actions (cl-remove-if-not
(lambda (item) (string-match regexp (lsp:code-action-title item)))
(lsp-get-or-calculate-code-actions))))
(pcase (length actions)
(0 (error (or not-found-message "Unable to find action")))
(1 (lsp-execute-code-action (car actions)))
(_ (lsp-execute-code-action (lsp--select-action actions))))))
(defun lsp-java-extract-to-local-variable (arg)
"Extract local variable refactoring.
The prefix ARG decide whether to act on all or only on the
current symbol."
(interactive "P")
(lsp-java-execute-matching-action
(if arg
"Extract to local variable$"
"Extract to local variable (replace all occurrences)")))
(defun lsp-java-convert-to-static-import (arg)
"Convert to static import.
The prefix ARG decide whether to act on all or only on the
current symbol."
(interactive "P")
(lsp-java-execute-matching-action
(if arg
"Convert to static import$"
"Convert to static import (replace all occurrences)$")))
(defun lsp-java-extract-to-constant ()
"Extract constant refactoring."
(interactive)
(lsp-java-execute-matching-action "Extract to constant"))
(defun lsp-java-add-throws ()
"Extract constant refactoring."
(interactive)
(lsp-java-execute-matching-action "Add throws declaration"))
(defun lsp-java-add-unimplemented-methods ()
"Extract constant refactoring."
(interactive)
(lsp-java-execute-matching-action "Add unimplemented methods"))
(defun lsp-java-create-parameter ()
"Create parameter refactoring."
(interactive)
(lsp-java-execute-matching-action "Create parameter '"))
(defun lsp-java-create-field ()
"Create field refactoring."
(interactive)
(lsp-java-execute-matching-action "Create field '"))
(defun lsp-java-create-local ()
"Create local refactoring."
(interactive)
(lsp-java-execute-matching-action "Create local variable"))
(defun lsp-java-extract-method ()
"Extract method refactoring."
(interactive)
(lsp-java-execute-matching-action "Extract to method"))
(defun lsp-java-inline ()
"Inline."
(interactive)
(lsp-java-execute-matching-action "Inline"))
(defun lsp-java-assign-to-field ()
"Assign to new field."
(interactive)
(lsp-java-execute-matching-action "Assign parameter to new field"))
(defun lsp-java-assign-statement-to-local ()
"Assign statement to new local variable"
(interactive)
(lsp-java-execute-matching-action "Assign statement to new local variable"))
(defun lsp-java-assign-statement-to-field ()
"Assign statement to new field"
(interactive)
(lsp-java-execute-matching-action "Assign statement to new field"))
(defun lsp-java-assign-all ()
"Assign to new field."
(interactive)
(lsp-java-execute-matching-action "Assign all parameters to new fields"))
(defun lsp-java-add-import ()
"Add missing import."
(interactive)
(lsp-java-execute-matching-action "Import '.*'"))
(defun lsp-java--bundles ()
"Get lsp java bundles."
(let ((bundles-dir (lsp-java--bundles-dir)))
(->> (-filter