2 * LESS - Leaner CSS v1.5.1
5 * Copyright (c) 2009-2013, Alexis Sellier <self@cloudhead.net>
6 * Licensed under the Apache v2 License.
13 (function (window, undefined) {//
14 // Stub out `require` in the browser
16 function require(arg) {
17 return window.less[arg.split('/')[1]];
21 if (typeof(window.less) === 'undefined' || typeof(window.less.nodeType) !== 'undefined') { window.less = {}; }
23 tree = window.less.tree = {};
24 less.mode = 'browser';
28 // Node.js does not have a header file added which defines less
29 if (less === undefined) {
31 tree = require('./tree');
37 // A relatively straight-forward predictive parser.
38 // There is no tokenization/lexing stage, the input is parsed
41 // To make the parser fast enough to run in the browser, several
42 // optimization had to be made:
44 // - Matching and slicing on a huge input is often cause of slowdowns.
45 // The solution is to chunkify the input into smaller strings.
46 // The chunks are stored in the `chunks` var,
47 // `j` holds the current chunk index, and `current` holds
48 // the index of the current chunk in relation to `input`.
49 // This gives us an almost 4x speed-up.
51 // - In many cases, we don't need to match individual tokens;
52 // for example, if a value doesn't hold any variables, operations
53 // or dynamic references, the parser can effectively 'skip' it,
54 // treating it as a literal.
55 // An example would be '1px solid #000' - which evaluates to itself,
56 // we don't need to know what the individual components are.
57 // The drawback, of course is that you don't get the benefits of
58 // syntax-checking on the CSS. This gives us a 50% speed-up in the parser,
59 // and a smaller speed-up in the code-gen.
62 // Token matching is done with the `$` function, which either takes
63 // a terminal string or regexp, or a non-terminal function to call.
64 // It also takes care of moving all the indices forwards.
67 less.Parser = function Parser(env) {
68 var input, // LeSS input string
69 i, // current index in `input`
71 temp, // temporarily holds a chunk's state, for backtracking
72 memo, // temporarily holds `i`, when backtracking
73 furthest, // furthest index the parser has gone to
74 chunks, // chunkified input
75 current, // index of current chunk, in `input`
77 rootFilename = env && env.filename;
79 // Top parser on an import tree must be sure there is one "env"
80 // which will then be passed around by reference.
81 if (!(env instanceof tree.parseEnv)) {
82 env = new tree.parseEnv(env);
85 var imports = this.imports = {
86 paths: env.paths || [], // Search paths, when importing
87 queue: [], // Files which haven't been imported yet
88 files: env.files, // Holds the imported parse trees
89 contents: env.contents, // Holds the imported file contents
90 mime: env.mime, // MIME type of .less files
91 error: null, // Error in parsing/evaluating an import
92 push: function (path, currentFileInfo, importOptions, callback) {
93 var parserImports = this;
94 this.queue.push(path);
96 var fileParsedFunc = function (e, root, fullPath) {
97 parserImports.queue.splice(parserImports.queue.indexOf(path), 1); // Remove the path from the queue
99 var importedPreviously = fullPath in parserImports.files || fullPath === rootFilename;
101 parserImports.files[fullPath] = root; // Store the root
103 if (e && !parserImports.error) { parserImports.error = e; }
105 callback(e, root, importedPreviously, fullPath);
108 if (less.Parser.importer) {
109 less.Parser.importer(path, currentFileInfo, fileParsedFunc, env);
111 less.Parser.fileLoader(path, currentFileInfo, function(e, contents, fullPath, newFileInfo) {
112 if (e) {fileParsedFunc(e); return;}
114 var newEnv = new tree.parseEnv(env);
116 newEnv.currentFileInfo = newFileInfo;
117 newEnv.processImports = false;
118 newEnv.contents[fullPath] = contents;
120 if (currentFileInfo.reference || importOptions.reference) {
121 newFileInfo.reference = true;
124 if (importOptions.inline) {
125 fileParsedFunc(null, contents, fullPath);
127 new(less.Parser)(newEnv).parse(contents, function (e, root) {
128 fileParsedFunc(e, root, fullPath);
136 function save() { temp = chunks[j], memo = i, current = i; }
137 function restore() { chunks[j] = temp, i = memo, current = i; }
141 chunks[j] = chunks[j].slice(i - current);
145 function isWhitespace(c) {
146 // Could change to \s?
147 var code = c.charCodeAt(0);
148 return code === 32 || code === 10 || code === 9;
151 // Parse from a token, regexp or string, and move forward if match
159 if (tok instanceof Function) {
160 return tok.call(parser.parsers);
164 // Either match a single character in the input,
165 // or match a regexp in the current chunk (chunk[j]).
167 } else if (typeof(tok) === 'string') {
168 match = input.charAt(i) === tok ? tok : null;
174 if (match = tok.exec(chunks[j])) {
175 length = match[0].length;
181 // The match is confirmed, add the match length to `i`,
182 // and consume any extra white-space characters (' ' || '\n')
183 // which come after that. The reason for this is that LeSS's
184 // grammar is mostly white-space insensitive.
187 skipWhitespace(length);
189 if(typeof(match) === 'string') {
192 return match.length === 1 ? match[0] : match;
197 function skipWhitespace(length) {
198 var oldi = i, oldj = j,
199 endIndex = i + chunks[j].length,
202 while (i < endIndex) {
203 if (! isWhitespace(input.charAt(i))) { break; }
206 chunks[j] = chunks[j].slice(length + (i - mem));
209 if (chunks[j].length === 0 && j < chunks.length - 1) { j++; }
211 return oldi !== i || oldj !== j;
214 function expect(arg, msg) {
217 error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + input.charAt(i) + "'"
218 : "unexpected token"));
224 function error(msg, type) {
225 var e = new Error(msg);
227 e.type = type || 'Syntax';
231 // Same as $(), but don't change the state of the parser,
232 // just return the match.
234 if (typeof(tok) === 'string') {
235 return input.charAt(i) === tok;
237 return tok.test(chunks[j]);
241 function getInput(e, env) {
242 if (e.filename && env.currentFileInfo.filename && (e.filename !== env.currentFileInfo.filename)) {
243 return parser.imports.contents[e.filename];
249 function getLocation(index, inputStream) {
254 while (--n >= 0 && inputStream.charAt(n) !== '\n') {
258 if (typeof index === 'number') {
259 line = (inputStream.slice(0, index).match(/\n/g) || "").length;
268 function getDebugInfo(index, inputStream, env) {
269 var filename = env.currentFileInfo.filename;
270 if(less.mode !== 'browser' && less.mode !== 'rhino') {
271 filename = require('path').resolve(filename);
275 lineNumber: getLocation(index, inputStream).line + 1,
280 function LessError(e, env) {
281 var input = getInput(e, env),
282 loc = getLocation(e.index, input),
285 callLine = e.call && getLocation(e.call, input).line,
286 lines = input.split('\n');
288 this.type = e.type || 'Syntax';
289 this.message = e.message;
290 this.filename = e.filename || env.currentFileInfo.filename;
291 this.index = e.index;
292 this.line = typeof(line) === 'number' ? line + 1 : null;
293 this.callLine = callLine + 1;
294 this.callExtract = lines[callLine];
295 this.stack = e.stack;
304 LessError.prototype = new Error();
305 LessError.prototype.constructor = LessError;
307 this.env = env = env || {};
309 // The optimization level dictates the thoroughness of the parser,
310 // the lower the number, the less nodes it will create in the tree.
311 // This could matter for debugging, or if you want to access
312 // the individual nodes in the tree.
313 this.optimization = ('optimization' in this.env) ? this.env.optimization : 1;
322 // Parse an input string into an abstract syntax tree,
323 // call `callback` when done.
325 parse: function (str, callback) {
326 var root, line, lines, error = null;
328 i = j = current = furthest = 0;
329 input = str.replace(/\r\n/g, '\n');
331 // Remove potential UTF Byte Order Mark
332 input = input.replace(/^\uFEFF/, '');
334 parser.imports.contents[env.currentFileInfo.filename] = input;
336 // Split the input into chunks.
337 chunks = (function (chunks) {
339 skip = /(?:@\{[\w-]+\}|[^"'`\{\}\/\(\)\\])+/g,
340 comment = /\/\*(?:[^*]|\*+[^\/*])*\*+\/|\/\/.*/g,
341 string = /"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'|`((?:[^`]|\\.)*)`/g,
347 for (var i = 0, c, cc; i < input.length;) {
349 if (match = skip.exec(input)) {
350 if (match.index === i) {
351 i += match[0].length;
352 chunk.push(match[0]);
356 comment.lastIndex = string.lastIndex = i;
358 if (match = string.exec(input)) {
359 if (match.index === i) {
360 i += match[0].length;
361 chunk.push(match[0]);
366 if (!inParam && c === '/') {
367 cc = input.charAt(i + 1);
368 if (cc === '/' || cc === '*') {
369 if (match = comment.exec(input)) {
370 if (match.index === i) {
371 i += match[0].length;
372 chunk.push(match[0]);
391 chunks[++j] = chunk = [];
416 error = new(LessError)({
419 message: (level > 0) ? "missing closing `}`" : "missing opening `{`",
420 filename: env.currentFileInfo.filename
424 return chunks.map(function (c) { return c.join(''); });
428 return callback(new(LessError)(error, env));
431 // Start with the primary rule.
432 // The whole syntax tree is held under a Ruleset node,
433 // with the `root` property set to true, so no `{}` are
434 // output. The callback is called when the input is parsed.
436 root = new(tree.Ruleset)([], $(this.parsers.primary));
438 root.firstRoot = true;
440 return callback(new(LessError)(e, env));
443 root.toCSS = (function (evaluate) {
444 return function (options, variables) {
445 options = options || {};
448 evalEnv = new tree.evalEnv(options);
451 // Allows setting variables with a hash, so:
453 // `{ color: new(tree.Color)('#f01') }` will become:
455 // new(tree.Rule)('@color',
457 // new(tree.Expression)([
458 // new(tree.Color)('#f01')
463 if (typeof(variables) === 'object' && !Array.isArray(variables)) {
464 variables = Object.keys(variables).map(function (k) {
465 var value = variables[k];
467 if (! (value instanceof tree.Value)) {
468 if (! (value instanceof tree.Expression)) {
469 value = new(tree.Expression)([value]);
471 value = new(tree.Value)([value]);
473 return new(tree.Rule)('@' + k, value, false, null, 0);
475 evalEnv.frames = [new(tree.Ruleset)(null, variables)];
479 evaldRoot = evaluate.call(this, evalEnv);
481 new(tree.joinSelectorVisitor)()
484 new(tree.processExtendsVisitor)()
487 new(tree.toCSSVisitor)({compress: Boolean(options.compress)})
490 if (options.sourceMap) {
491 evaldRoot = new tree.sourceMapOutput(
493 writeSourceMap: options.writeSourceMap,
495 contentsMap: parser.imports.contents,
496 sourceMapFilename: options.sourceMapFilename,
497 sourceMapURL: options.sourceMapURL,
498 outputFilename: options.sourceMapOutputFilename,
499 sourceMapBasepath: options.sourceMapBasepath,
500 sourceMapRootpath: options.sourceMapRootpath,
501 outputSourceFiles: options.outputSourceFiles,
502 sourceMapGenerator: options.sourceMapGenerator
506 css = evaldRoot.toCSS({
507 compress: Boolean(options.compress),
508 dumpLineNumbers: env.dumpLineNumbers,
509 strictUnits: Boolean(options.strictUnits)});
511 throw new(LessError)(e, env);
514 if (options.cleancss && less.mode === 'node') {
515 var CleanCSS = require('clean-css');
516 //TODO would be nice for no advanced to be an option
517 return new CleanCSS({keepSpecialComments: '*', processImport: false, noRebase: true, noAdvanced: true}).minify(css);
518 } else if (options.compress) {
519 return css.replace(/(^(\s)+)|((\s)+$)/g, "");
526 // If `i` is smaller than the `input.length - 1`,
527 // it means the parser wasn't able to parse the whole
528 // string, so we've got a parsing error.
530 // We try to extract a \n delimited string,
531 // showing the line where the parse error occured.
532 // We split it up into two parts (the part which parsed,
533 // and the part which didn't), so we can color them differently.
534 if (i < input.length - 1) {
536 var loc = getLocation(i, input);
537 lines = input.split('\n');
542 message: "Unrecognised input",
544 filename: env.currentFileInfo.filename,
555 var finish = function (e) {
556 e = error || e || parser.imports.error;
559 if (!(e instanceof LessError)) {
560 e = new(LessError)(e, env);
566 return callback(null, root);
570 if (env.processImports !== false) {
571 new tree.importVisitor(this.imports, finish)
579 // Here in, the parsing rules/functions
581 // The basic structure of the syntax tree generated is as follows:
583 // Ruleset -> Rule -> Value -> Expression -> Entity
585 // Here's some LESS code:
589 // border: 1px solid #000;
594 // And here's what the parse tree might look like:
596 // Ruleset (Selector '.class', [
597 // Rule ("color", Value ([Expression [Color #fff]]))
598 // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]]))
599 // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]]))
600 // Ruleset (Selector [Element '>', '.child'], [...])
603 // In general, most rules will try to parse a token with the `$()` function, and if the return
604 // value is truly, will return a new node, of the relevant type. Sometimes, we need to check
605 // first, before parsing, that's when we use `peek()`.
609 // The `primary` rule is the *entry* and *exit* point of the parser.
610 // The rules here can appear at any level of the parse tree.
612 // The recursive nature of the grammar is an interplay between the `block`
613 // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule,
614 // as represented by this simplified grammar:
616 // primary → (ruleset | rule)+
617 // ruleset → selector+ block
618 // block → '{' primary '}'
620 // Only at one point is the primary rule not called from the
621 // block rule: at the root level.
623 primary: function () {
626 while ((node = $(this.extendRule) || $(this.mixin.definition) || $(this.rule) || $(this.ruleset) ||
627 $(this.mixin.call) || $(this.comment) || $(this.directive))
628 || $(/^[\s\n]+/) || $(/^;+/)) {
629 node && root.push(node);
634 // We create a Comment node for CSS comments `/* */`,
635 // but keep the LeSS comments `//` silent, by just skipping
637 comment: function () {
640 if (input.charAt(i) !== '/') { return; }
642 if (input.charAt(i + 1) === '/') {
643 return new(tree.Comment)($(/^\/\/.*/), true, i, env.currentFileInfo);
644 } else if (comment = $(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/)) {
645 return new(tree.Comment)(comment, false, i, env.currentFileInfo);
649 comments: function () {
650 var comment, comments = [];
652 while(comment = $(this.comment)) {
653 comments.push(comment);
660 // Entities are tokens which can be found inside an Expression
664 // A string, which supports escaping " and '
666 // "milky way" 'he\'s the one!'
668 quoted: function () {
669 var str, j = i, e, index = i;
671 if (input.charAt(j) === '~') { j++, e = true; } // Escaped strings
672 if (input.charAt(j) !== '"' && input.charAt(j) !== "'") { return; }
676 if (str = $(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/)) {
677 return new(tree.Quoted)(str[0], str[1] || str[2], e, index, env.currentFileInfo);
682 // A catch-all word, such as:
684 // black border-collapse
686 keyword: function () {
689 if (k = $(/^[_A-Za-z-][_A-Za-z0-9-]*/)) {
690 var color = tree.Color.fromKeyword(k);
694 return new(tree.Keyword)(k);
703 // We also try to catch IE's `alpha()`, but let the `alpha` parser
704 // deal with the details.
706 // The arguments are parsed with the `entities.arguments` parser.
709 var name, nameLC, args, alpha_ret, index = i;
711 if (! (name = /^([\w-]+|%|progid:[\w\.]+)\(/.exec(chunks[j]))) { return; }
714 nameLC = name.toLowerCase();
716 if (nameLC === 'url') { return null; }
717 else { i += name.length; }
719 if (nameLC === 'alpha') {
720 alpha_ret = $(this.alpha);
721 if(typeof alpha_ret !== 'undefined') {
726 $('('); // Parse the '(' and consume whitespace.
728 args = $(this.entities.arguments);
734 if (name) { return new(tree.Call)(name, args, index, env.currentFileInfo); }
736 arguments: function () {
739 while (arg = $(this.entities.assignment) || $(this.expression)) {
747 literal: function () {
748 return $(this.entities.dimension) ||
749 $(this.entities.color) ||
750 $(this.entities.quoted) ||
751 $(this.entities.unicodeDescriptor);
754 // Assignments are argument entities for calls.
755 // They are present in ie filter properties as shown below.
757 // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* )
760 assignment: function () {
762 if ((key = $(/^\w+(?=\s?=)/i)) && $('=') && (value = $(this.entity))) {
763 return new(tree.Assignment)(key, value);
768 // Parse url() tokens
770 // We use a specific rule for urls, because they don't really behave like
771 // standard function calls. The difference is that the argument doesn't have
772 // to be enclosed within a string, so it can't be parsed as an Expression.
777 if (input.charAt(i) !== 'u' || !$(/^url\(/)) {
781 value = $(this.entities.quoted) || $(this.entities.variable) ||
782 $(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || "";
786 /*jshint eqnull:true */
787 return new(tree.URL)((value.value != null || value instanceof tree.Variable)
788 ? value : new(tree.Anonymous)(value), env.currentFileInfo);
792 // A Variable entity, such as `@fink`, in
794 // width: @fink + 2px
796 // We use a different parser for variable definitions,
797 // see `parsers.variable`.
799 variable: function () {
802 if (input.charAt(i) === '@' && (name = $(/^@@?[\w-]+/))) {
803 return new(tree.Variable)(name, index, env.currentFileInfo);
807 // A variable entity useing the protective {} e.g. @{var}
808 variableCurly: function () {
809 var curly, index = i;
811 if (input.charAt(i) === '@' && (curly = $(/^@\{([\w-]+)\}/))) {
812 return new(tree.Variable)("@" + curly[1], index, env.currentFileInfo);
817 // A Hexadecimal color
821 // `rgb` and `hsl` colors are parsed through the `entities.call` parser.
826 if (input.charAt(i) === '#' && (rgb = $(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) {
827 return new(tree.Color)(rgb[1]);
832 // A Dimension, that is, a number and a unit
836 dimension: function () {
837 var value, c = input.charCodeAt(i);
838 //Is the first char of the dimension 0-9, '.', '+' or '-'
839 if ((c > 57 || c < 43) || c === 47 || c == 44) {
843 if (value = $(/^([+-]?\d*\.?\d+)(%|[a-z]+)?/)) {
844 return new(tree.Dimension)(value[1], value[2]);
849 // A unicode descriptor, as is used in unicode-range
851 // U+0?? or U+00A1-00A9
853 unicodeDescriptor: function () {
856 if (ud = $(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/)) {
857 return new(tree.UnicodeDescriptor)(ud[0]);
862 // JavaScript code to be evaluated
864 // `window.location.href`
866 javascript: function () {
869 if (input.charAt(j) === '~') { j++; e = true; } // Escaped strings
870 if (input.charAt(j) !== '`') { return; }
871 if (env.javascriptEnabled !== undefined && !env.javascriptEnabled) {
872 error("You are using JavaScript, which has been disabled.");
877 if (str = $(/^`([^`]*)`/)) {
878 return new(tree.JavaScript)(str[1], i, e);
884 // The variable part of a variable definition. Used in the `rule` parser
888 variable: function () {
891 if (input.charAt(i) === '@' && (name = $(/^(@[\w-]+)\s*:/))) { return name[1]; }
895 // extend syntax - used to extend selectors
897 extend: function(isRule) {
898 var elements, e, index = i, option, extendList = [];
900 if (!$(isRule ? /^&:extend\(/ : /^:extend\(/)) { return; }
906 option = $(/^(all)(?=\s*(\)|,))/);
907 if (option) { break; }
913 option = option && option[1];
915 extendList.push(new(tree.Extend)(new(tree.Selector)(elements), option, index));
929 // extendRule - used in a rule to extend all the parent selectors
931 extendRule: function() {
932 return this.extend(true);
940 // A Mixin call, with an optional argument list
942 // #mixins > .square(#fff);
943 // .rounded(4px, black);
946 // The `while` loop is there because mixins can be
947 // namespaced, but we only support the child and descendant
951 var elements = [], e, c, args, index = i, s = input.charAt(i), important = false;
953 if (s !== '.' && s !== '#') { return; }
955 save(); // stop us absorbing part of an invalid selector
957 while (e = $(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/)) {
958 elements.push(new(tree.Element)(c, e, i, env.currentFileInfo));
962 args = this.mixin.args.call(this, true).args;
968 if ($(this.important)) {
972 if (elements.length > 0 && ($(';') || peek('}'))) {
973 return new(tree.mixin.Call)(elements, args, index, env.currentFileInfo, important);
978 args: function (isCall) {
979 var expressions = [], argsSemiColon = [], isSemiColonSeperated, argsComma = [], expressionContainsNamed, name, nameLoop, value, arg,
980 returner = {args:null, variadic: false};
983 arg = $(this.expression);
986 if (input.charAt(i) === '.' && $(/^\.{3}/)) {
987 returner.variadic = true;
988 if ($(";") && !isSemiColonSeperated) {
989 isSemiColonSeperated = true;
991 (isSemiColonSeperated ? argsSemiColon : argsComma)
992 .push({ variadic: true });
995 arg = $(this.entities.variable) || $(this.entities.literal)
996 || $(this.entities.keyword);
1004 if (arg.throwAwayComments) {
1005 arg.throwAwayComments();
1012 if (arg.value.length == 1) {
1019 if (val && val instanceof tree.Variable) {
1021 if (expressions.length > 0) {
1022 if (isSemiColonSeperated) {
1023 error("Cannot mix ; and , as delimiter types");
1025 expressionContainsNamed = true;
1027 value = expect(this.expression);
1028 nameLoop = (name = val.name);
1029 } else if (!isCall && $(/^\.{3}/)) {
1030 returner.variadic = true;
1031 if ($(";") && !isSemiColonSeperated) {
1032 isSemiColonSeperated = true;
1034 (isSemiColonSeperated ? argsSemiColon : argsComma)
1035 .push({ name: arg.name, variadic: true });
1037 } else if (!isCall) {
1038 name = nameLoop = val.name;
1044 expressions.push(value);
1047 argsComma.push({ name:nameLoop, value:value });
1053 if ($(';') || isSemiColonSeperated) {
1055 if (expressionContainsNamed) {
1056 error("Cannot mix ; and , as delimiter types");
1059 isSemiColonSeperated = true;
1061 if (expressions.length > 1) {
1062 value = new(tree.Value)(expressions);
1064 argsSemiColon.push({ name:name, value:value });
1068 expressionContainsNamed = false;
1072 returner.args = isSemiColonSeperated ? argsSemiColon : argsComma;
1076 // A Mixin definition, with a list of parameters
1078 // .rounded (@radius: 2px, @color) {
1082 // Until we have a finer grained state-machine, we have to
1083 // do a look-ahead, to make sure we don't have a mixin call.
1084 // See the `rule` function for more information.
1086 // We start by matching `.rounded (`, and then proceed on to
1087 // the argument list, which has optional default values.
1088 // We store the parameters in `params`, with a `value` key,
1089 // if there is a value, such as in the case of `@radius`.
1091 // Once we've got our params list, and a closing `)`, we parse
1092 // the `{...}` block.
1094 definition: function () {
1095 var name, params = [], match, ruleset, cond, variadic = false;
1096 if ((input.charAt(i) !== '.' && input.charAt(i) !== '#') ||
1103 if (match = $(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/)) {
1106 var argInfo = this.mixin.args.call(this, false);
1107 params = argInfo.args;
1108 variadic = argInfo.variadic;
1110 // .mixincall("@{a}");
1111 // looks a bit like a mixin definition.. so we have to be nice and restore
1119 if ($(/^when/)) { // Guard
1120 cond = expect(this.conditions, 'expected condition');
1123 ruleset = $(this.block);
1126 return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic);
1135 // Entities are the smallest recognized token,
1136 // and can be found inside a rule's value.
1138 entity: function () {
1139 return $(this.entities.literal) || $(this.entities.variable) || $(this.entities.url) ||
1140 $(this.entities.call) || $(this.entities.keyword) ||$(this.entities.javascript) ||
1145 // A Rule terminator. Note that we use `peek()` to check for '}',
1146 // because the `block` rule will be expecting it, but we still need to make sure
1147 // it's there, if ';' was ommitted.
1150 return $(';') || peek('}');
1154 // IE's alpha function
1156 // alpha(opacity=88)
1158 alpha: function () {
1161 if (! $(/^\(opacity=/i)) { return; }
1162 if (value = $(/^\d+/) || $(this.entities.variable)) {
1164 return new(tree.Alpha)(value);
1169 // A Selector Element
1174 // input[type="text"]
1176 // Elements are the building blocks for Selectors,
1177 // they are made out of a `Combinator` (see combinator rule),
1178 // and an element name, such as a tag a class, or `*`.
1180 element: function () {
1183 c = $(this.combinator);
1185 e = $(/^(?:\d+\.\d+|\d+)%/) || $(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) ||
1186 $('*') || $('&') || $(this.attribute) || $(/^\([^()@]+\)/) || $(/^[\.#](?=@)/) || $(this.entities.variableCurly);
1190 if ((v = ($(this.selector))) &&
1192 e = new(tree.Paren)(v);
1197 if (e) { return new(tree.Element)(c, e, i, env.currentFileInfo); }
1201 // Combinators combine elements together, in a Selector.
1203 // Because our parser isn't white-space sensitive, special care
1204 // has to be taken, when parsing the descendant combinator, ` `,
1205 // as it's an empty space. We have to check the previous character
1206 // in the input, to see if it's a ` ` character. More info on how
1207 // we deal with this in *combinator.js*.
1209 combinator: function () {
1210 var c = input.charAt(i);
1212 if (c === '>' || c === '+' || c === '~' || c === '|') {
1214 while (input.charAt(i).match(/\s/)) { i++; }
1215 return new(tree.Combinator)(c);
1216 } else if (input.charAt(i - 1).match(/\s/)) {
1217 return new(tree.Combinator)(" ");
1219 return new(tree.Combinator)(null);
1223 // A CSS selector (see selector below)
1224 // with less extensions e.g. the ability to extend and guard
1226 lessSelector: function () {
1227 return this.selector(true);
1232 // .class > div + h1
1235 // Selectors are made out of one or more Elements, see above.
1237 selector: function (isLess) {
1238 var e, elements = [], c, extend, extendList = [], when, condition;
1240 while ((isLess && (extend = $(this.extend))) || (isLess && (when = $(/^when/))) || (e = $(this.element))) {
1242 condition = expect(this.conditions, 'expected condition');
1243 } else if (condition) {
1244 error("CSS guard can only be used at the end of selector");
1245 } else if (extend) {
1246 extendList.push.apply(extendList, extend);
1248 if (extendList.length) {
1249 error("Extend can only be used at the end of selector");
1251 c = input.charAt(i);
1255 if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') {
1260 if (elements.length > 0) { return new(tree.Selector)(elements, extendList, condition, i, env.currentFileInfo); }
1261 if (extendList.length) { error("Extend must be used to extend a selector, it cannot be used on its own"); }
1263 attribute: function () {
1266 if (! $('[')) { return; }
1268 if (!(key = $(this.entities.variableCurly))) {
1269 key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/);
1272 if ((op = $(/^[|~*$^]?=/))) {
1273 val = $(this.entities.quoted) || $(/^[0-9]+%/) || $(/^[\w-]+/) || $(this.entities.variableCurly);
1278 return new(tree.Attribute)(key, op, val);
1282 // The `block` rule is used by `ruleset` and `mixin.definition`.
1283 // It's a wrapper around the `primary` rule, with added `{}`.
1285 block: function () {
1287 if ($('{') && (content = $(this.primary)) && $('}')) {
1293 // div, .class, body > p {...}
1295 ruleset: function () {
1296 var selectors = [], s, rules, debugInfo;
1300 if (env.dumpLineNumbers) {
1301 debugInfo = getDebugInfo(i, input, env);
1304 while (s = $(this.lessSelector)) {
1307 if (! $(',')) { break; }
1309 error("Guards are only currently allowed on a single selector.");
1314 if (selectors.length > 0 && (rules = $(this.block))) {
1315 var ruleset = new(tree.Ruleset)(selectors, rules, env.strictImports);
1316 if (env.dumpLineNumbers) {
1317 ruleset.debugInfo = debugInfo;
1326 rule: function (tryAnonymous) {
1327 var name, value, c = input.charAt(i), important, merge = false;
1330 if (c === '.' || c === '#' || c === '&') { return; }
1332 if (name = $(this.variable) || $(this.ruleProperty)) {
1333 // prefer to try to parse first if its a variable or we are compressing
1334 // but always fallback on the other one
1335 value = !tryAnonymous && (env.compress || (name.charAt(0) === '@')) ?
1336 ($(this.value) || $(this.anonymousValue)) :
1337 ($(this.anonymousValue) || $(this.value));
1340 important = $(this.important);
1341 if (name[name.length-1] === "+") {
1343 name = name.substr(0, name.length - 1);
1346 if (value && $(this.end)) {
1347 return new (tree.Rule)(name, value, important, merge, memo, env.currentFileInfo);
1351 if (value && !tryAnonymous) {
1352 return this.rule(true);
1357 anonymousValue: function () {
1359 if (match = /^([^@+\/'"*`(;{}-]*);/.exec(chunks[j])) {
1360 i += match[0].length - 1;
1361 return new(tree.Anonymous)(match[1]);
1366 // An @import directive
1370 // Depending on our environemnt, importing is done differently:
1371 // In the browser, it's an XHR request, in Node, it would be a
1372 // file-system operation. The function used for importing is
1373 // stored in `import`, which we pass to the Import constructor.
1375 "import": function () {
1376 var path, features, index = i;
1380 var dir = $(/^@import?\s+/);
1382 var options = (dir ? $(this.importOptions) : null) || {};
1384 if (dir && (path = $(this.entities.quoted) || $(this.entities.url))) {
1385 features = $(this.mediaFeatures);
1387 features = features && new(tree.Value)(features);
1388 return new(tree.Import)(path, features, options, index, env.currentFileInfo);
1395 importOptions: function() {
1396 var o, options = {}, optionName, value;
1398 // list of options, surrounded by parens
1399 if (! $('(')) { return null; }
1401 if (o = $(this.importOption)) {
1404 switch(optionName) {
1406 optionName = "less";
1410 optionName = "multiple";
1414 options[optionName] = value;
1415 if (! $(',')) { break; }
1422 importOption: function() {
1423 var opt = $(/^(less|css|multiple|once|inline|reference)/);
1429 mediaFeature: function () {
1430 var e, p, nodes = [];
1433 if (e = ($(this.entities.keyword) || $(this.entities.variable))) {
1435 } else if ($('(')) {
1436 p = $(this.property);
1440 nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, null, i, env.currentFileInfo, true)));
1442 nodes.push(new(tree.Paren)(e));
1446 } else { return null; }
1450 if (nodes.length > 0) {
1451 return new(tree.Expression)(nodes);
1455 mediaFeatures: function () {
1456 var e, features = [];
1459 if (e = $(this.mediaFeature)) {
1461 if (! $(',')) { break; }
1462 } else if (e = $(this.entities.variable)) {
1464 if (! $(',')) { break; }
1468 return features.length > 0 ? features : null;
1471 media: function () {
1472 var features, rules, media, debugInfo;
1474 if (env.dumpLineNumbers) {
1475 debugInfo = getDebugInfo(i, input, env);
1479 features = $(this.mediaFeatures);
1481 if (rules = $(this.block)) {
1482 media = new(tree.Media)(rules, features, i, env.currentFileInfo);
1483 if (env.dumpLineNumbers) {
1484 media.debugInfo = debugInfo;
1494 // @charset "utf-8";
1496 directive: function () {
1497 var name, value, rules, nonVendorSpecificName,
1498 hasBlock, hasIdentifier, hasExpression, identifier;
1500 if (input.charAt(i) !== '@') { return; }
1502 if (value = $(this['import']) || $(this.media)) {
1508 name = $(/^@[a-z-]+/);
1510 if (!name) { return; }
1512 nonVendorSpecificName = name;
1513 if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) {
1514 nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1);
1517 switch(nonVendorSpecificName) {
1523 case "@top-left-corner":
1526 case "@top-right-corner":
1527 case "@bottom-left":
1528 case "@bottom-left-corner":
1529 case "@bottom-center":
1530 case "@bottom-right":
1531 case "@bottom-right-corner":
1533 case "@left-middle":
1534 case "@left-bottom":
1536 case "@right-middle":
1537 case "@right-bottom":
1546 hasIdentifier = true;
1549 hasExpression = true;
1553 if (hasIdentifier) {
1554 identifier = ($(/^[^{]+/) || '').trim();
1556 name += " " + identifier;
1562 if (rules = $(this.block)) {
1563 return new(tree.Directive)(name, rules, i, env.currentFileInfo);
1566 if ((value = hasExpression ? $(this.expression) : $(this.entity)) && $(';')) {
1567 var directive = new(tree.Directive)(name, value, i, env.currentFileInfo);
1568 if (env.dumpLineNumbers) {
1569 directive.debugInfo = getDebugInfo(i, input, env);
1579 // A Value is a comma-delimited list of Expressions
1581 // font-family: Baskerville, Georgia, serif;
1583 // In a Rule, a Value represents everything after the `:`,
1584 // and before the `;`.
1586 value: function () {
1587 var e, expressions = [];
1589 while (e = $(this.expression)) {
1590 expressions.push(e);
1591 if (! $(',')) { break; }
1594 if (expressions.length > 0) {
1595 return new(tree.Value)(expressions);
1598 important: function () {
1599 if (input.charAt(i) === '!') {
1600 return $(/^! *important/);
1607 if (a = $(this.addition)) {
1608 e = new(tree.Expression)([a]);
1615 multiplication: function () {
1616 var m, a, op, operation, isSpaced;
1617 if (m = $(this.operand)) {
1618 isSpaced = isWhitespace(input.charAt(i - 1));
1619 while (!peek(/^\/[*\/]/) && (op = ($('/') || $('*')))) {
1620 if (a = $(this.operand)) {
1621 m.parensInOp = true;
1622 a.parensInOp = true;
1623 operation = new(tree.Operation)(op, [operation || m, a], isSpaced);
1624 isSpaced = isWhitespace(input.charAt(i - 1));
1629 return operation || m;
1632 addition: function () {
1633 var m, a, op, operation, isSpaced;
1634 if (m = $(this.multiplication)) {
1635 isSpaced = isWhitespace(input.charAt(i - 1));
1636 while ((op = $(/^[-+]\s+/) || (!isSpaced && ($('+') || $('-')))) &&
1637 (a = $(this.multiplication))) {
1638 m.parensInOp = true;
1639 a.parensInOp = true;
1640 operation = new(tree.Operation)(op, [operation || m, a], isSpaced);
1641 isSpaced = isWhitespace(input.charAt(i - 1));
1643 return operation || m;
1646 conditions: function () {
1647 var a, b, index = i, condition;
1649 if (a = $(this.condition)) {
1650 while (peek(/^,\s*(not\s*)?\(/) && $(',') && (b = $(this.condition))) {
1651 condition = new(tree.Condition)('or', condition || a, b, index);
1653 return condition || a;
1656 condition: function () {
1657 var a, b, c, op, index = i, negate = false;
1659 if ($(/^not/)) { negate = true; }
1661 if (a = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) {
1662 if (op = $(/^(?:>=|<=|=<|[<=>])/)) {
1663 if (b = $(this.addition) || $(this.entities.keyword) || $(this.entities.quoted)) {
1664 c = new(tree.Condition)(op, a, b, index, negate);
1666 error('expected expression');
1669 c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate);
1672 return $(/^and/) ? new(tree.Condition)('and', c, $(this.condition)) : c;
1677 // An operand is anything that can be part of an operation,
1678 // such as a Color, or a Variable
1680 operand: function () {
1681 var negate, p = input.charAt(i + 1);
1683 if (input.charAt(i) === '-' && (p === '@' || p === '(')) { negate = $('-'); }
1684 var o = $(this.sub) || $(this.entities.dimension) ||
1685 $(this.entities.color) || $(this.entities.variable) ||
1686 $(this.entities.call);
1689 o.parensInOp = true;
1690 o = new(tree.Negative)(o);
1697 // Expressions either represent mathematical operations,
1698 // or white-space delimited Entities.
1703 expression: function () {
1704 var e, delim, entities = [];
1706 while (e = $(this.addition) || $(this.entity)) {
1708 // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here
1709 if (!peek(/^\/[\/*]/) && (delim = $('/'))) {
1710 entities.push(new(tree.Anonymous)(delim));
1713 if (entities.length > 0) {
1714 return new(tree.Expression)(entities);
1717 property: function () {
1720 if (name = $(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/)) {
1724 ruleProperty: function () {
1727 if (name = $(/^(\*?-?[_a-zA-Z0-9-]+)\s*(\+?)\s*:/)) {
1728 return name[1] + (name[2] || "");
1739 rgb: function (r, g, b) {
1740 return this.rgba(r, g, b, 1.0);
1742 rgba: function (r, g, b, a) {
1743 var rgb = [r, g, b].map(function (c) { return scaled(c, 256); });
1745 return new(tree.Color)(rgb, a);
1747 hsl: function (h, s, l) {
1748 return this.hsla(h, s, l, 1.0);
1750 hsla: function (h, s, l, a) {
1752 h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h);
1753 if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; }
1754 else if (h * 2 < 1) { return m2; }
1755 else if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; }
1759 h = (number(h) % 360) / 360;
1760 s = clamp(number(s)); l = clamp(number(l)); a = clamp(number(a));
1762 var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
1763 var m1 = l * 2 - m2;
1765 return this.rgba(hue(h + 1/3) * 255,
1771 hsv: function(h, s, v) {
1772 return this.hsva(h, s, v, 1.0);
1775 hsva: function(h, s, v, a) {
1776 h = ((number(h) % 360) / 360) * 360;
1777 s = number(s); v = number(v); a = number(a);
1780 i = Math.floor((h / 60) % 6);
1786 v * (1 - (1 - f) * s)];
1787 var perm = [[0, 3, 1],
1794 return this.rgba(vs[perm[i][0]] * 255,
1795 vs[perm[i][1]] * 255,
1796 vs[perm[i][2]] * 255,
1800 hue: function (color) {
1801 return new(tree.Dimension)(Math.round(color.toHSL().h));
1803 saturation: function (color) {
1804 return new(tree.Dimension)(Math.round(color.toHSL().s * 100), '%');
1806 lightness: function (color) {
1807 return new(tree.Dimension)(Math.round(color.toHSL().l * 100), '%');
1809 hsvhue: function(color) {
1810 return new(tree.Dimension)(Math.round(color.toHSV().h));
1812 hsvsaturation: function (color) {
1813 return new(tree.Dimension)(Math.round(color.toHSV().s * 100), '%');
1815 hsvvalue: function (color) {
1816 return new(tree.Dimension)(Math.round(color.toHSV().v * 100), '%');
1818 red: function (color) {
1819 return new(tree.Dimension)(color.rgb[0]);
1821 green: function (color) {
1822 return new(tree.Dimension)(color.rgb[1]);
1824 blue: function (color) {
1825 return new(tree.Dimension)(color.rgb[2]);
1827 alpha: function (color) {
1828 return new(tree.Dimension)(color.toHSL().a);
1830 luma: function (color) {
1831 return new(tree.Dimension)(Math.round(color.luma() * color.alpha * 100), '%');
1833 saturate: function (color, amount) {
1834 // filter: saturate(3.2);
1835 // should be kept as is, so check for color
1839 var hsl = color.toHSL();
1841 hsl.s += amount.value / 100;
1842 hsl.s = clamp(hsl.s);
1845 desaturate: function (color, amount) {
1846 var hsl = color.toHSL();
1848 hsl.s -= amount.value / 100;
1849 hsl.s = clamp(hsl.s);
1852 lighten: function (color, amount) {
1853 var hsl = color.toHSL();
1855 hsl.l += amount.value / 100;
1856 hsl.l = clamp(hsl.l);
1859 darken: function (color, amount) {
1860 var hsl = color.toHSL();
1862 hsl.l -= amount.value / 100;
1863 hsl.l = clamp(hsl.l);
1866 fadein: function (color, amount) {
1867 var hsl = color.toHSL();
1869 hsl.a += amount.value / 100;
1870 hsl.a = clamp(hsl.a);
1873 fadeout: function (color, amount) {
1874 var hsl = color.toHSL();
1876 hsl.a -= amount.value / 100;
1877 hsl.a = clamp(hsl.a);
1880 fade: function (color, amount) {
1881 var hsl = color.toHSL();
1883 hsl.a = amount.value / 100;
1884 hsl.a = clamp(hsl.a);
1887 spin: function (color, amount) {
1888 var hsl = color.toHSL();
1889 var hue = (hsl.h + amount.value) % 360;
1891 hsl.h = hue < 0 ? 360 + hue : hue;
1896 // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein
1897 // http://sass-lang.com
1899 mix: function (color1, color2, weight) {
1901 weight = new(tree.Dimension)(50);
1903 var p = weight.value / 100.0;
1905 var a = color1.toHSL().a - color2.toHSL().a;
1907 var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0;
1910 var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2,
1911 color1.rgb[1] * w1 + color2.rgb[1] * w2,
1912 color1.rgb[2] * w1 + color2.rgb[2] * w2];
1914 var alpha = color1.alpha * p + color2.alpha * (1 - p);
1916 return new(tree.Color)(rgb, alpha);
1918 greyscale: function (color) {
1919 return this.desaturate(color, new(tree.Dimension)(100));
1921 contrast: function (color, dark, light, threshold) {
1922 // filter: contrast(3.2);
1923 // should be kept as is, so check for color
1927 if (typeof light === 'undefined') {
1928 light = this.rgba(255, 255, 255, 1.0);
1930 if (typeof dark === 'undefined') {
1931 dark = this.rgba(0, 0, 0, 1.0);
1933 //Figure out which is actually light and dark!
1934 if (dark.luma() > light.luma()) {
1939 if (typeof threshold === 'undefined') {
1942 threshold = number(threshold);
1944 if ((color.luma() * color.alpha) < threshold) {
1951 return new(tree.Anonymous)(str instanceof tree.JavaScript ? str.evaluated : str);
1953 escape: function (str) {
1954 return new(tree.Anonymous)(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B").replace(/\(/g, "%28").replace(/\)/g, "%29"));
1956 '%': function (quoted /* arg, arg, ...*/) {
1957 var args = Array.prototype.slice.call(arguments, 1),
1960 for (var i = 0; i < args.length; i++) {
1961 /*jshint loopfunc:true */
1962 str = str.replace(/%[sda]/i, function(token) {
1963 var value = token.match(/s/i) ? args[i].value : args[i].toCSS();
1964 return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value;
1967 str = str.replace(/%%/g, '%');
1968 return new(tree.Quoted)('"' + str + '"', str);
1970 unit: function (val, unit) {
1971 if(!(val instanceof tree.Dimension)) {
1972 throw { type: "Argument", message: "the first argument to unit must be a number" + (val instanceof tree.Operation ? ". Have you forgotten parenthesis?" : "") };
1974 return new(tree.Dimension)(val.value, unit ? unit.toCSS() : "");
1976 convert: function (val, unit) {
1977 return val.convertTo(unit.value);
1979 round: function (n, f) {
1980 var fraction = typeof(f) === "undefined" ? 0 : f.value;
1981 return this._math(function(num) { return num.toFixed(fraction); }, null, n);
1984 return new(tree.Dimension)(Math.PI);
1986 mod: function(a, b) {
1987 return new(tree.Dimension)(a.value % b.value, a.unit);
1989 pow: function(x, y) {
1990 if (typeof x === "number" && typeof y === "number") {
1991 x = new(tree.Dimension)(x);
1992 y = new(tree.Dimension)(y);
1993 } else if (!(x instanceof tree.Dimension) || !(y instanceof tree.Dimension)) {
1994 throw { type: "Argument", message: "arguments must be numbers" };
1997 return new(tree.Dimension)(Math.pow(x.value, y.value), x.unit);
1999 _math: function (fn, unit, n) {
2000 if (n instanceof tree.Dimension) {
2001 /*jshint eqnull:true */
2002 return new(tree.Dimension)(fn(parseFloat(n.value)), unit == null ? n.unit : unit);
2003 } else if (typeof(n) === 'number') {
2006 throw { type: "Argument", message: "argument must be a number" };
2009 _minmax: function (isMin, args) {
2010 args = Array.prototype.slice.call(args);
2011 switch(args.length) {
2012 case 0: throw { type: "Argument", message: "one or more arguments required" };
2013 case 1: return args[0];
2015 var i, j, current, currentUnified, referenceUnified, unit,
2016 order = [], // elems only contains original argument values.
2017 values = {}; // key is the unit.toString() for unified tree.Dimension values,
2018 // value is the index into the order array.
2019 for (i = 0; i < args.length; i++) {
2021 if (!(current instanceof tree.Dimension)) {
2022 order.push(current);
2025 currentUnified = current.unify();
2026 unit = currentUnified.unit.toString();
2028 if (j === undefined) {
2029 values[unit] = order.length;
2030 order.push(current);
2033 referenceUnified = order[j].unify();
2034 if ( isMin && currentUnified.value < referenceUnified.value ||
2035 !isMin && currentUnified.value > referenceUnified.value) {
2039 if (order.length == 1) {
2042 args = order.map(function (a) { return a.toCSS(this.env); })
2043 .join(this.env.compress ? "," : ", ");
2044 return new(tree.Anonymous)((isMin ? "min" : "max") + "(" + args + ")");
2047 return this._minmax(true, arguments);
2050 return this._minmax(false, arguments);
2052 argb: function (color) {
2053 return new(tree.Anonymous)(color.toARGB());
2056 percentage: function (n) {
2057 return new(tree.Dimension)(n.value * 100, '%');
2059 color: function (n) {
2060 if (n instanceof tree.Quoted) {
2061 var colorCandidate = n.value,
2063 returnColor = tree.Color.fromKeyword(colorCandidate);
2067 if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/.test(colorCandidate)) {
2068 return new(tree.Color)(colorCandidate.slice(1));
2070 throw { type: "Argument", message: "argument must be a color keyword or 3/6 digit hex e.g. #FFF" };
2072 throw { type: "Argument", message: "argument must be a string" };
2075 iscolor: function (n) {
2076 return this._isa(n, tree.Color);
2078 isnumber: function (n) {
2079 return this._isa(n, tree.Dimension);
2081 isstring: function (n) {
2082 return this._isa(n, tree.Quoted);
2084 iskeyword: function (n) {
2085 return this._isa(n, tree.Keyword);
2087 isurl: function (n) {
2088 return this._isa(n, tree.URL);
2090 ispixel: function (n) {
2091 return this.isunit(n, 'px');
2093 ispercentage: function (n) {
2094 return this.isunit(n, '%');
2096 isem: function (n) {
2097 return this.isunit(n, 'em');
2099 isunit: function (n, unit) {
2100 return (n instanceof tree.Dimension) && n.unit.is(unit.value || unit) ? tree.True : tree.False;
2102 _isa: function (n, Type) {
2103 return (n instanceof Type) ? tree.True : tree.False;
2106 /* Blending modes */
2108 multiply: function(color1, color2) {
2109 var r = color1.rgb[0] * color2.rgb[0] / 255;
2110 var g = color1.rgb[1] * color2.rgb[1] / 255;
2111 var b = color1.rgb[2] * color2.rgb[2] / 255;
2112 return this.rgb(r, g, b);
2114 screen: function(color1, color2) {
2115 var r = 255 - (255 - color1.rgb[0]) * (255 - color2.rgb[0]) / 255;
2116 var g = 255 - (255 - color1.rgb[1]) * (255 - color2.rgb[1]) / 255;
2117 var b = 255 - (255 - color1.rgb[2]) * (255 - color2.rgb[2]) / 255;
2118 return this.rgb(r, g, b);
2120 overlay: function(color1, color2) {
2121 var r = color1.rgb[0] < 128 ? 2 * color1.rgb[0] * color2.rgb[0] / 255 : 255 - 2 * (255 - color1.rgb[0]) * (255 - color2.rgb[0]) / 255;
2122 var g = color1.rgb[1] < 128 ? 2 * color1.rgb[1] * color2.rgb[1] / 255 : 255 - 2 * (255 - color1.rgb[1]) * (255 - color2.rgb[1]) / 255;
2123 var b = color1.rgb[2] < 128 ? 2 * color1.rgb[2] * color2.rgb[2] / 255 : 255 - 2 * (255 - color1.rgb[2]) * (255 - color2.rgb[2]) / 255;
2124 return this.rgb(r, g, b);
2126 softlight: function(color1, color2) {
2127 var t = color2.rgb[0] * color1.rgb[0] / 255;
2128 var r = t + color1.rgb[0] * (255 - (255 - color1.rgb[0]) * (255 - color2.rgb[0]) / 255 - t) / 255;
2129 t = color2.rgb[1] * color1.rgb[1] / 255;
2130 var g = t + color1.rgb[1] * (255 - (255 - color1.rgb[1]) * (255 - color2.rgb[1]) / 255 - t) / 255;
2131 t = color2.rgb[2] * color1.rgb[2] / 255;
2132 var b = t + color1.rgb[2] * (255 - (255 - color1.rgb[2]) * (255 - color2.rgb[2]) / 255 - t) / 255;
2133 return this.rgb(r, g, b);
2135 hardlight: function(color1, color2) {
2136 var r = color2.rgb[0] < 128 ? 2 * color2.rgb[0] * color1.rgb[0] / 255 : 255 - 2 * (255 - color2.rgb[0]) * (255 - color1.rgb[0]) / 255;
2137 var g = color2.rgb[1] < 128 ? 2 * color2.rgb[1] * color1.rgb[1] / 255 : 255 - 2 * (255 - color2.rgb[1]) * (255 - color1.rgb[1]) / 255;
2138 var b = color2.rgb[2] < 128 ? 2 * color2.rgb[2] * color1.rgb[2] / 255 : 255 - 2 * (255 - color2.rgb[2]) * (255 - color1.rgb[2]) / 255;
2139 return this.rgb(r, g, b);
2141 difference: function(color1, color2) {
2142 var r = Math.abs(color1.rgb[0] - color2.rgb[0]);
2143 var g = Math.abs(color1.rgb[1] - color2.rgb[1]);
2144 var b = Math.abs(color1.rgb[2] - color2.rgb[2]);
2145 return this.rgb(r, g, b);
2147 exclusion: function(color1, color2) {
2148 var r = color1.rgb[0] + color2.rgb[0] * (255 - color1.rgb[0] - color1.rgb[0]) / 255;
2149 var g = color1.rgb[1] + color2.rgb[1] * (255 - color1.rgb[1] - color1.rgb[1]) / 255;
2150 var b = color1.rgb[2] + color2.rgb[2] * (255 - color1.rgb[2] - color1.rgb[2]) / 255;
2151 return this.rgb(r, g, b);
2153 average: function(color1, color2) {
2154 var r = (color1.rgb[0] + color2.rgb[0]) / 2;
2155 var g = (color1.rgb[1] + color2.rgb[1]) / 2;
2156 var b = (color1.rgb[2] + color2.rgb[2]) / 2;
2157 return this.rgb(r, g, b);
2159 negation: function(color1, color2) {
2160 var r = 255 - Math.abs(255 - color2.rgb[0] - color1.rgb[0]);
2161 var g = 255 - Math.abs(255 - color2.rgb[1] - color1.rgb[1]);
2162 var b = 255 - Math.abs(255 - color2.rgb[2] - color1.rgb[2]);
2163 return this.rgb(r, g, b);
2165 tint: function(color, amount) {
2166 return this.mix(this.rgb(255,255,255), color, amount);
2168 shade: function(color, amount) {
2169 return this.mix(this.rgb(0, 0, 0), color, amount);
2171 extract: function(values, index) {
2172 index = index.value - 1; // (1-based index)
2173 // handle non-array values as an array of length 1
2174 // return 'undefined' if index is invalid
2175 return Array.isArray(values.value)
2176 ? values.value[index] : Array(values)[index];
2178 length: function(values) {
2179 var n = Array.isArray(values.value) ? values.value.length : 1;
2180 return new tree.Dimension(n);
2183 "data-uri": function(mimetypeNode, filePathNode) {
2185 if (typeof window !== 'undefined') {
2186 return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env);
2189 var mimetype = mimetypeNode.value;
2190 var filePath = (filePathNode && filePathNode.value);
2192 var fs = require("fs"),
2193 path = require("path"),
2196 if (arguments.length < 2) {
2197 filePath = mimetype;
2200 if (this.env.isPathRelative(filePath)) {
2201 if (this.currentFileInfo.relativeUrls) {
2202 filePath = path.join(this.currentFileInfo.currentDirectory, filePath);
2204 filePath = path.join(this.currentFileInfo.entryPath, filePath);
2208 // detect the mimetype if not given
2209 if (arguments.length < 2) {
2212 mime = require('mime');
2217 mimetype = mime.lookup(filePath);
2219 // use base 64 unless it's an ASCII or UTF-8 format
2220 var charset = mime.charsets.lookup(mimetype);
2221 useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0;
2222 if (useBase64) { mimetype += ';base64'; }
2225 useBase64 = /;base64$/.test(mimetype);
2228 var buf = fs.readFileSync(filePath);
2230 // IE8 cannot handle a data-uri larger than 32KB. If this is exceeded
2231 // and the --ieCompat flag is enabled, return a normal url() instead.
2232 var DATA_URI_MAX_KB = 32,
2233 fileSizeInKB = parseInt((buf.length / 1024), 10);
2234 if (fileSizeInKB >= DATA_URI_MAX_KB) {
2236 if (this.env.ieCompat !== false) {
2237 if (!this.env.silent) {
2238 console.warn("Skipped data-uri embedding of %s because its size (%dKB) exceeds IE8-safe %dKB!", filePath, fileSizeInKB, DATA_URI_MAX_KB);
2241 return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env);
2245 buf = useBase64 ? buf.toString('base64')
2246 : encodeURIComponent(buf);
2248 var uri = "'data:" + mimetype + ',' + buf + "'";
2249 return new(tree.URL)(new(tree.Anonymous)(uri));
2252 "svg-gradient": function(direction) {
2254 function throwArgumentDescriptor() {
2255 throw { type: "Argument", message: "svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]" };
2258 if (arguments.length < 3) {
2259 throwArgumentDescriptor();
2261 var stops = Array.prototype.slice.call(arguments, 1),
2262 gradientDirectionSvg,
2263 gradientType = "linear",
2264 rectangleDimension = 'x="0" y="0" width="1" height="1"',
2266 renderEnv = {compress: false},
2268 directionValue = direction.toCSS(renderEnv),
2269 i, color, position, positionValue, alpha;
2271 switch (directionValue) {
2273 gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"';
2276 gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"';
2278 case "to bottom right":
2279 gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"';
2281 case "to top right":
2282 gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"';
2285 case "ellipse at center":
2286 gradientType = "radial";
2287 gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"';
2288 rectangleDimension = 'x="-50" y="-50" width="101" height="101"';
2291 throw { type: "Argument", message: "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" };
2293 returner = '<?xml version="1.0" ?>' +
2294 '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' +
2295 '<' + gradientType + 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' + gradientDirectionSvg + '>';
2297 for (i = 0; i < stops.length; i+= 1) {
2298 if (stops[i].value) {
2299 color = stops[i].value[0];
2300 position = stops[i].value[1];
2303 position = undefined;
2306 if (!(color instanceof tree.Color) || (!((i === 0 || i+1 === stops.length) && position === undefined) && !(position instanceof tree.Dimension))) {
2307 throwArgumentDescriptor();
2309 positionValue = position ? position.toCSS(renderEnv) : i === 0 ? "0%" : "100%";
2310 alpha = color.alpha;
2311 returner += '<stop offset="' + positionValue + '" stop-color="' + color.toRGB() + '"' + (alpha < 1 ? ' stop-opacity="' + alpha + '"' : '') + '/>';
2313 returner += '</' + gradientType + 'Gradient>' +
2314 '<rect ' + rectangleDimension + ' fill="url(#gradient)" /></svg>';
2317 // only works in node, needs interface to what is supported in environment
2319 returner = new Buffer(returner).toString('base64');
2325 returner = "'data:image/svg+xml" + (useBase64 ? ";base64" : "") + "," + returner + "'";
2326 return new(tree.URL)(new(tree.Anonymous)(returner));
2330 // these static methods are used as a fallback when the optional 'mime' dependency is missing
2332 // this map is intentionally incomplete
2333 // if you want more, install 'mime' dep
2335 '.htm' : 'text/html',
2336 '.html': 'text/html',
2337 '.gif' : 'image/gif',
2338 '.jpg' : 'image/jpeg',
2339 '.jpeg': 'image/jpeg',
2340 '.png' : 'image/png'
2342 lookup: function (filepath) {
2343 var ext = require('path').extname(filepath),
2344 type = tree._mime._types[ext];
2345 if (type === undefined) {
2346 throw new Error('Optional dependency "mime" is required for ' + ext);
2351 lookup: function (type) {
2352 // assumes all text types are UTF-8
2353 return type && (/^text\//).test(type) ? 'UTF-8' : '';
2358 var mathFunctions = [{name:"ceil"}, {name:"floor"}, {name: "sqrt"}, {name:"abs"},
2359 {name:"tan", unit: ""}, {name:"sin", unit: ""}, {name:"cos", unit: ""},
2360 {name:"atan", unit: "rad"}, {name:"asin", unit: "rad"}, {name:"acos", unit: "rad"}],
2361 createMathFunction = function(name, unit) {
2362 return function(n) {
2363 /*jshint eqnull:true */
2367 return this._math(Math[name], unit, n);
2371 for(var i = 0; i < mathFunctions.length; i++) {
2372 tree.functions[mathFunctions[i].name] = createMathFunction(mathFunctions[i].name, mathFunctions[i].unit);
2375 function hsla(color) {
2376 return tree.functions.hsla(color.h, color.s, color.l, color.a);
2379 function scaled(n, size) {
2380 if (n instanceof tree.Dimension && n.unit.is('%')) {
2381 return parseFloat(n.value * size / 100);
2387 function number(n) {
2388 if (n instanceof tree.Dimension) {
2389 return parseFloat(n.unit.is('%') ? n.value / 100 : n.value);
2390 } else if (typeof(n) === 'number') {
2394 error: "RuntimeError",
2395 message: "color functions take numbers as parameters"
2400 function clamp(val) {
2401 return Math.min(1, Math.max(0, val));
2404 tree.functionCall = function(env, currentFileInfo) {
2406 this.currentFileInfo = currentFileInfo;
2409 tree.functionCall.prototype = tree.functions;
2411 })(require('./tree'));
2415 'aliceblue':'#f0f8ff',
2416 'antiquewhite':'#faebd7',
2418 'aquamarine':'#7fffd4',
2423 'blanchedalmond':'#ffebcd',
2425 'blueviolet':'#8a2be2',
2427 'burlywood':'#deb887',
2428 'cadetblue':'#5f9ea0',
2429 'chartreuse':'#7fff00',
2430 'chocolate':'#d2691e',
2432 'cornflowerblue':'#6495ed',
2433 'cornsilk':'#fff8dc',
2434 'crimson':'#dc143c',
2436 'darkblue':'#00008b',
2437 'darkcyan':'#008b8b',
2438 'darkgoldenrod':'#b8860b',
2439 'darkgray':'#a9a9a9',
2440 'darkgrey':'#a9a9a9',
2441 'darkgreen':'#006400',
2442 'darkkhaki':'#bdb76b',
2443 'darkmagenta':'#8b008b',
2444 'darkolivegreen':'#556b2f',
2445 'darkorange':'#ff8c00',
2446 'darkorchid':'#9932cc',
2447 'darkred':'#8b0000',
2448 'darksalmon':'#e9967a',
2449 'darkseagreen':'#8fbc8f',
2450 'darkslateblue':'#483d8b',
2451 'darkslategray':'#2f4f4f',
2452 'darkslategrey':'#2f4f4f',
2453 'darkturquoise':'#00ced1',
2454 'darkviolet':'#9400d3',
2455 'deeppink':'#ff1493',
2456 'deepskyblue':'#00bfff',
2457 'dimgray':'#696969',
2458 'dimgrey':'#696969',
2459 'dodgerblue':'#1e90ff',
2460 'firebrick':'#b22222',
2461 'floralwhite':'#fffaf0',
2462 'forestgreen':'#228b22',
2463 'fuchsia':'#ff00ff',
2464 'gainsboro':'#dcdcdc',
2465 'ghostwhite':'#f8f8ff',
2467 'goldenrod':'#daa520',
2471 'greenyellow':'#adff2f',
2472 'honeydew':'#f0fff0',
2473 'hotpink':'#ff69b4',
2474 'indianred':'#cd5c5c',
2478 'lavender':'#e6e6fa',
2479 'lavenderblush':'#fff0f5',
2480 'lawngreen':'#7cfc00',
2481 'lemonchiffon':'#fffacd',
2482 'lightblue':'#add8e6',
2483 'lightcoral':'#f08080',
2484 'lightcyan':'#e0ffff',
2485 'lightgoldenrodyellow':'#fafad2',
2486 'lightgray':'#d3d3d3',
2487 'lightgrey':'#d3d3d3',
2488 'lightgreen':'#90ee90',
2489 'lightpink':'#ffb6c1',
2490 'lightsalmon':'#ffa07a',
2491 'lightseagreen':'#20b2aa',
2492 'lightskyblue':'#87cefa',
2493 'lightslategray':'#778899',
2494 'lightslategrey':'#778899',
2495 'lightsteelblue':'#b0c4de',
2496 'lightyellow':'#ffffe0',
2498 'limegreen':'#32cd32',
2500 'magenta':'#ff00ff',
2502 'mediumaquamarine':'#66cdaa',
2503 'mediumblue':'#0000cd',
2504 'mediumorchid':'#ba55d3',
2505 'mediumpurple':'#9370d8',
2506 'mediumseagreen':'#3cb371',
2507 'mediumslateblue':'#7b68ee',
2508 'mediumspringgreen':'#00fa9a',
2509 'mediumturquoise':'#48d1cc',
2510 'mediumvioletred':'#c71585',
2511 'midnightblue':'#191970',
2512 'mintcream':'#f5fffa',
2513 'mistyrose':'#ffe4e1',
2514 'moccasin':'#ffe4b5',
2515 'navajowhite':'#ffdead',
2517 'oldlace':'#fdf5e6',
2519 'olivedrab':'#6b8e23',
2521 'orangered':'#ff4500',
2523 'palegoldenrod':'#eee8aa',
2524 'palegreen':'#98fb98',
2525 'paleturquoise':'#afeeee',
2526 'palevioletred':'#d87093',
2527 'papayawhip':'#ffefd5',
2528 'peachpuff':'#ffdab9',
2532 'powderblue':'#b0e0e6',
2535 'rosybrown':'#bc8f8f',
2536 'royalblue':'#4169e1',
2537 'saddlebrown':'#8b4513',
2539 'sandybrown':'#f4a460',
2540 'seagreen':'#2e8b57',
2541 'seashell':'#fff5ee',
2544 'skyblue':'#87ceeb',
2545 'slateblue':'#6a5acd',
2546 'slategray':'#708090',
2547 'slategrey':'#708090',
2549 'springgreen':'#00ff7f',
2550 'steelblue':'#4682b4',
2553 'thistle':'#d8bfd8',
2555 'turquoise':'#40e0d0',
2559 'whitesmoke':'#f5f5f5',
2561 'yellowgreen':'#9acd32'
2563 })(require('./tree'));
2567 tree.debugInfo = function(env, ctx, lineSeperator) {
2569 if (env.dumpLineNumbers && !env.compress) {
2570 switch(env.dumpLineNumbers) {
2572 result = tree.debugInfo.asComment(ctx);
2575 result = tree.debugInfo.asMediaQuery(ctx);
2578 result = tree.debugInfo.asComment(ctx) + (lineSeperator || "") + tree.debugInfo.asMediaQuery(ctx);
2585 tree.debugInfo.asComment = function(ctx) {
2586 return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n';
2589 tree.debugInfo.asMediaQuery = function(ctx) {
2590 return '@media -sass-debug-info{filename{font-family:' +
2591 ('file://' + ctx.debugInfo.fileName).replace(/([.:/\\])/g, function (a) {
2597 '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n';
2600 tree.find = function (obj, fun) {
2601 for (var i = 0, r; i < obj.length; i++) {
2602 if (r = fun.call(obj, obj[i])) { return r; }
2607 tree.jsify = function (obj) {
2608 if (Array.isArray(obj.value) && (obj.value.length > 1)) {
2609 return '[' + obj.value.map(function (v) { return v.toCSS(false); }).join(', ') + ']';
2611 return obj.toCSS(false);
2615 tree.toCSS = function (env) {
2618 add: function(chunk, fileInfo, index) {
2621 isEmpty: function () {
2622 return strs.length === 0;
2625 return strs.join('');
2628 tree.outputRuleset = function (env, output, rules) {
2629 output.add((env.compress ? '{' : ' {\n'));
2630 env.tabLevel = (env.tabLevel || 0) + 1;
2631 var tabRuleStr = env.compress ? '' : Array(env.tabLevel + 1).join(" "),
2632 tabSetStr = env.compress ? '' : Array(env.tabLevel).join(" ");
2633 for(var i = 0; i < rules.length; i++) {
2634 output.add(tabRuleStr);
2635 rules[i].genCSS(env, output);
2636 output.add(env.compress ? '' : '\n');
2639 output.add(tabSetStr + "}");
2642 })(require('./tree'));
2646 tree.Alpha = function (val) {
2649 tree.Alpha.prototype = {
2651 accept: function (visitor) {
2652 this.value = visitor.visit(this.value);
2654 eval: function (env) {
2655 if (this.value.eval) { return new tree.Alpha(this.value.eval(env)); }
2658 genCSS: function (env, output) {
2659 output.add("alpha(opacity=");
2661 if (this.value.genCSS) {
2662 this.value.genCSS(env, output);
2664 output.add(this.value);
2672 })(require('../tree'));
2676 tree.Anonymous = function (string, index, currentFileInfo, mapLines) {
2677 this.value = string.value || string;
2679 this.mapLines = mapLines;
2680 this.currentFileInfo = currentFileInfo;
2682 tree.Anonymous.prototype = {
2684 eval: function () { return this; },
2685 compare: function (x) {
2690 var left = this.toCSS(),
2693 if (left === right) {
2697 return left < right ? -1 : 1;
2699 genCSS: function (env, output) {
2700 output.add(this.value, this.currentFileInfo, this.index, this.mapLines);
2705 })(require('../tree'));
2709 tree.Assignment = function (key, val) {
2713 tree.Assignment.prototype = {
2715 accept: function (visitor) {
2716 this.value = visitor.visit(this.value);
2718 eval: function (env) {
2719 if (this.value.eval) {
2720 return new(tree.Assignment)(this.key, this.value.eval(env));
2724 genCSS: function (env, output) {
2725 output.add(this.key + '=');
2726 if (this.value.genCSS) {
2727 this.value.genCSS(env, output);
2729 output.add(this.value);
2735 })(require('../tree'));
2740 // A function call node.
2742 tree.Call = function (name, args, index, currentFileInfo) {
2746 this.currentFileInfo = currentFileInfo;
2748 tree.Call.prototype = {
2750 accept: function (visitor) {
2751 this.args = visitor.visit(this.args);
2754 // When evaluating a function call,
2755 // we either find the function in `tree.functions` [1],
2756 // in which case we call it, passing the evaluated arguments,
2757 // if this returns null or we cannot find the function, we
2758 // simply print it out as it appeared originally [2].
2760 // The *functions.js* file contains the built-in functions.
2762 // The reason why we evaluate the arguments, is in the case where
2763 // we try to pass a variable to a function, like: `saturate(@color)`.
2764 // The function should receive the value, not the variable.
2766 eval: function (env) {
2767 var args = this.args.map(function (a) { return a.eval(env); }),
2768 nameLC = this.name.toLowerCase(),
2771 if (nameLC in tree.functions) { // 1.
2773 func = new tree.functionCall(env, this.currentFileInfo);
2774 result = func[nameLC].apply(func, args);
2775 /*jshint eqnull:true */
2776 if (result != null) {
2780 throw { type: e.type || "Runtime",
2781 message: "error evaluating function `" + this.name + "`" +
2782 (e.message ? ': ' + e.message : ''),
2783 index: this.index, filename: this.currentFileInfo.filename };
2787 return new tree.Call(this.name, args, this.index, this.currentFileInfo);
2790 genCSS: function (env, output) {
2791 output.add(this.name + "(", this.currentFileInfo, this.index);
2793 for(var i = 0; i < this.args.length; i++) {
2794 this.args[i].genCSS(env, output);
2795 if (i + 1 < this.args.length) {
2806 })(require('../tree'));
2810 // RGB Colors - #ff0014, #eee
2812 tree.Color = function (rgb, a) {
2814 // The end goal here, is to parse the arguments
2815 // into an integer triplet, such as `128, 255, 0`
2817 // This facilitates operations and conversions.
2819 if (Array.isArray(rgb)) {
2821 } else if (rgb.length == 6) {
2822 this.rgb = rgb.match(/.{2}/g).map(function (c) {
2823 return parseInt(c, 16);
2826 this.rgb = rgb.split('').map(function (c) {
2827 return parseInt(c + c, 16);
2830 this.alpha = typeof(a) === 'number' ? a : 1;
2833 var transparentKeyword = "transparent";
2835 tree.Color.prototype = {
2837 eval: function () { return this; },
2838 luma: function () { return (0.2126 * this.rgb[0] / 255) + (0.7152 * this.rgb[1] / 255) + (0.0722 * this.rgb[2] / 255); },
2840 genCSS: function (env, output) {
2841 output.add(this.toCSS(env));
2843 toCSS: function (env, doNotCompress) {
2844 var compress = env && env.compress && !doNotCompress;
2846 // If we have some transparency, the only way to represent it
2847 // is via `rgba`. Otherwise, we use the hex representation,
2848 // which has better compatibility with older browsers.
2849 // Values are capped between `0` and `255`, rounded and zero-padded.
2850 if (this.alpha < 1.0) {
2851 if (this.alpha === 0 && this.isTransparentKeyword) {
2852 return transparentKeyword;
2854 return "rgba(" + this.rgb.map(function (c) {
2855 return Math.round(c);
2856 }).concat(this.alpha).join(',' + (compress ? '' : ' ')) + ")";
2858 var color = this.toRGB();
2861 var splitcolor = color.split('');
2863 // Convert color to short format
2864 if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) {
2865 color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5];
2874 // Operations have to be done per-channel, if not,
2875 // channels will spill onto each other. Once we have
2876 // our result, in the form of an integer triplet,
2877 // we create a new Color node to hold the result.
2879 operate: function (env, op, other) {
2882 if (! (other instanceof tree.Color)) {
2883 other = other.toColor();
2886 for (var c = 0; c < 3; c++) {
2887 result[c] = tree.operate(env, op, this.rgb[c], other.rgb[c]);
2889 return new(tree.Color)(result, this.alpha + other.alpha);
2892 toRGB: function () {
2893 return '#' + this.rgb.map(function (i) {
2895 i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16);
2896 return i.length === 1 ? '0' + i : i;
2900 toHSL: function () {
2901 var r = this.rgb[0] / 255,
2902 g = this.rgb[1] / 255,
2903 b = this.rgb[2] / 255,
2906 var max = Math.max(r, g, b), min = Math.min(r, g, b);
2907 var h, s, l = (max + min) / 2, d = max - min;
2912 s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
2915 case r: h = (g - b) / d + (g < b ? 6 : 0); break;
2916 case g: h = (b - r) / d + 2; break;
2917 case b: h = (r - g) / d + 4; break;
2921 return { h: h * 360, s: s, l: l, a: a };
2923 //Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript
2924 toHSV: function () {
2925 var r = this.rgb[0] / 255,
2926 g = this.rgb[1] / 255,
2927 b = this.rgb[2] / 255,
2930 var max = Math.max(r, g, b), min = Math.min(r, g, b);
2944 case r: h = (g - b) / d + (g < b ? 6 : 0); break;
2945 case g: h = (b - r) / d + 2; break;
2946 case b: h = (r - g) / d + 4; break;
2950 return { h: h * 360, s: s, v: v, a: a };
2952 toARGB: function () {
2953 var argb = [Math.round(this.alpha * 255)].concat(this.rgb);
2954 return '#' + argb.map(function (i) {
2956 i = (i > 255 ? 255 : (i < 0 ? 0 : i)).toString(16);
2957 return i.length === 1 ? '0' + i : i;
2960 compare: function (x) {
2965 return (x.rgb[0] === this.rgb[0] &&
2966 x.rgb[1] === this.rgb[1] &&
2967 x.rgb[2] === this.rgb[2] &&
2968 x.alpha === this.alpha) ? 0 : -1;
2972 tree.Color.fromKeyword = function(keyword) {
2973 if (tree.colors.hasOwnProperty(keyword)) {
2974 // detect named color
2975 return new(tree.Color)(tree.colors[keyword].slice(1));
2977 if (keyword === transparentKeyword) {
2978 var transparent = new(tree.Color)([0, 0, 0], 0);
2979 transparent.isTransparentKeyword = true;
2985 })(require('../tree'));
2989 tree.Comment = function (value, silent, index, currentFileInfo) {
2991 this.silent = !!silent;
2992 this.currentFileInfo = currentFileInfo;
2994 tree.Comment.prototype = {
2996 genCSS: function (env, output) {
2997 if (this.debugInfo) {
2998 output.add(tree.debugInfo(env, this), this.currentFileInfo, this.index);
3000 output.add(this.value.trim()); //TODO shouldn't need to trim, we shouldn't grab the \n
3003 isSilent: function(env) {
3004 var isReference = (this.currentFileInfo && this.currentFileInfo.reference && !this.isReferenced),
3005 isCompressed = env.compress && !this.value.match(/^\/\*!/);
3006 return this.silent || isReference || isCompressed;
3008 eval: function () { return this; },
3009 markReferenced: function () {
3010 this.isReferenced = true;
3014 })(require('../tree'));
3018 tree.Condition = function (op, l, r, i, negate) {
3019 this.op = op.trim();
3023 this.negate = negate;
3025 tree.Condition.prototype = {
3027 accept: function (visitor) {
3028 this.lvalue = visitor.visit(this.lvalue);
3029 this.rvalue = visitor.visit(this.rvalue);
3031 eval: function (env) {
3032 var a = this.lvalue.eval(env),
3033 b = this.rvalue.eval(env);
3035 var i = this.index, result;
3037 result = (function (op) {
3045 result = a.compare(b);
3046 } else if (b.compare) {
3047 result = b.compare(a);
3049 throw { type: "Type",
3050 message: "Unable to perform comparison",
3054 case -1: return op === '<' || op === '=<' || op === '<=';
3055 case 0: return op === '=' || op === '>=' || op === '=<' || op === '<=';
3056 case 1: return op === '>' || op === '>=';
3060 return this.negate ? !result : result;
3064 })(require('../tree'));
3069 // A number with a unit
3071 tree.Dimension = function (value, unit) {
3072 this.value = parseFloat(value);
3073 this.unit = (unit && unit instanceof tree.Unit) ? unit :
3074 new(tree.Unit)(unit ? [unit] : undefined);
3077 tree.Dimension.prototype = {
3079 accept: function (visitor) {
3080 this.unit = visitor.visit(this.unit);
3082 eval: function (env) {
3085 toColor: function () {
3086 return new(tree.Color)([this.value, this.value, this.value]);
3088 genCSS: function (env, output) {
3089 if ((env && env.strictUnits) && !this.unit.isSingular()) {
3090 throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: "+this.unit.toString());
3093 var value = this.value,
3094 strValue = String(value);
3096 if (value !== 0 && value < 0.000001 && value > -0.000001) {
3097 // would be output 1e-6 etc.
3098 strValue = value.toFixed(20).replace(/0+$/, "");
3101 if (env && env.compress) {
3102 // Zero values doesn't need a unit
3103 if (value === 0 && this.unit.isLength()) {
3104 output.add(strValue);
3108 // Float values doesn't need a leading zero
3109 if (value > 0 && value < 1) {
3110 strValue = (strValue).substr(1);
3114 output.add(strValue);
3115 this.unit.genCSS(env, output);
3119 // In an operation between two Dimensions,
3120 // we default to the first Dimension's unit,
3121 // so `1px + 2` will yield `3px`.
3122 operate: function (env, op, other) {
3123 /*jshint noempty:false */
3124 var value = tree.operate(env, op, this.value, other.value),
3125 unit = this.unit.clone();
3127 if (op === '+' || op === '-') {
3128 if (unit.numerator.length === 0 && unit.denominator.length === 0) {
3129 unit.numerator = other.unit.numerator.slice(0);
3130 unit.denominator = other.unit.denominator.slice(0);
3131 } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) {
3134 other = other.convertTo(this.unit.usedUnits());
3136 if(env.strictUnits && other.unit.toString() !== unit.toString()) {
3137 throw new Error("Incompatible units. Change the units or use the unit function. Bad units: '" + unit.toString() +
3138 "' and '" + other.unit.toString() + "'.");
3141 value = tree.operate(env, op, this.value, other.value);
3143 } else if (op === '*') {
3144 unit.numerator = unit.numerator.concat(other.unit.numerator).sort();
3145 unit.denominator = unit.denominator.concat(other.unit.denominator).sort();
3147 } else if (op === '/') {
3148 unit.numerator = unit.numerator.concat(other.unit.denominator).sort();
3149 unit.denominator = unit.denominator.concat(other.unit.numerator).sort();
3152 return new(tree.Dimension)(value, unit);
3155 compare: function (other) {
3156 if (other instanceof tree.Dimension) {
3157 var a = this.unify(), b = other.unify(),
3158 aValue = a.value, bValue = b.value;
3160 if (bValue > aValue) {
3162 } else if (bValue < aValue) {
3165 if (!b.unit.isEmpty() && a.unit.compare(b.unit) !== 0) {
3175 unify: function () {
3176 return this.convertTo({ length: 'm', duration: 's', angle: 'rad' });
3179 convertTo: function (conversions) {
3180 var value = this.value, unit = this.unit.clone(),
3181 i, groupName, group, targetUnit, derivedConversions = {}, applyUnit;
3183 if (typeof conversions === 'string') {
3184 for(i in tree.UnitConversions) {
3185 if (tree.UnitConversions[i].hasOwnProperty(conversions)) {
3186 derivedConversions = {};
3187 derivedConversions[i] = conversions;
3190 conversions = derivedConversions;
3192 applyUnit = function (atomicUnit, denominator) {
3193 /*jshint loopfunc:true */
3194 if (group.hasOwnProperty(atomicUnit)) {
3196 value = value / (group[atomicUnit] / group[targetUnit]);
3198 value = value * (group[atomicUnit] / group[targetUnit]);
3207 for (groupName in conversions) {
3208 if (conversions.hasOwnProperty(groupName)) {
3209 targetUnit = conversions[groupName];
3210 group = tree.UnitConversions[groupName];
3212 unit.map(applyUnit);
3218 return new(tree.Dimension)(value, unit);
3222 // http://www.w3.org/TR/css3-values/#absolute-lengths
3223 tree.UnitConversions = {
3230 'pc': 0.0254 / 72 * 12
3237 'rad': 1/(2*Math.PI),
3244 tree.Unit = function (numerator, denominator, backupUnit) {
3245 this.numerator = numerator ? numerator.slice(0).sort() : [];
3246 this.denominator = denominator ? denominator.slice(0).sort() : [];
3247 this.backupUnit = backupUnit;
3250 tree.Unit.prototype = {
3252 clone: function () {
3253 return new tree.Unit(this.numerator.slice(0), this.denominator.slice(0), this.backupUnit);
3255 genCSS: function (env, output) {
3256 if (this.numerator.length >= 1) {
3257 output.add(this.numerator[0]);
3259 if (this.denominator.length >= 1) {
3260 output.add(this.denominator[0]);
3262 if ((!env || !env.strictUnits) && this.backupUnit) {
3263 output.add(this.backupUnit);
3268 toString: function () {
3269 var i, returnStr = this.numerator.join("*");
3270 for (i = 0; i < this.denominator.length; i++) {
3271 returnStr += "/" + this.denominator[i];
3276 compare: function (other) {
3277 return this.is(other.toString()) ? 0 : -1;
3280 is: function (unitString) {
3281 return this.toString() === unitString;
3284 isLength: function () {
3285 return Boolean(this.toCSS().match(/px|em|%|in|cm|mm|pc|pt|ex/));
3288 isEmpty: function () {
3289 return this.numerator.length === 0 && this.denominator.length === 0;
3292 isSingular: function() {
3293 return this.numerator.length <= 1 && this.denominator.length === 0;
3296 map: function(callback) {
3299 for (i = 0; i < this.numerator.length; i++) {
3300 this.numerator[i] = callback(this.numerator[i], false);
3303 for (i = 0; i < this.denominator.length; i++) {
3304 this.denominator[i] = callback(this.denominator[i], true);
3308 usedUnits: function() {
3309 var group, result = {}, mapUnit;
3311 mapUnit = function (atomicUnit) {
3312 /*jshint loopfunc:true */
3313 if (group.hasOwnProperty(atomicUnit) && !result[groupName]) {
3314 result[groupName] = atomicUnit;
3320 for (var groupName in tree.UnitConversions) {
3321 if (tree.UnitConversions.hasOwnProperty(groupName)) {
3322 group = tree.UnitConversions[groupName];
3331 cancel: function () {
3332 var counter = {}, atomicUnit, i, backup;
3334 for (i = 0; i < this.numerator.length; i++) {
3335 atomicUnit = this.numerator[i];
3337 backup = atomicUnit;
3339 counter[atomicUnit] = (counter[atomicUnit] || 0) + 1;
3342 for (i = 0; i < this.denominator.length; i++) {
3343 atomicUnit = this.denominator[i];
3345 backup = atomicUnit;
3347 counter[atomicUnit] = (counter[atomicUnit] || 0) - 1;
3350 this.numerator = [];
3351 this.denominator = [];
3353 for (atomicUnit in counter) {
3354 if (counter.hasOwnProperty(atomicUnit)) {
3355 var count = counter[atomicUnit];
3358 for (i = 0; i < count; i++) {
3359 this.numerator.push(atomicUnit);
3361 } else if (count < 0) {
3362 for (i = 0; i < -count; i++) {
3363 this.denominator.push(atomicUnit);
3369 if (this.numerator.length === 0 && this.denominator.length === 0 && backup) {
3370 this.backupUnit = backup;
3373 this.numerator.sort();
3374 this.denominator.sort();
3378 })(require('../tree'));
3382 tree.Directive = function (name, value, index, currentFileInfo) {
3385 if (Array.isArray(value)) {
3386 this.rules = [new(tree.Ruleset)([], value)];
3387 this.rules[0].allowImports = true;
3391 this.currentFileInfo = currentFileInfo;
3394 tree.Directive.prototype = {
3396 accept: function (visitor) {
3397 this.rules = visitor.visit(this.rules);
3398 this.value = visitor.visit(this.value);
3400 genCSS: function (env, output) {
3401 output.add(this.name, this.currentFileInfo, this.index);
3403 tree.outputRuleset(env, output, this.rules);
3406 this.value.genCSS(env, output);
3411 eval: function (env) {
3412 var evaldDirective = this;
3414 env.frames.unshift(this);
3415 evaldDirective = new(tree.Directive)(this.name, null, this.index, this.currentFileInfo);
3416 evaldDirective.rules = [this.rules[0].eval(env)];
3417 evaldDirective.rules[0].root = true;
3420 return evaldDirective;
3422 variable: function (name) { return tree.Ruleset.prototype.variable.call(this.rules[0], name); },
3423 find: function () { return tree.Ruleset.prototype.find.apply(this.rules[0], arguments); },
3424 rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.rules[0]); },
3425 markReferenced: function () {
3427 this.isReferenced = true;
3429 rules = this.rules[0].rules;
3430 for (i = 0; i < rules.length; i++) {
3431 if (rules[i].markReferenced) {
3432 rules[i].markReferenced();
3439 })(require('../tree'));
3443 tree.Element = function (combinator, value, index, currentFileInfo) {
3444 this.combinator = combinator instanceof tree.Combinator ?
3445 combinator : new(tree.Combinator)(combinator);
3447 if (typeof(value) === 'string') {
3448 this.value = value.trim();
3455 this.currentFileInfo = currentFileInfo;
3457 tree.Element.prototype = {
3459 accept: function (visitor) {
3460 this.combinator = visitor.visit(this.combinator);
3461 this.value = visitor.visit(this.value);
3463 eval: function (env) {
3464 return new(tree.Element)(this.combinator,
3465 this.value.eval ? this.value.eval(env) : this.value,
3467 this.currentFileInfo);
3469 genCSS: function (env, output) {
3470 output.add(this.toCSS(env), this.currentFileInfo, this.index);
3472 toCSS: function (env) {
3473 var value = (this.value.toCSS ? this.value.toCSS(env) : this.value);
3474 if (value === '' && this.combinator.value.charAt(0) === '&') {
3477 return this.combinator.toCSS(env || {}) + value;
3482 tree.Attribute = function (key, op, value) {
3487 tree.Attribute.prototype = {
3489 accept: function (visitor) {
3490 this.value = visitor.visit(this.value);
3492 eval: function (env) {
3493 return new(tree.Attribute)(this.key.eval ? this.key.eval(env) : this.key,
3494 this.op, (this.value && this.value.eval) ? this.value.eval(env) : this.value);
3496 genCSS: function (env, output) {
3497 output.add(this.toCSS(env));
3499 toCSS: function (env) {
3500 var value = this.key.toCSS ? this.key.toCSS(env) : this.key;
3504 value += (this.value.toCSS ? this.value.toCSS(env) : this.value);
3507 return '[' + value + ']';
3511 tree.Combinator = function (value) {
3512 if (value === ' ') {
3515 this.value = value ? value.trim() : "";
3518 tree.Combinator.prototype = {
3529 _outputMapCompressed: {
3538 genCSS: function (env, output) {
3539 output.add((env.compress ? this._outputMapCompressed : this._outputMap)[this.value]);
3544 })(require('../tree'));
3548 tree.Expression = function (value) { this.value = value; };
3549 tree.Expression.prototype = {
3551 accept: function (visitor) {
3552 this.value = visitor.visit(this.value);
3554 eval: function (env) {
3556 inParenthesis = this.parens && !this.parensInOp,
3557 doubleParen = false;
3558 if (inParenthesis) {
3559 env.inParenthesis();
3561 if (this.value.length > 1) {
3562 returnValue = new(tree.Expression)(this.value.map(function (e) {
3565 } else if (this.value.length === 1) {
3566 if (this.value[0].parens && !this.value[0].parensInOp) {
3569 returnValue = this.value[0].eval(env);
3573 if (inParenthesis) {
3574 env.outOfParenthesis();
3576 if (this.parens && this.parensInOp && !(env.isMathOn()) && !doubleParen) {
3577 returnValue = new(tree.Paren)(returnValue);
3581 genCSS: function (env, output) {
3582 for(var i = 0; i < this.value.length; i++) {
3583 this.value[i].genCSS(env, output);
3584 if (i + 1 < this.value.length) {
3590 throwAwayComments: function () {
3591 this.value = this.value.filter(function(v) {
3592 return !(v instanceof tree.Comment);
3597 })(require('../tree'));
3601 tree.Extend = function Extend(selector, option, index) {
3602 this.selector = selector;
3603 this.option = option;
3608 this.allowBefore = true;
3609 this.allowAfter = true;
3612 this.allowBefore = false;
3613 this.allowAfter = false;
3618 tree.Extend.prototype = {
3620 accept: function (visitor) {
3621 this.selector = visitor.visit(this.selector);
3623 eval: function (env) {
3624 return new(tree.Extend)(this.selector.eval(env), this.option, this.index);
3626 clone: function (env) {
3627 return new(tree.Extend)(this.selector, this.option, this.index);
3629 findSelfSelectors: function (selectors) {
3630 var selfElements = [],
3634 for(i = 0; i < selectors.length; i++) {
3635 selectorElements = selectors[i].elements;
3636 // duplicate the logic in genCSS function inside the selector node.
3637 // future TODO - move both logics into the selector joiner visitor
3638 if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") {
3639 selectorElements[0].combinator.value = ' ';
3641 selfElements = selfElements.concat(selectors[i].elements);
3644 this.selfSelectors = [{ elements: selfElements }];
3648 })(require('../tree'));
3654 // The general strategy here is that we don't want to wait
3655 // for the parsing to be completed, before we start importing
3656 // the file. That's because in the context of a browser,
3657 // most of the time will be spent waiting for the server to respond.
3659 // On creation, we push the import path to our import queue, though
3660 // `import,push`, we also pass it a callback, which it'll call once
3661 // the file has been fetched, and parsed.
3663 tree.Import = function (path, features, options, index, currentFileInfo) {
3664 this.options = options;
3667 this.features = features;
3668 this.currentFileInfo = currentFileInfo;
3670 if (this.options.less !== undefined || this.options.inline) {
3671 this.css = !this.options.less || this.options.inline;
3673 var pathValue = this.getPath();
3674 if (pathValue && /css([\?;].*)?$/.test(pathValue)) {
3681 // The actual import node doesn't return anything, when converted to CSS.
3682 // The reason is that it's used at the evaluation stage, so that the rules
3683 // it imports can be treated like any other rules.
3685 // In `eval`, we make sure all Import nodes get evaluated, recursively, so
3686 // we end up with a flat structure, which can easily be imported in the parent
3689 tree.Import.prototype = {
3691 accept: function (visitor) {
3692 this.features = visitor.visit(this.features);
3693 this.path = visitor.visit(this.path);
3694 if (!this.options.inline) {
3695 this.root = visitor.visit(this.root);
3698 genCSS: function (env, output) {
3700 output.add("@import ", this.currentFileInfo, this.index);
3701 this.path.genCSS(env, output);
3702 if (this.features) {
3704 this.features.genCSS(env, output);
3710 getPath: function () {
3711 if (this.path instanceof tree.Quoted) {
3712 var path = this.path.value;
3713 return (this.css !== undefined || /(\.[a-z]*$)|([\?;].*)$/.test(path)) ? path : path + '.less';
3714 } else if (this.path instanceof tree.URL) {
3715 return this.path.value.value;
3719 evalForImport: function (env) {
3720 return new(tree.Import)(this.path.eval(env), this.features, this.options, this.index, this.currentFileInfo);
3722 evalPath: function (env) {
3723 var path = this.path.eval(env);
3724 var rootpath = this.currentFileInfo && this.currentFileInfo.rootpath;
3726 if (!(path instanceof tree.URL)) {
3728 var pathValue = path.value;
3729 // Add the base path if the import is relative
3730 if (pathValue && env.isPathRelative(pathValue)) {
3731 path.value = rootpath + pathValue;
3734 path.value = env.normalizePath(path.value);
3739 eval: function (env) {
3740 var ruleset, features = this.features && this.features.eval(env);
3742 if (this.skip) { return []; }
3744 if (this.options.inline) {
3745 //todo needs to reference css file not import
3746 var contents = new(tree.Anonymous)(this.root, 0, {filename: this.importedFilename}, true);
3747 return this.features ? new(tree.Media)([contents], this.features.value) : [contents];
3748 } else if (this.css) {
3749 var newImport = new(tree.Import)(this.evalPath(env), features, this.options, this.index);
3750 if (!newImport.css && this.error) {
3755 ruleset = new(tree.Ruleset)([], this.root.rules.slice(0));
3757 ruleset.evalImports(env);
3759 return this.features ? new(tree.Media)(ruleset.rules, this.features.value) : ruleset.rules;
3764 })(require('../tree'));
3768 tree.JavaScript = function (string, index, escaped) {
3769 this.escaped = escaped;
3770 this.expression = string;
3773 tree.JavaScript.prototype = {
3775 eval: function (env) {
3780 var expression = this.expression.replace(/@\{([\w-]+)\}/g, function (_, name) {
3781 return tree.jsify(new(tree.Variable)('@' + name, that.index).eval(env));
3785 expression = new(Function)('return (' + expression + ')');
3787 throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`" ,
3788 index: this.index };
3791 for (var k in env.frames[0].variables()) {
3792 /*jshint loopfunc:true */
3793 context[k.slice(1)] = {
3794 value: env.frames[0].variables()[k].value,
3796 return this.value.eval(env).toCSS();
3802 result = expression.call(context);
3804 throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message + "'" ,
3805 index: this.index };
3807 if (typeof(result) === 'string') {
3808 return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index);
3809 } else if (Array.isArray(result)) {
3810 return new(tree.Anonymous)(result.join(', '));
3812 return new(tree.Anonymous)(result);
3817 })(require('../tree'));
3822 tree.Keyword = function (value) { this.value = value; };
3823 tree.Keyword.prototype = {
3825 eval: function () { return this; },
3826 genCSS: function (env, output) {
3827 output.add(this.value);
3830 compare: function (other) {
3831 if (other instanceof tree.Keyword) {
3832 return other.value === this.value ? 0 : 1;
3839 tree.True = new(tree.Keyword)('true');
3840 tree.False = new(tree.Keyword)('false');
3842 })(require('../tree'));
3846 tree.Media = function (value, features, index, currentFileInfo) {
3848 this.currentFileInfo = currentFileInfo;
3850 var selectors = this.emptySelectors();
3852 this.features = new(tree.Value)(features);
3853 this.rules = [new(tree.Ruleset)(selectors, value)];
3854 this.rules[0].allowImports = true;
3856 tree.Media.prototype = {
3858 accept: function (visitor) {
3859 this.features = visitor.visit(this.features);
3860 this.rules = visitor.visit(this.rules);
3862 genCSS: function (env, output) {
3863 output.add('@media ', this.currentFileInfo, this.index);
3864 this.features.genCSS(env, output);
3865 tree.outputRuleset(env, output, this.rules);
3868 eval: function (env) {
3869 if (!env.mediaBlocks) {
3870 env.mediaBlocks = [];
3874 var media = new(tree.Media)([], [], this.index, this.currentFileInfo);
3875 if(this.debugInfo) {
3876 this.rules[0].debugInfo = this.debugInfo;
3877 media.debugInfo = this.debugInfo;
3879 var strictMathBypass = false;
3880 if (!env.strictMath) {
3881 strictMathBypass = true;
3882 env.strictMath = true;
3885 media.features = this.features.eval(env);
3888 if (strictMathBypass) {
3889 env.strictMath = false;
3893 env.mediaPath.push(media);
3894 env.mediaBlocks.push(media);
3896 env.frames.unshift(this.rules[0]);
3897 media.rules = [this.rules[0].eval(env)];
3900 env.mediaPath.pop();
3902 return env.mediaPath.length === 0 ? media.evalTop(env) :
3903 media.evalNested(env);
3905 variable: function (name) { return tree.Ruleset.prototype.variable.call(this.rules[0], name); },
3906 find: function () { return tree.Ruleset.prototype.find.apply(this.rules[0], arguments); },
3907 rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.rules[0]); },
3908 emptySelectors: function() {
3909 var el = new(tree.Element)('', '&', this.index, this.currentFileInfo);
3910 return [new(tree.Selector)([el], null, null, this.index, this.currentFileInfo)];
3912 markReferenced: function () {
3913 var i, rules = this.rules[0].rules;
3914 this.isReferenced = true;
3915 for (i = 0; i < rules.length; i++) {
3916 if (rules[i].markReferenced) {
3917 rules[i].markReferenced();
3922 evalTop: function (env) {
3925 // Render all dependent Media blocks.
3926 if (env.mediaBlocks.length > 1) {
3927 var selectors = this.emptySelectors();
3928 result = new(tree.Ruleset)(selectors, env.mediaBlocks);
3929 result.multiMedia = true;
3932 delete env.mediaBlocks;
3933 delete env.mediaPath;
3937 evalNested: function (env) {
3939 path = env.mediaPath.concat([this]);
3941 // Extract the media-query conditions separated with `,` (OR).
3942 for (i = 0; i < path.length; i++) {
3943 value = path[i].features instanceof tree.Value ?
3944 path[i].features.value : path[i].features;
3945 path[i] = Array.isArray(value) ? value : [value];
3948 // Trace all permutations to generate the resulting media-query.
3950 // (a, b and c) with nested (d, e) ->
3955 this.features = new(tree.Value)(this.permute(path).map(function (path) {
3956 path = path.map(function (fragment) {
3957 return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment);
3960 for(i = path.length - 1; i > 0; i--) {
3961 path.splice(i, 0, new(tree.Anonymous)("and"));
3964 return new(tree.Expression)(path);
3967 // Fake a tree-node that doesn't output anything.
3968 return new(tree.Ruleset)([], []);
3970 permute: function (arr) {
3971 if (arr.length === 0) {
3973 } else if (arr.length === 1) {
3977 var rest = this.permute(arr.slice(1));
3978 for (var i = 0; i < rest.length; i++) {
3979 for (var j = 0; j < arr[0].length; j++) {
3980 result.push([arr[0][j]].concat(rest[i]));
3986 bubbleSelectors: function (selectors) {
3987 this.rules = [new(tree.Ruleset)(selectors.slice(0), [this.rules[0]])];
3991 })(require('../tree'));
3996 tree.mixin.Call = function (elements, args, index, currentFileInfo, important) {
3997 this.selector = new(tree.Selector)(elements);
3998 this.arguments = args;
4000 this.currentFileInfo = currentFileInfo;
4001 this.important = important;
4003 tree.mixin.Call.prototype = {
4005 accept: function (visitor) {
4006 this.selector = visitor.visit(this.selector);
4007 this.arguments = visitor.visit(this.arguments);
4009 eval: function (env) {
4010 var mixins, mixin, args, rules = [], match = false, i, m, f, isRecursive, isOneFound, rule;
4012 args = this.arguments && this.arguments.map(function (a) {
4013 return { name: a.name, value: a.value.eval(env) };
4016 for (i = 0; i < env.frames.length; i++) {
4017 if ((mixins = env.frames[i].find(this.selector)).length > 0) {
4019 for (m = 0; m < mixins.length; m++) {
4021 isRecursive = false;
4022 for(f = 0; f < env.frames.length; f++) {
4023 if ((!(mixin instanceof tree.mixin.Definition)) && mixin === (env.frames[f].originalRuleset || env.frames[f])) {
4031 if (mixin.matchArgs(args, env)) {
4032 if (!mixin.matchCondition || mixin.matchCondition(args, env)) {
4034 if (!(mixin instanceof tree.mixin.Definition)) {
4035 mixin = new tree.mixin.Definition("", [], mixin.rules, null, false);
4036 mixin.originalRuleset = mixins[m].originalRuleset || mixins[m];
4038 //if (this.important) {
4039 // isImportant = env.isImportant;
4040 // env.isImportant = true;
4042 Array.prototype.push.apply(
4043 rules, mixin.eval(env, args, this.important).rules);
4044 //if (this.important) {
4045 // env.isImportant = isImportant;
4048 throw { message: e.message, index: this.index, filename: this.currentFileInfo.filename, stack: e.stack };
4055 if (!this.currentFileInfo || !this.currentFileInfo.reference) {
4056 for (i = 0; i < rules.length; i++) {
4058 if (rule.markReferenced) {
4059 rule.markReferenced();
4068 throw { type: 'Runtime',
4069 message: 'No matching definition was found for `' +
4070 this.selector.toCSS().trim() + '(' +
4071 (args ? args.map(function (a) {
4074 argValue += a.name + ":";
4076 if (a.value.toCSS) {
4077 argValue += a.value.toCSS();
4082 }).join(', ') : "") + ")`",
4083 index: this.index, filename: this.currentFileInfo.filename };
4085 throw { type: 'Name',
4086 message: this.selector.toCSS().trim() + " is undefined",
4087 index: this.index, filename: this.currentFileInfo.filename };
4092 tree.mixin.Definition = function (name, params, rules, condition, variadic) {
4094 this.selectors = [new(tree.Selector)([new(tree.Element)(null, name, this.index, this.currentFileInfo)])];
4095 this.params = params;
4096 this.condition = condition;
4097 this.variadic = variadic;
4098 this.arity = params.length;
4101 this.required = params.reduce(function (count, p) {
4102 if (!p.name || (p.name && !p.value)) { return count + 1; }
4103 else { return count; }
4105 this.parent = tree.Ruleset.prototype;
4108 tree.mixin.Definition.prototype = {
4109 type: "MixinDefinition",
4110 accept: function (visitor) {
4111 this.params = visitor.visit(this.params);
4112 this.rules = visitor.visit(this.rules);
4113 this.condition = visitor.visit(this.condition);
4115 variable: function (name) { return this.parent.variable.call(this, name); },
4116 variables: function () { return this.parent.variables.call(this); },
4117 find: function () { return this.parent.find.apply(this, arguments); },
4118 rulesets: function () { return this.parent.rulesets.apply(this); },
4120 evalParams: function (env, mixinEnv, args, evaldArguments) {
4121 /*jshint boss:true */
4122 var frame = new(tree.Ruleset)(null, []),
4124 params = this.params.slice(0),
4125 i, j, val, name, isNamedFound, argIndex;
4127 mixinEnv = new tree.evalEnv(mixinEnv, [frame].concat(mixinEnv.frames));
4130 args = args.slice(0);
4132 for(i = 0; i < args.length; i++) {
4134 if (name = (arg && arg.name)) {
4135 isNamedFound = false;
4136 for(j = 0; j < params.length; j++) {
4137 if (!evaldArguments[j] && name === params[j].name) {
4138 evaldArguments[j] = arg.value.eval(env);
4139 frame.rules.unshift(new(tree.Rule)(name, arg.value.eval(env)));
4140 isNamedFound = true;
4149 throw { type: 'Runtime', message: "Named argument for " + this.name +
4150 ' ' + args[i].name + ' not found' };
4156 for (i = 0; i < params.length; i++) {
4157 if (evaldArguments[i]) { continue; }
4159 arg = args && args[argIndex];
4161 if (name = params[i].name) {
4162 if (params[i].variadic && args) {
4164 for (j = argIndex; j < args.length; j++) {
4165 varargs.push(args[j].value.eval(env));
4167 frame.rules.unshift(new(tree.Rule)(name, new(tree.Expression)(varargs).eval(env)));
4169 val = arg && arg.value;
4171 val = val.eval(env);
4172 } else if (params[i].value) {
4173 val = params[i].value.eval(mixinEnv);
4176 throw { type: 'Runtime', message: "wrong number of arguments for " + this.name +
4177 ' (' + args.length + ' for ' + this.arity + ')' };
4180 frame.rules.unshift(new(tree.Rule)(name, val));
4181 evaldArguments[i] = val;
4185 if (params[i].variadic && args) {
4186 for (j = argIndex; j < args.length; j++) {
4187 evaldArguments[j] = args[j].value.eval(env);
4195 eval: function (env, args, important) {
4196 var _arguments = [],
4197 mixinFrames = this.frames.concat(env.frames),
4198 frame = this.evalParams(env, new(tree.evalEnv)(env, mixinFrames), args, _arguments),
4201 frame.rules.unshift(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env)));
4203 rules = this.rules.slice(0);
4205 ruleset = new(tree.Ruleset)(null, rules);
4206 ruleset.originalRuleset = this;
4207 ruleset = ruleset.eval(new(tree.evalEnv)(env, [this, frame].concat(mixinFrames)));
4209 ruleset = this.parent.makeImportant.apply(ruleset);
4213 matchCondition: function (args, env) {
4214 if (this.condition && !this.condition.eval(
4215 new(tree.evalEnv)(env,
4216 [this.evalParams(env, new(tree.evalEnv)(env, this.frames.concat(env.frames)), args, [])] // the parameter variables
4217 .concat(this.frames) // the parent namespace/mixin frames
4218 .concat(env.frames)))) { // the current environment frames
4223 matchArgs: function (args, env) {
4224 var argsLength = (args && args.length) || 0, len;
4226 if (! this.variadic) {
4227 if (argsLength < this.required) { return false; }
4228 if (argsLength > this.params.length) { return false; }
4230 if (argsLength < (this.required - 1)) { return false; }
4233 len = Math.min(argsLength, this.arity);
4235 for (var i = 0; i < len; i++) {
4236 if (!this.params[i].name && !this.params[i].variadic) {
4237 if (args[i].value.eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) {
4246 })(require('../tree'));
4250 tree.Negative = function (node) {
4253 tree.Negative.prototype = {
4255 accept: function (visitor) {
4256 this.value = visitor.visit(this.value);
4258 genCSS: function (env, output) {
4260 this.value.genCSS(env, output);
4263 eval: function (env) {
4264 if (env.isMathOn()) {
4265 return (new(tree.Operation)('*', [new(tree.Dimension)(-1), this.value])).eval(env);
4267 return new(tree.Negative)(this.value.eval(env));
4271 })(require('../tree'));
4275 tree.Operation = function (op, operands, isSpaced) {
4276 this.op = op.trim();
4277 this.operands = operands;
4278 this.isSpaced = isSpaced;
4280 tree.Operation.prototype = {
4282 accept: function (visitor) {
4283 this.operands = visitor.visit(this.operands);
4285 eval: function (env) {
4286 var a = this.operands[0].eval(env),
4287 b = this.operands[1].eval(env),
4290 if (env.isMathOn()) {
4291 if (a instanceof tree.Dimension && b instanceof tree.Color) {
4292 if (this.op === '*' || this.op === '+') {
4293 temp = b, b = a, a = temp;
4295 throw { type: "Operation",
4296 message: "Can't substract or divide a color from a number" };
4300 throw { type: "Operation",
4301 message: "Operation on an invalid type" };
4304 return a.operate(env, this.op, b);
4306 return new(tree.Operation)(this.op, [a, b], this.isSpaced);
4309 genCSS: function (env, output) {
4310 this.operands[0].genCSS(env, output);
4311 if (this.isSpaced) {
4314 output.add(this.op);
4315 if (this.isSpaced) {
4318 this.operands[1].genCSS(env, output);
4323 tree.operate = function (env, op, a, b) {
4325 case '+': return a + b;
4326 case '-': return a - b;
4327 case '*': return a * b;
4328 case '/': return a / b;
4332 })(require('../tree'));
4337 tree.Paren = function (node) {
4340 tree.Paren.prototype = {
4342 accept: function (visitor) {
4343 this.value = visitor.visit(this.value);
4345 genCSS: function (env, output) {
4347 this.value.genCSS(env, output);
4351 eval: function (env) {
4352 return new(tree.Paren)(this.value.eval(env));
4356 })(require('../tree'));
4360 tree.Quoted = function (str, content, escaped, index, currentFileInfo) {
4361 this.escaped = escaped;
4362 this.value = content || '';
4363 this.quote = str.charAt(0);
4365 this.currentFileInfo = currentFileInfo;
4367 tree.Quoted.prototype = {
4369 genCSS: function (env, output) {
4370 if (!this.escaped) {
4371 output.add(this.quote, this.currentFileInfo, this.index);
4373 output.add(this.value);
4374 if (!this.escaped) {
4375 output.add(this.quote);
4379 eval: function (env) {
4381 var value = this.value.replace(/`([^`]+)`/g, function (_, exp) {
4382 return new(tree.JavaScript)(exp, that.index, true).eval(env).value;
4383 }).replace(/@\{([\w-]+)\}/g, function (_, name) {
4384 var v = new(tree.Variable)('@' + name, that.index, that.currentFileInfo).eval(env, true);
4385 return (v instanceof tree.Quoted) ? v.value : v.toCSS();
4387 return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index, this.currentFileInfo);
4389 compare: function (x) {
4394 var left = this.toCSS(),
4397 if (left === right) {
4401 return left < right ? -1 : 1;
4405 })(require('../tree'));
4409 tree.Rule = function (name, value, important, merge, index, currentFileInfo, inline) {
4411 this.value = (value instanceof tree.Value) ? value : new(tree.Value)([value]);
4412 this.important = important ? ' ' + important.trim() : '';
4415 this.currentFileInfo = currentFileInfo;
4416 this.inline = inline || false;
4417 this.variable = (name.charAt(0) === '@');
4420 tree.Rule.prototype = {
4422 accept: function (visitor) {
4423 this.value = visitor.visit(this.value);
4425 genCSS: function (env, output) {
4426 output.add(this.name + (env.compress ? ':' : ': '), this.currentFileInfo, this.index);
4428 this.value.genCSS(env, output);
4431 e.index = this.index;
4432 e.filename = this.currentFileInfo.filename;
4435 output.add(this.important + ((this.inline || (env.lastRule && env.compress)) ? "" : ";"), this.currentFileInfo, this.index);
4438 eval: function (env) {
4439 var strictMathBypass = false;
4440 if (this.name === "font" && !env.strictMath) {
4441 strictMathBypass = true;
4442 env.strictMath = true;
4445 return new(tree.Rule)(this.name,
4446 this.value.eval(env),
4449 this.index, this.currentFileInfo, this.inline);
4452 if (strictMathBypass) {
4453 env.strictMath = false;
4457 makeImportant: function () {
4458 return new(tree.Rule)(this.name,
4462 this.index, this.currentFileInfo, this.inline);
4466 })(require('../tree'));
4470 tree.Ruleset = function (selectors, rules, strictImports) {
4471 this.selectors = selectors;
4474 this.strictImports = strictImports;
4476 tree.Ruleset.prototype = {
4478 accept: function (visitor) {
4480 for(var i = 0; i < this.paths.length; i++) {
4481 this.paths[i] = visitor.visit(this.paths[i]);
4484 this.selectors = visitor.visit(this.selectors);
4486 this.rules = visitor.visit(this.rules);
4488 eval: function (env) {
4489 var selectors = this.selectors && this.selectors.map(function (s) { return s.eval(env); });
4490 var ruleset = new(tree.Ruleset)(selectors, this.rules.slice(0), this.strictImports);
4495 ruleset.originalRuleset = this;
4496 ruleset.root = this.root;
4497 ruleset.firstRoot = this.firstRoot;
4498 ruleset.allowImports = this.allowImports;
4500 if(this.debugInfo) {
4501 ruleset.debugInfo = this.debugInfo;
4504 // push the current ruleset to the frames stack
4505 env.frames.unshift(ruleset);
4507 // currrent selectors
4508 if (!env.selectors) {
4511 env.selectors.unshift(this.selectors);
4514 if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) {
4515 ruleset.evalImports(env);
4518 // Store the frames around mixin definitions,
4519 // so they can be evaluated like closures when the time comes.
4520 for (i = 0; i < ruleset.rules.length; i++) {
4521 if (ruleset.rules[i] instanceof tree.mixin.Definition) {
4522 ruleset.rules[i].frames = env.frames.slice(0);
4526 var mediaBlockCount = (env.mediaBlocks && env.mediaBlocks.length) || 0;
4528 // Evaluate mixin calls.
4529 for (i = 0; i < ruleset.rules.length; i++) {
4530 if (ruleset.rules[i] instanceof tree.mixin.Call) {
4531 /*jshint loopfunc:true */
4532 rules = ruleset.rules[i].eval(env).filter(function(r) {
4533 if ((r instanceof tree.Rule) && r.variable) {
4534 // do not pollute the scope if the variable is
4535 // already there. consider returning false here
4536 // but we need a way to "return" variable from mixins
4537 return !(ruleset.variable(r.name));
4541 ruleset.rules.splice.apply(ruleset.rules, [i, 1].concat(rules));
4542 i += rules.length-1;
4543 ruleset.resetCache();
4547 // Evaluate everything else
4548 for (i = 0; i < ruleset.rules.length; i++) {
4549 rule = ruleset.rules[i];
4551 if (! (rule instanceof tree.mixin.Definition)) {
4552 ruleset.rules[i] = rule.eval ? rule.eval(env) : rule;
4558 env.selectors.shift();
4560 if (env.mediaBlocks) {
4561 for (i = mediaBlockCount; i < env.mediaBlocks.length; i++) {
4562 env.mediaBlocks[i].bubbleSelectors(selectors);
4568 evalImports: function(env) {
4570 for (i = 0; i < this.rules.length; i++) {
4571 if (this.rules[i] instanceof tree.Import) {
4572 rules = this.rules[i].eval(env);
4573 if (typeof rules.length === "number") {
4574 this.rules.splice.apply(this.rules, [i, 1].concat(rules));
4577 this.rules.splice(i, 1, rules);
4583 makeImportant: function() {
4584 return new tree.Ruleset(this.selectors, this.rules.map(function (r) {
4585 if (r.makeImportant) {
4586 return r.makeImportant();
4590 }), this.strictImports);
4592 matchArgs: function (args) {
4593 return !args || args.length === 0;
4595 matchCondition: function (args, env) {
4596 var lastSelector = this.selectors[this.selectors.length-1];
4597 if (lastSelector.condition &&
4598 !lastSelector.condition.eval(
4599 new(tree.evalEnv)(env,
4605 resetCache: function () {
4606 this._rulesets = null;
4607 this._variables = null;
4610 variables: function () {
4611 if (this._variables) { return this._variables; }
4613 return this._variables = this.rules.reduce(function (hash, r) {
4614 if (r instanceof tree.Rule && r.variable === true) {
4621 variable: function (name) {
4622 return this.variables()[name];
4624 rulesets: function () {
4625 return this.rules.filter(function (r) {
4626 return (r instanceof tree.Ruleset) || (r instanceof tree.mixin.Definition);
4629 find: function (selector, self) {
4630 self = self || this;
4631 var rules = [], match,
4632 key = selector.toCSS();
4634 if (key in this._lookups) { return this._lookups[key]; }
4636 this.rulesets().forEach(function (rule) {
4637 if (rule !== self) {
4638 for (var j = 0; j < rule.selectors.length; j++) {
4639 if (match = selector.match(rule.selectors[j])) {
4640 if (selector.elements.length > match) {
4641 Array.prototype.push.apply(rules, rule.find(
4642 new(tree.Selector)(selector.elements.slice(match)), self));
4651 return this._lookups[key] = rules;
4653 genCSS: function (env, output) {
4657 debugInfo, // Line number debugging
4659 firstRuleset = true,
4662 env.tabLevel = (env.tabLevel || 0);
4668 var tabRuleStr = env.compress ? '' : Array(env.tabLevel + 1).join(" "),
4669 tabSetStr = env.compress ? '' : Array(env.tabLevel).join(" ");
4671 for (i = 0; i < this.rules.length; i++) {
4672 rule = this.rules[i];
4673 if (rule.rules || (rule instanceof tree.Media) || rule instanceof tree.Directive || (this.root && rule instanceof tree.Comment)) {
4674 rulesetNodes.push(rule);
4676 ruleNodes.push(rule);
4680 // If this is the root node, we don't render
4681 // a selector, or {}.
4683 debugInfo = tree.debugInfo(env, this, tabSetStr);
4686 output.add(debugInfo);
4687 output.add(tabSetStr);
4690 for(i = 0; i < this.paths.length; i++) {
4691 path = this.paths[i];
4692 env.firstSelector = true;
4693 for(j = 0; j < path.length; j++) {
4694 path[j].genCSS(env, output);
4695 env.firstSelector = false;
4697 if (i + 1 < this.paths.length) {
4698 output.add(env.compress ? ',' : (',\n' + tabSetStr));
4702 output.add((env.compress ? '{' : ' {\n') + tabRuleStr);
4705 // Compile rules and rulesets
4706 for (i = 0; i < ruleNodes.length; i++) {
4707 rule = ruleNodes[i];
4709 // @page{ directive ends up with root elements inside it, a mix of rules and rulesets
4710 // In this instance we do not know whether it is the last property
4711 if (i + 1 === ruleNodes.length && (!this.root || rulesetNodes.length === 0 || this.firstRoot)) {
4712 env.lastRule = true;
4716 rule.genCSS(env, output);
4717 } else if (rule.value) {
4718 output.add(rule.value.toString());
4721 if (!env.lastRule) {
4722 output.add(env.compress ? '' : ('\n' + tabRuleStr));
4724 env.lastRule = false;
4729 output.add((env.compress ? '}' : '\n' + tabSetStr + '}'));
4733 for (i = 0; i < rulesetNodes.length; i++) {
4734 if (ruleNodes.length && firstRuleset) {
4735 output.add((env.compress ? "" : "\n") + (this.root ? tabRuleStr : tabSetStr));
4737 if (!firstRuleset) {
4738 output.add((env.compress ? "" : "\n") + (this.root ? tabRuleStr : tabSetStr));
4740 firstRuleset = false;
4741 rulesetNodes[i].genCSS(env, output);
4744 if (!output.isEmpty() && !env.compress && this.firstRoot) {
4751 markReferenced: function () {
4752 for (var s = 0; s < this.selectors.length; s++) {
4753 this.selectors[s].markReferenced();
4757 joinSelectors: function (paths, context, selectors) {
4758 for (var s = 0; s < selectors.length; s++) {
4759 this.joinSelector(paths, context, selectors[s]);
4763 joinSelector: function (paths, context, selector) {
4766 hasParentSelector, newSelectors, el, sel, parentSel,
4767 newSelectorPath, afterParentJoin, newJoinedSelector,
4768 newJoinedSelectorEmpty, lastSelector, currentElements,
4769 selectorsMultiplied;
4771 for (i = 0; i < selector.elements.length; i++) {
4772 el = selector.elements[i];
4773 if (el.value === '&') {
4774 hasParentSelector = true;
4778 if (!hasParentSelector) {
4779 if (context.length > 0) {
4780 for (i = 0; i < context.length; i++) {
4781 paths.push(context[i].concat(selector));
4785 paths.push([selector]);
4790 // The paths are [[Selector]]
4791 // The first list is a list of comma seperated selectors
4792 // The inner list is a list of inheritance seperated selectors
4798 // == [[.a] [.c]] [[.b] [.c]]
4801 // the elements from the current selector so far
4802 currentElements = [];
4803 // the current list of new selectors to add to the path.
4804 // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors
4806 newSelectors = [[]];
4808 for (i = 0; i < selector.elements.length; i++) {
4809 el = selector.elements[i];
4810 // non parent reference elements just get added
4811 if (el.value !== "&") {
4812 currentElements.push(el);
4814 // the new list of selectors to add
4815 selectorsMultiplied = [];
4817 // merge the current list of non parent selector elements
4818 // on to the current list of selectors to add
4819 if (currentElements.length > 0) {
4820 this.mergeElementsOnToSelectors(currentElements, newSelectors);
4823 // loop through our current selectors
4824 for (j = 0; j < newSelectors.length; j++) {
4825 sel = newSelectors[j];
4826 // if we don't have any parent paths, the & might be in a mixin so that it can be used
4827 // whether there are parents or not
4828 if (context.length === 0) {
4829 // the combinator used on el should now be applied to the next element instead so that
4831 if (sel.length > 0) {
4832 sel[0].elements = sel[0].elements.slice(0);
4833 sel[0].elements.push(new(tree.Element)(el.combinator, '', 0, el.index, el.currentFileInfo));
4835 selectorsMultiplied.push(sel);
4838 // and the parent selectors
4839 for (k = 0; k < context.length; k++) {
4840 parentSel = context[k];
4841 // We need to put the current selectors
4842 // then join the last selector's elements on to the parents selectors
4844 // our new selector path
4845 newSelectorPath = [];
4846 // selectors from the parent after the join
4847 afterParentJoin = [];
4848 newJoinedSelectorEmpty = true;
4850 //construct the joined selector - if & is the first thing this will be empty,
4851 // if not newJoinedSelector will be the last set of elements in the selector
4852 if (sel.length > 0) {
4853 newSelectorPath = sel.slice(0);
4854 lastSelector = newSelectorPath.pop();
4855 newJoinedSelector = selector.createDerived(lastSelector.elements.slice(0));
4856 newJoinedSelectorEmpty = false;
4859 newJoinedSelector = selector.createDerived([]);
4862 //put together the parent selectors after the join
4863 if (parentSel.length > 1) {
4864 afterParentJoin = afterParentJoin.concat(parentSel.slice(1));
4867 if (parentSel.length > 0) {
4868 newJoinedSelectorEmpty = false;
4870 // join the elements so far with the first part of the parent
4871 newJoinedSelector.elements.push(new(tree.Element)(el.combinator, parentSel[0].elements[0].value, el.index, el.currentFileInfo));
4872 newJoinedSelector.elements = newJoinedSelector.elements.concat(parentSel[0].elements.slice(1));
4875 if (!newJoinedSelectorEmpty) {
4876 // now add the joined selector
4877 newSelectorPath.push(newJoinedSelector);
4880 // and the rest of the parent
4881 newSelectorPath = newSelectorPath.concat(afterParentJoin);
4883 // add that to our new set of selectors
4884 selectorsMultiplied.push(newSelectorPath);
4889 // our new selectors has been multiplied, so reset the state
4890 newSelectors = selectorsMultiplied;
4891 currentElements = [];
4895 // if we have any elements left over (e.g. .a& .b == .b)
4896 // add them on to all the current selectors
4897 if (currentElements.length > 0) {
4898 this.mergeElementsOnToSelectors(currentElements, newSelectors);
4901 for (i = 0; i < newSelectors.length; i++) {
4902 if (newSelectors[i].length > 0) {
4903 paths.push(newSelectors[i]);
4908 mergeElementsOnToSelectors: function(elements, selectors) {
4911 if (selectors.length === 0) {
4912 selectors.push([ new(tree.Selector)(elements) ]);
4916 for (i = 0; i < selectors.length; i++) {
4919 // if the previous thing in sel is a parent this needs to join on to it
4920 if (sel.length > 0) {
4921 sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements));
4924 sel.push(new(tree.Selector)(elements));
4929 })(require('../tree'));
4933 tree.Selector = function (elements, extendList, condition, index, currentFileInfo, isReferenced) {
4934 this.elements = elements;
4935 this.extendList = extendList || [];
4936 this.condition = condition;
4937 this.currentFileInfo = currentFileInfo || {};
4938 this.isReferenced = isReferenced;
4940 this.evaldCondition = true;
4943 tree.Selector.prototype = {
4945 accept: function (visitor) {
4946 this.elements = visitor.visit(this.elements);
4947 this.extendList = visitor.visit(this.extendList);
4948 this.condition = visitor.visit(this.condition);
4950 createDerived: function(elements, extendList, evaldCondition) {
4951 /*jshint eqnull:true */
4952 evaldCondition = evaldCondition != null ? evaldCondition : this.evaldCondition;
4953 var newSelector = new(tree.Selector)(elements, extendList || this.extendList, this.condition, this.index, this.currentFileInfo, this.isReferenced);
4954 newSelector.evaldCondition = evaldCondition;
4957 match: function (other) {
4958 var elements = this.elements,
4959 len = elements.length,
4960 oelements, olen, max, i;
4962 oelements = other.elements.slice(
4963 (other.elements.length && other.elements[0].value === "&") ? 1 : 0);
4964 olen = oelements.length;
4965 max = Math.min(len, olen);
4967 if (olen === 0 || len < olen) {
4970 for (i = 0; i < max; i++) {
4971 if (elements[i].value !== oelements[i].value) {
4976 return max; // return number of matched selectors
4978 eval: function (env) {
4979 var evaldCondition = this.condition && this.condition.eval(env);
4981 return this.createDerived(this.elements.map(function (e) {
4983 }), this.extendList.map(function(extend) {
4984 return extend.eval(env);
4985 }), evaldCondition);
4987 genCSS: function (env, output) {
4989 if ((!env || !env.firstSelector) && this.elements[0].combinator.value === "") {
4990 output.add(' ', this.currentFileInfo, this.index);
4993 //TODO caching? speed comparison?
4994 for(i = 0; i < this.elements.length; i++) {
4995 element = this.elements[i];
4996 element.genCSS(env, output);
5001 markReferenced: function () {
5002 this.isReferenced = true;
5004 getIsReferenced: function() {
5005 return !this.currentFileInfo.reference || this.isReferenced;
5007 getIsOutput: function() {
5008 return this.evaldCondition;
5012 })(require('../tree'));
5016 tree.UnicodeDescriptor = function (value) {
5019 tree.UnicodeDescriptor.prototype = {
5020 type: "UnicodeDescriptor",
5021 genCSS: function (env, output) {
5022 output.add(this.value);
5025 eval: function () { return this; }
5028 })(require('../tree'));
5032 tree.URL = function (val, currentFileInfo) {
5034 this.currentFileInfo = currentFileInfo;
5036 tree.URL.prototype = {
5038 accept: function (visitor) {
5039 this.value = visitor.visit(this.value);
5041 genCSS: function (env, output) {
5043 this.value.genCSS(env, output);
5047 eval: function (ctx) {
5048 var val = this.value.eval(ctx), rootpath;
5050 // Add the base path if the URL is relative
5051 rootpath = this.currentFileInfo && this.currentFileInfo.rootpath;
5052 if (rootpath && typeof val.value === "string" && ctx.isPathRelative(val.value)) {
5054 rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return "\\"+match; });
5056 val.value = rootpath + val.value;
5059 val.value = ctx.normalizePath(val.value);
5061 return new(tree.URL)(val, null);
5065 })(require('../tree'));
5069 tree.Value = function (value) {
5072 tree.Value.prototype = {
5074 accept: function (visitor) {
5075 this.value = visitor.visit(this.value);
5077 eval: function (env) {
5078 if (this.value.length === 1) {
5079 return this.value[0].eval(env);
5081 return new(tree.Value)(this.value.map(function (v) {
5086 genCSS: function (env, output) {
5088 for(i = 0; i < this.value.length; i++) {
5089 this.value[i].genCSS(env, output);
5090 if (i+1 < this.value.length) {
5091 output.add((env && env.compress) ? ',' : ', ');
5098 })(require('../tree'));
5102 tree.Variable = function (name, index, currentFileInfo) {
5105 this.currentFileInfo = currentFileInfo;
5107 tree.Variable.prototype = {
5109 eval: function (env) {
5110 var variable, v, name = this.name;
5112 if (name.indexOf('@@') === 0) {
5113 name = '@' + new(tree.Variable)(name.slice(1)).eval(env).value;
5116 if (this.evaluating) {
5117 throw { type: 'Name',
5118 message: "Recursive variable definition for " + name,
5119 filename: this.currentFileInfo.file,
5120 index: this.index };
5123 this.evaluating = true;
5125 if (variable = tree.find(env.frames, function (frame) {
5126 if (v = frame.variable(name)) {
5127 return v.value.eval(env);
5130 this.evaluating = false;
5134 throw { type: 'Name',
5135 message: "variable " + name + " is undefined",
5136 filename: this.currentFileInfo.filename,
5137 index: this.index };
5142 })(require('../tree'));
5146 var parseCopyProperties = [
5147 'paths', // option - unmodified - paths to search for imports on
5148 'optimization', // option - optimization level (for the chunker)
5149 'files', // list of files that have been imported, used for import-once
5150 'contents', // browser-only, contents of all the files
5151 'relativeUrls', // option - whether to adjust URL's to be relative
5152 'rootpath', // option - rootpath to append to URL's
5153 'strictImports', // option -
5154 'insecure', // option - whether to allow imports from insecure ssl hosts
5155 'dumpLineNumbers', // option - whether to dump line numbers
5156 'compress', // option - whether to compress
5157 'processImports', // option - whether to process imports. if false then imports will not be imported
5158 'syncImport', // option - whether to import synchronously
5159 'javascriptEnabled',// option - whether JavaScript is enabled. if undefined, defaults to true
5160 'mime', // browser only - mime type for sheet import
5161 'useFileCache', // browser only - whether to use the per file session cache
5162 'currentFileInfo' // information about the current file - for error reporting and importing and making urls relative etc.
5165 //currentFileInfo = {
5166 // 'relativeUrls' - option - whether to adjust URL's to be relative
5167 // 'filename' - full resolved filename of current file
5168 // 'rootpath' - path to append to normal URLs for this node
5169 // 'currentDirectory' - path to the current file, absolute
5170 // 'rootFilename' - filename of the base file
5171 // 'entryPath' - absolute path to the entry file
5172 // 'reference' - whether the file should not be output and only output parts that are referenced
5174 tree.parseEnv = function(options) {
5175 copyFromOriginal(options, this, parseCopyProperties);
5177 if (!this.contents) { this.contents = {}; }
5178 if (!this.files) { this.files = {}; }
5180 if (!this.currentFileInfo) {
5181 var filename = (options && options.filename) || "input";
5182 var entryPath = filename.replace(/[^\/\\]*$/, "");
5184 options.filename = null;
5186 this.currentFileInfo = {
5188 relativeUrls: this.relativeUrls,
5189 rootpath: (options && options.rootpath) || "",
5190 currentDirectory: entryPath,
5191 entryPath: entryPath,
5192 rootFilename: filename
5197 var evalCopyProperties = [
5198 'silent', // whether to swallow errors and warnings
5199 'verbose', // whether to log more activity
5200 'compress', // whether to compress
5201 'yuicompress', // whether to compress with the outside tool yui compressor
5202 'ieCompat', // whether to enforce IE compatibility (IE8 data-uri)
5203 'strictMath', // whether math has to be within parenthesis
5204 'strictUnits', // whether units need to evaluate correctly
5205 'cleancss', // whether to compress with clean-css
5206 'sourceMap', // whether to output a source map
5207 'importMultiple'// whether we are currently importing multiple copies
5210 tree.evalEnv = function(options, frames) {
5211 copyFromOriginal(options, this, evalCopyProperties);
5213 this.frames = frames || [];
5216 tree.evalEnv.prototype.inParenthesis = function () {
5217 if (!this.parensStack) {
5218 this.parensStack = [];
5220 this.parensStack.push(true);
5223 tree.evalEnv.prototype.outOfParenthesis = function () {
5224 this.parensStack.pop();
5227 tree.evalEnv.prototype.isMathOn = function () {
5228 return this.strictMath ? (this.parensStack && this.parensStack.length) : true;
5231 tree.evalEnv.prototype.isPathRelative = function (path) {
5232 return !/^(?:[a-z-]+:|\/)/.test(path);
5235 tree.evalEnv.prototype.normalizePath = function( path ) {
5237 segments = path.split("/").reverse(),
5241 while (segments.length !== 0 ) {
5242 segment = segments.pop();
5247 if ((path.length === 0) || (path[path.length - 1] === "..")) {
5248 path.push( segment );
5254 path.push( segment );
5259 return path.join("/");
5262 //todo - do the same for the toCSS env
5263 //tree.toCSSEnv = function (options) {
5266 var copyFromOriginal = function(original, destination, propertiesToCopy) {
5267 if (!original) { return; }
5269 for(var i = 0; i < propertiesToCopy.length; i++) {
5270 if (original.hasOwnProperty(propertiesToCopy[i])) {
5271 destination[propertiesToCopy[i]] = original[propertiesToCopy[i]];
5276 })(require('./tree'));
5280 tree.visitor = function(implementation) {
5281 this._implementation = implementation;
5284 tree.visitor.prototype = {
5285 visit: function(node) {
5287 if (node instanceof Array) {
5288 return this.visitArray(node);
5291 if (!node || !node.type) {
5295 var funcName = "visit" + node.type,
5296 func = this._implementation[funcName],
5299 visitArgs = {visitDeeper: true};
5300 newNode = func.call(this._implementation, node, visitArgs);
5301 if (this._implementation.isReplacing) {
5305 if ((!visitArgs || visitArgs.visitDeeper) && node && node.accept) {
5308 funcName = funcName + "Out";
5309 if (this._implementation[funcName]) {
5310 this._implementation[funcName](node);
5314 visitArray: function(nodes) {
5315 var i, newNodes = [];
5316 for(i = 0; i < nodes.length; i++) {
5317 var evald = this.visit(nodes[i]);
5318 if (evald instanceof Array) {
5319 evald = this.flatten(evald);
5320 newNodes = newNodes.concat(evald);
5322 newNodes.push(evald);
5325 if (this._implementation.isReplacing) {
5330 doAccept: function (node) {
5333 flatten: function(arr, master) {
5334 return arr.reduce(this.flattenReduce.bind(this), master || []);
5336 flattenReduce: function(sum, element) {
5337 if (element instanceof Array) {
5338 sum = this.flatten(element, sum);
5346 })(require('./tree'));
5348 tree.importVisitor = function(importer, finish, evalEnv) {
5349 this._visitor = new tree.visitor(this);
5350 this._importer = importer;
5351 this._finish = finish;
5352 this.env = evalEnv || new tree.evalEnv();
5353 this.importCount = 0;
5356 tree.importVisitor.prototype = {
5358 run: function (root) {
5361 // process the contents
5362 this._visitor.visit(root);
5368 this.isFinished = true;
5370 if (this.importCount === 0) {
5371 this._finish(error);
5374 visitImport: function (importNode, visitArgs) {
5375 var importVisitor = this,
5377 inlineCSS = importNode.options.inline;
5379 if (!importNode.css || inlineCSS) {
5382 evaldImportNode = importNode.evalForImport(this.env);
5384 if (!e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; }
5385 // attempt to eval properly and treat as css
5386 importNode.css = true;
5387 // if that fails, this error will be thrown
5388 importNode.error = e;
5391 if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) {
5392 importNode = evaldImportNode;
5394 var env = new tree.evalEnv(this.env, this.env.frames.slice(0));
5396 if (importNode.options.multiple) {
5397 env.importMultiple = true;
5400 this._importer.push(importNode.getPath(), importNode.currentFileInfo, importNode.options, function (e, root, imported, fullPath) {
5401 if (e && !e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; }
5403 if (imported && !env.importMultiple) { importNode.skip = imported; }
5405 var subFinish = function(e) {
5406 importVisitor.importCount--;
5408 if (importVisitor.importCount === 0 && importVisitor.isFinished) {
5409 importVisitor._finish(e);
5414 importNode.root = root;
5415 importNode.importedFilename = fullPath;
5416 if (!inlineCSS && !importNode.skip) {
5417 new(tree.importVisitor)(importVisitor._importer, subFinish, env)
5427 visitArgs.visitDeeper = false;
5430 visitRule: function (ruleNode, visitArgs) {
5431 visitArgs.visitDeeper = false;
5434 visitDirective: function (directiveNode, visitArgs) {
5435 this.env.frames.unshift(directiveNode);
5436 return directiveNode;
5438 visitDirectiveOut: function (directiveNode) {
5439 this.env.frames.shift();
5441 visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
5442 this.env.frames.unshift(mixinDefinitionNode);
5443 return mixinDefinitionNode;
5445 visitMixinDefinitionOut: function (mixinDefinitionNode) {
5446 this.env.frames.shift();
5448 visitRuleset: function (rulesetNode, visitArgs) {
5449 this.env.frames.unshift(rulesetNode);
5452 visitRulesetOut: function (rulesetNode) {
5453 this.env.frames.shift();
5455 visitMedia: function (mediaNode, visitArgs) {
5456 this.env.frames.unshift(mediaNode.ruleset);
5459 visitMediaOut: function (mediaNode) {
5460 this.env.frames.shift();
5464 })(require('./tree'));
5466 tree.joinSelectorVisitor = function() {
5467 this.contexts = [[]];
5468 this._visitor = new tree.visitor(this);
5471 tree.joinSelectorVisitor.prototype = {
5472 run: function (root) {
5473 return this._visitor.visit(root);
5475 visitRule: function (ruleNode, visitArgs) {
5476 visitArgs.visitDeeper = false;
5478 visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
5479 visitArgs.visitDeeper = false;
5482 visitRuleset: function (rulesetNode, visitArgs) {
5483 var context = this.contexts[this.contexts.length - 1];
5485 this.contexts.push(paths);
5487 if (! rulesetNode.root) {
5488 rulesetNode.selectors = rulesetNode.selectors.filter(function(selector) { return selector.getIsOutput(); });
5489 if (rulesetNode.selectors.length === 0) {
5490 rulesetNode.rules.length = 0;
5492 rulesetNode.joinSelectors(paths, context, rulesetNode.selectors);
5493 rulesetNode.paths = paths;
5496 visitRulesetOut: function (rulesetNode) {
5497 this.contexts.length = this.contexts.length - 1;
5499 visitMedia: function (mediaNode, visitArgs) {
5500 var context = this.contexts[this.contexts.length - 1];
5501 mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia);
5505 })(require('./tree'));
5507 tree.toCSSVisitor = function(env) {
5508 this._visitor = new tree.visitor(this);
5512 tree.toCSSVisitor.prototype = {
5514 run: function (root) {
5515 return this._visitor.visit(root);
5518 visitRule: function (ruleNode, visitArgs) {
5519 if (ruleNode.variable) {
5525 visitMixinDefinition: function (mixinNode, visitArgs) {
5529 visitExtend: function (extendNode, visitArgs) {
5533 visitComment: function (commentNode, visitArgs) {
5534 if (commentNode.isSilent(this._env)) {
5540 visitMedia: function(mediaNode, visitArgs) {
5541 mediaNode.accept(this._visitor);
5542 visitArgs.visitDeeper = false;
5544 if (!mediaNode.rules.length) {
5550 visitDirective: function(directiveNode, visitArgs) {
5551 if (directiveNode.currentFileInfo.reference && !directiveNode.isReferenced) {
5554 if (directiveNode.name === "@charset") {
5555 // Only output the debug info together with subsequent @charset definitions
5556 // a comment (or @media statement) before the actual @charset directive would
5557 // be considered illegal css as it has to be on the first line
5559 if (directiveNode.debugInfo) {
5560 var comment = new tree.Comment("/* " + directiveNode.toCSS(this._env).replace(/\n/g, "")+" */\n");
5561 comment.debugInfo = directiveNode.debugInfo;
5562 return this._visitor.visit(comment);
5566 this.charset = true;
5568 return directiveNode;
5571 checkPropertiesInRoot: function(rules) {
5573 for(var i = 0; i < rules.length; i++) {
5574 ruleNode = rules[i];
5575 if (ruleNode instanceof tree.Rule && !ruleNode.variable) {
5576 throw { message: "properties must be inside selector blocks, they cannot be in the root.",
5577 index: ruleNode.index, filename: ruleNode.currentFileInfo ? ruleNode.currentFileInfo.filename : null};
5582 visitRuleset: function (rulesetNode, visitArgs) {
5583 var rule, rulesets = [];
5584 if (rulesetNode.firstRoot) {
5585 this.checkPropertiesInRoot(rulesetNode.rules);
5587 if (! rulesetNode.root) {
5589 rulesetNode.paths = rulesetNode.paths
5590 .filter(function(p) {
5592 if (p[0].elements[0].combinator.value === ' ') {
5593 p[0].elements[0].combinator = new(tree.Combinator)('');
5595 for(i = 0; i < p.length; i++) {
5596 if (p[i].getIsReferenced() && p[i].getIsOutput()) {
5603 // Compile rules and rulesets
5604 for (var i = 0; i < rulesetNode.rules.length; i++) {
5605 rule = rulesetNode.rules[i];
5608 // visit because we are moving them out from being a child
5609 rulesets.push(this._visitor.visit(rule));
5610 rulesetNode.rules.splice(i, 1);
5615 // accept the visitor to remove rules and refactor itself
5616 // then we can decide now whether we want it or not
5617 if (rulesetNode.rules.length > 0) {
5618 rulesetNode.accept(this._visitor);
5620 visitArgs.visitDeeper = false;
5622 this._mergeRules(rulesetNode.rules);
5623 this._removeDuplicateRules(rulesetNode.rules);
5625 // now decide whether we keep the ruleset
5626 if (rulesetNode.rules.length > 0 && rulesetNode.paths.length > 0) {
5627 rulesets.splice(0, 0, rulesetNode);
5630 rulesetNode.accept(this._visitor);
5631 visitArgs.visitDeeper = false;
5632 if (rulesetNode.firstRoot || rulesetNode.rules.length > 0) {
5633 rulesets.splice(0, 0, rulesetNode);
5636 if (rulesets.length === 1) {
5642 _removeDuplicateRules: function(rules) {
5643 // remove duplicates
5646 for(i = rules.length - 1; i >= 0 ; i--) {
5648 if (rule instanceof tree.Rule) {
5649 if (!ruleCache[rule.name]) {
5650 ruleCache[rule.name] = rule;
5652 ruleList = ruleCache[rule.name];
5653 if (ruleList instanceof tree.Rule) {
5654 ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._env)];
5656 var ruleCSS = rule.toCSS(this._env);
5657 if (ruleList.indexOf(ruleCSS) !== -1) {
5660 ruleList.push(ruleCSS);
5667 _mergeRules: function (rules) {
5673 for (var i = 0; i < rules.length; i++) {
5676 if ((rule instanceof tree.Rule) && rule.merge) {
5678 rule.important ? "!" : ""].join(",");
5681 parts = groups[key] = [];
5683 rules.splice(i--, 1);
5690 Object.keys(groups).map(function (k) {
5693 if (parts.length > 1) {
5696 rule.value = new (tree.Value)(parts.map(function (p) {
5704 })(require('./tree'));
5706 /*jshint loopfunc:true */
5708 tree.extendFinderVisitor = function() {
5709 this._visitor = new tree.visitor(this);
5711 this.allExtendsStack = [[]];
5714 tree.extendFinderVisitor.prototype = {
5715 run: function (root) {
5716 root = this._visitor.visit(root);
5717 root.allExtends = this.allExtendsStack[0];
5720 visitRule: function (ruleNode, visitArgs) {
5721 visitArgs.visitDeeper = false;
5723 visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
5724 visitArgs.visitDeeper = false;
5726 visitRuleset: function (rulesetNode, visitArgs) {
5728 if (rulesetNode.root) {
5732 var i, j, extend, allSelectorsExtendList = [], extendList;
5734 // get &:extend(.a); rules which apply to all selectors in this ruleset
5735 for(i = 0; i < rulesetNode.rules.length; i++) {
5736 if (rulesetNode.rules[i] instanceof tree.Extend) {
5737 allSelectorsExtendList.push(rulesetNode.rules[i]);
5738 rulesetNode.extendOnEveryPath = true;
5742 // now find every selector and apply the extends that apply to all extends
5743 // and the ones which apply to an individual extend
5744 for(i = 0; i < rulesetNode.paths.length; i++) {
5745 var selectorPath = rulesetNode.paths[i],
5746 selector = selectorPath[selectorPath.length-1];
5747 extendList = selector.extendList.slice(0).concat(allSelectorsExtendList).map(function(allSelectorsExtend) {
5748 return allSelectorsExtend.clone();
5750 for(j = 0; j < extendList.length; j++) {
5751 this.foundExtends = true;
5752 extend = extendList[j];
5753 extend.findSelfSelectors(selectorPath);
5754 extend.ruleset = rulesetNode;
5755 if (j === 0) { extend.firstExtendOnThisSelectorPath = true; }
5756 this.allExtendsStack[this.allExtendsStack.length-1].push(extend);
5760 this.contexts.push(rulesetNode.selectors);
5762 visitRulesetOut: function (rulesetNode) {
5763 if (!rulesetNode.root) {
5764 this.contexts.length = this.contexts.length - 1;
5767 visitMedia: function (mediaNode, visitArgs) {
5768 mediaNode.allExtends = [];
5769 this.allExtendsStack.push(mediaNode.allExtends);
5771 visitMediaOut: function (mediaNode) {
5772 this.allExtendsStack.length = this.allExtendsStack.length - 1;
5774 visitDirective: function (directiveNode, visitArgs) {
5775 directiveNode.allExtends = [];
5776 this.allExtendsStack.push(directiveNode.allExtends);
5778 visitDirectiveOut: function (directiveNode) {
5779 this.allExtendsStack.length = this.allExtendsStack.length - 1;
5783 tree.processExtendsVisitor = function() {
5784 this._visitor = new tree.visitor(this);
5787 tree.processExtendsVisitor.prototype = {
5788 run: function(root) {
5789 var extendFinder = new tree.extendFinderVisitor();
5790 extendFinder.run(root);
5791 if (!extendFinder.foundExtends) { return root; }
5792 root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends));
5793 this.allExtendsStack = [root.allExtends];
5794 return this._visitor.visit(root);
5796 doExtendChaining: function (extendsList, extendsListTarget, iterationCount) {
5798 // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting
5799 // the selector we would do normally, but we are also adding an extend with the same target selector
5800 // this means this new extend can then go and alter other extends
5802 // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors
5803 // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if
5804 // we look at each selector at a time, as is done in visitRuleset
5806 var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath, extend, targetExtend, newExtend;
5808 iterationCount = iterationCount || 0;
5810 //loop through comparing every extend with every target extend.
5811 // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place
5812 // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one
5813 // and the second is the target.
5814 // the seperation into two lists allows us to process a subset of chains with a bigger set, as is the
5815 // case when processing media queries
5816 for(extendIndex = 0; extendIndex < extendsList.length; extendIndex++){
5817 for(targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++){
5819 extend = extendsList[extendIndex];
5820 targetExtend = extendsListTarget[targetExtendIndex];
5822 // look for circular references
5823 if (this.inInheritanceChain(targetExtend, extend)) { continue; }
5825 // find a match in the target extends self selector (the bit before :extend)
5826 selectorPath = [targetExtend.selfSelectors[0]];
5827 matches = extendVisitor.findMatch(extend, selectorPath);
5829 if (matches.length) {
5831 // we found a match, so for each self selector..
5832 extend.selfSelectors.forEach(function(selfSelector) {
5834 // process the extend as usual
5835 newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector);
5837 // but now we create a new extend from it
5838 newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0);
5839 newExtend.selfSelectors = newSelector;
5841 // add the extend onto the list of extends for that selector
5842 newSelector[newSelector.length-1].extendList = [newExtend];
5844 // record that we need to add it.
5845 extendsToAdd.push(newExtend);
5846 newExtend.ruleset = targetExtend.ruleset;
5848 //remember its parents for circular references
5849 newExtend.parents = [targetExtend, extend];
5851 // only process the selector once.. if we have :extend(.a,.b) then multiple
5852 // extends will look at the same selector path, so when extending
5853 // we know that any others will be duplicates in terms of what is added to the css
5854 if (targetExtend.firstExtendOnThisSelectorPath) {
5855 newExtend.firstExtendOnThisSelectorPath = true;
5856 targetExtend.ruleset.paths.push(newSelector);
5863 if (extendsToAdd.length) {
5864 // try to detect circular references to stop a stack overflow.
5865 // may no longer be needed.
5866 this.extendChainCount++;
5867 if (iterationCount > 100) {
5868 var selectorOne = "{unable to calculate}";
5869 var selectorTwo = "{unable to calculate}";
5872 selectorOne = extendsToAdd[0].selfSelectors[0].toCSS();
5873 selectorTwo = extendsToAdd[0].selector.toCSS();
5876 throw {message: "extend circular reference detected. One of the circular extends is currently:"+selectorOne+":extend(" + selectorTwo+")"};
5879 // now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e...
5880 return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount+1));
5882 return extendsToAdd;
5885 inInheritanceChain: function (possibleParent, possibleChild) {
5886 if (possibleParent === possibleChild) {
5889 if (possibleChild.parents) {
5890 if (this.inInheritanceChain(possibleParent, possibleChild.parents[0])) {
5893 if (this.inInheritanceChain(possibleParent, possibleChild.parents[1])) {
5899 visitRule: function (ruleNode, visitArgs) {
5900 visitArgs.visitDeeper = false;
5902 visitMixinDefinition: function (mixinDefinitionNode, visitArgs) {
5903 visitArgs.visitDeeper = false;
5905 visitSelector: function (selectorNode, visitArgs) {
5906 visitArgs.visitDeeper = false;
5908 visitRuleset: function (rulesetNode, visitArgs) {
5909 if (rulesetNode.root) {
5912 var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length-1], selectorsToAdd = [], extendVisitor = this, selectorPath;
5914 // look at each selector path in the ruleset, find any extend matches and then copy, find and replace
5916 for(extendIndex = 0; extendIndex < allExtends.length; extendIndex++) {
5917 for(pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) {
5919 selectorPath = rulesetNode.paths[pathIndex];
5921 // extending extends happens initially, before the main pass
5922 if (rulesetNode.extendOnEveryPath || selectorPath[selectorPath.length-1].extendList.length) { continue; }
5924 matches = this.findMatch(allExtends[extendIndex], selectorPath);
5926 if (matches.length) {
5928 allExtends[extendIndex].selfSelectors.forEach(function(selfSelector) {
5929 selectorsToAdd.push(extendVisitor.extendSelector(matches, selectorPath, selfSelector));
5934 rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd);
5936 findMatch: function (extend, haystackSelectorPath) {
5938 // look through the haystack selector path to try and find the needle - extend.selector
5939 // returns an array of selector matches that can then be replaced
5941 var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement,
5942 targetCombinator, i,
5943 extendVisitor = this,
5944 needleElements = extend.selector.elements,
5945 potentialMatches = [], potentialMatch, matches = [];
5947 // loop through the haystack elements
5948 for(haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) {
5949 hackstackSelector = haystackSelectorPath[haystackSelectorIndex];
5951 for(hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) {
5953 haystackElement = hackstackSelector.elements[hackstackElementIndex];
5955 // if we allow elements before our match we can add a potential match every time. otherwise only at the first element.
5956 if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) {
5957 potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0, initialCombinator: haystackElement.combinator});
5960 for(i = 0; i < potentialMatches.length; i++) {
5961 potentialMatch = potentialMatches[i];
5963 // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't
5964 // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out
5965 // what the resulting combinator will be
5966 targetCombinator = haystackElement.combinator.value;
5967 if (targetCombinator === '' && hackstackElementIndex === 0) {
5968 targetCombinator = ' ';
5971 // if we don't match, null our match to indicate failure
5972 if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) ||
5973 (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) {
5974 potentialMatch = null;
5976 potentialMatch.matched++;
5979 // if we are still valid and have finished, test whether we have elements after and whether these are allowed
5980 if (potentialMatch) {
5981 potentialMatch.finished = potentialMatch.matched === needleElements.length;
5982 if (potentialMatch.finished &&
5983 (!extend.allowAfter && (hackstackElementIndex+1 < hackstackSelector.elements.length || haystackSelectorIndex+1 < haystackSelectorPath.length))) {
5984 potentialMatch = null;
5987 // if null we remove, if not, we are still valid, so either push as a valid match or continue
5988 if (potentialMatch) {
5989 if (potentialMatch.finished) {
5990 potentialMatch.length = needleElements.length;
5991 potentialMatch.endPathIndex = haystackSelectorIndex;
5992 potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match
5993 potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again
5994 matches.push(potentialMatch);
5997 potentialMatches.splice(i, 1);
6005 isElementValuesEqual: function(elementValue1, elementValue2) {
6006 if (typeof elementValue1 === "string" || typeof elementValue2 === "string") {
6007 return elementValue1 === elementValue2;
6009 if (elementValue1 instanceof tree.Attribute) {
6010 if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) {
6013 if (!elementValue1.value || !elementValue2.value) {
6014 if (elementValue1.value || elementValue2.value) {
6019 elementValue1 = elementValue1.value.value || elementValue1.value;
6020 elementValue2 = elementValue2.value.value || elementValue2.value;
6021 return elementValue1 === elementValue2;
6023 elementValue1 = elementValue1.value;
6024 elementValue2 = elementValue2.value;
6025 if (elementValue1 instanceof tree.Selector) {
6026 if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) {
6029 for(var i = 0; i <elementValue1.elements.length; i++) {
6030 if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) {
6031 if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) {
6035 if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) {
6043 extendSelector:function (matches, selectorPath, replacementSelector) {
6045 //for a set of matches, replace each match with the replacement selector
6047 var currentSelectorPathIndex = 0,
6048 currentSelectorPathElementIndex = 0,
6056 for (matchIndex = 0; matchIndex < matches.length; matchIndex++) {
6057 match = matches[matchIndex];
6058 selector = selectorPath[match.pathIndex];
6059 firstElement = new tree.Element(
6060 match.initialCombinator,
6061 replacementSelector.elements[0].value,
6062 replacementSelector.elements[0].index,
6063 replacementSelector.elements[0].currentFileInfo
6066 if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) {
6067 path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
6068 currentSelectorPathElementIndex = 0;
6069 currentSelectorPathIndex++;
6072 newElements = selector.elements
6073 .slice(currentSelectorPathElementIndex, match.index)
6074 .concat([firstElement])
6075 .concat(replacementSelector.elements.slice(1));
6077 if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) {
6078 path[path.length - 1].elements =
6079 path[path.length - 1].elements.concat(newElements);
6081 path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex));
6083 path.push(new tree.Selector(
6087 currentSelectorPathIndex = match.endPathIndex;
6088 currentSelectorPathElementIndex = match.endPathElementIndex;
6089 if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) {
6090 currentSelectorPathElementIndex = 0;
6091 currentSelectorPathIndex++;
6095 if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) {
6096 path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex));
6097 currentSelectorPathIndex++;
6100 path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length));
6104 visitRulesetOut: function (rulesetNode) {
6106 visitMedia: function (mediaNode, visitArgs) {
6107 var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]);
6108 newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends));
6109 this.allExtendsStack.push(newAllExtends);
6111 visitMediaOut: function (mediaNode) {
6112 this.allExtendsStack.length = this.allExtendsStack.length - 1;
6114 visitDirective: function (directiveNode, visitArgs) {
6115 var newAllExtends = directiveNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]);
6116 newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, directiveNode.allExtends));
6117 this.allExtendsStack.push(newAllExtends);
6119 visitDirectiveOut: function (directiveNode) {
6120 this.allExtendsStack.length = this.allExtendsStack.length - 1;
6124 })(require('./tree'));
6128 tree.sourceMapOutput = function (options) {
6130 this._rootNode = options.rootNode;
6131 this._writeSourceMap = options.writeSourceMap;
6132 this._contentsMap = options.contentsMap;
6133 this._sourceMapFilename = options.sourceMapFilename;
6134 this._outputFilename = options.outputFilename;
6135 this._sourceMapURL = options.sourceMapURL;
6136 this._sourceMapBasepath = options.sourceMapBasepath;
6137 this._sourceMapRootpath = options.sourceMapRootpath;
6138 this._outputSourceFiles = options.outputSourceFiles;
6139 this._sourceMapGeneratorConstructor = options.sourceMapGenerator || require("source-map").SourceMapGenerator;
6141 if (this._sourceMapRootpath && this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1) !== '/') {
6142 this._sourceMapRootpath += '/';
6145 this._lineNumber = 0;
6149 tree.sourceMapOutput.prototype.normalizeFilename = function(filename) {
6150 if (this._sourceMapBasepath && filename.indexOf(this._sourceMapBasepath) === 0) {
6151 filename = filename.substring(this._sourceMapBasepath.length);
6152 if (filename.charAt(0) === '\\' || filename.charAt(0) === '/') {
6153 filename = filename.substring(1);
6156 return (this._sourceMapRootpath || "") + filename.replace(/\\/g, '/');
6159 tree.sourceMapOutput.prototype.add = function(chunk, fileInfo, index, mapLines) {
6161 //ignore adding empty strings
6173 var inputSource = this._contentsMap[fileInfo.filename].substring(0, index);
6174 sourceLines = inputSource.split("\n");
6175 sourceColumns = sourceLines[sourceLines.length-1];
6178 lines = chunk.split("\n");
6179 columns = lines[lines.length-1];
6183 this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column},
6184 original: { line: sourceLines.length, column: sourceColumns.length},
6185 source: this.normalizeFilename(fileInfo.filename)});
6187 for(i = 0; i < lines.length; i++) {
6188 this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0},
6189 original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0},
6190 source: this.normalizeFilename(fileInfo.filename)});
6195 if (lines.length === 1) {
6196 this._column += columns.length;
6198 this._lineNumber += lines.length - 1;
6199 this._column = columns.length;
6202 this._css.push(chunk);
6205 tree.sourceMapOutput.prototype.isEmpty = function() {
6206 return this._css.length === 0;
6209 tree.sourceMapOutput.prototype.toCSS = function(env) {
6210 this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null });
6212 if (this._outputSourceFiles) {
6213 for(var filename in this._contentsMap) {
6214 this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), this._contentsMap[filename]);
6218 this._rootNode.genCSS(env, this);
6220 if (this._css.length > 0) {
6222 sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON());
6224 if (this._sourceMapURL) {
6225 sourceMapURL = this._sourceMapURL;
6226 } else if (this._sourceMapFilename) {
6227 sourceMapURL = this.normalizeFilename(this._sourceMapFilename);
6230 if (this._writeSourceMap) {
6231 this._writeSourceMap(sourceMapContent);
6233 sourceMapURL = "data:application/json," + encodeURIComponent(sourceMapContent);
6237 this._css.push("/*# sourceMappingURL=" + sourceMapURL + " */");
6241 return this._css.join('');
6244 })(require('./tree'));
6247 // browser.js - client-side engine
6249 /*global less, window, document, XMLHttpRequest, location */
6251 var isFileProtocol = /^(file|chrome(-extension)?|resource|qrc|app):/.test(location.protocol);
6253 less.env = less.env || (location.hostname == '127.0.0.1' ||
6254 location.hostname == '0.0.0.0' ||
6255 location.hostname == 'localhost' ||
6257 location.port.length > 0) ||
6258 isFileProtocol ? 'development'
6267 // The amount of logging in the javascript console.
6268 // 2 - Information and errors
6272 less.logLevel = typeof(less.logLevel) != 'undefined' ? less.logLevel : logLevel.info;
6274 // Load styles asynchronously (default: false)
6276 // This is set to `false` by default, so that the body
6277 // doesn't start loading before the stylesheets are parsed.
6278 // Setting this to `true` can result in flickering.
6280 less.async = less.async || false;
6281 less.fileAsync = less.fileAsync || false;
6283 // Interval between watch polls
6284 less.poll = less.poll || (isFileProtocol ? 1000 : 1500);
6286 //Setup user functions
6287 if (less.functions) {
6288 for(var func in less.functions) {
6289 less.tree.functions[func] = less.functions[func];
6293 var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(location.hash);
6294 if (dumpLineNumbers) {
6295 less.dumpLineNumbers = dumpLineNumbers[1];
6298 var typePattern = /^text\/(x-)?less$/;
6303 function log(str, level) {
6304 if (less.env == 'development' && typeof(console) !== 'undefined' && less.logLevel >= level) {
6305 console.log('less: ' + str);
6309 function extractId(href) {
6310 return href.replace(/^[a-z-]+:\/+?[^\/]+/, '' ) // Remove protocol & domain
6311 .replace(/^\//, '' ) // Remove root /
6312 .replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension
6313 .replace(/[^\.\w-]+/g, '-') // Replace illegal characters
6314 .replace(/\./g, ':'); // Replace dots with colons(for valid id)
6317 function errorConsole(e, rootHref) {
6318 var template = '{line} {content}';
6319 var filename = e.filename || rootHref;
6321 var content = (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') +
6322 " in " + filename + " ";
6324 var errorline = function (e, i, classname) {
6325 if (e.extract[i] !== undefined) {
6326 errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
6327 .replace(/\{class\}/, classname)
6328 .replace(/\{content\}/, e.extract[i]));
6333 errorline(e, 0, '');
6334 errorline(e, 1, 'line');
6335 errorline(e, 2, '');
6336 content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':\n' +
6338 } else if (e.stack) {
6341 log(content, logLevel.errors);
6344 function createCSS(styles, sheet, lastModified) {
6345 // Strip the query-string
6346 var href = sheet.href || '';
6348 // If there is no title set, use the filename, minus the extension
6349 var id = 'less:' + (sheet.title || extractId(href));
6351 // If this has already been inserted into the DOM, we may need to replace it
6352 var oldCss = document.getElementById(id);
6353 var keepOldCss = false;
6355 // Create a new stylesheet node for insertion or (if necessary) replacement
6356 var css = document.createElement('style');
6357 css.setAttribute('type', 'text/css');
6359 css.setAttribute('media', sheet.media);
6363 if (css.styleSheet) { // IE
6365 css.styleSheet.cssText = styles;
6367 throw new(Error)("Couldn't reassign styleSheet.cssText.");
6370 css.appendChild(document.createTextNode(styles));
6372 // If new contents match contents of oldCss, don't replace oldCss
6373 keepOldCss = (oldCss !== null && oldCss.childNodes.length > 0 && css.childNodes.length > 0 &&
6374 oldCss.firstChild.nodeValue === css.firstChild.nodeValue);
6377 var head = document.getElementsByTagName('head')[0];
6379 // If there is no oldCss, just append; otherwise, only append if we need
6380 // to replace oldCss with an updated stylesheet
6381 if (oldCss === null || keepOldCss === false) {
6382 var nextEl = sheet && sheet.nextSibling || null;
6384 nextEl.parentNode.insertBefore(css, nextEl);
6386 head.appendChild(css);
6389 if (oldCss && keepOldCss === false) {
6390 oldCss.parentNode.removeChild(oldCss);
6393 // Don't update the local store if the file wasn't modified
6394 if (lastModified && cache) {
6395 log('saving ' + href + ' to cache.', logLevel.info);
6397 cache.setItem(href, styles);
6398 cache.setItem(href + ':timestamp', lastModified);
6400 //TODO - could do with adding more robust error handling
6401 log('failed to save', logLevel.errors);
6406 function errorHTML(e, rootHref) {
6407 var id = 'less-error-message:' + extractId(rootHref || "");
6408 var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>';
6409 var elem = document.createElement('div'), timer, content, errors = [];
6410 var filename = e.filename || rootHref;
6411 var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1];
6414 elem.className = "less-error-message";
6416 content = '<h3>' + (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') +
6417 '</h3>' + '<p>in <a href="' + filename + '">' + filenameNoPath + "</a> ";
6419 var errorline = function (e, i, classname) {
6420 if (e.extract[i] !== undefined) {
6421 errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1))
6422 .replace(/\{class\}/, classname)
6423 .replace(/\{content\}/, e.extract[i]));
6428 errorline(e, 0, '');
6429 errorline(e, 1, 'line');
6430 errorline(e, 2, '');
6431 content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':</p>' +
6432 '<ul>' + errors.join('') + '</ul>';
6433 } else if (e.stack) {
6434 content += '<br/>' + e.stack.split('\n').slice(1).join('<br/>');
6436 elem.innerHTML = content;
6438 // CSS for error messages
6440 '.less-error-message ul, .less-error-message li {',
6441 'list-style-type: none;',
6442 'margin-right: 15px;',
6446 '.less-error-message label {',
6448 'margin-right: 15px;',
6452 '.less-error-message pre {',
6456 'display: inline-block;',
6458 '.less-error-message pre.line {',
6461 '.less-error-message h3 {',
6463 'font-weight: bold;',
6464 'padding: 15px 0 5px 0;',
6467 '.less-error-message a {',
6470 '.less-error-message .error {',
6472 'font-weight: bold;',
6473 'padding-bottom: 2px;',
6474 'border-bottom: 1px dashed red;',
6476 ].join('\n'), { title: 'error-message' });
6478 elem.style.cssText = [
6479 "font-family: Arial, sans-serif",
6480 "border: 1px solid #e00",
6481 "background-color: #eee",
6482 "border-radius: 5px",
6483 "-webkit-border-radius: 5px",
6484 "-moz-border-radius: 5px",
6487 "margin-bottom: 15px"
6490 if (less.env == 'development') {
6491 timer = setInterval(function () {
6492 if (document.body) {
6493 if (document.getElementById(id)) {
6494 document.body.replaceChild(elem, document.getElementById(id));
6496 document.body.insertBefore(elem, document.body.firstChild);
6498 clearInterval(timer);
6504 function error(e, rootHref) {
6505 if (!less.errorReporting || less.errorReporting === "html") {
6506 errorHTML(e, rootHref);
6507 } else if (less.errorReporting === "console") {
6508 errorConsole(e, rootHref);
6509 } else if (typeof less.errorReporting === 'function') {
6510 less.errorReporting("add", e, rootHref);
6514 function removeErrorHTML(path) {
6515 var node = document.getElementById('less-error-message:' + extractId(path));
6517 node.parentNode.removeChild(node);
6521 function removeErrorConsole(path) {
6525 function removeError(path) {
6526 if (!less.errorReporting || less.errorReporting === "html") {
6527 removeErrorHTML(path);
6528 } else if (less.errorReporting === "console") {
6529 removeErrorConsole(path);
6530 } else if (typeof less.errorReporting === 'function') {
6531 less.errorReporting("remove", path);
6535 function loadStyles(newVars) {
6536 var styles = document.getElementsByTagName('style'),
6538 for (var i = 0; i < styles.length; i++) {
6540 if (style.type.match(typePattern)) {
6541 var env = new less.tree.parseEnv(less),
6542 lessText = style.innerHTML || '';
6543 env.filename = document.location.href.replace(/#.*$/, '');
6545 if (newVars || varsPre) {
6546 env.useFileCache = true;
6548 lessText = varsPre + lessText;
6551 lessText += "\n" + newVars;
6555 /*jshint loopfunc:true */
6556 // use closure to store current value of i
6557 var callback = (function(style) {
6558 return function (e, cssAST) {
6560 return error(e, "inline");
6562 var css = cssAST.toCSS(less);
6563 style.type = 'text/css';
6564 if (style.styleSheet) {
6565 style.styleSheet.cssText = css;
6567 style.innerHTML = css;
6571 new(less.Parser)(env).parse(lessText, callback);
6576 function extractUrlParts(url, baseUrl) {
6577 // urlParts[1] = protocol&hostname || /
6578 // urlParts[2] = / if path relative to host base
6579 // urlParts[3] = directories
6580 // urlParts[4] = filename
6581 // urlParts[5] = parameters
6583 var urlPartsRegex = /^((?:[a-z-]+:)?\/+?(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i,
6584 urlParts = url.match(urlPartsRegex),
6585 returner = {}, directories = [], i, baseUrlParts;
6588 throw new Error("Could not parse sheet href - '"+url+"'");
6591 // Stylesheets in IE don't always return the full path
6592 if (!urlParts[1] || urlParts[2]) {
6593 baseUrlParts = baseUrl.match(urlPartsRegex);
6594 if (!baseUrlParts) {
6595 throw new Error("Could not parse page url - '"+baseUrl+"'");
6597 urlParts[1] = urlParts[1] || baseUrlParts[1] || "";
6599 urlParts[3] = baseUrlParts[3] + urlParts[3];
6604 directories = urlParts[3].replace(/\\/g, "/").split("/");
6606 // extract out . before .. so .. doesn't absorb a non-directory
6607 for(i = 0; i < directories.length; i++) {
6608 if (directories[i] === ".") {
6609 directories.splice(i, 1);
6614 for(i = 0; i < directories.length; i++) {
6615 if (directories[i] === ".." && i > 0) {
6616 directories.splice(i-1, 2);
6622 returner.hostPart = urlParts[1];
6623 returner.directories = directories;
6624 returner.path = urlParts[1] + directories.join("/");
6625 returner.fileUrl = returner.path + (urlParts[4] || "");
6626 returner.url = returner.fileUrl + (urlParts[5] || "");
6630 function pathDiff(url, baseUrl) {
6631 // diff between two paths to create a relative path
6633 var urlParts = extractUrlParts(url),
6634 baseUrlParts = extractUrlParts(baseUrl),
6635 i, max, urlDirectories, baseUrlDirectories, diff = "";
6636 if (urlParts.hostPart !== baseUrlParts.hostPart) {
6639 max = Math.max(baseUrlParts.directories.length, urlParts.directories.length);
6640 for(i = 0; i < max; i++) {
6641 if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; }
6643 baseUrlDirectories = baseUrlParts.directories.slice(i);
6644 urlDirectories = urlParts.directories.slice(i);
6645 for(i = 0; i < baseUrlDirectories.length-1; i++) {
6648 for(i = 0; i < urlDirectories.length-1; i++) {
6649 diff += urlDirectories[i] + "/";
6654 function getXMLHttpRequest() {
6655 if (window.XMLHttpRequest) {
6656 return new XMLHttpRequest();
6659 /*global ActiveXObject */
6660 return new ActiveXObject("MSXML2.XMLHTTP.3.0");
6662 log("browser doesn't support AJAX.", logLevel.errors);
6668 function doXHR(url, type, callback, errback) {
6669 var xhr = getXMLHttpRequest();
6670 var async = isFileProtocol ? less.fileAsync : less.async;
6672 if (typeof(xhr.overrideMimeType) === 'function') {
6673 xhr.overrideMimeType('text/css');
6675 log("XHR: Getting '" + url + "'", logLevel.info);
6676 xhr.open('GET', url, async);
6677 xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5');
6680 function handleResponse(xhr, callback, errback) {
6681 if (xhr.status >= 200 && xhr.status < 300) {
6682 callback(xhr.responseText,
6683 xhr.getResponseHeader("Last-Modified"));
6684 } else if (typeof(errback) === 'function') {
6685 errback(xhr.status, url);
6689 if (isFileProtocol && !less.fileAsync) {
6690 if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) {
6691 callback(xhr.responseText);
6693 errback(xhr.status, url);
6696 xhr.onreadystatechange = function () {
6697 if (xhr.readyState == 4) {
6698 handleResponse(xhr, callback, errback);
6702 handleResponse(xhr, callback, errback);
6706 function loadFile(originalHref, currentFileInfo, callback, env, newVars) {
6708 if (currentFileInfo && currentFileInfo.currentDirectory && !/^([a-z-]+:)?\//.test(originalHref)) {
6709 originalHref = currentFileInfo.currentDirectory + originalHref;
6712 // sheet may be set to the stylesheet for the initial load or a collection of properties including
6713 // some env variables for imports
6714 var hrefParts = extractUrlParts(originalHref, window.location.href);
6715 var href = hrefParts.url;
6717 currentDirectory: hrefParts.path,
6721 if (currentFileInfo) {
6722 newFileInfo.entryPath = currentFileInfo.entryPath;
6723 newFileInfo.rootpath = currentFileInfo.rootpath;
6724 newFileInfo.rootFilename = currentFileInfo.rootFilename;
6725 newFileInfo.relativeUrls = currentFileInfo.relativeUrls;
6727 newFileInfo.entryPath = hrefParts.path;
6728 newFileInfo.rootpath = less.rootpath || hrefParts.path;
6729 newFileInfo.rootFilename = href;
6730 newFileInfo.relativeUrls = env.relativeUrls;
6733 if (newFileInfo.relativeUrls) {
6735 newFileInfo.rootpath = extractUrlParts(env.rootpath + pathDiff(hrefParts.path, newFileInfo.entryPath)).path;
6737 newFileInfo.rootpath = hrefParts.path;
6741 if (env.useFileCache && fileCache[href]) {
6743 var lessText = fileCache[href];
6745 lessText += "\n" + newVars;
6747 callback(null, lessText, href, newFileInfo, { lastModified: new Date() });
6749 callback(e, null, href);
6754 doXHR(href, env.mime, function (data, lastModified) {
6755 data = varsPre + data;
6758 fileCache[href] = data;
6760 // Use remote copy (re-parse)
6762 callback(null, data, href, newFileInfo, { lastModified: lastModified });
6764 callback(e, null, href);
6766 }, function (status, url) {
6767 callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")" }, null, href);
6771 function loadStyleSheet(sheet, callback, reload, remaining, newVars) {
6773 var env = new less.tree.parseEnv(less);
6774 env.mime = sheet.type;
6776 if (newVars || varsPre) {
6777 env.useFileCache = true;
6780 loadFile(sheet.href, null, function(e, data, path, newFileInfo, webInfo) {
6783 webInfo.remaining = remaining;
6785 var css = cache && cache.getItem(path),
6786 timestamp = cache && cache.getItem(path + ':timestamp');
6788 if (!reload && timestamp && webInfo.lastModified &&
6789 (new(Date)(webInfo.lastModified).valueOf() ===
6790 new(Date)(timestamp).valueOf())) {
6792 createCSS(css, sheet);
6793 webInfo.local = true;
6794 callback(null, null, data, sheet, webInfo, path);
6799 //TODO add tests around how this behaves when reloading
6803 env.currentFileInfo = newFileInfo;
6804 new(less.Parser)(env).parse(data, function (e, root) {
6805 if (e) { return callback(e, null, null, sheet); }
6807 callback(e, root, data, sheet, webInfo, path);
6809 callback(e, null, null, sheet);
6813 callback(e, null, null, sheet, webInfo, path);
6818 function loadStyleSheets(callback, reload, newVars) {
6819 for (var i = 0; i < less.sheets.length; i++) {
6820 loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), newVars);
6824 function initRunningMode(){
6825 if (less.env === 'development') {
6826 less.optimization = 0;
6827 less.watchTimer = setInterval(function () {
6828 if (less.watchMode) {
6829 loadStyleSheets(function (e, root, _, sheet, env) {
6831 error(e, sheet.href);
6833 createCSS(root.toCSS(less), sheet, env.lastModified);
6839 less.optimization = 3;
6843 function serializeVars(vars) {
6846 for (var name in vars) {
6847 s += ((name.slice(0,1) === '@')? '' : '@') + name +': '+
6848 ((vars[name].slice(-1) === ';')? vars[name] : vars[name] +';');
6858 less.watch = function () {
6859 if (!less.watchMode ){
6860 less.env = 'development';
6863 return this.watchMode = true;
6866 less.unwatch = function () {clearInterval(less.watchTimer); return this.watchMode = false; };
6868 if (/!watch/.test(location.hash)) {
6872 if (less.env != 'development') {
6874 cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage;
6879 // Get all <link> tags with the 'rel' attribute set to "stylesheet/less"
6881 var links = document.getElementsByTagName('link');
6885 for (var i = 0; i < links.length; i++) {
6886 if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) &&
6887 (links[i].type.match(typePattern)))) {
6888 less.sheets.push(links[i]);
6893 // With this function, it's possible to alter variables and re-render
6894 // CSS without reloading less-files
6896 less.modifyVars = function(record) {
6897 less.refresh(false, serializeVars(record));
6900 less.refresh = function (reload, newVars) {
6901 var startTime, endTime;
6902 startTime = endTime = new Date();
6904 loadStyleSheets(function (e, root, _, sheet, env) {
6906 return error(e, sheet.href);
6909 log("loading " + sheet.href + " from cache.", logLevel.info);
6911 log("parsed " + sheet.href + " successfully.", logLevel.info);
6912 createCSS(root.toCSS(less), sheet, env.lastModified);
6914 log("css for " + sheet.href + " generated in " + (new Date() - endTime) + 'ms', logLevel.info);
6915 if (env.remaining === 0) {
6916 log("css generated in " + (new Date() - startTime) + 'ms', logLevel.info);
6918 endTime = new Date();
6919 }, reload, newVars);
6921 loadStyles(newVars);
6924 if (less.globalVars) {
6925 varsPre = serializeVars(less.globalVars) + "\n";
6928 less.refreshStyles = loadStyles;
6930 less.Parser.fileLoader = loadFile;
6932 less.refresh(less.env === 'development');
6936 // Define Less as an AMD module.
6937 if (typeof define === "function" && define.amd) {
6938 define(function () { return less; } );