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];
1017 protected function lib_isnumber($value)
1019 return $this->toBool($value[0] ==
"number");
1022 protected function lib_isstring($value)
1024 return $this->toBool($value[0] ==
"string");
1027 protected function lib_iscolor($value)
1029 return $this->toBool($this->coerceColor($value));
1032 protected function lib_iskeyword($value)
1034 return $this->toBool($value[0] ==
"keyword");
1037 protected function lib_ispixel($value)
1039 return $this->toBool($value[0] ==
"number" && $value[2] ==
"px");
1042 protected function lib_ispercentage($value)
1044 return $this->toBool($value[0] ==
"number" && $value[2] ==
"%");
1047 protected function lib_isem($value)
1049 return $this->toBool($value[0] ==
"number" && $value[2] ==
"em");
1052 protected function lib_isrem($value)
1054 return $this->toBool($value[0] ==
"number" && $value[2] ==
"rem");
1057 protected function lib_rgbahex($color)
1059 $color = $this->coerceColor($color);
1060 if (is_null($color)) {
1061 $this->
throwError(
"color expected for rgbahex");
1065 "#%02x%02x%02x%02x",
1066 isset($color[4]) ? $color[4] * 255 : 255,
1073 protected function lib_argb($color)
1075 return $this->lib_rgbahex($color);
1086 $mime = ($value[0] ===
'list') ? $value[2][0][2] :
null;
1087 $url = ($value[0] ===
'list') ? $value[2][1][2][0] : $value[2][0];
1089 $fullpath = $this->findImport($url);
1091 if ($fullpath && ($fsize = filesize($fullpath)) !==
false) {
1093 if ($fsize / 1024 < 32) {
1094 if (is_null($mime)) {
1095 if (class_exists(
'finfo')) {
1096 $finfo =
new finfo(FILEINFO_MIME);
1097 $mime = explode(
'; ', $finfo->file($fullpath));
1099 } elseif (function_exists(
'mime_content_type')) {
1100 $mime = mime_content_type($fullpath);
1104 if (!is_null($mime)) {
1105 $url = sprintf(
'data:%s;base64,%s', $mime, base64_encode(file_get_contents($fullpath)));
1110 return 'url("'.$url.
'")';
1114 protected function lib_e($arg)
1119 if (isset($items[0])) {
1120 return $this->lib_e($items[0]);
1133 protected function lib__sprintf($args)
1135 if ($args[0] !=
"list") {
1139 $string = array_shift($values);
1140 $template = $this->
compileValue($this->lib_e($string));
1144 if (preg_match_all(
'/%[dsa]/', $template, $m)) {
1145 foreach ($m[0] as $match) {
1146 $val = isset($values[$i]) ?
1147 $this->reduce($values[$i]) : array(
'keyword',
'');
1150 if ($color = $this->coerceColor($val)) {
1156 $template = preg_replace(
1157 '/'.self::preg_quote($match).
'/',
1165 $d = $string[0] ==
"string" ? $string[1] :
'"';
1166 return array(
"string", $d, array($template));
1169 protected function lib_floor($arg)
1171 $value = $this->assertNumber($arg);
1172 return array(
"number", floor($value), $arg[2]);
1175 protected function lib_ceil($arg)
1177 $value = $this->assertNumber($arg);
1178 return array(
"number", ceil($value), $arg[2]);
1181 protected function lib_round($arg)
1183 if ($arg[0] !=
"list") {
1184 $value = $this->assertNumber($arg);
1185 return array(
"number", round($value), $arg[2]);
1187 $value = $this->assertNumber($arg[2][0]);
1188 $precision = $this->assertNumber($arg[2][1]);
1189 return array(
"number", round($value, $precision), $arg[2][0][2]);
1193 protected function lib_unit($arg)
1195 if ($arg[0] ==
"list") {
1196 list($number, $newUnit) = $arg[2];
1197 return array(
"number", $this->assertNumber($number),
1200 return array(
"number", $this->assertNumber($arg),
"");
1210 if ($args[0] !=
'list' || count($args[2]) < 2) {
1211 return array(array(
'color', 0, 0, 0), 0);
1213 list($color, $delta) = $args[2];
1214 $color = $this->assertColor($color);
1215 $delta = floatval($delta[1]);
1217 return array($color, $delta);
1220 protected function lib_darken($args)
1222 list($color, $delta) = $this->
colorArgs($args);
1224 $hsl = $this->toHSL($color);
1225 $hsl[3] = $this->clamp($hsl[3] - $delta, 100);
1226 return $this->
toRGB($hsl);
1229 protected function lib_lighten($args)
1231 list($color, $delta) = $this->
colorArgs($args);
1233 $hsl = $this->toHSL($color);
1234 $hsl[3] = $this->clamp($hsl[3] + $delta, 100);
1235 return $this->
toRGB($hsl);
1238 protected function lib_saturate($args)
1240 list($color, $delta) = $this->
colorArgs($args);
1242 $hsl = $this->toHSL($color);
1243 $hsl[2] = $this->clamp($hsl[2] + $delta, 100);
1244 return $this->
toRGB($hsl);
1247 protected function lib_desaturate($args)
1249 list($color, $delta) = $this->
colorArgs($args);
1251 $hsl = $this->toHSL($color);
1252 $hsl[2] = $this->clamp($hsl[2] - $delta, 100);
1253 return $this->
toRGB($hsl);
1256 protected function lib_spin($args)
1258 list($color, $delta) = $this->
colorArgs($args);
1260 $hsl = $this->toHSL($color);
1262 $hsl[1] = $hsl[1] + $delta % 360;
1267 return $this->
toRGB($hsl);
1270 protected function lib_fadeout($args)
1272 list($color, $delta) = $this->
colorArgs($args);
1273 $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) - $delta / 100);
1277 protected function lib_fadein($args)
1279 list($color, $delta) = $this->
colorArgs($args);
1280 $color[4] = $this->clamp((isset($color[4]) ? $color[4] : 1) + $delta / 100);
1284 protected function lib_hue($color)
1286 $hsl = $this->toHSL($this->assertColor($color));
1287 return round($hsl[1]);
1290 protected function lib_saturation($color)
1292 $hsl = $this->toHSL($this->assertColor($color));
1293 return round($hsl[2]);
1296 protected function lib_lightness($color)
1298 $hsl = $this->toHSL($this->assertColor($color));
1299 return round($hsl[3]);
1304 protected function lib_alpha($value)
1306 if (!is_null($color = $this->coerceColor($value))) {
1307 return isset($color[4]) ? $color[4] : 1;
1313 protected function lib_fade($args)
1315 list($color, $alpha) = $this->
colorArgs($args);
1316 $color[4] = $this->clamp($alpha / 100.0);
1320 protected function lib_percentage($arg)
1322 $num = $this->assertNumber($arg);
1323 return array(
"number", $num * 100,
"%");
1339 $white = [
'color', 255, 255, 255];
1340 if ($args[0] ==
'color') {
1341 return $this->lib_mix([
'list',
',', [$white, $args]]);
1342 } elseif ($args[0] ==
"list" && count($args[2]) == 2) {
1343 return $this->lib_mix([$args[0], $args[1], [$white, $args[2][0], $args[2][1]]]);
1345 $this->
throwError(
"tint expects (color, weight)");
1362 $black = [
'color', 0, 0, 0];
1363 if ($args[0] ==
'color') {
1364 return $this->lib_mix([
'list',
',', [$black, $args]]);
1365 } elseif ($args[0] ==
"list" && count($args[2]) == 2) {
1366 return $this->lib_mix([$args[0], $args[1], [$black, $args[2][0], $args[2][1]]]);
1368 $this->
throwError(
"shade expects (color, weight)");
1375 protected function lib_mix($args)
1377 if ($args[0] !=
"list" || count($args[2]) < 2) {
1378 $this->
throwError(
"mix expects (color1, color2, weight)");
1381 list($first, $second) = $args[2];
1382 $first = $this->assertColor($first);
1383 $second = $this->assertColor($second);
1385 $first_a = $this->lib_alpha($first);
1386 $second_a = $this->lib_alpha($second);
1388 if (isset($args[2][2])) {
1389 $weight = $args[2][2][1] / 100.0;
1394 $w = $weight * 2 - 1;
1395 $a = $first_a - $second_a;
1397 $w1 = (($w * $a == -1 ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2.0;
1400 $new = array(
'color',
1401 $w1 * $first[1] + $w2 * $second[1],
1402 $w1 * $first[2] + $w2 * $second[2],
1403 $w1 * $first[3] + $w2 * $second[3],
1406 if ($first_a != 1.0 || $second_a != 1.0) {
1407 $new[] = $first_a * $weight + $second_a * ($weight - 1);
1410 return $this->fixColor($new);
1413 protected function lib_contrast($args)
1415 $darkColor = array(
'color', 0, 0, 0);
1416 $lightColor = array(
'color', 255, 255, 255);
1419 if ($args[0] ==
'list') {
1420 $inputColor = (isset($args[2][0])) ? $this->assertColor($args[2][0]) : $lightColor;
1421 $darkColor = (isset($args[2][1])) ? $this->assertColor($args[2][1]) : $darkColor;
1422 $lightColor = (isset($args[2][2])) ? $this->assertColor($args[2][2]) : $lightColor;
1423 $threshold = (isset($args[2][3])) ? $this->assertNumber($args[2][3]) : $threshold;
1425 $inputColor = $this->assertColor($args);
1428 $inputColor = $this->coerceColor($inputColor);
1429 $darkColor = $this->coerceColor($darkColor);
1430 $lightColor = $this->coerceColor($lightColor);
1433 if ($this->toLuma($darkColor) > $this->toLuma($lightColor)) {
1435 $lightColor = $darkColor;
1439 $inputColor_alpha = $this->lib_alpha($inputColor);
1440 if (($this->toLuma($inputColor) * $inputColor_alpha) < $threshold) {
1446 private function toLuma($color)
1448 list(, $r, $g, $b) = $this->coerceColor($color);
1454 $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
1455 $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
1456 $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);
1458 return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
1461 protected function lib_luma($color)
1463 return array(
"number", round($this->toLuma($color) * 100, 8),
"%");
1467 public function assertColor($value, $error =
"expected color value")
1469 $color = $this->coerceColor($value);
1470 if (is_null($color)) {
1476 public function assertNumber($value, $error =
"expecting number")
1478 if ($value[0] ==
"number") {
1484 public function assertArgs($value, $expectedArgs, $name =
"")
1486 if ($expectedArgs == 1) {
1489 if ($value[0] !==
"list" || $value[1] !=
",") {
1492 $values = $value[2];
1493 $numValues = count($values);
1494 if ($expectedArgs != $numValues) {
1499 $this->
throwError(
"${name}expecting $expectedArgs arguments, got $numValues");
1506 protected function toHSL($color)
1508 if ($color[0] ===
'hsl') {
1512 $r = $color[1] / 255;
1513 $g = $color[2] / 255;
1514 $b = $color[3] / 255;
1516 $min = min($r, $g, $b);
1517 $max = max($r, $g, $b);
1519 $L = ($min + $max) / 2;
1524 $S = ($max - $min) / ($max + $min);
1526 $S = ($max - $min) / (2.0 - $max - $min);
1529 $H = ($g - $b) / ($max - $min);
1530 } elseif ($g == $max) {
1531 $H = 2.0 + ($b - $r) / ($max - $min);
1532 } elseif ($b == $max) {
1533 $H = 4.0 + ($r - $g) / ($max - $min);
1538 ($H < 0 ? $H + 6 : $H) * 60,
1543 if (count($color) > 4) {
1550 protected function toRGB_helper($comp, $temp1, $temp2)
1554 } elseif ($comp > 1) {
1558 if (6 * $comp < 1) {
1559 return $temp1 + ($temp2 - $temp1) * 6 * $comp;
1561 if (2 * $comp < 1) {
1564 if (3 * $comp < 2) {
1565 return $temp1 + ($temp2 - $temp1) * ((2 / 3) - $comp) * 6;
1577 if ($color[0] ===
'color') {
1581 $H = $color[1] / 360;
1582 $S = $color[2] / 100;
1583 $L = $color[3] / 100;
1589 $L * (1.0 + $S) : $L + $S - $L * $S;
1591 $temp1 = 2.0 * $L - $temp2;
1593 $r = $this->toRGB_helper($H + 1 / 3, $temp1, $temp2);
1594 $g = $this->toRGB_helper($H, $temp1, $temp2);
1595 $b = $this->toRGB_helper($H - 1 / 3, $temp1, $temp2);
1599 $out = array(
'color', $r * 255, $g * 255, $b * 255);
1600 if (count($color) > 4) {
1607 protected function clamp($v, $max = 1, $min = 0)
1609 return min($max, max($min, $v));
1619 if ($func[2][0] !=
'list') {
1623 $rawComponents = $func[2][2];
1625 if ($fname ==
'hsl' || $fname ==
'hsla') {
1626 $hsl = array(
'hsl');
1628 foreach ($rawComponents as $c) {
1629 $val = $this->reduce($c);
1630 $val = isset($val[1]) ? floatval($val[1]) : 0;
1640 $hsl[] = $this->clamp($val, $clamp);
1644 while (count($hsl) < 4) {
1647 return $this->
toRGB($hsl);
1648 } elseif ($fname ==
'rgb' || $fname ==
'rgba') {
1649 $components = array();
1651 foreach ($rawComponents as $c) {
1652 $c = $this->reduce($c);
1654 if ($c[0] ==
"number" && $c[2] ==
"%") {
1655 $components[] = 255 * ($c[1] / 100);
1657 $components[] = floatval($c[1]);
1659 } elseif ($i == 4) {
1660 if ($c[0] ==
"number" && $c[2] ==
"%") {
1661 $components[] = 1.0 * ($c[1] / 100);
1663 $components[] = floatval($c[1]);
1671 while (count($components) < 3) {
1674 array_unshift($components,
'color');
1675 return $this->fixColor($components);
1681 protected function reduce($value, $forExpression =
false)
1683 switch ($value[0]) {
1685 $reduced = $this->reduce($value[1]);
1687 $res = $this->reduce(array(
"variable", $this->vPrefix.$var));
1689 if ($res[0] ==
"raw_color") {
1690 $res = $this->coerceColor($res);
1693 if (empty($value[2])) {
1694 $res = $this->lib_e($res);
1700 if (is_array($key)) {
1701 $key = $this->reduce($key);
1702 $key = $this->vPrefix.$this->compileValue($this->lib_e($key));
1705 $seen = & $this->env->seenNames;
1707 if (!empty($seen[$key])) {
1708 $this->
throwError(
"infinite loop detected: $key");
1712 $out = $this->reduce($this->
get($key));
1713 $seen[$key] =
false;
1716 foreach ($value[2] as &$item) {
1717 $item = $this->reduce($item, $forExpression);
1721 return $this->evaluate($value);
1723 foreach ($value[2] as &$part) {
1724 if (is_array($part)) {
1725 $strip = $part[0] ==
"variable";
1726 $part = $this->reduce($part);
1728 $part = $this->lib_e($part);
1734 list(,$inner) = $value;
1735 return $this->lib_e($this->reduce($inner));
1742 list(, $name, $args) = $value;
1747 $f = isset($this->libFunctions[$name]) ?
1748 $this->libFunctions[$name] : array($this,
'lib_'.str_replace(
'-',
'_', $name));
1750 if (is_callable($f)) {
1751 if ($args[0] ==
'list') {
1752 $args = self::compressList($args[2], $args[1]);
1755 $ret = call_user_func($f, $this->reduce($args,
true), $this);
1757 if (is_null($ret)) {
1758 return array(
"string",
"", array(
1759 $name,
"(", $args,
")"
1764 if (is_numeric($ret)) {
1765 $ret = array(
'number', $ret,
"");
1766 } elseif (!is_array($ret)) {
1767 $ret = array(
'keyword', $ret);
1774 $value[2] = $this->reduce($value[2]);
1777 list(, $op, $exp) = $value;
1778 $exp = $this->reduce($exp);
1780 if ($exp[0] ==
"number") {
1789 return array(
"string",
"", array($op, $exp));
1792 if ($forExpression) {
1793 switch ($value[0]) {
1795 if ($color = $this->coerceColor($value)) {
1800 return $this->coerceColor($value);
1809 protected function coerceColor($value)
1811 switch ($value[0]) {
1815 $c = array(
"color", 0, 0, 0);
1816 $colorStr = substr($value[1], 1);
1817 $num = hexdec($colorStr);
1818 $width = strlen($colorStr) == 3 ? 16 : 256;
1820 for ($i = 3; $i > 0; $i--) {
1824 $c[$i] = $t * (256 / $width) + $t * floor(16 / $width);
1830 if (isset(self::$cssColors[$name])) {
1831 $rgba = explode(
',', self::$cssColors[$name]);
1833 if (isset($rgba[3])) {
1834 return array(
'color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
1836 return array(
'color', $rgba[0], $rgba[1], $rgba[2]);
1844 protected function coerceString($value)
1846 switch ($value[0]) {
1850 return array(
"string",
"", array($value[1]));
1856 protected function flattenList($value)
1858 if ($value[0] ==
"list" && count($value[2]) == 1) {
1859 return $this->flattenList($value[2][0]);
1864 public function toBool($a)
1866 return $a ? self::$TRUE : self::$FALSE;
1870 protected function evaluate($exp)
1872 list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
1874 $left = $this->reduce($left,
true);
1875 $right = $this->reduce($right,
true);
1877 if ($leftColor = $this->coerceColor($left)) {
1881 if ($rightColor = $this->coerceColor($right)) {
1882 $right = $rightColor;
1890 return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
1894 return $this->toBool($this->eq($left, $right));
1897 if ($op ==
"+" && !is_null($str = $this->stringConcatenate($left, $right))) {
1902 $fname =
"op_${ltype}_${rtype}";
1903 if (is_callable(array($this, $fname))) {
1904 $out = $this->$fname($op, $left, $right);
1905 if (!is_null($out)) {
1913 $paddedOp =
" ".$paddedOp;
1919 return array(
"string",
"", array($left, $paddedOp, $right));
1922 protected function stringConcatenate($left, $right)
1924 if ($strLeft = $this->coerceString($left)) {
1925 if ($right[0] ==
"string") {
1928 $strLeft[2][] = $right;
1932 if ($strRight = $this->coerceString($right)) {
1933 array_unshift($strRight[2], $left);
1942 protected function fixColor($c)
1944 foreach (range(1, 3) as $i) {
1956 protected function op_number_color($op, $lft, $rgt)
1958 if ($op ==
'+' || $op ==
'*') {
1959 return $this->op_color_number($op, $rgt, $lft);
1965 protected function op_color_number($op, $lft, $rgt)
1967 if ($rgt[0] ==
'%') {
1971 return $this->op_color_color(
1974 array_fill(1, count($lft) - 1, $rgt[1])
1978 protected function op_color_color($op, $left, $right)
1980 $out = array(
'color');
1981 $max = count($left) > count($right) ? count($left) : count($right);
1982 foreach (range(1, $max - 1) as $i) {
1983 $lval = isset($left[$i]) ? $left[$i] : 0;
1984 $rval = isset($right[$i]) ? $right[$i] : 0;
1987 $out[] = $lval + $rval;
1990 $out[] = $lval - $rval;
1993 $out[] = $lval * $rval;
1996 $out[] = $lval % $rval;
2000 $this->
throwError(
"evaluate error: can't divide by zero");
2002 $out[] = $lval / $rval;
2005 $this->
throwError(
'evaluate error: color op number failed on op '.$op);
2008 return $this->fixColor($out);
2011 public function lib_red($color)
2013 $color = $this->coerceColor($color);
2014 if (is_null($color)) {
2015 $this->
throwError(
'color expected for red()');
2021 public function lib_green($color)
2023 $color = $this->coerceColor($color);
2024 if (is_null($color)) {
2025 $this->
throwError(
'color expected for green()');
2031 public function lib_blue($color)
2033 $color = $this->coerceColor($color);
2034 if (is_null($color)) {
2035 $this->
throwError(
'color expected for blue()');
2043 protected function op_number_number($op, $left, $right)
2045 $unit = empty($left[2]) ? $right[2] : $left[2];
2050 $value = $left[1] + $right[1];
2053 $value = $left[1] * $right[1];
2056 $value = $left[1] - $right[1];
2059 $value = $left[1] % $right[1];
2062 if ($right[1] == 0) {
2063 $this->
throwError(
'parse error: divide by zero');
2065 $value = $left[1] / $right[1];
2068 return $this->toBool($left[1] < $right[1]);
2070 return $this->toBool($left[1] > $right[1]);
2072 return $this->toBool($left[1] >= $right[1]);
2074 return $this->toBool($left[1] <= $right[1]);
2076 $this->
throwError(
'parse error: unknown number operator: '.$op);
2079 return array(
"number", $value, $unit);
2085 protected function makeOutputBlock($type, $selectors =
null)
2088 $b->lines = array();
2089 $b->children = array();
2090 $b->selectors = $selectors;
2092 $b->parent = $this->scope;
2097 protected function pushEnv($block =
null)
2100 $e->parent = $this->env;
2101 $e->store = array();
2109 protected function popEnv()
2112 $this->env = $this->env->parent;
2117 protected function set($name, $value)
2119 $this->env->store[$name] = $value;
2124 protected function get($name)
2126 $current = $this->env;
2128 $isArguments = $name == $this->vPrefix.
'arguments';
2130 if ($isArguments && isset($current->arguments)) {
2131 return array(
'list',
' ', $current->arguments);
2134 if (isset($current->store[$name])) {
2135 return $current->store[$name];
2138 $current = isset($current->storeParent) ?
2139 $current->storeParent : $current->parent;
2142 $this->
throwError(
"variable $name is undefined");
2146 protected function injectVariables($args)
2150 foreach ($args as $name => $strValue) {
2151 if ($name[0] !==
'@') {
2155 $parser->buffer = (string) $strValue;
2156 if (!$parser->propertyValue($value)) {
2157 throw new Exception(
"failed to parse passed in variable $name: $strValue");
2160 $this->
set($name, $value);
2170 if ($fname !==
null) {
2172 $this->_parseFile = $fname;
2176 public function compile($string, $name =
null)
2178 $locale = setlocale(LC_NUMERIC, 0);
2179 setlocale(LC_NUMERIC,
"C");
2181 $this->parser = $this->makeParser($name);
2182 $root = $this->parser->parse($string);
2185 $this->scope =
null;
2187 $this->formatter = $this->newFormatter();
2189 if (!empty($this->registeredVars)) {
2190 $this->injectVariables($this->registeredVars);
2193 $this->sourceParser = $this->parser;
2197 $this->formatter->block($this->scope);
2198 $out = ob_get_clean();
2199 setlocale(LC_NUMERIC, $locale);
2203 public function compileFile($fname, $outFname =
null)
2205 if (!is_readable($fname)) {
2206 throw new Exception(
'load error: failed to find '.$fname);
2209 $pi = pathinfo($fname);
2211 $oldImport = $this->importDir;
2213 $this->importDir = (array) $this->importDir;
2214 $this->importDir[] = $pi[
'dirname'].
'/';
2216 $this->addParsedFile($fname);
2218 $out = $this->compile(file_get_contents($fname), $fname);
2220 $this->importDir = $oldImport;
2222 if ($outFname !==
null) {
2223 return file_put_contents($outFname, $out);
2230 public function checkedCompile($in, $out)
2232 if (!is_file($out) || filemtime($in) > filemtime($out)) {
2233 $this->compileFile($in, $out);
2264 if (is_string($in)) {
2266 } elseif (is_array($in) && isset($in[
'root'])) {
2267 if ($force || !isset($in[
'files'])) {
2271 $root = $in[
'root'];
2272 } elseif (isset($in[
'files']) && is_array($in[
'files'])) {
2273 foreach ($in[
'files'] as $fname => $ftime) {
2274 if (!file_exists($fname) || filemtime($fname) > $ftime) {
2277 $root = $in[
'root'];
2288 if ($root !==
null) {
2291 $out[
'root'] = $root;
2292 $out[
'compiled'] = $this->compileFile($root);
2293 $out[
'files'] = $this->allParsedFiles();
2294 $out[
'updated'] = time();
2305 public function parse($str =
null, $initialVariables =
null)
2307 if (is_array($str)) {
2308 $initialVariables = $str;
2312 $oldVars = $this->registeredVars;
2313 if ($initialVariables !==
null) {
2314 $this->setVariables($initialVariables);
2318 if (empty($this->_parseFile)) {
2319 throw new exception(
"nothing to parse");
2322 $out = $this->compileFile($this->_parseFile);
2324 $out = $this->compile($str);
2327 $this->registeredVars = $oldVars;
2331 protected function makeParser($name)
2334 $parser->writeComments = $this->preserveComments;
2339 public function setFormatter($name)
2341 $this->formatterName = $name;
2344 protected function newFormatter()
2346 $className =
"lessc_formatter_lessjs";
2347 if (!empty($this->formatterName)) {
2348 if (!is_string($this->formatterName)) {
2349 return $this->formatterName;
2351 $className =
"lessc_formatter_$this->formatterName";
2354 return new $className;
2357 public function setPreserveComments($preserve)
2359 $this->preserveComments = $preserve;
2362 public function registerFunction($name, $func)
2364 $this->libFunctions[$name] = $func;
2367 public function unregisterFunction($name)
2369 unset($this->libFunctions[$name]);
2372 public function setVariables($variables)
2374 $this->registeredVars = array_merge($this->registeredVars, $variables);
2377 public function unsetVariable($name)
2379 unset($this->registeredVars[$name]);
2382 public function setImportDir($dirs)
2384 $this->importDir = (array) $dirs;
2387 public function addImportDir($dir)
2389 $this->importDir = (array) $this->importDir;
2390 $this->importDir[] = $dir;
2393 public function allParsedFiles()
2395 return $this->allParsedFiles;
2398 public function addParsedFile($file)
2400 $this->allParsedFiles[realpath($file)] = filemtime($file);
2408 if ($this->sourceLoc >= 0) {
2409 $this->sourceParser->throwError($msg, $this->sourceLoc);
2411 throw new exception($msg);
2416 public static function ccompile($in, $out, $less =
null)
2418 if ($less ===
null) {
2421 return $less->checkedCompile($in, $out);
2424 public static function cexecute($in, $force =
false, $less =
null)
2426 if ($less ===
null) {
2429 return $less->cachedCompile($in, $force);
2432 protected static $cssColors = array(
2433 'aliceblue' =>
'240,248,255',
2434 'antiquewhite' =>
'250,235,215',
2435 'aqua' =>
'0,255,255',
2436 'aquamarine' =>
'127,255,212',
2437 'azure' =>
'240,255,255',
2438 'beige' =>
'245,245,220',
2439 'bisque' =>
'255,228,196',
2441 'blanchedalmond' =>
'255,235,205',
2442 'blue' =>
'0,0,255',
2443 'blueviolet' =>
'138,43,226',
2444 'brown' =>
'165,42,42',
2445 'burlywood' =>
'222,184,135',
2446 'cadetblue' =>
'95,158,160',
2447 'chartreuse' =>
'127,255,0',
2448 'chocolate' =>
'210,105,30',
2449 'coral' =>
'255,127,80',
2450 'cornflowerblue' =>
'100,149,237',
2451 'cornsilk' =>
'255,248,220',
2452 'crimson' =>
'220,20,60',
2453 'cyan' =>
'0,255,255',
2454 'darkblue' =>
'0,0,139',
2455 'darkcyan' =>
'0,139,139',
2456 'darkgoldenrod' =>
'184,134,11',
2457 'darkgray' =>
'169,169,169',
2458 'darkgreen' =>
'0,100,0',
2459 'darkgrey' =>
'169,169,169',
2460 'darkkhaki' =>
'189,183,107',
2461 'darkmagenta' =>
'139,0,139',
2462 'darkolivegreen' =>
'85,107,47',
2463 'darkorange' =>
'255,140,0',
2464 'darkorchid' =>
'153,50,204',
2465 'darkred' =>
'139,0,0',
2466 'darksalmon' =>
'233,150,122',
2467 'darkseagreen' =>
'143,188,143',
2468 'darkslateblue' =>
'72,61,139',
2469 'darkslategray' =>
'47,79,79',
2470 'darkslategrey' =>
'47,79,79',
2471 'darkturquoise' =>
'0,206,209',
2472 'darkviolet' =>
'148,0,211',
2473 'deeppink' =>
'255,20,147',
2474 'deepskyblue' =>
'0,191,255',
2475 'dimgray' =>
'105,105,105',
2476 'dimgrey' =>
'105,105,105',
2477 'dodgerblue' =>
'30,144,255',
2478 'firebrick' =>
'178,34,34',
2479 'floralwhite' =>
'255,250,240',
2480 'forestgreen' =>
'34,139,34',
2481 'fuchsia' =>
'255,0,255',
2482 'gainsboro' =>
'220,220,220',
2483 'ghostwhite' =>
'248,248,255',
2484 'gold' =>
'255,215,0',
2485 'goldenrod' =>
'218,165,32',
2486 'gray' =>
'128,128,128',
2487 'green' =>
'0,128,0',
2488 'greenyellow' =>
'173,255,47',
2489 'grey' =>
'128,128,128',
2490 'honeydew' =>
'240,255,240',
2491 'hotpink' =>
'255,105,180',
2492 'indianred' =>
'205,92,92',
2493 'indigo' =>
'75,0,130',
2494 'ivory' =>
'255,255,240',
2495 'khaki' =>
'240,230,140',
2496 'lavender' =>
'230,230,250',
2497 'lavenderblush' =>
'255,240,245',
2498 'lawngreen' =>
'124,252,0',
2499 'lemonchiffon' =>
'255,250,205',
2500 'lightblue' =>
'173,216,230',
2501 'lightcoral' =>
'240,128,128',
2502 'lightcyan' =>
'224,255,255',
2503 'lightgoldenrodyellow' =>
'250,250,210',
2504 'lightgray' =>
'211,211,211',
2505 'lightgreen' =>
'144,238,144',
2506 'lightgrey' =>
'211,211,211',
2507 'lightpink' =>
'255,182,193',
2508 'lightsalmon' =>
'255,160,122',
2509 'lightseagreen' =>
'32,178,170',
2510 'lightskyblue' =>
'135,206,250',
2511 'lightslategray' =>
'119,136,153',
2512 'lightslategrey' =>
'119,136,153',
2513 'lightsteelblue' =>
'176,196,222',
2514 'lightyellow' =>
'255,255,224',
2515 'lime' =>
'0,255,0',
2516 'limegreen' =>
'50,205,50',
2517 'linen' =>
'250,240,230',
2518 'magenta' =>
'255,0,255',
2519 'maroon' =>
'128,0,0',
2520 'mediumaquamarine' =>
'102,205,170',
2521 'mediumblue' =>
'0,0,205',
2522 'mediumorchid' =>
'186,85,211',
2523 'mediumpurple' =>
'147,112,219',
2524 'mediumseagreen' =>
'60,179,113',
2525 'mediumslateblue' =>
'123,104,238',
2526 'mediumspringgreen' =>
'0,250,154',
2527 'mediumturquoise' =>
'72,209,204',
2528 'mediumvioletred' =>
'199,21,133',
2529 'midnightblue' =>
'25,25,112',
2530 'mintcream' =>
'245,255,250',
2531 'mistyrose' =>
'255,228,225',
2532 'moccasin' =>
'255,228,181',
2533 'navajowhite' =>
'255,222,173',
2534 'navy' =>
'0,0,128',
2535 'oldlace' =>
'253,245,230',
2536 'olive' =>
'128,128,0',
2537 'olivedrab' =>
'107,142,35',
2538 'orange' =>
'255,165,0',
2539 'orangered' =>
'255,69,0',
2540 'orchid' =>
'218,112,214',
2541 'palegoldenrod' =>
'238,232,170',
2542 'palegreen' =>
'152,251,152',
2543 'paleturquoise' =>
'175,238,238',
2544 'palevioletred' =>
'219,112,147',
2545 'papayawhip' =>
'255,239,213',
2546 'peachpuff' =>
'255,218,185',
2547 'peru' =>
'205,133,63',
2548 'pink' =>
'255,192,203',
2549 'plum' =>
'221,160,221',
2550 'powderblue' =>
'176,224,230',
2551 'purple' =>
'128,0,128',
2553 'rosybrown' =>
'188,143,143',
2554 'royalblue' =>
'65,105,225',
2555 'saddlebrown' =>
'139,69,19',
2556 'salmon' =>
'250,128,114',
2557 'sandybrown' =>
'244,164,96',
2558 'seagreen' =>
'46,139,87',
2559 'seashell' =>
'255,245,238',
2560 'sienna' =>
'160,82,45',
2561 'silver' =>
'192,192,192',
2562 'skyblue' =>
'135,206,235',
2563 'slateblue' =>
'106,90,205',
2564 'slategray' =>
'112,128,144',
2565 'slategrey' =>
'112,128,144',
2566 'snow' =>
'255,250,250',
2567 'springgreen' =>
'0,255,127',
2568 'steelblue' =>
'70,130,180',
2569 'tan' =>
'210,180,140',
2570 'teal' =>
'0,128,128',
2571 'thistle' =>
'216,191,216',
2572 'tomato' =>
'255,99,71',
2573 'transparent' =>
'0,0,0,0',
2574 'turquoise' =>
'64,224,208',
2575 'violet' =>
'238,130,238',
2576 'wheat' =>
'245,222,179',
2577 'white' =>
'255,255,255',
2578 'whitesmoke' =>
'245,245,245',
2579 'yellow' =>
'255,255,0',
2580 'yellowgreen' =>
'154,205,50'
2588 protected static $nextBlockId = 0;
2590 protected static $precedence = array(
2604 protected static $whitePattern;
2605 protected static $commentMulti;
2607 protected static $commentSingle =
"//";
2608 protected static $commentMultiLeft =
"/*";
2609 protected static $commentMultiRight =
"*/";
2612 protected static $operatorString;
2615 protected static $supressDivisionProps =
2616 array(
'/border-radius$/i',
'/^font$/i');
2618 protected $blockDirectives = array(
"font-face",
"keyframes",
"page",
"-moz-document",
"viewport",
"-moz-viewport",
"-o-viewport",
"-ms-viewport");
2619 protected $lineDirectives = array(
"charset");
2633 protected static $literalCache = array();
2635 public function __construct($lessc, $sourceName =
null)
2637 $this->eatWhiteDefault =
true;
2639 $this->lessc = $lessc;
2641 $this->sourceName = $sourceName;
2643 $this->writeComments =
false;
2645 if (!self::$operatorString) {
2646 self::$operatorString =
2647 '('.implode(
'|', array_map(
2648 array(
'lessc',
'preg_quote'),
2649 array_keys(self::$precedence)
2652 $commentSingle = lessc::preg_quote(self::$commentSingle);
2653 $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
2654 $commentMultiRight = lessc::preg_quote(self::$commentMultiRight);
2656 self::$commentMulti = $commentMultiLeft.
'.*?'.$commentMultiRight;
2657 self::$whitePattern =
'/'.$commentSingle.
'[^\n]*\s*|('.self::$commentMulti.
')\s*|\s+/Ais';
2674 $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
2675 $this->pushSpecialBlock(
"root");
2676 $this->eatWhiteDefault =
true;
2677 $this->seenComments = array();
2684 $this->whitespace();
2689 if ($this->count != strlen($this->buffer)) {
2690 $this->throwError(
'parse error count '.$this->count.
' != len buffer '.strlen($this->buffer));
2694 if (!property_exists($this->env,
'parent') || !is_null($this->env->parent)) {
2695 throw new exception(
'parse error: unclosed block');
2739 if (empty($this->buffer)) {
2744 if ($this->whitespace()) {
2749 if ($this->keyword($key) && $this->
assign() &&
2750 $this->propertyValue($value, $key) && $this->end()
2752 $this->append(array(
'assign', $key, $value), $s);
2760 if ($this->literal(
'@',
false)) {
2764 if ($this->literal(
'@media')) {
2765 if ($this->mediaQueryList($mediaQueries)
2766 && $this->literal(
'{')
2768 $media = $this->pushSpecialBlock(
"media");
2769 $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
2777 if ($this->literal(
"@",
false) && $this->keyword($dirName)) {
2778 if ($this->isDirective($dirName, $this->blockDirectives)) {
2779 if ($this->openString(
"{", $dirValue,
null, array(
";")) &&
2782 $dir = $this->pushSpecialBlock(
"directive");
2783 $dir->name = $dirName;
2784 if (isset($dirValue)) {
2785 $dir->value = $dirValue;
2789 } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
2790 if ($this->propertyValue($dirValue) && $this->end()) {
2791 $this->append(array(
"directive", $dirName, $dirValue));
2801 if ($this->variable($var) && $this->
assign() &&
2802 $this->propertyValue($value) && $this->end()
2804 $this->append(array(
'assign', $var, $value), $s);
2810 if ($this->
import($importValue)) {
2811 $this->append($importValue, $s);
2816 if ($this->tag($tag,
true) && $this->argumentDef($args, $isVararg) &&
2817 $this->guards($guards) &&
2820 $block = $this->pushBlock($this->fixTags(array($tag)));
2821 $block->args = $args;
2822 $block->isVararg = $isVararg;
2823 if (!empty($guards)) {
2824 $block->guards = $guards;
2832 if ($this->tags($tags) && $this->literal(
'{',
false)) {
2833 $tags = $this->fixTags($tags);
2834 $this->pushBlock($tags);
2841 if ($this->literal(
'}',
false)) {
2843 $block = $this->pop();
2844 }
catch (exception $e) {
2846 $this->throwError($e->getMessage());
2850 if (is_null($block->type)) {
2852 if (!isset($block->args)) {
2853 foreach ($block->tags as $tag) {
2854 if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix) {
2861 foreach ($block->tags as $tag) {
2862 if (is_string($tag)) {
2863 $this->env->children[$tag][] = $block;
2869 $this->append(array(
'block', $block), $s);
2874 $this->whitespace();
2879 if ($this->mixinTags($tags) &&
2880 $this->argumentDef($argv, $isVararg) &&
2881 $this->keyword($suffix) && $this->end()
2883 $tags = $this->fixTags($tags);
2884 $this->append(array(
'mixin', $tags, $argv, $suffix), $s);
2891 if ($this->literal(
';')) {
2898 protected function isDirective($dirname, $directives)
2903 array_map(array(
"lessc",
"preg_quote"), $directives)
2905 $pattern =
'/^(-[a-z-]+-)?('.$pattern.
')$/i';
2907 return preg_match($pattern, $dirname);
2910 protected function fixTags($tags)
2913 foreach ($tags as &$tag) {
2914 if ($tag[0] == $this->lessc->vPrefix) {
2915 $tag[0] = $this->lessc->mPrefix;
2922 protected function expressionList(&$exps)
2930 if (count($values) == 0) {
2934 $exps = lessc::compressList($values,
' ');
2944 if ($this->value($lhs)) {
2948 if (!empty($this->env->supressedDivision)) {
2949 unset($this->env->supressedDivision);
2951 if ($this->literal(
"/") && $this->value($rhs)) {
2952 $out = array(
"list",
"",
2953 array($out, array(
"keyword",
"/"), $rhs));
2969 $this->inExp =
true;
2970 $ss = $this->seek();
2973 $whiteBefore = isset($this->buffer[$this->count - 1]) &&
2974 ctype_space($this->buffer[$this->count - 1]);
2980 if ($this->match(self::$operatorString.($needWhite ?
'\s' :
''), $m) && self::$precedence[$m[1]] >= $minP) {
2981 if (!$this->inParens && isset($this->env->currentProperty) && $m[1] ==
"/" && empty($this->env->supressedDivision)) {
2982 foreach (self::$supressDivisionProps as $pattern) {
2983 if (preg_match($pattern, $this->env->currentProperty)) {
2984 $this->env->supressedDivision =
true;
2991 $whiteAfter = isset($this->buffer[$this->count - 1]) &&
2992 ctype_space($this->buffer[$this->count - 1]);
2994 if (!$this->value($rhs)) {
2999 if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
3000 $rhs = $this->
expHelper($rhs, self::$precedence[$next[1]]);
3003 $lhs = array(
'expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
3004 $ss = $this->seek();
3018 public function propertyValue(&$value, $keyName =
null)
3022 if ($keyName !==
null) {
3023 $this->env->currentProperty = $keyName;
3027 while ($this->expressionList($v)) {
3030 if (!$this->literal(
',')) {
3039 if ($keyName !==
null) {
3040 unset($this->env->currentProperty);
3043 if (count($values) == 0) {
3047 $value = lessc::compressList($values,
', ');
3051 protected function parenValue(&$out)
3056 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] !=
"(") {
3061 if ($this->literal(
"(") &&
3062 ($this->inParens =
true) && $this->
expression($exp) &&
3077 protected function value(&$value)
3082 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] ==
"-") {
3084 if ($this->literal(
"-",
false) &&
3085 (($this->variable($inner) && $inner = array(
"variable", $inner)) ||
3086 $this->unit($inner) ||
3087 $this->parenValue($inner))
3089 $value = array(
"unary",
"-", $inner);
3096 if ($this->parenValue($value)) {
3099 if ($this->unit($value)) {
3102 if ($this->color($value)) {
3105 if ($this->func($value)) {
3108 if ($this->
string($value)) {
3112 if ($this->keyword($word)) {
3113 $value = array(
'keyword', $word);
3118 if ($this->variable($var)) {
3119 $value = array(
'variable', $var);
3124 if ($this->literal(
"~") && $this->
string($str)) {
3125 $value = array(
"escape", $str);
3132 if ($this->literal(
'\\') && $this->match(
'([0-9]+)', $m)) {
3133 $value = array(
'keyword',
'\\'.$m[1]);
3143 protected function import(&$out, $value =
'')
3145 if (!$this->literal(
'@import')) {
3153 if ($this->propertyValue($value)) {
3154 $out = array(
"import", $value);
3161 protected function mediaQueryList(&$out)
3163 if ($this->genericList($list,
"mediaQuery",
",",
false)) {
3170 protected function mediaQuery(&$out)
3174 $expressions =
null;
3177 if ((($this->literal(
"only") && ($only =
true)) || ($this->literal(
"not") && ($not =
true))) && $this->keyword($mediaType)) {
3178 $prop = array(
"mediaType");
3185 $prop[] = $mediaType;
3192 if (!empty($mediaType) && !$this->literal(
"and")) {
3195 $this->genericList($expressions,
"mediaExpression",
"and",
false);
3196 if (is_array($expressions)) {
3197 $parts = array_merge($parts, $expressions[2]);
3201 if (count($parts) == 0) {
3210 protected function mediaExpression(&$out)
3214 if ($this->literal(
"(") &&
3215 $this->keyword($feature) &&
3216 ($this->literal(
":") && $this->
expression($value)) &&
3219 $out = array(
"mediaExp", $feature);
3224 } elseif ($this->variable($variable)) {
3225 $out = array(
'variable', $variable);
3234 protected function openString($end, &$out, $nestingOpen =
null, $rejectStrs =
null)
3236 $oldWhite = $this->eatWhiteDefault;
3237 $this->eatWhiteDefault =
false;
3239 $stop = array(
"'",
'"',
"@{", $end);
3240 $stop = array_map(array(
"lessc",
"preg_quote"), $stop);
3243 if (!is_null($rejectStrs)) {
3244 $stop = array_merge($stop, $rejectStrs);
3247 $patt =
'(.*?)('.implode(
"|", $stop).
')';
3252 while ($this->match($patt, $m,
false)) {
3253 if (!empty($m[1])) {
3256 $nestingLevel += substr_count($m[1], $nestingOpen);
3262 $this->count -= strlen($tok);
3264 if ($nestingLevel == 0) {
3271 if (($tok ==
"'" || $tok ==
'"') && $this->
string($str)) {
3276 if ($tok ==
"@{" && $this->interpolation($inter)) {
3277 $content[] = $inter;
3281 if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
3286 $this->count += strlen($tok);
3289 $this->eatWhiteDefault = $oldWhite;
3291 if (count($content) == 0) {
3296 if (is_string(end($content))) {
3297 $content[count($content) - 1] = rtrim(end($content));
3300 $out = array(
"string",
"", $content);
3304 protected function string(&$out)
3307 if ($this->literal(
'"',
false)) {
3309 } elseif ($this->literal(
"'",
false)) {
3318 $patt =
'([^\n]*?)(@\{|\\\\|'.
3319 lessc::preg_quote($delim).
')';
3321 $oldWhite = $this->eatWhiteDefault;
3322 $this->eatWhiteDefault =
false;
3324 while ($this->match($patt, $m,
false)) {
3326 if ($m[2] ==
"@{") {
3327 $this->count -= strlen($m[2]);
3328 if ($this->interpolation($inter)) {
3329 $content[] = $inter;
3331 $this->count += strlen($m[2]);
3334 } elseif ($m[2] ==
'\\') {
3336 if ($this->literal($delim,
false)) {
3337 $content[] = $delim;
3340 $this->count -= strlen($delim);
3345 $this->eatWhiteDefault = $oldWhite;
3347 if ($this->literal($delim)) {
3348 $out = array(
"string", $delim, $content);
3356 protected function interpolation(&$out)
3358 $oldWhite = $this->eatWhiteDefault;
3359 $this->eatWhiteDefault =
true;
3362 if ($this->literal(
"@{") &&
3363 $this->openString(
"}", $interp,
null, array(
"'",
'"',
";")) &&
3364 $this->literal(
"}",
false)
3366 $out = array(
"interpolate", $interp);
3367 $this->eatWhiteDefault = $oldWhite;
3368 if ($this->eatWhiteDefault) {
3369 $this->whitespace();
3374 $this->eatWhiteDefault = $oldWhite;
3379 protected function unit(&$unit)
3382 if (isset($this->buffer[$this->count])) {
3383 $char = $this->buffer[$this->count];
3384 if (!ctype_digit($char) && $char !=
".") {
3389 if ($this->match(
'([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
3390 $unit = array(
"number", $m[1], empty($m[2]) ?
"" : $m[2]);
3397 protected function color(&$out)
3399 if ($this->match(
'(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
3400 if (strlen($m[1]) > 7) {
3401 $out = array(
"string",
"", array($m[1]));
3403 $out = array(
"raw_color", $m[1]);
3416 protected function argumentDef(&$args, &$isVararg)
3419 if (!$this->literal(
'(')) {
3425 $method =
"expressionList";
3429 if ($this->literal(
"...")) {
3434 if ($this->$method($value)) {
3435 if ($value[0] ==
"variable") {
3436 $arg = array(
"arg", $value[1]);
3437 $ss = $this->seek();
3439 if ($this->
assign() && $this->$method($rhs)) {
3443 if ($this->literal(
"...")) {
3455 $values[] = array(
"lit", $value);
3460 if (!$this->literal($delim)) {
3461 if ($delim ==
"," && $this->literal(
";")) {
3464 $method =
"propertyValue";
3467 if (isset($values[1])) {
3469 foreach ($values as $i => $arg) {
3473 $this->throwError(
"Cannot mix ; and , as delimiter types");
3475 $newList[] = $arg[2];
3478 $newList[] = $arg[1];
3481 $this->throwError(
"Unexpected rest before semicolon");
3485 $newList = array(
"list",
", ", $newList);
3487 switch ($values[0][0]) {
3489 $newArg = array(
"arg", $values[0][1], $newList);
3492 $newArg = array(
"lit", $newList);
3495 } elseif ($values) {
3496 $newArg = $values[0];
3500 $values = array($newArg);
3508 if (!$this->literal(
')')) {
3520 protected function tags(&$tags, $simple =
false, $delim =
',')
3523 while ($this->tag($tt, $simple)) {
3525 if (!$this->literal($delim)) {
3529 if (count($tags) == 0) {
3538 protected function mixinTags(&$tags)
3541 while ($this->tag($tt,
true)) {
3543 $this->literal(
">");
3554 protected function tagBracket(&$parts, &$hasExpression)
3557 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] !=
"[") {
3563 $hasInterpolation =
false;
3565 if ($this->literal(
"[",
false)) {
3566 $attrParts = array(
"[");
3569 if ($this->literal(
"]",
false)) {
3574 if ($this->match(
'\s+', $m)) {
3578 if ($this->
string($str)) {
3580 foreach ($str[2] as &$chunk) {
3581 $chunk = str_replace($this->lessc->parentSelector,
"$&$", $chunk);
3584 $attrParts[] = $str;
3585 $hasInterpolation =
true;
3589 if ($this->keyword($word)) {
3590 $attrParts[] = $word;
3594 if ($this->interpolation($inter)) {
3595 $attrParts[] = $inter;
3596 $hasInterpolation =
true;
3601 if ($this->match(
'[|-~\$\*\^=]+', $m)) {
3602 $attrParts[] = $m[0];
3609 if ($this->literal(
"]",
false)) {
3611 foreach ($attrParts as $part) {
3614 $hasExpression = $hasExpression || $hasInterpolation;
3625 protected function tag(&$tag, $simple =
false)
3628 $chars =
'^@,:;{}\][>\(\) "\'';
3630 $chars =
'^@,;{}["\'';
3634 $hasExpression =
false;
3636 while ($this->tagBracket($parts, $hasExpression));
3638 $oldWhite = $this->eatWhiteDefault;
3639 $this->eatWhiteDefault =
false;
3642 if ($this->match(
'(['.$chars.
'0-9]['.$chars.
']*)', $m)) {
3648 while ($this->tagBracket($parts, $hasExpression));
3652 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] ==
"@") {
3653 if ($this->interpolation($interp)) {
3654 $hasExpression =
true;
3660 if ($this->literal(
"@")) {
3666 if ($this->unit($unit)) {
3667 $parts[] = $unit[1];
3668 $parts[] = $unit[2];
3675 $this->eatWhiteDefault = $oldWhite;
3681 if ($hasExpression) {
3682 $tag = array(
"exp", array(
"string",
"", $parts));
3684 $tag = trim(implode($parts));
3687 $this->whitespace();
3692 protected function func(&$func)
3696 if ($this->match(
'(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal(
'(')) {
3699 $sPreArgs = $this->seek();
3703 $ss = $this->seek();
3705 if ($this->keyword($name) && $this->literal(
'=') && $this->expressionList($value)) {
3706 $args[] = array(
"string",
"", array($name,
"=", $value));
3709 if ($this->expressionList($value)) {
3714 if (!$this->literal(
',')) {
3718 $args = array(
'list',
',', $args);
3720 if ($this->literal(
')')) {
3721 $func = array(
'function', $fname, $args);
3723 } elseif ($fname ==
'url') {
3725 $this->seek($sPreArgs);
3726 if ($this->openString(
")", $string) && $this->literal(
")")) {
3727 $func = array(
'function', $fname, $string);
3738 protected function variable(&$name)
3741 if ($this->literal($this->lessc->vPrefix,
false) &&
3742 ($this->variable($sub) || $this->keyword($name))
3745 $name = array(
'variable', $sub);
3747 $name = $this->lessc->vPrefix.$name;
3764 $this->currentProperty = $name;
3766 return $this->literal(
':') || $this->literal(
'=');
3770 protected function keyword(&$word)
3772 if ($this->match(
'([\w_\-\*!"][\w\-_"]*)', $m)) {
3780 protected function end()
3782 if ($this->literal(
';',
false)) {
3784 } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] ==
'}') {
3791 protected function guards(&$guards)
3795 if (!$this->literal(
"when")) {
3802 while ($this->guardGroup($g)) {
3804 if (!$this->literal(
",")) {
3809 if (count($guards) == 0) {
3820 protected function guardGroup(&$guardGroup)
3823 $guardGroup = array();
3824 while ($this->guard($guard)) {
3825 $guardGroup[] = $guard;
3826 if (!$this->literal(
"and")) {
3831 if (count($guardGroup) == 0) {
3840 protected function guard(&$guard)
3843 $negate = $this->literal(
"not");
3845 if ($this->literal(
"(") && $this->
expression($exp) && $this->literal(
")")) {
3848 $guard = array(
"negate", $guard);
3859 protected function literal($what, $eatWhitespace =
null)
3861 if ($eatWhitespace ===
null) {
3862 $eatWhitespace = $this->eatWhiteDefault;
3866 if (!isset($what[1]) && isset($this->buffer[$this->count])) {
3867 if ($this->buffer[$this->count] == $what) {
3868 if (!$eatWhitespace) {
3878 if (!isset(self::$literalCache[$what])) {
3879 self::$literalCache[$what] = lessc::preg_quote($what);
3882 return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
3885 protected function genericList(&$out, $parseItem, $delim =
"", $flatten =
true)
3889 while ($this->$parseItem($value)) {
3892 if (!$this->literal($delim)) {
3898 if (count($items) == 0) {
3903 if ($flatten && count($items) == 1) {
3906 $out = array(
"list", $delim, $items);
3916 protected function to($what, &$out, $until =
false, $allowNewline =
false)
3918 if (is_string($allowNewline)) {
3919 $validChars = $allowNewline;
3921 $validChars = $allowNewline ?
"." :
"[^\n]";
3923 if (!$this->match(
'('.$validChars.
'*?)'.lessc::preg_quote($what), $m, !$until)) {
3927 $this->count -= strlen($what);
3934 protected function match($regex, &$out, $eatWhitespace =
null)
3936 if ($eatWhitespace ===
null) {
3937 $eatWhitespace = $this->eatWhiteDefault;
3940 $r =
'/'.$regex.($eatWhitespace && !$this->writeComments ?
'\s*' :
'').
'/Ais';
3941 if (preg_match($r, $this->buffer, $out,
null, $this->count)) {
3942 $this->count += strlen($out[0]);
3943 if ($eatWhitespace && $this->writeComments) {
3944 $this->whitespace();
3952 protected function whitespace()
3954 if ($this->writeComments) {
3956 while (preg_match(self::$whitePattern, $this->buffer, $m,
null, $this->count)) {
3957 if (isset($m[1]) && empty($this->seenComments[$this->count])) {
3958 $this->append(array(
"comment", $m[1]));
3959 $this->seenComments[$this->count] =
true;
3961 $this->count += strlen($m[0]);
3966 $this->match(
"", $m);
3967 return strlen($m[0]) > 0;
3972 protected function peek($regex, &$out =
null, $from =
null)
3974 if (is_null($from)) {
3975 $from = $this->count;
3977 $r =
'/'.$regex.
'/Ais';
3978 $result = preg_match($r, $this->buffer, $out,
null, $from);
3984 protected function seek($where =
null)
3986 if ($where ===
null) {
3987 return $this->count;
3989 $this->count = $where;
3996 public function throwError($msg =
"parse error", $count =
null)
3998 $count = is_null($count) ? $this->count : $count;
4000 $line = $this->line +
4001 substr_count(substr($this->buffer, 0, $count),
"\n");
4003 if (!empty($this->sourceName)) {
4004 $loc =
"$this->sourceName on line $line";
4006 $loc =
"line: $line";
4010 if ($this->peek(
"(.*?)(\n|$)", $m, $count)) {
4011 throw new exception(
"$msg: failed at `$m[1]` $loc");
4013 throw new exception(
"$msg: $loc");
4017 protected function pushBlock($selectors =
null, $type =
null)
4020 $b->parent = $this->env;
4023 $b->id = self::$nextBlockId++;
4025 $b->isVararg =
false;
4026 $b->tags = $selectors;
4028 $b->props = array();
4029 $b->children = array();
4036 protected function pushSpecialBlock($type)
4038 return $this->pushBlock(
null, $type);
4042 protected function append($prop, $pos =
null)
4044 if ($pos !==
null) {
4047 $this->env->props[] = $prop;
4051 protected function pop()
4054 $this->env = $this->env->parent;
4060 protected function removeComments($text)
4063 'url(',
'//',
'/*',
'"',
"'"
4070 foreach ($look as $token) {
4071 $pos = strpos($text, $token);
4072 if ($pos !==
false) {
4073 if (!isset($min) || $pos < $min[1]) {
4074 $min = array($token, $pos);
4079 if (is_null($min)) {
4088 if (preg_match(
'/url\(.*?\)/', $text, $m, 0, $count)) {
4089 $count += strlen($m[0]) - strlen($min[0]);
4094 if (preg_match(
'/'.$min[0].
'.*?(?<!\\\\)'.$min[0].
'/', $text, $m, 0, $count)) {
4095 $count += strlen($m[0]) - 1;
4099 $skip = strpos($text,
"\n", $count);
4100 if ($skip ===
false) {
4101 $skip = strlen($text) - $count;
4107 if (preg_match(
'/\/\*.*?\*\//s', $text, $m, 0, $count)) {
4108 $skip = strlen($m[0]);
4109 $newlines = substr_count($m[0],
"\n");
4115 $count += strlen($min[0]);
4118 $out .= substr($text, 0, $count).str_repeat(
"\n", $newlines);
4119 $text = substr($text, $count + $skip);
4130 public $indentChar =
" ";
4132 public $break =
"\n";
4133 public $open =
" {";
4134 public $close =
"}";
4135 public $selectorSeparator =
", ";
4136 public $assignSeparator =
":";
4138 public $openSingle =
" { ";
4139 public $closeSingle =
" }";
4141 public $disableSingle =
false;
4142 public $breakSelectors =
false;
4144 public $compressColors =
false;
4146 public function __construct()
4148 $this->indentLevel = 0;
4151 public function indentStr($n = 0)
4153 return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
4156 public function property($name, $value)
4158 return $name.$this->assignSeparator.$value.
";";
4161 protected function isEmpty($block)
4163 if (empty($block->lines)) {
4164 foreach ($block->children as $child) {
4165 if (!$this->isEmpty($child)) {
4175 public function block($block)
4177 if ($this->isEmpty($block)) {
4181 $inner = $pre = $this->indentStr();
4183 $isSingle = !$this->disableSingle &&
4184 is_null($block->type) && count($block->lines) == 1;
4186 if (!empty($block->selectors)) {
4187 $this->indentLevel++;
4189 if ($this->breakSelectors) {
4190 $selectorSeparator = $this->selectorSeparator.$this->break.$pre;
4192 $selectorSeparator = $this->selectorSeparator;
4196 implode($selectorSeparator, $block->selectors);
4198 echo $this->openSingle;
4201 echo $this->open.$this->break;
4202 $inner = $this->indentStr();
4206 if (!empty($block->lines)) {
4207 $glue = $this->
break.$inner;
4208 echo $inner.implode($glue, $block->lines);
4209 if (!$isSingle && !empty($block->children)) {
4214 foreach ($block->children as $child) {
4215 $this->block($child);
4218 if (!empty($block->selectors)) {
4219 if (!$isSingle && empty($block->children)) {
4224 echo $this->closeSingle.$this->break;
4226 echo $pre.$this->close.$this->break;
4229 $this->indentLevel--;
4239 public $disableSingle =
true;
4241 public $selectorSeparator =
",";
4242 public $assignSeparator =
":";
4244 public $compressColors =
true;
4246 public function indentStr($n = 0)
4257 public $disableSingle =
true;
4258 public $breakSelectors =
true;
4259 public $assignSeparator =
": ";
4260 public $selectorSeparator =
",";