From a4294800bfe91976697239ff15c1f87f518df6e8 Mon Sep 17 00:00:00 2001
From: John MacFarlane <jgm@berkeley.edu>
Date: Fri, 24 Jun 2016 14:46:47 -0700
Subject: [PATCH] Make --webtex work with the Markdown writer.

Closes #1177.  This is a convenient option for people using
websites whose Markdown flavors don't provide for math.
---
 README                              |  2 ++
 src/Text/Pandoc/Writers/Markdown.hs | 29 +++++++++++++++++------------
 2 files changed, 19 insertions(+), 12 deletions(-)

diff --git a/README b/README
index ecbc248e0..e3904b74e 100644
--- a/README
+++ b/README
@@ -949,6 +949,8 @@ Math rendering in HTML
 :   Render TeX formulas using an external script that converts TeX
     formulas to images. The formula will be concatenated with the URL
     provided. If *URL* is not specified, the Google Chart API will be used.
+    Note:  the `--webtex` option will affect Markdown output
+    as well as HTML.
 
 `--katex`[`=`*URL*]
 
diff --git a/src/Text/Pandoc/Writers/Markdown.hs b/src/Text/Pandoc/Writers/Markdown.hs
index 1ff8d2ab9..b04e33085 100644
--- a/src/Text/Pandoc/Writers/Markdown.hs
+++ b/src/Text/Pandoc/Writers/Markdown.hs
@@ -55,6 +55,7 @@ import qualified Data.HashMap.Strict as H
 import qualified Data.Vector as V
 import qualified Data.Text as T
 import qualified Data.Set as Set
+import Network.HTTP ( urlEncode )
 
 type Notes = [[Block]]
 type Ref   = ([Inline], Target, Attr)
@@ -856,18 +857,22 @@ inlineToMarkdown opts (Str str) = do
   if stPlain st
      then return $ text str
      else return $ text $ escapeString opts str
-inlineToMarkdown opts (Math InlineMath str)
-  | isEnabled Ext_tex_math_dollars opts =
-      return $ "$" <> text str <> "$"
-  | isEnabled Ext_tex_math_single_backslash opts =
-      return $ "\\(" <> text str <> "\\)"
-  | isEnabled Ext_tex_math_double_backslash opts =
-      return $ "\\\\(" <> text str <> "\\\\)"
-  | otherwise = do
-    plain <- gets stPlain
-    inlineListToMarkdown opts $
-      (if plain then makeMathPlainer else id) $
-      texMathToInlines InlineMath str
+inlineToMarkdown opts (Math InlineMath str) =
+  case writerHTMLMathMethod opts of
+       WebTeX url ->
+             inlineToMarkdown opts (Image nullAttr [Str str]
+                 (url ++ urlEncode str, str))
+       _ | isEnabled Ext_tex_math_dollars opts ->
+             return $ "$" <> text str <> "$"
+         | isEnabled Ext_tex_math_single_backslash opts ->
+             return $ "\\(" <> text str <> "\\)"
+         | isEnabled Ext_tex_math_double_backslash opts ->
+             return $ "\\\\(" <> text str <> "\\\\)"
+         | otherwise -> do
+             plain <- gets stPlain
+             inlineListToMarkdown opts $
+               (if plain then makeMathPlainer else id) $
+               texMathToInlines InlineMath str
 inlineToMarkdown opts (Math DisplayMath str)
   | isEnabled Ext_tex_math_dollars opts =
       return $ "$$" <> text str <> "$$"