-
Notifications
You must be signed in to change notification settings - Fork 1
/
plugin.py
1245 lines (1091 loc) · 53.7 KB
/
plugin.py
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
from __future__ import annotations
from LSP.plugin import AbstractPlugin
from LSP.plugin import ClientConfig
from LSP.plugin import css
from LSP.plugin import LspTextCommand
from LSP.plugin import LspWindowCommand
from LSP.plugin import Notification
from LSP.plugin import parse_uri
from LSP.plugin import Request
from LSP.plugin import Response
from LSP.plugin import Session
from LSP.plugin import WorkspaceFolder
from LSP.plugin import register_plugin, unregister_plugin
from LSP.plugin.core.protocol import DocumentUri, Location, Point, Position, Range, TextDocumentIdentifier
from LSP.plugin.core.typing import StrEnum
from LSP.plugin.core.views import point_to_offset
from LSP.plugin.core.views import range_to_region
from LSP.plugin.core.views import text_document_position_params
from LSP.plugin.core.views import uri_from_view
from collections import deque
from functools import partial
from sublime_lib import ResourcePath
from typing import Any, Dict, List, Set, Tuple, TypedDict
from typing import cast
from typing_extensions import NotRequired
from urllib.parse import parse_qs, urldefrag
import html
import importlib
import itertools
import json
import mdpopups
import os
import re
import shutil
import sublime
import sublime_plugin
import subprocess
import threading
import toml
import traceback
# https://github.com/julia-vscode/julia-vscode/blob/main/src/interactive/misc.ts
# https://github.com/julia-vscode/LanguageServer.jl/blob/master/src/extensions/extensions.jl
class VersionedTextDocumentPositionParams(TypedDict):
textDocument: TextDocumentIdentifier
version: int
position: Position
# https://github.com/julia-vscode/julia-vscode/blob/main/src/testing/testFeature.ts
# https://github.com/julia-vscode/julia-vscode/blob/main/scripts/packages/VSCodeTestServer/src/testserver_protocol.jl
class TestserverRunTestitemRequestParams(TypedDict):
uri: str
name: str
packageName: str
useDefaultUsings: bool
line: int
column: int
code: str
class TestMessage(TypedDict):
message: str
location: Location | None
class TestserverRunTestitemRequestParamsReturn(TypedDict):
status: str
message: List[TestMessage] | None
duration: float | None
class TestItemDetail(TypedDict):
id: str
label: str
range: Range
code: str | None
code_range: Range | None
option_default_imports: bool | None
option_tags: List[str] | None
class TestSetupDetail(TypedDict):
name: str
range: Range
code: str | None
code_range: Range | None
class TestErrorDetail(TypedDict):
range: Range
error: str
class PublishTestsParams(TypedDict):
uri: DocumentUri
version: NotRequired[int]
project_path: str
package_path: str
package_name: str
testitemdetails: List[TestItemDetail]
testsetupdetails: List[TestSetupDetail]
testerrordetails: List[TestErrorDetail]
# Parameters for the runtestitem.jl script, which also requires project_path and package_path
class TestserverRunTestitemRequestExtendedParams(TypedDict):
uri: str
name: str
packageName: str
useDefaultUsings: bool
line: int
column: int
code: str
project_path: str
package_path: str
class TestItemStatus(StrEnum):
# Used as response values by VSCodeTestServer.jl
Passed = 'passed'
Failed = 'failed'
Errored = 'errored'
# Additional status indicators used for the different annotations in the view
Undetermined = 'undetermined'
Pending = 'pending'
Invalid = 'invalid'
# sublime.Kind tuples for the "Run Testitem" QuickPanelItems
KIND_PASSED = (sublime.KIND_ID_COLOR_GREENISH, "✓", "Passed")
KIND_FAILED = (sublime.KIND_ID_COLOR_REDISH, "✗", "Failed")
KIND_ERRORED = (sublime.KIND_ID_COLOR_REDISH, "✗", "Errored")
# sublime.Kind tuples for the "Change Current Environment" QuickPanelItems
KIND_DEFAULT_ENVIRONMENT = (sublime.KIND_ID_COLOR_YELLOWISH, "d", "Default Environment")
KIND_WORKSPACE_FOLDER = (sublime.KIND_ID_COLOR_PURPLISH, "f", "Workspace Folder")
# unnamed PointClassification flags for View.classify (no guarantee of correctness)
CLASS_INSIDE_WORD = 512
# CLASS_BRACKET_OPEN = 4096
# CLASS_BRACKET_CLOSE = 8192
TESTITEM_ICONS: Dict[TestItemStatus, str] = {
TestItemStatus.Passed: 'Packages/LSP-julia/icons/passed.png',
TestItemStatus.Failed: 'Packages/LSP-julia/icons/failed.png',
TestItemStatus.Errored: 'Packages/LSP/icons/error.png',
TestItemStatus.Undetermined: '',
TestItemStatus.Pending: 'Packages/LSP-julia/icons/stopwatch.png',
TestItemStatus.Invalid: ''
}
TESTITEM_SCOPES: Dict[TestItemStatus, str] = {
TestItemStatus.Passed: 'region.greenish markup.testitem.passed.lsp',
TestItemStatus.Failed: 'region.redish markup.error markup.testitem.failed.lsp',
TestItemStatus.Errored: 'region.redish markup.error markup.testitem.errored.lsp',
TestItemStatus.Undetermined: 'region.cyanish markup.testitem.undetermined.lsp',
TestItemStatus.Pending: 'region.yellowish markup.testitem.pending.lsp',
TestItemStatus.Invalid: 'region.redish markup.error markup.testitem.invalid.lsp'
}
TESTITEM_KINDS: Dict[TestItemStatus, Tuple[int, str, str]] = {
TestItemStatus.Passed: KIND_PASSED,
TestItemStatus.Failed: KIND_FAILED,
TestItemStatus.Errored: KIND_ERRORED
}
ST_VERSION = int(sublime.version()) # This API function is allowed to be invoked at importing time
INSTALLED_PACKAGES_PATH = sublime.installed_packages_path()
PACKAGES_PATH = sublime.packages_path()
SETTINGS_FILE = "LSP-julia.sublime-settings"
SESSION_NAME = "julia"
STATUS_BAR_KEY = "lsp_julia_environment"
JULIA_REPL_NAME = "Julia REPL"
JULIA_REPL_TAG = "julia_repl"
CELL_DELIMITERS = ("##", r"#%%", r"# %%")
def find_output_view(window: sublime.Window, name: str) -> sublime.View | None:
for view in window.views():
if view.name() == name:
return view
return None
def start_julia_repl(window: sublime.Window, focus: bool, panel: bool) -> None:
"""
Start Julia REPL in panel via Terminus package.
"""
settings = sublime.load_settings(SETTINGS_FILE)
julia_exe = settings.get("julia_executable_path") or "julia"
cmd = [julia_exe, "--banner=no", "--project"] # start in current project environment if available
window.run_command("terminus_open", {
"cmd": cmd,
"cwd": "${file_path:${folder}}",
"title": JULIA_REPL_NAME,
"panel_name": JULIA_REPL_NAME,
"show_in_panel": panel,
"focus": focus,
"tag": JULIA_REPL_TAG,
"env": settings.get("repl_env_variables"),
})
def ensure_julia_repl(window: sublime.Window) -> bool:
"""
Start Julia REPL in panel via Terminus package if not already running.
"""
if not window.find_output_panel(JULIA_REPL_NAME) and not find_output_view(window, JULIA_REPL_NAME):
start_julia_repl(window, False, True)
return False
return True
def send_julia_repl(window: sublime.Window, code_block: str) -> None:
"""
Send a code block string to Julia REPL via Terminus package.
"""
return_focus = window.active_view()
# ensure code block ends with newline to enforce execution in REPL
if not code_block.endswith("\n"):
code_block += "\n"
window.run_command("terminus_send_string", {"string": code_block, "tag": JULIA_REPL_TAG})
# return focus to the sending window
if return_focus:
window.focus_view(return_focus)
def versioned_text_document_position_params(view: sublime.View, location: int) -> VersionedTextDocumentPositionParams:
position_params = text_document_position_params(view, location)
return {
"textDocument": position_params["textDocument"],
"position": position_params["position"],
"version": view.change_count()
}
def is_julia_environment(folder_path: str) -> bool:
"""
Check whether a given folder path is a valid Julia project environment, i.e. it contains a file Project.toml
or JuliaProject.toml.
"""
return os.path.isfile(os.path.join(folder_path, "Project.toml")) or \
os.path.isfile(os.path.join(folder_path, "JuliaProject.toml"))
def find_julia_environment(folder_path: str) -> str | None:
"""
Search through parent directories for a Julia project environment.
"""
while os.path.basename(folder_path):
if is_julia_environment(folder_path):
return folder_path
else:
folder_path = os.path.dirname(folder_path)
return None
def find_project_file(folder_path: str) -> str | None:
""" Search through parent directories for a Project.toml or JuliaProject.toml file. """
while os.path.basename(folder_path):
project_file = os.path.join(folder_path, 'JuliaProject.toml')
if os.path.isfile(project_file):
return project_file
project_file = os.path.join(folder_path, 'Project.toml')
if os.path.isfile(project_file):
return project_file
folder_path = os.path.dirname(folder_path)
return None
def set_environment_status(session: Session, env_path) -> None:
project_file = find_project_file(env_path)
if not project_file:
session.set_config_status_async(os.path.basename(env_path))
return
env_path = os.path.dirname(project_file)
try:
project_name = toml.load(project_file).get('name')
if project_name:
session.set_config_status_async(project_name + '.jl')
return
parent_project_file = find_project_file(os.path.dirname(env_path))
if not parent_project_file:
session.set_config_status_async(os.path.basename(env_path))
return
parent_project_name = toml.load(parent_project_file).get('name')
if not parent_project_name:
session.set_config_status_async(os.path.basename(env_path))
return
relpath = os.path.relpath(env_path, os.path.dirname(parent_project_file))
session.set_config_status_async(parent_project_name + '.jl/' + relpath.replace('\\', '/'))
except toml.TomlDecodeError:
session.set_config_status_async(os.path.basename(env_path))
def prepare_markdown(content: str) -> str:
"""
This function applies a few modifications to the Markdown content used in hover popups and the documentation sheet,
in order to workaround some parsing inconsistencies in mdpopups' Markdown-to-minihtml converter and to enable links
with references to a documentation page.
"""
# Workaround CommonMark deficiency: two spaces followed by a newline should result in a new paragraph
content = re.sub("(\\S) \n", "\\1\n\n", content)
# Add another newline before horizontal rule following fenced code block
content = re.sub("```\n---", "```\n\n---", content)
# Add another newline before list items
content = re.sub("\n- ", "\n\n- ", content)
# Replace [`title`](@ref) links with the corresponding command to navigate the documentation with a new search query
content = re.sub(
r"\[`(.+?)`\]\(@ref.*?\)", r"""<a href='subl:julia_search_documentation {"word": "\1"}'>`\1`</a>""", content)
# Remove parameters after fenced code block language identifier
content = re.sub("```julia;.*?\n", "```julia\n", content)
content = re.sub("```jldoctest;.*?\n", "```jldoctest\n", content)
return content
def startupinfo():
if sublime.platform() == "windows":
si = subprocess.STARTUPINFO()
si.dwFlags |= subprocess.STARTF_USESHOWWINDOW
si.wShowWindow = 11
return si
return None
class TestItemStorage:
def __init__(self, window: sublime.Window) -> None:
self.window = window
self.pending_result = False
self.testitemparams: Dict[str, Dict[str, Any]] = {}
self.testitemdetails: Dict[str, List[TestItemDetail]] = {}
self.testerrordetails: Dict[str, List[TestErrorDetail]] = {}
self.testitemstatus: Dict[str, List[TestserverRunTestitemRequestParamsReturn]] = {}
self.error_keys: Dict[str, Set[str]] = {}
def update(self, uri: DocumentUri, params: PublishTestsParams) -> None:
# Use the filepath instead of the URI as the key for storing the testitems, because on Windows the language
# server sometimes uses uppercase and sometimes lowercase drive letters in the URI for the same file.
filepath = parse_uri(uri)[1]
testitems = params['testitemdetails']
testerrors = params['testerrordetails']
old_params = self.testitemparams.get(filepath)
if not testitems and not testerrors:
# If there are no testitems reported, just delete the key for the previously stored items if they existed.
if old_params:
del self.testitemparams[filepath]
del self.testitemdetails[filepath]
del self.testerrordetails[filepath]
del self.testitemstatus[filepath]
self.render_testitems(uri)
return
status: List[TestserverRunTestitemRequestParamsReturn] = [{
'status': TestItemStatus.Undetermined,
'message': None,
'duration': None
} for _ in testitems]
if not old_params or \
any(old_params[key] != params[key] for key in ('project_path', 'package_path', 'package_name')):
# If there were no testitems for this file already stored, or one of the major parameters changed, copy the
# new parameters and testitems.
self.testitemparams[filepath] = {
'uri': params['uri'],
'version': params.get('version', 0),
'project_path': params['project_path'],
'package_path': params['package_path'],
'package_name': params['package_name']
}
else:
# If there are both new and old testitems, compare them and determine the unchanged items so that the old
# status is not forgotten. An old and a new testitem is considered the same if it has the same "id".
# Unfortunately the "id" field for the testitems is not necessarily unique, so there might be incorrect
# matches via this approach. Perhaps it should be considered as an additional requirement that the "code"
# property must also be the same (that would mean that testitems lose their status whenever there are
# changes in the particular testitem code)...
self.testitemparams[filepath]['uri'] = params['uri']
self.testitemparams[filepath]['version'] = \
params.get('version', self.testitemparams[filepath]['version'] + 1)
for old_idx, old_item in enumerate(self.testitemdetails[filepath]):
for new_idx, new_item in enumerate(testitems):
if old_item['id'] == new_item['id']:
# Copy old status into new status for this testitem
status[new_idx] = self.testitemstatus[filepath][old_idx]
break
self.testitemdetails[filepath] = testitems
self.testerrordetails[filepath] = testerrors
self.testitemstatus[filepath] = status
self.render_testitems(uri)
def stored_version(self, uri: DocumentUri) -> int | None:
filepath = parse_uri(uri)[1]
params = self.testitemparams.get(filepath)
if params:
return params['version']
return None
def render_testitems(self, uri: DocumentUri, new_result_idx: int | None = None) -> None:
filepath = parse_uri(uri)[1]
view = self.window.find_open_file(filepath) # This doesn't work if the tab was dragged out of the window...
if view and not view.is_loading():
regions_by_status: Dict[TestItemStatus, List[sublime.Region]] = {
TestItemStatus.Passed: [],
TestItemStatus.Failed: [],
TestItemStatus.Errored: [],
TestItemStatus.Undetermined: [],
TestItemStatus.Pending: [],
TestItemStatus.Invalid: []
}
if filepath not in self.testitemdetails:
for status in regions_by_status:
view.erase_regions('lsp_julia_testitem_{}'.format(status))
return
annotations: Dict[TestItemStatus, List[str]] = {
TestItemStatus.Passed: [],
TestItemStatus.Failed: [],
TestItemStatus.Errored: [],
TestItemStatus.Undetermined: [],
TestItemStatus.Pending: [],
TestItemStatus.Invalid: []
}
version = self.testitemparams[filepath]['version']
error_annotation_color = cast(
str, view.style_for_scope(TESTITEM_SCOPES[TestItemStatus.Errored])['foreground'])
for idx, item, result in \
zip(itertools.count(), self.testitemdetails[filepath], self.testitemstatus[filepath]):
region = sublime.Region(point_to_offset(Point.from_lsp(item['range']['start']), view))
annotation = '<a href="{}#idx={}&version={}">Run Test</a>'.format(html.escape(uri), idx, version)
duration = result['duration']
if duration is not None:
if duration < 100:
annotation += " ({}ms)".format(round(duration))
else:
annotation += " ({:0.2f}s)".format(duration/1000)
status = cast(TestItemStatus, result['status'])
regions_by_status[status].append(region)
if status in (TestItemStatus.Passed, TestItemStatus.Undetermined):
annotations[status].append(annotation)
elif status == TestItemStatus.Pending:
annotations[status].append('Running…')
elif status in (TestItemStatus.Failed, TestItemStatus.Errored):
annotations[status].append(annotation)
if idx == new_result_idx and result['message'] is not None:
for error_idx, message in enumerate(result['message']):
location = message['location']
if location:
regions_key = 'lsp_julia_testitem_error_{}_{}'.format(item['id'], error_idx)
view.add_regions(
regions_key,
[range_to_region(location['range'], view)],
flags=sublime.HIDE_ON_MINIMAP | sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE,
annotations=["<br>".join(html.escape(message['message']).split("\n"))],
annotation_color=error_annotation_color,
on_close=partial(self.hide_annotation, uri, regions_key))
self.error_keys[filepath].add(regions_key)
elif status == TestItemStatus.Invalid:
annotations[status].append('<br>'.join([
"The test process crashed while running this testitem.",
"Please check the console and consider to create an issue report in the LSP-julia GitHub repo."
]))
for testerror in self.testerrordetails[filepath]:
region = sublime.Region(point_to_offset(Point.from_lsp(testerror['range']['start']), view))
regions_by_status[TestItemStatus.Invalid].append(region)
annotations[TestItemStatus.Invalid].append(testerror['error'])
for status, regions in regions_by_status.items():
regions_key = 'lsp_julia_testitem_{}'.format(status)
if regions:
on_navigate = self.run_testitem if status not in (TestItemStatus.Pending, TestItemStatus.Invalid) \
else None
view.add_regions(
regions_key,
regions,
scope=TESTITEM_SCOPES[status],
icon=TESTITEM_ICONS[status],
flags=sublime.HIDE_ON_MINIMAP | sublime.DRAW_NO_FILL | sublime.DRAW_NO_OUTLINE,
annotations=annotations[status],
annotation_color=cast(str, view.style_for_scope(TESTITEM_SCOPES[status])['foreground']),
on_navigate=on_navigate)
else:
view.erase_regions(regions_key)
def hide_annotation(self, uri: DocumentUri, key: str) -> None:
filepath = parse_uri(uri)[1]
view = self.window.find_open_file(filepath)
if view:
view.erase_regions(key)
self.error_keys[filepath].discard(key)
def clear_error_annotations(self, uri: DocumentUri, testitem_id: str | None = "") -> None:
filepath = parse_uri(uri)[1]
view = self.window.find_open_file(filepath)
if view:
for key in self.error_keys.setdefault(filepath, set()).copy():
if key.startswith('lsp_julia_testitem_error_{}'.format(testitem_id)):
view.erase_regions(key)
self.error_keys[filepath].discard(key)
def run_testitem_request_params(
self, uri: DocumentUri, idx: int
) -> TestserverRunTestitemRequestExtendedParams | None:
filepath = parse_uri(uri)[1]
params = self.testitemparams.get(filepath)
if not params:
return None
testitem = self.testitemdetails[filepath][idx]
code_range = testitem.get('code_range')
if not code_range:
return None
code = testitem.get('code')
if not code:
return None
project_path = params['project_path']
package_path = params['package_path']
package_name = params['package_name']
if not any([project_path, package_path, package_name]):
return None
line = code_range['start']['line']
column = code_range['start']['character']
if column == 0:
line -= 1 # Fix missmatch of start position between initial and subsequent reported testitem notifications
return {
'uri': params['uri'],
'name': testitem['label'],
'packageName': package_name,
'useDefaultUsings': testitem.get('option_default_imports') is not False,
'line': line,
'column': column,
'code': code,
'project_path': project_path,
'package_path': package_path
}
def run_testitem(self, href: str, focus_testitem: bool = False) -> None:
if self.pending_result:
self.window.status_message("Another testitem is already running")
return
uri, fragment = urldefrag(href)
filepath = parse_uri(uri)[1]
pq = parse_qs(fragment)
idx = int(pq['idx'][0])
version = int(pq['version'][0])
if version != self.stored_version(uri):
# Actually this should never happen in practice, because annotations for the corresponding view are redrawn
# on each julia/publishTestitems notification.
self.window.status_message("Version mismatch for testitem params")
return
params = self.run_testitem_request_params(uri, idx)
if params:
self.pending_result = True
self.testitemstatus[filepath][idx]['status'] = TestItemStatus.Pending
thread = threading.Thread(
target=self.run_testitem_daemon_thread, args=(uri, idx, version, params), daemon=True)
thread.start()
if focus_testitem:
view = self.window.open_file(
"{}:{}".format(filepath, params['line'] + 1), flags=sublime.ENCODED_POSITION)
# In case the file wasn't open before and is still loading, add a small delay before drawing the
# annotations.
if view.is_loading():
sublime.set_timeout(partial(self.render_testitems, uri), 50)
sublime.set_timeout(partial(self.clear_error_annotations, uri, params['name']), 50)
return
self.render_testitems(uri)
self.clear_error_annotations(uri, params['name'])
def run_testitem_daemon_thread(
self, uri: DocumentUri, idx: int, version: int, params: TestserverRunTestitemRequestExtendedParams
) -> None:
try:
file_directory = os.path.dirname(parse_uri(params['uri'])[1])
params_json = json.dumps(params, separators=(',', ':'))
result_json = subprocess.check_output([
LspJuliaPlugin.julia_exe(),
"--startup-file=no",
"--history-file=no",
"--project={}".format(LspJuliaPlugin.testrunnerdir()),
os.path.join(LspJuliaPlugin.testrunnerdir(), "runtestitem.jl"),
params_json
], cwd=file_directory, startupinfo=startupinfo()).decode("utf-8")
result = json.loads(result_json)
sublime.set_timeout(partial(self.on_result, uri, idx, version, result))
except Exception:
self.pending_result = False
filepath = parse_uri(uri)[1]
self.testitemstatus[filepath][idx]['status'] = TestItemStatus.Invalid
traceback.print_exc()
sublime.set_timeout(partial(self.render_testitems, uri))
def on_result(
self, uri: DocumentUri, idx: int, version: int, params: TestserverRunTestitemRequestParamsReturn
) -> None:
self.pending_result = False
filepath = parse_uri(uri)[1]
if self.testitemparams[filepath]['version'] == version:
self.testitemstatus[filepath][idx] = params
self.render_testitems(uri, idx)
else:
# Ignore result if the language server has notified about a new version of testitems for this file in the
# meantime. The index of the stored testitem might have changed! Search through all testitems for an item
# with "pending" status and reset status if found. Don't draw new error annotations.
for idx, status in enumerate(self.testitemstatus[filepath]):
if status['status'] == TestItemStatus.Pending:
self.testitemstatus[filepath][idx]['status'] = TestItemStatus.Undetermined
self.render_testitems(uri)
class LspJuliaPlugin(AbstractPlugin):
def __init__(self, weaksession) -> None:
super().__init__(weaksession)
session = weaksession()
if not session:
return
self.testitems = TestItemStorage(session.window)
if session.working_directory and find_project_file(session.working_directory):
set_environment_status(session, session.working_directory)
else:
session.set_config_status_async(LspJuliaPlugin.default_julia_environment())
@classmethod
def name(cls) -> str:
return SESSION_NAME
@classmethod
def additional_variables(cls) -> Dict[str, str] | None:
return {'julia_exe': cls.julia_exe(), 'server_path': cls.serverdir()}
@classmethod
def basedir(cls) -> str:
return os.path.join(cls.storage_path(), "LSP-julia")
@classmethod
def serverdir(cls) -> str:
return os.path.join(cls.basedir(), "languageserver")
@classmethod
def testrunnerdir(cls) -> str:
return os.path.join(cls.basedir(), "testrunner")
@classmethod
def version_file(cls) -> str:
return os.path.join(cls.serverdir(), "VERSION")
@classmethod
def packagedir(cls) -> str:
return os.path.join(sublime.packages_path(), "LSP-julia")
@classmethod
def julia_exe(cls) -> str:
return str(sublime.load_settings(SETTINGS_FILE).get("julia_executable_path")) or "julia"
@classmethod
def julia_version(cls) -> str:
return subprocess.check_output(
[cls.julia_exe(), "--version"], startupinfo=startupinfo()).decode("utf-8").rstrip().split()[-1]
@classmethod
def default_julia_environment(cls) -> str:
major, minor, _ = cls.julia_version().split(".")
return "v{}.{}".format(major, minor)
@classmethod
def server_version(cls) -> str:
return "1cc14a9-fix-1.11" # LanguageServer v4.5.1
@classmethod
def needs_update_or_installation(cls) -> bool:
if not shutil.which(cls.julia_exe()):
msg = ('The executable "{}" could not be found. Set up the path to the Julia executable by running the '
'command\n\n\tPreferences: LSP-julia Settings\n\nfrom the command palette.').format(cls.julia_exe())
raise RuntimeError(msg)
try:
with open(cls.version_file(), "r") as fp:
return cls.server_version() != fp.read().strip()
except OSError:
return True
@classmethod
def install_or_update(cls) -> None:
shutil.rmtree(cls.basedir(), ignore_errors=True)
try:
os.makedirs(cls.serverdir(), exist_ok=True)
for file in ("Project.toml", "Manifest.toml", "Manifest-v1.11.toml"):
ResourcePath.from_file_path(
os.path.join(cls.packagedir(), "server", file)).copy(os.path.join(cls.serverdir(), file))
# TODO Use cls.basedir() as DEPOT_PATH for language server
os.makedirs(cls.testrunnerdir(), exist_ok=True)
for file in ("Project.toml", "runtestitem.jl"):
ResourcePath.from_file_path(
os.path.join(cls.packagedir(), "testrunner", file)).copy(os.path.join(cls.testrunnerdir(), file))
returncode = subprocess.call([
cls.julia_exe(),
"--startup-file=no",
"--history-file=no",
"--project={}".format(cls.serverdir()),
"--eval", "ENV[\"JULIA_SSL_CA_ROOTS_PATH\"] = \"\"; import Pkg; Pkg.instantiate()"
])
if returncode == 0:
with open(cls.version_file(), "w") as fp:
fp.write(cls.server_version())
except Exception:
shutil.rmtree(cls.basedir(), ignore_errors=True)
raise
@classmethod
def on_pre_start(
cls,
window: sublime.Window,
initiating_view: sublime.View,
workspace_folders: List[WorkspaceFolder],
configuration: ClientConfig
) -> str | None:
# The working directory is used by the language server to find the Julia project environment, if not explicitly
# given as a parameter of runserver() or as a command line argument. We can make use of this to avoid adjusting
# the "command" setting everytime with a new environment argument when the server starts.
# If one or more folders are opened in Sublime Text, and one of it contains the initiating view, that folder is
# used as the working directory. This avoids to accidentally use a nested environment, e.g. if the initiating
# view is a file from a `docs` or `test` subdirectory.
# Otherwise we search through parent directories of the initiating view for a Julia environment. If no
# environment is found, the language server will fall back to the default Julia environment.
view_uri = uri_from_view(initiating_view)
for folder in workspace_folders:
if folder.includes_uri(view_uri):
return folder.path
file_path = initiating_view.file_name()
if file_path:
return find_julia_environment(os.path.dirname(file_path))
return None
def on_server_response_async(self, method: str, response: Response) -> None:
if method == "textDocument/hover" and isinstance(response.result, dict):
contents = response.result.get("contents")
if isinstance(contents, dict) and contents.get("kind") == "markdown":
response.result["contents"]["value"] = prepare_markdown(contents["value"])
# Handles the julia/publishTests notification
def m_julia_publishTests(self, params: PublishTestsParams) -> None:
if params:
uri = params['uri']
self.testitems.update(uri, params)
def plugin_loaded() -> None:
register_plugin(LspJuliaPlugin)
def plugin_unloaded() -> None:
unregister_plugin(LspJuliaPlugin)
class LspJuliaOpenFileCommand(sublime_plugin.WindowCommand):
""" An enhanced version and wrapper of the built-in open_file command, which also supports modifier keys when used
in form of a link in minihtml. """
def run(self, event: dict | None = None, **kwargs) -> None:
if event and kwargs.get('add_to_selection') is None:
modifier_keys = event.get('modifier_keys', {})
if 'primary' in modifier_keys or 'shift' in modifier_keys:
kwargs['add_to_selection'] = True
self.window.run_command('open_file', kwargs)
def want_event(self) -> bool:
return True
SELECT_FOLDER_DIALOG_FLAG = 1
class JuliaActivateEnvironmentCommand(LspWindowCommand):
""" Selects the active Julia environment, which is used by the language server to resolve the package dependencies
in order to provide autocomplete suggestions and diagnostics. The active environment will be shown in the status
bar, unless the "show_environment_status" setting is disabled. """
session_name = SESSION_NAME
def run(self, **kwargs) -> None:
files = kwargs.get('files')
if files:
self.activate_environment(os.path.dirname(files[0]))
return
env_path = kwargs.get('env_path')
if env_path == SELECT_FOLDER_DIALOG_FLAG:
curr_file = self.window.active_view().file_name() # pyright: ignore[reportOptionalMemberAccess]
starting_dir = os.path.dirname(curr_file) if curr_file else None
sublime.select_folder_dialog(
self.on_select_folder, starting_dir, multi_select=False) # pyright: ignore[reportArgumentType]
elif env_path:
self.activate_environment(env_path)
def is_visible(self, **kwargs) -> bool:
if not super().is_enabled():
return False
files = kwargs.get('files')
if files is not None: # command was invoked from the side bar context menu
return len(files) == 1 and os.path.basename(files[0]) in ('Project.toml', 'JuliaProject.toml')
return True
def on_select_folder(self, folder_path: str | None) -> None:
if folder_path:
if is_julia_environment(folder_path):
self.activate_environment(folder_path)
else:
self.window.status_message("The selected folder is not a valid Julia environment")
def activate_environment(self, env_path: str) -> None:
session = self.session()
if not session:
return
session.send_notification(Notification('julia/activateenvironment', {'envPath': env_path}))
set_environment_status(session, env_path)
def input(self, args: dict) -> sublime_plugin.ListInputHandler | None:
if 'files' in args: # command was invoked from the side bar context menu
return None
if 'env_path' not in args: # command was invoked from the command palette
session = self.session()
workspace_folders = session.get_workspace_folders() if session else []
return EnvPathInputHandler(workspace_folders)
class EnvPathInputHandler(sublime_plugin.ListInputHandler):
def __init__(self, workspace_folders: List[WorkspaceFolder]) -> None:
self.workspace_folders = workspace_folders
def list_items(self) -> List[sublime.ListInputItem]:
items: List[sublime.ListInputItem] = []
# Add option for folder picker dialog
items.append(sublime.ListInputItem("(pick a folder…)", SELECT_FOLDER_DIALOG_FLAG))
# Collect all folder names and corresponding paths in .julia/environments
julia_environments_path = os.path.expanduser(os.path.join("~", ".julia", "environments"))
env_names = [
env for env in reversed(os.listdir(julia_environments_path))
if os.path.isdir(os.path.join(julia_environments_path, env))
]
env_paths = [os.path.join(julia_environments_path, env) for env in env_names]
# Add all environments withing a working folder.
for folder in self.workspace_folders:
for subdir, dirs, files in os.walk(folder.path):
# exclude all hidden folders in the working folder
dirs[:] = [d for d in dirs if not d.startswith('.')]
folderpath = os.path.join(folder.path, subdir)
if folderpath not in env_paths and is_julia_environment(folderpath):
basename = os.path.basename(folder.path)
relpath = os.path.relpath(subdir, folder.path)
env_name = basename if relpath == '.' else os.path.join(basename, relpath)
items.append(sublime.ListInputItem(env_name, folderpath, kind=KIND_WORKSPACE_FOLDER))
# Add default Julia environments from .julia/environments
items.extend([
sublime.ListInputItem(name, path, kind=KIND_DEFAULT_ENVIRONMENT) for name, path in zip(env_names, env_paths)
])
return items
def placeholder(self) -> str:
return "Select Julia environment"
def preview(self, text: str | int | None) -> sublime.Html | str:
if text == SELECT_FOLDER_DIALOG_FLAG:
return "Open a folder picker dialog to select a Julia project"
elif text:
return sublime.Html("<i>{}</i>".format(text))
return ""
def validate(self, text: str | int | None) -> bool:
return text is not None
class JuliaOpenReplCommand(sublime_plugin.WindowCommand):
"""
Start a Julia REPL via the Terminus package, or focus panel if already started.
"""
def is_enabled(self) -> bool:
return importlib.find_loader("Terminus") is not None
def run(self, panel: bool = True) -> None:
repl_view = find_output_view(self.window, JULIA_REPL_NAME)
repl_panel = self.window.find_output_panel(JULIA_REPL_NAME)
if repl_view:
self.window.focus_view(repl_view)
elif repl_panel:
self.window.run_command("show_panel", {"panel": "output.{}".format(JULIA_REPL_NAME)})
self.window.focus_view(repl_panel)
else:
start_julia_repl(self.window, True, panel)
class JuliaSelectCodeBlockCommand(LspTextCommand):
"""
Can be invoked to select the code block containing the current cursor position.
Maybe not very useful on its own, but rather when combined with running the code in the Julia REPL.
"""
session_name = SESSION_NAME
def run(self, edit: sublime.Edit) -> None:
params = versioned_text_document_position_params(self.view, self.view.sel()[0].b)
session = self.session_by_name(self.session_name)
if session:
session.send_request(Request("julia/getCurrentBlockRange", params), self.on_result)
def on_result(self, params: Any) -> None:
a = point_to_offset(Point.from_lsp(params[0]), self.view)
b = point_to_offset(Point.from_lsp(params[1]), self.view)
self.view.run_command("lsp_selection_set", {"regions": [(a, b)]})
class JuliaRunCodeBlockCommand(LspTextCommand):
"""
Can be invoked to execute the current selection in the Julia REPL. If no text is selected, get the code block
containing the current cursor position from the language server and execute it in the Julia REPL.
"""
session_name = SESSION_NAME
def is_enabled(self, event: dict | None = None, point: int | None = None) -> bool:
# Language server must be ready
if not super().is_enabled(event, point):
return False
# Terminus package must be installed
if not importlib.find_loader("Terminus"):
return False
# cursor must not be at end of file
if self.view.sel()[0].b == self.view.size():
return False
return True
def run(self, edit: sublime.Edit, event: dict | None = None, point: int | None = None) -> None:
window = self.view.window()
if not window:
return
# ensure that Terminus output panel for Julia REPL is available
repl_ready = ensure_julia_repl(window)
sel = self.view.sel()[0]
if sel.empty():
params = versioned_text_document_position_params(self.view, self.view.sel()[0].b)
session = self.session_by_name(self.session_name)
if session:
session.send_request(Request("julia/getCurrentBlockRange", params), self.on_result)
else:
code_block = self.view.substr(sel)
if repl_ready:
send_julia_repl(window, code_block)
else:
# give Terminus a bit time to initialize, otherwise the terminus_send_string command doesn't work
sublime.set_timeout(lambda: send_julia_repl(window, code_block), 5)
def on_result(self, params: Any) -> None:
window = self.view.window()
if not window:
return
a = point_to_offset(Point.from_lsp(params[0]), self.view)
b = point_to_offset(Point.from_lsp(params[1]), self.view)
c = point_to_offset(Point.from_lsp(params[2]), self.view)
code_block = self.view.substr(sublime.Region(a, b))
self.view.run_command("lsp_selection_set", {"regions": [(c, c)]}) # move cursor to next code block
self.view.show_at_center(c)
send_julia_repl(window, code_block)
class JuliaRunCodeCellCommand(sublime_plugin.TextCommand):
"""
Can be invoked to execute the current selection, or if no text is selected, the code cell containing the current
cursor position in the Julia REPL. Code cells are delimited by specially formatted comments.
"""
def is_enabled(self) -> bool:
# must be Julia file
if not self.view.match_selector(0, "source.julia"):
return False
# Terminus package must be installed
if not importlib.find_loader("Terminus"):
return False
# cursor must not be at end of file
if self.view.sel()[0].b == self.view.size():
return False
return True
def run(self, edit: sublime.Edit) -> None:
window = self.view.window()
if not window:
return
sel = self.view.sel()[0]
repl_ready = ensure_julia_repl(window)
if sel.empty():
line_count = self.view.rowcol(self.view.size())[0]
# get start and end line of code cell
line_start = self.view.rowcol(sel.b)[0]
line_end = line_start
while line_start >= 0:
point = self.view.text_point(line_start, 0)
if self.view.substr(self.view.line(point)).startswith(CELL_DELIMITERS):
break
line_start -= 1
line_start += 1
while line_end <= line_count:
point = self.view.text_point(line_end, 0)
if self.view.substr(self.view.line(point)).startswith(CELL_DELIMITERS):
break
line_end += 1
code_block = ""
for line in range(line_start, line_end):