Projekt

Obecné

Profil

Stáhnout (47.5 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/ext/emmet",["require","exports","module","ace/keyboard/hash_handler","ace/editor","ace/snippets","ace/range","ace/config","resources","resources","tabStops","resources","utils","actions"], function(require, exports, module) {
1008
"use strict";
1009
var HashHandler = require("../keyboard/hash_handler").HashHandler;
1010
var Editor = require("../editor").Editor;
1011
var snippetManager = require("../snippets").snippetManager;
1012
var Range = require("../range").Range;
1013
var config = require("../config");
1014
var emmet, emmetPath;
1015
function AceEmmetEditor() {}
1016

    
1017
AceEmmetEditor.prototype = {
1018
    setupContext: function(editor) {
1019
        this.ace = editor;
1020
        this.indentation = editor.session.getTabString();
1021
        if (!emmet)
1022
            emmet = window.emmet;
1023
        var resources = emmet.resources || emmet.require("resources");
1024
        resources.setVariable("indentation", this.indentation);
1025
        this.$syntax = null;
1026
        this.$syntax = this.getSyntax();
1027
    },
1028
    getSelectionRange: function() {
1029
        var range = this.ace.getSelectionRange();
1030
        var doc = this.ace.session.doc;
1031
        return {
1032
            start: doc.positionToIndex(range.start),
1033
            end: doc.positionToIndex(range.end)
1034
        };
1035
    },
1036
    createSelection: function(start, end) {
1037
        var doc = this.ace.session.doc;
1038
        this.ace.selection.setRange({
1039
            start: doc.indexToPosition(start),
1040
            end: doc.indexToPosition(end)
1041
        });
1042
    },
1043
    getCurrentLineRange: function() {
1044
        var ace = this.ace;
1045
        var row = ace.getCursorPosition().row;
1046
        var lineLength = ace.session.getLine(row).length;
1047
        var index = ace.session.doc.positionToIndex({row: row, column: 0});
1048
        return {
1049
            start: index,
1050
            end: index + lineLength
1051
        };
1052
    },
1053
    getCaretPos: function(){
1054
        var pos = this.ace.getCursorPosition();
1055
        return this.ace.session.doc.positionToIndex(pos);
1056
    },
1057
    setCaretPos: function(index){
1058
        var pos = this.ace.session.doc.indexToPosition(index);
1059
        this.ace.selection.moveToPosition(pos);
1060
    },
1061
    getCurrentLine: function() {
1062
        var row = this.ace.getCursorPosition().row;
1063
        return this.ace.session.getLine(row);
1064
    },
1065
    replaceContent: function(value, start, end, noIndent) {
1066
        if (end == null)
1067
            end = start == null ? this.getContent().length : start;
1068
        if (start == null)
1069
            start = 0;        
1070
        
1071
        var editor = this.ace;
1072
        var doc = editor.session.doc;
1073
        var range = Range.fromPoints(doc.indexToPosition(start), doc.indexToPosition(end));
1074
        editor.session.remove(range);
1075
        
1076
        range.end = range.start;
1077
        
1078
        value = this.$updateTabstops(value);
1079
        snippetManager.insertSnippet(editor, value);
1080
    },
1081
    getContent: function(){
1082
        return this.ace.getValue();
1083
    },
1084
    getSyntax: function() {
1085
        if (this.$syntax)
1086
            return this.$syntax;
1087
        var syntax = this.ace.session.$modeId.split("/").pop();
1088
        if (syntax == "html" || syntax == "php") {
1089
            var cursor = this.ace.getCursorPosition();
1090
            var state = this.ace.session.getState(cursor.row);
1091
            if (typeof state != "string")
1092
                state = state[0];
1093
            if (state) {
1094
                state = state.split("-");
1095
                if (state.length > 1)
1096
                    syntax = state[0];
1097
                else if (syntax == "php")
1098
                    syntax = "html";
1099
            }
1100
        }
1101
        return syntax;
1102
    },
1103
    getProfileName: function() {
1104
        var resources = emmet.resources || emmet.require("resources");
1105
        switch (this.getSyntax()) {
1106
          case "css": return "css";
1107
          case "xml":
1108
          case "xsl":
1109
            return "xml";
1110
          case "html":
1111
            var profile = resources.getVariable("profile");
1112
            if (!profile)
1113
                profile = this.ace.session.getLines(0,2).join("").search(/<!DOCTYPE[^>]+XHTML/i) != -1 ? "xhtml": "html";
1114
            return profile;
1115
          default:
1116
            var mode = this.ace.session.$mode;
1117
            return mode.emmetConfig && mode.emmetConfig.profile || "xhtml";
1118
        }
1119
    },
1120
    prompt: function(title) {
1121
        return prompt(title); // eslint-disable-line no-alert
1122
    },
1123
    getSelection: function() {
1124
        return this.ace.session.getTextRange();
1125
    },
1126
    getFilePath: function() {
1127
        return "";
1128
    },
1129
    $updateTabstops: function(value) {
1130
        var base = 1000;
1131
        var zeroBase = 0;
1132
        var lastZero = null;
1133
        var ts = emmet.tabStops || emmet.require('tabStops');
1134
        var resources = emmet.resources || emmet.require("resources");
1135
        var settings = resources.getVocabulary("user");
1136
        var tabstopOptions = {
1137
            tabstop: function(data) {
1138
                var group = parseInt(data.group, 10);
1139
                var isZero = group === 0;
1140
                if (isZero)
1141
                    group = ++zeroBase;
1142
                else
1143
                    group += base;
1144

    
1145
                var placeholder = data.placeholder;
1146
                if (placeholder) {
1147
                    placeholder = ts.processText(placeholder, tabstopOptions);
1148
                }
1149

    
1150
                var result = '${' + group + (placeholder ? ':' + placeholder : '') + '}';
1151

    
1152
                if (isZero) {
1153
                    lastZero = [data.start, result];
1154
                }
1155

    
1156
                return result;
1157
            },
1158
            escape: function(ch) {
1159
                if (ch == '$') return '\\$';
1160
                if (ch == '\\') return '\\\\';
1161
                return ch;
1162
            }
1163
        };
1164

    
1165
        value = ts.processText(value, tabstopOptions);
1166

    
1167
        if (settings.variables['insert_final_tabstop'] && !/\$\{0\}$/.test(value)) {
1168
            value += '${0}';
1169
        } else if (lastZero) {
1170
            var common = emmet.utils ? emmet.utils.common : emmet.require('utils');
1171
            value = common.replaceSubstring(value, '${0}', lastZero[0], lastZero[1]);
1172
        }
1173
        
1174
        return value;
1175
    }
1176
};
1177

    
1178

    
1179
var keymap = {
1180
    expand_abbreviation: {"mac": "ctrl+alt+e", "win": "alt+e"},
1181
    match_pair_outward: {"mac": "ctrl+d", "win": "ctrl+,"},
1182
    match_pair_inward: {"mac": "ctrl+j", "win": "ctrl+shift+0"},
1183
    matching_pair: {"mac": "ctrl+alt+j", "win": "alt+j"},
1184
    next_edit_point: "alt+right",
1185
    prev_edit_point: "alt+left",
1186
    toggle_comment: {"mac": "command+/", "win": "ctrl+/"},
1187
    split_join_tag: {"mac": "shift+command+'", "win": "shift+ctrl+`"},
1188
    remove_tag: {"mac": "command+'", "win": "shift+ctrl+;"},
1189
    evaluate_math_expression: {"mac": "shift+command+y", "win": "shift+ctrl+y"},
1190
    increment_number_by_1: "ctrl+up",
1191
    decrement_number_by_1: "ctrl+down",
1192
    increment_number_by_01: "alt+up",
1193
    decrement_number_by_01: "alt+down",
1194
    increment_number_by_10: {"mac": "alt+command+up", "win": "shift+alt+up"},
1195
    decrement_number_by_10: {"mac": "alt+command+down", "win": "shift+alt+down"},
1196
    select_next_item: {"mac": "shift+command+.", "win": "shift+ctrl+."},
1197
    select_previous_item: {"mac": "shift+command+,", "win": "shift+ctrl+,"},
1198
    reflect_css_value: {"mac": "shift+command+r", "win": "shift+ctrl+r"},
1199

    
1200
    encode_decode_data_url: {"mac": "shift+ctrl+d", "win": "ctrl+'"},
1201
    expand_abbreviation_with_tab: "Tab",
1202
    wrap_with_abbreviation: {"mac": "shift+ctrl+a", "win": "shift+ctrl+a"}
1203
};
1204

    
1205
var editorProxy = new AceEmmetEditor();
1206
exports.commands = new HashHandler();
1207
exports.runEmmetCommand = function runEmmetCommand(editor) {
1208
    if (this.action == "expand_abbreviation_with_tab") {
1209
        if (!editor.selection.isEmpty())
1210
            return false;
1211
        var pos = editor.selection.lead;
1212
        var token = editor.session.getTokenAt(pos.row, pos.column);
1213
        if (token && /\btag\b/.test(token.type))
1214
            return false;
1215
    }
1216
    try {
1217
        editorProxy.setupContext(editor);
1218
        var actions = emmet.actions || emmet.require("actions");
1219
        
1220
        if (this.action == "wrap_with_abbreviation") {
1221
            return setTimeout(function() {
1222
                actions.run("wrap_with_abbreviation", editorProxy);
1223
            }, 0);
1224
        }
1225
        
1226
        var result = actions.run(this.action, editorProxy);
1227
    } catch(e) {
1228
        if (!emmet) {
1229
            var loading = exports.load(runEmmetCommand.bind(this, editor));
1230
            if (this.action == "expand_abbreviation_with_tab")
1231
                return false;
1232
            return loading;
1233
        }
1234
        editor._signal("changeStatus", typeof e == "string" ? e : e.message);
1235
        config.warn(e);
1236
        result = false;
1237
    }
1238
    return result;
1239
};
1240

    
1241
for (var command in keymap) {
1242
    exports.commands.addCommand({
1243
        name: "emmet:" + command,
1244
        action: command,
1245
        bindKey: keymap[command],
1246
        exec: exports.runEmmetCommand,
1247
        multiSelectAction: "forEach"
1248
    });
1249
}
1250

    
1251
exports.updateCommands = function(editor, enabled) {
1252
    if (enabled) {
1253
        editor.keyBinding.addKeyboardHandler(exports.commands);
1254
    } else {
1255
        editor.keyBinding.removeKeyboardHandler(exports.commands);
1256
    }
1257
};
1258

    
1259
exports.isSupportedMode = function(mode) {
1260
    if (!mode) return false;
1261
    if (mode.emmetConfig) return true;
1262
    var id = mode.$id || mode;
1263
    return /css|less|scss|sass|stylus|html|php|twig|ejs|handlebars/.test(id);
1264
};
1265

    
1266
exports.isAvailable = function(editor, command) {
1267
    if (/(evaluate_math_expression|expand_abbreviation)$/.test(command))
1268
        return true;
1269
    var mode = editor.session.$mode;
1270
    var isSupported = exports.isSupportedMode(mode);
1271
    if (isSupported && mode.$modes) {
1272
        try {
1273
            editorProxy.setupContext(editor);
1274
            if (/js|php/.test(editorProxy.getSyntax()))
1275
                isSupported = false;
1276
        } catch(e) {}
1277
    }
1278
    return isSupported;
1279
};
1280

    
1281
var onChangeMode = function(e, target) {
1282
    var editor = target;
1283
    if (!editor)
1284
        return;
1285
    var enabled = exports.isSupportedMode(editor.session.$mode);
1286
    if (e.enableEmmet === false)
1287
        enabled = false;
1288
    if (enabled)
1289
        exports.load();
1290
    exports.updateCommands(editor, enabled);
1291
};
1292

    
1293
exports.load = function(cb) {
1294
    if (typeof emmetPath !== "string") {
1295
        config.warn("script for emmet-core is not loaded");
1296
        return false;
1297
    }
1298
    config.loadModule(emmetPath, function() {
1299
        emmetPath = null;
1300
        cb && cb();
1301
    });
1302
    return true;
1303
};
1304

    
1305
exports.AceEmmetEditor = AceEmmetEditor;
1306
config.defineOptions(Editor.prototype, "editor", {
1307
    enableEmmet: {
1308
        set: function(val) {
1309
            this[val ? "on" : "removeListener"]("changeMode", onChangeMode);
1310
            onChangeMode({enableEmmet: !!val}, this);
1311
        },
1312
        value: true
1313
    }
1314
});
1315

    
1316
exports.setCore = function(e) {
1317
    if (typeof e == "string")
1318
       emmetPath = e;
1319
    else
1320
       emmet = e;
1321
};
1322
});                (function() {
1323
                    ace.require(["ace/ext/emmet"], function(m) {
1324
                        if (typeof module == "object" && typeof exports == "object" && module) {
1325
                            module.exports = m;
1326
                        }
1327
                    });
1328
                })();
1329
            
(5-5/244)