Peter Berg
Peter Berg

Reputation: 6206

Legal characters for SASS and SCSS variable names

What characters are valid for use in SCSS variable names?

Upvotes: 21

Views: 7633

Answers (1)

hopper
hopper

Reputation: 13410

If you check out the source for the SASS lexer, you'll see:

# A hash of regular expressions that are used for tokenizing.
REGULAR_EXPRESSIONS = {
  :whitespace => /\s+/,
  :comment => COMMENT,
  :single_line_comment => SINGLE_LINE_COMMENT,
  :variable => /(\$)(#{IDENT})/,
  :ident => /(#{IDENT})(\()?/,
  :number => /(-)?(?:(\d*\.\d+)|(\d+))([a-zA-Z%]+)?/,
  :color => HEXCOLOR,
  :bool => /(true|false)\b/,
  :null => /null\b/,
  :ident_op => %r{(#{Regexp.union(*IDENT_OP_NAMES.map{|s| Regexp.new(Regexp.escape(s) + "(?!#{NMCHAR}|\Z)")})})},
  :op => %r{(#{Regexp.union(*OP_NAMES)})},
}

Which references the IDENT character set defined in a separate file:

s = if Sass::Util.ruby1_8?
      '\200-\377'
    elsif Sass::Util.macruby?
      '\u0080-\uD7FF\uE000-\uFFFD\U00010000-\U0010FFFF'
    else
      '\u{80}-\u{D7FF}\u{E000}-\u{FFFD}\u{10000}-\u{10FFFF}'
    end

H = /[0-9a-fA-F]/
UNICODE = /\\#{H}{1,6}[ \t\r\n\f]?/

NONASCII = /[#{s}]/
ESCAPE = /#{UNICODE}|\\[ -~#{s}]/
NMSTART = /[_a-zA-Z]|#{NONASCII}|#{ESCAPE}/
NMCHAR = /[a-zA-Z0-9_-]|#{NONASCII}|#{ESCAPE}/

IDENT = /-?#{NMSTART}#{NMCHAR}*/

So, it looks like variable names can contain:

  • Any ASCII letter.
  • Any number 0-9 (as long as it is not the first character in the name).
  • Underscores and hyphens.
  • ASCII punctuation (!"#$%&'()*+,./:;<=>?@[]^{|}~) and spaces, if escaped with a backslash.
  • Unicode characters in the ranges 0080-D7FF, E000-FFFD, or 10000-10FFFF.
  • Unicode hex escape sequences such as \00E4.

Upvotes: 27

Related Questions