run pyupgrade to upgrade the codebase to python3.6

This commit is contained in:
Kovid Goyal 2021-10-21 12:43:55 +05:30
parent 8f0b3983ee
commit 6546c1da9b
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
159 changed files with 194 additions and 353 deletions

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Iterable, List, Union

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
@ -94,7 +93,7 @@ def main(args: List[str]) -> NoReturn:
data: Optional[bytes] = None
if not sys.stdin.isatty():
data = sys.stdin.buffer.read()
sys.stdin = open(os.ctermid(), 'r')
sys.stdin = open(os.ctermid())
loop = Loop()
handler = Clipboard(data, cli_opts)
loop.loop(handler)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import concurrent
@ -31,7 +30,7 @@ class DiffFormatter(Formatter):
except ClassNotFound:
initialized = False
if not initialized:
raise StyleNotFound('pygments style "{}" not found'.format(style))
raise StyleNotFound(f'pygments style "{style}" not found')
self.styles: Dict[str, Tuple[str, str]] = {}
for token, token_style in self.style:
@ -153,7 +152,7 @@ def highlight_collection(collection: Collection, aliases: Optional[Dict[str, str
try:
highlights = future.result()
except Exception as e:
return 'Running syntax highlighting for {} generated an exception: {}'.format(path, e)
return f'Running syntax highlighting for {path} generated an exception: {e}'
ans[path] = highlights
return ans
@ -166,5 +165,5 @@ def main() -> None:
with open(sys.argv[-1]) as f:
highlighted = highlight_data(f.read(), f.name, defaults.syntax_aliases)
if highlighted is None:
raise SystemExit('Unknown filetype: {}'.format(sys.argv[-1]))
raise SystemExit(f'Unknown filetype: {sys.argv[-1]}')
print(highlighted)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import atexit
@ -428,7 +427,7 @@ class DiffHandler(Handler):
elif self.state is MESSAGE:
self.cmd.styled(self.message, reverse=True)
else:
sp = '{:.0%}'.format(self.scroll_pos/self.max_scroll_pos) if self.scroll_pos and self.max_scroll_pos else '0%'
sp = f'{self.scroll_pos/self.max_scroll_pos:.0%}' if self.scroll_pos and self.max_scroll_pos else '0%'
scroll_frac = styled(sp, fg=self.opts.margin_fg)
if self.current_search is None:
counts = '{}{}{}'.format(
@ -437,7 +436,7 @@ class DiffHandler(Handler):
styled(str(self.removed_count), fg=self.opts.highlight_removed_bg)
)
else:
counts = styled('{} matches'.format(len(self.current_search)), fg=self.opts.margin_fg)
counts = styled(f'{len(self.current_search)} matches', fg=self.opts.margin_fg)
suffix = counts + ' ' + scroll_frac
prefix = styled(':', fg=self.opts.margin_fg)
filler = self.screen_size.cols - wcswidth(prefix) - wcswidth(suffix)
@ -632,7 +631,7 @@ def main(args: List[str]) -> None:
raise SystemExit('The items to be diffed should both be either directories or files. Comparing a directory to a file is not valid.')
for f in left, right:
if not os.path.exists(f):
raise SystemExit('{} does not exist'.format(f))
raise SystemExit(f'{f} does not exist')
loop = Loop()
handler = DiffHandler(cli_opts, opts, left, right)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import concurrent.futures
@ -151,9 +150,9 @@ class Hunk:
# Sanity check
c = self.chunks[-1]
if c.left_start + c.left_count != self.left_start + self.left_count:
raise ValueError('Left side line mismatch {} != {}'.format(c.left_start + c.left_count, self.left_start + self.left_count))
raise ValueError(f'Left side line mismatch {c.left_start + c.left_count} != {self.left_start + self.left_count}')
if c.right_start + c.right_count != self.right_start + self.right_count:
raise ValueError('Left side line mismatch {} != {}'.format(c.right_start + c.right_count, self.right_start + self.right_count))
raise ValueError(f'Left side line mismatch {c.right_start + c.right_count} != {self.right_start + self.right_count}')
for c in self.chunks:
c.finalize()
@ -240,18 +239,18 @@ class Differ:
try:
ok, returncode, output = future.result()
except FileNotFoundError as err:
return 'Could not find the {} executable. Is it in your PATH?'.format(err.filename)
return f'Could not find the {err.filename} executable. Is it in your PATH?'
except Exception as e:
return 'Running git diff for {} vs. {} generated an exception: {}'.format(left_path, right_path, e)
return f'Running git diff for {left_path} vs. {right_path} generated an exception: {e}'
if not ok:
return output + '\nRunning git diff for {} vs. {} failed'.format(left_path, right_path)
return output + f'\nRunning git diff for {left_path} vs. {right_path} failed'
left_lines = lines_for_path(left_path)
right_lines = lines_for_path(right_path)
try:
patch = parse_patch(output)
except Exception:
import traceback
return traceback.format_exc() + '\nParsing diff for {} vs. {} failed'.format(left_path, right_path)
return traceback.format_exc() + f'\nParsing diff for {left_path} vs. {right_path} failed'
else:
ans[key] = patch
return ans

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import warnings
@ -42,7 +41,7 @@ class Ref:
def __repr__(self) -> str:
return '{}({})'.format(self.__class__.__name__, ', '.join(
'{}={}'.format(n, getattr(self, n)) for n in self.__slots__ if n != '_hash'))
f'{n}={getattr(self, n)}' for n in self.__slots__ if n != '_hash'))
class LineRef(Ref):
@ -264,7 +263,7 @@ def render_diff_pair(
def hunk_title(hunk_num: int, hunk: Hunk, margin_size: int, available_cols: int) -> str:
m = hunk_margin_format(' ' * margin_size)
t = '@@ -{},{} +{},{} @@ {}'.format(hunk.left_start + 1, hunk.left_count, hunk.right_start + 1, hunk.right_count, hunk.title)
t = f'@@ -{hunk.left_start + 1},{hunk.left_count} +{hunk.right_start + 1},{hunk.right_count} @@ {hunk.title}'
return m + hunk_format(place_in(t, available_cols))
@ -539,7 +538,7 @@ class RenderDiff:
assert other_path is not None
ans = yield_lines_from(rename_lines(path, other_path, args, columns, margin_size), item_ref)
else:
raise ValueError('Unsupported item type: {}'.format(item_type))
raise ValueError(f'Unsupported item type: {item_type}')
yield from ans
if i < last_item_num:
yield Line('', item_ref)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import re
@ -30,7 +29,7 @@ class Search:
try:
self.pat = re.compile(query, flags=re.UNICODE | re.IGNORECASE)
except Exception:
raise BadRegex('Not a valid regex: {}'.format(query))
raise BadRegex(f'Not a valid regex: {query}')
def __call__(self, diff_lines: Iterable['Line'], margin_size: int, cols: int) -> bool:
self.matches = {}
@ -68,6 +67,6 @@ class Search:
return False
write(self.style)
for start, text in highlights:
write('\r\x1b[{}C{}'.format(start, text))
write(f'\r\x1b[{start}C{text}')
write('\x1b[m')
return True

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
@ -366,7 +365,7 @@ def functions_for(args: HintsCLIOptions) -> Tuple[str, List[PostprocessorFunc]]:
chars = args.word_characters
if chars is None:
chars = kitty_common_opts()['select_by_word_characters']
pattern = r'(?u)[{}\w]{{{},}}'.format(escape(chars), args.minimum_match_length)
pattern = fr'(?u)[{escape(chars)}\w]{{{args.minimum_match_length},}}'
post_processors.extend((brackets, quotes))
else:
pattern = args.regex

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import contextlib
@ -145,7 +144,7 @@ def get_screen_size() -> ScreenSize:
@run_once
def options_spec() -> str:
return OPTIONS.format(appname='{}-icat'.format(appname))
return OPTIONS.format(appname=f'{appname}-icat')
def write_gr_cmd(cmd: GraphicsCommand, payload: Optional[bytes] = None) -> None:
@ -195,7 +194,7 @@ def set_cursor_for_place(place: 'Place', cmd: GraphicsCommand, width: int, heigh
extra_cells = (place.width - num_of_cells_needed) // 2
elif align == 'right':
extra_cells = place.width - num_of_cells_needed
sys.stdout.buffer.write('\033[{};{}H'.format(place.top + 1, x + extra_cells).encode('ascii'))
sys.stdout.buffer.write(f'\033[{place.top + 1};{x + extra_cells}H'.encode('ascii'))
def write_chunked(cmd: GraphicsCommand, data: bytes) -> None:
@ -369,7 +368,7 @@ def scan(d: str) -> Generator[Tuple[str, str], None, None]:
def detect_support(wait_for: float = 10, silent: bool = False) -> bool:
global can_transfer_with_files
if not silent:
print('Checking for graphics ({}s max. wait)...'.format(wait_for), end='\r')
print(f'Checking for graphics ({wait_for}s max. wait)...', end='\r')
sys.stdout.flush()
try:
received = b''
@ -466,7 +465,7 @@ def process_single_item(
with socket_timeout(30):
urlretrieve(item, filename=tf.name)
except Exception as e:
raise SystemExit('Failed to download image at URL: {} with error: {}'.format(item, e))
raise SystemExit(f'Failed to download image at URL: {item} with error: {e}')
item = tf.name
is_tempfile = True
file_removed = process(item, args, parsed_opts, is_tempfile)
@ -493,14 +492,14 @@ def process_single_item(
def main(args: List[str] = sys.argv) -> None:
global can_transfer_with_files
cli_opts, items_ = parse_args(args[1:], options_spec, usage, help_text, '{} +kitten icat'.format(appname), result_class=IcatCLIOptions)
cli_opts, items_ = parse_args(args[1:], options_spec, usage, help_text, f'{appname} +kitten icat', result_class=IcatCLIOptions)
items: List[Union[str, bytes]] = list(items_)
if cli_opts.print_window_size:
screen_size_function.cache_clear()
with open(os.ctermid()) as tty:
ss = screen_size_function(tty)()
print('{}x{}'.format(ss.width, ss.height), end='')
print(f'{ss.width}x{ss.height}', end='')
raise SystemExit(0)
if not sys.stdout.isatty():
@ -511,7 +510,7 @@ def main(args: List[str] = sys.argv) -> None:
if stdin_data:
items.insert(0, stdin_data)
sys.stdin.close()
sys.stdin = open(os.ctermid(), 'r')
sys.stdin = open(os.ctermid())
screen_size = get_screen_size_function()
signal.signal(signal.SIGWINCH, lambda signum, frame: setattr(screen_size, 'changed', True))
@ -526,12 +525,12 @@ def main(args: List[str] = sys.argv) -> None:
try:
parsed_opts.place = parse_place(cli_opts.place)
except Exception:
raise SystemExit('Not a valid place specification: {}'.format(cli_opts.place))
raise SystemExit(f'Not a valid place specification: {cli_opts.place}')
try:
parsed_opts.z_index = parse_z_index(cli_opts.z_index)
except Exception:
raise SystemExit('Not a valid z-index specification: {}'.format(cli_opts.z_index))
raise SystemExit(f'Not a valid z-index specification: {cli_opts.z_index}')
if cli_opts.detect_support:
if not detect_support(wait_for=cli_opts.detection_timeout, silent=True):

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
@ -116,7 +115,7 @@ def setup_x11_window(win_id: int) -> None:
'-id', str(win_id), '-format', '_NET_WM_WINDOW_TYPE', '32a',
'-set', '_NET_WM_WINDOW_TYPE', '_NET_WM_WINDOW_TYPE_DOCK'
)
func = globals()['create_{}_strut'.format(args.edge)]
func = globals()[f'create_{args.edge}_strut']
func(win_id, window_width, window_height)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import re
@ -28,10 +27,10 @@ class Query:
def __init__(self) -> None:
self.encoded_query_name = hexlify(self.query_name.encode('utf-8')).decode('ascii')
self.pat = re.compile('\x1bP([01])\\+r{}(.*?)\x1b\\\\'.format(self.encoded_query_name).encode('ascii'))
self.pat = re.compile(f'\x1bP([01])\\+r{self.encoded_query_name}(.*?)\x1b\\\\'.encode('ascii'))
def query_code(self) -> str:
return "\x1bP+q{}\x1b\\".format(self.encoded_query_name)
return f"\x1bP+q{self.encoded_query_name}\x1b\\"
def decode_response(self, res: bytes) -> str:
return unhexlify(res).decode('utf-8')
@ -234,7 +233,7 @@ def main(args: List[str] = sys.argv) -> None:
options_spec,
usage,
help_text,
'{} +kitten query_terminal'.format(appname),
f'{appname} +kitten query_terminal',
result_class=QueryTerminalCLIOptions
)
queries: List[str] = list(items_)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
@ -43,7 +42,7 @@ class Resize(Handler):
if is_decrease:
increment *= -1
axis = 'reset' if reset else ('horizontal' if is_horizontal else 'vertical')
cmdline = [resize_window.name, '--self', '--increment={}'.format(increment), '--axis=' + axis]
cmdline = [resize_window.name, '--self', f'--increment={increment}', '--axis=' + axis]
opts, items = parse_subcommand_cli(resize_window, cmdline)
payload = resize_window.message_to_kitty(global_opts, opts, items)
send = {'cmd': resize_window.name, 'version': version, 'payload': payload, 'no_response': False}
@ -96,7 +95,7 @@ class Resize(Handler):
print('Hold down {} to double step size'.format(styled('Ctrl', italic=True)))
print()
print(styled('Sizes', bold=True, fg='white', fg_intense=True))
print('Original: {} rows {} cols'.format(self.original_size.rows, self.original_size.cols))
print(f'Original: {self.original_size.rows} rows {self.original_size.cols} cols')
print('Current: {} rows {} cols'.format(
styled(str(self.screen_size.rows), fg='magenta'), styled(str(self.screen_size.cols), fg='magenta')))

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
@ -61,7 +60,7 @@ def import_kitten_main_module(config_dir: str, kitten: str) -> Dict[str, Any]:
return {'start': g['main'], 'end': hr}
kitten = resolved_kitten(kitten)
m = importlib.import_module('kittens.{}.main'.format(kitten))
m = importlib.import_module(f'kittens.{kitten}.main')
return {'start': getattr(m, 'main'), 'end': getattr(m, 'handle_result', lambda *a, **k: None)}
@ -111,7 +110,7 @@ def deserialize(output: str) -> Any:
prefix, sz, rest = output.split(' ', 2)
return json.loads(rest[:int(sz)])
except Exception:
raise ValueError('Failed to parse kitten output: {!r}'.format(output))
raise ValueError(f'Failed to parse kitten output: {output!r}')
def run_kitten(kitten: str, run_name: str = '__main__') -> None:
@ -120,7 +119,7 @@ def run_kitten(kitten: str, run_name: str = '__main__') -> None:
kitten = resolved_kitten(kitten)
set_debug(kitten)
try:
runpy.run_module('kittens.{}.main'.format(kitten), run_name=run_name)
runpy.run_module(f'kittens.{kitten}.main', run_name=run_name)
return
except ImportError:
pass

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
from kitty.key_encoding import (

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
@ -245,7 +244,7 @@ def parse_ssh_args(args: List[str]) -> Tuple[List[str], List[str], bool]:
else:
expecting_option_val = True
break
raise InvalidSSHArgs('unknown option -- {}'.format(arg[1:]))
raise InvalidSSHArgs(f'unknown option -- {arg[1:]}')
continue
if expecting_option_val:
ssh_args.append(arg)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import datetime

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
from enum import auto

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os
@ -336,11 +335,11 @@ class Dircolors:
def _format_code(self, text: str, code: str) -> str:
val = self.codes.get(code)
return '\033[%sm%s\033[%sm' % (val, text, self.codes.get('rs', '0')) if val else text
return '\033[{}m{}\033[{}m'.format(val, text, self.codes.get('rs', '0')) if val else text
def _format_ext(self, text: str, ext: str) -> str:
val = self.extensions.get(ext, '0')
return '\033[%sm%s\033[%sm' % (val, text, self.codes.get('rs', '0')) if val else text
return '\033[{}m{}\033[{}m'.format(val, text, self.codes.get('rs', '0')) if val else text
def format_mode(self, text: str, sr: os.stat_result) -> str:
mode = sr.st_mode

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import codecs
@ -105,7 +104,7 @@ class OpenFailed(ValueError):
def __init__(self, path: str, message: str):
ValueError.__init__(
self, 'Failed to open image: {} with error: {}'.format(path, message)
self, f'Failed to open image: {path} with error: {message}'
)
self.path = path
@ -114,7 +113,7 @@ class ConvertFailed(ValueError):
def __init__(self, path: str, message: str):
ValueError.__init__(
self, 'Failed to convert image: {} with error: {}'.format(path, message)
self, f'Failed to convert image: {path} with error: {message}'
)
self.path = path
@ -212,7 +211,7 @@ def render_image(
scaled = True
if scaled or width > available_width or height > available_height:
width, height = fit_image(width, height, available_width, available_height)
resize_cmd = ['-resize', '{}x{}!'.format(width, height)]
resize_cmd = ['-resize', f'{width}x{height}!']
if get_multiple_frames:
# we have to coalesce, resize and de-coalesce all frames
resize_cmd = ['-coalesce'] + resize_cmd + ['-deconstruct']
@ -373,7 +372,7 @@ class GraphicsCommand:
def serialize(self, payload: Union[bytes, str] = b'') -> bytes:
items = []
for k, val in self._actual_values.items():
items.append('{}={}'.format(k, val))
items.append(f'{k}={val}')
ans: List[bytes] = []
w = ans.append

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Callable, Tuple

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import asyncio

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import sys
@ -57,13 +56,13 @@ def cmd(f: F) -> F:
@cmd
def set_mode(which: Mode) -> str:
num, private = which.value
return '\033[{}{}h'.format(private, num)
return f'\033[{private}{num}h'
@cmd
def reset_mode(which: Mode) -> str:
num, private = which.value
return '\033[{}{}l'.format(private, num)
return f'\033[{private}{num}l'
@cmd
@ -127,7 +126,7 @@ def set_cursor_visible(yes_or_no: bool) -> str:
@cmd
def set_cursor_position(x: int = 0, y: int = 0) -> str: # (0, 0) is top left
return '\033[{};{}H'.format(y + 1, x + 1)
return f'\033[{y + 1};{x + 1}H'
@cmd
@ -141,7 +140,7 @@ def set_cursor_shape(shape: str = 'block', blink: bool = True) -> str:
val = {'block': 1, 'underline': 3, 'bar': 5}.get(shape, 1)
if not blink:
val += 1
return '\033[{} q'.format(val)
return f'\033[{val} q'
@cmd
@ -156,7 +155,7 @@ def set_scrolling_region(screen_size: Optional['ScreenSize'] = None, top: Option
bottom = screen_size.rows - 1 + bottom
else:
bottom += 1
return '\033[{};{}r'.format(top + 1, bottom + 1)
return f'\033[{top + 1};{bottom + 1}r'
@cmd
@ -178,7 +177,7 @@ def color_code(color: ColorSpec, intense: bool = False, base: int = 30) -> str:
if isinstance(color, str):
e = str((base + 60 if intense else base) + STANDARD_COLORS[color])
elif isinstance(color, int):
e = '{}:5:{}'.format(base + 8, max(0, min(color, 255)))
e = f'{base + 8}:5:{max(0, min(color, 255))}'
else:
e = '{}:2:{}:{}:{}'.format(base + 8, *color)
return e
@ -198,7 +197,7 @@ def colored(
reset_to_intense: bool = False
) -> str:
e = color_code(color, intense)
return '\033[{}m{}\033[{}m'.format(e, text, 39 if reset_to is None else color_code(reset_to, reset_to_intense))
return f'\033[{e}m{text}\033[{39 if reset_to is None else color_code(reset_to, reset_to_intense)}m'
@cmd
@ -233,7 +232,7 @@ def styled(
start.append(color_code(underline_color, base=50))
end.append('59')
if underline is not None:
start.append('4:{}'.format(UNDERLINE_STYLES[underline]))
start.append(f'4:{UNDERLINE_STYLES[underline]}')
end.append('4:0')
if italic is not None:
s, e = (start, end) if italic else (end, start)
@ -383,7 +382,7 @@ def set_default_colors(
def item(which: Optional[Union[Color, str]], num: int) -> None:
nonlocal ans
if which is None:
ans += '\x1b]1{}\x1b\\'.format(num)
ans += f'\x1b]1{num}\x1b\\'
else:
if isinstance(which, Color):
q = color_as_sharp(which)
@ -391,7 +390,7 @@ def set_default_colors(
x = to_color(which)
assert x is not None
q = color_as_sharp(x)
ans += '\x1b]{};{}\x1b\\'.format(num, q)
ans += f'\x1b]{num};{q}\x1b\\'
item(fg, 10)
item(bg, 11)
@ -464,7 +463,7 @@ def as_type_stub() -> str:
args = ', '.join(func_sig(func))
if args:
args = ', ' + args
methods.append(' def {}(self{}) -> str: pass'.format(name, args))
methods.append(f' def {name}(self{args}) -> str: pass')
ans += ['', '', 'class CMD:'] + methods
return '\n'.join(ans) + '\n\n\n'

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
from time import monotonic

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
import string
@ -110,7 +109,7 @@ def serialize_favorites(favorites: Iterable[int]) -> str:
'''.splitlines()
for cp in favorites:
ans.append('{:x} # {} {}'.format(cp, chr(cp), name(cp)))
ans.append(f'{cp:x} # {chr(cp)} {name(cp)}')
return '\n'.join(ans)
@ -381,7 +380,7 @@ class UnicodeInput(Handler):
def draw_title_bar(self) -> None:
entries = []
for name, key, mode in all_modes:
entry = ' {} ({}) '.format(name, key)
entry = f' {name} ({key}) '
if mode is self.mode:
entry = styled(entry, reverse=False, bold=True)
entries.append(entry)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import inspect

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
from enum import IntFlag

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import atexit
@ -899,8 +898,8 @@ class Boss:
if w is None:
return
overlay_window = self._run_kitten('resize_window', args=[
'--horizontal-increment={}'.format(get_options().window_resize_step_cells),
'--vertical-increment={}'.format(get_options().window_resize_step_lines)
f'--horizontal-increment={get_options().window_resize_step_cells}',
f'--vertical-increment={get_options().window_resize_step_lines}'
])
if overlay_window is not None:
overlay_window.allow_remote_control = True
@ -1178,7 +1177,7 @@ class Boss:
q = type_of_input.split('-')
data = w.last_cmd_output(as_ansi='ansi' in q, add_wrap_markers='screen' in q).encode('utf-8')
else:
raise ValueError('Unknown type_of_input: {}'.format(type_of_input))
raise ValueError(f'Unknown type_of_input: {type_of_input}')
else:
data = input_data if isinstance(input_data, bytes) else input_data.encode('utf-8')
copts = common_opts_as_dict(get_options())
@ -1766,12 +1765,12 @@ class Boss:
assert update_check_process.stdout is not None
raw = update_check_process.stdout.read().decode('utf-8')
except Exception as e:
log_error('Failed to read data from update check process, with error: {}'.format(e))
log_error(f'Failed to read data from update check process, with error: {e}')
else:
try:
process_current_release(raw)
except Exception as e:
log_error('Failed to process update check data {!r}, with error: {}'.format(raw, e))
log_error(f'Failed to process update check data {raw!r}, with error: {e}')
def dbus_notification_callback(self, activated: bool, a: int, b: Union[int, str]) -> None:
from .notify import (
@ -1787,7 +1786,7 @@ class Boss:
def show_bad_config_lines(self, bad_lines: Iterable[BadLine]) -> None:
def format_bad_line(bad_line: BadLine) -> str:
return '{}:{} in line: {}\n'.format(bad_line.number, bad_line.exception, bad_line.line)
return f'{bad_line.number}:{bad_line.exception} in line: {bad_line.line}\n'
msg = '\n'.join(map(format_bad_line, bad_lines)).rstrip()
self.show_error(_('Errors in kitty.conf'), msg)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import fcntl
@ -41,15 +40,15 @@ if is_macos:
else:
def cmdline_of_process(pid: int) -> List[str]:
with open('/proc/{}/cmdline'.format(pid), 'rb') as f:
with open(f'/proc/{pid}/cmdline', 'rb') as f:
return list(filter(None, f.read().decode('utf-8').split('\0')))
def cwd_of_process(pid: int) -> str:
ans = '/proc/{}/cwd'.format(pid)
ans = f'/proc/{pid}/cwd'
return os.path.realpath(ans)
def _environ_of_process(pid: int) -> str:
with open('/proc/{}/environ'.format(pid), 'rb') as f:
with open(f'/proc/{pid}/environ', 'rb') as f:
return f.read().decode('utf-8')
def process_group_map() -> DefaultDict[int, List[int]]:

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
import re

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import re
@ -53,7 +52,7 @@ defaults for all users.
def surround(x: str, start: int, end: int) -> str:
if sys.stdout.isatty():
x = '\033[{}m{}\033[{}m'.format(start, x, end)
x = f'\033[{start}m{x}\033[{end}m'
return x
@ -185,7 +184,7 @@ def parse_option_spec(spec: Optional[str] = None) -> Tuple[OptionSpecSeq, Option
}
state = METADATA
continue
raise ValueError('Invalid option spec, unexpected line: {}'.format(line))
raise ValueError(f'Invalid option spec, unexpected line: {line}')
elif state is METADATA:
m = mpat.match(line)
if m is None:
@ -243,7 +242,7 @@ def version(add_rev: bool = False) -> str:
rev = ''
from . import fast_data_types
if add_rev and hasattr(fast_data_types, 'KITTY_VCS_REV'):
rev = ' ({})'.format(fast_data_types.KITTY_VCS_REV[:10])
rev = f' ({fast_data_types.KITTY_VCS_REV[:10]})'
return '{} {}{} created by {}'.format(italic(appname), green(str_version), rev, title('Kovid Goyal'))
@ -334,7 +333,7 @@ class PrintHelpForSeq:
a('{}:'.format(title('Options')))
for opt in seq:
if isinstance(opt, str):
a('{}:'.format(title(opt)))
a(f'{title(opt)}:')
continue
help_text = opt['help']
if help_text == '!':
@ -347,7 +346,7 @@ class PrintHelpForSeq:
t = help_text.replace('%default', str(defval))
wa(prettify(t.strip()), indent=4)
if defval is not None:
wa('Default: {}'.format(defval), indent=4)
wa(f'Default: {defval}', indent=4)
if opt.get('choices'):
wa('Choices: {}'.format(', '.join(opt['choices'])), indent=4)
a('')
@ -384,7 +383,7 @@ def seq_as_rst(
a('.. highlight:: sh')
a('.. code-block:: sh')
a('')
a(' {} {}{}'.format(appname, optstring, usage))
a(f' {appname} {optstring}{usage}')
a('')
message = message or default_msg
a(prettify_rst(message))
@ -412,7 +411,7 @@ def seq_as_rst(
a('')
a(textwrap.indent(prettify_rst(t), ' ' * 4))
if defval is not None:
a(textwrap.indent('Default: :code:`{}`'.format(defval), ' ' * 4))
a(textwrap.indent(f'Default: :code:`{defval}`', ' ' * 4))
if opt.get('choices'):
a(textwrap.indent('Choices: :code:`{}`'.format(', '.join(sorted(opt['choices']))), ' ' * 4))
a('')
@ -423,7 +422,7 @@ def seq_as_rst(
def as_type_stub(seq: OptionSpecSeq, disabled: OptionSpecSeq, class_name: str, extra_fields: Sequence[str] = ()) -> str:
from itertools import chain
ans: List[str] = ['class {}:'.format(class_name)]
ans: List[str] = [f'class {class_name}:']
for opt in chain(seq, disabled):
if isinstance(opt, str):
continue
@ -443,10 +442,10 @@ def as_type_stub(seq: OptionSpecSeq, disabled: OptionSpecSeq, class_name: str, e
elif otype.startswith('bool-'):
t = 'bool'
else:
raise ValueError('Unknown CLI option type: {}'.format(otype))
ans.append(' {}: {}'.format(name, t))
raise ValueError(f'Unknown CLI option type: {otype}')
ans.append(f' {name}: {t}')
for x in extra_fields:
ans.append(' {}'.format(x))
ans.append(f' {x}')
return '\n'.join(ans) + '\n\n\n'
@ -485,7 +484,7 @@ class Options:
def opt_for_alias(self, alias: str) -> OptionDict:
opt = self.alias_map.get(alias)
if opt is None:
raise SystemExit('Unknown option: {}'.format(emph(alias)))
raise SystemExit(f'Unknown option: {emph(alias)}')
return opt
def needs_arg(self, alias: str) -> bool:
@ -546,7 +545,7 @@ def parse_cmdline(oc: Options, disabled: OptionSpecSeq, ans: Any, args: Optional
needs_arg = oc.needs_arg(parts[0])
if not needs_arg:
if len(parts) != 1:
raise SystemExit('The {} option does not accept arguments'.format(emph(parts[0])))
raise SystemExit(f'The {emph(parts[0])} option does not accept arguments')
oc.process_arg(parts[0])
continue
if len(parts) == 1:
@ -561,7 +560,7 @@ def parse_cmdline(oc: Options, disabled: OptionSpecSeq, ans: Any, args: Optional
oc.process_arg(current_option, arg)
current_option, state = None, NORMAL
if state is EXPECTING_ARG:
raise SystemExit('An argument is required for the option: {}'.format(emph(arg)))
raise SystemExit(f'An argument is required for the option: {emph(arg)}')
for key, val in oc.values_map.items():
setattr(ans, key, val)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
# Replay the log from --dump-commands. To use first run
@ -43,7 +42,7 @@ def screen_alternate_keypad_mode() -> None:
def screen_cursor_position(y: int, x: int) -> None:
write(CSI + '%s;%sH' % (y, x))
write(CSI + f'{y};{x}H')
def screen_cursor_forward(amt: int) -> None:

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
@ -294,7 +293,7 @@ def bash_output_serializer(ans: Completions) -> str:
for word in matches:
if matches.trailing_space:
word += ' '
lines.append('COMPREPLY+=({})'.format(shlex.quote(word)))
lines.append(f'COMPREPLY+=({shlex.quote(word)})')
# debug('\n'.join(lines))
return '\n'.join(lines)
@ -685,7 +684,7 @@ def main(args: Sequence[str], entry_points: Iterable[str], namespaced_entry_poin
parser = parsers[cstyle]
serializer = serializers[cstyle]
except KeyError:
raise SystemExit('Unknown completion style: {}'.format(cstyle))
raise SystemExit(f'Unknown completion style: {cstyle}')
words, new_word = parser(data)
ans = find_completions(words, new_word, entry_points, namespaced_entry_points)
print(serializer(ans), end='')

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
@ -105,7 +104,7 @@ def generate_class(defn: Definition, loc: str) -> Tuple[str, str]:
t(f' ans[{option.name!r}] = {func.__name__}(val)')
tc_imports.add((func.__module__, func.__name__))
cnum = int(option.name[5:])
color_table[cnum] = '0x{:06x}'.format(func(option.defval_as_string).__int__())
color_table[cnum] = f'0x{func(option.defval_as_string).__int__():06x}'
continue
else:
func, typ = option_type_data(option)
@ -331,7 +330,7 @@ def generate_class(defn: Definition, loc: str) -> Tuple[str, str]:
t(' return True')
t(' return False')
preamble = ['# generated by gen-config.py DO NOT edit', '# vim:fileencoding=utf-8', '']
preamble = ['# generated by gen-config.py DO NOT edit', '']
a = preamble.append
def output_imports(imports: Set, add_module_imports: bool = True) -> None:
@ -368,7 +367,7 @@ def generate_class(defn: Definition, loc: str) -> Tuple[str, str]:
a(' ' + pprint.pformat(tuple(sorted(option_names, key=natural_keys)))[1:] + ' # }}''}')
class_def = '\n'.join(preamble + ['', ''] + class_lines)
preamble = ['# generated by gen-config.py DO NOT edit', '# vim:fileencoding=utf-8', '']
preamble = ['# generated by gen-config.py DO NOT edit', '']
a = preamble.append
output_imports(tc_imports, False)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import builtins
@ -35,7 +34,7 @@ def expand_opt_references(conf_name: str, text: str) -> str:
ref = m.group(1)
if '<' not in ref and '.' not in ref:
full_ref = conf_name + ref
return ':opt:`{} <{}>`'.format(ref, full_ref)
return f':opt:`{ref} <{full_ref}>`'
return str(m.group())
return re.sub(r':opt:`(.+?)`', expand, text)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2018, Kovid Goyal <kovid at kovidgoyal.net>
import os
@ -130,7 +129,7 @@ def parse_line(
return
m = key_pat.match(line)
if m is None:
log_error('Ignoring invalid config line: {}'.format(line))
log_error(f'Ignoring invalid config line: {line}')
return
key, val = m.groups()
if key == 'include':
@ -152,7 +151,7 @@ def parse_line(
)
return
if not parse_conf_item(key, val, ans):
log_error('Ignoring unknown config key: {}'.format(key))
log_error(f'Ignoring unknown config key: {key}')
def _parse(
@ -199,8 +198,7 @@ def resolve_config(SYSTEM_CONF: str, defconf: str, config_files_on_cmd_line: Seq
if config_files_on_cmd_line:
if 'NONE' not in config_files_on_cmd_line:
yield SYSTEM_CONF
for cf in config_files_on_cmd_line:
yield cf
yield from config_files_on_cmd_line
else:
yield SYSTEM_CONF
yield defconf
@ -240,7 +238,7 @@ def key_func() -> Tuple[Callable[..., Callable], Dict[str, Callable]]:
for name in names:
if ans.setdefault(name, f) is not f:
raise ValueError(
'the args_func {} is being redefined'.format(name)
f'the args_func {name} is being redefined'
)
return f
@ -277,7 +275,7 @@ def parse_kittens_func_args(action: str, args_funcs: Dict[str, Callable]) -> Key
try:
func, args = parser(func, rest)
except Exception:
raise ValueError('Unknown key action: {}'.format(action))
raise ValueError(f'Unknown key action: {action}')
if not isinstance(args, (list, tuple)):
args = (args, )

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import json

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import errno
@ -89,7 +88,7 @@ def _get_config_dir() -> str:
try:
os.makedirs(ans, exist_ok=True)
except FileExistsError:
raise SystemExit('A file {} already exists. It must be a directory, not a file.'.format(ans))
raise SystemExit(f'A file {ans} already exists. It must be a directory, not a file.')
except PermissionError:
make_tmp_conf()
except OSError as err:

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import os
@ -128,7 +127,7 @@ def compare_opts(opts: KittyOpts, print: Callable) -> None:
if f not in ignored and getattr(opts, f) != getattr(defaults, f)
]
field_len = max(map(len, changed_opts)) if changed_opts else 20
fmt = '{{:{:d}s}}'.format(field_len)
fmt = f'{{:{field_len:d}s}}'
colors = []
for f in changed_opts:
val = getattr(opts, f)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
import errno

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
#
@ -372,7 +371,7 @@ def get_bezier_limits(bezier_x: ParameterizedFunc, bezier_y: ParameterizedFunc)
if q > x:
increment /= 2
if increment < 1e-6:
raise ValueError('Failed to find t for x={}'.format(x))
raise ValueError(f'Failed to find t for x={x}')
else:
start_t += increment
increment = t_limit - start_t
@ -1096,7 +1095,7 @@ def test_drawing(sz: int = 48, family: str = 'monospace', start: int = 0x2500, n
rgb_data = b''.join(rows)
width *= 32
height *= len(rows)
assert len(rgb_data) == width * height * 4, '{} != {}'.format(len(rgb_data), width * height * 4)
assert len(rgb_data) == width * height * 4, f'{len(rgb_data)} != {width * height * 4}'
display_bitmap(rgb_data, width, height)
finally:
set_send_sprite_to_gpu(None)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import re
@ -82,7 +81,7 @@ def find_best_match(family: str, bold: bool = False, italic: bool = False, ignor
# Let CoreText choose the font if the family exists, otherwise
# fallback to Menlo
if q not in font_map['family_map']:
log_error('The font {} was not found, falling back to Menlo'.format(family))
log_error(f'The font {family} was not found, falling back to Menlo')
q = 'menlo'
candidates = font_map['family_map'][q]
return sorted(candidates, key=score)[-1]

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import re
@ -84,7 +83,7 @@ def find_font_features(postscript_name: str) -> Tuple[FontFeature, ...]:
try:
parsed = parse_font_feature(feat)
except ValueError:
log_error('Ignoring invalid font feature: {}'.format(feat))
log_error(f'Ignoring invalid font feature: {feat}')
else:
features.append(FontFeature(feat, parsed))

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import ctypes

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os

1
kitty/key_encoding.py generated
View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2017, Kovid Goyal <kovid at kovidgoyal.net>
from enum import IntEnum

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
import sys

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Optional, Union

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from functools import partial

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from functools import lru_cache

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Dict, Tuple, Type

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import (
@ -324,7 +323,7 @@ class Pair:
return 'top', 'bottom'
return 'bottom', 'top'
geometries = dict((group.id, group.geometry) for group in all_windows.groups if group.geometry)
geometries = {group.id: group.geometry for group in all_windows.groups if group.geometry}
def extend(other: Union[int, 'Pair', None], edge: EdgeLiteral, which: EdgeLiteral) -> None:
if not ans[which] and other:

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from kitty.typing import WindowType

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from itertools import islice, repeat

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Any, Dict, Generator, Iterable, List, Tuple

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPL v3 Copyright: 2016, Kovid Goyal <kovid at kovidgoyal.net>
import locale
@ -50,7 +49,7 @@ def set_custom_ibeam_cursor() -> None:
try:
set_custom_cursor(GLFW_IBEAM_CURSOR, images, 4, 8)
except Exception as e:
log_error('Failed to set custom beam cursor with error: {}'.format(e))
log_error(f'Failed to set custom beam cursor with error: {e}')
def talk_to_instance(args: CLIOptions) -> None:
@ -61,7 +60,7 @@ def talk_to_instance(args: CLIOptions) -> None:
'cwd': os.getcwd()}
notify_socket = None
if args.wait_for_single_instance_window_close:
address = '\0{}-os-window-close-notify-{}-{}'.format(appname, os.getpid(), os.geteuid())
address = f'\0{appname}-os-window-close-notify-{os.getpid()}-{os.geteuid()}'
notify_socket = socket.socket(family=socket.AF_UNIX)
try:
notify_socket.bind(address)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
import os
@ -45,8 +44,8 @@ def marker_from_multiple_regex(regexes: Iterable[Tuple[int, str]], flags: int =
expr = ''
color_map = {}
for i, (color, spec) in enumerate(regexes):
grp = 'mcg{}'.format(i)
expr += '|(?P<{}>{})'.format(grp, spec)
grp = f'mcg{i}'
expr += f'|(?P<{grp}>{spec})'
color_map[grp] = color
expr = expr[1:]
pat = re.compile(expr, flags=flags)
@ -92,4 +91,4 @@ def marker_from_spec(ftype: str, spec: Union[str, Sequence[Tuple[int, str]]], fl
if not os.path.isabs(path):
path = os.path.join(config_dir, path)
return marker_from_function(runpy.run_path(path, run_name='__marker__')["marker"])
raise ValueError('Unknown marker type: {}'.format(ftype))
raise ValueError(f'Unknown marker type: {ftype}')

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
# Monkeypatch the stdlib multiprocessing module to work with the embedded python

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python3
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2019, Kovid Goyal <kovid at kovidgoyal.net>
from base64 import standard_b64decode

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
# After editing this file run ./gen-config.py to apply the changes

View File

@ -1,5 +1,4 @@
# generated by gen-config.py DO NOT edit
# vim:fileencoding=utf-8
import typing
from kitty.conf.utils import (

View File

@ -1,5 +1,4 @@
# generated by gen-config.py DO NOT edit
# vim:fileencoding=utf-8
import typing
from array import array

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2021, Kovid Goyal <kovid at kovidgoyal.net>
@ -104,7 +103,7 @@ def goto_tab_parse(func: str, rest: str) -> FuncArgsType:
@func_with_args('detach_window')
def detach_window_parse(func: str, rest: str) -> FuncArgsType:
if rest not in ('new', 'new-tab', 'ask', 'tab-prev', 'tab-left', 'tab-right'):
log_error('Ignoring invalid detach_window argument: {}'.format(rest))
log_error(f'Ignoring invalid detach_window argument: {rest}')
rest = 'new'
return func, (rest,)
@ -112,7 +111,7 @@ def detach_window_parse(func: str, rest: str) -> FuncArgsType:
@func_with_args('detach_tab')
def detach_tab_parse(func: str, rest: str) -> FuncArgsType:
if rest not in ('new', 'ask'):
log_error('Ignoring invalid detach_tab argument: {}'.format(rest))
log_error(f'Ignoring invalid detach_tab argument: {rest}')
rest = 'new'
return func, (rest,)
@ -145,7 +144,7 @@ def signal_child_parse(func: str, rest: str) -> FuncArgsType:
def parse_change_font_size(func: str, rest: str) -> Tuple[str, Tuple[bool, Optional[str], float]]:
vals = rest.strip().split(maxsplit=1)
if len(vals) != 2:
log_error('Invalid change_font_size specification: {}, treating it as default'.format(rest))
log_error(f'Invalid change_font_size specification: {rest}, treating it as default')
return func, (True, None, 0)
c_all = vals[0].lower() == 'all'
sign: Optional[str] = None
@ -182,7 +181,7 @@ def neighboring_window(func: str, rest: str) -> FuncArgsType:
rest = rest.lower()
rest = {'up': 'top', 'down': 'bottom'}.get(rest, rest)
if rest not in ('left', 'right', 'top', 'bottom'):
log_error('Invalid neighbor specification: {}'.format(rest))
log_error(f'Invalid neighbor specification: {rest}')
rest = 'right'
return func, [rest]
@ -196,14 +195,14 @@ def resize_window(func: str, rest: str) -> FuncArgsType:
else:
quality = vals[0].lower()
if quality not in ('taller', 'shorter', 'wider', 'narrower'):
log_error('Invalid quality specification: {}'.format(quality))
log_error(f'Invalid quality specification: {quality}')
quality = 'wider'
increment = 1
if len(vals) == 2:
try:
increment = int(vals[1])
except Exception:
log_error('Invalid increment specification: {}'.format(vals[1]))
log_error(f'Invalid increment specification: {vals[1]}')
args = [quality, increment]
return func, args
@ -217,7 +216,7 @@ def move_window(func: str, rest: str) -> FuncArgsType:
prest = int(prest)
except Exception:
if prest not in ('left', 'right', 'top', 'bottom'):
log_error('Invalid move_window specification: {}'.format(rest))
log_error(f'Invalid move_window specification: {rest}')
prest = 0
return func, [prest]
@ -269,9 +268,9 @@ def disable_ligatures_in(func: str, rest: str) -> FuncArgsType:
else:
where, strategy = parts
if where not in ('active', 'all', 'tab'):
raise ValueError('{} is not a valid set of windows to disable ligatures in'.format(where))
raise ValueError(f'{where} is not a valid set of windows to disable ligatures in')
if strategy not in ('never', 'always', 'cursor'):
raise ValueError('{} is not a valid disable ligatures strategy'.format(strategy))
raise ValueError(f'{strategy} is not a valid disable ligatures strategy')
return func, [where, strategy]
@ -295,7 +294,7 @@ def parse_marker_spec(ftype: str, parts: Sequence[str]) -> Tuple[str, Union[str,
try:
color = max(1, min(int(parts[i]), 3))
except Exception:
raise ValueError('color {} in marker specification is not an integer'.format(parts[i]))
raise ValueError(f'color {parts[i]} in marker specification is not an integer')
sspec = parts[i + 1]
if 'regex' not in ftype:
sspec = re.escape(sspec)
@ -305,7 +304,7 @@ def parse_marker_spec(ftype: str, parts: Sequence[str]) -> Tuple[str, Union[str,
elif ftype == 'function':
spec = ' '.join(parts)
else:
raise ValueError('Unknown marker type: {}'.format(ftype))
raise ValueError(f'Unknown marker type: {ftype}')
return ftype, spec, flags
@ -314,7 +313,7 @@ def toggle_marker(func: str, rest: str) -> FuncArgsType:
import shlex
parts = rest.split(maxsplit=1)
if len(parts) != 2:
raise ValueError('{} is not a valid marker specification'.format(rest))
raise ValueError(f'{rest} is not a valid marker specification')
ftype, spec = parts
parts = shlex.split(spec)
return func, list(parse_marker_spec(ftype, parts))
@ -332,7 +331,7 @@ def scroll_to_mark(func: str, rest: str) -> FuncArgsType:
try:
return func, [True, max(0, min(int(q), 3))]
except Exception:
raise ValueError('{} is not a valid scroll_to_mark destination'.format(rest))
raise ValueError(f'{rest} is not a valid scroll_to_mark destination')
return func, [parts[0] != 'next', max(0, min(int(parts[1]), 3))]
@ -371,7 +370,7 @@ def parse_mods(parts: Iterable[str], sc: str) -> Optional[int]:
mods |= getattr(defines, 'GLFW_MOD_' + map_mod(m.upper()))
except AttributeError:
if m.upper() != 'NONE':
log_error('Shortcut: {} has unknown modifier, ignoring'.format(sc))
log_error(f'Shortcut: {sc} has unknown modifier, ignoring')
return None
return mods
@ -493,9 +492,9 @@ def url_style(x: str) -> int:
return url_style_map.get(x, url_style_map['curly'])
url_style_map = dict(
((v, i) for i, v in enumerate('none single double curly'.split()))
)
url_style_map = {
v: i for i, v in enumerate('none single double curly'.split())
}
def url_prefixes(x: str) -> Tuple[str, ...]:
@ -528,13 +527,13 @@ def parse_layout_names(parts: Iterable[str]) -> List[str]:
continue
name = p.partition(':')[0]
if name not in all_layouts:
raise ValueError('The window layout {} is unknown'.format(p))
raise ValueError(f'The window layout {p} is unknown')
ans.append(p)
return uniq(ans)
def to_layout_names(raw: str) -> List[str]:
return parse_layout_names((x.strip() for x in raw.split(',')))
return parse_layout_names(x.strip() for x in raw.split(','))
def window_border_width(x: Union[str, int, float]) -> Tuple[float, str]:
@ -721,7 +720,7 @@ def font_features(val: str) -> Iterable[Tuple[str, Tuple[FontFeature, ...]]]:
return
parts = val.split()
if len(parts) < 2:
log_error("Ignoring invalid font_features {}".format(val))
log_error(f"Ignoring invalid font_features {val}")
return
if parts[0]:
features = []
@ -729,7 +728,7 @@ def font_features(val: str) -> Iterable[Tuple[str, Tuple[FontFeature, ...]]]:
try:
parsed = defines.parse_font_feature(feat)
except ValueError:
log_error('Ignoring invalid font feature: {}'.format(feat))
log_error(f'Ignoring invalid font feature: {feat}')
else:
features.append(FontFeature(feat, parsed))
yield parts[0], tuple(features)
@ -886,7 +885,7 @@ def parse_map(val: str) -> Iterable[KeyDefinition]:
return
if key == 0:
if mods is not None:
log_error('Shortcut: {} has unknown key, ignoring'.format(sc))
log_error(f'Shortcut: {sc} has unknown key, ignoring')
return
if trigger is None:
trigger = SingleKey(mods, is_native, key)
@ -900,7 +899,7 @@ def parse_map(val: str) -> Iterable[KeyDefinition]:
return
if key == 0:
if mods is not None:
log_error('Shortcut: {} has unknown key, ignoring'.format(sc))
log_error(f'Shortcut: {sc} has unknown key, ignoring')
return
try:
paction = parse_key_action(action)
@ -961,7 +960,7 @@ def parse_mouse_map(val: str) -> Iterable[MouseMapping]:
def deprecated_hide_window_decorations_aliases(key: str, val: str, ans: Dict[str, Any]) -> None:
if not hasattr(deprecated_hide_window_decorations_aliases, key):
setattr(deprecated_hide_window_decorations_aliases, key, True)
log_error('The option {} is deprecated. Use hide_window_decorations instead.'.format(key))
log_error(f'The option {key} is deprecated. Use hide_window_decorations instead.')
if to_bool(val):
if is_macos and key == 'macos_hide_titlebar' or (not is_macos and key == 'x11_hide_window_decorations'):
ans['hide_window_decorations'] = True
@ -970,7 +969,7 @@ def deprecated_hide_window_decorations_aliases(key: str, val: str, ans: Dict[str
def deprecated_macos_show_window_title_in_menubar_alias(key: str, val: str, ans: Dict[str, Any]) -> None:
if not hasattr(deprecated_macos_show_window_title_in_menubar_alias, key):
setattr(deprecated_macos_show_window_title_in_menubar_alias, 'key', True)
log_error('The option {} is deprecated. Use macos_show_window_title_in menubar instead.'.format(key))
log_error(f'The option {key} is deprecated. Use macos_show_window_title_in menubar instead.')
macos_show_window_title_in = ans.get('macos_show_window_title_in', 'all')
if to_bool(val):
if macos_show_window_title_in == 'none':
@ -996,6 +995,6 @@ def deprecated_send_text(key: str, val: str, ans: Dict[str, Any]) -> None:
return abort('Incomplete')
mode, sc = parts[:2]
text = ' '.join(parts[2:])
key_str = '{} send_text {} {}'.format(sc, mode, text)
key_str = f'{sc} send_text {mode} {text}'
for k in parse_map(key_str):
ans['map'].append(k)

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Any, Callable, Dict, NamedTuple, Tuple

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from contextlib import suppress
@ -37,7 +36,7 @@ class MatchError(ValueError):
hide_traceback = True
def __init__(self, expression: str, target: str = 'windows'):
ValueError.__init__(self, 'No matching {} for expression: {}'.format(target, expression))
ValueError.__init__(self, f'No matching {target} for expression: {expression}')
class OpacityError(ValueError):
@ -199,15 +198,15 @@ class RemoteCommand:
def cli_params_for(command: RemoteCommand) -> Tuple[Callable[[], str], str, str, str]:
return (command.options_spec or '\n').format, command.argspec, command.desc, '{} @ {}'.format(appname, command.name)
return (command.options_spec or '\n').format, command.argspec, command.desc, f'{appname} @ {command.name}'
def parse_subcommand_cli(command: RemoteCommand, args: ArgsType) -> Tuple[Any, ArgsType]:
opts, items = parse_args(args[1:], *cli_params_for(command), result_class=command.options_class)
if command.args_count is not None and command.args_count != len(items):
if command.args_count == 0:
raise SystemExit('Unknown extra argument(s) supplied to {}'.format(command.name))
raise SystemExit('Must specify exactly {} argument(s) for {}'.format(command.args_count, command.name))
raise SystemExit(f'Unknown extra argument(s) supplied to {command.name}')
raise SystemExit(f'Must specify exactly {command.args_count} argument(s) for {command.name}')
return opts, items

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import TYPE_CHECKING, Optional

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import TYPE_CHECKING, Optional

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import TYPE_CHECKING, Optional, Union

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import Any, Optional

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>
from typing import TYPE_CHECKING, Optional

View File

@ -1,5 +1,4 @@
#!/usr/bin/env python
# vim:fileencoding=utf-8
# License: GPLv3 Copyright: 2020, Kovid Goyal <kovid at kovidgoyal.net>

Some files were not shown because too many files have changed in this diff Show More