module System.ReadEditor
(
readEditor
, readEditorWith
, openEditor
, openEditorWithPrompt
, prompt
, withSystemTempFile
)
where
import Control.Exception (finally)
import System.Directory (getTemporaryDirectory, removeFile)
import System.Environment (getEnv)
import System.IO (Handle, hClose, hFlush, hPutStr,
openTempFile, stdout)
import System.IO.Error (catchIOError)
import System.Process (system)
readEditor :: IO String
readEditor = withSystemTempFile "read-editor" readEditor'
readEditorWith :: String -> IO String
readEditorWith contents = withSystemTempFile "read-editor" $ \fp temph -> do
hPutStr temph contents
hFlush temph
readEditor' fp temph
readEditor' :: FilePath -> Handle -> IO String
readEditor' fp temph = do
openEditor fp
hClose temph
readFile fp
openEditor :: FilePath -> IO ()
openEditor = openEditorWithPrompt "What editor should I use? "
openEditorWithPrompt :: String -> FilePath -> IO ()
openEditorWithPrompt p fp = do
editorCmd <- catchIOError (getEnv "EDITOR") (const promptForEditor)
_ <- system $ editorCmd ++ " " ++ fp
return ()
where
promptForEditor = prompt p
prompt :: String -> IO String
prompt str = do
putStr str
hFlush stdout
getLine
withSystemTempFile :: String -> (FilePath -> Handle -> IO a) -> IO a
withSystemTempFile templ fn = do
tempdir <- catchIOError getTemporaryDirectory (\_ -> return ".")
(tempfile, temph) <- openTempFile tempdir templ
finally
(fn tempfile temph)
(removeFile tempfile)