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
21 Copyright : Copyright (C) 2006 John MacFarlane
22 License : GNU GPL, version 2 or above
24 Maintainer : John MacFarlane <jgm at berkeley dot edu>
26 Portability : portable
28Parses command-line options and calls the appropriate readers and
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.Markdown ( writeMarkdown )
45import Text.Pandoc.Writers.DefaultHeaders ( defaultRTFHeader,
48 defaultDocbookHeader )
49import Text.Pandoc.Definition
50import Text.Pandoc.Shared
51import Text.Regex ( mkRegex, matchRegex )
52import System.Environment ( getArgs, getProgName, getEnvironment )
53import System.Exit ( exitWith, ExitCode (..) )
54import System.Console.GetOpt
56import Data.Maybe ( fromMaybe )
57import Data.List ( isPrefixOf )
58import Char ( toLower )
59import Control.Monad ( (>>=) )
64copyrightMessage :: String
65copyrightMessage = "\nCopyright (C) 2006 John MacFarlane\n\
66 \Web: http://sophos.berkeley.edu/macfarlane/pandoc\n\
67 \This is free software; see the source for copying conditions. There is no\n\
68 \warranty, not even for merchantability or fitness for a particular purpose."
70-- | Association list of formats and readers.
71readers :: [(String, ParserState -> String -> Pandoc)]
72readers = [("native" , readPandoc)
73 ,("markdown" , readMarkdown)
76 ,("latex" , readLaTeX)
79-- | Reader for native Pandoc format.
80readPandoc :: ParserState -> String -> Pandoc
81readPandoc state input = read input
83-- | Association list of formats and pairs of writers and default headers.
84writers :: [ ( String, ( WriterOptions -> Pandoc -> String, String ) ) ]
85writers = [("native" , (writeDoc, ""))
86 ,("html" , (writeHtmlString, ""))
87 ,("s5" , (writeS5String, defaultS5Header))
88 ,("docbook" , (writeDocbook, defaultDocbookHeader))
89 ,("latex" , (writeLaTeX, defaultLaTeXHeader))
90 ,("markdown" , (writeMarkdown, ""))
91 ,("rst" , (writeRST, ""))
92 ,("rtf" , (writeRTF, defaultRTFHeader))
95-- | Writer for Pandoc native format.
96writeDoc :: WriterOptions -> Pandoc -> String
97writeDoc options = prettyPandoc
99-- | Data structure for command line options.
101 { optPreserveTabs :: Bool -- ^ Convert tabs to spaces
102 , optTabStop :: Int -- ^ Number of spaces per tab
103 , optStandalone :: Bool -- ^ Include header, footer
104 , optReader :: String -- ^ Reader format
105 , optWriter :: String -- ^ Writer format
106 , optParseRaw :: Bool -- ^ Parse unconvertable HTML and TeX
107 , optCSS :: String -- ^ CSS file to link to
108 , optIncludeInHeader :: String -- ^ File to include in header
109 , optIncludeBeforeBody :: String -- ^ File to include at top of body
110 , optIncludeAfterBody :: String -- ^ File to include at end of body
111 , optCustomHeader :: String -- ^ Custom header to use, or "DEFAULT"
112 , optTitlePrefix :: String -- ^ Optional prefix for HTML title
113 , optOutputFile :: String -- ^ Name of output file
114 , optNumberSections :: Bool -- ^ Number sections in LaTeX
115 , optIncremental :: Bool -- ^ Use incremental lists in S5
116 , optSmart :: Bool -- ^ Use smart typography
117 , optASCIIMathML :: Bool -- ^ Use ASCIIMathML in HTML
118 , optDumpArgs :: Bool -- ^ Output command-line arguments
119 , optIgnoreArgs :: Bool -- ^ Ignore command-line arguments
120 , optStrict :: Bool -- ^ Use strict markdown syntax
123-- | Defaults for command-line options.
126 { optPreserveTabs = False
128 , optStandalone = False
129 , optReader = "" -- null for default reader
130 , optWriter = "" -- null for default writer
131 , optParseRaw = False
133 , optIncludeInHeader = ""
134 , optIncludeBeforeBody = ""
135 , optIncludeAfterBody = ""
136 , optCustomHeader = "DEFAULT"
137 , optTitlePrefix = ""
138 , optOutputFile = "-" -- "-" means stdout
139 , optNumberSections = False
140 , optIncremental = False
142 , optASCIIMathML = False
143 , optDumpArgs = False
144 , optIgnoreArgs = False
148-- | A list of functions, each transforming the options data structure
149-- in response to a command-line option.
150options :: [OptDescr (Opt -> IO Opt)]
152 [ Option "fr" ["from","read"]
154 (\arg opt -> return opt { optReader = map toLower arg })
156 "" -- ("(" ++ (joinWithSep ", " (map fst readers)) ++ ")")
158 , Option "tw" ["to","write"]
160 (\arg opt -> return opt { optWriter = map toLower arg })
162 "" -- ("(" ++ (joinWithSep ", " (map fst writers)) ++ ")")
164 , Option "s" ["standalone"]
166 (\opt -> return opt { optStandalone = True }))
167 "" -- "Include needed header and footer on output"
169 , Option "o" ["output"]
171 (\arg opt -> return opt { optOutputFile = arg })
173 "" -- "Name of output file"
175 , Option "p" ["preserve-tabs"]
177 (\opt -> return opt { optPreserveTabs = True }))
178 "" -- "Preserve tabs instead of converting to spaces"
180 , Option "" ["tab-stop"]
182 (\arg opt -> return opt { optTabStop = (read arg) } )
184 "" -- "Tab stop (default 4)"
186 , Option "" ["strict"]
188 (\opt -> return opt { optStrict = True } ))
189 "" -- "Use strict markdown syntax with no extensions"
191 , Option "R" ["parse-raw"]
193 (\opt -> return opt { optParseRaw = True }))
194 "" -- "Parse untranslatable HTML codes and LaTeX environments as raw"
196 , Option "S" ["smart"]
198 (\opt -> return opt { optSmart = True }))
199 "" -- "Use smart quotes, dashes, and ellipses"
201 , Option "m" ["asciimathml"]
203 (\opt -> return opt { optASCIIMathML = True,
204 optStandalone = True }))
205 "" -- "Use ASCIIMathML script in html output"
207 , Option "i" ["incremental"]
209 (\opt -> return opt { optIncremental = True }))
210 "" -- "Make list items display incrementally in S5"
212 , Option "N" ["number-sections"]
214 (\opt -> return opt { optNumberSections = True }))
215 "" -- "Number sections in LaTeX"
219 (\arg opt -> return opt { optCSS = arg,
220 optStandalone = True })
222 "" -- "Link to CSS style sheet"
224 , Option "H" ["include-in-header"]
228 return opt { optIncludeInHeader = text,
229 optStandalone = True })
231 "" -- "File to include at end of header (implies -s)"
233 , Option "B" ["include-before-body"]
237 return opt { optIncludeBeforeBody = text })
239 "" -- "File to include before document body"
241 , Option "A" ["include-after-body"]
245 return opt { optIncludeAfterBody = text })
247 "" -- "File to include after document body"
249 , Option "C" ["custom-header"]
253 return opt { optCustomHeader = text,
254 optStandalone = True })
256 "" -- "File to use for custom header (implies -s)"
258 , Option "T" ["title-prefix"]
260 (\arg opt -> return opt { optTitlePrefix = arg,
261 optStandalone = True })
263 "" -- "String to prefix to HTML window title"
265 , Option "D" ["print-default-header"]
268 let header = case (lookup arg writers) of
269 Just (writer, head) -> head
270 Nothing -> error ("Unknown reader: " ++ arg)
271 hPutStr stdout header
272 exitWith ExitSuccess)
274 "" -- "Print default header for FORMAT"
276 , Option "" ["dump-args"]
278 (\opt -> return opt { optDumpArgs = True }))
279 "" -- "Print output filename and arguments to stdout."
281 , Option "" ["ignore-args"]
283 (\opt -> return opt { optIgnoreArgs = True }))
284 "" -- "Ignore command-line arguments."
286 , Option "v" ["version"]
290 hPutStrLn stderr (prg ++ " " ++ version ++
292 exitWith $ ExitFailure 4))
293 "" -- "Print version"
295 , Option "h" ["help"]
299 hPutStr stderr (usageMessage prg options)
300 exitWith $ ExitFailure 2))
304-- Returns usage message
305usageMessage :: String -> [OptDescr (Opt -> IO Opt)] -> String
306usageMessage programName options = usageInfo
307 (programName ++ " [OPTIONS] [FILES]" ++ "\nInput formats: " ++
308 joinWithSep ", " (map fst readers) ++ "\nOutput formats: " ++
309 joinWithSep ", " (map fst writers) ++ "\nOptions:")
312-- Determine default reader based on source file extensions
313defaultReaderName :: [String] -> String
314defaultReaderName [] = "markdown"
315defaultReaderName (x:xs) =
316 let x' = map toLower x in
317 case (matchRegex (mkRegex ".*\\.(.*)") x') of
318 Nothing -> defaultReaderName xs -- no extension
319 Just ["xhtml"] -> "html"
320 Just ["html"] -> "html"
321 Just ["htm"] -> "html"
322 Just ["tex"] -> "latex"
323 Just ["latex"] -> "latex"
324 Just ["ltx"] -> "latex"
325 Just ["rst"] -> "rst"
326 Just ["native"] -> "native"
329-- Determine default writer based on output file extension
330defaultWriterName :: String -> String
331defaultWriterName "-" = "html" -- no output file
333 let x' = map toLower x in
334 case (matchRegex (mkRegex ".*\\.(.*)") x') of
335 Nothing -> "markdown" -- no extension
336 Just [""] -> "markdown" -- empty extension
337 Just ["tex"] -> "latex"
338 Just ["latex"] -> "latex"
339 Just ["ltx"] -> "latex"
340 Just ["rtf"] -> "rtf"
341 Just ["rst"] -> "rst"
343 Just ["native"] -> "native"
344 Just ["txt"] -> "markdown"
345 Just ["text"] -> "markdown"
346 Just ["md"] -> "markdown"
347 Just ["markdown"] -> "markdown"
348 Just ["db"] -> "docbook"
349 Just ["xml"] -> "docbook"
350 Just ["sgml"] -> "docbook"
357 let compatMode = (prg == "hsmarkdown")
359 let (actions, args, errors) = if compatMode
360 then ([], rawArgs, [])
361 else getOpt Permute options rawArgs
363 if (not (null errors))
366 mapM (\e -> hPutStrLn stderr e) errors
367 hPutStr stderr (usageMessage name options)
368 exitWith $ ExitFailure 2
372 let defaultOpts' = if compatMode
373 then defaultOpts { optReader = "markdown"
378 -- thread option data structure through all supplied option actions
379 opts <- foldl (>>=) (return defaultOpts') actions
381 let Opt { optPreserveTabs = preserveTabs
382 , optTabStop = tabStop
383 , optStandalone = standalone
384 , optReader = readerName
385 , optWriter = writerName
386 , optParseRaw = parseRaw
388 , optIncludeInHeader = includeHeader
389 , optIncludeBeforeBody = includeBefore
390 , optIncludeAfterBody = includeAfter
391 , optCustomHeader = customHeader
392 , optTitlePrefix = titlePrefix
393 , optOutputFile = outputFile
394 , optNumberSections = numberSections
395 , optIncremental = incremental
397 , optASCIIMathML = asciiMathML
398 , optDumpArgs = dumpArgs
399 , optIgnoreArgs = ignoreArgs
405 hPutStrLn stdout outputFile
406 mapM (\arg -> hPutStrLn stdout arg) args
407 exitWith $ ExitSuccess
410 let sources = if ignoreArgs then [] else args
412 -- assign reader and writer based on options and filenames
413 let readerName' = if null readerName
414 then defaultReaderName sources
417 let writerName' = if null writerName
418 then defaultWriterName outputFile
421 reader <- case (lookup readerName' readers) of
423 Nothing -> error ("Unknown reader: " ++ readerName')
425 (writer, defaultHeader) <- case (lookup writerName' writers) of
426 Just (w,h) -> return (w, h)
427 Nothing -> error ("Unknown writer: " ++ writerName')
429 output <- if (outputFile == "-")
431 else openFile outputFile WriteMode
433 environment <- getEnvironment
434 let columns = case lookup "COLUMNS" environment of
435 Just cols -> read cols
436 Nothing -> stateColumns defaultParserState
438 let tabFilter = if preserveTabs then id else (tabsToSpaces tabStop)
439 let addBlank str = str ++ "\n\n"
440 let removeCRs str = filter (/= '\r') str -- remove DOS-style line endings
441 let filter = tabFilter . addBlank . removeCRs
442 let startParserState =
443 defaultParserState { stateParseRaw = parseRaw,
444 stateTabStop = tabStop,
445 stateStandalone = standalone && (not strict),
446 stateSmart = smart || writerName' == "latex",
447 stateColumns = columns,
448 stateStrict = strict }
449 let csslink = if (css == "")
451 else "<link rel=\"stylesheet\" href=\"" ++ css ++
452 "\" type=\"text/css\" media=\"all\" />\n"
453 let asciiMathMLLink = if asciiMathML then asciiMathMLScript else ""
454 let header = (if (customHeader == "DEFAULT")
456 else customHeader) ++
457 csslink ++ asciiMathMLLink ++ includeHeader
458 let writerOptions = WriterOptions { writerStandalone = standalone &&
460 writerHeader = header,
461 writerTitlePrefix = titlePrefix,
462 writerTabStop = tabStop,
464 writerS5 = (writerName=="s5"),
465 writerIncremental = incremental,
466 writerNumberSections = numberSections,
467 writerIncludeBefore = includeBefore,
468 writerIncludeAfter = includeAfter,
469 writerStrictMarkdown = strict }
471 (readSources sources) >>= (hPutStr output . encodeUTF8 .
472 (writer writerOptions) .
473 (reader startParserState) . filter .
474 decodeUTF8 . (joinWithSep "\n")) >> hClose output
477 readSources [] = mapM readSource ["-"]
478 readSources sources = mapM readSource sources
479 readSource "-" = getContents
480 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