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);
1964 protected function op_color_number($op, $lft, $rgt)
1966 if ($rgt[0] ==
'%') {
1970 return $this->op_color_color(
1973 array_fill(1, count($lft) - 1, $rgt[1])
1977 protected function op_color_color($op, $left, $right)
1979 $out = array(
'color');
1980 $max = count($left) > count($right) ? count($left) : count($right);
1981 foreach (range(1, $max - 1) as $i) {
1982 $lval = isset($left[$i]) ? $left[$i] : 0;
1983 $rval = isset($right[$i]) ? $right[$i] : 0;
1986 $out[] = $lval + $rval;
1989 $out[] = $lval - $rval;
1992 $out[] = $lval * $rval;
1995 $out[] = $lval % $rval;
1999 $this->
throwError(
"evaluate error: can't divide by zero");
2001 $out[] = $lval / $rval;
2004 $this->
throwError(
'evaluate error: color op number failed on op '.$op);
2007 return $this->fixColor($out);
2010 public function lib_red($color)
2012 $color = $this->coerceColor($color);
2013 if (is_null($color)) {
2014 $this->
throwError(
'color expected for red()');
2020 public function lib_green($color)
2022 $color = $this->coerceColor($color);
2023 if (is_null($color)) {
2024 $this->
throwError(
'color expected for green()');
2030 public function lib_blue($color)
2032 $color = $this->coerceColor($color);
2033 if (is_null($color)) {
2034 $this->
throwError(
'color expected for blue()');
2042 protected function op_number_number($op, $left, $right)
2044 $unit = empty($left[2]) ? $right[2] : $left[2];
2049 $value = $left[1] + $right[1];
2052 $value = $left[1] * $right[1];
2055 $value = $left[1] - $right[1];
2058 $value = $left[1] % $right[1];
2061 if ($right[1] == 0) {
2062 $this->
throwError(
'parse error: divide by zero');
2064 $value = $left[1] / $right[1];
2067 return $this->toBool($left[1] < $right[1]);
2069 return $this->toBool($left[1] > $right[1]);
2071 return $this->toBool($left[1] >= $right[1]);
2073 return $this->toBool($left[1] <= $right[1]);
2075 $this->
throwError(
'parse error: unknown number operator: '.$op);
2078 return array(
"number", $value, $unit);
2084 protected function makeOutputBlock($type, $selectors =
null)
2087 $b->lines = array();
2088 $b->children = array();
2089 $b->selectors = $selectors;
2091 $b->parent = $this->scope;
2096 protected function pushEnv($block =
null)
2099 $e->parent = $this->env;
2100 $e->store = array();
2108 protected function popEnv()
2111 $this->env = $this->env->parent;
2116 protected function set($name, $value)
2118 $this->env->store[$name] = $value;
2123 protected function get($name)
2125 $current = $this->env;
2127 $isArguments = $name == $this->vPrefix.
'arguments';
2129 if ($isArguments && isset($current->arguments)) {
2130 return array(
'list',
' ', $current->arguments);
2133 if (isset($current->store[$name])) {
2134 return $current->store[$name];
2137 $current = isset($current->storeParent) ?
2138 $current->storeParent : $current->parent;
2141 $this->
throwError(
"variable $name is undefined");
2145 protected function injectVariables($args)
2149 foreach ($args as $name => $strValue) {
2150 if ($name[0] !==
'@') {
2154 $parser->buffer = (string) $strValue;
2155 if (!$parser->propertyValue($value)) {
2156 throw new Exception(
"failed to parse passed in variable $name: $strValue");
2159 $this->
set($name, $value);
2169 if ($fname !==
null) {
2171 $this->_parseFile = $fname;
2175 public function compile($string, $name =
null)
2177 $locale = setlocale(LC_NUMERIC, 0);
2178 setlocale(LC_NUMERIC,
"C");
2180 $this->parser = $this->makeParser($name);
2181 $root = $this->parser->parse($string);
2184 $this->scope =
null;
2186 $this->formatter = $this->newFormatter();
2188 if (!empty($this->registeredVars)) {
2189 $this->injectVariables($this->registeredVars);
2192 $this->sourceParser = $this->parser;
2196 $this->formatter->block($this->scope);
2197 $out = ob_get_clean();
2198 setlocale(LC_NUMERIC, $locale);
2202 public function compileFile($fname, $outFname =
null)
2204 if (!is_readable($fname)) {
2205 throw new Exception(
'load error: failed to find '.$fname);
2208 $pi = pathinfo($fname);
2210 $oldImport = $this->importDir;
2212 $this->importDir = (array) $this->importDir;
2213 $this->importDir[] = $pi[
'dirname'].
'/';
2215 $this->addParsedFile($fname);
2217 $out = $this->compile(file_get_contents($fname), $fname);
2219 $this->importDir = $oldImport;
2221 if ($outFname !==
null) {
2222 return file_put_contents($outFname, $out);
2229 public function checkedCompile($in, $out)
2231 if (!is_file($out) || filemtime($in) > filemtime($out)) {
2232 $this->compileFile($in, $out);
2263 if (is_string($in)) {
2265 } elseif (is_array($in) && isset($in[
'root'])) {
2266 if ($force || !isset($in[
'files'])) {
2270 $root = $in[
'root'];
2271 } elseif (isset($in[
'files']) && is_array($in[
'files'])) {
2272 foreach ($in[
'files'] as $fname => $ftime) {
2273 if (!file_exists($fname) || filemtime($fname) > $ftime) {
2276 $root = $in[
'root'];
2287 if ($root !==
null) {
2290 $out[
'root'] = $root;
2291 $out[
'compiled'] = $this->compileFile($root);
2292 $out[
'files'] = $this->allParsedFiles();
2293 $out[
'updated'] = time();
2304 public function parse($str =
null, $initialVariables =
null)
2306 if (is_array($str)) {
2307 $initialVariables = $str;
2311 $oldVars = $this->registeredVars;
2312 if ($initialVariables !==
null) {
2313 $this->setVariables($initialVariables);
2317 if (empty($this->_parseFile)) {
2318 throw new exception(
"nothing to parse");
2321 $out = $this->compileFile($this->_parseFile);
2323 $out = $this->compile($str);
2326 $this->registeredVars = $oldVars;
2330 protected function makeParser($name)
2333 $parser->writeComments = $this->preserveComments;
2338 public function setFormatter($name)
2340 $this->formatterName = $name;
2343 protected function newFormatter()
2345 $className =
"lessc_formatter_lessjs";
2346 if (!empty($this->formatterName)) {
2347 if (!is_string($this->formatterName)) {
2348 return $this->formatterName;
2350 $className =
"lessc_formatter_$this->formatterName";
2353 return new $className;
2356 public function setPreserveComments($preserve)
2358 $this->preserveComments = $preserve;
2361 public function registerFunction($name, $func)
2363 $this->libFunctions[$name] = $func;
2366 public function unregisterFunction($name)
2368 unset($this->libFunctions[$name]);
2371 public function setVariables($variables)
2373 $this->registeredVars = array_merge($this->registeredVars, $variables);
2376 public function unsetVariable($name)
2378 unset($this->registeredVars[$name]);
2381 public function setImportDir($dirs)
2383 $this->importDir = (array) $dirs;
2386 public function addImportDir($dir)
2388 $this->importDir = (array) $this->importDir;
2389 $this->importDir[] = $dir;
2392 public function allParsedFiles()
2394 return $this->allParsedFiles;
2397 public function addParsedFile($file)
2399 $this->allParsedFiles[realpath($file)] = filemtime($file);
2407 if ($this->sourceLoc >= 0) {
2408 $this->sourceParser->throwError($msg, $this->sourceLoc);
2410 throw new exception($msg);
2415 public static function ccompile($in, $out, $less =
null)
2417 if ($less ===
null) {
2420 return $less->checkedCompile($in, $out);
2423 public static function cexecute($in, $force =
false, $less =
null)
2425 if ($less ===
null) {
2428 return $less->cachedCompile($in, $force);
2431 protected static $cssColors = array(
2432 'aliceblue' =>
'240,248,255',
2433 'antiquewhite' =>
'250,235,215',
2434 'aqua' =>
'0,255,255',
2435 'aquamarine' =>
'127,255,212',
2436 'azure' =>
'240,255,255',
2437 'beige' =>
'245,245,220',
2438 'bisque' =>
'255,228,196',
2440 'blanchedalmond' =>
'255,235,205',
2441 'blue' =>
'0,0,255',
2442 'blueviolet' =>
'138,43,226',
2443 'brown' =>
'165,42,42',
2444 'burlywood' =>
'222,184,135',
2445 'cadetblue' =>
'95,158,160',
2446 'chartreuse' =>
'127,255,0',
2447 'chocolate' =>
'210,105,30',
2448 'coral' =>
'255,127,80',
2449 'cornflowerblue' =>
'100,149,237',
2450 'cornsilk' =>
'255,248,220',
2451 'crimson' =>
'220,20,60',
2452 'cyan' =>
'0,255,255',
2453 'darkblue' =>
'0,0,139',
2454 'darkcyan' =>
'0,139,139',
2455 'darkgoldenrod' =>
'184,134,11',
2456 'darkgray' =>
'169,169,169',
2457 'darkgreen' =>
'0,100,0',
2458 'darkgrey' =>
'169,169,169',
2459 'darkkhaki' =>
'189,183,107',
2460 'darkmagenta' =>
'139,0,139',
2461 'darkolivegreen' =>
'85,107,47',
2462 'darkorange' =>
'255,140,0',
2463 'darkorchid' =>
'153,50,204',
2464 'darkred' =>
'139,0,0',
2465 'darksalmon' =>
'233,150,122',
2466 'darkseagreen' =>
'143,188,143',
2467 'darkslateblue' =>
'72,61,139',
2468 'darkslategray' =>
'47,79,79',
2469 'darkslategrey' =>
'47,79,79',
2470 'darkturquoise' =>
'0,206,209',
2471 'darkviolet' =>
'148,0,211',
2472 'deeppink' =>
'255,20,147',
2473 'deepskyblue' =>
'0,191,255',
2474 'dimgray' =>
'105,105,105',
2475 'dimgrey' =>
'105,105,105',
2476 'dodgerblue' =>
'30,144,255',
2477 'firebrick' =>
'178,34,34',
2478 'floralwhite' =>
'255,250,240',
2479 'forestgreen' =>
'34,139,34',
2480 'fuchsia' =>
'255,0,255',
2481 'gainsboro' =>
'220,220,220',
2482 'ghostwhite' =>
'248,248,255',
2483 'gold' =>
'255,215,0',
2484 'goldenrod' =>
'218,165,32',
2485 'gray' =>
'128,128,128',
2486 'green' =>
'0,128,0',
2487 'greenyellow' =>
'173,255,47',
2488 'grey' =>
'128,128,128',
2489 'honeydew' =>
'240,255,240',
2490 'hotpink' =>
'255,105,180',
2491 'indianred' =>
'205,92,92',
2492 'indigo' =>
'75,0,130',
2493 'ivory' =>
'255,255,240',
2494 'khaki' =>
'240,230,140',
2495 'lavender' =>
'230,230,250',
2496 'lavenderblush' =>
'255,240,245',
2497 'lawngreen' =>
'124,252,0',
2498 'lemonchiffon' =>
'255,250,205',
2499 'lightblue' =>
'173,216,230',
2500 'lightcoral' =>
'240,128,128',
2501 'lightcyan' =>
'224,255,255',
2502 'lightgoldenrodyellow' =>
'250,250,210',
2503 'lightgray' =>
'211,211,211',
2504 'lightgreen' =>
'144,238,144',
2505 'lightgrey' =>
'211,211,211',
2506 'lightpink' =>
'255,182,193',
2507 'lightsalmon' =>
'255,160,122',
2508 'lightseagreen' =>
'32,178,170',
2509 'lightskyblue' =>
'135,206,250',
2510 'lightslategray' =>
'119,136,153',
2511 'lightslategrey' =>
'119,136,153',
2512 'lightsteelblue' =>
'176,196,222',
2513 'lightyellow' =>
'255,255,224',
2514 'lime' =>
'0,255,0',
2515 'limegreen' =>
'50,205,50',
2516 'linen' =>
'250,240,230',
2517 'magenta' =>
'255,0,255',
2518 'maroon' =>
'128,0,0',
2519 'mediumaquamarine' =>
'102,205,170',
2520 'mediumblue' =>
'0,0,205',
2521 'mediumorchid' =>
'186,85,211',
2522 'mediumpurple' =>
'147,112,219',
2523 'mediumseagreen' =>
'60,179,113',
2524 'mediumslateblue' =>
'123,104,238',
2525 'mediumspringgreen' =>
'0,250,154',
2526 'mediumturquoise' =>
'72,209,204',
2527 'mediumvioletred' =>
'199,21,133',
2528 'midnightblue' =>
'25,25,112',
2529 'mintcream' =>
'245,255,250',
2530 'mistyrose' =>
'255,228,225',
2531 'moccasin' =>
'255,228,181',
2532 'navajowhite' =>
'255,222,173',
2533 'navy' =>
'0,0,128',
2534 'oldlace' =>
'253,245,230',
2535 'olive' =>
'128,128,0',
2536 'olivedrab' =>
'107,142,35',
2537 'orange' =>
'255,165,0',
2538 'orangered' =>
'255,69,0',
2539 'orchid' =>
'218,112,214',
2540 'palegoldenrod' =>
'238,232,170',
2541 'palegreen' =>
'152,251,152',
2542 'paleturquoise' =>
'175,238,238',
2543 'palevioletred' =>
'219,112,147',
2544 'papayawhip' =>
'255,239,213',
2545 'peachpuff' =>
'255,218,185',
2546 'peru' =>
'205,133,63',
2547 'pink' =>
'255,192,203',
2548 'plum' =>
'221,160,221',
2549 'powderblue' =>
'176,224,230',
2550 'purple' =>
'128,0,128',
2552 'rosybrown' =>
'188,143,143',
2553 'royalblue' =>
'65,105,225',
2554 'saddlebrown' =>
'139,69,19',
2555 'salmon' =>
'250,128,114',
2556 'sandybrown' =>
'244,164,96',
2557 'seagreen' =>
'46,139,87',
2558 'seashell' =>
'255,245,238',
2559 'sienna' =>
'160,82,45',
2560 'silver' =>
'192,192,192',
2561 'skyblue' =>
'135,206,235',
2562 'slateblue' =>
'106,90,205',
2563 'slategray' =>
'112,128,144',
2564 'slategrey' =>
'112,128,144',
2565 'snow' =>
'255,250,250',
2566 'springgreen' =>
'0,255,127',
2567 'steelblue' =>
'70,130,180',
2568 'tan' =>
'210,180,140',
2569 'teal' =>
'0,128,128',
2570 'thistle' =>
'216,191,216',
2571 'tomato' =>
'255,99,71',
2572 'transparent' =>
'0,0,0,0',
2573 'turquoise' =>
'64,224,208',
2574 'violet' =>
'238,130,238',
2575 'wheat' =>
'245,222,179',
2576 'white' =>
'255,255,255',
2577 'whitesmoke' =>
'245,245,245',
2578 'yellow' =>
'255,255,0',
2579 'yellowgreen' =>
'154,205,50'
2587 protected static $nextBlockId = 0;
2589 protected static $precedence = array(
2603 protected static $whitePattern;
2604 protected static $commentMulti;
2606 protected static $commentSingle =
"//";
2607 protected static $commentMultiLeft =
"/*";
2608 protected static $commentMultiRight =
"*/";
2611 protected static $operatorString;
2614 protected static $supressDivisionProps =
2615 array(
'/border-radius$/i',
'/^font$/i');
2617 protected $blockDirectives = array(
"font-face",
"keyframes",
"page",
"-moz-document",
"viewport",
"-moz-viewport",
"-o-viewport",
"-ms-viewport");
2618 protected $lineDirectives = array(
"charset");
2632 protected static $literalCache = array();
2634 public function __construct($lessc, $sourceName =
null)
2636 $this->eatWhiteDefault =
true;
2638 $this->lessc = $lessc;
2640 $this->sourceName = $sourceName;
2642 $this->writeComments =
false;
2644 if (!self::$operatorString) {
2645 self::$operatorString =
2646 '('.implode(
'|', array_map(
2647 array(
'lessc',
'preg_quote'),
2648 array_keys(self::$precedence)
2651 $commentSingle = lessc::preg_quote(self::$commentSingle);
2652 $commentMultiLeft = lessc::preg_quote(self::$commentMultiLeft);
2653 $commentMultiRight = lessc::preg_quote(self::$commentMultiRight);
2655 self::$commentMulti = $commentMultiLeft.
'.*?'.$commentMultiRight;
2656 self::$whitePattern =
'/'.$commentSingle.
'[^\n]*\s*|('.self::$commentMulti.
')\s*|\s+/Ais';
2673 $this->buffer = $this->writeComments ? $buffer : $this->removeComments($buffer);
2674 $this->pushSpecialBlock(
"root");
2675 $this->eatWhiteDefault =
true;
2676 $this->seenComments = array();
2683 $this->whitespace();
2688 if ($this->count != strlen($this->buffer)) {
2689 $this->throwError(
'parse error count '.$this->count.
' != len buffer '.strlen($this->buffer));
2693 if (!property_exists($this->env,
'parent') || !is_null($this->env->parent)) {
2694 throw new exception(
'parse error: unclosed block');
2738 if (empty($this->buffer)) {
2743 if ($this->whitespace()) {
2748 if ($this->keyword($key) && $this->
assign() &&
2749 $this->propertyValue($value, $key) && $this->end()
2751 $this->append(array(
'assign', $key, $value), $s);
2759 if ($this->literal(
'@',
false)) {
2763 if ($this->literal(
'@media')) {
2764 if ($this->mediaQueryList($mediaQueries)
2765 && $this->literal(
'{')
2767 $media = $this->pushSpecialBlock(
"media");
2768 $media->queries = is_null($mediaQueries) ? array() : $mediaQueries;
2776 if ($this->literal(
"@",
false) && $this->keyword($dirName)) {
2777 if ($this->isDirective($dirName, $this->blockDirectives)) {
2778 if ($this->openString(
"{", $dirValue,
null, array(
";")) &&
2781 $dir = $this->pushSpecialBlock(
"directive");
2782 $dir->name = $dirName;
2783 if (isset($dirValue)) {
2784 $dir->value = $dirValue;
2788 } elseif ($this->isDirective($dirName, $this->lineDirectives)) {
2789 if ($this->propertyValue($dirValue) && $this->end()) {
2790 $this->append(array(
"directive", $dirName, $dirValue));
2800 if ($this->variable($var) && $this->
assign() &&
2801 $this->propertyValue($value) && $this->end()
2803 $this->append(array(
'assign', $var, $value), $s);
2809 if ($this->
import($importValue)) {
2810 $this->append($importValue, $s);
2815 if ($this->tag($tag,
true) && $this->argumentDef($args, $isVararg) &&
2816 $this->guards($guards) &&
2819 $block = $this->pushBlock($this->fixTags(array($tag)));
2820 $block->args = $args;
2821 $block->isVararg = $isVararg;
2822 if (!empty($guards)) {
2823 $block->guards = $guards;
2831 if ($this->tags($tags) && $this->literal(
'{',
false)) {
2832 $tags = $this->fixTags($tags);
2833 $this->pushBlock($tags);
2840 if ($this->literal(
'}',
false)) {
2842 $block = $this->pop();
2843 }
catch (exception $e) {
2845 $this->throwError($e->getMessage());
2849 if (is_null($block->type)) {
2851 if (!isset($block->args)) {
2852 foreach ($block->tags as $tag) {
2853 if (!is_string($tag) || $tag[0] != $this->lessc->mPrefix) {
2860 foreach ($block->tags as $tag) {
2861 if (is_string($tag)) {
2862 $this->env->children[$tag][] = $block;
2868 $this->append(array(
'block', $block), $s);
2873 $this->whitespace();
2878 if ($this->mixinTags($tags) &&
2879 $this->argumentDef($argv, $isVararg) &&
2880 $this->keyword($suffix) && $this->end()
2882 $tags = $this->fixTags($tags);
2883 $this->append(array(
'mixin', $tags, $argv, $suffix), $s);
2890 if ($this->literal(
';')) {
2897 protected function isDirective($dirname, $directives)
2902 array_map(array(
"lessc",
"preg_quote"), $directives)
2904 $pattern =
'/^(-[a-z-]+-)?('.$pattern.
')$/i';
2906 return preg_match($pattern, $dirname);
2909 protected function fixTags($tags)
2912 foreach ($tags as &$tag) {
2913 if ($tag[0] == $this->lessc->vPrefix) {
2914 $tag[0] = $this->lessc->mPrefix;
2921 protected function expressionList(&$exps)
2929 if (count($values) == 0) {
2933 $exps = lessc::compressList($values,
' ');
2943 if ($this->value($lhs)) {
2947 if (!empty($this->env->supressedDivision)) {
2948 unset($this->env->supressedDivision);
2950 if ($this->literal(
"/") && $this->value($rhs)) {
2951 $out = array(
"list",
"",
2952 array($out, array(
"keyword",
"/"), $rhs));
2968 $this->inExp =
true;
2969 $ss = $this->seek();
2972 $whiteBefore = isset($this->buffer[$this->count - 1]) &&
2973 ctype_space($this->buffer[$this->count - 1]);
2979 if ($this->match(self::$operatorString.($needWhite ?
'\s' :
''), $m) && self::$precedence[$m[1]] >= $minP) {
2980 if (!$this->inParens && isset($this->env->currentProperty) && $m[1] ==
"/" && empty($this->env->supressedDivision)) {
2981 foreach (self::$supressDivisionProps as $pattern) {
2982 if (preg_match($pattern, $this->env->currentProperty)) {
2983 $this->env->supressedDivision =
true;
2990 $whiteAfter = isset($this->buffer[$this->count - 1]) &&
2991 ctype_space($this->buffer[$this->count - 1]);
2993 if (!$this->value($rhs)) {
2998 if ($this->peek(self::$operatorString, $next) && self::$precedence[$next[1]] > self::$precedence[$m[1]]) {
2999 $rhs = $this->
expHelper($rhs, self::$precedence[$next[1]]);
3002 $lhs = array(
'expression', $m[1], $lhs, $rhs, $whiteBefore, $whiteAfter);
3003 $ss = $this->seek();
3017 public function propertyValue(&$value, $keyName =
null)
3021 if ($keyName !==
null) {
3022 $this->env->currentProperty = $keyName;
3026 while ($this->expressionList($v)) {
3029 if (!$this->literal(
',')) {
3038 if ($keyName !==
null) {
3039 unset($this->env->currentProperty);
3042 if (count($values) == 0) {
3046 $value = lessc::compressList($values,
', ');
3050 protected function parenValue(&$out)
3055 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] !=
"(") {
3060 if ($this->literal(
"(") &&
3061 ($this->inParens =
true) && $this->
expression($exp) &&
3076 protected function value(&$value)
3081 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] ==
"-") {
3083 if ($this->literal(
"-",
false) &&
3084 (($this->variable($inner) && $inner = array(
"variable", $inner)) ||
3085 $this->unit($inner) ||
3086 $this->parenValue($inner))
3088 $value = array(
"unary",
"-", $inner);
3095 if ($this->parenValue($value)) {
3098 if ($this->unit($value)) {
3101 if ($this->color($value)) {
3104 if ($this->func($value)) {
3107 if ($this->
string($value)) {
3111 if ($this->keyword($word)) {
3112 $value = array(
'keyword', $word);
3117 if ($this->variable($var)) {
3118 $value = array(
'variable', $var);
3123 if ($this->literal(
"~") && $this->
string($str)) {
3124 $value = array(
"escape", $str);
3131 if ($this->literal(
'\\') && $this->match(
'([0-9]+)', $m)) {
3132 $value = array(
'keyword',
'\\'.$m[1]);
3142 protected function import(&$out, $value =
'')
3144 if (!$this->literal(
'@import')) {
3152 if ($this->propertyValue($value)) {
3153 $out = array(
"import", $value);
3160 protected function mediaQueryList(&$out)
3162 if ($this->genericList($list,
"mediaQuery",
",",
false)) {
3169 protected function mediaQuery(&$out)
3173 $expressions =
null;
3176 if ((($this->literal(
"only") && ($only =
true)) || ($this->literal(
"not") && ($not =
true))) && $this->keyword($mediaType)) {
3177 $prop = array(
"mediaType");
3184 $prop[] = $mediaType;
3191 if (!empty($mediaType) && !$this->literal(
"and")) {
3194 $this->genericList($expressions,
"mediaExpression",
"and",
false);
3195 if (is_array($expressions)) {
3196 $parts = array_merge($parts, $expressions[2]);
3200 if (count($parts) == 0) {
3209 protected function mediaExpression(&$out)
3213 if ($this->literal(
"(") &&
3214 $this->keyword($feature) &&
3215 ($this->literal(
":") && $this->
expression($value)) &&
3218 $out = array(
"mediaExp", $feature);
3223 } elseif ($this->variable($variable)) {
3224 $out = array(
'variable', $variable);
3233 protected function openString($end, &$out, $nestingOpen =
null, $rejectStrs =
null)
3235 $oldWhite = $this->eatWhiteDefault;
3236 $this->eatWhiteDefault =
false;
3238 $stop = array(
"'",
'"',
"@{", $end);
3239 $stop = array_map(array(
"lessc",
"preg_quote"), $stop);
3242 if (!is_null($rejectStrs)) {
3243 $stop = array_merge($stop, $rejectStrs);
3246 $patt =
'(.*?)('.implode(
"|", $stop).
')';
3251 while ($this->match($patt, $m,
false)) {
3252 if (!empty($m[1])) {
3255 $nestingLevel += substr_count($m[1], $nestingOpen);
3261 $this->count -= strlen($tok);
3263 if ($nestingLevel == 0) {
3270 if (($tok ==
"'" || $tok ==
'"') && $this->
string($str)) {
3275 if ($tok ==
"@{" && $this->interpolation($inter)) {
3276 $content[] = $inter;
3280 if (!empty($rejectStrs) && in_array($tok, $rejectStrs)) {
3285 $this->count += strlen($tok);
3288 $this->eatWhiteDefault = $oldWhite;
3290 if (count($content) == 0) {
3295 if (is_string(end($content))) {
3296 $content[count($content) - 1] = rtrim(end($content));
3299 $out = array(
"string",
"", $content);
3303 protected function string(&$out)
3306 if ($this->literal(
'"',
false)) {
3308 } elseif ($this->literal(
"'",
false)) {
3317 $patt =
'([^\n]*?)(@\{|\\\\|'.
3318 lessc::preg_quote($delim).
')';
3320 $oldWhite = $this->eatWhiteDefault;
3321 $this->eatWhiteDefault =
false;
3323 while ($this->match($patt, $m,
false)) {
3325 if ($m[2] ==
"@{") {
3326 $this->count -= strlen($m[2]);
3327 if ($this->interpolation($inter)) {
3328 $content[] = $inter;
3330 $this->count += strlen($m[2]);
3333 } elseif ($m[2] ==
'\\') {
3335 if ($this->literal($delim,
false)) {
3336 $content[] = $delim;
3339 $this->count -= strlen($delim);
3344 $this->eatWhiteDefault = $oldWhite;
3346 if ($this->literal($delim)) {
3347 $out = array(
"string", $delim, $content);
3355 protected function interpolation(&$out)
3357 $oldWhite = $this->eatWhiteDefault;
3358 $this->eatWhiteDefault =
true;
3361 if ($this->literal(
"@{") &&
3362 $this->openString(
"}", $interp,
null, array(
"'",
'"',
";")) &&
3363 $this->literal(
"}",
false)
3365 $out = array(
"interpolate", $interp);
3366 $this->eatWhiteDefault = $oldWhite;
3367 if ($this->eatWhiteDefault) {
3368 $this->whitespace();
3373 $this->eatWhiteDefault = $oldWhite;
3378 protected function unit(&$unit)
3381 if (isset($this->buffer[$this->count])) {
3382 $char = $this->buffer[$this->count];
3383 if (!ctype_digit($char) && $char !=
".") {
3388 if ($this->match(
'([0-9]+(?:\.[0-9]*)?|\.[0-9]+)([%a-zA-Z]+)?', $m)) {
3389 $unit = array(
"number", $m[1], empty($m[2]) ?
"" : $m[2]);
3396 protected function color(&$out)
3398 if ($this->match(
'(#(?:[0-9a-f]{8}|[0-9a-f]{6}|[0-9a-f]{3}))', $m)) {
3399 if (strlen($m[1]) > 7) {
3400 $out = array(
"string",
"", array($m[1]));
3402 $out = array(
"raw_color", $m[1]);
3415 protected function argumentDef(&$args, &$isVararg)
3418 if (!$this->literal(
'(')) {
3424 $method =
"expressionList";
3428 if ($this->literal(
"...")) {
3433 if ($this->$method($value)) {
3434 if ($value[0] ==
"variable") {
3435 $arg = array(
"arg", $value[1]);
3436 $ss = $this->seek();
3438 if ($this->
assign() && $this->$method($rhs)) {
3442 if ($this->literal(
"...")) {
3454 $values[] = array(
"lit", $value);
3459 if (!$this->literal($delim)) {
3460 if ($delim ==
"," && $this->literal(
";")) {
3463 $method =
"propertyValue";
3466 if (isset($values[1])) {
3468 foreach ($values as $i => $arg) {
3472 $this->throwError(
"Cannot mix ; and , as delimiter types");
3474 $newList[] = $arg[2];
3477 $newList[] = $arg[1];
3480 $this->throwError(
"Unexpected rest before semicolon");
3484 $newList = array(
"list",
", ", $newList);
3486 switch ($values[0][0]) {
3488 $newArg = array(
"arg", $values[0][1], $newList);
3491 $newArg = array(
"lit", $newList);
3494 } elseif ($values) {
3495 $newArg = $values[0];
3499 $values = array($newArg);
3507 if (!$this->literal(
')')) {
3519 protected function tags(&$tags, $simple =
false, $delim =
',')
3522 while ($this->tag($tt, $simple)) {
3524 if (!$this->literal($delim)) {
3528 if (count($tags) == 0) {
3537 protected function mixinTags(&$tags)
3540 while ($this->tag($tt,
true)) {
3542 $this->literal(
">");
3553 protected function tagBracket(&$parts, &$hasExpression)
3556 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] !=
"[") {
3562 $hasInterpolation =
false;
3564 if ($this->literal(
"[",
false)) {
3565 $attrParts = array(
"[");
3568 if ($this->literal(
"]",
false)) {
3573 if ($this->match(
'\s+', $m)) {
3577 if ($this->
string($str)) {
3579 foreach ($str[2] as &$chunk) {
3580 $chunk = str_replace($this->lessc->parentSelector,
"$&$", $chunk);
3583 $attrParts[] = $str;
3584 $hasInterpolation =
true;
3588 if ($this->keyword($word)) {
3589 $attrParts[] = $word;
3593 if ($this->interpolation($inter)) {
3594 $attrParts[] = $inter;
3595 $hasInterpolation =
true;
3600 if ($this->match(
'[|-~\$\*\^=]+', $m)) {
3601 $attrParts[] = $m[0];
3608 if ($this->literal(
"]",
false)) {
3610 foreach ($attrParts as $part) {
3613 $hasExpression = $hasExpression || $hasInterpolation;
3624 protected function tag(&$tag, $simple =
false)
3627 $chars =
'^@,:;{}\][>\(\) "\'';
3629 $chars =
'^@,;{}["\'';
3633 $hasExpression =
false;
3635 while ($this->tagBracket($parts, $hasExpression));
3637 $oldWhite = $this->eatWhiteDefault;
3638 $this->eatWhiteDefault =
false;
3641 if ($this->match(
'(['.$chars.
'0-9]['.$chars.
']*)', $m)) {
3647 while ($this->tagBracket($parts, $hasExpression));
3651 if (isset($this->buffer[$this->count]) && $this->buffer[$this->count] ==
"@") {
3652 if ($this->interpolation($interp)) {
3653 $hasExpression =
true;
3659 if ($this->literal(
"@")) {
3665 if ($this->unit($unit)) {
3666 $parts[] = $unit[1];
3667 $parts[] = $unit[2];
3674 $this->eatWhiteDefault = $oldWhite;
3680 if ($hasExpression) {
3681 $tag = array(
"exp", array(
"string",
"", $parts));
3683 $tag = trim(implode($parts));
3686 $this->whitespace();
3691 protected function func(&$func)
3695 if ($this->match(
'(%|[\w\-_][\w\-_:\.]+|[\w_])', $m) && $this->literal(
'(')) {
3698 $sPreArgs = $this->seek();
3702 $ss = $this->seek();
3704 if ($this->keyword($name) && $this->literal(
'=') && $this->expressionList($value)) {
3705 $args[] = array(
"string",
"", array($name,
"=", $value));
3708 if ($this->expressionList($value)) {
3713 if (!$this->literal(
',')) {
3717 $args = array(
'list',
',', $args);
3719 if ($this->literal(
')')) {
3720 $func = array(
'function', $fname, $args);
3722 } elseif ($fname ==
'url') {
3724 $this->seek($sPreArgs);
3725 if ($this->openString(
")", $string) && $this->literal(
")")) {
3726 $func = array(
'function', $fname, $string);
3737 protected function variable(&$name)
3740 if ($this->literal($this->lessc->vPrefix,
false) &&
3741 ($this->variable($sub) || $this->keyword($name))
3744 $name = array(
'variable', $sub);
3746 $name = $this->lessc->vPrefix.$name;
3763 $this->currentProperty = $name;
3765 return $this->literal(
':') || $this->literal(
'=');
3769 protected function keyword(&$word)
3771 if ($this->match(
'([\w_\-\*!"][\w\-_"]*)', $m)) {
3779 protected function end()
3781 if ($this->literal(
';',
false)) {
3783 } elseif ($this->count == strlen($this->buffer) || $this->buffer[$this->count] ==
'}') {
3790 protected function guards(&$guards)
3794 if (!$this->literal(
"when")) {
3801 while ($this->guardGroup($g)) {
3803 if (!$this->literal(
",")) {
3808 if (count($guards) == 0) {
3819 protected function guardGroup(&$guardGroup)
3822 $guardGroup = array();
3823 while ($this->guard($guard)) {
3824 $guardGroup[] = $guard;
3825 if (!$this->literal(
"and")) {
3830 if (count($guardGroup) == 0) {
3839 protected function guard(&$guard)
3842 $negate = $this->literal(
"not");
3844 if ($this->literal(
"(") && $this->
expression($exp) && $this->literal(
")")) {
3847 $guard = array(
"negate", $guard);
3858 protected function literal($what, $eatWhitespace =
null)
3860 if ($eatWhitespace ===
null) {
3861 $eatWhitespace = $this->eatWhiteDefault;
3865 if (!isset($what[1]) && isset($this->buffer[$this->count])) {
3866 if ($this->buffer[$this->count] == $what) {
3867 if (!$eatWhitespace) {
3877 if (!isset(self::$literalCache[$what])) {
3878 self::$literalCache[$what] = lessc::preg_quote($what);
3881 return $this->match(self::$literalCache[$what], $m, $eatWhitespace);
3884 protected function genericList(&$out, $parseItem, $delim =
"", $flatten =
true)
3888 while ($this->$parseItem($value)) {
3891 if (!$this->literal($delim)) {
3897 if (count($items) == 0) {
3902 if ($flatten && count($items) == 1) {
3905 $out = array(
"list", $delim, $items);
3915 protected function to($what, &$out, $until =
false, $allowNewline =
false)
3917 if (is_string($allowNewline)) {
3918 $validChars = $allowNewline;
3920 $validChars = $allowNewline ?
"." :
"[^\n]";
3922 if (!$this->match(
'('.$validChars.
'*?)'.lessc::preg_quote($what), $m, !$until)) {
3926 $this->count -= strlen($what);
3933 protected function match($regex, &$out, $eatWhitespace =
null)
3935 if ($eatWhitespace ===
null) {
3936 $eatWhitespace = $this->eatWhiteDefault;
3939 $r =
'/'.$regex.($eatWhitespace && !$this->writeComments ?
'\s*' :
'').
'/Ais';
3940 if (preg_match($r, $this->buffer, $out,
null, $this->count)) {
3941 $this->count += strlen($out[0]);
3942 if ($eatWhitespace && $this->writeComments) {
3943 $this->whitespace();
3951 protected function whitespace()
3953 if ($this->writeComments) {
3955 while (preg_match(self::$whitePattern, $this->buffer, $m,
null, $this->count)) {
3956 if (isset($m[1]) && empty($this->seenComments[$this->count])) {
3957 $this->append(array(
"comment", $m[1]));
3958 $this->seenComments[$this->count] =
true;
3960 $this->count += strlen($m[0]);
3965 $this->match(
"", $m);
3966 return strlen($m[0]) > 0;
3971 protected function peek($regex, &$out =
null, $from =
null)
3973 if (is_null($from)) {
3974 $from = $this->count;
3976 $r =
'/'.$regex.
'/Ais';
3977 $result = preg_match($r, $this->buffer, $out,
null, $from);
3983 protected function seek($where =
null)
3985 if ($where ===
null) {
3986 return $this->count;
3988 $this->count = $where;
3995 public function throwError($msg =
"parse error", $count =
null)
3997 $count = is_null($count) ? $this->count : $count;
3999 $line = $this->line +
4000 substr_count(substr($this->buffer, 0, $count),
"\n");
4002 if (!empty($this->sourceName)) {
4003 $loc =
"$this->sourceName on line $line";
4005 $loc =
"line: $line";
4009 if ($this->peek(
"(.*?)(\n|$)", $m, $count)) {
4010 throw new exception(
"$msg: failed at `$m[1]` $loc");
4012 throw new exception(
"$msg: $loc");
4016 protected function pushBlock($selectors =
null, $type =
null)
4019 $b->parent = $this->env;
4022 $b->id = self::$nextBlockId++;
4024 $b->isVararg =
false;
4025 $b->tags = $selectors;
4027 $b->props = array();
4028 $b->children = array();
4035 protected function pushSpecialBlock($type)
4037 return $this->pushBlock(
null, $type);
4041 protected function append($prop, $pos =
null)
4043 if ($pos !==
null) {
4046 $this->env->props[] = $prop;
4050 protected function pop()
4053 $this->env = $this->env->parent;
4059 protected function removeComments($text)
4062 'url(',
'//',
'/*',
'"',
"'"
4069 foreach ($look as $token) {
4070 $pos = strpos($text, $token);
4071 if ($pos !==
false) {
4072 if (!isset($min) || $pos < $min[1]) {
4073 $min = array($token, $pos);
4078 if (is_null($min)) {
4087 if (preg_match(
'/url\(.*?\)/', $text, $m, 0, $count)) {
4088 $count += strlen($m[0]) - strlen($min[0]);
4093 if (preg_match(
'/'.$min[0].
'.*?(?<!\\\\)'.$min[0].
'/', $text, $m, 0, $count)) {
4094 $count += strlen($m[0]) - 1;
4098 $skip = strpos($text,
"\n", $count);
4099 if ($skip ===
false) {
4100 $skip = strlen($text) - $count;
4106 if (preg_match(
'/\/\*.*?\*\//s', $text, $m, 0, $count)) {
4107 $skip = strlen($m[0]);
4108 $newlines = substr_count($m[0],
"\n");
4114 $count += strlen($min[0]);
4117 $out .= substr($text, 0, $count).str_repeat(
"\n", $newlines);
4118 $text = substr($text, $count + $skip);
4129 public $indentChar =
" ";
4131 public $break =
"\n";
4132 public $open =
" {";
4133 public $close =
"}";
4134 public $selectorSeparator =
", ";
4135 public $assignSeparator =
":";
4137 public $openSingle =
" { ";
4138 public $closeSingle =
" }";
4140 public $disableSingle =
false;
4141 public $breakSelectors =
false;
4143 public $compressColors =
false;
4145 public function __construct()
4147 $this->indentLevel = 0;
4150 public function indentStr($n = 0)
4152 return str_repeat($this->indentChar, max($this->indentLevel + $n, 0));
4155 public function property($name, $value)
4157 return $name.$this->assignSeparator.$value.
";";
4160 protected function isEmpty($block)
4162 if (empty($block->lines)) {
4163 foreach ($block->children as $child) {
4164 if (!$this->isEmpty($child)) {
4174 public function block($block)
4176 if ($this->isEmpty($block)) {
4180 $inner = $pre = $this->indentStr();
4182 $isSingle = !$this->disableSingle &&
4183 is_null($block->type) && count($block->lines) == 1;
4185 if (!empty($block->selectors)) {
4186 $this->indentLevel++;
4188 if ($this->breakSelectors) {
4189 $selectorSeparator = $this->selectorSeparator.$this->break.$pre;
4191 $selectorSeparator = $this->selectorSeparator;
4195 implode($selectorSeparator, $block->selectors);
4197 echo $this->openSingle;
4200 echo $this->open.$this->break;
4201 $inner = $this->indentStr();
4205 if (!empty($block->lines)) {
4206 $glue = $this->
break.$inner;
4207 echo $inner.implode($glue, $block->lines);
4208 if (!$isSingle && !empty($block->children)) {
4213 foreach ($block->children as $child) {
4214 $this->block($child);
4217 if (!empty($block->selectors)) {
4218 if (!$isSingle && empty($block->children)) {
4223 echo $this->closeSingle.$this->break;
4225 echo $pre.$this->close.$this->break;
4228 $this->indentLevel--;
4238 public $disableSingle =
true;
4240 public $selectorSeparator =
",";
4241 public $assignSeparator =
":";
4243 public $compressColors =
true;
4245 public function indentStr($n = 0)
4256 public $disableSingle =
true;
4257 public $breakSelectors =
true;
4258 public $assignSeparator =
": ";
4259 public $selectorSeparator =
",";
lessphp v0.5.0 http://leafo.net/lessphp
compileBlock($block)
Recursively compiles a block.
__construct($fname=null)
Initialize any static state, can initialize parser for a file $opts isn't used yet.
cachedCompile($in, $force=false)
Execute lessphp on a .less file or a lessphp cache structure.
lib_data_uri($value)
Given an url, decide whether to output a regular link or the base64-encoded contents of the file.
funcToColor($func)
Convert the rgb, rgba, hsl color literals of function type as returned by the parser into values of c...
deduplicate($lines)
Deduplicate lines in a block.
lib_shade($args)
Mix color with black in variable proportion.
fileExists($name)
fileExists
toRGB($color)
Converts a hsl array into a color value in rgb.
throwError($msg=null)
Uses the current value of $this->count to show line and line number.
colorArgs($args)
Helper function to get arguments for color manipulation functions.
compileValue($value)
Compiles a primitive value into a CSS property value.
lib_tint($args)
Mix color with white in variable proportion.
expHelper($lhs, $minP)
recursively parse infix equation with $lhs at precedence $minP
parseChunk()
Parse a single chunk off the head of the buffer and append it to the current parse environment.
assign($name=null)
Consume an assignment operator Can optionally take a name that will be set to the current property na...
parse($buffer)
Parse a string.
$inParens
if we are in parens we can be more liberal with whitespace around operators because it must evaluate ...
expression(&$out)
Attempt to consume an expression.