aboutsummaryrefslogtreecommitdiff
path: root/thcolor/_color.py
blob: 828ab2124e5c8265e77cfab177c728e6456ed9d0 (plain)
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
#!/usr/bin/env python3
#******************************************************************************
# Copyright (C) 2019 Thomas "Cakeisalie5" Touhey <thomas@touhey.fr>
# This file is part of the thcolor project, which is MIT-licensed.
#******************************************************************************
""" HTML/CSS like color parsing, mainly for the `[color]` tag.
	Defines the `get_color()` function which returns an rgba value. """

from enum import Enum as _Enum
from warnings import warn as _warn

_gg_no_re = False

try:
	import regex as _re
except ImportError:
	_warn("could not import regex, text parsing is disabled.",
		RuntimeWarning)
	_gg_no_re = True

from ._ref import Reference as _Reference
from ._angle import Angle as _Angle
from ._sys import (hls_to_rgb as _hls_to_rgb, rgb_to_hls as _rgb_to_hls,
	rgb_to_hwb as _rgb_to_hwb, hwb_to_rgb as _hwb_to_rgb,
	rgb_to_cmyk as _rgb_to_cmyk, cmyk_to_rgb as _cmyk_to_rgb,
	netscape_color as _netscape_color)
from ._exc import (\
	ColorExpressionDecodingError as _ColorExpressionDecodingError,
	NotEnoughArgumentsError as _NotEnoughArgumentsError,
	TooManyArgumentsError as _TooManyArgumentsError,
	InvalidArgumentTypeError as _InvalidArgumentTypeError,
	InvalidArgumentValueError as _InvalidArgumentValueError)

__all__ = ["Color"]

# ---
# Decoding utilities.
# ---

_color_pattern = None

def _get_color_pattern():
	global _color_pattern

	if _color_pattern is None:
		if _gg_no_re:
			raise ImportError("text parsing is disabled until you install " \
				"the 'regex' module, e.g. via `pip install regex`.")

		_color_pattern = _re.compile(r"""
			(
				((?P<agl_val>-? ([0-9]+\.?|[0-9]*\.[0-9]+)) \s*
				 (?P<agl_typ>deg|grad|rad|turn))
			  | ((?P<per>[0-9]+(\.[0-9]*)? | \.[0-9]+) \s* \%)
			  |  (?P<num>[0-9]+(\.[0-9]*)? | \.[0-9]+)
			  |  (?P<ncol>[RYGCBM] [0-9]{0,2} (\.[0-9]*)?)
			  |  (\# (?P<hex>[0-9a-f]{3} | [0-9a-f]{4} | [0-9a-f]{6} | [0-9a-f]{8}))
			  |  ((?P<name>[a-z]([a-z0-9\s_-]*[a-z0-9_-])?)
				  ( \s* \( \s* (?P<arg> (?0)? ) \s* \) )?)
			)

			\s* ((?P<sep>[,/\s])+ \s* (?P<nextargs> (?0))?)?
		""", _re.VERBOSE | _re.I | _re.M)

	return _color_pattern

# ---
# Color initialization varargs utilities.
# ---

def _byte(name, value):
	try:
		assert value == int(value)
		assert 0 <= value < 256
	except (AssertionError, TypeError, ValueError):
		raise ValueError(f"{name} should be a byte between 0 and 255") \
			from None

	return value

def _percentage(name, value):
	try:
		assert value == float(value)
		assert 0.0 <= value <= 1.0
	except (AssertionError, TypeError, ValueError):
		raise ValueError(f"{name} should be a proportion between 0 " \
			"and 1.0") from None

	return round(value, 4)

def _hue(name, value):
	if isinstance(value, _Angle):
		pass
	else:
		try:
			value = _Angle(value)
		except:
			raise ValueError(f"{name} should be an Angle instance")

	return value

# ---
# Color class definition.
# ---

class Color:
	""" Class representing a color within thcolor. Its constructor depends
		on the first given argument, which represents the color type as one
		of the :class:`Color.Type` constants.

		.. function:: Color(Color.Type.RGB, red, green, blue, alpha = 1.0)

			Create a color using its red, green and blue components. Each is
			expressed as a byte value, from 0 (dark) to 255 (light).

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components.

		.. function:: Color(Color.Type.HSL, hue, saturation, lightness, """ \
			"""alpha = 1.0)

			Create a color using its hue, saturation and lightness components.
			The hue is represented by an :class:`Angle` object, and the
			saturation and lightness are values going from 0.0 to 1.0.

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components.

		.. function:: Color(Color.Type.HWB, hue, whiteness, blackness, """ \
			"""alpha = 1.0)

			Create a color using its hue, whiteness and blackness components.
			The hue is represented by an :class:`Angle` object, and the
			whiteness and lightness are values going from 0.0 to 1.0.

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components.

		.. function:: Color(Color.Type.CMYK, cyan, magenta, yellow, """ \
			"""black, alpha = 1.0)

			Create a color using its cyan, magenta, yellow and blackness
			components, which are all values going from 0.0 to 1.0.

			An alpha value going from 0.0 (invisible) to 1.0 (opaque) can be
			appended to the base components. """

	# Properties to work with:
	#
	# `_type`: the type as one of the `Color.Type` constants.
	# `_alpha`: alpha value.
	# `_r`, `_g`, `_b`: rgb components, as bytes.
	# `_hue`: hue for HSL and HWB notations.
	# `_sat`, `_lgt`: saturation and light for HSL.
	# `_wht`, `_blk`: whiteness and blackness for HWB.
	# `_cy`, `_ma`, `_ye`, `_bl`: CMYK components.

	class Type(_Enum):
		""" Class representing the type of a color, or how it is expressed.
			The following types are available:

			.. data:: INVALID

				An invalid color, for internal processing.

			.. data:: RGB

				A color expressed through its sRGB components: red, green
				and blue.

			.. data:: HSL

				A color expressed through its HSL components: hue, saturation
				and lightness.

			.. data:: HWB

				A color expressed through its HWB components: hue, whiteness
				and blackness.

			.. data:: CMYK

				A color expressed through its CMYK components: cyan, magenta,
				yellow and black.

			An alpha component can be added to every single one of these
			types, so it is not included in the type names. """

		INVALID = 0
		RGB     = 1
		HSL     = 2
		HWB     = 3
		CMYK    = 4

	def __init__(self, *args, **kwargs):
		self._type = Color.Type.INVALID
		self.set(*args, **kwargs)

	def __repr__(self):
		args = (('type', f'{self.__class__.__name__}.{str(self._type)}'),)
		if   self._type == Color.Type.RGB:
			args += (('red', repr(self._r)), ('green', repr(self._g)),
				('blue', repr(self._b)))
		elif self._type == Color.Type.HSL:
			args += (('hue', repr(self._hue)), ('saturation', repr(self._sat)),
				('lightness', repr(self._lgt)))
		elif self._type == Color.Type.HWB:
			args += (('hue', repr(self._hue)), ('whiteness', repr(self._wht)),
				('blackness', repr(self._blk)))
		elif self._type == Color.Type.CMYK:
			args += (('cyan', repr(self._cy)), ('magenta', repr(self._ma)),
				('yellow', repr(self._ye)), ('black', repr(self._bl)))

		args += (('alpha', self._alpha),)

		argtext = ', '.join(f'{key} = {value}' for key, value in args)
		return f"{self.__class__.__name__}({argtext})"

	def __eq__(self, other):
		if not isinstance(other, Color):
			return super().__eq__(other)

		if   other.type == Color.Type.INVALID:
			return self._type == Color.Type.INVALID
		elif other.type == Color.Type.HSL:
			return self.hsla() == other.hsla()
		elif other.type == Color.Type.HWB:
			return self.hwba() == other.hwba()

		return self.rgba() == other.rgba()

	# ---
	# Management methods.
	# ---

	def set(self, *args, **kwargs):
		""" Set the color using its constructor arguments and keyword
			arguments. """

		args = list(args)

		def _decode_varargs(*keys):
			# Check for each key.

			results = ()

			for names, convert_func, *value in keys:
				for name in names:
					if name in kwargs:
						if args:
							raise TypeError(f"{self.__class__.__name__}() " \
								f"got multiple values for argument {name}")

						raw_result = kwargs.pop(name)
						break
				else:
					name = names[0]
					if args:
						raw_result = args.pop(0)
					elif value:
						raw_result = value[0] if len(value) == 1 else value
					else:
						raise TypeError(f"{self.__class__.__name__}() " \
							"missing a required positional argument: " \
							f"{name}")

				result = convert_func(name, raw_result)
				results += (result,)

			# Check for keyword arguments for which keys are not in the set.

			if kwargs:
				raise TypeError(f"{next(iter(kwargs.keys()))} is an invalid " \
					f"keyword argument for type {type}")

			return results

		# ---
		# Main function body.
		# ---

		# Check for the type.

		if args:
			try:
				type = kwargs.pop('type')
			except:
				type = args.pop(0)
			else:
				if isinstance(args[0], Color.Type):
					raise TypeError(f"{self.__class__.__name__}() got " \
						"multiple values for argument 'type'")
		else:
			try:
				type = kwargs.pop('type')
			except:
				type = self._type
				if type == Color.Type.INVALID:
					raise TypeError(f"{self.__class__.__name__}() missing " \
						"required argument: 'type'")

		try:
			type = Color.Type(type)
		except:
			type = Color.Type.RGB

		# Initialize the properties.

		if   type == Color.Type.RGB:
			self._r, self._g, self._b, self._alpha = _decode_varargs(\
				(('r', 'red'),   _byte),
				(('g', 'green'), _byte),
				(('b', 'blue'),  _byte),
				(('a', 'alpha'), _percentage, 1.0))
		elif type == Color.Type.HSL:
			self._hue, self._sat, self._lgt, self._alpha = _decode_varargs(\
				(('h', 'hue'),                       _hue),
				(('s', 'sat', 'saturation'),         _percentage),
				(('l', 'lig', 'light', 'lightness'), _percentage),
				(('a', 'alpha'),                     _percentage, 1.0))
		elif type == Color.Type.HWB:
			self._hue, self._wht, self._blk, self._alpha = _decode_varargs(\
				(('h', 'hue'),                _hue),
				(('w', 'white', 'whiteness'), _percentage),
				(('b', 'black', 'blackness'), _percentage),
				(('a', 'alpha'),              _percentage, 1.0))
		elif type == Color.Type.CMYK:
			self._cy, self._ma, self._ye, self._bl, self._alpha = \
				_decode_varargs(\
				(('c', 'cyan'),    _percentage),
				(('m', 'magenta'), _percentage),
				(('y', 'yellow'),  _percentage),
				(('b', 'black'),   _percentage),
				(('a', 'alpha'),   _percentage, 1.0))
		else:
			raise ValueError(f"invalid color type: {type}")

		# Once the arguments have been tested to be valid, we can set the
		# type.

		self._type = type

	# ---
	# Properties.
	# ---

	@property
	def type(self):
		""" The read-only angle type as one of the :class:`Color.Type`
			constants. """

		return self._type

	# ---
	# Conversion methods.
	# ---

	def rgb(self):
		""" Get the sRGB (red, green, blue) components of the color.
			For example:

				>>> Color.from_text("#876543").rgb()
				... (135, 101, 67)

			If the color is not represented as sRGB internally, it will be
			converted. """

		if   self._type == Color.Type.RGB:
			return (self._r, self._g, self._b)
		elif self._type == Color.Type.HSL:
			return _hls_to_rgb(self._hue, self._lgt, self._sat)
		elif self._type == Color.Type.HWB:
			return _hwb_to_rgb(self._hue, self._wht, self._blk)
		elif self._type == Color.Type.CMYK:
			return _cmyk_to_rgb(self._cy, self._ma, self._ye, self._bl)

		raise ValueError(f"color type {self._type} doesn't translate to rgb")

	def hsl(self):
		""" Get the HSL (hue, saturation, lightness) components of the color.
			For example:

				>>> Color.from_text("hsl(90turn 0% 5%)").hls()
				... (Angle(type = Angle.Type.TURN, value = 90.0), 0.05, 0.0)

			If the color is not represented as HSL internally, it will be
			converted. """

		if self._type == Color.Type.HSL:
			return (self._hue, self._sat, self._lgt)

		try:
			rgb = self.rgb()
		except ValueError:
			raise ValueError(f"color type {self._type} doesn't translate " \
				"to hsl") from None

		return _rgb_to_hls(*rgb)

	def hwb(self):
		""" Get the HWB (hue, whiteness, blackness) components of the color.
			For example:

				>>> Color.from_text("hwb(.7 turn / 5% 10%)").hwb()
				... (Angle(type = Angle.Type.TURN, value = 0.7), 0.05, 0.1)

			If the color is not represented as HSL internally, it will be
			converted. """

		if self._type == Color.Type.HWB:
			return (self._hue, self._wht, self._blk)

		try:
			rgb = self.rgb()
		except ValueError:
			raise ValueError(f"color type {self._type} doesn't translate " \
				"to hwb") from None

		return _rgb_to_hwb(*rgb)

	def cmyk(self):
		""" Get the CMYK (cyan, magenta, yellow, black) components of the
			color. For example:

				>>> Color.from_text("cmyk(.1 .2 .3 .4)").cmyk()
				... (0.1, 0.2, 0.3, 0.4)

			If the color is not represented as CMYK internally, it will be
			converted naively. """

		if self._type == Color.Type.CMYK:
			return (self._cy, self._ma, self._ye, self._bl)

		try:
			rgb = self.rgb()
		except ValueError:
			raise ValueError(f"color type {self._type} doesn't translate " \
				"to cmyk") from None

		return _rgb_to_cmyk(*rgb)

	def rgba(self):
		""" Get the sRGB (red, green, blue) and alpha components of the color.
			For example:

				>>> Color.from_text("#87654321").rgb()
				... (135, 101, 67, 0.1294)

			If the color is not represented as sRGB internally, it will be
			converted. """

		r, g, b = self.rgb()
		alpha = self._alpha

		return (r, g, b, alpha)

	def hsla(self):
		""" Get the HSL (hue, saturation, lightness) and alpha components of
			the color. For example:

				>>> Color.from_text("hsl(90turn 0% 5% .8)").hlsa()
				... (Angle(type = Angle.Type.TURN, value = 90.0), 0.05, 0.0, 0.8)

			If the color is not represented as HSL internally, it will be
			converted. """

		h, s, l = self.hsl()
		alpha = self._alpha

		return (h, s, l, alpha)

	def hls(self):
		""" Alias for :meth:`hsl` but reverses the lightness and
			saturation for commodity. """

		h, s, l = self.hsl()
		return (h, l, s)

	def hlsa(self):
		""" Alias for :meth:`hsla` but reverses the lightness and
			saturation for commodity. """

		h, s, l, a = self.hsla()
		return (h, l, s, a)

	def hwba(self):
		""" Get the HWB (hue, whiteness, blackness) and alpha components of
			the color. For example:

				>>> Color.from_text("hwb(.7 turn / 5% 10% .2)").hwba()
				... (Angle(type = Angle.Type.TURN, value = 0.7), 0.05, 0.1, 0.2)

			If the color is not represented as HSL internally, it will be
			converted. """

		h, w, b = self.hwb()
		a = self._alpha

		return (h, w, b, a)

	def cmyka(self):
		""" Get the CMYK (cyan, magenta, yellow, black) and alpha components
			of the color. For example:

				>>> Color.from_text("cmyk(.1 .2 .3 .4 / 10%)").cmyka()
				... (0.1, 0.2, 0.3, 0.4, 0.1)

			If the color is not represented as CMYK internally, it will be
			converted naively. """

		c, m, y, k = self.cmyk()
		a = self._alpha

		return (c, m, y, k, a)

	def css(self):
		""" Get the CSS color descriptions, with older CSS specifications
			compatibility, as a list of strings.

			For example:

				>>> Color(Color.Type.RGB, 18, 52, 86, 0.82).css()
				... ["#123456", "rgba(18, 52, 86, 82%)"] """

		def _percent(prop):
			per = round(prop, 4) * 100
			if per == int(per):
				per = int(per)
			return per

		def _deg(agl):
			agl = round(agl.degrees, 2)
			if agl == int(agl):
				agl = int(agl)
			return agl

		def statements():
			# Start by yelling a #RRGGBB color, compatible with most
			# web browsers around the world, followed by the rgba()
			# notation if the alpha value isn't 1.0.

			r, g, b, a = self.rgba()
			a = round(a, 3)
			yield f'#{r:02X}{g:02X}{b:02X}'

			if a < 1.0:
				yield f'rgba({r}, {g}, {b}, {_percent(a)}%)'

			# Then yield more specific CSS declarations in case
			# they're supported (which would be neat!).

			if   self._type == Color.Type.HSL:
				args = f'{_deg(self._hue)}deg, ' \
					f'{_percent(self._sat)}%, {_percent(self._lgt)}%'

				if a < 1.0:
					yield f'hsla({args}, {_percent(a)}%)'
				else:
					yield f'hsl({args})'
			elif self._type == Color.Type.HWB:
				args = f'{_deg(self._hue)}deg, ' \
					f'{_percent(self._wht)}%, {_percent(self._blk)}%'

				if a < 1.0:
					yield f'hwba({args}, {_percent(a)}%)'
				else:
					yield f'hwb({args})'

		return tuple(statements())

	# ---
	# Static methods for decoding.
	# ---

	def from_str(*args, **kwargs):
		""" Alias for :meth:`from_text()`. """

		return Color.from_text(value)

	def from_string(*args, **kwargs):
		""" Alias for :meth:`from_text()`. """

		return Color.from_text(value)

	def from_text(expr, ref = None):
		""" Create a color from a string using a :class:`Reference` object.
			If the ``ref`` argument is ``None``, then the default reference
			is loaded.

			An example:

				>>> Color.from_text("#123456")
				... Color(type = Color.Type.RGB, red = 18, green = 52, """ \
				""" blue = 86, alpha = 1.0) """

		if ref is None:
			ref = _Reference.default()
		if not isinstance(ref, _Reference):
			raise ValueError("ref is expected to be a subclass of Reference")

		class argument:
			def __init__(self, column, value):
				self._column = column
				self._value = value

			def __repr__(self):
				return f"{self.__class__.__name__}(column = {self._column}, " \
					f"value = {repr(self._value)})"

			@property
			def column(self):
				return self._column

			@property
			def value(self):
				return self._value

		def recurse(column, match):
			if not match:
				return ()

			if   match['agl_val'] is not None:
				# The matched value is an angle.

				agl_typ = {
					'deg':  _Angle.Type.DEG,
					'grad': _Angle.Type.GRAD,
					'rad':  _Angle.Type.RAD,
					'turn': _Angle.Type.TURN}[match['agl_typ']]

				value = _Reference.angle(_Angle(agl_typ,
					float(match['agl_val'])))
			elif match['per'] is not None:
				# The matched value is a percentage.

				value = float(match['per'])
				value = _Reference.percentage(value)
			elif match['num'] is not None:
				# The matched value is a number.

				value = _Reference.number(match['num'])
			elif match['hex'] is not None:
				# The matched value is a hex color.

				name = match['hex']

				if len(name) <= 4:
					name = ''.join(map(lambda x: x + x, name))

				r = int(name[0:2], 16)
				g = int(name[2:4], 16)
				b = int(name[4:6], 16)
				a = int(name[6:8], 16) / 255.0 if len(name) == 8 else 1.0

				value = _Reference.color(Color(Color.Type.RGB, r, g, b, a))
			elif match['arg'] is not None:
				# The matched value is a function.

				name = match['name']

				# Get the arguments.

				args = recurse(column + match.start('arg'),
					_get_color_pattern().fullmatch(match['arg']))

				# Get the function and call it with the arguments.

				try:
					func = ref.functions[name]
				except KeyError:
					raise _ColorExpressionDecodingError("no such function " \
						f"{repr(name)}", column = column)

				try:
					value = func(*map(lambda x: x.value, args))
				except _NotEnoughArgumentsError as e:
					raise _ColorExpressionDecodingError("not enough " \
						f"arguments (expected at least {e.count} arguments)",
						column = column, func = name)
				except _TooManyArgumentsError as e:
					raise _ColorExpressionDecodingError("extraneous " \
						f"argument (expected {e.count} arguments at most)",
						column = args[e.count].column, func = name)
				except _InvalidArgumentTypeError as e:
					raise _ColorExpressionDecodingError("type mismatch for " \
						f"argument {e.index + 1}: expected {e.expected}, " \
						f"got {e.got}", column = args[e.index].column,
						func = name)
				except _InvalidArgumentValueError as e:
					raise _ColorExpressionDecodingError("erroneous value " \
						f"for argument {e.index + 1}: {e.text}",
						column = args[e.index].column, func = name)
				except NotImplementedError:
					raise _ColorExpressionDecodingError("not implemented",
						column = column, func = name)
			else:
				if match['ncol']:
					# The match is probably a natural color (ncol), we ought
					# to parse it and get the following arguments or, if
					# anything is invalid, to treat it as a color name.

					name = match['ncol']

					# First, get the letter and proportion.

					letter = name[0]
					number = float(name[1:])

					if number >= 0 and number < 100:
						# Get the following arguments and check.

						args = recurse(column + match.start('nextargs'),
							_get_color_pattern().fullmatch(match['nextargs'] \
							or ""))

						try:
							assert len(args) >= 2
							w = args[0].value.to_factor()
							b = args[1].value.to_factor()
						except:
							w = 0
							b = 0
						else:
							args = args[2:]

						# Calculate the color and return the args.

						color = Color(Color.Type.HWB,
							_Angle(_Angle.Type.DEG, 'RYGCBM'.find(letter) \
								* 60 + number / 100 * 60), w, b)

						# And finally, return the args.

						return (argument(column, _Reference.color(color)),) \
							+ args

				# The matched value is a named color.

				name = match['name']

				try:
					# Get the named color (e.g. 'blue').

					value = ref.colors[name]
					assert value != None
				except:
					r, g, b = _netscape_color(name)
					value = Color(Color.Type.RGB, r, g, b, 1.0)

				value = _Reference.color(value)

			return (argument(column, value),) \
				+ recurse(column + match.start('nextargs'),
				_get_color_pattern().fullmatch(match['nextargs'] or ""))

		# Strip the expression.

		lexpr = expr.strip()
		column = (len(expr) - len(lexpr))
		expr = lexpr
		del lexpr

		# Match the expression (and check it as a whole directly).

		match = _get_color_pattern().fullmatch(expr)
		if match is None:
			raise _ColorExpressionDecodingError("expression parsing failed")

		# Get the result and check its type.

		results = recurse(column, match)
		if len(results) > 1:
			raise _ColorExpressionDecodingError("extraneous value",
				column = results[1].column)

		result = results[0].value
		try:
			result = ref.colors[result]
		except AttributeError:
			raise _ColorExpressionDecodingError("expected a color",
				column = column)

		return result

# End of file.