aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJohn MacFarlane <[email protected]>2025-05-11 18:10:11 -0700
committerJohn MacFarlane <[email protected]>2025-05-11 18:10:11 -0700
commit1239eaa4bea2074d658c3c9f4ad788c7cfef4873 (patch)
tree1afbedc1c171820fd276ea97aff55f07776b7783
parent5901d1ca86f0d6ec624751505940b49811013f64 (diff)
Add new option `--variable-json`.
This allows non-string values (booleans, lists, maps) to be given to template variables on the command line. Closes #10341. Supersedes #10342.
-rw-r--r--MANUAL.txt11
-rw-r--r--src/Text/Pandoc/App/CommandLineOptions.hs18
2 files changed, 29 insertions, 0 deletions
diff --git a/MANUAL.txt b/MANUAL.txt
index 5025aba82..ef71be2aa 100644
--- a/MANUAL.txt
+++ b/MANUAL.txt
@@ -789,6 +789,17 @@ header when requesting a document from a URL:
`-V keyword=Joe -V author=Sue` makes `author` contain a list
of strings: `Joe` and `Sue`.
+`--variable-json=`*KEY*[`=`:*JSON*]
+
+: Set the template variable *KEY* to the value specified by a JSON
+ string (this may be a boolean, a string, a list, or a mapping;
+ a number will be treated as a string). For example,
+ `--variable-json foo=false` will give `foo` the boolean false
+ value, while `--variable-json foo='"false"'` will give it the
+ string value `"false"`. Either `:` or `=` may be used to
+ separate *KEY* from *VAL*. If the variable already has a
+ value, this value will be replaced.
+
`--sandbox[=true|false]`
: Run pandoc in a sandbox, limiting IO operations in readers
diff --git a/src/Text/Pandoc/App/CommandLineOptions.hs b/src/Text/Pandoc/App/CommandLineOptions.hs
index e65bb65ae..a4fec880d 100644
--- a/src/Text/Pandoc/App/CommandLineOptions.hs
+++ b/src/Text/Pandoc/App/CommandLineOptions.hs
@@ -25,6 +25,7 @@ module Text.Pandoc.App.CommandLineOptions (
import Control.Monad.Trans
import Control.Monad.State.Strict
import Data.Containers.ListUtils (nubOrd)
+import Data.Aeson (eitherDecode)
import Data.Aeson.Encode.Pretty (encodePretty', Config(..), keyOrder,
defConfig, Indent(..), NumberFormat(..))
import Data.Bifunctor (second)
@@ -372,6 +373,23 @@ options =
"KEY[:VALUE]")
""
+ , Option "" ["variable-json"]
+ (ReqArg
+ (\arg opt -> do
+ let (key, json) = splitField arg
+ case eitherDecode (B.fromStrict . UTF8.fromString $ json) of
+ Right (val :: Val Text) ->
+ return opt{ optVariables =
+ let Context m = optVariables opt
+ in Context $ M.insert (T.pack key) val m }
+ -- note that this replaces any existing value, which
+ -- is different from what --variable does
+ Left err' -> optError $ PandocOptionError $
+ "Could not parse '" <> T.pack json <> "' as JSON:\n" <>
+ T.pack err')
+ "KEY[:JSON]")
+ ""
+
, Option "" ["wrap"]
(ReqArg
(\arg opt ->