1

I'm trying to process arrow key ANSI escape sequences i.e.

up - "\033[A"
down - "\033[B"
left - "\033[D"
right - "\033[C"

in my programme so when I press the up/down/left/right arrow key, it won't have to look like this:

% stack runghc test.hs
Input a name?
^[[A^[[B^[[C^[[D^

on my stdin, but rather I would like those keys to be suppressed or even better, for them to actually work(i.e move the cursor left/right). My code is as follows:

main = do putStrLn "Input a name?"  
          name <- getLine  
          putStrLn $ ("His name is " ++ name)

Any help would be appreciated. Thanks in advance.

digitalguy99
  • 443
  • 4
  • 13

2 Answers2

3

The easiest way to get readline-like functionality is to just use readline. For most simple use cases, rlwrap is good enough, as described in One REPL to bind them all?. If you need to do fancier integrations, you can use the readline package.

amalloy
  • 89,153
  • 8
  • 140
  • 205
0

I had trouble installing the readline library due to some errors and decided to use the haskeline library, which is a more portable pure-haskell replacement for it.

Using its syntax and modifying the earlier code, I got:

main :: IO ()
main = do putStrLn "Input a name?"
          runInputT defaultSettings insertion
  where
      insertion :: InputT IO ()
      insertion = do
          minput <- getInputLine ""
          case minput of
              Nothing -> return ()
              Just input -> do outputStrLn $ "His name is " ++ input

Which solves the problem as I am now able to move my cursor with the arrow keys freely without having to see any trailing ANSI escape sequences as shown below:

result

digitalguy99
  • 443
  • 4
  • 13