# HG changeset patch
# User Daniel J Sebald <daniel.sebald@ieee.org>
# Date 1436860990 18000
# Node ID 2598c800ca0c6306c16cec03b7573ca83b552044
# Parent  0e2da885a410c209233ab6473df19e78623c184d
Fix gnuplot toolkit bugs and add a demo to print(). (bug #44187)

* __gnuplot_drawnow__.m (__gnuplot_drawnow__): Pass variable "mono" into
gnuplot_set_term().
(gnuplot_set_term): Accept "mono" variable and supply "mono" or "color" to the
gnuplot command string based upon the availability of those options.  Change
"nargin == 5" to "nargin >= 5" where appropriate.

* print.m (print): Clarify in the help text that it is pslatexstandalone,
pdflatex, and pdflatexstandalone that aren't available in gnuplot.  Also
indicate paperunits and paperposition control the size latex-based devices.
Add notes about these possible devices: eepic, pstricks, texdraw, emtex, latex,
cairolatex, tikzstandalone, eepic, pstricks, texdraw, tkcanvas and canvas.  Add
a demo that lists the many device alternatives with a few options the user can
select test mono and color modes then print and send the result through a
systemn application for viewing the result.

* __gnuplot_print__.m (__gnuplot_print__): Add "emtex", "latex" and "epslatex",
to the latex devices case, and for that case make figure paperunits and
position control the eventual size after processing with latex.  Add
"tikzstandalone" to the "tikz" case and add "standalone" option if warranted.
Add "epscairo" and "eepic" to the "pdfcairo" case.  Add "jpeg", "jpg",
"postscript" and "tkcanvas" to the "canvas" case.  If the formats/languages
aliases, i.e., postscript device with external translation, "png16m" or
"pdfwrite" are detected, use a gnuplot terminal if possible before utilizing a
postscript conversion.
(font_spec): Add a comma before the numerical fontsize specification string.
Move "gif", "jpeg" and "png" to the "pdfcairo" case.  Also, check that the
font properties aren't empty before using them as strings.

* __go_draw_axes__.m (__go_draw_axes__): Place a newline character after all
binary data has been written to avoid gnuplot dropping the first character of
the followup gnuplot command.  Remove redundant !mono in conditional test for
markerfacecolor and markeredgecolor.
(create_fontspec): Add an empty string test to the conditional for ",%d" case.
(__gnuplot_write_data__): Remove incorrect, speculative FIXME comment about
efficiency.  Increase efficiency slightly by using logical indexing instead of
find().
(get_fontname_and_size): Make unknown/default font an empty string, not "{}".

* __go_draw_figure__.m (__go_draw_figure__): Add test cases to not draw the
axes background rectangle if the color is similar to that of the plot
background color dependent upon mono setting.

* __print_parse_opts__.m (__print_parse_opts__): Fix several bugs where
strings indexed with {a:b} should be indexed with (a:b).  Use !any(.) rather
than all(!.).

diff --git a/scripts/plot/util/__gnuplot_drawnow__.m b/scripts/plot/util/__gnuplot_drawnow__.m
--- a/scripts/plot/util/__gnuplot_drawnow__.m
+++ b/scripts/plot/util/__gnuplot_drawnow__.m
@@ -39,11 +39,11 @@ function __gnuplot_drawnow__ (h, term, f
       plot_stream = __gnuplot_open_stream__ (2, h);
       gnuplot_supports_term = __gnuplot_has_terminal__ (term, plot_stream);
       if (gnuplot_supports_term)
-        enhanced = gnuplot_set_term (plot_stream(1), true, h, term, file);
+        enhanced = gnuplot_set_term (plot_stream(1), true, h, term, file, mono);
         __go_draw_figure__ (h, plot_stream(1), enhanced, mono);
         if (nargin == 5)
           fid = fopen (debug_file, "wb");
-          enhanced = gnuplot_set_term (fid, true, h, term, file);
+          enhanced = gnuplot_set_term (fid, true, h, term, file, mono);
           __go_draw_figure__ (h, fid, enhanced, mono);
         endif
       else
@@ -79,9 +79,10 @@ function __gnuplot_drawnow__ (h, term, f
       ## popen2 eats stdout of gnuplot, use temporary file instead
       dumb_tmp_file = tempname ();
       enhanced = gnuplot_set_term (plot_stream(1), new_stream, h,
-                                   term, dumb_tmp_file);
+                                   term, dumb_tmp_file, mono);
     else
-      enhanced = gnuplot_set_term (plot_stream(1), new_stream, h, term);
+      enhanced = gnuplot_set_term (plot_stream(1), new_stream, h,
+                                   term, "", mono);
     endif
     __go_draw_figure__ (h, plot_stream(1), enhanced, mono);
     fflush (plot_stream(1));
@@ -106,7 +107,7 @@ function __gnuplot_drawnow__ (h, term, f
 
 endfunction
 
-function enhanced = gnuplot_set_term (plot_stream, new_stream, h, term, file)
+function enhanced = gnuplot_set_term (plot_stream, new_stream, h, term, file, mono)
   ## Generate the gnuplot "set terminal <term> ..." command.
   ## When "term" originates from print.m, it may include other options.
   if (nargin < 4)
@@ -266,14 +267,34 @@ function enhanced = gnuplot_set_term (pl
       size_str = "";
     endif
 
-    ## Set the gnuplot terminal (type, enhanced, title, options & size).
+    ## Set the gnuplot terminal (type, mono, enhanced, title, options & size).
     term_str = ["set terminal " term];
+
+    ## These two subsets should be the same, but "eepic" is odd in the sense
+    ## it uses {color|dashed} rather than {color|mono}.
+    persistent ...
+    terminals_with_mono = {"cairolatex", "cgm", "context", "corel", ...
+                           "emf", "eps", "epscairo", "epslatex", "fig", ...
+                           "mp", "pcl5", "pdfcairo", "pngcairo", "postscript", ...
+                           "pslatex", "pstex", "tgif", "tikz"};
+    persistent ...
+    terminals_with_color = {"cairolatex", "cgm", "context", "corel", ...
+                            "eepic", "emf", "eps", "epscairo", "epslatex", "fig", ...
+                            "mp", "pcl5", "pdfcairo", "pngcairo", "postscript", ...
+                            "pslatex", "pstex", "tgif", "tikz"};
+    if (mono && any (strcmp (term, terminals_with_mono)))
+      term_str = [term_str " mono"];
+    elseif (any (strcmp (term, terminals_with_color)))
+      term_str = [term_str " color"];
+    endif
+
     if (! isempty (enh_str))
       term_str = [term_str " " enh_str];
     endif
     if (! isempty (title_str))
       term_str = [term_str " " title_str];
     endif
+
     if (isempty (strfind (term, "corel")))
       if (! isempty (size_str) && new_stream)
         ## size_str comes after other options to permit specification of
@@ -295,6 +316,7 @@ function enhanced = gnuplot_set_term (pl
         term_str = [term_str " " size_str];
       endif
     endif
+
     if (! __gnuplot_has_feature__ ("has_termoption_dashed"))
       ## If "set termoption dashed" isn't available add "dashed" option
       ## to the "set terminal ..." command, if it is supported.
@@ -320,7 +342,7 @@ function enhanced = gnuplot_set_term (pl
         || have_non_legend_axes (h)
         || numel (findall (h, "type", "image")) > 0)
       fprintf (plot_stream, "%s\n", term_str);
-      if (nargin == 5)
+      if (nargin >= 5)
         if (! isempty (file))
           fprintf (plot_stream, "set output '%s';\n", file);
         endif
@@ -328,7 +350,7 @@ function enhanced = gnuplot_set_term (pl
       fputs (plot_stream, "set multiplot;\n");
     elseif (any (strcmp (term, flickering_terms)))
       fprintf (plot_stream, "%s\n", term_str);
-      if (nargin == 5)
+      if (nargin >= 5)
         if (! isempty (file))
           fprintf (plot_stream, "set output '%s';\n", file);
         endif
diff --git a/scripts/plot/util/print.m b/scripts/plot/util/print.m
--- a/scripts/plot/util/print.m
+++ b/scripts/plot/util/print.m
@@ -122,13 +122,34 @@
 ## edited before @LaTeX{} processing.  Specifically, the special characters
 ## must be enclosed with dollar signs (@code{$ @dots{} $}), and other
 ## characters that are recognized by @LaTeX{} may also need editing (.e.g.,
-## braces).  The @samp{pdflatex} device, and any of the @samp{standalone}
-## formats, are not available with the Gnuplot toolkit.
+## braces).  The @samp{pdflatex}, @samp{pslatexstandalone} and
+## @samp{pdflatexstandalone} devices are not available with the Gnuplot
+## toolkit.  For Gnuplot toolkit, the properties @code{paperunits} and
+## @code{paperposition} control the eventual size of the processed output.
+##
+##   @item emtex
+##   @item latex
+##   @item cairolatex
+##     Generate a @LaTeX{} file (only available for the Gnuplot graphics
+## toolkit).
 ##
 ##   @item tikz
+##   @item tikzstandalone
 ##     Generate a @LaTeX{} file using PGF/TikZ@.  For the FLTK toolkit
 ## the result is PGF.
 ##
+##   @item eepic
+##     Generate a @LaTeX{} file suitable for the epic and eepic packages
+## (only available for the Gnuplot graphics toolkit).
+##
+##   @item pstricks
+##     Generate a @LaTeX{} file suitable for the pstricks package (only
+## available for the Gnuplot graphics toolkit).
+##
+##   @item texdraw
+##     Generate a @LaTeX{} file suitable for the pstricks package (only
+## available for the Gnuplot graphics toolkit).
+##
 ##   @item  ill
 ##   @itemx aifm
 ##     Adobe Illustrator (Obsolete for Gnuplot versions > 4.2)
@@ -172,6 +193,14 @@
 ##
 ##   @item pdf
 ##     Portable document format
+##
+##   @item tkcanvas
+##     Tcl/Tk tool command language scripts viewable in wish (only available
+## for Gnuplot graphics toolkit).
+##
+##   @item canvas
+##     Javascript-based drawing on HTML5 canvas viewable in a web browser
+## (only available for Gnuplot graphics toolkit).
 ##   @end table
 ##
 ##   If the device is omitted, it is inferred from the file extension,
@@ -236,9 +265,11 @@
 ##   Plot size in pixels for EMF, GIF, JPEG, PBM, PNG, and SVG@.
 ## For PS, EPS, PDF, and other vector formats the plot size is in points.
 ## This option is equivalent to changing the size of the plot box associated
-## with the @qcode{"paperposition"} property.  When using the command form of
-## the print function you must quote the @var{xsize},@var{ysize} option.  For
-## example, by writing @w{"-S640,480"}.
+## with the @qcode{"paperposition"} property.  For @LaTeX{} devices in the
+## Gnuplot toolkit, the properties @code{paperunits} and @code{paperposition}
+## control the eventual size of the processed output.  When using the command
+## form of the print function you must quote the @var{xsize},@var{ysize}
+## option.  For example, by writing @w{"-S640,480"}.
 ##
 ## @item  -F@var{fontname}
 ## @itemx -F@var{fontname}:@var{size}
@@ -739,3 +770,204 @@ function cmd = pstoedit (opts, devopt)
   endif
 endfunction
 
+
+%!demo
+%! valid_gtlk = {'fltk', 'gnuplot', 'qt'};
+%! gtlk = {};
+%!
+%! if (isempty (gtlk))
+%!   idx = listdlg ('ListString',valid_gtlk, ...
+%!               'SelectionMode','Multiple', ...
+%!               'Name','Print Demo Graphics Toolkit', ...
+%!               'InitialValue',1:length(valid_gtlk), ...
+%!               'PromptString',{'Choose toolkit(s) for which to print examples'});
+%!   if isempty (idx)
+%!     return
+%!   else
+%!     gtlk = valid_gtlk (idx);
+%!   endif
+%! endif
+%!
+%! % Check for acroread and if not present look for xpdf.
+%! persistent pdfviewer = '';
+%! if isempty (pdfviewer)
+%!   pdfviewer = 'acroread %f.%e';
+%!   if (system('acroread -v > /dev/null'))
+%!     if (any (system('xpdf -v >& /dev/null') == [0 99]))
+%!       pdfviewer = 'xpdf %f.%e';
+%!     endif
+%!   endif
+%! endif
+%! bitviewer = 'eog %f.%e';
+%! psviewer = 'gv %f.%e';
+%! xfigviewer = 'xfig %f.%e';
+%! texviewer = ['echo "\end" | tex -output-directory ', tempdir() ' %f; xdvi %f'];
+%! latexviewer = ['echo "\documentclass[12pt]{article}',...
+%!                      '\usepackage{color}',...
+%!                      '\usepackage{graphicx}',...
+%!                      '\usepackage{epic}',...
+%!                      '\usepackage{eepic}',...
+%!                      '\setlength{\textheight}{10in}',...
+%!                      '\title{Including Plot In \LaTeX\ File}',...
+%!                      '\begin{document}',...
+%!                      '\maketitle',...
+%!                      '\section{Using \textbackslash input\{\} to import plot}',...
+%!                      'Place the output file name inside the \LaTeX\ \textbackslash input\{\} ',...
+%!                      'directive.  To change scale, use \textit{paperunits} and \textit{paperposition} ',...
+%!                      'properties of figure. Alternatively, use standalone mode and ',...
+%!                      'process the plot with \LaTeX, convert the DVI file to ',...
+%!                      'PostScript then use \textbackslash includegraphics\{\} to scale.',...
+%!                      '\begin{figure}[h]',...
+%!                      '\centering',...
+%!                      '\setlength{\unitlength}{1pt}',...
+%!                      '\input{%f.%e}',...
+%!                      '\caption{The plot font is the same as the document ',...
+%!                      'font?  Whoa!}',...
+%!                      '\end{figure}',...
+%!                      '\end{document}"',...
+%!                      ' > %f-sa.%e;',...
+%!                      ' latex -output-directory ' tempdir() ' %f-sa -o %f-sa.dvi;'...
+%!                      ' xdvi %f-sa'];
+%! salatexviewer = ['latex -output-directory ' tempdir() ' %f -o %f.dvi; xdvi %f'];
+%! pdflatexviewer = ['pdflatex -output-directory ', tempdir() ' %f; ' strrep(pdfviewer,'%e','pdf')];
+%! tikzviewer = strrep (latexviewer, '{article}', ['{article}\usepackage[T1]{fontenc}',...
+%!                      '\usepackage{textcomp}',...
+%!                      '\usepackage[utf8x]{inputenc}',...
+%!                      '\usepackage{gnuplot-lua-tikz}',...
+%!                      '\usepackage[active,tightpage]{preview}',...
+%!                      '\PreviewEnvironment{tikzpicture}']);
+%! tikzviewer = strrep (tikzviewer, 'latex -output-directory', 'pdflatex -output-directory');
+%! pstricksviewer = strrep (latexviewer, '{article}', '{article}\usepackage{pstricks}');
+%! texdrawviewer = strrep (latexviewer, '{article}', '{article}\usepackage{texdraw}');
+%! tktclviewer = ['echo "source %f.%e; canvas .c; pack .c; gnuplot .c" | wish'];
+%! htmlviewer = ['htmlview %f.%e'];
+%! devlist = {'png',                '',    bitviewer; ...
+%!            'pngcairo',           '',    bitviewer; ...
+%!            'jpg',                '',    bitviewer; ...
+%!            'jpeg',               '',    bitviewer; ...
+%!            'gif',                '',    bitviewer; ...
+%!            'svg',                '',    bitviewer; ...
+%!            'postscript',         '',    psviewer; ...
+%!            'eps',                '',    psviewer; ...
+%!            'epsc',               '',    psviewer; ...
+%!            'eps2',               '',    psviewer; ...
+%!            'epsc2',              '',    psviewer; ...
+%!            'epscairo',           '',    psviewer; ...
+%!            'pdf',                '',    pdfviewer; ...
+%!            'pdfcairo',           '',    pdfviewer; ...
+%!            'pslatex',            'tex', latexviewer; ...
+%!            'pstex',              'tex', texviewer; ...
+%!            'epslatex',           'tex', latexviewer; ...
+%!            'cairolatex',         'tex', latexviewer; ...
+%!            'pdflatex',           'tex', latexviewer; ...
+%!            'pslatexstandalone',  'tex', salatexviewer; ...
+%!            'epslatexstandalone', 'tex', salatexviewer; ...
+%!            'pdflatexstandalone', 'tex', pdflatexviewer; ...
+%!            'texdraw',            'tex', texdrawviewer; ...
+%!            'emtex',              'tex', latexviewer; ...
+%!            'latex',              'tex', latexviewer; ...
+%!            'eepic',              'tex', latexviewer; ...
+%!            'pstricks',           'tex', pstricksviewer; ...
+%!            'tikz',               'tex', tikzviewer; ...
+%!            'tikzstandalone',     'tex', pdflatexviewer; ...
+%!            'fig',                '',    xfigviewer; ...
+%!            'tkcanvas',           '',    tktclviewer; ...
+%!            'canvas',             '',    htmlviewer; ...
+%!            'cgm',                '',    bitviewer; ...
+%!            'context',            '',    bitviewer; ...
+%!            'corel',              '',    bitviewer; ...
+%!            'dxf',                '',    bitviewer; ...
+%!            'emf',                '',    bitviewer; ...
+%!            'hpgl',               '',    bitviewer; ...
+%!            'lua',                '',    bitviewer; ...
+%!            'mf',                 '',    bitviewer; ...
+%!            'mp',                 '',    bitviewer; ...
+%!            'pcl5',               '',    bitviewer; ...
+%!            'qms',                '',    bitviewer; ...
+%!            'tgif',               '',    bitviewer; ...
+%!            'tpic',               '',    bitviewer};
+%!
+%! opt = {'', '-mono', '-color', 'background [0,0,0]', ...
+%!        'background [1,1,1]', 'background [1/3 1/2 1]', ...
+%!        '-debug PRINTDEMO.DBG'};
+%!
+%! dev_idx = 1;
+%! opt_idx = [1];
+%!
+%! for i_gtlk = 1:length(gtlk)
+%!
+%!   graphics_toolkit (gtlk{i_gtlk});
+%!   fid = figure ();
+%!   set (fid, 'PaperUnits', 'inches');
+%!   set (fid, 'PaperPosition', [0 0 5 3]);
+%!
+%!   do
+%!
+%!     dev_ans = listdlg ('ListString',devlist(:,1), ...
+%!               'SelectionMode','Single', ...
+%!               'Name','Print Demo Device', ...
+%!               'InitialValue',dev_idx, ...
+%!               'PromptString',{'Choose device for which to print example'});
+%!
+%!     if ~isempty (dev_ans)
+%!
+%!       dev_idx = dev_ans;
+%!
+%!       opt_ans = listdlg ('ListString',opt, ...
+%!               'SelectionMode','Multiple', ...
+%!               'Name','Print Demo Device Options', ...
+%!               'InitialValue',opt_idx, ...
+%!               'PromptString',{'Choose options for the device'});
+%!
+%!       if ~isempty (opt_ans)
+%!
+%!         opt_idx = opt_ans;
+%!
+%!         subplot (1, 2, 1);
+%!         x = [0:35];
+%!         plot (x, x.^2, 'r-', x, flip(x).^2, 'g:');
+%!         subplot (1, 2, 2);
+%!         surf (peaks);
+%!         pause (0); ## Needed to cause drawnow before print()
+%!
+%!         cmdstr = ['print (fename,''-d' devlist{dev_idx,1} ''''];
+%!         for i_opt = opt_idx
+%!           if strfind (opt{i_opt}, 'background')
+%!             s = opt{i_opt};
+%!             set (get (gcf, 'Children'), 'color', ...
+%!                  eval (s(strfind (s,'[') : strfind (s,']'))));
+%!             pause (0); ## Needed to cause drawnow before print()
+%!           elseif ~isempty (opt{i_opt})
+%!             cmdstr = [cmdstr ',''' opt{i_opt} ''''];
+%!           endif
+%!         end
+%!         cmdstr = [cmdstr ');'];
+%!         try
+%!           fname = tmpnam ();
+%!           if ~isempty (devlist{dev_idx,2})
+%!             ename = devlist{dev_idx,2};
+%!           else
+%!             ename = devlist{dev_idx,1};
+%!           end
+%!           fename = [fname '.' ename];
+%!           eval (cmdstr);
+%!           sysstr = strrep(devlist{dev_idx,3}, '%f', fname);
+%!           sysstr = strrep(sysstr, '%e', ename);
+%!           system (sysstr);
+%!           system (['rm ' fname '*']);
+%!         catch message
+%!           printf ("\nFailed with command: %s\n", cmdstr);
+%!           printf (  "              fname: %s\n", fname);
+%!           message
+%!         end
+%!
+%!       endif
+%!
+%!     endif
+%!
+%!   until (isempty (dev_ans))
+%!
+%!   close (fid);
+%!
+%! endfor
+
diff --git a/scripts/plot/util/private/__gnuplot_print__.m b/scripts/plot/util/private/__gnuplot_print__.m
--- a/scripts/plot/util/private/__gnuplot_print__.m
+++ b/scripts/plot/util/private/__gnuplot_print__.m
@@ -67,7 +67,8 @@ function opts = __gnuplot_print__ (opts)
       else
         eps_drawnow (opts, opts.name, gp_opts);
       endif
-    case {"epslatex", "pslatex", "pstex", "epslatexstandalone"}
+    case {"emtex", "latex", "epslatex", "pslatex", "pstex",...
+          "epslatexstandalone", "cairolatex"}
       dot = find (opts.name == ".", 1, "last");
       n = find (opts.devopt == "l", 1);
       suffix = opts.devopt(1:n-1);
@@ -92,11 +93,36 @@ function opts = __gnuplot_print__ (opts)
         ## Gnuplot 4.0 wants a ".eps" suffix.
         suffix = "eps";
       endif
+      paperunits = get(opts.figure, 'paperunits');
+      paperposition = get(opts.figure, 'paperposition');
+      if (strcmp (paperunits, 'normalized'))
+        warning ('__gnuplot_print__: Normalized units treated as inches');
+        paperunits = 'inches';
+      endif
+      if (strcmp (paperunits, 'inches'))
+        xsize = paperposition(3);
+        xunit = 'in';
+        ysize = paperposition(4);
+        yunit = 'in';
+      elseif (strcmp (paperunits, 'centimeters'))
+        xsize = paperposition(3);
+        xunit = 'cm';
+        ysize = paperposition(4);
+        yunit = 'cm';
+      elseif (strcmp (paperunits, 'points'))
+        xsize = paperposition(3) / 72;
+        xunit = 'in';
+        ysize = paperposition(4) / 72;
+        yunit = 'in';
+      else
+        error ('__gnuplot_print__: Unknown paperunits %s', paperunits);
+      endif
+      gp_opts = sprintf("%s size %3.2f%s,%5.3f%s", gp_opts, xsize, xunit, ysize, yunit)
       local_drawnow ([term " " gp_opts],
                      strcat (name, ".", suffix), opts);
-    case "tikz"
+    case {"tikz", "tikzstandalone"}
       if (__gnuplot_has_terminal__ ("tikz"))
-        local_drawnow (["lua tikz " gp_opts], opts.name, opts);
+        local_drawnow (['lua ' strrep(opts.devopt,'standalone',' standalone') ' ' gp_opts], opts.name, opts);
       else
         error (sprintf ("print:no%soutput", opts.devopt),
                "print.m: '%s' output is not available for gnuplot-%s",
@@ -106,7 +132,7 @@ function opts = __gnuplot_print__ (opts)
       local_drawnow (["svg dynamic " gp_opts], opts.name, opts);
     case {"aifm", "corel", "eepic", "emf", "fig"}
       local_drawnow ([opts.devopt " " gp_opts], opts.name, opts);
-    case {"pdfcairo", "pngcairo"}
+    case {"epscairo", "pdfcairo", "pngcairo", "eepic"}
       if (__gnuplot_has_terminal__ (opts.devopt))
         local_drawnow ([opts.devopt " " gp_opts], opts.name, opts);
       else
@@ -114,9 +140,24 @@ function opts = __gnuplot_print__ (opts)
                "print.m: '%s' output is not available for gnuplot-%s",
                upper (opts.devopt), __gnuplot_version__ ());
       endif
-    case {"canvas", "dxf", "hpgl", "mf", "gif", "pstricks", "texdraw"}
+    case {"canvas", "dxf", "hpgl", "jpeg", "jpg", "mf", "gif", "postscript",...
+          "pstricks", "texdraw", "tkcanvas"}
       local_drawnow ([opts.devopt " " gp_opts], opts.name, opts);
     case opts.ghostscript.device
+      if (any (strcmp ({"png16m"}, opts.devopt)) && ...
+          __gnuplot_has_terminal__ ("png"))
+        opts.devopt = "png";
+        gp_opts = font_spec (opts);
+        local_drawnow ([opts.devopt " " gp_opts], opts.name, opts);
+        continue;
+      endif
+      if (any (strcmp ({"pdfwrite"}, opts.devopt)) && ...
+          __gnuplot_has_terminal__ ("pdfcairo"))
+        opts.devopt = "pdfcairo";
+        gp_opts = font_spec (opts);
+        local_drawnow ([opts.devopt " " gp_opts], opts.name, opts);
+        continue;
+      endif
       gp_opts = font_spec (opts, "devopt", "eps");
       opts.ghostscript.output = opts.name;
       opts.ghostscript.source = [tempname() ".eps"];
@@ -237,11 +278,15 @@ function f = font_spec (opts, varargin)
       elseif (! isempty (opts.font))
         f = sprintf ('font "%s"', opts.font);
       elseif (! isempty (opts.fontsize))
-        f = sprintf ("fsize %d", f, opts.fontsize);
+        f = sprintf ("fsize %d", opts.fontsize);
       endif
-    case {"pdfcairo", "pngcairo"}
-      if (! isempty (opts.font))
+    case {"gif", "jpeg", "png", "pdfcairo", "pngcairo"}
+      if (! isempty (opts.font) && ! isempty (opts.fontsize))
+        f = sprintf ('font "%s,%d"', opts.font, opts.fontsize);
+      elseif (! isempty (opts.font))
         f = sprintf ('font "%s"', opts.font);
+      elseif (! isempty (opts.fontsize))
+        f = sprintf ('font ",%d"', opts.fontsize);
       endif
     case {"epslatex", "epslatexstandalone"}
       if (! isempty (opts.font) && ! isempty (opts.fontsize))
@@ -255,14 +300,6 @@ function f = font_spec (opts, varargin)
       if (! isempty (opts.fontsize))
         f = sprintf ("%d", opts.fontsize);
       endif
-    case {"gif", "jpeg", "png"}
-      if (! isempty (opts.font) && ! isempty (opts.fontsize))
-        f = sprintf ('font "%s ,%d"', opts.font, opts.fontsize);
-      elseif (! isempty (opts.font))
-        f = sprintf ('font "%s"', opts.font);
-      elseif (! isempty (opts.fontsize))
-        f = sprintf ('font "%d"', opts.fontsize);
-      endif
     case "emf"
       if (! isempty (opts.font) && ! isempty (opts.fontsize))
         f = sprintf ('"%s" %d', opts.font, opts.fontsize);
diff --git a/scripts/plot/util/private/__go_draw_axes__.m b/scripts/plot/util/private/__go_draw_axes__.m
--- a/scripts/plot/util/private/__go_draw_axes__.m
+++ b/scripts/plot/util/private/__go_draw_axes__.m
@@ -1731,7 +1731,7 @@ function __go_draw_axes__ (h, plot_strea
             fputs (plot_stream, "\n\n");
           endif
           fprintf (plot_stream, "%.15g %.15g %.15g %.15g\n", data{i}(:,j).');
-          fprintf (plot_stream, "%.15g %.15g %.15g %.15g\n\n",data{i}(:,j+1).');
+          fprintf (plot_stream, "%.15g %.15g %.15g %.15g\n\n", data{i}(:,j+1).');
           fprintf (plot_stream, "%.15g %.15g %.15g %.15g\n", data{i}(:,j+2).');
           fprintf (plot_stream, "%.15g %.15g %.15g %.15g\n", data{i}(:,j+3).');
         endfor
@@ -1743,6 +1743,7 @@ function __go_draw_axes__ (h, plot_strea
                                 have_cdata(i));
       endif
     endfor
+    fputs (plot_stream, "\n");
   else
     fputs (plot_stream, "plot \"-\";\nInf Inf\ne\n");
   endif
@@ -1787,7 +1788,7 @@ function spacing_spec = create_spacingsp
 endfunction
 
 function fontspec = create_fontspec (f, s, gp_term)
-  if (strcmp (f, "*") || strcmp (gp_term, "tikz"))
+  if (isempty (f) || strcmp (f, "*") || strcmp (gp_term, "tikz"))
     fontspec = sprintf ("font \",%d\"", s);
   else
     fontspec = sprintf ("font \"%s,%d\"", f, s);
@@ -2025,14 +2026,9 @@ function __gnuplot_write_data__ (plot_st
 
   ## DATA is already transposed.
 
-  ## FIXME: this may need to be converted to C++ for speed.
-
   ## Convert NA elements to normal NaN values because fprintf writes
   ## "NA" and that confuses gnuplot.
-  idx = find (isna (data));
-  if (any (idx))
-    data(idx) = NaN;
-  endif
+  data(isna (data)) = NaN;
 
   if (nd == 2)
     fwrite (plot_stream, data, "float64");
@@ -2240,7 +2236,7 @@ endfunction
 
 function [f, s, fnt, it, bld] = get_fontname_and_size (t)
   if (isempty (t.fontname) || strcmp (t.fontname, "*"))
-    fnt = "{}";
+    fnt = "";
   else
     fnt = t.fontname;
   endif
diff --git a/scripts/plot/util/private/__go_draw_figure__.m b/scripts/plot/util/private/__go_draw_figure__.m
--- a/scripts/plot/util/private/__go_draw_figure__.m
+++ b/scripts/plot/util/private/__go_draw_figure__.m
@@ -139,7 +139,13 @@ function __go_draw_figure__ (h, plot_str
               unwind_protect
                 set (kids(i), "units", "normalized");
                 fg = get (kids(i), "color");
-                if (isnumeric (fg) && strcmp (get (kids(i), "visible"), "on"))
+                ## The test against [1 1 1] circumvents gnuplot bug (up to at
+                ## least v5.0) which maps white to black for "-mono" because
+                ## of incorrect color to gray math conversion.
+                if (isnumeric (fg) && strcmp (get (kids(i), "visible"), "on") && ...
+                    ((! isnumeric (bg) && ! mono) || ...
+                     (isnumeric (bg) && ! isequal (fg, bg)) || ...
+                     (mono && ! isequal (fg, [1 1 1]))))
                   fprintf (plot_stream, "set obj 2 rectangle from graph 0,0 to graph 1,1 behind fc rgb \"#%02x%02x%02x\" fs solid noborder\n", round (255 * fg));
                   fg_is_set = true;
                   fg_was_set = true;
diff --git a/scripts/plot/util/private/__print_parse_opts__.m b/scripts/plot/util/private/__print_parse_opts__.m
--- a/scripts/plot/util/private/__print_parse_opts__.m
+++ b/scripts/plot/util/private/__print_parse_opts__.m
@@ -115,11 +115,11 @@ function arg_st = __print_parse_opts__ (
       elseif (length (arg) > 2 && arg(1:2) == "-P")
         arg_st.printer = arg;
       elseif (strncmp (arg, "-EPSTOOL:", 9))
-        arg_st.epstool_binary = arg{10:end};
+        arg_st.epstool_binary = arg(10:end);
       elseif (strncmp (arg, "-FIG2DEV:", 9))
-        arg_st.fig2dev_binary = arg{10:end};
+        arg_st.fig2dev_binary = arg(10:end);
       elseif (strncmp (arg, "-PSTOEDIT:", 9))
-        arg_st.pstoedit_binary = arg{10:end};
+        arg_st.pstoedit_binary = arg(10:end);
       elseif (strncmpi (arg, "-textalphabits=", 15))
         n = find (arg == "=");
         if (! isempty (n) && n == numel (arg) - 1 && any (arg(end) == "124"))
@@ -315,7 +315,7 @@ function arg_st = __print_parse_opts__ (
       ## pstoedit throws errors if the EPS file isn't cropped
       arg_st.ghostscript.epscrop = true;
     endif
-  elseif (all (! strcmp (arg_st.devopt, dev_list)))
+  elseif (! any (strcmp (arg_st.devopt, dev_list)))
     ## Assume we are formating output for a printer
     arg_st.formatted_for_printing = true;
     arg_st.ghostscript.device = arg_st.devopt;
exporting patch:
<fdopen>
