diff --git a/docs/graphics-protocol.rst b/docs/graphics-protocol.rst index be45e6e73..55b818446 100644 --- a/docs/graphics-protocol.rst +++ b/docs/graphics-protocol.rst @@ -107,7 +107,8 @@ features of the graphics protocol: sys.stdout.flush() cmd.clear() - write_chunked({'a': 'T', 'f': 100}, open(sys.argv[-1], 'rb').read()) + with open(sys.argv[-1], 'rb') as f: + write_chunked({'a': 'T', 'f': 100}, f.read()) Save this script as :file:`png.py`, then you can use it to display any PNG diff --git a/docs/installer.py b/docs/installer.py index fa67b1259..8b4dd4768 100644 --- a/docs/installer.py +++ b/docs/installer.py @@ -229,7 +229,8 @@ def script_launch(): def update_intaller_wrapper(): # To run: python3 -c "import runpy; runpy.run_path('installer.py', run_name='update_wrapper')" installer.sh - src = open(__file__, 'rb').read().decode('utf-8') + with open(__file__, 'rb') as f: + src = f.read().decode('utf-8') wrapper = sys.argv[-1] with open(wrapper, 'r+b') as f: raw = f.read().decode('utf-8') diff --git a/gen-wcwidth.py b/gen-wcwidth.py index 2a1e307d1..1242e8ded 100755 --- a/gen-wcwidth.py +++ b/gen-wcwidth.py @@ -29,10 +29,12 @@ def get_data(fname, folder='UCD'): bn = os.path.basename(url) local = os.path.join('/tmp', bn) if os.path.exists(local): - data = open(local, 'rb').read() + with open(local, 'rb') as f: + data = f.read() else: data = urlopen(url).read() - open(local, 'wb').write(data) + with open(local, 'wb') as f: + f.write(data) for line in data.decode('utf-8').splitlines(): line = line.strip() if line and not line.startswith('#'): @@ -166,21 +168,20 @@ def write_case(spec, p): @contextmanager def create_header(path, include_data_types=True): - f = open(path, 'w') - p = partial(print, file=f) - p('// unicode data, built from the unicode standard on:', date.today()) - p('// see gen-wcwidth.py') - if path.endswith('.h'): - p('#pragma once') - if include_data_types: - p('#include "data-types.h"\n') - p('START_ALLOW_CASE_RANGE') - p() - yield p - p() - if include_data_types: - p('END_ALLOW_CASE_RANGE') - f.close() + with open(path, 'w') as f: + p = partial(print, file=f) + p('// unicode data, built from the unicode standard on:', date.today()) + p('// see gen-wcwidth.py') + if path.endswith('.h'): + p('#pragma once') + if include_data_types: + p('#include "data-types.h"\n') + p('START_ALLOW_CASE_RANGE') + p() + yield p + p() + if include_data_types: + p('END_ALLOW_CASE_RANGE') def gen_emoji(): @@ -282,7 +283,9 @@ def gen_ucd(): p('combining_type mark_for_codepoint(char_type c) {') rmap = codepoint_to_mark_map(p, mark_map) p('}\n') - expected = int(re.search(r'^#define VS15 (\d+)', open('kitty/unicode-data.h').read(), re.M).group(1)) + with open('kitty/unicode-data.h') as f: + unicode_data = f.read() + expected = int(re.search(r'^#define VS15 (\d+)', unicode_data, re.M).group(1)) if rmap[0xfe0e] != expected: raise ValueError('The mark for 0xfe0e has changed, you have to update VS15 to {} and VS16 to {} in unicode-data.h'.format( rmap[0xfe0e], rmap[0xfe0f] diff --git a/glfw/glfw.py b/glfw/glfw.py index 3f6f31ee6..d5c855caa 100755 --- a/glfw/glfw.py +++ b/glfw/glfw.py @@ -38,7 +38,8 @@ def init_env(env, pkg_config, at_least_version, test_compile, module='x11'): ) else: ans.ldpaths.extend('-lrt -lm -ldl'.split()) - sinfo = json.load(open(os.path.join(base, 'source-info.json'))) + with open(os.path.join(base, 'source-info.json')) as f: + sinfo = json.load(f) module_sources = list(sinfo[module]['sources']) if module in ('x11', 'wayland'): remove = 'linux_joystick.c' if is_bsd else 'null_joystick.c' @@ -157,7 +158,8 @@ class Function: def generate_wrappers(glfw_header): - src = open(glfw_header).read() + with open(glfw_header) as f: + src = f.read() functions = [] first = None for m in re.finditer(r'^GLFWAPI\s+(.+[)]);\s*$', src, flags=re.MULTILINE): diff --git a/kittens/tui/images.py b/kittens/tui/images.py index 2f64e362e..194b69a2d 100644 --- a/kittens/tui/images.py +++ b/kittens/tui/images.py @@ -249,7 +249,8 @@ class ImageManager: cmd, standard_b64encode(rgba_path.encode(fsenc))) else: import zlib - data = open(rgba_path, 'rb').read() + with open(rgba_path, 'rb') as f: + data = f.read() cmd['S'] = len(data) data = zlib.compress(data) cmd['o'] = 'z' diff --git a/kitty/child.py b/kitty/child.py index 58b43538d..4e8855b57 100644 --- a/kitty/child.py +++ b/kitty/child.py @@ -30,14 +30,16 @@ if is_macos: else: def cmdline_of_process(pid): - return list(filter(None, open('/proc/{}/cmdline'.format(pid), 'rb').read().decode('utf-8').split('\0'))) + with open('/proc/{}/cmdline'.format(pid), 'rb') as f: + return list(filter(None, f.read().decode('utf-8').split('\0'))) def cwd_of_process(pid): ans = '/proc/{}/cwd'.format(pid) return os.path.realpath(ans) def _environ_of_process(pid): - return open('/proc/{}/environ'.format(pid), 'rb').read().decode('utf-8') + with open('/proc/{}/environ'.format(pid), 'rb') as f: + return f.read().decode('utf-8') def process_group_map(): ans = defaultdict(list) @@ -47,7 +49,8 @@ else: except Exception: continue try: - raw = open('/proc/' + x + '/stat', 'rb').read().decode('utf-8') + with open('/proc/' + x + '/stat', 'rb') as f: + raw = f.read().decode('utf-8') except EnvironmentError: continue try: diff --git a/kitty/cli.py b/kitty/cli.py index 14ca30dce..acbdc68a6 100644 --- a/kitty/cli.py +++ b/kitty/cli.py @@ -728,9 +728,11 @@ def create_opts(args, debug_config=False, accumulate_bad_lines=None): import subprocess print(' '.join(subprocess.check_output(['sw_vers']).decode('utf-8').splitlines()).strip()) if os.path.exists('/etc/issue'): - print(open('/etc/issue', encoding='utf-8', errors='replace').read().strip()) + with open('/etc/issue', encoding='utf-8', errors='replace') as f: + print(f.read().strip()) if os.path.exists('/etc/lsb-release'): - print(open('/etc/lsb-release', encoding='utf-8', errors='replace').read().strip()) + with open('/etc/lsb-release', encoding='utf-8', errors='replace') as f: + print(f.read().strip()) config = tuple(x for x in config if os.path.exists(x)) if config: print(green('Loaded config files:'), ', '.join(config)) diff --git a/kitty/client.py b/kitty/client.py index c7f4fbf01..498268ae3 100644 --- a/kitty/client.py +++ b/kitty/client.py @@ -157,7 +157,8 @@ def replay(raw): def main(path): - raw = open(path).read() + with open(path) as f: + raw = f.read() replay(raw) with suppress(EOFError, KeyboardInterrupt): input() diff --git a/kitty/conf/utils.py b/kitty/conf/utils.py index d16999d5d..136b3e7ea 100644 --- a/kitty/conf/utils.py +++ b/kitty/conf/utils.py @@ -177,12 +177,11 @@ def load_config(Options, defaults, parse_config, merge_configs, *paths, override if not path: continue try: - f = open(path, encoding='utf-8', errors='replace') + with open(path, encoding='utf-8', errors='replace') as f: + vals = parse_config(f) except FileNotFoundError: continue - with f: - vals = parse_config(f) - ans = merge_configs(ans, vals) + ans = merge_configs(ans, vals) if overrides is not None: vals = parse_config(overrides) ans = merge_configs(ans, vals) diff --git a/kitty/keys.py b/kitty/keys.py index e11a10161..07141a03e 100644 --- a/kitty/keys.py +++ b/kitty/keys.py @@ -293,99 +293,99 @@ def generate_key_table(): # To run this, use: python3 . +runpy "from kitty.keys import *; generate_key_table()" import os from functools import partial - f = open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys.h'), 'w') - w = partial(print, file=f) - w('// auto-generated from keys.py, do not edit!') - w('#pragma once') - w('#include ') - w('#include ') - w('#include ') - w('#include ') - number_of_keys = defines.GLFW_KEY_LAST + 1 - w('// map glfw key numbers to 7-bit numbers for compact data storage') - w('static const uint8_t key_map[%d] = {' % number_of_keys) - key_count = 0 + with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys.h'), 'w') as f: + w = partial(print, file=f) + w('// auto-generated from keys.py, do not edit!') + w('#pragma once') + w('#include ') + w('#include ') + w('#include ') + w('#include ') + number_of_keys = defines.GLFW_KEY_LAST + 1 + w('// map glfw key numbers to 7-bit numbers for compact data storage') + w('static const uint8_t key_map[%d] = {' % number_of_keys) + key_count = 0 - def key_name(k): - return k[len('GLFW_KEY_'):] + def key_name(k): + return k[len('GLFW_KEY_'):] - keys = {v: k for k, v in vars(defines).items() if k.startswith('GLFW_KEY_') and k not in {'GLFW_KEY_LAST', 'GLFW_KEY_UNKNOWN'}} - key_rmap = [] - for i in range(number_of_keys): - k = keys.get(i) - if k is None: - w('UINT8_MAX,') - else: - w('%d, /* %s */' % (key_count, key_name(k))) - key_rmap.append(i) - key_count += 1 - if key_count > 128: - raise OverflowError('Too many keys') - w('};\n') - w('static inline const char* key_name(int key) { switch(key) {') - for i in range(number_of_keys): - k = keys.get(i) - if k is not None: - w('case %d: return "%s";' % (i, key_name(k))) - w('default: return NULL; }}\n') - w('typedef enum { NORMAL, APPLICATION, EXTENDED } KeyboardMode;\n') - w('static inline const char*\nkey_lookup(uint8_t key, KeyboardMode mode, uint8_t mods, uint8_t action) {') - i = 1 - - def ind(*a): - w((' ' * i)[:-1], *a) - ind('switch(mode) {') - mmap = [(False, False), (True, False), (False, True)] - for (smkx, extended), mode in zip(mmap, 'NORMAL APPLICATION EXTENDED'.split()): - i += 1 - ind('case {}:'.format(mode)) - i += 1 - ind('switch(action & 3) { case 3: return NULL;') - for action in (defines.GLFW_RELEASE, defines.GLFW_PRESS, defines.GLFW_REPEAT): - i += 1 - ind('case {}: // {}'.format(action, 'RELEASE PRESS REPEAT'.split()[action])) - i += 1 - if action != defines.GLFW_RELEASE or mode == 'EXTENDED': - ind('switch (mods & 0xf) {') - i += 1 - for mods in range(16): - key_bytes = {} - for key in range(key_count): - glfw_key = key_rmap[key] - data = key_to_bytes(glfw_key, smkx, extended, mods, action) - if data: - key_bytes[key] = data, glfw_key - i += 1 - ind('case 0x{:x}:'.format(mods)) - i += 1 - if key_bytes: - ind('switch(key & 0x7f) { default: return NULL;') - i += 1 - for key, (data, glfw_key) in key_bytes.items(): - ind('case {}: // {}'.format(key, key_name(keys[glfw_key]))) - i += 1 - items = bytearray(data) - items.insert(0, len(items)) - ind('return "{}";'.format(''.join('\\x{:02x}'.format(x) for x in items))) - i -= 1 - i -= 1 - ind('} // end switch(key)') - else: - ind('return NULL;') - i -= 2 - i -= 1 - ind('} // end switch(mods)') - ind('break;\n') - i -= 1 + keys = {v: k for k, v in vars(defines).items() if k.startswith('GLFW_KEY_') and k not in {'GLFW_KEY_LAST', 'GLFW_KEY_UNKNOWN'}} + key_rmap = [] + for i in range(number_of_keys): + k = keys.get(i) + if k is None: + w('UINT8_MAX,') else: - ind('return NULL;\n') + w('%d, /* %s */' % (key_count, key_name(k))) + key_rmap.append(i) + key_count += 1 + if key_count > 128: + raise OverflowError('Too many keys') + w('};\n') + w('static inline const char* key_name(int key) { switch(key) {') + for i in range(number_of_keys): + k = keys.get(i) + if k is not None: + w('case %d: return "%s";' % (i, key_name(k))) + w('default: return NULL; }}\n') + w('typedef enum { NORMAL, APPLICATION, EXTENDED } KeyboardMode;\n') + w('static inline const char*\nkey_lookup(uint8_t key, KeyboardMode mode, uint8_t mods, uint8_t action) {') + i = 1 + + def ind(*a): + w((' ' * i)[:-1], *a) + ind('switch(mode) {') + mmap = [(False, False), (True, False), (False, True)] + for (smkx, extended), mode in zip(mmap, 'NORMAL APPLICATION EXTENDED'.split()): + i += 1 + ind('case {}:'.format(mode)) + i += 1 + ind('switch(action & 3) { case 3: return NULL;') + for action in (defines.GLFW_RELEASE, defines.GLFW_PRESS, defines.GLFW_REPEAT): + i += 1 + ind('case {}: // {}'.format(action, 'RELEASE PRESS REPEAT'.split()[action])) + i += 1 + if action != defines.GLFW_RELEASE or mode == 'EXTENDED': + ind('switch (mods & 0xf) {') + i += 1 + for mods in range(16): + key_bytes = {} + for key in range(key_count): + glfw_key = key_rmap[key] + data = key_to_bytes(glfw_key, smkx, extended, mods, action) + if data: + key_bytes[key] = data, glfw_key + i += 1 + ind('case 0x{:x}:'.format(mods)) + i += 1 + if key_bytes: + ind('switch(key & 0x7f) { default: return NULL;') + i += 1 + for key, (data, glfw_key) in key_bytes.items(): + ind('case {}: // {}'.format(key, key_name(keys[glfw_key]))) + i += 1 + items = bytearray(data) + items.insert(0, len(items)) + ind('return "{}";'.format(''.join('\\x{:02x}'.format(x) for x in items))) + i -= 1 + i -= 1 + ind('} // end switch(key)') + else: + ind('return NULL;') + i -= 2 + i -= 1 + ind('} // end switch(mods)') + ind('break;\n') + i -= 1 + else: + ind('return NULL;\n') + i -= 1 i -= 1 + ind('}} // end switch(action) in mode {}'.format(mode)) + ind('break;\n\n') i -= 1 - ind('}} // end switch(action) in mode {}'.format(mode)) - ind('break;\n\n') i -= 1 - i -= 1 - ind('}') - ind('return NULL;') - i -= 1 - w('}') + ind('}') + ind('return NULL;') + i -= 1 + w('}') diff --git a/kitty/rgb.py b/kitty/rgb.py index a70f8127a..510c13ff7 100644 --- a/kitty/rgb.py +++ b/kitty/rgb.py @@ -835,14 +835,15 @@ if __name__ == '__main__': import sys import pprint data = {} - for line in open(sys.argv[-1]): - line = line.strip() - if not line or line.startswith('!'): - continue - parts = line.split() - r, g, b = map(int, parts[:3]) - name = ' '.join(parts[3:]).lower() - data[name] = data[name.replace(' ', '')] = r, g, b + with open(sys.argv[-1]) as f: + for line in f: + line = line.strip() + if not line or line.startswith('!'): + continue + parts = line.split() + r, g, b = map(int, parts[:3]) + name = ' '.join(parts[3:]).lower() + data[name] = data[name.replace(' ', '')] = r, g, b data = pprint.pformat(data).replace('{', '{\n ').replace('(', 'Color(') with open(__file__, 'r+') as src: raw = src.read() diff --git a/kitty/utils.py b/kitty/utils.py index 94f7b5bf1..06c2c30f7 100644 --- a/kitty/utils.py +++ b/kitty/utils.py @@ -23,8 +23,10 @@ BASE = os.path.dirname(os.path.abspath(__file__)) def load_shaders(name): from .fast_data_types import GLSL_VERSION - vert = open(os.path.join(BASE, '{}_vertex.glsl'.format(name))).read().replace('GLSL_VERSION', str(GLSL_VERSION), 1) - frag = open(os.path.join(BASE, '{}_fragment.glsl'.format(name))).read().replace('GLSL_VERSION', str(GLSL_VERSION), 1) + with open(os.path.join(BASE, '{}_vertex.glsl'.format(name))) as f: + vert = f.read().replace('GLSL_VERSION', str(GLSL_VERSION), 1) + with open(os.path.join(BASE, '{}_fragment.glsl'.format(name))) as f: + frag = f.read().replace('GLSL_VERSION', str(GLSL_VERSION), 1) return vert, frag diff --git a/kitty_tests/gr.py b/kitty_tests/gr.py index 0d1f25eb2..6f9bfb17b 100755 --- a/kitty_tests/gr.py +++ b/kitty_tests/gr.py @@ -56,7 +56,8 @@ def main(): raise SystemExit('Must specify a PNG file to display') clear_screen() display(b'\xdd\xdd\xdd\xff', 1, 1, 0, 0, -10, 40, 20) - display(open(os.path.join(base, '../logo/kitty.rgba'), 'rb').read(), 256, 256, 0, 5, -9) + with open(os.path.join(base, '../logo/kitty.rgba'), 'rb') as f: + display(f.read(), 256, 256, 0, 5, -9) display(b'\0\0\0\xaa', 1, 1, 0, 7, -8, 40, 3) move_cursor(5, 8) print('kitty is \033[3m\033[32mawesome\033[m!') diff --git a/publish.py b/publish.py index 5764d2ac9..b61a586ef 100755 --- a/publish.py +++ b/publish.py @@ -23,7 +23,8 @@ os.chdir(os.path.dirname(os.path.abspath(__file__))) build_path = os.path.abspath('../build-kitty') docs_dir = os.path.abspath('docs') publish_dir = os.path.abspath(os.path.join('..', 'kovidgoyal.github.io', 'kitty')) -raw = open('kitty/constants.py').read() +with open('kitty/constants.py') as f: + raw = f.read() nv = re.search( r'^version\s+=\s+\((\d+), (\d+), (\d+)\)', raw, flags=re.MULTILINE) version = '%s.%s.%s' % (nv.group(1), nv.group(2), nv.group(3)) diff --git a/setup.py b/setup.py index e7c6ba930..68e474118 100755 --- a/setup.py +++ b/setup.py @@ -315,7 +315,8 @@ def get_vcs_rev_defines(): with open('.git/refs/heads/master') as f: rev = f.read() except NotADirectoryError: - gitloc = open('.git').read() + with open('.git') as f: + gitloc = f.read() with open(os.path.join(gitloc, 'refs/heads/master')) as f: rev = f.read() @@ -343,7 +344,8 @@ def newer(dest, *sources): def dependecies_for(src, obj, all_headers): dep_file = obj.rpartition('.')[0] + '.d' try: - deps = open(dep_file).read() + with open(dep_file) as f: + deps = f.read() except FileNotFoundError: yield src yield from iter(all_headers) diff --git a/update-on-ox b/update-on-ox index 01d4f444a..aa5d4fe28 100755 --- a/update-on-ox +++ b/update-on-ox @@ -46,7 +46,8 @@ def run(what): raise SystemExit(ret.returncode) -script = open(__file__, 'rb').read().decode('utf-8') +with open(__file__, 'rb') as f: + script = f.read().decode('utf-8') script = script[:script.find('# EOF_REMOTE')].replace('if False:', 'if True:', 1) os.chdir(os.path.expanduser('~/work/build-kitty')) with tempfile.NamedTemporaryFile(prefix='install-dmg-', suffix='.py') as f: diff --git a/update-on-ubuntu b/update-on-ubuntu index f01a7a26f..f7b43e5d2 100755 --- a/update-on-ubuntu +++ b/update-on-ubuntu @@ -44,7 +44,8 @@ def run(what): raise SystemExit(ret.returncode) -script = open(__file__, 'rb').read().decode('utf-8') +with open(__file__, 'rb') as f: + script = f.read().decode('utf-8') script = script[:script.find('# EOF_REMOTE')].replace('if False:', 'if True:', 1) os.chdir(os.path.expanduser('~/work/build-kitty')) with tempfile.NamedTemporaryFile(prefix='install-tarball-', suffix='.py') as f: