aboutsummaryrefslogtreecommitdiff
path: root/haddock-library/src/Documentation/Haddock/Parser.hs
blob: 149ff93d71e0d82a2f590e643724fe5612c27528 (plain) (blame)
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE ViewPatterns      #-}
-- |
-- Module      :  Documentation.Haddock.Parser
-- Copyright   :  (c) Mateusz Kowalczyk 2013-2014,
--                    Simon Hengel      2013
-- License     :  BSD-like
--
-- Maintainer  :  haddock@projects.haskell.org
-- Stability   :  experimental
-- Portability :  portable
--
-- Parser used for Haddock comments. For external users of this
-- library, the most commonly used combination of functions is going
-- to be
--
-- @'toRegular' . '_doc' . 'parseParas'@
module Documentation.Haddock.Parser (
  parseString,
  parseParas,
  overIdentifier,
  toRegular,
  Identifier
) where

import           Control.Applicative
import           Control.Arrow (first)
import           Control.Monad
import           Data.Char (chr, isUpper, isAlpha, isSpace)
import           Data.List (intercalate, unfoldr, elemIndex)
import           Data.Maybe (fromMaybe, mapMaybe)
import           Data.Monoid
import qualified Data.Set as Set
import           Documentation.Haddock.Doc
import           Documentation.Haddock.Markup ( markup, plainMarkup )
import           Documentation.Haddock.Parser.Monad
import           Documentation.Haddock.Parser.Util
import           Documentation.Haddock.Parser.Identifier
import           Documentation.Haddock.Types
import           Prelude hiding (takeWhile)
import qualified Prelude as P

import qualified Text.Parsec as Parsec
import           Text.Parsec (try)

import qualified Data.Text as T
import           Data.Text (Text)


-- $setup
-- >>> :set -XOverloadedStrings

-- | Drops the quotes/backticks around all identifiers, as if they
-- were valid but still 'String's.
toRegular :: DocH mod Identifier -> DocH mod String
toRegular = fmap (\(Identifier _ _ x _) -> x)

-- | Maps over 'DocIdentifier's over 'String' with potentially failing
-- conversion using user-supplied function. If the conversion fails,
-- the identifier is deemed to not be valid and is treated as a
-- regular string.
overIdentifier :: (Namespace -> String -> Maybe a)
               -> DocH mod Identifier
               -> DocH mod a
overIdentifier f d = g d
  where
    g (DocIdentifier (Identifier ns o x e)) = case f ns x of
      Nothing -> DocString $ renderNs ns ++ [o] ++ x ++ [e]
      Just x' -> DocIdentifier x'
    g DocEmpty = DocEmpty
    g (DocAppend x x') = DocAppend (g x) (g x')
    g (DocString x) = DocString x
    g (DocParagraph x) = DocParagraph $ g x
    g (DocIdentifierUnchecked x) = DocIdentifierUnchecked x
    g (DocModule x) = DocModule x
    g (DocWarning x) = DocWarning $ g x
    g (DocEmphasis x) = DocEmphasis $ g x
    g (DocMonospaced x) = DocMonospaced $ g x
    g (DocBold x) = DocBold $ g x
    g (DocUnorderedList x) = DocUnorderedList $ fmap g x
    g (DocOrderedList x) = DocOrderedList $ fmap g x
    g (DocDefList x) = DocDefList $ fmap (\(y, z) -> (g y, g z)) x
    g (DocCodeBlock x) = DocCodeBlock $ g x
    g (DocHyperlink (Hyperlink u x)) = DocHyperlink (Hyperlink u (fmap g x))
    g (DocPic x) = DocPic x
    g (DocMathInline x) = DocMathInline x
    g (DocMathDisplay x) = DocMathDisplay x
    g (DocAName x) = DocAName x
    g (DocProperty x) = DocProperty x
    g (DocExamples x) = DocExamples x
    g (DocHeader (Header l x)) = DocHeader . Header l $ g x
    g (DocTable (Table h b)) = DocTable (Table (map (fmap g) h) (map (fmap g) b))


choice' :: [Parser a] -> Parser a
choice' [] = empty
choice' [p] = p
choice' (p : ps) = try p <|> choice' ps

parse :: Parser a -> Text -> (ParserState, a)
parse p = either err id . parseOnly (p <* Parsec.eof)
  where
    err = error . ("Haddock.Parser.parse: " ++)

-- | Main entry point to the parser. Appends the newline character
-- to the input string.
parseParas :: Maybe Package
           -> String -- ^ String to parse
           -> MetaDoc mod Identifier
parseParas pkg input = case parseParasState input of
  (state, a) -> MetaDoc { _meta = Meta { _version = parserStateSince state
                                       , _package = pkg
                                       }
                        , _doc = a
                        }

parseParasState :: String -> (ParserState, DocH mod Identifier)
parseParasState = parse (emptyLines *> p) . T.pack . (++ "\n") . filter (/= '\r')
  where
    p :: Parser (DocH mod Identifier)
    p = docConcat <$> many (paragraph <* emptyLines)

    emptyLines :: Parser ()
    emptyLines = void $ many (try (skipHorizontalSpace *> "\n"))

parseParagraphs :: String -> Parser (DocH mod Identifier)
parseParagraphs input = case parseParasState input of
  (state, a) -> Parsec.putState state *> pure a

-- | Variant of 'parseText' for 'String' instead of 'Text'
parseString :: String -> DocH mod Identifier
parseString = parseText . T.pack

-- | Parse a text paragraph. Actually just a wrapper over 'parseParagraph' which
-- drops leading whitespace.
parseText :: Text -> DocH mod Identifier
parseText = parseParagraph . T.dropWhile isSpace . T.filter (/= '\r')

parseParagraph :: Text -> DocH mod Identifier
parseParagraph = snd . parse p
  where
    p :: Parser (DocH mod Identifier)
    p = docConcat <$> many (choice' [ monospace
                                    , anchor
                                    , identifier
                                    , moduleName
                                    , picture
                                    , mathDisplay
                                    , mathInline
                                    , markdownImage
                                    , hyperlink
                                    , bold
                                    , emphasis
                                    , encodedChar
                                    , string'
                                    , skipSpecialChar
                                    ])

-- | Parses and processes
-- <https://en.wikipedia.org/wiki/Numeric_character_reference Numeric character references>
--
-- >>> parseString "&#65;"
-- DocString "A"
encodedChar :: Parser (DocH mod a)
encodedChar = "&#" *> c <* ";"
  where
    c = DocString . return . chr <$> num
    num = hex <|> decimal
    hex = ("x" <|> "X") *> hexadecimal

-- | List of characters that we use to delimit any special markup.
-- Once we have checked for any of these and tried to parse the
-- relevant markup, we can assume they are used as regular text.
specialChar :: [Char]
specialChar = "_/<@\"&'`# "

-- | Plain, regular parser for text. Called as one of the last parsers
-- to ensure that we have already given a chance to more meaningful parsers
-- before capturing their characers.
string' :: Parser (DocH mod a)
string' = DocString . unescape . T.unpack <$> takeWhile1_ (`notElem` specialChar)
  where
    unescape "" = ""
    unescape ('\\':x:xs) = x : unescape xs
    unescape (x:xs) = x : unescape xs

-- | Skips a single special character and treats it as a plain string.
-- This is done to skip over any special characters belonging to other
-- elements but which were not deemed meaningful at their positions.
skipSpecialChar :: Parser (DocH mod a)
skipSpecialChar = DocString . return <$> Parsec.oneOf specialChar

-- | Emphasis parser.
--
-- >>> parseString "/Hello world/"
-- DocEmphasis (DocString "Hello world")
emphasis :: Parser (DocH mod Identifier)
emphasis = DocEmphasis . parseParagraph <$>
  disallowNewline ("/" *> takeWhile1_ (/= '/') <* "/")

-- | Bold parser.
--
-- >>> parseString "__Hello world__"
-- DocBold (DocString "Hello world")
bold :: Parser (DocH mod Identifier)
bold = DocBold . parseParagraph <$> disallowNewline ("__" *> takeUntil "__")

disallowNewline :: Parser Text -> Parser Text
disallowNewline = mfilter (T.all (/= '\n'))

-- | Like `takeWhile`, but unconditionally take escaped characters.
takeWhile_ :: (Char -> Bool) -> Parser Text
takeWhile_ p = scan p_ False
  where
    p_ escaped c
      | escaped = Just False
      | not $ p c = Nothing
      | otherwise = Just (c == '\\')

-- | Like 'takeWhile1', but unconditionally take escaped characters.
takeWhile1_ :: (Char -> Bool) -> Parser Text
takeWhile1_ = mfilter (not . T.null) . takeWhile_

-- | Text anchors to allow for jumping around the generated documentation.
--
-- >>> parseString "#Hello world#"
-- DocAName "Hello world"
anchor :: Parser (DocH mod a)
anchor = DocAName . T.unpack <$>
         disallowNewline ("#" *> takeWhile1_ (/= '#') <* "#")

-- | Monospaced strings.
--
-- >>> parseString "@cruel@"
-- DocMonospaced (DocString "cruel")
monospace :: Parser (DocH mod Identifier)
monospace = DocMonospaced . parseParagraph
            <$> ("@" *> takeWhile1_ (/= '@') <* "@")

-- | Module names.
--
-- Note that we allow '#' and '\' to support anchors (old style anchors are of
-- the form "SomeModule\#anchor").
moduleName :: Parser (DocH mod a)
moduleName = DocModule <$> ("\"" *> modid <* "\"")
  where
    modid = intercalate "." <$> conid `Parsec.sepBy1` "."
    conid = (:)
      <$> Parsec.satisfy (\c -> isAlpha c && isUpper c)
      <*> many (conChar <|> Parsec.oneOf "\\#")

    conChar = Parsec.alphaNum <|> Parsec.char '_'

-- | Picture parser, surrounded by \<\< and \>\>. It's possible to specify
-- a title for the picture.
--
-- >>> parseString "<<hello.png>>"
-- DocPic (Picture {pictureUri = "hello.png", pictureTitle = Nothing})
-- >>> parseString "<<hello.png world>>"
-- DocPic (Picture {pictureUri = "hello.png", pictureTitle = Just "world"})
picture :: Parser (DocH mod a)
picture = DocPic . makeLabeled Picture
          <$> disallowNewline ("<<" *> takeUntil ">>")

-- | Inline math parser, surrounded by \\( and \\).
--
-- >>> parseString "\\(\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}\\)"
-- DocMathInline "\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}"
mathInline :: Parser (DocH mod a)
mathInline = DocMathInline . T.unpack
             <$> disallowNewline  ("\\(" *> takeUntil "\\)")

-- | Display math parser, surrounded by \\[ and \\].
--
-- >>> parseString "\\[\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}\\]"
-- DocMathDisplay "\\int_{-\\infty}^{\\infty} e^{-x^2/2} = \\sqrt{2\\pi}"
mathDisplay :: Parser (DocH mod a)
mathDisplay = DocMathDisplay . T.unpack
              <$> ("\\[" *> takeUntil "\\]")

-- | Markdown image parser. As per the commonmark reference recommendation, the
-- description text for an image converted to its a plain string representation.
--
-- >>> parseString "![some /emphasis/ in a description](www.site.com)"
-- DocPic (Picture "www.site.com" (Just "some emphasis in a description"))
markdownImage :: Parser (DocH mod Identifier)
markdownImage = DocPic . fromHyperlink <$> ("!" *> linkParser)
  where
    fromHyperlink (Hyperlink u l) = Picture u (fmap (markup stringMarkup) l)
    stringMarkup = plainMarkup (const "") renderIdent
    renderIdent (Identifier ns l c r) = renderNs ns <> [l] <> c <> [r]

-- | Paragraph parser, called by 'parseParas'.
paragraph :: Parser (DocH mod Identifier)
paragraph = choice' [ examples
                    , table
                    , do indent <- takeIndent
                         choice' [ since
                                 , unorderedList indent
                                 , orderedList indent
                                 , birdtracks
                                 , codeblock
                                 , property
                                 , header
                                 , textParagraphThatStartsWithMarkdownLink
                                 , definitionList indent
                                 , docParagraph <$> textParagraph
                                 ]
                    ]

-- | Provides support for grid tables.
--
-- Tables are composed by an optional header and body. The header is composed by
-- a single row. The body is composed by a non-empty list of rows.
--
-- Example table with header:
--
-- > +----------+----------+
-- > | /32bit/  |   64bit  |
-- > +==========+==========+
-- > |  0x0000  | @0x0000@ |
-- > +----------+----------+
--
-- Algorithms loosely follows ideas in
-- http://docutils.sourceforge.net/docutils/parsers/rst/tableparser.py
--
table :: Parser (DocH mod Identifier)
table = do
    -- first we parse the first row, which determines the width of the table
    firstRow <- parseFirstRow
    let len = T.length firstRow

    -- then we parse all consequtive rows starting and ending with + or |,
    -- of the width `len`.
    restRows <- many (try (parseRestRows len))

    -- Now we gathered the table block, the next step is to split the block
    -- into cells.
    DocTable <$> tableStepTwo len (firstRow : restRows)
  where
    parseFirstRow :: Parser Text
    parseFirstRow = do
        skipHorizontalSpace
        cs <- takeWhile (\c -> c == '-' || c == '+')

        -- upper-left and upper-right corners are `+`
        guard (T.length cs >= 2 &&
               T.head cs == '+' &&
               T.last cs == '+')

        -- trailing space
        skipHorizontalSpace
        _ <- Parsec.newline

        return cs

    parseRestRows :: Int -> Parser Text
    parseRestRows l = do
        skipHorizontalSpace
        bs <- scan predicate l

        -- Left and right edges are `|` or `+`
        guard (T.length bs >= 2 &&
               (T.head bs == '|' || T.head bs == '+') &&
               (T.last bs == '|' || T.last bs == '+'))

        -- trailing space
        skipHorizontalSpace
        _ <- Parsec.newline

        return bs
      where
        predicate n c
            | n <= 0    = Nothing
            | c == '\n' = Nothing
            | otherwise = Just (n - 1)

-- Second step searchs for row of '+' and '=' characters, records it's index
-- and changes to '=' to '-'.
tableStepTwo
    :: Int              -- ^ width
    -> [Text]           -- ^ rows
    -> Parser (Table (DocH mod Identifier))
tableStepTwo width = go 0 [] where
    go _ left [] = tableStepThree width (reverse left) Nothing
    go n left (r : rs)
        | T.all (`elem` ['+', '=']) r =
            tableStepThree width (reverse left ++ r' : rs) (Just n)
        | otherwise =
            go (n + 1) (r :  left) rs
      where
        r' = T.map (\c -> if c == '=' then '-' else c) r

-- Third step recognises cells in the table area, returning a list of TC, cells.
tableStepThree
    :: Int              -- ^ width
    -> [Text]           -- ^ rows
    -> Maybe Int        -- ^ index of header separator
    -> Parser (Table (DocH mod Identifier))
tableStepThree width rs hdrIndex = do
    cells <- loop (Set.singleton (0, 0))
    tableStepFour rs hdrIndex cells
  where
    height = length rs

    loop :: Set.Set (Int, Int) -> Parser [TC]
    loop queue = case Set.minView queue of
        Nothing -> return []
        Just ((y, x), queue')
            | y + 1 >= height || x + 1 >= width -> loop queue'
            | otherwise -> case scanRight x y of
                Nothing -> loop queue'
                Just (x2, y2) -> do
                    let tc = TC y x y2 x2
                    fmap (tc :) $ loop $ queue' `Set.union` Set.fromList
                        [(y, x2), (y2, x), (y2, x2)]

    -- scan right looking for +, then try scan down
    --
    -- do we need to record + saw on the way left and down?
    scanRight :: Int -> Int -> Maybe (Int, Int)
    scanRight x y = go (x + 1) where
        bs = rs !! y
        go x' | x' >= width          = fail "overflow right "
              | T.index bs x' == '+' = scanDown x y x' <|> go (x' + 1)
              | T.index bs x' == '-' = go (x' + 1)
              | otherwise            = fail $ "not a border (right) " ++ show (x,y,x')

    -- scan down looking for +
    scanDown :: Int -> Int -> Int -> Maybe (Int, Int)
    scanDown x y x2 = go (y + 1) where
        go y' | y' >= height                 = fail "overflow down"
              | T.index (rs !! y') x2 == '+' = scanLeft x y x2 y' <|> go (y' + 1)
              | T.index (rs !! y') x2 == '|' = go (y' + 1)
              | otherwise                    = fail $ "not a border (down) " ++ show (x,y,x2,y')

    -- check that at y2 x..x2 characters are '+' or '-'
    scanLeft :: Int -> Int -> Int -> Int -> Maybe (Int, Int)
    scanLeft x y x2 y2
        | all (\x' -> T.index bs x' `elem` ['+', '-']) [x..x2] = scanUp x y x2 y2
        | otherwise                                            = fail $ "not a border (left) " ++ show (x,y,x2,y2)
      where
        bs = rs !! y2

    -- check that at y2 x..x2 characters are '+' or '-'
    scanUp :: Int -> Int -> Int -> Int -> Maybe (Int, Int)
    scanUp x y x2 y2
        | all (\y' -> T.index (rs !! y') x `elem` ['+', '|']) [y..y2] = return (x2, y2)
        | otherwise                                                   = fail $ "not a border (up) " ++ show (x,y,x2,y2)

-- | table cell: top left bottom right
data TC = TC !Int !Int !Int !Int
  deriving Show

tcXS :: TC -> [Int]
tcXS (TC _ x _ x2) = [x, x2]

tcYS :: TC -> [Int]
tcYS (TC y _ y2 _) = [y, y2]

-- | Fourth step. Given the locations of cells, forms 'Table' structure.
tableStepFour :: [Text] -> Maybe Int -> [TC] -> Parser (Table (DocH mod Identifier))
tableStepFour rs hdrIndex cells =  case hdrIndex of
    Nothing -> return $ Table [] rowsDoc
    Just i  -> case elemIndex i yTabStops of
        Nothing -> return $ Table [] rowsDoc
        Just i' -> return $ uncurry Table $ splitAt i' rowsDoc
  where
    xTabStops = sortNub $ concatMap tcXS cells
    yTabStops = sortNub $ concatMap tcYS cells

    sortNub :: Ord a => [a] -> [a]
    sortNub = Set.toList . Set.fromList

    init' :: [a] -> [a]
    init' []       = []
    init' [_]      = []
    init' (x : xs) = x : init' xs

    rowsDoc = (fmap . fmap) parseParagraph rows

    rows = map makeRow (init' yTabStops)
      where
        makeRow y = TableRow $ mapMaybe (makeCell y) cells
        makeCell y (TC y' x y2 x2)
            | y /= y' = Nothing
            | otherwise = Just $ TableCell xts yts (extract (x + 1) (y + 1) (x2 - 1) (y2 - 1))
          where
            xts = length $ P.takeWhile (< x2) $ dropWhile (< x) xTabStops
            yts = length $ P.takeWhile (< y2) $ dropWhile (< y) yTabStops

    -- extract cell contents given boundaries
    extract :: Int -> Int -> Int -> Int -> Text
    extract x y x2 y2 = T.intercalate "\n"
        [ T.stripEnd $ T.stripStart $ T.take (x2 - x + 1) $ T.drop x $ rs !! y'
        | y' <- [y .. y2]
        ]

-- | Parse \@since annotations.
since :: Parser (DocH mod a)
since = ("@since " *> version <* skipHorizontalSpace <* endOfLine) >>= setSince >> return DocEmpty
  where
    version = decimal `Parsec.sepBy1` "."

-- | Headers inside the comment denoted with @=@ signs, up to 6 levels
-- deep.
--
-- >>> snd <$> parseOnly header "= Hello"
-- Right (DocHeader (Header {headerLevel = 1, headerTitle = DocString "Hello"}))
-- >>> snd <$> parseOnly header "== World"
-- Right (DocHeader (Header {headerLevel = 2, headerTitle = DocString "World"}))
header :: Parser (DocH mod Identifier)
header = do
  let psers = map (string . flip T.replicate "=") [6, 5 .. 1]
      pser = Parsec.choice psers
  depth <- T.length <$> pser
  line <- parseText <$> (skipHorizontalSpace *> nonEmptyLine)
  rest <- try paragraph <|> return DocEmpty
  return $ DocHeader (Header depth line) `docAppend` rest

textParagraph :: Parser (DocH mod Identifier)
textParagraph = parseText . T.intercalate "\n" <$> some nonEmptyLine

textParagraphThatStartsWithMarkdownLink :: Parser (DocH mod Identifier)
textParagraphThatStartsWithMarkdownLink = docParagraph <$> (docAppend <$> markdownLink <*> optionalTextParagraph)
  where
    optionalTextParagraph :: Parser (DocH mod Identifier)
    optionalTextParagraph = choice' [ docAppend <$> whitespace <*> textParagraph
                                    , pure DocEmpty ]

    whitespace :: Parser (DocH mod a)
    whitespace = DocString <$> (f <$> takeHorizontalSpace <*> optional "\n")
      where
        f :: Text -> Maybe Text -> String
        f xs (fromMaybe "" -> x)
          | T.null (xs <> x) = ""
          | otherwise = " "

-- | Parses unordered (bullet) lists.
unorderedList :: Text -> Parser (DocH mod Identifier)
unorderedList indent = DocUnorderedList <$> p
  where
    p = ("*" <|> "-") *> innerList indent p

-- | Parses ordered lists (numbered or dashed).
orderedList :: Text -> Parser (DocH mod Identifier)
orderedList indent = DocOrderedList <$> p
  where
    p = (paren <|> dot) *> innerList indent p
    dot = (decimal :: Parser Int) <* "."
    paren = "(" *> decimal <* ")"

-- | Generic function collecting any further lines belonging to the
-- list entry and recursively collecting any further lists in the
-- same paragraph. Usually used as
--
-- > someListFunction = listBeginning *> innerList someListFunction
innerList :: Text -> Parser [DocH mod Identifier]
          -> Parser [DocH mod Identifier]
innerList indent item = do
  c <- takeLine
  (cs, items) <- more indent item
  let contents = docParagraph . parseText . dropNLs . T.unlines $ c : cs
  return $ case items of
    Left p -> [contents `docAppend` p]
    Right i -> contents : i

-- | Parses definition lists.
definitionList :: Text -> Parser (DocH mod Identifier)
definitionList indent = DocDefList <$> p
  where
    p = do
      label <- "[" *> (parseParagraph <$> takeWhile1_ (`notElem` ("]\n" :: String))) <* ("]" <* optional ":")
      c <- takeLine
      (cs, items) <- more indent p
      let contents = parseText . dropNLs . T.unlines $ c : cs
      return $ case items of
        Left x -> [(label, contents `docAppend` x)]
        Right i -> (label, contents) : i

-- | Drops all trailing newlines.
dropNLs :: Text -> Text
dropNLs = T.dropWhileEnd (== '\n')

-- | Main worker for 'innerList' and 'definitionList'.
-- We need the 'Either' here to be able to tell in the respective functions
-- whether we're dealing with the next list or a nested paragraph.
more :: Monoid a => Text -> Parser a
     -> Parser ([Text], Either (DocH mod Identifier) a)
more indent item = choice' [ innerParagraphs indent
                           , moreListItems indent item
                           , moreContent indent item
                           , pure ([], Right mempty)
                           ]

-- | Used by 'innerList' and 'definitionList' to parse any nested paragraphs.
innerParagraphs :: Text
                -> Parser ([Text], Either (DocH mod Identifier) a)
innerParagraphs indent = (,) [] . Left <$> ("\n" *> indentedParagraphs indent)

-- | Attempts to fetch the next list if possibly. Used by 'innerList' and
-- 'definitionList' to recursively grab lists that aren't separated by a whole
-- paragraph.
moreListItems :: Text -> Parser a
              -> Parser ([Text], Either (DocH mod Identifier) a)
moreListItems indent item = (,) [] . Right <$> indentedItem
  where
    indentedItem = string indent *> Parsec.spaces *> item

-- | Helper for 'innerList' and 'definitionList' which simply takes
-- a line of text and attempts to parse more list content with 'more'.
moreContent :: Monoid a => Text -> Parser a
            -> Parser ([Text], Either (DocH mod Identifier) a)
moreContent indent item = first . (:) <$> nonEmptyLine <*> more indent item

-- | Parses an indented paragraph.
-- The indentation is 4 spaces.
indentedParagraphs :: Text -> Parser (DocH mod Identifier)
indentedParagraphs indent =
    (T.unpack . T.concat <$> dropFrontOfPara indent') >>= parseParagraphs
  where
    indent' = string $ indent <> "    "

-- | Grab as many fully indented paragraphs as we can.
dropFrontOfPara :: Parser Text -> Parser [Text]
dropFrontOfPara sp = do
  currentParagraph <- some (try (sp *> takeNonEmptyLine))
  followingParagraphs <-
    choice' [ skipHorizontalSpace *> nextPar -- we have more paragraphs to take
            , skipHorizontalSpace *> nlList -- end of the ride, remember the newline
            , Parsec.eof *> return []       -- nothing more to take at all
            ]
  return (currentParagraph ++ followingParagraphs)
  where
    nextPar = (++) <$> nlList <*> dropFrontOfPara sp
    nlList = "\n" *> return ["\n"]

nonSpace :: Text -> Parser Text
nonSpace xs
  | T.all isSpace xs = fail "empty line"
  | otherwise = return xs

-- | Takes a non-empty, not fully whitespace line.
--
--  Doesn't discard the trailing newline.
takeNonEmptyLine :: Parser Text
takeNonEmptyLine = do
    l <- takeWhile1 (/= '\n') >>= nonSpace
    _ <- "\n"
    pure (l <> "\n")

-- | Takes indentation of first non-empty line.
--
-- More precisely: skips all whitespace-only lines and returns indentation
-- (horizontal space, might be empty) of that non-empty line.
takeIndent :: Parser Text
takeIndent = do
  indent <- takeHorizontalSpace
  choice' [ "\n" *> takeIndent
          , return indent
          ]

-- | Blocks of text of the form:
--
-- >> foo
-- >> bar
-- >> baz
--
birdtracks :: Parser (DocH mod a)
birdtracks = DocCodeBlock . DocString . T.unpack . T.intercalate "\n" . stripSpace <$> some line
  where
    line = try (skipHorizontalSpace *> ">" *> takeLine)

stripSpace :: [Text] -> [Text]
stripSpace = fromMaybe <*> mapM strip'
  where
    strip' t = case T.uncons t of
                 Nothing -> Just ""
                 Just (' ',t') -> Just t'
                 _ -> Nothing

-- | Parses examples. Examples are a paragraph level entitity (separated by an empty line).
-- Consecutive examples are accepted.
examples :: Parser (DocH mod a)
examples = DocExamples <$> (many (try (skipHorizontalSpace *> "\n")) *> go)
  where
    go :: Parser [Example]
    go = do
      prefix <- takeHorizontalSpace <* ">>>"
      expr <- takeLine
      (rs, es) <- resultAndMoreExamples
      return (makeExample prefix expr rs : es)
      where
        resultAndMoreExamples :: Parser ([Text], [Example])
        resultAndMoreExamples = choice' [ moreExamples, result, pure ([], []) ]
          where
            moreExamples :: Parser ([Text], [Example])
            moreExamples = (,) [] <$> go

            result :: Parser ([Text], [Example])
            result = first . (:) <$> nonEmptyLine <*> resultAndMoreExamples

    makeExample :: Text -> Text -> [Text] -> Example
    makeExample prefix expression res =
      Example (T.unpack (T.strip expression)) result
      where
        result = map (T.unpack . substituteBlankLine . tryStripPrefix) res

        tryStripPrefix xs = fromMaybe xs (T.stripPrefix prefix xs)

        substituteBlankLine "<BLANKLINE>" = ""
        substituteBlankLine xs = xs

nonEmptyLine :: Parser Text
nonEmptyLine = try (mfilter (T.any (not . isSpace)) takeLine)

takeLine :: Parser Text
takeLine = try (takeWhile (/= '\n') <* endOfLine)

endOfLine :: Parser ()
endOfLine = void "\n" <|> Parsec.eof

-- | Property parser.
--
-- >>> snd <$> parseOnly property "prop> hello world"
-- Right (DocProperty "hello world")
property :: Parser (DocH mod a)
property = DocProperty . T.unpack . T.strip <$> ("prop>" *> takeWhile1 (/= '\n'))

-- |
-- Paragraph level codeblock. Anything between the two delimiting \@ is parsed
-- for markup.
codeblock :: Parser (DocH mod Identifier)
codeblock =
  DocCodeBlock . parseParagraph . dropSpaces
  <$> ("@" *> skipHorizontalSpace *> "\n" *> block' <* "@")
  where
    dropSpaces xs =
      case splitByNl xs of
        [] -> xs
        ys -> case T.uncons (last ys) of
          Just (' ',_) -> case mapM dropSpace ys of
                            Nothing -> xs
                            Just zs -> T.intercalate "\n" zs
          _ -> xs

    -- This is necessary because ‘lines’ swallows up a trailing newline
    -- and we lose information about whether the last line belongs to @ or to
    -- text which we need to decide whether we actually want to be dropping
    -- anything at all.
    splitByNl = unfoldr (\x -> case T.uncons x of
                                 Just ('\n',x') -> Just (T.span (/= '\n') x')
                                 _ -> Nothing)
                . ("\n" <>)

    dropSpace t = case T.uncons t of
                    Nothing -> Just ""
                    Just (' ',t') -> Just t'
                    _ -> Nothing

    block' = scan p False
      where
        p isNewline c
          | isNewline && c == '@' = Nothing
          | isNewline && isSpace c = Just isNewline
          | otherwise = Just $ c == '\n'

hyperlink :: Parser (DocH mod Identifier)
hyperlink = choice' [ angleBracketLink, markdownLink, autoUrl ]

angleBracketLink :: Parser (DocH mod a)
angleBracketLink =
    DocHyperlink . makeLabeled (\s -> Hyperlink s . fmap DocString)
    <$> disallowNewline ("<" *> takeUntil ">")

markdownLink :: Parser (DocH mod Identifier)
markdownLink = DocHyperlink <$> linkParser

linkParser :: Parser (Hyperlink (DocH mod Identifier))
linkParser = flip Hyperlink <$> label <*> (whitespace *> url)
  where
    label :: Parser (Maybe (DocH mod Identifier))
    label = Just . parseParagraph . T.strip <$> ("[" *> takeUntil "]")

    whitespace :: Parser ()
    whitespace = skipHorizontalSpace <* optional ("\n" *> skipHorizontalSpace)

    url :: Parser String
    url = rejectWhitespace (decode <$> ("(" *> takeUntil ")"))

    rejectWhitespace :: MonadPlus m => m String -> m String
    rejectWhitespace = mfilter (all (not . isSpace))

    decode :: Text -> String
    decode = T.unpack . removeEscapes

-- | Looks for URL-like things to automatically hyperlink even if they
-- weren't marked as links.
autoUrl :: Parser (DocH mod a)
autoUrl = mkLink <$> url
  where
    url = mappend <$> choice' [ "http://", "https://", "ftp://"] <*> takeWhile1 (not . isSpace)

    mkLink :: Text -> DocH mod a
    mkLink s = case T.unsnoc s of
      Just (xs,x) | x `elem` (",.!?" :: String) -> DocHyperlink (mkHyperlink xs) `docAppend` DocString [x]
      _ -> DocHyperlink (mkHyperlink s)

    mkHyperlink :: Text -> Hyperlink (DocH mod a)
    mkHyperlink lnk = Hyperlink (T.unpack lnk) Nothing


-- | Parses identifiers with help of 'parseValid'.
identifier :: Parser (DocH mod Identifier)
identifier = DocIdentifier <$> parseValid