Skip to content

Instantly share code, notes, and snippets.

@Xion Xion/preview.hs
Last active Jun 14, 2017

What would you like to do?
Preview structured text files (like Markdown) in the browser
#!/usr/bin/env runhaskell
-- Preview structured text files in the browser
-- Usage: $ preview FILE [BROWSER]
-- by Karol Kuczmarski "Xion" -- 25 August 2013
import Control.Exception (bracket)
import System.Environment (getArgs)
import System.Directory (getTemporaryDirectory)
import System.Info (os)
import System.IO (Handle, hClose, hPutStr, openTempFile)
import System.Process (readProcess, runCommand)
import Text.Printf (printf)
main = do
(inFilePath, browser) <- parseArgs
withTempFile "pandoc-preview-.html" $ \outFilePath outHandle -> do
outHtml <- readProcess "pandoc" [inFilePath] []
hPutStr outHandle outHtml
runCommand $ printf "%s \"%s\"" browser outFilePath
parseArgs :: IO (FilePath, String)
parseArgs = do
args <- getArgs
case args of
[file] -> return (file, defaultBrowser)
[file, browser] -> return (file, browser)
_ -> error $ printf "invalid number of arguments (%d)" (length args)
defaultBrowser = if os == "darwin" then "open" else "firefox"
-- Utility functions
withTempFile :: String -> (FilePath -> Handle -> IO a) -> IO a
withTempFile filenameTemplate callback = do
tmpDirectory <- getTemporaryDirectory
bracket (openTempFile tmpDirectory filenameTemplate) (hClose . snd) $
uncurry callback
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session.