Skip to content

Commit

Permalink
Fix format string usage.
Browse files Browse the repository at this point in the history
This makes ruff happy, but it's unclear how we got into this situation to start with.
  • Loading branch information
Anteru committed Apr 27, 2024
1 parent 544e58c commit c9165cf
Show file tree
Hide file tree
Showing 70 changed files with 483 additions and 496 deletions.
2 changes: 1 addition & 1 deletion external/markdown-processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ def repl(m):
lexer = TextLexer()
code = highlight(m.group(2), lexer, self.formatter)
code = code.replace('\n\n', '\n&nbsp;\n').replace('\n', '<br />')
return '\n\n<div class="code">%s</div>\n\n' % code
return f'\n\n<div class="code">{code}</div>\n\n'
joined_lines = "\n".join(lines)
joined_lines = self.pattern.sub(repl, joined_lines)
return joined_lines.split("\n")
Expand Down
2 changes: 1 addition & 1 deletion external/moin-parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def __init__(self, raw, request, **kw):

def format(self, formatter):
codeid[0] += 1
id = "pygments_%s" % codeid[0]
id = f"pygments_{codeid[0]}"
w = self.req.write
w(formatter.code_area(1, id, start=1, step=1))
w(formatter.rawHTML(highlight(self.raw, self.lexer, htmlformatter)))
Expand Down
18 changes: 9 additions & 9 deletions pygments/cmdline.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,19 @@ def _print_help(what, name):
try:
if what == 'lexer':
cls = get_lexer_by_name(name)
print("Help on the %s lexer:" % cls.name)
print(f"Help on the {cls.name} lexer:")
print(dedent(cls.__doc__))
elif what == 'formatter':
cls = find_formatter_class(name)
print("Help on the %s formatter:" % cls.name)
print(f"Help on the {cls.name} formatter:")
print(dedent(cls.__doc__))
elif what == 'filter':
cls = find_filter_class(name)
print("Help on the %s filter:" % name)
print(f"Help on the {name} filter:")
print(dedent(cls.__doc__))
return 0
except (AttributeError, ValueError):
print("%s not found!" % what, file=sys.stderr)
print(f"{what} not found!", file=sys.stderr)
return 1


Expand Down Expand Up @@ -122,7 +122,7 @@ def _print_list(what):
for name in get_all_filters():
cls = find_filter_class(name)
print("* " + name + ':')
print(" %s" % docstring_headline(cls))
print(f" {docstring_headline(cls)}")

elif what == 'style':
print()
Expand All @@ -132,7 +132,7 @@ def _print_list(what):
for name in get_all_styles():
cls = get_style_by_name(name)
print("* " + name + ':')
print(" %s" % docstring_headline(cls))
print(f" {docstring_headline(cls)}")


def _print_list_as_json(requested_items):
Expand Down Expand Up @@ -185,8 +185,8 @@ def main_inner(parser, argns):
return 0

if argns.V:
print('Pygments version %s, (c) 2006-2024 by Georg Brandl, Matthäus '
'Chajdas and contributors.' % __version__)
print(f'Pygments version {__version__}, (c) 2006-2024 by Georg Brandl, Matthäus '
'Chajdas and contributors.')
return 0

def is_only_option(opt):
Expand Down Expand Up @@ -659,7 +659,7 @@ def main(args=sys.argv):
msg = info[-1].strip()
if len(info) >= 3:
# extract relevant file and position info
msg += '\n (f%s)' % info[-2].split('\n')[0].strip()[1:]
msg += '\n (f{})'.format(info[-2].split('\n')[0].strip()[1:])
print(file=sys.stderr)
print('*** Error while highlighting:', file=sys.stderr)
print(msg, file=sys.stderr)
Expand Down
3 changes: 1 addition & 2 deletions pygments/filter.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,7 @@ class FunctionFilter(Filter):

def __init__(self, **options):
if not hasattr(self, 'function'):
raise TypeError('%r used without bound function' %
self.__class__.__name__)
raise TypeError(f'{self.__class__.__name__!r} used without bound function')
Filter.__init__(self, **options)

def filter(self, lexer, stream):
Expand Down
6 changes: 3 additions & 3 deletions pygments/filters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ def get_filter_by_name(filtername, **options):
if cls:
return cls(**options)
else:
raise ClassNotFound('filter %r not found' % filtername)
raise ClassNotFound(f'filter {filtername!r} not found')


def get_all_filters():
Expand Down Expand Up @@ -79,9 +79,9 @@ def __init__(self, **options):
Filter.__init__(self, **options)
tags = get_list_opt(options, 'codetags',
['XXX', 'TODO', 'FIXME', 'BUG', 'NOTE'])
self.tag_re = re.compile(r'\b(%s)\b' % '|'.join([
self.tag_re = re.compile(r'\b({})\b'.format('|'.join([
re.escape(tag) for tag in tags if tag
]))
])))

def filter(self, lexer, stream):
regex = self.tag_re
Expand Down
6 changes: 3 additions & 3 deletions pygments/formatters/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def get_formatter_by_name(_alias, **options):
"""
cls = find_formatter_class(_alias)
if cls is None:
raise ClassNotFound("no formatter found for name %r" % _alias)
raise ClassNotFound(f"no formatter found for name {_alias!r}")
return cls(**options)


Expand Down Expand Up @@ -112,7 +112,7 @@ def load_formatter_from_file(filename, formattername="CustomFormatter", **option
except ClassNotFound:
raise
except Exception as err:
raise ClassNotFound('error when loading custom formatter: %s' % err)
raise ClassNotFound(f'error when loading custom formatter: {err}')


def get_formatter_for_filename(fn, **options):
Expand All @@ -134,7 +134,7 @@ def get_formatter_for_filename(fn, **options):
for filename in cls.filenames:
if _fn_matches(fn, filename):
return cls(**options)
raise ClassNotFound("no formatter found for file name %r" % fn)
raise ClassNotFound(f"no formatter found for file name {fn!r}")


class _automodule(types.ModuleType):
Expand Down
2 changes: 1 addition & 1 deletion pygments/formatters/bbcode.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ def _make_styles(self):
for ttype, ndef in self.style:
start = end = ''
if ndef['color']:
start += '[color=#%s]' % ndef['color']
start += '[color=#{}]'.format(ndef['color'])
end = '[/color]' + end
if ndef['bold']:
start += '[b]'
Expand Down
4 changes: 2 additions & 2 deletions pygments/formatters/groff.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ def _make_styles(self):
for ttype, ndef in self.style:
start = end = ''
if ndef['color']:
start += '\\m[%s]' % ndef['color']
start += '\\m[{}]'.format(ndef['color'])
end = '\\m[]' + end
if ndef['bold']:
start += bold
Expand All @@ -72,7 +72,7 @@ def _make_styles(self):
start += italic
end = regular + end
if ndef['bgcolor']:
start += '\\M[%s]' % ndef['bgcolor']
start += '\\M[{}]'.format(ndef['bgcolor'])
end = '\\M[]' + end

self.styles[ttype] = start, end
Expand Down
34 changes: 17 additions & 17 deletions pygments/formatters/html.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,17 +488,17 @@ def _create_stylesheet(self):
name = self._get_css_class(ttype)
style = ''
if ndef['color']:
style += 'color: %s; ' % webify(ndef['color'])
style += 'color: {}; '.format(webify(ndef['color']))
if ndef['bold']:
style += 'font-weight: bold; '
if ndef['italic']:
style += 'font-style: italic; '
if ndef['underline']:
style += 'text-decoration: underline; '
if ndef['bgcolor']:
style += 'background-color: %s; ' % webify(ndef['bgcolor'])
style += 'background-color: {}; '.format(webify(ndef['bgcolor']))
if ndef['border']:
style += 'border: 1px solid %s; ' % webify(ndef['border'])
style += 'border: 1px solid {}; '.format(webify(ndef['border']))
if style:
t2c[ttype] = name
# save len(ttype) to enable ordering the styles by
Expand Down Expand Up @@ -561,11 +561,11 @@ def get_background_style_defs(self, arg=None):

def get_linenos_style_defs(self):
lines = [
'pre { %s }' % self._pre_style,
'td.linenos .normal { %s }' % self._linenos_style,
'span.linenos { %s }' % self._linenos_style,
'td.linenos .special { %s }' % self._linenos_special_style,
'span.linenos.special { %s }' % self._linenos_special_style,
f'pre {{ {self._pre_style} }}',
f'td.linenos .normal {{ {self._linenos_style} }}',
f'span.linenos {{ {self._linenos_style} }}',
f'td.linenos .special {{ {self._linenos_special_style} }}',
f'span.linenos.special {{ {self._linenos_special_style} }}',
]

return lines
Expand Down Expand Up @@ -683,9 +683,9 @@ def _wrap_tablelinenos(self, inner):

if nocls:
if special_line:
style = ' style="%s"' % self._linenos_special_style
style = f' style="{self._linenos_special_style}"'
else:
style = ' style="%s"' % self._linenos_style
style = f' style="{self._linenos_style}"'
else:
if special_line:
style = ' class="special"'
Expand Down Expand Up @@ -742,9 +742,9 @@ def _wrap_inlinelinenos(self, inner):

if nocls:
if special_line:
style = ' style="%s"' % self._linenos_special_style
style = f' style="{self._linenos_special_style}"'
else:
style = ' style="%s"' % self._linenos_style
style = f' style="{self._linenos_style}"'
else:
if special_line:
style = ' class="linenos special"'
Expand Down Expand Up @@ -794,8 +794,8 @@ def _wrap_div(self, inner):
style.append(self.cssstyles)
style = '; '.join(style)

yield 0, ('<div' + (self.cssclass and ' class="%s"' % self.cssclass) +
(style and (' style="%s"' % style)) + '>')
yield 0, ('<div' + (self.cssclass and f' class="{self.cssclass}"') +
(style and (f' style="{style}"')) + '>')
yield from inner
yield 0, '</div>\n'

Expand All @@ -812,7 +812,7 @@ def _wrap_pre(self, inner):

# the empty span here is to keep leading empty lines from being
# ignored by HTML parsers
yield 0, ('<pre' + (style and ' style="%s"' % style) + '><span></span>')
yield 0, ('<pre' + (style and f' style="{style}"') + '><span></span>')
yield from inner
yield 0, '</pre>'

Expand Down Expand Up @@ -841,7 +841,7 @@ def _format_lines(self, tokensource):
try:
cspan = self.span_element_openers[ttype]
except KeyError:
title = ' title="%s"' % '.'.join(ttype) if self.debug_token_types else ''
title = ' title="{}"'.format('.'.join(ttype)) if self.debug_token_types else ''
if nocls:
css_style = self._get_css_inline_styles(ttype)
if css_style:
Expand Down Expand Up @@ -928,7 +928,7 @@ def _highlight_lines(self, tokensource):
style = (f' style="background-color: {self.style.highlight_color}"')
yield 1, f'<span{style}>{value}</span>'
else:
yield 1, '<span class="hll">%s</span>' % value
yield 1, f'<span class="hll">{value}</span>'
else:
yield 1, value

Expand Down
6 changes: 2 additions & 4 deletions pygments/formatters/img.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,7 @@ def _create_nix(self):
self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
break
else:
raise FontNotFound('No usable fonts named: "%s"' %
self.font_name)
raise FontNotFound(f'No usable fonts named: "{self.font_name}"')
for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
for stylename in STYLES[style]:
path = self._get_nix_font_path(self.font_name, stylename)
Expand Down Expand Up @@ -142,8 +141,7 @@ def _create_mac(self):
self.fonts['NORMAL'] = ImageFont.truetype(path, self.font_size)
break
else:
raise FontNotFound('No usable fonts named: "%s"' %
self.font_name)
raise FontNotFound(f'No usable fonts named: "{self.font_name}"')
for style in ('ITALIC', 'BOLD', 'BOLDITALIC'):
for stylename in STYLES[style]:
path = self._get_mac_font_path(font_map, self.font_name, stylename)
Expand Down
38 changes: 18 additions & 20 deletions pygments/formatters/latex.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,21 @@ def escape_tex(text, commandprefix):
return text.replace('\\', '\x00'). \
replace('{', '\x01'). \
replace('}', '\x02'). \
replace('\x00', r'\%sZbs{}' % commandprefix). \
replace('\x01', r'\%sZob{}' % commandprefix). \
replace('\x02', r'\%sZcb{}' % commandprefix). \
replace('^', r'\%sZca{}' % commandprefix). \
replace('_', r'\%sZus{}' % commandprefix). \
replace('&', r'\%sZam{}' % commandprefix). \
replace('<', r'\%sZlt{}' % commandprefix). \
replace('>', r'\%sZgt{}' % commandprefix). \
replace('#', r'\%sZsh{}' % commandprefix). \
replace('%', r'\%sZpc{}' % commandprefix). \
replace('$', r'\%sZdl{}' % commandprefix). \
replace('-', r'\%sZhy{}' % commandprefix). \
replace("'", r'\%sZsq{}' % commandprefix). \
replace('"', r'\%sZdq{}' % commandprefix). \
replace('~', r'\%sZti{}' % commandprefix)
replace('\x00', rf'\{commandprefix}Zbs{{}}'). \
replace('\x01', rf'\{commandprefix}Zob{{}}'). \
replace('\x02', rf'\{commandprefix}Zcb{{}}'). \
replace('^', rf'\{commandprefix}Zca{{}}'). \
replace('_', rf'\{commandprefix}Zus{{}}'). \
replace('&', rf'\{commandprefix}Zam{{}}'). \
replace('<', rf'\{commandprefix}Zlt{{}}'). \
replace('>', rf'\{commandprefix}Zgt{{}}'). \
replace('#', rf'\{commandprefix}Zsh{{}}'). \
replace('%', rf'\{commandprefix}Zpc{{}}'). \
replace('$', rf'\{commandprefix}Zdl{{}}'). \
replace('-', rf'\{commandprefix}Zhy{{}}'). \
replace("'", rf'\{commandprefix}Zsq{{}}'). \
replace('"', rf'\{commandprefix}Zdq{{}}'). \
replace('~', rf'\{commandprefix}Zti{{}}')


DOC_TEMPLATE = r'''
Expand Down Expand Up @@ -304,16 +304,14 @@ def rgbcolor(col):
if ndef['mono']:
cmndef += r'\let\$$@ff=\textsf'
if ndef['color']:
cmndef += (r'\def\$$@tc##1{\textcolor[rgb]{%s}{##1}}' %
rgbcolor(ndef['color']))
cmndef += (r'\def\$$@tc##1{{\textcolor[rgb]{{{}}}{{##1}}}}'.format(rgbcolor(ndef['color'])))
if ndef['border']:
cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{\string -\fboxrule}}'
r'\fcolorbox[rgb]{{{}}}{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['border']),
rgbcolor(ndef['bgcolor'])))
elif ndef['bgcolor']:
cmndef += (r'\def\$$@bc##1{{\setlength{\fboxsep}{0pt}'
r'\colorbox[rgb]{%s}{\strut ##1}}}' %
rgbcolor(ndef['bgcolor']))
cmndef += (r'\def\$$@bc##1{{{{\setlength{{\fboxsep}}{{0pt}}'
r'\colorbox[rgb]{{{}}}{{\strut ##1}}}}}}'.format(rgbcolor(ndef['bgcolor'])))
if cmndef == '':
continue
cmndef = cmndef.replace('$$', cp)
Expand Down
3 changes: 1 addition & 2 deletions pygments/formatters/other.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ def __init__(self, **options):
try:
colorize(self.error_color, '')
except KeyError:
raise ValueError("Invalid color %r specified" %
self.error_color)
raise ValueError(f"Invalid color {self.error_color!r} specified")

def format(self, tokensource, outfile):
try:
Expand Down
2 changes: 1 addition & 1 deletion pygments/formatters/pangomarkup.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def __init__(self, **options):
start = ''
end = ''
if style['color']:
start += '<span fgcolor="#%s">' % style['color']
start += '<span fgcolor="#{}">'.format(style['color'])
end = '</span>' + end
if style['bold']:
start += '<b>'
Expand Down
10 changes: 4 additions & 6 deletions pygments/formatters/rtf.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,18 +237,16 @@ def _create_color_mapping(self):
@property
def _lineno_template(self):
if self.lineno_fontsize != self.fontsize:
return '{\\fs%s \\cf%s %%s%s}' \
% (self.lineno_fontsize,
return '{{\\fs{} \\cf{} %s{}}}'.format(self.lineno_fontsize,
self.color_mapping[self.lineno_color],
" " * self.lineno_padding)

return '{\\cf%s %%s%s}' \
% (self.color_mapping[self.lineno_color],
return '{{\\cf{} %s{}}}'.format(self.color_mapping[self.lineno_color],
" " * self.lineno_padding)

@property
def _hl_open_str(self):
return r'{\highlight%s ' % self.color_mapping[self.hl_color]
return rf'{{\highlight{self.color_mapping[self.hl_color]} '

@property
def _rtf_header(self):
Expand Down Expand Up @@ -331,7 +329,7 @@ def format_unencoded(self, tokensource, outfile):
self.color_mapping[style['border']])
start = ''.join(buf)
if start:
outfile.write('{%s ' % start)
outfile.write(f'{{{start} ')
outfile.write(self._escape_text(value))
if start:
outfile.write('}')
Expand Down

0 comments on commit c9165cf

Please sign in to comment.