2Copyright (C) 2006-7 John MacFarlane <jgm@berkeley.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
21 Copyright : Copyright (C) 2006-7 John MacFarlane
22 License : GNU GPL, version 2 or above
24 Maintainer : John MacFarlane <jgm@berkeley@edu>
26 Portability : portable
28Parses command-line options and calls the appropriate readers and
33import Text.Pandoc.UTF8
34import Text.Pandoc.Shared ( joinWithSep )
35import Text.Regex ( mkRegex, matchRegex )
36import System.Environment ( getArgs, getProgName, getEnvironment )
37import System.Exit ( exitWith, ExitCode (..) )
38import System.Console.GetOpt
40import Data.Maybe ( fromMaybe )
41import Data.List ( isPrefixOf )
42import Data.Char ( toLower )
43import Control.Monad ( (>>=) )
45copyrightMessage :: String
46copyrightMessage = "\nCopyright (C) 2006-7 John MacFarlane\n\
47 \Web: http://johnmacfarlane.net/pandoc\n\
48 \This is free software; see the source for copying conditions. There is no\n\
49 \warranty, not even for merchantability or fitness for a particular purpose."
51-- | Association list of formats and readers.
52readers :: [(String, ParserState -> String -> Pandoc)]
53readers = [("native" , readPandoc)
54 ,("markdown" , readMarkdown)
57 ,("latex" , readLaTeX)
60-- | Reader for native Pandoc format.
61readPandoc :: ParserState -> String -> Pandoc
62readPandoc state input = read input
64-- | Association list of formats and pairs of writers and default headers.
65writers :: [ ( String, ( WriterOptions -> Pandoc -> String, String ) ) ]
66writers = [("native" , (writeDoc, ""))
67 ,("html" , (writeHtmlString, ""))
68 ,("s5" , (writeS5String, defaultS5Header))
69 ,("docbook" , (writeDocbook, defaultDocbookHeader))
70 ,("latex" , (writeLaTeX, defaultLaTeXHeader))
71 ,("context" , (writeConTeXt, defaultConTeXtHeader))
72 ,("man" , (writeMan, ""))
73 ,("markdown" , (writeMarkdown, ""))
74 ,("rst" , (writeRST, ""))
75 ,("rtf" , (writeRTF, defaultRTFHeader))
78-- | Writer for Pandoc native format.
79writeDoc :: WriterOptions -> Pandoc -> String
80writeDoc options = prettyPandoc
82-- | Data structure for command line options.
84 { optPreserveTabs :: Bool -- ^ Convert tabs to spaces
85 , optTabStop :: Int -- ^ Number of spaces per tab
86 , optStandalone :: Bool -- ^ Include header, footer
87 , optReader :: String -- ^ Reader format
88 , optWriter :: String -- ^ Writer format
89 , optParseRaw :: Bool -- ^ Parse unconvertable HTML and TeX
90 , optCSS :: String -- ^ CSS file to link to
91 , optTableOfContents :: Bool -- ^ Include table of contents
92 , optIncludeInHeader :: String -- ^ File to include in header
93 , optIncludeBeforeBody :: String -- ^ File to include at top of body
94 , optIncludeAfterBody :: String -- ^ File to include at end of body
95 , optCustomHeader :: String -- ^ Custom header to use, or "DEFAULT"
96 , optTitlePrefix :: String -- ^ Optional prefix for HTML title
97 , optOutputFile :: String -- ^ Name of output file
98 , optNumberSections :: Bool -- ^ Number sections in LaTeX
99 , optIncremental :: Bool -- ^ Use incremental lists in S5
100 , optSmart :: Bool -- ^ Use smart typography
101 , optUseASCIIMathML :: Bool -- ^ Use ASCIIMathML
102 , optASCIIMathMLURL :: Maybe String -- ^ URL to ASCIIMathML.js
103 , optDumpArgs :: Bool -- ^ Output command-line arguments
104 , optIgnoreArgs :: Bool -- ^ Ignore command-line arguments
105 , optStrict :: Bool -- ^ Use strict markdown syntax
106 , optReferenceLinks :: Bool -- ^ Use reference links in writing markdown, rst
107 , optWrapText :: Bool -- ^ Wrap text
110-- | Defaults for command-line options.
113 { optPreserveTabs = False
115 , optStandalone = False
116 , optReader = "" -- null for default reader
117 , optWriter = "" -- null for default writer
118 , optParseRaw = False
120 , optTableOfContents = False
121 , optIncludeInHeader = ""
122 , optIncludeBeforeBody = ""
123 , optIncludeAfterBody = ""
124 , optCustomHeader = "DEFAULT"
125 , optTitlePrefix = ""
126 , optOutputFile = "-" -- "-" means stdout
127 , optNumberSections = False
128 , optIncremental = False
130 , optUseASCIIMathML = False
131 , optASCIIMathMLURL = Nothing
132 , optDumpArgs = False
133 , optIgnoreArgs = False
135 , optReferenceLinks = False
139-- | A list of functions, each transforming the options data structure
140-- in response to a command-line option.
141options :: [OptDescr (Opt -> IO Opt)]
143 [ Option "fr" ["from","read"]
145 (\arg opt -> return opt { optReader = map toLower arg })
147 "" -- ("(" ++ (joinWithSep ", " $ map fst readers) ++ ")")
149 , Option "tw" ["to","write"]
151 (\arg opt -> return opt { optWriter = map toLower arg })
153 "" -- ("(" ++ (joinWithSep ", " $ map fst writers) ++ ")")
155 , Option "s" ["standalone"]
157 (\opt -> return opt { optStandalone = True }))
158 "" -- "Include needed header and footer on output"
160 , Option "o" ["output"]
162 (\arg opt -> return opt { optOutputFile = arg })
164 "" -- "Name of output file"
166 , Option "p" ["preserve-tabs"]
168 (\opt -> return opt { optPreserveTabs = True }))
169 "" -- "Preserve tabs instead of converting to spaces"
171 , Option "" ["tab-stop"]
173 (\arg opt -> return opt { optTabStop = (read arg) } )
175 "" -- "Tab stop (default 4)"
177 , Option "" ["strict"]
179 (\opt -> return opt { optStrict = True } ))
180 "" -- "Disable markdown syntax extensions"
182 , Option "" ["reference-links"]
184 (\opt -> return opt { optReferenceLinks = True } ))
185 "" -- "Use reference links in parsing HTML"
187 , Option "R" ["parse-raw"]
189 (\opt -> return opt { optParseRaw = True }))
190 "" -- "Parse untranslatable HTML codes and LaTeX environments as raw"
192 , Option "S" ["smart"]
194 (\opt -> return opt { optSmart = True }))
195 "" -- "Use smart quotes, dashes, and ellipses"
197 , Option "m" ["asciimathml"]
199 (\arg opt -> return opt { optUseASCIIMathML = True,
200 optASCIIMathMLURL = arg,
201 optStandalone = True })
203 "" -- "Use ASCIIMathML script in html output"
205 , Option "i" ["incremental"]
207 (\opt -> return opt { optIncremental = True }))
208 "" -- "Make list items display incrementally in S5"
210 , Option "N" ["number-sections"]
212 (\opt -> return opt { optNumberSections = True }))
213 "" -- "Number sections in LaTeX"
215 , Option "" ["no-wrap"]
217 (\opt -> return opt { optWrapText = False }))
218 "" -- "Do not wrap text in output"
220 , Option "" ["toc", "table-of-contents"]
222 (\opt -> return opt { optTableOfContents = True }))
223 "" -- "Include table of contents"
227 (\arg opt -> return opt { optCSS = arg,
228 optStandalone = True })
230 "" -- "Link to CSS style sheet"
232 , Option "H" ["include-in-header"]
236 return opt { optIncludeInHeader = fromUTF8 text,
237 optStandalone = True })
239 "" -- "File to include at end of header (implies -s)"
241 , Option "B" ["include-before-body"]
245 return opt { optIncludeBeforeBody = fromUTF8 text })
247 "" -- "File to include before document body"
249 , Option "A" ["include-after-body"]
253 return opt { optIncludeAfterBody = fromUTF8 text })
255 "" -- "File to include after document body"
257 , Option "C" ["custom-header"]
261 return opt { optCustomHeader = fromUTF8 text,
262 optStandalone = True })
264 "" -- "File to use for custom header (implies -s)"
266 , Option "T" ["title-prefix"]
268 (\arg opt -> return opt { optTitlePrefix = arg,
269 optStandalone = True })
271 "" -- "String to prefix to HTML window title"
273 , Option "D" ["print-default-header"]
276 let header = case (lookup arg writers) of
277 Just (writer, head) -> head
278 Nothing -> error ("Unknown reader: " ++ arg)
279 hPutStr stdout header
280 exitWith ExitSuccess)
282 "" -- "Print default header for FORMAT"
284 , Option "" ["dump-args"]
286 (\opt -> return opt { optDumpArgs = True }))
287 "" -- "Print output filename and arguments to stdout."
289 , Option "" ["ignore-args"]
291 (\opt -> return opt { optIgnoreArgs = True }))
292 "" -- "Ignore command-line arguments."
294 , Option "v" ["version"]
298 hPutStrLn stderr (prg ++ " " ++ pandocVersion ++
300 exitWith $ ExitFailure 4))
301 "" -- "Print version"
303 , Option "h" ["help"]
307 hPutStr stderr (usageMessage prg options)
308 exitWith $ ExitFailure 2))
312-- Returns usage message
313usageMessage :: String -> [OptDescr (Opt -> IO Opt)] -> String
314usageMessage programName options = usageInfo
315 (programName ++ " [OPTIONS] [FILES]" ++ "\nInput formats: " ++
316 (joinWithSep ", " $ map fst readers) ++ "\nOutput formats: " ++
317 (joinWithSep ", " $ map fst writers) ++ "\nOptions:")
320-- Determine default reader based on source file extensions
321defaultReaderName :: [String] -> String
322defaultReaderName [] = "markdown"
323defaultReaderName (x:xs) =
324 let x' = map toLower x in
325 case (matchRegex (mkRegex ".*\\.(.*)") x') of
326 Nothing -> defaultReaderName xs -- no extension
327 Just ["xhtml"] -> "html"
328 Just ["html"] -> "html"
329 Just ["htm"] -> "html"
330 Just ["tex"] -> "latex"
331 Just ["latex"] -> "latex"
332 Just ["ltx"] -> "latex"
333 Just ["rst"] -> "rst"
334 Just ["native"] -> "native"
337-- Determine default writer based on output file extension
338defaultWriterName :: String -> String
339defaultWriterName "-" = "html" -- no output file
341 let x' = map toLower x in
342 case (matchRegex (mkRegex ".*\\.(.*)") x') of
343 Nothing -> "markdown" -- no extension
344 Just [""] -> "markdown" -- empty extension
345 Just ["tex"] -> "latex"
346 Just ["latex"] -> "latex"
347 Just ["ltx"] -> "latex"
348 Just ["context"] -> "context"
349 Just ["ctx"] -> "context"
350 Just ["rtf"] -> "rtf"
351 Just ["rst"] -> "rst"
353 Just ["native"] -> "native"
354 Just ["txt"] -> "markdown"
355 Just ["text"] -> "markdown"
356 Just ["md"] -> "markdown"
357 Just ["markdown"] -> "markdown"
358 Just ["db"] -> "docbook"
359 Just ["xml"] -> "docbook"
360 Just ["sgml"] -> "docbook"
361 Just [[x]] | x `elem` ['1'..'9'] -> "man"
368 let compatMode = (prg == "hsmarkdown")
370 let (actions, args, errors) = if compatMode
371 then ([], rawArgs, [])
372 else getOpt Permute options rawArgs
374 if (not (null errors))
377 mapM (\e -> hPutStrLn stderr e) errors
378 hPutStr stderr (usageMessage name options)
379 exitWith $ ExitFailure 2
383 let defaultOpts' = if compatMode
384 then defaultOpts { optReader = "markdown"
389 -- thread option data structure through all supplied option actions
390 opts <- foldl (>>=) (return defaultOpts') actions
392 let Opt { optPreserveTabs = preserveTabs
393 , optTabStop = tabStop
394 , optStandalone = standalone
395 , optReader = readerName
396 , optWriter = writerName
397 , optParseRaw = parseRaw
399 , optTableOfContents = toc
400 , optIncludeInHeader = includeHeader
401 , optIncludeBeforeBody = includeBefore
402 , optIncludeAfterBody = includeAfter
403 , optCustomHeader = customHeader
404 , optTitlePrefix = titlePrefix
405 , optOutputFile = outputFile
406 , optNumberSections = numberSections
407 , optIncremental = incremental
409 , optUseASCIIMathML = useAsciiMathML
410 , optASCIIMathMLURL = asciiMathMLURL
411 , optDumpArgs = dumpArgs
412 , optIgnoreArgs = ignoreArgs
414 , optReferenceLinks = referenceLinks
420 hPutStrLn stdout outputFile
421 mapM (\arg -> hPutStrLn stdout arg) args
422 exitWith $ ExitSuccess
425 let sources = if ignoreArgs then [] else args
427 -- assign reader and writer based on options and filenames
428 let readerName' = if null readerName
429 then defaultReaderName sources
432 let writerName' = if null writerName
433 then defaultWriterName outputFile
436 reader <- case (lookup readerName' readers) of
438 Nothing -> error ("Unknown reader: " ++ readerName')
440 (writer, defaultHeader) <- case (lookup writerName' writers) of
441 Just (w,h) -> return (w, h)
442 Nothing -> error ("Unknown writer: " ++ writerName')
444 output <- if (outputFile == "-")
446 else openFile outputFile WriteMode
448 environment <- getEnvironment
449 let columns = case lookup "COLUMNS" environment of
450 Just cols -> read cols
451 Nothing -> stateColumns defaultParserState
453 let tabFilter _ [] = ""
454 tabFilter _ ('\n':xs) = '\n':(tabFilter tabStop xs)
455 -- remove DOS line endings
456 tabFilter _ ('\r':'\n':xs) = '\n':(tabFilter tabStop xs)
457 tabFilter _ ('\r':xs) = '\n':(tabFilter tabStop xs)
458 tabFilter spsToNextStop ('\t':xs) =
460 then '\t':(tabFilter tabStop xs)
461 else replicate spsToNextStop ' ' ++ tabFilter tabStop xs
463 x:(tabFilter tabStop xs)
464 tabFilter spsToNextStop (x:xs) =
465 x:(tabFilter (spsToNextStop - 1) xs)
467 let startParserState =
468 defaultParserState { stateParseRaw = parseRaw,
469 stateTabStop = tabStop,
470 stateStandalone = standalone && (not strict),
471 stateSmart = smart || writerName' `elem`
472 ["latex", "context"],
473 stateColumns = columns,
474 stateStrict = strict }
475 let csslink = if (css == "")
477 else "<link rel=\"stylesheet\" href=\"" ++ css ++
478 "\" type=\"text/css\" media=\"all\" />\n"
479 let header = (if (customHeader == "DEFAULT")
481 else customHeader) ++ csslink ++ includeHeader
482 let writerOptions = WriterOptions { writerStandalone = standalone &&
484 writerHeader = header,
485 writerTitlePrefix = titlePrefix,
486 writerTabStop = tabStop,
487 writerTableOfContents = toc &&
490 writerUseASCIIMathML = useAsciiMathML,
491 writerASCIIMathMLURL = asciiMathMLURL,
492 writerS5 = (writerName=="s5"),
493 writerIgnoreNotes = False,
494 writerIncremental = incremental,
495 writerNumberSections = numberSections,
496 writerIncludeBefore = includeBefore,
497 writerIncludeAfter = includeAfter,
498 writerStrictMarkdown = strict,
499 writerReferenceLinks = referenceLinks,
500 writerWrapText = wrap }
502 (readSources sources) >>= (hPutStrLn output . toUTF8 .
503 (writer writerOptions) .
504 (reader startParserState) . tabFilter tabStop .
505 fromUTF8 . (joinWithSep "\n")) >>
509 readSources [] = mapM readSource ["-"]
510 readSources sources = mapM readSource sources
511 readSource "-" = getContents
512 readSource source = readFile source
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list