1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
|
{-# LANGUAGE CPP #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NoImplicitPrelude #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TupleSections #-}
{- |
Module : Text.Pandoc.App
Copyright : Copyright (C) 2006-2019 John MacFarlane
License : GNU GPL, version 2 or above
Maintainer : John MacFarlane <jgm@berkeley@edu>
Stability : alpha
Portability : portable
Does a pandoc conversion based on command-line options.
-}
module Text.Pandoc.App.OutputSettings
( OutputSettings (..)
, optToOutputSettings
) where
import Prelude
import qualified Control.Exception as E
import Control.Monad
import Control.Monad.Except (catchError, throwError)
import Control.Monad.Trans
import Data.Char (toLower)
import Data.List (find, isPrefixOf, isSuffixOf)
import Data.Maybe (fromMaybe)
import Skylighting (defaultSyntaxMap)
import Skylighting.Parser (addSyntaxDefinition, parseSyntaxDefinition)
import System.Directory (getCurrentDirectory)
import System.Exit (exitSuccess)
import System.FilePath
import System.IO (stdout)
import Text.Pandoc
import Text.Pandoc.App.FormatHeuristics (formatFromFilePaths)
import Text.Pandoc.App.Opt (Opt (..))
import Text.Pandoc.App.CommandLineOptions (engines, lookupHighlightStyle,
setVariable)
import qualified Text.Pandoc.UTF8 as UTF8
-- | Settings specifying how document output should be produced.
data OutputSettings = OutputSettings
{ outputFormat :: String
, outputWriter :: Writer PandocIO
, outputWriterName :: String
, outputWriterOptions :: WriterOptions
, outputPdfProgram :: Maybe String
}
readUtf8File :: PandocMonad m => FilePath -> m String
readUtf8File = fmap UTF8.toString . readFileStrict
-- | Get output settings from command line options.
optToOutputSettings :: Opt -> PandocIO OutputSettings
optToOutputSettings opts = do
let outputFile = fromMaybe "-" (optOutputFile opts)
when (optDumpArgs opts) . liftIO $ do
UTF8.hPutStrLn stdout outputFile
mapM_ (UTF8.hPutStrLn stdout) (optInputFiles opts)
exitSuccess
epubMetadata <- case optEpubMetadata opts of
Nothing -> return Nothing
Just fp -> Just <$> readUtf8File fp
let pdfOutput = map toLower (takeExtension outputFile) == ".pdf"
(writerName, maybePdfProg) <-
if pdfOutput
then liftIO $ pdfWriterAndProg (optWriter opts) (optPdfEngine opts)
else case optWriter opts of
Nothing
| outputFile == "-" -> return ("html", Nothing)
| otherwise ->
case formatFromFilePaths [outputFile] of
Nothing -> do
report $ CouldNotDeduceFormat
[takeExtension outputFile] "html"
return ("html", Nothing)
Just f -> return (f, Nothing)
Just f -> return (f, Nothing)
let format = if ".lua" `isSuffixOf` writerName
then writerName
else map toLower $ baseWriterName writerName
(writer :: Writer PandocIO, writerExts) <-
if ".lua" `isSuffixOf` format
then return (TextWriter
(\o d -> writeCustom writerName o d)
:: Writer PandocIO, mempty)
else getWriter (map toLower writerName)
let standalone = optStandalone opts || not (isTextFormat format) || pdfOutput
let addSyntaxMap existingmap f = do
res <- liftIO (parseSyntaxDefinition f)
case res of
Left errstr -> throwError $ PandocSyntaxMapError errstr
Right syn -> return $ addSyntaxDefinition syn existingmap
syntaxMap <- foldM addSyntaxMap defaultSyntaxMap
(optSyntaxDefinitions opts)
hlStyle <- maybe (return Nothing) (fmap Just . lookupHighlightStyle)
(optHighlightStyle opts)
-- note: this reverses the list constructed in option parsing,
-- which in turn was reversed from the command-line order,
-- so we end up with the correct order in the variable list:
let withList _ [] vars = return vars
withList f (x:xs) vars = f x vars >>= withList f xs
let setVariableM k v = return . setVariable k v
let addContentsAsVariable varname fp vars = do
s <- UTF8.toString . fst <$> fetchItem fp
setVariableM varname s vars
curdir <- liftIO getCurrentDirectory
variables <-
withList (setVariableM "sourcefile")
-- we reverse this list because, unlike
-- the other option lists here, it is
-- not reversed when parsed from CLI arguments.
-- See withList, above.
(reverse $ optInputFiles opts)
(optVariables opts)
>>=
setVariableM "outputfile" (fromMaybe "-" (optOutputFile opts))
>>=
withList (addContentsAsVariable "include-before")
(optIncludeBeforeBody opts)
>>=
withList (addContentsAsVariable "include-after")
(optIncludeAfterBody opts)
>>=
withList (addContentsAsVariable "header-includes")
(optIncludeInHeader opts)
>>=
withList (setVariableM "css") (optCss opts)
>>=
maybe return (setVariableM "title-prefix")
(optTitlePrefix opts)
>>=
maybe return (setVariableM "epub-cover-image")
(optEpubCoverImage opts)
>>=
setVariableM "curdir" curdir
>>=
(\vars -> if format == "dzslides"
then do
dztempl <- UTF8.toString <$> readDataFile
("dzslides" </> "template.html")
let dzline = "<!-- {{{{ dzslides core"
let dzcore = unlines
$ dropWhile (not . (dzline `isPrefixOf`))
$ lines dztempl
setVariableM "dzslides-core" dzcore vars
else return vars)
templStr <- case optTemplate opts of
_ | not standalone -> return Nothing
Nothing -> Just <$> getDefaultTemplate format
Just tp -> do
-- strip off extensions
let tp' = case takeExtension tp of
"" -> tp <.> format
_ -> tp
Just . UTF8.toText <$>
((do surl <- stSourceURL <$> getCommonState
-- we don't want to look for templates remotely
-- unless the full URL is specified:
modifyCommonState $ \st -> st{
stSourceURL = Nothing }
(bs, _) <- fetchItem tp'
modifyCommonState $ \st -> st{
stSourceURL = surl }
return bs)
`catchError`
(\e ->
case e of
PandocResourceNotFound _ ->
readDataFile ("templates" </> tp')
_ -> throwError e))
let templatePath = fromMaybe "" $ optTemplate opts
templ <- case templStr of
Nothing -> return Nothing
Just ts -> do
res <- compileTemplate templatePath ts
case res of
Left e -> throwError $ PandocTemplateError e
Right t -> return $ Just t
let writerOpts = def {
writerTemplate = templ
, writerVariables = variables
, writerTabStop = optTabStop opts
, writerTableOfContents = optTableOfContents opts
, writerHTMLMathMethod = optHTMLMathMethod opts
, writerIncremental = optIncremental opts
, writerCiteMethod = optCiteMethod opts
, writerNumberSections = optNumberSections opts
, writerNumberOffset = optNumberOffset opts
, writerSectionDivs = optSectionDivs opts
, writerExtensions = writerExts
, writerReferenceLinks = optReferenceLinks opts
, writerReferenceLocation = optReferenceLocation opts
, writerDpi = optDpi opts
, writerWrapText = optWrapText opts
, writerColumns = optColumns opts
, writerEmailObfuscation = optEmailObfuscation opts
, writerIdentifierPrefix = optIdentifierPrefix opts
, writerHtmlQTags = optHtmlQTags opts
, writerTopLevelDivision = optTopLevelDivision opts
, writerListings = optListings opts
, writerSlideLevel = optSlideLevel opts
, writerHighlightStyle = hlStyle
, writerSetextHeaders = optSetextHeaders opts
, writerEpubSubdirectory = optEpubSubdirectory opts
, writerEpubMetadata = epubMetadata
, writerEpubFonts = optEpubFonts opts
, writerEpubChapterLevel = optEpubChapterLevel opts
, writerTOCDepth = optTOCDepth opts
, writerReferenceDoc = optReferenceDoc opts
, writerSyntaxMap = syntaxMap
, writerPreferAscii = optAscii opts
}
return $ OutputSettings
{ outputFormat = format
, outputWriter = writer
, outputWriterName = writerName
, outputWriterOptions = writerOpts
, outputPdfProgram = maybePdfProg
}
baseWriterName :: String -> String
baseWriterName = takeWhile (\c -> c /= '+' && c /= '-')
pdfWriterAndProg :: Maybe String -- ^ user-specified writer name
-> Maybe String -- ^ user-specified pdf-engine
-> IO (String, Maybe String) -- ^ IO (writerName, maybePdfEngineProg)
pdfWriterAndProg mWriter mEngine = do
let panErr msg = liftIO $ E.throwIO $ PandocAppError msg
case go mWriter mEngine of
Right (writ, prog) -> return (writ, Just prog)
Left "pdf writer" -> liftIO $ E.throwIO $
PandocUnknownWriterError "pdf"
Left err -> panErr err
where
go Nothing Nothing = Right ("latex", "pdflatex")
go (Just writer) Nothing = (writer,) <$> engineForWriter writer
go Nothing (Just engine) = (,engine) <$> writerForEngine (takeBaseName engine)
go (Just writer) (Just engine) =
case find (== (baseWriterName writer, takeBaseName engine)) engines of
Just _ -> Right (writer, engine)
Nothing -> Left $ "pdf-engine " ++ engine ++
" is not compatible with output format " ++ writer
writerForEngine eng = case [f | (f,e) <- engines, e == eng] of
fmt : _ -> Right fmt
[] -> Left $
"pdf-engine " ++ eng ++ " not known"
engineForWriter "pdf" = Left "pdf writer"
engineForWriter w = case [e | (f,e) <- engines, f == baseWriterName w] of
eng : _ -> Right eng
[] -> Left $
"cannot produce pdf output from " ++ w
isTextFormat :: String -> Bool
isTextFormat s = s `notElem` ["odt","docx","epub2","epub3","epub","pptx"]
|