2 // @codingStandardsIgnoreFile File external to MediaWiki. Ignore coding conventions checks.
4 * lessphp v0.4.0@2cc77e3c7b
5 * http://leafo.net/lessphp
7 * LESS CSS compiler, adapted from http://lesscss.org
9 * For ease of distribution, lessphp 0.4.0 is under a dual license.
10 * You are free to pick which one suits your needs.
14 * Copyright 2013, Leaf Corcoran <leafot@gmail.com>
16 * Permission is hereby granted, free of charge, to any person obtaining
17 * a copy of this software and associated documentation files (the
18 * "Software"), to deal in the Software without restriction, including
19 * without limitation the rights to use, copy, modify, merge, publish,
20 * distribute, sublicense, and/or sell copies of the Software, and to
21 * permit persons to whom the Software is furnished to do so, subject to
22 * the following conditions:
24 * The above copyright notice and this permission notice shall be
25 * included in all copies or substantial portions of the Software.
27 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
37 * Please refer to http://www.gnu.org/licenses/gpl-3.0.html for the full
38 * text of the GPL version 3
43 * The LESS compiler and parser.
45 * Converting LESS to CSS is a three stage process. The incoming file is parsed
46 * by `lessc_parser` into a syntax tree, then it is compiled into another tree
47 * representing the CSS structure by `lessc`. The CSS tree is fed into a
48 * formatter, like `lessc_formatter` which then outputs CSS as a string.
50 * During the first compile, all values are *reduced*, which means that their
51 * types are brought to the lowest form before being dump as strings. This
52 * handles math equations, variable dereferences, and the like.
54 * The `parse` function of `lessc` is the entry point.
58 * The `lessc` class creates an instance of the parser, feeds it LESS code,
59 * then transforms the resulting tree to a CSS tree. This class also holds the
60 * evaluation context, such as all available mixins and variables at any given
63 * The `lessc_parser` class is only concerned with parsing its input.
65 * The `lessc_formatter` takes a CSS tree, and dumps it to a formatted string,
66 * handling things like indentation.
69 static public $VERSION = "v0.4.0";
71 static public $TRUE = array("keyword", "true");
72 static public $FALSE = array("keyword", "false");
74 protected $libFunctions = array();
75 protected $registeredVars = array();
76 protected $preserveComments = false;
78 public $vPrefix = '@'; // prefix of abstract properties
79 public $mPrefix = '$'; // prefix of abstract blocks
80 public $parentSelector = '&';
82 public $importDisabled = false;
83 public $importDir = '';
85 protected $numberPrecision = null;
87 protected $allParsedFiles = array();
89 // set to the parser that generated the current line when compiling
90 // so we know how to create error messages
91 protected $sourceParser = null;
92 protected $sourceLoc = null;
94 static protected $nextImportId = 0; // uniquely identify imports
96 // attempts to find the path of an import url, returns null for css files
97 protected function findImport($url) {
98 foreach ((array)$this->importDir
as $dir) {
99 $full = $dir.(substr($dir, -1) != '/' ?
'/' : '').$url;
100 if ($this->fileExists($file = $full.'.less') ||
$this->fileExists($file = $full)) {
108 protected function fileExists($name) {
109 return is_file($name);
112 static public function compressList($items, $delim) {
113 if (!isset($items[1]) && isset($items[0])) return $items[0];
114 else return array('list', $delim, $items);
117 static public function preg_quote($what) {
118 return preg_quote($what, '/');
121 protected function tryImport($importPath, $parentBlock, $out) {
122 if ($importPath[0] == "function" && $importPath[1] == "url") {
123 $importPath = $this->flattenList($importPath[2]);
126 $str = $this->coerceString($importPath);
127 if ($str === null) return false;
129 $url = $this->compileValue($this->lib_e($str));
131 // don't import if it ends in css
132 if (substr_compare($url, '.css', -4, 4) === 0) return false;
134 $realPath = $this->findImport($url);
136 if ($realPath === null) return false;
138 if ($this->importDisabled
) {
139 return array(false, "/* import disabled */");
142 if (isset($this->allParsedFiles
[realpath($realPath)])) {
143 return array(false, null);
146 $this->addParsedFile($realPath);
147 $parser = $this->makeParser($realPath);
148 $root = $parser->parse(file_get_contents($realPath));
150 // set the parents of all the block props
151 foreach ($root->props
as $prop) {
152 if ($prop[0] == "block") {
153 $prop[1]->parent
= $parentBlock;
157 // copy mixins into scope, set their parents
158 // bring blocks from import into current block
159 // TODO: need to mark the source parser these came from this file
160 foreach ($root->children
as $childName => $child) {
161 if (isset($parentBlock->children
[$childName])) {
162 $parentBlock->children
[$childName] = array_merge(
163 $parentBlock->children
[$childName],
166 $parentBlock->children
[$childName] = $child;
170 $pi = pathinfo($realPath);
171 $dir = $pi["dirname"];
173 list($top, $bottom) = $this->sortProps($root->props
, true);
174 $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
176 return array(true, $bottom, $parser, $dir);
179 protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir) {
180 $oldSourceParser = $this->sourceParser
;
182 $oldImport = $this->importDir
;
184 // TODO: this is because the importDir api is stupid
185 $this->importDir
= (array)$this->importDir
;
186 array_unshift($this->importDir
, $importDir);
188 foreach ($props as $prop) {
189 $this->compileProp($prop, $block, $out);
192 $this->importDir
= $oldImport;
193 $this->sourceParser
= $oldSourceParser;
197 * Recursively compiles a block.
199 * A block is analogous to a CSS block in most cases. A single LESS document
200 * is encapsulated in a block when parsed, but it does not have parent tags
201 * so all of it's children appear on the root level when compiled.
203 * Blocks are made up of props and children.
205 * Props are property instructions, array tuples which describe an action
206 * to be taken, eg. write a property, set a variable, mixin a block.
208 * The children of a block are just all the blocks that are defined within.
209 * This is used to look up mixins when performing a mixin.
211 * Compiling the block involves pushing a fresh environment on the stack,
212 * and iterating through the props, compiling each one.
214 * See lessc::compileProp()
217 protected function compileBlock($block) {
218 switch ($block->type
) {
220 $this->compileRoot($block);
223 $this->compileCSSBlock($block);
226 $this->compileMedia($block);
229 $name = "@" . $block->name
;
230 if (!empty($block->value
)) {
231 $name .= " " . $this->compileValue($this->reduce($block->value
));
234 $this->compileNestedBlock($block, array($name));
237 $this->throwError("unknown block type: $block->type\n");
241 protected function compileCSSBlock($block) {
242 $env = $this->pushEnv();
244 $selectors = $this->compileSelectors($block->tags
);
245 $env->selectors
= $this->multiplySelectors($selectors);
246 $out = $this->makeOutputBlock(null, $env->selectors
);
248 $this->scope
->children
[] = $out;
249 $this->compileProps($block, $out);
251 $block->scope
= $env; // mixins carry scope with them!
255 protected function compileMedia($media) {
256 $env = $this->pushEnv($media);
257 $parentScope = $this->mediaParent($this->scope
);
259 $query = $this->compileMediaQuery($this->multiplyMedia($env));
261 $this->scope
= $this->makeOutputBlock($media->type
, array($query));
262 $parentScope->children
[] = $this->scope
;
264 $this->compileProps($media, $this->scope
);
266 if (count($this->scope
->lines
) > 0) {
267 $orphanSelelectors = $this->findClosestSelectors();
268 if (!is_null($orphanSelelectors)) {
269 $orphan = $this->makeOutputBlock(null, $orphanSelelectors);
270 $orphan->lines
= $this->scope
->lines
;
271 array_unshift($this->scope
->children
, $orphan);
272 $this->scope
->lines
= array();
276 $this->scope
= $this->scope
->parent
;
280 protected function mediaParent($scope) {
281 while (!empty($scope->parent
)) {
282 if (!empty($scope->type
) && $scope->type
!= "media") {
285 $scope = $scope->parent
;
291 protected function compileNestedBlock($block, $selectors) {
292 $this->pushEnv($block);
293 $this->scope
= $this->makeOutputBlock($block->type
, $selectors);
294 $this->scope
->parent
->children
[] = $this->scope
;
296 $this->compileProps($block, $this->scope
);
298 $this->scope
= $this->scope
->parent
;
302 protected function compileRoot($root) {
304 $this->scope
= $this->makeOutputBlock($root->type
);
305 $this->compileProps($root, $this->scope
);
309 protected function compileProps($block, $out) {
310 foreach ($this->sortProps($block->props
) as $prop) {
311 $this->compileProp($prop, $block, $out);
313 $out->lines
= $this->deduplicate($out->lines
);
317 * Deduplicate lines in a block. Comments are not deduplicated. If a
318 * duplicate rule is detected, the comments immediately preceding each
319 * occurence are consolidated.
321 protected function deduplicate($lines) {
325 foreach($lines as $line) {
326 if (strpos($line, '/*') === 0) {
330 if (!in_array($line, $unique)) {
333 array_splice($unique, array_search($line, $unique), 0, $comments);
336 return array_merge($unique, $comments);
339 protected function sortProps($props, $split = false) {
345 foreach ($props as $prop) {
352 if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix
) {
353 $vars = array_merge($vars, $stack);
355 $other = array_merge($other, $stack);
360 $id = self
::$nextImportId++
;
363 $imports = array_merge($imports, $stack);
364 $other[] = array("import_mixin", $id);
369 $other = array_merge($other, $stack);
374 $other = array_merge($other, $stack);
377 return array(array_merge($vars, $imports), $other);
379 return array_merge($vars, $imports, $other);
383 protected function compileMediaQuery($queries) {
384 $compiledQueries = array();
385 foreach ($queries as $query) {
387 foreach ($query as $q) {
390 $parts[] = implode(" ", array_slice($q, 1));
394 $parts[] = "($q[1]: " .
395 $this->compileValue($this->reduce($q[2])) . ")";
397 $parts[] = "($q[1])";
401 $parts[] = $this->compileValue($this->reduce($q));
406 if (count($parts) > 0) {
407 $compiledQueries[] = implode(" and ", $parts);
412 if (!empty($parts)) {
414 implode($this->formatter
->selectorSeparator
, $compiledQueries);
419 protected function multiplyMedia($env, $childQueries = null) {
421 !empty($env->block
->type
) && $env->block
->type
!= "media")
423 return $childQueries;
426 // plain old block, skip
427 if (empty($env->block
->type
)) {
428 return $this->multiplyMedia($env->parent
, $childQueries);
432 $queries = $env->block
->queries
;
433 if (is_null($childQueries)) {
436 foreach ($queries as $parent) {
437 foreach ($childQueries as $child) {
438 $out[] = array_merge($parent, $child);
443 return $this->multiplyMedia($env->parent
, $out);
446 protected function expandParentSelectors(&$tag, $replace) {
447 $parts = explode("$&$", $tag);
449 foreach ($parts as &$part) {
450 $part = str_replace($this->parentSelector
, $replace, $part, $c);
453 $tag = implode($this->parentSelector
, $parts);
457 protected function findClosestSelectors() {
460 while ($env !== null) {
461 if (isset($env->selectors
)) {
462 $selectors = $env->selectors
;
472 // multiply $selectors against the nearest selectors in env
473 protected function multiplySelectors($selectors) {
474 // find parent selectors
476 $parentSelectors = $this->findClosestSelectors();
477 if (is_null($parentSelectors)) {
478 // kill parent reference in top level selector
479 foreach ($selectors as &$s) {
480 $this->expandParentSelectors($s, "");
487 foreach ($parentSelectors as $parent) {
488 foreach ($selectors as $child) {
489 $count = $this->expandParentSelectors($child, $parent);
491 // don't prepend the parent tag if & was used
493 $out[] = trim($child);
495 $out[] = trim($parent . ' ' . $child);
503 // reduces selector expressions
504 protected function compileSelectors($selectors) {
507 foreach ($selectors as $s) {
510 $out[] = trim($this->compileValue($this->reduce($value)));
519 protected function eq($left, $right) {
520 return $left == $right;
523 protected function patternMatch($block, $orderedArgs, $keywordArgs) {
524 // match the guards if it has them
525 // any one of the groups must have all its guards pass for a match
526 if (!empty($block->guards
)) {
527 $groupPassed = false;
528 foreach ($block->guards
as $guardGroup) {
529 foreach ($guardGroup as $guard) {
531 $this->zipSetArgs($block->args
, $orderedArgs, $keywordArgs);
534 if ($guard[0] == "negate") {
539 $passed = $this->reduce($guard) == self
::$TRUE;
540 if ($negate) $passed = !$passed;
547 $groupPassed = false;
552 if ($groupPassed) break;
560 if (empty($block->args
)) {
561 return $block->isVararg ||
empty($orderedArgs) && empty($keywordArgs);
564 $remainingArgs = $block->args
;
566 $remainingArgs = array();
567 foreach ($block->args
as $arg) {
568 if ($arg[0] == "arg" && isset($keywordArgs[$arg[1]])) {
572 $remainingArgs[] = $arg;
577 // try to match by arity or by argument literal
578 foreach ($remainingArgs as $i => $arg) {
581 if (empty($orderedArgs[$i]) ||
!$this->eq($arg[1], $orderedArgs[$i])) {
586 // no arg and no default value
587 if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
592 $i--; // rest can be empty
597 if ($block->isVararg
) {
598 return true; // not having enough is handled above
600 $numMatched = $i +
1;
601 // greater than becuase default values always match
602 return $numMatched >= count($orderedArgs);
606 protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip=array()) {
608 foreach ($blocks as $block) {
609 // skip seen blocks that don't have arguments
610 if (isset($skip[$block->id
]) && !isset($block->args
)) {
614 if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
622 // attempt to find blocks matched by path and args
623 protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen=array()) {
624 if ($searchIn == null) return null;
625 if (isset($seen[$searchIn->id
])) return null;
626 $seen[$searchIn->id
] = true;
630 if (isset($searchIn->children
[$name])) {
631 $blocks = $searchIn->children
[$name];
632 if (count($path) == 1) {
633 $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
634 if (!empty($matches)) {
635 // This will return all blocks that match in the closest
636 // scope that has any matching block, like lessjs
641 foreach ($blocks as $subBlock) {
642 $subMatches = $this->findBlocks($subBlock,
643 array_slice($path, 1), $orderedArgs, $keywordArgs, $seen);
645 if (!is_null($subMatches)) {
646 foreach ($subMatches as $sm) {
652 return count($matches) > 0 ?
$matches : null;
655 if ($searchIn->parent
=== $searchIn) return null;
656 return $this->findBlocks($searchIn->parent
, $path, $orderedArgs, $keywordArgs, $seen);
659 // sets all argument names in $args to either the default value
660 // or the one passed in through $values
661 protected function zipSetArgs($args, $orderedValues, $keywordValues) {
662 $assignedValues = array();
665 foreach ($args as $a) {
666 if ($a[0] == "arg") {
667 if (isset($keywordValues[$a[1]])) {
669 $value = $keywordValues[$a[1]];
670 } elseif (isset($orderedValues[$i])) {
672 $value = $orderedValues[$i];
674 } elseif (isset($a[2])) {
678 $this->throwError("Failed to assign arg " . $a[1]);
682 $value = $this->reduce($value);
683 $this->set($a[1], $value);
684 $assignedValues[] = $value;
693 if ($last[0] == "rest") {
694 $rest = array_slice($orderedValues, count($args) - 1);
695 $this->set($last[1], $this->reduce(array("list", " ", $rest)));
698 // wow is this the only true use of PHP's + operator for arrays?
699 $this->env
->arguments
= $assignedValues +
$orderedValues;
702 // compile a prop and update $lines or $blocks appropriately
703 protected function compileProp($prop, $block, $out) {
704 // set error position context
705 $this->sourceLoc
= isset($prop[-1]) ?
$prop[-1] : -1;
709 list(, $name, $value) = $prop;
710 if ($name[0] == $this->vPrefix
) {
711 $this->set($name, $value);
713 $out->lines
[] = $this->formatter
->property($name,
714 $this->compileValue($this->reduce($value)));
718 list(, $child) = $prop;
719 $this->compileBlock($child);
722 list(, $path, $args, $suffix) = $prop;
724 $orderedArgs = array();
725 $keywordArgs = array();
726 foreach ((array)$args as $arg) {
730 if (!isset($arg[2])) {
731 $orderedArgs[] = $this->reduce(array("variable", $arg[1]));
733 $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
738 $orderedArgs[] = $this->reduce($arg[1]);
741 $this->throwError("Unknown arg type: " . $arg[0]);
745 $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
747 if ($mixins === null) {
748 $this->throwError("{$prop[1][0]} is undefined");
751 foreach ($mixins as $mixin) {
752 if ($mixin === $block && !$orderedArgs) {
757 if (isset($mixin->parent
->scope
)) {
759 $mixinParentEnv = $this->pushEnv();
760 $mixinParentEnv->storeParent
= $mixin->parent
->scope
;
764 if (isset($mixin->args
)) {
767 $this->zipSetArgs($mixin->args
, $orderedArgs, $keywordArgs);
770 $oldParent = $mixin->parent
;
771 if ($mixin != $block) $mixin->parent
= $block;
773 foreach ($this->sortProps($mixin->props
) as $subProp) {
774 if ($suffix !== null &&
775 $subProp[0] == "assign" &&
776 is_string($subProp[1]) &&
777 $subProp[1]{0} != $this->vPrefix
)
781 array($subProp[2], array('keyword', $suffix))
785 $this->compileProp($subProp, $mixin, $out);
788 $mixin->parent
= $oldParent;
790 if ($haveArgs) $this->popEnv();
791 if ($haveScope) $this->popEnv();
796 $out->lines
[] = $prop[1];
799 list(, $name, $value) = $prop;
800 $out->lines
[] = "@$name " . $this->compileValue($this->reduce($value)).';';
803 $out->lines
[] = $prop[1];
806 list(, $importPath, $importId) = $prop;
807 $importPath = $this->reduce($importPath);
809 if (!isset($this->env
->imports
)) {
810 $this->env
->imports
= array();
813 $result = $this->tryImport($importPath, $block, $out);
815 $this->env
->imports
[$importId] = $result === false ?
816 array(false, "@import " . $this->compileValue($importPath).";") :
821 list(,$importId) = $prop;
822 $import = $this->env
->imports
[$importId];
823 if ($import[0] === false) {
824 if (isset($import[1])) {
825 $out->lines
[] = $import[1];
828 list(, $bottom, $parser, $importDir) = $import;
829 $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
834 $this->throwError("unknown op: {$prop[0]}\n");
840 * Compiles a primitive value into a CSS property value.
842 * Values in lessphp are typed by being wrapped in arrays, their format is
845 * array(type, contents [, additional_contents]*)
847 * The input is expected to be reduced. This function will not work on
848 * things like expressions and variables.
850 public function compileValue($value) {
854 // [2] - array of values
855 return implode($value[1], array_map(array($this, 'compileValue'), $value[2]));
857 if (!empty($this->formatter
->compressColors
)) {
858 return $this->compileValue($this->coerceColor($value));
865 list(, $num, $unit) = $value;
868 if ($this->numberPrecision
!== null) {
869 $num = round($num, $this->numberPrecision
);
873 // [1] - contents of string (includes quotes)
874 list(, $delim, $content) = $value;
875 foreach ($content as &$part) {
876 if (is_array($part)) {
877 $part = $this->compileValue($part);
880 return $delim . implode($content) . $delim;
882 // [1] - red component (either number or a %)
883 // [2] - green component
884 // [3] - blue component
885 // [4] - optional alpha component
886 list(, $r, $g, $b) = $value;
891 if (count($value) == 5 && $value[4] != 1) { // rgba
892 return 'rgba('.$r.','.$g.','.$b.','.$value[4].')';
895 $h = sprintf("#%02x%02x%02x", $r, $g, $b);
897 if (!empty($this->formatter
->compressColors
)) {
898 // Converting hex color to short notation (e.g. #003399 to #039)
899 if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
900 $h = '#' . $h[1] . $h[3] . $h[5];
907 list(, $name, $args) = $value;
908 return $name.'('.$this->compileValue($args).')';
909 default: // assumed to be unit
910 $this->throwError("unknown value type: $value[0]");
914 protected function lib_pow($args) {
915 list($base, $exp) = $this->assertArgs($args, 2, "pow");
916 return pow($this->assertNumber($base), $this->assertNumber($exp));
919 protected function lib_pi() {
923 protected function lib_mod($args) {
924 list($a, $b) = $this->assertArgs($args, 2, "mod");
925 return $this->assertNumber($a) %
$this->assertNumber($b);
928 protected function lib_tan($num) {
929 return tan($this->assertNumber($num));
932 protected function lib_sin($num) {
933 return sin($this->assertNumber($num));
936 protected function lib_cos($num) {
937 return cos($this->assertNumber($num));
940 protected function lib_atan($num) {
941 $num = atan($this->assertNumber($num));
942 return array("number", $num, "rad");
945 protected function lib_asin($num) {
946 $num = asin($this->assertNumber($num));
947 return array("number", $num, "rad");
950 protected function lib_acos($num) {
951 $num = acos($this->assertNumber($num));
952 return array("number", $num, "rad");
955 protected function lib_sqrt($num) {
956 return sqrt($this->assertNumber($num));
959 protected function lib_extract($value) {
960 list($list, $idx) = $this->assertArgs($value, 2, "extract");
961 $idx = $this->assertNumber($idx);
963 if ($list[0] == "list" && isset($list[2][$idx - 1])) {
964 return $list[2][$idx - 1];
968 protected function lib_isnumber($value) {
969 return $this->toBool($value[0] == "number");
972 protected function lib_isstring($value) {
973 return $this->toBool($value[0] == "string");
976 protected function lib_iscolor($value) {
977 return $this->toBool($this->coerceColor($value));
980 protected function lib_iskeyword($value) {
981 return $this->toBool($value[0] == "keyword");
984 protected function lib_ispixel($value) {
985 return $this->toBool($value[0] == "number" && $value[2] == "px");
988 protected function lib_ispercentage($value) {
989 return $this->toBool($value[0] == "number" && $value[2] == "%");
992 protected function lib_isem($value) {
993 return $this->toBool($value[0] == "number" && $value[2] == "em");
996 protected function lib_isrem($value) {
997 return $this->toBool($value[0] == "number" && $value[2] == "rem");
1000 protected function lib_rgbahex($color) {
1001 $color = $this->coerceColor($color);
1002 if (is_null($color))
1003 $this->throwError("color expected for rgbahex");
1005 return sprintf("#%02x%02x%02x%02x",
1006 isset($color[4]) ?
$color[4]*255 : 255,
1007 $color[1],$color[2], $color[3]);
1010 protected function lib_argb($color){
1011 return $this->lib_rgbahex($color);
1015 * Given an url, decide whether to output a regular link or the base64-encoded contents of the file
1017 * @param array $value either an argument list (two strings) or a single string
1018 * @return string formatted url(), either as a link or base64-encoded
1020 protected function lib_data_uri($value) {
1021 $mime = ($value[0] === 'list') ?
$value[2][0][2] : null;
1022 $url = ($value[0] === 'list') ?
$value[2][1][2][0] : $value[2][0];
1024 $fullpath = $this->findImport($url);
1026 if($fullpath && ($fsize = filesize($fullpath)) !== false) {
1027 // IE8 can't handle data uris larger than 32KB
1028 if($fsize/1024 < 32) {
1029 if(is_null($mime)) {
1030 if(class_exists('finfo')) { // php 5.3+
1031 $finfo = new finfo(FILEINFO_MIME
);
1032 $mime = explode('; ', $finfo->file($fullpath));
1034 } elseif(function_exists('mime_content_type')) { // PHP 5.2
1035 $mime = mime_content_type($fullpath);
1039 if(!is_null($mime)) // fallback if the MIME type is still unknown
1040 $url = sprintf('data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath)));
1044 return 'url("'.$url.'")';
1047 // utility func to unquote a string
1048 protected function lib_e($arg) {
1052 if (isset($items[0])) {
1053 return $this->lib_e($items[0]);
1055 $this->throwError("unrecognised input");
1062 return array("keyword", $this->compileValue($arg));
1066 protected function lib__sprintf($args) {
1067 if ($args[0] != "list") return $args;
1069 $string = array_shift($values);
1070 $template = $this->compileValue($this->lib_e($string));
1073 if (preg_match_all('/%[dsa]/', $template, $m)) {
1074 foreach ($m[0] as $match) {
1075 $val = isset($values[$i]) ?
1076 $this->reduce($values[$i]) : array('keyword', '');
1078 // lessjs compat, renders fully expanded color, not raw color
1079 if ($color = $this->coerceColor($val)) {
1084 $rep = $this->compileValue($this->lib_e($val));
1085 $template = preg_replace('/'.self
::preg_quote($match).'/',
1086 $rep, $template, 1);
1090 $d = $string[0] == "string" ?
$string[1] : '"';
1091 return array("string", $d, array($template));
1094 protected function lib_floor($arg) {
1095 $value = $this->assertNumber($arg);
1096 return array("number", floor($value), $arg[2]);
1099 protected function lib_ceil($arg) {
1100 $value = $this->assertNumber($arg);
1101 return array("number", ceil($value), $arg[2]);
1104 protected function lib_round($arg) {
1105 if($arg[0] != "list") {
1106 $value = $this->assertNumber($arg);
1107 return array("number", round($value), $arg[2]);
1109 $value = $this->assertNumber($arg[2][0]);
1110 $precision = $this->assertNumber($arg[2][1]);
1111 return array("number", round($value, $precision), $arg[2][0][2]);
1115 protected function lib_unit($arg) {
1116 if ($arg[0] == "list") {
1117 list($number, $newUnit) = $arg[2];
1118 return array("number", $this->assertNumber($number),
1119 $this->compileValue($this->lib_e($newUnit)));
1121 return array("number", $this->assertNumber($arg), "");
1126 * Helper function to get arguments for color manipulation functions.
1127 * takes a list that contains a color like thing and a percentage
1129 public function colorArgs($args) {
1130 if ($args[0] != 'list' ||
count($args[2]) < 2) {
1131 return array(array('color', 0, 0, 0), 0);
1133 list($color, $delta) = $args[2];
1134 $color = $this->assertColor($color);
1135 $delta = floatval($delta[1]);
1137 return array($color, $delta);
1140 protected function lib_darken($args) {
1141 list($color, $delta) = $this->colorArgs($args);
1143 $hsl = $this->toHSL($color);
1144 $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
1145 return $this->toRGB($hsl);
1148 protected function lib_lighten($args) {
1149 list($color, $delta) = $this->colorArgs($args);
1151 $hsl = $this->toHSL($color);
1152 $hsl[3] = $this->clamp($hsl[3] +
$delta, 100);
1153 return $this->toRGB($hsl);
1156 protected function lib_saturate($args) {
1157 list($color, $delta) = $this->colorArgs($args);
1159 $hsl = $this->toHSL($color);
1160 $hsl[2] = $this->clamp($hsl[2] +
$delta, 100);
1161 return $this->toRGB($hsl);
1164 protected function lib_desaturate($args) {
1165 list($color, $delta) = $this->colorArgs($args);
1167 $hsl = $this->toHSL($color);
1168 $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
1169 return $this->toRGB($hsl);
1172 protected function lib_spin($args) {
1173 list($color, $delta) = $this->colorArgs($args);
1175 $hsl = $this->toHSL($color);
1177 $hsl[1] = $hsl[1] +
$delta %
360;
1178 if ($hsl[1] < 0) $hsl[1] +
= 360;
1180 return $this->toRGB($hsl);
1183 protected function lib_fadeout($args) {
1184 list($color, $delta) = $this->colorArgs($args);
1185 $color[4] = $this->clamp((isset($color[4]) ?
$color[4] : 1) - $delta/100);
1189 protected function lib_fadein($args) {
1190 list($color, $delta) = $this->colorArgs($args);
1191 $color[4] = $this->clamp((isset($color[4]) ?
$color[4] : 1) +
$delta/100);
1195 protected function lib_hue($color) {
1196 $hsl = $this->toHSL($this->assertColor($color));
1197 return round($hsl[1]);
1200 protected function lib_saturation($color) {
1201 $hsl = $this->toHSL($this->assertColor($color));
1202 return round($hsl[2]);
1205 protected function lib_lightness($color) {
1206 $hsl = $this->toHSL($this->assertColor($color));
1207 return round($hsl[3]);
1210 // get the alpha of a color
1211 // defaults to 1 for non-colors or colors without an alpha
1212 protected function lib_alpha($value) {
1213 if (!is_null($color = $this->coerceColor($value))) {
1214 return isset($color[4]) ?
$color[4] : 1;
1218 // set the alpha of the color
1219 protected function lib_fade($args) {
1220 list($color, $alpha) = $this->colorArgs($args);
1221 $color[4] = $this->clamp($alpha / 100.0);
1225 protected function lib_percentage($arg) {
1226 $num = $this->assertNumber($arg);
1227 return array("number", $num*100, "%");
1230 // mixes two colors by weight
1231 // mix(@color1, @color2, [@weight: 50%]);
1232 // http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html#mix-instance_method
1233 protected function lib_mix($args) {
1234 if ($args[0] != "list" ||
count($args[2]) < 2)
1235 $this->throwError("mix expects (color1, color2, weight)");
1237 list($first, $second) = $args[2];
1238 $first = $this->assertColor($first);
1239 $second = $this->assertColor($second);
1241 $first_a = $this->lib_alpha($first);
1242 $second_a = $this->lib_alpha($second);
1244 if (isset($args[2][2])) {
1245 $weight = $args[2][2][1] / 100.0;
1250 $w = $weight * 2 - 1;
1251 $a = $first_a - $second_a;
1253 $w1 = (($w * $a == -1 ?
$w : ($w +
$a)/(1 +
$w * $a)) +
1) / 2.0;
1256 $new = array('color',
1257 $w1 * $first[1] +
$w2 * $second[1],
1258 $w1 * $first[2] +
$w2 * $second[2],
1259 $w1 * $first[3] +
$w2 * $second[3],
1262 if ($first_a != 1.0 ||
$second_a != 1.0) {
1263 $new[] = $first_a * $weight +
$second_a * ($weight - 1);
1266 return $this->fixColor($new);
1269 protected function lib_contrast($args) {
1270 $darkColor = array('color', 0, 0, 0);
1271 $lightColor = array('color', 255, 255, 255);
1274 if ( $args[0] == 'list' ) {
1275 $inputColor = ( isset($args[2][0]) ) ?
$this->assertColor($args[2][0]) : $lightColor;
1276 $darkColor = ( isset($args[2][1]) ) ?
$this->assertColor($args[2][1]) : $darkColor;
1277 $lightColor = ( isset($args[2][2]) ) ?
$this->assertColor($args[2][2]) : $lightColor;
1278 $threshold = ( isset($args[2][3]) ) ?
$this->assertNumber($args[2][3]) : $threshold;
1281 $inputColor = $this->assertColor($args);
1284 $inputColor = $this->coerceColor($inputColor);
1285 $darkColor = $this->coerceColor($darkColor);
1286 $lightColor = $this->coerceColor($lightColor);
1288 //Figure out which is actually light and dark!
1289 if ( $this->lib_luma($darkColor) > $this->lib_luma($lightColor) ) {
1291 $lightColor = $darkColor;
1295 $inputColor_alpha = $this->lib_alpha($inputColor);
1296 if ( ( $this->lib_luma($inputColor) * $inputColor_alpha) < $threshold) {
1302 protected function lib_luma($color) {
1303 $color = $this->coerceColor($color);
1304 return (0.2126 * $color[0] / 255) +
(0.7152 * $color[1] / 255) +
(0.0722 * $color[2] / 255);
1308 public function assertColor($value, $error = "expected color value") {
1309 $color = $this->coerceColor($value);
1310 if (is_null($color)) $this->throwError($error);
1314 public function assertNumber($value, $error = "expecting number") {
1315 if ($value[0] == "number") return $value[1];
1316 $this->throwError($error);
1319 public function assertArgs($value, $expectedArgs, $name="") {
1320 if ($expectedArgs == 1) {
1323 if ($value[0] !== "list" ||
$value[1] != ",") $this->throwError("expecting list");
1324 $values = $value[2];
1325 $numValues = count($values);
1326 if ($expectedArgs != $numValues) {
1328 $name = $name . ": ";
1331 $this->throwError("${name}expecting $expectedArgs arguments, got $numValues");
1338 protected function toHSL($color) {
1339 if ($color[0] == 'hsl') return $color;
1341 $r = $color[1] / 255;
1342 $g = $color[2] / 255;
1343 $b = $color[3] / 255;
1345 $min = min($r, $g, $b);
1346 $max = max($r, $g, $b);
1348 $L = ($min +
$max) / 2;
1353 $S = ($max - $min)/($max +
$min);
1355 $S = ($max - $min)/(2.0 - $max - $min);
1357 if ($r == $max) $H = ($g - $b)/($max - $min);
1358 elseif ($g == $max) $H = 2.0 +
($b - $r)/($max - $min);
1359 elseif ($b == $max) $H = 4.0 +
($r - $g)/($max - $min);
1364 ($H < 0 ?
$H +
6 : $H)*60,
1369 if (count($color) > 4) $out[] = $color[4]; // copy alpha
1373 protected function toRGB_helper($comp, $temp1, $temp2) {
1374 if ($comp < 0) $comp +
= 1.0;
1375 elseif ($comp > 1) $comp -= 1.0;
1377 if (6 * $comp < 1) return $temp1 +
($temp2 - $temp1) * 6 * $comp;
1378 if (2 * $comp < 1) return $temp2;
1379 if (3 * $comp < 2) return $temp1 +
($temp2 - $temp1)*((2/3) - $comp) * 6;
1385 * Converts a hsl array into a color value in rgb.
1386 * Expects H to be in range of 0 to 360, S and L in 0 to 100
1388 protected function toRGB($color) {
1389 if ($color[0] == 'color') return $color;
1391 $H = $color[1] / 360;
1392 $S = $color[2] / 100;
1393 $L = $color[3] / 100;
1402 $temp1 = 2.0 * $L - $temp2;
1404 $r = $this->toRGB_helper($H +
1/3, $temp1, $temp2);
1405 $g = $this->toRGB_helper($H, $temp1, $temp2);
1406 $b = $this->toRGB_helper($H - 1/3, $temp1, $temp2);
1409 // $out = array('color', round($r*255), round($g*255), round($b*255));
1410 $out = array('color', $r*255, $g*255, $b*255);
1411 if (count($color) > 4) $out[] = $color[4]; // copy alpha
1415 protected function clamp($v, $max = 1, $min = 0) {
1416 return min($max, max($min, $v));
1420 * Convert the rgb, rgba, hsl color literals of function type
1421 * as returned by the parser into values of color type.
1423 protected function funcToColor($func) {
1425 if ($func[2][0] != 'list') return false; // need a list of arguments
1426 $rawComponents = $func[2][2];
1428 if ($fname == 'hsl' ||
$fname == 'hsla') {
1429 $hsl = array('hsl');
1431 foreach ($rawComponents as $c) {
1432 $val = $this->reduce($c);
1433 $val = isset($val[1]) ?
floatval($val[1]) : 0;
1435 if ($i == 0) $clamp = 360;
1436 elseif ($i < 3) $clamp = 100;
1439 $hsl[] = $this->clamp($val, $clamp);
1443 while (count($hsl) < 4) $hsl[] = 0;
1444 return $this->toRGB($hsl);
1446 } elseif ($fname == 'rgb' ||
$fname == 'rgba') {
1447 $components = array();
1449 foreach ($rawComponents as $c) {
1450 $c = $this->reduce($c);
1452 if ($c[0] == "number" && $c[2] == "%") {
1453 $components[] = 255 * ($c[1] / 100);
1455 $components[] = floatval($c[1]);
1457 } elseif ($i == 4) {
1458 if ($c[0] == "number" && $c[2] == "%") {
1459 $components[] = 1.0 * ($c[1] / 100);
1461 $components[] = floatval($c[1]);
1467 while (count($components) < 3) $components[] = 0;
1468 array_unshift($components, 'color');
1469 return $this->fixColor($components);
1475 protected function reduce($value, $forExpression = false) {
1476 switch ($value[0]) {
1478 $reduced = $this->reduce($value[1]);
1479 $var = $this->compileValue($reduced);
1480 $res = $this->reduce(array("variable", $this->vPrefix
. $var));
1482 if ($res[0] == "raw_color") {
1483 $res = $this->coerceColor($res);
1486 if (empty($value[2])) $res = $this->lib_e($res);
1491 if (is_array($key)) {
1492 $key = $this->reduce($key);
1493 $key = $this->vPrefix
. $this->compileValue($this->lib_e($key));
1496 $seen =& $this->env
->seenNames
;
1498 if (!empty($seen[$key])) {
1499 $this->throwError("infinite loop detected: $key");
1503 $out = $this->reduce($this->get($key));
1504 $seen[$key] = false;
1507 foreach ($value[2] as &$item) {
1508 $item = $this->reduce($item, $forExpression);
1512 return $this->evaluate($value);
1514 foreach ($value[2] as &$part) {
1515 if (is_array($part)) {
1516 $strip = $part[0] == "variable";
1517 $part = $this->reduce($part);
1518 if ($strip) $part = $this->lib_e($part);
1523 list(,$inner) = $value;
1524 return $this->lib_e($this->reduce($inner));
1526 $color = $this->funcToColor($value);
1527 if ($color) return $color;
1529 list(, $name, $args) = $value;
1530 if ($name == "%") $name = "_sprintf";
1532 $f = isset($this->libFunctions
[$name]) ?
1533 $this->libFunctions
[$name] : array($this, 'lib_'.str_replace('-', '_', $name));
1535 if (is_callable($f)) {
1536 if ($args[0] == 'list')
1537 $args = self
::compressList($args[2], $args[1]);
1539 $ret = call_user_func($f, $this->reduce($args, true), $this);
1541 if (is_null($ret)) {
1542 return array("string", "", array(
1543 $name, "(", $args, ")"
1547 // convert to a typed value if the result is a php primitive
1548 if (is_numeric($ret)) $ret = array('number', $ret, "");
1549 elseif (!is_array($ret)) $ret = array('keyword', $ret);
1554 // plain function, reduce args
1555 $value[2] = $this->reduce($value[2]);
1558 list(, $op, $exp) = $value;
1559 $exp = $this->reduce($exp);
1561 if ($exp[0] == "number") {
1570 return array("string", "", array($op, $exp));
1573 if ($forExpression) {
1574 switch ($value[0]) {
1576 if ($color = $this->coerceColor($value)) {
1581 return $this->coerceColor($value);
1589 // coerce a value for use in color operation
1590 protected function coerceColor($value) {
1592 case 'color': return $value;
1594 $c = array("color", 0, 0, 0);
1595 $colorStr = substr($value[1], 1);
1596 $num = hexdec($colorStr);
1597 $width = strlen($colorStr) == 3 ?
16 : 256;
1599 for ($i = 3; $i > 0; $i--) { // 3 2 1
1603 $c[$i] = $t * (256/$width) +
$t * floor(16/$width);
1609 if (isset(self
::$cssColors[$name])) {
1610 $rgba = explode(',', self
::$cssColors[$name]);
1613 return array('color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
1615 return array('color', $rgba[0], $rgba[1], $rgba[2]);
1621 // make something string like into a string
1622 protected function coerceString($value) {
1623 switch ($value[0]) {
1627 return array("string", "", array($value[1]));
1632 // turn list of length 1 into value type
1633 protected function flattenList($value) {
1634 if ($value[0] == "list" && count($value[2]) == 1) {
1635 return $this->flattenList($value[2][0]);
1640 public function toBool($a) {
1641 if ($a) return self
::$TRUE;
1642 else return self
::$FALSE;
1645 // evaluate an expression
1646 protected function evaluate($exp) {
1647 list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
1649 $left = $this->reduce($left, true);
1650 $right = $this->reduce($right, true);
1652 if ($leftColor = $this->coerceColor($left)) {
1656 if ($rightColor = $this->coerceColor($right)) {
1657 $right = $rightColor;
1663 // operators that work on all types
1665 return $this->toBool($left == self
::$TRUE && $right == self
::$TRUE);
1669 return $this->toBool($this->eq($left, $right) );
1672 if ($op == "+" && !is_null($str = $this->stringConcatenate($left, $right))) {
1676 // type based operators
1677 $fname = "op_${ltype}_${rtype}";
1678 if (is_callable(array($this, $fname))) {
1679 $out = $this->$fname($op, $left, $right);
1680 if (!is_null($out)) return $out;
1683 // make the expression look it did before being parsed
1685 if ($whiteBefore) $paddedOp = " " . $paddedOp;
1686 if ($whiteAfter) $paddedOp .= " ";
1688 return array("string", "", array($left, $paddedOp, $right));
1691 protected function stringConcatenate($left, $right) {
1692 if ($strLeft = $this->coerceString($left)) {
1693 if ($right[0] == "string") {
1696 $strLeft[2][] = $right;
1700 if ($strRight = $this->coerceString($right)) {
1701 array_unshift($strRight[2], $left);
1707 // make sure a color's components don't go out of bounds
1708 protected function fixColor($c) {
1709 foreach (range(1, 3) as $i) {
1710 if ($c[$i] < 0) $c[$i] = 0;
1711 if ($c[$i] > 255) $c[$i] = 255;
1717 protected function op_number_color($op, $lft, $rgt) {
1718 if ($op == '+' ||
$op == '*') {
1719 return $this->op_color_number($op, $rgt, $lft);
1723 protected function op_color_number($op, $lft, $rgt) {
1724 if ($rgt[0] == '%') $rgt[1] /= 100;
1726 return $this->op_color_color($op, $lft,
1727 array_fill(1, count($lft) - 1, $rgt[1]));
1730 protected function op_color_color($op, $left, $right) {
1731 $out = array('color');
1732 $max = count($left) > count($right) ?
count($left) : count($right);
1733 foreach (range(1, $max - 1) as $i) {
1734 $lval = isset($left[$i]) ?
$left[$i] : 0;
1735 $rval = isset($right[$i]) ?
$right[$i] : 0;
1738 $out[] = $lval +
$rval;
1741 $out[] = $lval - $rval;
1744 $out[] = $lval * $rval;
1747 $out[] = $lval %
$rval;
1750 if ($rval == 0) $this->throwError("evaluate error: can't divide by zero");
1751 $out[] = $lval / $rval;
1754 $this->throwError('evaluate error: color op number failed on op '.$op);
1757 return $this->fixColor($out);
1760 function lib_red($color){
1761 $color = $this->coerceColor($color);
1762 if (is_null($color)) {
1763 $this->throwError('color expected for red()');
1769 function lib_green($color){
1770 $color = $this->coerceColor($color);
1771 if (is_null($color)) {
1772 $this->throwError('color expected for green()');
1778 function lib_blue($color){
1779 $color = $this->coerceColor($color);
1780 if (is_null($color)) {
1781 $this->throwError('color expected for blue()');
1788 // operator on two numbers
1789 protected function op_number_number($op, $left, $right) {
1790 $unit = empty($left[2]) ?
$right[2] : $left[2];
1795 $value = $left[1] +
$right[1];
1798 $value = $left[1] * $right[1];
1801 $value = $left[1] - $right[1];
1804 $value = $left[1] %
$right[1];
1807 if ($right[1] == 0) $this->throwError('parse error: divide by zero');
1808 $value = $left[1] / $right[1];
1811 return $this->toBool($left[1] < $right[1]);
1813 return $this->toBool($left[1] > $right[1]);
1815 return $this->toBool($left[1] >= $right[1]);
1817 return $this->toBool($left[1] <= $right[1]);
1819 $this->throwError('parse error: unknown number operator: '.$op);
1822 return array("number", $value, $unit);
1826 /* environment functions */
1828 protected function makeOutputBlock($type, $selectors = null) {
1830 $b->lines
= array();
1831 $b->children
= array();
1832 $b->selectors
= $selectors;
1834 $b->parent
= $this->scope
;
1838 // the state of execution
1839 protected function pushEnv($block = null) {
1841 $e->parent
= $this->env
;
1842 $e->store
= array();
1849 // pop something off the stack
1850 protected function popEnv() {
1852 $this->env
= $this->env
->parent
;
1856 // set something in the current env
1857 protected function set($name, $value) {
1858 $this->env
->store
[$name] = $value;
1862 // get the highest occurrence entry for a name
1863 protected function get($name) {
1864 $current = $this->env
;
1866 $isArguments = $name == $this->vPrefix
. 'arguments';
1868 if ($isArguments && isset($current->arguments
)) {
1869 return array('list', ' ', $current->arguments
);
1872 if (isset($current->store
[$name]))
1873 return $current->store
[$name];
1875 $current = isset($current->storeParent
) ?
1876 $current->storeParent
: $current->parent
;
1880 $this->throwError("variable $name is undefined");
1883 // inject array of unparsed strings into environment as variables
1884 protected function injectVariables($args) {
1886 $parser = new lessc_parser($this, __METHOD__
);
1887 foreach ($args as $name => $strValue) {
1888 if ($name{0} != '@') $name = '@'.$name;
1890 $parser->buffer
= (string)$strValue;
1891 if (!$parser->propertyValue($value)) {
1892 throw new Exception("failed to parse passed in variable $name: $strValue");
1895 $this->set($name, $value);
1900 * Initialize any static state, can initialize parser for a file
1901 * $opts isn't used yet
1903 public function __construct($fname = null) {
1904 if ($fname !== null) {
1905 // used for deprecated parse method
1906 $this->_parseFile
= $fname;
1910 public function compile($string, $name = null) {
1911 $locale = setlocale(LC_NUMERIC
, 0);
1912 setlocale(LC_NUMERIC
, "C");
1914 $this->parser
= $this->makeParser($name);
1915 $root = $this->parser
->parse($string);
1918 $this->scope
= null;
1920 $this->formatter
= $this->newFormatter();
1922 if (!empty($this->registeredVars
)) {
1923 $this->injectVariables($this->registeredVars
);
1926 $this->sourceParser
= $this->parser
; // used for error messages
1927 $this->compileBlock($root);
1930 $this->formatter
->block($this->scope
);
1931 $out = ob_get_clean();
1932 setlocale(LC_NUMERIC
, $locale);
1936 public function compileFile($fname, $outFname = null) {
1937 if (!is_readable($fname)) {
1938 throw new Exception('load error: failed to find '.$fname);
1941 $pi = pathinfo($fname);
1943 $oldImport = $this->importDir
;
1945 $this->importDir
= (array)$this->importDir
;
1946 $this->importDir
[] = $pi['dirname'].'/';
1948 $this->addParsedFile($fname);
1950 $out = $this->compile(file_get_contents($fname), $fname);
1952 $this->importDir
= $oldImport;
1954 if ($outFname !== null) {
1955 return file_put_contents($outFname, $out);
1961 // compile only if changed input has changed or output doesn't exist
1962 public function checkedCompile($in, $out) {
1963 if (!is_file($out) ||
filemtime($in) > filemtime($out)) {
1964 $this->compileFile($in, $out);
1971 * Execute lessphp on a .less file or a lessphp cache structure
1973 * The lessphp cache structure contains information about a specific
1974 * less file having been parsed. It can be used as a hint for future
1975 * calls to determine whether or not a rebuild is required.
1977 * The cache structure contains two important keys that may be used
1980 * compiled: The final compiled CSS
1981 * updated: The time (in seconds) the CSS was last compiled
1983 * The cache structure is a plain-ol' PHP associative array and can
1984 * be serialized and unserialized without a hitch.
1986 * @param mixed $in Input
1987 * @param bool $force Force rebuild?
1988 * @return array lessphp cache structure
1990 public function cachedCompile($in, $force = false) {
1994 if (is_string($in)) {
1996 } elseif (is_array($in) and isset($in['root'])) {
1997 if ($force or ! isset($in['files'])) {
1998 // If we are forcing a recompile or if for some reason the
1999 // structure does not contain any file information we should
2000 // specify the root to trigger a rebuild.
2001 $root = $in['root'];
2002 } elseif (isset($in['files']) and is_array($in['files'])) {
2003 foreach ($in['files'] as $fname => $ftime ) {
2004 if (!file_exists($fname) or filemtime($fname) > $ftime) {
2005 // One of the files we knew about previously has changed
2006 // so we should look at our incoming root again.
2007 $root = $in['root'];
2013 // TODO: Throw an exception? We got neither a string nor something
2014 // that looks like a compatible lessphp cache structure.
2018 if ($root !== null) {
2019 // If we have a root value which means we should rebuild.
2021 $out['root'] = $root;
2022 $out['compiled'] = $this->compileFile($root);
2023 $out['files'] = $this->allParsedFiles();
2024 $out['updated'] = time();
2027 // No changes, pass back the structure
2028 // we were given initially.
2034 // parse and compile buffer
2035 // This is deprecated
2036 public function parse($str = null, $initialVariables = null) {
2037 if (is_array($str)) {
2038 $initialVariables = $str;
2042 $oldVars = $this->registeredVars
;
2043 if ($initialVariables !== null) {
2044 $this->setVariables($initialVariables);
2048 if (empty($this->_parseFile
)) {
2049 throw new exception("nothing to parse");
2052 $out = $this->compileFile($this->_parseFile
);
2054 $out = $this->compile($str);
2057 $this->registeredVars
= $oldVars;
2061 protected function makeParser($name) {
2062 $parser = new lessc_parser($this, $name);
2063 $parser->writeComments
= $this->preserveComments
;
2068 public function setFormatter($name) {
2069 $this->formatterName
= $name;
2072 protected function newFormatter() {
2073 $className = "lessc_formatter_lessjs";
2074 if (!empty($this->formatterName
)) {
2075 if (!is_string($this->formatterName
))
2076 return $this->formatterName
;
2077 $className = "lessc_formatter_$this->formatterName";
2080 return new $className;
2083 public function setPreserveComments($preserve) {
2084 $this->preserveComments
= $preserve;
2087 public function registerFunction($name, $func) {
2088 $this->libFunctions
[$name] = $func;
2091 public function unregisterFunction($name) {
2092 unset($this->libFunctions
[$name]);
2095 public function setVariables($variables) {
2096 $this->registeredVars
= array_merge($this->registeredVars
, $variables);
2099 public function unsetVariable($name) {
2100 unset($this->registeredVars
[$name]);
2103 public function setImportDir($dirs) {
2104 $this->importDir
= (array)$dirs;
2107 public function addImportDir($dir) {
2108 $this->importDir
= (array)$this->importDir
;
2109 $this->importDir
[] = $dir;
2112 public function allParsedFiles() {
2113 return $this->allParsedFiles
;
2116 public function addParsedFile($file) {
2117 $this->allParsedFiles
[realpath($file)] = filemtime($file);
2121 * Uses the current value of $this->count to show line and line number
2123 public function throwError($msg = null) {
2124 if ($this->sourceLoc
>= 0) {
2125 $this->sourceParser
->throwError($msg, $this->sourceLoc
);
2127 throw new exception($msg);
2130 // compile file $in to file $out if $in is newer than $out
2131 // returns true when it compiles, false otherwise
2132 public static function ccompile($in, $out, $less = null) {
2133 if ($less === null) {
2136 return $less->checkedCompile($in, $out);
2139 public static function cexecute($in, $force = false, $less = null) {
2140 if ($less === null) {
2143 return $less->cachedCompile($in, $force);
2146 static protected $cssColors = array(
2147 'aliceblue' => '240,248,255',
2148 'antiquewhite' => '250,235,215',
2149 'aqua' => '0,255,255',
2150 'aquamarine' => '127,255,212',
2151 'azure' => '240,255,255',
2152 'beige' => '245,245,220',
2153 'bisque' => '255,228,196',
2155 'blanchedalmond' => '255,235,205',
2156 'blue' => '0,0,255',
2157 'blueviolet' => '138,43,226',
2158 'brown' => '165,42,42',
2159 'burlywood' => '222,184,135',
2160 'cadetblue' => '95,158,160',
2161 'chartreuse' => '127,255,0',
2162 'chocolate' => '210,105,30',
2163 'coral' => '255,127,80',
2164 'cornflowerblue' => '100,149,237',
2165 'cornsilk' => '255,248,220',
2166 'crimson' => '220,20,60',
2167 'cyan' => '0,255,255',
2168 'darkblue' => '0,0,139',
2169 'darkcyan' => '0,139,139',
2170 'darkgoldenrod' => '184,134,11',
2171 'darkgray' => '169,169,169',
2172 'darkgreen' => '0,100,0',
2173 'darkgrey' => '169,169,169',
2174 'darkkhaki' => '189,183,107',
2175 'darkmagenta' => '139,0,139',
2176 'darkolivegreen' => '85,107,47',
2177 'darkorange' => '255,140,0',
2178 'darkorchid' => '153,50,204',
2179 'darkred' => '139,0,0',
2180 'darksalmon' => '233,150,122',
2181 'darkseagreen' => '143,188,143',
2182 'darkslateblue' => '72,61,139',
2183 'darkslategray' => '47,79,79',
2184 'darkslategrey' => '47,79,79',
2185 'darkturquoise' => '0,206,209',
2186 'darkviolet' => '148,0,211',
2187 'deeppink' => '255,20,147',
2188 'deepskyblue' => '0,191,255',
2189 'dimgray' => '105,105,105',
2190 'dimgrey' => '105,105,105',
2191 'dodgerblue' => '30,144,255',
2192 'firebrick' => '178,34,34',
2193 'floralwhite' => '255,250,240',
2194 'forestgreen' => '34,139,34',
2195 'fuchsia' => '255,0,255',
2196 'gainsboro' => '220,220,220',
2197 'ghostwhite' => '248,248,255',
2198 'gold' => '255,215,0',
2199 'goldenrod' => '218,165,32',
2200 'gray' => '128,128,128',
2201 'green' => '0,128,0',
2202 'greenyellow' => '173,255,47',
2203 'grey' => '128,128,128',
2204 'honeydew' => '240,255,240',
2205 'hotpink' => '255,105,180',
2206 'indianred' => '205,92,92',
2207 'indigo' => '75,0,130',
2208 'ivory' => '255,255,240',
2209 'khaki' => '240,230,140',
2210 'lavender' => '230,230,250',
2211 'lavenderblush' => '255,240,245',
2212 'lawngreen' => '124,252,0',
2213 'lemonchiffon' => '255,250,205',
2214 'lightblue' => '173,216,230',
2215 'lightcoral' => '240,128,128',
2216 'lightcyan' => '224,255,255',
2217 'lightgoldenrodyellow' => '250,250,210',
2218 'lightgray' => '211,211,211',
2219 'lightgreen' => '144,238,144',
2220 'lightgrey' => '211,211,211',
2221 'lightpink' => '255,182,193',
2222 'lightsalmon' => '255,160,122',
2223 'lightseagreen' => '32,178,170',
2224 'lightskyblue' => '135,206,250',
2225 'lightslategray' => '119,136,153',
2226 'lightslategrey' => '119,136,153',
2227 'lightsteelblue' => '176,196,222',
2228 'lightyellow' => '255,255,224',
2229 'lime' => '0,255,0',
2230 'limegreen' => '50,205,50',
2231 'linen' => '250,240,230',
2232 'magenta' => '255,0,255',
2233 'maroon' => '128,0,0',
2234 'mediumaquamarine' => '102,205,170',
2235 'mediumblue' => '0,0,205',
2236 'mediumorchid' => '186,85,211',
2237 'mediumpurple' => '147,112,219',
2238 'mediumseagreen' => '60,179,113',
2239 'mediumslateblue' => '123,104,238',
2240 'mediumspringgreen' => '0,250,154',
2241 'mediumturquoise' => '72,209,204',
2242 'mediumvioletred' => '199,21,133',
2243 'midnightblue' => '25,25,112',
2244 'mintcream' => '245,255,250',
2245 'mistyrose' => '255,228,225',
2246 'moccasin' => '255,228,181',
2247 'navajowhite' => '255,222,173',
2248 'navy' => '0,0,128',
2249 'oldlace' => '253,245,230',
2250 'olive' => '128,128,0',
2251 'olivedrab' => '107,142,35',
2252 'orange' => '255,165,0',
2253 'orangered' => '255,69,0',
2254 'orchid' => '218,112,214',
2255 'palegoldenrod' => '238,232,170',
2256 'palegreen' => '152,251,152',
2257 'paleturquoise' => '175,238,238',
2258 'palevioletred' => '219,112,147',
2259 'papayawhip' => '255,239,213',
2260 'peachpuff' => '255,218,185',
2261 'peru' => '205,133,63',
2262 'pink' => '255,192,203',
2263 'plum' => '221,160,221',
2264 'powderblue' => '176,224,230',
2265 'purple' => '128,0,128',
2267 'rosybrown' => '188,143,143',
2268 'royalblue' => '65,105,225',
2269 'saddlebrown' => '139,69,19',
2270 'salmon' => '250,128,114',
2271 'sandybrown' => '244,164,96',
2272 'seagreen' => '46,139,87',
2273 'seashell' => '255,245,238',
2274 'sienna' => '160,82,45',
2275 'silver' => '192,192,192',
2276 'skyblue' => '135,206,235',
2277 'slateblue' => '106,90,205',
2278 'slategray' => '112,128,144',
2279 'slategrey' => '112,128,144',
2280 'snow' => '255,250,250',
2281 'springgreen' => '0,255,127',
2282 'steelblue' => '70,130,180',
2283 'tan' => '210,180,140',
2284 'teal' => '0,128,128',
2285 'thistle' => '216,191,216',
2286 'tomato' => '255,99,71',
2287 'transparent' => '0,0,0,0',
2288 'turquoise' => '64,224,208',
2289 'violet' => '238,130,238',
2290 'wheat' => '245,222,179',
2291 'white' => '255,255,255',
2292 'whitesmoke' => '245,245,245',
2293 'yellow' => '255,255,0',
2294 'yellowgreen' => '154,205,50'
2298 // responsible for taking a string of LESS code and converting it into a
2300 class lessc_parser
{
2301 static protected $nextBlockId = 0; // used to uniquely identify blocks
2303 static protected $precedence = array(
2317 static protected $whitePattern;
2318 static protected $commentMulti;
2320 static protected $commentSingle = "//";
2321 static protected $commentMultiLeft = "/*";
2322 static protected $commentMultiRight = "*/";
2324 // regex string to match any of the operators
2325 static protected $operatorString;
2327 // these properties will supress division unless it's inside parenthases
2328 static protected $supressDivisionProps =
2329 array('/border-radius$/i', '/^font$/i');
2331 protected $blockDirectives = array("font-face", "keyframes", "page", "-moz-document", "viewport", "-moz-viewport", "-o-viewport", "-ms-viewport");
2332 protected $lineDirectives = array("charset");
2335 * if we are in parens we can be more liberal with whitespace around
2336 * operators because it must evaluate to a single value and thus is less
2340 * property1: 10 -5; // is two numbers, 10 and -5
2341 * property2: (10 -5); // should evaluate to 5
2343 protected $inParens = false;
2345 // caches preg escaped literals
2346 static protected $literalCache = array();
2348 public function __construct($lessc, $sourceName = null) {
2349 $this->eatWhiteDefault
= true;
2350 // reference to less needed for vPrefix, mPrefix, and parentSelector
2351 $this->lessc
= $lessc;
2353 $this->sourceName
= $sourceName; // name used for error messages
2355 $this->writeComments
= false;
2357 if (!self
::$operatorString) {
2358 self
::$operatorString =
2359 '('.implode('|', array_map(array('lessc', 'preg_quote'),
2360 array_keys(self
::$precedence))).')';
2362 $commentSingle = lessc
::preg_quote(self
::$commentSingle);
2363 $commentMultiLeft = lessc
::preg_quote(self
::$commentMultiLeft);
2364 $commentMultiRight = lessc
::preg_quote(self
::$commentMultiRight);
2366 self
::$commentMulti = $commentMultiLeft.'.*?'.$commentMultiRight;
2367 self
::$whitePattern = '/'.$commentSingle.'[^\n]*\s*|('.self
::$commentMulti.')\s*|\s+/Ais';
2371 public function parse($buffer) {
2375 $this->env
= null; // block stack
2376 $this->buffer
= $this->writeComments ?
$buffer : $this->removeComments($buffer);
2377 $this->pushSpecialBlock("root");
2378 $this->eatWhiteDefault
= true;
2379 $this->seenComments
= array();
2381 // trim whitespace on head
2382 // if (preg_match('/^\s+/', $this->buffer, $m)) {
2383 // $this->line += substr_count($m[0], "\n");
2384 // $this->buffer = ltrim($this->buffer);
2386 $this->whitespace();
2388 // parse the entire file
2389 while (false !== $this->parseChunk());
2391 if ($this->count
!= strlen($this->buffer
))
2392 $this->throwError();
2394 // TODO report where the block was opened
2395 if ( !property_exists($this->env
, 'parent') ||
!is_null($this->env
->parent
) )
2396 throw new exception('parse error: unclosed block');
2402 * Parse a single chunk off the head of the buffer and append it to the
2403 * current parse environment.
2404 * Returns false when the buffer is empty, or when there is an error.
2406 * This function is called repeatedly until the entire document is
2409 * This parser is most similar to a recursive descent parser. Single
2410 * functions represent discrete grammatical rules for the language, and
2411 * they are able to capture the text that represents those rules.
2413 * Consider the function lessc::keyword(). (all parse functions are
2414 * structured the same)
2416 * The function takes a single reference argument. When calling the
2417 * function it will attempt to match a keyword on the head of the buffer.
2418 * If it is successful, it will place the keyword in the referenced
2419 * argument, advance the position in the buffer, and return true. If it
2420 * fails then it won't advance the buffer and it will return false.
2422 * All of these parse functions are powered by lessc::match(), which behaves
2423 * the same way, but takes a literal regular expression. Sometimes it is
2424 * more convenient to use match instead of creating a new function.
2426 * Because of the format of the functions, to parse an entire string of
2427 * grammatical rules, you can chain them together using &&.
2429 * But, if some of the rules in the chain succeed before one fails, then
2430 * the buffer position will be left at an invalid state. In order to
2431 * avoid this, lessc::seek() is used to remember and set buffer positions.
2433 * Before parsing a chain, use $s = $this->seek() to remember the current
2434 * position into $s. Then if a chain fails, use $this->seek($s) to
2435 * go back where we started.
2437 protected function parseChunk() {
2438 if (empty($this->buffer
)) return false;
2441 if ($this->whitespace()) {
2445 // setting a property
2446 if ($this->keyword($key) && $this->assign() &&
2447 $this->propertyValue($value, $key) && $this->end())
2449 $this->append(array('assign', $key, $value), $s);
2456 // look for special css blocks
2457 if ($this->literal('@', false)) {
2461 if ($this->literal('@media')) {
2462 if (($this->mediaQueryList($mediaQueries) ||
true)
2463 && $this->literal('{'))
2465 $media = $this->pushSpecialBlock("media");
2466 $media->queries
= is_null($mediaQueries) ?
array() : $mediaQueries;
2474 if ($this->literal("@", false) && $this->keyword($dirName)) {
2475 if ($this->isDirective($dirName, $this->blockDirectives
)) {
2476 if (($this->openString("{", $dirValue, null, array(";")) ||
true) &&
2477 $this->literal("{"))
2479 $dir = $this->pushSpecialBlock("directive");
2480 $dir->name
= $dirName;
2481 if (isset($dirValue)) $dir->value
= $dirValue;
2484 } elseif ($this->isDirective($dirName, $this->lineDirectives
)) {
2485 if ($this->propertyValue($dirValue) && $this->end()) {
2486 $this->append(array("directive", $dirName, $dirValue));
2495 // setting a variable
2496 if ($this->variable($var) && $this->assign() &&
2497 $this->propertyValue($value) && $this->end())
2499 $this->append(array('assign', $var, $value), $s);
2505 if ($this->import($importValue)) {
2506 $this->append($importValue, $s);
2510 // opening parametric mixin
2511 if ($this->tag($tag, true) && $this->argumentDef($args, $isVararg) &&
2512 ($this->guards($guards) ||
true) &&
2513 $this->literal('{'))
2515 $block = $this->pushBlock($this->fixTags(array($tag)));
2516 $block->args
= $args;
2517 $block->isVararg
= $isVararg;
2518 if (!empty($guards)) $block->guards
= $guards;
2524 // opening a simple block
2525 if ($this->tags($tags) && $this->literal('{', false)) {
2526 $tags = $this->fixTags($tags);
2527 $this->pushBlock($tags);
2534 if ($this->literal('}', false)) {
2536 $block = $this->pop();
2537 } catch (exception
$e) {
2539 $this->throwError($e->getMessage());
2543 if (is_null($block->type
)) {
2545 if (!isset($block->args
)) {
2546 foreach ($block->tags
as $tag) {
2547 if (!is_string($tag) ||
$tag{0} != $this->lessc
->mPrefix
) {
2554 foreach ($block->tags
as $tag) {
2555 if (is_string($tag)) {
2556 $this->env
->children
[$tag][] = $block;
2562 $this->append(array('block', $block), $s);
2565 // this is done here so comments aren't bundled into he block that
2567 $this->whitespace();
2572 if ($this->mixinTags($tags) &&
2573 ($this->argumentDef($argv, $isVararg) ||
true) &&
2574 ($this->keyword($suffix) ||
true) && $this->end())
2576 $tags = $this->fixTags($tags);
2577 $this->append(array('mixin', $tags, $argv, $suffix), $s);
2584 if ($this->literal(';')) return true;
2586 return false; // got nothing, throw error
2589 protected function isDirective($dirname, $directives) {
2590 // TODO: cache pattern in parser
2591 $pattern = implode("|",
2592 array_map(array("lessc", "preg_quote"), $directives));
2593 $pattern = '/^(-[a-z-]+-)?(' . $pattern . ')$/i';
2595 return preg_match($pattern, $dirname);
2598 protected function fixTags($tags) {
2599 // move @ tags out of variable namespace
2600 foreach ($tags as &$tag) {
2601 if ($tag{0} == $this->lessc
->vPrefix
)
2602 $tag[0] = $this->lessc
->mPrefix
;
2607 // a list of expressions
2608 protected function expressionList(&$exps) {
2611 while ($this->expression($exp)) {
2615 if (count($values) == 0) return false;
2617 $exps = lessc
::compressList($values, ' ');
2622 * Attempt to consume an expression.
2623 * @link http://en.wikipedia.org/wiki/Operator-precedence_parser#Pseudo-code
2625 protected function expression(&$out) {
2626 if ($this->value($lhs)) {
2627 $out = $this->expHelper($lhs, 0);
2629 // look for / shorthand
2630 if (!empty($this->env
->supressedDivision
)) {
2631 unset($this->env
->supressedDivision
);
2633 if ($this->literal("/") && $this->value($rhs)) {
2634 $out = array("list", "",
2635 array($out, array("keyword", "/"), $rhs));
2647 * recursively parse infix equation with $lhs at precedence $minP
2649 protected function expHelper($lhs, $minP) {
2650 $this->inExp
= true;
2651 $ss = $this->seek();
2654 $whiteBefore = isset($this->buffer
[$this->count
- 1]) &&
2655 ctype_space($this->buffer
[$this->count
- 1]);
2657 // If there is whitespace before the operator, then we require
2658 // whitespace after the operator for it to be an expression
2659 $needWhite = $whiteBefore && !$this->inParens
;
2661 if ($this->match(self
::$operatorString.($needWhite ?
'\s' : ''), $m) && self
::$precedence[$m[1]] >= $minP) {
2662 if (!$this->inParens
&& isset($this->env
->currentProperty
) && $m[1] == "/" && empty($this->env
->supressedDivision
)) {
2663 foreach (self
::$supressDivisionProps as $pattern) {
2664 if (preg_match($pattern, $this->env
->currentProperty
)) {
2665 $this->env
->supressedDivision
= true;
2672 $whiteAfter = isset($this->buffer
[$this->count
- 1]) &&
2673 ctype_space($this->buffer
[$this->count
- 1]);
2675 if (!$this->value($rhs)) break;
2677 // peek for next operator to see what to do with rhs
2678 if ($this->peek(self
::$operatorString, $next) && self
::$precedence[$next[1]] > self
::$precedence[$m[1]]) {
2679 $rhs = $this->expHelper($rhs, self
::$precedence[$next[1]]);
2682 $lhs = array('expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
2683 $ss = $this->seek();
2696 // consume a list of values for a property
2697 public function propertyValue(&$value, $keyName = null) {
2700 if ($keyName !== null) $this->env
->currentProperty
= $keyName;
2703 while ($this->expressionList($v)) {
2706 if (!$this->literal(',')) break;
2709 if ($s) $this->seek($s);
2711 if ($keyName !== null) unset($this->env
->currentProperty
);
2713 if (count($values) == 0) return false;
2715 $value = lessc
::compressList($values, ', ');
2719 protected function parenValue(&$out) {
2723 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] != "(") {
2727 $inParens = $this->inParens
;
2728 if ($this->literal("(") &&
2729 ($this->inParens
= true) && $this->expression($exp) &&
2730 $this->literal(")"))
2733 $this->inParens
= $inParens;
2736 $this->inParens
= $inParens;
2744 protected function value(&$value) {
2748 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] == "-") {
2750 if ($this->literal("-", false) &&
2751 (($this->variable($inner) && $inner = array("variable", $inner)) ||
2752 $this->unit($inner) ||
2753 $this->parenValue($inner)))
2755 $value = array("unary", "-", $inner);
2762 if ($this->parenValue($value)) return true;
2763 if ($this->unit($value)) return true;
2764 if ($this->color($value)) return true;
2765 if ($this->func($value)) return true;
2766 if ($this->string($value)) return true;
2768 if ($this->keyword($word)) {
2769 $value = array('keyword', $word);
2774 if ($this->variable($var)) {
2775 $value = array('variable', $var);
2779 // unquote string (should this work on any type?
2780 if ($this->literal("~") && $this->string($str)) {
2781 $value = array("escape", $str);
2788 if ($this->literal('\\') && $this->match('([0-9]+)', $m)) {
2789 $value = array('keyword', '\\'.$m[1]);
2798 // an import statement
2799 protected function import(&$out) {
2800 if (!$this->literal('@import')) return false;
2802 // @import "something.css" media;
2803 // @import url("something.css") media;
2804 // @import url(something.css) media;
2806 if ($this->propertyValue($value)) {
2807 $out = array("import", $value);
2812 protected function mediaQueryList(&$out) {
2813 if ($this->genericList($list, "mediaQuery", ",", false)) {
2820 protected function mediaQuery(&$out) {
2823 $expressions = null;
2826 if (($this->literal("only") && ($only = true) ||
$this->literal("not") && ($not = true) ||
true) && $this->keyword($mediaType)) {
2827 $prop = array("mediaType");
2828 if (isset($only)) $prop[] = "only";
2829 if (isset($not)) $prop[] = "not";
2830 $prop[] = $mediaType;
2837 if (!empty($mediaType) && !$this->literal("and")) {
2840 $this->genericList($expressions, "mediaExpression", "and", false);
2841 if (is_array($expressions)) $parts = array_merge($parts, $expressions[2]);
2844 if (count($parts) == 0) {
2853 protected function mediaExpression(&$out) {
2856 if ($this->literal("(") &&
2857 $this->keyword($feature) &&
2858 ($this->literal(":") && $this->expression($value) ||
true) &&
2859 $this->literal(")"))
2861 $out = array("mediaExp", $feature);
2862 if ($value) $out[] = $value;
2864 } elseif ($this->variable($variable)) {
2865 $out = array('variable', $variable);
2873 // an unbounded string stopped by $end
2874 protected function openString($end, &$out, $nestingOpen=null, $rejectStrs = null) {
2875 $oldWhite = $this->eatWhiteDefault
;
2876 $this->eatWhiteDefault
= false;
2878 $stop = array("'", '"', "@{", $end);
2879 $stop = array_map(array("lessc", "preg_quote"), $stop);
2880 // $stop[] = self::$commentMulti;
2882 if (!is_null($rejectStrs)) {
2883 $stop = array_merge($stop, $rejectStrs);
2886 $patt = '(.*?)('.implode("|", $stop).')';
2891 while ($this->match($patt, $m, false)) {
2892 if (!empty($m[1])) {
2895 $nestingLevel +
= substr_count($m[1], $nestingOpen);
2901 $this->count
-= strlen($tok);
2903 if ($nestingLevel == 0) {
2910 if (($tok == "'" ||
$tok == '"') && $this->string($str)) {
2915 if ($tok == "@{" && $this->interpolation($inter)) {
2916 $content[] = $inter;
2920 if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
2925 $this->count+
= strlen($tok);
2928 $this->eatWhiteDefault
= $oldWhite;
2930 if (count($content) == 0) return false;
2933 if (is_string(end($content))) {
2934 $content[count($content) - 1] = rtrim(end($content));
2937 $out = array("string", "", $content);
2941 protected function string(&$out) {
2943 if ($this->literal('"', false)) {
2945 } elseif ($this->literal("'", false)) {
2953 // look for either ending delim , escape, or string interpolation
2954 $patt = '([^\n]*?)(@\{|\\\\|' .
2955 lessc
::preg_quote($delim).')';
2957 $oldWhite = $this->eatWhiteDefault
;
2958 $this->eatWhiteDefault
= false;
2960 while ($this->match($patt, $m, false)) {
2962 if ($m[2] == "@{") {
2963 $this->count
-= strlen($m[2]);
2964 if ($this->interpolation($inter, false)) {
2965 $content[] = $inter;
2967 $this->count +
= strlen($m[2]);
2968 $content[] = "@{"; // ignore it
2970 } elseif ($m[2] == '\\') {
2972 if ($this->literal($delim, false)) {
2973 $content[] = $delim;
2976 $this->count
-= strlen($delim);
2981 $this->eatWhiteDefault
= $oldWhite;
2983 if ($this->literal($delim)) {
2984 $out = array("string", $delim, $content);
2992 protected function interpolation(&$out) {
2993 $oldWhite = $this->eatWhiteDefault
;
2994 $this->eatWhiteDefault
= true;
2997 if ($this->literal("@{") &&
2998 $this->openString("}", $interp, null, array("'", '"', ";")) &&
2999 $this->literal("}", false))
3001 $out = array("interpolate", $interp);
3002 $this->eatWhiteDefault
= $oldWhite;
3003 if ($this->eatWhiteDefault
) $this->whitespace();
3007 $this->eatWhiteDefault
= $oldWhite;
3012 protected function unit(&$unit) {
3014 if (isset($this->buffer
[$this->count
])) {
3015 $char = $this->buffer
[$this->count
];
3016 if (!ctype_digit($char) && $char != ".") return false;
3019 if ($this->match('([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
3020 $unit = array("number", $m[1], empty($m[2]) ?
"" : $m[2]);
3027 protected function color(&$out) {
3028 if ($this->match('(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
3029 if (strlen($m[1]) > 7) {
3030 $out = array("string", "", array($m[1]));
3032 $out = array("raw_color", $m[1]);
3040 // consume an argument definition list surrounded by ()
3041 // each argument is a variable name with optional value
3042 // or at the end a ... or a variable named followed by ...
3043 // arguments are separated by , unless a ; is in the list, then ; is the
3045 protected function argumentDef(&$args, &$isVararg) {
3047 if (!$this->literal('(')) return false;
3051 $method = "expressionList";
3055 if ($this->literal("...")) {
3060 if ($this->$method($value)) {
3061 if ($value[0] == "variable") {
3062 $arg = array("arg", $value[1]);
3063 $ss = $this->seek();
3065 if ($this->assign() && $this->$method($rhs)) {
3069 if ($this->literal("...")) {
3076 if ($isVararg) break;
3079 $values[] = array("lit", $value);
3084 if (!$this->literal($delim)) {
3085 if ($delim == "," && $this->literal(";")) {
3086 // found new delim, convert existing args
3088 $method = "propertyValue";
3090 // transform arg list
3091 if (isset($values[1])) { // 2 items
3093 foreach ($values as $i => $arg) {
3097 $this->throwError("Cannot mix ; and , as delimiter types");
3099 $newList[] = $arg[2];
3102 $newList[] = $arg[1];
3105 $this->throwError("Unexpected rest before semicolon");
3109 $newList = array("list", ", ", $newList);
3111 switch ($values[0][0]) {
3113 $newArg = array("arg", $values[0][1], $newList);
3116 $newArg = array("lit", $newList);
3120 } elseif ($values) { // 1 item
3121 $newArg = $values[0];
3125 $values = array($newArg);
3133 if (!$this->literal(')')) {
3143 // consume a list of tags
3144 // this accepts a hanging delimiter
3145 protected function tags(&$tags, $simple = false, $delim = ',') {
3147 while ($this->tag($tt, $simple)) {
3149 if (!$this->literal($delim)) break;
3151 if (count($tags) == 0) return false;
3156 // list of tags of specifying mixin path
3157 // optionally separated by > (lazy, accepts extra >)
3158 protected function mixinTags(&$tags) {
3160 while ($this->tag($tt, true)) {
3162 $this->literal(">");
3165 if (count($tags) == 0) return false;
3170 // a bracketed value (contained within in a tag definition)
3171 protected function tagBracket(&$parts, &$hasExpression) {
3173 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] != "[") {
3179 $hasInterpolation = false;
3181 if ($this->literal("[", false)) {
3182 $attrParts = array("[");
3183 // keyword, string, operator
3185 if ($this->literal("]", false)) {
3187 break; // get out early
3190 if ($this->match('\s+', $m)) {
3194 if ($this->string($str)) {
3195 // escape parent selector, (yuck)
3196 foreach ($str[2] as &$chunk) {
3197 $chunk = str_replace($this->lessc
->parentSelector
, "$&$", $chunk);
3200 $attrParts[] = $str;
3201 $hasInterpolation = true;
3205 if ($this->keyword($word)) {
3206 $attrParts[] = $word;
3210 if ($this->interpolation($inter, false)) {
3211 $attrParts[] = $inter;
3212 $hasInterpolation = true;
3216 // operator, handles attr namespace too
3217 if ($this->match('[|-~\$\*\^=]+', $m)) {
3218 $attrParts[] = $m[0];
3225 if ($this->literal("]", false)) {
3227 foreach ($attrParts as $part) {
3230 $hasExpression = $hasExpression ||
$hasInterpolation;
3240 // a space separated list of selectors
3241 protected function tag(&$tag, $simple = false) {
3243 $chars = '^@,:;{}\][>\(\) "\'';
3245 $chars = '^@,;{}["\'';
3249 $hasExpression = false;
3251 while ($this->tagBracket($parts, $hasExpression));
3253 $oldWhite = $this->eatWhiteDefault
;
3254 $this->eatWhiteDefault
= false;
3257 if ($this->match('(['.$chars.'0-9]['.$chars.']*)', $m)) {
3261 while ($this->tagBracket($parts, $hasExpression));
3265 if (isset($this->buffer
[$this->count
]) && $this->buffer
[$this->count
] == "@") {
3266 if ($this->interpolation($interp)) {
3267 $hasExpression = true;
3268 $interp[2] = true; // don't unescape
3273 if ($this->literal("@")) {
3279 if ($this->unit($unit)) { // for keyframes
3280 $parts[] = $unit[1];
3281 $parts[] = $unit[2];
3288 $this->eatWhiteDefault
= $oldWhite;
3294 if ($hasExpression) {
3295 $tag = array("exp", array("string", "", $parts));
3297 $tag = trim(implode($parts));
3300 $this->whitespace();
3305 protected function func(&$func) {
3308 if ($this->match('(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal('(')) {
3311 $sPreArgs = $this->seek();
3315 $ss = $this->seek();
3316 // this ugly nonsense is for ie filter properties
3317 if ($this->keyword($name) && $this->literal('=') && $this->expressionList($value)) {
3318 $args[] = array("string", "", array($name, "=", $value));
3321 if ($this->expressionList($value)) {
3326 if (!$this->literal(',')) break;
3328 $args = array('list', ',', $args);
3330 if ($this->literal(')')) {
3331 $func = array('function', $fname, $args);
3333 } elseif ($fname == 'url') {
3334 // couldn't parse and in url? treat as string
3335 $this->seek($sPreArgs);
3336 if ($this->openString(")", $string) && $this->literal(")")) {
3337 $func = array('function', $fname, $string);
3347 // consume a less variable
3348 protected function variable(&$name) {
3350 if ($this->literal($this->lessc
->vPrefix
, false) &&
3351 ($this->variable($sub) ||
$this->keyword($name)))
3354 $name = array('variable', $sub);
3356 $name = $this->lessc
->vPrefix
.$name;
3367 * Consume an assignment operator
3368 * Can optionally take a name that will be set to the current property name
3370 protected function assign($name = null) {
3371 if ($name) $this->currentProperty
= $name;
3372 return $this->literal(':') ||
$this->literal('=');
3375 // consume a keyword
3376 protected function keyword(&$word) {
3377 if ($this->match('([\w_\-\*!"][\w\-_"]*)', $m)) {
3384 // consume an end of statement delimiter
3385 protected function end() {
3386 if ($this->literal(';', false)) {
3388 } elseif ($this->count
== strlen($this->buffer
) ||
$this->buffer
[$this->count
] == '}') {
3389 // if there is end of file or a closing block next then we don't need a ;
3395 protected function guards(&$guards) {
3398 if (!$this->literal("when")) {
3405 while ($this->guardGroup($g)) {
3407 if (!$this->literal(",")) break;
3410 if (count($guards) == 0) {
3419 // a bunch of guards that are and'd together
3420 // TODO rename to guardGroup
3421 protected function guardGroup(&$guardGroup) {
3423 $guardGroup = array();
3424 while ($this->guard($guard)) {
3425 $guardGroup[] = $guard;
3426 if (!$this->literal("and")) break;
3429 if (count($guardGroup) == 0) {
3438 protected function guard(&$guard) {
3440 $negate = $this->literal("not");
3442 if ($this->literal("(") && $this->expression($exp) && $this->literal(")")) {
3444 if ($negate) $guard = array("negate", $guard);
3452 /* raw parsing functions */
3454 protected function literal($what, $eatWhitespace = null) {
3455 if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault
;
3457 // shortcut on single letter
3458 if (!isset($what[1]) && isset($this->buffer
[$this->count
])) {
3459 if ($this->buffer
[$this->count
] == $what) {
3460 if (!$eatWhitespace) {
3470 if (!isset(self
::$literalCache[$what])) {
3471 self
::$literalCache[$what] = lessc
::preg_quote($what);
3474 return $this->match(self
::$literalCache[$what], $m, $eatWhitespace);
3477 protected function genericList(&$out, $parseItem, $delim="", $flatten=true) {
3480 while ($this->$parseItem($value)) {
3483 if (!$this->literal($delim)) break;
3487 if (count($items) == 0) {
3492 if ($flatten && count($items) == 1) {
3495 $out = array("list", $delim, $items);
3502 // advance counter to next occurrence of $what
3503 // $until - don't include $what in advance
3504 // $allowNewline, if string, will be used as valid char set
3505 protected function to($what, &$out, $until = false, $allowNewline = false) {
3506 if (is_string($allowNewline)) {
3507 $validChars = $allowNewline;
3509 $validChars = $allowNewline ?
"." : "[^\n]";
3511 if (!$this->match('('.$validChars.'*?)'.lessc
::preg_quote($what), $m, !$until)) return false;
3512 if ($until) $this->count
-= strlen($what); // give back $what
3517 // try to match something on head of buffer
3518 protected function match($regex, &$out, $eatWhitespace = null) {
3519 if ($eatWhitespace === null) $eatWhitespace = $this->eatWhiteDefault
;
3521 $r = '/'.$regex.($eatWhitespace && !$this->writeComments ?
'\s*' : '').'/Ais';
3522 if (preg_match($r, $this->buffer
, $out, null, $this->count
)) {
3523 $this->count +
= strlen($out[0]);
3524 if ($eatWhitespace && $this->writeComments
) $this->whitespace();
3530 // match some whitespace
3531 protected function whitespace() {
3532 if ($this->writeComments
) {
3534 while (preg_match(self
::$whitePattern, $this->buffer
, $m, null, $this->count
)) {
3535 if (isset($m[1]) && empty($this->seenComments
[$this->count
])) {
3536 $this->append(array("comment", $m[1]));
3537 $this->seenComments
[$this->count
] = true;
3539 $this->count +
= strlen($m[0]);
3544 $this->match("", $m);
3545 return strlen($m[0]) > 0;
3549 // match something without consuming it
3550 protected function peek($regex, &$out = null, $from=null) {
3551 if (is_null($from)) $from = $this->count
;
3552 $r = '/'.$regex.'/Ais';
3553 $result = preg_match($r, $this->buffer
, $out, null, $from);
3558 // seek to a spot in the buffer or return where we are on no argument
3559 protected function seek($where = null) {
3560 if ($where === null) return $this->count
;
3561 else $this->count
= $where;
3565 /* misc functions */
3567 public function throwError($msg = "parse error", $count = null) {
3568 $count = is_null($count) ?
$this->count
: $count;
3570 $line = $this->line +
3571 substr_count(substr($this->buffer
, 0, $count), "\n");
3573 if (!empty($this->sourceName
)) {
3574 $loc = "$this->sourceName on line $line";
3576 $loc = "line: $line";
3579 // TODO this depends on $this->count
3580 if ($this->peek("(.*?)(\n|$)", $m, $count)) {
3581 throw new exception("$msg: failed at `$m[1]` $loc");
3583 throw new exception("$msg: $loc");
3587 protected function pushBlock($selectors=null, $type=null) {
3589 $b->parent
= $this->env
;
3592 $b->id
= self
::$nextBlockId++
;
3594 $b->isVararg
= false; // TODO: kill me from here
3595 $b->tags
= $selectors;
3597 $b->props
= array();
3598 $b->children
= array();
3604 // push a block that doesn't multiply tags
3605 protected function pushSpecialBlock($type) {
3606 return $this->pushBlock(null, $type);
3609 // append a property to the current block
3610 protected function append($prop, $pos = null) {
3611 if ($pos !== null) $prop[-1] = $pos;
3612 $this->env
->props
[] = $prop;
3615 // pop something off the stack
3616 protected function pop() {
3618 $this->env
= $this->env
->parent
;
3622 // remove comments from $text
3623 // todo: make it work for all functions, not just url
3624 protected function removeComments($text) {
3626 'url(', '//', '/*', '"', "'"
3632 // find the next item
3633 foreach ($look as $token) {
3634 $pos = strpos($text, $token);
3635 if ($pos !== false) {
3636 if (!isset($min) ||
$pos < $min[1]) $min = array($token, $pos);
3640 if (is_null($min)) break;
3647 if (preg_match('/url\(.*?\)/', $text, $m, 0, $count))
3648 $count +
= strlen($m[0]) - strlen($min[0]);
3652 if (preg_match('/'.$min[0].'.*?(?<!\\\\)'.$min[0].'/', $text, $m, 0, $count))
3653 $count +
= strlen($m[0]) - 1;
3656 $skip = strpos($text, "\n", $count);
3657 if ($skip === false) $skip = strlen($text) - $count;
3658 else $skip -= $count;
3661 if (preg_match('/\/\*.*?\*\//s', $text, $m, 0, $count)) {
3662 $skip = strlen($m[0]);
3663 $newlines = substr_count($m[0], "\n");
3668 if ($skip == 0) $count +
= strlen($min[0]);
3670 $out .= substr($text, 0, $count).str_repeat("\n", $newlines);
3671 $text = substr($text, $count +
$skip);
3681 class lessc_formatter_classic
{
3682 public $indentChar = " ";
3684 public $break = "\n";
3685 public $open = " {";
3686 public $close = "}";
3687 public $selectorSeparator = ", ";
3688 public $assignSeparator = ":";
3690 public $openSingle = " { ";
3691 public $closeSingle = " }";
3693 public $disableSingle = false;
3694 public $breakSelectors = false;
3696 public $compressColors = false;
3698 public function __construct() {
3699 $this->indentLevel
= 0;
3702 public function indentStr($n = 0) {
3703 return str_repeat($this->indentChar
, max($this->indentLevel +
$n, 0));
3706 public function property($name, $value) {
3707 return $name . $this->assignSeparator
. $value . ";";
3710 protected function isEmpty($block) {
3711 if (empty($block->lines
)) {
3712 foreach ($block->children
as $child) {
3713 if (!$this->isEmpty($child)) return false;
3721 public function block($block) {
3722 if ($this->isEmpty($block)) return;
3724 $inner = $pre = $this->indentStr();
3726 $isSingle = !$this->disableSingle
&&
3727 is_null($block->type
) && count($block->lines
) == 1;
3729 if (!empty($block->selectors
)) {
3730 $this->indentLevel++
;
3732 if ($this->breakSelectors
) {
3733 $selectorSeparator = $this->selectorSeparator
. $this->break . $pre;
3735 $selectorSeparator = $this->selectorSeparator
;
3739 implode($selectorSeparator, $block->selectors
);
3741 echo $this->openSingle
;
3744 echo $this->open
. $this->break;
3745 $inner = $this->indentStr();
3750 if (!empty($block->lines
)) {
3751 $glue = $this->break.$inner;
3752 echo $inner . implode($glue, $block->lines
);
3753 if (!$isSingle && !empty($block->children
)) {
3758 foreach ($block->children
as $child) {
3759 $this->block($child);
3762 if (!empty($block->selectors
)) {
3763 if (!$isSingle && empty($block->children
)) echo $this->break;
3766 echo $this->closeSingle
. $this->break;
3768 echo $pre . $this->close
. $this->break;
3771 $this->indentLevel
--;
3776 class lessc_formatter_compressed
extends lessc_formatter_classic
{
3777 public $disableSingle = true;
3779 public $selectorSeparator = ",";
3780 public $assignSeparator = ":";
3782 public $compressColors = true;
3784 public function indentStr($n = 0) {
3789 class lessc_formatter_lessjs
extends lessc_formatter_classic
{
3790 public $disableSingle = true;
3791 public $breakSelectors = true;
3792 public $assignSeparator = ": ";
3793 public $selectorSeparator = ",";