forked from clemos/haxe-sublime-bundle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HaxeComplete.py
1387 lines (1064 loc) · 35.3 KB
/
HaxeComplete.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 sys
#sys.path.append("/usr/lib/python2.6/")
#sys.path.append("/usr/lib/python2.6/lib-dynload")
import sublime, sublime_plugin
import subprocess
import tempfile
import os
#import xml.parsers.expat
import re
import codecs
import glob
import hashlib
import shutil
from xml.etree import ElementTree
from xml.etree.ElementTree import XMLTreeBuilder
#from xml.etree import ElementTree
from elementtree import SimpleXMLTreeBuilder # part of your codebase
ElementTree.XMLTreeBuilder = SimpleXMLTreeBuilder.TreeBuilder
from subprocess import Popen, PIPE
from datetime import datetime
try:
STARTUP_INFO = subprocess.STARTUPINFO()
STARTUP_INFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
STARTUP_INFO.wShowWindow = subprocess.SW_HIDE
except (AttributeError):
STARTUP_INFO = None
def runcmd( args, input=None ):
try:
p = Popen(args, stdout=PIPE, stderr=PIPE, stdin=PIPE, startupinfo=STARTUP_INFO)
if isinstance(input, unicode):
input = input.encode('utf-8')
out, err = p.communicate(input=input)
return (out.decode('utf-8') if out else '', err.decode('utf-8') if err else '')
except (OSError, ValueError) as e:
err = u'Error while running %s: %s' % (args[0], e)
return ("", err)
compilerOutput = re.compile("^([^:]+):([0-9]+): characters? ([0-9]+)-?([0-9]+)? : (.*)", re.M)
compactFunc = re.compile("\(.*\)")
compactProp = re.compile(":.*\.([a-z_0-9]+)", re.I)
spaceChars = re.compile("\s")
wordChars = re.compile("[a-z0-9._]", re.I)
importLine = re.compile("^([ \t]*)import\s+([a-z0-9._]+);", re.I | re.M)
packageLine = re.compile("package\s*([a-z0-9.]*);", re.I)
libLine = re.compile("([^:]*):[^\[]*\[(dev\:)?(.*)\]")
classpathLine = re.compile("Classpath : (.*)")
typeDecl = re.compile("(class|typedef|enum)\s+([A-Z][a-zA-Z0-9_]*)(<[a-zA-Z0-9_,]+>)?" , re.M )
libFlag = re.compile("-lib\s+(.*?)")
skippable = re.compile("^[a-zA-Z0-9_\s]*$")
inAnonymous = re.compile("[{,]\s*([a-zA-Z0-9_\"\']+)\s*:\s*$" , re.M | re.U )
comments = re.compile( "/\*(.*)\*/" , re.M )
extractTag = re.compile("<([a-z0-9_-]+).*\s(name|main)=\"([a-z0-9_./-]+)\"", re.I)
variables = re.compile("var\s+([^:;\s]*)", re.I)
functions = re.compile("function\s+([^;\.\(\)\s]*)", re.I)
functionParams = re.compile("function\s+[a-zA-Z0-9_]+\s*\(([^\)]*)", re.M)
paramDefault = re.compile("(=\s*\"*[^\"]*\")", re.M)
serverPort = 6000
haxeVersion = re.compile("haxe_([0-9]{3})",re.M)
class HaxeLib :
available = {}
basePath = None
def __init__( self , name , dev , version ):
self.name = name
self.dev = dev
self.version = version
self.classes = None
self.packages = None
if self.dev :
self.path = self.version
self.version = "dev"
else :
self.path = os.path.join( HaxeLib.basePath , self.name , ",".join(self.version.split(".")) )
#print(self.name + " => " + self.path)
def extract_types( self ):
if self.dev is True or ( self.classes is None and self.packages is None ):
self.classes, self.packages = HaxeComplete.inst.extract_types( self.path )
return self.classes, self.packages
@staticmethod
def get( name ) :
if( name in HaxeLib.available.keys()):
return HaxeLib.available[name]
else :
sublime.status_message( "Haxelib : "+ name +" project not installed" )
return None
@staticmethod
def get_completions() :
comps = []
for l in HaxeLib.available :
lib = HaxeLib.available[l]
comps.append( ( lib.name + " [" + lib.version + "]" , lib.name ) )
return comps
@staticmethod
def scan() :
hlout, hlerr = runcmd( ["haxelib" , "config" ] )
HaxeLib.basePath = hlout.strip()
HaxeLib.available = {}
hlout, hlerr = runcmd( ["haxelib" , "list" ] )
for l in hlout.split("\n") :
found = libLine.match( l )
if found is not None :
name, dev, version = found.groups()
lib = HaxeLib( name , dev is not None , version )
HaxeLib.available[ name ] = lib
HaxeLib.scan()
inst = None
class HaxeBuild :
#auto = None
targets = ["js","cpp","swf","swf9","neko","php"]
nme_targets = ["flash","html5","cpp","ios -simulator","android","webos"]
nme_target = "flash"
def __init__(self) :
self.args = []
self.main = None
self.target = None
self.output = "dummy.js"
self.hxml = None
self.nmml = None
self.classpaths = []
self.libs = []
def to_string(self) :
out = os.path.basename(self.output)
if self.nmml is not None:
return "{out} ({target})".format(self=self, out=out, target=HaxeBuild.nme_target);
else:
return "{out}".format(self=self, out=out);
#return "{self.main} {self.target}:{out}".format(self=self, out=out);
def make_hxml( self ) :
outp = "# Autogenerated "+self.hxml+"\n\n"
outp += "# "+self.to_string() + "\n"
outp += "-main "+ self.main + "\n"
for a in self.args :
outp += " ".join( list(a) ) + "\n"
d = os.path.dirname( self.hxml ) + "/"
# relative paths
outp = outp.replace( d , "")
outp = outp.replace( "-cp "+os.path.dirname( self.hxml )+"\n", "")
outp = outp.replace("--no-output " , "")
outp = outp.replace("-v" , "")
outp = outp.replace("dummy" , self.main.lower() )
#print( outp )
return outp.strip()
def get_types( self ) :
classes = []
packs = []
cp = []
cp.extend( self.classpaths )
for lib in self.libs :
if lib is not None :
cp.append( lib.path )
#print("extract types :")
#print(cp)
for path in cp :
c, p = HaxeComplete.inst.extract_types( path )
classes.extend( c )
packs.extend( p )
classes.sort()
packs.sort()
return classes, packs
class HaxeInstallLib( sublime_plugin.WindowCommand ):
def run(self):
out,err = runcmd(["haxelib" , "search" , " "]);
libs = out.splitlines()
self.libs = libs[0:-1]
menu = []
for l in self.libs :
if l in HaxeLib.available :
menu.append( [ l + " [" + HaxeLib.available[l].version + "]" , "Remove" ] )
else :
menu.append( [ l , 'Install' ] )
menu.append( ["Upgrade libraries"] )
self.window.show_quick_panel(menu,self.install)
def install( self, i ):
if i < 0 :
return
if i == len(self.libs) :
cmd = ["haxelib" , "upgrade" ]
else :
lib = self.libs[i]
if lib in HaxeLib.available :
cmd = ["haxelib" , "remove" , lib ]
else :
cmd = ["haxelib" , "install" , lib ]
out,err = runcmd(cmd)
lines = out.splitlines()
lines.append( "" )
panel = self.window.get_output_panel("haxelib")
edit = panel.begin_edit()
panel.insert(edit, panel.size(), "\n".join(lines) )
panel.end_edit( edit )
self.window.run_command("show_panel",{"panel":"output.haxelib"})
HaxeLib.scan()
class HaxeGenerateImport( sublime_plugin.TextCommand ):
start = None
size = None
cname = None
def get_end( self, src, offset ) :
end = len(src)
while offset < end:
c = src[offset]
offset += 1
if not wordChars.match(c): break
return offset - 1
def get_start( self, src, offset ) :
foundWord = 0
offset -= 1
while offset > 0:
c = src[offset]
offset -= 1
if foundWord == 0:
if spaceChars.match(c): continue
foundWord = 1
if not wordChars.match(c): break
return offset + 2
def is_membername( self, token ) :
return token[0] >= "Z" or token == token.upper()
def is_module( self , token ) :
return re.search("[\.^][A-Z]+", token);
def get_classname( self, view, src ) :
loc = view.sel()[0]
end = max(loc.a, loc.b)
self.size = loc.size()
if self.size == 0:
end = self.get_end(src, end)
self.start = self.get_start(src, end)
self.size = end - self.start
else:
self.start = end - self.size
self.cname = view.substr(sublime.Region(self.start, end)).rpartition(".")
#print(self.cname)
while (not self.cname[0] == "" and self.is_membername(self.cname[2])):
self.size -= 1 + len(self.cname[2])
self.cname = self.cname[0].rpartition(".")
def compact_classname( self, edit, view ) :
view.replace(edit, sublime.Region(self.start, self.start+self.size), self.cname[2])
view.sel().clear()
loc = self.start + len(self.cname[2])
view.sel().add(sublime.Region(loc, loc))
def get_indent( self, src, index ) :
if src[index] == "\n": return index + 1
return index
def insert_import( self, edit, view, src) :
cname = "".join(self.cname)
clow = cname.lower()
last = None
for imp in importLine.finditer(src):
if clow < imp.group(2).lower():
ins = "{0}import {1};\n".format(imp.group(1), cname)
view.insert(edit, self.get_indent(src, imp.start(0)), ins)
return
last = imp
if not last is None:
ins = ";\n{0}import {1}".format(last.group(1), cname)
view.insert(edit, last.end(2), ins)
else:
pkg = packageLine.search(src)
if not pkg is None:
ins = "\n\nimport {0};".format(cname)
view.insert(edit, pkg.end(0), ins)
else:
ins = "import {0};\n\n".format(cname)
view.insert(edit, 0, ins)
def run( self , edit ) :
complete = HaxeComplete.inst
view = self.view
src = view.substr(sublime.Region(0, view.size()))
self.get_classname(view, src)
if self.cname[1] == "":
sublime.status_message("Nothing to import")
return
self.compact_classname(edit, view)
if re.search("import\s+{0};".format("".join(self.cname)), src):
sublime.status_message("Already imported")
return
self.insert_import(edit, view, src)
class HaxeDisplayCompletion( sublime_plugin.TextCommand ):
def run( self , edit ) :
#print("completing")
view = self.view
s = view.settings();
view.run_command( "auto_complete" , {
"api_completions_only" : True,
"disable_auto_insert" : True,
"next_completion_if_showing" : False
} )
class HaxeInsertCompletion( sublime_plugin.TextCommand ):
def run( self , edit ) :
#print("insert completion")
view = self.view
view.run_command( "insert_best_completion" , {
"default" : ".",
"exact" : True
} )
class HaxeSaveAllAndBuild( sublime_plugin.TextCommand ):
def run( self , edit ) :
complete = HaxeComplete.inst
view = self.view
view.window().run_command("save_all")
complete.run_build( view )
class HaxeRunBuild( sublime_plugin.TextCommand ):
def run( self , edit ) :
complete = HaxeComplete.inst
view = self.view
complete.run_build( view )
class HaxeSelectBuild( sublime_plugin.TextCommand ):
def run( self , edit ) :
complete = HaxeComplete.inst
view = self.view
complete.select_build( view )
class HaxeHint( sublime_plugin.TextCommand ):
def run( self , edit ) :
#print("haxe hint")
complete = HaxeComplete.inst
view = self.view
sel = view.sel()
for r in sel :
comps = complete.get_haxe_completions( self.view , r.end() )
#print(status);
#view.set_status("haxe-status", status)
#sublime.status_message(status)
#if( len(comps) > 0 ) :
# view.run_command('auto_complete', {'disable_auto_insert': True})
class HaxeComplete( sublime_plugin.EventListener ):
#folder = ""
#buildArgs = []
currentBuild = None
selectingBuild = False
builds = []
errors = []
currentCompletion = {
"inp" : None,
"outp" : None
}
stdPaths = []
stdPackages = []
#stdClasses = ["Void","Float","Int","UInt","Null","Bool","Dynamic","Iterator","Iterable","ArrayAccess"]
stdClasses = []
stdCompletes = []
panel = None
serverMode = False
serverStarted = False
def __init__(self):
#print("init haxecomplete")
HaxeComplete.inst = self
out, err = runcmd( ["haxe", "-main", "Nothing", "-v", "--no-output"] )
m = classpathLine.match(out)
if m is not None :
HaxeComplete.stdPaths = set(m.group(1).split(";")) - set([".","./"])
for p in HaxeComplete.stdPaths :
#print("std path : "+p)
if len(p) > 1 and os.path.exists(p) and os.path.isdir(p):
classes, packs = self.extract_types( p )
HaxeComplete.stdClasses.extend( classes )
HaxeComplete.stdPackages.extend( packs )
ver = re.search( haxeVersion , out )
if ver is not None :
self.serverMode = int(ver.group(1)) >= 209
def extract_types( self , path , depth = 0 ) :
classes = []
packs = []
hasClasses = False
for fullpath in glob.glob( os.path.join(path,"*.hx") ) :
f = os.path.basename(fullpath)
cl, ext = os.path.splitext( f )
if cl not in HaxeComplete.stdClasses:
s = open( os.path.join( path , f ) , "r" )
src = s.read() #comments.sub( s.read() , "" )
clPack = "";
for ps in packageLine.findall( src ) :
clPack = ps
if clPack == "" :
packDepth = 0
else:
packDepth = len(clPack.split("."))
for decl in typeDecl.findall( src ):
t = decl[1]
if( packDepth == depth ) : # and t == cl or cl == "StdTypes"
if t == cl or cl == "StdTypes":
classes.append( t )
else:
classes.append( cl + "." + t )
hasClasses = True
if hasClasses or depth == 0 :
for f in os.listdir( path ) :
cl, ext = os.path.splitext( f )
if os.path.isdir( os.path.join( path , f ) ) and f not in HaxeComplete.stdPackages :
packs.append( f )
subclasses,subpacks = self.extract_types( os.path.join( path , f ) , depth + 1 )
for cl in subclasses :
classes.append( f + "." + cl )
classes.sort()
packs.sort()
return classes, packs
def highlight_errors( self , view ) :
fn = view.file_name()
regions = []
for e in self.errors :
if e["file"] == fn :
l = e["line"]
left = e["from"]
right = e["to"]
a = view.text_point(l,left)
b = view.text_point(l,right)
regions.append( sublime.Region(a,b))
view.set_status("haxe-status" , "Error: " + e["message"] )
view.add_regions("haxe-error" , regions , "invalid" , "dot" )
def on_load( self, view ) :
scopes = view.scope_name(view.sel()[0].end()).split()
#sublime.status_message( scopes[0] )
if 'source.haxe.2' not in scopes and 'source.hxml' not in scopes:
return []
self.generate_build(view)
self.highlight_errors( view )
def on_post_save( self , view ) :
scopes = view.scope_name(view.sel()[0].end()).split()
#sublime.status_message( scopes[0] )
if 'source.hxml' in scopes:
self.clear_build(view)
def on_activated( self , view ) :
scopes = view.scope_name(view.sel()[0].end()).split()
#sublime.status_message( scopes[0] )
if 'source.haxe.2' not in scopes and 'source.hxml' not in scopes:
return []
if 'source.haxe.2' in scopes :
self.get_build(view)
self.extract_build_args( view )
self.generate_build(view)
self.highlight_errors( view )
def __on_modified( self , view ):
win = sublime.active_window()
if win is None :
return None
isOk = ( win.active_view().buffer_id() == view.buffer_id() )
if not isOk :
return None
sel = view.sel()
caret = 0
for s in sel :
caret = s.a
if caret == 0 :
return None
if view.score_selector(caret,"source.haxe") == 0 or view.score_selector(caret,"string") > 0 or view.score_selector(caret,"comment") :
return None
src = view.substr(sublime.Region(0, view.size()))
ch = src[caret-1]
#print(ch)
if ch not in ".(:, " :
#print("here")
view.run_command("haxe_display_completion")
#else :
# view.run_command("haxe_insert_completion")
def generate_build(self, view) :
fn = view.file_name()
if self.currentBuild is not None and fn == self.currentBuild.hxml and view.size() == 0 :
e = view.begin_edit()
hxmlSrc = self.currentBuild.make_hxml()
view.insert(e,0,hxmlSrc)
view.end_edit(e)
def select_build( self , view ) :
self.extract_build_args( view , True )
def find_nmml( self, folder ) :
nmmls = glob.glob( os.path.join( folder , "*.nmml" ) )
for build in nmmls:
currentBuild = HaxeBuild()
currentBuild.hxml = build
currentBuild.nmml = build
buildPath = os.path.dirname(build)
# TODO delegate compiler options extractions to NME 3.2:
# runcmd("nme diplay project.nmml nme_target")
outp = "NME"
f = open( build , "r+" )
while 1:
l = f.readline()
if not l :
break;
m = extractTag.search(l)
if not m is None:
#print(m.groups())
tag = m.group(1)
name = m.group(3)
if (tag == "app"):
currentBuild.main = name
mFile = re.search("\\b(file|title)=\"([a-z0-9_-]+)\"", l, re.I)
if not mFile is None:
outp = mFile.group(2)
elif (tag == "haxelib"):
currentBuild.libs.append( HaxeLib.get( name ) )
currentBuild.args.append( ("-lib" , name) )
elif (tag == "classpath"):
currentBuild.classpaths.append( os.path.join( buildPath , name ) )
currentBuild.args.append( ("-cp" , os.path.join( buildPath , name ) ) )
else: # NME 3.2
mPath = re.search("\\bpath=\"([a-z0-9_-]+)\"", l, re.I)
if not mPath is None:
#print(mPath.groups())
path = mPath.group(1)
currentBuild.classpaths.append( os.path.join( buildPath , path ) )
currentBuild.args.append( ("-cp" , os.path.join( buildPath , path ) ) )
outp = os.path.join( folder , outp )
currentBuild.target = "cpp"
currentBuild.args.append( ("--remap", "flash:nme") )
currentBuild.args.append( ("-cpp", outp) )
currentBuild.output = outp
if currentBuild.main is not None :
self.builds.append( currentBuild )
def find_hxml( self, folder ) :
hxmls = glob.glob( os.path.join( folder , "*.hxml" ) )
for build in hxmls:
currentBuild = HaxeBuild()
currentBuild.hxml = build
buildPath = os.path.dirname(build);
# print("build file exists")
f = open( build , "r+" )
while 1:
l = f.readline()
if not l :
break;
if l.startswith("--next") :
self.builds.append( currentBuild )
currentBuild = HaxeBuild()
currentBuild.hxml = build
l = l.strip()
if l.startswith("-main") :
spl = l.split(" ")
if len( spl ) == 2 :
currentBuild.main = spl[1]
else :
sublime.status_message( "Invalid build.hxml : no Main class" )
if l.startswith("-lib") :
spl = l.split(" ")
if len( spl ) == 2 :
lib = HaxeLib.get( spl[1] )
currentBuild.libs.append( lib )
else :
sublime.status_message( "Invalid build.hxml : lib not found" )
if l.startswith("-cmd") :
spl = l.split(" ")
currentBuild.args.append( ( "-cmd" , " ".join(spl[1:]) ) )
for flag in [ "lib" , "D" , "swf-version" , "swf-header", "debug" , "-no-traces" , "-flash-use-stage" , "-gen-hx-classes" , "-remap" , "-no-inline" , "-no-opt" , "-php-prefix" , "-js-namespace" , "-interp" , "-macro" , "-dead-code-elimination" , "-remap" , "-php-front" , "-php-lib" ] :
if l.startswith( "-"+flag ) :
currentBuild.args.append( tuple(l.split(" ") ) )
break
for flag in [ "resource" , "xml" , "x" , "swf-lib" ] :
if l.startswith( "-"+flag ) :
spl = l.split(" ")
outp = os.path.join( folder , " ".join(spl[1:]) )
currentBuild.args.append( ("-"+flag, outp) )
break
for flag in HaxeBuild.targets :
if l.startswith( "-" + flag + " " ) :
spl = l.split(" ")
outp = os.path.join( folder , " ".join(spl[1:]) )
currentBuild.args.append( ("-"+flag, outp) )
currentBuild.target = flag
currentBuild.output = outp
break
if l.startswith("-cp "):
cp = l.split(" ")
#view.set_status( "haxe-status" , "Building..." )
cp.pop(0)
classpath = " ".join( cp )
currentBuild.classpaths.append( os.path.join( buildPath , classpath ) )
currentBuild.args.append( ("-cp" , os.path.join( buildPath , classpath ) ) )
if len(currentBuild.classpaths) == 0:
currentBuild.classpaths.append( buildPath )
currentBuild.args.append( ("-cp" , buildPath ) )
if currentBuild.main is not None :
self.builds.append( currentBuild )
def extract_build_args( self , view , forcePanel = False ) :
scopes = view.scope_name(view.sel()[0].end()).split()
#sublime.status_message( scopes[0] )
if 'source.haxe.2' not in scopes and 'source.hxml' not in scopes and 'source.nmml' not in scopes:
return []
self.builds = []
fn = view.file_name()
settings = view.settings()
folder = os.path.dirname(fn)
folders = view.window().folders()
for f in folders:
if f in fn :
folder = f
# settings.set("haxe-complete-folder", folder)
self.find_hxml(folder)
self.find_nmml(folder)
if len(self.builds) == 1:
sublime.status_message("There is only one build")
self.set_current_build( view , int(0), forcePanel )
elif len(self.builds) == 0 and forcePanel :
sublime.status_message("No hxml or nmml file found")
f = os.path.join(folder,"build.hxml")
if self.currentBuild is not None :
self.currentBuild.hxml = f
#for whatever reason generate_build doesn't work without transient
v = view.window().open_file(f,sublime.TRANSIENT)
elif len(self.builds) > 1 and forcePanel :
buildsView = []
for b in self.builds :
#for a in b.args :
# v.append( " ".join(a) )
buildsView.append( [b.to_string(), os.path.basename( b.hxml ) ] )
self.selectingBuild = True
sublime.status_message("Please select your build")
view.window().show_quick_panel( buildsView , lambda i : self.set_current_build(view, int(i), forcePanel) , sublime.MONOSPACE_FONT )
elif settings.has("haxe-build-id"):
self.set_current_build( view , int(settings.get("haxe-build-id")), forcePanel )
else:
self.set_current_build( view , int(0), forcePanel )
def set_current_build( self , view , id , forcePanel ) :
#print("setting current build #"+str(id))
#print( self.builds )
if id < 0 or id >= len(self.builds) :
id = 0
view.settings().set( "haxe-build-id" , id )
if len(self.builds) > 0 :
self.currentBuild = self.builds[id]
view.set_status( "haxe-build" , self.currentBuild.to_string() )
else:
#self.currentBuild = None
view.set_status( "haxe-build" , "No build" )
self.selectingBuild = False
if forcePanel and self.currentBuild is not None: # choose NME target
if self.currentBuild.nmml is not None:
sublime.status_message("Please select a NME target")
view.window().show_quick_panel(HaxeBuild.nme_targets, lambda i : self.select_nme_target(i, view))
def select_nme_target( self, i, view ):
target = HaxeBuild.nme_targets[i]
if self.currentBuild.nmml is not None:
HaxeBuild.nme_target = target
view.set_status( "haxe-build" , self.currentBuild.to_string() )
def run_build( self , view ) :
#view.run_command("save")
self.clear_output_panel(view)
#view.set_status( "haxe-status" , "Building..." )
self.panel_output( view, "Building: " + self.currentBuild.to_string() , "success" )
err, comps, status = self.run_haxe( view )
if status == "Build success" or status.startswith("Total time"):
self.panel_output( view , "Build success!" , "success")
self.panel_output( view , err , "success")
elif status != "Running...":
self.panel_output( view , err , "invalid" )
#print(status)
view.set_status( "haxe-status" , status )
#if not "success" in status :
#sublime.error_message( err )
def clear_output_panel(self, view) :
win = view.window()
self.panel = win.get_output_panel("haxe")
def panel_output( self , view , text , scope = None ) :
win = view.window()
if self.panel is None :
self.panel = win.get_output_panel("haxe")
panel = self.panel
text = datetime.now().strftime("%H:%M:%S") + " " + text;
edit = panel.begin_edit()
region = sublime.Region(panel.size(),panel.size() + len(text))
panel.insert(edit, panel.size(), text + "\n")
panel.end_edit( edit )
if scope is not None :
icon = "dot"
key = "haxe-" + scope
regions = panel.get_regions( key );
regions.append(region)
panel.add_regions( key , regions , scope , icon )
#print( err )
win.run_command("show_panel",{"panel":"output.haxe"})
return self.panel
def get_toplevel_completion( self , src , src_dir , build ) :
cl = []
comps = [("trace","trace"),("this","this"),("super","super")]
localTypes = typeDecl.findall( src )
for t in localTypes :
if t[1] not in cl:
cl.append( t[1] )
packageClasses, subPacks = self.extract_types( src_dir )
for c in packageClasses :
if c not in cl:
cl.append( c )
imports = importLine.findall( src )
imported = []
for i in imports :
imp = i[1]
imported.append(imp)
#dot = imp.rfind(".")+1
#clname = imp[dot:]
#cl.append( clname )
#print( i )
#print cl
buildClasses , buildPacks = build.get_types()
cl.extend( HaxeComplete.stdClasses )
cl.extend( buildClasses )
cl.sort();
packs = []
stdPackages = []
#print("target : "+build.target)
for p in HaxeComplete.stdPackages :
#print(p)
if p == "flash9" or p == "flash8" :
p = "flash"
if build.target is None or (p not in HaxeBuild.targets) or (p == build.target) :
stdPackages.append(p)
packs.extend( stdPackages )
packs.extend( buildPacks )
packs.sort()
for v in variables.findall(src) :
comps.append(( v + "\tvar" , v ))
for f in functions.findall(src) :
if f not in ["new"] :
comps.append(( f + "\tfunction" , f ))
#TODO can we restrict this to local scope ?
for paramsText in functionParams.findall(src) :
cleanedParamsText = re.sub(paramDefault,"",paramsText)
paramsList = cleanedParamsText.split(",")
for param in paramsList:
a = param.strip();
if a.startswith("?"):
a = a[1:]
idx = a.find(":")
if idx > -1:
a = a[0:idx]
idx = a.find("=")
if idx > -1:
a = a[0:idx]
a = a.strip()
cm = (a + "\tvar", a)
if cm not in comps:
comps.append( cm )
for c in cl :
spl = c.split(".")
if spl[0] == "flash9" or spl[0] == "flash8" :
spl[0] = "flash"
top = spl[0]
#print(spl)
clname = spl.pop()
pack = ".".join(spl)
display = clname
#if pack in imported:
# pack = ""
if pack != "" :
display += "\t" + pack
else :
display += "\tclass"
spl.append(clname)
if pack in imported or c in imported :
cm = ( display , clname )
else :
cm = ( display , ".".join(spl) )
if cm not in comps and ( build.target is None or (top not in HaxeBuild.targets) or (top == build.target) ) :
comps.append( cm )
for p in packs :
cm = (p + "\tpackage",p)
if cm not in comps :
comps.append(cm)
return comps
def clear_build( self , view ) :
self.currentBuild = None
self.currentCompletion = {
"inp" : None,
"outp" : None
}
def get_build( self , view ) :
if self.currentBuild is None:
fn = view.file_name()
src_dir = os.path.dirname( fn )
src = view.substr(sublime.Region(0, view.size()))
build = HaxeBuild()
build.target = "js"