Parse a css style sheet into the CSS object.

        For the moment this will only work for very simple css
        documents.  It works by using regular expression matching css
        syntax.  This is not bullet proof.
494715
def parse_css(self, css):
        
        rulesets = self.ruleset_re.findall(css)
        for (selector, declarations) in rulesets:
            rule = Rule(self.parse_selector(selector))
            rule.properties = self.parse_declarations(declarations)
            self.rules.append(rule)
874560
function parse(code, done) {
  var ast, err, jsonStyle = {}, log = []

  // css parse
  ast = css.parse(code, {silent: true})

  // catch syntax error
  if (ast.stylesheet.parsingErrors && ast.stylesheet.parsingErrors.length) {
    err = ast.stylesheet.parsingErrors
    err.forEach(function (error) {
      log.push({line: error.line, column: error.column, reason: error.toString().replace('Error', 'ERROR')})
    })
  }

  // walk all
  /* istanbul ignore else */
  if (ast && ast.type === 'stylesheet' && ast.stylesheet &&
      ast.stylesheet.rules && ast.stylesheet.rules.length) {
    ast.stylesheet.rules.forEach(function (rule) {
      var type = rule.type
      var ruleResult = {}
      var ruleLog = []

      if (type === 'rule') {
        if (rule.declarations && rule.declarations.length) {
          // transition shorthand parsing
          var CHUNK_REGEXP = /^(\S*)?\s*(\d*\.?\d+(?:ms|s)?)?\s*(\S*)?\s*(\d*\.?\d+(?:ms|s)?)?$/
          for (var i = 0; i < rule.declarations.length; i++) {
            var declaration = rule.declarations[i]
            if (declaration.property === 'transition') {
              var match = declaration.value.match(CHUNK_REGEXP)
              /* istanbul ignore else */
              if (match) {
                match[1] && rule.declarations.push({type: 'declaration', property: 'transition-property', value: match[1], position: declaration.position})
                match[2] && rule.declarations.push({type: 'declaration', property: 'transition-duration', value: match[2], position: declaration.position})
                match[3] && rule.declarations.push({type: 'declaration', property: 'transition-timing-function', value: match[3], position: declaration.position})
                match[4] && rule.declarations.push({type: 'declaration', property: 'transition-delay', value: match[4], position: declaration.position})
                rule.declarations.splice(i, 1)
                break
              }
            }
          }

          rule.declarations.forEach(function (declaration) {
            var subType = declaration.type
            var name, value, line, column, subResult, camelCasedName

            /* istanbul ignore if */
            if (subType !== 'declaration') {
              return
            }

            name = declaration.property
            value = declaration.value

            // validate declarations and collect them to result
            camelCasedName = util.hyphenedToCamelCase(name)
            subResult = validateItem(camelCasedName, value)

            /* istanbul ignore else */
            if (typeof subResult.value === 'number' || typeof subResult.value === 'string') {
              ruleResult[camelCasedName] = subResult.value
            }
            if (subResult.log) {
              subResult.log.line = declaration.position.start.line
              subResult.log.column = declaration.position.start.column
              ruleLog.push(subResult.log)
            }
          })

          rule.selectors.forEach(function (selector) {
            if (selector.match(/^\.[A-Za-z0-9_\-:]+$/)) {
              var className = selector.slice(1)

              // handle pseudo class
              var pseudoIndex = className.indexOf(':')
              if (pseudoIndex > -1) {
                var pseudoCls = className.slice(pseudoIndex)
                className = className.slice(0, pseudoIndex)
                var pseudoRuleResult = {}
                Object.keys(ruleResult).forEach(function (prop) {
                  pseudoRuleResult[prop + pseudoCls] = ruleResult[prop]
                })
                ruleResult = pseudoRuleResult
              }

              // merge style
              Object.keys(ruleResult).forEach(function (prop) {
                if (prop.indexOf('transition') === 0) { // handle transition
                  var realProp = prop.replace('transition', '')
                  realProp = realProp[0].toLowerCase() + realProp.slice(1)
                  jsonStyle['@TRANSITION'] = jsonStyle['@TRANSITION'] || {}
                  jsonStyle['@TRANSITION'][className] = jsonStyle['@TRANSITION'][className] || {}
                  jsonStyle['@TRANSITION'][className][realProp] = ruleResult[prop]
                }
                else {
                  jsonStyle[className] = jsonStyle[className] || {}
                  jsonStyle[className][prop] = ruleResult[prop]
                }
              })
            }
            else {
              log.push({
                line: rule.position.start.line,
                column: rule.position.start.column,
                reason: 'ERROR: Selector `' + selector + '` is not supported. Jud only support single-classname selector'
              })
            }
          })
          log = log.concat(ruleLog)
        }
      }
      /* istanbul ignore else */
      else if (type === 'font-face') {
        /* istanbul ignore else */
        if (rule.declarations && rule.declarations.length) {
          rule.declarations.forEach(function (declaration) {
            /* istanbul ignore if */
            if (declaration.type !== 'declaration') {
              return
            }
            var name = util.hyphenedToCamelCase(declaration.property)
            var value = declaration.value
            if (name === 'fontFamily' && '\"\''.indexOf(value[0]) > -1) { // FIXME: delete leading and trailing quotes
              value = value.slice(1, value.length - 1)
            }
            ruleResult[name] = value
          })
          if (!jsonStyle['@FONT-FACE']) {
            jsonStyle['@FONT-FACE'] = []
          }
          jsonStyle['@FONT-FACE'].push(ruleResult)
        }
      }
    })
  }

  done(err, {jsonStyle: jsonStyle, log: log})
}
967777
function getTokens(css) {
    // Parse string, character by character:
    for (pos = 0; pos < css.length; col++, pos++) {
      c = css.charAt(pos);
      cn = css.charAt(pos + 1);

      // If we meet `/*`, it's a start of a multiline comment.
      // Parse following characters as a multiline comment:
      if (c === '/' && cn === '*') {
        parseMLComment(css);
      }

      // If we meet `//` and it is not a part of url:
      else if (!urlMode && c === '/' && cn === '/') {
        // If we're currently inside a block, treat `//` as a start
        // of identifier. Else treat `//` as a start of a single-line
        // comment:
        parseSLComment(css);
      }

      // If current character is a double or single quote, it's a start
      // of a string:
      else if (c === '"' || c === "'") {
        parseString(css, c);
      }

      // If current character is a space:
      else if (c === ' ') {
        parseSpaces(css);
      }

      // If current character is `=`, it must be combined with next `=`
      else if (c === '=' && cn === '=') {
        parseEquality(css);
      }

      // If we meet `!=`, this must be inequality
      else if (c === '!' && cn === '=') {
        parseInequality(css);
      }

      // If current character is a punctuation mark:
      else if (c in Punctuation) {
        // Check for CRLF here or just LF
        if (c === '\r' && cn === '\n' || c === '\n') {
          // If \r we know the next character is \n due to statement above
          // so we push a CRLF token type to the token list and importantly
          // skip the next character so as not to double count newlines or
          // columns etc
          if (c === '\r') {
            pushToken(TokenType.Newline, '\r\n', col);
            pos++; // If CRLF skip the next character and push crlf token
          } else if (c === '\n') {
            // If just a LF newline and not part of CRLF newline we can just
            // push punctuation as usual
            pushToken(Punctuation[c], c, col);
          }

          ln++; // Go to next line
          col = 0; // Reset the column count
        } else if (c !== '\r' && c !== '\n') {
          // Handle all other punctuation and add to list of tokens
          pushToken(Punctuation[c], c, col);
        }// Go to next line
        if (c === ')') urlMode = false; // Exit url mode
        else if (c === '\t' && tabSize > 1) col += (tabSize - 1);
      }

      // If current character is a decimal digit:
      else if (isDecimalDigit(c)) {
        parseDecimalNumber(css);
      }

      // If current character is anything else:
      else {
        parseIdentifier(css);
      }
    }

    return tokens;
  }
490113
def parse
      ## pass 1) check for (css style) classes and data attributes
      ## check for css style classes
      from = 0
      while( pos = @content.index( /<!-- _S9(SLIDE|STYLE)_(.*?)-->/m, from ))
        logger.debug "  adding css classes from pi >#{$1.downcase}<: >#{$2.strip}<"

        from = Regexp.last_match.end(0)  # continue search later from here
        
        values = $2.strip.dup
        
        # remove data values (eg. x=-20 scale=4) and store in data hash
        values.gsub!( /([-\w]+)[ \t]*=[ \t]*([-\w\.]+)/ ) do |_|
          logger.debug "    adding data pair: key=>#{$1.downcase}< value=>#{$2}<"
          @data[ $1.downcase.dup ] = $2.dup
          " "  # replace w/ space
        end
        
        values.strip!  # remove spaces  # todo: use squish or similar and check for empty string
                
        if @classes.nil?
          @classes = values
        else
          @classes << " #{values}"
        end
      end

      ## pass 2) split slide source into header (optional) and content/body

      ## todo: add option split on h1/h2 etc.

      # try to extract first header using non-greedy .+? pattern;
      # tip test regex online at rubular.com
      #  note/fix: needs to get improved to also handle case for h1 wrapped into div

      if @header_level == 1
        pattern = /^(.*?)(<h1.*?>.*?<\/h1>)(.*)/m
      else # assume header level 2
        ## note: header_level 2 also incl. header_level 1 slides
        pattern = /^(.*?)(<(?:h1|h2).*?>.*?<\/(?:h1|h2)>)(.*)/m
      end

      if @content =~ pattern
        @header  = $2
        @content_without_header = ($1 ? $1 : '') + ($3 ? $3 : '')
        logger.debug "  adding slide with header:\n#{@header}"
      else
        @header = nil    # todo: set to '' empty string? why not?
        @content_without_header = @content
        logger.debug "  adding slide with *no* header:\n#{@content}"
      end
    end
327799
function loadCss (css, name) {
  if (css) {
    cssLoader.insertStyleElement(document, document.head, css, name, false)
  }
}
1074051
function (stylesheet) {
		var sheetMedia = stylesheet.media && stylesheet.media.mediaText;
		var sheetHost;

		// if this sheet is cross-origin and option is set skip it
		if (objectFit.disableCrossDomain == 'true') {
			sheetHost = getCSSHost(stylesheet.href);

			if ((sheetHost !== window.location.host)) {
				return [];
			}
		}


		// if this sheet is disabled skip it
		if (stylesheet.disabled) {
			return [];
		}

		if (!window.matchMedia) {
			if (sheetMedia && sheetMedia.length) {
				return [];
			}
		}
		// if this sheet's media is specified and doesn't match the viewport then skip it
		else if (sheetMedia && sheetMedia.length && ! window.matchMedia(sheetMedia).matches) {
			return [];
		}

		// get the style rules of this sheet
		return toArray(stylesheet.cssRules);
	}
1225847
def from_css(Class, csstext, encoding=None, href=None, media=None, title=None, validate=None):
        
        styles = Class()
        cssStyleSheet = cssutils.parseString(csstext, encoding=encoding, href=href, media=media, title=title, validate=validate)
        for rule in cssStyleSheet.cssRules:
            if rule.type==cssutils.css.CSSRule.FONT_FACE_RULE:
                if styles.get('@font-face') is None: styles['@font-face'] = []
                styles['@font-face'].append(Class.styleProperties(rule.style))
            
            elif rule.type==cssutils.css.CSSRule.IMPORT_RULE:
                if styles.get('@import') is None: styles['@import'] = []
                styles['@import'].append("url(%s)" % rule.href)

            elif rule.type==cssutils.css.CSSRule.NAMESPACE_RULE:
                if styles.get('@namespace') is None: styles['@namespace'] = {}
                styles['@namespace'][rule.prefix] = rule.namespaceURI
            
            elif rule.type==cssutils.css.CSSRule.MEDIA_RULE:
                if styles.get('@media') is None: styles['@media'] = []
                styles['@media'].append(rule.cssText)
            
            elif rule.type==cssutils.css.CSSRule.PAGE_RULE:
                if styles.get('@page') is None: styles['@page'] = []
                styles['@page'].append(rule.cssText)

            elif rule.type==cssutils.css.CSSRule.STYLE_RULE:
                for selector in rule.selectorList:
                    sel = selector.selectorText
                    if sel not in styles:
                        styles[sel] = Class.styleProperties(rule.style)
            
            elif rule.type==cssutils.css.CSSRule.CHARSET_RULE:
                styles['@charset'] = rule.encoding

            elif rule.type==cssutils.css.CSSRule.COMMENT:   # comments are thrown away
                pass

            elif rule.type==cssutils.css.CSSRule.VARIABLES_RULE:
                pass
            
            else:
                log.warning("Unknown rule type: %r" % rule.cssText)

        return styles
1236678
def process_styles (out)
      out.gsub /(<style\b[^>]*?>([\s\S]*?)<\/style>)\s*/i do
        css = $2
        m = $1.gsub /^<style\s([^>]+)>/i do |m|
          attrs(m, 'style', true)
        end
        begin
          css_compressed = MultiCss.min css
          m.gsub!(css, css_compressed)
        rescue Exception => e
          log e.message
        end
        reserve m
      end
    end
534813
def parse_style(document, xmlcontent):
    

    styles = etree.fromstring(xmlcontent)

    _r = styles.xpath('.//w:rPrDefault', namespaces=NAMESPACES)

    if len(_r) > 0:
        rpr = _r[0].find(_name('{{{w}}}rPr'))

        if rpr is not None:
            st = doc.Style()
            parse_previous_properties(document, st, rpr)
            document.default_style = st

    # rest of the styles
    for style in styles.xpath('.//w:style', namespaces=NAMESPACES):
        st = doc.Style()

        st.style_id = style.attrib[_name('{{{w}}}styleId')]

        style_type = style.attrib[_name('{{{w}}}type')]
        if style_type is not None:
            st.style_type = style_type

        if _name('{{{w}}}default') in style.attrib:
            is_default = style.attrib[_name('{{{w}}}default')]
            if is_default is not None:
                st.is_default = is_default == '1'

        name = style.find(_name('{{{w}}}name'))
        if name is not None:
            st.name = name.attrib[_name('{{{w}}}val')]

        based_on = style.find(_name('{{{w}}}basedOn'))

        if based_on is not None:
            st.based_on = based_on.attrib[_name('{{{w}}}val')]

        document.styles.styles[st.style_id] = st

        if st.is_default:
            document.styles.default_styles[st.style_type] = st.style_id

        rpr = style.find(_name('{{{w}}}rPr'))

        if rpr is not None:
            parse_previous_properties(document, st, rpr)

        ppr = style.find(_name('{{{w}}}pPr'))

        if ppr is not None:
            parse_paragraph_properties(document, st, ppr)
1088003
def to_css
      css = ''
      css << resolved_modifier
      css << ' ' unless resolved_modifier.empty?
      css << resolved_type
      css << ' and ' unless resolved_type.empty? || expressions.empty?
      css << expressions.map do |e|
        # It's possible for there to be script nodes in Expressions even when
        # we're converting to CSS in the case where we parsed the document as
        # CSS originally (as in css_test.rb).
        e.map {|c| c.is_a?(Sass::Script::Tree::Node) ? c.to_sass : c.to_s}.join
      end.join(' and ')
      css
    end
849592
def _bake_css(link):
    
    if "href" in link.attrs and (re.search("\.css$", link["href"])) or ("rel" in link.attrs and link["rel"] is "stylesheet") or ("type" in link.attrs and link["type"] is "text/css"):
        if re.match("https?://", link["href"]):
            css_data = _load_url(link["href"]).read()
        else:
            css_data = _load_file(link["href"]).read()
        link.clear()
        if USING_PYTHON2:
            link.string = css_data
        else:
            link.string = str(css_data)
        link.name = "style"
        del link["rel"]
        del link["href"]
1031223
function match(re) {
    var m = re.exec(css);
    if (!m) return;
    var str = m[0];
    updatePosition(str);
    css = css.slice(str.length);
    return m;
  }
1172368
def dumb_css_parser(data):
    """"""
    # remove @import sentences
    data += ';'
    importIndex = data.find('@import')
    while importIndex != -1:
        data = data[0:importIndex] + data[data.find(';', importIndex) + 1:]
        importIndex = data.find('@import')

    # parse the css. reverted from dictionary compehension in order to support older pythons
    elements =  [x.split('{') for x in data.split('}') if '{' in x.strip()]
    try:
        elements = dict([(a.strip(), dumb_property_dict(b)) for a, b in elements])
    except ValueError:
        elements = {} # not that important

    return elements
1321850
def parse_css (url_data):
    
    lineno = 0
    linkfinder = linkparse.css_url_re.finditer
    strip_comments = linkparse.strip_c_comments
    for line in strip_comments(url_data.get_content()).splitlines():
        lineno += 1
        for mo in linkfinder(line):
            column = mo.start("url")
            url = strformat.unquote(mo.group("url").strip())
            url_data.add_url(url, line=lineno, column=column)
1373536
def _create_parser(self, html_parser, current_url):
        

        css_code = ''

        elements = html_parser.find(
            'style,link[rel="stylesheet"]'
        ).list_results()
        for element in elements:
            if element.get_tag_name() == 'STYLE':
                css_code = css_code + element.get_text_content()
            else:
                css_code = css_code + requests.get(
                    urljoin(current_url, element.get_attribute('href'))
                ).text

        self.stylesheet = tinycss.make_parser().parse_stylesheet(css_code)
963910
function(css) {
  css = css
    // remove comments
    .replace(/\/\*[^\0]*?\*\//g, '')
    // trim space before characters
    .replace(/\s+({|})/g, '$1')
    // trim space after characters
    .replace(/(;|,|:|{|}|^)\s+/g, '$1')
    // trim combinators
    .replace(/\s+(>|\+|~)\s+/g, '$1')
    // remove escaped newlines and spaces
    .replace(/\\\r?\n\s+/g, '')
    // remove trailing semicolons in rules
    .replace(/;(})/g, '$1');

  return css;
}
343789
function parseStyleText( styleText )
	{
		var retval = {};
		styleText
		   .replace( /&quot;/g, '"' )
		   .replace( /\s*([^ :;]+)\s*:\s*([^;]+)\s*(?=;|$)/g, function( match, name, value )
		{
			retval[ name ] = value;
		} );
		return retval;
	}