-
Notifications
You must be signed in to change notification settings - Fork 28
/
index.html
967 lines (838 loc) · 31.3 KB
/
index.html
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
<!doctype html>
<meta charset=utf8>
<script src="node_modules/codemirror/lib/codemirror.js"></script>
<link rel=stylesheet href="node_modules/codemirror/lib/codemirror.css">
<link rel=stylesheet href="node_modules/codemirror/addon/fold/foldgutter.css">
<link rel=stylesheet href="node_modules/codemirror/addon/dialog/dialog.css">
<link rel=stylesheet href="node_modules/codemirror/addon/hint/show-hint.css">
<link rel=stylesheet href="node_modules/codemirror/addon/lint/lint.css">
<link rel=stylesheet href="node_modules/codemirror/addon/scroll/simplescrollbars.css">
<link rel=stylesheet href="node_modules/codemirror/addon/scroll/matchesonscrollbar.css">
<script src="node_modules/codemirror/addon/wrap/hardwrap.js"></script>
<script src="node_modules/codemirror/addon/selection/selection-pointer.js"></script>
<script src="node_modules/codemirror/addon/selection/mark-selection.js"></script>
<script src="node_modules/codemirror/addon/selection/active-line.js"></script>
<script src="node_modules/codemirror/addon/search/searchcursor.js"></script>
<script src="node_modules/codemirror/addon/search/search.js"></script>
<script src="node_modules/codemirror/addon/search/matchesonscrollbar.js"></script>
<script src="node_modules/codemirror/addon/search/match-highlighter.js"></script>
<script src="node_modules/codemirror/addon/scroll/simplescrollbars.js"></script>
<script src="node_modules/codemirror/addon/scroll/scrollpastend.js"></script>
<script src="node_modules/codemirror/addon/scroll/annotatescrollbar.js"></script>
<script src="node_modules/codemirror/addon/runmode/runmode.js"></script>
<script src="node_modules/codemirror/addon/runmode/colorize.js"></script>
<script src="node_modules/codemirror/addon/lint/yaml-lint.js"></script>
<script src="node_modules/codemirror/addon/lint/lint.js"></script>
<script src="node_modules/codemirror/addon/lint/json-lint.js"></script>
<script src="node_modules/codemirror/addon/lint/javascript-lint.js"></script>
<script src="node_modules/codemirror/addon/lint/html-lint.js"></script>
<script src="node_modules/codemirror/addon/lint/css-lint.js"></script>
<script src="node_modules/codemirror/addon/lint/coffeescript-lint.js"></script>
<script src="node_modules/codemirror/addon/hint/xml-hint.js"></script>
<script src="node_modules/codemirror/addon/hint/sql-hint.js"></script>
<script src="node_modules/codemirror/addon/hint/show-hint.js"></script>
<script src="node_modules/codemirror/addon/hint/javascript-hint.js"></script>
<script src="node_modules/codemirror/addon/hint/html-hint.js"></script>
<script src="node_modules/codemirror/addon/hint/css-hint.js"></script>
<script src="node_modules/codemirror/addon/hint/anyword-hint.js"></script>
<script src="node_modules/codemirror/addon/fold/xml-fold.js"></script>
<script src="node_modules/codemirror/addon/fold/markdown-fold.js"></script>
<script src="node_modules/codemirror/addon/fold/indent-fold.js"></script>
<script src="node_modules/codemirror/addon/fold/foldgutter.js"></script>
<script src="node_modules/codemirror/addon/fold/foldcode.js"></script>
<script src="node_modules/codemirror/addon/fold/comment-fold.js"></script>
<script src="node_modules/codemirror/addon/fold/brace-fold.js"></script>
<script src="node_modules/codemirror/addon/edit/trailingspace.js"></script>
<script src="node_modules/codemirror/addon/edit/matchtags.js"></script>
<script src="node_modules/codemirror/addon/edit/matchbrackets.js"></script>
<script src="node_modules/codemirror/addon/edit/continuelist.js"></script>
<script src="node_modules/codemirror/addon/edit/closetag.js"></script>
<script src="node_modules/codemirror/addon/edit/closebrackets.js"></script>
<script src="node_modules/codemirror/addon/display/rulers.js"></script>
<script src="node_modules/codemirror/addon/display/placeholder.js"></script>
<script src="node_modules/codemirror/addon/display/panel.js"></script>
<script src="node_modules/codemirror/addon/display/fullscreen.js"></script>
<script src="node_modules/codemirror/addon/display/autorefresh.js"></script>
<script src="node_modules/codemirror/addon/dialog/dialog.js"></script>
<script src="node_modules/codemirror/addon/comment/continuecomment.js"></script>
<script src="node_modules/codemirror/addon/comment/comment.js"></script>
<script src="node_modules/codemirror-grammar-mode/src/mode.js"></script>
<script src="dist/javascript.js"></script>
<script src="dist/typescript.js"></script>
<script src="dist/java.js"></script>
<script src="dist/cpp.js"></script>
<script src="dist/python.js"></script>
<script src="dist/go.js"></script>
<script src="dist/angulartemplate.js"></script>
<script src="dist/kotlin.js"></script>
<script src="dist/clif.js"></script>
<style>
.CodeMirror { border: 1px solid silver; height: 500px; }
</style>
<title>Mode demos</title>
<h1>Mode demos</h1>
<h2>JavaScript</h2>
<textarea id=code-javascript>
import * as CodeMirror from "codemirror"
function hasSubStatement(context) {
let m = /^(if|for|do|while)\b/.exec(context.startLine.slice(context.startPos))
return m && m[1]
}
function isSwitch(context) {
return context && context.name == "Statement" &&
/^switch\b/.test(context.startLine.slice(context.startPos))
}
function isLabel(text) {
return text && /^\s*(case|default)\b/.test(text)
}
function aligned(cx) {
return !/^\s*((\/\/.*)?$|.*=>)/.test(cx.startLine.slice(cx.startPos + 1))
}
const bracketed = {
Block: "}", BlockOf: "}", ClassBody: "}", ObjectLiteral: "}", EnumBody: "}", ArrayInitializer: "}",
ArrayLiteral: "]",
ParamList: ")", SimpleParamList: ")", ArgList: ")", ParenExpr: ")", CondExpr: ")", TemplateArgs: ")", ForSpec: ")",
TypeParams: ">", TypeArgs: ">"
}
function statementIndent(cx, config) {
for (;; cx = cx.parent) {
if (!cx) return 0
if (cx.name == "Statement" || cx.name == "ObjectMember" || cx.name == "ClassItem" || cx.name == "NewExpr")
return CodeMirror.countColumn(cx.startLine, null, config.tabSize)
}
}
function plus(result, add) {
return typeof result == "number" ? result + add : result
}
function findIndent(cx, textAfter, curLine, config) {
if (!cx) return 0
if (cx.name == "string" || cx.name == "comment") return CodeMirror.Pass
let brack = bracketed[cx.name]
if (brack) {
let closed = textAfter && textAfter.charAt(0) == brack
if (config.align !== false && curLine != cx.startLine && aligned(cx))
return CodeMirror.countColumn(cx.startLine, cx.startPos, config.tabSize) + (closed ? 0 : 1)
if (cx.name == "Block" || cx.name == "ClassBody" || cx.name == "BlockOf" || cx.name == "EnumBody") {
// Skip wrapping statement context
let skipCx = cx
if (cx.parent && cx.parent.name == "Statement" && cx.parent.parent &&
cx.parent.parent.name == "Statement" && hasSubStatement(cx.parent.parent))
skipCx = cx.parent.parent
return statementIndent(skipCx, config) + (
/^(public|private|protected)\s*:/.test(textAfter) ? 1 :
closed ? 0 :
isSwitch(cx.parent) && !isLabel(textAfter) ? 2 * config.indentUnit
: config.indentUnit
)
}
let flat = closed && brack != ")" || curLine == cx.startLine && cx.name != "CondExpr"
return findIndent(cx.parent, closed ? null : textAfter, cx.startLine, config) +
(flat ? 0 : config.indentUnit * (brack == ")" || brack == ">" ? 2 : 1))
} else if (cx.name == "Statement" || cx.name == "ObjectMember" || cx.name == "ClassItem") {
let base = statementIndent(cx, config)
if (!curLine && hasSubStatement(cx))
return base + (/^else\b/.test(textAfter) ? 0 : config.indentUnit)
let flat = curLine == cx.startLine ||
curLine && CodeMirror.countColumn(curLine, null, config.tabSize) <= base
return base + (flat ? 0 : 2 * config.indentUnit)
} else if (cx.name == "ArrowRest") {
return plus(findIndent(cx.parent, textAfter, cx.startLine, config), config.indentUnit)
} else {
return plus(findIndent(cx.parent, textAfter, curLine, config),
(cx.name == "InitializerList" ? 2 : cx.name == "ThrowsClause" ? 2 * config.indentUnit : 0))
}
}
export function indent(state, textAfter, line, config) {
if (textAfter.charAt(0) == "#") return 0
let top = state.context && state.context.name
if (top == "DeclType" || top == "BeforeStatement" || top == "AnnotationHead")
return statementIndent(state.context, config)
if ((top == "doccomment.braced" || top == "doccomment.tagGroup") && !/^\s*(@|\*\/)/.test(textAfter))
return CodeMirror.countColumn(state.context.startLine, null, config.tabSize) + 2 * config.indentUnit
return findIndent(state.contextAt(line, line.length - textAfter.length), textAfter, null, config)
}
</textarea>
<h2>TypeScript</h2>
<textarea id=code-typescript>
function isString(test: any): test is string{
return typeof test === “string”;
}
function example(foo: any){
if(isString(foo)){
console.log(“it is a string” + foo);
console.log(foo.length); // string function
}
}
example(“hello world”);
</textarea>
<h2>Java</h2>
<textarea id=code-java>
import com.demo.util.MyType;
import com.demo.util.MyInterface;
public enum Enum {
VAL1, VAL2, VAL3
}
public class Class<T, V> implements MyInterface {
public static final MyType<T, V> member;
private class InnerClass {
public int zero() {
return 0;
}
}
@Override
public MyType method() {
return member;
}
public void method2(MyType<T, V> value) {
method();
value.method3();
member = value;
}
}
</textarea>
<h2>Kotlin</h2>
<textarea id=code-kotlin>
enum class Color(val rgb: Int) { // 1
RED(0xFF0000), // 2
GREEN(0x00FF00),
BLUE(0x0000FF),
YELLOW(0xFFFF00);
fun containsRed() = (this.rgb and 0xFF0000 != 0) // 3
}
fun main() {
val red = Color.RED
println(red) // 4
println(red.containsRed()) // 5
println(Color.BLUE.containsRed()) // 6
}
</textarea>
<h2>C++</h2>
<textarea id=code-cpp>
#include <iostream>
#include "mystuff/util.h"
namespace {
enum Enum {
VAL1, VAL2, VAL3
};
char32_t unicode_string = U"\U0010FFFF";
string raw_string = R"delim(anything
you
want)delim";
/** @brief Helper function.
*
* @param[in] param Input parameter.
* @return Returns zero.
*/
int Helper(const MyType& param) {
return 0;
}
} // namespace
class ForwardDec;
template <class T, class V>
class Class : public BaseClass {
const MyType<T, V> member_;
public:
const MyType<T, V>& Method() const {
return member_;
}
void Method2(MyType<T, V>* value);
}
template <class T, class V>
void Class::Method2(MyType<T, V>* value) {
std::out << 1 >> method();
value->Method3(member_);
member_ = value;
}
</textarea>
<h2>Python</h2>
<textarea id=code-python>
pdir = project_dir(fname)
if pdir is None: return None
project = None
for f in files.values():
if f.project.dir == pdir:
project = f.project
break
if project is None: project = Project(pdir)
pfile = files[fname] = ProjectFile(fname, view, project)
if project.disabled: return None
return pfile
def project_dir(fname):
dir = os.path.dirname(fname)
if not os.path.isdir(dir): return None
cur = dir
while True:
parent = os.path.dirname(cur[:-1])
if not parent:
break
if os.path.isfile(os.path.join(cur, ".tern-project")):
return cur
cur = parent
return dir
def pfile_modified(pfile, view):
pfile.dirty = True
now = time.time()
if now - pfile.last_modified > .5:
pfile.last_modified = now
if is_st2:
sublime.set_timeout(lambda: maybe_save_pfile(pfile, view, now), 5000)
else:
sublime.set_timeout_async(lambda: maybe_save_pfile(pfile, view, now), 5000)
if pfile.cached_completions and sel_start(view.sel()[0]) < pfile.cached_completions[0]:
pfile.cached_completions = None
if pfile.cached_arguments and sel_start(view.sel()[0]) < pfile.cached_arguments[0]:
pfile.cached_arguments = None
def maybe_save_pfile(pfile, view, timestamp):
if pfile.last_modified == timestamp and pfile.dirty:
send_buffer(pfile, view)
def server_port(project, ignored=None):
if project.port is not None and project.port != ignored:
return (project.port, True)
if project.port == ignored:
kill_server(project)
port_file = os.path.join(project.dir, ".tern-port")
if os.path.isfile(port_file):
port = int(open(port_file, "r").read())
if port != ignored:
project.port = port
return (port, True)
started = start_server(project)
if started is not None:
project.port = started
return (started, False)
def start_server(project):
if not tern_command: return None
if time.time() - project.last_failed < 30: return None
env = None
if platform.system() == "Darwin":
env = os.environ.copy()
env["PATH"] += ":/usr/local/bin"
proc = subprocess.Popen(tern_command + tern_arguments, cwd=project.dir, env=env,
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT, shell=windows)
output = ""
while True:
line = proc.stdout.readline().decode("utf-8")
if not line:
sublime.error_message("Failed to start server" + (output and ":\n" + output))
project.last_failed = time.time()
return None
match = re.match("Listening on port (\\d+)", line)
if match:
project.proc = proc
return int(match.group(1))
else:
output += line
def kill_server(project):
if project.proc is None: return
project.proc.stdin.close()
project.proc.wait()
project.proc = None
def relative_file(pfile):
return pfile.name[len(pfile.project.dir) + 1:]
def buffer_fragment(view, pos):
region = None
for js_region in view.find_by_selector("source.js"):
if js_region.a <= pos and js_region.b >= pos:
region = js_region
break
if region is None: return sublime.Region(pos, pos)
start = view.line(max(region.a, pos - 1000)).a
if start < pos - 1500: start = pos - 1500
cur = start
min_indent = 10000
while True:
next = view.find("\\bfunction\\b", cur)
if next is None or next.b > pos or (next.a == -1 and next.b == -1): break
line = view.line(next.a)
if line.a < pos - 1500: line = sublime.Region(pos - 1500, line.b)
indent = count_indentation(view.substr(line))
if indent < min_indent:
min_indent = indent
start = line.a
cur = line.b
return sublime.Region(start, min(pos + 500, region.b))
def count_indentation(line):
count, pos = (0, 0)
while pos < len(line):
ch = line[pos]
if ch == " ": count += 1
elif ch == "\t": count += 4
else: break
pos += 1
return count
def sel_start(sel):
return min(sel.a, sel.b)
def sel_end(sel):
return max(sel.a, sel.b)
class Req_Error(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
localhost = (windows and "127.0.0.1") or "localhost"
def make_request_py2():
import urllib2
opener = urllib2.build_opener(urllib2.ProxyHandler({}))
def f(port, doc):
try:
req = opener.open("http://" + localhost + ":" + str(port) + "/", json.dumps(doc), 1)
return json.loads(req.read())
except urllib2.HTTPError as error:
raise Req_Error(error.read())
return f
def make_request_py3():
import urllib.request, urllib.error
opener = urllib.request.build_opener(urllib.request.ProxyHandler({}))
def f(port, doc):
try:
req = opener.open("http://" + localhost + ":" + str(port) + "/", json.dumps(doc).encode("utf-8"), 1)
return json.loads(req.read().decode("utf-8"))
except urllib.error.URLError as error:
if hasattr(error, "read"):
raise Req_Error(error.read().decode("utf-8"))
else:
raise error
return f
if python3:
make_request = make_request_py3()
else:
make_request = make_request_py2()
def view_js_text(view):
text, pos = ("", 0)
for region in view.find_by_selector("source.js"):
if region.a > pos: text += ";" + re.sub(r'[^\n]', " ", view.substr(sublime.Region(pos + 1, region.a)))
text += view.substr(region)
pos = region.b
return text
def run_command(view, query, pos=None, fragments=True, silent=False):
"""Run the query on the Tern server.
See default queries at http://ternjs.net/doc/manual.html#protocol.
"""
pfile = get_pfile(view)
if pfile is None or pfile.project.disabled: return
if isinstance(query, str): query = {"type": query}
if (pos is None): pos = view.sel()[0].b
port, port_is_old = server_port(pfile.project)
if port is None: return
doc = {"query": query, "files": []}
if not pfile.dirty:
fname, sending_file = (relative_file(pfile), False)
if fragments and view.size() > 8000:
region = buffer_fragment(view, pos)
doc["files"].append({"type": "part",
"name": relative_file(pfile),
"offset": region.a,
"text": view.substr(region)})
pos -= region.a
fname, sending_file = ("#0", False)
else:
doc["files"].append({"type": "full",
"name": relative_file(pfile),
"text": view_js_text(view)})
fname, sending_file = ("#0", True)
query["file"] = fname
query["end"] = pos
data = None
try:
data = make_request(port, doc)
except Req_Error as e:
if not silent: report_error(str(e), pfile.project)
return None
except:
pass
if data is None and port_is_old:
try:
port = server_port(pfile.project, port)[0]
if port is None: return
data = make_request(port, doc)
if data is None: return None
except Exception as e:
if not silent: report_error(str(e), pfile.project)
if sending_file: pfile.dirty = False
return data
def send_buffer(pfile, view):
port = server_port(pfile.project)[0]
if port is None: return False
try:
make_request(port,
{"files": [{"type": "full",
"name": relative_file(pfile),
"text": view_js_text(view)}]})
pfile.dirty = False
return True
except:
return False
def report_error(message, project):
if sublime.ok_cancel_dialog(message, "Disable Tern"):
project.disabled = True
def completion_icon(type):
if type is None or type == "?": return "\t? "
if type.startswith("fn("): return "\tfn "
if type.startswith("["): return "\t[] "
if type == "number": return "\tnum "
if type == "string": return "\tstr "
if type == "bool": return "\tbool "
return "\t{} "
def fn_completion_icon(arguments, retval):
# return " (fn/"+str(len(arguments))+")"
ret = ""
if retval is not None:
ret = retval
return "(" + ", ".join(arguments) + ")" + ret + ("\tfn ")
# create auto complete string from list arguments
def create_arg_str(arguments):
if len(arguments) == 0:
return "${1}"
arg_str = ""
k = 1
for argument in arguments:
arg_str += "${" + str(k) + ":" + argument.replace("$", "\$") + "}, "
k += 1
return arg_str[0:-2]
# parse the type to get the arguments
def get_arguments(type):
type = type[3:type.find(')')] + ",'"
arg_list = []
arg_start = 0
arg_end = 0
# this two variables are used to skip ': {...}' in signature like 'a: {...}'
depth = 0
arg_already = False
for ch in type:
if depth == 0 and ch == ',':
if arg_already:
arg_already = False
elif arg_start != arg_end:
arg_list.append(type[arg_start:arg_end])
arg_start = arg_end+1
elif depth == 0 and ch == ':':
arg_already = True
arg_list.append(type[arg_start:arg_end])
elif ch == '{' or ch == '(' or ch == '[':
depth += 1
elif ch == '}' or ch == ')' or ch == ']':
depth -= 1
elif ch == ' ':
arg_start = arg_end + 1
arg_end += 1
return arg_list
def ensure_completions_cached(pfile, view):
pos = view.sel()[0].b
if pfile.cached_completions is not None:
c_start, c_word, c_completions = pfile.cached_completions
if c_start <= pos:
slice = view.substr(sublime.Region(c_start, pos))
if slice.startswith(c_word) and not re.match(".*\\W", slice):
return (c_completions, False)
data = run_command(view, {"type": "completions", "types": True, "includeKeywords": True})
if data is None: return (None, False)
completions = []
completions_arity = []
for rec in data["completions"]:
rec_name = rec.get('name').replace('$', '\\$')
rec_type = rec.get("type", None)
if arg_completion_enabled and rec_type is not None and rec_type.startswith("fn("):
retval = parse_function_type(rec).get('retval')
if retval is None or retval == "()":
retval = ""
elif retval.startswith("{"):
retval = "{}"
elif retval.startswith("["):
retval = "[]"
if retval != "":
retval = " -> " + retval
arguments = get_arguments(rec_type)
fn_name = rec_name + "(" + create_arg_str(arguments) + ")"
completions.append((rec.get("name") + fn_completion_icon(arguments, retval), fn_name))
else:
completions.append((rec.get("name") + completion_icon(rec_type), rec_name))
# put the auto completions of functions with lower arity at the bottom of the autocomplete list
# so they don't clog up the autocompeltions at the top of the list
completions = completions + completions_arity
pfile.cached_completions = (data["start"], view.substr(sublime.Region(data["start"], pos)), completions)
return (completions, True)
def locate_call(view):
sel = view.sel()[0]
if sel.a != sel.b: return (None, 0)
context = view.substr(sublime.Region(max(0, sel.b - 500), sel.b))
pos = len(context)
depth = argpos = 0
while pos > 0:
pos -= 1
ch = context[pos]
if ch == "}" or ch == ")" or ch == "]":
depth += 1
elif ch == "{" or ch == "(" or ch == "[":
if depth > 0: depth -= 1
elif ch == "(": return (pos + sel.b - len(context), argpos)
else: return (None, 0)
elif ch == "," and depth == 0:
argpos += 1
return (None, 0)
def show_argument_hints(pfile, view):
call_start, argpos = locate_call(view)
if call_start is None: return render_argument_hints(pfile, view, None, 0)
if pfile.cached_arguments is not None and pfile.cached_arguments[0] == call_start:
return render_argument_hints(pfile, view, pfile.cached_arguments[1], argpos)
data = run_command(view, {"type": "type", "preferFunction": True}, call_start, silent=True)
if data is not None:
parsed = parse_function_type(data)
if parsed is not None:
parsed['url'] = data.get('url', None)
parsed['doc'] = data.get('doc', None)
pfile.cached_arguments = (call_start, parsed)
render_argument_hints(pfile, view, parsed, argpos)
def render_argument_hints(pfile, view, ftype, argpos):
if ftype is None:
renderer.clean(pfile, view)
else:
renderer.render_arghints(pfile, view, ftype, argpos)
def parse_function_type(data):
type = data["type"]
if not re.match("fn\\(", type): return None
pos = 3
args, retval = ([], None)
while pos < len(type) and type[pos] != ")":
colon = type.find(":", pos)
name = "?"
if colon != -1:
name = type[pos:colon]
if not re.match("[\\w_$]+$", name): name = "?"
else: pos = colon + 2
type_start = pos
depth = 0
while pos < len(type):
ch = type[pos]
if ch == "(" or ch == "[" or ch == "{":
depth += 1
elif ch == ")" or ch == "]" or ch == "}":
if depth > 0: depth -= 1
else: break
elif ch == "," and depth == 0:
break
pos += 1
args.append((name, type[type_start:pos]))
if type[pos] == ",": pos += 2
if type[pos:pos + 5] == ") -> ":
retval = type[pos + 5:]
return {"name": data.get("exprName", None) or data.get("name", None) or "fn",
"args": args,
"retval": retval}
jump_stack = []
class TernArghintCommand(sublime_plugin.TextCommand):
def run(self, edit, **args):
self.view.insert(edit, 0, args.get('msg', ''))
class TernJumpToDef(sublime_plugin.TextCommand):
def run(self, edit, **args):
data = run_command(self.view, {"type": "definition", "lineCharPositions": True})
if data is None: return
file = data.get("file", None)
if file is not None:
# Found an actual definition
row, col = self.view.rowcol(self.view.sel()[0].b)
cur_pos = self.view.file_name() + ":" + str(row + 1) + ":" + str(col + 1)
jump_stack.append(cur_pos)
if len(jump_stack) > 50: jump_stack.pop(0)
real_file = (os.path.join(get_pfile(self.view).project.dir, file) +
":" + str(data["start"]["line"] + 1) + ":" + str(data["start"]["ch"] + 1))
sublime.active_window().open_file(real_file, sublime.ENCODED_POSITION)
else:
url = data.get("url", None)
if url is None:
sublime.error_message("Could not find a definition")
else:
webbrowser.open(url)
class TernJumpBack(sublime_plugin.TextCommand):
def run(self, edit, **args):
if len(jump_stack) > 0:
sublime.active_window().open_file(jump_stack.pop(), sublime.ENCODED_POSITION)
class TernSelectVariable(sublime_plugin.TextCommand):
def run(self, edit, **args):
data = run_command(self.view, "refs", fragments=False)
if data is None: return
file = relative_file(get_pfile(self.view))
shown_error = False
regions = []
for ref in data["refs"]:
if ref["file"].replace('\\','/') != file.replace('\\','/'):
if not shown_error:
sublime.error_message("Not all uses of this variable are file-local. Selecting only local ones.")
shown_error = True
else:
regions.append(sublime.Region(ref["start"], ref["end"]))
self.view.sel().clear()
for r in regions: self.view.sel().add(r)
class TernDescribe(sublime_plugin.TextCommand):
def run(self, edit, **args):
data = run_command(self.view, {"type": "documentation"})
if data is None:
return
renderer.render_description(get_pfile(self.view), self.view,
data["type"], data.get("doc", None),
data.get("url", None))
class TernDisableProject(sublime_plugin.TextCommand):
def run(self, edit, **args):
pfile = get_pfile(view)
pfile.project.disabled = False
class TernEnableProject(sublime_plugin.TextCommand):
def run(self, edit, **args):
pfile = get_pfile(view)
pfile.project.disabled = True
# fetch a certain setting from the package settings file and if it doesn't exist check the
# Preferences.sublime-settings file for backwards compatibility.
def get_setting(key, default):
old_settings = sublime.load_settings("Preferences.sublime-settings")
new_settings = sublime.load_settings("Tern.sublime-settings")
setting = new_settings.get(key, None)
if setting is None:
return old_settings.get(key, default)
else:
return new_settings.get(key, default)
plugin_dir = os.path.abspath(os.path.dirname(__file__))
def plugin_loaded():
global arghints_enabled, renderer, tern_command, tern_arguments
global arg_completion_enabled
arghints_enabled = get_setting("tern_argument_hints", False)
arg_completion_enabled = get_setting("tern_argument_completion", False)
if "show_popup" in dir(sublime.View):
default_output_style = "tooltip"
else:
default_output_style = "status"
output_style = get_setting("tern_output_style", get_setting("tern_argument_hints_type", default_output_style))
renderer = create_renderer(output_style)
tern_arguments = get_setting("tern_arguments", [])
if not isinstance(tern_arguments, list):
tern_arguments = [tern_arguments]
tern_command = get_setting("tern_command", None)
if tern_command is None:
if not os.path.isdir(os.path.join(plugin_dir, "node_modules/tern")):
if sublime.ok_cancel_dialog(
"It appears Tern has not been installed. Do you want tern_for_sublime to try and install it? "
"(Note that this will only work if you already have node.js and npm installed on your system.)"
"\n\nTo get rid of this dialog, either uninstall tern_for_sublime, or set the tern_command setting.",
"Yes, install."):
try:
if hasattr(subprocess, "check_output"):
subprocess.check_output(["npm", "--loglevel=silent", "install"], cwd=plugin_dir, shell=windows)
else:
subprocess.check_call(["npm", "--loglevel=silent", "install"], cwd=plugin_dir, shell=windows)
except (IOError, OSError, CalledProcessError) as e:
msg = "Installation failed. Try doing 'npm install' manually in " + plugin_dir + "."
if hasattr(e, "output") and e.output is not None:
msg += "\nError message was:\n\n" + e.output
if hasattr(e, "returncode"):
msg += "\nReturn code was: " + str(e.returncode)
sublime.error_message(msg)
return
tern_command = ["node", os.path.join(plugin_dir, "node_modules/tern/bin/tern"), "--no-port-file"]
def cleanup():
for f in files.values():
kill_server(f.project)
atexit.register(cleanup)
if is_st2:
sublime.set_timeout(plugin_loaded, 500)
</textarea>
<h2>Go</h2>
<textarea id=code-go>
// Prime Sieve in Go.
// Taken from the Go specification.
// Copyright © The Go Authors.
package main
import "fmt"
// Send the sequence 2, 3, 4, ... to channel 'ch'.
func generate(ch chan<- int) {
for i := 2; ; i++ {
ch <- i // Send 'i' to channel 'ch'
}
}
// Copy the values from channel 'src' to channel 'dst',
// removing those divisible by 'prime'.
func filter(src <-chan int, dst chan<- int, prime int) {
for i := range src { // Loop over values received from 'src'.
if i%prime != 0 {
dst <- i // Send 'i' to channel 'dst'.
}
}
}
// The prime sieve: Daisy-chain filter processes together.
func sieve() {
ch := make(chan int) // Create a new channel.
go generate(ch) // Start generate() as a subprocess.
for {
prime := <-ch
fmt.Print(prime, "\n")
ch1 := make(chan int)
go filter(ch, ch1, prime)
ch = ch1
}
}
func main() {
sieve()
}
</textarea>
<h2>Angular Template</h2>
<textarea id=code-angular-template>
<form (ngSubmit)="onSubmit(heroForm)" #heroForm="ngForm">
<div class="form-group">
<label for="name">Name
<input class="form-control" name="name" required [(ngModel)]="hero.name">
</label>
</div>
<button type="submit" [disabled]="!heroForm.form.valid">Submit</button>
</form>
<div [hidden]="!heroForm.form.valid">
{{submitMessage}}
</div>
</textarea>
<h2>CLIF</h2>
<textarea id=code-clif>
from "foo.h" import *
from "bar.h" import * as bar
from foo.bar import baz
from "foo/bar.h":
enum NAME with:
`Abra` as ABRA
interface Foo<T>:
def bar(self) -> T
</textarea>
<script>
let editors = {}
;[
{name: "javascript", continueComments: "Enter"},
{name: "typescript"},
{name: "java"},
{name: "cpp"},
{name: "python"},
{name: "go", tabSize: 2, indentWithTabs: true, indentUnit: 2},
{name: "angular-template"},
{name: "kotlin"},
{name: "clif"},
].forEach(spec => {
editors[spec.name] = CodeMirror.fromTextArea(document.querySelector(`#code-${spec.name}`),
Object.assign({
mode: "google-" + spec.name,
autoCloseBrackets: true,
continueComments: {key: "Enter", continueLineComment: false},
foldGutter: true,
gutters: ["gutter", "CodeMirror-linenumbers", "CodeMirror-foldgutter"],
highlightSelectionMatches: {showToken: true, delay: 500, annotateScrollbar: true},
indentUnit: 2,
inputStyle: "textarea",
lineNumbers: true,
lineWrapping: false,
matchBrackets: {maxScanLines: 5000},
pasteLinesPerSelection: false,
readOnly: false,
scrollPastEnd: false,
showCursorWhenSelecting: true,
showTrailingSpace: true,
smartIndent: true,
styleActiveLine: true,
styleSelectedText: true,
tabSize: 2,
undoDepth: 500,
vimMode: false,
}, spec))
})
</script>