-
Notifications
You must be signed in to change notification settings - Fork 13
/
Types.hs
1740 lines (1587 loc) · 56.4 KB
/
Types.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 DeriveTraversable #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE GeneralizedNewtypeDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE OverloadedStrings #-}
module Citeproc.Types
( CiteprocOptions(..)
, defaultCiteprocOptions
, CiteprocOutput(..)
, addFormatting
, CiteprocError(..)
, prettyCiteprocError
, ItemId(..)
, CitationItem(..)
, CitationItemType(..)
, Citation(..)
, ElementType(..)
, Element(..)
, NumberForm(..)
, Pluralize(..)
, DateType(..)
, Date(..)
, rawDateEDTF
, DateParts(..)
, ShowDateParts(..)
, DPName(..)
, DPForm(..)
, DP(..)
, VariableForm(..)
, TextType(..)
, NameFormat(..)
, defaultNameFormat
, NameAsSortOrder(..)
, NamesFormat(..)
, NameForm(..)
, Name(..)
, extractParticles
, isByzantineName
, DelimiterPrecedes(..)
, Condition(..)
, Position(..)
, Match(..)
, Formatting(..)
, FontStyle(..)
, FontVariant(..)
, FontWeight(..)
, TextDecoration(..)
, VerticalAlign(..)
, DisplayStyle(..)
, TextCase(..)
, DemoteNonDroppingParticle(..)
, StyleOptions(..)
, SubsequentAuthorSubstitute(..)
, SubsequentAuthorSubstituteRule(..)
, SecondFieldAlign(..)
, PageRangeFormat(..)
, Style(..)
, TermMatch(..)
, TermGender(..)
, TermNumber(..)
, TermForm(..)
, Term(..)
, emptyTerm
, SortDirection(..)
, SortKey(..)
, SortKeyValue(..)
, LayoutOptions(..)
, Collapsing(..)
, Layout(..)
, DisambiguationStrategy(..)
, GivenNameDisambiguationRule(..)
, Lang(..)
, parseLang
, renderLang
, Locale(..)
, DisambiguationData(..)
, NameHints(..)
, Reference(..)
, ReferenceMap(..)
, makeReferenceMap
, lookupReference
, Val(..)
, valToText
, Variable
, toVariable
, fromVariable
, lookupVariable
, Output(..)
, Identifier(..)
, identifierToURL
, fixShortDOI
, Tag(..)
, outputToText
, renderOutput
, grouped
, formatted
, readAsInt
, variableType
, VariableType(..)
, Abbreviations
, lookupAbbreviation
, Result(..)
, Inputs(..)
)
where
import qualified Data.Set as Set
import qualified Data.Map as M
import qualified Data.Text.Read as TR
import qualified Data.Scientific as S
import qualified Data.CaseInsensitive as CI
import Control.Monad (foldM, guard, mzero)
import Control.Applicative ((<|>), optional)
import Data.Char (isLower, isDigit, isLetter, isSpace)
import Data.Text (Text)
import qualified Data.Text as T
import Data.List (elemIndex)
import Data.Maybe
import qualified Data.Vector as V
import Data.Aeson (FromJSON (..), ToJSON (..), ToJSONKey (..),
FromJSONKey (..), FromJSONKeyFunction (..),
withArray, withObject, object, Value(..),
(.:), (.:?), (.!=))
import Data.Aeson.Types (typeMismatch, Parser, toJSONKeyText)
import Data.Coerce
import Data.Generics.Uniplate.Direct
import qualified Data.Attoparsec.Text as P
import Safe (readMay)
import Data.String (IsString)
import Citeproc.Unicode (Lang(..), parseLang, renderLang)
-- import Debug.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
-- | Options affecting the output in ways that go beyond
-- what can be specified in styles.
data CiteprocOptions =
CiteprocOptions
{ linkCitations :: Bool
-- ^ Create hyperlinks from citations to bibliography entries
, linkBibliography :: Bool
-- ^ Enables the following options:
--
-- * Automatically linkify any DOI, PMCID, PMID, or URL
-- appearing in a bibliography entry.
-- * When a bibliography entry has a DOI, PMCID, PMID, or URL available
-- (in order of priority), but the style does not explicitly render at
-- least one of them, add a hyperlink to the title instead.
-- * A bibliography item with a DOI, PMCID, PMID, or URL available
-- (in order of priority) will be wrapped in a hyperlink when the hyperlink
-- has not already been applied to one of its parts (e.g. to the title).
}
deriving (Show, Eq)
defaultCiteprocOptions :: CiteprocOptions
defaultCiteprocOptions =
CiteprocOptions
{ linkCitations = False
, linkBibliography = False
}
data CiteprocError =
CiteprocXMLError Text
| CiteprocParseError Text
| CiteprocLocaleNotFound Text
deriving (Show, Eq)
prettyCiteprocError :: CiteprocError -> Text
prettyCiteprocError (CiteprocXMLError t) =
"CiteprocXMLError: " <> t
prettyCiteprocError (CiteprocParseError t) =
"CiteprocParseError: " <> t
prettyCiteprocError (CiteprocLocaleNotFound t) =
"CiteprocLocaleNotFound: " <> t
-- | CSL styles require certain formatting transformations to
-- be defined. These are defined in the 'CiteprocOutput' class.
-- The library may be used with any structured format that defines
-- these operations. See the 'Citeproc.CslJson' module for an instance
-- that corresponds to the markup allowed in CSL JSON. See
-- the 'Citeproc.Pandoc' module for an instance for Pandoc 'Inlines'.
class (Semigroup a, Monoid a, Show a, Eq a, Ord a) => CiteprocOutput a where
toText :: a -> Text
fromText :: Text -> a
dropTextWhile :: (Char -> Bool) -> a -> a
dropTextWhileEnd :: (Char -> Bool) -> a -> a
addFontVariant :: FontVariant -> a -> a
addFontStyle :: FontStyle -> a -> a
addFontWeight :: FontWeight -> a -> a
addTextDecoration :: TextDecoration -> a -> a
addVerticalAlign :: VerticalAlign -> a -> a
addTextCase :: Maybe Lang -> TextCase -> a -> a
addDisplay :: DisplayStyle -> a -> a
addQuotes :: a -> a
movePunctuationInsideQuotes :: a -> a
inNote :: a -> a
mapText :: (Text -> Text) -> a -> a
addHyperlink :: Text -> a -> a
localizeQuotes :: Locale -> a -> a
addFormatting :: CiteprocOutput a => Formatting -> a -> a
addFormatting f x =
if T.null (toText x) -- TODO inefficient
then mempty
else
maybe id addDisplay (formatDisplay f) .
(if affixesInside then id else addPrefix . addSuffix) .
(if formatQuotes f then addQuotes else id) .
maybe id addVerticalAlign (formatVerticalAlign f) .
maybe id addTextDecoration (formatTextDecoration f) .
maybe id addFontWeight (formatFontWeight f) .
maybe id addFontVariant (formatFontVariant f) .
maybe id (addTextCase (formatLang f)) (formatTextCase f) .
maybe id addFontStyle (formatFontStyle f) .
(if affixesInside then addPrefix . addSuffix else id) .
(if formatStripPeriods f then mapText (T.filter (/='.')) else id)
$ x
where
addPrefix z = case formatPrefix f of
Just s -> mconcat $ fixPunct [fromText s, z]
Nothing -> z
addSuffix z = case formatSuffix f of
Just s -> mconcat $ fixPunct [z, fromText s]
Nothing -> z
affixesInside = formatAffixesInside f
-- | The identifier used to identify a work in a bibliographic
-- database.
newtype ItemId = ItemId { unItemId :: Text }
deriving (Show, Eq, Ord, Semigroup, Monoid, ToJSON, FromJSON)
data CitationItemType =
AuthorOnly -- ^ e.g., Smith
| SuppressAuthor -- ^ e.g., (2000, p. 30)
| NormalCite -- ^ e.g., (Smith 2000, p. 30)
deriving (Show, Eq, Ord)
instance FromJSON CitationItemType where
parseJSON x = parseJSON x >>=
\case
"author-only" -> pure AuthorOnly
"suppress-author" -> pure SuppressAuthor
"normal-cite" -> pure NormalCite
t -> fail $ "Unknown type " ++ t
instance ToJSON CitationItemType where
toJSON AuthorOnly = "author-only"
toJSON SuppressAuthor = "suppress-author"
toJSON NormalCite = "normal-cite"
-- | The part of a citation corresponding to a single work,
-- possibly including a label, locator, prefix and suffix.
data CitationItem a =
CitationItem
{ citationItemId :: ItemId
, citationItemLabel :: Maybe Text
, citationItemLocator :: Maybe Text
, citationItemType :: CitationItemType
, citationItemPrefix :: Maybe a
, citationItemSuffix :: Maybe a
, citationItemData :: Maybe (Reference a)
} deriving (Show, Eq, Ord)
instance (FromJSON a, Eq a) => FromJSON (CitationItem a) where
parseJSON = withObject "CitationItem" $ \v -> CitationItem
<$> (v .: "id" >>= fmap ItemId . asText)
<*> v .:? "label"
<*> optional (v .: "locator" >>= asText)
<*> ( (v .: "type")
<|> (do suppressAuth <- v .:? "suppress-author"
authorOnly <- v .:? "author-only"
return $
case suppressAuth of
Just True -> SuppressAuthor
_ -> case authorOnly of
Just True -> AuthorOnly
_ -> NormalCite) )
<*> v .:? "prefix"
<*> v .:? "suffix"
<*> v .:? "itemData"
instance ToJSON a => ToJSON (CitationItem a) where
toJSON i = object $
[ ( "id", toJSON (citationItemId i) )
, ("type", toJSON $ citationItemType i) ] ++
[ ( "label", toJSON (citationItemLabel i) )
| isJust (citationItemLabel i) ] ++
[ ("locator", toJSON (citationItemLocator i) )
| isJust (citationItemLocator i) ] ++
[ ("prefix", toJSON (citationItemPrefix i))
| isJust (citationItemPrefix i) ] ++
[ ("suffix", toJSON (citationItemSuffix i))
| isJust (citationItemSuffix i) ] ++
[ ("itemData", toJSON (citationItemData i))
| isJust (citationItemData i) ]
-- | A citation (which may include several items, e.g.
-- in @(Smith 2000; Jones 2010, p. 30)@).
data Citation a =
Citation { citationId :: Maybe Text
, citationNoteNumber :: Maybe Int
, citationItems :: [CitationItem a] }
deriving (Show, Eq, Ord)
instance (FromJSON a, Eq a) => FromJSON (Citation a) where
parseJSON v =
withArray "Citation"
(\ary ->
case ary V.!? 0 of
Just v' -> (withObject "Citation" $ \o
-> Citation <$> o .:? "citationID"
<*> ((o .: "properties"
>>= (.: "noteIndex"))
<|> pure Nothing)
<*> o .: "citationItems") v'
<|> Citation Nothing Nothing <$> parseJSON v'
Nothing -> fail "Empty array") v
<|>
withObject "Citation"
(\o -> Citation <$> o .:? "citationID"
<*> o .:? "citationNoteNumber"
<*> o .: "citationItems") v
<|>
(Citation Nothing Nothing <$> parseJSON v)
instance ToJSON a => ToJSON (Citation a) where
toJSON c =
object $
[ ("citationID", toJSON $ citationId c) | isJust (citationId c) ] ++
[ ("citationItems" , toJSON $ citationItems c) ] ++
case citationNoteNumber c of
Nothing -> []
Just n -> [ ("citationNoteNumber", toJSON n) ]
data Match =
MatchAll
| MatchAny
| MatchNone
deriving (Show, Eq)
data Condition =
HasVariable Variable
| HasType Text
| IsUncertainDate Variable
| IsNumeric Variable
| HasLocatorType Variable
| HasPosition Position
| WouldDisambiguate
deriving (Show, Eq)
data Position =
FirstPosition
| IbidWithLocator
| Ibid
| NearNote
| Subsequent
deriving (Show, Eq, Ord)
data DateType =
LocalizedNumeric
| LocalizedText
| NonLocalized
deriving (Show, Eq, Ord)
data ShowDateParts =
YearMonthDay
| YearMonth
| Year
deriving (Show, Eq)
data DPName =
DPYear
| DPMonth
| DPDay
deriving (Show, Eq, Ord)
data DPForm =
DPNumeric
| DPNumericLeadingZeros
| DPOrdinal
| DPLong
| DPShort
deriving (Show, Eq)
data DP =
DP
{ dpName :: DPName
, dpForm :: DPForm
, dpRangeDelimiter :: Text
, dpFormatting :: Formatting
}
deriving (Show, Eq)
data VariableForm =
ShortForm
| LongForm
deriving (Show, Eq)
data TextType =
TextVariable VariableForm Variable
| TextMacro Text
| TextTerm Term
| TextValue Text
deriving (Show, Eq)
data NumberForm =
NumberNumeric
| NumberOrdinal
| NumberLongOrdinal
| NumberRoman
deriving (Show, Eq)
data Pluralize =
ContextualPluralize
| AlwaysPluralize
| NeverPluralize
deriving (Show, Eq)
data NamesFormat =
NamesFormat
{ namesLabel :: Maybe (TermForm, Pluralize, Formatting)
, namesEtAl :: Maybe (Text, Formatting)
, namesName :: Maybe (NameFormat, Formatting)
, namesLabelBeforeName :: Bool
} deriving (Show, Eq)
data DelimiterPrecedes =
PrecedesContextual
| PrecedesAfterInvertedName
| PrecedesAlways
| PrecedesNever
deriving (Show, Eq)
data NameForm =
LongName
| ShortName
| CountName
deriving (Show, Eq)
data NameFormat =
NameFormat
{ nameGivenFormatting :: Maybe Formatting
, nameFamilyFormatting :: Maybe Formatting
, nameAndStyle :: Maybe TermForm
, nameDelimiter :: Text
, nameDelimiterPrecedesEtAl :: DelimiterPrecedes
, nameDelimiterPrecedesLast :: DelimiterPrecedes
, nameEtAlMin :: Maybe Int
, nameEtAlUseFirst :: Maybe Int
, nameEtAlSubsequentUseFirst :: Maybe Int
, nameEtAlSubsequentMin :: Maybe Int
, nameEtAlUseLast :: Bool
, nameForm :: NameForm
, nameInitialize :: Bool
, nameInitializeWith :: Maybe Text
, nameAsSortOrder :: Maybe NameAsSortOrder
, nameSortSeparator :: Text
} deriving (Show, Eq)
defaultNameFormat :: NameFormat
defaultNameFormat =
NameFormat
{ nameGivenFormatting = Nothing
, nameFamilyFormatting = Nothing
, nameAndStyle = Nothing
, nameDelimiter = ", "
, nameDelimiterPrecedesEtAl = PrecedesContextual
, nameDelimiterPrecedesLast = PrecedesContextual
, nameEtAlMin = Nothing
, nameEtAlUseFirst = Nothing
, nameEtAlSubsequentUseFirst = Nothing
, nameEtAlSubsequentMin = Nothing
, nameEtAlUseLast = False
, nameForm = LongName
, nameInitialize = True
, nameInitializeWith = Nothing
, nameAsSortOrder = Nothing
, nameSortSeparator = ", "
}
data NameAsSortOrder =
NameAsSortOrderFirst
| NameAsSortOrderAll
deriving (Show, Eq)
data ElementType a =
EText TextType
| EDate Variable DateType (Maybe ShowDateParts) [DP]
| ENumber Variable NumberForm
| ENames [Variable] NamesFormat [Element a] -- last part is substitutes if any
| ELabel Variable TermForm Pluralize
| EGroup Bool [Element a] -- Bool is true if it's an expanded macro
| EChoose [(Match, [Condition], [Element a])]
-- 'else' can be represented by a final trivial match condition
deriving (Show, Eq)
data Formatting =
Formatting
{ formatLang :: Maybe Lang
, formatFontStyle :: Maybe FontStyle
, formatFontVariant :: Maybe FontVariant
, formatFontWeight :: Maybe FontWeight
, formatTextDecoration :: Maybe TextDecoration
, formatVerticalAlign :: Maybe VerticalAlign
, formatPrefix :: Maybe Text
, formatSuffix :: Maybe Text
, formatDisplay :: Maybe DisplayStyle
, formatTextCase :: Maybe TextCase
, formatDelimiter :: Maybe Text
, formatStripPeriods :: Bool
, formatQuotes :: Bool
, formatAffixesInside :: Bool -- put affixes inside other formatting
} deriving (Show, Eq)
defaultFormatting :: Formatting
defaultFormatting = Formatting Nothing Nothing Nothing Nothing Nothing
Nothing Nothing Nothing Nothing Nothing Nothing False False False
combineFormatting :: Formatting -> Formatting -> Formatting
combineFormatting
(Formatting la1 a1 b1 c1 d1 e1 f1 g1 h1 i1 j1 k1 l1 m1)
(Formatting la2 a2 b2 c2 d2 e2 f2 g2 h2 i2 j2 k2 l2 m2) =
Formatting (la1 <|> la2) (a1 <|> a2) (b1 <|> b2) (c1 <|> c2)
(d1 <|> d2) (e1 <|> e2) (f1 <|> f2)
(g1 <|> g2) (h1 <|> h2) (i1 <|> i2)
(j1 <|> j2) (k1 || k2) (l1 || l2) (m1 || m2)
instance Semigroup Formatting where
(<>) = combineFormatting
instance Monoid Formatting where
mempty = defaultFormatting
mappend = (<>)
data TextCase =
Lowercase
| Uppercase
| CapitalizeFirst
| CapitalizeAll
| SentenceCase
| TitleCase
deriving (Show, Eq)
data DisplayStyle =
DisplayBlock
| DisplayLeftMargin
| DisplayRightInline
| DisplayIndent
deriving (Show, Eq)
data FontStyle =
NormalFont
| ItalicFont
| ObliqueFont
deriving (Show, Eq)
data FontVariant =
NormalVariant
| SmallCapsVariant
deriving (Show, Eq)
data FontWeight =
NormalWeight
| BoldWeight
| LightWeight
deriving (Show, Eq)
data TextDecoration =
NoDecoration
| UnderlineDecoration
deriving (Show, Eq)
data VerticalAlign =
BaselineAlign
| SupAlign
| SubAlign
deriving (Show, Eq)
data Element a = Element (ElementType a) Formatting
deriving (Show, Eq)
data SortDirection =
Ascending
| Descending
deriving (Show, Eq)
data SortKey a =
SortKeyVariable SortDirection Variable
| SortKeyMacro SortDirection [Element a]
deriving (Show, Eq)
data SortKeyValue =
SortKeyValue SortDirection (Maybe [Text])
deriving (Show, Eq)
data Layout a =
Layout
{ layoutOptions :: LayoutOptions
, layoutFormatting :: Formatting
, layoutElements :: [Element a]
, layoutSortKeys :: [SortKey a]
} deriving (Show, Eq)
data LayoutOptions =
LayoutOptions
{ layoutCollapse :: Maybe Collapsing
, layoutYearSuffixDelimiter :: Maybe Text
, layoutAfterCollapseDelimiter :: Maybe Text
} deriving (Show, Eq)
data Collapsing =
CollapseCitationNumber
| CollapseYear
| CollapseYearSuffix
| CollapseYearSuffixRanged
deriving (Show, Eq)
data DisambiguationStrategy =
DisambiguationStrategy
{ disambiguateAddNames :: Bool
, disambiguateAddGivenNames :: Maybe GivenNameDisambiguationRule
, disambiguateAddYearSuffix :: Bool
} deriving (Show, Eq, Ord)
data GivenNameDisambiguationRule =
AllNames
| AllNamesWithInitials
| PrimaryName
| PrimaryNameWithInitials
| ByCite
deriving (Show, Eq, Ord)
data DemoteNonDroppingParticle =
DemoteDisplayAndSort
| DemoteSortOnly
| DemoteNever
deriving (Show, Eq)
data StyleOptions =
StyleOptions
{ styleIsNoteStyle :: Bool
, styleDefaultLocale :: Maybe Lang
, styleDemoteNonDroppingParticle :: DemoteNonDroppingParticle
, styleInitializeWithHyphen :: Bool
, stylePageRangeFormat :: Maybe PageRangeFormat
, stylePageRangeDelimiter :: Maybe Text
, styleDisambiguation :: DisambiguationStrategy
, styleNearNoteDistance :: Maybe Int
, styleCiteGroupDelimiter :: Maybe Text
, styleLineSpacing :: Maybe Int
, styleEntrySpacing :: Maybe Int
, styleHangingIndent :: Bool
, styleSecondFieldAlign :: Maybe SecondFieldAlign
, styleSubsequentAuthorSubstitute :: Maybe SubsequentAuthorSubstitute
, styleUsesYearSuffixVariable :: Bool
} deriving (Show, Eq)
data SubsequentAuthorSubstitute =
SubsequentAuthorSubstitute Text SubsequentAuthorSubstituteRule
deriving (Show, Eq)
data SubsequentAuthorSubstituteRule =
CompleteAll
| CompleteEach
| PartialEach
| PartialFirst
deriving (Show, Eq)
data SecondFieldAlign =
SecondFieldAlignFlush
| SecondFieldAlignMargin
deriving (Show, Eq)
data PageRangeFormat =
PageRangeChicago15
| PageRangeChicago16
| PageRangeExpanded
| PageRangeMinimal
| PageRangeMinimalTwo
deriving (Show, Eq, Ord)
data Style a =
Style
{ styleCslVersion :: (Int,Int,Int)
, styleOptions :: StyleOptions
, styleCitation :: Layout a
, styleBibliography :: Maybe (Layout a)
, styleLocales :: [Locale]
, styleAbbreviations :: Maybe Abbreviations
} deriving (Show, Eq)
-- Note: no macros section, because we
-- expand these after parsing the CSL.
data TermForm =
Long
| Short
| Verb
| VerbShort
| Symbol
deriving (Show, Ord, Eq)
data TermNumber =
Singular
| Plural
deriving (Show, Ord, Eq)
data TermGender =
Masculine
| Feminine
deriving (Show, Ord, Eq)
data TermMatch =
LastDigit
| LastTwoDigits
| WholeNumber
deriving (Show, Ord, Eq)
data Term =
Term
{ termName :: Text
, termForm :: TermForm
, termNumber :: Maybe TermNumber
, termGender :: Maybe TermGender
, termGenderForm :: Maybe TermGender
, termMatch :: Maybe TermMatch
} deriving (Show, Eq)
emptyTerm :: Term
emptyTerm = Term mempty Long Nothing Nothing Nothing Nothing
instance Ord Term where
(<=)(Term name1 form1 num1 gen1 gf1 match1)
(Term name2 form2 num2 gen2 gf2 match2) =
name1 == name2 &&
form1 == form2 &&
(isNothing num1 || isNothing num2 || num1 == num2) &&
(isNothing gen1 || isNothing gen2 || gen1 == gen2) &&
(isNothing gf1 || isNothing gf2 || gf1 == gf2 ) &&
(isNothing match1 || isNothing match2 || match1 == match2)
-- | Defines locale-specific terms, punctuation styles, and date
-- formats.
data Locale =
Locale
{ localeLanguage :: Maybe Lang
, localePunctuationInQuote :: Maybe Bool
, localeLimitDayOrdinalsToDay1 :: Maybe Bool
, localeDate :: M.Map DateType (Element Text)
, localeTerms :: M.Map Text [(Term, Text)]
}
deriving (Show, Eq)
-- in x <> y, x values take precedence
instance Semigroup Locale where
Locale lang1 pq1 ldo1 date1 ts1 <>
Locale lang2 pq2 ldo2 date2 ts2 =
Locale (lang1 <|> lang2)
(pq1 <|> pq2)
(ldo1 <|> ldo2)
(date1 <> date2)
(M.unionWith (<>) ts1 ts2)
instance Monoid Locale where
mempty = Locale Nothing Nothing Nothing mempty mempty
mappend = (<>)
newtype Variable = Variable (CI.CI Text)
deriving (Show, Ord, Eq, IsString)
toVariable :: Text -> Variable
toVariable = Variable . CI.mk
fromVariable :: Variable -> Text
fromVariable (Variable x) = CI.original x
instance Semigroup Variable where
Variable x <> Variable y = Variable (x <> y)
instance Monoid Variable where
mappend = (<>)
mempty = Variable mempty
instance FromJSON Variable where
parseJSON = fmap (Variable . CI.mk) . parseJSON
instance FromJSONKey Variable where
fromJSONKey = FromJSONKeyText toVariable
instance ToJSON Variable where
toJSON (Variable v) = toJSON $ CI.original v
instance ToJSONKey Variable where
toJSONKey = toJSONKeyText fromVariable
-- | Encodes bibliographic data for a single work.
data Reference a =
Reference
{ referenceId :: ItemId
, referenceType :: Text
, referenceDisambiguation :: Maybe DisambiguationData
-- ^ This is added in processing; if you are constructing
-- a Reference, set to Nothing
, referenceVariables :: M.Map Variable (Val a)
} deriving (Show, Ord, Eq, Functor, Foldable, Traversable)
instance ToJSON a => ToJSON (Reference a) where
toJSON r = toJSON $
M.insert "id" (TextVal $ coerce (referenceId r)) $
M.insert "type" (TextVal $ referenceType r) $
referenceVariables r
data DisambiguationData =
DisambiguationData
{ disambYearSuffix :: Maybe Int
, disambNameMap :: M.Map Name NameHints
, disambEtAlNames :: Maybe Int
, disambCondition :: Bool
} deriving (Show, Ord, Eq)
data NameHints =
AddInitials
| AddGivenName
| AddInitialsIfPrimary
| AddGivenNameIfPrimary
deriving (Show, Ord, Eq)
instance (Eq a, FromJSON a) => FromJSON (Reference a) where
parseJSON v = parseJSON v >>= parseReference
lookupVariable :: CiteprocOutput a => Variable -> Reference a -> Maybe (Val a)
lookupVariable "id" r =
case referenceId r of
ItemId "" -> Nothing
ItemId t -> Just (TextVal t)
lookupVariable "type" r =
case referenceType r of
"" -> Nothing
t -> Just (TextVal t)
lookupVariable "page-first" r = -- compute "page-first" if not set
M.lookup "page-first" (referenceVariables r) <|>
case M.lookup "pages" (referenceVariables r) of
Nothing -> Nothing
Just (NumVal n) -> Just (NumVal n)
Just (TextVal t) -> NumVal <$> readMay (T.unpack (takeDigits t))
Just (FancyVal x) -> NumVal <$> readMay (T.unpack
(takeDigits $ toText x))
_ -> Nothing
where
takeDigits = T.takeWhile isDigit
lookupVariable v r = M.lookup v $ referenceVariables r
parseReference :: FromJSON a
=> M.Map Variable Value -> Parser (Reference a)
parseReference rawmap =
foldM go (Reference mempty mempty Nothing mempty) (M.toList rawmap)
where
go (Reference i t d m) (k, v)
| k == "id" = do
id' <- ItemId <$> readString v
return $ Reference id' t d m
| k == "type" = do
type' <- readString v
return $ Reference i type' d m
| k == "journalAbbreviation" || k == "shortTitle" = -- legacy citeproc-js
go (Reference i t d m) ("container-title-short", v)
| k == "note" = do
t' <- parseJSON v
let (kvs, rest) = parseNote t'
in (if T.null rest
then id
else \(Reference i' t'' d' m') ->
Reference i' t'' d' (M.insert "note" (TextVal rest) m'))
<$> foldM go (Reference i t d m) (consolidateNameVariables kvs)
| otherwise = Reference i t d <$>
case variableType k of
StringVariable -> do
v' <- FancyVal <$> parseJSON v <|> TextVal <$> readString v
return $ M.insert k v' m
NumberVariable -> do
v' <- case v of
String{} -> parseJSON v
Number{} -> T.pack . show <$> (parseJSON v :: Parser Int)
_ -> typeMismatch "String or Number" v
return $ M.insert k (TextVal v') m
DateVariable -> do
v' <- parseJSON v
return $ M.insert k (DateVal v') m
NameVariable -> do
v' <- parseJSON v
return $ M.insert k (NamesVal v') m
UnknownVariable -> -- treat as string variable if possible
case v of
String{} -> (\x -> M.insert k x m) <$>
(FancyVal <$> parseJSON v <|> TextVal <$> readString v)
Number{} -> (\x -> M.insert k (TextVal x) m) <$> readString v
_ -> return m -- silently ignore
readString v =
case v of
String{} -> parseJSON v
Number{} -> T.pack . show <$> (parseJSON v :: Parser Int)
_ -> typeMismatch "String or Number" v
-- name variables are cumulative and should be packed into an array
consolidateNameVariables :: [(Variable, Text)] -> [(Variable, Value)]
consolidateNameVariables [] = []
consolidateNameVariables ((k,v):kvs)
= case variableType k of
NameVariable
-> (k, Array
(V.fromList [String t | (k',t) <- (k,v):kvs, k' == k])) :
consolidateNameVariables (filter ((/= k) . fst) kvs)
_ -> (k, String v) : consolidateNameVariables kvs
parseNote :: Text
-> ([(Variable, Text)], Text)
parseNote t =
either (const ([],t)) id $
P.parseOnly ((,) <$> P.many' pNoteField <*> P.takeText) t
where
pNoteField = pBracedField <|> pLineField
pLineField = do
name <- pVarname
_ <- P.char ':'
val <- P.takeWhile (/='\n')
() <$ P.char '\n' <|> P.endOfInput
return (Variable $ CI.mk name, T.strip val)
pBracedField = do
_ <- P.string "{:"
name <- pVarname
_ <- P.char ':'
val <- P.takeWhile (/='}')
_ <- P.char '}'
return (Variable $ CI.mk name, T.strip val)
pVarname = P.takeWhile1 (\c -> isLetter c || c == '-')
data VariableType =
DateVariable
| NameVariable
| NumberVariable
| StringVariable
| UnknownVariable
deriving (Show, Eq)
variableType :: Variable -> VariableType
variableType "accessed" = DateVariable
variableType "available-date" = DateVariable
variableType "container" = DateVariable
variableType "event-date" = DateVariable
variableType "issued" = DateVariable
variableType "original-date" = DateVariable
variableType "submitted" = DateVariable
variableType "author" = NameVariable
variableType "chair" = NameVariable
variableType "collection-editor" = NameVariable
variableType "composer" = NameVariable
variableType "compiler" = NameVariable
variableType "container-author" = NameVariable
variableType "contributor" = NameVariable
variableType "curator" = NameVariable
variableType "director" = NameVariable
variableType "editor" = NameVariable
variableType "editor-translator" = NameVariable
variableType "editorial-director" = NameVariable
variableType "executive-producer" = NameVariable
variableType "guest" = NameVariable
variableType "host" = NameVariable
variableType "illustrator" = NameVariable
variableType "interviewer" = NameVariable
variableType "narrator" = NameVariable
variableType "original-author" = NameVariable
variableType "organizer" = NameVariable
variableType "performer" = NameVariable
variableType "producer" = NameVariable
variableType "recipient" = NameVariable
variableType "reviewed-author" = NameVariable
variableType "script-writer" = NameVariable
variableType "series-creator" = NameVariable
variableType "translator" = NameVariable
variableType "chapter-number" = NumberVariable
variableType "citation-number" = NumberVariable
variableType "collection-number" = NumberVariable
variableType "edition" = NumberVariable
variableType "first-reference-note-number" = NumberVariable
variableType "issue" = NumberVariable
variableType "locator" = NumberVariable
variableType "number" = NumberVariable
variableType "number-of-pages" = NumberVariable
variableType "number-of-volumes" = NumberVariable
variableType "page" = NumberVariable