Haskell 读取原始键盘输入 [英] Haskell read raw keyboard input
问题描述
我正在用 Haskell 编写一个终端模式程序.我将如何阅读原始按键信息?
I'm writing a terminal-mode program in Haskell. How would I go about reading raw keypress information?
特别是,似乎有一些东西在 Haskell 之上提供了行编辑功能.如果我执行 getLine
,我似乎能够使用向上箭头来获取前几行,编辑文本,并且只有当我按下 Enter 时,文本才会对 Haskell 应用程序本身可见.
In particular, there seems to be something providing line-editing facilities on top of Haskell. If I do getLine
, I seem to be able to use the up-arrow to get previous lines, edit the text, and only when I press Enter does the text become visible to the Haskell application itself.
我追求的是能够读取单个按键,这样我就可以自己实现行编辑.
What I'm after is the ability to read individual keypresses, so I can implement the line-editing stuff myself.
也许我的问题不清楚.基本上我想构建类似 Vi 或 Emacs(或 Yi)的东西.我已经知道有终端绑定可以让我进行花哨的控制台模式打印,所以输出端应该不是问题.我只是在寻找一种获取原始按键输入的方法,因此我可以执行以下操作:(例如)当用户按下字母 K 时将 K 添加到当前文本行,或者在用户按下时将文件保存到磁盘按 Ctrl+S.
Perhaps my question was unclear. Basically I want to build something like Vi or Emacs (or Yi). I already know there are terminal bindings that will let me do fancy console-mode printing, so the output side shouldn't be an issue. I'm just looking for a way to get at raw keypress input, so I can do things like (for example) add K to the current line of text when the user presses the letter K, or save the file to disk when the user presses Ctrl+S.
推荐答案
听起来您想要 readline 支持.有几个包可以做到这一点,但 haskeline 可能是最容易在支持最多的平台上使用的.>
Sounds like you want readline support. There are a couple of packages to do this, but haskeline is probably the easiest to use with the most supported platforms.
import Control.Monad.Trans
import System.Console.Haskeline
type Repl a = InputT IO a
process :: String -> IO ()
process = putStrLn
repl :: Repl ()
repl = do
minput <- getInputLine "> "
case minput of
Nothing -> outputStrLn "Goodbye."
Just input -> (liftIO $ process input) >> repl
main :: IO ()
main = runInputT defaultSettings repl
这篇关于Haskell 读取原始键盘输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!