pandoc-plot 1.9.1 → 1.9.2
raw patch · 19 files changed
+356/−75 lines, 19 filesPVP: major bump suggested
API removals or changes: PVP suggests a major version bump
API changes (from Hackage documentation)
+ Text.Pandoc.Filter.Plot: [configBuildDir] :: Configuration -> !Maybe FilePath
+ Text.Pandoc.Filter.Plot.Internal: [configBuildDir] :: Configuration -> !Maybe FilePath
- Text.Pandoc.Filter.Plot: Configuration :: !FilePath -> !Bool -> !Int -> !SaveFormat -> ![FilePath] -> !Format -> !Text -> !Bool -> !Verbosity -> !LogSink -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Bool -> !Bool -> Configuration
+ Text.Pandoc.Filter.Plot: Configuration :: !FilePath -> !Bool -> !Int -> !SaveFormat -> ![FilePath] -> !Format -> !Text -> !Bool -> !Verbosity -> !LogSink -> !Maybe FilePath -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Bool -> !Bool -> Configuration
- Text.Pandoc.Filter.Plot.Internal: Configuration :: !FilePath -> !Bool -> !Int -> !SaveFormat -> ![FilePath] -> !Format -> !Text -> !Bool -> !Verbosity -> !LogSink -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Bool -> !Bool -> Configuration
+ Text.Pandoc.Filter.Plot.Internal: Configuration :: !FilePath -> !Bool -> !Int -> !SaveFormat -> ![FilePath] -> !Format -> !Text -> !Bool -> !Verbosity -> !LogSink -> !Maybe FilePath -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !Script -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !FilePath -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Text -> !Bool -> !Bool -> Configuration
- Text.Pandoc.Filter.Plot.Internal: captionReader :: Format -> Text -> Maybe [Inline]
+ Text.Pandoc.Filter.Plot.Internal: captionReader :: Format -> Text -> Either PandocError [Inline]
- Text.Pandoc.Filter.Plot.Internal: type PlotM = StateT PlotState (ReaderT RuntimeEnv IO)
+ Text.Pandoc.Filter.Plot.Internal: type PlotM = StateT PlotState ReaderT RuntimeEnv IO
Files
- CHANGELOG.md +14/−8
- MANUAL.md +36/−24
- README.md +6/−5
- example-config.yml +9/−2
- pandoc-plot.cabal +21/−11
- src/Text/Pandoc/Filter/Plot/Configuration.hs +9/−2
- src/Text/Pandoc/Filter/Plot/Embed.hs +35/−10
- src/Text/Pandoc/Filter/Plot/Monad.hs +5/−0
- src/Text/Pandoc/Filter/Plot/Parse.hs +3/−2
- src/Text/Pandoc/Filter/Plot/Scripting.hs +8/−1
- tests/Common.hs +11/−7
- tests/Main.hs +13/−3
- tests/fixtures/.build-directory-config.yml +1/−0
- tests/fixtures/.issue30.yml +8/−0
- tests/integration.md +39/−0
- tests/issue16.md +13/−0
- tests/issue46.md +9/−0
- tests/issue53.md +42/−0
- tests/issue55.md +74/−0
CHANGELOG.md view
@@ -2,6 +2,12 @@ pandoc-plot uses [Semantic Versioning](http://semver.org/spec/v2.0.0.html) +## Release 1.9.2++* Added a `build_directory` configuration option to override the directory where temporary rendering scripts are written. This is useful for sandboxed renderers (e.g. `mmdc` installed via `snap` on Linux) that cannot access the system temporary directory (#82).+* Fixed an issue where TeX output contained a figure even if the caption was empty (#37).+* Fixed a documentation issue where the null command-line arguments for `plantuml` should have been `""` (#76).+ ## Release 1.9.1 * Fixed an issue where extra parameters were not passed down to `pandoc`, depending on the output format (#38).@@ -173,7 +179,7 @@ ## Release 1.0.0.0 * Added support for Pandoc 2.11. Unfortunately, there is no way to support prior versions of Pandoc at the same time.-* With release 1.0.0.0, `pandoc-plot` has stabilized. The Haskell library API will not change until version 2+. +* With release 1.0.0.0, `pandoc-plot` has stabilized. The Haskell library API will not change until version 2+. ## Release 0.9.4.0 @@ -204,13 +210,13 @@ ```` * Better error messages when specifying logger verbosity.-* Cleaning output directories with `pandoc-plot clean` now follows configuration values for logging. +* Cleaning output directories with `pandoc-plot clean` now follows configuration values for logging. * Fixed an issue where configuration in metadata did not get parsed properly. ## Release 0.9.0.0 * The `bokeh` toolkit now supports exporting plots as SVGs (#8).-* Interactive plots relying on javascript scripts will now defer loading the scripts (#9). +* Interactive plots relying on javascript scripts will now defer loading the scripts (#9). * Added the `dependencies` argument, which tells `pandoc-plot` what files are important to a particular figure (#10). If a file listed in `dependencies` changes (for example, a data file), `pandoc-plot` will re-render the associated figure. * Better heuristic to determine what `bokeh` plot to save. This allows the user to export plots like the [`bokeh.layouts` module](https://docs.bokeh.org/en/latest/docs/user_guide/layout.html#creating-layouts). * Added support for the `dpi` parameter in `graphviz` and `mathematica`.@@ -254,7 +260,7 @@ ## Release 0.7.1.0 -* Better multi-threaded logging. Only one thread (the logging thread) performs IO on the log file. This prevents hang-ups when working on large documents. +* Better multi-threaded logging. Only one thread (the logging thread) performs IO on the log file. This prevents hang-ups when working on large documents. ## Release 0.7.0.0 @@ -267,7 +273,7 @@ # debug level shows all messages # error level shows all but debug messages, etc. verbosity: info- + # OPTIONAL: log to file # Remove line below to log to stderr filepath: log.txt@@ -300,7 +306,7 @@ title: My document author: John Doe plot-configuration: /path/to/file.yml- --- + --- ``` or on the command line:@@ -312,10 +318,10 @@ ## Release 0.5.0.0 -* The `pandoc-plot` executable will now process documents in parallel. This should dramatically speed up processing of large documents with lots of figures. +* The `pandoc-plot` executable will now process documents in parallel. This should dramatically speed up processing of large documents with lots of figures. This happens automatically through the function `plotTransform`. * Added a benchmarking suite.-* Added `defaultConfiguration` so that people don't have to install the `data-default` package to get access to default configuration values. +* Added `defaultConfiguration` so that people don't have to install the `data-default` package to get access to default configuration values. * Added a check for the `matplotlib` toolkit, preventing users from using `matplotlib.pyplot.show` in figures. This would halt `pandoc-plot`. ## Release 0.4.0.1
MANUAL.md view
@@ -174,7 +174,7 @@ ``` bash pandoc-plot 1.3.0 - generate figures directly in documents -Usage: pandoc-plot.EXE [(-v|--version) | --full-version | (-m|--manual)] +Usage: pandoc-plot.EXE [(-v|--version) | --full-version | (-m|--manual)] [COMMAND] [AST] This pandoc filter generates plots from code blocks using a multitude of possible renderers. This allows to keep documentation and figures in perfect@@ -243,18 +243,18 @@ There are parameters that affect the figure that will be included in your document. Here are all the possible general parameters, in Markdown syntax: ```` markdown- ```{.cls + ```{.cls .language- directory=(path) - caption=(text) - format=(PNG|PDF|SVG|JPG|EPS|GIF|TIF|WEBP|HTML|LATEX) - source=(true|True|false|False) + directory=(path)+ caption=(text)+ format=(PNG|PDF|SVG|JPG|EPS|GIF|TIF|WEBP|HTML|LATEX)+ source=(true|True|false|False) source_label=(text)- preamble=(path) + preamble=(path) dpi=(integer) dependencies=[...] file=(path)- executable=(path) + executable=(path) caption_format=(text) } # script content@@ -323,7 +323,7 @@ Many interactive plots rely on javascript scripts stored on the internet. If you want to have a self-contained document that can be viewed offline – or you want your document to work for the next 10 years –, you can use pandoc’s `--self-contained` flag: ``` bash-pandoc --self-contained --filter pandoc-plot -i mydoc.md -o webpage.html +pandoc --self-contained --filter pandoc-plot -i mydoc.md -o webpage.html ``` The resulting output `webpage.html` will contain everything, at the cost of size.@@ -350,7 +350,7 @@ # current working directory, or absolute. directory: plots/ -# Whether or not to include a link to the source script in the caption. +# Whether or not to include a link to the source script in the caption. # Particularly useful for HTML output. source: false @@ -360,15 +360,15 @@ strict: false # Text label for links to source code.-# You can change this label if you are writing a document in a non-English language. +# You can change this label if you are writing a document in a non-English language. # This only matters if `source` is set to `true`. source_label: Source code -# Default density of figures in dots per inches (DPI). +# Default density of figures in dots per inches (DPI). # This can be changed in the document specifically as well. dpi: 80 -# Default format in which to save the figures. This can be specified +# Default format in which to save the figures. This can be specified # individually as well. format: PNG @@ -380,13 +380,20 @@ - file2.txt # Text format for the captions. Unfortunately, there is no way to detect-# this automatically. You can use the same notation as Pandoc's --from -# parameter, specified here: +# this automatically. You can use the same notation as Pandoc's --from+# parameter, specified here: # https://pandoc.org/MANUAL.html#option--from # Example: markdown, rst+raw_tex caption_format: markdown+tex_math_dollars +# Directory in which to write temporary rendering scripts before they+# are executed by each toolkit. By default, the system temporary directory+# is used (e.g. /tmp on Linux). Override this when the renderer cannot+# access the system temporary directory -- for example, when `mmdc` is+# installed via `snap` on Linux and is sandboxed away from /tmp.+# build_directory: .pandoc-plot-build + # Logging configuration logging: # Possible verbosity values: debug, error, warning, info, silent@@ -468,12 +475,17 @@ # preamble: plantuml.txt executable: java command_line_arguments: -jar plantuml.jar- # On Linux, if you have `plantuml.jar` as an executable, you can also- # use the following configuration instead:- # plantuml:- # executable: plantuml- # command_line_arguments: +# On Linux, if you have `plantuml.jar` as an executable, you can also+# use the following configuration instead:+# plantuml:+# executable: plantuml+# command_line_arguments: ""+#+# Note that the `command_line_arguments` above are specifically the empty string.+# Providing no value is equivalent to the default command line arguments, which+# for `plantuml` are "-jar plantuml.jar".+ sageplot: # preamble: sageplot.sage executable: sage@@ -567,7 +579,7 @@ # debug level shows all messages # error level shows all but debug messages, etc. verbosity: info- + # OPTIONAL: log to file # Remove line below to log to stderr filepath: log.txt@@ -660,15 +672,15 @@ import Hakyll plotFilter' :: Pandoc -> IO Pandoc-plotFilter' = +plotFilter' = -- Notify pandoc-plot that the final conversion will be to HTML -- This helps give better error messages and adjust default values- plotFilter defaultConfiguration (Just $ Format "html5") + plotFilter defaultConfiguration (Just $ Format "html5") -- Unsafe compiler is required because of the interaction -- in IO (i.e. running an external script). makePlotPandocCompiler :: Compiler (Item String)-makePlotPandocCompiler = +makePlotPandocCompiler = pandocCompilerWithTransformM defaultHakyllReaderOptions defaultHakyllWriterOptions
README.md view
@@ -1,8 +1,8 @@-# pandoc-plot +# pandoc-plot ## A Pandoc filter to generate figures from code blocks in documents -[](https://www.gnu.org/licenses/gpl.html) +[](https://www.gnu.org/licenses/gpl.html) `pandoc-plot` turns code blocks present in your documents (Markdown, LaTeX, etc.) into embedded figures, using your plotting toolkit of choice, including Matplotlib, ggplot2, MATLAB, Mathematica, and more. @@ -72,7 +72,8 @@ - `plantuml`: diagrams using the [PlantUML](https://plantuml.com/) software suite; - `sageplot`: plots using the [Sage](https://www.sagemath.org/) software system; - `d2`: plots using [D2](https://d2lang.com/);- - `asymptote`: plots using [Asymptote](https://asymptote.sourceforge.io/).+ - `asymptote`: plots using [Asymptote](https://asymptote.sourceforge.io/);+ - `mermaid`: plots using the [MermaidJS](https://mermaid.js.org//). To know which toolkits are useable on *your machine* (and which ones are not available), you can check with the `toolkits` command:@@ -113,11 +114,11 @@ conda install -c conda-forge pandoc-plot ``` -### Homebrew +### Homebrew [](https://formulae.brew.sh/formula/pandoc-plot) -`pandoc-plot` is available as a package via [`Homebrew`](https://brew.sh/). [Click here to see the package page](https://formulae.brew.sh/formula/pandoc-plot#default). +`pandoc-plot` is available as a package via [`Homebrew`](https://brew.sh/). [Click here to see the package page](https://formulae.brew.sh/formula/pandoc-plot#default). To install:
example-config.yml view
@@ -44,11 +44,18 @@ - file2.txt # Text format for the captions. Unfortunately, there is no way to detect-# this automatically. You can use the same notation as Pandoc's --from -# parameter, specified here: +# this automatically. You can use the same notation as Pandoc's --from+# parameter, specified here: # https://pandoc.org/MANUAL.html#option--from # Example: markdown, rst+raw_tex caption_format: markdown+tex_math_dollars++# Directory in which to write temporary rendering scripts before they+# are executed by each toolkit. By default, the system temporary directory+# is used (e.g. /tmp on Linux). Override this when the renderer cannot+# access the system temporary directory -- for example, when `mmdc` is+# installed via `snap` on Linux and is sandboxed away from /tmp.+# build_directory: .pandoc-plot-build # Logging configuration
pandoc-plot.cabal view
@@ -1,9 +1,9 @@ cabal-version: 2.2 name: pandoc-plot-version: 1.9.1+version: 1.9.2 synopsis: A Pandoc filter to include figures generated from code blocks using your plotting toolkit of choice.-description: A Pandoc filter to include figures generated from code blocks. - Keep the document and code in the same location. Output is +description: A Pandoc filter to include figures generated from code blocks.+ Keep the document and code in the same location. Output is captured and included as a figure. category: Text copyright: (c) 2019-present Laurent P. René de Cotret@@ -14,9 +14,9 @@ license: GPL-2.0-or-later license-file: LICENSE build-type: Simple-tested-with: GHC == 8.10.4, - GHC == 9.0.1, - GHC == 9.2.1, +tested-with: GHC == 8.10.4,+ GHC == 9.0.1,+ GHC == 9.2.1, GHC == 9.2.2, GHC == 9.4.4, GHC == 9.6.1,@@ -33,12 +33,20 @@ data/srctemplate.html + tests/integration.md+ tests/issue16.md+ tests/issue46.md+ tests/issue53.md+ tests/issue55.md++ tests/fixtures/.build-directory-config.yml tests/fixtures/.config-meta.yml tests/fixtures/.empty-config.yml+ tests/fixtures/.issue30.yml tests/fixtures/.verbose-config.yml tests/fixtures/plotfile.py tests/fixtures/data.csv- + tests/includes/bokeh.py tests/includes/ggplot2.r tests/includes/gnuplot.gp@@ -95,8 +103,8 @@ Paths_pandoc_plot hs-source-dirs: src- ghc-options: - -Wall + ghc-options:+ -Wall -Wcompat -Widentities -Wincomplete-uni-patterns@@ -110,7 +118,7 @@ , base >= 4.11 && < 5 , bytestring , containers- , data-default + , data-default , directory >= 1.2.7 && < 2 , filepath >= 1.4 && < 2 , hashable >= 1 && < 2@@ -134,6 +142,8 @@ ExampleConfig OpenFile Paths_pandoc_plot+ autogen-modules:+ Paths_pandoc_plot hs-source-dirs: executable ghc-options: -Wall -Wcompat -threaded -rtsopts -with-rtsopts=-N@@ -142,7 +152,7 @@ , directory , filepath , gitrev >= 1 && < 2- , optparse-applicative >= 0.14 && < 0.19+ , optparse-applicative >= 0.14 && < 0.20 , pandoc , pandoc-plot , pandoc-types >= 1.21 && < 2
src/Text/Pandoc/Filter/Plot/Configuration.hs view
@@ -50,6 +50,7 @@ strictMode = False, logVerbosity = Warning, logSink = StdErr,+ configBuildDir = Nothing, -- Preambles matplotlibPreamble = mempty, plotlyPythonPreamble = mempty,@@ -163,7 +164,8 @@ _sagemathPrec :: !SageMathPrecursor, _d2Prec :: !D2Precursor, _asyPrec :: !AsyPrecursor,- _mermaidPrec :: !MermaidPrecursor+ _mermaidPrec :: !MermaidPrecursor,+ _configBuildDir :: !(Maybe FilePath) } defaultConfigPrecursor :: ConfigPrecursor@@ -193,7 +195,8 @@ _sagemathPrec = SageMathPrecursor Nothing (sagemathExe defaultConfiguration) (sagemathCmdArgs defaultConfiguration), _d2Prec = D2Precursor Nothing (d2Exe defaultConfiguration) (d2CmdArgs defaultConfiguration), _asyPrec = AsyPrecursor Nothing (asyExe defaultConfiguration) (asyCmdArgs defaultConfiguration),- _mermaidPrec = MermaidPrecursor Nothing (mermaidExe defaultConfiguration) (mermaidCmdArgs defaultConfiguration)+ _mermaidPrec = MermaidPrecursor Nothing (mermaidExe defaultConfiguration) (mermaidCmdArgs defaultConfiguration),+ _configBuildDir = configBuildDir defaultConfiguration } data LoggingPrecursor = LoggingPrecursor@@ -353,6 +356,8 @@ _asyPrec <- v .:? toolkitAsKey Asymptote .!= _asyPrec defaultConfigPrecursor _mermaidPrec <- v .:? toolkitAsKey Mermaid .!= _mermaidPrec defaultConfigPrecursor + _configBuildDir <- v .:? "build_directory" .!= _configBuildDir defaultConfigPrecursor+ return $ ConfigPrecursor {..} parseJSON _ = fail "Could not parse configuration." @@ -372,6 +377,8 @@ matplotlibTightBBox = _matplotlibTightBBox _matplotlibPrec matplotlibTransparent = _matplotlibTransparent _matplotlibPrec++ configBuildDir = _configBuildDir matplotlibExe = _matplotlibExe _matplotlibPrec matlabExe = _matlabExe _matlabPrec
src/Text/Pandoc/Filter/Plot/Embed.hs view
@@ -16,8 +16,9 @@ ) where +import Control.Exception (Exception, throwIO) import Data.Default (def)-import Data.Maybe (fromMaybe)+import Data.Maybe (listToMaybe) import Data.Text (Text, pack) import qualified Data.Text.IO as T import Text.HTML.TagSoup@@ -63,11 +64,19 @@ target <- figurePath spec scp <- pack <$> sourceCodePath spec sourceLabel <- asksConfig sourceCodeLabel -- Allow the possibility for non-english labels++ cap <- case (captionReader fmt $ caption spec) of+ Left exc -> do+ err $ "Unable to parse caption: " <> (pack $ show exc)+ pure mempty+ Right c -> do+ debug $ "Parsed caption: " <> (pack $ show c)+ pure $ fromList c+ let srcLink = link scp mempty (str sourceLabel) attrs' = blockAttrs spec- captionText = fromList $ fromMaybe mempty (captionReader fmt $ caption spec) captionLinks = mconcat [" (", srcLink, ")"]- caption' = if withSource spec then captionText <> captionLinks else captionText+ caption' = if withSource spec then cap <> captionLinks else cap builder attrs' target caption' where builder = case saveFormat spec of@@ -81,12 +90,20 @@ Inlines -> PlotM Block figure as fp caption' =- return . head . toList $- -- We want the attributes both on the Figure element and the contained Image element- -- so that pandoc-plot plays nice with pandoc-crossref and other filters- figureWith as (simpleCaption (plain caption')) $- plain $- imageWith as (pack fp) mempty caption'+ maybe+ (liftIO $ throwIO PandocBuilderException) -- We cannot build a single `Block` unfortunately, so we must be ready to throw an exception.+ pure+ . listToMaybe+ . toList+ $ if null caption'+ -- If there is no caption, a LaTeX figure may look strange. See #37+ then plain $ imageWith as (pack fp) mempty caption'+ else+ -- We want the attributes both on the Figure element and the contained Image element+ -- so that pandoc-plot plays nice with pandoc-crossref and other filters+ figureWith as (simpleCaption (plain caption')) $+ plain $+ imageWith as (pack fp) mempty caption' -- TODO: also add the case where SVG plots can be -- embedded in HTML output@@ -188,6 +205,14 @@ -- | Get content inside a tag, e.g. /inside "body"/ returns all tags -- between /<body>/ and /</body>/ inside :: Text -> [Tag Text] -> [Tag Text]-inside t = init . tail . tgs+inside t = init . drop 1 . tgs where tgs = takeWhile (~/= TagClose t) . dropWhile (~/= TagOpen t [])+++-- | Exception thrown when a Pandoc builder (e.g. `Blocks`)+-- has an unexpected structure.+data PandocBuilderException = PandocBuilderException+ deriving (Show)++instance Exception PandocBuilderException
src/Text/Pandoc/Filter/Plot/Monad.hs view
@@ -327,6 +327,11 @@ logVerbosity :: !Verbosity, -- | Method of logging, i.e. printing to stderr or file. logSink :: !LogSink,+ -- | Directory in which to write temporary rendering scripts. When @Nothing@,+ -- the system temporary directory is used. Override this when the renderer+ -- is sandboxed and cannot access the system temporary directory (e.g.+ -- @mmdc@ installed via @snap@ on Linux).+ configBuildDir :: !(Maybe FilePath), -- | The default preamble script for the matplotlib toolkit. matplotlibPreamble :: !Script, -- | The default preamble script for the Plotly/Python toolkit.
src/Text/Pandoc/Filter/Plot/Parse.hs view
@@ -44,6 +44,7 @@ import Text.Pandoc.Format (parseFlavoredFormat) import Text.Pandoc.Options (ReaderOptions (..)) import Text.Pandoc.Readers (Reader (..), getReader)+import Text.Pandoc (PandocError) tshow :: (Show a) => a -> Text tshow = pack . show@@ -162,8 +163,8 @@ plotToolkit _ = Nothing -- | Reader a caption, based on input document format-captionReader :: Format -> Text -> Maybe [Inline]-captionReader (Format f) t = either (const Nothing) (Just . extractFromBlocks) $+captionReader :: Format -> Text -> Either PandocError [Inline]+captionReader (Format f) t = fmap extractFromBlocks $ runPure $ do fmt <- parseFlavoredFormat f (reader, exts) <- getReader fmt
src/Text/Pandoc/Filter/Plot/Scripting.hs view
@@ -148,7 +148,14 @@ -- be rendered or not. fp <- figurePath fs let hashedPath = takeBaseName fp <> ext- liftIO $ (</> hashedPath) <$> getTemporaryDirectory+ -- If a custom build directory is configured (see issue #81), use it so+ -- that sandboxed renderers like snap-installed mmdc can read the script.+ -- Otherwise fall back to the system temporary directory.+ mBuildDir <- asksConfig configBuildDir+ buildDir <- liftIO $ case mBuildDir of+ Just d -> createDirectoryIfMissing True d >> pure d+ Nothing -> getTemporaryDirectory+ return (buildDir </> hashedPath) -- | Determine the path to the source code that generated the figure. -- To ensure that the source code path is distinguished from HTML figures, we use the extension .src.html.
tests/Common.hs view
@@ -380,12 +380,13 @@ -- constructed let expectedAttrs = ("hello", [cls tk], [("key1", "val1"), ("key2", "val2")]) cb =- setAttrs expectedAttrs $ addDirectory tempDir $- addCaption "[title](https://google.com)" $- codeBlock tk (trivialContent tk)+ addCaption "This is a caption [title](https://google.com)" $+ setAttrs expectedAttrs $+ codeBlock tk (trivialContent tk) fmt = B.Format "markdown"- Figure (id', _, keyvals) _ _ <-++ block <- runPlotM Nothing ( defaultTestConfig@@ -394,9 +395,12 @@ } ) $ make cb- let (expectedId, _, expectedKeyVals) = expectedAttrs- assertEqual "identifier" expectedId id'- assertEqual "key-value pairs" expectedKeyVals keyvals+ case block of+ Figure (id', _, keyvals) _ _ -> do+ let (expectedId, _, expectedKeyVals) = expectedAttrs+ assertEqual "identifier" expectedId id'+ assertEqual "key-value pairs" expectedKeyVals keyvals+ other -> assertFailure $ "Unexpected block: " <> show block where extractCaption (B.Figure _ (Caption _ caption) _) = caption
tests/Main.hs view
@@ -28,7 +28,8 @@ "Configuration tests" [ testEmptyConfiguration, testExampleConfiguration,- testConfigurationPathMeta+ testConfigurationPathMeta,+ testBuildDirectoryConfiguration ], testGroup "Parsing tests"@@ -92,6 +93,13 @@ parsedConfig <- configuration "example-config.yml" assertEqual "" config parsedConfig +-- Test for #81: a build_directory key in YAML maps to configBuildDir.+testBuildDirectoryConfiguration :: TestTree+testBuildDirectoryConfiguration =+ testCase "build_directory is parsed into configBuildDir" $ do+ parsedConfig <- configuration "tests/fixtures/.build-directory-config.yml"+ assertEqual "" (Just "my-build-dir") (configBuildDir parsedConfig)+ -- Test that the path to configuration in metadata is found correctly testConfigurationPathMeta :: TestTree testConfigurationPathMeta =@@ -109,11 +117,13 @@ -- Note that this test is fragile, in the sense that the expected result must be carefully -- constructed let caption = "Here is a [link](https://www.google.com) in a caption."- expected = Just [Str "Here", Space, Str "is", Space, Str "a", Space, Link ("", [], []) [Str "link"] ("https://www.google.com", ""), Space, Str "in", Space, Str "a", Space, Str "caption."]+ expected = [Str "Here", Space, Str "is", Space, Str "a", Space, Link ("", [], []) [Str "link"] ("https://www.google.com", ""), Space, Str "in", Space, Str "a", Space, Str "caption."] fmt = B.Format "markdown+tex_math_dollars" parsed = captionReader fmt caption - assertEqual "" expected parsed+ case parsed of+ Left exc -> assertFailure $ show exc+ Right result -> assertEqual "" expected result testHtmlBodyEmbedding :: TestTree testHtmlBodyEmbedding =
+ tests/fixtures/.build-directory-config.yml view
@@ -0,0 +1,1 @@+build_directory: my-build-dir
+ tests/fixtures/.issue30.yml view
@@ -0,0 +1,8 @@+strict: true++logging:+ verbosity: debug++plantuml:+ executable: "plantuml"+ command_line_arguments: ""
+ tests/integration.md view
@@ -0,0 +1,39 @@+---+title: Integration test+plot-configuration: tests/fixtures/.verbose-config.yml+---++```{.matplotlib}+# Example from:+# https://matplotlib.org/gallery/lines_bars_and_markers/scatter_demo2.html#sphx-glr-gallery-lines-bars-and-markers-scatter-demo2-py+# +import matplotlib.pyplot as plt++# Pie chart, where the slices will be ordered and plotted counter-clockwise:+labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'+sizes = [15, 30, 45, 10]+explode = (0, 0.1, 0, 0) # only "explode" the 2nd slice (i.e. 'Hogs')++fig1, ax1 = plt.subplots()+ax1.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',+ shadow=True, startangle=90)+ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.++```++Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.++```{.matplotlib file=tests/fixtures/plotfile.py caption="Example of plot included by file."}+```++The following plot uses a file that is specified using a path relative+from the location where pandoc-plot is called. Read issue #2 for context.+```{.matplotlib}+import numpy as np+import matplotlib.pyplot as plt++x, y = np.loadtxt("tests/fixtures/data.csv", delimiter=',', unpack=True)++plt.figure()+plt.plot(x,y)+```
+ tests/issue16.md view
@@ -0,0 +1,13 @@+---+plot-configuration: tests/fixtures/.verbose-config.yml+---++# Verifying that unicode symbols work with the PlotJL toolkit++```{.plotsjl}+using Plots++plot(sin, (x->begin+ sin(2x)+ end), 0, 2π, line = 4, leg = false, fill = (0, :orange))+```
+ tests/issue46.md view
@@ -0,0 +1,9 @@+---+plot-configuration: tests/fixtures/.verbose-config.yml+---++```{.matplotlib executable="./issue46/bin/python"}+import sys+print(f"sys.executable={sys.executable}", file=sys.stderr)+import npstreams+```
+ tests/issue53.md view
@@ -0,0 +1,42 @@+++```{.python .matplotlib}+import matplotlib.pyplot as plt+plt.plot([1,2,3,4,5])+```+++```{.python .matplotlib}+import matplotlib.pyplot as plt+plt.plot([1,2,3,4,5])+```+++```{.python .matplotlib}+import matplotlib.pyplot as plt+plt.plot([1,2,3,4,5])+```+++```{.python .matplotlib}+import matplotlib.pyplot as plt+plt.plot([1,2,3,4,5])+```+++```{.python .matplotlib}+import matplotlib.pyplot as plt+plt.plot([1,2,3,4,5])+```+++```{.python .matplotlib}+import matplotlib.pyplot as plt+plt.plot([1,2,3,4,5])+```+++```{.python .matplotlib}+import matplotlib.pyplot as plt+plt.plot([1,2,3,4,5])+```
+ tests/issue55.md view
@@ -0,0 +1,74 @@+---+plot-configuration: tests/fixtures/.verbose-config.yml+---++# Example Asymptote plot++```{.asy}++// This example was taken from Asymptote's gallery+import graph;++size(9cm,8cm,IgnoreAspect);+string data="westnile.csv";++file in=input(data).line().csv();++string[] columnlabel=in;++real[][] A=in;+A=transpose(A);+real[] number=A[0], survival=A[1];++path g=graph(number,survival);+draw(g);++scale(true);++xaxis("Initial no.\ of mosquitoes per bird ($S_{M_0}/N_{B_0}$)",+ Bottom,LeftTicks);+xaxis(Top);+yaxis("Susceptible bird survival",Left,RightTicks(trailingzero));+yaxis(Right);++real a=number[0];+real b=number[number.length-1];++real S1=0.475;+path h1=(a,S1)--(b,S1);+real M1=interp(a,b,intersect(h1,g)[0]);++real S2=0.9;+path h2=(a,S2)--(b,S2);+real M2=interp(a,b,intersect(h2,g)[0]);++labelx("$M_1$",M1);+labelx("$M_2$",M2);++draw((a,S2)--(M2,S2)--(M2,0),Dotted);+draw((a,S1)--(M1,S1)--(M1,0),dashed);++pen p=fontsize(10pt);++real y3=0.043;+path reduction=(M1,y3)--(M2,y3);+draw(reduction,Arrow,TrueMargin(0,0.5*(linewidth(Dotted)+linewidth())));++arrow(shift(-20,5)*Label(minipage("\flushleft{\begin{itemize}\item[1.]+Estimate proportion of birds surviving at end of season\end{itemize}}",100),+ align=NNE),+ (M1,S1),NNE,1cm,p,Arrow(NoFill));++arrow(shift(-24,5)*Label(minipage("\flushleft{\begin{itemize}\item[2.]+Read off initial mosquito abundance\end{itemize}}",80),align=NNE),+ (M1,0),NE,2cm,p,Arrow(NoFill));++arrow(shift(20,0)*Label(minipage("\flushleft{\begin{itemize}\item[3.]+Determine desired bird survival for next season\end{itemize}}",90),align=SW),+ (M2,S2),SW,arrowlength,p,Arrow(NoFill));++arrow(shift(8,-15)*Label(minipage("\flushleft{\begin{itemize}\item[4.]+Calculate required proportional reduction in mosquitoes\end{itemize}}",90),+ align=NW),+ point(reduction,0.5),NW,1.5cm,p,Arrow(NoFill));+```