在命令行中获取光标位置(Elixir)

use*_*809 11 elixir

我想知道是否有一种方法可以从Elixir中获取命令行中的绝对光标位置.

我知道我必须使用以下ansi转义序列\ 033 [6n,执行后:

echo -en "\033[6n" 
Run Code Online (Sandbox Code Playgroud)

打印正是我正在寻找的,但我不知道如何从Elixir得到命令响应.

谢谢!

Tar*_*ani 5

这个差点把我逼疯了,我不得不挖出太多我无法分辨的线索。我将添加与解决方案相关的所有线程,它们都值得一读。

首先,我们不能使用System.cmdSystem.cmd 在没有 tty 的情况下运行

iex(1)> System.cmd("tty", [])
{"not a tty\n", 1}
Run Code Online (Sandbox Code Playgroud)

我们正在尝试做的事情需要 TTY。因此,几乎没有相同的有趣的库

https://github.com/alco/porcelain

但这也不适用于 TTY

iex(1)> Porcelain.shell("tty")
%Porcelain.Result{err: nil, out: "not a tty\n", status: 1}
Run Code Online (Sandbox Code Playgroud)

然后来到另一个图书馆

https://github.com/aleandros/shell_stream

这个似乎共享TTY

iex(3)> ShellStream.shell("tty") |> Enum.to_list
["/dev/pts/6"]
Run Code Online (Sandbox Code Playgroud)

这个TTY和当前终端的TTY是一样的,表示这个TTY正在传播给子进程

接下来是检查我们是否可以获得坐标

iex(8)> ShellStream.shell("echo -en '033[6n'") |> Enum.to_list
[]
Run Code Online (Sandbox Code Playgroud)

所以经过大量的尝试和试验后,我想出了一个方法

defmodule CursorPos do

  def get_pos do
      settings = ShellStream.shell("stty -g") |> Enum.to_list

      #ShellStream.shell("stty -echo -echoctl -imaxbel -isig -icanon min 1 time 0")
      ShellStream.shell("stty raw -echo")
      #settings |> IO.inspect
      spawn(fn ->
            IO.write "\e[6n"
            #ShellStream.shell "echo -en \"\033[6n\" > `tty`"
            :timer.sleep(50)
            IO.write "\n"
           end)
      io = IO.stream(:stdio,1)
      data = io |> Stream.take_while(&(&1 != "R"))
      data|> Enum.join  |> IO.inspect
      ShellStream.shell("stty #{settings}")
  end

  def main(args) do
      get_pos
  end
end
Run Code Online (Sandbox Code Playgroud)

这种工作,但仍然需要你按回车读取stdio

$ ./cursorpos
^[[24;1R

"\e[24;1"
Run Code Online (Sandbox Code Playgroud)

它还更改屏幕坐标以获取它们,这不是人们想要的。但问题是坐标控制字符需要由您的外壳而不是子外壳处理。我尝试使用

ShellStream.shell("stty -echo -echoctl -imaxbel -isig -icanon min 1 time 0")
Run Code Online (Sandbox Code Playgroud)

不起作用,因为stty它不会影响我们需要获取坐标的父壳。所以下一个可能的解决方案是在下面做

$ EXISTING=$(stty -g);stty -echo -echonl -imaxbel -isig -icanon min 1 time 0; ./cursorpos ; stty $EXISTING
"\e[24;1"
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为我们能够改变当前 tty 的属性。现在您可能想要更深入地挖掘并找到如何从代码内部做到这一点。

我已经把我所有的代码放到了 Github 项目下面

https://github.com/tarunlalwani/elixir-get-current-cursor-position

你也应该看看下面的项目

https://github.com/henrik/progress_bar

如果您获得光标位置并不重要,那么您可以自己将光标固定到某个位置。

参考

https://unix.stackexchange.com/questions/88296/get-vertical-cursor-position

如何在bash中获取光标位置?

https://groups.google.com/forum/#!topic/elixir-lang-talk/9B1oe3KgjnE

https://hexdocs.pm/elixir/IO.html#getn/3

https://unix.stackexchange.com/questions/264920/why-doesnt-the-enter-key-send-eol

http://man7.org/linux/man-pages/man1/stty.1.html

https://github.com/jfreeze/ex_ncurses

如何在 ANSI 终端中获取光标的位置?

按字符获取控制台用户输入


小智 -1

如果您知道系统命令,请使用系统模块从 Elixir 执行它