Skip to content

Instantly share code, notes, and snippets.

@ttdoda
Last active November 19, 2023 16:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ttdoda/413834b50497d63feadad750ce787c85 to your computer and use it in GitHub Desktop.
Save ttdoda/413834b50497d63feadad750ce787c85 to your computer and use it in GitHub Desktop.
xterm付属のresizeコマンドの手抜き再実装
#!/usr/bin/env ruby
#encoding: ASCII-8BIT
#
# resize.rb -- resize コマンドの手抜き実装
#
# xterm の付属コマンド resize[1] の機能の内、端末(エミュレータ)の現在の
# サイズを調べて TTY の設定を合わせる機能の実装例です。
#
# 原理:
# カーソル位置を 9999 行目 9999 桁目に移動する命令を送信し、実際に移動した
# 位置を確認する事で端末のサイズを判別しています。
# 端末の幅または高さが 10000 以上の時は誤動作します。
#
# *1: http://invisible-island.net/xterm/manpage/resize.html
#
# License: CC0
require 'io/console'
STTY = "/bin/stty"
resp = ""
STDIN.raw do |stdin|
STDERR.print "\e7" # カーソル位置保存
STDERR.print "\e[9999;9999H" # カーソルを 9999, 9999 に移動
STDERR.print "\e[6n" # カーソル位置問い合わせ
STDERR.print "\r" # カーソル位置を行頭に移動 -- DECSC/DECRC 非対応端末向け
STDERR.print "\e8" # カーソル位置復元
resp = ""
while (c = stdin.getc)
break unless /[\[\x1b\x9c;0-9]/ =~ c
resp << c.chr
end
resp << c.chr
end
if /(?:\x9c|\x1b\[)(\d+);(\d+)R/ =~ resp # 応答が正しいカーソル位置報告(CPR)であるか確認
rows = $1.to_i
cols = $2.to_i
system("#{STTY} cols #{cols} rows #{rows}")
if /csh$/ =~ ENV["SHELL"]
puts "setenv COLUMNS #{cols};"
puts "setenv LINES #{rows};"
else
puts "COLUMNS=#{cols};"
puts "LINES=#{rows};"
puts "export COLUMNS LINES;"
end
else
STDERR.puts "Invalid response"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment