forked from SublimeHaskell/SublimeHaskell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
autocomplete.py
2099 lines (1689 loc) · 78.7 KB
/
autocomplete.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
# -*- coding: UTF-8 -*-
import json
import os
import os.path
import re
import sublime
import sublime_plugin
import threading
import time
import sys
import webbrowser
try:
import queue
except ImportError:
import Queue as queue
if int(sublime.version()) < 3000:
from sublime_haskell_common import *
import symbols
import hdocs
from ghci import ghci_info
from haskell_docs import haskell_docs
from hdevtools import start_hdevtools, stop_hdevtools
from parseoutput import write_panel
import hsdev
else:
from SublimeHaskell.sublime_haskell_common import *
import SublimeHaskell.symbols as symbols
import SublimeHaskell.hdocs as hdocs
from SublimeHaskell.ghci import ghci_info
from SublimeHaskell.haskell_docs import haskell_docs
from SublimeHaskell.hdevtools import start_hdevtools, stop_hdevtools
from SublimeHaskell.parseoutput import write_panel
import SublimeHaskell.hsdev as hsdev
# If true, files that have not changed will not be re-inspected.
CHECK_MTIME = True
HSDEV_CACHE_PATH = None
HSDEV_LOG = None
# The agent sleeps this long between inspections.
AGENT_SLEEP_TIMEOUT = 60.0
# Checks if we are in a LANGUAGE pragma.
LANGUAGE_RE = re.compile(r'.*{-#\s+LANGUAGE.*')
# Checks if we are in OPTIONS_GHC pragma
OPTIONS_GHC_RE = re.compile(r'.*{-#\s+OPTIONS_GHC.*')
WORD_RE = re.compile(r'^(?P<word>[\w\d\'\.]*)(?P<tail>.*)')
# Checks if we are in an import statement.
IMPORT_RE = re.compile(r'.*import(\s+qualified)?\s+')
IMPORT_RE_PREFIX = re.compile(r'^\s*import(\s+qualified)?\s+([\w\d\.]*)$')
IMPORT_QUALIFIED_POSSIBLE_RE = re.compile(r'.*import\s+(?P<qualifiedprefix>\S*)$')
# Checks if a word contains only alhanums, -, and _, and dot
NO_SPECIAL_CHARS_RE = re.compile(r'^(\w|[\-\.])*$')
# Get symbol qualified prefix and its name
SYMBOL_RE = re.compile(r'((?P<module>[A-Z][\w\d]*(\.[A-Z][\w\d\']*)*)\.)?((?P<identifier>(\w[\w\d\']*)?)|(?P<operator>[!#$%&*+\./<=>?@\\\^|\-~:]+))$')
# Get import name
IMPORT_MODULE_RE = re.compile(r'import(\s+qualified)?\s+(?P<module>[A-Z][\w\d\']*(\.[A-Z][\w\d\']*)*)\b')
# SYMBOL_RE = re.compile(r'((?P<module>\w+(\.\w+)*)\.)?(?P<identifier>((\w*)|([]*)))$')
# Get symbol module scope and its name within import statement
IMPORT_SYMBOL_RE = re.compile(r'import(\s+qualified)?\s+(?P<module>[A-Z][\w\d\']*(\.[A-Z][\w\d\']*)*)(\s+as\s+(?P<as>[A-Z][\w\d\']*))?\s*\(.*?((?P<identifier>([a-z][\w\d\']*)?)|(\((?P<operator>[!#$%&*+\.\/<=>?@\\\^|\-~:]*)))$')
# Export module
EXPORT_MODULE_RE = re.compile(r'\bmodule\s+[\w\d\.]*$')
def is_scanned_source(view = None):
window, view, file_shown_in_view = get_haskell_command_window_view_file_project(view)
if file_shown_in_view is None:
return False
m = head_of(hsdev_client.module(file = file_shown_in_view))
return m is not None
def is_in_project(view = None):
window, view, file_shown_in_view = get_haskell_command_window_view_file_project(view)
if file_shown_in_view is None:
return False
m = head_of(hsdev_client.module(file = file_shown_in_view))
if m is None:
return False
return m.location.project is not None
def get_line_contents(view, location):
"""
Returns contents of line at the given location.
"""
return view.substr(sublime.Region(view.line(location).a, location))
def logged(v, fmt = '{0}'):
log(fmt.format(v), log_trace)
return v
def get_line_contents_at_region(view, region):
"""
Returns (before, at, after)
"""
line_region = view.line(region)
before = view.substr(sublime.Region(line_region.a, region.a))
at = view.substr(region)
after = view.substr(sublime.Region(region.b, line_region.b))
return (before, at, after)
def get_line_contents_before_region(view, region):
"""
Returns contents of line before the given region (including it).
"""
(before, at, _) = get_line_contents_at_region(view, region)
return before + at
def get_qualified_name(s):
"""
'bla bla bla Data.List.fo' -> ('Data.List', 'Data.List.fo')
"""
if len(s) == 0:
return ('', '')
quals = s.split()[-1].split('.')
filtered = map(lambda s: list(filter(lambda c: c.isalpha() or c.isdigit() or c == '_', s)), quals)
return ('.'.join(filtered[0:len(filtered) - 1]), '.'.join(filtered))
class QualifiedSymbol(object):
def __init__(self, name = None, module = None, module_as = None, is_import_list = False, is_operator = False):
self.name = name
self.module = module
self.module_as = module_as
self.is_import_list = is_import_list
self.is_operator = is_operator
def qualified_name(self):
if self.name is None:
return self.module
return '{0}.{1}'.format(self.module_as or self.module, self.name) if self.module else self.name
def full_name(self):
if self.name is None:
return self.module
return '{0}.{1}'.format(self.module, self.name) if self.module else self.name
def is_module(self):
return self.name is None and self.module is not None
def get_qualified_symbol(line):
"""
Get module context of symbol and symbol itself
Returns (module, as, name, is_import_list, is_operator), where module (or one of) can be None
"""
res = IMPORT_SYMBOL_RE.search(line)
if res:
return QualifiedSymbol(
name = next(i for i in [res.group('identifier'), res.group('operator')] if i is not None),
module = res.group('module'),
module_as = res.group('as'),
is_import_list = True,
is_operator = bool(res.group('operator')))
res = IMPORT_MODULE_RE.search(line)
if res:
return QualifiedSymbol(module = res.group('module'))
res = SYMBOL_RE.search(line)
# res always match
return QualifiedSymbol(
module = res.group('module'),
name = next(i for i in [res.group('identifier'), res.group('operator')] if i is not None),
is_operator = bool(res.group('operator')))
def get_qualified_symbol_at_region(view, region):
"""
Get module context of symbol and symbol itself for line before (and with) word on region
Returns (module, name), where module (or one of) can be None
"""
(before, at, after) = get_line_contents_at_region(view, region)
res = WORD_RE.match(after)
if res:
at = at + res.group('word')
return get_qualified_symbol(before + at)
# Gets available LANGUAGE options and import modules from ghc-mod
def get_ghcmod_language_pragmas():
if get_setting_async('enable_hsdev'):
return hsdev_client.ghcmod_lang()
elif get_setting_async('enable_ghc_mod'):
return call_ghcmod_and_wait(['lang']).splitlines()
return []
def get_ghcmod_flags_pragmas():
if get_setting_async('enable_hsdev'):
return hsdev_client.ghcmod_flags()
elif get_setting_async('enable_ghc_mod'):
return call_ghcmod_and_wait(['flag']).splitlines()
return []
# Background worker
class Worker(threading.Thread):
def __init__(self):
super(Worker, self).__init__()
self.jobs = queue.Queue()
def run(self):
while True:
name, fn, args, kwargs = self.jobs.get()
try:
fn(*args, **kwargs)
except Exception as e:
log('worker: job {0} fails with {1}'.format(name, e), log_debug)
def async(self, name, fn, *args, **kwargs):
self.jobs.put((name, fn, args, kwargs))
worker = None
def run_async(name, fn, *args, **kwargs):
global worker
if not worker:
worker = Worker()
worker.start()
worker.async(name, fn, *args, **kwargs)
def sort_completions(comps):
comps.sort(key = lambda k: k[0])
def sorted_completions(comps):
return list(set(comps)) # unique + sort
def make_completions(suggestions):
return sorted_completions([s.suggest() for s in (suggestions or [])])
def make_locations(comps):
return sorted([[s.brief(), s.get_source_location()] for s in comps if s.has_source_location()], key = lambda k: k[0])
class CompletionCache(object):
def __init__(self):
self.files = {}
self.cabal = []
self.sources = []
self.global_comps = []
def set_files(self, filename, comps):
self.files[filename] = comps
def set_cabal(self, comps):
self.cabal = comps
self.global_comps = sorted_completions(self.cabal + self.sources)
def set_sources(self, comps):
self.sources = comps
self.global_comps = sorted_completions(self.cabal + self.sources)
def set_locs(self, locs):
self.source_locs = locs
def global_completions(self):
return self.global_comps
# Autocompletion data
class AutoCompletion(object):
"""Information for completion"""
def __init__(self):
self.language_pragmas = []
self.flags_pragmas = []
# cabal name => set of modules, where cabal name is 'cabal' for cabal or sandbox path for cabal-devs
self.module_completions = LockedObject({})
# keywords
# TODO: keywords can't appear anywhere, we can suggest in right places
self.keyword_completions = list(map(
lambda k: (k + '\tkeyword', k),
['do', 'case', 'of', 'let', 'in', 'data', 'instance', 'type', 'newtype', 'where', 'deriving', 'import', 'module']))
self.current_filename = None
# filename ⇒ preloaded completions + None ⇒ all completions
self.cache = LockedObject(CompletionCache())
self.wide_completion = None
def mark_wide_completion(self, view):
self.wide_completion = view
@hsdev.use_hsdev
def get_completions_async(self, file_name = None):
def log_result(r):
log('completions: {0}'.format(len(r)), log_trace)
return r
none_comps = []
update_cabal = False
update_sources = False
with self.cache as cache_:
if file_name in cache_.files:
return log_result(cache_.files.get(file_name, []))
else:
update_cabal = not cache_.cabal
update_sources = not cache_.sources
if update_cabal:
self.update_cabal_completions()
if update_sources:
self.update_sources_completions()
with self.cache as cache_:
none_comps = cache_.global_completions()
import_names = []
comps = none_comps
if file_name is None:
return log_result(none_comps)
else:
log('preparing completions for {0}'.format(file_name), log_debug)
current_module = head_of(hsdev_client_back.module(file = file_name))
if current_module:
comps = make_completions(
hsdev_client_back.complete('', file_name, timeout = None))
# Get imports names
# Note, that if module imported with 'as', then it can be used only with its synonym instead of full name
import_names.extend([('{0}\tmodule {1}'.format(i.import_as, i.module), i.import_as) for i in current_module.imports if i.import_as])
import_names.extend([('{0}\tmodule'.format(i.module), i.module) for i in current_module.imports if not i.import_as])
comps.extend(import_names)
sort_completions(comps)
with self.cache as cache_:
cache_.files[file_name] = comps
return log_result(cache_.files[file_name])
def drop_completions_async(self, file_name = None):
log('drop prepared completions')
with self.cache as cache_:
if file_name is None:
cache_.files.clear()
elif file_name in cache_.files:
del cache_.files[file_name]
def update_cabal_completions(self):
pass
def update_sources_completions(self):
pass
def init_completions_async(self):
window = sublime.active_window()
if window:
view = window.active_view()
if view and is_haskell_source(view):
filename = view.file_name()
if filename:
self.get_completions_async(filename)
@hsdev.use_hsdev
def get_completions(self, view, prefix, locations):
"Get all the completions that apply to the current file."
current_file_name = view.file_name()
if not current_file_name:
return []
self.current_filename = current_file_name
line_contents = get_line_contents(view, locations[0])
qsymbol = get_qualified_symbol(line_contents)
qualified_prefix = qsymbol.qualified_name()
suggestions = []
wide = self.wide_completion == view
if wide: # Drop wide
self.wide_completion = None
if qsymbol.module:
current_module = head_of(hsdev_client.module(file = current_file_name))
current_project = None
if current_module:
current_project = current_module.location.project
if qsymbol.is_import_list:
if current_project:
# Search for declarations of qsymbol.module within current project
q_module = head_of(hsdev_client.scope_modules(file = current_file_name, input = qsymbol.module, search_type = 'exact'))
if q_module.by_source():
proj_module = hsdev_client.resolve(file = q_module.location.file, exports = True)
if proj_module:
suggestions = proj_module.declarations.values()
elif q_module.by_cabal():
cabal_module = head_of(hsdev_client.module(q_module.name, search_type = 'exact', package = q_module.location.package.name))
if cabal_module:
suggestions = cabal_module.declarations.values()
else:
suggestions = hsdev_client.complete(qualified_prefix, current_file_name, wide = wide)
return self.keyword_completions + make_completions(suggestions)
else:
with self.cache as cache_:
if wide:
return self.keyword_completions + cache_.global_completions()
else:
return self.keyword_completions + cache_.files.get(current_file_name, cache_.global_completions())
@hsdev.use_hsdev
def completions_for_module(self, module, filename = None):
"""
Returns completions for module
"""
if not module:
return []
ms = []
if filename:
ms = hsdev_client.scope_modules(filename, input = module, search_type = 'exact')
m = head_of(hsdev_client.module(
input = module,
search_type = 'exact',
file = ms[0].location.file if ms and ms[0].by_source() else None,
db = ms[0].location.db if ms and ms[0].by_cabal() else None,
package = ms[0].location.package.name if ms and ms[0].by_cabal() else None))
if not m:
return []
return make_completions(m.declarations.values())
def completions_for(self, module_name, filename = None):
"""
Returns completions for module
"""
return self.completions_for_module(module_name, filename)
@hsdev.use_hsdev
def get_import_completions(self, view, prefix, locations):
self.current_filename = view.file_name()
line_contents = get_line_contents(view, locations[0])
# Autocompletion for import statements
if get_setting('auto_complete_imports'):
match_import_list = IMPORT_SYMBOL_RE.search(line_contents)
if match_import_list:
module_name = match_import_list.group('module')
import_list_completions = []
import_list_completions.extend(self.completions_for(module_name, self.current_filename))
return import_list_completions
match_import = IMPORT_RE_PREFIX.match(line_contents)
if match_import:
(qualified, pref) = match_import.groups()
import_completions = self.get_module_completions_for(pref)
# Right after "import "? Propose "qualified" as well!
qualified_match = IMPORT_QUALIFIED_POSSIBLE_RE.match(line_contents)
if qualified_match:
qualified_prefix = qualified_match.group('qualifiedprefix')
if qualified_prefix == "" or "qualified".startswith(qualified_prefix):
import_completions.insert(0, (u"qualified", "qualified "))
return list(set(import_completions))
return []
def get_special_completions(self, view, prefix, locations):
# Contents of the current line up to the cursor
line_contents = get_line_contents(view, locations[0])
# Autocompletion for LANGUAGE pragmas
if get_setting('auto_complete_language_pragmas'):
# TODO handle multiple selections
match_language = LANGUAGE_RE.match(line_contents)
if match_language:
if not self.language_pragmas:
self.language_pragmas = get_ghcmod_language_pragmas()
return [(to_unicode(c),) * 2 for c in self.language_pragmas]
match_options = OPTIONS_GHC_RE.match(line_contents)
if match_options:
if not self.flags_pragmas:
self.flags_pragmas = get_ghcmod_flags_pragmas()
return [(to_unicode(c),) * 2 for c in self.flags_pragmas]
return []
@hsdev.use_hsdev
def get_module_completions_for(self, qualified_prefix, modules = None, current_dir = None):
def module_next_name(mname):
"""
Returns next name for prefix
pref = Control.Con, mname = Control.Concurrent.MVar, result = Concurrent.MVar
"""
suffix = mname.split('.')[(len(qualified_prefix.split('.')) - 1):]
# Sublime replaces full module name with suffix, if it contains no dots?
return suffix[0]
module_list = modules if modules else self.get_current_module_completions(current_dir = current_dir)
return list(set((module_next_name(m) + '\tmodule', module_next_name(m)) for m in module_list if m.startswith(qualified_prefix)))
@hsdev.use_hsdev
def get_current_module_completions(self, current_dir = None):
"""
Get modules, that are in scope of file/project
In case of file we just return 'scope modules' result
In case of dir we look for a related project or sandbox:
project - get dependent modules
sandbox - get sandbox modules
"""
if self.current_filename:
return set([m.name for m in hsdev_client.scope_modules(self.current_filename)])
elif current_dir:
proj = hsdev_client.project(path = current_dir)
if proj and 'path' in proj:
return set([m.name for m in hsdev_client.list_modules(deps = proj['path'])])
sbox = hsdev_client.sandbox(path = current_dir)
if sbox and type(sbox) == dict and 'sandbox' in sbox:
sbox = sbox.get('sandbox')
if sbox:
return set([m.name for m in hsdev_client.list_modules(sandbox = sbox)])
else:
return set([m.name for m in hsdev_client.list_modules(cabal = True)])
autocompletion = AutoCompletion()
def can_complete_qualified_symbol(info):
"""
Helper function, returns whether sublime_haskell_complete can run for (module, symbol, is_import_list)
"""
if not info.module:
return False
if info.is_import_list:
return info.module in autocompletion.get_current_module_completions()
else:
return list(filter(lambda m: m.startswith(info.module), autocompletion.get_current_module_completions())) != []
class SublimeHaskellComplete(SublimeHaskellTextCommand):
""" Shows autocompletion popup """
def run(self, edit, characters, wide = False):
self.wide = wide
if characters:
for region in self.view.sel():
self.view.insert(edit, region.end(), characters)
# if can_complete_qualified_symbol(get_qualified_symbol_at_region(self.view, self.view.sel()[0])):
self.view.run_command("hide_auto_complete")
sublime.set_timeout(self.do_complete, 1)
def do_complete(self):
if self.wide:
autocompletion.mark_wide_completion(self.view)
self.view.run_command("auto_complete")
class SublimeHaskellBrowseDeclarations(SublimeHaskellTextCommand):
"""
Show all available declarations in scope
"""
def run(self, edit):
self.decls = []
self.current_file_name = self.view.file_name()
self.status_msg = status_message_process('Browse declarations', priority = 3)
self.status_msg.start()
hsdev_client.scope(self.current_file_name, wait = False, on_response = self.on_resp, on_error = self.on_err)
def on_resp(self, rs):
self.decls = rs
self.status_msg.stop()
self.view.window().show_quick_panel([[decl.brief(), decl.docs.splitlines()[0] if decl.docs else ''] for decl in self.decls], self.on_done)
def on_err(self, e):
self.status_msg.fail()
self.status_msg.stop()
show_status_message('Browse declarations: {0}'.format(e))
def on_done(self, idx):
if idx == -1:
return
show_declaration_info(self.view, self.decls[idx])
class SublimeHaskellFindDeclarations(SublimeHaskellWindowCommand):
def run(self):
self.window.show_input_panel("Search string", "", self.on_done, self.on_change, self.on_cancel)
def on_done(self, input):
self.decls = hsdev_client.symbol(input = input, search_type = 'regex')
if not self.decls:
show_status_message("Nothing found for: {0}".format(input))
return
self.window.show_quick_panel([[decl.module.name + ': ' + decl.brief(), str(decl.defined_module().location)] for decl in self.decls], self.on_select)
def on_change(self, input):
pass
def on_cancel(self):
pass
def on_select(self, idx):
if idx == -1:
return
show_declaration_info(self.window.active_view(), self.decls[idx])
class SublimeHaskellHayoo(SublimeHaskellWindowCommand):
def run(self):
self.window.show_input_panel("Search string", "", self.on_done, self.on_change, self.on_cancel)
def on_done(self, input):
self.input = input
self.status_msg = status_message_process("Hayoo '{0}'".format(self.input), priority = 3)
self.status_msg.start()
hsdev_client.hayoo(self.input, page = 0, pages = 5, on_response = self.on_resp, on_error = self.on_err, wait = False)
def on_change(self, input):
pass
def on_cancel(self):
pass
def on_select(self, idx):
if idx == -1:
return
show_declaration_info(self.window.active_view(), self.decls[idx])
def on_err(self, e):
self.status_msg.fail()
self.status_msg.stop()
show_status_message("Hayoo '{0}': {1}".format(self.input, e))
def on_resp(self, rs):
self.status_msg.stop()
self.decls = rs
if not self.decls:
show_status_message("Hayoo '{0}': not found".format(self.input))
return
self.window.show_quick_panel([[decl.module.name + ': ' + decl.brief(), str(decl.defined_module().location)] for decl in self.decls], self.on_select)
class SublimeHaskellSearch(SublimeHaskellWindowCommand):
def run(self):
self.window.show_input_panel("Search string", "", self.on_done, self.on_change, self.on_cancel)
def on_done(self, input):
self.input = input
self.decls = []
self.status_msg = status_message_process("Search '{0}'".format(self.input), priority = 3)
self.status_msg.start()
hsdev_client.symbol(input = self.input, search_type = 'infix', wait = False, on_response = self.on_symbol, on_error = self.on_err)
def on_change(self, input):
pass
def on_cancel(self):
pass
def on_select(self, idx):
if idx == -1:
return
show_declaration_info(self.window.active_view(), self.decls[idx])
def on_err(self, e):
self.status_msg.fail()
self.status_msg.stop()
show_status_message("Search '{0}': {1}".format(self.input, e))
def on_symbol(self, rs):
self.decls.extend(rs)
hsdev_client.hayoo(self.input, page = 0, pages = 5, wait = False, on_response = self.on_resp, on_error = self.on_err)
def on_resp(self, rs):
self.status_msg.stop()
self.decls.extend(rs)
if not self.decls:
show_status_message("Search '{0}' not found".format(self.input))
return
self.window.show_quick_panel([[decl.module.name + ': ' + decl.brief(), str(decl.defined_module().location)] for decl in self.decls], self.on_select)
# General goto command
class SublimeHaskellGoTo(SublimeHaskellWindowCommand):
def run(self, project = False):
self.decls = []
self.declarations = []
decls = []
self.view = self.window.active_view()
self.current_filename = self.view.file_name()
(self.line, self.column) = self.view.rowcol(self.view.sel()[0].a)
if project:
current_project = head_of(hsdev_client.module(file = self.current_filename)).location.project
if not current_project:
show_status_message('File {0} is not in project'.format(self.current_filename), False)
return
decls = self.sorted_decls_name(hsdev_client.symbol(project = current_project))
self.declarations = [[decl.brief(), decl.module.name, decl.get_source_location()] for decl in decls]
else:
decls = self.sorted_decls_pos(hsdev_client.symbol(file = self.current_filename, locals = True))
self.declarations = [[(decl.position.column * ' ') + decl.brief()] for decl in decls]
self.decls = decls[:]
if not decls:
return
self.window.show_quick_panel(self.declarations, self.on_done, 0, self.closest_idx(decls), self.on_highlighted if not project else None)
def qualified_decls(self, decls):
for decl in decls:
decl.make_qualified()
return decls
def sorted_decls_name(self, decls):
return list(sorted(decls, key = lambda d: d.name))
def sorted_decls_pos(self, decls):
return list(sorted(decls, key = lambda d: (d.position.line, d.position.column)))
def closest_idx(self, decls):
fdecls = list(filter(
lambda d: d[1].defined_module().location.filename == self.current_filename,
enumerate(decls)))
if not fdecls:
return -1
return min(fdecls, key = lambda d: abs(d[1].position.line - self.line))[0]
def on_done(self, idx):
if idx == -1:
return
self.open(self.decls[idx])
def on_highlighted(self, idx):
if idx == -1:
return
self.open(self.decls[idx], True)
def open(self, decl, transient = False):
view = self.window.open_file(decl.get_source_location(), sublime.ENCODED_POSITION | sublime.TRANSIENT if transient else sublime.ENCODED_POSITION)
class SublimeHaskellGoToModule(SublimeHaskellWindowCommand):
def run(self):
self.modules = hsdev_client.list_modules(source = True)
self.window.show_quick_panel([[m.name if m.name != 'Main' else 'Main in {0}'.format(m.location.to_string()), m.location.to_string()] for m in self.modules], self.on_done, 0, 0, self.on_highlighted)
def on_done(self, idx):
if idx == -1:
return
self.window.open_file(self.modules[idx].location.to_string())
def on_highlighted(self, idx):
if idx == -1:
return
self.window.open_file(self.modules[idx].location.to_string(), sublime.TRANSIENT)
class SublimeHaskellGoToHackagePackage(SublimeHaskellTextCommand):
def run(self, edit):
pack = self.view.settings().get('package')
if pack:
webbrowser.open('http://hackage.haskell.org/package/{0}'.format(pack))
def is_enabled(self):
return self.view.settings().get('package') is not None
def is_visible(self):
return is_haskell_symbol_info(self.view)
class SublimeHaskellGoToHackageModule(SublimeHaskellTextCommand):
def run(self, edit):
if is_haskell_symbol_info(self.view):
pack = self.view.settings().get('package')
mod = self.view.settings().get('module')
if pack and mod:
webbrowser.open('http://hackage.haskell.org/package/{0}/docs/{1}.html'.format(pack, mod.replace('.', '-')))
else:
qsymbol = get_qualified_symbol_at_region(self.view, self.view.sel()[0])
ms = []
if qsymbol.is_module(): # module
scope = self.view.file_name()
if scope:
ms = [m for m in hsdev_client.scope_modules(
scope, input = qsymbol.module, search_type = 'exact') if m.by_cabal()]
else:
ms = [m for m in hsdev_client.list_modules(db = m.location.db) if m.name == qsymbol.module and m.by_cabal()]
else: # symbol
scope = self.view.file_name()
if scope:
decls = hsdev_client.whois(
qsymbol.qualified_name(),
file = scope)
if not decls:
decls = hsdev_client.lookup(
qsymbol.full_name(),
file = scope)
if not decls:
decls = hsdev_client.symbol(
input = qsymbol.full_name(),
search_type = 'exact')
if not decls:
show_status_message('Module for symbol {0} not found'.format(qsymbol.full_name()))
return
ms = [decl.defined_module() for decl in decls]
if len(ms) == 0:
show_status_message('Module {0} not found'.format(module_name))
return
if len(ms) == 1:
webbrowser.open('http://hackage.haskell.org/package/{0}/docs/{1}.html'.format(ms[0].location.package.package_id(), ms[0].name.replace('.', '-')))
else:
self.candidates = ms[:]
self.view.window().show_quick_panel([[m.name, m.location.package.package_id()] for m in self.candidates], self.on_done)
def on_done(self, idx):
if idx == -1:
return
webbrowser.open('http://hackage.haskell.org/package/{0}/docs/{1}.html'.format(self.candidates[idx].location.package.package_id(), self.candidates[idx].name.replace('.', '-')))
def is_enabled(self):
return (self.view.settings().get('package') is not None) or is_haskell_source(self.view) or is_haskell_repl(self.view)
def is_visible(self):
return is_haskell_symbol_info(self.view) or is_haskell_source(self.view) or is_haskell_repl(self.view)
class SublimeHaskellGoToAnyDeclaration(SublimeHaskellWindowCommand):
def run(self):
with autocompletion.cache as cache_:
self.cache_ = cache_
self.window.show_quick_panel(cache_.source_locs, self.on_done)
def on_done(self, idx):
if idx == -1:
return
self.window.open_file(self.cache_.source_locs[idx][1], sublime.ENCODED_POSITION)
class SublimeHaskellReinspectAll(SublimeHaskellWindowCommand):
def run(self):
if hsdev_inspector.agent_connected():
hsdev_inspector.start_inspect()
else:
show_status_message("inspector not connected", is_ok=False)
class SublimeHaskellScanContents(SublimeHaskellTextCommand):
"""
Scan module contents
"""
def run(self, edit, filename = None):
self.current_file_name = filename or self.view.file_name()
self.status_msg = status_message_process("Scanning {0}".format(self.current_file_name), priority = 3)
self.status_msg.start()
def on_resp(r):
self.status_msg.stop()
update_completions_async([self.current_file_name])
def on_err(r):
self.status_msg.fail()
self.status_msg.stop()
hsdev_client.scan(contents = {self.current_file_name: self.view.substr(sublime.Region(0, self.view.size()))}, on_response = on_resp, on_error = on_err)
class SublimeHaskellInferDocs(SublimeHaskellTextCommand):
"""
Infer types and scan docs for current module
"""
def run(self, edit, filename = None):
self.current_file_name = filename or self.view.file_name()
self.status_msg = status_message_process("Scanning docs for {0}".format(self.current_file_name), priority = 3)
self.status_msg.start()
def run_infer():
self.status_msg = status_message_process("Inferring types for {0}".format(self.current_file_name), priority = 3)
self.status_msg.start()
def on_resp_(r):
self.status_msg.stop()
def on_err_(e):
self.status_msg.fail()
self.status_msg.stop()
hsdev_client.infer(files = [self.current_file_name], on_response = on_resp_, on_error = on_err_)
def on_resp(r):
self.status_msg.stop()
run_infer()
def on_err(e):
self.status_msg.fail()
self.status_msg.stop()
run_infer()
hsdev_client.docs(files = [self.current_file_name], on_response = on_resp, on_error = on_err)
class SublimeHaskellSymbolInfoCommand(SublimeHaskellTextCommand):
"""
Show information about selected symbol
"""
def run(self, edit, filename = None, module_name = None, package_name = None, db = None, name = None, qname = None, no_browse = False):
if qname:
self.full_name = qname
self.current_file_name = self.view.file_name()
# Try whois it
self.candidates = hsdev_client.whois(qname, file = self.current_file_name)
if not self.candidates:
if filename:
self.candidates = hsdev_client.symbol(name, search_type = 'exact', file = filename)
elif module_name and package_name and db:
self.candidates = hsdev_client.symbol(
name,
search_type = 'exact',
module = module_name,
db = symbols.PackageDb.from_string(db) if db else None,
package = package_name)
else:
self.current_file_name = self.view.file_name()
qsymbol = get_qualified_symbol(qname) if qname else get_qualified_symbol_at_region(self.view, self.view.sel()[0])
module_word = qsymbol.module
ident = qsymbol.name
if ident is None: # module
if not no_browse:
self.view.window().run_command('sublime_haskell_browse_module', {
'module_name': module_word,
'scope': self.current_file_name })
return
if not module_word and not ident:
show_status_message('No symbol selected', False)
return
self.whois_name = qsymbol.qualified_name()
self.full_name = qsymbol.full_name()
self.candidates = (hsdev_client.whois(self.whois_name, self.current_file_name) or [])[:1]
if not self.candidates:
self.candidates = hsdev_client.lookup(self.full_name, self.current_file_name)
if not self.candidates:
self.candidates = hsdev_client.symbol(input = self.full_name, search_type = 'exact')
if not self.candidates:
show_status_message('Symbol {0} not found'.format(self.full_name))
return
if len(self.candidates) == 1:
self.show_symbol_info(self.candidates[0])
return
if not no_browse:
self.view.window().show_quick_panel([[c.qualified_name(), c.defined_module().location.to_string()] for c in self.candidates], self.on_done)
def on_done(self, idx):
if idx == -1:
return
self.show_symbol_info(self.candidates[idx])
def on_import_selected(self, idx):
if idx == 0: # Yes, select imported module
sublime.set_timeout(
lambda: self.view.window().show_quick_panel(['{0}.{1}'.format(i[0], i[1]) for i in self.candidates], self.on_candidate_selected), 0)
def on_candidate_selected(self, idx):
if idx == -1:
return
(module_name, ident_name) = self.candidates[idx]
info = hsdev_client.whois('{0}.{1}'.format(module_name, ident_name), self.view.file_name())
if info:
self.show_symbol_info(info[0])
else:
show_status_message("Can't get info for {0}.{1}".format(module_name, ident_name), False)
def show_symbol_info(self, decl):
show_declaration_info_panel(self.view, decl)
def is_visible(self):
return is_haskell_source(self.view) or is_haskell_repl(self.view)
# Show symbol info for declaration via calling command
def show_declaration_info(view, decl):
if decl.by_hayoo():