forked from pichillilorenzo/JavaScriptEnhancements
/
_generated_2018_01_26_at_21_58_40.py
6078 lines (4764 loc) · 221 KB
/
_generated_2018_01_26_at_21_58_40.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
import sublime, sublime_plugin
import os, sys, imp, platform, json, traceback, threading, urllib, shutil, re, time
from shutil import copyfile
from threading import Timer
from os import environ
from subprocess import Popen, PIPE
PLUGIN_VERSION = "0.13.17"
PACKAGE_PATH = os.path.abspath(os.path.dirname(__file__))
PACKAGE_NAME = os.path.basename(PACKAGE_PATH)
SUBLIME_PACKAGES_PATH = os.path.dirname(PACKAGE_PATH)
JC_SETTINGS_FOLDER_NAME = "javascript_completions"
JC_SETTINGS_FOLDER = os.path.join(PACKAGE_PATH, "helper", JC_SETTINGS_FOLDER_NAME)
PROJECT_FOLDER_NAME = "project"
PROJECT_FOLDER = os.path.join(PACKAGE_PATH, PROJECT_FOLDER_NAME)
socket_server_list = dict()
HELPER_FOLDER_NAME = "helper"
HELPER_FOLDER = os.path.join(PACKAGE_PATH, HELPER_FOLDER_NAME)
BOOKMARKS_FOLDER = os.path.join(HELPER_FOLDER, 'bookmarks')
WINDOWS_BATCH_FOLDER = os.path.join(PACKAGE_PATH, 'windows_batch')
platform_switcher = {"osx": "OSX", "linux": "Linux", "windows": "Windows"}
os_switcher = {"osx": "darwin", "linux": "linux", "windows": "win"}
PLATFORM = platform_switcher.get(sublime.platform())
PLATFORM_ARCHITECTURE = "64bit" if platform.architecture()[0] == "64bit" else "32bit"
PROJECT_TYPE_SUPPORTED = ['empty', 'angularv1', 'angularv2', 'cordova', 'express', 'ionicv1', 'ionicv2', 'react', 'react-native', 'yeoman']
class Hook(object):
hook_list = {}
@staticmethod
def add (hook_name, hook_func, priority = 10) :
if not hook_name in Hook.hook_list :
Hook.hook_list[hook_name] = []
Hook.hook_list[hook_name].append({
"hook_func": hook_func,
"priority": priority if priority >= 0 else 0
})
Hook.hook_list[hook_name] = sorted(Hook.hook_list[hook_name], key=lambda hook: hook["priority"])
@staticmethod
def apply(hook_name, value='', *args, **kwargs) :
args = (value,) + args
if hook_name in Hook.hook_list :
for hook in Hook.hook_list[hook_name] :
hook["hook_func"](*args, **kwargs)
#value = hook["hook_func"](*args, **kwargs)
#args = (value,) + args[1:]
#return value
@staticmethod
def count(hook_name) :
if hook_name in Hook.hook_list :
return len(Hook.hook_list[hook_name])
return 0
@staticmethod
def removeHook(hook_name, hook_func, priority = -1) :
if hook_name in Hook.hook_list :
if priority >= 0 :
hook = {
"hook_func": hook_func,
"priority": priority
}
while hook in Hook.hook_list[hook_name] :
Hook.hook_list[hook_name].remove(hook)
else :
for hook in Hook.hook_list[hook_name] :
if hook["hook_func"] == hook_func :
Hook.hook_list[hook_name].remove(hook)
@staticmethod
def removeAllHook(hook_name) :
if hook_name in Hook.hook_list :
Hook.hook_list[hook_name] = []
import sublime
class AnimationLoader(object):
def __init__(self, animation, sec, str_before="", str_after=""):
self.animation = animation
self.sec = sec
self.animation_length = len(animation)
self.str_before = str_before
self.str_after = str_after
self.cur_anim = 0
def animate(self):
sublime.active_window().status_message(self.str_before+self.animation[self.cur_anim % self.animation_length]+self.str_after)
self.cur_anim = self.cur_anim + 1
def on_complete(self):
sublime.active_window().status_message("")
from threading import Timer
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.start()
def _run(self):
self.is_running = False
self.start()
self.function(*self.args, **self.kwargs)
def start(self):
if not self.is_running:
self._timer = Timer(self.interval, self._run)
self._timer.start()
self.is_running = True
def stop(self):
self._timer.cancel()
self.is_running = False
import subprocess, threading
import sys, imp, codecs, shlex, os, json, traceback, tempfile
NODE_JS_EXEC = "node"
NPM_EXEC = "npm"
YARN_EXEC = "yarn"
NODE_MODULES_FOLDER_NAME = "node_modules"
NODE_MODULES_PATH = os.path.join(PACKAGE_PATH, NODE_MODULES_FOLDER_NAME)
NODE_MODULES_BIN_PATH = os.path.join(NODE_MODULES_PATH, ".bin")
class NodeJS(object):
def __init__(self, check_local = False):
self.check_local = check_local
self.node_js_path = ""
if self.check_local :
settings = get_project_settings()
if settings :
self.node_js_path = settings["project_settings"]["node_js_custom_path"] or javascriptCompletions.get("node_js_custom_path") or NODE_JS_EXEC
else :
self.node_js_path = javascriptCompletions.get("node_js_custom_path") or NODE_JS_EXEC
else :
self.node_js_path = javascriptCompletions.get("node_js_custom_path") or NODE_JS_EXEC
def eval(self, js, eval_type="eval", strict_mode=False):
js = ("'use strict'; " if strict_mode else "") + js
eval_type = "--eval" if eval_type == "eval" else "--print"
args = [self.node_js_path, eval_type, js]
result = Util.execute(args[0], args[1:])
if result[0] :
return result[1]
raise Exception(result[1])
def getCurrentNodeJSVersion(self) :
args = [self.node_js_path, "-v"]
result = Util.execute(args[0], args[1:])
if result[0] :
return result[1].strip()
raise Exception(result[1])
def execute(self, command, command_args, is_from_bin=False, chdir="", wait_terminate=True, func_stdout=None, args_func_stdout=[], bin_path="", use_node=True) :
if sublime.platform() == 'windows':
if is_from_bin :
args = [os.path.join( (bin_path or NODE_MODULES_BIN_PATH), command+".cmd")] + command_args
else :
args = ([self.node_js_path] if use_node else []) + [os.path.join( (bin_path or NODE_MODULES_BIN_PATH), command)] + command_args
else :
args = ([self.node_js_path] if use_node else []) + [os.path.join( (bin_path or NODE_MODULES_BIN_PATH), command)] + command_args
return Util.execute(args[0], args[1:], chdir=chdir, wait_terminate=wait_terminate, func_stdout=func_stdout, args_func_stdout=args_func_stdout)
def execute_check_output(self, command, command_args, is_from_bin=False, use_fp_temp=False, use_only_filename_view_flow=False, fp_temp_contents="", is_output_json=False, chdir="", clean_output_flow=False, bin_path="", use_node=True) :
fp = None
args = ""
if use_fp_temp :
if sublime.platform() == "windows":
fp = tempfile.NamedTemporaryFile(delete=False)
fp.write(str.encode(fp_temp_contents))
fp.close()
else :
fp = tempfile.NamedTemporaryFile()
fp.write(str.encode(fp_temp_contents))
fp.flush()
command_args_list = list()
for command_arg in command_args :
if command_arg == ":temp_file":
command_arg = fp.name
command_args_list.append(shlex.quote(command_arg) if sublime.platform() != 'windows' else json.dumps(command_arg))
command_args = " ".join(command_args_list)
if sublime.platform() == 'windows':
if is_from_bin :
args = json.dumps(os.path.join((bin_path or NODE_MODULES_BIN_PATH), command)+'.cmd')+' '+command_args+(' < '+json.dumps(fp.name) if fp and not use_only_filename_view_flow else "")
else :
args = ( json.dumps(self.node_js_path)+" " if use_node else "")+json.dumps(os.path.join((bin_path or NODE_MODULES_BIN_PATH), command))+" "+command_args+(" < "+json.dumps(fp.name) if fp and not use_only_filename_view_flow else "")
else:
args = ( shlex.quote(self.node_js_path)+" " if use_node else "")+shlex.quote(os.path.join((bin_path or NODE_MODULES_BIN_PATH), command))+" "+command_args+(" < "+shlex.quote(fp.name) if fp and not use_only_filename_view_flow else "")
#print(args)
old_env = os.environ.copy()
new_env = old_env.copy()
new_env["PATH"] = new_env["PATH"] + javascriptCompletions.get("PATH")
# update the PATH environment variable
os.environ.update(new_env)
try:
output = None
result = None
owd = os.getcwd()
if chdir :
os.chdir(chdir)
output = subprocess.check_output(
args, shell=True, stderr=subprocess.STDOUT, timeout=10
)
if sublime.platform() == "windows" and use_fp_temp:
os.remove(fp.name)
# reset the PATH environment variable
os.environ.update(old_env)
if chdir:
os.chdir(owd)
if clean_output_flow :
out = output.decode("utf-8", "ignore").strip()
out = out.split("\n")
# if len(out) > 1 and out[3:][0].startswith("Started a new flow server: -flow is still initializing; this can take some time. [processing] "):
# out = out[3:]
# out[0] = out[0].replace("Started a new flow server: -flow is still initializing; this can take some time. [processing] ", "")[1:]
# out = "\n".join(out)
# print(out)
# result = json.loads(out) if is_output_json else out
# elif len(out) > 1 and out[3:][0].startswith("Started a new flow server: -flow is still initializing; this can take some time. [merging inference] "):
# out = out[3:]
# out[0] = out[0].replace("Started a new flow server: -flow is still initializing; this can take some time. [merging inference] ", "")[1:]
# out = "\n".join(out)
# result = json.loads(out) if is_output_json else out
# elif len(out) > 1 and out[3:][0].startswith("Started a new flow server: -"):
# out = out[3:]
# out[0] = out[0].replace("Started a new flow server: -", "")
# out = "\n".join(out)
# result = json.loads(out) if is_output_json else out
out = out[-1]
if '{"flowVersion":"' in out :
index = out.index('{"flowVersion":"')
out = out[index:]
result = json.loads(out) if is_output_json else out
else :
return [False, {}]
else :
try:
result = json.loads(output.decode("utf-8", "ignore")) if is_output_json else output.decode("utf-8", "ignore")
except ValueError as e:
print(traceback.format_exc())
print(output.decode("utf-8", "ignore"))
return [False, {}]
if use_fp_temp :
fp.close()
return [True, result]
except subprocess.CalledProcessError as e:
print(traceback.format_exc())
if e.output:
output_error_message = e.output.decode("utf-8", "ignore").strip()
output_error_message = output_error_message.split("\n")
output_error_message = "\n".join(output_error_message[:-2]) if '{"flowVersion":"' in output_error_message[-1] else "\n".join(output_error_message)
print(e.output)
sublime.active_window().status_message(output_error_message)
# reset the PATH environment variable
os.environ.update(old_env)
if sublime.platform() == "windows" and use_fp_temp:
os.remove(fp.name)
try:
result = json.loads(output.decode("utf-8", "ignore")) if is_output_json else output.decode("utf-8", "ignore")
if use_fp_temp :
fp.close()
return [False, result]
except:
#print(traceback.format_exc())
if use_fp_temp :
fp.close()
return [False, None]
except subprocess.TimeoutExpired as e:
# reset the PATH environment variable
os.environ.update(old_env)
#print(traceback.format_exc())
if use_fp_temp :
if sublime.platform() == "windows":
os.remove(fp.name)
else:
fp.close()
return [False, None]
except:
# reset the PATH environment variable
os.environ.update(old_env)
print(traceback.format_exc())
if use_fp_temp :
if sublime.platform() == "windows":
os.remove(fp.name)
else:
fp.close()
return [False, None]
class NPM(object):
def __init__(self, check_local = False):
self.check_local = check_local
self.npm_path = ""
self.yarn_path = ""
self.cli_path = ""
self.node_js_path = ""
if self.check_local :
settings = get_project_settings()
if settings :
self.node_js_path = settings["project_settings"]["node_js_custom_path"] or javascriptCompletions.get("node_js_custom_path") or NODE_JS_EXEC
self.npm_path = settings["project_settings"]["npm_custom_path"] or javascriptCompletions.get("npm_custom_path") or NPM_EXEC
self.yarn_path = settings["project_settings"]["yarn_custom_path"] or javascriptCompletions.get("yarn_custom_path") or YARN_EXEC
if settings["project_settings"]["use_yarn"] and self.yarn_path :
self.cli_path = self.yarn_path
else :
self.cli_path = self.npm_path
else :
self.node_js_path = javascriptCompletions.get("node_js_custom_path") or NODE_JS_EXEC
self.npm_path = javascriptCompletions.get("npm_custom_path") or NPM_EXEC
self.yarn_path = javascriptCompletions.get("yarn_custom_path") or YARN_EXEC
self.cli_path = self.npm_path
else :
self.node_js_path = javascriptCompletions.get("node_js_custom_path") or NODE_JS_EXEC
self.npm_path = javascriptCompletions.get("npm_custom_path") or NPM_EXEC
self.yarn_path = javascriptCompletions.get("yarn_custom_path") or YARN_EXEC
self.cli_path = self.npm_path
def execute(self, command, command_args, chdir="", wait_terminate=True, func_stdout=None, args_func_stdout=[]) :
args = []
if sublime.platform() == 'windows':
args = [self.cli_path, command] + command_args
else :
args = [self.cli_path, command] + command_args
return Util.execute(args[0], args[1:], chdir=chdir, wait_terminate=wait_terminate, func_stdout=func_stdout, args_func_stdout=args_func_stdout)
def install_all(self, save=False, chdir="", wait_terminate=True, func_stdout=None, args_func_stdout=[]) :
return self.execute('install', (["--save"] if save else []), chdir=(PACKAGE_PATH if not chdir else chdir), wait_terminate=wait_terminate, func_stdout=func_stdout, args_func_stdout=args_func_stdout)
def update_all(self, save=False, chdir="", wait_terminate=True, func_stdout=None, args_func_stdout=[]) :
return self.execute('update', (["--save"] if save else []), chdir=(PACKAGE_PATH if not chdir else chdir), wait_terminate=wait_terminate, func_stdout=func_stdout, args_func_stdout=args_func_stdout)
def install(self, package_name, save=False, chdir="", wait_terminate=True, func_stdout=None, args_func_stdout=[]) :
return self.execute('install', (["--save"] if save else []) + [package_name], chdir=(PACKAGE_PATH if not chdir else chdir), wait_terminate=wait_terminate, func_stdout=func_stdout, args_func_stdout=args_func_stdout)
def update(self, package_name, save=False, chdir="", wait_terminate=True, func_stdout=None, args_func_stdout=[]) :
return self.execute('update', (["--save"] if save else []) + [package_name], chdir=(PACKAGE_PATH if not chdir else chdir), wait_terminate=wait_terminate, func_stdout=func_stdout, args_func_stdout=args_func_stdout)
def getPackageJson(self):
package_json_path = ""
settings = get_project_settings()
if self.check_local and settings and os.path.isfile( os.path.join(settings["project_dir_name"], "package.json") ) :
package_json_path = os.path.join(settings["project_dir_name"], "package.json")
elif self.check_local and (not settings or not os.path.isfile( os.path.join(settings["project_dir_name"], "package.json") ) ) :
return None
else :
package_json_path = os.path.join(PACKAGE_PATH, "package.json")
return Util.open_json(package_json_path)
def getCurrentNPMVersion(self) :
if sublime.platform() == 'windows':
args = [self.cli_path, "-v"]
else :
args = [self.cli_path, "-v"]
result = Util.execute(args[0], args[1:])
if result[0] :
return result[1].strip()
raise Exception(result[1])
import sublime, sublime_plugin
import re, urllib, shutil, traceback, threading, time, os, hashlib, json, multiprocessing, shlex
class Util(object) :
multiprocessing_list = []
@staticmethod
def download_and_save(url, where_to_save) :
if where_to_save :
try :
request = urllib.request.Request(url)
request.add_header('User-agent', r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/22.0.1207.1 Safari/537.1')
with urllib.request.urlopen(request) as response :
with open(where_to_save, 'wb+') as out_file :
shutil.copyfileobj(response, out_file)
return True
except Exception as e:
traceback.print_exc()
return False
@staticmethod
def open_json(path):
with open(path) as json_file :
try :
return json.load(json_file)
except Exception as e :
print("Error: "+traceback.format_exc())
return None
@staticmethod
def check_thread_is_alive(thread_name) :
for thread in threading.enumerate() :
if thread.getName() == thread_name and thread.is_alive() :
return True
return False
@staticmethod
def create_and_start_thread(target, thread_name="", args=[], kwargs={}, daemon=True) :
if not Util.check_thread_is_alive(thread_name) :
thread = threading.Thread(target=target, name=thread_name, args=args, kwargs=kwargs, daemon=daemon)
thread.start()
return thread
return None
@staticmethod
def check_process_is_alive(process_name) :
Util.multiprocessing_list
for process in Util.multiprocessing_list :
if process.name == process_name :
if process.is_alive() :
return True
else :
Util.multiprocessing_list.remove(process)
return False
@staticmethod
def create_and_start_process(target, process_name="", args=[], kwargs={}, daemon=True) :
Util.multiprocessing_list
if not Util.check_process_is_alive(process_name) :
process = multiprocessing.Process(target=target, name=process_name, args=args, kwargs=kwargs, daemon=daemon)
process.start()
Util.multiprocessing_list.append(process)
return process
return None
@staticmethod
def setTimeout(time, func):
timer = threading.Timer(time, func)
timer.start()
return timer
@staticmethod
def checksum_sha1(fname):
hash_sha1 = hashlib.sha1()
with open(fname, "rb") as f:
for chunk in iter(lambda: f.read(4096), b""):
hash_sha1.update(chunk)
return hash_sha1.hexdigest()
@staticmethod
def checksum_sha1_equalcompare(fname1, fname2):
return Util.checksum_sha1(fname1) == Util.checksum_sha1(fname2)
@staticmethod
def split_string_and_find(string_to_split, search_value, split_delimiter=" ") :
string_splitted = string_to_split.split(split_delimiter)
return Util.indexOf(string_splitted, search_value)
@staticmethod
def split_string_and_find_on_multiple(string_to_split, search_values, split_delimiter=" ") :
string_splitted = string_to_split.split(split_delimiter)
for search_value in search_values :
index = Util.indexOf(string_splitted, search_value)
if index >= 0 :
return index
return -1
@staticmethod
def split_string_and_findLast(string_to_split, search_value, split_delimiter=" ") :
string_splitted = string_to_split.split(split_delimiter)
return Util.lastIndexOf(string_splitted, search_value)
@staticmethod
def indexOf(list_to_search, search_value) :
index = -1
try :
index = list_to_search.index(search_value)
except Exception as e:
pass
return index
@staticmethod
def lastIndexOf(list_to_search, search_value) :
index = -1
list_to_search_reversed = reversed(list_to_search)
list_length = len(list_to_search)
try :
index = next(i for i,v in zip(range(list_length-1, 0, -1), list_to_search_reversed) if v == search_value)
except Exception as e:
pass
return index
@staticmethod
def firstIndexOfMultiple(list_to_search, search_values) :
index = -1
string = ""
for search_value in search_values :
index_search = Util.indexOf(list_to_search, search_value)
if index_search >= 0 and index == -1 :
index = index_search
string = search_value
elif index_search >= 0 :
index = min(index, index_search)
string = search_value
return {
"index": index,
"string": string
}
@staticmethod
def find_and_get_pre_string_and_first_match(string, search_value) :
result = None
index = Util.indexOf(string, search_value)
if index >= 0 :
result = string[:index+len(search_value)]
return result
@staticmethod
def find_and_get_pre_string_and_matches(string, search_value) :
result = None
index = Util.indexOf(string, search_value)
if index >= 0 :
result = string[:index+len(search_value)]
string = string[index+len(search_value):]
count_occ = string.count(search_value)
i = 0
while i < count_occ :
result += " "+search_value
i = i + 1
return result
@staticmethod
def get_region_scope_first_match(view, scope, selection, selector) :
scope = Util.find_and_get_pre_string_and_first_match(scope, selector)
if scope :
for region in view.find_by_selector(scope) :
if region.contains(selection):
selection.a = region.begin()
selection.b = selection.a
return {
"scope": scope,
"region": region,
"region_string": view.substr(region),
"region_string_stripped": view.substr(region).strip(),
"selection": selection
}
return None
@staticmethod
def get_region_scope_last_match(view, scope, selection, selector) :
scope = Util.find_and_get_pre_string_and_matches(scope, selector)
if scope :
for region in view.find_by_selector(scope) :
if region.contains(selection):
selection.a = region.begin()
selection.b = selection.a
return {
"scope": scope,
"region": region,
"region_string": view.substr(region),
"region_string_stripped": view.substr(region).strip(),
"selection": selection
}
return None
@staticmethod
def find_regions_on_same_depth_level(view, scope, selection, selectors, depth_level, forward) :
scope_splitted = scope.split(" ")
regions = list()
add_unit = 1 if forward else -1
if len(scope_splitted) >= depth_level :
for selector in selectors :
while Util.indexOf(scope_splitted, selector) == -1 :
if selection.a == 0 or len(scope_splitted) < depth_level :
return list()
selection.a = selection.a + add_unit
selection.b = selection.a
scope = view.scope_name(selection.begin()).strip()
scope_splitted = scope.split(" ")
region = view.extract_scope(selection.begin())
regions.append({
"scope": scope,
"region": region,
"region_string": view.substr(region),
"region_string_stripped": view.substr(region).strip(),
"selection": selection
})
return regions
@staticmethod
def get_current_region_scope(view, selection) :
scope = view.scope_name(selection.begin()).strip()
for region in view.find_by_selector(scope) :
if region.contains(selection):
selection.a = region.begin()
selection.b = selection.a
return {
"scope": scope,
"region": region,
"region_string": view.substr(region),
"region_string_stripped": view.substr(region).strip(),
"selection": selection
}
return None
@staticmethod
def get_parent_region_scope(view, selection) :
scope = view.scope_name(selection.begin()).strip()
scope = " ".join(scope.split(" ")[:-1])
for region in view.find_by_selector(scope) :
if region.contains(selection):
selection.a = region.begin()
selection.b = selection.a
return {
"scope": scope,
"region": region,
"region_string": view.substr(region),
"region_string_stripped": view.substr(region).strip(),
"selection": selection
}
return None
@staticmethod
def get_specified_parent_region_scope(view, selection, parent) :
scope = view.scope_name(selection.begin()).strip()
scope = scope.split(" ")
index_parent = Util.lastIndexOf(scope, parent)
scope = " ".join(scope[:index_parent+1])
for region in view.find_by_selector(scope) :
if region.contains(selection):
selection.a = region.begin()
selection.b = selection.a
return {
"scope": scope,
"region": region,
"region_string": view.substr(region),
"region_string_stripped": view.substr(region).strip(),
"selection": selection
}
return None
@staticmethod
def cover_regions(regions) :
first_region = regions[0]
other_regions = regions[1:]
for region in other_regions :
first_region = first_region.cover(region)
return first_region
@staticmethod
def rowcol_to_region(view, row, endrow, col, endcol):
start = view.text_point(row, col)
end = view.text_point(endrow, endcol)
return sublime.Region(start, end)
@staticmethod
def trim_Region(view, region):
new_region = sublime.Region(region.begin(), region.end())
while(view.substr(new_region).startswith(" ") or view.substr(new_region).startswith("\n")):
new_region.a = new_region.a + 1
while(view.substr(new_region).endswith(" ") or view.substr(new_region).startswith("\n")):
new_region.b = new_region.b - 1
return new_region
@staticmethod
def selection_in_js_scope(view, point = -1, except_for = ""):
try :
sel_begin = view.sel()[0].begin() if point == -1 else point
return view.match_selector(
sel_begin,
'source.js ' + except_for
) or view.match_selector(
sel_begin,
'source.js.embedded.html ' + except_for
)
except IndexError as e:
return False
@staticmethod
def replace_with_tab(view, region, pre="", after="", add_to_each_line_before="", add_to_each_line_after="") :
lines = view.substr(region).split("\n")
body = list()
empty_line = 0
for line in lines :
if line.strip() == "" :
empty_line = empty_line + 1
if empty_line == 2 :
empty_line = 1 # leave at least one empty line
continue
else :
empty_line = 0
line = "\t"+add_to_each_line_before+line+add_to_each_line_after
body.append(line)
if body[len(body)-1].strip() == "" :
del body[len(body)-1]
body = "\n".join(body)
return pre+body+after
@staticmethod
def replace_without_tab(view, region, pre="", after="", add_to_each_line_before="", add_to_each_line_after="") :
lines = view.substr(region).split("\n")
body = list()
empty_line = 0
for line in lines :
if line.strip() == "" :
empty_line = empty_line + 1
if empty_line == 2 :
empty_line = 1 # leave at least one empty line
continue
else :
empty_line = 0
body.append(add_to_each_line_before+line+add_to_each_line_after)
if body[len(body)-1].strip() == "" :
del body[len(body)-1]
body = "\n".join(body)
return pre+body+after
@staticmethod
def get_whitespace_from_line_begin(view, region) :
return " " * ( region.begin() - view.line(region).begin() )
@staticmethod
def add_whitespace_indentation(view, region, string, replace="\t", add_whitespace_end=True) :
whitespace = Util.get_whitespace_from_line_begin(view, region)
if replace == "\n" :
lines = string.split("\n")
lines = [whitespace+line for line in lines]
lines[0] = lines[0].lstrip()
string = "\n".join(lines)
return string
if add_whitespace_end :
lines = string.split("\n")
lines[len(lines)-1] = whitespace + lines[-1:][0]
string = "\n".join(lines)
string = re.sub("(["+replace+"]+)", whitespace+r"\1", string)
return string
@staticmethod
def go_to_centered(view, row, col):
while view.is_loading() :
time.sleep(.1)
point = view.text_point(row, col)
view.sel().clear()
view.sel().add(point)
view.show_at_center(point)
@staticmethod
def wait_view(view, fun):
while view.is_loading() :
time.sleep(.1)
fun()
@staticmethod
def move_content_to_parent_folder(path):
for filename in os.listdir(path):
shutil.move(os.path.join(path, filename), os.path.dirname(path))
os.rmdir(path)
@staticmethod
def merge_dicts(*dict_args):
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
@staticmethod
def removeItemIfExists(arr, item):
if item in arr: arr.remove(item)
@staticmethod
def getListItemIfExists(arr, item):
if item in arr :
return item
return None
@staticmethod
def delItemIfExists(obj, key):
try :
del obj[key]
except KeyError as e:
pass
@staticmethod
def getDictItemIfExists(obj, key):
try :
return obj[key]
except KeyError as e:
pass
return None
@staticmethod
def create_and_show_panel(output_panel_name, window = None, syntax=""):
window = sublime.active_window() if not window else window
panel = window.create_output_panel(output_panel_name, False)
panel.set_read_only(True)
if syntax :
panel.set_syntax_file(syntax)
window.run_command("show_panel", {"panel": "output."+output_panel_name})
return panel
@staticmethod
def execute(command, command_args, chdir="", wait_terminate=True, func_stdout=None, args_func_stdout=[]) :
if sublime.platform() == 'windows':
args = [command] + command_args
else :
command_args_list = list()
for command_arg in command_args :
command_args_list.append(shlex.quote(command_arg))
command_args = " ".join(command_args_list)
args = shlex.quote(command)+" "+command_args
#print(args)
if wait_terminate :
env = os.environ.copy()
env["PATH"] = env["PATH"] + javascriptCompletions.get("PATH")
shell = None if sublime.platform() == 'windows' else '/bin/bash'
with subprocess.Popen(args, shell=True, executable=shell, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=(None if not chdir else chdir)) as p:
lines_output = []
lines_error = []
thread_output = Util.create_and_start_thread(Util._wrapper_func_stdout_listen_output, "", (p, None, [], lines_output))
thread_error = Util.create_and_start_thread(Util._wrapper_func_stdout_listen_error, "", (p, None, [], lines_error))
if thread_output:
thread_output.join()
if thread_error:
thread_error.join()
lines = "\n".join(lines_output) + "\n" + "\n".join(lines_error)
return [True if p.wait() == 0 else False, lines]
elif not wait_terminate and func_stdout :
return Util.create_and_start_thread(Util._wrapper_func_stdout, "", (args, func_stdout, args_func_stdout, chdir))
@staticmethod
def _wrapper_func_stdout(args, func_stdout, args_func_stdout=[], chdir=""):
env = os.environ.copy()
env["PATH"] = env["PATH"] + javascriptCompletions.get("PATH")
shell = None if sublime.platform() == 'windows' else '/bin/bash'
with subprocess.Popen(args, shell=True, executable=shell, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, preexec_fn=os.setsid, cwd=(None if not chdir else chdir)) as p:
func_stdout(None, p, *args_func_stdout)
thread_output = Util.create_and_start_thread(Util._wrapper_func_stdout_listen_output, "", (p, func_stdout, args_func_stdout))
thread_error = Util.create_and_start_thread(Util._wrapper_func_stdout_listen_error, "", (p, func_stdout, args_func_stdout))
if thread_output:
thread_output.join()
if thread_error:
thread_error.join()
if p.wait() == 0:
func_stdout("OUTPUT-SUCCESS", p, *args_func_stdout)
else :
func_stdout("OUTPUT-ERROR", p, *args_func_stdout)
func_stdout("OUTPUT-DONE", p, *args_func_stdout)
@staticmethod
def _wrapper_func_stdout_listen_output(process, func_stdout=None, args_func_stdout=[], lines_output=[]):
char = b""
line = b""
while True :
char = process.stdout.read(1)
if not char :
break
if not char.endswith(b'\n') :
line = line + char
else :
line = line + char
line = codecs.decode(line, "utf-8", "ignore").strip()
line = re.sub(r'\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))', '', line)
line = re.sub(r'[\n\r]', '\n', line)
lines_output.append(line)
line = line + ( b"\n" if type(line) is bytes else "\n" )
if func_stdout :
func_stdout(line, process, *args_func_stdout)
line = b""
char = b""
@staticmethod
def _wrapper_func_stdout_listen_error(process, func_stdout=None, args_func_stdout=[], lines_error=[]):
char = b""
line = b""
while True :
char = process.stderr.read(1)
if not char :
break
if not char.endswith(b'\n') :
line = line + char
else :
line = line + char
line = codecs.decode(line, "utf-8", "ignore").strip()
line = re.sub(r'\x1b(\[.*?[@-~]|\].*?(\x07|\x1b\\))', '', line)
line = re.sub(r'[\n\r]', '\n', line)
lines_error.append(line)
line = line + ( b"\n" if type(line) is bytes else "\n" )
if func_stdout :
func_stdout(line, process, *args_func_stdout)
line = b""
char = b""
@staticmethod
def nested_lookup(key, values, document, wild=False):
"""Lookup a key in a nested document, return a list of values"""
return list(Util._nested_lookup(key, values, document, wild=wild))
@staticmethod
def _nested_lookup(key, values, document, wild=False):
"""Lookup a key in a nested document, yield a value"""