Support for ANSI escape sequence cursor moving

℡╲_俬逩灬. 提交于 2019-12-12 02:13:55

问题


I'm making a simple ASCII animation, and I need the ability to place the cursor at an arbitrary point in the console screen.

While searching, I found this blog that shows this can be achieved by doing:

(print (str (char 27) "[2J")) ; clear screen
(print (str (char 27) "[;H")) ; move cursor to the top left corner of the screen

, which uses ANSI escape sequences.

The first line works as expected, but unfortunately, I haven't been able to find a console that allows for the second line to move the cursor.

After looking up how ANSI escape sequences work, I wrote up this function to ease it's use:

(defn move-cursor-to [x y]
  (print (str (char 27) "[" y ";" x "H")))

But when I run (move-cursor-to 10 10), the output is wrong in every "console" I've tried:

  • IntelliJ/Cursive's REPL ignores it outright; printing nothing.

  • IntelliJ's Terminal prints the escape character as a ?, and literally prints the rest (?[10;10H)

  • The Window's 10 command prompt prints something similar to IntelliJ's Terminal, except the ? it prints is inside a box.

Am I doing something wrong? Is there a way to get this to work in the standard Windows 10 command prompt?

I wrote this to fill in the blanks in the meantime:

(defn move-cursor-to [x y]
  (let [r #(apply str (repeat % %2))]
    (print (str (r y \newline)
                (r x \space)))))

but this is a poor solution. It requires clearing the screen prior to use, which for anything beyond a simple animation is unacceptable.


回答1:


There is an easier way!

There is a much easier way to do this. Have a look at the clojure-lanterna library.

This library will allow you to address an arbitrary location on a screen. It can either use a terminal emulator or it can create a swing based window.

Another advantage of using this library is that it also incorporates support for a virtual window or virtual screen, which can make your output appear to be much smoother and reduces potential flicker.

The library also has support for ANSI colour codes and a few other nice features.




回答2:


Cursive only implements a limited subset of ANSI commands. In particular, most of the caret movement commands don't work. Feel free to file an issue for this, but fixing it is likely to be low priority since it's quite tricky to do in a REPL output pane.



来源:https://stackoverflow.com/questions/42462165/support-for-ansi-escape-sequence-cursor-moving

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!