/lenasys/trunk

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/lenasys/trunk

« back to all changes in this revision

Viewing changes to js/ace/mode-lua.js

  • Committer: gustav.hartvigsson at gmail
  • Date: 2013-04-02 12:13:01 UTC
  • mfrom: (4.2.7 hitlerhorabajs)
  • Revision ID: gustav.hartvigsson@gmail.com-20130402121301-ytfzuo7y6cku9s3o
Merge from implemenation group 2:s branch.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
/* ***** BEGIN LICENSE BLOCK *****
2
 
 * Distributed under the BSD license:
3
 
 *
4
 
 * Copyright (c) 2010, Ajax.org B.V.
5
 
 * All rights reserved.
6
 
 * 
7
 
 * Redistribution and use in source and binary forms, with or without
8
 
 * modification, are permitted provided that the following conditions are met:
9
 
 *     * Redistributions of source code must retain the above copyright
10
 
 *       notice, this list of conditions and the following disclaimer.
11
 
 *     * Redistributions in binary form must reproduce the above copyright
12
 
 *       notice, this list of conditions and the following disclaimer in the
13
 
 *       documentation and/or other materials provided with the distribution.
14
 
 *     * Neither the name of Ajax.org B.V. nor the
15
 
 *       names of its contributors may be used to endorse or promote products
16
 
 *       derived from this software without specific prior written permission.
17
 
 * 
18
 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
19
 
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20
 
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
 
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
22
 
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23
 
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
24
 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
25
 
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26
 
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
27
 
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
 
 *
29
 
 * ***** END LICENSE BLOCK ***** */
30
 
 
31
 
define('ace/mode/lua', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text', 'ace/tokenizer', 'ace/mode/lua_highlight_rules', 'ace/mode/folding/lua', 'ace/range'], function(require, exports, module) {
32
 
 
33
 
 
34
 
var oop = require("../lib/oop");
35
 
var TextMode = require("./text").Mode;
36
 
var Tokenizer = require("../tokenizer").Tokenizer;
37
 
var LuaHighlightRules = require("./lua_highlight_rules").LuaHighlightRules;
38
 
var LuaFoldMode = require("./folding/lua").FoldMode;
39
 
var Range = require("../range").Range;
40
 
 
41
 
var Mode = function() {
42
 
    this.$tokenizer = new Tokenizer(new LuaHighlightRules().getRules());
43
 
    this.foldingRules = new LuaFoldMode();
44
 
};
45
 
oop.inherits(Mode, TextMode);
46
 
 
47
 
(function() {
48
 
   
49
 
    this.lineCommentStart = "--";
50
 
    this.blockComment = {start: "--[", end: "]--"};
51
 
    
52
 
    var indentKeywords = {
53
 
        "function": 1,
54
 
        "then": 1,
55
 
        "do": 1,
56
 
        "else": 1,
57
 
        "elseif": 1,
58
 
        "repeat": 1,
59
 
        "end": -1,
60
 
        "until": -1
61
 
    };
62
 
    var outdentKeywords = [
63
 
        "else",
64
 
        "elseif",
65
 
        "end",
66
 
        "until"
67
 
    ];
68
 
 
69
 
    function getNetIndentLevel(tokens) {
70
 
        var level = 0;
71
 
        for (var i = 0; i < tokens.length; i++) {
72
 
            var token = tokens[i];
73
 
            if (token.type == "keyword") {
74
 
                if (token.value in indentKeywords) {
75
 
                    level += indentKeywords[token.value];
76
 
                }
77
 
            } else if (token.type == "paren.lparen") {
78
 
                level ++;
79
 
            } else if (token.type == "paren.rparen") {
80
 
                level --;
81
 
            }
82
 
        }
83
 
        if (level < 0) {
84
 
            return -1;
85
 
        } else if (level > 0) {
86
 
            return 1;
87
 
        } else {
88
 
            return 0;
89
 
        }
90
 
    }
91
 
 
92
 
    this.getNextLineIndent = function(state, line, tab) {
93
 
        var indent = this.$getIndent(line);
94
 
        var level = 0;
95
 
 
96
 
        var tokenizedLine = this.$tokenizer.getLineTokens(line, state);
97
 
        var tokens = tokenizedLine.tokens;
98
 
 
99
 
        if (state == "start") {
100
 
            level = getNetIndentLevel(tokens);
101
 
        }
102
 
        if (level > 0) {
103
 
            return indent + tab;
104
 
        } else if (level < 0 && indent.substr(indent.length - tab.length) == tab) {
105
 
            if (!this.checkOutdent(state, line, "\n")) {
106
 
                return indent.substr(0, indent.length - tab.length);
107
 
            }
108
 
        }
109
 
        return indent;
110
 
    };
111
 
 
112
 
    this.checkOutdent = function(state, line, input) {
113
 
        if (input != "\n" && input != "\r" && input != "\r\n")
114
 
            return false;
115
 
 
116
 
        if (line.match(/^\s*[\)\}\]]$/))
117
 
            return true;
118
 
 
119
 
        var tokens = this.$tokenizer.getLineTokens(line.trim(), state).tokens;
120
 
 
121
 
        if (!tokens || !tokens.length)
122
 
            return false;
123
 
 
124
 
        return (tokens[0].type == "keyword" && outdentKeywords.indexOf(tokens[0].value) != -1);
125
 
    };
126
 
 
127
 
    this.autoOutdent = function(state, session, row) {
128
 
        var prevLine = session.getLine(row - 1);
129
 
        var prevIndent = this.$getIndent(prevLine).length;
130
 
        var prevTokens = this.$tokenizer.getLineTokens(prevLine, "start").tokens;
131
 
        var tabLength = session.getTabString().length;
132
 
        var expectedIndent = prevIndent + tabLength * getNetIndentLevel(prevTokens);
133
 
        var curIndent = this.$getIndent(session.getLine(row)).length;
134
 
        if (curIndent < expectedIndent) {
135
 
            return;
136
 
        }
137
 
        session.outdentRows(new Range(row, 0, row + 2, 0));
138
 
    };
139
 
 
140
 
}).call(Mode.prototype);
141
 
 
142
 
exports.Mode = Mode;
143
 
});
144
 
 
145
 
define('ace/mode/lua_highlight_rules', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/text_highlight_rules'], function(require, exports, module) {
146
 
 
147
 
 
148
 
var oop = require("../lib/oop");
149
 
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;
150
 
 
151
 
var LuaHighlightRules = function() {
152
 
 
153
 
    var keywords = (
154
 
        "break|do|else|elseif|end|for|function|if|in|local|repeat|"+
155
 
         "return|then|until|while|or|and|not"
156
 
    );
157
 
 
158
 
    var builtinConstants = ("true|false|nil|_G|_VERSION");
159
 
 
160
 
    var functions = (
161
 
        "string|xpcall|package|tostring|print|os|unpack|require|"+
162
 
        "getfenv|setmetatable|next|assert|tonumber|io|rawequal|"+
163
 
        "collectgarbage|getmetatable|module|rawset|math|debug|"+
164
 
        "pcall|table|newproxy|type|coroutine|_G|select|gcinfo|"+
165
 
        "pairs|rawget|loadstring|ipairs|_VERSION|dofile|setfenv|"+
166
 
        "load|error|loadfile|"+
167
 
 
168
 
        "sub|upper|len|gfind|rep|find|match|char|dump|gmatch|"+
169
 
        "reverse|byte|format|gsub|lower|preload|loadlib|loaded|"+
170
 
        "loaders|cpath|config|path|seeall|exit|setlocale|date|"+
171
 
        "getenv|difftime|remove|time|clock|tmpname|rename|execute|"+
172
 
        "lines|write|close|flush|open|output|type|read|stderr|"+
173
 
        "stdin|input|stdout|popen|tmpfile|log|max|acos|huge|"+
174
 
        "ldexp|pi|cos|tanh|pow|deg|tan|cosh|sinh|random|randomseed|"+
175
 
        "frexp|ceil|floor|rad|abs|sqrt|modf|asin|min|mod|fmod|log10|"+
176
 
        "atan2|exp|sin|atan|getupvalue|debug|sethook|getmetatable|"+
177
 
        "gethook|setmetatable|setlocal|traceback|setfenv|getinfo|"+
178
 
        "setupvalue|getlocal|getregistry|getfenv|setn|insert|getn|"+
179
 
        "foreachi|maxn|foreach|concat|sort|remove|resume|yield|"+
180
 
        "status|wrap|create|running|"+
181
 
        "__add|__sub|__mod|__unm|__concat|__lt|__index|__call|__gc|__metatable|"+
182
 
         "__mul|__div|__pow|__len|__eq|__le|__newindex|__tostring|__mode|__tonumber"
183
 
    );
184
 
 
185
 
    var stdLibaries = ("string|package|os|io|math|debug|table|coroutine");
186
 
 
187
 
    var futureReserved = "";
188
 
 
189
 
    var deprecatedIn5152 = ("setn|foreach|foreachi|gcinfo|log10|maxn");
190
 
 
191
 
    var keywordMapper = this.createKeywordMapper({
192
 
        "keyword": keywords,
193
 
        "support.function": functions,
194
 
        "invalid.deprecated": deprecatedIn5152,
195
 
        "constant.library": stdLibaries,
196
 
        "constant.language": builtinConstants,
197
 
        "invalid.illegal": futureReserved,
198
 
        "variable.language": "this"
199
 
    }, "identifier");
200
 
 
201
 
    var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))";
202
 
    var hexInteger = "(?:0[xX][\\dA-Fa-f]+)";
203
 
    var integer = "(?:" + decimalInteger + "|" + hexInteger + ")";
204
 
 
205
 
    var fraction = "(?:\\.\\d+)";
206
 
    var intPart = "(?:\\d+)";
207
 
    var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
208
 
    var floatNumber = "(?:" + pointFloat + ")";
209
 
 
210
 
    this.$rules = {
211
 
        "start" : [{
212
 
            stateName: "bracketedComment",
213
 
            onMatch : function(value, currentState, stack){
214
 
                stack.unshift(this.next, value.length, currentState);
215
 
                return "comment";
216
 
            },
217
 
            regex : /\-\-\[=*\[/,
218
 
            next  : [
219
 
                {
220
 
                    onMatch : function(value, currentState, stack) {
221
 
                        if (value.length == stack[1]) {
222
 
                            stack.shift();
223
 
                            stack.shift();
224
 
                            this.next = stack.shift();
225
 
                        } else {
226
 
                            this.next = "";
227
 
                        }
228
 
                        return "comment";
229
 
                    },
230
 
                    regex : /(?:[^\\]|\\.)*?\]=*\]/,
231
 
                    next  : "start"
232
 
                }, {
233
 
                    defaultToken : "comment"
234
 
                }
235
 
            ]
236
 
        },
237
 
 
238
 
        {
239
 
            token : "comment",
240
 
            regex : "\\-\\-.*$"
241
 
        },
242
 
        {
243
 
            stateName: "bracketedString",
244
 
            onMatch : function(value, currentState, stack){
245
 
                stack.unshift(this.next, value.length, currentState);
246
 
                return "comment";
247
 
            },
248
 
            regex : /\[=*\[/,
249
 
            next  : [
250
 
                {
251
 
                    onMatch : function(value, currentState, stack) {
252
 
                        if (value.length == stack[1]) {
253
 
                            stack.shift();
254
 
                            stack.shift();
255
 
                            this.next = stack.shift();
256
 
                        } else {
257
 
                            this.next = "";
258
 
                        }
259
 
                        return "comment";
260
 
                    },
261
 
                    
262
 
                    regex : /(?:[^\\]|\\.)*?\]=*\]/,
263
 
                    next  : "start"
264
 
                }, {
265
 
                    defaultToken : "comment"
266
 
                }
267
 
            ]
268
 
        },
269
 
        {
270
 
            token : "string",           // " string
271
 
            regex : '"(?:[^\\\\]|\\\\.)*?"'
272
 
        }, {
273
 
            token : "string",           // ' string
274
 
            regex : "'(?:[^\\\\]|\\\\.)*?'"
275
 
        }, {
276
 
            token : "constant.numeric", // float
277
 
            regex : floatNumber
278
 
        }, {
279
 
            token : "constant.numeric", // integer
280
 
            regex : integer + "\\b"
281
 
        }, {
282
 
            token : keywordMapper,
283
 
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
284
 
        }, {
285
 
            token : "keyword.operator",
286
 
            regex : "\\+|\\-|\\*|\\/|%|\\#|\\^|~|<|>|<=|=>|==|~=|=|\\:|\\.\\.\\.|\\.\\."
287
 
        }, {
288
 
            token : "paren.lparen",
289
 
            regex : "[\\[\\(\\{]"
290
 
        }, {
291
 
            token : "paren.rparen",
292
 
            regex : "[\\]\\)\\}]"
293
 
        }, {
294
 
            token : "text",
295
 
            regex : "\\s+|\\w+"
296
 
        } ]
297
 
    };
298
 
    
299
 
    this.normalizeRules();
300
 
}
301
 
 
302
 
oop.inherits(LuaHighlightRules, TextHighlightRules);
303
 
 
304
 
exports.LuaHighlightRules = LuaHighlightRules;
305
 
});
306
 
 
307
 
define('ace/mode/folding/lua', ['require', 'exports', 'module' , 'ace/lib/oop', 'ace/mode/folding/fold_mode', 'ace/range', 'ace/token_iterator'], function(require, exports, module) {
308
 
 
309
 
 
310
 
var oop = require("../../lib/oop");
311
 
var BaseFoldMode = require("./fold_mode").FoldMode;
312
 
var Range = require("../../range").Range;
313
 
var TokenIterator = require("../../token_iterator").TokenIterator;
314
 
 
315
 
 
316
 
var FoldMode = exports.FoldMode = function() {};
317
 
 
318
 
oop.inherits(FoldMode, BaseFoldMode);
319
 
 
320
 
(function() {
321
 
 
322
 
    this.foldingStartMarker = /\b(function|then|do|repeat)\b|{\s*$|(\[=*\[)/;
323
 
    this.foldingStopMarker = /\bend\b|^\s*}|\]=*\]/;
324
 
 
325
 
    this.getFoldWidget = function(session, foldStyle, row) {
326
 
        var line = session.getLine(row);
327
 
        var isStart = this.foldingStartMarker.test(line);
328
 
        var isEnd = this.foldingStopMarker.test(line);
329
 
 
330
 
        if (isStart && !isEnd) {
331
 
            var match = line.match(this.foldingStartMarker);
332
 
            if (match[1] == "then" && /\belseif\b/.test(line))
333
 
                return;
334
 
            if (match[1]) {
335
 
                if (session.getTokenAt(row, match.index + 1).type === "keyword")
336
 
                    return "start";
337
 
            } else if (match[2]) {
338
 
                var type = session.bgTokenizer.getState(row) || "";
339
 
                if (type[0] == "bracketedComment" || type[0] == "bracketedString")
340
 
                    return "start";
341
 
            } else {
342
 
                return "start";
343
 
            }
344
 
        }
345
 
        if (foldStyle != "markbeginend" || !isEnd || isStart && isEnd)
346
 
            return "";
347
 
 
348
 
        var match = line.match(this.foldingStopMarker);
349
 
        if (match[0] === "end") {
350
 
            if (session.getTokenAt(row, match.index + 1).type === "keyword")
351
 
                return "end";
352
 
        } else if (match[0][0] === "]") {
353
 
            var type = session.bgTokenizer.getState(row - 1) || "";
354
 
            if (type[0] == "bracketedComment" || type[0] == "bracketedString")
355
 
                return "end";
356
 
        } else
357
 
            return "end";
358
 
    };
359
 
 
360
 
    this.getFoldWidgetRange = function(session, foldStyle, row) {
361
 
        var line = session.doc.getLine(row);
362
 
        var match = this.foldingStartMarker.exec(line);
363
 
        if (match) {
364
 
            if (match[1])
365
 
                return this.luaBlock(session, row, match.index + 1);
366
 
 
367
 
            if (match[2])
368
 
                return session.getCommentFoldRange(row, match.index + 1);
369
 
 
370
 
            return this.openingBracketBlock(session, "{", row, match.index);
371
 
        }
372
 
 
373
 
        var match = this.foldingStopMarker.exec(line);
374
 
        if (match) {
375
 
            if (match[0] === "end") {
376
 
                if (session.getTokenAt(row, match.index + 1).type === "keyword")
377
 
                    return this.luaBlock(session, row, match.index + 1);
378
 
            }
379
 
 
380
 
            if (match[0][0] === "]")
381
 
                return session.getCommentFoldRange(row, match.index + 1);
382
 
 
383
 
            return this.closingBracketBlock(session, "}", row, match.index + match[0].length);
384
 
        }
385
 
    };
386
 
 
387
 
    this.luaBlock = function(session, row, column) {
388
 
        var stream = new TokenIterator(session, row, column);
389
 
        var indentKeywords = {
390
 
            "function": 1,
391
 
            "do": 1,
392
 
            "then": 1,
393
 
            "elseif": -1,
394
 
            "end": -1,
395
 
            "repeat": 1,
396
 
            "until": -1,
397
 
        };
398
 
 
399
 
        var token = stream.getCurrentToken();
400
 
        if (!token || token.type != "keyword")
401
 
            return;
402
 
 
403
 
        var val = token.value;
404
 
        var stack = [val];
405
 
        var dir = indentKeywords[val];
406
 
 
407
 
        if (!dir)
408
 
            return;
409
 
 
410
 
        var startColumn = dir === -1 ? stream.getCurrentTokenColumn() : session.getLine(row).length;
411
 
        var startRow = row;
412
 
 
413
 
        stream.step = dir === -1 ? stream.stepBackward : stream.stepForward;
414
 
        while(token = stream.step()) {
415
 
            if (token.type !== "keyword")
416
 
                continue;
417
 
            var level = dir * indentKeywords[token.value];
418
 
 
419
 
            if (level > 0) {
420
 
                stack.unshift(token.value);
421
 
            } else if (level <= 0) {
422
 
                stack.shift();
423
 
                if (!stack.length && token.value != "elseif")
424
 
                    break;
425
 
                if (level === 0)
426
 
                    stack.unshift(token.value);
427
 
            }
428
 
        }
429
 
 
430
 
        var row = stream.getCurrentTokenRow();
431
 
        if (dir === -1)
432
 
            return new Range(row, session.getLine(row).length, startRow, startColumn);
433
 
        else
434
 
            return new Range(startRow, startColumn, row, stream.getCurrentTokenColumn());
435
 
    };
436
 
 
437
 
}).call(FoldMode.prototype);
438
 
 
439
 
});