Skip to content

Instantly share code, notes, and snippets.

@Xion
Last active June 14, 2017 20:54
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save Xion/b8fdb6a896264915ad85 to your computer and use it in GitHub Desktop.
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)
where
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