-
Notifications
You must be signed in to change notification settings - Fork 236
/
Copy pathTypeScript.py
1464 lines (1290 loc) · 56.8 KB
/
TypeScript.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
import json
import os
import sys
import time
import re
import codecs
import sublime
import sublime_plugin
# get the directory path to this file; ST2 requires this to be done at global scope
pluginDir = os.path.dirname(os.path.realpath(__file__))
pluginName = os.path.basename(pluginDir)
libsDir = os.path.join(pluginDir, 'libs')
if libsDir not in sys.path:
sys.path.insert(0, libsDir)
from nodeclient import NodeCommClient
from serviceproxy import *
# Enable Python Tools for visual studio remote debugging
try:
from ptvsd import enable_attach
enable_attach(secret=None)
except ImportError:
pass
TOOLTIP_SUPPORT = int(sublime.version()) >= 3072
# globally-accessible information singleton; set in function plugin_loaded
cli = None
# currently active view
def active_view():
return sublime.active_window().active_view()
# view is typescript if outer syntactic scope is 'source.ts'
def is_typescript(view):
if not view.file_name():
return False
try:
location = view.sel()[0].begin()
except:
return False
return view.match_selector(location, 'source.ts')
# True if the cursor is in a syntactic scope specified by selector scopeSel
def is_typescript_scope(view, scopeSel):
try:
location = view.sel()[0].begin()
except:
return False
return view.match_selector(location, scopeSel)
def getLocationFromView(view):
"""
Returns the Location tuple of the beginning of the first selected region in the view
"""
region = view.sel()[0]
return getLocationFromRegion(view, region)
def getLocationFromRegion(view, region):
"""
Returns the Location tuple of the beginning of the given region
"""
position = region.begin()
return getLocationFromPosition(view, position)
def getLocationFromPosition(view, position):
"""
Returns the LineOffset object of the given text position
"""
cursor = view.rowcol(position)
line = cursor[0] + 1
offset = cursor[1] + 1
return Location(line, offset)
def extractLineOffset(lineOffset):
"""
Destructure line and offset tuple from LineOffset object
convert 1-based line, offset to zero-based line, offset
``lineOffset`` LineOffset object
"""
line = lineOffset.line - 1
offset = lineOffset.offset - 1
return (line, offset)
# per-file, globally-accessible information
class ClientFileInfo:
def __init__(self, filename):
self.filename = filename
self.pendingChanges = False
self.changeCount = 0
self.errors = {
'syntacticDiag': [],
'semanticDiag': [],
}
self.renameOnLoad = None
# a reference to a source file, line, offset; next and prev refer to the
# next and previous reference in a view containing references
class Ref:
def __init__(self, filename, line, offset, prevLine):
self.filename = filename
self.line = line
self.offset = offset
self.nextLine = None
self.prevLine = prevLine
def setNextLine(self, n):
self.nextLine = n
def asTuple(self):
return (self.filename, self.line, self.offset, self.prevLine, self.nextLine)
# maps (line in view containing references) to (filename, line, offset)
# referenced
class RefInfo:
def __init__(self, firstLine, refId):
self.refMap = {}
self.currentRefLine = None
self.firstLine = firstLine
self.lastLine = None
self.refId = refId
def setLastLine(self, lastLine):
self.lastLine = lastLine
def addMapping(self, line, target):
self.refMap[line] = target
def containsMapping(self, line):
return line in self.refMap
def getMapping(self, line):
if line in self.refMap:
return self.refMap[line]
def getCurrentMapping(self):
if self.currentRefLine:
return self.getMapping(self.currentRefLine)
def setRefLine(self, line):
self.currentRefLine = line
def getRefLine(self):
return self.currentRefLine
def getRefId(self):
return self.refId
def nextRefLine(self):
currentMapping = self.getCurrentMapping()
if (not self.currentRefLine) or (not currentMapping):
self.currentRefLine = self.firstLine
else:
(filename, l, c, p, n) = currentMapping.asTuple()
if n:
self.currentRefLine = n
else:
self.currentRefLine = self.firstLine
return self.currentRefLine
def prevRefLine(self):
currentMapping = self.getCurrentMapping()
if (not self.currentRefLine) or (not currentMapping):
self.currentRefLine = self.lastLine
else:
(filename, l, c, p, n) = currentMapping.asTuple()
if p:
self.currentRefLine = p
else:
self.currentRefLine = self.lastLine
return self.currentRefLine
def asValue(self):
vmap = {}
keys = self.refMap.keys()
for key in keys:
vmap[key] = self.refMap[key].asTuple()
return (vmap, self.currentRefLine, self.firstLine, self.lastLine, self.refId)
# build a reference from a serialized reference
def buildRef(refTuple):
(filename, line, offset, prevLine, nextLine) = refTuple
ref = Ref(filename, line, offset, prevLine)
ref.setNextLine(nextLine)
return ref
# build a ref info from a serialized ref info
def buildRefInfo(refInfoV):
(dict, currentLine, firstLine, lastLine, refId) = refInfoV
refInfo = RefInfo(firstLine, refId)
refInfo.setRefLine(currentLine)
refInfo.setLastLine(lastLine)
for key in dict.keys():
refInfo.addMapping(key, buildRef(dict[key]))
return refInfo
# hold information that must be accessible globally; this is a singleton
class EditorClient:
def __init__(self):
# retrieve the path to tsserver.js
# first see if user set the path to the file
settings = sublime.load_settings('Preferences.sublime-settings')
procFile = settings.get('typescript_proc_file')
if not procFile:
# otherwise, get tsserver.js from package directory
procFile = os.path.join(pluginDir, "tsserver/tsserver.js")
print("spawning node module: " + procFile)
self.nodeClient = NodeCommClient(procFile)
self.service = ServiceProxy(self.nodeClient)
self.completions = {}
self.fileMap = {}
self.refInfo = None
self.versionST2 = False
def ST2(self):
return self.versionST2
def setFeatures(self):
if int(sublime.version()) < 3000:
self.versionST2 = True
hostInfo = "Sublime Text version " + str(sublime.version())
# Preferences Settings
pref_settings = sublime.load_settings('Preferences.sublime-settings')
tabSize = pref_settings.get('tab_size', 4)
indentSize = pref_settings.get('indent_size', tabSize)
formatOptions = buildSimpleFormatOptions(tabSize, indentSize)
self.service.configure(hostInfo, None, formatOptions)
def reloadRequired(self, view):
clientInfo = self.getOrAddFile(view.file_name())
return self.versionST2 or clientInfo.pendingChanges or (clientInfo.changeCount < view.change_count())
# ref info is for Find References view
# TODO: generalize this so that there can be multiple
# for example, one for Find References and one for build errors
def disposeRefInfo(self):
self.refInfo = None
def initRefInfo(self, firstLine, refId):
self.refInfo = RefInfo(firstLine, refId)
return self.refInfo
def updateRefInfo(self, refInfo):
self.refInfo = refInfo
def getRefInfo(self):
return self.refInfo
# get or add per-file information that must be globally acessible
def getOrAddFile(self, filename):
if (os.name == "nt") and filename:
filename = filename.replace('/','\\')
if not filename in self.fileMap:
clientInfo = ClientFileInfo(filename)
self.fileMap[filename] = clientInfo
else:
clientInfo = self.fileMap[filename]
return clientInfo
def hasErrors(self, filename):
clientInfo = self.getOrAddFile(filename)
return (len(clientInfo.errors['syntacticDiag']) > 0) or (len(clientInfo.errors['semanticDiag']) > 0)
# per-file info that will only be accessible from TypeScriptListener instance
class FileInfo:
def __init__(self, filename, cc):
self.filename = filename
self.changeSent = False
self.preChangeSent = False
self.modified = False
self.completionPrefixSel = None
self.completionSel = None
self.lastCompletionLoc = None
self.lastCompletions = None
self.lastCompletionPrefix = None
self.prevSel = None
self.view = None
self.hasErrors = False
self.clientInfo = None
self.changeCountErrReq = -1
self.lastModChangeCount = cc
self.modCount = 0
# region that will not change as buffer is modified
class StaticRegion:
def __init__(self, b, e):
self.b = b
self.e = e
def toRegion(self):
return sublime.Region(self.b, self.e)
def begin(self):
return self.b
def empty(self):
return self.b == self.e
# convert a list of static regions to ordinary regions
def staticRegionsToRegions(staticRegions):
result = []
for staticRegion in staticRegions:
result.append(staticRegion.toRegion())
return result
# copy a region into a static region
def copyRegionStatic(r):
return StaticRegion(r.begin(), r.end())
# copy a list of regions into a list of static regions
def copyRegionsStatic(regions):
result = []
for region in regions:
result.append(copyRegionStatic(region))
return result
# copy a region (this is needed because the original region may change)
def copyRegion(r):
return sublime.Region(r.begin(), r.end())
# copy a list of regions
def copyRegions(regions):
result = []
for region in regions:
result.append(copyRegion(region))
return result
# from a list of empty regions, make a list of regions whose begin() value is
# one before the begin() value of the corresponding input (for left_delete)
def decrRegions(emptyRegions, amt):
rr = []
for region in emptyRegions:
rr.append(sublime.Region(region.begin() - amt, region.begin() - amt))
return rr
def decrLocsToRegions(locs, amt):
rr = []
for loc in locs:
rr.append(sublime.Region(loc - amt, loc - amt))
return rr
def buildSimpleFormatOptions(tabSize, indentSize):
formatOptions = { "tabSize": tabSize, "indentSize": indentSize }
return formatOptions
def reconfig_file(view):
hostInfo = "Sublime Text version " + str(sublime.version())
# Preferences Settings
view_settings = view.settings()
tabSize = view_settings.get('tab_size', 4)
indentSize = view_settings.get('indent_size', tabSize)
formatOptions = buildSimpleFormatOptions(tabSize, indentSize)
cli.service.configure(hostInfo, view.file_name(), formatOptions)
def open_file(view):
cli.service.open(view.file_name())
def tab_size_changed(view):
reconfig_file(view)
clientInfo = cli.getOrAddFile(view.file_name())
clientInfo.pendingChanges = True
def setFilePrefs(view):
settings = view.settings()
settings.set('use_tab_stops', False)
settings.set('translate_tabs_to_spaces', True)
settings.add_on_change('tab_size',lambda: tab_size_changed(view))
# given a list of regions and a (possibly zero-length) string to insert,
# send the appropriate change information to the server
def sendReplaceChangesForRegions(view, regions, insertString):
if cli.ST2() or (not is_typescript(view)):
return
for region in regions:
location = getLocationFromPosition(view, region.begin())
endLocation = getLocationFromPosition(view, region.end())
cli.service.change(view.file_name(), location, endLocation, insertString)
def getTempFileName():
return os.path.join(pluginDir, ".tmpbuf")
# write the buffer of view to a temporary file and have the server reload it
def reloadBuffer(view, clientInfo=None):
if not view.is_loading():
t = time.time()
tmpfileName = getTempFileName()
tmpfile = codecs.open(tmpfileName, "w", "utf-8")
text = view.substr(sublime.Region(0, view.size()))
tmpfile.write(text)
tmpfile.flush()
cli.service.reload(view.file_name(), tmpfileName)
et = time.time()
print("time for reload %f" % (et - t))
if not cli.ST2():
if not clientInfo:
clientInfo = cli.getOrAddFile(view.file_name())
clientInfo.changeCount = view.change_count()
clientInfo.pendingChanges = False
# if we have changes to the view not accounted for by change messages,
# send the whole buffer through a temporary file
def checkUpdateView(view):
if is_typescript(view):
clientInfo = cli.getOrAddFile(view.file_name())
if cli.reloadRequired(view):
reloadBuffer(view, clientInfo)
# singleton that receives event calls from Sublime
class TypeScriptListener(sublime_plugin.EventListener):
def __init__(self):
self.fileMap = {}
self.pendingCompletions = None
self.completionView = None
self.mruFileList = []
self.pendingTimeout = 0
self.pendingSelectionTimeout = 0
self.errRefreshRequested = False
self.changeFocus = False
self.mod = False
def getInfo(self, view):
info = None
if view.file_name() is not None:
if is_typescript(view):
info = self.fileMap.get(view.file_name())
if not info:
if not cli:
plugin_loaded()
info = FileInfo(view.file_name(), None)
info.view = view
settings = view.settings()
info.clientInfo = cli.getOrAddFile(view.file_name())
setFilePrefs(view)
self.fileMap[view.file_name()] = info
open_file(view)
if view.is_dirty():
if not view.is_loading():
reloadBuffer(view, info.clientInfo)
else:
info.clientInfo.pendingChanges = True
if (info in self.mruFileList):
self.mruFileList.remove(info)
self.mruFileList.append(info)
return info
def change_count(self, view):
info = self.getInfo(view)
if info:
if cli.ST2():
return info.modCount
else:
return view.change_count()
# called by Sublime when a view receives focus
def on_activated(self, view):
info = self.getInfo(view)
if info:
info.lastCompletionLoc = None
# save cursor in case we need to read what was inserted
info.prevSel = copyRegionsStatic(view.sel())
# ask server for initial error diagnostics
self.refreshErrors(view, 200)
# set modified and selection idle timers, so we can read
# diagnostics and update
# status line
self.setOnIdleTimer(20)
self.setOnSelectionIdleTimer(20)
self.changeFocus = True
# ask the server for diagnostic information on all opened ts files in
# most-recently-used order
# TODO: limit this request to ts files currently visible in views
def refreshErrors(self, view, errDelay):
info = self.getInfo(view)
if info and (self.changeFocus or (info.changeCountErrReq < self.change_count(view))):
self.changeFocus = False
info.changeCountErrReq = self.change_count(view)
window = sublime.active_window()
numGroups = window.num_groups()
files = []
for i in range(numGroups):
groupActiveView = window.active_view_in_group(i)
info = self.getInfo(groupActiveView)
if info:
files.append(groupActiveView.file_name())
checkUpdateView(groupActiveView)
if len(files) > 0:
cli.service.requestGetError(errDelay, files)
self.errRefreshRequested = True
self.setOnIdleTimer(errDelay + 300)
# expand region list one to left for backspace change info
def expandEmptyLeft(self, regions):
result = []
for region in regions:
if region.empty():
result.append(sublime.Region(region.begin() - 1, region.end()))
else:
result.append(region)
return result
# expand region list one to right for delete key change info
def expandEmptyRight(self, regions):
result = []
for region in regions:
if region.empty():
result.append(sublime.Region(region.begin(), region.end() + 1))
else:
result.append(region)
return result
# error messages arrived from the server; show them in view
def showErrorMsgs(self, diagEvtBody, syntactic):
filename = diagEvtBody.file
if os.name == 'nt':
filename = filename.replace('/', '\\')
diags = diagEvtBody.diagnostics
info = self.fileMap.get(filename)
if info:
view = info.view
if not (info.changeCountErrReq == self.change_count(view)):
self.setOnIdleTimer(200)
else:
if syntactic:
regionKey = 'syntacticDiag'
else:
regionKey = 'semanticDiag'
view.erase_regions(regionKey)
clientInfo = cli.getOrAddFile(filename)
clientInfo.errors[regionKey] = []
errRegions = []
if diags:
for diag in diags:
startlc = diag.start
endlc = diag.end
(l, c) = extractLineOffset(startlc)
(endl, endc) = extractLineOffset(endlc)
text = diag.text
start = view.text_point(l, c)
end = view.text_point(endl, endc)
if (end <= view.size()):
region = sublime.Region(start, end)
errRegions.append(region)
clientInfo.errors[regionKey].append((region, text))
info.hasErrors = cli.hasErrors(filename)
self.update_status(view, info)
if cli.ST2():
view.add_regions(regionKey, errRegions, "keyword", "", sublime.DRAW_OUTLINED)
else:
view.add_regions(regionKey, errRegions, "keyword", "",
sublime.DRAW_NO_FILL + sublime.DRAW_NO_OUTLINE + sublime.DRAW_SQUIGGLY_UNDERLINE)
# event arrived from the server; call appropriate handler
def dispatchEvent(self, ev):
evtype = ev.event
if evtype == 'syntaxDiag':
self.showErrorMsgs(ev.body, syntactic=True)
elif evtype == 'semanticDiag':
self.showErrorMsgs(ev.body, syntactic=False)
# set timer to go off when selection is idle
def setOnSelectionIdleTimer(self, ms):
self.pendingSelectionTimeout+=1
sublime.set_timeout(self.handleSelectionTimeout, ms)
def handleSelectionTimeout(self):
self.pendingSelectionTimeout-=1
if self.pendingSelectionTimeout == 0:
self.onSelectionIdle()
# if selection is idle (cursor is not moving around)
# update the status line (error message or quick info, if any)
def onSelectionIdle(self):
view = active_view()
info = self.getInfo(view)
if info:
self.update_status(view, info)
# set timer to go off when file not being modified
def setOnIdleTimer(self, ms):
self.pendingTimeout+=1
sublime.set_timeout(self.handleTimeout, ms)
def handleTimeout(self):
self.pendingTimeout-=1
if self.pendingTimeout == 0:
self.onIdle()
# if file hasn't been modified for a time
# check the event queue and dispatch any events
def onIdle(self):
view = active_view()
ev = cli.service.getEvent()
if ev is not None:
self.dispatchEvent(ev)
self.errRefreshRequested = False
# reset the timer in case more events are on the queue
self.setOnIdleTimer(50)
elif self.errRefreshRequested:
# reset the timer if we haven't gotten an event
# since the last time errors were requested
self.setOnIdleTimer(50)
info = self.getInfo(view)
if info:
# request errors
self.refreshErrors(view, 500)
def on_load(self, view):
clientInfo = cli.getOrAddFile(view.file_name())
print("loaded " + view.file_name())
if clientInfo and clientInfo.renameOnLoad:
view.run_command('typescript_delayed_rename_file',
{ "locsName" : clientInfo.renameOnLoad })
clientInfo.renameOnLoad = None
# ST3 only
# for certain text commands, learn what changed and notify the
# server, to avoid sending the whole buffer during completion
# or when key can be held down and repeated
# called by ST3 for some, but not all, text commands
def on_text_command(self, view, command_name, args):
info = self.getInfo(view)
if info:
info.changeSent = True
info.preChangeSent = True
if command_name == "left_delete":
# backspace
sendReplaceChangesForRegions(view, self.expandEmptyLeft(view.sel()), "")
elif command_name == "right_delete":
# delete
sendReplaceChangesForRegions(view, self.expandEmptyRight(view.sel()), "")
else:
# notify on_modified and on_post_text_command events that
# nothing was handled
# there are multiple flags because Sublime does not always call
# all three events
info.preChangeSent = False
info.changeSent = False
info.modified = False
if (command_name == "commit_completion") or (command_name == "insert_best_completion"):
# for finished completion, remember current cursor and set
# a region that will be
# moved by the inserted text
info.completionSel = copyRegions(view.sel())
view.add_regions("apresComp", copyRegions(view.sel()),
flags=sublime.HIDDEN)
# update the status line with error info and quick info if no error info
def update_status(self, view, info):
if info.hasErrors:
view.run_command('typescript_error_info')
else:
view.erase_status("typescript_error")
errstatus = view.get_status('typescript_error')
if errstatus and (len(errstatus) > 0):
view.erase_status("typescript_info")
else:
view.run_command('typescript_quick_info')
def on_close(self, view):
if not cli:
plugin_loaded()
if view.is_scratch() and (view.name() == "Find References"):
cli.disposeRefInfo()
else:
info = self.getInfo(view)
if info:
if (info in self.mruFileList):
self.mruFileList.remove(info)
# make sure we know the latest state of the file
reloadBuffer(view, info.clientInfo)
# notify the server that the file is closed
cli.service.close(view.file_name())
# called by Sublime when the cursor moves (or when text is selected)
# called after on_modified (when on_modified is called)
def on_selection_modified(self, view):
info = self.getInfo(view)
if info:
if not info.clientInfo:
info.clientInfo = cli.getOrAddFile(view.file_name())
if (info.clientInfo.changeCount < self.change_count(view)) and (info.lastModChangeCount != self.change_count(view)):
# detected a change to the view for which Sublime did not call
# on_modified
# and for which we have no hope of discerning what changed
info.clientInfo.pendingChanges = True
# save the current cursor position so that we can see (in
# on_modified) what was inserted
info.prevSel = copyRegionsStatic(view.sel())
if self.mod:
self.setOnSelectionIdleTimer(1250)
else:
self.setOnSelectionIdleTimer(50)
self.mod = False
# hide the doc info output panel if it's up
panelView = sublime.active_window().get_output_panel("doc")
if panelView.window():
sublime.active_window().run_command("hide_panel", { "cancel" : True })
# usually called by Sublime when the buffer is modified
# not called for undo, redo
def on_modified(self, view):
info = self.getInfo(view)
if info:
info.modified = True
if cli.ST2():
info.modCount+=1
info.lastModChangeCount = self.change_count(view)
self.mod = True
(lastCommand, args, rept) = view.command_history(0)
# print("modified " + view.file_name() + " command " + lastCommand + " args " + str(args) + " rept " + str(rept))
if info.preChangeSent:
# change handled in on_text_command
info.clientInfo.changeCount = self.change_count(view)
info.preChangeSent = False
elif lastCommand == "insert":
if (not "\n" in args['characters']) and info.prevSel and (len(info.prevSel) == 1) and (info.prevSel[0].empty()) and (not info.clientInfo.pendingChanges):
info.clientInfo.changeCount = self.change_count(view)
prevCursor = info.prevSel[0].begin()
cursor = view.sel()[0].begin()
key = view.substr(sublime.Region(prevCursor, cursor))
sendReplaceChangesForRegions(view, staticRegionsToRegions(info.prevSel), key)
# mark change as handled so that on_post_text_command doesn't
# try to handle it
info.changeSent = True
else:
# request reload because we have strange insert
info.clientInfo.pendingChanges = True
self.setOnIdleTimer(100)
# ST3 only
# called by ST3 for some, but not all, text commands
# not called for insert command
def on_post_text_command(self, view, command_name, args):
def buildReplaceRegions(emptyRegionsA, emptyRegionsB):
rr = []
for i in range(len(emptyRegionsA)):
rr.append(sublime.Region(emptyRegionsA[i].begin(), emptyRegionsB[i].begin()))
return rr
info = self.getInfo(view)
if info:
if (not info.changeSent) and info.modified:
# file is modified but on_text_command and on_modified did not
# handle it
# handle insertion of string from completion menu, so that
# it is fast to type completedName1.completedName2 (avoid a lag
# when completedName1 is committed)
if ((command_name == "commit_completion") or command_name == ("insert_best_completion")) and (len(view.sel()) == 1) and (not info.clientInfo.pendingChanges):
# get saved region that was pushed forward by insertion of
# the completion
apresCompReg = view.get_regions("apresComp")
# note: assuming sublime makes all regions empty for
# completion, which the doc claims is true
# insertion string is from region saved in
# on_query_completion to region pushed forward by
# completion insertion
insertionString = view.substr(sublime.Region(info.completionPrefixSel[0].begin(), apresCompReg[0].begin()))
sendReplaceChangesForRegions(view, buildReplaceRegions(info.completionPrefixSel, info.completionSel), insertionString)
view.erase_regions("apresComp")
info.lastCompletionLoc = None
elif ((command_name == "typescript_format_on_key") or (command_name == "typescript_format_document") or (command_name == "typescript_format_selection") or (command_name == "typescript_format_line") or (command_name == "typescript_paste_and_format")):
# changes were sent by the command so no need to
print("handled changes for " + command_name)
else:
print(command_name)
# give up and send whole buffer to server (do this eagerly
# to avoid lag on next request to server)
reloadBuffer(view, info.clientInfo)
# we are up-to-date because either change was sent to server or
# whole buffer was sent to server
info.clientInfo.changeCount = view.change_count()
# reset flags and saved regions used for communication among
# on_text_command, on_modified, on_selection_modified,
# on_post_text_command, and on_query_completion
info.changeSent = False
info.modified = False
info.completionSel = None
# helper called back when completion info received from server
def handleCompletionInfo(self, completionsResp):
if completionsResp.success:
completions = []
rawCompletions = completionsResp.body
if rawCompletions:
for rawCompletion in rawCompletions:
name = rawCompletion.name
completion = (name + "\t" + rawCompletion.kind, name)
completions.append(completion)
self.pendingCompletions = completions
else:
self.pendingCompletions = []
else:
self.pendingCompletions = []
# not currently used; would be used in async case
def run_auto_complete(self):
active_view().run_command("auto_complete", {
'disable_auto_insert': True,
'api_completions_only': False,
'next_completion_if_showing': False,
'auto_complete_commit_on_tab': True,
})
# synchronous for now; can change to async by adding hide/show from the
# handler
def on_query_completions(self, view, prefix, locations):
info = self.getInfo(view)
if info:
print("complete with: " + prefix)
info.completionPrefixSel = decrLocsToRegions(locations, len(prefix))
if not cli.ST2():
view.add_regions("apresComp", decrLocsToRegions(locations, 0), flags=sublime.HIDDEN)
if info.lastCompletionLoc:
if (((len(prefix)-1)+info.lastCompletionLoc == locations[0]) and (prefix.startswith(info.lastCompletionPrefix))):
return (info.lastCompletions,
sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
location = getLocationFromPosition(view, locations[0])
checkUpdateView(view)
cli.service.completions(view.file_name(), location, prefix, self.handleCompletionInfo)
completions = self.pendingCompletions
info.lastCompletions = completions
info.lastCompletionLoc = locations[0]
info.lastCompletionPrefix = prefix
self.pendingCompletions = None
return (completions, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
# for debugging, send command to server to save server buffer in temp file
# TODO: safe temp file name on Windows
class TypescriptSave(sublime_plugin.TextCommand):
def run(self, text):
if (not is_typescript(self.view)):
print("To run this command, please first assign a file name to the view")
return
cli.service.saveto(self.view.file_name(), "/tmp/curstate")
sublimeWordMask = 515
# command currently called only from event handlers
class TypescriptQuickInfo(sublime_plugin.TextCommand):
def handleQuickInfo(self, quickInfoResp):
if quickInfoResp.success:
infoStr = quickInfoResp.body.displayString
docStr = quickInfoResp.body.documentation
if len(docStr) > 0:
infoStr = infoStr + " (^T^Q for more)"
self.view.set_status("typescript_info", infoStr)
else:
self.view.erase_status("typescript_info")
def run(self, text):
checkUpdateView(self.view)
wordAtSel = self.view.classify(self.view.sel()[0].begin())
if (wordAtSel & sublimeWordMask):
cli.service.quickInfo(self.view.file_name(), getLocationFromView(self.view), self.handleQuickInfo)
else:
self.view.erase_status("typescript_info")
def is_enabled(self):
return is_typescript(self.view)
class TypescriptShowDoc(sublime_plugin.TextCommand):
def run(self, text, infoStr="", docStr=""):
self.view.insert(text, self.view.sel()[0].begin(), infoStr + "\n\n")
self.view.insert(text, self.view.sel()[0].begin(), docStr)
# only use for short strings
def htmlEscape(str):
return str.replace('<','<').replace('>',">")
# command to show the doc string associated with quick info;
# re-runs quick info in case info has changed
class TypescriptQuickInfoDoc(sublime_plugin.TextCommand):
def handleQuickInfo(self, quickInfoResp):
if quickInfoResp.success:
infoStr = quickInfoResp.body.displayString
finfoStr = infoStr
docStr = quickInfoResp.body.documentation
if len(docStr) > 0:
if not TOOLTIP_SUPPORT:
docPanel = sublime.active_window().get_output_panel("doc")
docPanel.run_command('typescript_show_doc',
{ 'infoStr': infoStr,
'docStr': docStr })
docPanel.settings().set('color_scheme', "Packages/Color Scheme - Default/Blackboard.tmTheme")
sublime.active_window().run_command('show_panel', { 'panel': 'output.doc' })
finfoStr = infoStr + " (^T^Q for more)"
self.view.set_status("typescript_info", finfoStr)
if TOOLTIP_SUPPORT:
hinfoStr = htmlEscape(infoStr)
hdocStr = htmlEscape(docStr)
html = "<div>"+hinfoStr+"</div>"
if len(docStr) > 0:
html += "<div>"+hdocStr+"</div>"
self.view.show_popup(html, location = -1, max_width = 600)
else:
self.view.erase_status("typescript_info")
def run(self, text):
if (not is_typescript(self.view)):
print("To run this command, please first assign a file name to the view")
return
checkUpdateView(self.view)
wordAtSel = self.view.classify(self.view.sel()[0].begin())
if (wordAtSel & sublimeWordMask):
cli.service.quickInfo(self.view.file_name(), getLocationFromView(self.view), self.handleQuickInfo)
else:
self.view.erase_status("typescript_info")
def is_enabled(self):
return is_typescript(self.view)
# command called from event handlers to show error text in status line
# (or to erase error text from status line if no error text for location)
class TypescriptErrorInfo(sublime_plugin.TextCommand):
def run(self, text):
clientInfo = cli.getOrAddFile(self.view.file_name())
pt = self.view.sel()[0].begin()
errorText = ""
for (region, text) in clientInfo.errors['syntacticDiag']:
if region.contains(pt):
errorText = text
for (region, text) in clientInfo.errors['semanticDiag']:
if region.contains(pt):
errorText = text
if len(errorText) > 0:
self.view.set_status("typescript_error", errorText)
else:
self.view.erase_status("typescript_error")
# go to definition command
class TypescriptGoToDefinitionCommand(sublime_plugin.TextCommand):
def run(self, text):
if (not is_typescript(self.view)):
print("To run this command, please first assign a file name to the view")
return
checkUpdateView(self.view)
definitionResp = cli.service.definition(self.view.file_name(), getLocationFromView(self.view))
if definitionResp.success:
codeSpan = definitionResp.body[0] if len(definitionResp.body) > 0 else None
if codeSpan:
filename = codeSpan.file
startlc = codeSpan.start
sublime.active_window().open_file('{0}:{1}:{2}'.format(filename, startlc.line, startlc.offset),
sublime.ENCODED_POSITION)
# go to type command
class TypescriptGoToTypeCommand(sublime_plugin.TextCommand):
def run(self, text):
if (not is_typescript(self.view)):
print("To run this command, please first assign a file name to the view")
return
checkUpdateView(self.view)
typeResp = cli.service.type(self.view.file_name(), getLocationFromView(self.view))
if typeResp.success:
items = typeResp.body
if len(items) > 0:
codeSpan = items[0]
filename = codeSpan.file
startlc = codeSpan.start
sublime.active_window().open_file('{0}:{1}:{2}'.format(filename, startlc.line or 0, startlc.offset or 0),
sublime.ENCODED_POSITION)
class FinishRenameCommandArgs:
def __init__(self, newName, outerLocs):
self.newName = newName
self.outerLocs = outerLocs
@staticmethod
def fromDict(newName, outerLocs):
return FinishRenameCommandArgs(
newName,
jsonhelpers.fromDict(servicedefs.FileLocations, outerLocs))
# rename command
class TypescriptRenameCommand(sublime_plugin.TextCommand):
def run(self, text):
if (not is_typescript(self.view)):