-
Notifications
You must be signed in to change notification settings - Fork 19
/
Eval.hs
2699 lines (2532 loc) · 107 KB
/
Eval.hs
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
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
{-# LANGUAGE StrictData #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TupleSections #-}
module Citeproc.Eval
( evalStyle )
where
import Citeproc.Types
import Citeproc.Style (mergeLocales)
import qualified Citeproc.Unicode as Unicode
import Control.Monad.Trans.RWS.CPS
import Data.Containers.ListUtils (nubOrdOn, nubOrd)
import Safe (headMay, headDef, lastMay, initSafe, tailSafe, maximumMay)
import Data.Maybe
import Control.Monad (foldM, foldM_, zipWithM, when, unless)
import qualified Data.Map as M
import qualified Data.Set as Set
import Data.Coerce (coerce)
import Data.List (find, intersperse, sortBy, sortOn, groupBy, foldl', transpose,
sort, (\\))
import Data.Text (Text)
import qualified Data.Text as T
import Data.Char (isSpace, isDigit, isUpper, isLower, isLetter,
ord, chr)
import Text.Printf (printf)
import Control.Applicative
import Data.Generics.Uniplate.Operations (universe, transform)
-- import Debug.Trace (trace)
--
-- traceShowIdLabeled :: Show a => String -> a -> a
-- traceShowIdLabeled label x =
-- trace (label ++ ": " ++ show x) x
--
-- import Text.Show.Pretty (ppShow)
-- ppTrace :: Show a => a -> a
-- ppTrace x = trace (ppShow x) x
data Context a =
Context
{ contextLocale :: Locale
, contextCollate :: [SortKeyValue] -> [SortKeyValue] -> Ordering
, contextAbbreviations :: Maybe Abbreviations
, contextStyleOptions :: StyleOptions
, contextLocator :: Maybe Text
, contextLabel :: Maybe Text
, contextPosition :: [Position]
, contextInSubstitute :: Bool
, contextInSortKey :: Bool
, contextInBibliography :: Bool
, contextSubstituteNamesForm :: Maybe NamesFormat
}
-- used internally for group elements, which
-- are skipped if (a) the group calls a variable
-- but (b) all of the variables called are empty.
data VarCount =
VarCount
{ variablesAccessed :: Int
, variablesNonempty :: Int
} deriving (Show)
data EvalState a =
EvalState
{ stateVarCount :: VarCount
, stateLastCitedMap :: M.Map ItemId (Int, Maybe Int, Int,
Bool, Maybe Text, Maybe Text)
-- (citegroup, noteNum, posInGroup,
-- aloneInCitation, label, locator)
, stateNoteMap :: M.Map Int (Set.Set ItemId) -- ids cited in note
, stateRefMap :: ReferenceMap a
, stateReference :: Reference a
, stateUsedYearSuffix :: Bool
, stateUsedIdentifier :: Bool
-- ^ tracks whether an identifier (DOI,PMCID,PMID,URL) has yet been used
, stateUsedTitle :: Bool
-- ^ tracks whether the item title has yet been used
} deriving (Show)
type Eval a = RWS (Context a) (Set.Set Text) (EvalState a)
updateVarCount :: Int -> Int -> Eval a ()
updateVarCount total' nonempty' =
modify $ \st ->
let VarCount{ variablesAccessed = total
, variablesNonempty = nonempty } = stateVarCount st
in st{ stateVarCount =
VarCount { variablesAccessed = total + total',
variablesNonempty = nonempty + nonempty' } }
evalStyle :: CiteprocOutput a
=> Style a -- ^ Parsed CSL style.
-> Maybe Lang -- ^ Override style default locale.
-> [Reference a] -- ^ List of references (bibliographic data).
-> [Citation a] -- ^ List of citations.
-> ([Output a], [(Text, Output a)], [Text])
-- ^ (citations, (id, bibentry) pairs, warnings)
evalStyle style mblang refs' citations =
(citationOs, bibliographyOs, Set.toList warnings)
where
(refs, refmap) = makeReferenceMap refs'
((citationOs, bibliographyOs), warnings) = evalRWS go
Context
{ contextLocale = mergeLocales mblang style
, contextCollate = \xs ys ->
compSortKeyValues (Unicode.comp mblang)
xs ys
, contextAbbreviations = styleAbbreviations style
, contextStyleOptions = styleOptions style
, contextLocator = Nothing
, contextLabel = Nothing
, contextPosition = []
, contextInSubstitute = False
, contextInSortKey = False
, contextInBibliography = False
, contextSubstituteNamesForm = Nothing
}
EvalState
{ stateVarCount = VarCount 0 0
, stateLastCitedMap = mempty
, stateNoteMap = mempty
, stateRefMap = refmap
, stateReference = Reference mempty mempty Nothing mempty
, stateUsedYearSuffix = False
, stateUsedIdentifier = False
, stateUsedTitle = False
}
assignCitationNumbers sortedIds =
modify $ \st ->
st{ stateRefMap = ReferenceMap $ foldl'
(\m (citeId, num) ->
M.adjust (\ref ->
ref{ referenceVariables =
M.insert "citation-number"
(NumVal num) .
M.alter (addIfMissing (citationLabel ref))
"citation-label"
$ referenceVariables ref
}) citeId m)
(unReferenceMap (stateRefMap st))
(zip sortedIds [1..]) }
addIfMissing x Nothing = Just x
addIfMissing _ (Just x) = Just x
go = do
-- list of citationItemIds that are actually cited
let citationOrder = M.fromList $ reverse $ zip
(concatMap (map citationItemId . citationItems) citations)
[(1 :: Int)..]
let citeIds = M.keysSet citationOrder
let sortedCiteIds = sortOn
(fromMaybe maxBound . (`M.lookup` citationOrder))
(map referenceId refs)
let layoutOpts = layoutOptions $ styleCitation style
let mbcgDelim =
case styleCiteGroupDelimiter (styleOptions style) of
Just x -> Just x
Nothing
-- grouping is activated whenever there is
-- collapsing; this is the default
-- cite-group-delimiter
| isJust (layoutCollapse layoutOpts) -> Just ", "
| otherwise -> Nothing
assignCitationNumbers sortedCiteIds
-- sorting of bibliography, insertion of citation-number
collate <- asks contextCollate
(bibCitations, bibSortKeyMap) <-
case styleBibliography style of
Nothing -> return ([], mempty)
Just biblayout -> do
bibSortKeyMap <- M.fromList
<$> mapM
((\citeId ->
(citeId,) <$> evalSortKeys biblayout citeId)
. referenceId)
refs
let sortedIds =
if null (layoutSortKeys biblayout)
then sortedCiteIds
else sortBy
(\x y -> collate
(fromMaybe [] $ M.lookup x bibSortKeyMap)
(fromMaybe [] $ M.lookup y bibSortKeyMap))
(map referenceId refs)
assignCitationNumbers $
case layoutSortKeys biblayout of
(SortKeyVariable Descending "citation-number":_)
-> reverse sortedIds
(SortKeyMacro Descending
(Element (ENumber "citation-number" _) _:_) : _)
-> reverse sortedIds
(SortKeyMacro Descending
(Element (EText (TextVariable _ "citation-number")) _:_): _)
-> reverse sortedIds
_ -> sortedIds
let bibCitations = map (\ident ->
Citation (Just $ unItemId ident) Nothing
[CitationItem ident Nothing Nothing
NormalCite Nothing Nothing]) sortedIds
return (bibCitations, bibSortKeyMap)
-- styling of citations
sortKeyMap <-
foldM (\m citeId -> do
sk <- evalSortKeys (styleCitation style) citeId
return $ M.insert citeId sk m)
M.empty
citeIds
-- We can't just sort all the citations, because
-- this can make a hash out of prefixes and suffixes.
-- See e.g. pandoc-citeproc issue #292.
-- we need to first break into groups so that any
-- suffix ends a group and any prefix begins a group;
-- then sort the groups; then combine again:
let canGroup i1 i2
= isNothing (citationItemSuffix i1) &&
isNothing (citationItemPrefix i2)
let sortCitationItems citation' =
citation'{ citationItems =
concatMap
(sortBy
(\item1 item2 ->
collate
(fromMaybe [] $ M.lookup
(citationItemId item1) sortKeyMap)
(fromMaybe [] $ M.lookup
(citationItemId item2) sortKeyMap)))
$ groupBy canGroup
$ citationItems citation' }
let citCitations = map sortCitationItems citations
cs <- disambiguateCitations style bibSortKeyMap citCitations
let cs' = case mbcgDelim of
Nothing -> cs
Just citeGroupDelim -> map
(groupAndCollapseCitations citeGroupDelim
(layoutYearSuffixDelimiter layoutOpts)
(layoutAfterCollapseDelimiter layoutOpts)
(layoutCollapse layoutOpts))
cs
let removeIfEqual x y
| x == y = NullOutput
| otherwise = y
let removeNamesIfSuppressAuthor
(Tagged (TagItem SuppressAuthor cid') x)
= let y = getAuthors x
in Tagged (TagItem SuppressAuthor cid')
(transform (removeIfEqual y) x)
removeNamesIfSuppressAuthor x = x
-- we need to do this after disambiguation and collapsing
let handleSuppressAuthors = transform removeNamesIfSuppressAuthor
let isNoteCitation = styleIsNoteStyle (styleOptions style)
-- if we have an author-only citation at the beginning
-- separate it out:
let handleAuthorOnly formattedCit =
case formattedCit of
Formatted f
(x@(Tagged (TagItem AuthorOnly _) _):xs)
| isNoteCitation
-> formatted mempty
(x : [InNote (formatted f xs) | not (null xs)])
| otherwise
-> formatted mempty
(x :
if null xs
then []
else [Literal (fromText " "),
formatted f xs])
Formatted f
(Formatted f'
(x@(Tagged (TagItem AuthorOnly _) _):xs) : ys)
| isNoteCitation
-> formatted mempty
(x :
if null xs && null ys
then []
else [InNote (formatted f
(formatted f' xs : ys))])
| otherwise
-> Formatted mempty
(x :
if null xs && null ys
then []
else [Literal (fromText " "),
formatted f (formatted f' xs : ys)])
_ | isNoteCitation -> InNote formattedCit
| otherwise -> formattedCit
let cs'' = map (handleSuppressAuthors . handleAuthorOnly) cs'
-- styling of bibliography (this needs to go here to take account
-- of year suffixes added in disambiguation)
bs <- case styleBibliography style of
Just biblayout
-> local (\context ->
context{ contextInBibliography = True }) $
mapM (evalLayout biblayout) (zip [1..] bibCitations)
>>= \bs ->
case styleSubsequentAuthorSubstitute
(styleOptions style) of
Nothing -> return bs
Just subs -> subsequentAuthorSubstitutes subs bs
Nothing -> return []
return (cs'', case styleBibliography style of
Nothing -> []
Just _ ->
zip (map (fromMaybe "" . citationId) bibCitations) bs)
subsequentAuthorSubstitutes :: CiteprocOutput a
=> SubsequentAuthorSubstitute
-> [Output a]
-> Eval a [Output a]
subsequentAuthorSubstitutes (SubsequentAuthorSubstitute t rule) =
return . groupCitesByNames
where
groupCitesByNames [] = []
groupCitesByNames (x:xs) =
let xnames = fromMaybe ([],NullOutput) $ getNames x
samenames = replaceMatch rule (fromText t) xnames xs
rest = drop (length samenames) xs
in (x : samenames) ++ groupCitesByNames rest
getNames (Formatted _ (x:_)) =
case [(ns,r) | (Tagged (TagNames _ _ ns) r) <- universe x] of
((ns,r) : _) -> Just (ns,r)
[] -> Nothing
getNames _ = Nothing
replaceMatch :: CiteprocOutput a
=> SubsequentAuthorSubstituteRule
-> a
-> ([Name], Output a)
-> [Output a]
-> [Output a]
replaceMatch _ _ _ [] = []
replaceMatch rule replacement (names, raw) (z:zs) =
case go z of
Nothing -> []
Just z' -> z' : replaceMatch rule replacement (names, raw) zs
where
go (Tagged t@TagItem{} y) =
Tagged t <$> go y
go (Formatted f (y:ys)) =
Formatted f . (: ys) <$> go y
go y@(Tagged (TagNames _ _ ns) r) =
case (if null names then CompleteAll else rule) of
CompleteAll ->
if ns == names && (not (null names) || r == raw)
then Just $ replaceAll y
else Nothing
CompleteEach ->
if ns == names
then Just $ transform replaceEach y
else Nothing
PartialEach ->
case numberOfMatches ns names of
num | num >= 1 -> Just $ transform (replaceFirst num) y
_ -> Nothing
PartialFirst ->
case numberOfMatches ns names of
num | num >= (1 :: Int) -> Just $ transform (replaceFirst 1) y
_ -> Nothing
go _ = Nothing
replaceAll (Tagged (TagNames t' nf ns') x)
= Tagged (TagNames t' nf ns') $
-- removeName will leave label "ed."
-- which we want, but it will also leave the substituted
-- title when there is no name, which we do not want.
-- So, if ns' is null, then we just remove everything.
if null ns'
then Literal replacement
else
case transform removeName x of
Formatted f' xs -> Formatted f' (Literal replacement : xs)
_ -> Literal replacement
replaceAll x = x
removeName (Tagged (TagName _) _) = NullOutput
removeName x = x
replaceEach (Tagged (TagName n) _)
| n `elem` names
= Tagged (TagName n) (Literal replacement)
replaceEach x = x
replaceFirst num x@(Tagged (TagNames _ _ ns') _)
-- a kludge to get this to type-check!
| True = foldr (transform . replaceName) x $ take num ns'
| False = Literal replacement
replaceFirst _num x = x
replaceName name (Tagged (TagName n) _)
| n == name = Tagged (TagName n) (Literal replacement)
replaceName _ x = x
numberOfMatches (a:as) (b:bs)
| a == b = 1 + numberOfMatches as bs
| otherwise = 0
numberOfMatches _ _ = 0
--
-- Disambiguation
--
data DisambData =
DisambData
{ ddItem :: ItemId
, ddNames :: [Name]
, ddDates :: [Date]
, ddRendered :: Text
} deriving (Eq, Ord, Show)
disambiguateCitations :: forall a . CiteprocOutput a
=> Style a
-> M.Map ItemId [SortKeyValue]
-> [Citation a]
-> Eval a [Output a]
disambiguateCitations style bibSortKeyMap citations = do
refs <- unReferenceMap <$> gets stateRefMap
let refIds = M.keys refs
let citeIds = concatMap (map citationItemId . citationItems) citations
let citeIdsSet = Set.fromList citeIds
let ghostItems = [ ident
| ident <- refIds
, not (ident `Set.member` citeIdsSet)]
-- for purposes of disambiguation, we remove prefixes and
-- suffixes and locators, and we convert author-in-text to normal citation.
let removeAffix item = item{ citationItemLabel = Nothing
, citationItemLocator = Nothing
, citationItemPrefix = Nothing
, citationItemSuffix = Nothing }
let cleanCitation (Citation a b (i1:i2:is))
| citationItemType i1 == AuthorOnly
, citationItemType i2 == SuppressAuthor
= Citation a b
(map removeAffix (i2{ citationItemType = NormalCite }:is))
cleanCitation (Citation a b is)
= Citation a b (map removeAffix is)
-- note that citations must go first, and order must be preserved:
-- we use a "basic item" that strips off prefixes, suffixes, locators
let citations' = map cleanCitation citations ++
[Citation Nothing Nothing (map basicItem ghostItems)]
allCites <- renderCitations citations'
mblang <- asks (localeLanguage . contextLocale)
styleOpts <- asks contextStyleOptions
let strategy = styleDisambiguation styleOpts
let allNameGroups = [ns | Tagged (TagNames _ _ ns) _ <-
concatMap universe allCites]
let allNames = nubOrd $ concat allNameGroups
let primaryNames = nubOrd $ concatMap (take 1) allNameGroups
allCites' <-
case disambiguateAddGivenNames strategy of
Nothing -> return allCites
Just ByCite -> return allCites -- do this later
Just rule -> do -- disambiguate names, not just citations
let relevantNames =
case rule of
PrimaryNameWithInitials -> primaryNames
PrimaryName -> primaryNames
_ -> allNames
let familyNames = nubOrd $ mapMaybe nameFamily relevantNames
let grps = map (\name ->
[v | v <- relevantNames
, nameFamily v == Just name])
familyNames
let toHint names name =
if any (initialsMatch mblang name) (filter (/= name) names)
then
case rule of
AllNamesWithInitials -> Nothing
PrimaryNameWithInitials -> Nothing
PrimaryName -> Just AddGivenNameIfPrimary
_ -> Just AddGivenName
else
case rule of
PrimaryNameWithInitials -> Just AddInitialsIfPrimary
PrimaryName -> Just AddInitialsIfPrimary
_ -> Just AddInitials
let namesMap = mconcat $ map
(\names -> if length names > 1
then foldr
(\name ->
case toHint names name of
Just x -> M.insert name x
Nothing -> id)
mempty
names
else mempty) grps
-- use this same names map for every citation
modify $ \st ->
st{ stateRefMap = ReferenceMap $
foldr
(M.adjust (alterReferenceDisambiguation
(\d -> d{ disambNameMap = namesMap })))
(unReferenceMap $ stateRefMap st)
refIds }
-- redo citations
renderCitations citations'
case getAmbiguities allCites' of
[] -> return ()
ambiguities -> analyzeAmbiguities mblang strategy citations' ambiguities
renderCitations citations
where
renderCitations :: [Citation a] -> Eval a [Output a]
renderCitations cs =
withRWST (\ctx st -> (ctx,
st { stateLastCitedMap = mempty
, stateNoteMap = mempty })) $
mapM (evalLayout (styleCitation style)) (zip [1..] cs)
refreshAmbiguities :: [Citation a] -> Eval a [[DisambData]]
refreshAmbiguities = fmap getAmbiguities . renderCitations
analyzeAmbiguities :: Maybe Lang
-> DisambiguationStrategy
-> [Citation a]
-> [[DisambData]]
-> Eval a ()
analyzeAmbiguities mblang strategy cs ambiguities = do
-- add names to et al.
return ambiguities
>>= (\as ->
(if not (null as) && disambiguateAddNames strategy
then do
mapM_ (tryAddNames mblang (disambiguateAddGivenNames strategy)) as
refreshAmbiguities cs
else
return as))
>>= (\as ->
(case disambiguateAddGivenNames strategy of
Just ByCite | not (null as) -> do
mapM_ (tryAddGivenNames mblang) as
refreshAmbiguities cs
_ -> return as))
>>= (\as ->
(if not (null as) && disambiguateAddYearSuffix strategy
then do
addYearSuffixes bibSortKeyMap as
refreshAmbiguities cs
else return as))
>>= mapM_ tryDisambiguateCondition
basicItem :: ItemId -> CitationItem a
basicItem iid = CitationItem
{ citationItemId = iid
, citationItemLabel = Nothing
, citationItemLocator = Nothing
, citationItemType = NormalCite
, citationItemPrefix = Nothing
, citationItemSuffix = Nothing
}
isDisambiguated :: Maybe Lang
-> Maybe GivenNameDisambiguationRule
-> Int -- et al min
-> [DisambData]
-> DisambData
-> Bool
isDisambiguated mblang mbrule etAlMin xs x =
all (\y -> x == y || disambiguatedName y /= disambiguatedName x) xs
where
disambiguatedName = nameParts . take etAlMin . ddNames
nameParts =
case mbrule of
Just AllNames -> id
Just AllNamesWithInitials ->
map (\name -> name{ nameGiven = initialize mblang True False ""
<$> nameGiven name })
Just PrimaryName ->
\case
[] -> []
(z:zs) -> z : map (\name -> name{ nameGiven = Nothing }) zs
Just PrimaryNameWithInitials ->
\case
[] -> []
(z:zs) -> z{ nameGiven =
initialize mblang True False "" <$> nameGiven z } :
map (\name -> name{ nameGiven = Nothing }) zs
Just ByCite -> id -- hints will be added later
_ -> map (\name -> name{ nameGiven = Nothing })
tryAddNames :: Maybe Lang
-> Maybe GivenNameDisambiguationRule
-> [DisambData]
-> Eval a ()
tryAddNames mblang mbrule bs =
(case mbrule of
Just ByCite -> bs <$ tryAddGivenNames mblang bs
_ -> return bs) >>= go 1
-- if ByCite, we want to make sure that
-- tryAddGivenNames is still applied, as
-- calculation of "add names" assumes this.
where
maxnames = fromMaybe 0 . maximumMay . map (length . ddNames)
go n as
| n > maxnames as = return ()
| otherwise = do
let ds = filter (isDisambiguated mblang mbrule n as) as
if null ds
then go (n + 1) as
else do
modify $ \st ->
st{ stateRefMap = ReferenceMap
$ foldr (setEtAlNames (Just n) . ddItem)
(unReferenceMap $ stateRefMap st) as }
go (n + 1) (as \\ ds)
tryAddGivenNames :: Maybe Lang
-> [DisambData]
-> Eval a ()
tryAddGivenNames mblang as = do
let correspondingNames =
map (zip (map ddItem as)) $ transpose $ map ddNames as
go [] _ = return []
go (as' :: [DisambData]) (ns :: [(ItemId, Name)]) = do
hintedIds <- Set.fromList . catMaybes <$>
mapM (addNameHint mblang (map snd ns)) ns
return $ filter (\x -> ddItem x `Set.notMember` hintedIds) as'
foldM_ go as correspondingNames
addYearSuffixes :: M.Map ItemId [SortKeyValue]
-> [[DisambData]]
-> Eval a ()
addYearSuffixes bibSortKeyMap' as = do
let allitems = concat as
collate <- asks contextCollate
let companions a =
sortBy
(\item1 item2 ->
collate
(fromMaybe [] $ M.lookup (ddItem item1) bibSortKeyMap')
(fromMaybe [] $ M.lookup (ddItem item2) bibSortKeyMap'))
(concat [ x | x <- as, a `elem` x ])
let groups = Set.map companions $ Set.fromList allitems
let addYearSuffix item suff =
modify $ \st ->
st{ stateRefMap = ReferenceMap
$ setYearSuffix suff item
$ unReferenceMap
$ stateRefMap st }
mapM_ (\xs -> zipWithM addYearSuffix (map ddItem xs) [1..]) groups
tryDisambiguateCondition :: [DisambData] -> Eval a ()
tryDisambiguateCondition as =
case as of
[] -> return ()
xs -> modify $ \st ->
st{ stateRefMap = ReferenceMap
$ foldr (setDisambCondition True . ddItem)
(unReferenceMap (stateRefMap st))
xs }
alterReferenceDisambiguation :: (DisambiguationData -> DisambiguationData)
-> Reference a
-> Reference a
alterReferenceDisambiguation f r =
r{ referenceDisambiguation = f <$>
case referenceDisambiguation r of
Nothing -> Just
DisambiguationData
{ disambYearSuffix = Nothing
, disambNameMap = mempty
, disambEtAlNames = Nothing
, disambCondition = False
}
Just x -> Just x }
initialsMatch :: Maybe Lang -> Name -> Name -> Bool
initialsMatch mblang x y =
case (nameGiven x, nameGiven y) of
(Just x', Just y') ->
initialize mblang True False "" x' ==
initialize mblang True False "" y'
_ -> False
addNameHint :: Maybe Lang -> [Name] -> (ItemId, Name) -> Eval a (Maybe ItemId)
addNameHint mblang names (item, name) = do
let familyMatches = [n | n <- names
, n /= name
, nameFamily n == nameFamily name]
case familyMatches of
[] -> return Nothing
_ -> do
let hint = if any (initialsMatch mblang name) familyMatches
then AddGivenName
else AddInitials
modify $ \st ->
st{ stateRefMap = ReferenceMap
$ setNameHint hint name item
$ unReferenceMap (stateRefMap st) }
return $ Just item
setNameHint :: NameHints -> Name -> ItemId
-> M.Map ItemId (Reference a) -> M.Map ItemId (Reference a)
setNameHint hint name = M.adjust
(alterReferenceDisambiguation
(\d -> d{ disambNameMap =
M.insert name hint
(disambNameMap d) }))
setEtAlNames :: Maybe Int -> ItemId
-> M.Map ItemId (Reference a) -> M.Map ItemId (Reference a)
setEtAlNames x = M.adjust
(alterReferenceDisambiguation
(\d -> d{ disambEtAlNames = x }))
setYearSuffix :: Int -> ItemId
-> M.Map ItemId (Reference a) -> M.Map ItemId (Reference a)
setYearSuffix x = M.adjust
(alterReferenceDisambiguation
(\d -> d{ disambYearSuffix = Just x }))
setDisambCondition :: Bool -> ItemId
-> M.Map ItemId (Reference a) -> M.Map ItemId (Reference a)
setDisambCondition x = M.adjust
(alterReferenceDisambiguation
(\d -> d{ disambCondition = x }))
getAmbiguities :: CiteprocOutput a => [Output a] -> [[DisambData]]
getAmbiguities =
mapMaybe
(\zs ->
case zs of
[] -> Nothing
[_] -> Nothing
(z:_) ->
case ddRendered z of
"" -> Nothing
_ -> case nubOrdOn ddItem zs of
ys@(_:_:_) -> Just ys -- > 1 ambiguous entry
_ -> Nothing)
. groupBy (\x y -> ddRendered x == ddRendered y)
. sortOn ddRendered
. map toDisambData
. extractTagItems
extractTagItems :: [Output a] -> [(ItemId, Output a)]
extractTagItems xs =
[(iid, x) | Tagged (TagItem NormalCite iid) x <- concatMap universe xs
, not (hasIbid x)]
where -- we don't want two "ibid" entries to be treated as ambiguous.
hasIbid x = not $ null [ trm | Tagged (TagTerm trm) _ <- universe x
, termName trm == "ibid" ]
toDisambData :: CiteprocOutput a => (ItemId, Output a) -> DisambData
toDisambData (iid, x) =
let xs = universe x
ns' = getNames xs
ds' = getDates xs
t = outputToText x
in DisambData { ddItem = iid
, ddNames = ns'
, ddDates = ds'
, ddRendered = t }
where
getNames :: [Output a] -> [Name]
getNames (Tagged (TagNames _ _ ns) _ : xs)
= ns ++ getNames xs
getNames (_ : xs) = getNames xs
getNames [] = []
getDates :: [Output a] -> [Date]
getDates (Tagged (TagDate d) _ : xs)
= d : getDates xs
getDates (_ : xs) = getDates xs
getDates [] = []
--
-- Grouping and collapsing
--
groupAndCollapseCitations :: forall a . CiteprocOutput a
=> Text
-> Maybe Text
-> Maybe Text
-> Maybe Collapsing
-> Output a
-> Output a
groupAndCollapseCitations citeGroupDelim yearSuffixDelim afterCollapseDelim
collapsing (Formatted f xs) =
case collapsing of
Just CollapseCitationNumber ->
Formatted f{ formatDelimiter = Nothing } $
foldr collapseRange []
(groupSuccessive isAdjacentCitationNumber xs)
Just collapseType ->
Formatted f{ formatDelimiter = Nothing } $
foldr (collapseGroup collapseType) [] (groupWith sameNames xs)
Nothing ->
Formatted f $
map (Formatted mempty{ formatDelimiter = Just citeGroupDelim })
(groupWith sameNames xs)
where
-- Note that we cannot assume we've sorted by name,
-- so we can't just use Data.ListgroupBy. We also
-- take care not to move anything past a prefix or suffix.
groupWith :: (Output a -> Output a -> Bool)
-> [Output a]
-> [[Output a]]
groupWith _ [] = []
groupWith isMatched (z:zs)
| hasSuffix z = [z] : groupWith isMatched zs
| otherwise = -- we allow a prefix on first item in collapsed group
case span hasNoPrefixOrSuffix zs of
([],ys) -> [z] : groupWith isMatched ys
(ws,ys) ->
(z : filter (isMatched z) ws) :
groupWith isMatched (filter (not . isMatched z) ws ++ ys)
hasNoPrefixOrSuffix :: Output a -> Bool
hasNoPrefixOrSuffix x = not (hasPrefix x) && not (hasSuffix x)
hasPrefix :: Output a -> Bool
hasPrefix x = not $ null [y | y@(Tagged TagPrefix _) <- universe x]
hasSuffix :: Output a -> Bool
hasSuffix x = not $ null [y | y@(Tagged TagSuffix _) <- universe x]
collapseRange :: [Output a] -> [Output a] -> [Output a]
collapseRange ys zs
| length ys >= 3
, Just yhead <- headMay ys
, Just ylast <- lastMay ys
= Formatted mempty{ formatDelimiter = Just $ T.singleton enDash }
[yhead, ylast] :
if null zs
then []
else maybe NullOutput literal afterCollapseDelim : zs
collapseRange ys zs =
Formatted mempty{ formatDelimiter = formatDelimiter f } ys :
if null zs
then []
else maybe NullOutput literal (formatDelimiter f) : zs
collapseGroup :: Collapsing -> [Output a] -> [Output a] -> [Output a]
collapseGroup _ [] zs = zs
collapseGroup collapseType (y:ys) zs =
let ys' = y : map (transform removeNames) ys
ws = collapseYearSuffix collapseType ys'
noCollapse = ws == y:ys
noYearSuffixCollapse = ws == ys'
hasLocator u = not $ null [x | x@(Tagged TagLocator _) <- universe u]
anyHasLocator = any hasLocator ws
-- https://github.com/citation-style-language/test-suite/issues/36 :
flippedAfterCollapseDelim = collapseType == CollapseYear
addCGDelim u [] = [u]
addCGDelim u us =
Formatted mempty{ formatSuffix =
if noCollapse || noYearSuffixCollapse &&
not (flippedAfterCollapseDelim &&
anyHasLocator)
then Just citeGroupDelim
else afterCollapseDelim <|>
formatDelimiter f } [u] : us
in Formatted mempty{ formatDelimiter = Nothing
, formatSuffix =
if null zs
then Nothing
else if noCollapse &&
not flippedAfterCollapseDelim
then formatDelimiter f
else afterCollapseDelim <|>
formatDelimiter f }
(foldr addCGDelim [] ws) : zs
collapseRanges = map rangifyGroup . groupSuccessive isSuccessive
isSuccessive x y
= case ([c | Tagged (TagYearSuffix c) _ <- universe x],
[d | Tagged (TagYearSuffix d) _ <- universe y]) of
([c],[d]) -> d == c + 1
_ -> False
rangifyGroup :: [Output a] -> Output a
rangifyGroup zs
| length zs >= 3
, Just zhead <- headMay zs
, Just zlast <- lastMay zs
= Formatted mempty{ formatDelimiter = Just (T.singleton enDash) }
[zhead, zlast]
rangifyGroup [z] = z
rangifyGroup zs = Formatted mempty{ formatDelimiter = yearSuffixDelim
} zs
yearSuffixGroup :: Bool -> [Output a] -> Output a
yearSuffixGroup _ [x] = x
yearSuffixGroup useRanges zs =
Formatted mempty{ formatDelimiter = yearSuffixDelim }
$ if useRanges then collapseRanges zs else zs
collapseYearSuffix :: Collapsing -> [Output a] -> [Output a]
collapseYearSuffix CollapseYearSuffix zs =
reverse $ yearSuffixGroup False cur : items
where
(cur, items) = foldl' (goYearSuffix False) ([], []) zs
collapseYearSuffix CollapseYearSuffixRanged zs =
reverse $ yearSuffixGroup True cur : items
where
(cur, items) = foldl' (goYearSuffix True) ([], []) zs
collapseYearSuffix _ zs = zs
getDates :: Output a -> [Date]
getDates x = [d | Tagged (TagDate d) _ <- universe x]
getYears :: Output a -> [[Maybe Int]]
getYears x = [map (\case
DateParts (y:_) -> Just y
_ -> Nothing) (dateParts d)
| d <- getDates x
, isNothing (dateLiteral d)]
goYearSuffix :: Bool -> ([Output a], [Output a]) -> Output a
-> ([Output a], [Output a])
goYearSuffix useRanges (cur, items) item =
case cur of
[] -> ([item], items)
(z:zs)
| getYears z == getYears item
-> (z:zs ++ [x | x@(Tagged (TagYearSuffix _) _) <- universe item],
items)
| otherwise -> ([item], yearSuffixGroup useRanges (z:zs) : items)
isAdjacentCitationNumber :: Output a -> Output a -> Bool
isAdjacentCitationNumber
(Tagged (TagItem _ _)
(Formatted _f1 [Tagged (TagCitationNumber n1) _xs1]))
(Tagged (TagItem _ _)
(Formatted _f2 [Tagged (TagCitationNumber n2) _xs2]))
= n2 == n1 + 1
isAdjacentCitationNumber
(Tagged (TagItem _ _) (Tagged (TagCitationNumber n1) _xs1))
(Tagged (TagItem _ _) (Tagged (TagCitationNumber n2) _xs2))
= n2 == n1 + 1
isAdjacentCitationNumber _ _ = False
sameNames :: Output a -> Output a -> Bool
sameNames x y =
case (extractTagged x, extractTagged y) of
(Just (Tagged (TagNames t1 _nf1 ns1) ws1),
Just (Tagged (TagNames t2 _nf2 ns2) ws2))
-> t1 == t2 && (if ns1 == ns2
then not (null ns1) || ws1 == ws2
else ws1 == ws2)
-- case where it's just a date with no name or anything;
-- we treat this as same name e.g. (1955a,b)
(Just (Tagged TagDate{} _), Just (Tagged TagDate{} _))
-> True
-- case where title is substituted
_ -> False
extractTagged :: Output a -> Maybe (Output a)
extractTagged x =
let items = [y | y@(Tagged (TagItem ty _) _) <- universe x
, ty /= AuthorOnly]
names = [y | y@(Tagged TagNames{} _) <- concatMap universe items]
dates = [y | y@(Tagged TagDate{} _) <- concatMap universe items]
in if null items
then Nothing
else listToMaybe names <|> listToMaybe dates
groupAndCollapseCitations _ _ _ _ x = x
takeSeq :: Show a => (a -> a -> Bool) -> [a] -> ([a], [a])
takeSeq isAdjacent (x1 : x2 : rest)
| isAdjacent x1 x2 = (x1:ys, zs)
where (ys, zs) = takeSeq isAdjacent (x2:rest)
takeSeq _ (y:ys) = ([y], ys)
takeSeq _ [] = ([], [])
groupSuccessive :: Show a => (a -> a -> Bool) -> [a] -> [[a]]
groupSuccessive isAdjacent zs =
case takeSeq isAdjacent zs of
([],_) -> []
(xs,ys) -> xs : groupSuccessive isAdjacent ys
--
-- Sorting
--
evalSortKeys :: CiteprocOutput a
=> Layout a
-> ItemId
-> Eval a [SortKeyValue]
evalSortKeys layout citeId =
withRWST (\ctx st -> (ctx{ contextInSortKey = True }, st)) $
mapM (evalSortKey citeId) (layoutSortKeys layout)
evalSortKey :: CiteprocOutput a
=> ItemId
-> SortKey a