forked from SublimeCodeIntel/SublimeCodeIntel
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSublimeCodeIntel.py
More file actions
Latest commit
1109 lines (937 loc) · 41.9 KB
/
Copy pathSublimeCodeIntel.py
File metadata and controls
1109 lines (937 loc) · 41.9 KB
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
# ***** 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',
"phpExtraPaths": [],
"phpConfigFile": 'php.ini'
},
"JavaScript": {
"javascriptExtraPaths": []
},
"Perl": {
"perl": "/usr/bin/perl",
"perlExtraPaths": []
},
"Ruby": {
"ruby": "/usr/bin/ruby",
"rubyExtraPaths": []
},
"Python": {
"python": '/usr/bin/python',
"pythonExtraPaths": []
},
"Python3": {
"python": '/usr/bin/python3',
"pythonExtraPaths": []
}
}
"""
importos, sys, stat, time, datetime, collections, re
importsublime_plugin, sublime
importthreading
importlogging
fromcStringIOimportStringIO
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')
iflibs_pathnotinsys.path:
sys.path.insert(0, libs_path)
fromcodeintel2.commonimport*
fromcodeintel2.managerimportManager
fromcodeintel2.citadelimportCitadelBuffer
fromcodeintel2.environmentimportSimplePrefsEnvironment
fromcodeintel2.utilimportguess_lang_from_path
QUEUE= {} # views waiting to be processed by codeintel
# Setup the complex logging (status bar gets stuff from there):
classNullHandler(logging.Handler):
defemit(self, record):
pass
codeintel_hdlr=NullHandler()
codeintel_hdlr.setFormatter(logging.Formatter("%(name)s: %(levelname)s: %(message)s"))
stderr_hdlr=logging.StreamHandler(sys.stderr)
stderr_hdlr.setFormatter(logging.Formatter("%(name)s: %(levelname)s: %(message)s"))
codeintel_log=logging.getLogger("codeintel")
condeintel_log_filename=''
condeintel_log_file=None
log=logging.getLogger("SublimeCodeIntel")
codeintel_log.handlers= [codeintel_hdlr]
log.handlers= [stderr_hdlr]
codeintel_log.setLevel(logging.INFO) # INFO
logging.getLogger("codeintel.db").setLevel(logging.WARNING) # WARNING/INFO
forlangin ('css', 'django', 'html', 'html5', 'javascript', 'mason', 'nodejs',
'perl', 'php', 'python', 'python3', 'rhtml', 'ruby', 'smarty',
'tcl', 'templatetoolkit', 'xbl', 'xml', 'xslt', 'xul'):
logging.getLogger("codeintel."+lang).setLevel(logging.WARNING) # WARNING/DEBUG
log.setLevel(logging.ERROR) # ERROR
cpln_fillup_chars= {
'Ruby': "~`@#$%^&*(+}[]|\\;:,<>/ ",
'Python': "~`!@#$%^&()-=+{}[]|\\;:'\",.<>?/ ",
'PHP': "~`%^&*()-+{}[]|;'\",.< ",
'Perl': "~`!@#$%^&*(=+}[]|\\;'\",.<>?/ ",
'CSS': " '\";},/",
'JavaScript': "~`!#%^&*()-=+{}[]|\\;:'\",.<>?/",
}
cpln_stop_chars= {
'Ruby': "~`@#$%^&*(+}[]|\\;:,<>/ '\".",
'Python': "~`!@#$%^&*()-=+{}[]|\\;:'\",.<>?/ ",
'PHP': "~`@%^&*()=+{}]|\\;:'\",.<>?/ ",
'Perl': "-~`!@#$%^&*()=+{}[]|\\;:'\",.<>?/ ",
'CSS': " ('\";{},.>/",
'JavaScript': "~`!@#%^&*()-=+{}[]|\\;:'\",.<>?/ ",
}
old_pos=None
despair=0
despaired=False
completions= {}
languages= {}
sentinel= {}
status_msg= {}
status_lineno= {}
status_lock=threading.Lock()
HISTORY_SIZE=64
jump_history_by_window= {} # map of window id -> collections.deque([], HISTORY_SIZE)
defpos2bytes(content, pos):
returnlen(content[:pos].encode('utf-8'))
defcalltip(view, type, msg=None, timeout=None, delay=0, id='CodeIntel', logger=None):
iftimeoutisNone:
timeout= {'error': 3000, 'warning': 5000, 'info': 10000, 'event': 10000, 'tip': 15000}.get(type, 3000)
ifmsgisNone:
msg, type=type, 'debug'
msg=msg.strip()
status_lock.acquire()
try:
status_msg.setdefault(id, [None, None, 0])
ifmsg==status_msg[id][1]:
return
status_msg[id][2] +=1
order=status_msg[id][2]
finally:
status_lock.release()
def_calltip_set():
lineno=view.line(view.sel()[0])
status_lock.acquire()
try:
current_type, current_msg, current_order=status_msg.get(id, [None, None, 0])
ifmsg!=current_msgandorder==current_order:
ifmsg:
print>>condeintel_log_file, "+", "%s: %s"% (type.capitalize(), msg)
view.set_status(id, "%s: %s"% (type.capitalize(), msg))
(loggerorlog.info)(msg)
else:
view.erase_status(id)
status_msg[id][0] = [type, msg, order]
if'warning'notinidandmsg:
status_lineno[id] =lineno
elifidinstatus_lineno:
delstatus_lineno[id]
finally:
status_lock.release()
def_calltip_erase():
status_lock.acquire()
try:
ifmsg==status_msg.get(id, [None, None, 0])[1]:
view.erase_status(id)
status_msg[id][1] =None
ifidinstatus_lineno:
delstatus_lineno[id]
finally:
status_lock.release()
sublime.set_timeout(_calltip_set, delayor0)
ifmsg:
sublime.set_timeout(_calltip_erase, timeout)
deflogger(view, type, msg=None, timeout=None, delay=0, id='CodeIntel'):
ifmsgisNone:
msg, type=type, 'info'
calltip(view, type, msg, timeout=timeout, delay=delay, id=id+'-'+type, logger=getattr(log, type, None))
defguess_lang(view=None, path=None):
ifnotview.settings().get('codeintel', True):
returnNone
syntax=None
ifview:
syntax=os.path.splitext(os.path.basename(view.settings().get('syntax')))[0]
id=view.id()
_k_='%s::%s'% (syntax, path)
try:
returnlanguages[id][_k_]
exceptKeyError:
pass
languages.setdefault(id, {})
lang=None
_codeintel_syntax_map=dict((k.lower(), v) fork, vinview.settings().get('codeintel_syntax_map', {}).items())
_lang=lang=syntaxand_codeintel_syntax_map.get(syntax.lower(), syntax)
mgr=codeintel_manager()
ifnotmgr.is_citadel_lang(lang) andnotmgr.is_cpln_lang(lang):
lang=None
ifmgr.is_citadel_lang(syntax) ormgr.is_cpln_lang(syntax):
_lang=lang=syntax
else:
ifviewandnotpath:
path=view.file_name()
ifpath:
try:
_lang=lang=guess_lang_from_path(path)
exceptCodeIntelError:
languages[id][_k_] =None
return
_codeintel_disabled_languages= [l.lower() forlinview.settings().get('codeintel_disabled_languages', [])]
iflangandlang.lower() in_codeintel_disabled_languages:
logger(view, 'info', "skip `%s': disabled language"%lang)
languages[id][_k_] =None
return
ifnotlangand_langand_langnotin ('Console',):
ifmgr:
logger(view, 'info', "Invalid language: %s. Available: %s"% (_lang, ', '.join(set(mgr.get_citadel_langs() +mgr.get_cpln_langs()))))
else:
logger(view, 'info', "Invalid language: %s"%_lang)
languages[id][_k_] =lang
returnlang
defautocomplete(view, timeout, busy_timeout, preemptive=False, args=[], kwargs={}):
def_autocomplete_callback(view, path, lang):
id=view.id()
content=view.substr(sublime.Region(0, view.size()))
sel=view.sel()[0]
pos=sel.end()
try:
next=content[pos].strip()
exceptIndexError:
next=''
ifposandcontentandcontent[view.line(sel).begin():pos].strip() andnotnext.isalnum() andnext!='_':
#TODO: For the sentinel to work, we need to send a prefix to the completions... but no show_completions() currently available
#pos = sentinel[id] if sentinel[id] is not None else view.sel()[0].end()
def_trigger(cplns, calltips):
ifcplnsisnotNoneorcalltipsisnotNone:
codeintel_log.info("Autocomplete called (%s) [%s]", lang, ','.join(cforcin ['cplns'ifcplnselseNone, 'calltips'ifcalltipselseNone] ifc))
ifcplns:
# Show autocompletions:
_completions=sorted(
[('%s (%s)'% (name, type), name+ ('(${1})'iftype=='function'else'')) fortype, nameincplns],
cmp=lambdaa, b: a[1] <b[1] ifa[1].startswith('_') andb[1].startswith('_') elseFalseifa[1].startswith('_') elseTrueifb[1].startswith('_') elsea[1] <b[1]
)
if_completions:
completions[id] =_completions
view.run_command('auto_complete', {
'disable_auto_insert': True,
'api_completions_only': True,
'next_completion_if_showing': False,
'auto_complete_commit_on_tab': True,
})
elifcalltipsisnotNone:
# Trigger a tooltip
calltip(view, 'tip', calltips[0])
ifcontent[sel.a-1] =='('andcontent[sel.a] ==')':
rex=re.compile("\(([^\[\(\)]*)")
m=rex.search(calltips[0])
ifmisNone:
return
params=m.group(1).split(',')
snippet= []
i=1
forpinparams:
p=p.strip()
ifp.find('=') !=-1:
continue
ifp.find(' ') !=-1:
p=p.split(' ')[1]
var=p.replace('$', '').strip()
snippet.append('${'+str(i) +':'+var+'}')
i+=1
ifi==1:
return
view.run_command('insert_snippet', {
'contents': ', '.join(snippet)
})
sentinel[id] =None
codeintel(view, path, content, lang, pos, ('cplns', 'calltips'), _trigger)
# If it's a fill char, queue using lower values and preemptive behavior
queue(view, _autocomplete_callback, timeout, busy_timeout, preemptive, args=args, kwargs=kwargs)
_ci_envs_= {}
_ci_next_scan_= {}
_ci_mgr_=None
_ci_db_base_dir_=None
_ci_db_catalog_dirs_= []
_ci_db_import_everything_langs=None
_ci_extra_module_dirs_=None
_ci_next_savedb_=0
_ci_next_cullmem_=0
################################################################################
# Queue dispatcher system:
queue_thread_name="codeintel callbacks"
MAX_DELAY=-1# Does not apply
defqueue_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()
defqueue(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)
ifnow<__signaled_+timeout*4:
timeout=busy_timeoutortimeout
__signaled_=now
_delay_queue(timeout, preemptive)
ifnot__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()
ifnotpreemptiveandnow<=__queued_+0.01:
return# never delay queues too fast (except preemptively)
__queued_=now
_timeout=float(timeout) /1000
if__signaled_first_:
ifMAX_DELAY>0andnow-__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.01and (preemptiveornew__signaled_>=__signaled_-0.01):
__signaled_=new__signaled_
#print 'delayed to', (preemptive, __signaled_ - now)
def_signal():
iftime.time() <__signaled_:
return
__semaphore_.release()
sublime.set_timeout(_signal, timeout)
defdelay_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
defqueue_finalize(timeout=None):
global__pre_initialized_
forthreadinthreading.enumerate():
ifthread.isAlive() andthread.name==queue_thread_name:
__pre_initialized_=True
thread.__semaphore_.release()
thread.join(timeout)
queue_finalize()
# Initialize background thread:
__loop_=True
__active_codeintel_thread=threading.Thread(target=queue_loop, name=queue_thread_name)
__active_codeintel_thread.__semaphore_=__semaphore_
__active_codeintel_thread.start()
################################################################################
ifnot__pre_initialized_:
# Start a timer
def_signal_loop():
__semaphore_.release()
sublime.set_timeout(_signal_loop, 20000)
_signal_loop()
defcodeintel_callbacks(force=False):
global_ci_next_savedb_, _ci_next_cullmem_
__lock_.acquire()
try:
views=QUEUE.values()
QUEUE.clear()
finally:
__lock_.release()
forview, callback, args, kwargsinviews:
def_callback():
callback(view, *args, **kwargs)
sublime.set_timeout(_callback, 0)
# saving and culling cached parts of the database:
mgr=codeintel_manager()
now=time.time()
ifnow>=_ci_next_savedb_orforce:
if_ci_next_savedb_:
log.debug('Saving database')
mgr.db.save() # Save every 6 seconds
_ci_next_savedb_=now+6
ifnow>=_ci_next_cullmem_orforce:
if_ci_next_cullmem_:
log.debug('Culling memory')
mgr.db.cull_mem() # Every 30 seconds
_ci_next_cullmem_=now+30
queue_dispatcher=codeintel_callbacks
defcodeintel_cleanup(id):
ifidin_ci_envs_:
del_ci_envs_[id]
ifidin_ci_next_scan_:
del_ci_next_scan_[id]
defcodeintel_manager():
global_ci_mgr_, condeintel_log_filename, condeintel_log_file
if_ci_mgr_:
mgr=_ci_mgr_
else:
forthreadinthreading.enumerate():
ifthread.name=="CodeIntel Manager":
thread.finalize() # this finalizes the index, citadel and the manager and waits them to end (join)
mgr=Manager(
extra_module_dirs=_ci_extra_module_dirs_,
db_base_dir=_ci_db_base_dir_,
db_catalog_dirs=_ci_db_catalog_dirs_,
db_import_everything_langs=_ci_db_import_everything_langs,
)
mgr.upgrade()
mgr.initialize()
# Connect the logging file to the handler
condeintel_log_filename=os.path.join(mgr.db.base_dir, 'codeintel.log')
condeintel_log_file=open(condeintel_log_filename, 'w', 1)
codeintel_log.handlers= [logging.StreamHandler(condeintel_log_file)]
msg="Starting logging SublimeCodeIntel rev %s (%s) on %s"% (get_revision()[:12], os.stat(__file__)[stat.ST_MTIME], datetime.datetime.now().ctime())
print>>condeintel_log_file, "%s\n%s"% (msg, "="*len(msg))
_ci_mgr_=mgr
returnmgr
defcodeintel_scan(view, path, content, lang, callback=None, pos=None, forms=None):
globaldespair
forthreadinthreading.enumerate():
ifthread.isAlive() andthread.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()
id=view.id()
folders=getattr(view.window(), 'folders', lambda: [])() # FIXME: it's like this for backward compatibility (<= 2060)
def_codeintel_scan():
globaldespair, despaired
env=None
mtime=None
catalogs= []
now=time.time()
mgr=codeintel_manager()
mgr.db.event_reporter=lambdam: logger(view, 'event', m)
try:
env=_ci_envs_[id]
ifenv._folders!=folders:
raiseKeyError
ifnow>env._time:
mtime=max(tryGetMTime(env._config_file), tryGetMTime(env._config_default_file))
ifenv._mtime<mtime:
raiseKeyError
exceptKeyError:
ifenvisnotNone:
config_default_file=env._config_default_file
project_dir=env._project_dir
project_base_dir=env._project_base_dir
config_file=env._config_file
else:
config_default_file=os.path.join(CODEINTEL_HOME_DIR, 'config')
ifnot (config_default_fileandos.path.exists(config_default_file)):
config_default_file=None
project_dir=None
project_base_dir=None
ifpath:
# Try to find a suitable project directory (or best guess):
forfolderin ['.codeintel', '.git', '.hg', '.svn', 'trunk']:
project_dir=find_folder(path, folder)
ifproject_dir:
iffolder=='.codeintel':
ifproject_dir==CODEINTEL_HOME_DIRoros.path.exists(os.path.join(project_dir, 'db')):
continue
iffolder.startswith('.'):
project_base_dir=os.path.abspath(os.path.join(project_dir, '..'))
else:
project_base_dir=project_dir
break
ifnot (project_dirandos.path.exists(project_dir)):
project_dir=None
config_file=project_dirandfolder=='.codeintel'andos.path.join(project_dir, 'config')
ifnot (config_fileandos.path.exists(config_file)):
config_file=None
valid=True
ifnotmgr.is_citadel_lang(lang) andnotmgr.is_cpln_lang(lang):
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
# Load configuration files:
forcataloginmgr.db.get_catalogs_zone().avail_catalogs():
ifcatalog['lang'] ==lang:
catalogs.append(catalog['name'])
config= {
"codeintel_selected_catalogs": catalogs,
"codeintel_max_recursive_dir_depth": 10,
"codeintel_scan_files_in_project": True,
}
_config= {}
try:
tryReadDict(config_default_file, _config)
exceptException, e:
msg="Malformed configuration file '%s': %s"% (config_default_file, e)
log.error(msg)
codeintel_log.error(msg)
try:
tryReadDict(config_file, _config)
exceptException, e:
msg="Malformed configuration file '%s': %s"% (config_default_file, e)
log.error(msg)
codeintel_log.error(msg)
config.update(_config.get(lang, {}))
forconfin ['pythonExtraPaths', 'rubyExtraPaths', 'perlExtraPaths', 'javascriptExtraPaths', 'phpExtraPaths']:
v= [p.strip() forpinconfig.get(conf, []) +foldersifp.strip()]
config[conf] =os.pathsep.join(set(pifp.startswith('/') elseos.path.expanduser(p) ifp.startswith('~') elseos.path.abspath(os.path.join(project_base_dir, p)) ifproject_base_direlsepforpinvifp.strip()))
env=SimplePrefsEnvironment(**config)
env._valid=valid
env._mtime=mtimeormax(tryGetMTime(config_file), tryGetMTime(config_default_file))
env._folders=folders
env._config_default_file=config_default_file
env._project_dir=project_dir
env._project_base_dir=project_base_dir
env._config_file=config_file
env.__class__.get_proj_base_dir=lambdaself: project_base_dir
_ci_envs_[id] =env
env._time=now+5# don't check again in less than five seconds
msgs= []
ifenv._valid:
ifforms:
calltip(view, 'tip', "")
calltip(view, 'event', "")
msg="CodeIntel(%s) for %s@%s [%s]"% (', '.join(forms), path, pos, lang)
msgs.append(('info', "\n%s\n%s"% (msg, "-"*len(msg))))
ifcatalogs:
msgs.append(('info', "New env with catalogs for '%s': %s"% (lang, ', '.join(catalogs) orNone)))
buf=mgr.buf_from_content(content.encode('utf-8'), lang, env, pathor"<Unsaved>", 'utf-8')
now=datetime.datetime.now()
ifnot_ci_next_scan_.get(id) ornow>_ci_next_scan_[id]:
_ci_next_scan_[id] =now+datetime.timedelta(seconds=10)
ifisinstance(buf, CitadelBuffer):
despair=0
despaired=False
msg="Updating indexes for '%s'... The first time this can take a while."%lang
print>>condeintel_log_file, msg
logger(view, 'info', msg, timeout=20000, delay=1000)
ifnotpathoris_scratch:
buf.scan() # FIXME: Always scanning unsaved files (since many tabs can have unsaved files, or find other path as ID)
else:
ifis_dirty:
mtime=1
else:
mtime=os.stat(path)[stat.ST_MTIME]
buf.scan(mtime=mtime, skip_scan_time_check=is_dirty)
else:
buf=None
ifcallback:
msg="Doing CodeIntel for '%s' (hold on)..."%lang
print>>condeintel_log_file, msg
logger(view, 'info', msg, timeout=20000, delay=1000)
callback(buf, msgs)
else:
logger(view, 'info', "")
threading.Thread(target=_codeintel_scan, name="scanning thread").start()
defcodeintel(view, path, content, lang, pos, forms, callback=None, timeout=7000):
start=time.time()
def_codeintel(buf, msgs):
cplns=None
calltips=None
defns=None
ifnotbuf:
logger(view, 'warning', "`%s' (%s) is not a language that uses CIX"% (path, lang))
return [None] *len(forms)
try:
trg=getattr(buf, 'preceding_trg_from_pos', lambdap: None)(pos2bytes(content, pos), pos2bytes(content, pos))
defn_trg=getattr(buf, 'defn_trg_from_pos', lambdap: None)(pos2bytes(content, pos))
except (CodeIntelError):
codeintel_log.exception("Exception! %s:%s (%s)"% (pathor'<Unsaved>', pos, lang))
logger(view, 'info', "Error indexing! Please send the log file: '%s"%condeintel_log_filename)
trg=None
defn_trg=None
except:
codeintel_log.exception("Exception! %s:%s (%s)"% (pathor'<Unsaved>', pos, lang))
logger(view, 'info', "Error indexing! Please send the log file: '%s"%condeintel_log_filename)
raise
else:
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'informsandtrgandtrg.form==TRG_FORM_CPLN:
cplns=buf.cplns_from_trg(trg, ctlr=ctlr, timeout=20)
if'calltips'informsandtrgandtrg.form==TRG_FORM_CALLTIP:
calltips=buf.calltips_from_trg(trg, ctlr=ctlr, timeout=20)
if'defns'informsanddefn_trganddefn_trg.form==TRG_FORM_DEFN:
defns=buf.defns_from_trg(defn_trg, ctlr=ctlr, timeout=20)
exceptEvalTimeout:
logger(view, 'info', "Timeout while resolving completions!")
finally:
codeintel_log.handlers=_hdlrs
logger(view, 'warning', "")
logger(view, 'event', "")
result=False
merge=''
formsginreversed(eval_log_stream.getvalue().strip().split('\n')):
msg=msg.strip()
ifmsg:
try:
name, levelname, msg=msg.split(':', 2)
name=name.strip()
levelname=levelname.strip().lower()
msg=msg.strip()
except:
merge= (msg+' '+merge) ifmergeelsemsg
continue
merge=''
ifnotresultandmsg.startswith('evaluating '):
calltip(view, 'warning', msg)
result=True
ret= []
forfinforms:
iff=='cplns':
ret.append(cplns)
eliff=='calltips':
ret.append(calltips)
eliff=='defns':
ret.append(defns)
total= (time.time() -start) *1000
iftotal>1000:
timestr="~%ss"%int(round(total/1000))
else:
timestr="%sms"%int(round(total))
ifnotdespairedortotal<timeout:
msg="Done '%s' CodeIntel! Full CodeIntel took %s"% (lang, timestr)
print>>condeintel_log_file, msg
def_callback():
ifview.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>>condeintel_log_file, msg
logger(view, 'info', msg, timeout=3000)
codeintel_scan(view, path, content, lang, _codeintel, pos, forms)
deffind_folder(start_at, look_for):
start_at=os.path.abspath(start_at)
ifnotos.path.isdir(start_at):
start_at=os.path.dirname(start_at)
whileTrue:
iflook_forinos.listdir(start_at):
returnos.path.join(start_at, look_for)
continue_at=os.path.abspath(os.path.join(start_at, '..'))
ifcontinue_at==start_at:
returnNone
start_at=continue_at
defupdateCodeIntelDict(master, partial):
forkey, valueinpartial.items():
ifisinstance(value, dict):
master.setdefault(key, {}).update(value)
elifisinstance(value, (list, tuple)):
master.setdefault(key, []).extend(value)
deftryReadDict(filename, dictToUpdate):
iffilename:
file=open(filename, 'r')
try:
updateCodeIntelDict(dictToUpdate, eval(file.read()))
finally:
file.close()
deftryGetMTime(filename):
iffilename:
returnos.stat(filename)[stat.ST_MTIME]
return0
def_get_git_revision(path):
path=os.path.join(path, '.git')
ifos.path.exists(path):
revision_file=os.path.join(path, 'refs', 'heads', 'master')
ifos.path.isfile(revision_file):
fh=open(revision_file, 'r')
try:
returnfh.read().strip()
finally:
fh.close()
defget_revision(path=None):
"""
:returns: Revision number of this branch/checkout, if available. None if
no revision number can be determined.
"""
path=os.path.abspath(os.path.normpath(__path__ifpathisNoneelsepath))
whilepathandpath!='/'andpath!='\\':
rev=_get_git_revision(path)
ifrev:
returnu'GIT-%s'%rev
uppath=os.path.abspath(os.path.join(path, '..'))
ifuppath!=path:
path=uppath
else:
break
returnu'GIT-unknown'
classPythonCodeIntel(sublime_plugin.EventListener):
defon_close(self, view):
id=view.id()
ifidincompletions:
delcompletions[id]
ifidinsentinel:
delsentinel[id]
ifidinlanguages:
dellanguages[id]
codeintel_cleanup(view.file_name())
defon_modified(self, view):
path=view.file_name()
lang=guess_lang(view, path)
iflang:
pos=view.sel()[0].end()
text=view.substr(sublime.Region(pos-1, pos))
is_fill_char= (textandtext[-1] incpln_fillup_chars.get(lang, ''))
live=True
live=liveandview.settings().get('codeintel_live', True)
live=liveandnotlang.lower() in [l.lower() forlinview.settings().get('codeintel_live_disabled_languages', [])]
# if live:
# id = view.id()
# _sentinel = sentinel.get(id)
# sentinel[id] = pos if is_fill_char else (_sentinel if _sentinel is not None else None)
# print sentinel[id]
# live = live and sentinel[id] is not None
iflive:
ifnothasattr(view, 'command_history') or (view.command_history(0)[0] =='insert'andview.command_history(0)[1]['characters'] !=',') or (view.command_history(0)[0] =='insert_snippet'andview.command_history(0)[1]['contents'] =='($0)') or (text=='('andview.command_history(0)[0] =='commit_completion'):
autocomplete(view, 0ifis_fill_charelse200, 50ifis_fill_charelse600, is_fill_char, args=[path, lang])
else:
view.run_command('hide_auto_complete')
else:
def_scan_callback(view, path):
content=view.substr(sublime.Region(0, view.size()))
codeintel_scan(view, path, content, lang)
queue(view, _scan_callback, 3000, args=[path])
defon_selection_modified(self, view):
globaldespair, despaired, old_pos
delay_queue(600) # on movement, delay queue (to make movement responsive)
rowcol=view.rowcol(view.sel()[0].end())
ifold_pos!=rowcol:
id=view.id()
sentinel[id] =None
old_pos=rowcol
despair=1000
despaired=True
status_lock.acquire()
try:
slns= [idforid, slninstatus_lineno.items() ifsln!=rowcol[0]]
finally:
status_lock.release()
foridinslns:
calltip(view, "", id=id)
defon_query_completions(self, view, prefix, locations):
id=view.id()
ifidincompletions:
_completions=completions[id]
delcompletions[id]
return_completions
return []
classCodeIntelAutoComplete(sublime_plugin.TextCommand):
defrun(self, edit, block=False):
view=self.view
path=view.file_name()
lang=guess_lang(view, path)
iflang:
autocomplete(view, 0, 0, True, args=[path, lang])
classGotoPythonDefinition(sublime_plugin.TextCommand):
defrun(self, edit, block=False):
view=self.view
path=view.file_name()
lang=guess_lang(view, path)
iflang:
content=view.substr(sublime.Region(0, view.size()))
pos=view.sel()[0].end()
file_name=view.file_name()
def_trigger(defns):
ifdefnsisnotNone:
defn=defns[0]
ifdefn.nameanddefn.doc:
msg="%s: %s"% (defn.name, defn.doc)
logger(view, 'info', msg, timeout=3000)
ifdefn.pathanddefn.line:
ifdefn.line!=1ordefn.path!=file_name:
path=defn.path+':'+str(defn.line)
msg='Jumping to: %s'%path
log.debug(msg)
codeintel_log.debug(msg)
window=sublime.active_window()
ifwindow.id() notinjump_history_by_window:
jump_history_by_window[window.id()] =collections.deque([], HISTORY_SIZE)
jump_history=jump_history_by_window[window.id()]
# Save current position so we can return to it
row, col=view.rowcol(view.sel()[0].begin())
current_location="%s:%d"% (file_name, row+1)
jump_history.append(current_location)
window.open_file(path, sublime.ENCODED_POSITION)
window.open_file(path, sublime.ENCODED_POSITION)
elifdefn.name:
msg='Cannot find jumping point to: %s'%defn.name
log.debug(msg)
codeintel_log.debug(msg)
codeintel(view, path, content, lang, pos, ('defns',), _trigger)
classBackToPythonDefinition(sublime_plugin.TextCommand):
defrun(self, edit, block=False):
window=sublime.active_window()
ifwindow.id() injump_history_by_window:
jump_history=jump_history_by_window[window.id()]
iflen(jump_history) >0:
previous_location=jump_history.pop()
window=sublime.active_window()
window.open_file(previous_location, sublime.ENCODED_POSITION)
classCodeintelCommand(sublime_plugin.TextCommand):
"""command to interact with codeintel"""
def__init__(self, view):
self.view=view
self.help_called=False
defrun_(self, action):
"""method called by default via view.run_command;
used to dispatch to appropriate method"""
ifnotaction:
return
try:
lc_action=action.lower()
exceptAttributeError:
return
iflc_action=='reset':
self.reset()
eliflc_action=='enable':
self.enable(True)
eliflc_action=='disable':
self.enable(False)
eliflc_action=='on':
self.on_off(True)
eliflc_action=='off':
self.on_off(False)
eliflc_action=='lang-on':
self.on_off(True, guess_lang(self.view, self.view.file_name()))
eliflc_action=='lang-off':
self.on_off(False, guess_lang(self.view, self.view.file_name()))
defreset(self):
"""Restores user settings."""
settings=sublime.load_settings('Base File.sublime-settings')
forattrin ('codeintel', 'codeintel_live', 'codeintel_live_disabled_languages'):