From 2c66a42ab81d40e771eda0f054c62f22ad45f3d0 Mon Sep 17 00:00:00 2001
From: Albert Krewinkel <albert@zeitkraut.de>
Date: Sat, 23 Dec 2017 13:35:27 +0100
Subject: Lua modules: add function pandoc.utils.normalize_date

The function parses a date and converts it (if possible) to "YYYY-MM-DD"
format.
---
 src/Text/Pandoc/Lua/Module/Utils.hs | 12 ++++++++++--
 src/Text/Pandoc/Lua/Util.hs         |  4 ++++
 2 files changed, 14 insertions(+), 2 deletions(-)

(limited to 'src')

diff --git a/src/Text/Pandoc/Lua/Module/Utils.hs b/src/Text/Pandoc/Lua/Module/Utils.hs
index 3c830a4bd..458716a03 100644
--- a/src/Text/Pandoc/Lua/Module/Utils.hs
+++ b/src/Text/Pandoc/Lua/Module/Utils.hs
@@ -33,7 +33,7 @@ import Control.Applicative ((<|>))
 import Foreign.Lua (FromLuaStack, Lua, LuaInteger, NumResults)
 import Text.Pandoc.Definition (Pandoc, Meta, Block, Inline)
 import Text.Pandoc.Lua.StackInstances ()
-import Text.Pandoc.Lua.Util (addFunction)
+import Text.Pandoc.Lua.Util (OrNil (OrNil), addFunction)
 
 import qualified Data.Digest.Pure.SHA as SHA
 import qualified Data.ByteString.Lazy as BSL
@@ -44,9 +44,10 @@ import qualified Text.Pandoc.Shared as Shared
 pushModule :: Lua NumResults
 pushModule = do
   Lua.newtable
-  addFunction "to_roman_numeral" toRomanNumeral
+  addFunction "normalize_date" normalizeDate
   addFunction "sha1" sha1
   addFunction "stringify" stringify
+  addFunction "to_roman_numeral" toRomanNumeral
   return 1
 
 -- | Calculate the hash of the given contents.
@@ -85,3 +86,10 @@ instance FromLuaStack AstElement where
 -- | Convert a number < 4000 to uppercase roman numeral.
 toRomanNumeral :: LuaInteger -> Lua String
 toRomanNumeral = return . Shared.toRomanNumeral . fromIntegral
+
+-- | Parse a date and convert (if possible) to "YYYY-MM-DD" format. We
+-- limit years to the range 1601-9999 (ISO 8601 accepts greater than
+-- or equal to 1583, but MS Word only accepts dates starting 1601).
+-- Returns nil instead of a string if the conversion failed.
+normalizeDate :: String -> Lua (OrNil String)
+normalizeDate = return . OrNil . Shared.normalizeDate
diff --git a/src/Text/Pandoc/Lua/Util.hs b/src/Text/Pandoc/Lua/Util.hs
index 28d09d339..1f7664fc0 100644
--- a/src/Text/Pandoc/Lua/Util.hs
+++ b/src/Text/Pandoc/Lua/Util.hs
@@ -125,6 +125,10 @@ instance FromLuaStack a => FromLuaStack (OrNil a) where
       then return (OrNil Nothing)
       else OrNil . Just <$> Lua.peek idx
 
+instance ToLuaStack a => ToLuaStack (OrNil a) where
+  push (OrNil Nothing)  = Lua.pushnil
+  push (OrNil (Just x)) = Lua.push x
+
 -- | Helper class for pushing a single value to the stack via a lua function.
 -- See @pushViaCall@.
 class PushViaCall a where
-- 
cgit v1.2.3