File: css.go

package info (click to toggle)
golang-github-tdewolff-minify 2.20.37-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 39,388 kB
  • sloc: javascript: 394,644; xml: 25,649; ansic: 253; makefile: 108; python: 108; sh: 47
file content (1568 lines) | stat: -rw-r--r-- 50,564 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
// Package css minifies CSS3 following the specifications at http://www.w3.org/TR/css-syntax-3/.
package css

import (
	"bytes"
	"fmt"
	"io"
	"math"
	"sort"
	"strconv"
	"strings"

	"github.com/tdewolff/minify/v2"
	"github.com/tdewolff/parse/v2"
	"github.com/tdewolff/parse/v2/css"
	strconvParse "github.com/tdewolff/parse/v2/strconv"
)

var (
	spaceBytes        = []byte(" ")
	colonBytes        = []byte(":")
	semicolonBytes    = []byte(";")
	commaBytes        = []byte(",")
	leftBracketBytes  = []byte("{")
	rightBracketBytes = []byte("}")
	rightParenBytes   = []byte(")")
	urlBytes          = []byte("url(")
	varBytes          = []byte("var(")
	zeroBytes         = []byte("0")
	oneBytes          = []byte("1")
	transparentBytes  = []byte("transparent")
	blackBytes        = []byte("#0000")
	initialBytes      = []byte("initial")
	noneBytes         = []byte("none")
	autoBytes         = []byte("auto")
	leftBytes         = []byte("left")
	topBytes          = []byte("top")
	n400Bytes         = []byte("400")
	n700Bytes         = []byte("700")
	n50pBytes         = []byte("50%")
	n100pBytes        = []byte("100%")
	repeatXBytes      = []byte("repeat-x")
	repeatYBytes      = []byte("repeat-y")
	importantBytes    = []byte("!important")
	dataSchemeBytes   = []byte("data:")
)

type cssMinifier struct {
	m *minify.M
	w io.Writer
	p *css.Parser
	o *Minifier

	tokenBuffer []Token
	tokensLevel int
}

////////////////////////////////////////////////////////////////

// Minifier is a CSS minifier.
type Minifier struct {
	KeepCSS2     bool
	Precision    int // number of significant digits
	newPrecision int // precision for new numbers
	Inline       bool
}

// Minify minifies CSS data, it reads from r and writes to w.
func Minify(m *minify.M, w io.Writer, r io.Reader, params map[string]string) error {
	return (&Minifier{}).Minify(m, w, r, params)
}

// Token is a parsed token with extra information for functions.
type Token struct {
	css.TokenType
	Data       []byte
	Args       []Token // only filled for functions
	Fun, Ident Hash    // only filled for functions and identifiers respectively
}

func (t Token) String() string {
	if len(t.Args) == 0 {
		return t.TokenType.String() + "(" + string(t.Data) + ")"
	}

	sb := strings.Builder{}
	sb.Write(t.Data)
	for _, arg := range t.Args {
		sb.WriteString(arg.String())
	}
	sb.WriteByte(')')
	return sb.String()
}

// Equal returns true if both tokens are equal.
func (t Token) Equal(t2 Token) bool {
	if t.TokenType == t2.TokenType && bytes.Equal(t.Data, t2.Data) && len(t.Args) == len(t2.Args) {
		for i := 0; i < len(t.Args); i++ {
			if !t.Args[i].Equal(t2.Args[i]) {
				return false
			}
		}
		return true
	}
	return false
}

// IsZero return true if a dimension, percentage, or number token is zero.
func (t Token) IsZero() bool {
	// as each number is already minified, starting with a zero means it is zero
	return (t.TokenType == css.DimensionToken || t.TokenType == css.PercentageToken || t.TokenType == css.NumberToken) && t.Data[0] == '0'
}

// IsLength returns true if the token is a length.
func (t Token) IsLength() bool {
	if t.TokenType == css.DimensionToken {
		return true
	} else if t.TokenType == css.NumberToken && t.Data[0] == '0' {
		return true
	} else if t.TokenType == css.FunctionToken {
		fun := ToHash(t.Data[:len(t.Data)-1])
		if fun == Calc || fun == Min || fun == Max || fun == Clamp || fun == Attr || fun == Var || fun == Env {
			return true
		}
	}
	return false
}

// IsLengthPercentage returns true if the token is a length or percentage token.
func (t Token) IsLengthPercentage() bool {
	return t.TokenType == css.PercentageToken || t.IsLength()
}

////////////////////////////////////////////////////////////////

// Minify minifies CSS data, it reads from r and writes to w.
func (o *Minifier) Minify(m *minify.M, w io.Writer, r io.Reader, params map[string]string) error {
	tmp := &Minifier{}
	*tmp = *o
	o = tmp

	o.newPrecision = o.Precision
	if o.newPrecision <= 0 || 15 < o.newPrecision {
		o.newPrecision = 15 // minimum number of digits a double can represent exactly
	}
	if !o.Inline {
		o.Inline = params != nil && params["inline"] == "1"
	}

	z := parse.NewInput(r)
	defer z.Restore()

	c := &cssMinifier{
		m: m,
		w: w,
		p: css.NewParser(z, o.Inline),
		o: o,
	}
	c.minifyGrammar()

	if _, err := w.Write(nil); err != nil {
		return err
	}
	if c.p.Err() == io.EOF {
		return nil
	}
	return c.p.Err()
}

func (c *cssMinifier) minifyGrammar() {
	semicolonQueued := false
	for {
		gt, _, data := c.p.Next()
		switch gt {
		case css.ErrorGrammar:
			if c.p.HasParseError() {
				if semicolonQueued {
					c.w.Write(semicolonBytes)
				}

				// write out the offending declaration (but save the semicolon)
				vals := c.p.Values()
				if len(vals) > 0 && vals[len(vals)-1].TokenType == css.SemicolonToken {
					vals = vals[:len(vals)-1]
					semicolonQueued = true
				}
				for _, val := range vals {
					c.w.Write(val.Data)
				}
				continue
			}
			return
		case css.EndAtRuleGrammar, css.EndRulesetGrammar:
			c.w.Write(rightBracketBytes)
			semicolonQueued = false
			continue
		}

		if semicolonQueued {
			c.w.Write(semicolonBytes)
			semicolonQueued = false
		}

		switch gt {
		case css.AtRuleGrammar:
			c.w.Write(data)
			values := c.p.Values()
			if ToHash(data[1:]) == Import && len(values) == 2 && values[1].TokenType == css.URLToken && 4 < len(values[1].Data) && values[1].Data[len(values[1].Data)-1] == ')' {
				url := values[1].Data
				if url[4] != '"' && url[4] != '\'' {
					a := 4
					for parse.IsWhitespace(url[a]) || parse.IsNewline(url[a]) {
						a++
					}
					b := len(url) - 2
					for a < b && (parse.IsWhitespace(url[b]) || parse.IsNewline(url[b])) {
						b--
					}
					if a == b {
						url = url[:2]
					} else {
						url = url[a-1 : b+2]
					}
					url[0] = '"'
					url[len(url)-1] = '"'
				} else {
					url = url[4 : len(url)-1]
				}
				values[1].Data = url
			}
			for _, val := range values {
				c.w.Write(val.Data)
			}
			semicolonQueued = true
		case css.BeginAtRuleGrammar:
			c.w.Write(data)
			for _, val := range c.p.Values() {
				c.w.Write(val.Data)
			}
			c.w.Write(leftBracketBytes)
		case css.QualifiedRuleGrammar:
			c.minifySelectors(data, c.p.Values())
			c.w.Write(commaBytes)
		case css.BeginRulesetGrammar:
			c.minifySelectors(data, c.p.Values())
			c.w.Write(leftBracketBytes)
		case css.DeclarationGrammar:
			c.minifyDeclaration(data, c.p.Values())
			semicolonQueued = true
		case css.CustomPropertyGrammar:
			c.w.Write(data)
			c.w.Write(colonBytes)
			value := parse.TrimWhitespace(c.p.Values()[0].Data)
			if len(c.p.Values()[0].Data) != 0 && len(value) == 0 {
				value = spaceBytes
			}
			c.w.Write(value)
			semicolonQueued = true
		case css.CommentGrammar:
			if 5 < len(data) && data[1] == '*' && data[2] == '!' {
				c.w.Write(data[:3])
				comment := parse.TrimWhitespace(parse.ReplaceMultipleWhitespace(data[3 : len(data)-2]))
				c.w.Write(comment)
				c.w.Write(data[len(data)-2:])
			} else if 5 < len(data) && (data[2] == '#' || data[2] == '@') {
				c.w.Write(data) // sourceMappingURL
			}
		default:
			c.w.Write(data)
		}
	}
}

func (c *cssMinifier) minifySelectors(property []byte, values []css.Token) {
	inAttr := false
	isClass := false
	for _, val := range c.p.Values() {
		if !inAttr {
			if val.TokenType == css.IdentToken {
				if !isClass {
					parse.ToLower(val.Data)
				}
				isClass = false
			} else if val.TokenType == css.DelimToken && val.Data[0] == '.' {
				isClass = true
			} else if val.TokenType == css.LeftBracketToken {
				inAttr = true
			}
		} else {
			if val.TokenType == css.StringToken && len(val.Data) > 2 {
				s := val.Data[1 : len(val.Data)-1]
				if css.IsIdent(s) {
					c.w.Write(s)
					continue
				}
			} else if val.TokenType == css.RightBracketToken {
				inAttr = false
			} else if val.TokenType == css.IdentToken && len(val.Data) == 1 && (val.Data[0] == 'i' || val.Data[0] == 'I') {
				c.w.Write(spaceBytes)
			}
		}
		c.w.Write(val.Data)
	}
}

func (c *cssMinifier) parseFunction(values []css.Token) ([]Token, int) {
	i := 1
	level := 0
	args := []Token{}
	for ; i < len(values); i++ {
		tt := values[i].TokenType
		data := values[i].Data
		if tt == css.LeftParenthesisToken {
			level++
		} else if tt == css.RightParenthesisToken {
			if level == 0 {
				i++
				break
			}
			level--
		}
		if tt == css.FunctionToken {
			subArgs, di := c.parseFunction(values[i:])
			h := ToHash(parse.ToLower(parse.Copy(data[:len(data)-1]))) // TODO: use ToHashFold
			args = append(args, Token{tt, data, subArgs, h, 0})
			i += di - 1
		} else {
			var h Hash
			if tt == css.IdentToken {
				h = ToHash(parse.ToLower(parse.Copy(data))) // TODO: use ToHashFold
			}
			args = append(args, Token{tt, data, nil, 0, h})
		}
	}
	return args, i
}

func (c *cssMinifier) parseDeclaration(values []css.Token) []Token {
	// Check if this is a simple list of values separated by whitespace or commas, otherwise we'll not be processing
	prevSep := true
	tokens := c.tokenBuffer[:0]
	for i := 0; i < len(values); i++ {
		tt := values[i].TokenType
		data := values[i].Data
		if tt == css.LeftParenthesisToken || tt == css.LeftBraceToken || tt == css.LeftBracketToken ||
			tt == css.RightParenthesisToken || tt == css.RightBraceToken || tt == css.RightBracketToken {
			return nil
		}

		if !prevSep && tt != css.WhitespaceToken && tt != css.CommaToken && (tt != css.DelimToken || values[i].Data[0] != '/') {
			return nil
		}

		if tt == css.WhitespaceToken || tt == css.CommaToken || tt == css.DelimToken && values[i].Data[0] == '/' {
			if tt != css.WhitespaceToken {
				tokens = append(tokens, Token{tt, data, nil, 0, 0})
			}
			prevSep = true
		} else if tt == css.FunctionToken {
			args, di := c.parseFunction(values[i:])
			h := ToHash(parse.ToLower(parse.Copy(data[:len(data)-1]))) // TODO: use ToHashFold
			tokens = append(tokens, Token{tt, data, args, h, 0})
			prevSep = true
			i += di - 1
		} else {
			var h Hash
			if tt == css.IdentToken {
				h = ToHash(parse.ToLower(parse.Copy(data))) // TODO: use ToHashFold
			}
			tokens = append(tokens, Token{tt, data, nil, 0, h})
			prevSep = tt == css.URLToken
		}
	}
	c.tokenBuffer = tokens // update buffer size for memory reuse
	return tokens
}

func (c *cssMinifier) minifyDeclaration(property []byte, components []css.Token) {
	c.w.Write(property)
	c.w.Write(colonBytes)

	if len(components) == 0 {
		return
	}

	// Strip !important from the component list, this will be added later separately
	important := false
	if len(components) > 2 && components[len(components)-2].TokenType == css.DelimToken && components[len(components)-2].Data[0] == '!' && ToHash(components[len(components)-1].Data) == Important {
		components = components[:len(components)-2]
		important = true
	}

	prop := ToHash(property)
	values := c.parseDeclaration(components)

	// Do not process complex values (eg. containing blocks or is not alternated between whitespace/commas and flat values
	if values == nil {
		if prop == Filter && len(components) == 11 {
			if bytes.Equal(components[0].Data, []byte("progid")) &&
				components[1].TokenType == css.ColonToken &&
				bytes.Equal(components[2].Data, []byte("DXImageTransform")) &&
				components[3].Data[0] == '.' &&
				bytes.Equal(components[4].Data, []byte("Microsoft")) &&
				components[5].Data[0] == '.' &&
				bytes.Equal(components[6].Data, []byte("Alpha(")) &&
				bytes.Equal(parse.ToLower(components[7].Data), []byte("opacity")) &&
				components[8].Data[0] == '=' &&
				components[10].Data[0] == ')' {
				components = components[6:]
				components[0].Data = []byte("alpha(")
			}
		}

		for _, component := range components {
			c.w.Write(component.Data)
		}
		if important {
			c.w.Write(importantBytes)
		}
		return
	}

	values = c.minifyTokens(prop, 0, values)
	if 0 < len(values) {
		values = c.minifyProperty(prop, values)
	}
	c.writeDeclaration(values, important)
}

func (c *cssMinifier) writeFunction(args []Token) {
	for _, arg := range args {
		c.w.Write(arg.Data)
		if arg.TokenType == css.FunctionToken {
			c.writeFunction(arg.Args)
			c.w.Write(rightParenBytes)
		}
	}
}

func (c *cssMinifier) writeDeclaration(values []Token, important bool) {
	prevSep := true
	for _, value := range values {
		if !prevSep && value.TokenType != css.CommaToken && (value.TokenType != css.DelimToken || value.Data[0] != '/') {
			c.w.Write(spaceBytes)
		}

		c.w.Write(value.Data)
		if value.TokenType == css.FunctionToken {
			c.writeFunction(value.Args)
			c.w.Write(rightParenBytes)
		}

		if value.TokenType == css.CommaToken || value.TokenType == css.DelimToken && value.Data[0] == '/' || value.TokenType == css.FunctionToken || value.TokenType == css.URLToken {
			prevSep = true
		} else {
			prevSep = false
		}
	}

	if important {
		c.w.Write(importantBytes)
	}
}

func (c *cssMinifier) minifyTokens(prop Hash, fun Hash, values []Token) []Token {
	if 100 < c.tokensLevel+1 {
		return values
	}
	c.tokensLevel++

	for i, value := range values {
		tt := value.TokenType
		switch tt {
		case css.NumberToken:
			if prop == Z_Index || prop == Counter_Increment || prop == Counter_Reset || prop == Orphans || prop == Widows {
				break // integers
			}
			if c.o.KeepCSS2 {
				values[i].Data = minify.Decimal(values[i].Data, c.o.Precision) // don't use exponents
			} else {
				values[i].Data = minify.Number(values[i].Data, c.o.Precision)
			}
		case css.PercentageToken:
			n := len(values[i].Data) - 1
			if c.o.KeepCSS2 {
				values[i].Data = minify.Decimal(values[i].Data[:n], c.o.Precision) // don't use exponents
			} else {
				values[i].Data = minify.Number(values[i].Data[:n], c.o.Precision)
			}
			values[i].Data = append(values[i].Data, '%')
		case css.DimensionToken:
			var dim []byte
			values[i], dim = c.minifyDimension(values[i])
			if 1 < len(values[i].Data) && values[i].Data[0] == '0' && optionalZeroDimension[string(dim)] && prop != Flex && fun == 0 {
				// cut dimension for zero value, TODO: don't hardcode check for Flex and remove the dimension in minifyDimension
				values[i].Data = values[i].Data[:1]
			}
		case css.StringToken:
			values[i].Data = removeMarkupNewlines(values[i].Data)
		case css.URLToken:
			if 10 < len(values[i].Data) {
				uri := parse.TrimWhitespace(values[i].Data[4 : len(values[i].Data)-1])
				delim := byte('"')
				if 1 < len(uri) && (uri[0] == '\'' || uri[0] == '"') {
					delim = uri[0]
					uri = removeMarkupNewlines(uri)
					uri = uri[1 : len(uri)-1]
				}
				if 4 < len(uri) && parse.EqualFold(uri[:5], dataSchemeBytes) {
					uri = minify.DataURI(c.m, uri)
				}
				if css.IsURLUnquoted(uri) {
					values[i].Data = append(append(urlBytes, uri...), ')')
				} else {
					values[i].Data = append(append(append(urlBytes, delim), uri...), delim, ')')
				}
			}
		case css.FunctionToken:
			values[i].Args = c.minifyTokens(prop, values[i].Fun, values[i].Args)

			fun := values[i].Fun
			args := values[i].Args
			if fun == Rgb || fun == Rgba || fun == Hsl || fun == Hsla {
				valid := true
				vals := []float64{}
				for i, arg := range args {
					numeric := arg.TokenType == css.NumberToken || arg.TokenType == css.PercentageToken
					separator := arg.TokenType == css.CommaToken || i != 5 && arg.TokenType == css.WhitespaceToken || i == 5 && arg.TokenType == css.DelimToken && arg.Data[0] == '/'
					if i%2 == 0 && !numeric || i%2 == 1 && !separator {
						valid = false
						break
					} else if numeric {
						var d float64
						if arg.TokenType == css.PercentageToken {
							var err error
							d, err = strconv.ParseFloat(string(arg.Data[:len(arg.Data)-1]), 32) // can overflow
							if err != nil {
								valid = false
								break
							}
							d /= 100.0
							if d < minify.Epsilon {
								d = 0.0
							} else if 1.0-minify.Epsilon < d {
								d = 1.0
							}
						} else {
							var err error
							d, err = strconv.ParseFloat(string(arg.Data), 32) // can overflow
							if err != nil {
								valid = false
								break
							}
						}
						vals = append(vals, d)
					}
				}
				if !valid {
					break
				}

				a := 1.0
				if len(vals) == 4 {
					if vals[0] < minify.Epsilon && vals[1] < minify.Epsilon && vals[2] < minify.Epsilon && vals[3] < minify.Epsilon {
						values[i] = Token{css.IdentToken, transparentBytes, nil, 0, Transparent}
						break
					} else if 1.0-minify.Epsilon < vals[3] {
						vals = vals[:3]
						values[i].Args = values[i].Args[:len(values[i].Args)-2]
						if fun == Rgba || fun == Hsla {
							values[i].Data = values[i].Data[:len(values[i].Data)-1]
							values[i].Data[len(values[i].Data)-1] = '('
						}
					} else {
						a = vals[3]
					}
				}

				if a == 1.0 && (len(vals) == 3 || len(vals) == 4) { // only minify color if fully opaque
					if fun == Rgb || fun == Rgba {
						for j := 0; j < 3; j++ {
							if args[j*2].TokenType == css.NumberToken {
								vals[j] /= 255.0
								if vals[j] < minify.Epsilon {
									vals[j] = 0.0
								} else if 1.0-minify.Epsilon < vals[j] {
									vals[j] = 1.0
								}
							}
						}
						values[i] = rgbToToken(vals[0], vals[1], vals[2])
						break
					} else if fun == Hsl || fun == Hsla && args[0].TokenType == css.NumberToken && args[2].TokenType == css.PercentageToken && args[4].TokenType == css.PercentageToken {
						vals[0] /= 360.0
						_, vals[0] = math.Modf(vals[0])
						if vals[0] < 0.0 {
							vals[0] = 1.0 + vals[0]
						}
						r, g, b := css.HSL2RGB(vals[0], vals[1], vals[2])
						values[i] = rgbToToken(r, g, b)
						break
					}
				} else if len(vals) == 4 {
					args[6] = minifyNumberPercentage(args[6])
				}

				if 3 <= len(vals) && (fun == Rgb || fun == Rgba) {
					// 0%, 20%, 40%, 60%, 80% and 100% can be represented exactly as, 51, 102, 153, 204, and 255 respectively
					removePercentage := true
					for j := 0; j < 3; j++ {
						if args[j*2].TokenType != css.PercentageToken || 2.0*minify.Epsilon <= math.Mod(vals[j]+minify.Epsilon, 0.2) {
							removePercentage = false
							break
						}
					}
					if removePercentage {
						for j := 0; j < 3; j++ {
							args[j*2].TokenType = css.NumberToken
							if vals[j] < minify.Epsilon {
								args[j*2].Data = zeroBytes
							} else if math.Abs(vals[j]-0.2) < minify.Epsilon {
								args[j*2].Data = []byte("51")
							} else if math.Abs(vals[j]-0.4) < minify.Epsilon {
								args[j*2].Data = []byte("102")
							} else if math.Abs(vals[j]-0.6) < minify.Epsilon {
								args[j*2].Data = []byte("153")
							} else if math.Abs(vals[j]-0.8) < minify.Epsilon {
								args[j*2].Data = []byte("204")
							} else if math.Abs(vals[j]-1.0) < minify.Epsilon {
								args[j*2].Data = []byte("255")
							}
						}
					}
				}
			}
		}
	}
	c.tokensLevel--
	return values
}

func (c *cssMinifier) minifyProperty(prop Hash, values []Token) []Token {
	// limit maximum to prevent slow recursions (e.g. for background's append)
	if 100 < len(values) {
		return values
	}

	switch prop {
	case Font:
		if len(values) > 1 { // must contain atleast font-size and font-family
			// the font-families are separated by commas and are at the end of font
			// get index for last token before font family names
			i := len(values) - 1
			for j, value := range values[2:] {
				if value.TokenType == css.CommaToken {
					i = 2 + j - 1 // identifier before first comma is a font-family
					break
				}
			}
			i--

			// advance i while still at font-families when they contain spaces but no quotes
			for ; i > 0; i-- { // i cannot be 0, font-family must be prepended by font-size
				if values[i-1].TokenType == css.DelimToken && values[i-1].Data[0] == '/' {
					break
				} else if values[i].TokenType != css.IdentToken && values[i].TokenType != css.StringToken {
					break
				} else if h := values[i].Ident; h == Xx_Small || h == X_Small || h == Small || h == Medium || h == Large || h == X_Large || h == Xx_Large || h == Smaller || h == Larger || h == Inherit || h == Initial || h == Unset {
					// inherit, initial and unset are followed by an IdentToken/StringToken, so must be for font-size
					break
				}
			}

			// font-family minified in place
			values = append(values[:i+1], c.minifyProperty(Font_Family, values[i+1:])...)

			// fix for IE9, IE10, IE11: font name starting with `-` is not recognized
			if values[i+1].Data[0] == '-' {
				v := make([]byte, len(values[i+1].Data)+2)
				v[0] = '\''
				copy(v[1:], values[i+1].Data)
				v[len(v)-1] = '\''
				values[i+1].Data = v
			}

			if i > 0 {
				// line-height
				if i > 1 && values[i-1].TokenType == css.DelimToken && values[i-1].Data[0] == '/' {
					if values[i].Ident == Normal {
						values = append(values[:i-1], values[i+1:]...)
					}
					i -= 2
				}

				// font-size
				i--

				for ; i > -1; i-- {
					if values[i].Ident == Normal {
						values = append(values[:i], values[i+1:]...)
					} else if values[i].Ident == Bold {
						values[i].TokenType = css.NumberToken
						values[i].Data = n700Bytes
					} else if values[i].TokenType == css.NumberToken && bytes.Equal(values[i].Data, n400Bytes) {
						values = append(values[:i], values[i+1:]...)
					}
				}
			}
		}
	case Font_Family:
		for i, value := range values {
			if value.TokenType == css.StringToken && 2 < len(value.Data) {
				unquote := true
				parse.ToLower(value.Data)
				s := value.Data[1 : len(value.Data)-1]
				if 0 < len(s) {
					for _, split := range bytes.Split(s, spaceBytes) {
						// if len is zero, it contains two consecutive spaces
						if len(split) == 0 || !css.IsIdent(split) {
							unquote = false
							break
						}
					}
				}
				if unquote {
					values[i].Data = s
				}
			}
		}
	case Font_Weight:
		if values[0].Ident == Normal {
			values[0].TokenType = css.NumberToken
			values[0].Data = n400Bytes
		} else if values[0].Ident == Bold {
			values[0].TokenType = css.NumberToken
			values[0].Data = n700Bytes
		}
	case Url:
		for i := 0; i < len(values); i++ {
			if values[i].TokenType == css.FunctionToken && len(values[i].Args) == 1 {
				fun := values[i].Fun
				data := values[i].Args[0].Data
				if fun == Local && (data[0] == '\'' || data[0] == '"') {
					if css.IsURLUnquoted(data[1 : len(data)-1]) {
						data = data[1 : len(data)-1]
					}
					values[i].Args[0].Data = data
				}
			}
		}
	case Margin, Padding, Border_Width:
		switch len(values) {
		case 2:
			if values[0].Equal(values[1]) {
				values = values[:1]
			}
		case 3:
			if values[0].Equal(values[1]) && values[0].Equal(values[2]) {
				values = values[:1]
			} else if values[0].Equal(values[2]) {
				values = values[:2]
			}
		case 4:
			if values[0].Equal(values[1]) && values[0].Equal(values[2]) && values[0].Equal(values[3]) {
				values = values[:1]
			} else if values[0].Equal(values[2]) && values[1].Equal(values[3]) {
				values = values[:2]
			} else if values[1].Equal(values[3]) {
				values = values[:3]
			}
		}
	case Border, Border_Bottom, Border_Left, Border_Right, Border_Top:
		for i := 0; i < len(values); i++ {
			if values[i].Ident == None || values[i].Ident == Currentcolor || values[i].Ident == Medium {
				values = append(values[:i], values[i+1:]...)
				i--
			} else {
				values[i] = minifyColor(values[i])
			}
		}
		if len(values) == 0 {
			values = []Token{{css.IdentToken, noneBytes, nil, 0, None}}
		}
	case Outline:
		for i := 0; i < len(values); i++ {
			if values[i].Ident == Invert || values[i].Ident == None || values[i].Ident == Medium {
				values = append(values[:i], values[i+1:]...)
				i--
			} else {
				values[i] = minifyColor(values[i])
			}
		}
		if len(values) == 0 {
			values = []Token{{css.IdentToken, noneBytes, nil, 0, None}}
		}
	case Background:
		start := 0
		for end := 0; end <= len(values); end++ { // loop over comma-separated lists
			if end != len(values) && values[end].TokenType != css.CommaToken {
				continue
			} else if start == end {
				start++
				continue
			}

			// minify background-size and lowercase all identifiers
			for i := start; i < end; i++ {
				if values[i].TokenType == css.DelimToken && values[i].Data[0] == '/' {
					// background-size consists of either [<length-percentage> | auto | cover | contain] or [<length-percentage> | auto]{2}
					// we can only minify the latter
					if i+1 < end && (values[i+1].TokenType == css.NumberToken || values[i+1].IsLengthPercentage() || values[i+1].Ident == Auto) {
						if i+2 < end && (values[i+2].TokenType == css.NumberToken || values[i+2].IsLengthPercentage() || values[i+2].Ident == Auto) {
							sizeValues := c.minifyProperty(Background_Size, values[i+1:i+3])
							if len(sizeValues) == 1 && sizeValues[0].Ident == Auto {
								// remove background-size if it is '/ auto' after minifying the property
								values = append(values[:i], values[i+3:]...)
								end -= 3
								i--
							} else {
								values = append(values[:i+1], append(sizeValues, values[i+3:]...)...)
								end -= 2 - len(sizeValues)
								i += len(sizeValues) - 1
							}
						} else if values[i+1].Ident == Auto {
							// remove background-size if it is '/ auto'
							values = append(values[:i], values[i+2:]...)
							end -= 2
							i--
						}
					}
				}
			}

			// minify all other values
			iPaddingBox := -1 // position of background-origin that is padding-box
			for i := start; i < end; i++ {
				h := values[i].Ident
				values[i] = minifyColor(values[i])
				if values[i].TokenType == css.IdentToken {
					if i+1 < end && values[i+1].TokenType == css.IdentToken && (h == Space || h == Round || h == Repeat || h == No_Repeat) {
						if h2 := values[i+1].Ident; h2 == Space || h2 == Round || h2 == Repeat || h2 == No_Repeat {
							repeatValues := c.minifyProperty(Background_Repeat, values[i:i+2])
							if len(repeatValues) == 1 && repeatValues[0].Ident == Repeat {
								values = append(values[:i], values[i+2:]...)
								end -= 2
								i--
							} else {
								values = append(values[:i], append(repeatValues, values[i+2:]...)...)
								end -= 2 - len(repeatValues)
								i += len(repeatValues) - 1
							}
							continue
						}
					} else if h == None || h == Scroll || h == Transparent {
						values = append(values[:i], values[i+1:]...)
						end--
						i--
						continue
					} else if h == Border_Box || h == Padding_Box {
						if iPaddingBox == -1 && h == Padding_Box { // background-origin
							iPaddingBox = i
						} else if iPaddingBox != -1 && h == Border_Box { // background-clip
							values = append(values[:i], values[i+1:]...)
							values = append(values[:iPaddingBox], values[iPaddingBox+1:]...)
							end -= 2
							i -= 2
						}
						continue
					}
				} else if values[i].TokenType == css.HashToken && bytes.Equal(values[i].Data, blackBytes) {
					values = append(values[:i], values[i+1:]...)
					end--
					i--
					continue
				} else if values[i].TokenType == css.FunctionToken && bytes.Equal(values[i].Data, varBytes) {
					continue
				}

				// further minify background-position and background-size combination
				if values[i].TokenType == css.NumberToken || values[i].IsLengthPercentage() || h == Left || h == Right || h == Top || h == Bottom || h == Center {
					j := i + 1
					for ; j < len(values); j++ {
						if h := values[j].Ident; h == Left || h == Right || h == Top || h == Bottom || h == Center {
							continue
						} else if values[j].TokenType == css.NumberToken || values[j].IsLengthPercentage() {
							continue
						}
						break
					}

					positionValues := c.minifyProperty(Background_Position, values[i:j])
					hasSize := j < len(values) && values[j].TokenType == css.DelimToken && values[j].Data[0] == '/'
					if !hasSize && len(positionValues) == 2 && positionValues[0].IsZero() && positionValues[1].IsZero() {
						if end-start == 2 {
							values[i] = Token{css.NumberToken, zeroBytes, nil, 0, 0}
							values[i+1] = Token{css.NumberToken, zeroBytes, nil, 0, 0}
							i++
						} else {
							values = append(values[:i], values[j:]...)
							end -= j - i
							i--
						}
					} else {
						if len(positionValues) == j-i {
							for k, positionValue := range positionValues {
								values[i+k] = positionValue
							}
						} else {
							values = append(values[:i], append(positionValues, values[j:]...)...)
							end -= j - i - len(positionValues)
						}
						i += len(positionValues) - 1
					}
				}
			}

			if end-start == 0 {
				values = append(values[:start], append([]Token{{css.NumberToken, zeroBytes, nil, 0, 0}, {css.NumberToken, zeroBytes, nil, 0, 0}}, values[end:]...)...)
				end += 2
			}
			start = end + 1
		}
	case Background_Size:
		start := 0
		for end := 0; end <= len(values); end++ { // loop over comma-separated lists
			if end != len(values) && values[end].TokenType != css.CommaToken {
				continue
			} else if start == end {
				start++
				continue
			}

			if end-start == 2 && values[start+1].Ident == Auto {
				values = append(values[:start+1], values[start+2:]...)
				end--
			}
			start = end + 1
		}
	case Background_Repeat:
		start := 0
		for end := 0; end <= len(values); end++ { // loop over comma-separated lists
			if end != len(values) && values[end].TokenType != css.CommaToken {
				continue
			} else if start == end {
				start++
				continue
			}

			if end-start == 2 && values[start].TokenType == css.IdentToken && values[start+1].TokenType == css.IdentToken {
				if values[start].Ident == values[start+1].Ident {
					values = append(values[:start+1], values[start+2:]...)
					end--
				} else if values[start].Ident == Repeat && values[start+1].Ident == No_Repeat {
					values[start].Data = repeatXBytes
					values[start].Ident = Repeat_X
					values = append(values[:start+1], values[start+2:]...)
					end--
				} else if values[start].Ident == No_Repeat && values[start+1].Ident == Repeat {
					values[start].Data = repeatYBytes
					values[start].Ident = Repeat_Y
					values = append(values[:start+1], values[start+2:]...)
					end--
				}
			}
			start = end + 1
		}
	case Background_Position:
		start := 0
		for end := 0; end <= len(values); end++ { // loop over comma-separated lists
			if end != len(values) && values[end].TokenType != css.CommaToken {
				continue
			} else if start == end {
				start++
				continue
			}

			if end-start == 3 || end-start == 4 {
				// remove zero offsets
				for _, i := range []int{end - start - 1, start + 1} {
					if 2 < end-start && values[i].IsZero() {
						values = append(values[:i], values[i+1:]...)
						end--
					}
				}

				j := start + 1 // position of second set of horizontal/vertical values
				if 2 < end-start && values[start+2].TokenType == css.IdentToken {
					j = start + 2
				}

				b := make([]byte, 0, 4)
				offsets := make([]Token, 2)
				for _, i := range []int{j, start} {
					if i+1 < end && i+1 != j {
						if values[i+1].TokenType == css.PercentageToken {
							// change right or bottom with percentage offset to left or top respectively
							if values[i].Ident == Right || values[i].Ident == Bottom {
								n, _ := strconvParse.ParseInt(values[i+1].Data[:len(values[i+1].Data)-1])
								b = strconv.AppendInt(b[:0], 100-n, 10)
								b = append(b, '%')
								values[i+1].Data = b
								if values[i].Ident == Right {
									values[i].Data = leftBytes
									values[i].Ident = Left
								} else {
									values[i].Data = topBytes
									values[i].Ident = Top
								}
							}
						}
						if values[i].Ident == Left {
							offsets[0] = values[i+1]
						} else if values[i].Ident == Top {
							offsets[1] = values[i+1]
						}
					} else if values[i].Ident == Left {
						offsets[0] = Token{css.NumberToken, zeroBytes, nil, 0, 0}
					} else if values[i].Ident == Top {
						offsets[1] = Token{css.NumberToken, zeroBytes, nil, 0, 0}
					} else if values[i].Ident == Right {
						offsets[0] = Token{css.PercentageToken, n100pBytes, nil, 0, 0}
						values[i].Ident = Left
					} else if values[i].Ident == Bottom {
						offsets[1] = Token{css.PercentageToken, n100pBytes, nil, 0, 0}
						values[i].Ident = Top
					}
				}

				if values[start].Ident == Center || values[j].Ident == Center {
					if values[start].Ident == Left || values[j].Ident == Left {
						offsets = offsets[:1]
					} else if values[start].Ident == Top || values[j].Ident == Top {
						offsets[0] = Token{css.NumberToken, n50pBytes, nil, 0, 0}
					}
				}

				if offsets[0].Data != nil && (len(offsets) == 1 || offsets[1].Data != nil) {
					values = append(append(values[:start], offsets...), values[end:]...)
					end -= end - start - len(offsets)
				}
			}
			// removing zero offsets in the previous loop might make it eligible for the next loop
			if end-start == 1 || end-start == 2 {
				if end-start == 1 && (values[start].Ident == Top || values[start].Ident == Bottom) {
					// we can't make this smaller, and converting to a number will break it
					// (https://github.com/tdewolff/minify/issues/221#issuecomment-415419918)
					break
				}

				if end-start == 2 && (values[start].Ident == Top || values[start].Ident == Bottom || values[start+1].Ident == Left || values[start+1].Ident == Right) {
					// if it's a vertical position keyword, swap it with the next element
					// since otherwise converted number positions won't be valid anymore
					// (https://github.com/tdewolff/minify/issues/221#issue-353067229)
					values[start], values[start+1] = values[start+1], values[start]
				}

				// transform keywords to lengths|percentages
				for i := start; i < end; i++ {
					if values[i].TokenType == css.IdentToken {
						if values[i].Ident == Left || values[i].Ident == Top {
							values[i].TokenType = css.NumberToken
							values[i].Data = zeroBytes
							values[i].Ident = 0
						} else if values[i].Ident == Right || values[i].Ident == Bottom {
							values[i].TokenType = css.PercentageToken
							values[i].Data = n100pBytes
							values[i].Ident = 0
						} else if values[i].Ident == Center {
							if i == start {
								values[i].TokenType = css.PercentageToken
								values[i].Data = n50pBytes
								values[i].Ident = 0
							} else {
								values = append(values[:start+1], values[start+2:]...)
								end--
							}
						}
					} else if i == start+1 && values[i].TokenType == css.PercentageToken && bytes.Equal(values[i].Data, n50pBytes) {
						values = append(values[:start+1], values[start+2:]...)
						end--
					} else if values[i].TokenType == css.PercentageToken && values[i].Data[0] == '0' {
						values[i].TokenType = css.NumberToken
						values[i].Data = zeroBytes
						values[i].Ident = 0
					}
				}
			}
			start = end + 1
		}
	case Box_Shadow:
		start := 0
		for end := 0; end <= len(values); end++ { // loop over comma-separated lists
			if end != len(values) && values[end].TokenType != css.CommaToken {
				continue
			} else if start == end {
				start++
				continue
			}

			if end-start == 1 && values[start].Ident == Initial {
				values[start].Ident = None
				values[start].Data = noneBytes
			} else {
				numbers := []int{}
				for i := start; i < end; i++ {
					if values[i].IsLength() {
						numbers = append(numbers, i)
					}
				}
				if len(numbers) == 4 && values[numbers[3]].IsZero() {
					values = append(values[:numbers[3]], values[numbers[3]+1:]...)
					numbers = numbers[:3]
					end--
				}
				if len(numbers) == 3 && values[numbers[2]].IsZero() {
					values = append(values[:numbers[2]], values[numbers[2]+1:]...)
					end--
				}
			}
			start = end + 1
		}
	case Ms_Filter:
		alpha := []byte("progid:DXImageTransform.Microsoft.Alpha(Opacity=")
		if values[0].TokenType == css.StringToken && 2 < len(values[0].Data) && bytes.HasPrefix(values[0].Data[1:len(values[0].Data)-1], alpha) {
			values[0].Data = append(append([]byte{values[0].Data[0]}, []byte("alpha(opacity=")...), values[0].Data[1+len(alpha):]...)
		}
	case Color:
		values[0] = minifyColor(values[0])
	case Background_Color:
		values[0] = minifyColor(values[0])
		if !c.o.KeepCSS2 {
			if values[0].Ident == Transparent {
				values[0].Data = initialBytes
				values[0].Ident = Initial
			}
		}
	case Border_Color:
		sameValues := true
		for i := range values {
			if values[i].Ident == Currentcolor {
				values[i].Data = initialBytes
				values[i].Ident = Initial
			} else {
				values[i] = minifyColor(values[i])
			}
			if 0 < i && sameValues && !values[0].Equal(values[i]) {
				sameValues = false
			}
		}
		if sameValues {
			values = values[:1]
		}
	case Border_Left_Color, Border_Right_Color, Border_Top_Color, Border_Bottom_Color, Text_Decoration_Color, Text_Emphasis_Color:
		if values[0].Ident == Currentcolor {
			values[0].Data = initialBytes
			values[0].Ident = Initial
		} else {
			values[0] = minifyColor(values[0])
		}
	case Caret_Color, Outline_Color, Fill, Stroke:
		values[0] = minifyColor(values[0])
	case Column_Rule:
		for i := 0; i < len(values); i++ {
			if values[i].Ident == Currentcolor || values[i].Ident == None || values[i].Ident == Medium {
				values = append(values[:i], values[i+1:]...)
				i--
			} else {
				values[i] = minifyColor(values[i])
			}
		}
		if len(values) == 0 {
			values = []Token{{css.IdentToken, noneBytes, nil, 0, None}}
		}
	case Text_Shadow:
		// TODO: minify better (can be comma separated list)
		for i := 0; i < len(values); i++ {
			values[i] = minifyColor(values[i])
		}
	case Text_Decoration:
		for i := 0; i < len(values); i++ {
			if values[i].Ident == Currentcolor || values[i].Ident == None || values[i].Ident == Solid {
				values = append(values[:i], values[i+1:]...)
				i--
			} else {
				values[i] = minifyColor(values[i])
			}
		}
		if len(values) == 0 {
			values = []Token{{css.IdentToken, noneBytes, nil, 0, None}}
		}
	case Text_Emphasis:
		for i := 0; i < len(values); i++ {
			if values[i].Ident == Currentcolor || values[i].Ident == None {
				values = append(values[:i], values[i+1:]...)
				i--
			} else {
				values[i] = minifyColor(values[i])
			}
		}
		if len(values) == 0 {
			values = []Token{{css.IdentToken, noneBytes, nil, 0, None}}
		}
	case Flex:
		if len(values) == 2 && values[0].TokenType == css.NumberToken {
			if values[1].TokenType != css.NumberToken && values[1].IsZero() {
				values = values[:1] // remove <flex-basis> if it is zero
			}
		} else if len(values) == 3 && values[0].TokenType == css.NumberToken && values[1].TokenType == css.NumberToken {
			if len(values[0].Data) == 1 && len(values[1].Data) == 1 {
				if values[2].Ident == Auto {
					if values[0].Data[0] == '0' && values[1].Data[0] == '1' {
						values = values[:1]
						values[0].TokenType = css.IdentToken
						values[0].Data = initialBytes
						values[0].Ident = Initial
					} else if values[0].Data[0] == '1' && values[1].Data[0] == '1' {
						values = values[:1]
						values[0].TokenType = css.IdentToken
						values[0].Data = autoBytes
						values[0].Ident = Auto
					} else if values[0].Data[0] == '0' && values[1].Data[0] == '0' {
						values = values[:1]
						values[0].TokenType = css.IdentToken
						values[0].Data = noneBytes
						values[0].Ident = None
					}
				} else if values[1].Data[0] == '1' && values[2].IsZero() {
					values = values[:1] // remove <flex-shrink> and <flex-basis> if they are 1 and 0 respectively
				} else if values[2].IsZero() {
					values = values[:2] // remove auto to write 2-value syntax of <flex-grow> <flex-shrink>
				} else {
					values[2] = minifyLengthPercentage(values[2])
				}
			}
		}
	case Flex_Basis:
		if values[0].Ident == Initial {
			values[0].Data = autoBytes
			values[0].Ident = Auto
		} else {
			values[0] = minifyLengthPercentage(values[0])
		}
	case Order, Flex_Grow:
		if values[0].Ident == Initial {
			values[0].TokenType = css.NumberToken
			values[0].Data = zeroBytes
			values[0].Ident = 0
		}
	case Flex_Shrink:
		if values[0].Ident == Initial {
			values[0].TokenType = css.NumberToken
			values[0].Data = oneBytes
			values[0].Ident = 0
		}
	case Unicode_Range:
		ranges := [][2]int{}
		for _, value := range values {
			if value.TokenType == css.CommaToken {
				continue
			} else if value.TokenType != css.UnicodeRangeToken {
				return values
			}

			i := 2
			iWildcard := 0
			start := 0
			for i < len(value.Data) && value.Data[i] != '-' {
				start *= 16
				if '0' <= value.Data[i] && value.Data[i] <= '9' {
					start += int(value.Data[i] - '0')
				} else if 'a' <= value.Data[i]|32 && value.Data[i]|32 <= 'f' {
					start += int(value.Data[i]|32-'a') + 10
				} else if iWildcard == 0 && value.Data[i] == '?' {
					iWildcard = i
				}
				i++
			}
			end := start
			if iWildcard != 0 {
				end = start + int(math.Pow(16.0, float64(len(value.Data)-iWildcard))) - 1
			} else if i < len(value.Data) && value.Data[i] == '-' {
				i++
				end = 0
				for i < len(value.Data) {
					end *= 16
					if '0' <= value.Data[i] && value.Data[i] <= '9' {
						end += int(value.Data[i] - '0')
					} else if 'a' <= value.Data[i]|32 && value.Data[i]|32 <= 'f' {
						end += int(value.Data[i]|32-'a') + 10
					}
					i++
				}
				if end <= start {
					end = start
				}
			}
			ranges = append(ranges, [2]int{start, end})
		}

		// sort and remove overlapping ranges
		sort.Slice(ranges, func(i, j int) bool { return ranges[i][0] < ranges[j][0] })
		for i := 0; i < len(ranges)-1; i++ {
			if ranges[i+1][1] <= ranges[i][1] {
				// next range is fully contained in the current range
				ranges = append(ranges[:i+1], ranges[i+2:]...)
			} else if ranges[i+1][0] <= ranges[i][1]+1 {
				// next range is partially covering the current range
				ranges[i][1] = ranges[i+1][1]
				ranges = append(ranges[:i+1], ranges[i+2:]...)
			}
		}

		values = values[:0]
		for i, ran := range ranges {
			if i != 0 {
				values = append(values, Token{css.CommaToken, commaBytes, nil, 0, None})
			}
			if ran[0] == ran[1] {
				urange := []byte(fmt.Sprintf("U+%X", ran[0]))
				values = append(values, Token{css.UnicodeRangeToken, urange, nil, 0, None})
			} else if ran[0] == 0 && ran[1] == 0x10FFFF {
				values = append(values, Token{css.IdentToken, initialBytes, nil, 0, None})
			} else {
				k := 0
				for k < 6 && (ran[0]>>(k*4))&0xF == 0 && (ran[1]>>(k*4))&0xF == 0xF {
					k++
				}
				wildcards := k
				for k < 6 {
					if (ran[0]>>(k*4))&0xF != (ran[1]>>(k*4))&0xF {
						wildcards = 0
						break
					}
					k++
				}
				var urange []byte
				if wildcards != 0 {
					if ran[0]>>(wildcards*4) == 0 {
						urange = []byte(fmt.Sprintf("U+%s", strings.Repeat("?", wildcards)))
					} else {
						urange = []byte(fmt.Sprintf("U+%X%s", ran[0]>>(wildcards*4), strings.Repeat("?", wildcards)))
					}
				} else {
					urange = []byte(fmt.Sprintf("U+%X-%X", ran[0], ran[1]))
				}
				values = append(values, Token{css.UnicodeRangeToken, urange, nil, 0, None})
			}
		}
	}
	return values
}

func minifyColor(value Token) Token {
	data := value.Data
	if value.TokenType == css.IdentToken {
		if hexValue, ok := ShortenColorName[value.Ident]; ok {
			value.TokenType = css.HashToken
			value.Data = hexValue
		}
	} else if value.TokenType == css.HashToken {
		parse.ToLower(data[1:])
		if len(data) == 9 && data[7] == data[8] {
			if data[7] == 'f' {
				data = data[:7]
			} else if data[7] == '0' {
				data = blackBytes
			}
		}
		if ident, ok := ShortenColorHex[string(data)]; ok {
			value.TokenType = css.IdentToken
			data = ident
		} else if len(data) == 7 && data[1] == data[2] && data[3] == data[4] && data[5] == data[6] {
			value.TokenType = css.HashToken
			data[2] = data[3]
			data[3] = data[5]
			data = data[:4]
		} else if len(data) == 9 && data[1] == data[2] && data[3] == data[4] && data[5] == data[6] && data[7] == data[8] {
			// from working draft Color Module Level 4
			value.TokenType = css.HashToken
			data[2] = data[3]
			data[3] = data[5]
			data[4] = data[7]
			data = data[:5]
		}
		value.Data = data
	}
	return value
}

func minifyNumberPercentage(value Token) Token {
	// assumes input already minified
	if value.TokenType == css.PercentageToken && len(value.Data) == 3 && value.Data[len(value.Data)-2] == '0' {
		value.Data[1] = value.Data[0]
		value.Data[0] = '.'
		value.Data = value.Data[:2]
		value.TokenType = css.NumberToken
	} else if value.TokenType == css.NumberToken && 2 < len(value.Data) && value.Data[0] == '.' && value.Data[1] == '0' {
		if value.Data[2] == '0' {
			value.Data[0] = '.'
			copy(value.Data[1:], value.Data[3:])
			value.Data[len(value.Data)-2] = '%'
			value.Data = value.Data[:len(value.Data)-1]
			value.TokenType = css.PercentageToken
		} else if len(value.Data) == 3 {
			value.Data[0] = value.Data[2]
			value.Data[1] = '%'
			value.Data = value.Data[:2]
			value.TokenType = css.PercentageToken
		}
	}
	return value
}

func minifyLengthPercentage(value Token) Token {
	if value.TokenType != css.NumberToken && value.IsZero() {
		value.TokenType = css.NumberToken
		value.Data = value.Data[:1] // remove dimension for zero value
	}
	return value
}

func (c *cssMinifier) minifyDimension(value Token) (Token, []byte) {
	// TODO: add check for zero value
	var dim []byte
	if value.TokenType == css.DimensionToken {
		n := len(value.Data)
		for 0 < n {
			lower := 'a' <= value.Data[n-1] && value.Data[n-1] <= 'z'
			upper := 'A' <= value.Data[n-1] && value.Data[n-1] <= 'Z'
			if !lower && !upper {
				break
			} else if upper {
				value.Data[n-1] = value.Data[n-1] + ('a' - 'A')
			}
			n--
		}

		num := value.Data[:n]
		if c.o.KeepCSS2 {
			num = minify.Decimal(num, c.o.Precision) // don't use exponents
		} else {
			num = minify.Number(num, c.o.Precision)
		}
		dim = value.Data[n:]
		value.Data = append(num, dim...)
	}
	return value, dim

	// TODO: optimize
	//if value.TokenType == css.DimensionToken {
	//	// TODO: reverse; parse dim not number
	//	n := parse.Number(value.Data)
	//	num := value.Data[:n]
	//	dim = value.Data[n:]
	//	parse.ToLower(dim)

	//	if c.o.KeepCSS2 {
	//		num = minify.Decimal(num, c.o.Precision) // don't use exponents
	//	} else {
	//		num = minify.Number(num, c.o.Precision)
	//	}

	//	// change dimension to compress number
	//	h := ToHash(dim)
	//	if h == Px || h == Pt || h == Pc || h == In || h == Mm || h == Cm || h == Q || h == Deg || h == Grad || h == Rad || h == Turn || h == S || h == Ms || h == Hz || h == Khz || h == Dpi || h == Dpcm || h == Dppx {
	//		d, _ := strconv.ParseFloat(string(num), 64) // can never fail
	//		var dimensions []Hash
	//		var multipliers []float64
	//		switch h {
	//		case Px:
	//			//dimensions = []Hash{In, Cm, Pc, Mm, Pt, Q}
	//			//multipliers = []float64{0.010416666666666667, 0.026458333333333333, 0.0625, 0.26458333333333333, 0.75, 1.0583333333333333}
	//			dimensions = []Hash{In, Pc, Pt}
	//			multipliers = []float64{0.010416666666666667, 0.0625, 0.75}
	//		case Pt:
	//			//dimensions = []Hash{In, Cm, Pc, Mm, Px, Q}
	//			//multipliers = []float64{0.013888888888888889, 0.035277777777777778, 0.083333333333333333, 0.35277777777777778, 1.3333333333333333, 1.4111111111111111}
	//			dimensions = []Hash{In, Pc, Px}
	//			multipliers = []float64{0.013888888888888889, 0.083333333333333333, 1.3333333333333333}
	//		case Pc:
	//			//dimensions = []Hash{In, Cm, Mm, Pt, Px, Q}
	//			//multipliers = []float64{0.16666666666666667, 0.42333333333333333, 4.2333333333333333, 12.0, 16.0, 16.933333333333333}
	//			dimensions = []Hash{In, Pt, Px}
	//			multipliers = []float64{0.16666666666666667, 12.0, 16.0}
	//		case In:
	//			//dimensions = []Hash{Cm, Pc, Mm, Pt, Px, Q}
	//			//multipliers = []float64{2.54, 6.0, 25.4, 72.0, 96.0, 101.6}
	//			dimensions = []Hash{Pc, Pt, Px}
	//			multipliers = []float64{6.0, 72.0, 96.0}
	//		case Cm:
	//			//dimensions = []Hash{In, Pc, Mm, Pt, Px, Q}
	//			//multipliers = []float64{0.39370078740157480, 2.3622047244094488, 10.0, 28.346456692913386, 37.795275590551181, 40.0}
	//			dimensions = []Hash{Mm, Q}
	//			multipliers = []float64{10.0, 40.0}
	//		case Mm:
	//			//dimensions = []Hash{In, Cm, Pc, Pt, Px, Q}
	//			//multipliers = []float64{0.039370078740157480, 0.1, 0.23622047244094488, 2.8346456692913386, 3.7795275590551181, 4.0}
	//			dimensions = []Hash{Cm, Q}
	//			multipliers = []float64{0.1, 4.0}
	//		case Q:
	//			//dimensions = []Hash{In, Cm, Pc, Pt, Px} // Q to mm is never smaller
	//			//multipliers = []float64{0.0098425196850393701, 0.025, 0.059055118110236220, 0.70866141732283465, 0.94488188976377953}
	//			dimensions = []Hash{Cm} // Q to mm is never smaller
	//			multipliers = []float64{0.025}
	//		case Deg:
	//			//dimensions = []Hash{Turn, Rad, Grad}
	//			//multipliers = []float64{0.0027777777777777778, 0.017453292519943296, 1.1111111111111111}
	//			dimensions = []Hash{Turn, Grad}
	//			multipliers = []float64{0.0027777777777777778, 1.1111111111111111}
	//		case Grad:
	//			//dimensions = []Hash{Turn, Rad, Deg}
	//			//multipliers = []float64{0.0025, 0.015707963267948966, 0.9}
	//			dimensions = []Hash{Turn, Deg}
	//			multipliers = []float64{0.0025, 0.9}
	//		case Turn:
	//			//dimensions = []Hash{Rad, Deg, Grad}
	//			//multipliers = []float64{6.2831853071795865, 360.0, 400.0}
	//			dimensions = []Hash{Deg, Grad}
	//			multipliers = []float64{360.0, 400.0}
	//		case Rad:
	//			//dimensions = []Hash{Turn, Deg, Grad}
	//			//multipliers = []float64{0.15915494309189534, 57.295779513082321, 63.661977236758134}
	//		case S:
	//			dimensions = []Hash{Ms}
	//			multipliers = []float64{1000.0}
	//		case Ms:
	//			dimensions = []Hash{S}
	//			multipliers = []float64{0.001}
	//		case Hz:
	//			dimensions = []Hash{Khz}
	//			multipliers = []float64{0.001}
	//		case Khz:
	//			dimensions = []Hash{Hz}
	//			multipliers = []float64{1000.0}
	//		case Dpi:
	//			dimensions = []Hash{Dppx, Dpcm}
	//			multipliers = []float64{0.010416666666666667, 0.39370078740157480}
	//		case Dpcm:
	//			//dimensions = []Hash{Dppx, Dpi}
	//			//multipliers = []float64{0.026458333333333333, 2.54}
	//			dimensions = []Hash{Dpi}
	//			multipliers = []float64{2.54}
	//		case Dppx:
	//			//dimensions = []Hash{Dpcm, Dpi}
	//			//multipliers = []float64{37.795275590551181, 96.0}
	//			dimensions = []Hash{Dpi}
	//			multipliers = []float64{96.0}
	//		}
	//		for i := range dimensions {
	//			if dimensions[i] != h { //&& (d < 1.0) == (multipliers[i] > 1.0) {
	//				b, _ := strconvParse.AppendFloat([]byte{}, d*multipliers[i], -1)
	//				if c.o.KeepCSS2 {
	//					b = minify.Decimal(b, c.o.newPrecision) // don't use exponents
	//				} else {
	//					b = minify.Number(b, c.o.newPrecision)
	//				}
	//				newDim := []byte(dimensions[i].String())
	//				if len(b)+len(newDim) < len(num)+len(dim) {
	//					num = b
	//					dim = newDim
	//				}
	//			}
	//		}
	//	}
	//	value.Data = append(num, dim...)
	//}
	//return value, dim
}