40 public static $VERSION =
"v0.5.0";
42 public static $TRUE = array(
"keyword",
"true");
43 public static $FALSE = array(
"keyword",
"false");
45 protected $libFunctions = array();
46 protected $registeredVars = array();
47 protected $preserveComments =
false;
49 public $vPrefix =
'@';
50 public $mPrefix =
'$';
51 public $parentSelector =
'&';
53 public $importDisabled =
false;
54 public $importDir =
'';
56 protected $numberPrecision =
null;
58 protected $allParsedFiles = array();
62 protected $sourceParser =
null;
63 protected $sourceLoc =
null;
65 protected static $nextImportId = 0;
68 protected function findImport($url)
70 foreach ((array) $this->importDir as $dir) {
71 $full = $dir.(substr($dir, -1) !=
'/' ?
'/' :
'').$url;
88 return is_file($name);
91 public static function compressList($items, $delim)
93 if (!isset($items[1]) && isset($items[0])) {
96 return array(
'list', $delim, $items);
100 public static function preg_quote($what)
102 return preg_quote($what,
'/');
105 protected function tryImport($importPath, $parentBlock, $out)
107 if ($importPath[0] ==
"function" && $importPath[1] ==
"url") {
108 $importPath = $this->flattenList($importPath[2]);
111 $str = $this->coerceString($importPath);
119 if (substr_compare($url,
'.css', -4, 4) === 0) {
123 $realPath = $this->findImport($url);
125 if ($realPath ===
null) {
129 if ($this->importDisabled) {
130 return array(
false,
"/* import disabled */");
133 if (isset($this->allParsedFiles[realpath($realPath)])) {
134 return array(
false,
null);
137 $this->addParsedFile($realPath);
138 $parser = $this->makeParser($realPath);
139 $root = $parser->parse(file_get_contents($realPath));
142 foreach ($root->props as $prop) {
143 if ($prop[0] ==
"block") {
144 $prop[1]->parent = $parentBlock;
151 foreach ($root->children as $childName => $child) {
152 if (isset($parentBlock->children[$childName])) {
153 $parentBlock->children[$childName] = array_merge(
154 $parentBlock->children[$childName],
158 $parentBlock->children[$childName] = $child;
162 $pi = pathinfo($realPath);
163 $dir = $pi[
"dirname"];
165 list($top, $bottom) = $this->sortProps($root->props,
true);
166 $this->compileImportedProps($top, $parentBlock, $out, $parser, $dir);
168 return array(
true, $bottom, $parser, $dir);
171 protected function compileImportedProps($props, $block, $out, $sourceParser, $importDir)
173 $oldSourceParser = $this->sourceParser;
175 $oldImport = $this->importDir;
178 $this->importDir = (array) $this->importDir;
179 array_unshift($this->importDir, $importDir);
181 foreach ($props as $prop) {
182 $this->compileProp($prop, $block, $out);
185 $this->importDir = $oldImport;
186 $this->sourceParser = $oldSourceParser;
212 switch ($block->type) {
214 $this->compileRoot($block);
217 $this->compileCSSBlock($block);
220 $this->compileMedia($block);
223 $name =
"@".$block->name;
224 if (!empty($block->value)) {
225 $name .=
" ".$this->compileValue($this->reduce($block->value));
228 $this->compileNestedBlock($block, array($name));
231 $this->
throwError(
"unknown block type: $block->type\n");
235 protected function compileCSSBlock($block)
237 $env = $this->pushEnv();
239 $selectors = $this->compileSelectors($block->tags);
240 $env->selectors = $this->multiplySelectors($selectors);
241 $out = $this->makeOutputBlock(
null, $env->selectors);
243 $this->scope->children[] = $out;
244 $this->compileProps($block, $out);
246 $block->scope = $env;
250 protected function compileMedia($media)
252 $env = $this->pushEnv($media);
253 $parentScope = $this->mediaParent($this->scope);
255 $query = $this->compileMediaQuery($this->multiplyMedia($env));
257 $this->scope = $this->makeOutputBlock($media->type, array($query));
258 $parentScope->children[] = $this->scope;
260 $this->compileProps($media, $this->scope);
262 if (count($this->scope->lines) > 0) {
263 $orphanSelelectors = $this->findClosestSelectors();
264 if (!is_null($orphanSelelectors)) {
265 $orphan = $this->makeOutputBlock(
null, $orphanSelelectors);
266 $orphan->lines = $this->scope->lines;
267 array_unshift($this->scope->children, $orphan);
268 $this->scope->lines = array();
272 $this->scope = $this->scope->parent;
276 protected function mediaParent($scope)
278 while (!empty($scope->parent)) {
279 if (!empty($scope->type) && $scope->type !=
"media") {
282 $scope = $scope->parent;
288 protected function compileNestedBlock($block, $selectors)
290 $this->pushEnv($block);
291 $this->scope = $this->makeOutputBlock($block->type, $selectors);
292 $this->scope->parent->children[] = $this->scope;
294 $this->compileProps($block, $this->scope);
296 $this->scope = $this->scope->parent;
300 protected function compileRoot($root)
303 $this->scope = $this->makeOutputBlock($root->type);
304 $this->compileProps($root, $this->scope);
308 protected function compileProps($block, $out)
310 foreach ($this->sortProps($block->props) as $prop) {
311 $this->compileProp($prop, $block, $out);
326 foreach ($lines as $line) {
327 if (strpos($line,
'/*') === 0) {
331 if (!in_array($line, $unique)) {
334 array_splice($unique, array_search($line, $unique), 0, $comments);
337 return array_merge($unique, $comments);
340 protected function sortProps($props, $split =
false)
347 foreach ($props as $prop) {
354 if (isset($prop[1][0]) && $prop[1][0] == $this->vPrefix) {
355 $vars = array_merge($vars, $stack);
357 $other = array_merge($other, $stack);
362 $id = self::$nextImportId++;
365 $imports = array_merge($imports, $stack);
366 $other[] = array(
"import_mixin", $id);
371 $other = array_merge($other, $stack);
376 $other = array_merge($other, $stack);
379 return array(array_merge($imports, $vars), $other);
381 return array_merge($imports, $vars, $other);
385 protected function compileMediaQuery($queries)
387 $compiledQueries = array();
388 foreach ($queries as $query) {
390 foreach ($query as $q) {
393 $parts[] = implode(
" ", array_slice($q, 1));
397 $parts[] =
"($q[1]: ".
400 $parts[] =
"($q[1])";
409 if (count($parts) > 0) {
410 $compiledQueries[] = implode(
" and ", $parts);
415 if (!empty($parts)) {
417 implode($this->formatter->selectorSeparator, $compiledQueries);
422 protected function multiplyMedia($env, $childQueries =
null)
425 !empty($env->block->type) && $env->block->type !=
"media"
427 return $childQueries;
431 if (empty($env->block->type)) {
432 return $this->multiplyMedia($env->parent, $childQueries);
436 $queries = $env->block->queries;
437 if (is_null($childQueries)) {
440 foreach ($queries as $parent) {
441 foreach ($childQueries as $child) {
442 $out[] = array_merge($parent, $child);
447 return $this->multiplyMedia($env->parent, $out);
450 protected function expandParentSelectors(&$tag, $replace)
452 $parts = explode(
"$&$", $tag);
454 foreach ($parts as &$part) {
455 $part = str_replace($this->parentSelector, $replace, $part, $c);
458 $tag = implode($this->parentSelector, $parts);
462 protected function findClosestSelectors()
466 while ($env !==
null) {
467 if (isset($env->selectors)) {
468 $selectors = $env->selectors;
479 protected function multiplySelectors($selectors)
483 $parentSelectors = $this->findClosestSelectors();
484 if (is_null($parentSelectors)) {
486 foreach ($selectors as &$s) {
487 $this->expandParentSelectors($s,
"");
494 foreach ($parentSelectors as $parent) {
495 foreach ($selectors as $child) {
496 $count = $this->expandParentSelectors($child, $parent);
500 $out[] = trim($child);
502 $out[] = trim($parent.
' '.$child);
511 protected function compileSelectors($selectors)
515 foreach ($selectors as $s) {
518 $out[] = trim($this->
compileValue($this->reduce($value)));
527 protected function eq($left, $right)
529 return $left == $right;
532 protected function patternMatch($block, $orderedArgs, $keywordArgs)
536 if (!empty($block->guards)) {
537 $groupPassed =
false;
538 foreach ($block->guards as $guardGroup) {
539 foreach ($guardGroup as $guard) {
541 $this->zipSetArgs($block->args, $orderedArgs, $keywordArgs);
544 if ($guard[0] ==
"negate") {
549 $passed = $this->reduce($guard) == self::$TRUE;
559 $groupPassed =
false;
574 if (empty($block->args)) {
575 return $block->isVararg || empty($orderedArgs) && empty($keywordArgs);
578 $remainingArgs = $block->args;
580 $remainingArgs = array();
581 foreach ($block->args as $arg) {
582 if ($arg[0] ==
"arg" && isset($keywordArgs[$arg[1]])) {
586 $remainingArgs[] = $arg;
592 foreach ($remainingArgs as $i => $arg) {
595 if (empty($orderedArgs[$i]) || !$this->eq($arg[1], $orderedArgs[$i])) {
601 if (!isset($orderedArgs[$i]) && !isset($arg[2])) {
611 if ($block->isVararg) {
614 $numMatched = $i + 1;
616 return $numMatched >= count($orderedArgs);
620 protected function patternMatchAll($blocks, $orderedArgs, $keywordArgs, $skip = array())
623 foreach ($blocks as $block) {
625 if (isset($skip[$block->id]) && !isset($block->args)) {
629 if ($this->patternMatch($block, $orderedArgs, $keywordArgs)) {
638 protected function findBlocks($searchIn, $path, $orderedArgs, $keywordArgs, $seen = array())
640 if ($searchIn ==
null) {
643 if (isset($seen[$searchIn->id])) {
646 $seen[$searchIn->id] =
true;
650 if (isset($searchIn->children[$name])) {
651 $blocks = $searchIn->children[$name];
652 if (count($path) == 1) {
653 $matches = $this->patternMatchAll($blocks, $orderedArgs, $keywordArgs, $seen);
654 if (!empty($matches)) {
661 foreach ($blocks as $subBlock) {
662 $subMatches = $this->findBlocks(
664 array_slice($path, 1),
670 if (!is_null($subMatches)) {
671 foreach ($subMatches as $sm) {
677 return count($matches) > 0 ? $matches :
null;
680 if ($searchIn->parent === $searchIn) {
683 return $this->findBlocks($searchIn->parent, $path, $orderedArgs, $keywordArgs, $seen);
688 protected function zipSetArgs($args, $orderedValues, $keywordValues)
690 $assignedValues = array();
693 foreach ($args as $a) {
694 if ($a[0] ==
"arg") {
695 if (isset($keywordValues[$a[1]])) {
697 $value = $keywordValues[$a[1]];
698 } elseif (isset($orderedValues[$i])) {
700 $value = $orderedValues[$i];
702 } elseif (isset($a[2])) {
707 $this->
throwError(
"Failed to assign arg ".$a[1]);
710 $value = $this->reduce($value);
711 $this->
set($a[1], $value);
712 $assignedValues[] = $value;
721 if ($last[0] ==
"rest") {
722 $rest = array_slice($orderedValues, count($args) - 1);
723 $this->
set($last[1], $this->reduce(array(
"list",
" ", $rest)));
727 $this->env->arguments = $assignedValues + $orderedValues;
731 protected function compileProp($prop, $block, $out)
734 $this->sourceLoc = isset($prop[-1]) ? $prop[-1] : -1;
738 list(, $name, $value) = $prop;
739 if ($name[0] == $this->vPrefix) {
740 $this->
set($name, $value);
742 $out->lines[] = $this->formatter->property(
749 list(, $child) = $prop;
753 list(, $path, $args, $suffix) = $prop;
755 $orderedArgs = array();
756 $keywordArgs = array();
757 foreach ((array) $args as $arg) {
761 if (!isset($arg[2])) {
762 $orderedArgs[] = $this->reduce(array(
"variable", $arg[1]));
764 $keywordArgs[$arg[1]] = $this->reduce($arg[2]);
769 $orderedArgs[] = $this->reduce($arg[1]);
772 $this->
throwError(
"Unknown arg type: ".$arg[0]);
776 $mixins = $this->findBlocks($block, $path, $orderedArgs, $keywordArgs);
778 if ($mixins ===
null) {
779 $this->
throwError(
"{$prop[1][0]} is undefined");
782 foreach ($mixins as $mixin) {
783 if ($mixin === $block && !$orderedArgs) {
788 if (isset($mixin->parent->scope)) {
790 $mixinParentEnv = $this->pushEnv();
791 $mixinParentEnv->storeParent = $mixin->parent->scope;
795 if (isset($mixin->args)) {
798 $this->zipSetArgs($mixin->args, $orderedArgs, $keywordArgs);
801 $oldParent = $mixin->parent;
802 if ($mixin != $block) {
803 $mixin->parent = $block;
806 foreach ($this->sortProps($mixin->props) as $subProp) {
807 if ($suffix !==
null &&
808 $subProp[0] ==
"assign" &&
809 is_string($subProp[1]) &&
810 $subProp[1][0] != $this->vPrefix
814 array($subProp[2], array(
'keyword', $suffix))
818 $this->compileProp($subProp, $mixin, $out);
821 $mixin->parent = $oldParent;
833 $out->lines[] = $prop[1];
836 list(, $name, $value) = $prop;
837 $out->lines[] =
"@$name ".$this->compileValue($this->reduce($value)).
';';
840 $out->lines[] = $prop[1];
843 list(, $importPath, $importId) = $prop;
844 $importPath = $this->reduce($importPath);
846 if (!isset($this->env->imports)) {
847 $this->env->imports = array();
850 $result = $this->tryImport($importPath, $block, $out);
852 $this->env->imports[$importId] = $result ===
false ?
853 array(
false,
"@import ".$this->
compileValue($importPath).
";") : $result;
857 list(,$importId) = $prop;
858 $import = $this->env->imports[$importId];
859 if ($import[0] ===
false) {
860 if (isset($import[1])) {
861 $out->lines[] = $import[1];
864 list(, $bottom, $parser, $importDir) = $import;
865 $this->compileImportedProps($bottom, $block, $out, $parser, $importDir);
870 $this->
throwError(
"unknown op: {$prop[0]}\n");
892 return implode($value[1], array_map(array($this,
'compileValue'), $value[2]));
894 if (!empty($this->formatter->compressColors)) {
902 list(, $num, $unit) = $value;
905 if ($this->numberPrecision !==
null) {
906 $num = round($num, $this->numberPrecision);
911 list(, $delim, $content) = $value;
912 foreach ($content as &$part) {
913 if (is_array($part)) {
917 return $delim.implode($content).$delim;
923 list(, $r, $g, $b) = $value;
928 if (count($value) == 5 && $value[4] != 1) {
929 return 'rgba('.$r.
','.$g.
','.$b.
','.$value[4].
')';
932 $h = sprintf(
"#%02x%02x%02x", $r, $g, $b);
934 if (!empty($this->formatter->compressColors)) {
936 if ($h[1] === $h[2] && $h[3] === $h[4] && $h[5] === $h[6]) {
937 $h =
'#'.$h[1].$h[3].$h[5];
944 list(, $name, $args) = $value;
947 $this->
throwError(
"unknown value type: $value[0]");
951 protected function lib_pow($args)
953 list($base, $exp) = $this->assertArgs($args, 2,
"pow");
954 return pow($this->assertNumber($base), $this->assertNumber($exp));
957 protected function lib_pi()
962 protected function lib_mod($args)
964 list($a, $b) = $this->assertArgs($args, 2,
"mod");
965 return $this->assertNumber($a) % $this->assertNumber($b);
968 protected function lib_tan($num)
970 return tan($this->assertNumber($num));
973 protected function lib_sin($num)
975 return sin($this->assertNumber($num));
978 protected function lib_cos($num)
980 return cos($this->assertNumber($num));
983 protected function lib_atan($num)
985 $num = atan($this->assertNumber($num));
986 return array(
"number", $num,
"rad");
989 protected function lib_asin($num)
991 $num = asin($this->assertNumber($num));
992 return array(
"number", $num,
"rad");
995 protected function lib_acos($num)
997 $num = acos($this->assertNumber($num));
998 return array(
"number", $num,
"rad");
1001 protected function lib_sqrt($num)
1003 return sqrt($this->assertNumber($num));
1006 protected function lib_extract($value)
1008 list($list, $idx) = $this->assertArgs($value, 2,
"extract");
1009 $idx = $this->assertNumber($idx);
1011 if ($list[0] ==
"list" && isset($list[2][$idx - 1])) {
1012 return $list[2][$idx - 1];
1016 protected function lib_isnumber($value)
1018 return $this->toBool($value[0] ==
"number");
1021 protected function lib_isstring($value)
1023 return $this->toBool($value[0] ==
"string");
1026 protected function lib_iscolor($value)
1028 return $this->toBool($this->coerceColor($value));
1031 protected function lib_iskeyword($value)
1033 return $this->toBool($value[0] ==
"keyword");
1036 protected function lib_ispixel($value)
1038 return $this->toBool($value[0] ==
"number" && $value[2] ==
"px");
1041 protected function lib_ispercentage($value)
1043 return $this->toBool($value[0] ==
"number" && $value[2] ==
"%");
1046 protected function lib_isem($value)
1048 return $this->toBool($value[0] ==
"number" && $value[2] ==
"em");
1051 protected function lib_isrem($value)
1053 return $this->toBool($value[0] ==
"number" && $value[2] ==
"rem");
1056 protected function lib_rgbahex($color)
1058 $color = $this->coerceColor($color);
1059 if (is_null($color)) {
1060 $this->
throwError(
"color expected for rgbahex");
1064 "#%02x%02x%02x%02x",
1065 isset($color[4]) ? $color[4] * 255 : 255,
1072 protected function lib_argb($color)
1074 return $this->lib_rgbahex($color);
1085 $mime = ($value[0] ===
'list') ? $value[2][0][2] :
null;
1086 $url = ($value[0] ===
'list') ? $value[2][1][2][0] : $value[2][0];
1088 $fullpath = $this->findImport($url);
1090 if ($fullpath && ($fsize = filesize($fullpath)) !==
false) {
1092 if ($fsize / 1024 < 32) {
1093 if (is_null($mime)) {
1094 if (class_exists(
'finfo')) {
1095 $finfo =
new finfo(FILEINFO_MIME);
1096 $mime = explode(
'; ', $finfo->file($fullpath));
1098 } elseif (function_exists(
'mime_content_type')) {
1099 $mime = mime_content_type($fullpath);
1103 if (!is_null($mime)) {
1104 $url = sprintf(
'data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath)));
1109 return 'url("'.$url.
'")';
1113 protected function lib_e($arg)
1118 if (isset($items[0])) {
1119 return $this->lib_e($items[0]);
1132 protected function lib__sprintf($args)
1134 if ($args[0] !=
"list") {
1138 $string = array_shift($values);
1139 $template = $this->
compileValue($this->lib_e($string));
1143 if (preg_match_all(
'/%[dsa]/', $template, $m)) {
1144 foreach ($m[0] as $match) {
1145 $val = isset($values[$i]) ?
1146 $this->reduce($values[$i]) : array(
'keyword',
'');
1149 if ($color = $this->coerceColor($val)) {
1155 $template = preg_replace(
1156 '/'.self::preg_quote($match).
'/',
1164 $d = $string[0] ==
"string" ? $string[1] :
'"';
1165 return array(
"string", $d, array($template));
1168 protected function lib_floor($arg)
1170 $value = $this->assertNumber($arg);
1171 return array(
"number", floor($value), $arg[2]);
1174 protected function lib_ceil($arg)
1176 $value = $this->assertNumber($arg);
1177 return array(
"number", ceil($value), $arg[2]);
1180 protected function lib_round($arg)
1182 if ($arg[0] !=
"list") {
1183 $value = $this->assertNumber($arg);
1184 return array(
"number", round($value), $arg[2]);
1186 $value = $this->assertNumber($arg[2][0]);
1187 $precision = $this->assertNumber($arg[2][1]);
1188 return array(
"number", round($value, $precision), $arg[2][0][2]);
1192 protected function lib_unit($arg)
1194 if ($arg[0] ==
"list") {
1195 list($number, $newUnit) = $arg[2];
1196 return array(
"number", $this->assertNumber($number),
1199 return array(
"number", $this->assertNumber($arg),
"");
1209 if ($args[0] !=
'list' || count($args[2]) < 2) {
1210 return array(array(
'color', 0, 0, 0), 0);
1212 list($color, $delta) = $args[2];
1213 $color = $this->assertColor($color);
1214 $delta = floatval($delta[1]);
1216 return array($color, $delta);
1219 protected function lib_darken($args)
1221 list($color, $delta) = $this->
colorArgs($args);
1223 $hsl = $this->toHSL($color);
1224 $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
1225 return $this->
toRGB($hsl);
1228 protected function lib_lighten($args)
1230 list($color, $delta) = $this->
colorArgs($args);
1232 $hsl = $this->toHSL($color);
1233 $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
1234 return $this->
toRGB($hsl);
1237 protected function lib_saturate($args)
1239 list($color, $delta) = $this->
colorArgs($args);
1241 $hsl = $this->toHSL($color);
1242 $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
1243 return $this->
toRGB($hsl);
1246 protected function lib_desaturate($args)
1248 list($color, $delta) = $this->
colorArgs($args);
1250 $hsl = $this->toHSL($color);
1251 $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
1252 return $this->
toRGB($hsl);
1255 protected function lib_spin($args)
1257 list($color, $delta) = $this->
colorArgs($args);
1259 $hsl = $this->toHSL($color);
1261 $hsl[1] = $hsl[1] + $delta % 360;
1266 return $this->
toRGB($hsl);
1269 protected function lib_fadeout($args)
1271 list($color, $delta) = $this->
colorArgs($args);
1272 $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta / 100);
1276 protected function lib_fadein($args)
1278 list($color, $delta) = $this->
colorArgs($args);
1279 $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta / 100);
1283 protected function lib_hue($color)
1285 $hsl = $this->toHSL($this->assertColor($color));
1286 return round($hsl[1]);
1289 protected function lib_saturation($color)
1291 $hsl = $this->toHSL($this->assertColor($color));
1292 return round($hsl[2]);
1295 protected function lib_lightness($color)
1297 $hsl = $this->toHSL($this->assertColor($color));
1298 return round($hsl[3]);
1303 protected function lib_alpha($value)
1305 if (!is_null($color = $this->coerceColor($value))) {
1306 return isset($color[4]) ? $color[4] : 1;
1311 protected function lib_fade($args)
1313 list($color, $alpha) = $this->
colorArgs($args);
1314 $color[4] = $this->clamp($alpha / 100.0);
1318 protected function lib_percentage($arg)
1320 $num = $this->assertNumber($arg);
1321 return array(
"number", $num * 100,
"%");
1337 $white = [
'color', 255, 255, 255];
1338 if ($args[0] ==
'color') {
1339 return $this->lib_mix([
'list',
',', [$white, $args]]);
1340 } elseif ($args[0] ==
"list" && count($args[2]) == 2) {
1341 return $this->lib_mix([$args[0], $args[1], [$white, $args[2][0], $args[2][1]]]);
1343 $this->
throwError(
"tint expects (color, weight)");
1360 $black = [
'color', 0, 0, 0];
1361 if ($args[0] ==
'color') {
1362 return $this->lib_mix([
'list',
',', [$black, $args]]);
1363 } elseif ($args[0] ==
"list" && count($args[2]) == 2) {
1364 return $this->lib_mix([$args[0], $args[1], [$black, $args[2][0], $args[2][1]]]);
1366 $this->
throwError(
"shade expects (color, weight)");
1373 protected function lib_mix($args)
1375 if ($args[0] !=
"list" || count($args[2]) < 2) {
1376 $this->
throwError(
"mix expects (color1, color2, weight)");
1379 list($first, $second) = $args[2];
1380 $first = $this->assertColor($first);
1381 $second = $this->assertColor($second);
1383 $first_a = $this->lib_alpha($first);
1384 $second_a = $this->lib_alpha($second);
1386 if (isset($args[2][2])) {
1387 $weight = $args[2][2][1] / 100.0;
1392 $w = $weight * 2 - 1;
1393 $a = $first_a - $second_a;
1395 $w1 = (($w * $a == -1 ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2.0;
1398 $new = array(
'color',
1399 $w1 * $first[1] + $w2 * $second[1],
1400 $w1 * $first[2] + $w2 * $second[2],
1401 $w1 * $first[3] + $w2 * $second[3],
1404 if ($first_a != 1.0 || $second_a != 1.0) {
1405 $new[] = $first_a * $weight + $second_a * ($weight - 1);
1408 return $this->fixColor($new);
1411 protected function lib_contrast($args)
1413 $darkColor = array(
'color', 0, 0, 0);
1414 $lightColor = array(
'color', 255, 255, 255);
1417 if ($args[0] ==
'list') {
1418 $inputColor = (isset($args[2][0])) ? $this->assertColor($args[2][0]) : $lightColor;
1419 $darkColor = (isset($args[2][1])) ? $this->assertColor($args[2][1]) : $darkColor;
1420 $lightColor = (isset($args[2][2])) ? $this->assertColor($args[2][2]) : $lightColor;
1421 $threshold = (isset($args[2][3])) ? $this->assertNumber($args[2][3]) : $threshold;
1423 $inputColor = $this->assertColor($args);
1426 $inputColor = $this->coerceColor($inputColor);
1427 $darkColor = $this->coerceColor($darkColor);
1428 $lightColor = $this->coerceColor($lightColor);
1431 if ($this->toLuma($darkColor) > $this->toLuma($lightColor)) {
1433 $lightColor = $darkColor;
1437 $inputColor_alpha = $this->lib_alpha($inputColor);
1438 if (($this->toLuma($inputColor) * $inputColor_alpha) < $threshold) {
1444 private function toLuma($color)
1446 list(, $r, $g, $b) = $this->coerceColor($color);
1452 $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
1453 $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
1454 $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);
1456 return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
1459 protected function lib_luma($color)
1461 return array(
"number", round($this->toLuma($color) * 100, 8),
"%");
1465 public function assertColor($value, $error =
"expected color value")
1467 $color = $this->coerceColor($value);
1468 if (is_null($color)) {
1474 public function assertNumber($value, $error =
"expecting number")
1476 if ($value[0] ==
"number") {
1482 public function assertArgs($value, $expectedArgs, $name =
"")
1484 if ($expectedArgs == 1) {
1487 if ($value[0] !==
"list" || $value[1] !=
",") {
1490 $values = $value[2];
1491 $numValues = count($values);
1492 if ($expectedArgs != $numValues) {
1497 $this->
throwError(
"${name}expecting $expectedArgs arguments, got $numValues");
1504 protected function toHSL($color)
1506 if ($color[0] ===
'hsl') {
1510 $r = $color[1] / 255;
1511 $g = $color[2] / 255;
1512 $b = $color[3] / 255;
1514 $min = min($r, $g, $b);
1515 $max = max($r, $g, $b);
1517 $L = ($min + $max) / 2;
1522 $S = ($max - $min) / ($max + $min);
1524 $S = ($max - $min) / (2.0 - $max - $min);
1527 $H = ($g - $b) / ($max - $min);
1528 } elseif ($g == $max) {
1529 $H = 2.0 + ($b - $r) / ($max - $min);
1530 } elseif ($b == $max) {
1531 $H = 4.0 + ($r - $g) / ($max - $min);
1536 ($H < 0 ? $H + 6 : $H) * 60,
1541 if (count($color) > 4) {
1548 protected function toRGB_helper($comp, $temp1, $temp2)
1552 } elseif ($comp > 1) {
1556 if (6 * $comp < 1) {
1557 return $temp1 + ($temp2 - $temp1) * 6 * $comp;
1559 if (2 * $comp < 1) {
1562 if (3 * $comp < 2) {
1563 return $temp1 + ($temp2 - $temp1) * ((2 / 3) - $comp) * 6;
1575 if ($color[0] ===
'color') {
1579 $H = $color[1] / 360;
1580 $S = $color[2] / 100;
1581 $L = $color[3] / 100;
1587 $L * (1.0 + $S) : $L + $S - $L * $S;
1589 $temp1 = 2.0 * $L - $temp2;
1591 $r = $this->toRGB_helper($H + 1 / 3, $temp1, $temp2);
1592 $g = $this->toRGB_helper($H, $temp1, $temp2);
1593 $b = $this->toRGB_helper($H - 1 / 3, $temp1, $temp2);
1597 $out = array(
'color', $r * 255, $g * 255, $b * 255);
1598 if (count($color) > 4) {
1605 protected function clamp($v, $max = 1, $min = 0)
1607 return min($max, max($min, $v));
1617 if ($func[2][0] !=
'list') {
1621 $rawComponents = $func[2][2];
1623 if ($fname ==
'hsl' || $fname ==
'hsla') {
1624 $hsl = array(
'hsl');
1626 foreach ($rawComponents as $c) {
1627 $val = $this->reduce($c);
1628 $val = isset($val[1]) ? floatval($val[1]) : 0;
1638 $hsl[] = $this->clamp($val, $clamp);
1642 while (count($hsl) < 4) {
1645 return $this->
toRGB($hsl);
1646 } elseif ($fname ==
'rgb' || $fname ==
'rgba') {
1647 $components = array();
1649 foreach ($rawComponents as $c) {
1650 $c = $this->reduce($c);
1652 if ($c[0] ==
"number" && $c[2] ==
"%") {
1653 $components[] = 255 * ($c[1] / 100);
1655 $components[] = floatval($c[1]);
1657 } elseif ($i == 4) {
1658 if ($c[0] ==
"number" && $c[2] ==
"%") {
1659 $components[] = 1.0 * ($c[1] / 100);
1661 $components[] = floatval($c[1]);
1669 while (count($components) < 3) {
1672 array_unshift($components,
'color');
1673 return $this->fixColor($components);
1679 protected function reduce($value, $forExpression =
false)
1681 switch ($value[0]) {
1683 $reduced = $this->reduce($value[1]);
1685 $res = $this->reduce(array(
"variable", $this->vPrefix.$var));
1687 if ($res[0] ==
"raw_color") {
1688 $res = $this->coerceColor($res);
1691 if (empty($value[2])) {
1692 $res = $this->lib_e($res);
1698 if (is_array($key)) {
1699 $key = $this->reduce($key);
1700 $key = $this->vPrefix.$this->compileValue($this->lib_e($key));
1703 $seen = & $this->env->seenNames;
1705 if (!empty($seen[$key])) {
1706 $this->
throwError(
"infinite loop detected: $key");
1710 $out = $this->reduce($this->
get($key));
1711 $seen[$key] =
false;
1714 foreach ($value[2] as &$item) {
1715 $item = $this->reduce($item, $forExpression);
1719 return $this->evaluate($value);
1721 foreach ($value[2] as &$part) {
1722 if (is_array($part)) {
1723 $strip = $part[0] ==
"variable";
1724 $part = $this->reduce($part);
1726 $part = $this->lib_e($part);
1732 list(,$inner) = $value;
1733 return $this->lib_e($this->reduce($inner));
1740 list(, $name, $args) = $value;
1745 $f = isset($this->libFunctions[$name]) ?
1746 $this->libFunctions[$name] : array($this,
'lib_'.str_replace(
'-',
'_', $name));
1748 if (is_callable($f)) {
1749 if ($args[0] ==
'list') {
1750 $args = self::compressList($args[2], $args[1]);
1753 $ret = call_user_func($f, $this->reduce($args,
true), $this);
1755 if (is_null($ret)) {
1756 return array(
"string",
"", array(
1757 $name,
"(", $args,
")"
1762 if (is_numeric($ret)) {
1763 $ret = array(
'number', $ret,
"");
1764 } elseif (!is_array($ret)) {
1765 $ret = array(
'keyword', $ret);
1772 $value[2] = $this->reduce($value[2]);
1775 list(, $op, $exp) = $value;
1776 $exp = $this->reduce($exp);
1778 if ($exp[0] ==
"number") {
1787 return array(
"string",
"", array($op, $exp));
1790 if ($forExpression) {
1791 switch ($value[0]) {
1793 if ($color = $this->coerceColor($value)) {
1798 return $this->coerceColor($value);
1807 protected function coerceColor($value)
1809 switch ($value[0]) {
1813 $c = array(
"color", 0, 0, 0);
1814 $colorStr = substr($value[1], 1);
1815 $num = hexdec($colorStr);
1816 $width = strlen($colorStr) == 3 ? 16 : 256;
1818 for ($i = 3; $i > 0; $i--) {
1822 $c[$i] = $t * (256 / $width) + $t * floor(16 / $width);
1828 if (isset(self::$cssColors[$name])) {
1829 $rgba = explode(
',', self::$cssColors[$name]);
1831 if (isset($rgba[3])) {
1832 return array(
'color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
1834 return array(
'color', $rgba[0], $rgba[1], $rgba[2]);
1841 protected function coerceString($value)
1843 switch ($value[0]) {
1847 return array(
"string",
"", array($value[1]));
1853 protected function flattenList($value)
1855 if ($value[0] ==
"list" && count($value[2]) == 1) {
1856 return $this->flattenList($value[2][0]);
1861 public function toBool($a)
1863 return $a ? self::$TRUE : self::$FALSE;
1867 protected function evaluate($exp)
1869 list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
1871 $left = $this->reduce($left,
true);
1872 $right = $this->reduce($right,
true);
1874 if ($leftColor = $this->coerceColor($left)) {
1878 if ($rightColor = $this->coerceColor($right)) {
1879 $right = $rightColor;
1887 return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
1891 return $this->toBool($this->eq($left, $right));
1894 if ($op ==
"+" && !is_null($str = $this->stringConcatenate($left, $right))) {
1899 $fname =
"op_${ltype}_${rtype}";
1900 if (is_callable(array($this, $fname))) {
1901 $out = $this->$fname($op, $left, $right);
1902 if (!is_null($out)) {
1910 $paddedOp =
" ".$paddedOp;
1916 return array(
"string",
"", array($left, $paddedOp, $right));
1919 protected function stringConcatenate($left, $right)
1921 if ($strLeft = $this->coerceString($left)) {
1922 if ($right[0] ==
"string") {
1925 $strLeft[2][] = $right;
1929 if ($strRight = $this->coerceString($right)) {
1930 array_unshift($strRight[2], $left);
1937 protected function fixColor($c)
1939 foreach (range(1, 3) as $i) {
1951 protected function op_number_color($op, $lft, $rgt)
1953 if ($op ==
'+' || $op ==
'*') {
1954 return $this->op_color_number($op, $rgt, $lft);
1958 protected function op_color_number($op, $lft, $rgt)
1960 if ($rgt[0] ==
'%') {
1964 return $this->op_color_color(
1967 array_fill(1, count($lft) - 1, $rgt[1])
1971 protected function op_color_color($op, $left, $right)
1973 $out = array(
'color');
1974 $max = count($left) > count($right) ? count($left) : count($right);
1975 foreach (range(1, $max - 1) as $i) {
1976 $lval = isset($left[$i]) ? $left[$i] : 0;
1977 $rval = isset($right[$i]) ? $right[$i] : 0;
1980 $out[] = $lval + $rval;
1983 $out[] = $lval - $rval;
1986 $out[] = $lval * $rval;
1989 $out[] = $lval % $rval;
1993 $this->
throwError(
"evaluate error: can't divide by zero");
1995 $out[] = $lval / $rval;
1998 $this->
throwError(
'evaluate error: color op number failed on op '.$op);
2001 return $this->fixColor($out);
2004 public function lib_red($color)
2006 $color = $this->coerceColor($color);
2007 if (is_null($color)) {
2008 $this->
throwError(
'color expected for red()');
2014 public function lib_green($color)
2016 $color = $this->coerceColor($color);
2017 if (is_null($color)) {
2018 $this->
throwError(
'color expected for green()');
2024 public function lib_blue($color)
2026 $color = $this->coerceColor($color);
2027 if (is_null($color)) {
2028 $this->
throwError(
'color expected for blue()');
2036 protected function op_number_number($op, $left, $right)
2038 $unit = empty($left[2]) ? $right[2] : $left[2];
2043 $value = $left[1] + $right[1];
2046 $value = $left[1] * $right[1];
2049 $value = $left[1] - $right[1];
2052 $value = $left[1] % $right[1];
2055 if ($right[1] == 0) {
2056 $this->
throwError(
'parse error: divide by zero');
2058 $value = $left[1] / $right[1];
2061 return $this->toBool($left[1] < $right[1]);
2063 return $this->toBool($left[1] > $right[1]);
2065 return $this->toBool($left[1] >= $right[1]);
2067 return $this->toBool($left[1] <= $right[1]);
2069 $this->
throwError(
'parse error: unknown number operator: '.$op);
2072 return array(
"number", $value, $unit);
2078 protected function makeOutputBlock($type, $selectors =
null)
2081 $b->lines = array();
2082 $b->children = array();
2083 $b->selectors = $selectors;
2085 $b->parent = $this->scope;
2090 protected function pushEnv($block =
null)
2093 $e->parent = $this->env;
2094 $e->store = array();
2102 protected function popEnv()
2105 $this->env = $this->env->parent;
2110 protected function set($name, $value)
2112 $this->env->store[$name] = $value;
2117 protected function get($name)
2119 $current = $this->env;
2121 $isArguments = $name == $this->vPrefix.
'arguments';
2123 if ($isArguments && isset($current->arguments)) {
2124 return array(
'list',
' ', $current->arguments);
2127 if (isset($current->store[$name])) {
2128 return $current->store[$name];
2131 $current = isset($current->storeParent) ?
2132 $current->storeParent : $current->parent;
2135 $this->
throwError(
"variable $name is undefined");
2139 protected function injectVariables($args)
2143 foreach ($args as $name => $strValue) {
2144 if ($name[0] !==
'@') {
2148 $parser->buffer = (string) $strValue;
2149 if (!$parser->propertyValue($value)) {
2150 throw new Exception(
"failed to parse passed in variable $name: $strValue");
2153 $this->
set($name, $value);
2163 if ($fname !==
null) {
2165 $this->_parseFile = $fname;
2169 public function compile($string, $name =
null)
2171 $locale = setlocale(LC_NUMERIC, 0);
2172 setlocale(LC_NUMERIC,
"C");
2174 $this->parser = $this->makeParser($name);
2175 $root = $this->parser->parse($string);
2178 $this->scope =
null;
2180 $this->formatter = $this->newFormatter();
2182 if (!empty($this->registeredVars)) {
2183 $this->injectVariables($this->registeredVars);
2186 $this->sourceParser = $this->parser;
2190 $this->formatter->block($this->scope);
2191 $out = ob_get_clean();
2192 setlocale(LC_NUMERIC, $locale);
2196 public function compileFile($fname, $outFname =
null)
2198 if (!is_readable($fname)) {
2199 throw new Exception(
'load error: failed to find '.$fname);
2202 $pi = pathinfo($fname);
2204 $oldImport = $this->importDir;
2206 $this->importDir = (array) $this->importDir;
2207 $this->importDir[] = $pi[
'dirname'].
'/';
2209 $this->addParsedFile($fname);
2211 $out = $this->compile(file_get_contents($fname), $fname);
2213 $this->importDir = $oldImport;
2215 if ($outFname !==
null) {
2216 return file_put_contents($outFname, $out);
2223 public function checkedCompile($in, $out)
2225 if (!is_file($out) || filemtime($in) > filemtime($out)) {
2226 $this->compileFile($in, $out);
2257 if (is_string($in)) {
2259 } elseif (is_array($in) && isset($in[
'root'])) {
2260 if ($force || !isset($in[
'files'])) {
2264 $root = $in[
'root'];
2265 } elseif (isset($in[
'files']) && is_array($in[
'files'])) {
2266 foreach ($in[
'files'] as $fname => $ftime) {
2267 if (!file_exists($fname) || filemtime($fname) > $ftime) {
2270 $root = $in[
'root'];
2281 if ($root !==
null) {
2284 $out[
'root'] = $root;
2285 $out[
'compiled'] = $this->compileFile($root);
2286 $out[
'files'] = $this->allParsedFiles();
2287 $out[
'updated'] = time();
2298 public function parse($str =
null, $initialVariables =
null)
2300 if (is_array($str)) {
2301 $initialVariables = $str;
2305 $oldVars = $this->registeredVars;
2306 if ($initialVariables !==
null) {
2307 $this->setVariables($initialVariables);
2311 if (empty($this->_parseFile)) {
2312 throw new exception(
"nothing to parse");
2315 $out = $this->compileFile($this->_parseFile);
2317 $out = $this->compile($str);
2320 $this->registeredVars = $oldVars;
2324 protected function makeParser($name)
2327 $parser->writeComments = $this->preserveComments;
2332 public function setFormatter($name)
2334 $this->formatterName = $name;
2337 protected function newFormatter()
2339 $className =
"lessc_formatter_lessjs";
2340 if (!empty($this->formatterName)) {
2341 if (!is_string($this->formatterName)) {
2342 return $this->formatterName;
2344 $className =
"lessc_formatter_$this->formatterName";
2347 return new $className;
2350 public function setPreserveComments($preserve)
2352 $this->preserveComments = $preserve;
2355 public function registerFunction($name, $func)
2357 $this->libFunctions[$name] = $func;
2360 public function unregisterFunction($name)
2362 unset($this->libFunctions[$name]);
2365 public function setVariables($variables)
2367 $this->registeredVars = array_merge($this->registeredVars, $variables);
2370 public function unsetVariable($name)
2372 unset($this->registeredVars[$name]);
2375 public function setImportDir($dirs)
2377 $this->importDir = (array) $dirs;
2380 public function addImportDir($dir)
2382 $this->importDir = (array) $this->importDir;
2383 $this->importDir[] = $dir;
2386 public function allParsedFiles()
2388 return $this->allParsedFiles;
2391 public function addParsedFile($file)
2393 $this->allParsedFiles[realpath($file)] = filemtime($file);
2401 if ($this->sourceLoc >= 0) {
2402 $this->sourceParser->throwError($msg, $this->sourceLoc);
2404 throw new exception($msg);
2409 public static function ccompile($in, $out, $less =
null)
2411 if ($less ===
null) {
2414 return $less->checkedCompile($in, $out);
2417 public static function cexecute($in, $force =
false, $less =
null)
2419 if ($less ===
null) {
2422 return $less->cachedCompile($in, $force);
2425 protected static $cssColors = array(
2426 'aliceblue' =>
'240,248,255',
2427 'antiquewhite' =>
'250,235,215',
2428 'aqua' =>
'0,255,255',
2429 'aquamarine' =>
'127,255,212',
2430 'azure' =>
'240,255,255',
2431 'beige' =>
'245,245,220',
2432 'bisque' =>
'255,228,196',
2434 'blanchedalmond' =>
'255,235,205',
2435 'blue' =>
'0,0,255',
2436 'blueviolet' =>
'138,43,226',
2437 'brown' =>
'165,42,42',
2438 'burlywood' =>
'222,184,135',
2439 'cadetblue' =>
'95,158,160',
2440 'chartreuse' =>
'127,255,0',
2441 'chocolate' =>
'210,105,30',
2442 'coral' =>
'255,127,80',
2443 'cornflowerblue' =>
'100,149,237',
2444 'cornsilk' =>
'255,248,220',
2445 'crimson' =>
'220,20,60',
2446 'cyan' =>
'0,255,255',
2447 'darkblue' =>
'0,0,139',
2448 'darkcyan' =>
'0,139,139',
2449 'darkgoldenrod' =>
'184,134,11',
2450 'darkgray' =>
'169,169,169',
2451 'darkgreen' =>
'0,100,0',
2452 'darkgrey' =>
'169,169,169',
2453 'darkkhaki' =>
'189,183,107',
2454 'darkmagenta' =>
'139,0,139',
2455 'darkolivegreen' =>
'85,107,47',
2456 'darkorange' =>
'255,140,0',
2457 'darkorchid' =>
'153,50,204',
2458 'darkred' =>
'139,0,0',
2459 'darksalmon' =>
'233,150,122',
2460 'darkseagreen' =>
'143,188,143',
2461 'darkslateblue' =>
'72,61,139',
2462 'darkslategray' =>
'47,79,79',
2463 'darkslategrey' =>
'47,79,79',
2464 'darkturquoise' =>
'0,206,209',
2465 'darkviolet' =>
'148,0,211',
2466 'deeppink' =>
'255,20,147',
2467 'deepskyblue' =>
'0,191,255',
2468 'dimgray' =>
'105,105,105',
2469 'dimgrey' =>
'105,105,105',
2470 'dodgerblue' =>
'30,144,255',
2471 'firebrick' =>
'178,34,34',
2472 'floralwhite' =>
'255,250,240',
2473 'forestgreen' =>
'34,139,34',
2474 'fuchsia' =>
'255,0,255',
2475 'gainsboro' =>
'220,220,220',
2476 'ghostwhite' =>
'248,248,255',
2477 'gold' =>
'255,215,0',
2478 'goldenrod' =>
'218,165,32',
2479 'gray' =>
'128,128,128',
2480 'green' =>
'0,128,0',
2481 'greenyellow' =>
'173,255,47',
2482 'grey' =>
'128,128,128',
2483 'honeydew' =>
'240,255,240',
2484 'hotpink' =>
'255,105,180',
2485 'indianred' =>
'205,92,92',
2486 'indigo' =>
'75,0,130',
2487 'ivory' =>
'255,255,240',
2488 'khaki' =>
'240,230,140',
2489 'lavender' =>
'230,230,250',
2490 'lavenderblush' =>
'255,240,245',
2491 'lawngreen' =>
'124,252,0',
2492 'lemonchiffon' =>
'255,250,205',
2493 'lightblue' =>
'173,216,230',
2494 'lightcoral' =>
'240,128,128',
2495 'lightcyan' =>
'224,255,255',
2496 'lightgoldenrodyellow' =>
'250,250,210',
2497 'lightgray' =>
'211,211,211',
2498 'lightgreen' =>
'144,238,144',
2499 'lightgrey' =>
'211,211,211',
2500 'lightpink' =>
'255,182,193',
2501 'lightsalmon' =>
'255,160,122',
2502 'lightseagreen' =>
'32,178,170',
2503 'lightskyblue' =>
'135,206,250',
2504 'lightslategray' =>
'119,136,153',
2505 'lightslategrey' =>
'119,136,153',
2506 'lightsteelblue' =>
'176,196,222',
2507 'lightyellow' =>
'255,255,224',
2508 'lime' =>
'0,255,0',
2509 'limegreen' =>
'50,205,50',
2510 'linen' =>
'250,240,230',
2511 'magenta' =>
'255,0,255',
2512 'maroon' =>
'128,0,0',
2513 'mediumaquamarine' =>
'102,205,170',
2514 'mediumblue' =>
'0,0,205',
2515 'mediumorchid' =>
'186,85,211',
2516 'mediumpurple' =>
'147,112,219',
2517 'mediumseagreen' =>
'60,179,113',
2518 'mediumslateblue' =>
'123,104,238',
2519 'mediumspringgreen' =>
'0,250,154',
2520 'mediumturquoise' =>
'72,209,204',
2521 'mediumvioletred' =>
'199,21,133',
2522 'midnightblue' =>
'25,25,112',
2523 'mintcream' =>
'245,255,250',
2524 'mistyrose' =>
'255,228,225',
2525 'moccasin' =>
'255,228,181',
2526 'navajowhite' =>
'255,222,173',
2527 'navy' =>
'0,0,128',
2528 'oldlace' =>
'253,245,230',
2529 'olive' =>
'128,128,0',
2530 'olivedrab' =>
'107,142,35',
2531 'orange' =>
'255,165,0',
2532 'orangered' =>
'255,69,0',
2533 'orchid' =>
'218,112,214',
2534 'palegoldenrod' =>
'238,232,170',
2535 'palegreen' =>
'152,251,152',
2536 'paleturquoise' =>
'175,238,238',
2537 'palevioletred' =>
'219,112,147',
2538 'papayawhip' =>
'255,239,213',
2539 'peachpuff' =>
'255,218,185',
2540 'peru' =>
'205,133,63',
2541 'pink' =>
'255,192,203',
2542 'plum' =>
'221,160,221',
2543 'powderblue' =>
'176,224,230',
2544 'purple' =>
'128,0,128',
2546 'rosybrown' =>
'188,143,143',
2547 'royalblue' =>
'65,105,225',
2548 'saddlebrown' =>
'139,69,19',
2549 'salmon' =>
'250,128,114',
2550 'sandybrown' =>
'244,164,96',
2551 'seagreen' =>
'46,139,87',
2552 'seashell' =>
'255,245,238',
2553 'sienna' =>
'160,82,45',
2554 'silver' =>
'192,192,192',
2555 'skyblue' =>
'135,206,235',
2556 'slateblue' =>
'106,90,205',
2557 'slategray' =>
'112,128,144',
2558 'slategrey' =>
'112,128,144',
2559 'snow' =>
'255,250,250',
2560 'springgreen' =>
'0,255,127',
2561 'steelblue' =>
'70,130,180',
2562 'tan' =>
'210,180,140',
2563 'teal' =>
'0,128,128',
2564 'thistle' =>
'216,191,216',
2565 'tomato' =>
'255,99,71',
2566 'transparent' =>
'0,0,0,0',
2567 'turquoise' =>
'64,224,208',
2568 'violet' =>
'238,130,238',
2569 'wheat' =>
'245,222,179',
2570 'white' =>
'255,255,255',
2571 'whitesmoke' =>
'245,245,245',
2572 'yellow' =>
'255,255,0',
2573 'yellowgreen' =>
'154,205,50'
2581 protected static $nextBlockId = 0;
2583 protected static $precedence = array(
2597 protected static $whitePattern;
2598 protected static $commentMulti;
2600 protected static $commentSingle =
"//";
2601 protected static $commentMultiLeft =
"/*";
2602 protected static $commentMultiRight =
"*/";
2605 protected static $operatorString;
2608 protected static $supressDivisionProps =
2609 array(
'/border-radius$/i',
'/^font$/i');
2611 protected $blockDirectives = array(
"font-face",
"keyframes",
"page",
"-moz-document",
"viewport",
"-moz-viewport",
"-o-viewport",
"-ms-viewport");
2612 protected $lineDirectives = array(
"charset");
2626 protected static $literalCache = array();
2628 public function __construct($lessc, $sourceName =
null)
2630 $this->eatWhiteDefault =
true;
2632 $this->lessc = $lessc;
2634 $this->sourceName = $sourceName;
2636 $this->writeComments =
false;
2638 if (!self::$operatorString) {
2639 self::$operatorString =
2640 '('.implode(
'|', array_map(
2641 array(
'lessc',
'preg_quote'),
2642 array_keys(self::$precedence)
2645 $commentSingle = lessc::preg_quote(self::$commentSingle);
2646 $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
2647 $commentMultiRight = lessc::preg_quote(self::$commentMultiRight);
2649 self::$commentMulti = $commentMultiLeft.
'.*?'.$commentMultiRight;
2650 self::$whitePattern =
'/'.$commentSingle.
'[^\n]*\s*|('.self::$commentMulti.
')\s*|\s+/Ais';
2667 $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
2668 $this->pushSpecialBlock(
"root");
2669 $this->eatWhiteDefault =
true;
2670 $this->seenComments = array();
2677 $this->whitespace();
2682 if ($this->count != strlen($this->buffer)) {
2683 $this->throwError(
'parse error count '.$this->count.
' != len buffer '.strlen($this->buffer));
2687 if (!property_exists($this->env,
'parent') || !is_null($this->env->parent)) {
2688 throw new exception(
'parse error: unclosed block');
2732 if (empty($this->buffer)) {
2737 if ($this->whitespace()) {
2742 if ($this->keyword($key) && $this->
assign() &&
2743 $this->propertyValue($value, $key) && $this->end()
2745 $this->append(array(
'assign', $key, $value), $s);
2753 if ($this->literal(
'@',
false)) {
2757 if ($this->literal(
'@media')) {
2758 if (($this->mediaQueryList($mediaQueries) ||
true)
2759 && $this->literal(
'{')
2761 $media = $this->pushSpecialBlock(
"media");
2762 $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
2770 if ($this->literal(
"@",
false) && $this->keyword($dirName)) {
2771 if ($this->isDirective($dirName, $this->blockDirectives)) {
2772 if (($this->openString(
"{", $dirValue,
null, array(
";")) ||
true) &&
2775 $dir = $this->pushSpecialBlock(
"directive");
2776 $dir->name = $dirName;
2777 if (isset($dirValue)) {
2778 $dir->value = $dirValue;
2782 } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
2783 if ($this->propertyValue($dirValue) && $this->end()) {
2784 $this->append(array(
"directive", $dirName, $dirValue));
2794 if ($this->variable($var) && $this->
assign() &&
2795 $this->propertyValue($value) && $this->end()
2797 $this->append(array(
'assign', $var, $value), $s);
2803 if ($this->
import($importValue)) {
2804 $this->append($importValue, $s);
2809 if ($this->tag($tag,
true) && $this->argumentDef($args, $isVararg) &&
2810 ($this->guards($guards) ||
true) &&
2813 $block = $this->pushBlock($this->fixTags(array($tag)));
2814 $block->args = $args;
2815 $block->isVararg = $isVararg;
2816 if (!empty($guards)) {
2817 $block->guards = $guards;
2825 if ($this->tags($tags) && $this->literal(
'{',
false)) {
2826 $tags = $this->fixTags($tags);
2827 $this->pushBlock($tags);
2834 if ($this->literal(
'}',
false)) {
2836 $block = $this->pop();
2837 }
catch (exception $e) {
2839 $this->throwError($e->getMessage());
2843 if (is_null($block->type)) {
2845 if (!isset($block->args)) {
2846 foreach ($block->tags as $tag) {
2847 if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix) {
2854 foreach ($block->tags as $tag) {
2855 if (is_string($tag)) {
2856 $this->env->children[$tag][] = $block;
2862 $this->append(array(
'block', $block), $s);
2867 $this->whitespace();
2872 if ($this->mixinTags($tags) &&
2873 ($this->argumentDef($argv, $isVararg) ||
true) &&
2874 ($this->keyword($suffix) ||
true) && $this->end()
2876 $tags = $this->fixTags($tags);
2877 $this->append(array(
'mixin', $tags, $argv, $suffix), $s);
2884 if ($this->literal(
';')) {
2891 protected function isDirective($dirname, $directives)
2896 array_map(array(
"lessc",
"preg_quote"), $directives)
2898 $pattern =
'/^(-[a-z-]+-)?('.$pattern.
')$/i';
2900 return preg_match($pattern, $dirname);
2903 protected function fixTags($tags)
2906 foreach ($tags as &$tag) {
2907 if ($tag[0] == $this->lessc->vPrefix) {
2908 $tag[0] = $this->lessc->mPrefix;
2915 protected function expressionList(&$exps)
2923 if (count($values) == 0) {
2927 $exps = lessc::compressList($values,
' ');
2937 if ($this->value($lhs)) {
2941 if (!empty($this->env->supressedDivision)) {
2942 unset($this->env->supressedDivision);
2944 if ($this->literal(
"/") && $this->value($rhs)) {
2945 $out = array(
"list",
"",
2946 array($out, array(
"keyword",
"/"), $rhs));
2962 $this->inExp =
true;
2963 $ss = $this->seek();
2966 $whiteBefore = isset($this->buffer[$this->count - 1]) &&
2967 ctype_space($this->buffer[$this->count - 1]);
2973 if ($this->match(self::$operatorString.($needWhite ?
'\s' :
''), $m) && self::$precedence[$m[1]] >= $minP) {
2974 if (!$this->inParens && isset($this->env->currentProperty) && $m[1] ==
"/" && empty($this->env->supressedDivision)) {
2975 foreach (self::$supressDivisionProps as $pattern) {
2976 if (preg_match($pattern, $this->env->currentProperty)) {
2977 $this->env->supressedDivision =
true;
2984 $whiteAfter = isset($this->buffer[$this->count - 1]) &&
2985 ctype_space($this->buffer[$this->count - 1]);
2987 if (!$this->value($rhs)) {
2992 if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
2993 $rhs = $this->
expHelper($rhs, self::$precedence[$next[1]]);
2996 $lhs = array(
'expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
2997 $ss = $this->seek();
3011 public function propertyValue(&$value, $keyName =
null)
3015 if ($keyName !==
null) {
3016 $this->env->currentProperty = $keyName;
3020 while ($this->expressionList($v)) {
3023 if (!$this->literal(
',')) {
3032 if ($keyName !==
null) {
3033 unset($this->env->currentProperty);
3036 if (count($values) == 0) {
3040 $value = lessc::compressList($values,
', ');
3044 protected function parenValue(&$out)
3049 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] !=
"(") {
3054 if ($this->literal(
"(") &&
3055 ($this->inParens =
true) && $this->
expression($exp) &&
3070 protected function value(&$value)
3075 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] ==
"-") {
3077 if ($this->literal(
"-",
false) &&
3078 (($this->variable($inner) && $inner = array(
"variable", $inner)) ||
3079 $this->unit($inner) ||
3080 $this->parenValue($inner))
3082 $value = array(
"unary",
"-", $inner);
3089 if ($this->parenValue($value)) {
3092 if ($this->unit($value)) {
3095 if ($this->color($value)) {
3098 if ($this->func($value)) {
3101 if ($this->
string($value)) {
3105 if ($this->keyword($word)) {
3106 $value = array(
'keyword', $word);
3111 if ($this->variable($var)) {
3112 $value = array(
'variable', $var);
3117 if ($this->literal(
"~") && $this->
string($str)) {
3118 $value = array(
"escape", $str);
3125 if ($this->literal(
'\\') && $this->match(
'([0-9]+)', $m)) {
3126 $value = array(
'keyword',
'\\'.$m[1]);
3136 protected function import(&$out)
3138 if (!$this->literal(
'@import')) {
3146 if ($this->propertyValue($value)) {
3147 $out = array(
"import", $value);
3152 protected function mediaQueryList(&$out)
3154 if ($this->genericList($list,
"mediaQuery",
",",
false)) {
3161 protected function mediaQuery(&$out)
3165 $expressions =
null;
3168 if (($this->literal(
"only") && ($only =
true) || $this->literal(
"not") && ($not =
true) ||
true) && $this->keyword($mediaType)) {
3169 $prop = array(
"mediaType");
3176 $prop[] = $mediaType;
3183 if (!empty($mediaType) && !$this->literal(
"and")) {
3186 $this->genericList($expressions,
"mediaExpression",
"and",
false);
3187 if (is_array($expressions)) {
3188 $parts = array_merge($parts, $expressions[2]);
3192 if (count($parts) == 0) {
3201 protected function mediaExpression(&$out)
3205 if ($this->literal(
"(") &&
3206 $this->keyword($feature) &&
3207 ($this->literal(
":") && $this->
expression($value) ||
true) &&
3210 $out = array(
"mediaExp", $feature);
3215 } elseif ($this->variable($variable)) {
3216 $out = array(
'variable', $variable);
3225 protected function openString($end, &$out, $nestingOpen =
null, $rejectStrs =
null)
3227 $oldWhite = $this->eatWhiteDefault;
3228 $this->eatWhiteDefault =
false;
3230 $stop = array(
"'",
'"',
"@{", $end);
3231 $stop = array_map(array(
"lessc",
"preg_quote"), $stop);
3234 if (!is_null($rejectStrs)) {
3235 $stop = array_merge($stop, $rejectStrs);
3238 $patt =
'(.*?)('.implode(
"|", $stop).
')';
3243 while ($this->match($patt, $m,
false)) {
3244 if (!empty($m[1])) {
3247 $nestingLevel += substr_count($m[1], $nestingOpen);
3253 $this->count -= strlen($tok);
3255 if ($nestingLevel == 0) {
3262 if (($tok ==
"'" || $tok ==
'"') && $this->
string($str)) {
3267 if ($tok ==
"@{" && $this->interpolation($inter)) {
3268 $content[] = $inter;
3272 if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
3277 $this->count += strlen($tok);
3280 $this->eatWhiteDefault = $oldWhite;
3282 if (count($content) == 0) {
3287 if (is_string(end($content))) {
3288 $content[count($content) - 1] = rtrim(end($content));
3291 $out = array(
"string",
"", $content);
3295 protected function string(&$out)
3298 if ($this->literal(
'"',
false)) {
3300 } elseif ($this->literal(
"'",
false)) {
3309 $patt =
'([^\n]*?)(@\{|\\\\|'.
3310 lessc::preg_quote($delim).
')';
3312 $oldWhite = $this->eatWhiteDefault;
3313 $this->eatWhiteDefault =
false;
3315 while ($this->match($patt, $m,
false)) {
3317 if ($m[2] ==
"@{") {
3318 $this->count -= strlen($m[2]);
3319 if ($this->interpolation($inter)) {
3320 $content[] = $inter;
3322 $this->count += strlen($m[2]);
3325 } elseif ($m[2] ==
'\\') {
3327 if ($this->literal($delim,
false)) {
3328 $content[] = $delim;
3331 $this->count -= strlen($delim);
3336 $this->eatWhiteDefault = $oldWhite;
3338 if ($this->literal($delim)) {
3339 $out = array(
"string", $delim, $content);
3347 protected function interpolation(&$out)
3349 $oldWhite = $this->eatWhiteDefault;
3350 $this->eatWhiteDefault =
true;
3353 if ($this->literal(
"@{") &&
3354 $this->openString(
"}", $interp,
null, array(
"'",
'"',
";")) &&
3355 $this->literal(
"}",
false)
3357 $out = array(
"interpolate", $interp);
3358 $this->eatWhiteDefault = $oldWhite;
3359 if ($this->eatWhiteDefault) {
3360 $this->whitespace();
3365 $this->eatWhiteDefault = $oldWhite;
3370 protected function unit(&$unit)
3373 if (isset($this->buffer[$this->count])) {
3374 $char = $this->buffer[$this->count];
3375 if (!ctype_digit($char) && $char !=
".") {
3380 if ($this->match(
'([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
3381 $unit = array(
"number", $m[1], empty($m[2]) ?
"" : $m[2]);
3388 protected function color(&$out)
3390 if ($this->match(
'(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
3391 if (strlen($m[1]) > 7) {
3392 $out = array(
"string",
"", array($m[1]));
3394 $out = array(
"raw_color", $m[1]);
3407 protected function argumentDef(&$args, &$isVararg)
3410 if (!$this->literal(
'(')) {
3416 $method =
"expressionList";
3420 if ($this->literal(
"...")) {
3425 if ($this->$method($value)) {
3426 if ($value[0] ==
"variable") {
3427 $arg = array(
"arg", $value[1]);
3428 $ss = $this->seek();
3430 if ($this->
assign() && $this->$method($rhs)) {
3434 if ($this->literal(
"...")) {
3446 $values[] = array(
"lit", $value);
3451 if (!$this->literal($delim)) {
3452 if ($delim ==
"," && $this->literal(
";")) {
3455 $method =
"propertyValue";
3458 if (isset($values[1])) {
3460 foreach ($values as $i => $arg) {
3464 $this->throwError(
"Cannot mix ; and , as delimiter types");
3466 $newList[] = $arg[2];
3469 $newList[] = $arg[1];
3472 $this->throwError(
"Unexpected rest before semicolon");
3476 $newList = array(
"list",
", ", $newList);
3478 switch ($values[0][0]) {
3480 $newArg = array(
"arg", $values[0][1], $newList);
3483 $newArg = array(
"lit", $newList);
3486 } elseif ($values) {
3487 $newArg = $values[0];
3491 $values = array($newArg);
3499 if (!$this->literal(
')')) {
3511 protected function tags(&$tags, $simple =
false, $delim =
',')
3514 while ($this->tag($tt, $simple)) {
3516 if (!$this->literal($delim)) {
3520 if (count($tags) == 0) {
3529 protected function mixinTags(&$tags)
3532 while ($this->tag($tt,
true)) {
3534 $this->literal(
">");
3545 protected function tagBracket(&$parts, &$hasExpression)
3548 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] !=
"[") {
3554 $hasInterpolation =
false;
3556 if ($this->literal(
"[",
false)) {
3557 $attrParts = array(
"[");
3560 if ($this->literal(
"]",
false)) {
3565 if ($this->match(
'\s+', $m)) {
3569 if ($this->
string($str)) {
3571 foreach ($str[2] as &$chunk) {
3572 $chunk = str_replace($this->lessc->parentSelector,
"$&$", $chunk);
3575 $attrParts[] = $str;
3576 $hasInterpolation =
true;
3580 if ($this->keyword($word)) {
3581 $attrParts[] = $word;
3585 if ($this->interpolation($inter)) {
3586 $attrParts[] = $inter;
3587 $hasInterpolation =
true;
3592 if ($this->match(
'[|-~\$\*\^=]+', $m)) {
3593 $attrParts[] = $m[0];
3600 if ($this->literal(
"]",
false)) {
3602 foreach ($attrParts as $part) {
3605 $hasExpression = $hasExpression || $hasInterpolation;
3616 protected function tag(&$tag, $simple =
false)
3619 $chars =
'^@,:;{}\][>\(\) "\'';
3621 $chars =
'^@,;{}["\'';
3625 $hasExpression =
false;
3627 while ($this->tagBracket($parts, $hasExpression));
3629 $oldWhite = $this->eatWhiteDefault;
3630 $this->eatWhiteDefault =
false;
3633 if ($this->match(
'(['.$chars.
'0-9]['.$chars.
']*)', $m)) {
3639 while ($this->tagBracket($parts, $hasExpression));
3643 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] ==
"@") {
3644 if ($this->interpolation($interp)) {
3645 $hasExpression =
true;
3651 if ($this->literal(
"@")) {
3657 if ($this->unit($unit)) {
3658 $parts[] = $unit[1];
3659 $parts[] = $unit[2];
3666 $this->eatWhiteDefault = $oldWhite;
3672 if ($hasExpression) {
3673 $tag = array(
"exp", array(
"string",
"", $parts));
3675 $tag = trim(implode($parts));
3678 $this->whitespace();
3683 protected function func(&$func)
3687 if ($this->match(
'(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal(
'(')) {
3690 $sPreArgs = $this->seek();
3694 $ss = $this->seek();
3696 if ($this->keyword($name) && $this->literal(
'=') && $this->expressionList($value)) {
3697 $args[] = array(
"string",
"", array($name,
"=", $value));
3700 if ($this->expressionList($value)) {
3705 if (!$this->literal(
',')) {
3709 $args = array(
'list',
',', $args);
3711 if ($this->literal(
')')) {
3712 $func = array(
'function', $fname, $args);
3714 } elseif ($fname ==
'url') {
3716 $this->seek($sPreArgs);
3717 if ($this->openString(
")", $string) && $this->literal(
")")) {
3718 $func = array(
'function', $fname, $string);
3729 protected function variable(&$name)
3732 if ($this->literal($this->lessc->vPrefix,
false) &&
3733 ($this->variable($sub) || $this->keyword($name))
3736 $name = array(
'variable', $sub);
3738 $name = $this->lessc->vPrefix.$name;
3755 $this->currentProperty = $name;
3757 return $this->literal(
':') || $this->literal(
'=');
3761 protected function keyword(&$word)
3763 if ($this->match(
'([\w_\-\*!"][\w\-_"]*)', $m)) {
3771 protected function end()
3773 if ($this->literal(
';',
false)) {
3775 } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] ==
'}') {
3782 protected function guards(&$guards)
3786 if (!$this->literal(
"when")) {
3793 while ($this->guardGroup($g)) {
3795 if (!$this->literal(
",")) {
3800 if (count($guards) == 0) {
3811 protected function guardGroup(&$guardGroup)
3814 $guardGroup = array();
3815 while ($this->guard($guard)) {
3816 $guardGroup[] = $guard;
3817 if (!$this->literal(
"and")) {
3822 if (count($guardGroup) == 0) {
3831 protected function guard(&$guard)
3834 $negate = $this->literal(
"not");
3836 if ($this->literal(
"(") && $this->
expression($exp) && $this->literal(
")")) {
3839 $guard = array(
"negate", $guard);
3850 protected function literal($what, $eatWhitespace =
null)
3852 if ($eatWhitespace ===
null) {
3853 $eatWhitespace = $this->eatWhiteDefault;
3857 if (!isset($what[1]) && isset($this->buffer[$this->count])) {
3858 if ($this->buffer[$this->count] == $what) {
3859 if (!$eatWhitespace) {
3869 if (!isset(self::$literalCache[$what])) {
3870 self::$literalCache[$what] = lessc::preg_quote($what);
3873 return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
3876 protected function genericList(&$out, $parseItem, $delim =
"", $flatten =
true)
3880 while ($this->$parseItem($value)) {
3883 if (!$this->literal($delim)) {
3889 if (count($items) == 0) {
3894 if ($flatten && count($items) == 1) {
3897 $out = array(
"list", $delim, $items);
3907 protected function to($what, &$out, $until =
false, $allowNewline =
false)
3909 if (is_string($allowNewline)) {
3910 $validChars = $allowNewline;
3912 $validChars = $allowNewline ?
"." :
"[^\n]";
3914 if (!$this->match(
'('.$validChars.
'*?)'.lessc::preg_quote($what), $m, !$until)) {
3918 $this->count -= strlen($what);
3925 protected function match($regex, &$out, $eatWhitespace =
null)
3927 if ($eatWhitespace ===
null) {
3928 $eatWhitespace = $this->eatWhiteDefault;
3931 $r =
'/'.$regex.($eatWhitespace && !$this->writeComments ?
'\s*' :
'').
'/Ais';
3932 if (preg_match($r, $this->buffer, $out,
null, $this->count)) {
3933 $this->count += strlen($out[0]);
3934 if ($eatWhitespace && $this->writeComments) {
3935 $this->whitespace();
3943 protected function whitespace()
3945 if ($this->writeComments) {
3947 while (preg_match(self::$whitePattern, $this->buffer, $m,
null, $this->count)) {
3948 if (isset($m[1]) && empty($this->seenComments[$this->count])) {
3949 $this->append(array(
"comment", $m[1]));
3950 $this->seenComments[$this->count] =
true;
3952 $this->count += strlen($m[0]);
3957 $this->match(
"", $m);
3958 return strlen($m[0]) > 0;
3963 protected function peek($regex, &$out =
null, $from =
null)
3965 if (is_null($from)) {
3966 $from = $this->count;
3968 $r =
'/'.$regex.
'/Ais';
3969 $result = preg_match($r, $this->buffer, $out,
null, $from);
3975 protected function seek($where =
null)
3977 if ($where ===
null) {
3978 return $this->count;
3980 $this->count = $where;
3987 public function throwError($msg =
"parse error", $count =
null)
3989 $count = is_null($count) ? $this->count : $count;
3991 $line = $this->line +
3992 substr_count(substr($this->buffer, 0, $count),
"\n");
3994 if (!empty($this->sourceName)) {
3995 $loc =
"$this->sourceName on line $line";
3997 $loc =
"line: $line";
4001 if ($this->peek(
"(.*?)(\n|$)", $m, $count)) {
4002 throw new exception(
"$msg: failed at `$m[1]` $loc");
4004 throw new exception(
"$msg: $loc");
4008 protected function pushBlock($selectors =
null, $type =
null)
4011 $b->parent = $this->env;
4014 $b->id = self::$nextBlockId++;
4016 $b->isVararg =
false;
4017 $b->tags = $selectors;
4019 $b->props = array();
4020 $b->children = array();
4027 protected function pushSpecialBlock($type)
4029 return $this->pushBlock(
null, $type);
4033 protected function append($prop, $pos =
null)
4035 if ($pos !==
null) {
4038 $this->env->props[] = $prop;
4042 protected function pop()
4045 $this->env = $this->env->parent;
4051 protected function removeComments($text)
4054 'url(',
'//',
'/*',
'"',
"'"
4061 foreach ($look as $token) {
4062 $pos = strpos($text, $token);
4063 if ($pos !==
false) {
4064 if (!isset($min) || $pos < $min[1]) {
4065 $min = array($token, $pos);
4070 if (is_null($min)) {
4079 if (preg_match(
'/url\(.*?\)/', $text, $m, 0, $count)) {
4080 $count += strlen($m[0]) - strlen($min[0]);
4085 if (preg_match(
'/'.$min[0].
'.*?(?<!\\\\)'.$min[0].
'/', $text, $m, 0, $count)) {
4086 $count += strlen($m[0]) - 1;
4090 $skip = strpos($text,
"\n", $count);
4091 if ($skip ===
false) {
4092 $skip = strlen($text) - $count;
4098 if (preg_match(
'/\/\*.*?\*\//s', $text, $m, 0, $count)) {
4099 $skip = strlen($m[0]);
4100 $newlines = substr_count($m[0],
"\n");
4106 $count += strlen($min[0]);
4109 $out .= substr($text, 0, $count).str_repeat(
"\n", $newlines);
4110 $text = substr($text, $count + $skip);
4121 public $indentChar =
" ";
4123 public $break =
"\n";
4124 public $open =
" {";
4125 public $close =
"}";
4126 public $selectorSeparator =
", ";
4127 public $assignSeparator =
":";
4129 public $openSingle =
" { ";
4130 public $closeSingle =
" }";
4132 public $disableSingle =
false;
4133 public $breakSelectors =
false;
4135 public $compressColors =
false;
4137 public function __construct()
4139 $this->indentLevel = 0;
4142 public function indentStr($n = 0)
4144 return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
4147 public function property($name, $value)
4149 return $name.$this->assignSeparator.$value.
";";
4152 protected function isEmpty($block)
4154 if (empty($block->lines)) {
4155 foreach ($block->children as $child) {
4156 if (!$this->isEmpty($child)) {
4166 public function block($block)
4168 if ($this->isEmpty($block)) {
4172 $inner = $pre = $this->indentStr();
4174 $isSingle = !$this->disableSingle &&
4175 is_null($block->type) && count($block->lines) == 1;
4177 if (!empty($block->selectors)) {
4178 $this->indentLevel++;
4180 if ($this->breakSelectors) {
4181 $selectorSeparator = $this->selectorSeparator.$this->break.$pre;
4183 $selectorSeparator = $this->selectorSeparator;
4187 implode($selectorSeparator, $block->selectors);
4189 echo $this->openSingle;
4192 echo $this->open.$this->break;
4193 $inner = $this->indentStr();
4197 if (!empty($block->lines)) {
4198 $glue = $this->
break.$inner;
4199 echo $inner.implode($glue, $block->lines);
4200 if (!$isSingle && !empty($block->children)) {
4205 foreach ($block->children as $child) {
4206 $this->block($child);
4209 if (!empty($block->selectors)) {
4210 if (!$isSingle && empty($block->children)) {
4215 echo $this->closeSingle.$this->break;
4217 echo $pre.$this->close.$this->break;
4220 $this->indentLevel--;
4230 public $disableSingle =
true;
4232 public $selectorSeparator =
",";
4233 public $assignSeparator =
":";
4235 public $compressColors =
true;
4237 public function indentStr($n = 0)
4248 public $disableSingle =
true;
4249 public $breakSelectors =
true;
4250 public $assignSeparator =
": ";
4251 public $selectorSeparator =
",";
lessphp v0.5.0 http://leafo.net/lessphp
compileBlock($block)
Recursively compiles a block.
__construct($fname=null)
Initialize any static state, can initialize parser for a file $opts isn't used yet.
cachedCompile($in, $force=false)
Execute lessphp on a .less file or a lessphp cache structure.
lib_data_uri($value)
Given an url, decide whether to output a regular link or the base64-encoded contents of the file.
funcToColor($func)
Convert the rgb, rgba, hsl color literals of function type as returned by the parser into values of c...
deduplicate($lines)
Deduplicate lines in a block.
lib_shade($args)
Mix color with black in variable proportion.
fileExists($name)
fileExists
toRGB($color)
Converts a hsl array into a color value in rgb.
throwError($msg=null)
Uses the current value of $this->count to show line and line number.
colorArgs($args)
Helper function to get arguments for color manipulation functions.
compileValue($value)
Compiles a primitive value into a CSS property value.
lib_tint($args)
Mix color with white in variable proportion.
expHelper($lhs, $minP)
recursively parse infix equation with $lhs at precedence $minP
parseChunk()
Parse a single chunk off the head of the buffer and append it to the current parse environment.
assign($name=null)
Consume an assignment operator Can optionally take a name that will be set to the current property na...
parse($buffer)
Parse a string.
$inParens
if we are in parens we can be more liberal with whitespace around operators because it must evaluate ...
expression(&$out)
Attempt to consume an expression.