diff --git a/lib/matplotlib/__init__.py b/lib/matplotlib/__init__.py index 15e32d0ae870..fd29cd8d84cb 100644 --- a/lib/matplotlib/__init__.py +++ b/lib/matplotlib/__init__.py @@ -751,6 +751,47 @@ def _open_file_or_url(fname): yield f +def _strip_comment(line): + """ + Strip line and remove comment line. + Only removes comments at the start of a line (may have leading whitespace) + """ + line = line.strip() + if re.match('^#', line): # line starts with a comment + line = '' + return line + + +def _parse_keyval(key, val): + """ + Parse a key-value pair. + We are only passing key in case we want to conditionally allow quoted strings + """ + # remove whitespace + val = val.strip() + # regex + quoted = re.compile(r""" + ^ # beginning of line + (?P['"]) # $1: opening quote (cannot make this non-capturing) + (. *?) # $2: non-greedy anything, the quoted text + (?P=quote) # closing quote, not stored + (. *?) # $3: non-greedy anything, the rest + $ # end of line + """, re.VERBOSE) + match = quoted.match(val) + if match: # a quoted string + val2 = match.group(2) + # ensure the rest is just a comment + rest = match.group(3).strip() + if rest and not re.match('^#', rest): + return None # let it fail + else: # treat as a regular value + val2 = val.split('#', 1)[0] # remove optional comments at the end + val2 = val2.strip() + + return val2 + + def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False): """ Construct a `RcParams` instance from file *fname*. @@ -773,7 +814,7 @@ def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False): try: for line_no, line in enumerate(fd, 1): line = transform(line) - strippedline = line.split('#', 1)[0].strip() + strippedline = _strip_comment(line).strip() if not strippedline: continue tup = strippedline.split(':', 1) @@ -784,6 +825,11 @@ def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False): key, val = tup key = key.strip() val = val.strip() + val = _parse_keyval(key, val) + if val is None: + _log.warning('Cannot parse key value in file %r, line %d (%r)', + fname, line_no, line.rstrip('\n')) + continue if key in rc_temp: _log.warning('Duplicate key in file %r, line %d (%r)', fname, line_no, line.rstrip('\n'))