git.iko.soy/typeable/pandoc
on a669f64 help sign in
491 lines 20 kB history raw
1{-
2Copyright (C) 2006 John MacFarlane <jgm at berkeley dot edu>
4This program is free software; you can redistribute it and/or modify
5it under the terms of the GNU General Public License as published by
6the Free Software Foundation; either version 2 of the License, or
7(at your option) any later version.
9This program is distributed in the hope that it will be useful,
10but WITHOUT ANY WARRANTY; without even the implied warranty of
11MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12GNU General Public License for more details.
14You should have received a copy of the GNU General Public License
15along with this program; if not, write to the Free Software
16Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17-}
19{- |
20 Module : Main
21 Copyright : Copyright (C) 2006 John MacFarlane
22 License : GNU GPL, version 2 or above
24 Maintainer : John MacFarlane <jgm at berkeley dot edu>
25 Stability : alpha
26 Portability : portable
28Parses command-line options and calls the appropriate readers and
29writers.
30-}
31module Main where
32import Text.Pandoc.UTF8 ( decodeUTF8, encodeUTF8 )
33import Text.Pandoc.Readers.Markdown ( readMarkdown )
34import Text.Pandoc.Readers.HTML ( readHtml )
35import Text.Pandoc.Writers.S5 ( writeS5String )
36import Text.Pandoc.Writers.RST ( writeRST )
37import Text.Pandoc.Readers.RST ( readRST )
38import Text.Pandoc.ASCIIMathML ( asciiMathMLScript )
39import Text.Pandoc.Writers.HTML ( writeHtmlString )
40import Text.Pandoc.Writers.Docbook ( writeDocbook )
41import Text.Pandoc.Writers.LaTeX ( writeLaTeX )
42import Text.Pandoc.Readers.LaTeX ( readLaTeX )
43import Text.Pandoc.Writers.RTF ( writeRTF )
44import Text.Pandoc.Writers.Man ( writeMan )
45import Text.Pandoc.Writers.Markdown ( writeMarkdown )
46import Text.Pandoc.Writers.DefaultHeaders ( defaultRTFHeader,
47 defaultS5Header,
48 defaultLaTeXHeader,
49 defaultDocbookHeader )
50import Text.Pandoc.Definition
51import Text.Pandoc.Shared
52import Text.Regex ( mkRegex, matchRegex )
53import System.Environment ( getArgs, getProgName, getEnvironment )
54import System.Exit ( exitWith, ExitCode (..) )
55import System.Console.GetOpt
56import System.IO
57import Data.Maybe ( fromMaybe )
58import Data.List ( isPrefixOf )
59import Data.Char ( toLower )
60import Control.Monad ( (>>=) )
62version :: String
63version = "0.4"
65copyrightMessage :: String
66copyrightMessage = "\nCopyright (C) 2006 John MacFarlane\n\
67 \Web: http://sophos.berkeley.edu/macfarlane/pandoc\n\
68 \This is free software; see the source for copying conditions. There is no\n\
69 \warranty, not even for merchantability or fitness for a particular purpose."
71-- | Association list of formats and readers.
72readers :: [(String, ParserState -> String -> Pandoc)]
73readers = [("native" , readPandoc)
74 ,("markdown" , readMarkdown)
75 ,("rst" , readRST)
76 ,("html" , readHtml)
77 ,("latex" , readLaTeX)
78 ]
80-- | Reader for native Pandoc format.
81readPandoc :: ParserState -> String -> Pandoc
82readPandoc state input = read input
84-- | Association list of formats and pairs of writers and default headers.
85writers :: [ ( String, ( WriterOptions -> Pandoc -> String, String ) ) ]
86writers = [("native" , (writeDoc, ""))
87 ,("html" , (writeHtmlString, ""))
88 ,("s5" , (writeS5String, defaultS5Header))
89 ,("docbook" , (writeDocbook, defaultDocbookHeader))
90 ,("latex" , (writeLaTeX, defaultLaTeXHeader))
91 ,("man" , (writeMan, ""))
92 ,("markdown" , (writeMarkdown, ""))
93 ,("rst" , (writeRST, ""))
94 ,("rtf" , (writeRTF, defaultRTFHeader))
95 ]
97-- | Writer for Pandoc native format.
98writeDoc :: WriterOptions -> Pandoc -> String
99writeDoc options = prettyPandoc
101-- | Data structure for command line options.
102data Opt = Opt
103 { optPreserveTabs :: Bool -- ^ Convert tabs to spaces
104 , optTabStop :: Int -- ^ Number of spaces per tab
105 , optStandalone :: Bool -- ^ Include header, footer
106 , optReader :: String -- ^ Reader format
107 , optWriter :: String -- ^ Writer format
108 , optParseRaw :: Bool -- ^ Parse unconvertable HTML and TeX
109 , optCSS :: String -- ^ CSS file to link to
110 , optIncludeInHeader :: String -- ^ File to include in header
111 , optIncludeBeforeBody :: String -- ^ File to include at top of body
112 , optIncludeAfterBody :: String -- ^ File to include at end of body
113 , optCustomHeader :: String -- ^ Custom header to use, or "DEFAULT"
114 , optTitlePrefix :: String -- ^ Optional prefix for HTML title
115 , optOutputFile :: String -- ^ Name of output file
116 , optNumberSections :: Bool -- ^ Number sections in LaTeX
117 , optIncremental :: Bool -- ^ Use incremental lists in S5
118 , optSmart :: Bool -- ^ Use smart typography
119 , optASCIIMathML :: Bool -- ^ Use ASCIIMathML in HTML
120 , optDumpArgs :: Bool -- ^ Output command-line arguments
121 , optIgnoreArgs :: Bool -- ^ Ignore command-line arguments
122 , optStrict :: Bool -- ^ Use strict markdown syntax
123 , optReferenceLinks :: Bool -- ^ Use reference links in writing markdown, rst
124 }
126-- | Defaults for command-line options.
127defaultOpts :: Opt
128defaultOpts = Opt
129 { optPreserveTabs = False
130 , optTabStop = 4
131 , optStandalone = False
132 , optReader = "" -- null for default reader
133 , optWriter = "" -- null for default writer
134 , optParseRaw = False
135 , optCSS = ""
136 , optIncludeInHeader = ""
137 , optIncludeBeforeBody = ""
138 , optIncludeAfterBody = ""
139 , optCustomHeader = "DEFAULT"
140 , optTitlePrefix = ""
141 , optOutputFile = "-" -- "-" means stdout
142 , optNumberSections = False
143 , optIncremental = False
144 , optSmart = False
145 , optASCIIMathML = False
146 , optDumpArgs = False
147 , optIgnoreArgs = False
148 , optStrict = False
149 , optReferenceLinks = False
150 }
152-- | A list of functions, each transforming the options data structure
153-- in response to a command-line option.
154options :: [OptDescr (Opt -> IO Opt)]
155options =
156 [ Option "fr" ["from","read"]
157 (ReqArg
158 (\arg opt -> return opt { optReader = map toLower arg })
159 "FORMAT")
160 "" -- ("(" ++ (joinWithSep ", " (map fst readers)) ++ ")")
162 , Option "tw" ["to","write"]
163 (ReqArg
164 (\arg opt -> return opt { optWriter = map toLower arg })
165 "FORMAT")
166 "" -- ("(" ++ (joinWithSep ", " (map fst writers)) ++ ")")
168 , Option "s" ["standalone"]
169 (NoArg
170 (\opt -> return opt { optStandalone = True }))
171 "" -- "Include needed header and footer on output"
173 , Option "o" ["output"]
174 (ReqArg
175 (\arg opt -> return opt { optOutputFile = arg })
176 "FILENAME")
177 "" -- "Name of output file"
179 , Option "p" ["preserve-tabs"]
180 (NoArg
181 (\opt -> return opt { optPreserveTabs = True }))
182 "" -- "Preserve tabs instead of converting to spaces"
184 , Option "" ["tab-stop"]
185 (ReqArg
186 (\arg opt -> return opt { optTabStop = (read arg) } )
187 "TABSTOP")
188 "" -- "Tab stop (default 4)"
190 , Option "" ["strict"]
191 (NoArg
192 (\opt -> return opt { optStrict = True } ))
193 "" -- "Use strict markdown syntax with no extensions"
195 , Option "" ["reference-links"]
196 (NoArg
197 (\opt -> return opt { optReferenceLinks = True } ))
198 "" -- "Use reference links in parsing HTML"
200 , Option "R" ["parse-raw"]
201 (NoArg
202 (\opt -> return opt { optParseRaw = True }))
203 "" -- "Parse untranslatable HTML codes and LaTeX environments as raw"
205 , Option "S" ["smart"]
206 (NoArg
207 (\opt -> return opt { optSmart = True }))
208 "" -- "Use smart quotes, dashes, and ellipses"
210 , Option "m" ["asciimathml"]
211 (NoArg
212 (\opt -> return opt { optASCIIMathML = True,
213 optStandalone = True }))
214 "" -- "Use ASCIIMathML script in html output"
216 , Option "i" ["incremental"]
217 (NoArg
218 (\opt -> return opt { optIncremental = True }))
219 "" -- "Make list items display incrementally in S5"
221 , Option "N" ["number-sections"]
222 (NoArg
223 (\opt -> return opt { optNumberSections = True }))
224 "" -- "Number sections in LaTeX"
226 , Option "c" ["css"]
227 (ReqArg
228 (\arg opt -> return opt { optCSS = arg,
229 optStandalone = True })
230 "CSS")
231 "" -- "Link to CSS style sheet"
233 , Option "H" ["include-in-header"]
234 (ReqArg
235 (\arg opt -> do
236 text <- readFile arg
237 return opt { optIncludeInHeader = text,
238 optStandalone = True })
239 "FILENAME")
240 "" -- "File to include at end of header (implies -s)"
242 , Option "B" ["include-before-body"]
243 (ReqArg
244 (\arg opt -> do
245 text <- readFile arg
246 return opt { optIncludeBeforeBody = text })
247 "FILENAME")
248 "" -- "File to include before document body"
250 , Option "A" ["include-after-body"]
251 (ReqArg
252 (\arg opt -> do
253 text <- readFile arg
254 return opt { optIncludeAfterBody = text })
255 "FILENAME")
256 "" -- "File to include after document body"
258 , Option "C" ["custom-header"]
259 (ReqArg
260 (\arg opt -> do
261 text <- readFile arg
262 return opt { optCustomHeader = text,
263 optStandalone = True })
264 "FILENAME")
265 "" -- "File to use for custom header (implies -s)"
267 , Option "T" ["title-prefix"]
268 (ReqArg
269 (\arg opt -> return opt { optTitlePrefix = arg,
270 optStandalone = True })
271 "STRING")
272 "" -- "String to prefix to HTML window title"
274 , Option "D" ["print-default-header"]
275 (ReqArg
276 (\arg opt -> do
277 let header = case (lookup arg writers) of
278 Just (writer, head) -> head
279 Nothing -> error ("Unknown reader: " ++ arg)
280 hPutStr stdout header
281 exitWith ExitSuccess)
282 "FORMAT")
283 "" -- "Print default header for FORMAT"
285 , Option "" ["dump-args"]
286 (NoArg
287 (\opt -> return opt { optDumpArgs = True }))
288 "" -- "Print output filename and arguments to stdout."
290 , Option "" ["ignore-args"]
291 (NoArg
292 (\opt -> return opt { optIgnoreArgs = True }))
293 "" -- "Ignore command-line arguments."
295 , Option "v" ["version"]
296 (NoArg
297 (\_ -> do
298 prg <- getProgName
299 hPutStrLn stderr (prg ++ " " ++ version ++
300 copyrightMessage)
301 exitWith $ ExitFailure 4))
302 "" -- "Print version"
304 , Option "h" ["help"]
305 (NoArg
306 (\_ -> do
307 prg <- getProgName
308 hPutStr stderr (usageMessage prg options)
309 exitWith $ ExitFailure 2))
310 "" -- "Show help"
311 ]
313-- Returns usage message
314usageMessage :: String -> [OptDescr (Opt -> IO Opt)] -> String
315usageMessage programName options = usageInfo
316 (programName ++ " [OPTIONS] [FILES]" ++ "\nInput formats: " ++
317 joinWithSep ", " (map fst readers) ++ "\nOutput formats: " ++
318 joinWithSep ", " (map fst writers) ++ "\nOptions:")
319 options
321-- Determine default reader based on source file extensions
322defaultReaderName :: [String] -> String
323defaultReaderName [] = "markdown"
324defaultReaderName (x:xs) =
325 let x' = map toLower x in
326 case (matchRegex (mkRegex ".*\\.(.*)") x') of
327 Nothing -> defaultReaderName xs -- no extension
328 Just ["xhtml"] -> "html"
329 Just ["html"] -> "html"
330 Just ["htm"] -> "html"
331 Just ["tex"] -> "latex"
332 Just ["latex"] -> "latex"
333 Just ["ltx"] -> "latex"
334 Just ["rst"] -> "rst"
335 Just ["native"] -> "native"
336 Just _ -> "markdown"
338-- Determine default writer based on output file extension
339defaultWriterName :: String -> String
340defaultWriterName "-" = "html" -- no output file
341defaultWriterName x =
342 let x' = map toLower x in
343 case (matchRegex (mkRegex ".*\\.(.*)") x') of
344 Nothing -> "markdown" -- no extension
345 Just [""] -> "markdown" -- empty extension
346 Just ["tex"] -> "latex"
347 Just ["latex"] -> "latex"
348 Just ["ltx"] -> "latex"
349 Just ["rtf"] -> "rtf"
350 Just ["rst"] -> "rst"
351 Just ["s5"] -> "s5"
352 Just ["native"] -> "native"
353 Just ["txt"] -> "markdown"
354 Just ["text"] -> "markdown"
355 Just ["md"] -> "markdown"
356 Just ["markdown"] -> "markdown"
357 Just ["db"] -> "docbook"
358 Just ["xml"] -> "docbook"
359 Just ["sgml"] -> "docbook"
360 Just ["1"] -> "man"
361 Just _ -> "html"
363main = do
365 rawArgs <- getArgs
366 prg <- getProgName
367 let compatMode = (prg == "hsmarkdown")
369 let (actions, args, errors) = if compatMode
370 then ([], rawArgs, [])
371 else getOpt Permute options rawArgs
373 if (not (null errors))
374 then do
375 name <- getProgName
376 mapM (\e -> hPutStrLn stderr e) errors
377 hPutStr stderr (usageMessage name options)
378 exitWith $ ExitFailure 2
379 else
380 return ()
382 let defaultOpts' = if compatMode
383 then defaultOpts { optReader = "markdown"
384 , optWriter = "html"
385 , optStrict = True }
386 else defaultOpts
388 -- thread option data structure through all supplied option actions
389 opts <- foldl (>>=) (return defaultOpts') actions
391 let Opt { optPreserveTabs = preserveTabs
392 , optTabStop = tabStop
393 , optStandalone = standalone
394 , optReader = readerName
395 , optWriter = writerName
396 , optParseRaw = parseRaw
397 , optCSS = css
398 , optIncludeInHeader = includeHeader
399 , optIncludeBeforeBody = includeBefore
400 , optIncludeAfterBody = includeAfter
401 , optCustomHeader = customHeader
402 , optTitlePrefix = titlePrefix
403 , optOutputFile = outputFile
404 , optNumberSections = numberSections
405 , optIncremental = incremental
406 , optSmart = smart
407 , optASCIIMathML = asciiMathML
408 , optDumpArgs = dumpArgs
409 , optIgnoreArgs = ignoreArgs
410 , optStrict = strict
411 , optReferenceLinks = referenceLinks
412 } = opts
414 if dumpArgs
415 then do
416 hPutStrLn stdout outputFile
417 mapM (\arg -> hPutStrLn stdout arg) args
418 exitWith $ ExitSuccess
419 else return ()
421 let sources = if ignoreArgs then [] else args
423 -- assign reader and writer based on options and filenames
424 let readerName' = if null readerName
425 then defaultReaderName sources
426 else readerName
428 let writerName' = if null writerName
429 then defaultWriterName outputFile
430 else writerName
432 reader <- case (lookup readerName' readers) of
433 Just r -> return r
434 Nothing -> error ("Unknown reader: " ++ readerName')
436 (writer, defaultHeader) <- case (lookup writerName' writers) of
437 Just (w,h) -> return (w, h)
438 Nothing -> error ("Unknown writer: " ++ writerName')
440 output <- if (outputFile == "-")
441 then return stdout
442 else openFile outputFile WriteMode
444 environment <- getEnvironment
445 let columns = case lookup "COLUMNS" environment of
446 Just cols -> read cols
447 Nothing -> stateColumns defaultParserState
449 let tabFilter = if preserveTabs then id else (tabsToSpaces tabStop)
450 let addBlank str = str
451 let removeCRs str = filter (/= '\r') str -- remove DOS-style line endings
452 let filter = tabFilter . addBlank . removeCRs
453 let startParserState =
454 defaultParserState { stateParseRaw = parseRaw,
455 stateTabStop = tabStop,
456 stateStandalone = standalone && (not strict),
457 stateSmart = smart || writerName' == "latex",
458 stateColumns = columns,
459 stateStrict = strict }
460 let csslink = if (css == "")
461 then ""
462 else "<link rel=\"stylesheet\" href=\"" ++ css ++
463 "\" type=\"text/css\" media=\"all\" />\n"
464 let asciiMathMLLink = if asciiMathML then asciiMathMLScript else ""
465 let header = (if (customHeader == "DEFAULT")
466 then defaultHeader
467 else customHeader) ++
468 csslink ++ asciiMathMLLink ++ includeHeader
469 let writerOptions = WriterOptions { writerStandalone = standalone &&
470 (not strict),
471 writerHeader = header,
472 writerTitlePrefix = titlePrefix,
473 writerTabStop = tabStop,
474 writerS5 = (writerName=="s5"),
475 writerIncremental = incremental,
476 writerNumberSections = numberSections,
477 writerIncludeBefore = includeBefore,
478 writerIncludeAfter = includeAfter,
479 writerStrictMarkdown = strict,
480 writerReferenceLinks = referenceLinks }
482 (readSources sources) >>= (hPutStr output . encodeUTF8 .
483 (writer writerOptions) .
484 (reader startParserState) . filter .
485 decodeUTF8 . (joinWithSep "\n")) >> hClose output
487 where
488 readSources [] = mapM readSource ["-"]
489 readSources sources = mapM readSource sources
490 readSource "-" = getContents
491 readSource source = readFile source