Preview structured text files (like Markdown) in the browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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