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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
|
{-
Copyright (C) 2018 Yan Pashkovsky <yanp.bugz@gmail.com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-}
{- |
Module : Text.Pandoc.Readers.Man
Copyright : Copyright (C) 2018 Yan Pashkovsky
License : GNU GPL, version 2 or above
Maintainer : Yan Pashkovsky <yanp.bugz@gmail.com>
Stability : WIP
Portability : portable
Conversion of man to 'Pandoc' document.
-}
module Text.Pandoc.Readers.Man (readMan, testFile) where
import Prelude
import Control.Monad (liftM)
import Control.Monad.Except (throwError)
import Data.Default (Default)
import Data.Map (insert)
import Data.Maybe (isJust, catMaybes)
import Data.List (intersperse, intercalate)
import qualified Data.Text as T
import Text.Pandoc.Class (PandocMonad(..), runIOorExplode)
import Text.Pandoc.Definition
import Text.Pandoc.Error (PandocError (PandocParsecError))
import Text.Pandoc.Logging (LogMessage(..))
import Text.Pandoc.Options
import Text.Pandoc.Parsing
import Text.Pandoc.Shared (crFilter)
import Text.Parsec hiding (tokenPrim)
import Text.Parsec.Char ()
import Text.Parsec.Pos (updatePosString)
--
-- Data Types
--
data FontKind = Regular | Italic | Bold | ItalicBold deriving Show
data MacroKind = KTitle
| KCodeBlStart
| KCodeBlEnd
| KTab
| KTabEnd
deriving (Show, Eq)
data ManToken = MStr String FontKind
| MLine [(String, FontKind)]
| MLink String Target
| MEmptyLine
| MHeader Int String
| MMacro MacroKind [String]
| MUnknownMacro String [String]
| MComment String
deriving Show
data EscapeThing = EFont FontKind
| EChar Char
| ENothing
deriving Show
data RoffState = RoffState { fontKind :: FontKind
} deriving Show
instance Default RoffState where
def = RoffState {fontKind = Regular}
type ManParser m = ParserT [Char] RoffState m
type ManCompiler m = ParserT [ManToken] ParserState m
----
-- testStrr :: [Char] -> Either PandocError Pandoc
-- testStrr s = runPure $ readMan def (T.pack s)
printPandoc :: Pandoc -> [Char]
printPandoc (Pandoc m content) =
let ttl = "Pandoc: " ++ (show $ unMeta m)
cnt = intercalate "\n" $ map show content
in ttl ++ "\n" ++ cnt
-- strrepr :: Either PandocError Pandoc -> [Char]
-- strrepr obj = case obj of
-- Right x -> printPandoc x
-- Left y -> show y
testFile :: FilePath -> IO ()
testFile fname = do
cont <- readFile fname
pand <- runIOorExplode $ readMan def (T.pack cont)
putStrLn $ printPandoc pand
----
-- | Read man (troff) from an input string and return a Pandoc document.
readMan :: PandocMonad m => ReaderOptions -> T.Text -> m Pandoc
readMan opts txt = do
eithertokens <- readWithM parseMan def (T.unpack $ crFilter txt)
case eithertokens of
Right tokenz -> do
let state = def {stateOptions = opts} :: ParserState
eitherdoc <- readWithMTokens compileMan state tokenz
case eitherdoc of
Right doc -> return doc
Left e -> throwError e
Left e -> throwError e
where
readWithMTokens :: PandocMonad m
=> ParserT [ManToken] ParserState m a -- ^ parser
-> ParserState -- ^ initial state
-> [ManToken] -- ^ input
-> m (Either PandocError a)
readWithMTokens parser state input =
mapLeft (PandocParsecError . concat $ show <$> input) `liftM` runParserT parser state "source" input
mapLeft :: (a -> c) -> Either a b -> Either c b
mapLeft f (Left x) = Left $ f x
mapLeft _ (Right r) = Right r
--
-- String -> ManToken function
--
parseMan :: PandocMonad m => ManParser m [ManToken]
parseMan = many (parseMacro <|> parseLine <|> parseEmptyLine)
compileMan :: PandocMonad m => ManCompiler m Pandoc
compileMan = do
let compilers = [compileTitle, compilePara, compileSkippedContent
, compileCodeBlock, compileHeader, compileSkipMacro]
blocks <- many $ choice compilers
parserst <- getState
return $ Pandoc (stateMeta parserst) (filter (not . isNull) blocks)
where
isNull Null = True
isNull _ = False
parseMacro :: PandocMonad m => ManParser m ManToken
parseMacro = do
char '.' <|> char '\''
many space
macroName <- many1 (letter <|> oneOf ['\\', '"'])
args <- parseArgs
let joinedArgs = concat $ intersperse " " args
let tok = case macroName of
x | x `elem` ["\\\"", "\\#"] -> MComment joinedArgs
"TH" -> MMacro KTitle args
"TP" -> MMacro KTab []
"PP" -> MMacro KTabEnd []
"nf" -> MMacro KCodeBlStart []
"fi" -> MMacro KCodeBlEnd []
x | x `elem` ["B", "BR"] -> MStr joinedArgs Bold -- "BR" is often used as a link to another man
x | x `elem` ["BI", "IB"] -> MStr joinedArgs ItalicBold
x | x `elem` ["I", "IR", "RI"] -> MStr joinedArgs Italic
"SH" -> MHeader 2 joinedArgs
"sp" -> MEmptyLine
_ -> MUnknownMacro macroName args
return tok
where
linkToMan :: String -> Maybe Block
linkToMan txt = case runParser linkParser () "" txt of
Right lnk -> Just $ Plain [lnk]
Left _ -> Nothing
where
linkParser :: Parsec String () Inline
linkParser = do
mpage <- many1 alphaNum
space
char '('
mansect <- digit
char ')'
-- assuming man pages are generated from Linux-like repository
let manurl pagename section = "../"++section++"/"++pagename++"."++section
return $ Link nullAttr [Str txt] (manurl mpage [mansect], mpage)
parseArgs :: PandocMonad m => ManParser m [String]
parseArgs = do
eolOpt <- optionMaybe $ char '\n'
if isJust eolOpt
then return []
else do
many1 space
arg <- try quotedArg <|> plainArg
otherargs <- parseArgs
return $ arg : otherargs
where
plainArg :: PandocMonad m => ManParser m String
plainArg = many1 $ noneOf " \t\n"
quotedArg :: PandocMonad m => ManParser m String
quotedArg = do
char '"'
val <- many1 quotedChar
char '"'
return val
quotedChar :: PandocMonad m => ManParser m Char
quotedChar = noneOf "\"\n" <|> try (string "\"\"" >> return '"')
escapeParser :: PandocMonad m => ManParser m EscapeThing
escapeParser = do
char '\\'
choice [escChar, escFont]
where
escChar :: PandocMonad m => ManParser m EscapeThing
escChar = choice [ char '-' >> return (EChar '-')
, oneOf ['%', '{', '}'] >> return ENothing
]
escFont :: PandocMonad m => ManParser m EscapeThing
escFont = do
char 'f'
font <- choice [ char 'B' >> return Bold
, char 'I' >> return Italic
, (char 'P' <|> anyChar) >> return Regular
, char '(' >> anyChar >> anyChar >> return Regular
, string "[]" >> return Regular
, char '[' >> many1 letter >> char ']' >> return Regular
]
modifyState (\r -> r {fontKind = font})
return $ EFont font
parseLine :: PandocMonad m => ManParser m ManToken
parseLine = do
lnparts <- many1 (esc <|> linePart)
newline
return $ MLine $ catMaybes lnparts
where
esc :: PandocMonad m => ManParser m (Maybe (String, FontKind))
esc = do
someesc <- escapeParser
font <- currentFont
let rv = case someesc of
EChar c -> Just ([c], font)
_ -> Nothing
return rv
linePart :: PandocMonad m => ManParser m (Maybe (String, FontKind))
linePart = do
lnpart <- many1 $ noneOf "\n\\"
font <- currentFont
return $ Just (lnpart, font)
currentFont :: PandocMonad m => ManParser m FontKind
currentFont = do
RoffState {fontKind = fk} <- getState
return fk
parseEmptyLine :: PandocMonad m => ManParser m ManToken
parseEmptyLine = char '\n' >> return MEmptyLine
--
-- ManToken parsec functions
--
msatisfy :: (Show t, Stream s m t) => (t -> Bool) -> ParserT s st m t
msatisfy predic = tokenPrim show nextPos testTok
where
testTok t = if predic t then Just t else Nothing
nextPos pos x _xs = updatePosString pos (show x)
mstr :: PandocMonad m => ManCompiler m ManToken
mstr = msatisfy isMStr where
isMStr (MStr _ _) = True
isMStr _ = False
mline :: PandocMonad m => ManCompiler m ManToken
mline = msatisfy isMLine where
isMLine (MLine _) = True
isMLine _ = False
mlink :: PandocMonad m => ManCompiler m ManToken
mlink = msatisfy isMLink where
isMLink (MLink _ _) = True
isMLink _ = False
memplyLine :: PandocMonad m => ManCompiler m ManToken
memplyLine = msatisfy isMEmptyLine where
isMEmptyLine MEmptyLine = True
isMEmptyLine _ = False
mheader :: PandocMonad m => ManCompiler m ManToken
mheader = msatisfy isMHeader where
isMHeader (MHeader _ _) = True
isMHeader _ = False
mmacro :: PandocMonad m => MacroKind -> ManCompiler m ManToken
mmacro mk = msatisfy isMMacro where
isMMacro (MMacro mk' _) | mk == mk' = True
| otherwise = False
isMMacro _ = False
mmacroAny :: PandocMonad m => ManCompiler m ManToken
mmacroAny = msatisfy isMMacro where
isMMacro (MMacro _ _) = True
isMMacro _ = False
munknownMacro :: PandocMonad m => ManCompiler m ManToken
munknownMacro = msatisfy isMUnknownMacro where
isMUnknownMacro (MUnknownMacro _ _) = True
isMUnknownMacro _ = False
mcomment :: PandocMonad m => ManCompiler m ManToken
mcomment = msatisfy isMComment where
isMComment (MComment _) = True
isMComment _ = False
--
-- ManToken -> Block functions
--
compileTitle :: PandocMonad m => ManCompiler m Block
compileTitle = do
(MMacro _ args) <- mmacro KTitle
if null args
then return Null
else do
let mantitle = head args
modifyState (changeTitle mantitle)
return $ Header 1 nullAttr [Str mantitle]
where
changeTitle title pst =
let meta = stateMeta pst
metaUp = Meta $ insert "title" (MetaString title) (unMeta meta)
in
pst {stateMeta = metaUp}
compileSkippedContent :: PandocMonad m => ManCompiler m Block
compileSkippedContent = do
tok <- munknownMacro <|> mcomment <|> memplyLine
onToken tok
return Null
where
onToken :: PandocMonad m => ManToken -> ManCompiler m ()
onToken (MUnknownMacro mname _) = do
pos <- getPosition
logMessage $ SkippedContent ("Unknown macro: " ++ mname) pos
onToken _ = return ()
strToInline :: String -> FontKind -> Inline
strToInline s Regular = Str s
strToInline s Italic = Emph [Str s]
strToInline s Bold = Strong [Str s]
strToInline s ItalicBold = Strong [Emph [Str s]]
compilePara :: PandocMonad m => ManCompiler m Block
compilePara = do
inls <- many1 (strInl <|> lineInl <|> comment)
let withspaces = intersperse [Str " "] inls
return $ Para (concat withspaces)
where
strInl :: PandocMonad m => ManCompiler m [Inline]
strInl = do
(MStr str fk) <- mstr
return [strToInline str fk]
lineInl :: PandocMonad m => ManCompiler m [Inline]
lineInl = do
(MLine fragments) <- mline
return $ fmap (\(s,f) -> strToInline s f) fragments
comment :: PandocMonad m => ManCompiler m [Inline]
comment = mcomment >> return []
compileCodeBlock :: PandocMonad m => ManCompiler m Block
compileCodeBlock = do
mmacro KCodeBlStart
toks <- many (mstr <|> mline <|> mlink <|> memplyLine <|> munknownMacro <|> mcomment)
mmacro KCodeBlEnd
return $ CodeBlock nullAttr (intercalate "\n" . catMaybes $ extractText <$> toks)
where
extractText :: ManToken -> Maybe String
extractText (MStr s _) = Just s
extractText (MLine ss) = Just . intercalate " " $ map fst ss
extractText (MLink s _) = Just s
extractText MEmptyLine = Just "" -- string are intercalated with '\n', this prevents double '\n'
extractText _ = Nothing
compileHeader :: PandocMonad m => ManCompiler m Block
compileHeader = do
(MHeader lvl s) <- mheader
return $ Header lvl nullAttr [Str s]
compileSkipMacro :: PandocMonad m => ManCompiler m Block
compileSkipMacro = mmacroAny >> return Null
|