haskellcommand-linehaskelineword-completion

Haskell (haskeline) word completion


Haskeline makes it very easy to get filename tab-completion functionality:

module Main where

import System.Console.Haskeline
import System.Environment

mySettings :: Settings IO
mySettings = defaultSettings {historyFile = Just "myhist"}

main :: IO ()
main = do
        args <- getArgs
        let inputFunc = getInputLine
        runInputT mySettings $ withInterrupt $ loop inputFunc 0
    where
        loop inputFunc n = do
            minput <-  handleInterrupt (return (Just "Caught interrupted"))
                        $ inputFunc (show n ++ ":")
            case minput of
                Nothing -> return ()
                Just s -> do
                            outputStrLn ("line " ++ show n ++ ":" ++ s)
                            loop inputFunc (n+1)

It also provides functions like completeWord and completeQuotedWord, which should be able to be used in the same way that completeFilename is used to make the above functionality.
(In other words, have tab-completion based on a list of words (say, function names), instead of based on the contents of a folder)

Can anyone provide a working example - or working code - of this?

Recommendations for functions from other packages (like HCL) are helpful also.


Solution

  • Is this the sort of thing you're after?

    import Data.List
    
    wordList = [ "Apple", "Pear", "Peach", "Grape", "Grapefruit", "Slime Mold"]
    
    searchFunc :: String -> [Completion]
    searchFunc str = map simpleCompletion $ filter (str `isPrefixOf`) wordList
    
    mySettings :: Settings IO
    mySettings = Settings { historyFile = Just "myhist"
                          , complete = completeWord Nothing " \t" $ return . searchFunc
                          , autoAddHistory = True
                          }
    

    Replace the definition of mySettings in your snippet with that and it should work.