forked from quarnster/SublimeClang
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sublimeclang.py
546 lines (456 loc) · 21.3 KB
/
sublimeclang.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
"""
Copyright (c) 2011-2012 Fredrik Ehnbom
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
"""
try:
import sublime
import ctypes
except:
sublime.error_message("""\
Unfortunately ctypes can't be imported, so SublimeClang will not work.
There is a work around for this to get it to work, \
please see http://www.github.com/quarnster/SublimeClang for more details. """)
import os
import sys
try:
import Queue
from internals.clang import cindex
from errormarkers import clear_error_marks, add_error_mark, show_error_marks, \
update_statusbar, erase_error_marks, clang_error_panel
from internals.common import get_setting, get_settings, is_supported_language, \
get_language,get_cpu_count, run_in_main_thread, \
status_message, sencode, are_we_there_yet, plugin_loaded
from internals import translationunitcache
from internals.parsehelp import parsehelp
plugin_loaded()
except ImportError:
import queue as Queue
from .internals.clang import cindex
from .errormarkers import clear_error_marks, add_error_mark, show_error_marks, \
update_statusbar, erase_error_marks, clang_error_panel
from .internals.common import get_setting, get_settings, is_supported_language, \
get_language,get_cpu_count, run_in_main_thread, \
status_message, sencode, are_we_there_yet, plugin_loaded
from .internals import translationunitcache
from .internals.parsehelp import parsehelp
import sublime_plugin
from sublime import Region
import sublime
import re
import threading
import time
import traceback
def warm_up_cache(view, filename=None):
if filename == None:
filename = sencode(view.file_name())
stat = translationunitcache.tuCache.get_status(filename)
if stat == translationunitcache.TranslationUnitCache.STATUS_NOT_IN_CACHE:
translationunitcache.tuCache.add(view, filename)
return stat
def get_translation_unit(view, filename=None, blocking=False):
if filename == None:
filename = sencode(view.file_name())
if get_setting("warm_up_in_separate_thread", True, view) and not blocking:
stat = warm_up_cache(view, filename)
if stat == translationunitcache.TranslationUnitCache.STATUS_NOT_IN_CACHE:
return None
elif stat == translationunitcache.TranslationUnitCache.STATUS_PARSING:
sublime.status_message("Hold your horses, cache still warming up")
return None
return translationunitcache.tuCache.get_translation_unit(filename, translationunitcache.tuCache.get_opts(view), translationunitcache.tuCache.get_opts_script(view))
navigation_stack = []
clang_complete_enabled = True
clang_fast_completions = True
class ClangTogglePanel(sublime_plugin.WindowCommand):
def run(self, **args):
show = args["show"] if "show" in args else None
aview = sublime.active_window().active_view()
error_marks = get_setting("error_marks_on_panel_only", False, aview)
if show or (show == None and not clang_error_panel.is_visible(self.window)):
clang_error_panel.open(self.window)
if error_marks:
show_error_marks(aview)
else:
clang_error_panel.close()
if error_marks:
erase_error_marks(aview)
class ClangToggleCompleteEnabled(sublime_plugin.TextCommand):
def run(self, edit):
global clang_complete_enabled
clang_complete_enabled = not clang_complete_enabled
sublime.status_message("Clang complete is %s" % ("On" if clang_complete_enabled else "Off"))
class ClangToggleFastCompletions(sublime_plugin.TextCommand):
def run(self, edit):
global clang_fast_completions
clang_fast_completions = not clang_fast_completions
sublime.status_message("Clang fast completions are %s" % ("On" if clang_fast_completions else "Off"))
class ClangWarmupCache(sublime_plugin.TextCommand):
def run(self, edit):
stat = warm_up_cache(self.view)
if stat == translationunitcache.TranslationUnitCache.STATUS_PARSING:
sublime.status_message("Cache is already warming up")
elif stat != translationunitcache.TranslationUnitCache.STATUS_NOT_IN_CACHE:
sublime.status_message("Cache is already warmed up")
class ClangGoBackEventListener(sublime_plugin.EventListener):
def on_close(self, view):
if not get_setting("pop_on_close", True, view):
return
# If the view we just closed was last in the navigation_stack,
# consider it "popped" from the stack
fn = view.file_name()
if fn == None:
return
fn = sencode(fn)
while True:
if len(navigation_stack) == 0 or \
not navigation_stack[
len(navigation_stack) - 1][1].startswith(fn):
break
navigation_stack.pop()
class ClangGoBack(sublime_plugin.TextCommand):
def run(self, edit):
if len(navigation_stack) > 0:
self.view.window().open_file(
navigation_stack.pop()[0], sublime.ENCODED_POSITION)
def is_enabled(self):
return is_supported_language(sublime.active_window().active_view()) and len(navigation_stack) > 0
def is_visible(self):
return is_supported_language(sublime.active_window().active_view())
def format_current_file(view):
row, col = view.rowcol(view.sel()[0].a)
return "%s:%d:%d" % (sencode(view.file_name()), row + 1, col + 1)
def open(view, target):
navigation_stack.append((format_current_file(view), target))
view.window().open_file(target, sublime.ENCODED_POSITION)
class ClangGotoBase(sublime_plugin.TextCommand):
def get_target(self, tu, data, offset, found_callback, folders):
pass
def found_callback(self, target):
if target == None:
sublime.status_message("Don't know where the %s is!" % self.goto_type)
elif not isinstance(target, list):
open(self.view, target)
else:
self.targets = target
self.view.window().show_quick_panel(target, self.open_file)
def open_file(self, idx):
if idx >= 0:
target = self.targets[idx]
if isinstance(target, list):
target = target[1]
open(self.view, target)
def run(self, edit):
view = self.view
tu = get_translation_unit(view)
if tu == None:
return
offset = view.sel()[0].a
data = view.substr(sublime.Region(0, view.size()))
self.get_target(tu, data, offset, self.found_callback, self.view.window().folders())
def is_enabled(self):
return is_supported_language(sublime.active_window().active_view())
def is_visible(self):
return is_supported_language(sublime.active_window().active_view())
class ClangGotoImplementation(ClangGotoBase):
def get_target(self, tu, data, offset, found_callback, folders):
self.goto_type = "implementation"
return tu.get_implementation(data, offset, found_callback, folders)
class ClangGotoDef(ClangGotoBase):
def get_target(self, tu, data, offset, found_callback, folders):
self.goto_type = "definition"
return tu.get_definition(data, offset, found_callback, folders)
class ClangClearCache(sublime_plugin.TextCommand):
def run(self, edit):
translationunitcache.tuCache.clear()
sublime.status_message("Cache cleared!")
class ClangReparse(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
unsaved_files = []
if view.is_dirty():
unsaved_files.append((sencode(view.file_name()),
view.substr(Region(0, view.size()))))
translationunitcache.tuCache.reparse(view, sencode(view.file_name()), unsaved_files)
def ignore_diagnostic(path, ignoreDirs):
normalized_path = os.path.abspath(os.path.normpath(os.path.normcase(path)))
for d in ignoreDirs:
if normalized_path.startswith(d):
return True
return False
def display_compilation_results(view):
tu = get_translation_unit(view)
errString = ""
show = False
clear_error_marks() # clear visual error marks
erase_error_marks(view)
if tu == None:
return
if not tu.try_lock():
return
try:
errorCount = 0
warningCount = 0
ignoreDirs = [os.path.abspath(os.path.normpath(os.path.normcase(d))) for d in get_setting("diagnostic_ignore_dirs", [], view)]
ignore_regex_str = get_setting("diagnostic_ignore_regex", "pragma once in main file")
if ignore_regex_str:
ignore_regex = re.compile(ignore_regex_str)
else:
ignore_regex = None
if len(tu.var.diagnostics):
errString = ""
for diag in tu.var.diagnostics:
f = diag.location
filename = ""
if f.file != None:
filename = f.file.name
if ignore_diagnostic(filename, ignoreDirs):
continue
err = "%s:%d,%d - %s - %s" % (filename, f.line, f.column,
diag.severityName,
diag.spelling)
if ignore_regex and ignore_regex.search(err):
continue
try:
if len(diag.disable_option) > 0:
err = "%s [Disable with %s]" % (err, diag.disable_option)
except AttributeError:
pass
if diag.severity == cindex.Diagnostic.Fatal and \
"not found" in diag.spelling:
err = "%s\nDid you configure the include path used by clang properly?\n" \
"See http://github.com/quarnster/SublimeClang for more details on "\
"how to configure SublimeClang." % (err)
errString = "%s%s\n" % (errString, err)
if diag.severity == cindex.Diagnostic.Warning:
warningCount += 1
elif diag.severity >= cindex.Diagnostic.Error:
errorCount += 1
"""
for range in diag.ranges:
errString = "%s%s\n" % (errString, range)
for fix in diag.fixits:
errString = "%s%s\n" % (errString, fix)
"""
add_error_mark(
diag.severityName, filename, f.line - 1, diag.spelling)
show = errString and get_setting("show_output_panel", True, view)
finally:
tu.unlock()
if (errorCount > 0 or warningCount > 0) and get_setting("show_status", True, view):
statusString = "Clang Status: "
if errorCount > 0:
statusString = "%s%d Error%s" % (statusString, errorCount, "s" if errorCount != 1 else "")
if warningCount > 0:
statusString = "%s%s%d Warning%s" % (statusString, ", " if errorCount > 0 else "",
warningCount, "s" if warningCount != 1 else "")
view.set_status("SublimeClang", statusString)
else:
view.erase_status("SublimeClang")
window = view.window()
clang_error_panel.set_data(errString)
update_statusbar(view)
if not get_setting("error_marks_on_panel_only", False, view):
show_error_marks(view)
if not window is None:
if show:
window.run_command("clang_toggle_panel", {"show": True})
elif get_setting("hide_output_when_empty", False, view):
if clang_error_panel.is_visible():
window.run_command("clang_toggle_panel", {"show": False})
member_regex = re.compile(r"(([a-zA-Z_]+[0-9_]*)|([\)\]])+)((\.)|(->))$")
def is_member_completion(view, caret):
line = view.substr(Region(view.line(caret).a, caret))
if member_regex.search(line) != None:
return True
elif get_language(view).startswith("objc"):
return re.search(r"\[[\.\->\s\w\]]+\s+$", line) != None
return False
class ClangComplete(sublime_plugin.TextCommand):
def run(self, edit, characters):
regions = [a for a in self.view.sel()]
self.view.sel().clear()
for region in reversed(regions):
pos = 0
region.end() + len(characters)
if region.size() > 0:
self.view.replace(edit, region, characters)
pos = region.begin() + len(characters)
else:
self.view.insert(edit, region.end(), characters)
pos = region.end() + len(characters)
self.view.sel().add(sublime.Region(pos, pos))
caret = self.view.sel()[0].begin()
line = self.view.substr(sublime.Region(self.view.word(caret-1).a, caret))
if is_member_completion(self.view, caret) or line.endswith("::") or re.search("(^|\W)new\s+\w*$", line):
self.view.run_command("hide_auto_complete")
sublime.set_timeout(self.delayed_complete, 1)
def delayed_complete(self):
self.view.run_command("auto_complete")
class SublimeClangAutoComplete(sublime_plugin.EventListener):
def __init__(self):
s = get_settings()
s.clear_on_change("options")
s.add_on_change("options", self.load_settings)
are_we_there_yet(lambda: self.load_settings())
self.recompile_timer = None
self.not_code_regex = re.compile("(string.)|(comment.)")
def load_settings(self):
translationunitcache.tuCache.clear()
self.dont_complete_startswith = get_setting("dont_complete_startswith",
['operator', '~'])
self.recompile_delay = get_setting("recompile_delay", 1000)
self.cache_on_load = get_setting("cache_on_load", True)
self.remove_on_close = get_setting("remove_on_close", True)
self.time_completions = get_setting("time_completions", False)
def is_member_kind(self, kind):
return kind == cindex.CursorKind.CXX_METHOD or \
kind == cindex.CursorKind.FIELD_DECL or \
kind == cindex.CursorKind.OBJC_PROPERTY_DECL or \
kind == cindex.CursorKind.OBJC_CLASS_METHOD_DECL or \
kind == cindex.CursorKind.OBJC_INSTANCE_METHOD_DECL or \
kind == cindex.CursorKind.OBJC_IVAR_DECL or \
kind == cindex.CursorKind.FUNCTION_TEMPLATE or \
kind == cindex.CursorKind.NOT_IMPLEMENTED
def return_completions(self, comp, view):
if get_setting("inhibit_sublime_completions", True, view):
return (comp, sublime.INHIBIT_WORD_COMPLETIONS | sublime.INHIBIT_EXPLICIT_COMPLETIONS)
return comp
def on_query_completions(self, view, prefix, locations):
global clang_complete_enabled
if not is_supported_language(view) or not clang_complete_enabled or \
not view.match_selector(locations[0], '-string -comment -constant'):
return []
line = view.substr(sublime.Region(view.line(locations[0]).begin(), locations[0]))
match = re.search(r"[,\s]*(\w+)\s+\w+$", line)
if match != None:
valid = ["new", "delete", "return", "goto", "case", "const", "static", "class", "struct", "typedef", "union"]
if match.group(1) not in valid:
# Probably a variable or function declaration
# There's no point in trying to complete
# a name that hasn't been typed yet...
return self.return_completions([], view)
timing = ""
tot = 0
start = time.time()
tu = get_translation_unit(view)
if tu == None:
return self.return_completions([], view)
ret = None
tu.lock()
try:
if self.time_completions:
curr = (time.time() - start)*1000
tot += curr
timing += "TU: %f" % (curr)
start = time.time()
cached_results = None
if clang_fast_completions and get_setting("enable_fast_completions", True, view):
data = view.substr(sublime.Region(0, locations[0]))
try:
cached_results = tu.cache.complete(data, prefix)
except:
traceback.print_exc()
if cached_results != None:
# print("found fast completions")
ret = cached_results
else:
# print("doing slow completions")
row, col = view.rowcol(locations[0] - len(prefix))
unsaved_files = []
if view.is_dirty():
unsaved_files.append((sencode(view.file_name()),
view.substr(Region(0, view.size()))))
ret = tu.cache.clangcomplete(sencode(view.file_name()), row+1, col+1, unsaved_files, is_member_completion(view, locations[0] - len(prefix)))
if self.time_completions:
curr = (time.time() - start)*1000
tot += curr
timing += ", Comp: %f" % (curr)
start = time.time()
if len(self.dont_complete_startswith) and ret:
i = 0
while i < len(ret):
disp = ret[i][0]
pop = False
for comp in self.dont_complete_startswith:
if disp.startswith(comp):
pop = True
break
if pop:
ret.pop(i)
else:
i += 1
if self.time_completions:
curr = (time.time() - start)*1000
tot += curr
timing += ", Filter: %f" % (curr)
timing += ", Tot: %f ms" % (tot)
print(timing)
sublime.status_message(timing)
finally:
tu.unlock()
if not ret is None:
return self.return_completions(ret, view)
return self.return_completions([], view)
def reparse_done(self):
display_compilation_results(self.view)
def restart_recompile_timer(self, timeout):
if self.recompile_timer != None:
self.recompile_timer.cancel()
self.recompile_timer = threading.Timer(timeout, sublime.set_timeout,
[self.recompile, 0])
self.recompile_timer.start()
def recompile(self):
view = self.view
unsaved_files = []
if view.is_dirty() and get_setting("reparse_use_dirty_buffer", False, view):
unsaved_files.append((sencode(view.file_name()),
view.substr(Region(0, view.size()))))
if not translationunitcache.tuCache.reparse(view, sencode(view.file_name()), unsaved_files,
self.reparse_done):
# Already parsing so retry in a bit
self.restart_recompile_timer(1)
def on_activated(self, view):
if is_supported_language(view) and get_setting("reparse_on_activated", True, view):
self.view = view
self.restart_recompile_timer(0.1)
def on_post_save(self, view):
if is_supported_language(view) and get_setting("reparse_on_save", True, view):
self.view = view
self.restart_recompile_timer(0.1)
def on_modified(self, view):
if (self.recompile_delay <= 0) or not is_supported_language(view):
return
self.view = view
self.restart_recompile_timer(self.recompile_delay / 1000.0)
def on_load(self, view):
if self.cache_on_load and is_supported_language(view):
warm_up_cache(view)
def on_close(self, view):
if self.remove_on_close and is_supported_language(view):
translationunitcache.tuCache.remove(sencode(view.file_name()))
def on_query_context(self, view, key, operator, operand, match_all):
if key == "clang_supported_language":
if view == None:
view = sublime.active_window().active_view()
return is_supported_language(view)
elif key == "clang_is_code":
return self.not_code_regex.search(view.scope_name(view.sel()[0].begin())) == None
elif key == "clang_complete_enabled":
return clang_complete_enabled
elif key == "clang_automatic_completion_popup":
return get_setting("automatic_completion_popup", True, view)
elif key == "clang_panel_visible":
return clang_error_panel.is_visible()