Permalink
Browse files

Added library functions & better string handling

quote() and unquote() format functions can remove and add quotes around the
arguments passed to them.

eg. say you have some complex css syntax that can't be parsed, you can
use string operations and unquote() to do a raw output.

	@color: #aabbcc;
	some-property: unquote("[doSomething color: {@color}]");

outputs:

	some-property: [doSomething color: #aabbcc];

If you subclass lessc then you can add your own functions, prefix
them with lib_ to make them visible. Take a look at the implementations
of lib_quote and lib_unquote as an example (they are very short).

Improved string parsing and concatenation
  • Loading branch information...
leafo committed Mar 12, 2010
1 parent 25b17ba commit 2fb4296a6a7287ea53e99b73858bfd5a44834cad
Showing with 29 additions and 12 deletions.
  1. +29 −12 lessc.inc.php
View
@@ -431,9 +431,9 @@ function accessor(&$var) {
// a string
function string(&$string, &$d = null) {
$s = $this->seek();
if ($this->literal('"')) {
if ($this->literal('"', false)) {
$delim = '"';
} else if($this->literal("'")) {
} else if($this->literal("'", false)) {
$delim = "'";
} else {
return false;
@@ -754,13 +754,36 @@ function compileValue($value) {
case 'function':
// [1] - function name
// [2] - some value representing arguments
// see if there is a library function for this func
$f = array($this, 'lib_'.$value[1]);
if (is_callable($f)) {
return call_user_func($f, $value[2]);
}
return $value[1].'('.$this->compileValue($value[2]).')';
default: // assumed to be unit
return $value[1].$value[0];
}
}
function lib_quote($arg) {
return '"'.$this->compileValue($arg).'"';
}
function lib_unquote($arg) {
$out = $this->compileValue($arg);
if ($this->quoted($out)) $out = substr($out, 1, -1);
return $out;
}
// is a string surrounded in quotes? returns the quoting char if true
function quoted($s) {
if (preg_match('/^("|\').*?\1$/', $s, $m))
return $m[1];
else return false;
}
// convert rgb, rgba into color type suitable for math
// todo: add hsl
@@ -837,18 +860,12 @@ function evaluate($op, $left, $right) {
// concatenate strings
if ($op == '+' && $left[0] == 'string') {
// todo: normalize string quotes
$append = $this->compileValue($right);
if ($right[0] == 'string' && ($append{0} == '"' || $append{0} == "'")) {
$append = substr($append, 1, -1);
}
if ($this->quoted($append)) $append = substr($append, 1, -1);
$lhs = $this->compileValue($left);
$q = '';
if ($left[0] == 'string' && ($lhs{0} == '"' || $lhs{0} == "'")) {
$q = $lhs{0};
$lhs = substr($lhs, 1, -1);
}
if ($q = $this->quoted($lhs)) $lhs = substr($lhs, 1, -1);
if (!$q) $q = '';
return array('string', $q.$lhs.$append.$q);
}
@@ -1159,7 +1176,7 @@ function parse($str = null) {
if (count($this->env) > 1)
throw new exception('parse error: unclosed block');
// print_r($this->env);
//print_r($this->env);
return $out;
}

0 comments on commit 2fb4296

Please sign in to comment.