From c6ec189a966c100a7992cc633d88efdd176c2a46 Mon Sep 17 00:00:00 2001
From: John MacFarlane <jgm@berkeley.edu>
Date: Wed, 16 Aug 2017 10:39:34 -0700
Subject: [PATCH] Revision to binary format output to stdout:

We now allow default output to stdout when it can be
determined that the output is being piped.  (On Windows,
as mentioned before, this can't be determined.)

Using '-o -' forces output to stdout regardless.
---
 MANUAL.txt             |  7 ++++---
 src/Text/Pandoc/App.hs | 17 ++++++++++++++---
 2 files changed, 18 insertions(+), 6 deletions(-)

diff --git a/MANUAL.txt b/MANUAL.txt
index e106af052..639c5e7ee 100644
--- a/MANUAL.txt
+++ b/MANUAL.txt
@@ -109,9 +109,10 @@ Using `pandoc`
 If no *input-file* is specified, input is read from *stdin*.
 Otherwise, the *input-files* are concatenated (with a blank
 line between each) and used as input.  Output goes to *stdout* by
-default (though output to *stdout* is disabled for the `odt`, `docx`,
-`epub2`, and `epub3` output formats, unless it is forced using
-`-o -`).  For output to a file, use the `-o` option:
+default (though output to the terminal is disabled for the
+`odt`, `docx`, `epub2`, and `epub3` output formats, unless it is
+forced using `-o -`).  For output to a file, use the `-o`
+option:
 
     pandoc -o output.html input.txt
 
diff --git a/src/Text/Pandoc/App.hs b/src/Text/Pandoc/App.hs
index c7f8bbb89..367a1f550 100644
--- a/src/Text/Pandoc/App.hs
+++ b/src/Text/Pandoc/App.hs
@@ -91,6 +91,10 @@ import Text.Pandoc.Shared (headerShift, isURI, openURL,
 import qualified Text.Pandoc.UTF8 as UTF8
 import Text.Pandoc.XML (toEntities)
 import Text.Printf
+#ifndef _WINDOWS
+import System.Posix.IO (stdOutput)
+import System.Posix.Terminal (queryTerminal)
+#endif
 
 data LineEnding = LF | CRLF | Native deriving (Show, Generic)
 
@@ -243,10 +247,17 @@ convertWithOpts opts = do
 
   -- We don't want to send output to the terminal if the user
   -- does 'pandoc -t docx input.txt'; though we allow them to
-  -- force this with '-o -'.
-  when (not (isTextFormat format) && optOutputFile opts == Nothing) $
+  -- force this with '-o -'.  On posix systems, we detect
+  -- when stdout is being piped and allow output to stdout
+  -- in that case, but on Windows we can't.
+#ifdef _WINDOWS
+  let istty = True
+#else
+  istty <- queryTerminal stdOutput
+#endif
+  when (not (isTextFormat format) && istty && optOutputFile opts == Nothing) $
     E.throwIO $ PandocAppError $
-            "Cannot write " ++ format ++ " output to stdout.\n" ++
+            "Cannot write " ++ format ++ " output to terminal.\n" ++
             "Specify an output file using the -o option, or " ++
             "use '-o -' to force output to stdout."