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])) {
706 $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]);
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;
1312 protected function lib_fade($args)
1314 list($color, $alpha) = $this->
colorArgs($args);
1315 $color[4] = $this->clamp($alpha / 100.0);
1319 protected function lib_percentage($arg)
1321 $num = $this->assertNumber($arg);
1322 return array(
"number", $num * 100,
"%");
1338 $white = [
'color', 255, 255, 255];
1339 if ($args[0] ==
'color') {
1340 return $this->lib_mix([
'list',
',', [$white, $args]]);
1341 } elseif ($args[0] ==
"list" && count($args[2]) == 2) {
1342 return $this->lib_mix([$args[0], $args[1], [$white, $args[2][0], $args[2][1]]]);
1344 $this->
throwError(
"tint expects (color, weight)");
1361 $black = [
'color', 0, 0, 0];
1362 if ($args[0] ==
'color') {
1363 return $this->lib_mix([
'list',
',', [$black, $args]]);
1364 } elseif ($args[0] ==
"list" && count($args[2]) == 2) {
1365 return $this->lib_mix([$args[0], $args[1], [$black, $args[2][0], $args[2][1]]]);
1367 $this->
throwError(
"shade expects (color, weight)");
1374 protected function lib_mix($args)
1376 if ($args[0] !=
"list" || count($args[2]) < 2) {
1377 $this->
throwError(
"mix expects (color1, color2, weight)");
1380 list($first, $second) = $args[2];
1381 $first = $this->assertColor($first);
1382 $second = $this->assertColor($second);
1384 $first_a = $this->lib_alpha($first);
1385 $second_a = $this->lib_alpha($second);
1387 if (isset($args[2][2])) {
1388 $weight = $args[2][2][1] / 100.0;
1393 $w = $weight * 2 - 1;
1394 $a = $first_a - $second_a;
1396 $w1 = (($w * $a == -1 ? $w : ($w + $a) / (1 + $w * $a)) + 1) / 2.0;
1399 $new = array(
'color',
1400 $w1 * $first[1] + $w2 * $second[1],
1401 $w1 * $first[2] + $w2 * $second[2],
1402 $w1 * $first[3] + $w2 * $second[3],
1405 if ($first_a != 1.0 || $second_a != 1.0) {
1406 $new[] = $first_a * $weight + $second_a * ($weight - 1);
1409 return $this->fixColor($new);
1412 protected function lib_contrast($args)
1414 $darkColor = array(
'color', 0, 0, 0);
1415 $lightColor = array(
'color', 255, 255, 255);
1418 if ($args[0] ==
'list') {
1419 $inputColor = (isset($args[2][0])) ? $this->assertColor($args[2][0]) : $lightColor;
1420 $darkColor = (isset($args[2][1])) ? $this->assertColor($args[2][1]) : $darkColor;
1421 $lightColor = (isset($args[2][2])) ? $this->assertColor($args[2][2]) : $lightColor;
1422 $threshold = (isset($args[2][3])) ? $this->assertNumber($args[2][3]) : $threshold;
1424 $inputColor = $this->assertColor($args);
1427 $inputColor = $this->coerceColor($inputColor);
1428 $darkColor = $this->coerceColor($darkColor);
1429 $lightColor = $this->coerceColor($lightColor);
1432 if ($this->toLuma($darkColor) > $this->toLuma($lightColor)) {
1434 $lightColor = $darkColor;
1438 $inputColor_alpha = $this->lib_alpha($inputColor);
1439 if (($this->toLuma($inputColor) * $inputColor_alpha) < $threshold) {
1445 private function toLuma($color)
1447 list(, $r, $g, $b) = $this->coerceColor($color);
1453 $r = ($r <= 0.03928) ? $r / 12.92 : pow((($r + 0.055) / 1.055), 2.4);
1454 $g = ($g <= 0.03928) ? $g / 12.92 : pow((($g + 0.055) / 1.055), 2.4);
1455 $b = ($b <= 0.03928) ? $b / 12.92 : pow((($b + 0.055) / 1.055), 2.4);
1457 return (0.2126 * $r) + (0.7152 * $g) + (0.0722 * $b);
1460 protected function lib_luma($color)
1462 return array(
"number", round($this->toLuma($color) * 100, 8),
"%");
1466 public function assertColor($value, $error =
"expected color value")
1468 $color = $this->coerceColor($value);
1469 if (is_null($color)) {
1475 public function assertNumber($value, $error =
"expecting number")
1477 if ($value[0] ==
"number") {
1483 public function assertArgs($value, $expectedArgs, $name =
"")
1485 if ($expectedArgs == 1) {
1488 if ($value[0] !==
"list" || $value[1] !=
",") {
1491 $values = $value[2];
1492 $numValues = count($values);
1493 if ($expectedArgs != $numValues) {
1498 $this->
throwError(
"${name}expecting $expectedArgs arguments, got $numValues");
1505 protected function toHSL($color)
1507 if ($color[0] ===
'hsl') {
1511 $r = $color[1] / 255;
1512 $g = $color[2] / 255;
1513 $b = $color[3] / 255;
1515 $min = min($r, $g, $b);
1516 $max = max($r, $g, $b);
1518 $L = ($min + $max) / 2;
1523 $S = ($max - $min) / ($max + $min);
1525 $S = ($max - $min) / (2.0 - $max - $min);
1528 $H = ($g - $b) / ($max - $min);
1529 } elseif ($g == $max) {
1530 $H = 2.0 + ($b - $r) / ($max - $min);
1531 } elseif ($b == $max) {
1532 $H = 4.0 + ($r - $g) / ($max - $min);
1537 ($H < 0 ? $H + 6 : $H) * 60,
1542 if (count($color) > 4) {
1549 protected function toRGB_helper($comp, $temp1, $temp2)
1553 } elseif ($comp > 1) {
1557 if (6 * $comp < 1) {
1558 return $temp1 + ($temp2 - $temp1) * 6 * $comp;
1560 if (2 * $comp < 1) {
1563 if (3 * $comp < 2) {
1564 return $temp1 + ($temp2 - $temp1) * ((2 / 3) - $comp) * 6;
1576 if ($color[0] ===
'color') {
1580 $H = $color[1] / 360;
1581 $S = $color[2] / 100;
1582 $L = $color[3] / 100;
1588 $L * (1.0 + $S) : $L + $S - $L * $S;
1590 $temp1 = 2.0 * $L - $temp2;
1592 $r = $this->toRGB_helper($H + 1 / 3, $temp1, $temp2);
1593 $g = $this->toRGB_helper($H, $temp1, $temp2);
1594 $b = $this->toRGB_helper($H - 1 / 3, $temp1, $temp2);
1598 $out = array(
'color', $r * 255, $g * 255, $b * 255);
1599 if (count($color) > 4) {
1606 protected function clamp($v, $max = 1, $min = 0)
1608 return min($max, max($min, $v));
1618 if ($func[2][0] !=
'list') {
1622 $rawComponents = $func[2][2];
1624 if ($fname ==
'hsl' || $fname ==
'hsla') {
1625 $hsl = array(
'hsl');
1627 foreach ($rawComponents as $c) {
1628 $val = $this->reduce($c);
1629 $val = isset($val[1]) ? floatval($val[1]) : 0;
1639 $hsl[] = $this->clamp($val, $clamp);
1643 while (count($hsl) < 4) {
1646 return $this->
toRGB($hsl);
1647 } elseif ($fname ==
'rgb' || $fname ==
'rgba') {
1648 $components = array();
1650 foreach ($rawComponents as $c) {
1651 $c = $this->reduce($c);
1653 if ($c[0] ==
"number" && $c[2] ==
"%") {
1654 $components[] = 255 * ($c[1] / 100);
1656 $components[] = floatval($c[1]);
1658 } elseif ($i == 4) {
1659 if ($c[0] ==
"number" && $c[2] ==
"%") {
1660 $components[] = 1.0 * ($c[1] / 100);
1662 $components[] = floatval($c[1]);
1670 while (count($components) < 3) {
1673 array_unshift($components,
'color');
1674 return $this->fixColor($components);
1680 protected function reduce($value, $forExpression =
false)
1682 switch ($value[0]) {
1684 $reduced = $this->reduce($value[1]);
1686 $res = $this->reduce(array(
"variable", $this->vPrefix.$var));
1688 if ($res[0] ==
"raw_color") {
1689 $res = $this->coerceColor($res);
1692 if (empty($value[2])) {
1693 $res = $this->lib_e($res);
1699 if (is_array($key)) {
1700 $key = $this->reduce($key);
1701 $key = $this->vPrefix.$this->compileValue($this->lib_e($key));
1704 $seen = & $this->env->seenNames;
1706 if (!empty($seen[$key])) {
1707 $this->
throwError(
"infinite loop detected: $key");
1711 $out = $this->reduce($this->
get($key));
1712 $seen[$key] =
false;
1715 foreach ($value[2] as &$item) {
1716 $item = $this->reduce($item, $forExpression);
1720 return $this->evaluate($value);
1722 foreach ($value[2] as &$part) {
1723 if (is_array($part)) {
1724 $strip = $part[0] ==
"variable";
1725 $part = $this->reduce($part);
1727 $part = $this->lib_e($part);
1733 list(,$inner) = $value;
1734 return $this->lib_e($this->reduce($inner));
1741 list(, $name, $args) = $value;
1746 $f = isset($this->libFunctions[$name]) ?
1747 $this->libFunctions[$name] : array($this,
'lib_'.str_replace(
'-',
'_', $name));
1749 if (is_callable($f)) {
1750 if ($args[0] ==
'list') {
1751 $args = self::compressList($args[2], $args[1]);
1754 $ret = call_user_func($f, $this->reduce($args,
true), $this);
1756 if (is_null($ret)) {
1757 return array(
"string",
"", array(
1758 $name,
"(", $args,
")"
1763 if (is_numeric($ret)) {
1764 $ret = array(
'number', $ret,
"");
1765 } elseif (!is_array($ret)) {
1766 $ret = array(
'keyword', $ret);
1773 $value[2] = $this->reduce($value[2]);
1776 list(, $op, $exp) = $value;
1777 $exp = $this->reduce($exp);
1779 if ($exp[0] ==
"number") {
1788 return array(
"string",
"", array($op, $exp));
1791 if ($forExpression) {
1792 switch ($value[0]) {
1794 if ($color = $this->coerceColor($value)) {
1799 return $this->coerceColor($value);
1808 protected function coerceColor($value)
1810 switch ($value[0]) {
1814 $c = array(
"color", 0, 0, 0);
1815 $colorStr = substr($value[1], 1);
1816 $num = hexdec($colorStr);
1817 $width = strlen($colorStr) == 3 ? 16 : 256;
1819 for ($i = 3; $i > 0; $i--) {
1823 $c[$i] = $t * (256 / $width) + $t * floor(16 / $width);
1829 if (isset(self::$cssColors[$name])) {
1830 $rgba = explode(
',', self::$cssColors[$name]);
1832 if (isset($rgba[3])) {
1833 return array(
'color', $rgba[0], $rgba[1], $rgba[2], $rgba[3]);
1835 return array(
'color', $rgba[0], $rgba[1], $rgba[2]);
1842 protected function coerceString($value)
1844 switch ($value[0]) {
1848 return array(
"string",
"", array($value[1]));
1854 protected function flattenList($value)
1856 if ($value[0] ==
"list" && count($value[2]) == 1) {
1857 return $this->flattenList($value[2][0]);
1862 public function toBool($a)
1864 return $a ? self::$TRUE : self::$FALSE;
1868 protected function evaluate($exp)
1870 list(, $op, $left, $right, $whiteBefore, $whiteAfter) = $exp;
1872 $left = $this->reduce($left,
true);
1873 $right = $this->reduce($right,
true);
1875 if ($leftColor = $this->coerceColor($left)) {
1879 if ($rightColor = $this->coerceColor($right)) {
1880 $right = $rightColor;
1888 return $this->toBool($left == self::$TRUE && $right == self::$TRUE);
1892 return $this->toBool($this->eq($left, $right));
1895 if ($op ==
"+" && !is_null($str = $this->stringConcatenate($left, $right))) {
1900 $fname =
"op_${ltype}_${rtype}";
1901 if (is_callable(array($this, $fname))) {
1902 $out = $this->$fname($op, $left, $right);
1903 if (!is_null($out)) {
1911 $paddedOp =
" ".$paddedOp;
1917 return array(
"string",
"", array($left, $paddedOp, $right));
1920 protected function stringConcatenate($left, $right)
1922 if ($strLeft = $this->coerceString($left)) {
1923 if ($right[0] ==
"string") {
1926 $strLeft[2][] = $right;
1930 if ($strRight = $this->coerceString($right)) {
1931 array_unshift($strRight[2], $left);
1938 protected function fixColor($c)
1940 foreach (range(1, 3) as $i) {
1952 protected function op_number_color($op, $lft, $rgt)
1954 if ($op ==
'+' || $op ==
'*') {
1955 return $this->op_color_number($op, $rgt, $lft);
1959 protected function op_color_number($op, $lft, $rgt)
1961 if ($rgt[0] ==
'%') {
1965 return $this->op_color_color(
1968 array_fill(1, count($lft) - 1, $rgt[1])
1972 protected function op_color_color($op, $left, $right)
1974 $out = array(
'color');
1975 $max = count($left) > count($right) ? count($left) : count($right);
1976 foreach (range(1, $max - 1) as $i) {
1977 $lval = isset($left[$i]) ? $left[$i] : 0;
1978 $rval = isset($right[$i]) ? $right[$i] : 0;
1981 $out[] = $lval + $rval;
1984 $out[] = $lval - $rval;
1987 $out[] = $lval * $rval;
1990 $out[] = $lval % $rval;
1994 $this->
throwError(
"evaluate error: can't divide by zero");
1996 $out[] = $lval / $rval;
1999 $this->
throwError(
'evaluate error: color op number failed on op '.$op);
2002 return $this->fixColor($out);
2005 public function lib_red($color)
2007 $color = $this->coerceColor($color);
2008 if (is_null($color)) {
2009 $this->
throwError(
'color expected for red()');
2015 public function lib_green($color)
2017 $color = $this->coerceColor($color);
2018 if (is_null($color)) {
2019 $this->
throwError(
'color expected for green()');
2025 public function lib_blue($color)
2027 $color = $this->coerceColor($color);
2028 if (is_null($color)) {
2029 $this->
throwError(
'color expected for blue()');
2037 protected function op_number_number($op, $left, $right)
2039 $unit = empty($left[2]) ? $right[2] : $left[2];
2044 $value = $left[1] + $right[1];
2047 $value = $left[1] * $right[1];
2050 $value = $left[1] - $right[1];
2053 $value = $left[1] % $right[1];
2056 if ($right[1] == 0) {
2057 $this->
throwError(
'parse error: divide by zero');
2059 $value = $left[1] / $right[1];
2062 return $this->toBool($left[1] < $right[1]);
2064 return $this->toBool($left[1] > $right[1]);
2066 return $this->toBool($left[1] >= $right[1]);
2068 return $this->toBool($left[1] <= $right[1]);
2070 $this->
throwError(
'parse error: unknown number operator: '.$op);
2073 return array(
"number", $value, $unit);
2079 protected function makeOutputBlock($type, $selectors =
null)
2082 $b->lines = array();
2083 $b->children = array();
2084 $b->selectors = $selectors;
2086 $b->parent = $this->scope;
2091 protected function pushEnv($block =
null)
2094 $e->parent = $this->env;
2095 $e->store = array();
2103 protected function popEnv()
2106 $this->env = $this->env->parent;
2111 protected function set($name, $value)
2113 $this->env->store[$name] = $value;
2118 protected function get($name)
2120 $current = $this->env;
2122 $isArguments = $name == $this->vPrefix.
'arguments';
2124 if ($isArguments && isset($current->arguments)) {
2125 return array(
'list',
' ', $current->arguments);
2128 if (isset($current->store[$name])) {
2129 return $current->store[$name];
2132 $current = isset($current->storeParent) ?
2133 $current->storeParent : $current->parent;
2136 $this->
throwError(
"variable $name is undefined");
2140 protected function injectVariables($args)
2144 foreach ($args as $name => $strValue) {
2145 if ($name[0] !==
'@') {
2149 $parser->buffer = (string) $strValue;
2150 if (!$parser->propertyValue($value)) {
2151 throw new Exception(
"failed to parse passed in variable $name: $strValue");
2154 $this->
set($name, $value);
2164 if ($fname !==
null) {
2166 $this->_parseFile = $fname;
2170 public function compile($string, $name =
null)
2172 $locale = setlocale(LC_NUMERIC, 0);
2173 setlocale(LC_NUMERIC,
"C");
2175 $this->parser = $this->makeParser($name);
2176 $root = $this->parser->parse($string);
2179 $this->scope =
null;
2181 $this->formatter = $this->newFormatter();
2183 if (!empty($this->registeredVars)) {
2184 $this->injectVariables($this->registeredVars);
2187 $this->sourceParser = $this->parser;
2191 $this->formatter->block($this->scope);
2192 $out = ob_get_clean();
2193 setlocale(LC_NUMERIC, $locale);
2197 public function compileFile($fname, $outFname =
null)
2199 if (!is_readable($fname)) {
2200 throw new Exception(
'load error: failed to find '.$fname);
2203 $pi = pathinfo($fname);
2205 $oldImport = $this->importDir;
2207 $this->importDir = (array) $this->importDir;
2208 $this->importDir[] = $pi[
'dirname'].
'/';
2210 $this->addParsedFile($fname);
2212 $out = $this->compile(file_get_contents($fname), $fname);
2214 $this->importDir = $oldImport;
2216 if ($outFname !==
null) {
2217 return file_put_contents($outFname, $out);
2224 public function checkedCompile($in, $out)
2226 if (!is_file($out) || filemtime($in) > filemtime($out)) {
2227 $this->compileFile($in, $out);
2258 if (is_string($in)) {
2260 } elseif (is_array($in) && isset($in[
'root'])) {
2261 if ($force || !isset($in[
'files'])) {
2265 $root = $in[
'root'];
2266 } elseif (isset($in[
'files']) && is_array($in[
'files'])) {
2267 foreach ($in[
'files'] as $fname => $ftime) {
2268 if (!file_exists($fname) || filemtime($fname) > $ftime) {
2271 $root = $in[
'root'];
2282 if ($root !==
null) {
2285 $out[
'root'] = $root;
2286 $out[
'compiled'] = $this->compileFile($root);
2287 $out[
'files'] = $this->allParsedFiles();
2288 $out[
'updated'] = time();
2299 public function parse($str =
null, $initialVariables =
null)
2301 if (is_array($str)) {
2302 $initialVariables = $str;
2306 $oldVars = $this->registeredVars;
2307 if ($initialVariables !==
null) {
2308 $this->setVariables($initialVariables);
2312 if (empty($this->_parseFile)) {
2313 throw new exception(
"nothing to parse");
2316 $out = $this->compileFile($this->_parseFile);
2318 $out = $this->compile($str);
2321 $this->registeredVars = $oldVars;
2325 protected function makeParser($name)
2328 $parser->writeComments = $this->preserveComments;
2333 public function setFormatter($name)
2335 $this->formatterName = $name;
2338 protected function newFormatter()
2340 $className =
"lessc_formatter_lessjs";
2341 if (!empty($this->formatterName)) {
2342 if (!is_string($this->formatterName)) {
2343 return $this->formatterName;
2345 $className =
"lessc_formatter_$this->formatterName";
2348 return new $className;
2351 public function setPreserveComments($preserve)
2353 $this->preserveComments = $preserve;
2356 public function registerFunction($name, $func)
2358 $this->libFunctions[$name] = $func;
2361 public function unregisterFunction($name)
2363 unset($this->libFunctions[$name]);
2366 public function setVariables($variables)
2368 $this->registeredVars = array_merge($this->registeredVars, $variables);
2371 public function unsetVariable($name)
2373 unset($this->registeredVars[$name]);
2376 public function setImportDir($dirs)
2378 $this->importDir = (array) $dirs;
2381 public function addImportDir($dir)
2383 $this->importDir = (array) $this->importDir;
2384 $this->importDir[] = $dir;
2387 public function allParsedFiles()
2389 return $this->allParsedFiles;
2392 public function addParsedFile($file)
2394 $this->allParsedFiles[realpath($file)] = filemtime($file);
2402 if ($this->sourceLoc >= 0) {
2403 $this->sourceParser->throwError($msg, $this->sourceLoc);
2405 throw new exception($msg);
2410 public static function ccompile($in, $out, $less =
null)
2412 if ($less ===
null) {
2415 return $less->checkedCompile($in, $out);
2418 public static function cexecute($in, $force =
false, $less =
null)
2420 if ($less ===
null) {
2423 return $less->cachedCompile($in, $force);
2426 protected static $cssColors = array(
2427 'aliceblue' =>
'240,248,255',
2428 'antiquewhite' =>
'250,235,215',
2429 'aqua' =>
'0,255,255',
2430 'aquamarine' =>
'127,255,212',
2431 'azure' =>
'240,255,255',
2432 'beige' =>
'245,245,220',
2433 'bisque' =>
'255,228,196',
2435 'blanchedalmond' =>
'255,235,205',
2436 'blue' =>
'0,0,255',
2437 'blueviolet' =>
'138,43,226',
2438 'brown' =>
'165,42,42',
2439 'burlywood' =>
'222,184,135',
2440 'cadetblue' =>
'95,158,160',
2441 'chartreuse' =>
'127,255,0',
2442 'chocolate' =>
'210,105,30',
2443 'coral' =>
'255,127,80',
2444 'cornflowerblue' =>
'100,149,237',
2445 'cornsilk' =>
'255,248,220',
2446 'crimson' =>
'220,20,60',
2447 'cyan' =>
'0,255,255',
2448 'darkblue' =>
'0,0,139',
2449 'darkcyan' =>
'0,139,139',
2450 'darkgoldenrod' =>
'184,134,11',
2451 'darkgray' =>
'169,169,169',
2452 'darkgreen' =>
'0,100,0',
2453 'darkgrey' =>
'169,169,169',
2454 'darkkhaki' =>
'189,183,107',
2455 'darkmagenta' =>
'139,0,139',
2456 'darkolivegreen' =>
'85,107,47',
2457 'darkorange' =>
'255,140,0',
2458 'darkorchid' =>
'153,50,204',
2459 'darkred' =>
'139,0,0',
2460 'darksalmon' =>
'233,150,122',
2461 'darkseagreen' =>
'143,188,143',
2462 'darkslateblue' =>
'72,61,139',
2463 'darkslategray' =>
'47,79,79',
2464 'darkslategrey' =>
'47,79,79',
2465 'darkturquoise' =>
'0,206,209',
2466 'darkviolet' =>
'148,0,211',
2467 'deeppink' =>
'255,20,147',
2468 'deepskyblue' =>
'0,191,255',
2469 'dimgray' =>
'105,105,105',
2470 'dimgrey' =>
'105,105,105',
2471 'dodgerblue' =>
'30,144,255',
2472 'firebrick' =>
'178,34,34',
2473 'floralwhite' =>
'255,250,240',
2474 'forestgreen' =>
'34,139,34',
2475 'fuchsia' =>
'255,0,255',
2476 'gainsboro' =>
'220,220,220',
2477 'ghostwhite' =>
'248,248,255',
2478 'gold' =>
'255,215,0',
2479 'goldenrod' =>
'218,165,32',
2480 'gray' =>
'128,128,128',
2481 'green' =>
'0,128,0',
2482 'greenyellow' =>
'173,255,47',
2483 'grey' =>
'128,128,128',
2484 'honeydew' =>
'240,255,240',
2485 'hotpink' =>
'255,105,180',
2486 'indianred' =>
'205,92,92',
2487 'indigo' =>
'75,0,130',
2488 'ivory' =>
'255,255,240',
2489 'khaki' =>
'240,230,140',
2490 'lavender' =>
'230,230,250',
2491 'lavenderblush' =>
'255,240,245',
2492 'lawngreen' =>
'124,252,0',
2493 'lemonchiffon' =>
'255,250,205',
2494 'lightblue' =>
'173,216,230',
2495 'lightcoral' =>
'240,128,128',
2496 'lightcyan' =>
'224,255,255',
2497 'lightgoldenrodyellow' =>
'250,250,210',
2498 'lightgray' =>
'211,211,211',
2499 'lightgreen' =>
'144,238,144',
2500 'lightgrey' =>
'211,211,211',
2501 'lightpink' =>
'255,182,193',
2502 'lightsalmon' =>
'255,160,122',
2503 'lightseagreen' =>
'32,178,170',
2504 'lightskyblue' =>
'135,206,250',
2505 'lightslategray' =>
'119,136,153',
2506 'lightslategrey' =>
'119,136,153',
2507 'lightsteelblue' =>
'176,196,222',
2508 'lightyellow' =>
'255,255,224',
2509 'lime' =>
'0,255,0',
2510 'limegreen' =>
'50,205,50',
2511 'linen' =>
'250,240,230',
2512 'magenta' =>
'255,0,255',
2513 'maroon' =>
'128,0,0',
2514 'mediumaquamarine' =>
'102,205,170',
2515 'mediumblue' =>
'0,0,205',
2516 'mediumorchid' =>
'186,85,211',
2517 'mediumpurple' =>
'147,112,219',
2518 'mediumseagreen' =>
'60,179,113',
2519 'mediumslateblue' =>
'123,104,238',
2520 'mediumspringgreen' =>
'0,250,154',
2521 'mediumturquoise' =>
'72,209,204',
2522 'mediumvioletred' =>
'199,21,133',
2523 'midnightblue' =>
'25,25,112',
2524 'mintcream' =>
'245,255,250',
2525 'mistyrose' =>
'255,228,225',
2526 'moccasin' =>
'255,228,181',
2527 'navajowhite' =>
'255,222,173',
2528 'navy' =>
'0,0,128',
2529 'oldlace' =>
'253,245,230',
2530 'olive' =>
'128,128,0',
2531 'olivedrab' =>
'107,142,35',
2532 'orange' =>
'255,165,0',
2533 'orangered' =>
'255,69,0',
2534 'orchid' =>
'218,112,214',
2535 'palegoldenrod' =>
'238,232,170',
2536 'palegreen' =>
'152,251,152',
2537 'paleturquoise' =>
'175,238,238',
2538 'palevioletred' =>
'219,112,147',
2539 'papayawhip' =>
'255,239,213',
2540 'peachpuff' =>
'255,218,185',
2541 'peru' =>
'205,133,63',
2542 'pink' =>
'255,192,203',
2543 'plum' =>
'221,160,221',
2544 'powderblue' =>
'176,224,230',
2545 'purple' =>
'128,0,128',
2547 'rosybrown' =>
'188,143,143',
2548 'royalblue' =>
'65,105,225',
2549 'saddlebrown' =>
'139,69,19',
2550 'salmon' =>
'250,128,114',
2551 'sandybrown' =>
'244,164,96',
2552 'seagreen' =>
'46,139,87',
2553 'seashell' =>
'255,245,238',
2554 'sienna' =>
'160,82,45',
2555 'silver' =>
'192,192,192',
2556 'skyblue' =>
'135,206,235',
2557 'slateblue' =>
'106,90,205',
2558 'slategray' =>
'112,128,144',
2559 'slategrey' =>
'112,128,144',
2560 'snow' =>
'255,250,250',
2561 'springgreen' =>
'0,255,127',
2562 'steelblue' =>
'70,130,180',
2563 'tan' =>
'210,180,140',
2564 'teal' =>
'0,128,128',
2565 'thistle' =>
'216,191,216',
2566 'tomato' =>
'255,99,71',
2567 'transparent' =>
'0,0,0,0',
2568 'turquoise' =>
'64,224,208',
2569 'violet' =>
'238,130,238',
2570 'wheat' =>
'245,222,179',
2571 'white' =>
'255,255,255',
2572 'whitesmoke' =>
'245,245,245',
2573 'yellow' =>
'255,255,0',
2574 'yellowgreen' =>
'154,205,50'
2582 protected static $nextBlockId = 0;
2584 protected static $precedence = array(
2598 protected static $whitePattern;
2599 protected static $commentMulti;
2601 protected static $commentSingle =
"//";
2602 protected static $commentMultiLeft =
"/*";
2603 protected static $commentMultiRight =
"*/";
2606 protected static $operatorString;
2609 protected static $supressDivisionProps =
2610 array(
'/border-radius$/i',
'/^font$/i');
2612 protected $blockDirectives = array(
"font-face",
"keyframes",
"page",
"-moz-document",
"viewport",
"-moz-viewport",
"-o-viewport",
"-ms-viewport");
2613 protected $lineDirectives = array(
"charset");
2627 protected static $literalCache = array();
2629 public function __construct($lessc, $sourceName =
null)
2631 $this->eatWhiteDefault =
true;
2633 $this->lessc = $lessc;
2635 $this->sourceName = $sourceName;
2637 $this->writeComments =
false;
2639 if (!self::$operatorString) {
2640 self::$operatorString =
2641 '('.implode(
'|', array_map(
2642 array(
'lessc',
'preg_quote'),
2643 array_keys(self::$precedence)
2646 $commentSingle = lessc::preg_quote(self::$commentSingle);
2647 $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
2648 $commentMultiRight = lessc::preg_quote(self::$commentMultiRight);
2650 self::$commentMulti = $commentMultiLeft.
'.*?'.$commentMultiRight;
2651 self::$whitePattern =
'/'.$commentSingle.
'[^\n]*\s*|('.self::$commentMulti.
')\s*|\s+/Ais';
2668 $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
2669 $this->pushSpecialBlock(
"root");
2670 $this->eatWhiteDefault =
true;
2671 $this->seenComments = array();
2678 $this->whitespace();
2683 if ($this->count != strlen($this->buffer)) {
2684 $this->throwError(
'parse error count '.$this->count.
' != len buffer '.strlen($this->buffer));
2688 if (!property_exists($this->env,
'parent') || !is_null($this->env->parent)) {
2689 throw new exception(
'parse error: unclosed block');
2733 if (empty($this->buffer)) {
2738 if ($this->whitespace()) {
2743 if ($this->keyword($key) && $this->
assign() &&
2744 $this->propertyValue($value, $key) && $this->end()
2746 $this->append(array(
'assign', $key, $value), $s);
2754 if ($this->literal(
'@',
false)) {
2758 if ($this->literal(
'@media')) {
2759 if (($this->mediaQueryList($mediaQueries) ||
true)
2760 && $this->literal(
'{')
2762 $media = $this->pushSpecialBlock(
"media");
2763 $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
2771 if ($this->literal(
"@",
false) && $this->keyword($dirName)) {
2772 if ($this->isDirective($dirName, $this->blockDirectives)) {
2773 if (($this->openString(
"{", $dirValue,
null, array(
";")) ||
true) &&
2776 $dir = $this->pushSpecialBlock(
"directive");
2777 $dir->name = $dirName;
2778 if (isset($dirValue)) {
2779 $dir->value = $dirValue;
2783 } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
2784 if ($this->propertyValue($dirValue) && $this->end()) {
2785 $this->append(array(
"directive", $dirName, $dirValue));
2795 if ($this->variable($var) && $this->
assign() &&
2796 $this->propertyValue($value) && $this->end()
2798 $this->append(array(
'assign', $var, $value), $s);
2804 if ($this->
import($importValue)) {
2805 $this->append($importValue, $s);
2810 if ($this->tag($tag,
true) && $this->argumentDef($args, $isVararg) &&
2811 ($this->guards($guards) ||
true) &&
2814 $block = $this->pushBlock($this->fixTags(array($tag)));
2815 $block->args = $args;
2816 $block->isVararg = $isVararg;
2817 if (!empty($guards)) {
2818 $block->guards = $guards;
2826 if ($this->tags($tags) && $this->literal(
'{',
false)) {
2827 $tags = $this->fixTags($tags);
2828 $this->pushBlock($tags);
2835 if ($this->literal(
'}',
false)) {
2837 $block = $this->pop();
2838 }
catch (exception $e) {
2840 $this->throwError($e->getMessage());
2844 if (is_null($block->type)) {
2846 if (!isset($block->args)) {
2847 foreach ($block->tags as $tag) {
2848 if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix) {
2855 foreach ($block->tags as $tag) {
2856 if (is_string($tag)) {
2857 $this->env->children[$tag][] = $block;
2863 $this->append(array(
'block', $block), $s);
2868 $this->whitespace();
2873 if ($this->mixinTags($tags) &&
2874 ($this->argumentDef($argv, $isVararg) ||
true) &&
2875 ($this->keyword($suffix) ||
true) && $this->end()
2877 $tags = $this->fixTags($tags);
2878 $this->append(array(
'mixin', $tags, $argv, $suffix), $s);
2885 if ($this->literal(
';')) {
2892 protected function isDirective($dirname, $directives)
2897 array_map(array(
"lessc",
"preg_quote"), $directives)
2899 $pattern =
'/^(-[a-z-]+-)?('.$pattern.
')$/i';
2901 return preg_match($pattern, $dirname);
2904 protected function fixTags($tags)
2907 foreach ($tags as &$tag) {
2908 if ($tag[0] == $this->lessc->vPrefix) {
2909 $tag[0] = $this->lessc->mPrefix;
2916 protected function expressionList(&$exps)
2924 if (count($values) == 0) {
2928 $exps = lessc::compressList($values,
' ');
2938 if ($this->value($lhs)) {
2942 if (!empty($this->env->supressedDivision)) {
2943 unset($this->env->supressedDivision);
2945 if ($this->literal(
"/") && $this->value($rhs)) {
2946 $out = array(
"list",
"",
2947 array($out, array(
"keyword",
"/"), $rhs));
2963 $this->inExp =
true;
2964 $ss = $this->seek();
2967 $whiteBefore = isset($this->buffer[$this->count - 1]) &&
2968 ctype_space($this->buffer[$this->count - 1]);
2974 if ($this->match(self::$operatorString.($needWhite ?
'\s' :
''), $m) && self::$precedence[$m[1]] >= $minP) {
2975 if (!$this->inParens && isset($this->env->currentProperty) && $m[1] ==
"/" && empty($this->env->supressedDivision)) {
2976 foreach (self::$supressDivisionProps as $pattern) {
2977 if (preg_match($pattern, $this->env->currentProperty)) {
2978 $this->env->supressedDivision =
true;
2985 $whiteAfter = isset($this->buffer[$this->count - 1]) &&
2986 ctype_space($this->buffer[$this->count - 1]);
2988 if (!$this->value($rhs)) {
2993 if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
2994 $rhs = $this->
expHelper($rhs, self::$precedence[$next[1]]);
2997 $lhs = array(
'expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
2998 $ss = $this->seek();
3012 public function propertyValue(&$value, $keyName =
null)
3016 if ($keyName !==
null) {
3017 $this->env->currentProperty = $keyName;
3021 while ($this->expressionList($v)) {
3024 if (!$this->literal(
',')) {
3033 if ($keyName !==
null) {
3034 unset($this->env->currentProperty);
3037 if (count($values) == 0) {
3041 $value = lessc::compressList($values,
', ');
3045 protected function parenValue(&$out)
3050 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] !=
"(") {
3055 if ($this->literal(
"(") &&
3056 ($this->inParens =
true) && $this->
expression($exp) &&
3071 protected function value(&$value)
3076 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] ==
"-") {
3078 if ($this->literal(
"-",
false) &&
3079 (($this->variable($inner) && $inner = array(
"variable", $inner)) ||
3080 $this->unit($inner) ||
3081 $this->parenValue($inner))
3083 $value = array(
"unary",
"-", $inner);
3090 if ($this->parenValue($value)) {
3093 if ($this->unit($value)) {
3096 if ($this->color($value)) {
3099 if ($this->func($value)) {
3102 if ($this->
string($value)) {
3106 if ($this->keyword($word)) {
3107 $value = array(
'keyword', $word);
3112 if ($this->variable($var)) {
3113 $value = array(
'variable', $var);
3118 if ($this->literal(
"~") && $this->
string($str)) {
3119 $value = array(
"escape", $str);
3126 if ($this->literal(
'\\') && $this->match(
'([0-9]+)', $m)) {
3127 $value = array(
'keyword',
'\\'.$m[1]);
3137 protected function import(&$out)
3139 if (!$this->literal(
'@import')) {
3147 if ($this->propertyValue($value)) {
3148 $out = array(
"import", $value);
3153 protected function mediaQueryList(&$out)
3155 if ($this->genericList($list,
"mediaQuery",
",",
false)) {
3162 protected function mediaQuery(&$out)
3166 $expressions =
null;
3169 if (($this->literal(
"only") && ($only =
true) || $this->literal(
"not") && ($not =
true) ||
true) && $this->keyword($mediaType)) {
3170 $prop = array(
"mediaType");
3177 $prop[] = $mediaType;
3184 if (!empty($mediaType) && !$this->literal(
"and")) {
3187 $this->genericList($expressions,
"mediaExpression",
"and",
false);
3188 if (is_array($expressions)) {
3189 $parts = array_merge($parts, $expressions[2]);
3193 if (count($parts) == 0) {
3202 protected function mediaExpression(&$out)
3206 if ($this->literal(
"(") &&
3207 $this->keyword($feature) &&
3208 ($this->literal(
":") && $this->
expression($value) ||
true) &&
3211 $out = array(
"mediaExp", $feature);
3216 } elseif ($this->variable($variable)) {
3217 $out = array(
'variable', $variable);
3226 protected function openString($end, &$out, $nestingOpen =
null, $rejectStrs =
null)
3228 $oldWhite = $this->eatWhiteDefault;
3229 $this->eatWhiteDefault =
false;
3231 $stop = array(
"'",
'"',
"@{", $end);
3232 $stop = array_map(array(
"lessc",
"preg_quote"), $stop);
3235 if (!is_null($rejectStrs)) {
3236 $stop = array_merge($stop, $rejectStrs);
3239 $patt =
'(.*?)('.implode(
"|", $stop).
')';
3244 while ($this->match($patt, $m,
false)) {
3245 if (!empty($m[1])) {
3248 $nestingLevel += substr_count($m[1], $nestingOpen);
3254 $this->count -= strlen($tok);
3256 if ($nestingLevel == 0) {
3263 if (($tok ==
"'" || $tok ==
'"') && $this->
string($str)) {
3268 if ($tok ==
"@{" && $this->interpolation($inter)) {
3269 $content[] = $inter;
3273 if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
3278 $this->count += strlen($tok);
3281 $this->eatWhiteDefault = $oldWhite;
3283 if (count($content) == 0) {
3288 if (is_string(end($content))) {
3289 $content[count($content) - 1] = rtrim(end($content));
3292 $out = array(
"string",
"", $content);
3296 protected function string(&$out)
3299 if ($this->literal(
'"',
false)) {
3301 } elseif ($this->literal(
"'",
false)) {
3310 $patt =
'([^\n]*?)(@\{|\\\\|'.
3311 lessc::preg_quote($delim).
')';
3313 $oldWhite = $this->eatWhiteDefault;
3314 $this->eatWhiteDefault =
false;
3316 while ($this->match($patt, $m,
false)) {
3318 if ($m[2] ==
"@{") {
3319 $this->count -= strlen($m[2]);
3320 if ($this->interpolation($inter)) {
3321 $content[] = $inter;
3323 $this->count += strlen($m[2]);
3326 } elseif ($m[2] ==
'\\') {
3328 if ($this->literal($delim,
false)) {
3329 $content[] = $delim;
3332 $this->count -= strlen($delim);
3337 $this->eatWhiteDefault = $oldWhite;
3339 if ($this->literal($delim)) {
3340 $out = array(
"string", $delim, $content);
3348 protected function interpolation(&$out)
3350 $oldWhite = $this->eatWhiteDefault;
3351 $this->eatWhiteDefault =
true;
3354 if ($this->literal(
"@{") &&
3355 $this->openString(
"}", $interp,
null, array(
"'",
'"',
";")) &&
3356 $this->literal(
"}",
false)
3358 $out = array(
"interpolate", $interp);
3359 $this->eatWhiteDefault = $oldWhite;
3360 if ($this->eatWhiteDefault) {
3361 $this->whitespace();
3366 $this->eatWhiteDefault = $oldWhite;
3371 protected function unit(&$unit)
3374 if (isset($this->buffer[$this->count])) {
3375 $char = $this->buffer[$this->count];
3376 if (!ctype_digit($char) && $char !=
".") {
3381 if ($this->match(
'([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
3382 $unit = array(
"number", $m[1], empty($m[2]) ?
"" : $m[2]);
3389 protected function color(&$out)
3391 if ($this->match(
'(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
3392 if (strlen($m[1]) > 7) {
3393 $out = array(
"string",
"", array($m[1]));
3395 $out = array(
"raw_color", $m[1]);
3408 protected function argumentDef(&$args, &$isVararg)
3411 if (!$this->literal(
'(')) {
3417 $method =
"expressionList";
3421 if ($this->literal(
"...")) {
3426 if ($this->$method($value)) {
3427 if ($value[0] ==
"variable") {
3428 $arg = array(
"arg", $value[1]);
3429 $ss = $this->seek();
3431 if ($this->
assign() && $this->$method($rhs)) {
3435 if ($this->literal(
"...")) {
3447 $values[] = array(
"lit", $value);
3452 if (!$this->literal($delim)) {
3453 if ($delim ==
"," && $this->literal(
";")) {
3456 $method =
"propertyValue";
3459 if (isset($values[1])) {
3461 foreach ($values as $i => $arg) {
3465 $this->throwError(
"Cannot mix ; and , as delimiter types");
3467 $newList[] = $arg[2];
3470 $newList[] = $arg[1];
3473 $this->throwError(
"Unexpected rest before semicolon");
3477 $newList = array(
"list",
", ", $newList);
3479 switch ($values[0][0]) {
3481 $newArg = array(
"arg", $values[0][1], $newList);
3484 $newArg = array(
"lit", $newList);
3487 } elseif ($values) {
3488 $newArg = $values[0];
3492 $values = array($newArg);
3500 if (!$this->literal(
')')) {
3512 protected function tags(&$tags, $simple =
false, $delim =
',')
3515 while ($this->tag($tt, $simple)) {
3517 if (!$this->literal($delim)) {
3521 if (count($tags) == 0) {
3530 protected function mixinTags(&$tags)
3533 while ($this->tag($tt,
true)) {
3535 $this->literal(
">");
3546 protected function tagBracket(&$parts, &$hasExpression)
3549 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] !=
"[") {
3555 $hasInterpolation =
false;
3557 if ($this->literal(
"[",
false)) {
3558 $attrParts = array(
"[");
3561 if ($this->literal(
"]",
false)) {
3566 if ($this->match(
'\s+', $m)) {
3570 if ($this->
string($str)) {
3572 foreach ($str[2] as &$chunk) {
3573 $chunk = str_replace($this->lessc->parentSelector,
"$&$", $chunk);
3576 $attrParts[] = $str;
3577 $hasInterpolation =
true;
3581 if ($this->keyword($word)) {
3582 $attrParts[] = $word;
3586 if ($this->interpolation($inter)) {
3587 $attrParts[] = $inter;
3588 $hasInterpolation =
true;
3593 if ($this->match(
'[|-~\$\*\^=]+', $m)) {
3594 $attrParts[] = $m[0];
3601 if ($this->literal(
"]",
false)) {
3603 foreach ($attrParts as $part) {
3606 $hasExpression = $hasExpression || $hasInterpolation;
3617 protected function tag(&$tag, $simple =
false)
3620 $chars =
'^@,:;{}\][>\(\) "\'';
3622 $chars =
'^@,;{}["\'';
3626 $hasExpression =
false;
3628 while ($this->tagBracket($parts, $hasExpression));
3630 $oldWhite = $this->eatWhiteDefault;
3631 $this->eatWhiteDefault =
false;
3634 if ($this->match(
'(['.$chars.
'0-9]['.$chars.
']*)', $m)) {
3640 while ($this->tagBracket($parts, $hasExpression));
3644 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] ==
"@") {
3645 if ($this->interpolation($interp)) {
3646 $hasExpression =
true;
3652 if ($this->literal(
"@")) {
3658 if ($this->unit($unit)) {
3659 $parts[] = $unit[1];
3660 $parts[] = $unit[2];
3667 $this->eatWhiteDefault = $oldWhite;
3673 if ($hasExpression) {
3674 $tag = array(
"exp", array(
"string",
"", $parts));
3676 $tag = trim(implode($parts));
3679 $this->whitespace();
3684 protected function func(&$func)
3688 if ($this->match(
'(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal(
'(')) {
3691 $sPreArgs = $this->seek();
3695 $ss = $this->seek();
3697 if ($this->keyword($name) && $this->literal(
'=') && $this->expressionList($value)) {
3698 $args[] = array(
"string",
"", array($name,
"=", $value));
3701 if ($this->expressionList($value)) {
3706 if (!$this->literal(
',')) {
3710 $args = array(
'list',
',', $args);
3712 if ($this->literal(
')')) {
3713 $func = array(
'function', $fname, $args);
3715 } elseif ($fname ==
'url') {
3717 $this->seek($sPreArgs);
3718 if ($this->openString(
")", $string) && $this->literal(
")")) {
3719 $func = array(
'function', $fname, $string);
3730 protected function variable(&$name)
3733 if ($this->literal($this->lessc->vPrefix,
false) &&
3734 ($this->variable($sub) || $this->keyword($name))
3737 $name = array(
'variable', $sub);
3739 $name = $this->lessc->vPrefix.$name;
3756 $this->currentProperty = $name;
3758 return $this->literal(
':') || $this->literal(
'=');
3762 protected function keyword(&$word)
3764 if ($this->match(
'([\w_\-\*!"][\w\-_"]*)', $m)) {
3772 protected function end()
3774 if ($this->literal(
';',
false)) {
3776 } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] ==
'}') {
3783 protected function guards(&$guards)
3787 if (!$this->literal(
"when")) {
3794 while ($this->guardGroup($g)) {
3796 if (!$this->literal(
",")) {
3801 if (count($guards) == 0) {
3812 protected function guardGroup(&$guardGroup)
3815 $guardGroup = array();
3816 while ($this->guard($guard)) {
3817 $guardGroup[] = $guard;
3818 if (!$this->literal(
"and")) {
3823 if (count($guardGroup) == 0) {
3832 protected function guard(&$guard)
3835 $negate = $this->literal(
"not");
3837 if ($this->literal(
"(") && $this->
expression($exp) && $this->literal(
")")) {
3840 $guard = array(
"negate", $guard);
3851 protected function literal($what, $eatWhitespace =
null)
3853 if ($eatWhitespace ===
null) {
3854 $eatWhitespace = $this->eatWhiteDefault;
3858 if (!isset($what[1]) && isset($this->buffer[$this->count])) {
3859 if ($this->buffer[$this->count] == $what) {
3860 if (!$eatWhitespace) {
3870 if (!isset(self::$literalCache[$what])) {
3871 self::$literalCache[$what] = lessc::preg_quote($what);
3874 return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
3877 protected function genericList(&$out, $parseItem, $delim =
"", $flatten =
true)
3881 while ($this->$parseItem($value)) {
3884 if (!$this->literal($delim)) {
3890 if (count($items) == 0) {
3895 if ($flatten && count($items) == 1) {
3898 $out = array(
"list", $delim, $items);
3908 protected function to($what, &$out, $until =
false, $allowNewline =
false)
3910 if (is_string($allowNewline)) {
3911 $validChars = $allowNewline;
3913 $validChars = $allowNewline ?
"." :
"[^\n]";
3915 if (!$this->match(
'('.$validChars.
'*?)'.lessc::preg_quote($what), $m, !$until)) {
3919 $this->count -= strlen($what);
3926 protected function match($regex, &$out, $eatWhitespace =
null)
3928 if ($eatWhitespace ===
null) {
3929 $eatWhitespace = $this->eatWhiteDefault;
3932 $r =
'/'.$regex.($eatWhitespace && !$this->writeComments ?
'\s*' :
'').
'/Ais';
3933 if (preg_match($r, $this->buffer, $out,
null, $this->count)) {
3934 $this->count += strlen($out[0]);
3935 if ($eatWhitespace && $this->writeComments) {
3936 $this->whitespace();
3944 protected function whitespace()
3946 if ($this->writeComments) {
3948 while (preg_match(self::$whitePattern, $this->buffer, $m,
null, $this->count)) {
3949 if (isset($m[1]) && empty($this->seenComments[$this->count])) {
3950 $this->append(array(
"comment", $m[1]));
3951 $this->seenComments[$this->count] =
true;
3953 $this->count += strlen($m[0]);
3958 $this->match(
"", $m);
3959 return strlen($m[0]) > 0;
3964 protected function peek($regex, &$out =
null, $from =
null)
3966 if (is_null($from)) {
3967 $from = $this->count;
3969 $r =
'/'.$regex.
'/Ais';
3970 $result = preg_match($r, $this->buffer, $out,
null, $from);
3976 protected function seek($where =
null)
3978 if ($where ===
null) {
3979 return $this->count;
3981 $this->count = $where;
3988 public function throwError($msg =
"parse error", $count =
null)
3990 $count = is_null($count) ? $this->count : $count;
3992 $line = $this->line +
3993 substr_count(substr($this->buffer, 0, $count),
"\n");
3995 if (!empty($this->sourceName)) {
3996 $loc =
"$this->sourceName on line $line";
3998 $loc =
"line: $line";
4002 if ($this->peek(
"(.*?)(\n|$)", $m, $count)) {
4003 throw new exception(
"$msg: failed at `$m[1]` $loc");
4005 throw new exception(
"$msg: $loc");
4009 protected function pushBlock($selectors =
null, $type =
null)
4012 $b->parent = $this->env;
4015 $b->id = self::$nextBlockId++;
4017 $b->isVararg =
false;
4018 $b->tags = $selectors;
4020 $b->props = array();
4021 $b->children = array();
4028 protected function pushSpecialBlock($type)
4030 return $this->pushBlock(
null, $type);
4034 protected function append($prop, $pos =
null)
4036 if ($pos !==
null) {
4039 $this->env->props[] = $prop;
4043 protected function pop()
4046 $this->env = $this->env->parent;
4052 protected function removeComments($text)
4055 'url(',
'//',
'/*',
'"',
"'"
4062 foreach ($look as $token) {
4063 $pos = strpos($text, $token);
4064 if ($pos !==
false) {
4065 if (!isset($min) || $pos < $min[1]) {
4066 $min = array($token, $pos);
4071 if (is_null($min)) {
4080 if (preg_match(
'/url\(.*?\)/', $text, $m, 0, $count)) {
4081 $count += strlen($m[0]) - strlen($min[0]);
4086 if (preg_match(
'/'.$min[0].
'.*?(?<!\\\\)'.$min[0].
'/', $text, $m, 0, $count)) {
4087 $count += strlen($m[0]) - 1;
4091 $skip = strpos($text,
"\n", $count);
4092 if ($skip ===
false) {
4093 $skip = strlen($text) - $count;
4099 if (preg_match(
'/\/\*.*?\*\//s', $text, $m, 0, $count)) {
4100 $skip = strlen($m[0]);
4101 $newlines = substr_count($m[0],
"\n");
4107 $count += strlen($min[0]);
4110 $out .= substr($text, 0, $count).str_repeat(
"\n", $newlines);
4111 $text = substr($text, $count + $skip);
4122 public $indentChar =
" ";
4124 public $break =
"\n";
4125 public $open =
" {";
4126 public $close =
"}";
4127 public $selectorSeparator =
", ";
4128 public $assignSeparator =
":";
4130 public $openSingle =
" { ";
4131 public $closeSingle =
" }";
4133 public $disableSingle =
false;
4134 public $breakSelectors =
false;
4136 public $compressColors =
false;
4138 public function __construct()
4140 $this->indentLevel = 0;
4143 public function indentStr($n = 0)
4145 return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
4148 public function property($name, $value)
4150 return $name.$this->assignSeparator.$value.
";";
4153 protected function isEmpty($block)
4155 if (empty($block->lines)) {
4156 foreach ($block->children as $child) {
4157 if (!$this->isEmpty($child)) {
4167 public function block($block)
4169 if ($this->isEmpty($block)) {
4173 $inner = $pre = $this->indentStr();
4175 $isSingle = !$this->disableSingle &&
4176 is_null($block->type) && count($block->lines) == 1;
4178 if (!empty($block->selectors)) {
4179 $this->indentLevel++;
4181 if ($this->breakSelectors) {
4182 $selectorSeparator = $this->selectorSeparator.$this->break.$pre;
4184 $selectorSeparator = $this->selectorSeparator;
4188 implode($selectorSeparator, $block->selectors);
4190 echo $this->openSingle;
4193 echo $this->open.$this->break;
4194 $inner = $this->indentStr();
4198 if (!empty($block->lines)) {
4199 $glue = $this->
break.$inner;
4200 echo $inner.implode($glue, $block->lines);
4201 if (!$isSingle && !empty($block->children)) {
4206 foreach ($block->children as $child) {
4207 $this->block($child);
4210 if (!empty($block->selectors)) {
4211 if (!$isSingle && empty($block->children)) {
4216 echo $this->closeSingle.$this->break;
4218 echo $pre.$this->close.$this->break;
4221 $this->indentLevel--;
4231 public $disableSingle =
true;
4233 public $selectorSeparator =
",";
4234 public $assignSeparator =
":";
4236 public $compressColors =
true;
4238 public function indentStr($n = 0)
4249 public $disableSingle =
true;
4250 public $breakSelectors =
true;
4251 public $assignSeparator =
": ";
4252 public $selectorSeparator =
",";