packages feed

mdoc-0.2.0.0: src/Mdoc/Syntax/MacroArg.hs

-- |
--
-- Module      : Mdoc.Syntax.MacroArg
-- Copyright   : (c) 2026 Patrick Brisbin
-- License     : AGPL-3
-- Maintainer  : pbrisbin@gmail.com
-- Stability   : experimental
-- Portability : POSIX
module Mdoc.Syntax.MacroArg
  ( MacroArg (..)

    -- * Lenses
  , _Mdocdate

    -- * Pretty
  , prettyMacroArg
  ) where

import Mdoc.Prelude

import Data.Text qualified as T
import Data.Time (Day, defaultTimeLocale, formatTime)
import Mdoc.Optics
import Mdoc.Pretty
import Mdoc.Syntax.MacroName

data MacroArg
  = Mdocdate (Maybe Day)
  | Callable MacroName
  | Quoted Text
  | QuotedComma Text
  | Bare Text
  deriving stock (Eq, Show)
  deriving (ToJSON) via (Rendered MacroArg)

instance IsString MacroArg where
  fromString = Bare . pack

_Mdocdate :: Prism' MacroArg (Maybe Day)
_Mdocdate = prism Mdocdate $ \case
  Mdocdate day -> Right day
  other -> Left other

prettyMacroArg :: MacroArg -> Doc Ann
prettyMacroArg = \case
  Mdocdate md ->
    mconcat
      [ annotate AnnSymbol "$"
      , annotate AnnSpecial "Mdocdate"
      , maybe
          ""
          ( (annotate AnnSymbol ":" <+>)
              . annotate AnnArgument
              . pretty
              . formatTime defaultTimeLocale "%B %e %Y "
          )
          md
      , annotate AnnSymbol "$"
      ]
  Callable name -> annotate AnnKeyword (prettyMacroName name)
  Quoted x ->
    mconcat
      [ annotate AnnQuote $ pretty '"'
      , annotate AnnQuoted $ pretty $ T.replace "\"" "\\\"" x
      , annotate AnnQuote $ pretty '"'
      ]
  QuotedComma x ->
    mconcat
      [ annotate AnnQuote $ pretty '"'
      , annotate AnnQuoted $ pretty $ T.replace "\"" "\\\"" x
      , annotate AnnQuote $ pretty '"'
      , pretty ("," :: Text)
      ]
  Bare x -> pretty x

instance Pretty MacroArg where
  pretty = unAnnotate . prettyMacroArg