Here's egmont's and Aaron Digulla's answers combined into one script:
import termios
import array
import fcntl
import tty
import sys
def get_text_area_size(): # https://gist.github.com/secemp9/ab0ce0bfb0eaf73d831033dbfade44d9 + ...
# Save the terminal's original settings
fd = sys.stdin.fileno()
original_attributes = termios.tcgetattr(fd)
try:
# Set the terminal to raw mode
tty.setraw(sys.stdin.fileno())
# Query the text area size
print("\x1b[14t", end="", flush=True)
# Read the response (format: "\x1b[4;height;widtht")
response = ""
while True:
char = sys.stdin.read(1) # (in nvim-toogleterm for some reason stucks)
response += char
if char == "t":
break
# Parse the response to extract height and width
if response:
return tuple(map(int, response[:-1].split(';')[1:]))
else: # ... https://mcmap.net/q/1433245/-how-to-get-terminal-size-or-font-size-in-pixels
buf = array.array('H', [0, 0, 0, 0])
fcntl.ioctl(1, termios.TIOCGWINSZ, buf)
return (buf[3], buf[2])
finally:
# Restore the terminal's original settings
termios.tcsetattr(fd, termios.TCSADRAIN, original_attributes)
# Example usage
text_area_size = get_text_area_size()
if text_area_size:
print(f"Text area size is {text_area_size[0]} rows by {text_area_size[1]} columns")
else:
print("Failed to get text area size")
Thanks to: source
read
) – Gig