Skip to content

Instantly share code, notes, and snippets.

@zeero
Created March 30, 2011 14:08
Show Gist options
  • Save zeero/894454 to your computer and use it in GitHub Desktop.
Save zeero/894454 to your computer and use it in GitHub Desktop.
detect tty width & height
# Determines if a shell command exists by searching for it in ENV['PATH'].
def command_exists?(command)
ENV['PATH'].split(File::PATH_SEPARATOR).any? {
|d| File.exists? File.join(d, command)
}
end
# Returns [width, height] of terminal when detected, nil if not detected.
def detect_terminal_size
@log.debug_var binding, "ENV['COLUMNS']", "ENV['LINES']"
if (ENV['COLUMNS'] =~ /^\d+$/) && (ENV['LINES'] =~ /^\d+$/)
[ENV['COLUMNS'].to_i, ENV['LINES'].to_i]
elsif (RUBY_PLATFORM =~ /java/ || (!STDIN.tty? && ENV['TERM'])) && command_exists?('tput')
[`tput cols`.to_i, `tput lines`.to_i]
elsif STDIN.tty? && command_exists?('stty')
`stty size`.scan(/\d+/).map { |s| s.to_i }.reverse
else
[0, 0]
end
rescue
[0, 0]
end
@zeero
Copy link
Author

zeero commented Mar 30, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment