├── .gitignore ├── .travis.yml ├── ChangeLog.txt ├── DESCRIPTION ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── docs ├── Makefile ├── changes.rst ├── conf.py ├── index.rst └── make.bat ├── requirements.txt ├── scss ├── __init__.py ├── base.py ├── compat.py ├── control.py ├── function.py ├── grammar.py ├── parser.py ├── tests │ ├── __init__.py │ ├── bag2_64.png │ ├── box_64.png │ ├── bubble_64.png │ ├── bug_64.png │ ├── example.scss │ ├── test.png │ ├── test_color_functions.py │ ├── test_extend.py │ ├── test_fake.py │ ├── test_files.py │ ├── test_font_face.py │ ├── test_for.py │ ├── test_functions.py │ ├── test_if.py │ ├── test_mixin.py │ ├── test_nesting.py │ ├── test_options.py │ ├── test_scss.py │ └── test_variables.py ├── tool.py └── value.py ├── setup.cfg ├── setup.py └── todo.txt /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .ropeproject 3 | docs/_* 4 | *.pyc 5 | compass 6 | venv 7 | /build 8 | /dist 9 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: python 2 | 3 | python: 4 | - 2.7 5 | - 3.3 6 | 7 | script: python scss/tests/__init__.py 8 | 9 | 10 | # vim:sw=2 11 | -------------------------------------------------------------------------------- /ChangeLog.txt: -------------------------------------------------------------------------------- 1 | Changes 2 | ======= 3 | 4 | ## 2011-12-19 0.8.72 5 | -------------------- 6 | * Fix broken invert function (Ceesjan Luiten) 7 | 8 | ## 2011-11-21 0.8.71 9 | -------------------- 10 | * Some fix in warnings 11 | 12 | ## 2011-09-15 0.8.70 13 | -------------------- 14 | * Python 2.5 support 15 | 16 | ## 2011-09-15 0.8.60 17 | -------------------- 18 | * Fix scss load 19 | 20 | ## 2011-08-05 0.8.50 21 | -------------------- 22 | * Improve version 23 | 24 | ## 2011-07-25 0.8.3 25 | ------------------- 26 | * Fix multipart string values in functions 27 | * Fix watch mode 28 | * Drop last semicolon in rule only with compress=option enabled. 29 | 30 | ## 2011-07-24 0.8.22 31 | -------------------- 32 | * Fix -moz-linear-gradient 33 | * Thanks lgriesterer 34 | 35 | ## 2011-07-10 0.8.2 36 | ------------------- 37 | * Fix :not selectors 38 | 39 | ## 2011-06-24 0.8.1 40 | ------------------- 41 | * Fix color functions 42 | 43 | ## 2011-06-20 0.8.0 44 | ------------------- 45 | * Big scss refactoring begin 46 | 47 | ## 2011-06-19 0.7.2 48 | ------------------- 49 | * Add argv parse to tools.main 50 | * Fix watch mode 51 | 52 | ## 2011-02-27 0.7.0 53 | ------------------- 54 | * Add link on pyScss 55 | * Fix None type bug 56 | * Add if() function 57 | 58 | ## 2011-02-25 0.6.5 59 | ------------------- 60 | * Add option path 61 | * Add image functions: image-width, image-height, image-url, inline-image 62 | * Add @function and @return 63 | * Add --watch mode 64 | 65 | ## 2011-02-24 0.6.3 66 | ------------------- 67 | * Fix recursion bug in variable redefinition 68 | * Add unwnown properties 69 | * Add @option @warn:true 70 | * Fix selector interpolation bug 71 | * Fix bug in url( address ) 72 | 73 | ## 2011-02-21 0.6.0 74 | ------------------- 75 | * Add warnings ( not found mix and etc ) 76 | * Add @warn 77 | * Add 'add', 'or', 'not' operators in expressions 78 | * Add mode compass support 79 | 80 | ## 2011-02-20 0.5.9 81 | ------------------- 82 | * Add @options sort, @option comments, @option cache 83 | * Upgrade scss command tools ( more options, see scss --help ) 84 | 85 | ## 2011-02-19 0.5.7 86 | ------------------- 87 | * Fix unused import ipdb 88 | * Add color functions 89 | * Add compass helpers: append-selector, elements-of-type, headlings, nest 90 | * Add real expression parse in @if nodes 91 | * Add "@else if" 92 | * Upgrade interactive mode. history support and tab completion 93 | * Add color name parse ( red + blue = #f0f ) 94 | * Change sorting declarations in Zen order http://code.google.com/p/zen-coding/wiki/ZenCSSPropertiesEn 95 | * Fix url path bug, improve perfomance 96 | * Add @option, compress output 97 | 98 | ## 2011-02-19 0.5.0 99 | ------------------- 100 | * Real conversion between numbers ( 10px + 2em = 36px ) 101 | * Add full rgba, hsl, hsla support 102 | * Add red, green, blue, mix rgba functions 103 | * Add hue, saturation, lightness, adjust_hue, lighten, darken, saturate, desaturate, grayscale, complement hsl functions 104 | * Add alpha, opacity, rgba, opacify, fade-in, fade-out, transparentize 105 | * Add quote, unqoute string functions 106 | * Add percentage, round, floor, ceil, abs number functions 107 | * Add comparable, unitless, unit, type-of functions 108 | * Add interactive mode 109 | 110 | ## 2011-02-18 0.4.9 111 | ------------------- 112 | * Rename compile script from pscss to scss 113 | 114 | ## 2011-02-16 0.4.8 115 | ------------------- 116 | * Fix pseudo selector bug 117 | * Fix declareset interpolation var in name 118 | * Add initial documentation 119 | 120 | ## 2011-02-11 0.4.2 121 | ------------------- 122 | * True op parsing, prepare to compaire values 123 | 124 | ## 2011-02-10 0.3.9 125 | ------------------- 126 | * Real parse function params 127 | * Now you can use vars in url() 128 | 129 | ## 2011-02-09 0.3.6 130 | ------------------- 131 | * Add @font-face support 132 | 133 | ## 2011-01-28 0.3.5 134 | ------------------- 135 | * Fix nesting 136 | 137 | ## 2011-01-25 0.3.3 138 | ------------------- 139 | * Fix tests 140 | * Add rgb( ) support 141 | 142 | ## 2011-01-24 0.3.1 143 | ------------------- 144 | * Ignore recursion 145 | 146 | ## 2010-12-27 0.3.0 147 | ------------------- 148 | * Add precache scss files 149 | * Move tests in scss 150 | * Add pscss console command 151 | 152 | ## 2010-12-27 0.2.16 153 | -------------------- 154 | * Fix number minus bug 155 | 156 | ## 2010-12-26 0.2.15 157 | -------------------- 158 | * Fix var definition 159 | * Fix dotted value 160 | 161 | ## 2010-12-25 0.2.11 162 | -------------------- 163 | * Not ignore css comments by default 164 | * More stable version 165 | * Fix comments 166 | * Fix enumerate 167 | * Fix @for 168 | * Fix vars 169 | 170 | ## 2010-12-22 0.1.1 171 | ------------------- 172 | * Add !default support for variable assigment 173 | * Add true, false, int parse in @if condition 174 | * Fix division and / bug 175 | * Fix @extend rule 176 | * Fix selector filter bug 177 | * Add parens support in operation 178 | * Add @for directive 179 | 180 | ## 2010-12-20 0.0.5 181 | ------------------- 182 | * Add math operation 183 | * Add parent references 184 | * Add scss comments 185 | * Add @if @else 186 | 187 | ## 2010-12-20 0.0.2 188 | ------------------- 189 | * Push in pypi 190 | 191 | ## 2010-12-20 0.0.1 192 | ------------------- 193 | * First public version. 194 | -------------------------------------------------------------------------------- /DESCRIPTION: -------------------------------------------------------------------------------- 1 | Python-scss is SCSS compiler for Python. See http://sass-lang.com for more information about scss syntax. 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | 9 | This version of the GNU Lesser General Public License incorporates 10 | the terms and conditions of version 3 of the GNU General Public 11 | License, supplemented by the additional permissions listed below. 12 | 13 | 0. Additional Definitions. 14 | 15 | As used herein, "this License" refers to version 3 of the GNU Lesser 16 | General Public License, and the "GNU GPL" refers to version 3 of the GNU 17 | General Public License. 18 | 19 | "The Library" refers to a covered work governed by this License, 20 | other than an Application or a Combined Work as defined below. 21 | 22 | An "Application" is any work that makes use of an interface provided 23 | by the Library, but which is not otherwise based on the Library. 24 | Defining a subclass of a class defined by the Library is deemed a mode 25 | of using an interface provided by the Library. 26 | 27 | A "Combined Work" is a work produced by combining or linking an 28 | Application with the Library. The particular version of the Library 29 | with which the Combined Work was made is also called the "Linked 30 | Version". 31 | 32 | The "Minimal Corresponding Source" for a Combined Work means the 33 | Corresponding Source for the Combined Work, excluding any source code 34 | for portions of the Combined Work that, considered in isolation, are 35 | based on the Application, and not on the Linked Version. 36 | 37 | The "Corresponding Application Code" for a Combined Work means the 38 | object code and/or source code for the Application, including any data 39 | and utility programs needed for reproducing the Combined Work from the 40 | Application, but excluding the System Libraries of the Combined Work. 41 | 42 | 1. Exception to Section 3 of the GNU GPL. 43 | 44 | You may convey a covered work under sections 3 and 4 of this License 45 | without being bound by section 3 of the GNU GPL. 46 | 47 | 2. Conveying Modified Versions. 48 | 49 | If you modify a copy of the Library, and, in your modifications, a 50 | facility refers to a function or data to be supplied by an Application 51 | that uses the facility (other than as an argument passed when the 52 | facility is invoked), then you may convey a copy of the modified 53 | version: 54 | 55 | a) under this License, provided that you make a good faith effort to 56 | ensure that, in the event an Application does not supply the 57 | function or data, the facility still operates, and performs 58 | whatever part of its purpose remains meaningful, or 59 | 60 | b) under the GNU GPL, with none of the additional permissions of 61 | this License applicable to that copy. 62 | 63 | 3. Object Code Incorporating Material from Library Header Files. 64 | 65 | The object code form of an Application may incorporate material from 66 | a header file that is part of the Library. You may convey such object 67 | code under terms of your choice, provided that, if the incorporated 68 | material is not limited to numerical parameters, data structure 69 | layouts and accessors, or small macros, inline functions and templates 70 | (ten or fewer lines in length), you do both of the following: 71 | 72 | a) Give prominent notice with each copy of the object code that the 73 | Library is used in it and that the Library and its use are 74 | covered by this License. 75 | 76 | b) Accompany the object code with a copy of the GNU GPL and this license 77 | document. 78 | 79 | 4. Combined Works. 80 | 81 | You may convey a Combined Work under terms of your choice that, 82 | taken together, effectively do not restrict modification of the 83 | portions of the Library contained in the Combined Work and reverse 84 | engineering for debugging such modifications, if you also do each of 85 | the following: 86 | 87 | a) Give prominent notice with each copy of the Combined Work that 88 | the Library is used in it and that the Library and its use are 89 | covered by this License. 90 | 91 | b) Accompany the Combined Work with a copy of the GNU GPL and this license 92 | document. 93 | 94 | c) For a Combined Work that displays copyright notices during 95 | execution, include the copyright notice for the Library among 96 | these notices, as well as a reference directing the user to the 97 | copies of the GNU GPL and this license document. 98 | 99 | d) Do one of the following: 100 | 101 | 0) Convey the Minimal Corresponding Source under the terms of this 102 | License, and the Corresponding Application Code in a form 103 | suitable for, and under terms that permit, the user to 104 | recombine or relink the Application with a modified version of 105 | the Linked Version to produce a modified Combined Work, in the 106 | manner specified by section 6 of the GNU GPL for conveying 107 | Corresponding Source. 108 | 109 | 1) Use a suitable shared library mechanism for linking with the 110 | Library. A suitable mechanism is one that (a) uses at run time 111 | a copy of the Library already present on the user's computer 112 | system, and (b) will operate properly with a modified version 113 | of the Library that is interface-compatible with the Linked 114 | Version. 115 | 116 | e) Provide Installation Information, but only if you would otherwise 117 | be required to provide such information under section 6 of the 118 | GNU GPL, and only to the extent that such information is 119 | necessary to install and execute a modified version of the 120 | Combined Work produced by recombining or relinking the 121 | Application with a modified version of the Linked Version. (If 122 | you use option 4d0, the Installation Information must accompany 123 | the Minimal Corresponding Source and Corresponding Application 124 | Code. If you use option 4d1, you must provide the Installation 125 | Information in the manner specified by section 6 of the GNU GPL 126 | for conveying Corresponding Source.) 127 | 128 | 5. Combined Libraries. 129 | 130 | You may place library facilities that are a work based on the 131 | Library side by side in a single library together with other library 132 | facilities that are not Applications and are not covered by this 133 | License, and convey such a combined library under terms of your 134 | choice, if you do both of the following: 135 | 136 | a) Accompany the combined library with a copy of the same work based 137 | on the Library, uncombined with any other library facilities, 138 | conveyed under the terms of this License. 139 | 140 | b) Give prominent notice with the combined library that part of it 141 | is a work based on the Library, and explaining where to find the 142 | accompanying uncombined form of the same work. 143 | 144 | 6. Revised Versions of the GNU Lesser General Public License. 145 | 146 | The Free Software Foundation may publish revised and/or new versions 147 | of the GNU Lesser General Public License from time to time. Such new 148 | versions will be similar in spirit to the present version, but may 149 | differ in detail to address new problems or concerns. 150 | 151 | Each version is given a distinguishing version number. If the 152 | Library as you received it specifies that a certain numbered version 153 | of the GNU Lesser General Public License "or any later version" 154 | applies to it, you have the option of following the terms and 155 | conditions either of that published version or of any later version 156 | published by the Free Software Foundation. If the Library as you 157 | received it does not specify a version number of the GNU Lesser 158 | General Public License, you may choose any version of the GNU Lesser 159 | General Public License ever published by the Free Software Foundation. 160 | 161 | If the Library as you received it specifies that a proxy can decide 162 | whether future versions of the GNU Lesser General Public License shall 163 | apply, that proxy's public statement of acceptance of any version is 164 | permanent authorization for you to choose that version for the 165 | Library. 166 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include MANIFEST.in 3 | include README.rst 4 | include requirements.txt 5 | 6 | recursive-include scss * 7 | 8 | recursive-exclude * __pycache__ 9 | recursive-exclude * *.py[co] 10 | recursive-exclude * *.orig 11 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | MODULE=scss 2 | 3 | clean: 4 | sudo rm -rf build dist $(MODULE).egg-info/ 5 | find . -name "*.pyc" -delete 6 | 7 | install: remove _install clean 8 | 9 | register: _register clean 10 | 11 | upload: _upload install _commit doc 12 | 13 | _upload: 14 | python setup.py sdist upload || echo 'Skipped' 15 | python setup.py bdist_wheel upload || echo 'Skipped' 16 | 17 | _commit: 18 | git add . 19 | git add . -u 20 | git commit 21 | git push origin 22 | 23 | _register: 24 | python setup.py register 25 | 26 | remove: 27 | sudo pip uninstall $(MODULE) 28 | 29 | _install: 30 | sudo pip install -U . 31 | 32 | test: 33 | python $(MODULE)/tests/__init__.py 34 | 35 | doc: 36 | python setup.py build_sphinx --source-dir=docs/ --build-dir=docs/_build --all-files 37 | python setup.py upload_sphinx --upload-dir=docs/_build/html 38 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | Python-scss 2 | =========== 3 | 4 | Warning: 5 | 6 | Im not support python-scss anymore. Use pyscss_ by Kronus. 7 | 8 | 9 | Python-scss is SCSS_ compiler for python. Documentation available at pypi_ or github_. 10 | This is part of zeta-library_. 11 | 12 | .. contents:: 13 | 14 | 15 | Features 16 | ======== 17 | Python-scss has most of the funcitonality in Sass SCSS_ 3.2 and more. It supports: 18 | 19 | * **Nested rules** 20 | * **Keyword arguments** 21 | * **Mixins**: ``@mixin``, ``@include`` 22 | * **Functions**: ``@function``, ``@return`` 23 | * **Inheritance**: ``@extend`` 24 | * **Conditions**: ``@if``, ``@else``, ``@if else`` 25 | * **Loops**: ``@for`` 26 | * **Variables**: ``$``, ``@variables``, ``@vars`` 27 | * **Images**: ``image-url``, ``image-width``, ``image-height``, .. 28 | * **Embedded inline images**: ``inline-image`` 29 | * **Colors handling**: ``adjust-color()``, ``scale-color()``, ``opacify()``/``transparentize()``, ``lighten()``/``darken()``, ``mix()``, ... 30 | * **Math functions**: ``sin()``, ``cos()``, ``tan()``, ``round()``, ``ceil()``, ``floor()``, ``pi()``, ... 31 | * **Options**: ``@option compress:true, sort:false;``, ``@option comments:false;`` 32 | * **Compass_ helpers**: ``enumerate``, ``type-of``, ... 33 | * **Sorting declarations**: in `Zen sorting order`_ 34 | 35 | .. note:: 36 | For ``@import`` support you can use zeta-library_, python compass alternative. 37 | 38 | Zeta-library supported ``@import url(path or http)``, but all static files css, scss. 39 | 40 | Also zeta support js import ``require( '../jquery.js' );``. Zeta allow you control all your static files. 41 | 42 | 43 | Requirements 44 | ============= 45 | - python >= 2.5 46 | - pyparsing >= 1.5.5 47 | 48 | 49 | Installation 50 | ============ 51 | **python-scss** should be installed using pip or setuptools: :: 52 | 53 | pip install scss 54 | 55 | easy_install scss 56 | 57 | 58 | Usage 59 | ===== 60 | 61 | #. **From python source code**: :: 62 | 63 | from scss import parser 64 | 65 | file_path = path_to_file 66 | src = open( file_path ).read() 67 | 68 | # from file 69 | print parser.load( 'file_path' ) 70 | 71 | # from string 72 | print parser.parse( 'src' ) 73 | 74 | # Create parser object 75 | p = parser.Stylesheet( options=dict( compress=True ) ) 76 | print p.loads( src ) 77 | p.load( file_path ) 78 | print p 79 | 80 | #. **From command line**: :: 81 | 82 | $ scss --help 83 | Usage: scss [OPTION]... [INFILE] [OUTFILE] 84 | 85 | Compile INFILE or standard input, to OUTFILE or standard output. 86 | 87 | Options: 88 | --version show program's version number and exit 89 | -h, --help show this help message and exit 90 | -c, --cache Create and use cache file. Only for files. 91 | -i, --interactive Run in interactive shell mode. 92 | -m, --compress Compress css output. 93 | -w WATCH, --watch=WATCH 94 | Watch files or directories for changes. The location 95 | of the generated CSS can be set using a colon: 96 | scss -w input.scss:output.css 97 | -S, --no-sorted Do not sort declaration. 98 | -C, --no-comments Clear css comments. 99 | -W, --no-warnings Disable warnings. 100 | 101 | #. **In interactive mode**: :: 102 | 103 | scss -i 104 | 105 | >>> 25px + 1.5em 106 | 107 | 108 | Changes 109 | ======= 110 | 111 | Make sure you`ve read the following document if you are upgrading from previous versions of scss: 112 | 113 | http://packages.python.org/scss/changes.html 114 | 115 | 116 | Examples 117 | ======== 118 | 119 | #. **Nested Rules** 120 | Example:: 121 | 122 | .selector { 123 | a { 124 | display: block; 125 | } 126 | strong { 127 | color: blue; 128 | } 129 | } 130 | 131 | ...produces:: 132 | 133 | .selector a { 134 | display: block} 135 | 136 | .selector strong { 137 | color: blue} 138 | 139 | 140 | #. **Variables** 141 | Example:: 142 | 143 | $main-color: #ce4dd6; 144 | $style: solid; 145 | $side: bottom; 146 | #navbar { 147 | border-#{$side}: { 148 | color: $main-color; 149 | style: $style; 150 | } 151 | } 152 | 153 | ...produces:: 154 | 155 | #navbar { 156 | border-bottom-color: #ce4dd6; 157 | border-bottom-style: solid} 158 | 159 | #. **Mixins** 160 | Example:: 161 | 162 | @mixin rounded($side, $radius: 10px) { 163 | border-#{$side}-radius: $radius; 164 | -moz-border-radius-#{$side}: $radius; 165 | -webkit-border-#{$side}-radius: $radius; 166 | } 167 | #navbar li { @include rounded(top); } 168 | #footer { @include rounded(top, 5px); } 169 | #sidebar { @include rounded(left, 8px); } 170 | 171 | ...produces:: 172 | 173 | #navbar li { 174 | -moz-border-radius-top: 10px; 175 | -webkit-border-top-radius: 10px; 176 | border-top-radius: 10px} 177 | 178 | #footer { 179 | -moz-border-radius-top: 5px; 180 | -webkit-border-top-radius: 5px; 181 | border-top-radius: 5px} 182 | 183 | #sidebar { 184 | -moz-border-radius-left: 8px; 185 | -webkit-border-left-radius: 8px; 186 | border-left-radius: 8px} 187 | 188 | #. **Extend** (using `@extend`) 189 | Example:: 190 | 191 | .error { 192 | border: 1px #f00; 193 | background-color: #fdd; 194 | } 195 | .error.intrusion { 196 | background-image: url("/image/hacked.png"); 197 | } 198 | .seriousError { 199 | @extend .error; 200 | border-width: 3px; 201 | } 202 | 203 | ...produces:: 204 | 205 | .error, .seriousError { 206 | background-color: #fdd; 207 | border: 1px #f00} 208 | 209 | .error .intrusion, .seriousError .intrusion { 210 | background-image: url('/image/hacked.png')} 211 | 212 | .seriousError { 213 | border-width: 3px} 214 | 215 | #. **Interactive mode** 216 | Example:: 217 | 218 | $ python scss.py --interactive 219 | >>> 25px + 1.5em 220 | 44.5px 221 | >>> lighten(rgba(130,130,130,.4),10%) 222 | rgba(155,155,155,0.40) 223 | >>> .rule { test: red; } 224 | .rule { 225 | test: red } 226 | >>> _ 227 | 228 | 229 | Options 230 | ======= 231 | 232 | Python-scss has the following options: 233 | 234 | - **compress**: Compress output css, default is False 235 | 236 | - **cache**: Precache compile result, default is False 237 | 238 | - **comments**: Leave css comments, default is True 239 | 240 | - **sort**: Sort declaration, default is True 241 | Declaration sorted in `Zen sorting order`_ 242 | 243 | - **warn**: Enable or disable warnings: unknown mixin, declaration name, extend ruleset, default is True 244 | 245 | Option can be defined... 246 | 247 | #. from command line: :: 248 | 249 | scss -m -S file.scss 250 | 251 | #. from python: :: 252 | 253 | parser = Stylesheet( options=dict( compress=True ) ) 254 | 255 | #. from scss source: :: 256 | 257 | @option compress: true, sort: false; 258 | 259 | 260 | .. note:: 261 | python-scss is still at early stages of development 262 | 263 | 264 | Bug tracker 265 | =========== 266 | 267 | If you have any suggestions, bug reports or 268 | annoyances please report them to the issue tracker 269 | at https://github.com/klen/python-scss/issues 270 | 271 | 272 | Contributing 273 | ============ 274 | 275 | Development of python-scss happens at github: https://github.com/klen/python-scss 276 | 277 | * klen_ (Kirill Klenov) 278 | 279 | 280 | License 281 | ======= 282 | 283 | Licensed under a `GNU lesser general public license`_. 284 | 285 | 286 | Copyright 287 | ========= 288 | 289 | Copyright (c) 2011 Kirill Klenov (horneds@gmail.com) 290 | 291 | Compass_: 292 | (c) 2009 Christopher M. Eppstein 293 | http://compass-style.org/ 294 | 295 | SCSS_: 296 | (c) 2006-2009 Hampton Catlin and Nathan Weizenbaum 297 | http://sass-lang.com/ 298 | 299 | 300 | Note 301 | ==== 302 | 303 | **Your feedback are welcome!** 304 | 305 | .. _zeta-library: http://github.com/klen/zeta-library 306 | .. _GNU lesser general public license: http://www.gnu.org/copyleft/lesser.html 307 | .. _SCSS: http://sass-lang.com 308 | .. _compass: http://compass-style.org/ 309 | .. _python scss git: http://packages.python.org/scss/ 310 | .. _pypi: http://packages.python.org/scss/ 311 | .. _github: https://github.com/klen/python-scss 312 | .. _Zen sorting order: http://code.google.com/p/zen-coding/wiki/ZenCSSPropertiesEn#Sorting_Methods 313 | .. _klen: https://klen.github.com 314 | .. _pyscss: https://github.com/Kronuz/pyScss 315 | 316 | -------------------------------------------------------------------------------- /docs/Makefile: -------------------------------------------------------------------------------- 1 | # Makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line. 5 | SPHINXOPTS = 6 | SPHINXBUILD = sphinx-build 7 | PAPER = 8 | BUILDDIR = _build 9 | 10 | # Internal variables. 11 | PAPEROPT_a4 = -D latex_paper_size=a4 12 | PAPEROPT_letter = -D latex_paper_size=letter 13 | ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . 14 | 15 | .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest 16 | 17 | help: 18 | @echo "Please use \`make ' where is one of" 19 | @echo " html to make standalone HTML files" 20 | @echo " dirhtml to make HTML files named index.html in directories" 21 | @echo " singlehtml to make a single large HTML file" 22 | @echo " pickle to make pickle files" 23 | @echo " json to make JSON files" 24 | @echo " htmlhelp to make HTML files and a HTML help project" 25 | @echo " qthelp to make HTML files and a qthelp project" 26 | @echo " devhelp to make HTML files and a Devhelp project" 27 | @echo " epub to make an epub" 28 | @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" 29 | @echo " latexpdf to make LaTeX files and run them through pdflatex" 30 | @echo " text to make text files" 31 | @echo " man to make manual pages" 32 | @echo " changes to make an overview of all changed/added/deprecated items" 33 | @echo " linkcheck to check all external links for integrity" 34 | @echo " doctest to run all doctests embedded in the documentation (if enabled)" 35 | 36 | clean: 37 | -rm -rf $(BUILDDIR)/* 38 | 39 | html: 40 | $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html 41 | @echo 42 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." 43 | 44 | dirhtml: 45 | $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml 46 | @echo 47 | @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." 48 | 49 | singlehtml: 50 | $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml 51 | @echo 52 | @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." 53 | 54 | pickle: 55 | $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle 56 | @echo 57 | @echo "Build finished; now you can process the pickle files." 58 | 59 | json: 60 | $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json 61 | @echo 62 | @echo "Build finished; now you can process the JSON files." 63 | 64 | htmlhelp: 65 | $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp 66 | @echo 67 | @echo "Build finished; now you can run HTML Help Workshop with the" \ 68 | ".hhp project file in $(BUILDDIR)/htmlhelp." 69 | 70 | qthelp: 71 | $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp 72 | @echo 73 | @echo "Build finished; now you can run "qcollectiongenerator" with the" \ 74 | ".qhcp project file in $(BUILDDIR)/qthelp, like this:" 75 | @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-scss.qhcp" 76 | @echo "To view the help file:" 77 | @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-scss.qhc" 78 | 79 | devhelp: 80 | $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp 81 | @echo 82 | @echo "Build finished." 83 | @echo "To view the help file:" 84 | @echo "# mkdir -p $$HOME/.local/share/devhelp/python-scss" 85 | @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-scss" 86 | @echo "# devhelp" 87 | 88 | epub: 89 | $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub 90 | @echo 91 | @echo "Build finished. The epub file is in $(BUILDDIR)/epub." 92 | 93 | latex: 94 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 95 | @echo 96 | @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." 97 | @echo "Run \`make' in that directory to run these through (pdf)latex" \ 98 | "(use \`make latexpdf' here to do that automatically)." 99 | 100 | latexpdf: 101 | $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex 102 | @echo "Running LaTeX files through pdflatex..." 103 | make -C $(BUILDDIR)/latex all-pdf 104 | @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." 105 | 106 | text: 107 | $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text 108 | @echo 109 | @echo "Build finished. The text files are in $(BUILDDIR)/text." 110 | 111 | man: 112 | $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man 113 | @echo 114 | @echo "Build finished. The manual pages are in $(BUILDDIR)/man." 115 | 116 | changes: 117 | $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes 118 | @echo 119 | @echo "The overview file is in $(BUILDDIR)/changes." 120 | 121 | linkcheck: 122 | $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck 123 | @echo 124 | @echo "Link check complete; look for any errors in the above output " \ 125 | "or in $(BUILDDIR)/linkcheck/output.txt." 126 | 127 | doctest: 128 | $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest 129 | @echo "Testing of doctests in the sources finished, look at the " \ 130 | "results in $(BUILDDIR)/doctest/output.txt." 131 | -------------------------------------------------------------------------------- /docs/changes.rst: -------------------------------------------------------------------------------- 1 | ../ChangeLog.txt -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # python-scss documentation build configuration file, created by 4 | # sphinx-quickstart on Wed Feb 16 19:24:45 2011. 5 | # 6 | # This file is execfile()d with the current directory set to its containing dir. 7 | # 8 | # Note that not all possible configuration values are present in this 9 | # autogenerated file. 10 | # 11 | # All configuration values have a default; values that are commented out 12 | # serve to show the default. 13 | 14 | import sys, os 15 | 16 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 17 | 18 | from scss import VERSION, AUTHOR 19 | 20 | # If extensions (or modules to document with autodoc) are in another directory, 21 | # add these directories to sys.path here. If the directory is relative to the 22 | # documentation root, use os.path.abspath to make it absolute, like shown here. 23 | #sys.path.insert(0, os.path.abspath('.')) 24 | 25 | # -- General configuration ----------------------------------------------------- 26 | 27 | # If your documentation needs a minimal Sphinx version, state it here. 28 | #needs_sphinx = '1.0' 29 | 30 | # Add any Sphinx extension module names here, as strings. They can be extensions 31 | # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. 32 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode'] 33 | 34 | # Add any paths that contain templates here, relative to this directory. 35 | templates_path = ['_templates'] 36 | 37 | # The suffix of source filenames. 38 | source_suffix = '.rst' 39 | 40 | # The encoding of source files. 41 | #source_encoding = 'utf-8-sig' 42 | 43 | # The master toctree document. 44 | master_doc = 'index' 45 | 46 | # General information about the project. 47 | project = u'python-scss' 48 | copyright = AUTHOR 49 | 50 | # The version info for the project you're documenting, acts as replacement for 51 | # |version| and |release|, also used in various other places throughout the 52 | # built documents. 53 | # 54 | # The short X.Y version. 55 | version = VERSION 56 | # The full version, including alpha/beta/rc tags. 57 | release = VERSION 58 | 59 | # The language for content autogenerated by Sphinx. Refer to documentation 60 | # for a list of supported languages. 61 | #language = None 62 | 63 | # There are two options for replacing |today|: either, you set today to some 64 | # non-false value, then it is used: 65 | #today = '' 66 | # Else, today_fmt is used as the format for a strftime call. 67 | #today_fmt = '%B %d, %Y' 68 | 69 | # List of patterns, relative to source directory, that match files and 70 | # directories to ignore when looking for source files. 71 | exclude_patterns = ['_build'] 72 | 73 | # The reST default role (used for this markup: `text`) to use for all documents. 74 | #default_role = None 75 | 76 | # If true, '()' will be appended to :func: etc. cross-reference text. 77 | #add_function_parentheses = True 78 | 79 | # If true, the current module name will be prepended to all description 80 | # unit titles (such as .. function::). 81 | #add_module_names = True 82 | 83 | # If true, sectionauthor and moduleauthor directives will be shown in the 84 | # output. They are ignored by default. 85 | #show_authors = False 86 | 87 | # The name of the Pygments (syntax highlighting) style to use. 88 | pygments_style = 'sphinx' 89 | 90 | # A list of ignored prefixes for module index sorting. 91 | #modindex_common_prefix = [] 92 | 93 | 94 | # -- Options for HTML output --------------------------------------------------- 95 | 96 | # The theme to use for HTML and HTML Help pages. See the documentation for 97 | # a list of builtin themes. 98 | html_theme = 'sphinxdoc' 99 | 100 | # Theme options are theme-specific and customize the look and feel of a theme 101 | # further. For a list of options available for each theme, see the 102 | # documentation. 103 | #html_theme_options = {} 104 | 105 | # Add any paths that contain custom themes here, relative to this directory. 106 | #html_theme_path = [] 107 | 108 | # The name for this set of Sphinx documents. If None, it defaults to 109 | # " v documentation". 110 | #html_title = None 111 | 112 | # A shorter title for the navigation bar. Default is the same as html_title. 113 | #html_short_title = None 114 | 115 | # The name of an image file (relative to this directory) to place at the top 116 | # of the sidebar. 117 | #html_logo = None 118 | 119 | # The name of an image file (within the static path) to use as favicon of the 120 | # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 121 | # pixels large. 122 | #html_favicon = None 123 | 124 | # Add any paths that contain custom static files (such as style sheets) here, 125 | # relative to this directory. They are copied after the builtin static files, 126 | # so a file named "default.css" will overwrite the builtin "default.css". 127 | html_static_path = ['_static'] 128 | 129 | # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, 130 | # using the given strftime format. 131 | #html_last_updated_fmt = '%b %d, %Y' 132 | 133 | # If true, SmartyPants will be used to convert quotes and dashes to 134 | # typographically correct entities. 135 | #html_use_smartypants = True 136 | 137 | # Custom sidebar templates, maps document names to template names. 138 | #html_sidebars = {} 139 | 140 | # Additional templates that should be rendered to pages, maps page names to 141 | # template names. 142 | #html_additional_pages = {} 143 | 144 | # If false, no module index is generated. 145 | #html_domain_indices = True 146 | 147 | # If false, no index is generated. 148 | #html_use_index = True 149 | 150 | # If true, the index is split into individual pages for each letter. 151 | #html_split_index = False 152 | 153 | # If true, links to the reST sources are added to the pages. 154 | #html_show_sourcelink = True 155 | 156 | # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. 157 | #html_show_sphinx = True 158 | 159 | # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. 160 | #html_show_copyright = True 161 | 162 | # If true, an OpenSearch description file will be output, and all pages will 163 | # contain a tag referring to it. The value of this option must be the 164 | # base URL from which the finished HTML is served. 165 | #html_use_opensearch = '' 166 | 167 | # This is the file name suffix for HTML files (e.g. ".xhtml"). 168 | #html_file_suffix = None 169 | 170 | # Output file base name for HTML help builder. 171 | htmlhelp_basename = 'python-scssdoc' 172 | 173 | 174 | # -- Options for LaTeX output -------------------------------------------------- 175 | 176 | # The paper size ('letter' or 'a4'). 177 | #latex_paper_size = 'letter' 178 | 179 | # The font size ('10pt', '11pt' or '12pt'). 180 | #latex_font_size = '10pt' 181 | 182 | # Grouping the document tree into LaTeX files. List of tuples 183 | # (source start file, target name, title, author, documentclass [howto/manual]). 184 | latex_documents = [ 185 | ('index', 'python-scss.tex', u'python-scss Documentation', 186 | u'Kirill Klenov', 'manual'), 187 | ] 188 | 189 | # The name of an image file (relative to this directory) to place at the top of 190 | # the title page. 191 | #latex_logo = None 192 | 193 | # For "manual" documents, if this is true, then toplevel headings are parts, 194 | # not chapters. 195 | #latex_use_parts = False 196 | 197 | # If true, show page references after internal links. 198 | #latex_show_pagerefs = False 199 | 200 | # If true, show URL addresses after external links. 201 | #latex_show_urls = False 202 | 203 | # Additional stuff for the LaTeX preamble. 204 | #latex_preamble = '' 205 | 206 | # Documents to append as an appendix to all manuals. 207 | #latex_appendices = [] 208 | 209 | # If false, no module index is generated. 210 | #latex_domain_indices = True 211 | 212 | 213 | # -- Options for manual page output -------------------------------------------- 214 | 215 | # One entry per manual page. List of tuples 216 | # (source start file, name, description, authors, manual section). 217 | man_pages = [ 218 | ('index', 'python-scss', u'python-scss Documentation', 219 | [u'Kirill Klenov'], 1) 220 | ] 221 | -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | ../README.rst -------------------------------------------------------------------------------- /docs/make.bat: -------------------------------------------------------------------------------- 1 | @ECHO OFF 2 | 3 | REM Command file for Sphinx documentation 4 | 5 | if "%SPHINXBUILD%" == "" ( 6 | set SPHINXBUILD=sphinx-build 7 | ) 8 | set BUILDDIR=_build 9 | set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . 10 | if NOT "%PAPER%" == "" ( 11 | set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% 12 | ) 13 | 14 | if "%1" == "" goto help 15 | 16 | if "%1" == "help" ( 17 | :help 18 | echo.Please use `make ^` where ^ is one of 19 | echo. html to make standalone HTML files 20 | echo. dirhtml to make HTML files named index.html in directories 21 | echo. singlehtml to make a single large HTML file 22 | echo. pickle to make pickle files 23 | echo. json to make JSON files 24 | echo. htmlhelp to make HTML files and a HTML help project 25 | echo. qthelp to make HTML files and a qthelp project 26 | echo. devhelp to make HTML files and a Devhelp project 27 | echo. epub to make an epub 28 | echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter 29 | echo. text to make text files 30 | echo. man to make manual pages 31 | echo. changes to make an overview over all changed/added/deprecated items 32 | echo. linkcheck to check all external links for integrity 33 | echo. doctest to run all doctests embedded in the documentation if enabled 34 | goto end 35 | ) 36 | 37 | if "%1" == "clean" ( 38 | for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i 39 | del /q /s %BUILDDIR%\* 40 | goto end 41 | ) 42 | 43 | if "%1" == "html" ( 44 | %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html 45 | if errorlevel 1 exit /b 1 46 | echo. 47 | echo.Build finished. The HTML pages are in %BUILDDIR%/html. 48 | goto end 49 | ) 50 | 51 | if "%1" == "dirhtml" ( 52 | %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml 53 | if errorlevel 1 exit /b 1 54 | echo. 55 | echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. 56 | goto end 57 | ) 58 | 59 | if "%1" == "singlehtml" ( 60 | %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml 61 | if errorlevel 1 exit /b 1 62 | echo. 63 | echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. 64 | goto end 65 | ) 66 | 67 | if "%1" == "pickle" ( 68 | %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle 69 | if errorlevel 1 exit /b 1 70 | echo. 71 | echo.Build finished; now you can process the pickle files. 72 | goto end 73 | ) 74 | 75 | if "%1" == "json" ( 76 | %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json 77 | if errorlevel 1 exit /b 1 78 | echo. 79 | echo.Build finished; now you can process the JSON files. 80 | goto end 81 | ) 82 | 83 | if "%1" == "htmlhelp" ( 84 | %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp 85 | if errorlevel 1 exit /b 1 86 | echo. 87 | echo.Build finished; now you can run HTML Help Workshop with the ^ 88 | .hhp project file in %BUILDDIR%/htmlhelp. 89 | goto end 90 | ) 91 | 92 | if "%1" == "qthelp" ( 93 | %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp 94 | if errorlevel 1 exit /b 1 95 | echo. 96 | echo.Build finished; now you can run "qcollectiongenerator" with the ^ 97 | .qhcp project file in %BUILDDIR%/qthelp, like this: 98 | echo.^> qcollectiongenerator %BUILDDIR%\qthelp\python-scss.qhcp 99 | echo.To view the help file: 100 | echo.^> assistant -collectionFile %BUILDDIR%\qthelp\python-scss.ghc 101 | goto end 102 | ) 103 | 104 | if "%1" == "devhelp" ( 105 | %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp 106 | if errorlevel 1 exit /b 1 107 | echo. 108 | echo.Build finished. 109 | goto end 110 | ) 111 | 112 | if "%1" == "epub" ( 113 | %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub 114 | if errorlevel 1 exit /b 1 115 | echo. 116 | echo.Build finished. The epub file is in %BUILDDIR%/epub. 117 | goto end 118 | ) 119 | 120 | if "%1" == "latex" ( 121 | %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex 122 | if errorlevel 1 exit /b 1 123 | echo. 124 | echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. 125 | goto end 126 | ) 127 | 128 | if "%1" == "text" ( 129 | %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text 130 | if errorlevel 1 exit /b 1 131 | echo. 132 | echo.Build finished. The text files are in %BUILDDIR%/text. 133 | goto end 134 | ) 135 | 136 | if "%1" == "man" ( 137 | %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man 138 | if errorlevel 1 exit /b 1 139 | echo. 140 | echo.Build finished. The manual pages are in %BUILDDIR%/man. 141 | goto end 142 | ) 143 | 144 | if "%1" == "changes" ( 145 | %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes 146 | if errorlevel 1 exit /b 1 147 | echo. 148 | echo.The overview file is in %BUILDDIR%/changes. 149 | goto end 150 | ) 151 | 152 | if "%1" == "linkcheck" ( 153 | %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck 154 | if errorlevel 1 exit /b 1 155 | echo. 156 | echo.Link check complete; look for any errors in the above output ^ 157 | or in %BUILDDIR%/linkcheck/output.txt. 158 | goto end 159 | ) 160 | 161 | if "%1" == "doctest" ( 162 | %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest 163 | if errorlevel 1 exit /b 1 164 | echo. 165 | echo.Testing of doctests in the sources finished, look at the ^ 166 | results in %BUILDDIR%/doctest/output.txt. 167 | goto end 168 | ) 169 | 170 | :end 171 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | pyparsing 2 | -------------------------------------------------------------------------------- /scss/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ Python SCSS parser. """ 4 | 5 | import operator 6 | 7 | from . import compat 8 | 9 | 10 | VERSION_INFO = (0, 8, 73) 11 | 12 | __project__ = "scss" 13 | __version__ = "0.8.73" 14 | __author__ = "Kirill Klenov " 15 | __license__ = "GNU LGPL" 16 | 17 | 18 | CONV = { 19 | 'size': { 20 | 'em': 13.0, 21 | 'px': 1.0}, 22 | 'length': { 23 | 'mm': 1.0, 24 | 'cm': 10.0, 25 | 'in': 25.4, 26 | 'pt': 25.4 / 72, 27 | 'pc': 25.4 / 6}, 28 | 'time': { 29 | 'ms': 1.0, 30 | 's': 1000.0}, 31 | 'freq': { 32 | 'hz': 1.0, 33 | 'khz': 1000.0}, 34 | 'any': { 35 | '%': 1.0 / 100, 36 | 'deg': 1.0 / 360, 37 | 's': 1.0 / 60}} 38 | CONV_TYPE = {} 39 | CONV_FACTOR = {} 40 | for t, m in CONV.items(): 41 | for k, f in m.items(): 42 | CONV_TYPE[k] = t 43 | CONV_FACTOR[k] = f 44 | 45 | OPRT = { 46 | '^': operator.__pow__, 47 | '+': operator.__add__, 48 | '-': operator.__sub__, 49 | '*': operator.__mul__, 50 | '/': compat.div, 51 | '!': operator.__neg__, 52 | '<': operator.__lt__, 53 | '<=': operator.__le__, 54 | '>': operator.__gt__, 55 | '>=': operator.__ge__, 56 | '==': operator.__eq__, 57 | '=': operator.__eq__, 58 | '!=': operator.__ne__, 59 | '&': operator.__and__, 60 | '|': operator.__or__, 61 | 'and': lambda x, y: x and y, 62 | 'or': lambda x, y: x or y, 63 | } 64 | 65 | ELEMENTS_OF_TYPE = { 66 | 'block': ( 67 | "address, article, aside, blockquote, center, dd, dialog, dir, div, dl, dt, fieldset, " 68 | "figure, footer, form, frameset, h1, h2, h3, h4, h5, h6, header, hgroup, hr, isindex, " 69 | "menu, nav, noframes, noscript, ol, p, pre, section, ul"), 70 | 'inline': ( 71 | "a, abbr, acronym, b, basefont, bdo, big, br, cite, code, dfn, em, font, i, img, input, " 72 | "kbd, label, q, s, samp, select, small, span, strike, strong, sub, sup, textarea, tt, u, " 73 | "var"), 74 | 'table': 'table', 'list-item': 'li', 'table-row-group': 'tbody', 75 | 'table-header-group': 'thead', 'table-footer-group': 'tfoot', 'table-row': 76 | 'tr', 'table-cell': 'td, th', } 77 | 78 | COLORS = { 79 | 'aliceblue': '#f0f8ff', 80 | 'antiquewhite': '#faebd7', 81 | 'aqua': '#00ffff', 82 | 'aquamarine': '#7fffd4', 83 | 'azure': '#f0ffff', 84 | 'beige': '#f5f5dc', 85 | 'bisque': '#ffe4c4', 86 | 'black': '#000000', 87 | 'blanchedalmond': '#ffebcd', 88 | 'blue': '#0000ff', 89 | 'blueviolet': '#8a2be2', 90 | 'brown': '#a52a2a', 91 | 'burlywood': '#deb887', 92 | 'cadetblue': '#5f9ea0', 93 | 'chartreuse': '#7fff00', 94 | 'chocolate': '#d2691e', 95 | 'coral': '#ff7f50', 96 | 'cornflowerblue': '#6495ed', 97 | 'cornsilk': '#fff8dc', 98 | 'crimson': '#dc143c', 99 | 'cyan': '#00ffff', 100 | 'darkblue': '#00008b', 101 | 'darkcyan': '#008b8b', 102 | 'darkgoldenrod': '#b8860b', 103 | 'darkgray': '#a9a9a9', 104 | 'darkgreen': '#006400', 105 | 'darkkhaki': '#bdb76b', 106 | 'darkmagenta': '#8b008b', 107 | 'darkolivegreen': '#556b2f', 108 | 'darkorange': '#ff8c00', 109 | 'darkorchid': '#9932cc', 110 | 'darkred': '#8b0000', 111 | 'darksalmon': '#e9967a', 112 | 'darkseagreen': '#8fbc8f', 113 | 'darkslateblue': '#483d8b', 114 | 'darkslategray': '#2f4f4f', 115 | 'darkturquoise': '#00ced1', 116 | 'darkviolet': '#9400d3', 117 | 'deeppink': '#ff1493', 118 | 'deepskyblue': '#00bfff', 119 | 'dimgray': '#696969', 120 | 'dodgerblue': '#1e90ff', 121 | 'firebrick': '#b22222', 122 | 'floralwhite': '#fffaf0', 123 | 'forestgreen': '#228b22', 124 | 'fuchsia': '#ff00ff', 125 | 'gainsboro': '#dcdcdc', 126 | 'ghostwhite': '#f8f8ff', 127 | 'gold': '#ffd700', 128 | 'goldenrod': '#daa520', 129 | 'gray': '#808080', 130 | 'green': '#008000', 131 | 'greenyellow': '#adff2f', 132 | 'honeydew': '#f0fff0', 133 | 'hotpink': '#ff69b4', 134 | 'indianred': '#cd5c5c', 135 | 'indigo': '#4b0082', 136 | 'ivory': '#fffff0', 137 | 'khaki': '#f0e68c', 138 | 'lavender': '#e6e6fa', 139 | 'lavenderblush': '#fff0f5', 140 | 'lawngreen': '#7cfc00', 141 | 'lemonchiffon': '#fffacd', 142 | 'lightblue': '#add8e6', 143 | 'lightcoral': '#f08080', 144 | 'lightcyan': '#e0ffff', 145 | 'lightgoldenrodyellow': '#fafad2', 146 | 'lightgreen': '#90ee90', 147 | 'lightgrey': '#d3d3d3', 148 | 'lightpink': '#ffb6c1', 149 | 'lightsalmon': '#ffa07a', 150 | 'lightseagreen': '#20b2aa', 151 | 'lightskyblue': '#87cefa', 152 | 'lightslategray': '#778899', 153 | 'lightsteelblue': '#b0c4de', 154 | 'lightyellow': '#ffffe0', 155 | 'lime': '#00ff00', 156 | 'limegreen': '#32cd32', 157 | 'linen': '#faf0e6', 158 | 'magenta': '#ff00ff', 159 | 'maroon': '#800000', 160 | 'mediumaquamarine': '#66cdaa', 161 | 'mediumblue': '#0000cd', 162 | 'mediumorchid': '#ba55d3', 163 | 'mediumpurple': '#9370db', 164 | 'mediumseagreen': '#3cb371', 165 | 'mediumslateblue': '#7b68ee', 166 | 'mediumspringgreen': '#00fa9a', 167 | 'mediumturquoise': '#48d1cc', 168 | 'mediumvioletred': '#c71585', 169 | 'midnightblue': '#191970', 170 | 'mintcream': '#f5fffa', 171 | 'mistyrose': '#ffe4e1', 172 | 'moccasin': '#ffe4b5', 173 | 'navajowhite': '#ffdead', 174 | 'navy': '#000080', 175 | 'oldlace': '#fdf5e6', 176 | 'olive': '#808000', 177 | 'olivedrab': '#6b8e23', 178 | 'orange': '#ffa500', 179 | 'orangered': '#ff4500', 180 | 'orchid': '#da70d6', 181 | 'palegoldenrod': '#eee8aa', 182 | 'palegreen': '#98fb98', 183 | 'paleturquoise': '#afeeee', 184 | 'palevioletred': '#db7093', 185 | 'papayawhip': '#ffefd5', 186 | 'peachpuff': '#ffdab9', 187 | 'peru': '#cd853f', 188 | 'pink': '#ffc0cb', 189 | 'plum': '#dda0dd', 190 | 'powderblue': '#b0e0e6', 191 | 'purple': '#800080', 192 | 'red': '#ff0000', 193 | 'rosybrown': '#bc8f8f', 194 | 'royalblue': '#4169e1', 195 | 'saddlebrown': '#8b4513', 196 | 'salmon': '#fa8072', 197 | 'sandybrown': '#f4a460', 198 | 'seagreen': '#2e8b57', 199 | 'seashell': '#fff5ee', 200 | 'sienna': '#a0522d', 201 | 'silver': '#c0c0c0', 202 | 'skyblue': '#87ceeb', 203 | 'slateblue': '#6a5acd', 204 | 'slategray': '#708090', 205 | 'snow': '#fffafa', 206 | 'springgreen': '#00ff7f', 207 | 'steelblue': '#4682b4', 208 | 'tan': '#d2b48c', 209 | 'teal': '#008080', 210 | 'thistle': '#d8bfd8', 211 | 'tomato': '#ff6347', 212 | 'turquoise': '#40e0d0', 213 | 'violet': '#ee82ee', 214 | 'wheat': '#f5deb3', 215 | 'white': '#ffffff', 216 | 'whitesmoke': '#f5f5f5', 217 | 'yellow': '#ffff00', 218 | 'yellowgreen': '#9acd32' 219 | } 220 | 221 | SORTING = dict((v, k) for k, v in enumerate(( 222 | 223 | # Positioning 224 | 'position', 225 | 'top', 226 | 'right', 227 | 'bottom', 228 | 'left', 229 | 'z-index', 230 | 231 | # Box behavior and properties 232 | 'float', 233 | 'clear', 234 | 'display', 235 | 'visibility', 236 | 'overflow', 237 | 'overflow-x', 238 | 'overflow-y', 239 | 'overflow-style', 240 | 'zoom', 241 | 'clip', 242 | 'box-sizing', 243 | 'box-shadow', 244 | 245 | # Sizing 246 | 'margin', 247 | 'margin-top', 248 | 'margin-right', 249 | 'margin-bottom', 250 | 'margin-left', 251 | 'padding', 252 | 'padding-top', 253 | 'padding-right', 254 | 'padding-bottom', 255 | 'padding-left', 256 | 'width', 257 | 'height', 258 | 'max-width', 259 | 'max-height', 260 | 'min-width', 261 | 'min-height', 262 | 263 | # Color appearance 264 | 'outline', 265 | 'outline-offset', 266 | 'outline-width', 267 | 'outline-style', 268 | 'outline-color', 269 | 'border', 270 | 'border-break', 271 | 'border-collapse', 272 | 'border-color', 273 | 'border-image', 274 | 'border-top-image', 275 | 'border-right-image', 276 | 'border-bottom-image', 277 | 'border-left-image', 278 | 'border-corner-image', 279 | 'border-top-left-image', 280 | 'border-top-right-image', 281 | 'border-bottom-right-image', 282 | 'border-bottom-left-image', 283 | 'border-fit', 284 | 'border-length', 285 | 'border-spacing', 286 | 'border-style', 287 | 'border-width', 288 | 'border-top', 289 | 'border-top-width', 290 | 'border-top-style', 291 | 'border-top-color', 292 | 'border-right', 293 | 'border-right-width', 294 | 'border-right-style', 295 | 'border-right-color', 296 | 'border-bottom', 297 | 'border-bottom-width', 298 | 'border-bottom-style', 299 | 'border-bottom-color', 300 | 'border-left', 301 | 'border-left-width', 302 | 'border-left-style', 303 | 'border-left-color', 304 | 'border-radius', 305 | 'border-top-right-radius', 306 | 'border-top-left-radius', 307 | 'border-bottom-right-radius', 308 | 'border-bottom-left-radius', 309 | 'background', 310 | 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader', 311 | 'background-color', 312 | 'background-image', 313 | 'background-repeat', 314 | 'background-attachment', 315 | 'background-position', 316 | 'background-position-x', 317 | 'background-position-y', 318 | 'background-break', 319 | 'background-clip', 320 | 'background-origin', 321 | 'background-size', 322 | 'color', 323 | 324 | # Special content types 325 | 'table-layout', 326 | 'caption-side', 327 | 'empty-cells', 328 | 'list-style', 329 | 'list-style-position', 330 | 'list-style-type', 331 | 'list-style-image', 332 | 'quotes', 333 | 'content', 334 | 'counter-increment', 335 | 'counter-reset', 336 | 337 | # Text 338 | 'direction', 339 | 'vertical-align', 340 | 'text-align', 341 | 'text-align-last', 342 | 'text-decoration', 343 | 'text-emphasis', 344 | 'text-height', 345 | 'text-indent', 346 | 'text-justify', 347 | 'text-outline', 348 | 'text-replace', 349 | 'text-transform', 350 | 'text-wrap', 351 | 'text-shadow', 352 | 'line-height', 353 | 'white-space', 354 | 'white-space-collapse', 355 | 'word-break', 356 | 'word-spacing', 357 | 'word-wrap', 358 | 'letter-spacing', 359 | 'font', 360 | 'font-weight', 361 | 'font-style', 362 | 'font-variant', 363 | 'font-size', 364 | 'font-size-adjust', 365 | 'font-family', 366 | 'font-effect', 367 | 'font-emphasize', 368 | 'font-emphasize-position', 369 | 'font-emphasize-style', 370 | 'font-smooth', 371 | 'font-stretch', 372 | 'src', 373 | 374 | # Visual properties 375 | 'opacity', 376 | 'filter:progid:DXImageTransform.Microsoft.Alpha', 377 | '-ms-filter:progid:DXImageTransform.Microsoft.Alpha', 378 | 'transitions', 379 | 'resize', 380 | 'cursor', 381 | 382 | # Print 383 | 'page-break-before', 384 | 'page-break-inside', 385 | 'page-break-after', 386 | 'orphans', 387 | 'widows', 388 | 389 | # Transfom 390 | 'transition', 391 | 'transition-delay', 392 | 'transition-duration', 393 | 'transition-property', 394 | 'transition-timing-function', 395 | 396 | ))) 397 | 398 | 399 | class ScssException(Exception): 400 | 401 | """ Raise SCSS exception. """ 402 | 403 | pass 404 | -------------------------------------------------------------------------------- /scss/base.py: -------------------------------------------------------------------------------- 1 | from . import SORTING 2 | 3 | 4 | class Node(object): 5 | 6 | """ Base class for parsed objects. """ 7 | 8 | delim = ' ' 9 | root = None 10 | 11 | def __init__(self, s, n, t): 12 | self.num, self.data = n, t 13 | self.parent = self._ctx = None 14 | 15 | def __str__(self): 16 | return self.delim.join(map(str, self.data)) 17 | 18 | def __repr__(self): 19 | return '(%s%s)' % ( 20 | self.__class__.__name__, 21 | ': %s' % ' '.join(map(repr, self.data)) if self.data else '' 22 | ) 23 | 24 | def parse(self, target): 25 | self.parent = target 26 | 27 | def copy(self): 28 | return self 29 | 30 | def _get_ctx(self): 31 | if self._ctx: 32 | return self._ctx 33 | 34 | if self.parent: 35 | return self.parent.ctx 36 | 37 | self._ctx = dict() 38 | return self._ctx 39 | 40 | def _set_ctx(self, value): 41 | self._ctx = value 42 | 43 | ctx = property(_get_ctx, _set_ctx) 44 | 45 | 46 | class Empty(Node): 47 | 48 | def __str__(self): 49 | return '' 50 | 51 | 52 | class ParseNode(Node): 53 | 54 | def parse(self, target): 55 | super(ParseNode, self).parse(target) 56 | for n in self.data: 57 | if isinstance(n, Node): 58 | n.parse(self) 59 | 60 | def copy(self): 61 | t = [n.copy() if isinstance(n, Node) else n for n in self.data] 62 | return self.__class__(None, self.num, t) 63 | 64 | 65 | class ContentNode(ParseNode): 66 | 67 | def __init__(self, s, n, t): 68 | super(ContentNode, self).__init__(s, n, t) 69 | self.name = self.data[0] if self.data else '' 70 | self.declareset = [] 71 | self.ruleset = [] 72 | 73 | def __str__(self): 74 | # Sort declaration 75 | if self.root.get_opt('sort'): 76 | self.declareset.sort( 77 | key=lambda x: SORTING.get(x.name.lstrip('_#*'), 999)) 78 | 79 | nl, ws, ts = self.root.cache['delims'] 80 | semicolon = '' if self.root.cache['opts'].get('compress') else ';' 81 | 82 | return ''.join(( 83 | 84 | # Self 85 | ''.join(( 86 | 87 | # Selector tree 88 | str(self.name), 89 | 90 | "%s{%s%s" % (ws, nl, ts) if self.name else '', 91 | 92 | # Declarations 93 | (';%s%s' % (nl, ts)).join(str(d) for d in self.declareset), 94 | 95 | semicolon, 96 | 97 | '}%s%s' % (nl, nl) if self.name else '' 98 | 99 | )) if self.declareset else '', 100 | 101 | # Children 102 | ''.join(str(r) for r in self.ruleset) 103 | )) 104 | 105 | 106 | class IncludeNode(ParseNode): 107 | 108 | def parse(self, target): 109 | for node in self.data: 110 | if isinstance(node, Node): 111 | node.ctx.update(self.ctx) 112 | node.parse(target) 113 | 114 | def __str__(self): 115 | node = ContentNode(None, None, []) 116 | self.parse(node) 117 | return str(node) 118 | 119 | # pylama:ignore=D 120 | -------------------------------------------------------------------------------- /scss/compat.py: -------------------------------------------------------------------------------- 1 | import operator 2 | import sys 3 | 4 | PY3 = sys.version_info[0] == 3 5 | 6 | 7 | def with_metaclass(base, meta): 8 | return meta('%sWithMeta' % base.__name__, (base,), {}) 9 | 10 | if PY3: 11 | div = operator.__truediv__ 12 | else: 13 | div = operator.__div__ 14 | 15 | if PY3: 16 | unicode_ = str 17 | bytes_ = bytes 18 | else: 19 | unicode_ = unicode 20 | bytes_ = str 21 | 22 | if PY3: 23 | import io 24 | file_ = io.IOBase 25 | else: 26 | file_ = file 27 | 28 | if PY3: 29 | import pickle 30 | else: 31 | import cPickle as pickle 32 | 33 | # pylama:ignore=W0611,D 34 | -------------------------------------------------------------------------------- /scss/control.py: -------------------------------------------------------------------------------- 1 | from . import OPRT 2 | from .base import ParseNode, Empty, Node, IncludeNode 3 | from .function import FUNCTION_LIST, unknown, warn 4 | from .value import StringValue, Value, BooleanValue, NumberValue 5 | 6 | 7 | class Option(Empty): 8 | 9 | """ Set parser option. 10 | """ 11 | 12 | def parse(self, target): 13 | opts = [(x.value, BooleanValue(y).value) 14 | for x, y in zip(*[iter(self.data[1:])] * 2)] 15 | for v in opts: 16 | self.root.set_opt(*v) 17 | 18 | 19 | class Variable(Value, ParseNode): 20 | 21 | def_value = StringValue('none') 22 | 23 | @classmethod 24 | def _do_op(cls, self, other, op): 25 | return self.value._do_op(self.value, other, op) 26 | 27 | @classmethod 28 | def _do_cmps(cls, self, other, op): 29 | return self.value._do_cmps(self.value, other, op) 30 | 31 | def __nonzero__(self): 32 | return True 33 | 34 | __bool__ = __nonzero__ 35 | 36 | @property 37 | def value(self): 38 | name = self.data[0].strip('-$') 39 | minus = self.data[0][0] == '-' 40 | value = self.ctx.get(name) or self.root.ctx.get(name, self.def_value) 41 | return (0 - value) if minus else value 42 | 43 | 44 | class Variables(ParseNode, Empty): 45 | pass 46 | 47 | 48 | class Expression(Variable): 49 | 50 | @property 51 | def value(self): 52 | it = iter(self.data) 53 | try: 54 | first = next(it) 55 | while True: 56 | res = next(it) 57 | op = OPRT.get(res.strip(), None) 58 | if op: 59 | second = next(it) 60 | first = op(first, second) 61 | 62 | if op == OPRT['and'] and not first: 63 | raise StopIteration 64 | 65 | elif op == OPRT['or'] and first: 66 | raise StopIteration 67 | 68 | except StopIteration: 69 | while isinstance(first, Variable): 70 | first = first.value 71 | return first 72 | 73 | 74 | class SepValString(Expression): 75 | 76 | @property 77 | def value(self): 78 | return ', '.join(str(e.value) for e in self.data) 79 | 80 | 81 | class Function(Expression): 82 | 83 | @property 84 | def value(self): 85 | name = self.data[0] 86 | func_name_a = "%s:%d" % (name, len(self.data) - 1) 87 | func_name_n = "%s:n" % name 88 | func = FUNCTION_LIST.get( 89 | func_name_a, 90 | FUNCTION_LIST.get( 91 | func_name_n, 92 | unknown)) 93 | 94 | params = [v.value for v in self.data[1:]] 95 | kwargs = dict(root=self.root, name=name) 96 | return func(*params, **kwargs) 97 | 98 | 99 | class FunctionDefinition(Empty): 100 | 101 | def parse(self, target): 102 | name = self.data[1].value 103 | params = self.data[2] 104 | func_name = '%s:%s' % (name, len(params)) 105 | FUNCTION_LIST[func_name] = self.wrapper 106 | 107 | def wrapper(self, *args, **kwargs): 108 | self.ctx = Mixin.get_context(self.data[2], args) 109 | for node in self.data[2:]: 110 | if isinstance(node, FunctionReturn): 111 | return node.value 112 | elif isinstance(node, Node): 113 | node.parse(self) 114 | 115 | 116 | class FunctionReturn(Variable): 117 | 118 | @property 119 | def value(self): 120 | return self.data[1] 121 | 122 | 123 | class MixinParam(Empty): 124 | 125 | def __init__(self, s, n, t): 126 | super(MixinParam, self).__init__(s, n, t) 127 | self.name = self.data[0].data[0][1:] 128 | self.value = self.data[1] if len(self.data) > 1 else None 129 | 130 | 131 | class Extend(Empty): 132 | 133 | def parse(self, target): 134 | for rule in self.root.cache['rset'][self.data[1]]: 135 | rule.name.extend(target.name) 136 | 137 | 138 | class Mixin(Empty): 139 | 140 | def __init__(self, s, n, t): 141 | super(Mixin, self).__init__(s, n, t) 142 | self.name = str(self.data[1]) 143 | self.default = self.data[2] 144 | 145 | def parse(self, target): 146 | self.root.cache['mix'][self.name] = self 147 | 148 | def include(self, target, params): 149 | ctx = self.get_context(self.default, params) 150 | if target.ctx: 151 | ctx.update(target.ctx) 152 | 153 | self.ctx = ctx 154 | for n in params: 155 | n.parse(self) 156 | 157 | for node in self.data[3:]: 158 | if isinstance(node, Node): 159 | copy = node.copy() 160 | copy.ctx = ctx 161 | copy.parse(target) 162 | 163 | @staticmethod 164 | def get_context(default, params=''): 165 | return { 166 | mp.name: (params[i] if i < len(params) else None) or mp.value 167 | for i, mp in enumerate(default) if mp 168 | } 169 | 170 | 171 | class Include(IncludeNode): 172 | 173 | def parse(self, target): 174 | if isinstance(target, ParseNode): 175 | name = str(self.data[1]) 176 | params = self.data[2:] 177 | mixin = self.root.cache['mix'].get(name) 178 | if mixin: 179 | mixin.include(target, params) 180 | else: 181 | warn("Required mixin not found: %s:%d." % (name, len(params))) 182 | 183 | 184 | class If(IncludeNode): 185 | 186 | def parse(self, target): 187 | self.data[0].parse(self) 188 | target.ctx.update(self.ctx) 189 | if isinstance(target, ParseNode): 190 | if self.data[0].value: 191 | self.data[1].parse(target) 192 | elif len(self.data) > 2: 193 | self.data[2].parse(target) 194 | 195 | 196 | class For(IncludeNode): 197 | 198 | def parse(self, target): 199 | if isinstance(target, ParseNode): 200 | name = self.data[1].data[0][1:] 201 | for i in range(int(float(self.data[2])), int(float(self.data[3])) + 1): 202 | body = self.data[4].copy() 203 | body.ctx.update({name: NumberValue(i)}) 204 | body.parse(target) 205 | 206 | # pylama:ignore=D,W0212 207 | -------------------------------------------------------------------------------- /scss/function.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import base64 4 | import colorsys 5 | import math 6 | import mimetypes 7 | import os.path 8 | import sys 9 | 10 | from .compat import PY3 11 | 12 | try: 13 | from itertools import product 14 | 15 | except ImportError: 16 | def product(*args, **kwds): 17 | # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy 18 | # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111 19 | pools = map(tuple, args) * kwds.get('repeat', 1) 20 | result = [[]] 21 | for pool in pools: 22 | result = [x + [y] for x in result for y in pool] 23 | for prod in result: 24 | yield tuple(prod) 25 | 26 | from . import OPRT, CONV_TYPE, ELEMENTS_OF_TYPE 27 | from .value import ( 28 | NumberValue, StringValue, QuotedStringValue, ColorValue, BooleanValue, 29 | hsl_op, rgba_op) 30 | 31 | 32 | try: 33 | from PIL import Image 34 | except ImportError: 35 | Image = None 36 | 37 | IMAGES = dict() 38 | 39 | 40 | def warn(warning): 41 | """ Write warning messages in stderr. 42 | """ 43 | print("\nWarning: %s" % str(warning), file=sys.stderr) 44 | 45 | 46 | def unknown(*args, **kwargs): 47 | """ Unknow scss function handler. 48 | Simple return 'funcname(args)' 49 | """ 50 | name = kwargs.get('name', '') 51 | return "%s(%s)" % (name, ', '.join(str(a) for a in args)) 52 | 53 | 54 | def check_pil(func): 55 | """ PIL module checking decorator. 56 | """ 57 | def __wrapper(*args, **kwargs): 58 | root = kwargs.get('root') 59 | if not Image: 60 | if root and root.get_opt('warn'): 61 | warn("Images manipulation require PIL") 62 | return 'none' 63 | return func(*args, **kwargs) 64 | return __wrapper 65 | 66 | 67 | # RGB functions 68 | # ============= 69 | 70 | def _rgb(r, g, b, **kwargs): 71 | """ Converts an rgb(red, green, blue) triplet into a color. 72 | """ 73 | return _rgba(r, g, b, 1.0) 74 | 75 | 76 | def _rgba(r, g, b, a, **kwargs): 77 | """ Converts an rgba(red, green, blue, alpha) quadruplet into a color. 78 | """ 79 | return ColorValue((float(r), float(g), float(b), float(a))) 80 | 81 | 82 | def _red(color, **kwargs): 83 | """ Gets the red component of a color. 84 | """ 85 | return NumberValue(color.value[0]) 86 | 87 | 88 | def _green(color, **kwargs): 89 | """ Gets the green component of a color. 90 | """ 91 | return NumberValue(color.value[1]) 92 | 93 | 94 | def _blue(color, **kwargs): 95 | """ Gets the blue component of a color. 96 | """ 97 | return NumberValue(color.value[2]) 98 | 99 | 100 | def _mix(color1, color2, weight=0.5, **kwargs): 101 | """ Mixes two colors together. 102 | """ 103 | weight = float(weight) 104 | c1 = color1.value 105 | c2 = color2.value 106 | p = 0.0 if weight < 0 else 1.0 if weight > 1 else weight 107 | w = p * 2 - 1 108 | a = c1[3] - c2[3] 109 | 110 | w1 = ((w if (w * a == -1) else (w + a) / (1 + w * a)) + 1) / 2.0 111 | w2 = 1 - w1 112 | q = [w1, w1, w1, p] 113 | r = [w2, w2, w2, 1 - p] 114 | return ColorValue([c1[i] * q[i] + c2[i] * r[i] for i in range(4)]) 115 | 116 | 117 | # HSL functions 118 | # ============= 119 | 120 | def _hsl(h, s, l, **kwargs): 121 | """ HSL color value. 122 | """ 123 | return _hsla(h, s, l, 1.0) 124 | 125 | 126 | def _hsla(h, s, l, a, **kwargs): 127 | """ HSL with alpha channel color value. 128 | """ 129 | res = colorsys.hls_to_rgb(float(h), float(l), float(s)) 130 | return ColorValue([x * 255.0 for x in res] + [float(a)]) 131 | 132 | 133 | def _hue(color, **kwargs): 134 | """ Get hue value of HSL color. 135 | """ 136 | h = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[0] 137 | return NumberValue(h * 360.0) 138 | 139 | 140 | def _lightness(color, **kwargs): 141 | """ Get lightness value of HSL color. 142 | """ 143 | l = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[1] 144 | return NumberValue((l * 100, '%')) 145 | 146 | 147 | def _saturation(color, **kwargs): 148 | """ Get saturation value of HSL color. 149 | """ 150 | s = colorsys.rgb_to_hls(*[x / 255.0 for x in color.value[:3]])[2] 151 | return NumberValue((s * 100, '%')) 152 | 153 | 154 | def _adjust_hue(color, degrees, **kwargs): 155 | return hsl_op(OPRT['+'], color, degrees, 0, 0) 156 | 157 | 158 | def _lighten(color, amount, **kwargs): 159 | return hsl_op(OPRT['+'], color, 0, 0, amount) 160 | 161 | 162 | def _darken(color, amount, **kwargs): 163 | return hsl_op(OPRT['-'], color, 0, 0, amount) 164 | 165 | 166 | def _saturate(color, amount, **kwargs): 167 | return hsl_op(OPRT['+'], color, 0, amount, 0) 168 | 169 | 170 | def _desaturate(color, amount, **kwargs): 171 | return hsl_op(OPRT['-'], color, 0, amount, 0) 172 | 173 | 174 | def _grayscale(color, **kwargs): 175 | return hsl_op(OPRT['-'], color, 0, 100, 0) 176 | 177 | 178 | def _complement(color, **kwargs): 179 | return hsl_op(OPRT['+'], color, 180.0, 0, 0) 180 | 181 | 182 | # Opacity functions 183 | # ================= 184 | 185 | def _alpha(color, **kwargs): 186 | c = ColorValue(color).value 187 | return NumberValue(c[3]) 188 | 189 | 190 | def _opacify(color, amount, **kwargs): 191 | return rgba_op(OPRT['+'], color, 0, 0, 0, amount) 192 | 193 | 194 | def _transparentize(color, amount, **kwargs): 195 | return rgba_op(OPRT['-'], color, 0, 0, 0, amount) 196 | 197 | 198 | # String functions 199 | # ================= 200 | 201 | def _unquote(*args, **kwargs): 202 | return StringValue(' '.join(str(s).strip("\"'") for s in args)) 203 | 204 | 205 | def _quote(*args, **kwargs): 206 | return QuotedStringValue(' '.join(str(s) for s in args)) 207 | 208 | 209 | # Number functions 210 | # ================= 211 | 212 | def _percentage(value, **kwargs): 213 | value = NumberValue(value) 214 | if not value.units == '%': 215 | value.value *= 100 216 | value.units = '%' 217 | return value 218 | 219 | 220 | def _abs(value, **kwargs): 221 | return abs(float(value)) 222 | 223 | 224 | def _pi(**kwargs): 225 | return NumberValue(math.pi) 226 | 227 | 228 | def _sin(value, **kwargs): 229 | return math.sin(value) 230 | 231 | 232 | def _cos(value, **kwargs): 233 | return math.cos(value) 234 | 235 | 236 | def _tan(value, **kwargs): 237 | return math.tan(value) 238 | 239 | 240 | def _round(value, **kwargs): 241 | return float(round(value)) 242 | 243 | 244 | def _ceil(value, **kwargs): 245 | return float(math.ceil(value)) 246 | 247 | 248 | def _floor(value, **kwargs): 249 | return float(math.floor(value)) 250 | 251 | 252 | # Introspection functions 253 | # ======================= 254 | 255 | def _type_of(obj, **kwargs): 256 | if isinstance(obj, BooleanValue): 257 | return StringValue('bool') 258 | if isinstance(obj, NumberValue): 259 | return StringValue('number') 260 | if isinstance(obj, QuotedStringValue): 261 | return StringValue('string') 262 | if isinstance(obj, ColorValue): 263 | return StringValue('color') 264 | if isinstance(obj, dict): 265 | return StringValue('list') 266 | return 'unknown' 267 | 268 | 269 | def _unit(value, **kwargs): 270 | return NumberValue(value).units 271 | 272 | 273 | def _unitless(value, **kwargs): 274 | if NumberValue(value).units: 275 | return BooleanValue(False) 276 | return BooleanValue(True) 277 | 278 | 279 | def _comparable(n1, n2, **kwargs): 280 | n1, n2 = NumberValue(n1), NumberValue(n2) 281 | type1 = CONV_TYPE.get(n1.units) 282 | type2 = CONV_TYPE.get(n2.units) 283 | return BooleanValue(type1 == type2) 284 | 285 | 286 | # Color functions 287 | # ================ 288 | 289 | def _adjust_color( 290 | color, 291 | saturation=0.0, 292 | lightness=0.0, 293 | red=0.0, 294 | green=0.0, 295 | blue=0.0, 296 | alpha=0.0, 297 | **kwargs): 298 | return __asc_color( 299 | OPRT['+'], 300 | color, 301 | saturation, 302 | lightness, 303 | red, 304 | green, 305 | blue, 306 | alpha) 307 | 308 | 309 | def _scale_color( 310 | color, 311 | saturation=1.0, 312 | lightness=1.0, 313 | red=1.0, 314 | green=1.0, 315 | blue=1.0, 316 | alpha=1.0, 317 | **kwargs): 318 | return __asc_color( 319 | OPRT['*'], 320 | color, 321 | saturation, 322 | lightness, 323 | red, 324 | green, 325 | blue, 326 | alpha) 327 | 328 | 329 | def _change_color( 330 | color, 331 | saturation=None, 332 | lightness=None, 333 | red=None, 334 | green=None, 335 | blue=None, 336 | alpha=None, 337 | **kwargs): 338 | return __asc_color( 339 | None, 340 | color, 341 | saturation, 342 | lightness, 343 | red, 344 | green, 345 | blue, 346 | alpha) 347 | 348 | 349 | def _invert(color, **kwargs): 350 | """ Returns the inverse (negative) of a color. 351 | The red, green, and blue values are inverted, while the opacity is left alone. 352 | """ 353 | col = ColorValue(color) 354 | args = [ 355 | 255.0 - col.value[0], 356 | 255.0 - col.value[1], 357 | 255.0 - col.value[2], 358 | col.value[3], 359 | ] 360 | inverted = ColorValue(args) 361 | return inverted 362 | 363 | 364 | def _adjust_lightness(color, amount, **kwargs): 365 | return hsl_op(OPRT['+'], color, 0, 0, amount) 366 | 367 | 368 | def _adjust_saturation(color, amount, **kwargs): 369 | return hsl_op(OPRT['+'], color, 0, amount, 0) 370 | 371 | 372 | def _scale_lightness(color, amount, **kwargs): 373 | return hsl_op(OPRT['*'], color, 0, 0, amount) 374 | 375 | 376 | def _scale_saturation(color, amount, **kwargs): 377 | return hsl_op(OPRT['*'], color, 0, amount, 0) 378 | 379 | 380 | # Compass helpers 381 | # ================ 382 | 383 | def _color_stops(*args, **kwargs): 384 | raise NotImplementedError 385 | 386 | 387 | def _elements_of_type(display, **kwargs): 388 | return StringValue(ELEMENTS_OF_TYPE.get(StringValue(display).value, '')) 389 | 390 | 391 | def _enumerate(s, b, e, **kwargs): 392 | return ', '.join( 393 | "%s%d" % (StringValue(s).value, x) 394 | for x in range(int(b.value), int(e.value + 1))) 395 | 396 | 397 | def _font_files(*args, **kwargs): 398 | raise NotImplementedError 399 | 400 | 401 | def _headings(a=None, b=None, **kwargs): 402 | h = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'] 403 | if not a or StringValue(a).value == 'all': 404 | a, b = 1, 6 405 | elif b is None: 406 | b, a = a.value + 1, 1 407 | return ', '.join(h[int(float(a) - 1):int(float(b))]) 408 | 409 | 410 | def _nest(*args, **kwargs): 411 | return ', '.join( 412 | ' '.join(s.strip() for s in p) 413 | if '&' not in p[1] else p[1].replace('&', p[0].strip()) 414 | for p in product( 415 | *(StringValue(sel).value.split(',') for sel in args) 416 | ) 417 | ) 418 | 419 | 420 | @check_pil 421 | def _image_width(image, **kwargs): 422 | root = kwargs.get('root') 423 | path = os.path.abspath( 424 | os.path.join( 425 | root.get_opt('path'), 426 | StringValue(image).value)) 427 | size = __get_size(path, root=root) 428 | return NumberValue([size[0], 'px']) 429 | 430 | 431 | @check_pil 432 | def _image_height(image, **kwargs): 433 | root = kwargs.get('root') 434 | path = os.path.abspath( 435 | os.path.join( 436 | root.get_opt('path'), 437 | StringValue(image).value)) 438 | size = __get_size(path, root=root) 439 | return NumberValue([size[1], 'px']) 440 | 441 | 442 | def _image_url(image, **kwargs): 443 | return QuotedStringValue(image).value 444 | 445 | 446 | def _inline_image(image, mimetype=None, **kwargs): 447 | root = kwargs.get('root') 448 | path = os.path.abspath( 449 | os.path.join( 450 | root.get_opt('path'), 451 | StringValue(image).value)) 452 | if os.path.exists(path): 453 | mimetype = StringValue(mimetype).value or mimetypes.guess_type(path)[0] 454 | f = open(path, 'rb') 455 | if PY3: 456 | data = base64.b64encode(f.read()).decode('utf-8') 457 | else: 458 | data = base64.b64encode(f.read()) 459 | url = 'data:' + mimetype + ';base64,' + data 460 | else: 461 | if root and root.get_opt('warn'): 462 | warn("Not found image: %s" % path) 463 | url = '%s?_=NA' % QuotedStringValue(image).value 464 | inline = 'url("%s")' % url 465 | return StringValue(inline) 466 | 467 | 468 | # Misc 469 | # ==== 470 | 471 | def _if(cond, body, els, **kwargs): 472 | if BooleanValue(cond).value: 473 | return body 474 | return els 475 | 476 | 477 | def _sprite_position(*args): 478 | pass 479 | 480 | 481 | def _sprite_file(*args): 482 | pass 483 | 484 | 485 | def _sprite(*args): 486 | pass 487 | 488 | 489 | def _sprite_map(*args): 490 | pass 491 | 492 | 493 | def _sprite_map_name(*args): 494 | pass 495 | 496 | 497 | def _sprite_url(*args): 498 | pass 499 | 500 | 501 | def _opposite_position(*args): 502 | pass 503 | 504 | 505 | def _grad_point(*args): 506 | pass 507 | 508 | 509 | def _grad_color_stops(*args): 510 | pass 511 | 512 | 513 | def _nth(*args): 514 | pass 515 | 516 | 517 | def _join(*args): 518 | pass 519 | 520 | 521 | def _append(*args): 522 | pass 523 | 524 | FUNCTION_LIST = { 525 | 526 | # RGB functions 527 | 'rgb:3': _rgb, 528 | 'rgba:4': _rgba, 529 | 'red:1': _red, 530 | 'green:1': _green, 531 | 'blue:1': _blue, 532 | 'mix:2': _mix, 533 | 'mix:3': _mix, 534 | 535 | # HSL functions 536 | 'hsl:3': _hsl, 537 | 'hsla:4': _hsla, 538 | 'hue:1': _hue, 539 | 'saturation:1': _saturation, 540 | 'lightness:1': _lightness, 541 | 'adjust-hue:2': _adjust_hue, 542 | 'spin:2': _adjust_hue, 543 | 'lighten:2': _lighten, 544 | 'darken:2': _darken, 545 | 'saturate:2': _saturate, 546 | 'desaturate:2': _desaturate, 547 | 'grayscale:1': _grayscale, 548 | 'complement:1': _complement, 549 | 550 | # Opacity functions 551 | 'alpha:1': _alpha, 552 | 'opacity:1': _alpha, 553 | 'opacify:2': _opacify, 554 | 'fadein:2': _opacify, 555 | 'fade-in:2': _opacify, 556 | 'transparentize:2': _transparentize, 557 | 'fadeout:2': _transparentize, 558 | 'fade-out:2': _transparentize, 559 | 560 | # String functions 561 | 'quote:n': _quote, 562 | 'unquote:n': _unquote, 563 | 564 | # Number functions 565 | 'percentage:1': _percentage, 566 | 'sin:1': _sin, 567 | 'cos:1': _cos, 568 | 'tan:1': _tan, 569 | 'abs:1': _abs, 570 | 'round:1': _round, 571 | 'ceil:1': _ceil, 572 | 'floor:1': _floor, 573 | 'pi:0': _pi, 574 | 575 | # Introspection functions 576 | 'type-of:1': _type_of, 577 | 'unit:1': _unit, 578 | 'unitless:1': _unitless, 579 | 'comparable:2': _comparable, 580 | 581 | # Color functions 582 | 'adjust-color:n': _adjust_color, 583 | 'scale-color:n': _scale_color, 584 | 'change-color:n': _change_color, 585 | 'adjust-lightness:2': _adjust_lightness, 586 | 'adjust-saturation:2': _adjust_saturation, 587 | 'scale-lightness:2': _scale_lightness, 588 | 'scale-saturation:2': _scale_saturation, 589 | 'invert:1': _invert, 590 | 591 | # Compass helpers 592 | 'append-selector:2': _nest, 593 | 'color-stops:n': _color_stops, 594 | 'enumerate:3': _enumerate, 595 | 'elements-of-type:1': _elements_of_type, 596 | 'font-files:n': _font_files, 597 | 'headings:n': _headings, 598 | 'nest:n': _nest, 599 | 600 | # Images functions 601 | 'image-url:1': _image_url, 602 | 'image-width:1': _image_width, 603 | 'image-height:1': _image_height, 604 | 'inline-image:1': _inline_image, 605 | 'inline-image:2': _inline_image, 606 | 607 | # Not implemented 608 | 'sprite-map:1': _sprite_map, 609 | 'sprite:2': _sprite, 610 | 'sprite:3': _sprite, 611 | 'sprite:4': _sprite, 612 | 'sprite-map-name:1': _sprite_map_name, 613 | 'sprite-file:2': _sprite_file, 614 | 'sprite-url:1': _sprite_url, 615 | 'sprite-position:2': _sprite_position, 616 | 'sprite-position:3': _sprite_position, 617 | 'sprite-position:4': _sprite_position, 618 | 619 | 'opposite-position:n': _opposite_position, 620 | 'grad-point:n': _grad_point, 621 | 'grad-color-stops:n': _grad_color_stops, 622 | 623 | 'nth:2': _nth, 624 | 'first-value-of:1': _nth, 625 | 'join:2': _join, 626 | 'join:3': _join, 627 | 'append:2': _append, 628 | 'append:3': _append, 629 | 630 | 'if:3': _if, 631 | 'escape:1': _unquote, 632 | 'e:1': _unquote, 633 | 634 | } 635 | 636 | 637 | def __asc_color(op, color, saturation, lightness, red, green, blue, alpha): 638 | if lightness or saturation: 639 | color = hsl_op(op, color, 0, saturation, lightness) 640 | if red or green or blue or alpha: 641 | color = rgba_op(op, color, red, green, blue, alpha) 642 | return color 643 | 644 | 645 | def __get_size(path, **kwargs): 646 | root = kwargs.get('root') 647 | if path not in IMAGES: 648 | 649 | if not os.path.exists(path): 650 | 651 | if root and root.get_opt('warn'): 652 | warn("Not found image: %s" % path) 653 | 654 | return 0, 0 655 | 656 | image = Image.open(path) 657 | IMAGES[path] = image.size 658 | return IMAGES[path] 659 | 660 | # pylama:ignore=F0401,D 661 | -------------------------------------------------------------------------------- /scss/grammar.py: -------------------------------------------------------------------------------- 1 | """ SCSS Grammars. """ 2 | 3 | from pyparsing import ( 4 | Word, Suppress, Literal, alphanums, SkipTo, ZeroOrMore, Optional, OneOrMore, 5 | Forward, cStyleComment, Combine, dblSlashComment, quotedString, Regex, 6 | lineEnd, Group) 7 | 8 | 9 | __all__ = ( 10 | "CHARSET", 11 | "COLOR_VALUE", 12 | "CSS_COMMENT", 13 | "DECLARATION", 14 | "DECLARATION_NAME", 15 | "ELSE", 16 | "EXPRESSION", 17 | "EXTEND", 18 | "FONT_FACE", 19 | "FOR", 20 | "FOR_BODY", 21 | "FUNCTION", 22 | "FUNCTION_DEFINITION", 23 | "FUNCTION_RETURN", 24 | "IDENT", 25 | "IF", 26 | "IF_BODY", 27 | "IMPORT", 28 | "INCLUDE", 29 | "MEDIA", 30 | "MIXIN", 31 | "MIXIN_PARAM", 32 | "NUMBER_VALUE", 33 | "OPTION", 34 | "PATH", 35 | "POINT", 36 | "RULESET", 37 | "SCSS_COMMENT", 38 | "SELECTOR", 39 | "SELECTOR_GROUP", 40 | "SELECTOR_TREE", 41 | "SEP_VAL_STRING", 42 | "STYLESHEET", 43 | "VARIABLE", 44 | "VARIABLES", 45 | "VAR_DEFINITION", 46 | "WARN", 47 | "quotedString", 48 | ) 49 | 50 | 51 | # Base css word and literals 52 | COMMA, COLON, SEMICOLON = [Suppress(c) for c in ",:;"] 53 | OPT_SEMICOLON = Optional(SEMICOLON) 54 | LACC, RACC, LPAREN, RPAREN = [Suppress(c) for c in "{}()"] 55 | LLACC, LRACC, LBRACK, RBRACK = [Literal(c) for c in "{}[]"] 56 | 57 | # Comment 58 | CSS_COMMENT = cStyleComment + Optional(lineEnd) 59 | SCSS_COMMENT = dblSlashComment 60 | 61 | IDENT = Regex(r"-?[a-zA-Z_][-a-zA-Z0-9_]*") 62 | COLOR_VALUE = Regex(r"#[a-zA-Z0-9]{3,6}") 63 | VARIABLE = Regex(r"-?\$[-a-zA-Z_][-a-zA-Z0-9_]*") 64 | NUMBER_VALUE = Regex(r"-?\d+(?:\.\d*)?|\.\d+") + \ 65 | Optional(Regex(r"(em|ex|px|cm|mm|in|pt|pc|deg|s|%)(?![-\w])")) 66 | PATH = Regex(r"[-\w\d_\.]*\/{1,2}[-\w\d_\.\/\?\=\&]*") | Regex( 67 | r"((https?|ftp|file):((//)|(\\\\))+[\w\d:#@%/;$()~_?\+-=\\\.&]*)") 68 | POINT_PART = (NUMBER_VALUE | Regex(r"(top|bottom|left|right)")) 69 | POINT = POINT_PART + POINT_PART 70 | 71 | # Values 72 | EXPRESSION = Forward() 73 | INTERPOLATION_VAR = Suppress("#") + LACC + EXPRESSION + RACC 74 | SIMPLE_VALUE = NUMBER_VALUE | PATH | IDENT | COLOR_VALUE | quotedString 75 | DIV_STRING = SIMPLE_VALUE + OneOrMore(Literal("/") + SIMPLE_VALUE) 76 | 77 | PARAMS = LPAREN + (POINT | EXPRESSION) + \ 78 | ZeroOrMore(COMMA + (POINT | EXPRESSION)) + RPAREN 79 | FUNCTION = Regex(r"-?[a-zA-Z_][-a-zA-Z0-9_]*") + PARAMS 80 | VALUE = FUNCTION | VARIABLE | SIMPLE_VALUE 81 | PARENS = LPAREN + EXPRESSION + RPAREN 82 | MATH_OPERATOR = Regex(r"(\+|-|/|\*|and|or|==|!=|<=|<|>|>=)\s+") 83 | _ = EXPRESSION << ( 84 | (VALUE | PARENS) + ZeroOrMore(MATH_OPERATOR + (VALUE | PARENS))) 85 | 86 | # Declaration 87 | TERM = (DIV_STRING | EXPRESSION | INTERPOLATION_VAR) + Optional(",") 88 | DECLARATION_NAME = Optional("*") + OneOrMore(IDENT | INTERPOLATION_VAR) 89 | DECLARATION = Forward() 90 | _ = DECLARATION << ( 91 | DECLARATION_NAME + 92 | ":" + 93 | ZeroOrMore(TERM) + 94 | Optional("!important") + 95 | Optional( 96 | LACC + 97 | OneOrMore( 98 | DECLARATION | CSS_COMMENT | SCSS_COMMENT) + 99 | RACC) + 100 | OPT_SEMICOLON) 101 | 102 | # Selectors 103 | ELEMENT_NAME = Combine(OneOrMore(IDENT | '&')) | Literal("*") 104 | ATTRIB = LBRACK + SkipTo("]") + RBRACK 105 | CLASS_NAME = Word('.', alphanums + "-_") 106 | HASH = Regex(r"#[-a-zA-Z_][-a-zA-Z0-9_]+") 107 | FILTER = HASH | CLASS_NAME | ATTRIB 108 | 109 | # PSEUDO = Regex(r':{1,2}[A-Za-z0-9-_]+') 110 | PSEUDO = Regex(r':{1,2}[^\s;{}]+') 111 | 112 | SELECTOR = OneOrMore(ELEMENT_NAME | FILTER | INTERPOLATION_VAR | PSEUDO) 113 | SELECTOR.leaveWhitespace() 114 | SELECTOR_GROUP = SELECTOR + ZeroOrMore(Optional(Word("+>", max=1)) + SELECTOR) 115 | SELECTOR_GROUP.skipWhitespace = True 116 | SELECTOR_TREE = SELECTOR_GROUP + ZeroOrMore(COMMA + SELECTOR_GROUP) 117 | 118 | # @debug 119 | DEBUG = "@debug" + EXPRESSION + OPT_SEMICOLON 120 | 121 | # @warn 122 | WARN = "@warn" + quotedString + OPT_SEMICOLON 123 | 124 | # @include 125 | INCLUDE = "@include" + IDENT + Optional(PARAMS) + OPT_SEMICOLON 126 | 127 | # @extend 128 | EXTEND = "@extend" + \ 129 | OneOrMore(ELEMENT_NAME | FILTER | INTERPOLATION_VAR | PSEUDO) + OPT_SEMICOLON 130 | 131 | # SCSS variable assigment 132 | SEP_VAL_STRING = EXPRESSION + OneOrMore(COMMA + EXPRESSION) 133 | VAR_DEFINITION = Regex(r"\$[a-zA-Z_][-a-zA-Z0-9_]*") + COLON + \ 134 | (SEP_VAL_STRING | EXPRESSION) + Optional("!default") + OPT_SEMICOLON 135 | 136 | RULESET = Forward() 137 | IF = Forward() 138 | CONTENT = CSS_COMMENT | SCSS_COMMENT | WARN | DEBUG | IF | INCLUDE \ 139 | | VAR_DEFINITION | RULESET | DECLARATION 140 | 141 | # SCSS control directives 142 | IF_BODY = LACC + ZeroOrMore(CONTENT) + RACC 143 | ELSE = Suppress("@else") + LACC + ZeroOrMore(CONTENT) + RACC 144 | _ = IF << ( 145 | (Suppress("@if") | Suppress("@else if")) + 146 | EXPRESSION + 147 | IF_BODY + 148 | Optional(ELSE)) 149 | 150 | FOR_BODY = ZeroOrMore(CONTENT) 151 | FOR = "@for" + VARIABLE + \ 152 | Suppress("from") + VALUE + (Suppress("through") | Suppress("to")) \ 153 | + VALUE + LACC + FOR_BODY + RACC 154 | 155 | _ = RULESET << ( 156 | SELECTOR_TREE + 157 | LACC + ZeroOrMore(CONTENT | FOR | EXTEND) + RACC) 158 | 159 | # SCSS mixin 160 | MIXIN_PARAM = VARIABLE + Optional(COLON + EXPRESSION) 161 | MIXIN_PARAMS = LPAREN + ZeroOrMore(COMMA | MIXIN_PARAM) + RPAREN 162 | MIXIN = "@mixin" + IDENT + \ 163 | Group(Optional(MIXIN_PARAMS)) + LACC + ZeroOrMore(CONTENT | FOR) + RACC 164 | 165 | # SCSS function 166 | FUNCTION_RETURN = "@return" + VARIABLE + OPT_SEMICOLON 167 | FUNCTION_BODY = LACC + ZeroOrMore(VAR_DEFINITION) + FUNCTION_RETURN + RACC 168 | FUNCTION_DEFINITION = "@function" + IDENT + Group(MIXIN_PARAMS) + FUNCTION_BODY 169 | 170 | # Root elements 171 | OPTION = "@option" + \ 172 | OneOrMore(IDENT + COLON + IDENT + Optional(COMMA)) + OPT_SEMICOLON 173 | IMPORT = "@import" + FUNCTION + OPT_SEMICOLON 174 | MEDIA = "@media" + IDENT + \ 175 | ZeroOrMore("," + IDENT) + LLACC + ZeroOrMore(CONTENT | MIXIN | FOR) + LRACC 176 | FONT_FACE = "@font-face" + LLACC + ZeroOrMore(DECLARATION) + LRACC 177 | VARIABLES = (Literal("@variables") | Literal('@vars')) + \ 178 | LLACC + ZeroOrMore(VAR_DEFINITION) + RACC 179 | PSEUDO_PAGE = ":" + IDENT 180 | PAGE = "@page" + Optional(IDENT) + Optional(PSEUDO_PAGE) + \ 181 | LLACC + ZeroOrMore(DECLARATION) + LRACC 182 | CHARSET = "@charset" + IDENT + OPT_SEMICOLON 183 | 184 | # Css stylesheet 185 | STYLESHEET = ZeroOrMore( 186 | FONT_FACE 187 | | CHARSET 188 | | OPTION 189 | | MEDIA 190 | | PAGE 191 | | CONTENT 192 | | FUNCTION_DEFINITION 193 | | MIXIN 194 | | FOR 195 | | IMPORT 196 | | VARIABLES 197 | | EXPRESSION 198 | ) 199 | -------------------------------------------------------------------------------- /scss/parser.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | 3 | import os.path 4 | import sys 5 | 6 | from collections import defaultdict 7 | from pyparsing import ParseBaseException 8 | 9 | from . import SORTING 10 | from .base import Node, Empty, ParseNode, ContentNode, IncludeNode 11 | from .compat import pickle, bytes_, unicode_, file_ 12 | from .control import ( 13 | Variable, Expression, Function, Mixin, Include, MixinParam, Extend, 14 | Variables, Option, FunctionDefinition, FunctionReturn, If, For, SepValString) 15 | from .function import warn, _nest 16 | from .grammar import * 17 | from .value import NumberValue, StringValue, ColorValue, QuotedStringValue, PointValue 18 | 19 | 20 | class Comment(Node): 21 | 22 | """ Comment node. 23 | """ 24 | delim = '' 25 | 26 | def __str__(self): 27 | """ Clean comments if option `comments` disabled 28 | or enabled option `compress` 29 | """ 30 | if self.root.get_opt('comments') and not self.root.get_opt('compress'): 31 | return super(Comment, self).__str__() 32 | return '' 33 | 34 | 35 | class Warn(Empty): 36 | 37 | """ Warning node @warn. 38 | """ 39 | 40 | def parse(self, target): 41 | """ Write message to stderr. 42 | """ 43 | if self.root.get_opt('warn'): 44 | warn(self.data[1]) 45 | 46 | 47 | class Import(Node): 48 | 49 | """ Import node @import. 50 | """ 51 | 52 | def __str__(self): 53 | """ Write @import to outstring. 54 | """ 55 | return "%s;\n" % super(Import, self).__str__() 56 | 57 | 58 | class Ruleset(ContentNode): 59 | 60 | """ Rule node. 61 | """ 62 | 63 | def parse(self, target): 64 | """ Parse nested rulesets 65 | and save it in cache. 66 | """ 67 | if isinstance(target, ContentNode): 68 | if target.name: 69 | self.parent = target 70 | self.name.parse(self) 71 | self.name += target.name 72 | target.ruleset.append(self) 73 | self.root.cache['rset'][str(self.name).split()[0]].add(self) 74 | super(Ruleset, self).parse(target) 75 | 76 | 77 | class Declaration(ParseNode): 78 | 79 | """ Declaration node. 80 | """ 81 | 82 | def __init__(self, s, n, t): 83 | """ Add self.name and self.expr to object. 84 | """ 85 | super(Declaration, self).__init__(s, n, t) 86 | self.name = self.expr = '' 87 | 88 | def parse(self, target): 89 | """ Parse nested declaration. 90 | """ 91 | if not isinstance(target, Node): 92 | parent = ContentNode(None, None, []) 93 | parent.parse(target) 94 | target = parent 95 | 96 | super(Declaration, self).parse(target) 97 | self.name = str(self.data[0]) 98 | while isinstance(target, Declaration): 99 | self.name = '-'.join((str(target.data[0]), self.name)) 100 | target = target.parent 101 | 102 | self.expr = ' '.join(str 103 | (n) 104 | for n in self.data 105 | [2:] if not isinstance(n, Declaration)) 106 | if self.expr: 107 | target.declareset.append(self) 108 | 109 | def __str__(self): 110 | """ Warning on unknown declaration 111 | and write current in outstring. 112 | """ 113 | name = self.name.strip('*_#') 114 | if name.startswith('-moz-'): 115 | name = name[5:] 116 | elif name.startswith('-webkit-'): 117 | name = name[8:] 118 | elif name.startswith('-o-'): 119 | name = name[3:] 120 | elif name.startswith('-ms-'): 121 | name = name[4:] 122 | 123 | if name not in SORTING and self.root.get_opt('warn'): 124 | warn("Unknown declaration: %s" % self.name) 125 | 126 | return (":%s" % self.root.cache['delims'][1]).join( 127 | (self.name, self.expr)) 128 | 129 | 130 | class DeclarationName(ParseNode): 131 | 132 | """ Name of declaration node. 133 | For spliting it in one string. 134 | """ 135 | delim = '' 136 | 137 | 138 | class SelectorTree(ParseNode): 139 | 140 | """ Tree of selectors in ruleset. 141 | """ 142 | delim = ', ' 143 | 144 | def extend(self, target): 145 | """ @extend selectors tree. 146 | """ 147 | self_test = ', '.join(map(str, self.data)) 148 | target_test = ', '.join(map(str, target.data)) 149 | self.data = ( 150 | self_test + ', ' + self_test.replace(str(self.data[0].data[0]), 151 | target_test)).split(', ') 152 | 153 | def __add__(self, target): 154 | """ Add selectors from parent nodes. 155 | """ 156 | if isinstance(target, SelectorTree): 157 | self_test = ', '.join(map(str, self.data)) 158 | target_test = ', '.join(map(str, target.data)) 159 | self.data = _nest(target_test, self_test).split(', ') 160 | return self 161 | 162 | 163 | class Selector(ParseNode): 164 | 165 | """ Simple selector node. 166 | """ 167 | delim = '' 168 | 169 | def __str__(self): 170 | """ Write to output. 171 | """ 172 | return ''.join(StringValue(n).value for n in self.data) 173 | 174 | 175 | class VarDefinition(ParseNode, Empty): 176 | 177 | """ Variable definition. 178 | """ 179 | 180 | def __init__(self, s, n, t): 181 | """ Save self.name, self.default, self.expression 182 | """ 183 | super(VarDefinition, self).__init__(s, n, t) 184 | self.name = t[0][1:] 185 | self.default = len(t) > 2 186 | self.expression = t[1] 187 | 188 | def parse(self, target): 189 | """ Update root and parent context. 190 | """ 191 | super(VarDefinition, self).parse(target) 192 | if isinstance(self.parent, ParseNode): 193 | self.parent.ctx.update({self.name: self.expression.value}) 194 | self.root.set_var(self) 195 | 196 | 197 | class Stylesheet(object): 198 | 199 | """ Root stylesheet node. 200 | """ 201 | 202 | def_delims = '\n', ' ', '\t' 203 | 204 | def __init__(self, cache=None, options=None): 205 | self.cache = cache or dict( 206 | 207 | # Variables context 208 | ctx=dict(), 209 | 210 | # Mixin context 211 | mix=dict(), 212 | 213 | # Rules context 214 | rset=defaultdict(set), 215 | 216 | # Options context 217 | opts=dict( 218 | comments=True, 219 | warn=True, 220 | sort=True, 221 | path=os.getcwd(), 222 | ), 223 | 224 | # CSS delimeters 225 | delims=self.def_delims, 226 | 227 | ) 228 | 229 | if options: 230 | for option in options.items(): 231 | self.set_opt(*option) 232 | 233 | self.setup() 234 | Node.root = self 235 | 236 | @staticmethod 237 | def setup(): 238 | 239 | # Values 240 | NUMBER_VALUE.setParseAction(NumberValue) 241 | IDENT.setParseAction(StringValue) 242 | PATH.setParseAction(StringValue) 243 | POINT.setParseAction(PointValue) 244 | COLOR_VALUE.setParseAction(ColorValue) 245 | quotedString.setParseAction(QuotedStringValue) 246 | EXPRESSION.setParseAction(Expression) 247 | SEP_VAL_STRING.setParseAction(SepValString) 248 | 249 | # Vars 250 | VARIABLE.setParseAction(Variable) 251 | VAR_DEFINITION.setParseAction(VarDefinition) 252 | VARIABLES.setParseAction(Variables) 253 | FUNCTION.setParseAction(Function) 254 | FUNCTION_DEFINITION.setParseAction(FunctionDefinition) 255 | FUNCTION_RETURN.setParseAction(FunctionReturn) 256 | 257 | # Coments 258 | SCSS_COMMENT.setParseAction(lambda x: '') 259 | CSS_COMMENT.setParseAction(Comment) 260 | 261 | # At rules 262 | IMPORT.setParseAction(Import) 263 | CHARSET.setParseAction(Import) 264 | MEDIA.setParseAction(Node) 265 | 266 | # Rules 267 | RULESET.setParseAction(Ruleset) 268 | DECLARATION.setParseAction(Declaration) 269 | DECLARATION_NAME.setParseAction(DeclarationName) 270 | SELECTOR.setParseAction(Selector) 271 | SELECTOR_GROUP.setParseAction(ParseNode) 272 | SELECTOR_TREE.setParseAction(SelectorTree) 273 | FONT_FACE.setParseAction(ContentNode) 274 | 275 | # SCSS Directives 276 | MIXIN.setParseAction(Mixin) 277 | MIXIN_PARAM.setParseAction(MixinParam) 278 | INCLUDE.setParseAction(Include) 279 | EXTEND.setParseAction(Extend) 280 | OPTION.setParseAction(Option) 281 | IF.setParseAction(If) 282 | IF_BODY.setParseAction(IncludeNode) 283 | ELSE.setParseAction(IncludeNode) 284 | FOR.setParseAction(For) 285 | FOR_BODY.setParseAction(IncludeNode) 286 | WARN.setParseAction(Warn) 287 | 288 | @property 289 | def ctx(self): 290 | return self.cache['ctx'] 291 | 292 | def set_var(self, vardef): 293 | """ Set variable to global stylesheet context. 294 | """ 295 | if not(vardef.default and self.cache['ctx'].get(vardef.name)): 296 | self.cache['ctx'][vardef.name] = vardef.expression.value 297 | 298 | def set_opt(self, name, value): 299 | """ Set option. 300 | """ 301 | self.cache['opts'][name] = value 302 | 303 | if name == 'compress': 304 | self.cache['delims'] = self.def_delims if not value else ( 305 | '', 306 | '', 307 | '') 308 | 309 | def get_opt(self, name): 310 | """ Get option. 311 | """ 312 | return self.cache['opts'].get(name) 313 | 314 | def update(self, cache): 315 | """ Update self cache from other. 316 | """ 317 | self.cache['delims'] = cache.get('delims') 318 | self.cache['opts'].update(cache.get('opts')) 319 | self.cache['rset'].update(cache.get('rset')) 320 | self.cache['mix'].update(cache.get('mix')) 321 | map(self.set_var, cache['ctx'].values()) 322 | 323 | @staticmethod 324 | def scan(src): 325 | """ Scan scss from string and return nodes. 326 | """ 327 | assert isinstance(src, (unicode_, bytes_)) 328 | try: 329 | nodes = STYLESHEET.parseString(src, parseAll=True) 330 | return nodes 331 | except ParseBaseException: 332 | err = sys.exc_info()[1] 333 | print(err.line, file=sys.stderr) 334 | print(" " * (err.column - 1) + "^", file=sys.stderr) 335 | print(err, file=sys.stderr) 336 | sys.exit(1) 337 | 338 | def parse(self, nodes): 339 | for n in nodes: 340 | if isinstance(n, Node): 341 | n.parse(self) 342 | 343 | def loads(self, src): 344 | """ Compile css from scss string. 345 | """ 346 | assert isinstance(src, (unicode_, bytes_)) 347 | nodes = self.scan(src.strip()) 348 | self.parse(nodes) 349 | return ''.join(map(str, nodes)) 350 | 351 | def load(self, f, precache=None): 352 | """ Compile scss from file. 353 | File is string path of file object. 354 | """ 355 | precache = precache or self.get_opt('cache') or False 356 | nodes = None 357 | if isinstance(f, file_): 358 | path = os.path.abspath(f.name) 359 | 360 | else: 361 | path = os.path.abspath(f) 362 | f = open(f) 363 | 364 | cache_path = os.path.splitext(path)[0] + '.ccss' 365 | 366 | if precache and os.path.exists(cache_path): 367 | ptime = os.path.getmtime(cache_path) 368 | ttime = os.path.getmtime(path) 369 | if ptime > ttime: 370 | dump = open(cache_path, 'rb').read() 371 | nodes = pickle.loads(dump) 372 | 373 | if not nodes: 374 | src = f.read() 375 | nodes = self.scan(src.strip()) 376 | 377 | if precache: 378 | f = open(cache_path, 'wb') 379 | pickle.dump(nodes, f, protocol=1) 380 | 381 | self.parse(nodes) 382 | return ''.join(map(str, nodes)) 383 | 384 | 385 | def parse(src, cache=None): 386 | """ Parse from string. 387 | """ 388 | parser = Stylesheet(cache) 389 | return parser.loads(src) 390 | 391 | 392 | def load(path, cache=None, precache=False): 393 | """ Parse from file. 394 | """ 395 | parser = Stylesheet(cache) 396 | return parser.load(path, precache=precache) 397 | 398 | # pylama:ignore=D,W0401 399 | -------------------------------------------------------------------------------- /scss/tests/__init__.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | 4 | def all_tests_suite(): 5 | return unittest.TestLoader().loadTestsFromNames([ 6 | # 'scss.tests.test_fake', 7 | 'scss.tests.test_variables', 8 | 'scss.tests.test_nesting', 9 | 'scss.tests.test_font_face', 10 | 'scss.tests.test_functions', 11 | 'scss.tests.test_options', 12 | 'scss.tests.test_extend', 13 | 'scss.tests.test_mixin', 14 | 'scss.tests.test_if', 15 | 'scss.tests.test_for', 16 | 'scss.tests.test_scss', 17 | 'scss.tests.test_files', 18 | 'scss.tests.test_color_functions', 19 | ]) 20 | 21 | 22 | def main(): 23 | runner = unittest.TextTestRunner() 24 | suite = all_tests_suite() 25 | runner.run(suite) 26 | 27 | 28 | if __name__ == '__main__': 29 | import os.path 30 | import sys 31 | sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) 32 | main() 33 | -------------------------------------------------------------------------------- /scss/tests/bag2_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/klen/python-scss/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/tests/bag2_64.png -------------------------------------------------------------------------------- /scss/tests/box_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/klen/python-scss/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/tests/box_64.png -------------------------------------------------------------------------------- /scss/tests/bubble_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/klen/python-scss/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/tests/bubble_64.png -------------------------------------------------------------------------------- /scss/tests/bug_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/klen/python-scss/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/tests/bug_64.png -------------------------------------------------------------------------------- /scss/tests/example.scss: -------------------------------------------------------------------------------- 1 | @charset utf-8; 2 | @import url(test); 3 | 4 | @mixin z-base { 5 | a:hover, a:active { outline: none; } 6 | a, a:active, a:visited { color: #607890; } 7 | a:hover { color: #036; } 8 | @debug test; } 9 | 10 | @media print { 11 | @include z-base; } 12 | 13 | // Test comment 14 | /* Css comment */ 15 | body { 16 | $font: Georgia; 17 | 18 | margin-bottom: .5em; 19 | font-family: $font, sans-serif; 20 | *font:13px/1.231 sans-serif; } 21 | 22 | .test { 23 | color: red; 24 | &:after { 25 | content: 'blue'; }} 26 | 27 | pre, code, kbd, samp { 28 | font: 12px/10px; 29 | font-family: monospace, sans-serif; } 30 | 31 | abbr[title], dfn[title] { 32 | border:2px; } 33 | -------------------------------------------------------------------------------- /scss/tests/test.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/klen/python-scss/34fe985e6b43caa9f9b9bcd0dc433be4b2a1fdec/scss/tests/test.png -------------------------------------------------------------------------------- /scss/tests/test_color_functions.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | def verify_testcases(func): 7 | """Runs the output of the function through SCSS and compares output. 8 | 9 | To use: Write a function that returns a list of tuples, where the first 10 | element of the tuple is SCSS code and the second element the expected 11 | output. When you place this decorator around your function it will take the 12 | SCSS code, run the parser over it and assert the output equals the expected 13 | output.""" 14 | 15 | def assert_testcases(self, *args, **kwargs): 16 | for (testcase, expected_output) in func(self, *args, **kwargs): 17 | out = self.parser.loads(testcase) 18 | self.assertEqual(expected_output, out) 19 | return assert_testcases 20 | 21 | 22 | class TestSCSS(unittest.TestCase): 23 | 24 | """Test color functions 25 | 26 | """ 27 | 28 | def setUp(self): 29 | self.parser = Stylesheet(options=dict(compress=True)) 30 | 31 | @verify_testcases 32 | def test_invert(self): 33 | return [ 34 | ('invert(#000)', '#fff'), 35 | ('invert(#fff)', '#000'), 36 | ('invert(#567)', '#a98'), 37 | ('invert(invert(#123456))', '#123456'), 38 | ('invert(rgba(100, 110, 120, 0.7))', 'rgba(155,145,135,0.70)'), 39 | ('invert(hsla(0, 50%, 50%, 0.7))', 'rgba(63,191,191,0.70)'), 40 | ] 41 | 42 | @verify_testcases 43 | def test_adjust_lightness(self): 44 | # First example is taken from 45 | # http://sass-lang.com/docs/yardoc/Sass/Script/Functions.html 46 | return [ 47 | ('adjust-lightness(#800, 20%)', '#e00'), 48 | ] 49 | -------------------------------------------------------------------------------- /scss/tests/test_extend.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | class TestSCSS(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.parser = Stylesheet(options=dict(compress=True)) 10 | 11 | def test_extend(self): 12 | src = """ 13 | .error { 14 | _border: 1px #f00; 15 | background-color: #fdd; 16 | } 17 | .error .intrusion { 18 | background-image: url("/image/hacked.png"); 19 | } 20 | .seriousError { 21 | @extend .error; 22 | border-width: 3px; 23 | } 24 | """ 25 | test = ".error, .seriousError{_border:1px #f00;background-color:#fdd}.error .intrusion, .seriousError .intrusion{background-image:url('/image/hacked.png')}.seriousError{border-width:3px}" 26 | out = self.parser.loads(src) 27 | self.assertEqual(test, out) 28 | -------------------------------------------------------------------------------- /scss/tests/test_fake.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | class TestSCSS(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.parser = Stylesheet(options=dict(compress=True)) 10 | 11 | def test_math(self): 12 | src = """ 13 | margin: 2px - 5em -1px 0; 14 | """ 15 | test = "" 16 | out = self.parser.loads(src) 17 | self.assertEqual(test, out) 18 | -------------------------------------------------------------------------------- /scss/tests/test_files.py: -------------------------------------------------------------------------------- 1 | import os 2 | import unittest 3 | 4 | from scss import parser 5 | 6 | 7 | class ScssCache(unittest.TestCase): 8 | 9 | path = os.path.join(os.path.dirname(__file__), 'example.scss') 10 | cache_path = os.path.join(os.path.dirname(__file__), 'example.ccss') 11 | 12 | def tearDown(self): 13 | os.remove(self.cache_path) 14 | 15 | def test_cache(self): 16 | src = open(self.path).read() 17 | test = parser.parse(src) 18 | f = open(self.path) 19 | out = parser.load(f, precache=True) 20 | self.assertEqual(test, out) 21 | cached_out = parser.load(f, precache=True) 22 | self.assertEqual(test, cached_out) 23 | -------------------------------------------------------------------------------- /scss/tests/test_font_face.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | class TestSCSS(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.parser = Stylesheet(options=dict(compress=True)) 10 | 11 | def test_font_face(self): 12 | src = """ 13 | @font-face { 14 | font-family: 'MyMinionPro'; 15 | src: url('minion-webfont.eot?') format('eot'), 16 | url('minion-webfont.woff') format('woff'), 17 | url('minion-webfont.ttf') format('truetype'); 18 | font-weight: normal; 19 | font-style: normal; 20 | font-size: ( 12px / 16px ) * 100%; 21 | } 22 | 23 | @font-face { 24 | font-family: 'MyMinionProItalic'; 25 | src: url('minionpro-it-webfont.eot?') format('eot'), 26 | url('minionpro-it-webfont.woff') format('woff'), 27 | url('minionpro-it-webfont.ttf') format('truetype'); 28 | font-weight: normal; 29 | font-style: italic; 30 | } 31 | 32 | h1,h2,h3, time, ol#using .number { 33 | font-weight: normal; 34 | font-family: 'MyMinionPro'; 35 | } 36 | """ 37 | test = "@font-face{font-weight:normal;font-style:normal;font-size:75%;font-family:'MyMinionPro';src:url('minion-webfont.eot?') format('eot') , url('minion-webfont.woff') format('woff') , url('minion-webfont.ttf') format('truetype')}@font-face{font-weight:normal;font-style:italic;font-family:'MyMinionProItalic';src:url('minionpro-it-webfont.eot?') format('eot') , url('minionpro-it-webfont.woff') format('woff') , url('minionpro-it-webfont.ttf') format('truetype')}h1, h2, h3, time, ol#using .number{font-weight:normal;font-family:'MyMinionPro'}" 38 | out = self.parser.loads(src) 39 | self.assertEqual(test, out) 40 | -------------------------------------------------------------------------------- /scss/tests/test_for.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | class TestSCSS(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.parser = Stylesheet(options=dict(compress=True)) 10 | 11 | def test_for(self): 12 | src = """ 13 | @mixin test($src:2px){ 14 | $width: $src + 5px; 15 | width: $width; 16 | } 17 | .test { 18 | color: blue; 19 | @for $i from 1 through 4 { 20 | .span-#{$i}{ 21 | @include test($i); } 22 | } 23 | } 24 | 25 | @for $i from 1 through 2 { 26 | .span-#{$i}{ 27 | color: red; } 28 | } 29 | """ 30 | test = ".test{color:#00f}.test .span-1{width:6px}.test .span-2{width:7px}.test .span-3{width:8px}.test .span-4{width:9px}.span-1{color:#f00}.span-2{color:#f00}" 31 | out = self.parser.loads(src) 32 | self.assertEqual(test, out) 33 | -------------------------------------------------------------------------------- /scss/tests/test_functions.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | try: 5 | from PIL import Image 6 | except ImportError: 7 | Image = None 8 | 9 | 10 | class TestSCSS(unittest.TestCase): 11 | 12 | def setUp(self): 13 | self.parser = Stylesheet(options=dict(compress=True)) 14 | 15 | def test_math(self): 16 | src = " 12 * (60px + 20px) " 17 | test = "960px" 18 | out = self.parser.loads(src) 19 | self.assertEqual(test, out) 20 | 21 | def test_operations_and_functions(self): 22 | src = """ 23 | #navbar { 24 | $navbar-width: 800px; 25 | $items: 1 + 2; 26 | $navbar-color: rgb(100, 100, 55); 27 | $font: "Verdana", monospace; 28 | width: $navbar-width; 29 | border-bottom: 2px solid $navbar-color; 30 | 31 | #{enumerate("div", 1, $items)} { 32 | p & { 33 | color: blue } 34 | color: red; } 35 | } 36 | 37 | li { 38 | background-color: $navbar-color - #333; 39 | background-image: url(test/value.png); 40 | float: left; 41 | font: 8px/10px $font; 42 | margin: 3px + 5.5px auto; 43 | height: 5px + (4px * (2 + $items)); 44 | width: $navbar-width / $items - 10px; 45 | &:hover { background-color: $navbar-color - 10%; } }""" 46 | test = "#navbar{width:800px;border-bottom:2px solid #646437}#navbar div1, #navbar div2, #navbar div3{color:#f00}p #navbar div1, p #navbar div2, p #navbar div3{color:#00f}li{float:left;margin:8.5px auto;width:256.667px;height:25px;background-color:#313104;background-image:url(test/value.png);font:8px / 10px 'Verdana', monospace}li:hover{background-color:#5c5c3e}" 47 | out = self.parser.loads(src) 48 | self.assertEqual(test, out) 49 | 50 | def test_rgb_functions(self): 51 | src = """ 52 | @option warn:false; 53 | 54 | $color: rgba(23, 45, 67, .4) 55 | $color2: #fdc; 56 | .test { 57 | red_test: red($color); 58 | blue_test: blue($color); 59 | green_test: green($color); 60 | color: mix(#f00, #00f, 25%); 61 | } 62 | """ 63 | test = ".test{color:#3f00bf;red_test:23;blue_test:67;green_test:45}" 64 | out = self.parser.loads(src) 65 | self.assertEqual(test, out) 66 | 67 | def test_hsl_functions(self): 68 | src = """ 69 | @option warn:false; 70 | 71 | $hsl: hsla(0, 100%, 25%, .4); 72 | .test { 73 | color: $hsl; 74 | hue: hue($hsl); 75 | s: saturation($hsl); 76 | g: grayscale(#099); 77 | l: lighten(#333, 50%); 78 | ah: adjust-hue(#811, 45deg); 79 | } 80 | """ 81 | test = ".test{color:rgba(127,0,0,0.40);hue:0;s:100%;g:#4c4c4c;l:#b2b2b2;ah:#886a10}" 82 | out = self.parser.loads(src) 83 | self.assertEqual(test, out) 84 | 85 | def test_opacity_functions(self): 86 | src = """ 87 | $color: rgba(100, 100, 100, .4); 88 | .test { 89 | color: opacify( $color, 60% ); 90 | } 91 | """ 92 | test = ".test{color:#646464}" 93 | out = self.parser.loads(src) 94 | self.assertEqual(test, out) 95 | 96 | def test_string_functions(self): 97 | src = """ 98 | $top: 'top'; 99 | $bottom: bottom; 100 | .test { 101 | bottom: quote($bottom); 102 | top: unquote($top); 103 | } 104 | """ 105 | test = ".test{top:top;bottom:'bottom'}" 106 | out = self.parser.loads(src) 107 | self.assertEqual(test, out) 108 | 109 | def test_number_functions(self): 110 | src = """ 111 | @option warn:false; 112 | 113 | $top: 100px; 114 | $bottom: 50px; 115 | .test { 116 | top: percentage($top / $bottom); 117 | round: round($top); 118 | ceil: ceil(1.24); 119 | floor: floor(1.24); 120 | abs: abs(-1.24); 121 | } 122 | """ 123 | test = ".test{top:200%;round:100.0;ceil:2.0;floor:1.0;abs:1.24}" 124 | out = self.parser.loads(src) 125 | self.assertEqual(test, out) 126 | 127 | def test_introspection_functions(self): 128 | src = """ 129 | @option warn:false; 130 | 131 | $top: 100px; 132 | $color: #f00; 133 | .test { 134 | test: type-of($top); 135 | test2: type-of($color); 136 | test3: unit($top); 137 | test4: unitless($top); 138 | } 139 | """ 140 | test = ".test{test:number;test2:color;test3:px;test4:false}" 141 | out = self.parser.loads(src) 142 | self.assertEqual(test, out) 143 | 144 | def test_compass_helpers(self): 145 | src = """ 146 | #{append-selector(".foo, .bar", ".baz")} { 147 | color: red; 148 | } 149 | 150 | .example { 151 | 152 | #{elements-of-type(block)} { 153 | border: 1px solid #777777; 154 | margin: 1em 3em; } 155 | 156 | #{elements-of-type(inline)} { 157 | color: #cc0000; } 158 | } 159 | 160 | a { 161 | #{headings(2, 4)} { 162 | font-weight: bold; 163 | } 164 | } 165 | """ 166 | test = ".foo .baz, .bar .baz{color:#f00}.example address, .example article, .example aside, .example blockquote, .example center, .example dd, .example dialog, .example dir, .example div, .example dl, .example dt, .example fieldset, .example figure, .example footer, .example form, .example frameset, .example h1, .example h2, .example h3, .example h4, .example h5, .example h6, .example header, .example hgroup, .example hr, .example isindex, .example menu, .example nav, .example noframes, .example noscript, .example ol, .example p, .example pre, .example section, .example ul{margin:1em 3em;border:1px solid #777}.example a, .example abbr, .example acronym, .example b, .example basefont, .example bdo, .example big, .example br, .example cite, .example code, .example dfn, .example em, .example font, .example i, .example img, .example input, .example kbd, .example label, .example q, .example s, .example samp, .example select, .example small, .example span, .example strike, .example strong, .example sub, .example sup, .example textarea, .example tt, .example u, .example var{color:#c00}a h2, a h3, a h4{font-weight:bold}" 167 | out = self.parser.loads(src) 168 | self.assertEqual(test, out) 169 | 170 | @unittest.skipIf(not Image, 'PIL not found') 171 | def test_image_functions(self): 172 | src = """ 173 | img.test { 174 | width: image-width(scss/tests/ + 'bug_64.png'); 175 | height: image-height(scss/tests/ + 'bug_64.png'); 176 | background-image: inline-image(scss/tests/ + 'test.png') 177 | 178 | } 179 | """ 180 | test = 'img.test{width:64px;height:64px;background-image:url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAMAAAC67D+PAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAlQTFRF8EFB3AAA////d5xsogAAAAN0Uk5T//8A18oNQQAAAClJREFUeNpiYIIDBkYGCAXEYDaEAFEQKbAQVBEyE6EASRuSYQgrAAIMAB1mAIkfpDEtAAAAAElFTkSuQmCC")}' 181 | out = self.parser.loads(src) 182 | self.assertEqual(test, out) 183 | 184 | def test_function_define(self): 185 | src = """ 186 | @function percent-width($t, $c) { 187 | $perc: $t / $c * 100%; 188 | @return $perc; 189 | } 190 | 191 | .test { 192 | width: percent-width(5px, 24px); 193 | } 194 | """ 195 | test = ".test{width:20.833%}" 196 | out = self.parser.loads(src) 197 | self.assertEqual(test, out) 198 | 199 | def test_misc(self): 200 | src = """ 201 | $test: center; 202 | .test { 203 | margin: 0 if($test == center, auto, 10px); 204 | } 205 | """ 206 | test = ".test{margin:0 auto}" 207 | out = self.parser.loads(src) 208 | self.assertEqual(test, out) 209 | -------------------------------------------------------------------------------- /scss/tests/test_if.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | class TestSCSS(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.parser = Stylesheet(options=dict(compress=True)) 10 | 11 | def test_if(self): 12 | src = """ 13 | $type: monster; 14 | $test: 9px; 15 | 16 | $rec: true; 17 | $rec2: $rec or true; 18 | $rec3: $rec or true; 19 | $rec: $rec2 or $rec3; 20 | 21 | @if $test + 2 > 10 { 22 | @if $rec { 23 | .test { border: 2px; } 24 | } 25 | } 26 | 27 | @mixin test($fix: true) { 28 | @if $fix { 29 | display: block; 30 | } @else { 31 | display: none; 32 | } 33 | } 34 | span { 35 | @include test(false) 36 | } 37 | p { 38 | @if $type == girl { 39 | color: pink; 40 | } 41 | @else if $type == monster { 42 | color: red; 43 | b { border: 2px; } 44 | } 45 | @else { 46 | color: blue; 47 | } 48 | } 49 | """ 50 | test = ".test{border:2px}span{display:none}p{color:#f00}p b{border:2px}" 51 | out = self.parser.loads(src) 52 | self.assertEqual(test, out) 53 | -------------------------------------------------------------------------------- /scss/tests/test_mixin.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | class TestSCSS(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.parser = Stylesheet(options=dict(compress=True)) 10 | 11 | def test_mixin(self): 12 | src = """ 13 | @mixin font { 14 | font: { 15 | weight: inherit; 16 | style: inherit; 17 | size: 100%; 18 | family: inherit; }; 19 | vertical-align: baseline; } 20 | 21 | @mixin global { 22 | .global { 23 | border:red; 24 | @include font; 25 | } 26 | } 27 | 28 | @include global; 29 | 30 | @mixin rounded-top( $radius:10px ) { 31 | $side: top; 32 | border-#{$side}-radius: $radius; 33 | -moz-border-radius-#{$side}: $radius; 34 | -webkit-border-#{$side}-radius: $radius; 35 | } 36 | #navbar li { @include rounded-top; } 37 | #footer { @include rounded-top(5px); } 38 | """ 39 | test = ".global{border:#f00;vertical-align:baseline;font-weight:inherit;font-style:inherit;font-size:100%;font-family:inherit}#navbar li{border-top-radius:10px;-moz-border-radius-top:10px;-webkit-border-top-radius:10px}#footer{border-top-radius:5px;-moz-border-radius-top:5px;-webkit-border-top-radius:5px}" 40 | out = self.parser.loads(src) 41 | self.assertEqual(test, out) 42 | -------------------------------------------------------------------------------- /scss/tests/test_nesting.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | class TestSCSS(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.parser = Stylesheet(options=dict(compress=True)) 10 | 11 | def test_variables(self): 12 | src = """ 13 | table.hl { 14 | margin: 2em 0; 15 | td.ln { 16 | text-align: right; 17 | 18 | li { 19 | color: red; 20 | } 21 | &:hover { 22 | width: 20px; 23 | } 24 | } 25 | } 26 | 27 | li { 28 | font: { 29 | family: serif; 30 | weight: bold; 31 | size: 1.2em; 32 | } 33 | } 34 | """ 35 | test = "table.hl{margin:2em 0}table.hl td.ln{text-align:right}table.hl td.ln li{color:#f00}table.hl td.ln:hover{width:20px}li{font-weight:bold;font-size:1.2em;font-family:serif}" 36 | out = self.parser.loads(src) 37 | self.assertEqual(test, out) 38 | -------------------------------------------------------------------------------- /scss/tests/test_options.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | class TestSCSS(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.parser = Stylesheet() 10 | 11 | def test_default(self): 12 | src = """ 13 | @option compress:false; 14 | // SCSS comment 15 | /* CSS Comment */ 16 | #navbar { 17 | height: 100px; 18 | color: #ff0033; 19 | border: 2px solid magenta; 20 | @warn "Test"; 21 | 22 | li { 23 | background-color: red - #333; 24 | float: left; 25 | font: 8px/10px verdana; 26 | margin: 3px + 5.5px auto; 27 | height: 5px + (4px * 2); 28 | } 29 | } 30 | """ 31 | test = "/* CSS Comment */\n#navbar {\n\theight: 100px;\n\tborder: 2px solid #f0f;\n\tcolor: #f03;}\n\n#navbar li {\n\tfloat: left;\n\tmargin: 8.5px auto;\n\theight: 13px;\n\tbackground-color: #c00;\n\tfont: 8px / 10px verdana;}\n\n" 32 | out = self.parser.loads(src) 33 | self.assertEqual(test, out) 34 | 35 | def test_compress(self): 36 | src = """ 37 | @option compress:true; 38 | // SCSS comment 39 | /* CSS Comment */ 40 | #navbar, p { 41 | height: 100px; 42 | color: #ff0033; 43 | border: 2px solid magenta; 44 | 45 | li { 46 | background-color: red - #333; 47 | float: left; 48 | font: 8px/10px verdana; 49 | margin: 3px + 5.5px auto; 50 | height: 5px + (4px * 2); 51 | } 52 | } 53 | """ 54 | test = "#navbar, p{height:100px;border:2px solid #f0f;color:#f03}#navbar li, p li{float:left;margin:8.5px auto;height:13px;background-color:#c00;font:8px / 10px verdana}" 55 | out = self.parser.loads(src) 56 | self.assertEqual(test, out) 57 | 58 | def test_comments(self): 59 | src = """ 60 | @option comments:false, compress: false; 61 | // SCSS comment 62 | /* CSS Comment */ 63 | #navbar, p { 64 | height: 100px; 65 | color: #ff0033; 66 | border: 2px solid magenta; 67 | 68 | li { 69 | background-color: red - #333; 70 | float: left; 71 | font: 8px/10px verdana; 72 | margin: 3px + 5.5px auto; 73 | height: 5px + (4px * 2); 74 | } 75 | } 76 | """ 77 | test = "#navbar, p {\n\theight: 100px;\n\tborder: 2px solid #f0f;\n\tcolor: #f03;}\n\n#navbar li, p li {\n\tfloat: left;\n\tmargin: 8.5px auto;\n\theight: 13px;\n\tbackground-color: #c00;\n\tfont: 8px / 10px verdana;}\n\n" 78 | out = self.parser.loads(src) 79 | self.assertEqual(test, out) 80 | 81 | def test_sortings(self): 82 | src = """ 83 | @option comments:true, compress: false, sort: false; 84 | // SCSS comment 85 | /* CSS Comment */ 86 | #navbar, p { 87 | height: 100px; 88 | color: #ff0033; 89 | border: 2px solid magenta; 90 | 91 | li { 92 | background-color: red - #333; 93 | float: left; 94 | font: 8px/10px verdana; 95 | margin: 3px + 5.5px auto; 96 | height: 5px + (4px * 2); 97 | } 98 | } 99 | """ 100 | test = "/* CSS Comment */\n#navbar, p {\n\theight: 100px;\n\tcolor: #f03;\n\tborder: 2px solid #f0f;}\n\n#navbar li, p li {\n\tbackground-color: #c00;\n\tfloat: left;\n\tfont: 8px / 10px verdana;\n\tmargin: 8.5px auto;\n\theight: 13px;}\n\n" 101 | out = self.parser.loads(src) 102 | self.assertEqual(test, out) 103 | -------------------------------------------------------------------------------- /scss/tests/test_scss.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | class TestSCSS(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.parser = Stylesheet(options=dict(compress=True)) 10 | 11 | def test_bugs(self): 12 | src = """ 13 | .bug { 14 | background: -webkit-gradient(linear, top left, 100% 100%, from(#ddd), to(#aaa)); 15 | background: -moz-linear-gradient (top, #DDD, #AAA); 16 | margin: 2px -5em -1px 0; 17 | } 18 | """ 19 | test = ".bug{margin:2px -5em -1px 0;background:-webkit-gradient(linear, top left, 100% 100%, from(#ddd), to(#aaa));background:-moz-linear-gradient(top, #ddd, #aaa)}" 20 | out = self.parser.loads(src) 21 | self.assertEqual(test, out) 22 | 23 | def test_base(self): 24 | src = """ 25 | @charset utf-8; 26 | @import url(test); 27 | 28 | @warn "Test warnings!" 29 | @mixin z-base { 30 | a:hover, a:active { outline: none; } 31 | a, a:active, a:visited { color: #607890; } 32 | a:hover { color: #036; } 33 | @debug test; } 34 | 35 | @media print { @include z-base; } 36 | 37 | // Test comment 38 | /* Css comment */ 39 | body:not(.test) { 40 | $font: Georgia; 41 | 42 | margin-bottom: .5em; 43 | font-family: $font, sans-serif; 44 | *font:13px/1.231 sans-serif; } 45 | 46 | ::selection { 47 | color: red; 48 | } 49 | 50 | .test:hover { 51 | color: red; 52 | &:after { 53 | content: 'blue'; }} 54 | 55 | pre, code, kbd, samp { 56 | font: 12px/10px; 57 | font-family: monospace, sans-serif; } 58 | 59 | abbr[title], dfn[title] { 60 | border:2px; } 61 | 62 | """ 63 | test = "@charset utf-8;\n@import url(test);\n@media print { a:hover, a:active{outline:none}a, a:active, a:visited{color:#607890}a:hover{color:#036} }body:not(.test){margin-bottom:.5em;*font:13px / 1.231 sans-serif;font-family:Georgia , sans-serif}::selection{color:#f00}.test:hover{color:#f00}.test:hover:after{content:#00f}pre, code, kbd, samp{font:12px / 10px;font-family:monospace , sans-serif}abbr[title], dfn[title]{border:2px}" 64 | out = self.parser.loads(src) 65 | self.assertEqual(test, out) 66 | 67 | def test_nesting_2(self): 68 | src = """#navbar { 69 | width: 80%; 70 | height: 23px; 71 | ul { list-style-type: none; } 72 | li { float: left; 73 | a .test .main{ font-weight: bold; } 74 | } }""" 75 | test = "#navbar{width:80%;height:23px}#navbar ul{list-style-type:none}#navbar li{float:left}#navbar li a .test .main{font-weight:bold}" 76 | out = self.parser.loads(src) 77 | self.assertEqual(test, out) 78 | 79 | def test_nestproperties(self): 80 | src = """.fakeshadow { 81 | border: { 82 | style: solid; 83 | left: { width: 4px; color: #888; } 84 | right: { width: 2px; color: #ccc; } 85 | } }""" 86 | test = ".fakeshadow{border-style:solid;border-right-width:2px;border-right-color:#ccc;border-left-width:4px;border-left-color:#888}" 87 | out = self.parser.loads(src) 88 | self.assertEqual(test, out) 89 | 90 | def test_parent_references(self): 91 | src = """a { color: #ce4dd6; 92 | &:hover { color: #ffb3ff; } 93 | &:visited { color: #c458cb; } 94 | .test & { color: red; }}""" 95 | test = "a{color:#ce4dd6}a:hover{color:#ffb3ff}a:visited{color:#c458cb}.test a{color:#f00}" 96 | out = self.parser.loads(src) 97 | self.assertEqual(test, out) 98 | 99 | def test_variables(self): 100 | src = """$main-color: #ce4dd6; 101 | $style: solid; 102 | $def_test: first; 103 | $def_test: second; 104 | $def_test: beep-beep !default; 105 | #navbar { border-bottom: { color: $main-color; style: $style; } } 106 | a.#{$def_test} { color: $main-color; &:hover { border-bottom: $style 1px; } }""" 107 | test = "#navbar{border-bottom-style:solid;border-bottom-color:#ce4dd6}a.second{color:#ce4dd6}a.second:hover{border-bottom:solid 1px}" 108 | out = self.parser.loads(src) 109 | self.assertEqual(test, out) 110 | 111 | def test_interpolation(self): 112 | src = """$side: top; 113 | $radius: 10px; 114 | div.rounded-#{$side} p { 115 | border-#{$side}-radius: $radius; 116 | -moz-border-radius-#{$side}: $radius; 117 | -webkit-border-#{$side}-radius: $radius; }""" 118 | test = "div.rounded-top p{border-top-radius:10px;-moz-border-radius-top:10px;-webkit-border-top-radius:10px}" 119 | out = self.parser.loads(src) 120 | self.assertEqual(test, out) 121 | 122 | def test_mixin_arg(self): 123 | src = """@mixin rounded($side, $radius: 10px, $dummy: false) { 124 | border-#{$side}-radius: $radius; 125 | -moz-border-radius-#{$side}: $radius; 126 | -webkit-border-#{$side}-radius: $radius; } 127 | #navbar li { @include rounded(top); } 128 | #footer { @include rounded(top, 5px); } 129 | #sidebar { @include rounded(left, 8px); }""" 130 | test = "#navbar li{border-top-radius:10px;-moz-border-radius-top:10px;-webkit-border-top-radius:10px}#footer{border-top-radius:5px;-moz-border-radius-top:5px;-webkit-border-top-radius:5px}#sidebar{border-left-radius:8px;-moz-border-radius-left:8px;-webkit-border-left-radius:8px}" 131 | out = self.parser.loads(src) 132 | self.assertEqual(test, out) 133 | 134 | def test_extend_rule(self): 135 | src = """ 136 | .error { border: 1px #f00; background-color: #fdd; } 137 | a:hover {text-decoration: underline} 138 | .hoverlink {@extend a:hover} 139 | .error .intrusion { background-image: url(/image/hacked.png); } 140 | .seriousError { @extend .error; border-width: 3px; } 141 | """ 142 | test = ".error, .seriousError{border:1px #f00;background-color:#fdd}a:hover{text-decoration:underline}.error .intrusion, .seriousError .intrusion{background-image:url(/image/hacked.png)}.seriousError{border-width:3px}" 143 | out = self.parser.loads(src) 144 | self.assertEqual(test, out) 145 | -------------------------------------------------------------------------------- /scss/tests/test_variables.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from scss.parser import Stylesheet 4 | 5 | 6 | class TestSCSS(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.parser = Stylesheet(options=dict(compress=True)) 10 | 11 | def test_variables(self): 12 | src = """ 13 | @vars { 14 | $blue: #ffdd00 !default; 15 | $test: rgb(120, 35, 64); 16 | $test2: rgba(120, 35, 64, .4); 17 | $property: float; 18 | $value: left; 19 | $len: 0px or 5px; 20 | } 21 | $margin: 16px; 22 | $side: top; 23 | $image: 'test.png'; 24 | 25 | .content-navigation { 26 | #{$property}: #{$value}; 27 | border-color: $blue; 28 | background-color: $test + 5%; 29 | 30 | 31 | background-image: url('/test/' + $image); 32 | display: -moz-inline-box; 33 | color: $blue - 9%; 34 | margin: $len (-$margin * 2 ) -12px; 35 | } 36 | 37 | .border { 38 | padding-#{$side}: $margin / 2; 39 | margin: $margin / 2; 40 | padding-left: -$margin + 2px; 41 | border-#{$side}: { 42 | color: $blue; 43 | } 44 | color: $test2; 45 | font: -1.5em + 50px; 46 | } 47 | """ 48 | test = ".content-navigation{float:left;display:-moz-inline-box;margin:5px -32px -12px;border-color:#fd0;background-color:#7b1f3e;background-image:url(/test/test.png);color:#f3d40b}.border{margin:8px;padding-top:8px;padding-left:-14px;border-top-color:#fd0;color:rgba(120,35,64,0.40);font:30.5px}" 49 | out = self.parser.loads(src) 50 | self.assertEqual(test, out) 51 | -------------------------------------------------------------------------------- /scss/tool.py: -------------------------------------------------------------------------------- 1 | """ Command-line tool to parse scss file. """ 2 | 3 | from __future__ import print_function 4 | 5 | import optparse 6 | import sys 7 | import os 8 | import time 9 | 10 | from . import parser, __version__ 11 | 12 | 13 | COMMANDS = ['import', 'option', 'mixin', 'include', 'for', 'if', 'else'] 14 | 15 | 16 | def complete(text, state): 17 | """ Auto complete scss constructions in interactive mode. """ 18 | for cmd in COMMANDS: 19 | if cmd.startswith(text): 20 | if not state: 21 | return cmd 22 | else: 23 | state -= 1 24 | 25 | 26 | def main(argv=None): # noqa 27 | 28 | try: 29 | # Upgrade shell in interactive mode 30 | import atexit 31 | import readline 32 | history = os.path.join(os.environ['HOME'], ".scss-history") 33 | atexit.register(readline.write_history_file, history) 34 | readline.parse_and_bind("tab: complete") 35 | readline.set_completer(complete) 36 | readline.read_history_file(history) 37 | except (ImportError, IOError): 38 | pass 39 | 40 | # Create options 41 | p = optparse.OptionParser( 42 | usage="%prog [OPTION]... [INFILE] [OUTFILE]", 43 | version="%prog " + __version__, 44 | epilog="SCSS compiler.", 45 | description="Compile INFILE or standard input, to OUTFILE or standard output.") 46 | 47 | p.add_option( 48 | '-c', '--cache', action='store_true', dest='cache', 49 | help="Create and use cache file. Only for files.") 50 | 51 | p.add_option( 52 | '-i', '--interactive', action='store_true', dest='shell', 53 | help="Run in interactive shell mode.") 54 | 55 | p.add_option( 56 | '-m', '--compress', action='store_true', dest='compress', 57 | help="Compress css output.") 58 | 59 | p.add_option( 60 | '-w', '--watch', dest='watch', 61 | help="""Watch files or directories for changes. 62 | The location of the generated CSS can be set using a colon: 63 | scss -w input.scss:output.css 64 | """) 65 | 66 | p.add_option( 67 | '-S', '--no-sorted', action='store_false', dest='sort', 68 | help="Do not sort declaration.") 69 | 70 | p.add_option( 71 | '-C', '--no-comments', action='store_false', dest='comments', 72 | help="Clear css comments.") 73 | 74 | p.add_option( 75 | '-W', '--no-warnings', action='store_false', dest='warn', 76 | help="Disable warnings.") 77 | 78 | opts, args = p.parse_args(argv or sys.argv[1:]) 79 | precache = opts.cache 80 | 81 | # Interactive mode 82 | if opts.shell: 83 | p = parser.Stylesheet() 84 | print('SCSS v. %s interactive mode' % __version__) 85 | print('================================') 86 | print('Ctrl+D or quit for exit') 87 | while True: 88 | try: 89 | s = input('>>> ').strip() 90 | if s == 'quit': 91 | raise EOFError 92 | print(p.loads(s)) 93 | except (EOFError, KeyboardInterrupt): 94 | print('\nBye bye.') 95 | break 96 | 97 | sys.exit() 98 | 99 | # Watch mode 100 | elif opts.watch: 101 | self, _, target = opts.watch.partition(':') 102 | files = [] 103 | if not os.path.exists(self): 104 | print(sys.stderr, "Path don't exist: %s" % self, file=sys.stderr) 105 | sys.exit(1) 106 | 107 | if os.path.isdir(self): 108 | for f in os.listdir(self): 109 | path = os.path.join(self, f) 110 | if os.path.isfile(path) and f.endswith('.scss'): 111 | tpath = os.path.join(target or self, f[:-5] + '.css') 112 | files.append([path, tpath, 0]) 113 | else: 114 | files.append([self, target or self[:-5] + '.css', 0]) 115 | 116 | s = parser.Stylesheet( 117 | options=dict( 118 | comments=opts.comments, 119 | compress=opts.compress, 120 | warn=opts.warn, 121 | sort=opts.sort, 122 | cache=precache, 123 | )) 124 | 125 | def parse(f): 126 | infile, outfile, mtime = f 127 | ttime = os.path.getmtime(infile) 128 | if mtime < ttime: 129 | print(" Parse '%s' to '%s' .. done" % (infile, outfile)) 130 | out = s.load(open(infile, 'r')) 131 | open(outfile, 'w').write(out) 132 | f[2] = os.path.getmtime(outfile) 133 | 134 | print('SCSS v. %s watch mode' % __version__) 135 | print('================================') 136 | print('Ctrl+C for exit\n') 137 | while True: 138 | try: 139 | for f in files: 140 | parse(f) 141 | time.sleep(0.3) 142 | except OSError: 143 | pass 144 | except KeyboardInterrupt: 145 | print("\nSCSS stoped.") 146 | break 147 | 148 | sys.exit() 149 | 150 | # Default compile files 151 | elif not args: 152 | infile = sys.stdin 153 | outfile = sys.stdout 154 | precache = False 155 | 156 | elif len(args) == 1: 157 | try: 158 | infile = open(args[0], 'r') 159 | outfile = sys.stdout 160 | except IOError as e: 161 | sys.stderr.write(str(e)) 162 | sys.exit() 163 | 164 | elif len(args) == 2: 165 | try: 166 | infile = open(args[0], 'r') 167 | outfile = open(args[1], 'w') 168 | except IOError as e: 169 | sys.stderr.write(str(e)) 170 | sys.exit() 171 | 172 | else: 173 | p.print_help(sys.stdout) 174 | sys.exit() 175 | 176 | try: 177 | s = parser.Stylesheet( 178 | options=dict( 179 | comments=opts.comments, 180 | compress=opts.compress, 181 | warn=opts.warn, 182 | sort=opts.sort, 183 | cache=precache, 184 | )) 185 | outfile.write(s.load(infile)) 186 | except ValueError as e: 187 | raise SystemExit(e) 188 | 189 | 190 | if __name__ == '__main__': 191 | main() 192 | -------------------------------------------------------------------------------- /scss/value.py: -------------------------------------------------------------------------------- 1 | " SCSS Values." 2 | 3 | from colorsys import rgb_to_hls, hls_to_rgb 4 | from pyparsing import ParseResults 5 | 6 | from scss import OPRT, CONV_FACTOR, COLORS 7 | from scss.base import Node 8 | from scss.compat import with_metaclass 9 | 10 | hex2rgba = { 11 | 8: lambda c: (int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16), int(c[6:8], 16)), 12 | 6: lambda c: (int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16), 1.0), 13 | 4: lambda c: (int(c[0]*2, 16), int(c[1]*2, 16), int(c[2]*2, 16), int(c[3]*2, 16)), 14 | 3: lambda c: (int(c[0]*2, 16), int(c[1]*2, 16), int(c[2]*2, 16), 1.0), 15 | } 16 | 17 | 18 | def hsl_op(op, color, h, s, l): 19 | color = ColorValue(color) 20 | h, s, l = map(NumberValue, (h, s, l)) 21 | h.units = 'deg' 22 | s.units = l.units = '%' 23 | other_hls = map(float, (h, l, s)) 24 | self_hls = rgb_to_hls(*map(lambda x: x / 255.0, color.value[:3])) 25 | res_hls = map( 26 | lambda x, y: op(x, y) if op else y if y else x, self_hls, other_hls) 27 | res_hls = map(lambda x: 1 if x > 1 else 0 if x < 0 else x, res_hls) 28 | res = hls_to_rgb(*res_hls) 29 | return ColorValue( 30 | (res[0] * 255.0, 31 | res[1] * 255.0, 32 | res[2] * 255.0, 33 | color.value[3])) 34 | 35 | 36 | def rgba_op(op, color, r, g, b, a): 37 | other = (float(r), float(g), float(b), float(a)) 38 | res = list(map(op or (lambda x, y: x or y), color.value, other)) 39 | res[3] = 1 if float(a) == color.value[3] == 1 else res[3] 40 | return ColorValue(res) 41 | 42 | 43 | class Value(Node): 44 | 45 | """ Abstract value. 46 | """ 47 | @classmethod 48 | def _do_op(cls, self, other, op): 49 | first, second = cls(self), cls(other) 50 | return op(first.value, second.value) 51 | 52 | @classmethod 53 | def _do_cmps(cls, first, second, op): 54 | return op(first.value, second.value) 55 | 56 | # Math operation 57 | def __add__(self, other): 58 | return self._do_op(self, other, OPRT['+']) 59 | 60 | __radd__ = __add__ 61 | 62 | def __div__(self, other): 63 | return self._do_op(self, other, OPRT['/']) 64 | 65 | __truediv__ = __div__ 66 | 67 | def __rdiv__(self, other): 68 | return self._do_op(other, self, OPRT['/']) 69 | 70 | def __sub__(self, other): 71 | return self._do_op(self, other, OPRT['-']) 72 | 73 | def __rsub__(self, other): 74 | return self._do_op(other, self, OPRT['-']) 75 | 76 | def __mul__(self, other): 77 | return self._do_op(self, other, OPRT['*']) 78 | 79 | def __lt__(self, other): 80 | return self._do_cmps(self, other, OPRT['<']) 81 | 82 | __rmul__ = __mul__ 83 | 84 | # Compare operation 85 | def __le__(self, other): 86 | return self._do_cmps(self, other, OPRT['<=']) 87 | 88 | def __gt__(self, other): 89 | return self._do_cmps(self, other, OPRT['>=']) 90 | 91 | def __ge__(self, other): 92 | return self._do_cmps(self, other, OPRT['>']) 93 | 94 | def __eq__(self, other): 95 | return self._do_cmps(self, other, OPRT['==']) 96 | 97 | def __ne__(self, other): 98 | return self._do_cmps(self, other, OPRT['!=']) 99 | 100 | # Boolean 101 | def __nonzero__(self): 102 | return getattr(self, 'value') and True or False 103 | 104 | def __bool__(self): 105 | return bool(self.value) if self.value != 'false' else False 106 | 107 | def __str__(self): 108 | return str(self.value) 109 | 110 | def __float__(self): 111 | return float(self.value) 112 | 113 | 114 | class StringValueMeta(type): 115 | 116 | def __call__(cls, *args, **kwargs): 117 | test = cls.__new__(cls) 118 | test.__init__(*args, **kwargs) 119 | 120 | if test.value in ('true', 'false'): 121 | return BooleanValue(test.value) 122 | 123 | elif test.value in COLORS: 124 | return ColorValue(COLORS.get(test.value)) 125 | 126 | return test 127 | 128 | 129 | class StringValue(with_metaclass(Value, StringValueMeta)): 130 | 131 | def_value = '' 132 | 133 | def __init__(self, t): 134 | super(StringValue, self).__init__(None, None, t) 135 | 136 | self.value = self.def_value 137 | 138 | if isinstance(t, ParseResults): 139 | self.value = ''.join(str(s) for s in t) 140 | 141 | elif isinstance(t, StringValue): 142 | self.value = t.value 143 | 144 | elif isinstance(t, Node): 145 | self.value = str(t.value).strip('"\'') 146 | 147 | elif isinstance(t, (str, int, float)): 148 | self.value = str(t) 149 | 150 | def __div__(self, other): 151 | self.value = '/'.join((str(self), str(other))) 152 | return self 153 | 154 | def __str__(self): 155 | return self.value 156 | 157 | 158 | class PointValue(Value): 159 | 160 | @property 161 | def value(self): 162 | return ' '.join(map(str, self.data)) 163 | 164 | def __str__(self): 165 | return self.value 166 | 167 | 168 | class QuotedStringValue(StringValue): 169 | 170 | def __init__(self, t): 171 | super(QuotedStringValue, self).__init__(t) 172 | self.value = self.value.strip('"\'') 173 | 174 | def __str__(self): 175 | return "'%s'" % self.value 176 | 177 | 178 | class ColorValue(Value): 179 | 180 | def_value = (255.0, 255.0, 255.0, 1) 181 | 182 | def __init__(self, t): 183 | super(ColorValue, self).__init__(None, None, t) 184 | self.value = self.def_value 185 | 186 | if isinstance(t, ParseResults): 187 | val = t[0][1:] 188 | self.value = hex2rgba[len(val)](val) 189 | 190 | elif isinstance(t, (list, tuple)): 191 | r = self.value 192 | c = list(map(lambda x, y: x if x is not None else y, t, r)) 193 | c = tuple( 194 | 0.0 195 | if c[i] < 0 else r[i] if c[i] > r[i] else c[i] 196 | for i in range(4)) 197 | self.value = c 198 | 199 | elif isinstance(t, str): 200 | val = t[1:] 201 | self.value = hex2rgba[len(val)](val) 202 | 203 | elif isinstance(t, ColorValue): 204 | self.value = t.value 205 | 206 | def __float__(self): 207 | return float(sum(self.value[:3], 0.0) / 3 * self.value[3]) 208 | 209 | def __str__(self): 210 | if self.value[3] == 1: 211 | v = '%02x%02x%02x' % self.value[:3] 212 | if v[0] == v[1] and v[2] == v[3] and v[4] == v[5]: 213 | v = v[0] + v[2] + v[4] 214 | return '#%s' % v 215 | return 'rgba(%d,%d,%d,%.2f)' % self.value 216 | 217 | __repr__ = __str__ 218 | 219 | @classmethod 220 | def _do_op(cls, self, other, op): 221 | if isinstance(other, ColorValue): 222 | return rgba_op(op, self, *other.value) 223 | 224 | elif isinstance(other, (NumberValue, int)): 225 | if op in (OPRT['*'], OPRT['/']): 226 | return ColorValue( 227 | [op 228 | (x, float(other)) 229 | for x in self.value[: 3]]) 230 | return hsl_op(op, self, 0, other, 0) 231 | 232 | else: 233 | return self 234 | 235 | 236 | class BooleanValue(Value): 237 | 238 | def_value = True 239 | 240 | def __init__(self, t): 241 | super(BooleanValue, self).__init__(None, None, t) 242 | self.value = self.def_value 243 | 244 | if isinstance(t, (str, bool)): 245 | self.value = bool(t) if t != 'false' else False 246 | 247 | elif isinstance(t, Node): 248 | self.value = bool(t) 249 | 250 | def __str__(self): 251 | return 'true' if self.value else 'false' 252 | 253 | __repr__ = __str__ 254 | 255 | def __float__(self): 256 | return 1.0 if self.value else 0.0 257 | 258 | 259 | class NumberValue(Value): 260 | 261 | def_value = 0.0 262 | 263 | def __init__(self, t): 264 | super(NumberValue, self).__init__(None, None, t) 265 | self.value = self.def_value 266 | self.units = '' 267 | 268 | if isinstance(t, (ParseResults, list, tuple)): 269 | if len(t) > 1: 270 | self.units = t[1] 271 | self.value = float(t[0]) 272 | 273 | elif isinstance(t, NumberValue): 274 | self.value, self.units = t.value, t.units 275 | 276 | elif isinstance(t, Node): 277 | self.value = float(t.value) 278 | self.units = getattr(t.value, 'units', '') 279 | 280 | elif isinstance(t, (int, float, str)): 281 | self.value = float(t) 282 | 283 | def __float__(self): 284 | return self.value * CONV_FACTOR.get(self.units, 1.0) 285 | 286 | def __round__(self, n=None): 287 | # Py3 output compatibility 288 | return float(round(float(self))) 289 | 290 | def __str__(self): 291 | value = ("%0.03f" % self.value).strip('0').rstrip('.') or 0 292 | return "%s%s" % (value, self.units if self.value else '') 293 | 294 | @classmethod 295 | def _do_op(cls, self, other, op): 296 | first, second = cls(self), cls(other) 297 | units = second.units or first.units 298 | value = op(float(first), float(second)) 299 | value /= CONV_FACTOR.get(units, 1.0) 300 | return cls((value, units)) 301 | 302 | # pylama:ignore=D,W0110 303 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [bdist_wheel] 2 | universal = 1 3 | 4 | [wheel] 5 | universal = 1 6 | 7 | [pylama] 8 | ignore = D,C0111 9 | 10 | [pylama:*/tests*] 11 | ignore=C0301,E501,F0401 12 | 13 | [pylama:pylint] 14 | max-line-length = 100 15 | 16 | [pylama:pep8] 17 | max_line_length = 100 18 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ SCSS - python parser. """ 4 | 5 | import re 6 | from os import path as op 7 | 8 | from setuptools import setup, find_packages 9 | 10 | 11 | def _read(fname): 12 | try: 13 | return open(op.join(op.dirname(__file__), fname)).read() 14 | except IOError: 15 | return '' 16 | 17 | _meta = _read('scss/__init__.py') 18 | _license = re.search(r'^__license__\s*=\s*"(.*)"', _meta, re.M).group(1) 19 | _project = re.search(r'^__project__\s*=\s*"(.*)"', _meta, re.M).group(1) 20 | _version = re.search(r'^__version__\s*=\s*"(.*)"', _meta, re.M).group(1) 21 | 22 | install_requires = [ 23 | l for l in _read('requirements.txt').split('\n') 24 | if l and not l.startswith('#')] 25 | 26 | setup( 27 | name=_project, 28 | version=_version, 29 | license=_license, 30 | description=_read('DESCRIPTION'), 31 | long_description=_read('README.rst'), 32 | platforms=('Any'), 33 | 34 | author='Kirill Klenov', 35 | author_email='horneds@gmail.com', 36 | url='http://github.com/klen/python-scss', 37 | 38 | keywords='css sass scss precompiler', 39 | classifiers=[ 40 | 'Development Status :: 4 - Beta', 41 | 'Intended Audience :: Developers', 42 | 'Natural Language :: Russian', 43 | 'Natural Language :: English', 44 | 'License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 45 | 'Programming Language :: Python', 46 | 'Environment :: Console', 47 | 'Topic :: Software Development :: Code Generators', 48 | 'Topic :: Text Processing :: Markup', 49 | ], 50 | 51 | packages=find_packages(), 52 | 53 | install_requires=install_requires, 54 | 55 | entry_points={ 56 | 'console_scripts': [ 57 | 'scss = scss.tool:main', 58 | ] 59 | }, 60 | ) 61 | -------------------------------------------------------------------------------- /todo.txt: -------------------------------------------------------------------------------- 1 | Drop root from functions 2 | Refactor EXPRESSION and etc grammars 3 | Real ctx parsing 4 | Ok, ok, add import support 5 | Check darken and other color functions 6 | Add col, lines to unknown messages 7 | Drop parse nodes 8 | Add zen codding abbr 9 | Drop root defined in node init, get this from str stylecheet 10 | Add ruleset check for dublicate 11 | Drop hasattr, getattr, update t patterns 12 | --------------------------------------------------------------------------------