Module: Sass::Script::Functions

Included in:
EvaluationContext
Defined in:
lib/sass/script/functions.rb

Overview

Methods in this module are accessible from the SassScript context. For example, you can write

$color: hsl(120deg, 100%, 50%)

and it will call #hsl.

The following functions are provided:

Note: These functions are described in more detail below.

RGB Functions

rgb($red, $green, $blue) : Creates a Color from red, green, and blue values.

rgba($red, $green, $blue, $alpha) : Creates a Color from red, green, blue, and alpha values.

red($color) : Gets the red component of a color.

green($color) : Gets the green component of a color.

blue($color) : Gets the blue component of a color.

mix($color1, $color2, [$weight]) : Mixes two colors together.

HSL Functions

hsl($hue, $saturation, $lightness) : Creates a Color from hue, saturation, and lightness values.

hsla($hue, $saturation, $lightness, $alpha) : Creates a Color from hue, saturation, lightness, and alpha values.

hue($color) : Gets the hue component of a color.

saturation($color) : Gets the saturation component of a color.

lightness($color) : Gets the lightness component of a color.

adjust-hue($color, $degrees) : Changes the hue of a color.

lighten($color, $amount) : Makes a color lighter.

darken($color, $amount) : Makes a color darker.

saturate($color, $amount) : Makes a color more saturated.

desaturate($color, $amount) : Makes a color less saturated.

grayscale($color) : Converts a color to grayscale.

complement($color) : Returns the complement of a color.

invert($color) : Returns the inverse of a color.

Opacity Functions

alpha($color) / opacity($color) : Gets the alpha component (opacity) of a color.

rgba($color, $alpha) : Changes the alpha component for a color.

opacify($color, $amount) / fade-in($color, $amount) : Makes a color more opaque.

transparentize($color, $amount) / fade-out($color, $amount) : Makes a color more transparent.

Other Color Functions

adjust-color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha]) : Increases or decreases one or more components of a color.

scale-color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha]) : Fluidly scales one or more properties of a color.

change-color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha]) : Changes one or more properties of a color.

ie-hex-str($color) : Converts a color into the format understood by IE filters.

String Functions

unquote($string) : Removes quotes from a string.

quote($string) : Adds quotes to a string.

str-length($string) : Returns the number of characters in a string.

str-insert($string, $insert, $index) : Inserts $insert into $string at $index.

str-index($string, $substring) : Returns the index of the first occurance of $substring in $string.

str-slice($string, $start-at, [$end-at]) : Extracts a substring from $string.

to-upper-case($string) : Converts a string to upper case.

to-lower-case($string) : Converts a string to lower case.

Number Functions

percentage($number) : Converts a unitless number to a percentage.

round($number) : Rounds a number to the nearest whole number.

ceil($number) : Rounds a number up to the next whole number.

floor($number) : Rounds a number down to the previous whole number.

abs($number) : Returns the absolute value of a number.

min($numbers...) : Finds the minimum of several numbers.

max($numbers...) : Finds the maximum of several numbers.

random([$limit]) : Returns a random number.

List Functions #list-functions

Lists in Sass are immutable; all list functions return a new list rather than updating the existing list in-place.

All list functions work for maps as well, treating them as lists of pairs.

length($list) : Returns the length of a list.

nth($list, $n) : Returns a specific item in a list.

set-nth($list, $n, $value) : Replaces the nth item in a list.

join($list1, $list2, [$separator]) : Joins together two lists into one.

append($list1, $val, [$separator]) : Appends a single value onto the end of a list.

zip($lists...) : Combines several lists into a single multidimensional list.

index($list, $value) : Returns the position of a value within a list.

list-separator($list) : Returns the separator of a list.

Map Functions #map-functions

Maps in Sass are immutable; all map functions return a new map rather than updating the existing map in-place.

map-get($map, $key) : Returns the value in a map associated with a given key.

map-merge($map1, $map2) : Merges two maps together into a new map.

map-remove($map, $keys...) : Returns a new map with keys removed.

map-keys($map) : Returns a list of all keys in a map.

map-values($map) : Returns a list of all values in a map.

map-has-key($map, $key) : Returns whether a map has a value associated with a given key.

keywords($args) : Returns the keywords passed to a function that takes variable arguments.

Selector Functions

Selector functions are very liberal in the formats they support for selector arguments. They can take a plain string, a list of lists as returned by & or anything in between:

  • A plain string, such as ".foo .bar, .baz .bang".
  • A space-separated list of strings such as (".foo" ".bar").
  • A comma-separated list of strings such as (".foo .bar", ".baz .bang").
  • A comma-separated list of space-separated lists of strings such as ((".foo" ".bar"), (".baz" ".bang")).

In general, selector functions allow placeholder selectors (%foo) but disallow parent-reference selectors (&).

selector-nest($selectors...) : Nests selector beneath one another like they would be nested in the stylesheet.

selector-append($selectors...) : Appends selectors to one another without spaces in between.

selector-extend($selector, $extendee, $extender) : Extends $extendee with $extender within $selector.

selector-replace($selector, $original, $replacement) : Replaces $original with $replacement within $selector.

selector-unify($selector1, $selector2) : Unifies two selectors to produce a selector that matches elements matched by both.

is-superselector($super, $sub) : Returns whether $super matches all the elements $sub does, and possibly more.

simple-selectors($selector) : Returns the simple selectors that comprise a compound selector.

selector-parse($selector) : Parses a selector into the format returned by &.

Introspection Functions

feature-exists($feature) : Returns whether a feature exists in the current Sass runtime.

variable-exists($name) : Returns whether a variable with the given name exists in the current scope.

global-variable-exists($name) : Returns whether a variable with the given name exists in the global scope.

function-exists($name) : Returns whether a function with the given name exists.

mixin-exists($name) : Returns whether a mixin with the given name exists.

inspect($value) : Returns the string representation of a value as it would be represented in Sass.

type-of($value) : Returns the type of a value.

unit($number) : Returns the unit(s) associated with a number.

unitless($number) : Returns whether a number has units.

comparable($number1, $number2) : Returns whether two numbers can be added, subtracted, or compared.

call($name, $args...) : Dynamically calls a Sass function.

Miscellaneous Functions

if($condition, $if-true, $if-false) : Returns one of two values, depending on whether or not $condition is true.

unique-id() : Returns a unique CSS identifier.

Adding Custom Functions

New Sass functions can be added by adding Ruby methods to this module. For example:

module Sass::Script::Functions
  def reverse(string)
    assert_type string, :String
    Sass::Script::Value::String.new(string.value.reverse)
  end
  declare :reverse, [:string]
end

Calling Functions.declare tells Sass the argument names for your function. If omitted, the function will still work, but will not be able to accept keyword arguments. Functions.declare can also allow your function to take arbitrary keyword arguments.

There are a few things to keep in mind when modifying this module. First of all, the arguments passed are Value objects. Value objects are also expected to be returned. This means that Ruby values must be unwrapped and wrapped.

Most Value objects support the value accessor for getting their Ruby values. Color objects, though, must be accessed using rgb, red, green, or blue.

Second, making Ruby functions accessible from Sass introduces the temptation to do things like database access within stylesheets. This is generally a bad idea; since Sass files are by default only compiled once, dynamic code is not a great fit.

If you really, really need to compile Sass on each request, first make sure you have adequate caching set up. Then you can use Engine to render the code, using the options parameter to pass in data that can be accessed from your Sass functions.

Within one of the functions in this module, methods of EvaluationContext can be used.

Caveats

When creating new Value objects within functions, be aware that it's not safe to call #to_s (or other methods that use the string representation) on those objects without first setting the #options attribute.

Defined Under Namespace

Classes: EvaluationContext, Signature

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.declare(method_name, args, options = {})

Declare a Sass signature for a Ruby-defined function. This includes the names of the arguments, whether the function takes a variable number of arguments, and whether the function takes an arbitrary set of keyword arguments.

It's not necessary to declare a signature for a function. However, without a signature it won't support keyword arguments.

A single function can have multiple signatures declared as long as each one takes a different number of arguments. It's also possible to declare multiple signatures that all take the same number of arguments, but none of them but the first will be used unless the user uses keyword arguments.

Examples:

declare :rgba, [:hex, :alpha]
declare :rgba, [:red, :green, :blue, :alpha]
declare :accepts_anything, [], :var_args => true, :var_kwargs => true
declare :some_func, [:foo, :bar, :baz], :var_kwargs => true

Parameters:

  • method_name (Symbol)

    The name of the method whose signature is being declared.

  • args (Array<Symbol>)

    The names of the arguments for the function signature.

  • options (Hash) (defaults to: {})

    a customizable set of options

Options Hash (options):

  • :var_args (Boolean) — default: false

    Whether the function accepts a variable number of (unnamed) arguments in addition to the named arguments.

  • :var_kwargs (Boolean) — default: false

    Whether the function accepts other keyword arguments in addition to those in :args. If this is true, the Ruby function will be passed a hash from strings to Values as the last argument. In addition, if this is true and :var_args is not, Sass will ensure that the last argument passed is a hash.



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
# File 'lib/sass/script/functions.rb', line 405

def self.declare(method_name, args, options = {})
  delayed_args = []
  args = args.map do |a|
    a = a.to_s
    if a[0] == ?&
      a = a[1..-1]
      delayed_args << a
    end
    a
  end
  # We don't expose this functionality except to certain builtin methods.
  if delayed_args.any? && method_name != :if
    raise ArgumentError.new("Delayed arguments are not allowed for method #{method_name}")
  end
  @signatures[method_name] ||= []
  @signatures[method_name] << Signature.new(
    args,
    delayed_args,
    options[:var_args],
    options[:var_kwargs],
    options[:deprecated] && options[:deprecated].map {|a| a.to_s})
end

.random_number_generatorRandom

Get Sass's internal random number generator.

Returns:

  • (Random)


479
480
481
# File 'lib/sass/script/functions.rb', line 479

def self.random_number_generator
  @random_number_generator ||= Sass::Util::CrossPlatformRandom.new
end

.random_seed=(seed) ⇒ Integer

Sets the random seed used by Sass's internal random number generator.

This can be used to ensure consistent random number sequences which allows for consistent results when testing, etc.

Parameters:

  • seed (Integer)

Returns:

  • (Integer)

    The same seed.



472
473
474
# File 'lib/sass/script/functions.rb', line 472

def self.random_seed=(seed)
  @random_number_generator = Sass::Util::CrossPlatformRandom.new(seed)
end

.signature(method_name, arg_arity, kwarg_arity) ⇒ {Symbol => Object}?

Determine the correct signature for the number of arguments passed in for a given function. If no signatures match, the first signature is returned for error messaging.

Parameters:

  • method_name (Symbol)

    The name of the Ruby function to be called.

  • arg_arity (Fixnum)

    The number of unnamed arguments the function was passed.

  • kwarg_arity (Fixnum)

    The number of keyword arguments the function was passed.

Returns:

  • ({Symbol => Object}, nil)

    The signature options for the matching signature, or nil if no signatures are declared for this function. See declare.



439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
# File 'lib/sass/script/functions.rb', line 439

def self.signature(method_name, arg_arity, kwarg_arity)
  return unless @signatures[method_name]
  @signatures[method_name].each do |signature|
    sig_arity = signature.args.size
    return signature if sig_arity == arg_arity + kwarg_arity
    next unless sig_arity < arg_arity + kwarg_arity

    # We have enough args.
    # Now we need to figure out which args are varargs
    # and if the signature allows them.
    t_arg_arity, t_kwarg_arity = arg_arity, kwarg_arity
    if sig_arity > t_arg_arity
      # we transfer some kwargs arity to args arity
      # if it does not have enough args -- assuming the names will work out.
      t_kwarg_arity -= (sig_arity - t_arg_arity)
      t_arg_arity = sig_arity
    end

    if   (t_arg_arity == sig_arity ||   t_arg_arity > sig_arity && signature.var_args) &&
       (t_kwarg_arity == 0         || t_kwarg_arity > 0         && signature.var_kwargs)
      return signature
    end
  end
  @signatures[method_name].first
end

Instance Method Details

#abs($number) ⇒ Sass::Script::Value::Number

Returns the absolute value of a number.

Examples:

abs(10px) => 10px
abs(-10px) => 10px

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $number isn't a number



1783
1784
1785
# File 'lib/sass/script/functions.rb', line 1783

def abs(number)
  numeric_transformation(number) {|n| n.abs}
end

#adjust_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha]) ⇒ Sass::Script::Value::Color

Increases or decreases one or more properties of a color. This can change the red, green, blue, hue, saturation, value, and alpha properties. The properties are specified as keyword arguments, and are added to or subtracted from the color's current value for that property.

All properties are optional. You can't specify both RGB properties ($red, $green, $blue) and HSL properties ($hue, $saturation, $value) at the same time.

Examples:

adjust-color(#102030, $blue: 5) => #102035
adjust-color(#102030, $red: -5, $blue: 5) => #0b2035
adjust-color(hsl(25, 100%, 80%), $lightness: -30%, $alpha: -0.4) => hsla(25, 100%, 50%, 0.6)

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if any parameter is the wrong type or out-of bounds, or if RGB properties and HSL properties are adjusted at the same time



1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
# File 'lib/sass/script/functions.rb', line 1125

def adjust_color(color, kwargs)
  assert_type color, :Color, :color
  with = Sass::Util.map_hash(
      "red" => [-255..255, ""],
      "green" => [-255..255, ""],
      "blue" => [-255..255, ""],
      "hue" => nil,
      "saturation" => [-100..100, "%"],
      "lightness" => [-100..100, "%"],
      "alpha" => [-1..1, ""]
    ) do |name, (range, units)|

    val = kwargs.delete(name)
    next unless val
    assert_type val, :Number, name
    Sass::Util.check_range("$#{name}: Amount", range, val, units) if range
    adjusted = color.send(name) + val.value
    adjusted = [0, Sass::Util.restrict(adjusted, range)].max if range
    [name.to_sym, adjusted]
  end

  unless kwargs.empty?
    name, val = kwargs.to_a.first
    raise ArgumentError.new("Unknown argument $#{name} (#{val})")
  end

  color.with(with)
end

#adjust_hue($color, $degrees) ⇒ Sass::Script::Value::Color

Changes the hue of a color. Takes a color and a number of degrees (usually between -360deg and 360deg), and returns a color with the hue rotated along the color wheel by that amount.

Examples:

adjust-hue(hsl(120, 30%, 90%), 60deg) => hsl(180, 30%, 90%)
adjust-hue(hsl(120, 30%, 90%), -60deg) => hsl(60, 30%, 90%)
adjust-hue(#811, 45deg) => #886a11

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if either parameter is the wrong type



1063
1064
1065
1066
1067
# File 'lib/sass/script/functions.rb', line 1063

def adjust_hue(color, degrees)
  assert_type color, :Color, :color
  assert_type degrees, :Number, :degrees
  color.with(:hue => color.hue + degrees.value)
end

#alpha($color) ⇒ Sass::Script::Value::Number

Returns the alpha component (opacity) of a color. This is 1 unless otherwise specified.

This function also supports the proprietary Microsoft alpha(opacity=20) syntax as a special case.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color



893
894
895
896
897
898
899
900
901
902
903
904
905
906
# File 'lib/sass/script/functions.rb', line 893

def alpha(*args)
  if args.all? do |a|
       a.is_a?(Sass::Script::Value::String) && a.type == :identifier &&
         a.value =~ /^[a-zA-Z]+\s*=/
     end
    # Support the proprietary MS alpha() function
    return identifier("alpha(#{args.map {|a| a.to_s}.join(", ")})")
  end

  raise ArgumentError.new("wrong number of arguments (#{args.size} for 1)") if args.size != 1

  assert_type args.first, :Color, :color
  number(args.first.alpha)
end

#append($list, $val, $separator: auto) ⇒ Sass::Script::Value::List

Appends a single value onto the end of a list.

Unless the $separator argument is passed, if the list had only one item, the resulting list will be space-separated.

Like all list functions, append() returns a new list rather than modifying its argument in place.

Examples:

append(10px 20px, 30px) => 10px 20px 30px
append((blue, red), green) => blue, red, green
append(10px 20px, 30px 40px) => 10px 20px (30px 40px)
append(10px, 20px, comma) => 10px, 20px
append((blue, red), green, space) => blue red green

Parameters:

Returns:



1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
# File 'lib/sass/script/functions.rb', line 1957

def append(list, val, separator = identifier("auto"))
  assert_type separator, :String, :separator
  unless %w[auto space comma].include?(separator.value)
    raise ArgumentError.new("Separator name must be space, comma, or auto")
  end
  sep = if separator.value == 'auto'
          list.separator || :space
        else
          separator.value.to_sym
        end
  list(list.to_a + [val], sep)
end

#blue($color) ⇒ Sass::Script::Value::Number

Gets the blue component of a color. Calculated from HSL where necessary via this algorithm.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color



823
824
825
826
# File 'lib/sass/script/functions.rb', line 823

def blue(color)
  assert_type color, :Color, :color
  number(color.blue)
end

#call($name, $args...)

Dynamically calls a function. This can call user-defined functions, built-in functions, or plain CSS functions. It will pass along all arguments, including keyword arguments, to the called function.

Examples:

call(rgb, 10, 100, 255) => #0a64ff
call(scale-color, #0a64ff, $lightness: -10%) => #0058ef

$fn: nth;
call($fn, (a b c), 2) => b

Parameters:

  • $name (String)

    The name of the function to call.



2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
# File 'lib/sass/script/functions.rb', line 2225

def call(name, *args)
  assert_type name, :String, :name
  kwargs = args.last.is_a?(Hash) ? args.pop : {}
  funcall = Sass::Script::Tree::Funcall.new(
    name.value,
    args.map {|a| Sass::Script::Tree::Literal.new(a)},
    Sass::Util.map_vals(kwargs) {|v| Sass::Script::Tree::Literal.new(v)},
    nil,
    nil)
  funcall.options = options
  perform(funcall)
end

#ceil($number) ⇒ Sass::Script::Value::Number

Rounds a number up to the next whole number.

Examples:

ceil(10.4px) => 11px
ceil(10.6px) => 11px

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $number isn't a number



1755
1756
1757
# File 'lib/sass/script/functions.rb', line 1755

def ceil(number)
  numeric_transformation(number) {|n| n.ceil}
end

#change_color($color, [$red], [$green], [$blue], [$hue], [$saturation], [$lightness], [$alpha]) ⇒ Sass::Script::Value::Color

Changes one or more properties of a color. This can change the red, green, blue, hue, saturation, value, and alpha properties. The properties are specified as keyword arguments, and replace the color's current value for that property.

All properties are optional. You can't specify both RGB properties ($red, $green, $blue) and HSL properties ($hue, $saturation, $value) at the same time.

Examples:

change-color(#102030, $blue: 5) => #102005
change-color(#102030, $red: 120, $blue: 5) => #782005
change-color(hsl(25, 100%, 80%), $lightness: 40%, $alpha: 0.8) => hsla(25, 100%, 40%, 0.8)

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if any parameter is the wrong type or out-of bounds, or if RGB properties and HSL properties are adjusted at the same time



1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
# File 'lib/sass/script/functions.rb', line 1267

def change_color(color, kwargs)
  assert_type color, :Color, :color
  with = Sass::Util.map_hash(
    'red' => ['Red value', 0..255],
    'green' => ['Green value', 0..255],
    'blue' => ['Blue value', 0..255],
    'hue' => [],
    'saturation' => ['Saturation', 0..100, '%'],
    'lightness' => ['Lightness', 0..100, '%'],
    'alpha' => ['Alpha channel', 0..1]
  ) do |name, (desc, range, unit)|
    val = kwargs.delete(name)
    next unless val
    assert_type val, :Number, name

    if range
      val = Sass::Util.check_range(desc, range, val, unit)
    else
      val = val.value
    end

    [name.to_sym, val]
  end

  unless kwargs.empty?
    name, val = kwargs.to_a.first
    raise ArgumentError.new("Unknown argument $#{name} (#{val})")
  end

  color.with(with)
end

#comparable($number1, $number2) ⇒ Sass::Script::Value::Bool

Returns whether two numbers can added, subtracted, or compared.

Examples:

comparable(2px, 1px) => true
comparable(100px, 3em) => false
comparable(10cm, 3mm) => true

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if either parameter is the wrong type



1708
1709
1710
1711
1712
# File 'lib/sass/script/functions.rb', line 1708

def comparable(number1, number2)
  assert_type number1, :Number, :number1
  assert_type number2, :Number, :number2
  bool(number1.comparable_to?(number2))
end

#complement($color) ⇒ Sass::Script::Value::Color

Returns the complement of a color. This is identical to adjust-hue(color, 180deg).

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color

See Also:



1386
1387
1388
# File 'lib/sass/script/functions.rb', line 1386

def complement(color)
  adjust_hue color, number(180)
end

#counter($args...) ⇒ Sass::Script::Value::String

This function only exists as a workaround for IE7's content: counter bug. It works identically to any other plain-CSS function, except it avoids adding spaces between the argument commas.

Examples:

counter(item, ".") => counter(item,".")

Returns:



2248
2249
2250
# File 'lib/sass/script/functions.rb', line 2248

def counter(*args)
  identifier("counter(#{args.map {|a| a.to_s(options)}.join(',')})")
end

#counters($args...) ⇒ Sass::Script::Value::String

This function only exists as a workaround for IE7's content: counter bug. It works identically to any other plain-CSS function, except it avoids adding spaces between the argument commas.

Examples:

counters(item, ".") => counters(item,".")

Returns:



2262
2263
2264
# File 'lib/sass/script/functions.rb', line 2262

def counters(*args)
  identifier("counters(#{args.map {|a| a.to_s(options)}.join(',')})")
end

#darken($color, $amount) ⇒ Sass::Script::Value::Color

Makes a color darker. Takes a color and a number between 0% and 100%, and returns a color with the lightness decreased by that amount.

Examples:

darken(hsl(25, 100%, 80%), 30%) => hsl(25, 100%, 50%)
darken(#800, 20%) => #200

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $amount is out of bounds, or either parameter is the wrong type

See Also:



1002
1003
1004
# File 'lib/sass/script/functions.rb', line 1002

def darken(color, amount)
  _adjust(color, amount, :lightness, 0..100, :-, "%")
end

#desaturate($color, $amount) ⇒ Sass::Script::Value::Color

Makes a color less saturated. Takes a color and a number between 0% and 100%, and returns a color with the saturation decreased by that value.

Examples:

desaturate(hsl(120, 30%, 90%), 20%) => hsl(120, 10%, 90%)
desaturate(#855, 20%) => #726b6b

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $amount is out of bounds, or either parameter is the wrong type

See Also:



1044
1045
1046
# File 'lib/sass/script/functions.rb', line 1044

def desaturate(color, amount)
  _adjust(color, amount, :saturation, 0..100, :-, "%")
end

#feature_exists($feature) ⇒ Sass::Script::Value::Bool

Returns whether a feature exists in the current Sass runtime.

The following features are supported:

  • global-variable-shadowing indicates that a local variable will shadow a global variable unless !global is used.

  • extend-selector-pseudoclass indicates that @extend will reach into selector pseudoclasses like :not.

  • units-level-3 indicates full support for unit arithmetic using units defined in the Values and Units Level 3 spec.

  • at-error indicates that the Sass @error directive is supported.

Examples:

feature-exists(some-feature-that-exists) => true
feature-exists(what-is-this-i-dont-know) => false

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $feature isn't a string



1656
1657
1658
1659
# File 'lib/sass/script/functions.rb', line 1656

def feature_exists(feature)
  assert_type feature, :String, :feature
  bool(Sass.has_feature?(feature.value))
end

#floor($number) ⇒ Sass::Script::Value::Number

Rounds a number down to the previous whole number.

Examples:

floor(10.4px) => 10px
floor(10.6px) => 10px

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $number isn't a number



1769
1770
1771
# File 'lib/sass/script/functions.rb', line 1769

def floor(number)
  numeric_transformation(number) {|n| n.floor}
end

#function_exists($name) ⇒ Sass::Script::Value::Bool

Check whether a function with the given name exists.

Examples:

function-exists(lighten) => true

@function myfunc { @return "something"; }
function-exists(myfunc) => true

Parameters:

Returns:



2322
2323
2324
2325
2326
2327
# File 'lib/sass/script/functions.rb', line 2322

def function_exists(name)
  assert_type name, :String, :name
  exists = Sass::Script::Functions.callable?(name.value.tr("-", "_"))
  exists ||= environment.function(name.value)
  bool(exists)
end

#global_variable_exists($name) ⇒ Sass::Script::Value::Bool

Check whether a variable with the given name exists in the global scope (at the top level of the file).

Examples:

$a-false-value: false;
global-variable-exists(a-false-value) => true

.foo {
  $some-var: false;
  @if global-variable-exists(some-var) { /* false, doesn't run */ }
}

Parameters:

Returns:



2304
2305
2306
2307
# File 'lib/sass/script/functions.rb', line 2304

def global_variable_exists(name)
  assert_type name, :String, :name
  bool(environment.global_env.var(name.value))
end

#grayscale($color) ⇒ Sass::Script::Value::Color

Converts a color to grayscale. This is identical to desaturate(color, 100%).

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color

See Also:



1370
1371
1372
1373
1374
1375
# File 'lib/sass/script/functions.rb', line 1370

def grayscale(color)
  if color.is_a?(Sass::Script::Value::Number)
    return identifier("grayscale(#{color})")
  end
  desaturate color, number(100)
end

#green($color) ⇒ Sass::Script::Value::Number

Gets the green component of a color. Calculated from HSL where necessary via this algorithm.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color



807
808
809
810
# File 'lib/sass/script/functions.rb', line 807

def green(color)
  assert_type color, :Color, :color
  number(color.green)
end

#hsl($hue, $saturation, $lightness) ⇒ Sass::Script::Value::Color

Creates a Color from hue, saturation, and lightness values. Uses the algorithm from the CSS3 spec.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $saturation or $lightness are out of bounds or any parameter is the wrong type

See Also:



731
732
733
734
735
736
737
# File 'lib/sass/script/functions.rb', line 731

def hsl(hue, saturation, lightness)
  if calc?(hue) || calc?(saturation) || calc?(lightness)
    unquoted_string("hsl(#{hue}, #{saturation}, #{lightness})")
  else
    hsla(hue, saturation, lightness, number(1))
  end
end

#hsla($hue, $saturation, $lightness, $alpha) ⇒ Sass::Script::Value::Color

Creates a Color from hue, saturation, lightness, and alpha values. Uses the algorithm from the CSS3 spec.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $saturation, $lightness, or $alpha are out of bounds or any parameter is the wrong type

See Also:



759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
# File 'lib/sass/script/functions.rb', line 759

def hsla(hue, saturation, lightness, alpha)
  if calc?(hue) || calc?(saturation) || calc?(lightness) || calc?(alpha)
    return unquoted_string("hsla(#{hue}, #{saturation}, #{lightness}, #{alpha})")
  end
  assert_type hue, :Number, :hue
  assert_type saturation, :Number, :saturation
  assert_type lightness, :Number, :lightness
  assert_type alpha, :Number, :alpha
  check_alpha_unit alpha, 'hsla'

  h = hue.value
  s = saturation.value
  l = lightness.value

  # Don't store the string representation for function-created colors, both
  # because it's not very useful and because some functions aren't supported
  # on older browsers.
  Sass::Script::Value::Color.new(
    :hue => h, :saturation => s, :lightness => l, :alpha => alpha.value)
end

#hue($color) ⇒ Sass::Script::Value::Number

Returns the hue component of a color. See the CSS3 HSL specification. Calculated from RGB where necessary via this algorithm.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color



841
842
843
844
# File 'lib/sass/script/functions.rb', line 841

def hue(color)
  assert_type color, :Color, :color
  number(color.hue, "deg")
end

#ie_hex_str($color) ⇒ Sass::Script::Value::String

Converts a color into the format understood by IE filters.

Examples:

ie-hex-str(#abc) => #FFAABBCC
ie-hex-str(#3322BB) => #FF3322BB
ie-hex-str(rgba(0, 255, 0, 0.5)) => #8000FF00

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color



1081
1082
1083
1084
1085
# File 'lib/sass/script/functions.rb', line 1081

def ie_hex_str(color)
  assert_type color, :Color, :color
  alpha = Sass::Util.round(color.alpha * 255).to_s(16).rjust(2, '0')
  identifier("##{alpha}#{color.send(:hex_str)[1..-1]}".upcase)
end

#if($condition, $if-true, $if-false) ⇒ Sass::Script::Value::Base

Returns one of two values, depending on whether or not $condition is true. Just like in @if, all values other than false and null are considered to be true.

Examples:

if(true, 1px, 2px) => 1px
if(false, 1px, 2px) => 2px

Parameters:

Returns:



2186
2187
2188
2189
2190
2191
2192
# File 'lib/sass/script/functions.rb', line 2186

def if(condition, if_true, if_false)
  if condition.to_bool
    perform(if_true)
  else
    perform(if_false)
  end
end

#index($list, $value) ⇒ Sass::Script::Value::Number, Sass::Script::Value::Null

Returns the position of a value within a list. If the value isn't found, returns null instead.

Note that unlike some languages, the first item in a Sass list is number 1, the second number 2, and so forth.

This can return the position of a pair in a map as well.

Examples:

index(1px solid red, solid) => 2
index(1px solid red, dashed) => null
index((width: 10px, height: 20px), (height 20px)) => 2

Returns:



2018
2019
2020
2021
# File 'lib/sass/script/functions.rb', line 2018

def index(list, value)
  index = list.to_a.index {|e| e.eq(value).to_bool}
  index ? number(index + 1) : null
end

#inspect($value) ⇒ Sass::Script::Value::String

Return a string containing the value as its Sass representation.

Parameters:

Returns:



2354
2355
2356
# File 'lib/sass/script/functions.rb', line 2354

def inspect(value)
  unquoted_string(value.to_sass)
end

#invert($color) ⇒ Sass::Script::Value::Color

Returns the inverse (negative) of a color. The red, green, and blue values are inverted, while the opacity is left alone.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color



1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
# File 'lib/sass/script/functions.rb', line 1398

def invert(color)
  if color.is_a?(Sass::Script::Value::Number)
    return identifier("invert(#{color})")
  end

  assert_type color, :Color, :color
  color.with(
    :red => (255 - color.red),
    :green => (255 - color.green),
    :blue => (255 - color.blue))
end

#is_superselector($super, $sub) ⇒ Sass::Script::Value::Bool

Returns whether $super is a superselector of $sub. This means that $super matches all the elements that $sub matches, as well as possibly additional elements. In general, simpler selectors tend to be superselectors of more complex oned.

Examples:

is-superselector(".foo", ".foo.bar") => true
is-superselector(".foo.bar", ".foo") => false
is-superselector(".bar", ".foo .bar") => true
is-superselector(".foo .bar", ".bar") => false

Returns Whether $selector1 is a superselector of $selector2.

Parameters:

Returns:



2651
2652
2653
2654
2655
# File 'lib/sass/script/functions.rb', line 2651

def is_superselector(sup, sub)
  sup = parse_selector(sup, :super)
  sub = parse_selector(sub, :sub)
  bool(sup.superselector?(sub))
end

#join($list1, $list2, $separator: auto) ⇒ Sass::Script::Value::List

Joins together two lists into one.

Unless $separator is passed, if one list is comma-separated and one is space-separated, the first parameter's separator is used for the resulting list. If both lists have fewer than two items, spaces are used for the resulting list.

Like all list functions, join() returns a new list rather than modifying its arguments in place.

Examples:

join(10px 20px, 30px 40px) => 10px 20px 30px 40px
join((blue, red), (#abc, #def)) => blue, red, #abc, #def
join(10px, 20px) => 10px 20px
join(10px, 20px, comma) => 10px, 20px
join((blue, red), (#abc, #def), space) => blue red #abc #def

Parameters:

Returns:



1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
# File 'lib/sass/script/functions.rb', line 1921

def join(list1, list2, separator = identifier("auto"))
  assert_type separator, :String, :separator
  unless %w[auto space comma].include?(separator.value)
    raise ArgumentError.new("Separator name must be space, comma, or auto")
  end
  sep = if separator.value == 'auto'
          list1.separator || list2.separator || :space
        else
          separator.value.to_sym
        end
  list(list1.to_a + list2.to_a, sep)
end

#keywords($args) ⇒ Sass::Script::Value::Map

Returns the map of named arguments passed to a function or mixin that takes a variable argument list. The argument names are strings, and they do not contain the leading $.

Examples:

@mixin foo($args...) {
  @debug keywords($args); //=> (arg1: val, arg2: val)
}

@include foo($arg1: val, $arg2: val);

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $args isn't a variable argument list



2167
2168
2169
2170
# File 'lib/sass/script/functions.rb', line 2167

def keywords(args)
  assert_type args, :ArgList, :args
  map(Sass::Util.map_keys(args.keywords.as_stored) {|k| Sass::Script::Value::String.new(k)})
end

#length($list) ⇒ Sass::Script::Value::Number

Return the length of a list.

This can return the number of pairs in a map as well.

Examples:

length(10px) => 1
length(10px 20px 30px) => 3
length((width: 10px, height: 20px)) => 2

Parameters:

Returns:



1833
1834
1835
# File 'lib/sass/script/functions.rb', line 1833

def length(list)
  number(list.to_a.size)
end

#lighten($color, $amount) ⇒ Sass::Script::Value::Color

Makes a color lighter. Takes a color and a number between 0% and 100%, and returns a color with the lightness increased by that amount.

Examples:

lighten(hsl(0, 0%, 0%), 30%) => hsl(0, 0, 30)
lighten(#800, 20%) => #e00

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $amount is out of bounds, or either parameter is the wrong type

See Also:



983
984
985
# File 'lib/sass/script/functions.rb', line 983

def lighten(color, amount)
  _adjust(color, amount, :lightness, 0..100, :+, "%")
end

#lightness($color) ⇒ Sass::Script::Value::Number

Returns the lightness component of a color. See the CSS3 HSL specification. Calculated from RGB where necessary via this algorithm.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color



877
878
879
880
# File 'lib/sass/script/functions.rb', line 877

def lightness(color)
  assert_type color, :Color, :color
  number(color.lightness, "%")
end

#list_separator($list) ⇒ Sass::Script::Value::String

Returns the separator of a list. If the list doesn't have a separator due to having fewer than two elements, returns space.

Examples:

list-separator(1px 2px 3px) => space
list-separator(1px, 2px, 3px) => comma
list-separator('foo') => space

Parameters:

Returns:



2034
2035
2036
# File 'lib/sass/script/functions.rb', line 2034

def list_separator(list)
  identifier((list.separator || :space).to_s)
end

#map_get($map, $key) ⇒ Sass::Script::Value::Base

Returns the value in a map associated with the given key. If the map doesn't have such a key, returns null.

Examples:

map-get(("foo": 1, "bar": 2), "foo") => 1
map-get(("foo": 1, "bar": 2), "bar") => 2
map-get(("foo": 1, "bar": 2), "baz") => null

Returns:

Raises:

  • (ArgumentError)

    if $map is not a map



2052
2053
2054
2055
# File 'lib/sass/script/functions.rb', line 2052

def map_get(map, key)
  assert_type map, :Map, :map
  map.to_h[key] || null
end

#map_has_key($map, $key) ⇒ Sass::Script::Value::Bool

Returns whether a map has a value associated with a given key.

Examples:

map-has-key(("foo": 1, "bar": 2), "foo") => true
map-has-key(("foo": 1, "bar": 2), "baz") => false

Returns:

Raises:

  • (ArgumentError)

    if $map is not a map



2147
2148
2149
2150
# File 'lib/sass/script/functions.rb', line 2147

def map_has_key(map, key)
  assert_type map, :Map, :map
  bool(map.to_h.has_key?(key))
end

#map_keys($map) ⇒ List

Returns a list of all keys in a map.

Examples:

map-keys(("foo": 1, "bar": 2)) => "foo", "bar"

Parameters:

  • $map (Map)

Returns:

  • (List)

    the list of keys, comma-separated

Raises:

  • (ArgumentError)

    if $map is not a map



2115
2116
2117
2118
# File 'lib/sass/script/functions.rb', line 2115

def map_keys(map)
  assert_type map, :Map, :map
  list(map.to_h.keys, :comma)
end

#map_merge($map1, $map2) ⇒ Sass::Script::Value::Map

Merges two maps together into a new map. Keys in $map2 will take precedence over keys in $map1.

This is the best way to add new values to a map.

All keys in the returned map that also appear in $map1 will have the same order as in $map1. New keys from $map2 will be placed at the end of the map.

Like all map functions, map-merge() returns a new map rather than modifying its arguments in place.

Examples:

map-merge(("foo": 1), ("bar": 2)) => ("foo": 1, "bar": 2)
map-merge(("foo": 1, "bar": 2), ("bar": 3)) => ("foo": 1, "bar": 3)

Returns:

Raises:

  • (ArgumentError)

    if either parameter is not a map



2078
2079
2080
2081
2082
# File 'lib/sass/script/functions.rb', line 2078

def map_merge(map1, map2)
  assert_type map1, :Map, :map1
  assert_type map2, :Map, :map2
  map(map1.to_h.merge(map2.to_h))
end

#map_remove($map, $keys...) ⇒ Sass::Script::Value::Map

Returns a new map with keys removed.

Like all map functions, map-merge() returns a new map rather than modifying its arguments in place.

Examples:

map-remove(("foo": 1, "bar": 2), "bar") => ("foo": 1)
map-remove(("foo": 1, "bar": 2, "baz": 3), "bar", "baz") => ("foo": 1)
map-remove(("foo": 1, "bar": 2), "baz") => ("foo": 1, "bar": 2)

Returns:

Raises:

  • (ArgumentError)

    if $map is not a map



2099
2100
2101
2102
2103
2104
# File 'lib/sass/script/functions.rb', line 2099

def map_remove(map, *keys)
  assert_type map, :Map, :map
  hash = map.to_h.dup
  hash.delete_if {|key, _| keys.include?(key)}
  map(hash)
end

#map_values($map) ⇒ List

Returns a list of all values in a map. This list may include duplicate values, if multiple keys have the same value.

Examples:

map-values(("foo": 1, "bar": 2)) => 1, 2
map-values(("foo": 1, "bar": 2, "baz": 1)) => 1, 2, 1

Parameters:

  • $map (Map)

Returns:

  • (List)

    the list of values, comma-separated

Raises:

  • (ArgumentError)

    if $map is not a map



2131
2132
2133
2134
# File 'lib/sass/script/functions.rb', line 2131

def map_values(map)
  assert_type map, :Map, :map
  list(map.to_h.values, :comma)
end

#max($numbers...) ⇒ Sass::Script::Value::Number

Finds the maximum of several numbers. This function takes any number of arguments.

Examples:

max(1px, 4px) => 4px
max(5em, 3em, 4em) => 5em

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if any argument isn't a number, or if not all of the arguments have comparable units



1816
1817
1818
1819
# File 'lib/sass/script/functions.rb', line 1816

def max(*values)
  values.each {|v| assert_type v, :Number}
  values.inject {|max, val| max.gt(val).to_bool ? max : val}
end

#min($numbers...) ⇒ Sass::Script::Value::Number

Finds the minimum of several numbers. This function takes any number of arguments.

Examples:

min(1px, 4px) => 1px
min(5em, 3em, 4em) => 3em

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if any argument isn't a number, or if not all of the arguments have comparable units



1799
1800
1801
1802
# File 'lib/sass/script/functions.rb', line 1799

def min(*numbers)
  numbers.each {|n| assert_type n, :Number}
  numbers.inject {|min, num| min.lt(num).to_bool ? min : num}
end

#mix($color1, $color2, $weight: 50%) ⇒ Sass::Script::Value::Color

Mixes two colors together. Specifically, takes the average of each of the RGB components, optionally weighted by the given percentage. The opacity of the colors is also considered when weighting the components.

The weight specifies the amount of the first color that should be included in the returned color. The default, 50%, means that half the first color and half the second color should be used. 25% means that a quarter of the first color and three quarters of the second color should be used.

Examples:

mix(#f00, #00f) => #7f007f
mix(#f00, #00f, 25%) => #3f00bf
mix(rgba(255, 0, 0, 0.5), #00f) => rgba(63, 0, 191, 0.75)

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $weight is out of bounds or any parameter is the wrong type



1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
# File 'lib/sass/script/functions.rb', line 1322

def mix(color1, color2, weight = number(50))
  assert_type color1, :Color, :color1
  assert_type color2, :Color, :color2
  assert_type weight, :Number, :weight

  Sass::Util.check_range("Weight", 0..100, weight, '%')

  # This algorithm factors in both the user-provided weight (w) and the
  # difference between the alpha values of the two colors (a) to decide how
  # to perform the weighted average of the two RGB values.
  #
  # It works by first normalizing both parameters to be within [-1, 1],
  # where 1 indicates "only use color1", -1 indicates "only use color2", and
  # all values in between indicated a proportionately weighted average.
  #
  # Once we have the normalized variables w and a, we apply the formula
  # (w + a)/(1 + w*a) to get the combined weight (in [-1, 1]) of color1.
  # This formula has two especially nice properties:
  #
  #   * When either w or a are -1 or 1, the combined weight is also that number
  #     (cases where w * a == -1 are undefined, and handled as a special case).
  #
  #   * When a is 0, the combined weight is w, and vice versa.
  #
  # Finally, the weight of color1 is renormalized to be within [0, 1]
  # and the weight of color2 is given by 1 minus the weight of color1.
  p = (weight.value / 100.0).to_f
  w = p * 2 - 1
  a = color1.alpha - color2.alpha

  w1 = ((w * a == -1 ? w : (w + a) / (1 + w * a)) + 1) / 2.0
  w2 = 1 - w1

  rgba = color1.rgb.zip(color2.rgb).map {|v1, v2| v1 * w1 + v2 * w2}
  rgba << color1.alpha * p + color2.alpha * (1 - p)
  rgb_color(*rgba)
end

#mixin_exists($name) ⇒ Sass::Script::Value::Bool

Check whether a mixin with the given name exists.

Examples:

mixin-exists(nonexistent) => false

@mixin red-text { color: red; }
mixin-exists(red-text) => true

Parameters:

Returns:



2342
2343
2344
2345
# File 'lib/sass/script/functions.rb', line 2342

def mixin_exists(name)
  assert_type name, :String, :name
  bool(environment.mixin(name.value))
end

#nth($list, $n) ⇒ Sass::Script::Value::Base

Gets the nth item in a list.

Note that unlike some languages, the first item in a Sass list is number 1, the second number 2, and so forth.

This can return the nth pair in a map as well.

Negative index values address elements in reverse order, starting with the last element in the list.

Examples:

nth(10px 20px 30px, 1) => 10px
nth((Helvetica, Arial, sans-serif), 3) => sans-serif
nth((width: 10px, length: 20px), 2) => length, 20px

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $n isn't an integer between 1 and the length of $list



1889
1890
1891
1892
1893
1894
1895
# File 'lib/sass/script/functions.rb', line 1889

def nth(list, n)
  assert_type n, :Number, :n
  Sass::Script::Value::List.assert_valid_index(list, n)

  index = n.to_i > 0 ? n.to_i - 1 : n.to_i
  list.to_a[index]
end

#opacify($color, $amount) ⇒ Sass::Script::Value::Color Also known as: fade_in

Makes a color more opaque. Takes a color and a number between 0 and 1, and returns a color with the opacity increased by that amount.

Examples:

opacify(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.6)
opacify(rgba(0, 0, 17, 0.8), 0.2) => #001

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $amount is out of bounds, or either parameter is the wrong type

See Also:



939
940
941
# File 'lib/sass/script/functions.rb', line 939

def opacify(color, amount)
  _adjust(color, amount, :alpha, 0..1, :+)
end

#opacity($color) ⇒ Sass::Script::Value::Number

Returns the alpha component (opacity) of a color. This is 1 unless otherwise specified.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color



916
917
918
919
920
921
922
# File 'lib/sass/script/functions.rb', line 916

def opacity(color)
  if color.is_a?(Sass::Script::Value::Number)
    return identifier("opacity(#{color})")
  end
  assert_type color, :Color, :color
  number(color.alpha)
end

#percentage($number) ⇒ Sass::Script::Value::Number

Converts a unitless number to a percentage.

Examples:

percentage(0.2) => 20%
percentage(100px / 50px) => 200%

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $number isn't a unitless number



1724
1725
1726
1727
1728
1729
# File 'lib/sass/script/functions.rb', line 1724

def percentage(number)
  unless number.is_a?(Sass::Script::Value::Number) && number.unitless?
    raise ArgumentError.new("$number: #{number.inspect} is not a unitless number")
  end
  number(number.value * 100, '%')
end

#quote($string) ⇒ Sass::Script::Value::String

Add quotes to a string if the string isn't quoted, or returns the same string if it is.

Examples:

quote("foo") => "foo"
quote(foo) => "foo"

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $string isn't a string

See Also:



1457
1458
1459
1460
1461
1462
1463
1464
# File 'lib/sass/script/functions.rb', line 1457

def quote(string)
  assert_type string, :String, :string
  if string.type != :string
    quoted_string(string.value)
  else
    string
  end
end

#randomSass::Script::Value::Number #random($limit) ⇒ Sass::Script::Value::Number

Overloads:



2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
# File 'lib/sass/script/functions.rb', line 2368

def random(limit = nil)
  generator = Sass::Script::Functions.random_number_generator
  if limit
    assert_integer limit, "limit"
    if limit.to_i < 1
      raise ArgumentError.new("$limit #{limit} must be greater than or equal to 1")
    end
    number(1 + generator.rand(limit.to_i))
  else
    number(generator.rand)
  end
end

#red($color) ⇒ Sass::Script::Value::Number

Gets the red component of a color. Calculated from HSL where necessary via this algorithm.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color



791
792
793
794
# File 'lib/sass/script/functions.rb', line 791

def red(color)
  assert_type color, :Color, :color
  number(color.red)
end

#rgb($red, $green, $blue) ⇒ Sass::Script::Value::Color

Creates a Color object from red, green, and blue values.

Parameters:

  • $red (Sass::Script::Value::Number)

    The amount of red in the color. Must be between 0 and 255 inclusive, or between 0% and 100% inclusive

  • $green (Sass::Script::Value::Number)

    The amount of green in the color. Must be between 0 and 255 inclusive, or between 0% and 100% inclusive

  • $blue (Sass::Script::Value::Number)

    The amount of blue in the color. Must be between 0 and 255 inclusive, or between 0% and 100% inclusive

Returns:

Raises:

  • (ArgumentError)

    if any parameter is the wrong type or out of bounds

See Also:



632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
# File 'lib/sass/script/functions.rb', line 632

def rgb(red, green, blue)
  if calc?(red) || calc?(green) || calc?(blue)
    return unquoted_string("rgb(#{red}, #{green}, #{blue})")
  end
  assert_type red, :Number, :red
  assert_type green, :Number, :green
  assert_type blue, :Number, :blue

  color_attrs = [[red, :red], [green, :green], [blue, :blue]].map do |(c, name)|
    if c.is_unit?("%")
      c.value * 255 / 100.0
    elsif c.unitless?
      c.value
    else
      raise ArgumentError.new("Expected #{c} to be unitless or have a unit of % but got #{c}")
    end
  end

  # Don't store the string representation for function-created colors, both
  # because it's not very useful and because some functions aren't supported
  # on older browsers.
  Sass::Script::Value::Color.new(color_attrs)
end

#rgba($red, $green, $blue, $alpha) ⇒ Sass::Script::Value::Color #rgba($color, $alpha) ⇒ Sass::Script::Value::Color

Creates a Color from red, green, blue, and alpha values.

Overloads:

See Also:



688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
# File 'lib/sass/script/functions.rb', line 688

def rgba(*args)
  case args.size
  when 2
    color, alpha = args

    assert_type color, :Color, :color
    if calc?(alpha)
      unquoted_string("rgba(#{color.red}, #{color.green}, #{color.blue}, #{alpha})")
    else
      assert_type alpha, :Number, :alpha
      check_alpha_unit alpha, 'rgba'
      color.with(:alpha => alpha.value)
    end
  when 4
    red, green, blue, alpha = args
    if calc?(red) || calc?(green) || calc?(blue) || calc?(alpha)
      unquoted_string("rgba(#{red}, #{green}, #{blue}, #{alpha})")
    else
      rgba(rgb(red, green, blue), alpha)
    end
  else
    raise ArgumentError.new("wrong number of arguments (#{args.size} for 4)")
  end
end

#round($number) ⇒ Sass::Script::Value::Number

Rounds a number to the nearest whole number.

Examples:

round(10.4px) => 10px
round(10.6px) => 11px

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $number isn't a number



1741
1742
1743
# File 'lib/sass/script/functions.rb', line 1741

def round(number)
  numeric_transformation(number) {|n| Sass::Util.round(n)}
end

#saturate($color, $amount) ⇒ Sass::Script::Value::Color

Makes a color more saturated. Takes a color and a number between 0% and 100%, and returns a color with the saturation increased by that amount.

Examples:

saturate(hsl(120, 30%, 90%), 20%) => hsl(120, 50%, 90%)
saturate(#855, 20%) => #9e3f3f

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $amount is out of bounds, or either parameter is the wrong type

See Also:



1021
1022
1023
1024
1025
1026
# File 'lib/sass/script/functions.rb', line 1021

def saturate(color, amount = nil)
  # Support the filter effects definition of saturate.
  # https://dvcs.w3.org/hg/FXTF/raw-file/tip/filters/index.html
  return identifier("saturate(#{color})") if amount.nil?
  _adjust(color, amount, :saturation, 0..100, :+, "%")
end

#saturation($color) ⇒ Sass::Script::Value::Number

Returns the saturation component of a color. See the CSS3 HSL specification. Calculated from RGB where necessary via this algorithm.

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $color isn't a color



859
860
861
862
# File 'lib/sass/script/functions.rb', line 859

def saturation(color)
  assert_type color, :Color, :color
  number(color.saturation, "%")
end

#scale_color($color, [$red], [$green], [$blue], [$saturation], [$lightness], [$alpha]) ⇒ Sass::Script::Value::Color

Fluidly scales one or more properties of a color. Unlike adjust-color, which changes a color's properties by fixed amounts, scale-color fluidly changes them based on how high or low they already are. That means that lightening an already-light color with scale-color won't change the lightness much, but lightening a dark color by the same amount will change it more dramatically. This has the benefit of making scale-color($color, ...) have a similar effect regardless of what $color is.

For example, the lightness of a color can be anywhere between 0% and 100%. If scale-color($color, $lightness: 40%) is called, the resulting color's lightness will be 40% of the way between its original lightness and 100. If scale-color($color, $lightness: -40%) is called instead, the lightness will be 40% of the way between the original and 0.

This can change the red, green, blue, saturation, value, and alpha properties. The properties are specified as keyword arguments. All arguments should be percentages between 0% and 100%.

All properties are optional. You can't specify both RGB properties ($red, $green, $blue) and HSL properties ($saturation, $value) at the same time.

Examples:

scale-color(hsl(120, 70%, 80%), $lightness: 50%) => hsl(120, 70%, 90%)
scale-color(rgb(200, 150%, 170%), $green: -40%, $blue: 70%) => rgb(200, 90, 229)
scale-color(hsl(200, 70%, 80%), $saturation: -90%, $alpha: -30%) => hsla(200, 7%, 80%, 0.7)

Returns:

Raises:

  • (ArgumentError)

    if any parameter is the wrong type or out-of bounds, or if RGB properties and HSL properties are adjusted at the same time



1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
# File 'lib/sass/script/functions.rb', line 1198

def scale_color(color, kwargs)
  assert_type color, :Color, :color
  with = Sass::Util.map_hash(
      "red" => 255,
      "green" => 255,
      "blue" => 255,
      "saturation" => 100,
      "lightness" => 100,
      "alpha" => 1
    ) do |name, max|

    val = kwargs.delete(name)
    next unless val
    assert_type val, :Number, name
    assert_unit val, '%', name
    Sass::Util.check_range("$#{name}: Amount", -100..100, val, '%')

    current = color.send(name)
    scale = val.value / 100.0
    diff = scale > 0 ? max - current : current
    [name.to_sym, current + diff * scale]
  end

  unless kwargs.empty?
    name, val = kwargs.to_a.first
    raise ArgumentError.new("Unknown argument $#{name} (#{val})")
  end

  color.with(with)
end

#selector_append($selectors...) ⇒ Sass::Script::Value::List

Return a new selector with all selectors in $selectors appended one another as though they had been nested in the stylesheet as $selector1 { &$selector2 { ... } }.

Examples:

selector-append(".foo", ".bar", ".baz") => .foo.bar.baz
selector-append(".a .foo", ".b .bar") => "a .foo.b .bar"
selector-append(".foo", "-suffix") => ".foo-suffix"

Returns A list of lists of strings representing the result of appending $selectors. This is in the same format as a selector returned by &.

Parameters:

Returns:

  • (Sass::Script::Value::List)

    A list of lists of strings representing the result of appending $selectors. This is in the same format as a selector returned by &.

Raises:

  • (ArgumentError)

    if a selector could not be appended.



2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
# File 'lib/sass/script/functions.rb', line 2452

def selector_append(*selectors)
  if selectors.empty?
    raise ArgumentError.new("$selectors: At least one selector must be passed")
  end

  selectors.map {|sel| parse_selector(sel, :selectors)}.inject do |parent, child|
    child.members.each do |seq|
      sseq = seq.members.first
      unless sseq.is_a?(Sass::Selector::SimpleSequence)
        raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"")
      end

      base = sseq.base
      case base
      when Sass::Selector::Universal
        raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"")
      when Sass::Selector::Element
        unless base.namespace.nil?
          raise ArgumentError.new("Can't append \"#{seq}\" to \"#{parent}\"")
        end
        sseq.members[0] = Sass::Selector::Parent.new(base.name)
      else
        sseq.members.unshift Sass::Selector::Parent.new
      end
    end
    child.resolve_parent_refs(parent)
  end.to_sass_script
end

#selector_extend($selector, $extendee, $extender) ⇒ Sass::Script::Value::List

Returns a new version of $selector with $extendee extended with $extender. This works just like the result of

$selector { ... }
$extender { @extend $extendee }

Examples:

selector-extend(".a .b", ".b", ".foo .bar") => .a .b, .a .foo .bar, .foo .a .bar

Returns A list of lists of strings representing the result of the extension. This is in the same format as a selector returned by &.

Parameters:

Returns:

  • (Sass::Script::Value::List)

    A list of lists of strings representing the result of the extension. This is in the same format as a selector returned by &.

Raises:

  • (ArgumentError)

    if the extension fails



2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
# File 'lib/sass/script/functions.rb', line 2509

def selector_extend(selector, extendee, extender)
  selector = parse_selector(selector, :selector)
  extendee = parse_selector(extendee, :extendee)
  extender = parse_selector(extender, :extender)

  extends = Sass::Util::SubsetMap.new
  begin
    extender.populate_extends(extends, extendee)
    selector.do_extend(extends).to_sass_script
  rescue Sass::SyntaxError => e
    raise ArgumentError.new(e.to_s)
  end
end

#selector_nest($selectors...) ⇒ Sass::Script::Value::List

Return a new selector with all selectors in $selectors nested beneath one another as though they had been nested in the stylesheet as $selector1 { $selector2 { ... } }.

Unlike most selector functions, selector-nest allows the parent selector & to be used in any selector but the first.

Examples:

selector-nest(".foo", ".bar", ".baz") => .foo .bar .baz
selector-nest(".a .foo", ".b .bar") => .a .foo .b .bar
selector-nest(".foo", "&.bar") => .foo.bar

Returns A list of lists of strings representing the result of nesting $selectors. This is in the same format as a selector returned by &.

Parameters:

Returns:

  • (Sass::Script::Value::List)

    A list of lists of strings representing the result of nesting $selectors. This is in the same format as a selector returned by &.



2422
2423
2424
2425
2426
2427
2428
2429
2430
# File 'lib/sass/script/functions.rb', line 2422

def selector_nest(*selectors)
  if selectors.empty?
    raise ArgumentError.new("$selectors: At least one selector must be passed")
  end

  parsed = [parse_selector(selectors.first, :selectors)]
  parsed += selectors[1..-1].map {|sel| parse_selector(sel, :selectors, !!:parse_parent_ref)}
  parsed.inject {|result, child| child.resolve_parent_refs(result)}.to_sass_script
end

#selector_parse($selector) ⇒ Sass::Script::Value::List

Parses a user-provided selector into a list of lists of strings as returned by &.

Examples:

selector-parse(".foo .bar, .baz .bang") => ('.foo' '.bar', '.baz' '.bang')

Returns A list of lists of strings representing $selector. This is in the same format as a selector returned by &.

Parameters:

Returns:

  • (Sass::Script::Value::List)

    A list of lists of strings representing $selector. This is in the same format as a selector returned by &.



2396
2397
2398
# File 'lib/sass/script/functions.rb', line 2396

def selector_parse(selector)
  parse_selector(selector, :selector).to_sass_script
end

#selector_replace($selector, $original, $replacement) ⇒ Sass::Script::Value::List

Replaces all instances of $original with $replacement in $selector

This works by using @extend and throwing away the original selector. This means that it can be used to do very advanced replacements; see the examples below.

Examples:

selector-replace(".foo .bar", ".bar", ".baz") => ".foo .baz"
selector-replace(".foo.bar.baz", ".foo.baz", ".qux") => ".bar.qux"

Returns A list of lists of strings representing the result of the extension. This is in the same format as a selector returned by &.

Parameters:

Returns:

  • (Sass::Script::Value::List)

    A list of lists of strings representing the result of the extension. This is in the same format as a selector returned by &.

Raises:

  • (ArgumentError)

    if the replacement fails



2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
# File 'lib/sass/script/functions.rb', line 2552

def selector_replace(selector, original, replacement)
  selector = parse_selector(selector, :selector)
  original = parse_selector(original, :original)
  replacement = parse_selector(replacement, :replacement)

  extends = Sass::Util::SubsetMap.new
  begin
    replacement.populate_extends(extends, original)
    selector.do_extend(extends, [], !!:replace).to_sass_script
  rescue Sass::SyntaxError => e
    raise ArgumentError.new(e.to_s)
  end
end

#selector_unify($selector1, $selector2) ⇒ Sass::Script::Value::List, Sass::Script::Value::Null

Unifies two selectors into a single selector that matches only elements matched by both input selectors. Returns null if there is no such selector.

Like the selector unification done for @extend, this doesn't guarantee that the output selector will match all elements matched by both input selectors. For example, if .a .b is unified with .x .y, .a .x .b.y, .x .a .b.y will be returned, but .a.x .b.y will not. This avoids exponential output size while matching all elements that are likely to exist in practice.

Examples:

selector-unify(".a", ".b") => .a.b
selector-unify(".a .b", ".x .y") => .a .x .b.y, .x .a .b.y
selector-unify(".a.b", ".b.c") => .a.b.c
selector-unify("#a", "#b") => null

Returns A list of lists of strings representing the result of the unification, or null if no unification exists. This is in the same format as a selector returned by &.

Parameters:

Returns:



2598
2599
2600
2601
2602
2603
# File 'lib/sass/script/functions.rb', line 2598

def selector_unify(selector1, selector2)
  selector1 = parse_selector(selector1, :selector1)
  selector2 = parse_selector(selector2, :selector2)
  return null unless (unified = selector1.unify(selector2))
  unified.to_sass_script
end

#setSass::Script::Value::List

Return a new list, based on the list provided, but with the nth element changed to the value given.

Note that unlike some languages, the first item in a Sass list is number 1, the second number 2, and so forth.

Negative index values address elements in reverse order, starting with the last element in the list.

Examples:

set-nth($list: 10px 20px 30px, $n: 2, $value: -20px) => 10px -20px 30px

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $n isn't an integer between 1 and the length of $list



1858
1859
1860
1861
1862
1863
1864
1865
# File 'lib/sass/script/functions.rb', line 1858

def set_nth(list, n, value)
  assert_type n, :Number, :n
  Sass::Script::Value::List.assert_valid_index(list, n)
  index = n.to_i > 0 ? n.to_i - 1 : n.to_i
  new_list = list.to_a.dup
  new_list[index] = value
  Sass::Script::Value::List.new(new_list, list.separator)
end

#simple_selectors($selector) ⇒ Sass::Script::Value::List

Returns the simple selectors that comprise the compound selector $selector.

Note that $selector must be a compound selector. That means it cannot contain commas or spaces. It also means that unlike other selector functions, this takes only strings, not lists.

Examples:

simple-selectors(".foo.bar") => ".foo", ".bar"
simple-selectors(".foo.bar.baz") => ".foo", ".bar", ".baz"

Returns A list of simple selectors in the compound selector.

Parameters:

Returns:



2625
2626
2627
2628
# File 'lib/sass/script/functions.rb', line 2625

def simple_selectors(selector)
  selector = parse_compound_selector(selector, :selector)
  list(selector.members.map {|simple| unquoted_string(simple.to_s)}, :comma)
end

#str_index($string, $substring) ⇒ Sass::Script::Value::Number, Sass::Script::Value::Null

Returns the index of the first occurrence of $substring in $string. If there is no such occurrence, returns null.

Note that unlike some languages, the first character in a Sass string is number 1, the second number 2, and so forth.

Examples:

str-index(abcd, a)  => 1
str-index(abcd, ab) => 1
str-index(abcd, X)  => null
str-index(abcd, c)  => 3

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if any parameter is the wrong type



1533
1534
1535
1536
1537
1538
# File 'lib/sass/script/functions.rb', line 1533

def str_index(string, substring)
  assert_type string, :String, :string
  assert_type substring, :String, :substring
  index = string.value.index(substring.value)
  index ? number(index + 1) : null
end

#str_insert($string, $insert, $index) ⇒ Sass::Script::Value::String

Inserts $insert into $string at $index.

Note that unlike some languages, the first character in a Sass string is number 1, the second number 2, and so forth.

Examples:

str-insert("abcd", "X", 1) => "Xabcd"
str-insert("abcd", "X", 4) => "abcXd"
str-insert("abcd", "X", 5) => "abcdX"

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if any parameter is the wrong type



1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
# File 'lib/sass/script/functions.rb', line 1501

def str_insert(original, insert, index)
  assert_type original, :String, :string
  assert_type insert, :String, :insert
  assert_integer index, :index
  assert_unit index, nil, :index
  insertion_point = if index.to_i > 0
                      [index.to_i - 1, original.value.size].min
                    else
                      [index.to_i, -original.value.size - 1].max
                    end
  result = original.value.dup.insert(insertion_point, insert.value)
  Sass::Script::Value::String.new(result, original.type)
end

#str_length($string) ⇒ Sass::Script::Value::Number

Returns the number of characters in a string.

Examples:

str-length("foo") => 3

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $string isn't a string



1475
1476
1477
1478
# File 'lib/sass/script/functions.rb', line 1475

def str_length(string)
  assert_type string, :String, :string
  number(string.value.size)
end

#str_slice($string, $start-at, $end-at: -1) ⇒ Sass::Script::Value::String

Extracts a substring from $string. The substring will begin at index $start-at and ends at index $end-at.

Note that unlike some languages, the first character in a Sass string is number 1, the second number 2, and so forth.

Examples:

str-slice("abcd", 2, 3)   => "bc"
str-slice("abcd", 2)      => "bcd"
str-slice("abcd", -3, -2) => "bc"
str-slice("abcd", 2, -2)  => "bc"

Returns The substring. This will be quoted if and only if $string was quoted.

Parameters:

  • $start-at (Sass::Script::Value::Number)

    The index of the first character of the substring. If this is negative, it counts from the end of $string

  • $end-before (Sass::Script::Value::Number)

    The index of the last character of the substring. If this is negative, it counts from the end of $string. Defaults to -1

Returns:

Raises:

  • (ArgumentError)

    if any parameter is the wrong type



1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
# File 'lib/sass/script/functions.rb', line 1563

def str_slice(string, start_at, end_at = nil)
  assert_type string, :String, :string
  assert_unit start_at, nil, "start-at"

  end_at = number(-1) if end_at.nil?
  assert_unit end_at, nil, "end-at"

  return Sass::Script::Value::String.new("", string.type) if end_at.value == 0
  s = start_at.value > 0 ? start_at.value - 1 : start_at.value
  e = end_at.value > 0 ? end_at.value - 1 : end_at.value
  s = string.value.length + s if s < 0
  s = 0 if s < 0
  e = string.value.length + e if e < 0
  e = 0 if s < 0
  extracted = string.value.slice(s..e)
  Sass::Script::Value::String.new(extracted || "", string.type)
end

#to_lower_case($string) ⇒ Sass::Script::Value::String

Convert a string to lower case,

Examples:

to-lower-case(ABCD) => abcd

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $string isn't a string



1607
1608
1609
1610
# File 'lib/sass/script/functions.rb', line 1607

def to_lower_case(string)
  assert_type string, :String, :string
  Sass::Script::Value::String.new(string.value.downcase, string.type)
end

#to_upper_case($string) ⇒ Sass::Script::Value::String

Converts a string to upper case.

Examples:

to-upper-case(abcd) => ABCD

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $string isn't a string



1592
1593
1594
1595
# File 'lib/sass/script/functions.rb', line 1592

def to_upper_case(string)
  assert_type string, :String, :string
  Sass::Script::Value::String.new(string.value.upcase, string.type)
end

#transparentize($color, $amount) ⇒ Sass::Script::Value::Color Also known as: fade_out

Makes a color more transparent. Takes a color and a number between 0 and 1, and returns a color with the opacity decreased by that amount.

Examples:

transparentize(rgba(0, 0, 0, 0.5), 0.1) => rgba(0, 0, 0, 0.4)
transparentize(rgba(0, 0, 0, 0.8), 0.2) => rgba(0, 0, 0, 0.6)

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $amount is out of bounds, or either parameter is the wrong type

See Also:



961
962
963
# File 'lib/sass/script/functions.rb', line 961

def transparentize(color, amount)
  _adjust(color, amount, :alpha, 0..1, :-)
end

#type_of($value) ⇒ Sass::Script::Value::String

Returns the type of a value.

Examples:

type-of(100px)  => number
type-of(asdf)   => string
type-of("asdf") => string
type-of(true)   => bool
type-of(#fff)   => color
type-of(blue)   => color

Parameters:

Returns:



1626
1627
1628
# File 'lib/sass/script/functions.rb', line 1626

def type_of(value)
  identifier(value.class.name.gsub(/Sass::Script::Value::/, '').downcase)
end

#unique_idSass::Script::Value::String

Returns a unique CSS identifier. The identifier is returned as an unquoted string. The identifier returned is only guaranteed to be unique within the scope of a single Sass run.



2201
2202
2203
2204
2205
2206
2207
2208
# File 'lib/sass/script/functions.rb', line 2201

def unique_id
  generator = Sass::Script::Functions.random_number_generator
  Thread.current[:sass_last_unique_id] ||= generator.rand(36**8)
  # avoid the temptation of trying to guess the next unique value.
  value = (Thread.current[:sass_last_unique_id] += (generator.rand(10) + 1))
  # the u makes this a legal identifier if it would otherwise start with a number.
  identifier("u" + value.to_s(36).rjust(8, '0'))
end

#unit($number) ⇒ Sass::Script::Value::String

Returns the unit(s) associated with a number. Complex units are sorted in alphabetical order by numerator and denominator.

Examples:

unit(100) => ""
unit(100px) => "px"
unit(3em) => "em"
unit(10px * 5em) => "em*px"
unit(10px * 5em / 30cm / 1rem) => "em*px/cm*rem"

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $number isn't a number



1676
1677
1678
1679
# File 'lib/sass/script/functions.rb', line 1676

def unit(number)
  assert_type number, :Number, :number
  quoted_string(number.unit_str)
end

#unitless($number) ⇒ Sass::Script::Value::Bool

Returns whether a number has units.

Examples:

unitless(100) => true
unitless(100px) => false

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $number isn't a number



1691
1692
1693
1694
# File 'lib/sass/script/functions.rb', line 1691

def unitless(number)
  assert_type number, :Number, :number
  bool(number.unitless?)
end

#unquote($string) ⇒ Sass::Script::Value::String

Removes quotes from a string. If the string is already unquoted, this will return it unmodified.

Examples:

unquote("foo") => foo
unquote(foo) => foo

Parameters:

Returns:

Raises:

  • (ArgumentError)

    if $string isn't a string

See Also:



1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
# File 'lib/sass/script/functions.rb', line 1422

def unquote(string)
  unless string.is_a?(Sass::Script::Value::String)
    # Don't warn multiple times for the same source line.
    # rubocop:disable GlobalVars
    $_sass_warned_for_unquote ||= Set.new
    frame = environment.stack.frames.last
    key = [frame.filename, frame.line] if frame
    return string if frame && $_sass_warned_for_unquote.include?(key)
    $_sass_warned_for_unquote << key if frame
    # rubocop:enable GlobalVars

    Sass::Util.sass_warn(<<MESSAGE.strip)
DEPRECATION WARNING: Passing #{string.to_sass}, a non-string value, to unquote()
will be an error in future versions of Sass.
#{environment.stack.to_s.gsub(/^/, ' ' * 8)}
MESSAGE
    return string
  end

  return string if string.type == :identifier
  identifier(string.value)
end

#variable_exists($name) ⇒ Sass::Script::Value::Bool

Check whether a variable with the given name exists in the current scope or in the global scope.

Examples:

$a-false-value: false;
variable-exists(a-false-value) => true

variable-exists(nonexistent) => false

Parameters:

Returns:



2281
2282
2283
2284
# File 'lib/sass/script/functions.rb', line 2281

def variable_exists(name)
  assert_type name, :String, :name
  bool(environment.caller.var(name.value))
end

#zip($lists...) ⇒ Sass::Script::Value::List

Combines several lists into a single multidimensional list. The nth value of the resulting list is a space separated list of the source lists' nth values.

The length of the resulting list is the length of the shortest list.

Examples:

zip(1px 1px 3px, solid dashed solid, red green blue)
=> 1px solid red, 1px dashed green, 3px solid blue

Parameters:

Returns:



1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
# File 'lib/sass/script/functions.rb', line 1985

def zip(*lists)
  length = nil
  values = []
  lists.each do |list|
    array = list.to_a
    values << array.dup
    length = length.nil? ? array.length : [length, array.length].min
  end
  values.each do |value|
    value.slice!(length)
  end
  new_list_value = values.first.zip(*values[1..-1])
  list(new_list_value.map {|list| list(list, :space)}, :comma)
end