Skip to content

Instantly share code, notes, and snippets.

@Thesola10
Last active January 26, 2022 07:10
Show Gist options
  • Save Thesola10/3c139d55b9dec8c17ed59fd9b6d6c468 to your computer and use it in GitHub Desktop.
Save Thesola10/3c139d55b9dec8c17ed59fd9b6d6c468 to your computer and use it in GitHub Desktop.
Wrapper around bat and pixcat to display images in the bat command
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This script is designed to be installed in ~/.local/bin/bat or equivalent
from os import execvp
import sys
import subprocess
if __name__ == "__main__":
try:
# If you installed pixcat as single-user (or not at all), this script would fail entirely.
from pixcat import Image
# The margin is needed to leave room for bat header and footer
im = Image(sys.argv[1]).fit_screen(v_margin=-2, h_margin=-1)
# This instance of bat is only used to print filename and vertical space, which maintains the illusion
bt = subprocess.Popen(["/usr/bin/bat", "--style=header,grid", "--paging=never", "--file-name", sys.argv[1]] + sys.argv[2:], stdin=subprocess.PIPE)
# We send it the vertical space in the form of newline characters
bt.communicate(b"\n" * im.rows)
# We send the cursor all the way back up (plus bat's two newlines)
print("\033[A" * (im.rows+2))
# And show the image and restore bat's end line.
im.show()
print("")
except:
# If anything went wrong when making the Image() instance, fall back to regular bat
execvp("/usr/bin/bat", sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment