-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
AmxxEditor.py
2050 lines (1544 loc) · 70.1 KB
/
AmxxEditor.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
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
#
# Licensing
#
# Copyright (C) 2013-2016 ppalex7 <https://github.com/ppalex7/SourcePawnCompletions>
# Copyright (C) 2016-2017 AMXX-Editor by Destro <https://forums.alliedmods.net/showthread.php?t=284385>
# Copyright (C) 2017-2018 Evandro Coan <https://github.com/evandrocoan/AmxxEditor>
#
# Redistributions of source code must retain the above
# copyright notice, this list of conditions and the
# following disclaimer.
#
# Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials
# provided with the distribution.
#
# Neither the name Evandro Coan nor the names of any
# contributors may be used to endorse or promote products
# derived from this software without specific prior written
# permission.
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the
# Free Software Foundation; either version 3 of the License, or ( at
# your option ) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import os
import re
import sys
import sublime
import sublime_plugin
import webbrowser
import time
import threading
from io import StringIO
from functools import wraps
from collections import deque
from xml.etree import ElementTree
sys.path.append(os.path.dirname(__file__))
from enum34 import Enum
import watchdog.events
import watchdog.observers
import watchdog.utils
from watchdog.utils.bricks import OrderedSetQueue
# Enable editor debug messages: (bitwise)
#
# 0 - Disabled debugging.
# 1 - Errors messages.
# 2 - Outputs when it starts a file parsing.
# 4 - General messages.
# 8 - Analyzer parser.
# 16 - Autocomplete debugging.
# 32 - Function parsing debugging.
# 63 - All debugging levels at the same time.
from debug_tools import getLogger
from debug_tools.utilities import wrap_text
log = getLogger( 1, __name__ )
# log = getLogger( 1, __name__, file="amxxeditor.txt", mode='w' )
EDITOR_VERSION = "3.0_zz"
CURRENT_PACKAGE_NAME = __package__
g_is_package_loading = True
class FUNC_TYPES(Enum):
function = 0
public = 1
stock = 2
forward = 3
native = 4
define = 5
# print( FUNC_TYPES(0) )
g_constants_list = set()
g_inteltip_style = ""
g_enable_inteltip = False
g_enable_inteltip_calls = False
g_enable_inteltip_name = False
g_enable_buildversion = False
g_delay_time = 1.0
g_include_dir = set()
g_add_paremeters = False
g_new_file_syntax = "Packages/%s/%sPawn.sublime-syntax" % (CURRENT_PACKAGE_NAME, CURRENT_PACKAGE_NAME)
g_word_autocomplete = False
g_function_autocomplete = False
g_enable_inteltip_color = "inteltip.pawn"
g_processing_set_queue = OrderedSetQueue()
g_processing_set_queue_set = set()
g_nodes = dict()
g_file_observer = watchdog.observers.Observer()
includes_regex = re.compile('^[\\s]*#include[\\s]+[<"]([^>"]+)[>"]', re.MULTILINE)
local_regex = re.compile('\\.(sma|inc)$')
function_regex = re.compile(r'(?:\s*\[.*\]\s*)?[\w_\d: ]*[\w_\d]\(')
function_return_regex = re.compile(r'(.+:\[.*\]|.+:)\s*(.+)')
function_return_array_regex = re.compile(r'(\[.*\])(.+)')
new_line_regex = re.compile(r'\n')
space_clean_regex = re.compile(r'\t+| +')
amxx_build_ver_regex = re.compile("(.*\"(?:v)?\\d{1,2}\\.\\d{1,2}\\.(?:\\d{1,2}-)?)(\\d+)(b(?:eta)?)?\"")
sort_nicely_regex = re.compile('([0-9]+)')
is_valid_name_regex = re.compile('^[\\w_]+$')
add_constant_regex = re.compile('(\\w*)')
parse_define_regex = re.compile(r'#define[\s]+([^\s]+)[\s]+((?:\\\n|.)+)')
has_define_next_line_regex = re.compile(r'[^\\]*(?:\\)+')
def plugin_unloaded():
global g_is_package_loading
g_is_package_loading=True
settings = sublime.load_settings("%s.sublime-settings" % CURRENT_PACKAGE_NAME)
settings.clear_on_change(CURRENT_PACKAGE_NAME)
log.delete()
def plugin_loaded():
threading.Thread(target=_plugin_loaded).start()
threading.Thread(target=force_popup_to_show_first).start()
def force_popup_to_show_first():
""" API to handle popups with predefined priorities to avoid popup fighting
https://github.com/sublimehq/sublime_text/issues/2079 """
if '_is_force_popup_to_show_first' not in globals():
global _is_force_popup_to_show_first
_is_force_popup_to_show_first = True
time.sleep(10)
sublime_plugin.reload_plugin( "AmxxEditor.AmxxEditor" )
def _plugin_loaded():
settings = sublime.load_settings("%s.sublime-settings" % CURRENT_PACKAGE_NAME)
install_build_systens("AmxxEditor.sh")
install_build_systens("AmxxEditor.bat")
install_setting_file("%s.sublime-settings" % CURRENT_PACKAGE_NAME)
install_setting_file("AmxxEditorConsole.sublime-settings")
# Fixes the settings dialog showing up when installing the package for the first time
global g_is_package_loading
g_is_package_loading=True
sublime.set_timeout( unlock_is_package_loading, 10000 )
_on_settings_modified()
settings.add_on_change(CURRENT_PACKAGE_NAME, on_settings_modified)
def unlock_is_package_loading():
global g_is_package_loading
g_is_package_loading = False
def install_build_systens(target_file_name):
target_folder = CURRENT_PACKAGE_NAME
target_file = os.path.join( sublime.packages_path(), "User", target_folder, target_file_name )
input_file_string = sublime.load_resource( "Packages/%s/%s" % ( CURRENT_PACKAGE_NAME, target_file_name ) )
target_directory = os.path.join( sublime.packages_path(), "User", target_folder )
attempt_to_install_file( target_directory, target_file, input_file_string )
def install_setting_file( target_file_name ):
target_file = os.path.join( sublime.packages_path(), "User", target_file_name )
input_file_string = sublime.load_resource( "Packages/%s/%s" % ( CURRENT_PACKAGE_NAME, target_file_name ) )
target_directory = os.path.join( sublime.packages_path(), "User" )
attempt_to_install_file( target_directory, target_file, input_file_string )
def attempt_to_install_file( target_directory, target_file, input_file_string ):
if not os.path.exists( target_directory ):
os.makedirs( target_directory )
# How can I force Python's file.write() to use the same newline format in Windows as in Linux (“\r\n” vs. “\n”)?
# https://stackoverflow.com/questions/9184107/how-can-i-force-pythons-file-write-to-use-the-same-newline-format-in-windows
#
# TypeError: 'str' does not support the buffer interface
# https://stackoverflow.com/questions/5471158/typeerror-str-does-not-support-the-buffer-interface
if not os.path.exists( target_file ):
text_file = open( target_file, "wb" )
text_file.write( bytes(input_file_string, 'UTF-8') )
text_file.close()
def unload_handler() :
g_file_observer.stop()
process_thread.stop()
g_processing_set_queue.put(("", ""))
sublime.load_settings("%s.sublime-settings" % CURRENT_PACKAGE_NAME).clear_on_change(CURRENT_PACKAGE_NAME)
class NewAmxxIncludeCommand(sublime_plugin.WindowCommand):
def run(self):
new_file("inc")
class NewAmxxPluginCommand(sublime_plugin.WindowCommand):
def run(self):
new_file("sma")
def new_file(file_type):
view = sublime.active_window().new_file()
view.set_name("untitled."+file_type)
plugin_template = sublime.load_resource("Packages/%s/default.%s" % (CURRENT_PACKAGE_NAME, file_type))
plugin_template = plugin_template.replace("\r", "")
view.run_command("insert_snippet", {"contents": plugin_template})
sublime.set_timeout_async( lambda: set_new_file_syntax( view ), 0 )
def set_new_file_syntax( view ):
view.set_syntax_file(g_new_file_syntax)
# https://stackoverflow.com/questions/2865250/python-textwrap-forcing-hard-breaks
def hard_wrap(text, width, indent=' '):
for line in StringIO(text):
indent_width = width - len(indent)
yield line[:width]
line = line[width:]
while line:
yield '\n' + indent + line[:indent_width]
line = line[indent_width:]
class AboutAmxxEditorCommand(sublime_plugin.WindowCommand):
def run(self):
about = "Sublime AmxxEditor v"+ EDITOR_VERSION +" by Destro\n\n\n"
about += "CREDITs:\n"
about += "- Great:\n"
about += " ppalex7 (SourcePawn Completions)\n\n"
about += "- Contributors:\n"
about += " sasske (white color scheme)\n"
about += " addons_zz (npp color scheme)\n"
about += " KliPPy (build version)\n"
about += " Mistrick (mistrick color scheme)\n"
about += "\nhttps://amxmodx-es.com/showthread.php?tid=12316\n"
sublime.message_dialog(about)
class AmxxBuildVerCommand(sublime_plugin.TextCommand):
def run(self, edit):
region = self.view.find("^#define\s+(?:PLUGIN_)?VERSION\s+\".+\"", 0, sublime.IGNORECASE)
if region == None :
region = self.view.find("new\s+const\s+(?:PLUGIN_)?VERSION\s*\[\s*\]\s*=\s*\".+\"", 0, sublime.IGNORECASE)
if region == None :
return
line = self.view.substr(region)
result = amxx_build_ver_regex.match(line)
if not result :
return
build = int(result.group(2))
build += 1
beta = result.group(3)
if not beta :
beta = ""
self.view.replace(edit, region, result.group(1) + str(build) + beta + '\"')
class AmxxEditor(sublime_plugin.EventListener):
def __init__(self) :
process_thread.start()
self.delay_queue = None
g_file_observer.start()
def on_window_command(self, window, cmd, args) :
if cmd != "build" :
return
view = window.active_view()
if not is_amxmodx_file(view) or not g_enable_buildversion :
return
view.run_command("amxx_build_ver")
def on_hover(self, view, location, hover_zone):
if hover_zone != sublime.HOVER_TEXT:
return
if not is_amxmodx_file(view) or not g_enable_inteltip :
return
region = view.word(location)
begin = region.begin()
# log('location', location, region, view.substr(region))
region = sublime.Region(begin, begin)
html, location, word_region, scope = self.is_valid_location(view, region)
if not html:
return
self.show_popup(view, html, location, word_region)
def show_popup(self, view, html, location, word_region):
def on_hide_hover():
view.add_regions("inteltip", [ ])
view.show_popup(
html,
flags=sublime.HIDE_ON_MOUSE_MOVE_AWAY,
location=location,
max_width=700,
on_navigate=self.on_navigate,
on_hide=on_hide_hover
)
if g_enable_inteltip_color:
view.add_regions("inteltip", [ word_region ], g_enable_inteltip_color)
def is_valid_location(self, view, region):
scope = view.scope_name(region.begin())
# log(1, "scope_name: [%s]" % scope)
if ( not "support.function" in scope and not "include_path.pawn" in scope ) \
or region.size() > 1 :
return None, None, None, None
try:
if "include_path.pawn" in scope :
html, location, word_region = self.inteltip_include(view, region)
else :
html, location, word_region = self.inteltip_function(view, region)
except Exception as error:
log(1, "Exception: %s" % error)
return None, None, None, None
return html, location, word_region, scope
def on_selection_modified(self, view) :
if not is_amxmodx_file(view):
return
if not g_enable_inteltip:
return
region = view.sel()[0]
html, location, word_region, scope = self.is_valid_location(view, region)
if not html or ( not g_enable_inteltip_calls and not g_enable_inteltip_name ):
view.erase_phantoms("AmxxEditor")
return
if g_enable_inteltip_name:
if not "keyword.brackets.paren.begin" in scope and not "support.function.call.pawn" in scope:
if "function.call.paren" in scope:
view.erase_phantoms("AmxxEditor")
return
if g_enable_inteltip_calls:
self.show_phantom(view, html, location, word_region)
else:
self.show_popup(view, html, location, word_region)
def show_phantom(self, view, html, location, word_region):
view.erase_phantoms("AmxxEditor")
row, col = view.rowcol(word_region.begin())
if col > 80:
new_begin = view.text_point(row, 80)
word_region = sublime.Region(new_begin, new_begin)
view.add_phantom(
"AmxxEditor",
word_region,
html.replace("margin: -5px;", "margin: +5px; height: 125px; overflow: scroll;"),
sublime.LAYOUT_BELOW,
self.on_navigate,
)
def inteltip_function(self, view, region) :
file_name = view.file_name()
if not file_name:
return None, None, None
word_region = view.word(region)
search_func = view.substr(word_region)
doctset = dict()
visited = set()
found = None
node = g_nodes.get(file_name, Node(view.file_name()))
self.generate_doctset_recur(node, doctset, visited)
found = doctset.get(search_func)
location = word_region.end()
actual_parameter = -1
# log('search_func', search_func)
if not found:
scope = view.scope_name(region.begin())
if "function.call.paren" in scope:
counter = 100
actual_parameter += 1
while counter > 0 and not found:
counter -= 1
begin = word_region.begin() - 1;
word_region = view.word(begin)
search_func = view.substr(word_region)
scope = view.scope_name(word_region.begin())
# log('search_func', search_func)
if search_func.strip() == ',':
actual_parameter += 1
if "function.call" not in scope:
break
elif "function.call.paren" in scope:
continue
else:
found = doctset.get(search_func)
if found:
parameters = simple_escape(found.parameters)
filename = os.path.basename(found.file_name)
log(4, "param2: [%s] '%s'", parameters, filename)
if found.function_type :
if found.return_type :
link_local = found.file_name + '#' + FUNC_TYPES(found.function_type).name + ' ' + found.return_type + ':' + found.function_name
else :
link_local = found.file_name + '#' + FUNC_TYPES(found.function_type).name + ' ' + found.function_name
link_web = filename.rsplit('.', 1)[0] + '#' + found.function_name
else :
link_local = found.file_name + '#' + '^' + found.function_name
link_web = ''
log( 4, "link_local: %s", link_local )
html = '<style>'+ g_inteltip_style + '</style>'
html += '<div class="top">' ############################## TOP
html += '<a class="file" href="' + link_local + '\\(">' + os.path.basename(found.file_name) + '</a>'
if link_web:
html += ' | <a class="file" href="' + link_web + '">WebAPI</a>'
html += '</div><div class="bottom">' ############################## BOTTOM
html += '<span class="func_type">' + FUNC_TYPES(found.function_type).name \
+':</span> <span class="func_name">' + found.function_name + '</span>'
if found.return_type :
html += '<span class="file"> -> </span>'
html += '<span class="return">Return:</span> <span class="return_type">' + found.return_type + '</span>'
html += '<br>'
html += '<span class="params">Params:</span> '
html += '<span class="params_definition">'
# log('actual_parameter', actual_parameter, 'parameters', parameters)
if actual_parameter != -1 and parameters:
parameters = parameters.split(",")
if actual_parameter < len( parameters ):
parameters[actual_parameter] = '<span class="file">' + parameters[actual_parameter] + '</span>'
html += ", ".join(parameters)
else:
html += parameters
html += '</span>'
html += '<br>'
html += '</div>' ############################## END
html += '<div class="file" style="margin-top: 7px;">'
html += html_newline( wrap_text( found.doc_comment, wrap=100 ) )
html += '</div>'
# log( 1, "html: %s", html )
return html, location, word_region
return None, None, None
def on_navigate(self, link) :
(file, search) = link.split('#')
if "." in file :
view = sublime.active_window().open_file(file);
def do_position() :
if view.is_loading():
sublime.set_timeout(do_position, 100)
else :
r=view.find(search, 0, sublime.IGNORECASE)
view.sel().clear()
view.sel().add(r)
view.show(r)
do_position()
else :
webbrowser.open_new_tab("http://www.amxmodx.org/api/"+file+"/"+search)
def inteltip_include(self, view, region) :
word_region = view.word(region)
location = word_region.end() + 1
text = view.substr(view.line(region))
include = includes_regex.match(text).group(1)
file_name_view = view.file_name()
if file_name_view is None:
return None, None, None
else:
( file_name, the_include_exists ) = get_file_name( file_name_view, include )
if not the_include_exists :
return None, None, None
link_local = file_name + '#'
if not '.' in include :
link_web = include + '#'
include += ".inc"
else :
link_web = None
html = '<style>'+ g_inteltip_style +'</style>'
html += '<div class="top">'
html += '<a class="file" href="'+link_local+'">'+include+'</a>'
if link_web :
html += ' | <a class="file" href="'+link_web+'">WebAPI</a>'
html += '</div><div class="bottom">'
html += '<span class="func_type">Location:</span><br>'
html += '<span class="func_name">'
html += html_newline( simple_escape( "".join( hard_wrap( file_name, 80, '' ) ) ) )
html += '</span>'
html += '</div>'
return html, location, word_region
def on_activated_async(self, view) :
view_size = view.size()
log(4, "")
log(4, "view.match_selector(0, 'source.sma'): " + str( view.match_selector(0, 'source.sma') ))
# log(4, "g_nodes:", g_nodes)
log(4, "view.substr(): \n", view.substr( sublime.Region( 0, view_size if view_size < 200 else 200 ) ))
if not is_amxmodx_file(view):
log(4, "returning on` if not is_amxmodx_file(view)")
return
if not view.file_name() in g_nodes :
log(4, "returning on` if not view.file_name() in g_nodes")
add_to_queue(view)
def on_modified_async(self, view) :
self.add_to_queue_delayed(view)
def on_post_save_async(self, view) :
self.add_to_queue_now(view)
def on_load_async(self, view) :
self.add_to_queue_now(view)
def add_to_queue_now(self, view) :
if not is_amxmodx_file(view):
return
add_to_queue(view)
def add_to_queue_delayed(self, view) :
if not is_amxmodx_file(view):
return
if self.delay_queue is not None :
self.delay_queue.cancel()
if g_delay_time > 0.3:
self.delay_queue = threading.Timer( float( g_delay_time ), add_to_queue_forward, [ view ] )
self.delay_queue.start()
def on_query_completions(self, view, prefix, locations):
"""
This is a forward called by Sublime Text when it is about to show the use completions.
See: https://www.sublimetext.com/docs/3/api_reference.html#sublime_plugin.ViewEventListener
"""
view_file_name = view.file_name()
if is_amxmodx_file(view):
# # # Autocompletion issue
# # # https://github.com/evandrocoan/AmxxEditor/issues/9
# # temporarily masking word_separators
# # https://github.com/SublimeTextIssues/Core/issues/819
# word_separators = view.settings().get("word_separators")
# view.settings().set("word_separators", "")
# sublime.set_timeout(lambda: view.settings().set("word_separators", word_separators), 0)
if view_file_name is None:
view_file_name = str( view.buffer_id() )
# Just in case it is not processed yet
if not view_file_name in g_nodes:
log(4, "Adding buffer id", view_file_name, " in g_nodes")
add_to_queue_forward( view )
# The queue is not processed yet, so there is nothing to show
if g_word_autocomplete:
log( 16, "(new buffer) Word autocomplete")
return None
else:
log( 16, "(new buffer) Without word autocomplete")
return ( [], sublime.INHIBIT_WORD_COMPLETIONS )
if g_word_autocomplete:
log( 16, "(Buffer) Word autocomplete + function")
return self.generate_funcset( view_file_name, view, prefix, locations )
else:
log( 16, "(Buffer) Without word autocomplete + function")
return ( self.generate_funcset( view_file_name, view, prefix, locations ), sublime.INHIBIT_WORD_COMPLETIONS )
else:
if g_word_autocomplete:
log( 16, "(File) Word autocomplete + function")
return self.generate_funcset( view_file_name, view, prefix, locations )
else:
log( 16, "(File) Without word autocomplete + function")
return ( self.generate_funcset( view_file_name, view, prefix, locations ), sublime.INHIBIT_WORD_COMPLETIONS )
log( 16, "No completions")
return None
def generate_funcset( self, file_name, view, prefix, locations ) :
words_list = []
funcs_list = []
funcs_word_list = []
if file_name in g_nodes:
node = g_nodes[file_name]
visited = set()
if not view.match_selector(locations[0], 'string') :
self.generate_funcset_recur( node, visited, funcs_list, funcs_word_list )
if g_word_autocomplete:
start_time = time.time()
if len( locations ) > 0:
view_words = view.extract_completions( prefix, locations[0] )
else:
view_words = view.extract_completions( prefix )
# This view goes first to prioritize matches close to cursor position.
for word in view_words:
# Remove the annoying `(` on the string
word = word.replace('$', '\\$').split('(')[0]
if word not in funcs_word_list:
words_list.append( ( word, word ) )
if time.time() - start_time > 0.05:
break
# log( 16, "( generate_funcset ) funcs_list size: %d" % len( funcs_list ) )
# log( 16, "( generate_funcset ) funcs_list items: " + str( sort_nicely( funcs_list ) ) )
return words_list + funcs_list
def generate_funcset_recur( self, node, visited, funcs_list, funcs_word_list ) :
if node in visited :
return
visited.add( node )
for child in node.children :
self.generate_funcset_recur( child, visited, funcs_list, funcs_word_list )
funcs_list.extend( node.funcs_list )
funcs_word_list.extend( node.words_list )
def generate_doctset_recur(self, node, doctset, visited) :
if node in visited :
return
visited.add(node)
for child in node.children :
self.generate_doctset_recur(child, doctset, visited)
doctset.update(node.doct)
def is_amxmodx_file(view) :
return view.match_selector(0, 'source.sma')
def check_color_scope_setting():
""" https://stackoverflow.com/questions/45734287/list-of-colors-for-highlightwords-sublime-plugin """
global g_enable_inteltip_color
found_scope = False
active_window = sublime.active_window()
settings = active_window.active_view().settings()
try:
color_scheme = settings.get("color_scheme")
xml_file = sublime.load_resource(color_scheme)
xml_tree = ElementTree.fromstring(xml_file)
xml_subtree = xml_tree.find("./dict/array")
if xml_subtree is None:
print("No color scheme xml_subtree found")
return
for child in xml_subtree:
for i in range(0, len(child), 2):
if child[i].tag == "key" and child[i].text == "scope":
if g_enable_inteltip_color in child[i + 1].text:
found_scope = True
if not found_scope:
g_enable_inteltip_color = ""
except Exception as error:
print("Error loading color scheme", error)
def on_settings_modified():
threading.Thread(target=_on_settings_modified).start()
def _on_settings_modified():
log(4, "")
global g_enable_inteltip
global g_enable_inteltip_calls
global g_enable_inteltip_name
global g_enable_inteltip_color
global g_new_file_syntax
global g_word_autocomplete
global g_function_autocomplete
settings = sublime.load_settings("%s.sublime-settings" % CURRENT_PACKAGE_NAME)
invalid = is_invalid_settings(settings)
if invalid:
if not g_is_package_loading:
sublime.message_dialog("AmxxEditor:\n\n" + invalid)
g_enable_inteltip = False
g_enable_inteltip_calls = False
g_enable_inteltip_name = False
return
# check package path
packages_path = os.path.join( sublime.packages_path(), CURRENT_PACKAGE_NAME )
if not os.path.isdir(packages_path) :
os.mkdir(packages_path)
# fix-path
fix_path(settings, 'include_directory')
# Get the set color scheme
popup_color_scheme = settings.get('popup_color_scheme')
# popUp.CSS
global g_inteltip_style
g_inteltip_style = sublime.load_resource("Packages/%s/%s-popup.css" % (CURRENT_PACKAGE_NAME, popup_color_scheme))
g_inteltip_style = g_inteltip_style.replace("\r", "") # fix win/linux newlines
# cache setting
global g_enable_buildversion, g_delay_time, g_add_paremeters
g_enable_inteltip = settings.get('enable_inteltip', True)
g_enable_inteltip_calls = settings.get('enable_inteltip_calls', True)
g_enable_inteltip_name = settings.get('enable_inteltip_name', False)
g_enable_inteltip_color = settings.get('enable_inteltip_color', "inteltip.pawn")
g_enable_buildversion = settings.get('enable_buildversion', False)
g_word_autocomplete = settings.get('word_autocomplete', False)
g_function_autocomplete = settings.get('function_autocomplete', False)
g_new_file_syntax = settings.get('amxx_file_syntax', g_new_file_syntax)
log.debug_level = settings.get('debug_level', 1)
g_delay_time = settings.get('live_refresh_delay', 1.0)
g_add_paremeters = settings.get('add_function_parameters', False)
check_color_scope_setting()
g_include_dir.clear()
include_directory = settings.get('include_directory', './include')
if isinstance( include_directory, list ):
for path in include_directory:
real_path = os.path.realpath( path )
if os.path.isdir( real_path ): g_include_dir.add( real_path )
else:
real_path = os.path.realpath( include_directory )
if os.path.isdir( real_path ): g_include_dir.add( real_path )
g_file_observer.unschedule_all()
log(4, "debug_level: %d", log.debug_level)
log(4, "g_include_dir: %s", g_include_dir)
log(4, "g_add_paremeters: %s", g_add_paremeters)
for directory in g_include_dir:
g_file_observer.schedule( file_event_handler, directory, True )
for window in sublime.windows():
for view in window.views():
view.erase_phantoms("AmxxEditor")
def is_invalid_settings(settings):
general_error = "You are not set correctly settings for AmxxEditor.\n\n"
setting_names = [ "include_directory", "popup_color_scheme", "amxx_file_syntax" ]
for setting_name in setting_names:
result = general_settings_checker( settings, setting_name, general_error )
if result:
return result
path_prefix = ""
setting_name = "include_directory"
default_value = "F:\\SteamCMD\\steamapps\\common\\Half-Life\\czero\\addons\\amxmodx\\scripting\\include"
checker = lambda file_path: os.path.exists( file_path )
result = path_settings_checker( settings, setting_name, default_value, path_prefix, checker )
if result:
return result
path_prefix = os.path.dirname( sublime.packages_path() )
setting_name = "amxx_file_syntax"
default_value = g_new_file_syntax
checker = lambda file_path: os.path.exists( file_path ) or is_inside_sublime_package( file_path )
result = path_settings_checker( settings, setting_name, default_value, path_prefix, checker )
if result:
return result
def general_settings_checker(settings, setting_name, general_error):
setting_value = settings.get( setting_name )
if setting_value is None:
return general_error + "Missing `%s` value." % setting_name
def path_settings_checker(settings, setting_name, default_value, prefix_path, checker):
setting_value = settings.get( setting_name )
if setting_value != default_value:
full_path = os.path.normpath( os.path.join( prefix_path, setting_value ) )
if not checker( full_path ):
lines = \
[
"The setting `%s` is not configured correctly. The following path does not exists:\n\n" % setting_name,
"%s (%s)" % (setting_value, full_path),
"\n\nPlease, go to the following menu and fix the setting:\n\n"
"`AmxxEditor -> Configure AMXX-Autocompletion Settings`\n\n",
"`Preferences -> Packages Settings -> AmxxEditor -> Configure AMXX-Autocompletion Settings`",
]
text = "".join( lines )
print( "\n" + text.replace( "\n\n", "\n" ) )
return text
def is_inside_sublime_package(file_path):
try:
packages_start = file_path.find( "Packages" )
packages_relative_path = file_path[packages_start:].replace( "\\", "/" )
# log( 1, "is_inside_sublime_package, packages_relative_path: " + str( packages_relative_path ) )
sublime.load_binary_resource( packages_relative_path )
return True
except IOError:
return False
def fix_path(settings, key) :
org_path = settings.get(key)
if org_path is "${file_path}" :
return
path = os.path.normpath(org_path)
if os.path.isdir(path):
path += '/'
settings.set(key, path)
def sort_nicely( words_set ):
"""
Sort the given iterable in the way that humans expect.
"""
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in sort_nicely_regex.split(key[0]) ]
return sorted( words_set, key = alphanum_key )
def add_to_queue_forward(view) :
if g_delay_time > 0.3:
sublime.set_timeout_async( lambda: add_to_queue( view ), float( g_delay_time ) * 1000.0 )
def add_to_queue(view) :
"""
The view can only be accessed from the main thread, so run the regex
now and process the results later
"""
log( 4, "( add_to_queue ) view.file_name(): %s", view.file_name() )
# When the view is not saved, we need to use its buffer id, instead of its file name.
view_file_name = view.file_name()
if view_file_name is None :
view_file_name = str( view.buffer_id() )
if view_file_name not in g_processing_set_queue_set:
g_processing_set_queue_set.add( view_file_name )
g_processing_set_queue.put( ( view_file_name, view.substr( sublime.Region( 0, view.size() ) ) ) )
include_directory = os.path.realpath( os.path.join( os.path.dirname( view_file_name ), "include" ) )
if include_directory not in g_include_dir:
if os.path.isdir( include_directory ):
g_include_dir.add( include_directory )
g_file_observer.schedule( file_event_handler, include_directory, True )
def add_include_to_queue(file_name) :
if file_name not in g_processing_set_queue_set:
g_processing_set_queue_set.add( file_name )
g_processing_set_queue.put((file_name, None))
class IncludeFileEventHandler(watchdog.events.FileSystemEventHandler) :
def __init__(self) :
watchdog.events.FileSystemEventHandler.__init__(self)
def on_created(self, event) :
sublime.set_timeout(lambda: on_modified_main_thread(event.src_path), 0)
def on_modified(self, event) :
sublime.set_timeout(lambda: on_modified_main_thread(event.src_path), 0)
def on_deleted(self, event) :
sublime.set_timeout(lambda: on_deleted_main_thread(event.src_path), 0)
def on_modified_main_thread(file_path) :
if not is_active(file_path) :
add_include_to_queue(file_path)
def on_deleted_main_thread(file_path) :
if is_active(file_path) :
return
node = g_nodes.get(file_path)
if node is None :
return
node.remove_all_children_and_funcs()