forked from SublimeCodeIntel/SublimeCodeIntel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SublimeCodeIntel.py
1842 lines (1524 loc) · 68.7 KB
/
SublimeCodeIntel.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 -*-
# ***** BEGIN LICENSE BLOCK *****
# Version: MPL 1.1/GPL 2.0/LGPL 2.1
#
# The contents of this file are subject to the Mozilla Public License
# Version 1.1 (the "License"); you may not use this file except in
# compliance with the License. You may obtain a copy of the License at
# http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS IS"
# basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
# License for the specific language governing rights and limitations
# under the License.
#
# The Original Code is SublimeCodeIntel code.
#
# The Initial Developer of the Original Code is German M. Bravo (Kronuz).
# Portions created by German M. Bravo (Kronuz) are Copyright (C) 2011
# German M. Bravo (Kronuz). All Rights Reserved.
#
# Contributor(s):
# German M. Bravo (Kronuz)
# ActiveState Software Inc
#
# Portions created by ActiveState Software Inc are Copyright (C) 2000-2007
# ActiveState Software Inc. All Rights Reserved.
#
"""
CodeIntel is a plugin intended to display "code intelligence" information.
The plugin is based in code from the Open Komodo Editor and has a MPL license.
Port by German M. Bravo (Kronuz). May 30, 2011
For Manual autocompletion:
User Key Bindings are setup like this:
{ "keys": ["super+j"], "command": "code_intel_auto_complete" }
For "Jump to symbol declaration":
User Key Bindings are set up like this
{ "keys": ["super+f3"], "command": "goto_python_definition" }
...and User Mouse Bindings as:
{ "button": "button1", "modifiers": ["alt"], "command": "goto_python_definition", "press_command": "drag_select" }
Configuration files (`~/.codeintel/config' or `project_root/.codeintel/config'). All configurations are optional. Example:
{
"PHP": {
"php": "/usr/bin/php",
"phpConfigFile": "php.ini"
},
"Perl": {
"perl": "/usr/bin/perl"
},
"Ruby": {
"ruby": "/usr/bin/ruby"
},
"Python": {
"python": "/usr/bin/python"
},
"Python3": {
"python3": "/usr/bin/python3"
}
}
"""
from __future__ import print_function, unicode_literals
VERSION = "2.2.0"
import os
import re
import sys
import stat
import time
import datetime
import collections
import sublime
import sublime_plugin
import threading
import logging
import json
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
try:
from io import StringIO
string_types = str
except ImportError:
from cStringIO import StringIO
string_types = basestring
CODEINTEL_HOME_DIR = os.path.expanduser(os.path.join('~', '.codeintel'))
__file__ = os.path.normpath(os.path.abspath(__file__))
__path__ = os.path.dirname(__file__)
libs_path = os.path.join(__path__, 'libs')
if libs_path not in sys.path:
sys.path.insert(0, libs_path)
arch_path = os.path.join(__path__, 'arch')
if arch_path not in sys.path:
sys.path.insert(0, arch_path)
cplns_were_empty = None
last_trigger_name = None
last_citdl_expr = None
from codeintel2.common import CodeIntelError, EvalTimeout, LogEvalController, TRG_FORM_CPLN, TRG_FORM_CALLTIP, TRG_FORM_DEFN
from codeintel2.manager import Manager
from codeintel2.environment import SimplePrefsEnvironment
from codeintel2.util import guess_lang_from_path
QUEUE = {} # views waiting to be processed by codeintel
# Setup the complex logging (status bar gets stuff from there):
# http://docs.python.org/3.3/howto/logging.html#logging-basic-tutorial
class NullHandler(logging.Handler):
def emit(self, record):
pass
condeintel_log_filename = ''
condeintel_log_file = None
stderr_hdlr = logging.StreamHandler(sys.stderr)
stderr_hdlr.setFormatter(logging.Formatter("%(name)s: %(levelname)s: %(message)s"))
codeintel_hdlr = NullHandler()
codeintel_hdlr.setFormatter(logging.Formatter("%(name)s: %(levelname)s: %(message)s"))
# Logging for this file / send to the sublime console
log = logging.getLogger("SublimeCodeIntel")
log.handlers = [stderr_hdlr]
log.setLevel(logging.ERROR) # ERROR
# the parent-logger for the rest of the plugin / send to the codeintel.log file in database dir
codeintel_log = logging.getLogger("codeintel")
codeintel_log.handlers = [codeintel_hdlr]
codeintel_log.setLevel(logging.INFO) # INFO
# create all the child-loggers for various parts of the plugin
for logger in ('codeintel.db', 'codeintel.pythoncile'):
logging.getLogger(logger).setLevel(logging.WARNING) # WARNING
for logger in ('citadel', 'css', 'django', 'html', 'html5', 'javascript', 'mason', 'nodejs',
'perl', 'php', 'python', 'python3', 'rhtml', 'ruby', 'smarty',
'tcl', 'templatetoolkit', 'xbl', 'xml', 'xslt', 'xul'):
logging.getLogger("codeintel." + logger).setLevel(logging.WARNING) # WARNING
cpln_fillup_chars = {
# These are characters that select the first item in an open autocomplete window when pressed.
# (autocompete_on_fillup should be a configuration and fillup chars take precedence over stop chars)
'Ruby': "~`@#$%^&*(+}[]|\\;:,<>/ ",
'PHP': "~`%^&*()-+{}[]|;'\",.< ",
'Python': "~`!@#$%^&()-=+{}[]|\\;:'\",.<>?/ ",
'Python3': "~`!@#$%^&()-=+{}[]|\\;:'\",.<>?/ ",
'Perl': "~`!@#$%^&*(=+}[]|\\;'\",.<>?/ ",
'CSS': " '\";},/",
'JavaScript': "~`!#%^&*()-=+{}[]|\\;:'\",.<>?/",
}
cpln_stop_chars = {
# These are characters that close the autocomplete window when pressed.
'Ruby': "~`@#$%^&*(+}[]|\\;:,<>/ '\".",
'PHP': "~`@%^&*()=+{}]|\\;:'\",.<>?/ ",
'Python': "~`!@#$%^&*()-=+{}[]|\\;:'\",.<>?/ ",
'Python3': "~`!@#$%^&*()-=+{}[]|\\;:'\",.<>?/ ",
'Perl': "-~`!@#$%^&*()=+{}[]|\\;:'\",.<>?/ ",
'CSS': " ('\";{},.>/",
'JavaScript': "~`!@#%^&*()-=+{}[]|\\;:'\",.<>?/ ",
}
old_pos = None
despair = 0
despaired = False
completions = {}
languages = {}
status_msg = {}
status_lineno = {}
status_lock = threading.Lock()
HISTORY_SIZE = 64
jump_history_by_window = {} # map of window id -> collections.deque([], HISTORY_SIZE)
def pos2bytes(content, pos):
return len(content[:pos].encode('utf-8'))
class TooltipOutputCommand(sublime_plugin.TextCommand):
def run(self, edit, output='', clear=True):
if clear:
region = sublime.Region(0, self.view.size())
self.view.erase(edit, region)
self.view.insert(edit, 0, output)
def hide_auto_complete(view):
view.run_command('hide_auto_complete')
def show_auto_complete(view, on_query_info,
disable_auto_insert=True, api_completions_only=True,
next_completion_if_showing=False, auto_complete_commit_on_tab=True):
# Show autocompletions:
def _show_auto_complete():
view.run_command('auto_complete', {
'disable_auto_insert': disable_auto_insert,
'api_completions_only': api_completions_only,
'next_completion_if_showing': next_completion_if_showing,
'auto_complete_commit_on_tab': auto_complete_commit_on_tab,
})
completions[view.id()] = on_query_info
sublime.set_timeout(_show_auto_complete, 0)
def tooltip_popup(view, snippets):
show_auto_complete(view, {
'params': ("tooltips", "none", "", None, None, False),
'cplns': snippets,
})
def tooltip(view, calltips, text_in_current_line, original_pos, lang):
codeintel_snippets = settings_manager.get('codeintel_snippets', default=True, language=lang)
codeintel_tooltips = settings_manager.get('codeintel_tooltips', default='popup', language=lang)
snippets = []
for calltip in calltips:
tip_info = calltip.split('\n')
text = ' '.join(tip_info[1:])
snippet = None
# TODO: This snippets are based and work for Python language.
# Other languages might need different treatment.
# Insert parameters as snippet:
m = re.search(r'([^\s]+)\(([^\[\(\)]*)', tip_info[0])
# Figure out how many arguments are there already:
text_in_current_line = text_in_current_line[:-1] # Remove next char after cursor
arguments = text_in_current_line.rpartition('(')[2].replace(' ', '').strip() or 0
if arguments:
initial_separator = ''
if arguments[-1] == ',':
arguments = arguments[:-1]
else:
initial_separator += ','
if not text_in_current_line.endswith(' '):
initial_separator += ' '
arguments = arguments.count(',') + 1 if arguments else 0
if m:
params = [p.strip() for p in m.group(2).split(',')]
if params:
n = 1
snippet = []
for i, p in enumerate(params):
if p and i >= arguments:
var, _, _ = p.partition('=')
var = var.strip()
if ' ' in var:
var = var.split(' ')[1]
if var[0] == '$':
var = var[1:]
snippet.append('${%s:%s}' % (n, var))
n += 1
snippet = ', '.join(snippet)
if arguments and snippet:
snippet = initial_separator + snippet
text += ' - ' + tip_info[0] # Add function to the end
else:
text = tip_info[0] + ' ' + text # No function match, just add the first line
if not codeintel_snippets:
snippet = None
# Wrap lines that are too long:
max_line_length = 80
measured_tips = []
for tip in tip_info:
if len(tip) > max_line_length:
chunks = len(tip)
for i in range(0, chunks, max_line_length):
measured_tips.append(tip[i:i + max_line_length])
else:
measured_tips.append(tip)
# Insert tooltip snippet
snippets.extend(((' ' if i > 0 else '') + l, snippet or '${0}') for i, l in enumerate(measured_tips))
if codeintel_tooltips == 'popup':
tooltip_popup(view, snippets)
elif codeintel_tooltips in ('status', 'panel'):
if codeintel_tooltips == 'status':
set_status(view, 'tip', text, timeout=15000)
else:
window = view.window()
output_panel = window.get_output_panel('tooltips')
output_panel.set_read_only(False)
text = '\n'.join(list(zip(*snippets))[0])
output_panel.run_command('tooltip_output', {'output': text})
output_panel.set_read_only(True)
window.run_command('show_panel', {'panel': 'output.tooltips'})
sublime.set_timeout(lambda: window.run_command('hide_panel', {'panel': 'output.tooltips'}), 15000)
if snippets and codeintel_snippets:
# Insert function call snippets:
# func = m.group(1)
# scope = view.scope_name(pos)
# view.run_command('new_snippet', {'contents': snippets[0][0], 'tab_trigger': func, 'scope': scope}) # FIXME: Doesn't add the new snippet... is it possible to do so?
def _insert_snippet():
# Check to see we are still at a position where the snippet is wanted:
view_sel = view.sel()
if not view_sel:
return
sel = view_sel[0]
pos = sel.end()
if not pos or pos != original_pos:
return
view.run_command('insert_snippet', {'contents': snippets[0][0]})
sublime.set_timeout(_insert_snippet, 500) # Delay snippet insertion a bit... it's annoying some times
def set_status(view, ltype, msg=None, timeout=None, delay=0, lid='CodeIntel', logger=None):
if timeout is None:
timeout = {'error': 3000, 'warning': 5000, 'info': 10000,
'event': 10000}.get(ltype, 3000)
if msg is None:
msg, ltype = ltype, 'debug'
msg = msg.strip()
status_lock.acquire()
try:
status_msg.setdefault(lid, [None, None, 0])
if msg == status_msg[lid][1]:
return
status_msg[lid][2] += 1
order = status_msg[lid][2]
finally:
status_lock.release()
def _set_status():
is_warning = 'warning' in lid
if not is_warning:
view_sel = view.sel()
lineno = view.rowcol(view_sel[0].end())[0] if view_sel else 0
status_lock.acquire()
try:
current_type, current_msg, current_order = status_msg.get(lid, [None, None, 0])
if msg != current_msg and order == current_order:
print("+", "%s: %s" % (ltype.capitalize(), msg), file=condeintel_log_file)
(logger or log.info)(msg)
if ltype != 'debug':
view.set_status(lid, "%s: %s" % (ltype.capitalize(), msg))
status_msg[lid] = [ltype, msg, order]
if not is_warning:
status_lineno[lid] = lineno
finally:
status_lock.release()
def _erase_status():
status_lock.acquire()
try:
if msg == status_msg.get(lid, [None, None, 0])[1]:
view.erase_status(lid)
status_msg[lid][1] = None
if lid in status_lineno:
del status_lineno[lid]
finally:
status_lock.release()
if msg:
sublime.set_timeout(_set_status, delay or 0)
sublime.set_timeout(_erase_status, timeout)
else:
sublime.set_timeout(_erase_status, delay or 0)
def logger(view, ltype, msg=None, timeout=None, delay=0, lid='CodeIntel'):
if msg is None:
msg, ltype = ltype, 'info'
set_status(view, ltype, msg, timeout=timeout, delay=delay, lid=lid + '-' + ltype, logger=getattr(log, ltype, None))
def getSublimeScope(view):
view_sel = view.sel()
if not view_sel:
sublime.message_dialog("NO VIEW SELECTION IN getSublimeScope()")
return
sel = view_sel[0]
pos = sel.end()
return view.scope_name(pos)
source_scopes = {
"json": "JSON",
"js": "JavaScript",
"python.3": "Python3",
"python": "Python",
"php": "PHP",
"perl": "Perl",
"ruby": "Ruby"
}
# order is important - longest keys first
ordered_checks = OrderedDict(sorted(source_scopes.items(), key=lambda t: len(t[0]), reverse=True))
def guess_lang(view=None, path=None, sublime_scope=None):
if not view:
return None
#######################################
# try to guess lang using sublime scope
scopes = sublime_scope if sublime_scope else getSublimeScope(view)
if scopes:
for scope in scopes.split(" "):
if "source" in scope:
for check in ordered_checks:
if scope[7:].startswith(check):
return source_scopes[check]
if 'text.plain' in scopes:
return None
if not codeintel_enabled(view):
return None
# check for html
if "text.html" in scopes:
return "HTML"
###################################################################
# try to guess lang by sublime syntax setting (see your status bar)
syntax = None
if view:
syntax = os.path.splitext(os.path.basename(view.settings().get('syntax')))[0]
vid = view.id()
_k_ = '%s::%s' % (syntax, path)
try:
return languages[vid][_k_]
except KeyError:
pass
languages.setdefault(vid, {})
lang = None
_codeintel_syntax_map = dict((k.lower(), v) for k, v in settings_manager.get('codeintel_syntax_map', {}).items())
_lang = lang = syntax and _codeintel_syntax_map.get(syntax.lower(), syntax)
# folders = getattr(view.window(), 'folders', lambda: [])() # FIXME: it's like this for backward compatibility (<= 2060)
# folders_id = str(hash(frozenset(folders)))
mgr = None if settings_manager._settings_id is None else codeintel_manager()
if mgr and not mgr.is_citadel_lang(lang) and not mgr.is_cpln_lang(lang):
lang = None
if mgr.is_citadel_lang(syntax) or mgr.is_cpln_lang(syntax):
_lang = lang = syntax
else:
if view and not path:
path = view.file_name()
if path:
try:
_lang = lang = guess_lang_from_path(path)
except CodeIntelError:
languages[vid][_k_] = None
return
_codeintel_enabled_languages = [l.lower() for l in view.settings().get('codeintel_enabled_languages', [])]
if lang and lang.lower() not in _codeintel_enabled_languages:
languages[vid][_k_] = None
return None
if not lang and _lang and _lang in ('Console', 'Plain text'):
if mgr:
logger(view, 'debug', "Invalid language: %s. Available: %s" % (_lang, ', '.join(set(mgr.get_citadel_langs() + mgr.get_cpln_langs()))))
else:
logger(view, 'debug', "Invalid language: %s" % _lang)
languages[vid][_k_] = lang
return lang
# timeout, busy_timeout are shorter for fill chars
# premptive is true for fillchars
def autocomplete(view, timeout, busy_timeout, forms, preemptive=False, args=[], kwargs={}):
def _autocomplete_callback(view, path, original_pos, lang, caller=None):
view_sel = view.sel()
if not view_sel:
return
# Figure out if we're still at the same position when the autocomplete was called, or abort
sel = view_sel[0]
pos = sel.end()
if not pos or pos != original_pos:
return
lpos = view.line(sel).begin()
text_in_current_line = view.substr(sublime.Region(lpos, pos + 1))
def _trigger(trigger, citdl_expr, calltips=None, cplns=None):
global cplns_were_empty, last_trigger_name, last_citdl_expr
add_word_completions = settings_manager.get("codeintel_word_completions", language=lang)
if cplns is not None or calltips is not None:
codeintel_log.info("Autocomplete called (%s) [%s]", lang, ','.join(c for c in ['cplns' if cplns else None, 'calltips' if calltips else None] if c))
# under certain circumstances we have to close before reopening
# the currently open completions-panel
# completions are available now, but were empty on last round,
# we have to close and reopen the completions tab to show them
cplns_are_empty = cplns is None
if cplns_were_empty and not cplns_are_empty:
hide_auto_complete(view)
cplns_were_empty = cplns_are_empty
# citdl_expr changed, so might the completions!
if citdl_expr != last_citdl_expr:
if not (not citdl_expr and not last_citdl_expr):
log.debug("hiding automplete-panel, b/c CITDL_EXPR CHANGED: FROM %r TO %r" % (last_citdl_expr, citdl_expr))
hide_auto_complete(view)
last_citdl_expr = citdl_expr
# the trigger changed, so will the completions!
current_trigger_name = trigger.name if trigger else None
if trigger is None and last_trigger_name is not None or last_trigger_name != current_trigger_name:
log.debug("hiding automplete-panel, b/c trigger changed: FROM %r TO %r " % (last_trigger_name, (trigger.name if trigger else 'None')))
hide_auto_complete(view)
last_trigger_name = current_trigger_name
api_completions_only = False
if trigger:
log.debug("current triggername: %r" % trigger.name)
print("current triggername: %r" % trigger.name)
api_cplns_only_trigger = [
"php-complete-static-members",
"php-complete-object-members",
"python3-complete-module-members",
"python3-complete-object-members",
"python3-complete-available-imports",
"javascript-complete-object-members"
]
if cplns is not None and trigger.name in api_cplns_only_trigger:
api_completions_only = True
add_word_completions = "None"
show_auto_complete(view, {
'params': ("cplns", add_word_completions, text_in_current_line, lang, trigger, False),
'cplns': cplns,
}, api_completions_only=api_completions_only)
if calltips:
tooltip(view, calltips, text_in_current_line, original_pos, lang)
content = view.substr(sublime.Region(0, view.size()))
codeintel(view, path, content, lang, pos, forms, _trigger, caller=caller)
queue(view, _autocomplete_callback, timeout, busy_timeout, preemptive, args=args, kwargs=kwargs)
_ci_envs_ = {}
_ci_next_scan_ = {}
_ci_mgr_ = {}
_ci_next_savedb_ = 0
_ci_next_cullmem_ = 0
################################################################################
# Queue dispatcher system:
MAX_DELAY = -1 # Does not apply
queue_thread_name = "codeintel callbacks"
def queue_dispatcher(force=False):
"""
Default implementation of queue dispatcher (just clears the queue)
"""
__lock_.acquire()
try:
QUEUE.clear()
finally:
__lock_.release()
def queue_loop():
"""An infinite loop running the codeintel in a background thread, meant to
update the view after user modifies it and then does no further
modifications for some time as to not slow down the UI with autocompletes."""
global __signaled_, __signaled_first_
while __loop_:
# print('acquire...')
__semaphore_.acquire()
__signaled_first_ = 0
__signaled_ = 0
# print("DISPATCHING!", len(QUEUE))
queue_dispatcher()
def queue(view, callback, timeout, busy_timeout=None, preemptive=False, args=[], kwargs={}):
global __signaled_, __signaled_first_
now = time.time()
__lock_.acquire()
try:
QUEUE[view.id()] = (view, callback, args, kwargs)
if now < __signaled_ + timeout * 4:
timeout = busy_timeout or timeout
__signaled_ = now
_delay_queue(timeout, preemptive)
if not __signaled_first_:
__signaled_first_ = __signaled_
# print('first',)
# print('queued in', (__signaled_ - now))
finally:
__lock_.release()
def _delay_queue(timeout, preemptive):
global __signaled_, __queued_
now = time.time()
if not preemptive and now <= __queued_ + 0.01:
return # never delay queues too fast (except preemptively)
__queued_ = now
_timeout = float(timeout) / 1000
if __signaled_first_:
if MAX_DELAY > 0 and now - __signaled_first_ + _timeout > MAX_DELAY:
_timeout -= now - __signaled_first_
if _timeout < 0:
_timeout = 0
timeout = int(round(_timeout * 1000, 0))
new__signaled_ = now + _timeout - 0.01
if __signaled_ >= now - 0.01 and (preemptive or new__signaled_ >= __signaled_ - 0.01):
__signaled_ = new__signaled_
# print('delayed to', (preemptive, __signaled_ - now))
def _signal():
if time.time() < __signaled_:
return
__semaphore_.release()
sublime.set_timeout(_signal, timeout)
def delay_queue(timeout):
__lock_.acquire()
try:
_delay_queue(timeout, False)
finally:
__lock_.release()
# only start the thread once - otherwise the plugin will get laggy
# when saving it often.
__semaphore_ = threading.Semaphore(0)
__lock_ = threading.Lock()
__queued_ = 0
__signaled_ = 0
__signaled_first_ = 0
# First finalize old standing threads:
__loop_ = False
__pre_initialized_ = False
def queue_finalize(timeout=None):
global __pre_initialized_
for thread in threading.enumerate():
if thread.isAlive() and thread.name == queue_thread_name:
__pre_initialized_ = True
print("thread finalize")
thread.__semaphore_.release()
thread.join(timeout)
queue_finalize()
# Initialize background thread:
__loop_ = True
# is this the replacement for the manager???
__active_codeintel_thread = threading.Thread(target=queue_loop, name=queue_thread_name)
__active_codeintel_thread.__semaphore_ = __semaphore_
__active_codeintel_thread.start()
################################################################################
if not __pre_initialized_:
# Start a timer
def _signal_loop():
__semaphore_.release()
sublime.set_timeout(_signal_loop, 20000)
_signal_loop()
# queue_dispatcher
def codeintel_callbacks(force=False):
global _ci_next_savedb_, _ci_next_cullmem_
__lock_.acquire()
try:
views = list(QUEUE.values())
QUEUE.clear()
finally:
__lock_.release()
for view, callback, args, kwargs in views:
def _callback():
callback(view, *args, **kwargs)
sublime.set_timeout(_callback, 0)
# saving and culling cached parts of the database:
for manager_id in list(_ci_mgr_.keys()):
mgr = codeintel_manager(manager_id)
if mgr is None:
del _ci_mgr_[manager_id]
print("NO MANAGER")
return
now = time.time()
if now >= _ci_next_savedb_ or force:
if _ci_next_savedb_:
log.debug('Saving database')
mgr.db.save() # Save every 6 seconds
_ci_next_savedb_ = now + 6
if now >= _ci_next_cullmem_ or force:
if _ci_next_cullmem_:
log.debug('Culling memory')
mgr.db.cull_mem() # Every 30 seconds
_ci_next_cullmem_ = now + 30
queue_dispatcher = codeintel_callbacks # NOQA
def codeintel_cleanup(id):
if id in _ci_envs_:
del _ci_envs_[id]
if id in _ci_next_scan_:
del _ci_next_scan_[id]
def codeintel_manager(manager_id=None):
global _ci_mgr_, condeintel_log_filename, condeintel_log_file
if manager_id is not None:
mgr = _ci_mgr_.get(manager_id, None)
return mgr
manager_id = settings_manager._settings_id
mgr = _ci_mgr_.get(manager_id, None)
if mgr is None:
codeintel_database_dir = os.path.expanduser(settings_manager.get("codeintel_database_dir"))
for thread in threading.enumerate():
if thread.name == "CodeIntel Manager":
thread.finalize() # this finalizes the index, citadel and the manager and waits them to end (join)
mgr = Manager(
extra_module_dirs=None,
db_base_dir=codeintel_database_dir, # os.path.expanduser(os.path.join('~', '.codeintel', 'databases', folders_id)),
db_catalog_dirs=[],
db_import_everything_langs=None,
)
mgr.upgrade()
mgr.initialize()
# Connect the logging file to the handler
condeintel_log_filename = os.path.join(codeintel_database_dir, 'codeintel.log')
condeintel_log_file = open(condeintel_log_filename, 'w', 1)
codeintel_log.handlers = [logging.StreamHandler(condeintel_log_file)]
msg = "Starting logging SublimeCodeIntel v%s rev %s (%s) on %s" % (VERSION, get_revision()[:12], os.stat(__file__)[stat.ST_MTIME], datetime.datetime.now().ctime())
print("%s\n%s" % (msg, "=" * len(msg)), file=condeintel_log_file)
_ci_mgr_ = {}
_ci_mgr_[manager_id] = mgr
return mgr
def codeintel_scan(view, path, content, lang, callback=None, pos=None, forms=None, caller=None):
global despair
for thread in threading.enumerate():
if thread.isAlive() and thread.name == "scanning thread":
logger(view, 'info', "Updating indexes... The first time this can take a while. Do not despair!", timeout=20000, delay=despair)
despair = 0
return
logger(view, 'info', "processing `%s': please wait..." % lang)
is_scratch = view.is_scratch()
is_dirty = view.is_dirty()
vid = view.id()
folders = getattr(view.window(), 'folders', lambda: [])() # FIXME: it's like this for backward compatibility (<= 2060)
# load settings for this language
config = settings_manager.getSettings(lang)
def _codeintel_scan():
global despair, despaired
env = None
mtime = None
catalogs = []
now = time.time()
mgr = codeintel_manager()
mgr.db.event_reporter = lambda m: logger(view, 'event', m)
# config values are provided per view(!) and are stored in an
# Environment Object
try:
env = _ci_envs_[vid]
if env._folders != folders:
raise KeyError
if env._lang != lang:
# if the language changes within one view (HTML/PHP) we need to
# update our Environment Object on each change!
raise KeyError
if env._mtime != settings_manager._settings_id:
raise KeyError
except KeyError:
# Generate new Environment
env = generateEnvironment(config, mgr, lang, folders)
_ci_envs_[vid] = env
# env._time = now + 5 # don't check again in less than five seconds
# this happens in any case:
msgs = []
buf = None
if env._valid:
# is citadel language or other supported language
if forms:
set_status(view, 'tip', "")
set_status(view, 'event', "")
msg = "CodeIntel(%s) for %s@%s [%s]" % (', '.join(forms), path, pos, lang)
msgs.append(('info', "\n%s\n%s" % (msg, "-" * len(msg))))
if catalogs:
msg = "New env with catalogs for '%s': %s" % (lang, ', '.join(catalogs) or None)
log.debug(msg)
codeintel_log.warning(msg)
msgs.append(('info', msg))
if mgr.is_citadel_lang(lang):
buf = mgr.buf_from_content(content, lang, env, path or "<Unsaved>", 'utf-8')
buf.caller = caller
buf.orig_pos = pos
now = datetime.datetime.now()
if not _ci_next_scan_.get(vid) or now > _ci_next_scan_[vid]:
_ci_next_scan_[vid] = now + datetime.timedelta(seconds=10)
despair = 0
despaired = False
msg = "Updating indexes for '%s'... The first time this can take a while." % lang
print(msg, file=condeintel_log_file)
logger(view, 'info', msg, timeout=20000, delay=1000)
if not path or is_scratch:
buf.scan() # FIXME: Always scanning unsaved files (since many tabs can have unsaved files, or find other path as ID)
else:
if is_dirty:
mtime = 1
else:
mtime = os.stat(path)[stat.ST_MTIME]
buf.scan(mtime=mtime, skip_scan_time_check=is_dirty)
if callback:
msg = "Doing CodeIntel for '%s' (hold on)..." % lang
print(msg, file=condeintel_log_file)
logger(view, 'info', msg, timeout=20000, delay=1000)
callback(buf, msgs)
else:
logger(view, 'info', "")
threading.Thread(target=_codeintel_scan, name="scanning thread").start()
def codeintel(view, path, content, lang, pos, forms, callback, timeout=7000, caller=None):
start = time.time()
def _codeintel(buf, msgs):
cplns = None
calltips = None
defns = None
if not buf:
logger(view, 'warning', "`%s' (%s) is not a language that uses CIX" % (path, lang))
return [None] * len(forms)
def get_trg(type, *args):
try:
trg = getattr(buf, type, lambda *a: None)(*args)
except CodeIntelError:
codeintel_log.exception("Exception! %s:%s (%s)" % (path or '<Unsaved>', pos, lang))
logger(view, 'info', "Error indexing! Please send the log file: '%s" % condeintel_log_filename)
trg = None
except:
codeintel_log.exception("Exception! %s:%s (%s)" % (path or '<Unsaved>', pos, lang))
logger(view, 'info', "Error indexing! Please send the log file: '%s" % condeintel_log_filename)
raise
return trg
bpos = pos2bytes(content, pos)
if caller == 'on_modified':
trg = get_trg('trg_from_pos', bpos) # Use fast trg_from_pos
else:
trg = get_trg('preceding_trg_from_pos', bpos, bpos) # Use more precise preceding_trg_from_pos
defn_trg = get_trg('defn_trg_from_pos', bpos) if 'defns' in forms else None
eval_log_stream = StringIO()
_hdlrs = codeintel_log.handlers
hdlr = logging.StreamHandler(eval_log_stream)
hdlr.setFormatter(logging.Formatter("%(name)s: %(levelname)s: %(message)s"))
codeintel_log.handlers = list(_hdlrs) + [hdlr]
ctlr = LogEvalController(codeintel_log)
try:
if 'cplns' in forms:
if trg and trg.form == TRG_FORM_CPLN:
cplns = buf.cplns_from_trg(trg, ctlr=ctlr, timeout=20)
if 'calltips' in forms:
if trg and trg.form == TRG_FORM_CALLTIP:
calltips = buf.calltips_from_trg(trg, ctlr=ctlr, timeout=20)
if 'defns' in forms:
if defn_trg and defn_trg.form == TRG_FORM_DEFN:
defns = buf.defns_from_trg(defn_trg, ctlr=ctlr, timeout=20)
except EvalTimeout:
logger(view, 'info', "Timeout while resolving completions!")
finally:
codeintel_log.handlers = _hdlrs
logger(view, 'warning', "")
logger(view, 'event', "")
result = False
merge = ''
for msg in reversed(eval_log_stream.getvalue().strip().split('\n')):
msg = msg.strip()
if msg:
try:
name, levelname, msg = msg.split(':', 2)
name = name.strip()
levelname = levelname.strip().lower()
msg = msg.strip()
except:
merge = (msg + ' ' + merge) if merge else msg
continue
merge = ''
if not result and msg.startswith('evaluating '):
set_status(view, 'warning', msg)
result = True
# collect citdl_expr from this run
citdl_expr = buf.last_citdl_expr
ret = {
"trigger": trg,
"citdl_expr": citdl_expr
}
for f in forms:
if f == 'cplns':
ret["cplns"] = cplns
elif f == 'calltips':
ret["calltips"] = calltips
elif f == 'defns':
ret["defns"] = defns
total = (time.time() - start) * 1000
if total > 1000:
timestr = "~%ss" % int(round(total / 1000))
else:
timestr = "%sms" % int(round(total))
if not despaired or total < timeout:
msg = "Done '%s' CodeIntel! Full CodeIntel took %s" % (lang, timestr)
print(msg, file=condeintel_log_file)
def _callback():
view_sel = view.sel()
if view_sel and view.line(view_sel[0]) == view.line(pos):
callback(**ret)
logger(view, 'info', "")
sublime.set_timeout(_callback, 0)
else:
msg = "Just finished indexing '%s'! Please try again. Full CodeIntel took %s" % (lang, timestr)
print(msg, file=condeintel_log_file)
logger(view, 'info', msg, timeout=3000)
codeintel_scan(view, path, content, lang, _codeintel, pos, forms, caller=caller)
def generateEnvironment(config, mgr, lang, folders):
catalogs = []
valid = True
if not mgr.is_citadel_lang(lang) and not mgr.is_cpln_lang(lang):
if lang in ('Console', 'Plain text'):
msg = "Invalid language: %s. Available: %s" % (lang, ', '.join(set(mgr.get_citadel_langs() + mgr.get_cpln_langs())))
log.debug(msg)
codeintel_log.warning(msg)
valid = False
codeintel_selected_catalogs = config.get('codeintel_selected_catalogs')
avail_catalogs = mgr.db.get_catalogs_zone().avail_catalogs()
# Load configuration files:
all_catalogs = []
for catalog in avail_catalogs:
all_catalogs.append("%s (for %s: %s)" % (catalog['name'], catalog['lang'], catalog['description']))
if catalog['lang'] == lang:
if catalog['name'] in codeintel_selected_catalogs:
catalogs.append(catalog['name'])