ruby - 从 Ruby 获取终端位置

标签 ruby terminal terminfo

绝对有更好的方法来做到这一点。

temp_file ||= Tempfile.new()
system("stty -echo; tput u7; read -d R x; stty echo; echo ${x#??} > #{temp_file.path}")
temp_file.gets.chomp.split(';').map(&:to_i)

基本上,我从 this question 运行 bash 脚本在子进程中,然后从重定向文件中读取输出。

在不使用 C 或任何 gems(stdlib okay)的情况下,有什么更好的方法来做到这一点?交叉兼容性不是很重要。

最佳答案

这是获取光标位置的纯 ruby​​ 实现:

require 'io/console'

class Cursor
  class << self
    def pos
      res = ''
      $stdin.raw do |stdin|
        $stdout << "\e[6n"
        $stdout.flush
        while (c = stdin.getc) != 'R'
          res << c if c
        end
      end
      m = res.match /(?<row>\d+);(?<column>\d+)/
      { row: Integer(m[:row]), column: Integer(m[:column]) }
    end
  end
end

puts Cursor.pos  #=> {:row=>25, :column=>1}

tput u7 替换为回显 \e[6n$stdout。它可能不太便携,但可以帮助我们仅使用 ruby​​ 代码。

关于ruby - 从 Ruby 获取终端位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5810131/

相关文章:

ruby-on-rails - Rails 中未定义的方法

macos - 如何将 emacs 颜色从常规终端保留到 gnu screen

ubuntu - 如何在 Vim 中更改 Jellybeans 配色方案中某些文本对象的彩色背景?

python - 删除并替换在 Python 中打印到终端的最后一个字符

C程序中使用terminfo捕获字符串key

utf-8 - 仅当使用 iTerm 时,垂直 tmux 边框才为虚线

c++ - 我可以在没有 tputs 或 putp 的情况下使用 tparm()

ruby - 在最后一个方法语句上分配变量

Ruby - 优雅地比较两个枚举器

ruby-on-rails - 如何在 cucumber 中 stub 方法?