Projekt

Obecné

Profil

Stáhnout (74.9 KB) Statistiky
| Větev: | Tag: | Revize:
1
ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/range_list","ace/keyboard/hash_handler","ace/tokenizer","ace/clipboard","ace/lib/dom","ace/editor"], function(require, exports, module) {
2
"use strict";
3
var oop = require("./lib/oop");
4
var EventEmitter = require("./lib/event_emitter").EventEmitter;
5
var lang = require("./lib/lang");
6
var Range = require("./range").Range;
7
var RangeList = require("./range_list").RangeList;
8
var HashHandler = require("./keyboard/hash_handler").HashHandler;
9
var Tokenizer = require("./tokenizer").Tokenizer;
10
var clipboard = require("./clipboard");
11

    
12
var VARIABLES = {
13
    CURRENT_WORD: function(editor) {
14
        return editor.session.getTextRange(editor.session.getWordRange());
15
    },
16
    SELECTION: function(editor, name, indentation) {
17
        var text = editor.session.getTextRange();
18
        if (indentation)
19
            return text.replace(/\n\r?([ \t]*\S)/g, "\n" + indentation + "$1");
20
        return text;
21
    },
22
    CURRENT_LINE: function(editor) {
23
        return editor.session.getLine(editor.getCursorPosition().row);
24
    },
25
    PREV_LINE: function(editor) {
26
        return editor.session.getLine(editor.getCursorPosition().row - 1);
27
    },
28
    LINE_INDEX: function(editor) {
29
        return editor.getCursorPosition().row;
30
    },
31
    LINE_NUMBER: function(editor) {
32
        return editor.getCursorPosition().row + 1;
33
    },
34
    SOFT_TABS: function(editor) {
35
        return editor.session.getUseSoftTabs() ? "YES" : "NO";
36
    },
37
    TAB_SIZE: function(editor) {
38
        return editor.session.getTabSize();
39
    },
40
    CLIPBOARD: function(editor) {
41
        return clipboard.getText && clipboard.getText();
42
    },
43
    FILENAME: function(editor) {
44
        return /[^/\\]*$/.exec(this.FILEPATH(editor))[0];
45
    },
46
    FILENAME_BASE: function(editor) {
47
        return /[^/\\]*$/.exec(this.FILEPATH(editor))[0].replace(/\.[^.]*$/, "");
48
    },
49
    DIRECTORY: function(editor) {
50
        return this.FILEPATH(editor).replace(/[^/\\]*$/, "");
51
    },
52
    FILEPATH: function(editor) { return "/not implemented.txt"; },
53
    WORKSPACE_NAME: function() { return "Unknown"; },
54
    FULLNAME: function() { return "Unknown"; },
55
    BLOCK_COMMENT_START: function(editor) {
56
        var mode = editor.session.$mode || {};
57
        return mode.blockComment && mode.blockComment.start || "";
58
    },
59
    BLOCK_COMMENT_END: function(editor) {
60
        var mode = editor.session.$mode || {};
61
        return mode.blockComment && mode.blockComment.end || "";
62
    },
63
    LINE_COMMENT: function(editor) {
64
        var mode = editor.session.$mode || {};
65
        return mode.lineCommentStart || "";
66
    },
67
    CURRENT_YEAR: date.bind(null, {year: "numeric"}),
68
    CURRENT_YEAR_SHORT: date.bind(null, {year: "2-digit"}),
69
    CURRENT_MONTH: date.bind(null, {month: "numeric"}),
70
    CURRENT_MONTH_NAME: date.bind(null, {month: "long"}),
71
    CURRENT_MONTH_NAME_SHORT: date.bind(null, {month: "short"}),
72
    CURRENT_DATE: date.bind(null, {day: "2-digit"}),
73
    CURRENT_DAY_NAME: date.bind(null, {weekday: "long"}),
74
    CURRENT_DAY_NAME_SHORT: date.bind(null, {weekday: "short"}),
75
    CURRENT_HOUR: date.bind(null, {hour: "2-digit", hour12: false}),
76
    CURRENT_MINUTE: date.bind(null, {minute: "2-digit"}),
77
    CURRENT_SECOND: date.bind(null, {second: "2-digit"})
78
};
79

    
80
VARIABLES.SELECTED_TEXT = VARIABLES.SELECTION;
81

    
82
function date(dateFormat) {
83
    var str = new Date().toLocaleString("en-us", dateFormat);
84
    return str.length == 1 ? "0" + str : str;
85
}
86

    
87
var SnippetManager = function() {
88
    this.snippetMap = {};
89
    this.snippetNameMap = {};
90
};
91

    
92
(function() {
93
    oop.implement(this, EventEmitter);
94
    
95
    this.getTokenizer = function() {
96
        return SnippetManager.$tokenizer || this.createTokenizer();
97
    };
98
    
99
    this.createTokenizer = function() {
100
        function TabstopToken(str) {
101
            str = str.substr(1);
102
            if (/^\d+$/.test(str))
103
                return [{tabstopId: parseInt(str, 10)}];
104
            return [{text: str}];
105
        }
106
        function escape(ch) {
107
            return "(?:[^\\\\" + ch + "]|\\\\.)";
108
        }
109
        var formatMatcher = {
110
            regex: "/(" + escape("/") + "+)/", 
111
            onMatch: function(val, state, stack) {
112
                var ts = stack[0];
113
                ts.fmtString = true;
114
                ts.guard = val.slice(1, -1);
115
                ts.flag = "";
116
                return "";
117
            },
118
            next: "formatString"
119
        };
120
        
121
        SnippetManager.$tokenizer = new Tokenizer({
122
            start: [
123
                {regex: /\\./, onMatch: function(val, state, stack) {
124
                    var ch = val[1];
125
                    if (ch == "}" && stack.length) {
126
                        val = ch;
127
                    } else if ("`$\\".indexOf(ch) != -1) {
128
                        val = ch;
129
                    }
130
                    return [val];
131
                }},
132
                {regex: /}/, onMatch: function(val, state, stack) {
133
                    return [stack.length ? stack.shift() : val];
134
                }},
135
                {regex: /\$(?:\d+|\w+)/, onMatch: TabstopToken},
136
                {regex: /\$\{[\dA-Z_a-z]+/, onMatch: function(str, state, stack) {
137
                    var t = TabstopToken(str.substr(1));
138
                    stack.unshift(t[0]);
139
                    return t;
140
                }, next: "snippetVar"},
141
                {regex: /\n/, token: "newline", merge: false}
142
            ],
143
            snippetVar: [
144
                {regex: "\\|" + escape("\\|") + "*\\|", onMatch: function(val, state, stack) {
145
                    var choices = val.slice(1, -1).replace(/\\[,|\\]|,/g, function(operator) {
146
                        return operator.length == 2 ? operator[1] : "\x00";
147
                    }).split("\x00");
148
                    stack[0].choices = choices;
149
                    return [choices[0]];
150
                }, next: "start"},
151
                formatMatcher,
152
                {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "start"}
153
            ],
154
            formatString: [
155
                {regex: /:/, onMatch: function(val, state, stack) {
156
                    if (stack.length && stack[0].expectElse) {
157
                        stack[0].expectElse = false;
158
                        stack[0].ifEnd = {elseEnd: stack[0]};
159
                        return [stack[0].ifEnd];
160
                    }
161
                    return ":";
162
                }},
163
                {regex: /\\./, onMatch: function(val, state, stack) {
164
                    var ch = val[1];
165
                    if (ch == "}" && stack.length)
166
                        val = ch;
167
                    else if ("`$\\".indexOf(ch) != -1)
168
                        val = ch;
169
                    else if (ch == "n")
170
                        val = "\n";
171
                    else if (ch == "t")
172
                        val = "\t";
173
                    else if ("ulULE".indexOf(ch) != -1)
174
                        val = {changeCase: ch, local: ch > "a"};
175
                    return [val];
176
                }},
177
                {regex: "/\\w*}", onMatch: function(val, state, stack) {
178
                    var next = stack.shift();
179
                    if (next)
180
                        next.flag = val.slice(1, -1);
181
                    this.next = next && next.tabstopId ? "start" : "";
182
                    return [next || val];
183
                }, next: "start"},
184
                {regex: /\$(?:\d+|\w+)/, onMatch: function(val, state, stack) {
185
                    return [{text: val.slice(1)}];
186
                }},
187
                {regex: /\${\w+/, onMatch: function(val, state, stack) {
188
                    var token = {text: val.slice(2)};
189
                    stack.unshift(token);
190
                    return [token];
191
                }, next: "formatStringVar"},
192
                {regex: /\n/, token: "newline", merge: false},
193
                {regex: /}/, onMatch: function(val, state, stack) {
194
                    var next = stack.shift();
195
                    this.next = next && next.tabstopId ? "start" : "";
196
                    return [next || val];
197
                }, next: "start"}
198
            ],
199
            formatStringVar: [
200
                {regex: /:\/\w+}/, onMatch: function(val, state, stack) {
201
                    var ts = stack[0];
202
                    ts.formatFunction = val.slice(2, -1);
203
                    return [stack.shift()];
204
                }, next: "formatString"},
205
                formatMatcher,
206
                {regex: /:[\?\-+]?/, onMatch: function(val, state, stack) {
207
                    if (val[1] == "+")
208
                        stack[0].ifEnd = stack[0];
209
                    if (val[1] == "?")
210
                        stack[0].expectElse = true;
211
                }, next: "formatString"},
212
                {regex: "([^:}\\\\]|\\\\.)*:?", token: "", next: "formatString"}
213
            ]
214
        });
215
        return SnippetManager.$tokenizer;
216
    };
217

    
218
    this.tokenizeTmSnippet = function(str, startState) {
219
        return this.getTokenizer().getLineTokens(str, startState).tokens.map(function(x) {
220
            return x.value || x;
221
        });
222
    };
223
    
224
    this.getVariableValue = function(editor, name, indentation) {
225
        if (/^\d+$/.test(name))
226
            return (this.variables.__ || {})[name] || "";
227
        if (/^[A-Z]\d+$/.test(name))
228
            return (this.variables[name[0] + "__"] || {})[name.substr(1)] || "";
229
        
230
        name = name.replace(/^TM_/, "");
231
        if (!this.variables.hasOwnProperty(name))
232
            return "";
233
        var value = this.variables[name];
234
        if (typeof value == "function")
235
            value = this.variables[name](editor, name, indentation);
236
        return value == null ? "" : value;
237
    };
238
    
239
    this.variables = VARIABLES;
240
    this.tmStrFormat = function(str, ch, editor) {
241
        if (!ch.fmt) return str;
242
        var flag = ch.flag || "";
243
        var re = ch.guard;
244
        re = new RegExp(re, flag.replace(/[^gim]/g, ""));
245
        var fmtTokens = typeof ch.fmt == "string" ? this.tokenizeTmSnippet(ch.fmt, "formatString") : ch.fmt;
246
        var _self = this;
247
        var formatted = str.replace(re, function() {
248
            var oldArgs = _self.variables.__;
249
            _self.variables.__ = [].slice.call(arguments);
250
            var fmtParts = _self.resolveVariables(fmtTokens, editor);
251
            var gChangeCase = "E";
252
            for (var i  = 0; i < fmtParts.length; i++) {
253
                var ch = fmtParts[i];
254
                if (typeof ch == "object") {
255
                    fmtParts[i] = "";
256
                    if (ch.changeCase && ch.local) {
257
                        var next = fmtParts[i + 1];
258
                        if (next && typeof next == "string") {
259
                            if (ch.changeCase == "u")
260
                                fmtParts[i] = next[0].toUpperCase();
261
                            else
262
                                fmtParts[i] = next[0].toLowerCase();
263
                            fmtParts[i + 1] = next.substr(1);
264
                        }
265
                    } else if (ch.changeCase) {
266
                        gChangeCase = ch.changeCase;
267
                    }
268
                } else if (gChangeCase == "U") {
269
                    fmtParts[i] = ch.toUpperCase();
270
                } else if (gChangeCase == "L") {
271
                    fmtParts[i] = ch.toLowerCase();
272
                }
273
            }
274
            _self.variables.__ = oldArgs;
275
            return fmtParts.join("");
276
        });
277
        return formatted;
278
    };
279
    
280
    this.tmFormatFunction = function(str, ch, editor) {
281
        if (ch.formatFunction == "upcase")
282
            return str.toUpperCase();
283
        if (ch.formatFunction == "downcase")
284
            return str.toLowerCase();
285
        return str;
286
    };
287

    
288
    this.resolveVariables = function(snippet, editor) {
289
        var result = [];
290
        var indentation = "";
291
        var afterNewLine = true;
292
        for (var i = 0; i < snippet.length; i++) {
293
            var ch = snippet[i];
294
            if (typeof ch == "string") {
295
                result.push(ch);
296
                if (ch == "\n") {
297
                    afterNewLine = true;
298
                    indentation = "";
299
                }
300
                else if (afterNewLine) {
301
                    indentation = /^\t*/.exec(ch)[0];
302
                    afterNewLine = /\S/.test(ch);
303
                }
304
                continue;
305
            }
306
            if (!ch)  continue;
307
            afterNewLine = false;
308
            
309
            if (ch.fmtString) {
310
                var j = snippet.indexOf(ch, i + 1);
311
                if (j == -1) j = snippet.length;
312
                ch.fmt = snippet.slice(i + 1, j);
313
                i = j;
314
            }
315
            
316
            if (ch.text) {
317
                var value = this.getVariableValue(editor, ch.text, indentation) + "";
318
                if (ch.fmtString)
319
                    value = this.tmStrFormat(value, ch, editor);
320
                if (ch.formatFunction)
321
                    value = this.tmFormatFunction(value, ch, editor);
322
                
323
                if (value && !ch.ifEnd) {
324
                    result.push(value);
325
                    gotoNext(ch);
326
                } else if (!value && ch.ifEnd) {
327
                    gotoNext(ch.ifEnd);
328
                }
329
            } else if (ch.elseEnd) {
330
                gotoNext(ch.elseEnd);
331
            } else if (ch.tabstopId != null) {
332
                result.push(ch);
333
            } else if (ch.changeCase != null) {
334
                result.push(ch);
335
            }
336
        }
337
        function gotoNext(ch) {
338
            var i1 = snippet.indexOf(ch, i + 1);
339
            if (i1 != -1)
340
                i = i1;
341
        }
342
        return result;
343
    };
344

    
345
    this.insertSnippetForSelection = function(editor, snippetText) {
346
        var cursor = editor.getCursorPosition();
347
        var line = editor.session.getLine(cursor.row);
348
        var tabString = editor.session.getTabString();
349
        var indentString = line.match(/^\s*/)[0];
350
        
351
        if (cursor.column < indentString.length)
352
            indentString = indentString.slice(0, cursor.column);
353

    
354
        snippetText = snippetText.replace(/\r/g, "");
355
        var tokens = this.tokenizeTmSnippet(snippetText);
356
        tokens = this.resolveVariables(tokens, editor);
357
        tokens = tokens.map(function(x) {
358
            if (x == "\n")
359
                return x + indentString;
360
            if (typeof x == "string")
361
                return x.replace(/\t/g, tabString);
362
            return x;
363
        });
364
        var tabstops = [];
365
        tokens.forEach(function(p, i) {
366
            if (typeof p != "object")
367
                return;
368
            var id = p.tabstopId;
369
            var ts = tabstops[id];
370
            if (!ts) {
371
                ts = tabstops[id] = [];
372
                ts.index = id;
373
                ts.value = "";
374
                ts.parents = {};
375
            }
376
            if (ts.indexOf(p) !== -1)
377
                return;
378
            if (p.choices && !ts.choices)
379
                ts.choices = p.choices;
380
            ts.push(p);
381
            var i1 = tokens.indexOf(p, i + 1);
382
            if (i1 === -1)
383
                return;
384

    
385
            var value = tokens.slice(i + 1, i1);
386
            var isNested = value.some(function(t) {return typeof t === "object";});
387
            if (isNested && !ts.value) {
388
                ts.value = value;
389
            } else if (value.length && (!ts.value || typeof ts.value !== "string")) {
390
                ts.value = value.join("");
391
            }
392
        });
393
        tabstops.forEach(function(ts) {ts.length = 0;});
394
        var expanding = {};
395
        function copyValue(val) {
396
            var copy = [];
397
            for (var i = 0; i < val.length; i++) {
398
                var p = val[i];
399
                if (typeof p == "object") {
400
                    if (expanding[p.tabstopId])
401
                        continue;
402
                    var j = val.lastIndexOf(p, i - 1);
403
                    p = copy[j] || {tabstopId: p.tabstopId};
404
                }
405
                copy[i] = p;
406
            }
407
            return copy;
408
        }
409
        for (var i = 0; i < tokens.length; i++) {
410
            var p = tokens[i];
411
            if (typeof p != "object")
412
                continue;
413
            var id = p.tabstopId;
414
            var ts = tabstops[id];
415
            var i1 = tokens.indexOf(p, i + 1);
416
            if (expanding[id]) {
417
                if (expanding[id] === p) {
418
                    delete expanding[id];
419
                    Object.keys(expanding).forEach(function(parentId) {
420
                        ts.parents[parentId] = true;
421
                    });
422
                }
423
                continue;
424
            }
425
            expanding[id] = p;
426
            var value = ts.value;
427
            if (typeof value !== "string")
428
                value = copyValue(value);
429
            else if (p.fmt)
430
                value = this.tmStrFormat(value, p, editor);
431
            tokens.splice.apply(tokens, [i + 1, Math.max(0, i1 - i)].concat(value, p));
432

    
433
            if (ts.indexOf(p) === -1)
434
                ts.push(p);
435
        }
436
        var row = 0, column = 0;
437
        var text = "";
438
        tokens.forEach(function(t) {
439
            if (typeof t === "string") {
440
                var lines = t.split("\n");
441
                if (lines.length > 1){
442
                    column = lines[lines.length - 1].length;
443
                    row += lines.length - 1;
444
                } else
445
                    column += t.length;
446
                text += t;
447
            } else if (t) {
448
                if (!t.start)
449
                    t.start = {row: row, column: column};
450
                else
451
                    t.end = {row: row, column: column};
452
            }
453
        });
454
        var range = editor.getSelectionRange();
455
        var end = editor.session.replace(range, text);
456

    
457
        var tabstopManager = new TabstopManager(editor);
458
        var selectionId = editor.inVirtualSelectionMode && editor.selection.index;
459
        tabstopManager.addTabstops(tabstops, range.start, end, selectionId);
460
    };
461
    
462
    this.insertSnippet = function(editor, snippetText) {
463
        var self = this;
464
        if (editor.inVirtualSelectionMode)
465
            return self.insertSnippetForSelection(editor, snippetText);
466
        
467
        editor.forEachSelection(function() {
468
            self.insertSnippetForSelection(editor, snippetText);
469
        }, null, {keepOrder: true});
470
        
471
        if (editor.tabstopManager)
472
            editor.tabstopManager.tabNext();
473
    };
474

    
475
    this.$getScope = function(editor) {
476
        var scope = editor.session.$mode.$id || "";
477
        scope = scope.split("/").pop();
478
        if (scope === "html" || scope === "php") {
479
            if (scope === "php" && !editor.session.$mode.inlinePhp) 
480
                scope = "html";
481
            var c = editor.getCursorPosition();
482
            var state = editor.session.getState(c.row);
483
            if (typeof state === "object") {
484
                state = state[0];
485
            }
486
            if (state.substring) {
487
                if (state.substring(0, 3) == "js-")
488
                    scope = "javascript";
489
                else if (state.substring(0, 4) == "css-")
490
                    scope = "css";
491
                else if (state.substring(0, 4) == "php-")
492
                    scope = "php";
493
            }
494
        }
495
        
496
        return scope;
497
    };
498

    
499
    this.getActiveScopes = function(editor) {
500
        var scope = this.$getScope(editor);
501
        var scopes = [scope];
502
        var snippetMap = this.snippetMap;
503
        if (snippetMap[scope] && snippetMap[scope].includeScopes) {
504
            scopes.push.apply(scopes, snippetMap[scope].includeScopes);
505
        }
506
        scopes.push("_");
507
        return scopes;
508
    };
509

    
510
    this.expandWithTab = function(editor, options) {
511
        var self = this;
512
        var result = editor.forEachSelection(function() {
513
            return self.expandSnippetForSelection(editor, options);
514
        }, null, {keepOrder: true});
515
        if (result && editor.tabstopManager)
516
            editor.tabstopManager.tabNext();
517
        return result;
518
    };
519
    
520
    this.expandSnippetForSelection = function(editor, options) {
521
        var cursor = editor.getCursorPosition();
522
        var line = editor.session.getLine(cursor.row);
523
        var before = line.substring(0, cursor.column);
524
        var after = line.substr(cursor.column);
525

    
526
        var snippetMap = this.snippetMap;
527
        var snippet;
528
        this.getActiveScopes(editor).some(function(scope) {
529
            var snippets = snippetMap[scope];
530
            if (snippets)
531
                snippet = this.findMatchingSnippet(snippets, before, after);
532
            return !!snippet;
533
        }, this);
534
        if (!snippet)
535
            return false;
536
        if (options && options.dryRun)
537
            return true;
538
        editor.session.doc.removeInLine(cursor.row,
539
            cursor.column - snippet.replaceBefore.length,
540
            cursor.column + snippet.replaceAfter.length
541
        );
542

    
543
        this.variables.M__ = snippet.matchBefore;
544
        this.variables.T__ = snippet.matchAfter;
545
        this.insertSnippetForSelection(editor, snippet.content);
546

    
547
        this.variables.M__ = this.variables.T__ = null;
548
        return true;
549
    };
550

    
551
    this.findMatchingSnippet = function(snippetList, before, after) {
552
        for (var i = snippetList.length; i--;) {
553
            var s = snippetList[i];
554
            if (s.startRe && !s.startRe.test(before))
555
                continue;
556
            if (s.endRe && !s.endRe.test(after))
557
                continue;
558
            if (!s.startRe && !s.endRe)
559
                continue;
560

    
561
            s.matchBefore = s.startRe ? s.startRe.exec(before) : [""];
562
            s.matchAfter = s.endRe ? s.endRe.exec(after) : [""];
563
            s.replaceBefore = s.triggerRe ? s.triggerRe.exec(before)[0] : "";
564
            s.replaceAfter = s.endTriggerRe ? s.endTriggerRe.exec(after)[0] : "";
565
            return s;
566
        }
567
    };
568

    
569
    this.snippetMap = {};
570
    this.snippetNameMap = {};
571
    this.register = function(snippets, scope) {
572
        var snippetMap = this.snippetMap;
573
        var snippetNameMap = this.snippetNameMap;
574
        var self = this;
575
        
576
        if (!snippets) 
577
            snippets = [];
578
        
579
        function wrapRegexp(src) {
580
            if (src && !/^\^?\(.*\)\$?$|^\\b$/.test(src))
581
                src = "(?:" + src + ")";
582

    
583
            return src || "";
584
        }
585
        function guardedRegexp(re, guard, opening) {
586
            re = wrapRegexp(re);
587
            guard = wrapRegexp(guard);
588
            if (opening) {
589
                re = guard + re;
590
                if (re && re[re.length - 1] != "$")
591
                    re = re + "$";
592
            } else {
593
                re = re + guard;
594
                if (re && re[0] != "^")
595
                    re = "^" + re;
596
            }
597
            return new RegExp(re);
598
        }
599

    
600
        function addSnippet(s) {
601
            if (!s.scope)
602
                s.scope = scope || "_";
603
            scope = s.scope;
604
            if (!snippetMap[scope]) {
605
                snippetMap[scope] = [];
606
                snippetNameMap[scope] = {};
607
            }
608

    
609
            var map = snippetNameMap[scope];
610
            if (s.name) {
611
                var old = map[s.name];
612
                if (old)
613
                    self.unregister(old);
614
                map[s.name] = s;
615
            }
616
            snippetMap[scope].push(s);
617

    
618
            if (s.prefix)
619
                s.tabTrigger = s.prefix;
620

    
621
            if (!s.content && s.body)
622
                s.content = Array.isArray(s.body) ? s.body.join("\n") : s.body;
623

    
624
            if (s.tabTrigger && !s.trigger) {
625
                if (!s.guard && /^\w/.test(s.tabTrigger))
626
                    s.guard = "\\b";
627
                s.trigger = lang.escapeRegExp(s.tabTrigger);
628
            }
629
            
630
            if (!s.trigger && !s.guard && !s.endTrigger && !s.endGuard)
631
                return;
632
            
633
            s.startRe = guardedRegexp(s.trigger, s.guard, true);
634
            s.triggerRe = new RegExp(s.trigger);
635

    
636
            s.endRe = guardedRegexp(s.endTrigger, s.endGuard, true);
637
            s.endTriggerRe = new RegExp(s.endTrigger);
638
        }
639

    
640
        if (Array.isArray(snippets)) {
641
            snippets.forEach(addSnippet);
642
        } else {
643
            Object.keys(snippets).forEach(function(key) {
644
                addSnippet(snippets[key]);
645
            });
646
        }
647
        
648
        this._signal("registerSnippets", {scope: scope});
649
    };
650
    this.unregister = function(snippets, scope) {
651
        var snippetMap = this.snippetMap;
652
        var snippetNameMap = this.snippetNameMap;
653

    
654
        function removeSnippet(s) {
655
            var nameMap = snippetNameMap[s.scope||scope];
656
            if (nameMap && nameMap[s.name]) {
657
                delete nameMap[s.name];
658
                var map = snippetMap[s.scope||scope];
659
                var i = map && map.indexOf(s);
660
                if (i >= 0)
661
                    map.splice(i, 1);
662
            }
663
        }
664
        if (snippets.content)
665
            removeSnippet(snippets);
666
        else if (Array.isArray(snippets))
667
            snippets.forEach(removeSnippet);
668
    };
669
    this.parseSnippetFile = function(str) {
670
        str = str.replace(/\r/g, "");
671
        var list = [], snippet = {};
672
        var re = /^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;
673
        var m;
674
        while (m = re.exec(str)) {
675
            if (m[1]) {
676
                try {
677
                    snippet = JSON.parse(m[1]);
678
                    list.push(snippet);
679
                } catch (e) {}
680
            } if (m[4]) {
681
                snippet.content = m[4].replace(/^\t/gm, "");
682
                list.push(snippet);
683
                snippet = {};
684
            } else {
685
                var key = m[2], val = m[3];
686
                if (key == "regex") {
687
                    var guardRe = /\/((?:[^\/\\]|\\.)*)|$/g;
688
                    snippet.guard = guardRe.exec(val)[1];
689
                    snippet.trigger = guardRe.exec(val)[1];
690
                    snippet.endTrigger = guardRe.exec(val)[1];
691
                    snippet.endGuard = guardRe.exec(val)[1];
692
                } else if (key == "snippet") {
693
                    snippet.tabTrigger = val.match(/^\S*/)[0];
694
                    if (!snippet.name)
695
                        snippet.name = val;
696
                } else if (key) {
697
                    snippet[key] = val;
698
                }
699
            }
700
        }
701
        return list;
702
    };
703
    this.getSnippetByName = function(name, editor) {
704
        var snippetMap = this.snippetNameMap;
705
        var snippet;
706
        this.getActiveScopes(editor).some(function(scope) {
707
            var snippets = snippetMap[scope];
708
            if (snippets)
709
                snippet = snippets[name];
710
            return !!snippet;
711
        }, this);
712
        return snippet;
713
    };
714

    
715
}).call(SnippetManager.prototype);
716

    
717

    
718
var TabstopManager = function(editor) {
719
    if (editor.tabstopManager)
720
        return editor.tabstopManager;
721
    editor.tabstopManager = this;
722
    this.$onChange = this.onChange.bind(this);
723
    this.$onChangeSelection = lang.delayedCall(this.onChangeSelection.bind(this)).schedule;
724
    this.$onChangeSession = this.onChangeSession.bind(this);
725
    this.$onAfterExec = this.onAfterExec.bind(this);
726
    this.attach(editor);
727
};
728
(function() {
729
    this.attach = function(editor) {
730
        this.index = 0;
731
        this.ranges = [];
732
        this.tabstops = [];
733
        this.$openTabstops = null;
734
        this.selectedTabstop = null;
735

    
736
        this.editor = editor;
737
        this.editor.on("change", this.$onChange);
738
        this.editor.on("changeSelection", this.$onChangeSelection);
739
        this.editor.on("changeSession", this.$onChangeSession);
740
        this.editor.commands.on("afterExec", this.$onAfterExec);
741
        this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
742
    };
743
    this.detach = function() {
744
        this.tabstops.forEach(this.removeTabstopMarkers, this);
745
        this.ranges = null;
746
        this.tabstops = null;
747
        this.selectedTabstop = null;
748
        this.editor.removeListener("change", this.$onChange);
749
        this.editor.removeListener("changeSelection", this.$onChangeSelection);
750
        this.editor.removeListener("changeSession", this.$onChangeSession);
751
        this.editor.commands.removeListener("afterExec", this.$onAfterExec);
752
        this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
753
        this.editor.tabstopManager = null;
754
        this.editor = null;
755
    };
756

    
757
    this.onChange = function(delta) {
758
        var isRemove = delta.action[0] == "r";
759
        var selectedTabstop = this.selectedTabstop || {};
760
        var parents = selectedTabstop.parents || {};
761
        var tabstops = (this.tabstops || []).slice();
762
        for (var i = 0; i < tabstops.length; i++) {
763
            var ts = tabstops[i];
764
            var active = ts == selectedTabstop || parents[ts.index];
765
            ts.rangeList.$bias = active ? 0 : 1;
766
            
767
            if (delta.action == "remove" && ts !== selectedTabstop) {
768
                var parentActive = ts.parents && ts.parents[selectedTabstop.index];
769
                var startIndex = ts.rangeList.pointIndex(delta.start, parentActive);
770
                startIndex = startIndex < 0 ? -startIndex - 1 : startIndex + 1;
771
                var endIndex = ts.rangeList.pointIndex(delta.end, parentActive);
772
                endIndex = endIndex < 0 ? -endIndex - 1 : endIndex - 1;
773
                var toRemove = ts.rangeList.ranges.slice(startIndex, endIndex);
774
                for (var j = 0; j < toRemove.length; j++)
775
                    this.removeRange(toRemove[j]);
776
            }
777
            ts.rangeList.$onChange(delta);
778
        }
779
        var session = this.editor.session;
780
        if (!this.$inChange && isRemove && session.getLength() == 1 && !session.getValue())
781
            this.detach();
782
    };
783
    this.updateLinkedFields = function() {
784
        var ts = this.selectedTabstop;
785
        if (!ts || !ts.hasLinkedRanges || !ts.firstNonLinked)
786
            return;
787
        this.$inChange = true;
788
        var session = this.editor.session;
789
        var text = session.getTextRange(ts.firstNonLinked);
790
        for (var i = 0; i < ts.length; i++) {
791
            var range = ts[i];
792
            if (!range.linked)
793
                continue;
794
            var original = range.original;
795
            var fmt = exports.snippetManager.tmStrFormat(text, original, this.editor);
796
            session.replace(range, fmt);
797
        }
798
        this.$inChange = false;
799
    };
800
    this.onAfterExec = function(e) {
801
        if (e.command && !e.command.readOnly)
802
            this.updateLinkedFields();
803
    };
804
    this.onChangeSelection = function() {
805
        if (!this.editor)
806
            return;
807
        var lead = this.editor.selection.lead;
808
        var anchor = this.editor.selection.anchor;
809
        var isEmpty = this.editor.selection.isEmpty();
810
        for (var i = 0; i < this.ranges.length; i++) {
811
            if (this.ranges[i].linked)
812
                continue;
813
            var containsLead = this.ranges[i].contains(lead.row, lead.column);
814
            var containsAnchor = isEmpty || this.ranges[i].contains(anchor.row, anchor.column);
815
            if (containsLead && containsAnchor)
816
                return;
817
        }
818
        this.detach();
819
    };
820
    this.onChangeSession = function() {
821
        this.detach();
822
    };
823
    this.tabNext = function(dir) {
824
        var max = this.tabstops.length;
825
        var index = this.index + (dir || 1);
826
        index = Math.min(Math.max(index, 1), max);
827
        if (index == max)
828
            index = 0;
829
        this.selectTabstop(index);
830
        if (index === 0)
831
            this.detach();
832
    };
833
    this.selectTabstop = function(index) {
834
        this.$openTabstops = null;
835
        var ts = this.tabstops[this.index];
836
        if (ts)
837
            this.addTabstopMarkers(ts);
838
        this.index = index;
839
        ts = this.tabstops[this.index];
840
        if (!ts || !ts.length)
841
            return;
842
        
843
        this.selectedTabstop = ts;
844
        var range = ts.firstNonLinked || ts;
845
        if (!this.editor.inVirtualSelectionMode) {
846
            var sel = this.editor.multiSelect;
847
            sel.toSingleRange(range.clone());
848
            for (var i = 0; i < ts.length; i++) {
849
                if (ts.hasLinkedRanges && ts[i].linked)
850
                    continue;
851
                sel.addRange(ts[i].clone(), true);
852
            }
853
            if (sel.ranges[0])
854
                sel.addRange(sel.ranges[0].clone());
855
        } else {
856
            this.editor.selection.setRange(range);
857
        }
858
        
859
        this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
860
        if (this.selectedTabstop && this.selectedTabstop.choices)
861
            this.editor.execCommand("startAutocomplete", {matches: this.selectedTabstop.choices});
862
    };
863
    this.addTabstops = function(tabstops, start, end) {
864
        var useLink = this.useLink || !this.editor.getOption("enableMultiselect");
865
        
866
        if (!this.$openTabstops)
867
            this.$openTabstops = [];
868
        if (!tabstops[0]) {
869
            var p = Range.fromPoints(end, end);
870
            moveRelative(p.start, start);
871
            moveRelative(p.end, start);
872
            tabstops[0] = [p];
873
            tabstops[0].index = 0;
874
        }
875

    
876
        var i = this.index;
877
        var arg = [i + 1, 0];
878
        var ranges = this.ranges;
879
        tabstops.forEach(function(ts, index) {
880
            var dest = this.$openTabstops[index] || ts;
881
            
882
            for (var i = 0; i < ts.length; i++) {
883
                var p = ts[i];
884
                var range = Range.fromPoints(p.start, p.end || p.start);
885
                movePoint(range.start, start);
886
                movePoint(range.end, start);
887
                range.original = p;
888
                range.tabstop = dest;
889
                ranges.push(range);
890
                if (dest != ts)
891
                    dest.unshift(range);
892
                else
893
                    dest[i] = range;
894
                if (p.fmtString || (dest.firstNonLinked && useLink)) {
895
                    range.linked = true;
896
                    dest.hasLinkedRanges = true;
897
                } else if (!dest.firstNonLinked)
898
                    dest.firstNonLinked = range;
899
            }
900
            if (!dest.firstNonLinked)
901
                dest.hasLinkedRanges = false;
902
            if (dest === ts) {
903
                arg.push(dest);
904
                this.$openTabstops[index] = dest;
905
            }
906
            this.addTabstopMarkers(dest);
907
            dest.rangeList = dest.rangeList || new RangeList();
908
            dest.rangeList.$bias = 0;
909
            dest.rangeList.addList(dest);
910
        }, this);
911
        
912
        if (arg.length > 2) {
913
            if (this.tabstops.length)
914
                arg.push(arg.splice(2, 1)[0]);
915
            this.tabstops.splice.apply(this.tabstops, arg);
916
        }
917
    };
918

    
919
    this.addTabstopMarkers = function(ts) {
920
        var session = this.editor.session;
921
        ts.forEach(function(range) {
922
            if  (!range.markerId)
923
                range.markerId = session.addMarker(range, "ace_snippet-marker", "text");
924
        });
925
    };
926
    this.removeTabstopMarkers = function(ts) {
927
        var session = this.editor.session;
928
        ts.forEach(function(range) {
929
            session.removeMarker(range.markerId);
930
            range.markerId = null;
931
        });
932
    };
933
    this.removeRange = function(range) {
934
        var i = range.tabstop.indexOf(range);
935
        if (i != -1) range.tabstop.splice(i, 1);
936
        i = this.ranges.indexOf(range);
937
        if (i != -1) this.ranges.splice(i, 1);
938
        i = range.tabstop.rangeList.ranges.indexOf(range);
939
        if (i != -1) range.tabstop.splice(i, 1);
940
        this.editor.session.removeMarker(range.markerId);
941
        if (!range.tabstop.length) {
942
            i = this.tabstops.indexOf(range.tabstop);
943
            if (i != -1)
944
                this.tabstops.splice(i, 1);
945
            if (!this.tabstops.length)
946
                this.detach();
947
        }
948
    };
949

    
950
    this.keyboardHandler = new HashHandler();
951
    this.keyboardHandler.bindKeys({
952
        "Tab": function(editor) {
953
            if (exports.snippetManager && exports.snippetManager.expandWithTab(editor))
954
                return;
955
            editor.tabstopManager.tabNext(1);
956
            editor.renderer.scrollCursorIntoView();
957
        },
958
        "Shift-Tab": function(editor) {
959
            editor.tabstopManager.tabNext(-1);
960
            editor.renderer.scrollCursorIntoView();
961
        },
962
        "Esc": function(editor) {
963
            editor.tabstopManager.detach();
964
        }
965
    });
966
}).call(TabstopManager.prototype);
967

    
968

    
969

    
970
var movePoint = function(point, diff) {
971
    if (point.row == 0)
972
        point.column += diff.column;
973
    point.row += diff.row;
974
};
975

    
976
var moveRelative = function(point, start) {
977
    if (point.row == start.row)
978
        point.column -= start.column;
979
    point.row -= start.row;
980
};
981

    
982

    
983
require("./lib/dom").importCssString("\
984
.ace_snippet-marker {\
985
    -moz-box-sizing: border-box;\
986
    box-sizing: border-box;\
987
    background: rgba(194, 193, 208, 0.09);\
988
    border: 1px dotted rgba(211, 208, 235, 0.62);\
989
    position: absolute;\
990
}");
991

    
992
exports.snippetManager = new SnippetManager();
993

    
994

    
995
var Editor = require("./editor").Editor;
996
(function() {
997
    this.insertSnippet = function(content, options) {
998
        return exports.snippetManager.insertSnippet(this, content, options);
999
    };
1000
    this.expandSnippet = function(options) {
1001
        return exports.snippetManager.expandWithTab(this, options);
1002
    };
1003
}).call(Editor.prototype);
1004

    
1005
});
1006

    
1007
ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"], function(require, exports, module) {
1008
"use strict";
1009

    
1010
var Renderer = require("../virtual_renderer").VirtualRenderer;
1011
var Editor = require("../editor").Editor;
1012
var Range = require("../range").Range;
1013
var event = require("../lib/event");
1014
var lang = require("../lib/lang");
1015
var dom = require("../lib/dom");
1016

    
1017
var $singleLineEditor = function(el) {
1018
    var renderer = new Renderer(el);
1019

    
1020
    renderer.$maxLines = 4;
1021

    
1022
    var editor = new Editor(renderer);
1023

    
1024
    editor.setHighlightActiveLine(false);
1025
    editor.setShowPrintMargin(false);
1026
    editor.renderer.setShowGutter(false);
1027
    editor.renderer.setHighlightGutterLine(false);
1028

    
1029
    editor.$mouseHandler.$focusTimeout = 0;
1030
    editor.$highlightTagPending = true;
1031

    
1032
    return editor;
1033
};
1034

    
1035
var AcePopup = function(parentNode) {
1036
    var el = dom.createElement("div");
1037
    var popup = new $singleLineEditor(el);
1038

    
1039
    if (parentNode)
1040
        parentNode.appendChild(el);
1041
    el.style.display = "none";
1042
    popup.renderer.content.style.cursor = "default";
1043
    popup.renderer.setStyle("ace_autocomplete");
1044

    
1045
    popup.setOption("displayIndentGuides", false);
1046
    popup.setOption("dragDelay", 150);
1047

    
1048
    var noop = function(){};
1049

    
1050
    popup.focus = noop;
1051
    popup.$isFocused = true;
1052

    
1053
    popup.renderer.$cursorLayer.restartTimer = noop;
1054
    popup.renderer.$cursorLayer.element.style.opacity = 0;
1055

    
1056
    popup.renderer.$maxLines = 8;
1057
    popup.renderer.$keepTextAreaAtCursor = false;
1058

    
1059
    popup.setHighlightActiveLine(false);
1060
    popup.session.highlight("");
1061
    popup.session.$searchHighlight.clazz = "ace_highlight-marker";
1062

    
1063
    popup.on("mousedown", function(e) {
1064
        var pos = e.getDocumentPosition();
1065
        popup.selection.moveToPosition(pos);
1066
        selectionMarker.start.row = selectionMarker.end.row = pos.row;
1067
        e.stop();
1068
    });
1069

    
1070
    var lastMouseEvent;
1071
    var hoverMarker = new Range(-1,0,-1,Infinity);
1072
    var selectionMarker = new Range(-1,0,-1,Infinity);
1073
    selectionMarker.id = popup.session.addMarker(selectionMarker, "ace_active-line", "fullLine");
1074
    popup.setSelectOnHover = function(val) {
1075
        if (!val) {
1076
            hoverMarker.id = popup.session.addMarker(hoverMarker, "ace_line-hover", "fullLine");
1077
        } else if (hoverMarker.id) {
1078
            popup.session.removeMarker(hoverMarker.id);
1079
            hoverMarker.id = null;
1080
        }
1081
    };
1082
    popup.setSelectOnHover(false);
1083
    popup.on("mousemove", function(e) {
1084
        if (!lastMouseEvent) {
1085
            lastMouseEvent = e;
1086
            return;
1087
        }
1088
        if (lastMouseEvent.x == e.x && lastMouseEvent.y == e.y) {
1089
            return;
1090
        }
1091
        lastMouseEvent = e;
1092
        lastMouseEvent.scrollTop = popup.renderer.scrollTop;
1093
        var row = lastMouseEvent.getDocumentPosition().row;
1094
        if (hoverMarker.start.row != row) {
1095
            if (!hoverMarker.id)
1096
                popup.setRow(row);
1097
            setHoverMarker(row);
1098
        }
1099
    });
1100
    popup.renderer.on("beforeRender", function() {
1101
        if (lastMouseEvent && hoverMarker.start.row != -1) {
1102
            lastMouseEvent.$pos = null;
1103
            var row = lastMouseEvent.getDocumentPosition().row;
1104
            if (!hoverMarker.id)
1105
                popup.setRow(row);
1106
            setHoverMarker(row, true);
1107
        }
1108
    });
1109
    popup.renderer.on("afterRender", function() {
1110
        var row = popup.getRow();
1111
        var t = popup.renderer.$textLayer;
1112
        var selected = t.element.childNodes[row - t.config.firstRow];
1113
        if (selected !== t.selectedNode && t.selectedNode)
1114
            dom.removeCssClass(t.selectedNode, "ace_selected");
1115
        t.selectedNode = selected;
1116
        if (selected)
1117
            dom.addCssClass(selected, "ace_selected");
1118
    });
1119
    var hideHoverMarker = function() { setHoverMarker(-1); };
1120
    var setHoverMarker = function(row, suppressRedraw) {
1121
        if (row !== hoverMarker.start.row) {
1122
            hoverMarker.start.row = hoverMarker.end.row = row;
1123
            if (!suppressRedraw)
1124
                popup.session._emit("changeBackMarker");
1125
            popup._emit("changeHoverMarker");
1126
        }
1127
    };
1128
    popup.getHoveredRow = function() {
1129
        return hoverMarker.start.row;
1130
    };
1131

    
1132
    event.addListener(popup.container, "mouseout", hideHoverMarker);
1133
    popup.on("hide", hideHoverMarker);
1134
    popup.on("changeSelection", hideHoverMarker);
1135

    
1136
    popup.session.doc.getLength = function() {
1137
        return popup.data.length;
1138
    };
1139
    popup.session.doc.getLine = function(i) {
1140
        var data = popup.data[i];
1141
        if (typeof data == "string")
1142
            return data;
1143
        return (data && data.value) || "";
1144
    };
1145

    
1146
    var bgTokenizer = popup.session.bgTokenizer;
1147
    bgTokenizer.$tokenizeRow = function(row) {
1148
        var data = popup.data[row];
1149
        var tokens = [];
1150
        if (!data)
1151
            return tokens;
1152
        if (typeof data == "string")
1153
            data = {value: data};
1154
        var caption = data.caption || data.value || data.name;
1155

    
1156
        function addToken(value, className) {
1157
            value && tokens.push({
1158
                type: (data.className || "") + (className || ""), 
1159
                value: value
1160
            });
1161
        }
1162
        
1163
        var lower = caption.toLowerCase();
1164
        var filterText = (popup.filterText || "").toLowerCase();
1165
        var lastIndex = 0;
1166
        var lastI = 0;
1167
        for (var i = 0; i <= filterText.length; i++) {
1168
            if (i != lastI && (data.matchMask & (1 << i) || i == filterText.length)) {
1169
                var sub = filterText.slice(lastI, i);
1170
                lastI = i;
1171
                var index = lower.indexOf(sub, lastIndex);
1172
                if (index == -1) continue;
1173
                addToken(caption.slice(lastIndex, index), "");
1174
                lastIndex = index + sub.length;
1175
                addToken(caption.slice(index, lastIndex), "completion-highlight");
1176
            }
1177
        }
1178
        addToken(caption.slice(lastIndex, caption.length), "");
1179
        
1180
        if (data.meta)
1181
            tokens.push({type: "completion-meta", value: data.meta});
1182
        if (data.message)
1183
            tokens.push({type: "completion-message", value: data.message});
1184

    
1185
        return tokens;
1186
    };
1187
    bgTokenizer.$updateOnChange = noop;
1188
    bgTokenizer.start = noop;
1189

    
1190
    popup.session.$computeWidth = function() {
1191
        return this.screenWidth = 0;
1192
    };
1193
    popup.isOpen = false;
1194
    popup.isTopdown = false;
1195
    popup.autoSelect = true;
1196
    popup.filterText = "";
1197

    
1198
    popup.data = [];
1199
    popup.setData = function(list, filterText) {
1200
        popup.filterText = filterText || "";
1201
        popup.setValue(lang.stringRepeat("\n", list.length), -1);
1202
        popup.data = list || [];
1203
        popup.setRow(0);
1204
    };
1205
    popup.getData = function(row) {
1206
        return popup.data[row];
1207
    };
1208

    
1209
    popup.getRow = function() {
1210
        return selectionMarker.start.row;
1211
    };
1212
    popup.setRow = function(line) {
1213
        line = Math.max(this.autoSelect ? 0 : -1, Math.min(this.data.length, line));
1214
        if (selectionMarker.start.row != line) {
1215
            popup.selection.clearSelection();
1216
            selectionMarker.start.row = selectionMarker.end.row = line || 0;
1217
            popup.session._emit("changeBackMarker");
1218
            popup.moveCursorTo(line || 0, 0);
1219
            if (popup.isOpen)
1220
                popup._signal("select");
1221
        }
1222
    };
1223

    
1224
    popup.on("changeSelection", function() {
1225
        if (popup.isOpen)
1226
            popup.setRow(popup.selection.lead.row);
1227
        popup.renderer.scrollCursorIntoView();
1228
    });
1229

    
1230
    popup.hide = function() {
1231
        this.container.style.display = "none";
1232
        this._signal("hide");
1233
        popup.isOpen = false;
1234
    };
1235
    popup.show = function(pos, lineHeight, topdownOnly) {
1236
        var el = this.container;
1237
        var screenHeight = window.innerHeight;
1238
        var screenWidth = window.innerWidth;
1239
        var renderer = this.renderer;
1240
        var maxH = renderer.$maxLines * lineHeight * 1.4;
1241
        var top = pos.top + this.$borderSize;
1242
        var allowTopdown = top > screenHeight / 2 && !topdownOnly;
1243
        if (allowTopdown && top + lineHeight + maxH > screenHeight) {
1244
            renderer.$maxPixelHeight = top - 2 * this.$borderSize;
1245
            el.style.top = "";
1246
            el.style.bottom = screenHeight - top + "px";
1247
            popup.isTopdown = false;
1248
        } else {
1249
            top += lineHeight;
1250
            renderer.$maxPixelHeight = screenHeight - top - 0.2 * lineHeight;
1251
            el.style.top = top + "px";
1252
            el.style.bottom = "";
1253
            popup.isTopdown = true;
1254
        }
1255

    
1256
        el.style.display = "";
1257

    
1258
        var left = pos.left;
1259
        if (left + el.offsetWidth > screenWidth)
1260
            left = screenWidth - el.offsetWidth;
1261

    
1262
        el.style.left = left + "px";
1263

    
1264
        this._signal("show");
1265
        lastMouseEvent = null;
1266
        popup.isOpen = true;
1267
    };
1268

    
1269
    popup.goTo = function(where) {
1270
        var row = this.getRow();
1271
        var max = this.session.getLength() - 1;
1272

    
1273
        switch(where) {
1274
            case "up": row = row <= 0 ? max : row - 1; break;
1275
            case "down": row = row >= max ? -1 : row + 1; break;
1276
            case "start": row = 0; break;
1277
            case "end": row = max; break;
1278
        }
1279

    
1280
        this.setRow(row);
1281
    };
1282

    
1283

    
1284
    popup.getTextLeftOffset = function() {
1285
        return this.$borderSize + this.renderer.$padding + this.$imageSize;
1286
    };
1287

    
1288
    popup.$imageSize = 0;
1289
    popup.$borderSize = 1;
1290

    
1291
    return popup;
1292
};
1293

    
1294
dom.importCssString("\
1295
.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\
1296
    background-color: #CAD6FA;\
1297
    z-index: 1;\
1298
}\
1299
.ace_dark.ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line {\
1300
    background-color: #3a674e;\
1301
}\
1302
.ace_editor.ace_autocomplete .ace_line-hover {\
1303
    border: 1px solid #abbffe;\
1304
    margin-top: -1px;\
1305
    background: rgba(233,233,253,0.4);\
1306
    position: absolute;\
1307
    z-index: 2;\
1308
}\
1309
.ace_dark.ace_editor.ace_autocomplete .ace_line-hover {\
1310
    border: 1px solid rgba(109, 150, 13, 0.8);\
1311
    background: rgba(58, 103, 78, 0.62);\
1312
}\
1313
.ace_completion-meta {\
1314
    opacity: 0.5;\
1315
    margin: 0.9em;\
1316
}\
1317
.ace_completion-message {\
1318
    color: blue;\
1319
}\
1320
.ace_editor.ace_autocomplete .ace_completion-highlight{\
1321
    color: #2d69c7;\
1322
}\
1323
.ace_dark.ace_editor.ace_autocomplete .ace_completion-highlight{\
1324
    color: #93ca12;\
1325
}\
1326
.ace_editor.ace_autocomplete {\
1327
    width: 300px;\
1328
    z-index: 200000;\
1329
    border: 1px lightgray solid;\
1330
    position: fixed;\
1331
    box-shadow: 2px 3px 5px rgba(0,0,0,.2);\
1332
    line-height: 1.4;\
1333
    background: #fefefe;\
1334
    color: #111;\
1335
}\
1336
.ace_dark.ace_editor.ace_autocomplete {\
1337
    border: 1px #484747 solid;\
1338
    box-shadow: 2px 3px 5px rgba(0, 0, 0, 0.51);\
1339
    line-height: 1.4;\
1340
    background: #25282c;\
1341
    color: #c1c1c1;\
1342
}", "autocompletion.css");
1343

    
1344
exports.AcePopup = AcePopup;
1345
exports.$singleLineEditor = $singleLineEditor;
1346
});
1347

    
1348
ace.define("ace/autocomplete/util",["require","exports","module"], function(require, exports, module) {
1349
"use strict";
1350

    
1351
exports.parForEach = function(array, fn, callback) {
1352
    var completed = 0;
1353
    var arLength = array.length;
1354
    if (arLength === 0)
1355
        callback();
1356
    for (var i = 0; i < arLength; i++) {
1357
        fn(array[i], function(result, err) {
1358
            completed++;
1359
            if (completed === arLength)
1360
                callback(result, err);
1361
        });
1362
    }
1363
};
1364

    
1365
var ID_REGEX = /[a-zA-Z_0-9\$\-\u00A2-\u2000\u2070-\uFFFF]/;
1366

    
1367
exports.retrievePrecedingIdentifier = function(text, pos, regex) {
1368
    regex = regex || ID_REGEX;
1369
    var buf = [];
1370
    for (var i = pos-1; i >= 0; i--) {
1371
        if (regex.test(text[i]))
1372
            buf.push(text[i]);
1373
        else
1374
            break;
1375
    }
1376
    return buf.reverse().join("");
1377
};
1378

    
1379
exports.retrieveFollowingIdentifier = function(text, pos, regex) {
1380
    regex = regex || ID_REGEX;
1381
    var buf = [];
1382
    for (var i = pos; i < text.length; i++) {
1383
        if (regex.test(text[i]))
1384
            buf.push(text[i]);
1385
        else
1386
            break;
1387
    }
1388
    return buf;
1389
};
1390

    
1391
exports.getCompletionPrefix = function (editor) {
1392
    var pos = editor.getCursorPosition();
1393
    var line = editor.session.getLine(pos.row);
1394
    var prefix;
1395
    editor.completers.forEach(function(completer) {
1396
        if (completer.identifierRegexps) {
1397
            completer.identifierRegexps.forEach(function(identifierRegex) {
1398
                if (!prefix && identifierRegex)
1399
                    prefix = this.retrievePrecedingIdentifier(line, pos.column, identifierRegex);
1400
            }.bind(this));
1401
        }
1402
    }.bind(this));
1403
    return prefix || this.retrievePrecedingIdentifier(line, pos.column);
1404
};
1405

    
1406
});
1407

    
1408
ace.define("ace/autocomplete",["require","exports","module","ace/keyboard/hash_handler","ace/autocomplete/popup","ace/autocomplete/util","ace/lib/lang","ace/lib/dom","ace/snippets","ace/config"], function(require, exports, module) {
1409
"use strict";
1410

    
1411
var HashHandler = require("./keyboard/hash_handler").HashHandler;
1412
var AcePopup = require("./autocomplete/popup").AcePopup;
1413
var util = require("./autocomplete/util");
1414
var lang = require("./lib/lang");
1415
var dom = require("./lib/dom");
1416
var snippetManager = require("./snippets").snippetManager;
1417
var config = require("./config");
1418

    
1419
var Autocomplete = function() {
1420
    this.autoInsert = false;
1421
    this.autoSelect = true;
1422
    this.exactMatch = false;
1423
    this.gatherCompletionsId = 0;
1424
    this.keyboardHandler = new HashHandler();
1425
    this.keyboardHandler.bindKeys(this.commands);
1426

    
1427
    this.blurListener = this.blurListener.bind(this);
1428
    this.changeListener = this.changeListener.bind(this);
1429
    this.mousedownListener = this.mousedownListener.bind(this);
1430
    this.mousewheelListener = this.mousewheelListener.bind(this);
1431

    
1432
    this.changeTimer = lang.delayedCall(function() {
1433
        this.updateCompletions(true);
1434
    }.bind(this));
1435

    
1436
    this.tooltipTimer = lang.delayedCall(this.updateDocTooltip.bind(this), 50);
1437
};
1438

    
1439
(function() {
1440

    
1441
    this.$init = function() {
1442
        this.popup = new AcePopup(document.body || document.documentElement);
1443
        this.popup.on("click", function(e) {
1444
            this.insertMatch();
1445
            e.stop();
1446
        }.bind(this));
1447
        this.popup.focus = this.editor.focus.bind(this.editor);
1448
        this.popup.on("show", this.tooltipTimer.bind(null, null));
1449
        this.popup.on("select", this.tooltipTimer.bind(null, null));
1450
        this.popup.on("changeHoverMarker", this.tooltipTimer.bind(null, null));
1451
        return this.popup;
1452
    };
1453

    
1454
    this.getPopup = function() {
1455
        return this.popup || this.$init();
1456
    };
1457

    
1458
    this.openPopup = function(editor, prefix, keepPopupPosition) {
1459
        if (!this.popup)
1460
            this.$init();
1461

    
1462
        this.popup.autoSelect = this.autoSelect;
1463

    
1464
        this.popup.setData(this.completions.filtered, this.completions.filterText);
1465

    
1466
        editor.keyBinding.addKeyboardHandler(this.keyboardHandler);
1467
        
1468
        var renderer = editor.renderer;
1469
        this.popup.setRow(this.autoSelect ? 0 : -1);
1470
        if (!keepPopupPosition) {
1471
            this.popup.setTheme(editor.getTheme());
1472
            this.popup.setFontSize(editor.getFontSize());
1473

    
1474
            var lineHeight = renderer.layerConfig.lineHeight;
1475

    
1476
            var pos = renderer.$cursorLayer.getPixelPosition(this.base, true);
1477
            pos.left -= this.popup.getTextLeftOffset();
1478

    
1479
            var rect = editor.container.getBoundingClientRect();
1480
            pos.top += rect.top - renderer.layerConfig.offset;
1481
            pos.left += rect.left - editor.renderer.scrollLeft;
1482
            pos.left += renderer.gutterWidth;
1483

    
1484
            this.popup.show(pos, lineHeight);
1485
        } else if (keepPopupPosition && !prefix) {
1486
            this.detach();
1487
        }
1488
    };
1489

    
1490
    this.detach = function() {
1491
        this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler);
1492
        this.editor.off("changeSelection", this.changeListener);
1493
        this.editor.off("blur", this.blurListener);
1494
        this.editor.off("mousedown", this.mousedownListener);
1495
        this.editor.off("mousewheel", this.mousewheelListener);
1496
        this.changeTimer.cancel();
1497
        this.hideDocTooltip();
1498

    
1499
        this.gatherCompletionsId += 1;
1500
        if (this.popup && this.popup.isOpen)
1501
            this.popup.hide();
1502

    
1503
        if (this.base)
1504
            this.base.detach();
1505
        this.activated = false;
1506
        this.completions = this.base = null;
1507
    };
1508

    
1509
    this.changeListener = function(e) {
1510
        var cursor = this.editor.selection.lead;
1511
        if (cursor.row != this.base.row || cursor.column < this.base.column) {
1512
            this.detach();
1513
        }
1514
        if (this.activated)
1515
            this.changeTimer.schedule();
1516
        else
1517
            this.detach();
1518
    };
1519

    
1520
    this.blurListener = function(e) {
1521
        var el = document.activeElement;
1522
        var text = this.editor.textInput.getElement();
1523
        var fromTooltip = e.relatedTarget && this.tooltipNode && this.tooltipNode.contains(e.relatedTarget);
1524
        var container = this.popup && this.popup.container;
1525
        if (el != text && el.parentNode != container && !fromTooltip
1526
            && el != this.tooltipNode && e.relatedTarget != text
1527
        ) {
1528
            this.detach();
1529
        }
1530
    };
1531

    
1532
    this.mousedownListener = function(e) {
1533
        this.detach();
1534
    };
1535

    
1536
    this.mousewheelListener = function(e) {
1537
        this.detach();
1538
    };
1539

    
1540
    this.goTo = function(where) {
1541
        this.popup.goTo(where);
1542
    };
1543

    
1544
    this.insertMatch = function(data, options) {
1545
        if (!data)
1546
            data = this.popup.getData(this.popup.getRow());
1547
        if (!data)
1548
            return false;
1549

    
1550
        this.editor.startOperation({command: {name: "insertMatch"}});
1551
        if (data.completer && data.completer.insertMatch) {
1552
            data.completer.insertMatch(this.editor, data);
1553
        } else {
1554
            if (this.completions.filterText) {
1555
                var ranges = this.editor.selection.getAllRanges();
1556
                for (var i = 0, range; range = ranges[i]; i++) {
1557
                    range.start.column -= this.completions.filterText.length;
1558
                    this.editor.session.remove(range);
1559
                }
1560
            }
1561
            if (data.snippet)
1562
                snippetManager.insertSnippet(this.editor, data.snippet);
1563
            else
1564
                this.editor.execCommand("insertstring", data.value || data);
1565
        }
1566
        this.detach();
1567
        this.editor.endOperation();
1568
    };
1569

    
1570

    
1571
    this.commands = {
1572
        "Up": function(editor) { editor.completer.goTo("up"); },
1573
        "Down": function(editor) { editor.completer.goTo("down"); },
1574
        "Ctrl-Up|Ctrl-Home": function(editor) { editor.completer.goTo("start"); },
1575
        "Ctrl-Down|Ctrl-End": function(editor) { editor.completer.goTo("end"); },
1576

    
1577
        "Esc": function(editor) { editor.completer.detach(); },
1578
        "Return": function(editor) { return editor.completer.insertMatch(); },
1579
        "Shift-Return": function(editor) { editor.completer.insertMatch(null, {deleteSuffix: true}); },
1580
        "Tab": function(editor) {
1581
            var result = editor.completer.insertMatch();
1582
            if (!result && !editor.tabstopManager)
1583
                editor.completer.goTo("down");
1584
            else
1585
                return result;
1586
        },
1587

    
1588
        "PageUp": function(editor) { editor.completer.popup.gotoPageUp(); },
1589
        "PageDown": function(editor) { editor.completer.popup.gotoPageDown(); }
1590
    };
1591

    
1592
    this.gatherCompletions = function(editor, callback) {
1593
        var session = editor.getSession();
1594
        var pos = editor.getCursorPosition();
1595

    
1596
        var prefix = util.getCompletionPrefix(editor);
1597

    
1598
        this.base = session.doc.createAnchor(pos.row, pos.column - prefix.length);
1599
        this.base.$insertRight = true;
1600

    
1601
        var matches = [];
1602
        var total = editor.completers.length;
1603
        editor.completers.forEach(function(completer, i) {
1604
            completer.getCompletions(editor, session, pos, prefix, function(err, results) {
1605
                if (!err && results)
1606
                    matches = matches.concat(results);
1607
                callback(null, {
1608
                    prefix: util.getCompletionPrefix(editor),
1609
                    matches: matches,
1610
                    finished: (--total === 0)
1611
                });
1612
            });
1613
        });
1614
        return true;
1615
    };
1616

    
1617
    this.showPopup = function(editor, options) {
1618
        if (this.editor)
1619
            this.detach();
1620

    
1621
        this.activated = true;
1622

    
1623
        this.editor = editor;
1624
        if (editor.completer != this) {
1625
            if (editor.completer)
1626
                editor.completer.detach();
1627
            editor.completer = this;
1628
        }
1629

    
1630
        editor.on("changeSelection", this.changeListener);
1631
        editor.on("blur", this.blurListener);
1632
        editor.on("mousedown", this.mousedownListener);
1633
        editor.on("mousewheel", this.mousewheelListener);
1634

    
1635
        this.updateCompletions(false, options);
1636
    };
1637

    
1638
    this.updateCompletions = function(keepPopupPosition, options) {
1639
        if (keepPopupPosition && this.base && this.completions) {
1640
            var pos = this.editor.getCursorPosition();
1641
            var prefix = this.editor.session.getTextRange({start: this.base, end: pos});
1642
            if (prefix == this.completions.filterText)
1643
                return;
1644
            this.completions.setFilter(prefix);
1645
            if (!this.completions.filtered.length)
1646
                return this.detach();
1647
            if (this.completions.filtered.length == 1
1648
            && this.completions.filtered[0].value == prefix
1649
            && !this.completions.filtered[0].snippet)
1650
                return this.detach();
1651
            this.openPopup(this.editor, prefix, keepPopupPosition);
1652
            return;
1653
        }
1654
        
1655
        if (options && options.matches) {
1656
            var pos = this.editor.getSelectionRange().start;
1657
            this.base = this.editor.session.doc.createAnchor(pos.row, pos.column);
1658
            this.base.$insertRight = true;
1659
            this.completions = new FilteredList(options.matches);
1660
            return this.openPopup(this.editor, "", keepPopupPosition);
1661
        }
1662
        var _id = this.gatherCompletionsId;
1663
        this.gatherCompletions(this.editor, function(err, results) {
1664
            var detachIfFinished = function() {
1665
                if (!results.finished) return;
1666
                return this.detach();
1667
            }.bind(this);
1668

    
1669
            var prefix = results.prefix;
1670
            var matches = results && results.matches;
1671

    
1672
            if (!matches || !matches.length)
1673
                return detachIfFinished();
1674
            if (prefix.indexOf(results.prefix) !== 0 || _id != this.gatherCompletionsId)
1675
                return;
1676

    
1677
            this.completions = new FilteredList(matches);
1678

    
1679
            if (this.exactMatch)
1680
                this.completions.exactMatch = true;
1681

    
1682
            this.completions.setFilter(prefix);
1683
            var filtered = this.completions.filtered;
1684
            if (!filtered.length)
1685
                return detachIfFinished();
1686
            if (filtered.length == 1 && filtered[0].value == prefix && !filtered[0].snippet)
1687
                return detachIfFinished();
1688
            if (this.autoInsert && filtered.length == 1 && results.finished)
1689
                return this.insertMatch(filtered[0]);
1690

    
1691
            this.openPopup(this.editor, prefix, keepPopupPosition);
1692
        }.bind(this));
1693
    };
1694

    
1695
    this.cancelContextMenu = function() {
1696
        this.editor.$mouseHandler.cancelContextMenu();
1697
    };
1698

    
1699
    this.updateDocTooltip = function() {
1700
        var popup = this.popup;
1701
        var all = popup.data;
1702
        var selected = all && (all[popup.getHoveredRow()] || all[popup.getRow()]);
1703
        var doc = null;
1704
        if (!selected || !this.editor || !this.popup.isOpen)
1705
            return this.hideDocTooltip();
1706
        this.editor.completers.some(function(completer) {
1707
            if (completer.getDocTooltip)
1708
                doc = completer.getDocTooltip(selected);
1709
            return doc;
1710
        });
1711
        if (!doc && typeof selected != "string")
1712
            doc = selected;
1713

    
1714
        if (typeof doc == "string")
1715
            doc = {docText: doc};
1716
        if (!doc || !(doc.docHTML || doc.docText))
1717
            return this.hideDocTooltip();
1718
        this.showDocTooltip(doc);
1719
    };
1720

    
1721
    this.showDocTooltip = function(item) {
1722
        if (!this.tooltipNode) {
1723
            this.tooltipNode = dom.createElement("div");
1724
            this.tooltipNode.className = "ace_tooltip ace_doc-tooltip";
1725
            this.tooltipNode.style.margin = 0;
1726
            this.tooltipNode.style.pointerEvents = "auto";
1727
            this.tooltipNode.tabIndex = -1;
1728
            this.tooltipNode.onblur = this.blurListener.bind(this);
1729
            this.tooltipNode.onclick = this.onTooltipClick.bind(this);
1730
        }
1731

    
1732
        var tooltipNode = this.tooltipNode;
1733
        if (item.docHTML) {
1734
            tooltipNode.innerHTML = item.docHTML;
1735
        } else if (item.docText) {
1736
            tooltipNode.textContent = item.docText;
1737
        }
1738

    
1739
        if (!tooltipNode.parentNode)
1740
            document.body.appendChild(tooltipNode);
1741
        var popup = this.popup;
1742
        var rect = popup.container.getBoundingClientRect();
1743
        tooltipNode.style.top = popup.container.style.top;
1744
        tooltipNode.style.bottom = popup.container.style.bottom;
1745

    
1746
        tooltipNode.style.display = "block";
1747
        if (window.innerWidth - rect.right < 320) {
1748
            if (rect.left < 320) {
1749
                if(popup.isTopdown) {
1750
                    tooltipNode.style.top = rect.bottom + "px";
1751
                    tooltipNode.style.left = rect.left + "px";
1752
                    tooltipNode.style.right = "";
1753
                    tooltipNode.style.bottom = "";
1754
                } else {
1755
                    tooltipNode.style.top = popup.container.offsetTop - tooltipNode.offsetHeight + "px";
1756
                    tooltipNode.style.left = rect.left + "px";
1757
                    tooltipNode.style.right = "";
1758
                    tooltipNode.style.bottom = "";
1759
                }
1760
            } else {
1761
                tooltipNode.style.right = window.innerWidth - rect.left + "px";
1762
                tooltipNode.style.left = "";
1763
            }
1764
        } else {
1765
            tooltipNode.style.left = (rect.right + 1) + "px";
1766
            tooltipNode.style.right = "";
1767
        }
1768
    };
1769

    
1770
    this.hideDocTooltip = function() {
1771
        this.tooltipTimer.cancel();
1772
        if (!this.tooltipNode) return;
1773
        var el = this.tooltipNode;
1774
        if (!this.editor.isFocused() && document.activeElement == el)
1775
            this.editor.focus();
1776
        this.tooltipNode = null;
1777
        if (el.parentNode)
1778
            el.parentNode.removeChild(el);
1779
    };
1780
    
1781
    this.onTooltipClick = function(e) {
1782
        var a = e.target;
1783
        while (a && a != this.tooltipNode) {
1784
            if (a.nodeName == "A" && a.href) {
1785
                a.rel = "noreferrer";
1786
                a.target = "_blank";
1787
                break;
1788
            }
1789
            a = a.parentNode;
1790
        }
1791
    };
1792

    
1793
    this.destroy = function() {
1794
        this.detach();
1795
        if (this.popup) {
1796
            this.popup.destroy();
1797
            var el = this.popup.container;
1798
            if (el && el.parentNode)
1799
                el.parentNode.removeChild(el);
1800
        }
1801
        if (this.editor && this.editor.completer == this)
1802
            this.editor.completer == null;
1803
        this.popup = null;
1804
    };
1805

    
1806
}).call(Autocomplete.prototype);
1807

    
1808

    
1809
Autocomplete.for = function(editor) {
1810
    if (editor.completer) {
1811
        return editor.completer;
1812
    }
1813
    if (config.get("sharedPopups")) {
1814
        if (!Autocomplete.$shared)
1815
            Autocomplete.$sharedInstance = new Autocomplete();
1816
        editor.completer = Autocomplete.$sharedInstance;
1817
    } else {
1818
        editor.completer = new Autocomplete();
1819
        editor.once("destroy", function(e, editor) {
1820
            editor.completer.destroy();
1821
        });
1822
    }
1823
    return editor.completer;
1824
};
1825

    
1826
Autocomplete.startCommand = {
1827
    name: "startAutocomplete",
1828
    exec: function(editor, options) {
1829
        var completer = Autocomplete.for(editor);
1830
        completer.autoInsert = false;
1831
        completer.autoSelect = true;
1832
        completer.showPopup(editor, options);
1833
        completer.cancelContextMenu();
1834
    },
1835
    bindKey: "Ctrl-Space|Ctrl-Shift-Space|Alt-Space"
1836
};
1837

    
1838
var FilteredList = function(array, filterText) {
1839
    this.all = array;
1840
    this.filtered = array;
1841
    this.filterText = filterText || "";
1842
    this.exactMatch = false;
1843
};
1844
(function(){
1845
    this.setFilter = function(str) {
1846
        if (str.length > this.filterText && str.lastIndexOf(this.filterText, 0) === 0)
1847
            var matches = this.filtered;
1848
        else
1849
            var matches = this.all;
1850

    
1851
        this.filterText = str;
1852
        matches = this.filterCompletions(matches, this.filterText);
1853
        matches = matches.sort(function(a, b) {
1854
            return b.exactMatch - a.exactMatch || b.$score - a.$score 
1855
                || (a.caption || a.value).localeCompare(b.caption || b.value);
1856
        });
1857
        var prev = null;
1858
        matches = matches.filter(function(item){
1859
            var caption = item.snippet || item.caption || item.value;
1860
            if (caption === prev) return false;
1861
            prev = caption;
1862
            return true;
1863
        });
1864

    
1865
        this.filtered = matches;
1866
    };
1867
    this.filterCompletions = function(items, needle) {
1868
        var results = [];
1869
        var upper = needle.toUpperCase();
1870
        var lower = needle.toLowerCase();
1871
        loop: for (var i = 0, item; item = items[i]; i++) {
1872
            var caption = item.caption || item.value || item.snippet;
1873
            if (!caption) continue;
1874
            var lastIndex = -1;
1875
            var matchMask = 0;
1876
            var penalty = 0;
1877
            var index, distance;
1878

    
1879
            if (this.exactMatch) {
1880
                if (needle !== caption.substr(0, needle.length))
1881
                    continue loop;
1882
            } else {
1883
                var fullMatchIndex = caption.toLowerCase().indexOf(lower);
1884
                if (fullMatchIndex > -1) {
1885
                    penalty = fullMatchIndex;
1886
                } else {
1887
                    for (var j = 0; j < needle.length; j++) {
1888
                        var i1 = caption.indexOf(lower[j], lastIndex + 1);
1889
                        var i2 = caption.indexOf(upper[j], lastIndex + 1);
1890
                        index = (i1 >= 0) ? ((i2 < 0 || i1 < i2) ? i1 : i2) : i2;
1891
                        if (index < 0)
1892
                            continue loop;
1893
                        distance = index - lastIndex - 1;
1894
                        if (distance > 0) {
1895
                            if (lastIndex === -1)
1896
                                penalty += 10;
1897
                            penalty += distance;
1898
                            matchMask = matchMask | (1 << j);
1899
                        }
1900
                        lastIndex = index;
1901
                    }
1902
                }
1903
            }
1904
            item.matchMask = matchMask;
1905
            item.exactMatch = penalty ? 0 : 1;
1906
            item.$score = (item.score || 0) - penalty;
1907
            results.push(item);
1908
        }
1909
        return results;
1910
    };
1911
}).call(FilteredList.prototype);
1912

    
1913
exports.Autocomplete = Autocomplete;
1914
exports.FilteredList = FilteredList;
1915

    
1916
});
1917

    
1918
ace.define("ace/autocomplete/text_completer",["require","exports","module","ace/range"], function(require, exports, module) {
1919
    var Range = require("../range").Range;
1920
    
1921
    var splitRegex = /[^a-zA-Z_0-9\$\-\u00C0-\u1FFF\u2C00-\uD7FF\w]+/;
1922

    
1923
    function getWordIndex(doc, pos) {
1924
        var textBefore = doc.getTextRange(Range.fromPoints({row: 0, column:0}, pos));
1925
        return textBefore.split(splitRegex).length - 1;
1926
    }
1927
    function wordDistance(doc, pos) {
1928
        var prefixPos = getWordIndex(doc, pos);
1929
        var words = doc.getValue().split(splitRegex);
1930
        var wordScores = Object.create(null);
1931
        
1932
        var currentWord = words[prefixPos];
1933

    
1934
        words.forEach(function(word, idx) {
1935
            if (!word || word === currentWord) return;
1936

    
1937
            var distance = Math.abs(prefixPos - idx);
1938
            var score = words.length - distance;
1939
            if (wordScores[word]) {
1940
                wordScores[word] = Math.max(score, wordScores[word]);
1941
            } else {
1942
                wordScores[word] = score;
1943
            }
1944
        });
1945
        return wordScores;
1946
    }
1947

    
1948
    exports.getCompletions = function(editor, session, pos, prefix, callback) {
1949
        var wordScore = wordDistance(session, pos);
1950
        var wordList = Object.keys(wordScore);
1951
        callback(null, wordList.map(function(word) {
1952
            return {
1953
                caption: word,
1954
                value: word,
1955
                score: wordScore[word],
1956
                meta: "local"
1957
            };
1958
        }));
1959
    };
1960
});
1961

    
1962
ace.define("ace/ext/language_tools",["require","exports","module","ace/snippets","ace/autocomplete","ace/config","ace/lib/lang","ace/autocomplete/util","ace/autocomplete/text_completer","ace/editor","ace/config"], function(require, exports, module) {
1963
"use strict";
1964

    
1965
var snippetManager = require("../snippets").snippetManager;
1966
var Autocomplete = require("../autocomplete").Autocomplete;
1967
var config = require("../config");
1968
var lang = require("../lib/lang");
1969
var util = require("../autocomplete/util");
1970

    
1971
var textCompleter = require("../autocomplete/text_completer");
1972
var keyWordCompleter = {
1973
    getCompletions: function(editor, session, pos, prefix, callback) {
1974
        if (session.$mode.completer) {
1975
            return session.$mode.completer.getCompletions(editor, session, pos, prefix, callback);
1976
        }
1977
        var state = editor.session.getState(pos.row);
1978
        var completions = session.$mode.getCompletions(state, session, pos, prefix);
1979
        callback(null, completions);
1980
    }
1981
};
1982

    
1983
var snippetCompleter = {
1984
    getCompletions: function(editor, session, pos, prefix, callback) {
1985
        var scopes = [];
1986
        var token = session.getTokenAt(pos.row, pos.column);
1987
        if (token && token.type.match(/(tag-name|tag-open|tag-whitespace|attribute-name|attribute-value)\.xml$/))
1988
            scopes.push('html-tag');
1989
        else
1990
            scopes = snippetManager.getActiveScopes(editor);
1991

    
1992
        var snippetMap = snippetManager.snippetMap;
1993
        var completions = [];
1994
        scopes.forEach(function(scope) {
1995
            var snippets = snippetMap[scope] || [];
1996
            for (var i = snippets.length; i--;) {
1997
                var s = snippets[i];
1998
                var caption = s.name || s.tabTrigger;
1999
                if (!caption)
2000
                    continue;
2001
                completions.push({
2002
                    caption: caption,
2003
                    snippet: s.content,
2004
                    meta: s.tabTrigger && !s.name ? s.tabTrigger + "\u21E5 " : "snippet",
2005
                    type: "snippet"
2006
                });
2007
            }
2008
        }, this);
2009
        callback(null, completions);
2010
    },
2011
    getDocTooltip: function(item) {
2012
        if (item.type == "snippet" && !item.docHTML) {
2013
            item.docHTML = [
2014
                "<b>", lang.escapeHTML(item.caption), "</b>", "<hr></hr>",
2015
                lang.escapeHTML(item.snippet)
2016
            ].join("");
2017
        }
2018
    }
2019
};
2020

    
2021
var completers = [snippetCompleter, textCompleter, keyWordCompleter];
2022
exports.setCompleters = function(val) {
2023
    completers.length = 0;
2024
    if (val) completers.push.apply(completers, val);
2025
};
2026
exports.addCompleter = function(completer) {
2027
    completers.push(completer);
2028
};
2029
exports.textCompleter = textCompleter;
2030
exports.keyWordCompleter = keyWordCompleter;
2031
exports.snippetCompleter = snippetCompleter;
2032

    
2033
var expandSnippet = {
2034
    name: "expandSnippet",
2035
    exec: function(editor) {
2036
        return snippetManager.expandWithTab(editor);
2037
    },
2038
    bindKey: "Tab"
2039
};
2040

    
2041
var onChangeMode = function(e, editor) {
2042
    loadSnippetsForMode(editor.session.$mode);
2043
};
2044

    
2045
var loadSnippetsForMode = function(mode) {
2046
    if (typeof mode == "string")
2047
        mode = config.$modes[mode];
2048
    if (!mode)
2049
        return;
2050
    if (!snippetManager.files)
2051
        snippetManager.files = {};
2052
    
2053
    loadSnippetFile(mode.$id, mode.snippetFileId);
2054
    if (mode.modes)
2055
        mode.modes.forEach(loadSnippetsForMode);
2056
};
2057

    
2058
var loadSnippetFile = function(id, snippetFilePath) {
2059
    if (!snippetFilePath || !id || snippetManager.files[id])
2060
        return;
2061
    snippetManager.files[id] = {};
2062
    config.loadModule(snippetFilePath, function(m) {
2063
        if (!m) return;
2064
        snippetManager.files[id] = m;
2065
        if (!m.snippets && m.snippetText)
2066
            m.snippets = snippetManager.parseSnippetFile(m.snippetText);
2067
        snippetManager.register(m.snippets || [], m.scope);
2068
        if (m.includeScopes) {
2069
            snippetManager.snippetMap[m.scope].includeScopes = m.includeScopes;
2070
            m.includeScopes.forEach(function(x) {
2071
                loadSnippetsForMode("ace/mode/" + x);
2072
            });
2073
        }
2074
    });
2075
};
2076

    
2077
var doLiveAutocomplete = function(e) {
2078
    var editor = e.editor;
2079
    var hasCompleter = editor.completer && editor.completer.activated;
2080
    if (e.command.name === "backspace") {
2081
        if (hasCompleter && !util.getCompletionPrefix(editor))
2082
            editor.completer.detach();
2083
    }
2084
    else if (e.command.name === "insertstring") {
2085
        var prefix = util.getCompletionPrefix(editor);
2086
        if (prefix && !hasCompleter) {
2087
            var completer = Autocomplete.for(editor);
2088
            completer.autoInsert = false;
2089
            completer.showPopup(editor);
2090
        }
2091
    }
2092
};
2093

    
2094
var Editor = require("../editor").Editor;
2095
require("../config").defineOptions(Editor.prototype, "editor", {
2096
    enableBasicAutocompletion: {
2097
        set: function(val) {
2098
            if (val) {
2099
                if (!this.completers)
2100
                    this.completers = Array.isArray(val)? val: completers;
2101
                this.commands.addCommand(Autocomplete.startCommand);
2102
            } else {
2103
                this.commands.removeCommand(Autocomplete.startCommand);
2104
            }
2105
        },
2106
        value: false
2107
    },
2108
    enableLiveAutocompletion: {
2109
        set: function(val) {
2110
            if (val) {
2111
                if (!this.completers)
2112
                    this.completers = Array.isArray(val)? val: completers;
2113
                this.commands.on('afterExec', doLiveAutocomplete);
2114
            } else {
2115
                this.commands.removeListener('afterExec', doLiveAutocomplete);
2116
            }
2117
        },
2118
        value: false
2119
    },
2120
    enableSnippets: {
2121
        set: function(val) {
2122
            if (val) {
2123
                this.commands.addCommand(expandSnippet);
2124
                this.on("changeMode", onChangeMode);
2125
                onChangeMode(null, this);
2126
            } else {
2127
                this.commands.removeCommand(expandSnippet);
2128
                this.off("changeMode", onChangeMode);
2129
            }
2130
        },
2131
        value: false
2132
    }
2133
});
2134
});                (function() {
2135
                    ace.require(["ace/ext/language_tools"], function(m) {
2136
                        if (typeof module == "object" && typeof exports == "object" && module) {
2137
                            module.exports = m;
2138
                        }
2139
                    });
2140
                })();
2141
            
(8-8/244)