1
2
3 r"""
4 ==============
5 CSS Minifier
6 ==============
7
8 CSS Minifier.
9
10 The minifier is based on the semantics of the `YUI compressor`_\\, which
11 itself is based on `the rule list by Isaac Schlueter`_\\.
12
13 :Copyright:
14
15 Copyright 2011 - 2014
16 Andr\xe9 Malo or his licensors, as applicable
17
18 :License:
19
20 Licensed under the Apache License, Version 2.0 (the "License");
21 you may not use this file except in compliance with the License.
22 You may obtain a copy of the License at
23
24 http://www.apache.org/licenses/LICENSE-2.0
25
26 Unless required by applicable law or agreed to in writing, software
27 distributed under the License is distributed on an "AS IS" BASIS,
28 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
29 See the License for the specific language governing permissions and
30 limitations under the License.
31
32 This module is a re-implementation aiming for speed instead of maximum
33 compression, so it can be used at runtime (rather than during a preprocessing
34 step). RCSSmin does syntactical compression only (removing spaces, comments
35 and possibly semicolons). It does not provide semantic compression (like
36 removing empty blocks, collapsing redundant properties etc). It does, however,
37 support various CSS hacks (by keeping them working as intended).
38
39 Here's a feature list:
40
41 - Strings are kept, except that escaped newlines are stripped
42 - Space/Comments before the very end or before various characters are
43 stripped: ``:{});=>+],!`` (The colon (``:``) is a special case, a single
44 space is kept if it's outside a ruleset.)
45 - Space/Comments at the very beginning or after various characters are
46 stripped: ``{}(=:>+[,!``
47 - Optional space after unicode escapes is kept, resp. replaced by a simple
48 space
49 - whitespaces inside ``url()`` definitions are stripped
50 - Comments starting with an exclamation mark (``!``) can be kept optionally.
51 - All other comments and/or whitespace characters are replaced by a single
52 space.
53 - Multiple consecutive semicolons are reduced to one
54 - The last semicolon within a ruleset is stripped
55 - CSS Hacks supported:
56
57 - IE7 hack (``>/**/``)
58 - Mac-IE5 hack (``/*\\*/.../**/``)
59 - The boxmodelhack is supported naturally because it relies on valid CSS2
60 strings
61 - Between ``:first-line`` and the following comma or curly brace a space is
62 inserted. (apparently it's needed for IE6)
63 - Same for ``:first-letter``
64
65 rcssmin.c is a reimplementation of rcssmin.py in C and improves runtime up to
66 factor 100 or so (depending on the input). docs/BENCHMARKS in the source
67 distribution contains the details.
68
69 Both python 2 (>= 2.4) and python 3 are supported.
70
71 .. _YUI compressor: https://github.com/yui/yuicompressor/
72
73 .. _the rule list by Isaac Schlueter: https://github.com/isaacs/cssmin/
74 """
75 if __doc__:
76
77 __doc__ = __doc__.encode('ascii').decode('unicode_escape')
78 __author__ = r"Andr\xe9 Malo".encode('ascii').decode('unicode_escape')
79 __docformat__ = "restructuredtext en"
80 __license__ = "Apache License, Version 2.0"
81 __version__ = '1.0.4'
82 __all__ = ['cssmin']
83
84 import re as _re
85
86
88 """
89 Generate CSS minifier.
90
91 :Parameters:
92 `python_only` : ``bool``
93 Use only the python variant. If true, the c extension is not even
94 tried to be loaded. (tdi.c._tdi_rcssmin)
95
96 :Return: Minifier
97 :Rtype: ``callable``
98 """
99
100
101
102
103
104
105 if not python_only:
106 from tdi import c
107 rcssmin = c.load('rcssmin')
108 if rcssmin is not None:
109 return rcssmin.cssmin
110
111 nl = r'(?:[\n\f]|\r\n?)'
112 spacechar = r'[\r\n\f\040\t]'
113
114 unicoded = r'[0-9a-fA-F]{1,6}(?:[\040\n\t\f]|\r\n?)?'
115 escaped = r'[^\n\r\f0-9a-fA-F]'
116 escape = r'(?:\\(?:%(unicoded)s|%(escaped)s))' % locals()
117
118 nmchar = r'[^\000-\054\056\057\072-\100\133-\136\140\173-\177]'
119
120
121
122
123
124 comment = r'(?:/\*[^*]*\*+(?:[^/*][^*]*\*+)*/)'
125
126
127 _bang_comment = r'(?:/\*(!?)[^*]*\*+(?:[^/*][^*]*\*+)*/)'
128
129 string1 = \
130 r'(?:\047[^\047\\\r\n\f]*(?:\\[^\r\n\f][^\047\\\r\n\f]*)*\047)'
131 string2 = r'(?:"[^"\\\r\n\f]*(?:\\[^\r\n\f][^"\\\r\n\f]*)*")'
132 strings = r'(?:%s|%s)' % (string1, string2)
133
134 nl_string1 = \
135 r'(?:\047[^\047\\\r\n\f]*(?:\\(?:[^\r]|\r\n?)[^\047\\\r\n\f]*)*\047)'
136 nl_string2 = r'(?:"[^"\\\r\n\f]*(?:\\(?:[^\r]|\r\n?)[^"\\\r\n\f]*)*")'
137 nl_strings = r'(?:%s|%s)' % (nl_string1, nl_string2)
138
139 uri_nl_string1 = r'(?:\047[^\047\\]*(?:\\(?:[^\r]|\r\n?)[^\047\\]*)*\047)'
140 uri_nl_string2 = r'(?:"[^"\\]*(?:\\(?:[^\r]|\r\n?)[^"\\]*)*")'
141 uri_nl_strings = r'(?:%s|%s)' % (uri_nl_string1, uri_nl_string2)
142
143 nl_escaped = r'(?:\\%(nl)s)' % locals()
144
145 space = r'(?:%(spacechar)s|%(comment)s)' % locals()
146
147 ie7hack = r'(?:>/\*\*/)'
148
149 uri = (r'(?:'
150 r'(?:[^\000-\040"\047()\\\177]*'
151 r'(?:%(escape)s[^\000-\040"\047()\\\177]*)*)'
152 r'(?:'
153 r'(?:%(spacechar)s+|%(nl_escaped)s+)'
154 r'(?:'
155 r'(?:[^\000-\040"\047()\\\177]|%(escape)s|%(nl_escaped)s)'
156 r'[^\000-\040"\047()\\\177]*'
157 r'(?:%(escape)s[^\000-\040"\047()\\\177]*)*'
158 r')+'
159 r')*'
160 r')') % locals()
161
162 nl_unesc_sub = _re.compile(nl_escaped).sub
163
164 uri_space_sub = _re.compile((
165 r'(%(escape)s+)|%(spacechar)s+|%(nl_escaped)s+'
166 ) % locals()).sub
167 uri_space_subber = lambda m: m.groups()[0] or ''
168
169 space_sub_simple = _re.compile((
170 r'[\r\n\f\040\t;]+|(%(comment)s+)'
171 ) % locals()).sub
172 space_sub_banged = _re.compile((
173 r'[\r\n\f\040\t;]+|(%(_bang_comment)s+)'
174 ) % locals()).sub
175
176 post_esc_sub = _re.compile(r'[\r\n\f\t]+').sub
177
178 main_sub = _re.compile((
179 r'([^\\"\047u>@\r\n\f\040\t/;:{}]+)'
180 r'|(?<=[{}(=:>+[,!])(%(space)s+)'
181 r'|^(%(space)s+)'
182 r'|(%(space)s+)(?=(([:{});=>+\],!])|$)?)'
183 r'|;(%(space)s*(?:;%(space)s*)*)(?=(\})?)'
184 r'|(\{)'
185 r'|(\})'
186 r'|(%(strings)s)'
187 r'|(?<!%(nmchar)s)url\(%(spacechar)s*('
188 r'%(uri_nl_strings)s'
189 r'|%(uri)s'
190 r')%(spacechar)s*\)'
191 r'|(@(?:'
192 r'[mM][eE][dD][iI][aA]'
193 r'|[sS][uU][pP][pP][oO][rR][tT][sS]'
194 r'|[dD][oO][cC][uU][mM][eE][nN][tT]'
195 r'|(?:-(?:'
196 r'[wW][eE][bB][kK][iI][tT]|[mM][oO][zZ]|[oO]|[mM][sS]'
197 r')-)?'
198 r'[kK][eE][yY][fF][rR][aA][mM][eE][sS]'
199 r'))(?!%(nmchar)s)'
200 r'|(%(ie7hack)s)(%(space)s*)'
201 r'|(:[fF][iI][rR][sS][tT]-[lL]'
202 r'(?:[iI][nN][eE]|[eE][tT][tT][eE][rR]))'
203 r'(%(space)s*)(?=[{,])'
204 r'|(%(nl_strings)s)'
205 r'|(%(escape)s[^\\"\047u>@\r\n\f\040\t/;:{}]*)'
206 ) % locals()).sub
207
208
209
210 def main_subber(keep_bang_comments):
211 """ Make main subber """
212 in_macie5, in_rule, at_group = [0], [0], [0]
213
214 if keep_bang_comments:
215 space_sub = space_sub_banged
216 def space_subber(match):
217 """ Space|Comment subber """
218 if match.lastindex:
219 group1, group2 = match.group(1, 2)
220 if group2:
221 if group1.endswith(r'\*/'):
222 in_macie5[0] = 1
223 else:
224 in_macie5[0] = 0
225 return group1
226 elif group1:
227 if group1.endswith(r'\*/'):
228 if in_macie5[0]:
229 return ''
230 in_macie5[0] = 1
231 return r'/*\*/'
232 elif in_macie5[0]:
233 in_macie5[0] = 0
234 return '/**/'
235 return ''
236 else:
237 space_sub = space_sub_simple
238 def space_subber(match):
239 """ Space|Comment subber """
240 if match.lastindex:
241 if match.group(1).endswith(r'\*/'):
242 if in_macie5[0]:
243 return ''
244 in_macie5[0] = 1
245 return r'/*\*/'
246 elif in_macie5[0]:
247 in_macie5[0] = 0
248 return '/**/'
249 return ''
250
251 def fn_space_post(group):
252 """ space with token after """
253 if group(5) is None or (
254 group(6) == ':' and not in_rule[0] and not at_group[0]):
255 return ' ' + space_sub(space_subber, group(4))
256 return space_sub(space_subber, group(4))
257
258 def fn_semicolon(group):
259 """ ; handler """
260 return ';' + space_sub(space_subber, group(7))
261
262 def fn_semicolon2(group):
263 """ ; handler """
264 if in_rule[0]:
265 return space_sub(space_subber, group(7))
266 return ';' + space_sub(space_subber, group(7))
267
268 def fn_open(group):
269 """ { handler """
270
271 if at_group[0]:
272 at_group[0] -= 1
273 else:
274 in_rule[0] = 1
275 return '{'
276
277 def fn_close(group):
278 """ } handler """
279
280 in_rule[0] = 0
281 return '}'
282
283 def fn_at_group(group):
284 """ @xxx group handler """
285 at_group[0] += 1
286 return group(13)
287
288 def fn_ie7hack(group):
289 """ IE7 Hack handler """
290 if not in_rule[0] and not at_group[0]:
291 in_macie5[0] = 0
292 return group(14) + space_sub(space_subber, group(15))
293 return '>' + space_sub(space_subber, group(15))
294
295 table = (
296 None,
297 None,
298 None,
299 None,
300 fn_space_post,
301 fn_space_post,
302 fn_space_post,
303 fn_semicolon,
304 fn_semicolon2,
305 fn_open,
306 fn_close,
307 lambda g: g(11),
308 lambda g: 'url(%s)' % uri_space_sub(uri_space_subber, g(12)),
309
310 fn_at_group,
311 None,
312 fn_ie7hack,
313 None,
314 lambda g: g(16) + ' ' + space_sub(space_subber, g(17)),
315
316
317
318 lambda g: nl_unesc_sub('', g(18)),
319 lambda g: post_esc_sub(' ', g(19)),
320 )
321
322 def func(match):
323 """ Main subber """
324 idx, group = match.lastindex, match.group
325 if idx > 3:
326 return table[idx](group)
327
328
329 elif idx == 1:
330 return group(1)
331
332 return space_sub(space_subber, group(idx))
333
334 return func
335
336 def cssmin(style, keep_bang_comments=False):
337 """
338 Minify CSS.
339
340 :Parameters:
341 `style` : ``str``
342 CSS to minify
343
344 `keep_bang_comments` : ``bool``
345 Keep comments starting with an exclamation mark? (``/*!...*/``)
346
347 :Return: Minified style
348 :Rtype: ``str``
349 """
350 return main_sub(main_subber(keep_bang_comments), style)
351
352 return cssmin
353
354 cssmin = _make_cssmin()
355
356
357 if __name__ == '__main__':
359 """ Main """
360 import sys as _sys
361 keep_bang_comments = (
362 '-b' in _sys.argv[1:]
363 or '-bp' in _sys.argv[1:]
364 or '-pb' in _sys.argv[1:]
365 )
366 if '-p' in _sys.argv[1:] or '-bp' in _sys.argv[1:] \
367 or '-pb' in _sys.argv[1:]:
368 global cssmin
369 cssmin = _make_cssmin(python_only=True)
370 _sys.stdout.write(cssmin(
371 _sys.stdin.read(), keep_bang_comments=keep_bang_comments
372 ))
373 main()
374