exporting patches:
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1444589516 -7200
#      Sun Oct 11 20:51:56 2015 +0200
# Node ID fa1e0e1e94dc5664a87a4dd274fbf409810388fb
# Parent  a5ab31b52ae84ad05a8dae326f0766097f5b4600
get screenpixelsperinch only once, and use /=

diff -r a5ab31b52ae8 -r fa1e0e1e94dc scripts/plot/util/__gnuplot_drawnow__.m
--- a/scripts/plot/util/__gnuplot_drawnow__.m	Mon Nov 23 20:50:07 2015 -0500
+++ b/scripts/plot/util/__gnuplot_drawnow__.m	Sun Oct 11 20:51:56 2015 +0200
@@ -185,8 +185,9 @@
                || any (strcmp (term, {"canvas", "emf", "gif", "jpeg", ...
                                       "pbm", "png", "pngcairo", "svg"}))))
           ## Convert to inches
-          gnuplot_pos = gnuplot_pos / get (0, "screenpixelsperinch");
-          gnuplot_size = gnuplot_size / get (0, "screenpixelsperinch");
+          pixelsperinch =  get(0, "ScreenPixelsPerInch");
+          gnuplot_pos /= pixelsperinch;
+          gnuplot_size /= pixelsperinch;
         endif
         if (all (gnuplot_size > 0))
           terminals_with_size = {"canvas", "emf", "epslatex", "fig", ...
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1444593076 -7200
#      Sun Oct 11 21:51:16 2015 +0200
# Node ID 7a4e380cbdd084a7ac1dfa557cc018d825cdd2af
# Parent  fa1e0e1e94dc5664a87a4dd274fbf409810388fb
base papersize conversion on screenpixelsperinch (fix pdf pagesize)

diff -r fa1e0e1e94dc -r 7a4e380cbdd0 scripts/plot/util/private/__ghostscript__.m
--- a/scripts/plot/util/private/__ghostscript__.m	Sun Oct 11 20:51:56 2015 +0200
+++ b/scripts/plot/util/private/__ghostscript__.m	Sun Oct 11 21:51:16 2015 +0200
@@ -94,8 +94,9 @@
     if (ischar (opts.papersize))
       gs_opts = sprintf ("%s -sPAPERSIZE=%s", gs_opts, opts.papersize);
     elseif (isnumeric (opts.papersize) && numel (opts.papersize) == 2)
+      papersize_pt = fix (opts.papersize * 72 / get (0 , "screenpixelsperinch"));
       gs_opts = sprintf ("%s -dDEVICEWIDTHPOINTS=%d -dDEVICEHEIGHTPOINTS=%d",
-                         gs_opts, fix (opts.papersize));
+                         gs_opts, papersize_pt);
       if (opts.papersize(1) > opts.papersize(2))
         ## Lanscape mode: This option will result in automatic rotation of the
         ##                document page if the requested page size matches one
diff -r fa1e0e1e94dc -r 7a4e380cbdd0 scripts/plot/util/private/__print_parse_opts__.m
--- a/scripts/plot/util/private/__print_parse_opts__.m	Sun Oct 11 20:51:56 2015 +0200
+++ b/scripts/plot/util/private/__print_parse_opts__.m	Sun Oct 11 21:51:16 2015 +0200
@@ -560,7 +560,7 @@
                    9.8, 13.9;  6.9,  9.8;  9.0, 12.0; 12.0, 18.0;
                   18.0, 24.0; 24.0, 36.0; 36.0, 48.0;  8.5, 11.0;
                   11.0, 17.0; 18.0, 24.0; 24.0, 36.0; 36.0, 48.0;
-                  11.0, 17.0] * 72;
+                  11.0, 17.0];
   endif
 
   papertype = get (hfig, "papertype");
@@ -568,7 +568,7 @@
   paperposition = get (hfig, "paperposition");
   if (strcmp (papertype, "<custom>"))
     papersize = get (hfig, "papersize");
-    papersize = convert2points (papersize , paperunits);
+    papersize = convert2pixels (papersize , paperunits);
   else
     papersize = papersizes (strcmp (papertypes, papertype), :);
   endif
@@ -576,7 +576,7 @@
   if (strcmp (paperunits, "normalized"))
     paperposition .*= papersize([1,2,1,2]);
   else
-    paperposition = convert2points (paperposition, paperunits);
+    paperposition = convert2pixels (paperposition, paperunits);
   endif
 
   ## FIXME: This will be obsoleted by listeners for paper properties.
@@ -608,12 +608,13 @@
 
 endfunction
 
-function value = convert2points (value, units)
+function value = convert2pixels (value, units)
+  ## units conversions are based on screenpixelsperinch, for consistency with listeners
   switch (units)
     case "inches"
-      value *= 72;
+      value *= get (0, "screenpixelsperinch");
     case "centimeters"
-      value *= 72 / 2.54;
+      value *= get (0, "screenpixelsperinch") / 2.54;
     case "normalized"
       error ("print:customnormalized",
              "print.m: papersize=='<custom>' and paperunits='normalized' may not be combined");
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1444852324 -7200
#      Wed Oct 14 21:52:04 2015 +0200
# Node ID a48b0a028f2b859980c654ddde04e4c190605bd1
# Parent  7a4e380cbdd084a7ac1dfa557cc018d825cdd2af
72 => screenpixelsperinch, for print -Ssx,sy file.png

diff -r 7a4e380cbdd0 -r a48b0a028f2b scripts/plot/util/private/__print_parse_opts__.m
--- a/scripts/plot/util/private/__print_parse_opts__.m	Sun Oct 11 21:51:16 2015 +0200
+++ b/scripts/plot/util/private/__print_parse_opts__.m	Wed Oct 14 21:52:04 2015 +0200
@@ -361,7 +361,7 @@
       ## Work around the eps bbox having whole numbers (both gnuplot & gl2ps).
       arg_st.scalefontsize = arg_st.ghostscript.resolution / 72;
     endif
-    arg_st.ghostscript.resolution = 72;
+    arg_st.ghostscript.resolution = get (0, "screenpixelsperinch");
     arg_st.ghostscript.papersize = arg_st.canvas_size;
     arg_st.ghostscript.epscrop = true;
     arg_st.ghostscript.pageoffset = [0, 0];
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1445021699 -7200
#      Fri Oct 16 20:54:59 2015 +0200
# Node ID c6d74ee642813f440c0022fc2aaf55271110a38a
# Parent  a48b0a028f2b859980c654ddde04e4c190605bd1
set and use opts.ghostscript.formatted_for_printing instead of setting papersize to "" for bitmaps

diff -r a48b0a028f2b -r c6d74ee64281 scripts/plot/util/private/__ghostscript__.m
--- a/scripts/plot/util/private/__ghostscript__.m	Wed Oct 14 21:52:04 2015 +0200
+++ b/scripts/plot/util/private/__ghostscript__.m	Fri Oct 16 20:54:59 2015 +0200
@@ -60,12 +60,6 @@
     opts.(args{n}) = args{n+1};
   endfor
 
-  if (isempty (opts.papersize))
-    format_for_printer = false;
-  else
-    format_for_printer = true;
-  endif
-
   gs_opts = ["-dQUIET -dNOPAUSE -dBATCH -dSAFER -sDEVICE=" opts.device];
 
   if (! isempty (opts.level) && ismember (opts.level, [1, 2, 3]))
@@ -77,7 +71,9 @@
     gs_opts = sprintf ("%s -dTextAlphaBits=%d -dGraphicsAlphaBits=%d",
                        gs_opts, fix (opts.antialiasing_textalphabits),
                        fix (opts.antialiasing_graphicsalphabits));
-    gs_opts = sprintf ("%s -r%dx%d", gs_opts, fix ([1, 1] * opts.resolution));
+    gs_opts = sprintf ("%s -r%gx%g", gs_opts, [1, 1] * opts.resolution);
+    ## need set the exact geometry, in order to avoid small roundoff errors
+    gs_opts = sprintf ("%s -g%dx%d", gs_opts, opts.papersize);
   elseif (any (strcmp (opts.device, {"pswrite", "ps2write", "pdfwrite"})))
     gs_opts = sprintf ("%s -dEmbedAllFonts=true", gs_opts);
     if (strcmp (opts.device, "pdfwrite"))
@@ -90,7 +86,7 @@
     ## papersize is specified by the eps bbox
     gs_opts = sprintf ("%s -dEPSCrop", gs_opts);
   endif
-  if (format_for_printer)
+  if (opts.formatted_for_printing)
     if (ischar (opts.papersize))
       gs_opts = sprintf ("%s -sPAPERSIZE=%s", gs_opts, opts.papersize);
     elseif (isnumeric (opts.papersize) && numel (opts.papersize) == 2)
@@ -169,7 +165,7 @@
       endif
     endif
   endif
-  if (! isempty (offsetfile) && format_for_printer)
+  if (! isempty (offsetfile) && opts.formatted_for_printing)
     cmd = sprintf ("%s %s", cmd, offsetfile);
   endif
   if (! isempty (opts.source))
diff -r a48b0a028f2b -r c6d74ee64281 scripts/plot/util/private/__print_parse_opts__.m
--- a/scripts/plot/util/private/__print_parse_opts__.m	Wed Oct 14 21:52:04 2015 +0200
+++ b/scripts/plot/util/private/__print_parse_opts__.m	Fri Oct 16 20:54:59 2015 +0200
@@ -43,6 +43,7 @@
   arg_st.ghostscript.debug = false;
   arg_st.ghostscript.device = "";
   arg_st.ghostscript.epscrop = true;
+  arg_st.ghostscript.formatted_for_printing = false; # same as arg_st.formatted_for_printing
   arg_st.ghostscript.level = 2;
   arg_st.ghostscript.output = "";
   arg_st.ghostscript.papersize = "";
@@ -368,9 +369,10 @@
   endif
 
   if (arg_st.formatted_for_printing)
+    arg_st.ghostscript.formatted_for_printing = true;
     arg_st.ghostscript.resolution = [];
   else
-    arg_st.ghostscript.papersize = "";
+    arg_st.ghostscript.formatted_for_printing = false;
     arg_st.ghostscript.pageoffset = [0, 0];
   endif
 
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1445094123 -7200
#      Sat Oct 17 17:02:03 2015 +0200
# Node ID 811cf7875cfa14bcef20d3179674e4aef1ba0685
# Parent  c6d74ee642813f440c0022fc2aaf55271110a38a
set the geometry only when explicitely given

diff -r c6d74ee64281 -r 811cf7875cfa scripts/plot/util/private/__ghostscript__.m
--- a/scripts/plot/util/private/__ghostscript__.m	Fri Oct 16 20:54:59 2015 +0200
+++ b/scripts/plot/util/private/__ghostscript__.m	Sat Oct 17 17:02:03 2015 +0200
@@ -72,8 +72,11 @@
                        gs_opts, fix (opts.antialiasing_textalphabits),
                        fix (opts.antialiasing_graphicsalphabits));
     gs_opts = sprintf ("%s -r%gx%g", gs_opts, [1, 1] * opts.resolution);
-    ## need set the exact geometry, in order to avoid small roundoff errors
-    gs_opts = sprintf ("%s -g%dx%d", gs_opts, opts.papersize);
+    if isnumeric (opts.papersize)
+      ## size has been given with the "-Ssx,xy" option.
+      ## need to set the exact geometry, in order to avoid small roundoff errors
+      gs_opts = sprintf ("%s -g%dx%d", gs_opts, opts.papersize);
+    endif
   elseif (any (strcmp (opts.device, {"pswrite", "ps2write", "pdfwrite"})))
     gs_opts = sprintf ("%s -dEmbedAllFonts=true", gs_opts);
     if (strcmp (opts.device, "pdfwrite"))
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1445448608 -7200
#      Wed Oct 21 19:30:08 2015 +0200
# Node ID b3a2f381fb0d74d9fe52bb0fe1dc0a434a4aecab
# Parent  811cf7875cfa14bcef20d3179674e4aef1ba0685
print the intermediate eps output from gl2ps to a debug file

diff -r 811cf7875cfa -r b3a2f381fb0d scripts/plot/util/private/__opengl_print__.m
--- a/scripts/plot/util/private/__opengl_print__.m	Sat Oct 17 17:02:03 2015 +0200
+++ b/scripts/plot/util/private/__opengl_print__.m	Wed Oct 21 19:30:08 2015 +0200
@@ -161,6 +161,10 @@
 
   for n = 1:numel (pipeline)
     if (opts.debug)
+      ## print the intermediate eps output from gl2ps to a debug file
+      [debug_file_dir, debug_file_base] = fileparts(opts.debug_file);
+      debug_file_eps = fullfile(debug_file_dir, [debug_file_base ".eps"]);
+      pipeline{n} = sprintf("tee %s | %s", debug_file_eps, pipeline{n});
       fprintf ("opengl-pipeline: '%s'\n", pipeline{n});
     endif
 
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1445770168 -3600
#      Sun Oct 25 11:49:28 2015 +0100
# Node ID 3224503a8500490377ce979e081130ed0f12a822
# Parent  b3a2f381fb0d74d9fe52bb0fe1dc0a434a4aecab
round-off papersize for gs -g<sx>,<sy>

diff -r b3a2f381fb0d -r 3224503a8500 scripts/plot/util/private/__ghostscript__.m
--- a/scripts/plot/util/private/__ghostscript__.m	Wed Oct 21 19:30:08 2015 +0200
+++ b/scripts/plot/util/private/__ghostscript__.m	Sun Oct 25 11:49:28 2015 +0100
@@ -75,7 +75,8 @@
     if isnumeric (opts.papersize)
       ## size has been given with the "-Ssx,xy" option.
       ## need to set the exact geometry, in order to avoid small roundoff errors
-      gs_opts = sprintf ("%s -g%dx%d", gs_opts, opts.papersize);
+      ## note: gs -g<sx>,<sy> requires integers
+      gs_opts = sprintf ("%s -g%dx%d", gs_opts, round(opts.papersize));
     endif
   elseif (any (strcmp (opts.device, {"pswrite", "ps2write", "pdfwrite"})))
     gs_opts = sprintf ("%s -dEmbedAllFonts=true", gs_opts);
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1445770892 -3600
#      Sun Oct 25 12:01:32 2015 +0100
# Node ID 5312b0bbb654d65d1b86ca6bf358455f9364f96c
# Parent  3224503a8500490377ce979e081130ed0f12a822
specific record for the -S<sx>,<sy> option usage

diff -r 3224503a8500 -r 5312b0bbb654 scripts/plot/util/private/__ghostscript__.m
--- a/scripts/plot/util/private/__ghostscript__.m	Sun Oct 25 11:49:28 2015 +0100
+++ b/scripts/plot/util/private/__ghostscript__.m	Sun Oct 25 12:01:32 2015 +0100
@@ -72,7 +72,7 @@
                        gs_opts, fix (opts.antialiasing_textalphabits),
                        fix (opts.antialiasing_graphicsalphabits));
     gs_opts = sprintf ("%s -r%gx%g", gs_opts, [1, 1] * opts.resolution);
-    if isnumeric (opts.papersize)
+    if opts.size_from_cmd_line
       ## size has been given with the "-Ssx,xy" option.
       ## need to set the exact geometry, in order to avoid small roundoff errors
       ## note: gs -g<sx>,<sy> requires integers
diff -r 3224503a8500 -r 5312b0bbb654 scripts/plot/util/private/__print_parse_opts__.m
--- a/scripts/plot/util/private/__print_parse_opts__.m	Sun Oct 25 11:49:28 2015 +0100
+++ b/scripts/plot/util/private/__print_parse_opts__.m	Sun Oct 25 12:01:32 2015 +0100
@@ -49,6 +49,7 @@
   arg_st.ghostscript.papersize = "";
   arg_st.ghostscript.pageoffset = [];
   arg_st.ghostscript.resolution = 150;
+  arg_st.ghostscript.size_from_cmd_line = false;
   arg_st.ghostscript.antialiasing = false;
   arg_st.ghostscript.antialiasing_textalphabits = 4;
   arg_st.ghostscript.antialiasing_graphicsalphabits = 4;
@@ -153,6 +154,7 @@
         endif
       elseif (length (arg) > 2 && arg(1:2) == "-S")
         arg_st.canvas_size = str2num (arg(3:end));
+        arg_st.ghostscript.size_from_cmd_line = true;
       elseif (length (arg) > 2 && arg(1:2) == "-r")
         arg_st.ghostscript.resolution = str2double (arg(3:end));
       elseif (length (arg) > 2 && arg(1:2) == "-f")
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1445804047 -3600
#      Sun Oct 25 21:14:07 2015 +0100
# Node ID 86d62705c6a7304549c5026e36e3bb69997dbc79
# Parent  5312b0bbb654d65d1b86ca6bf358455f9364f96c
scale all positions by 72 / screenpixelsperinch

diff -r 5312b0bbb654 -r 86d62705c6a7 scripts/plot/util/private/__opengl_print__.m
--- a/scripts/plot/util/private/__opengl_print__.m	Sun Oct 25 12:01:32 2015 +0100
+++ b/scripts/plot/util/private/__opengl_print__.m	Sun Oct 25 21:14:07 2015 +0100
@@ -25,6 +25,13 @@
 
   dos_shell = (ispc () && ! isunix ());
 
+  ## gl2ps takes positions in pixels as if they were points (1 pt = 1 inch / 72)
+  ## to get the right size after printing, the positions must be rescaled
+  sppi = get(0, "screenpixelsperinch");
+  h_list = num2cell(findall (opts.figure, "-property", "position"));
+  old_positions = cellfun(@(h) get(h, "position"), h_list, "UniformOutput", false);
+  cellfun(@(h, old_pos) set(h, "position", old_pos * 72 / sppi), h_list, old_positions)
+  
   set (0, "currentfigure", opts.figure);
   drawnow ("expose");
 
@@ -181,5 +188,7 @@
     opts.latex_standalone (opts);
   endif
 
+  ## set the positions back to normal
+  cellfun(@(h, old_pos) set(h, "position", old_pos), h_list, old_positions)
 endfunction
 
# HG changeset patch
# User Daniel J Sebald <daniel.sebald@ieee.org>
# Date 1437113029 18000
#      Fri Jul 17 01:03:49 2015 -0500
# Node ID 5f6e51677910da2f0d2f6a8c6dac54914c783311
# Parent  86d62705c6a7304549c5026e36e3bb69997dbc79
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.  Move the special condition
for the lua terminal to __gnuplot_print__.m.

* print.m (print): Clarify in the help text that it is pslatexstandalone, that
isn't available in gnuplot.  pdflatex and pdflatexstandalone device outputs
have been added via the cairolatex terminal.  Also indicate paperunits and
paperposition control the size latex-based devices.  Add comments 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_has_terminal__.m (__gnuplot_has_terminal__): Map term pdflatex to
cairolatex before checking gnuplot support.

* __gnuplot_print__.m (__gnuplot_print__): Add "emtex", "latex", "epslatex",
"cairolatex", "pdflatex" and "pdflatexstandalone" to the latex devices case.
Do better parse test for suffix.  For term based on "pdflatex", map to
"cairolatex pdf".  For the tex-based cases make figure paperunits and position
control the eventual size after processing with latex.  Add "lua" and
"tikzstandalone" to the "tikz" case and add "standalone" option if warranted.
If the term is "lua", map to tikz (code from __gnuplot_drawnow__.m).  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.

* __gnuplot_draw_axes__.m (__gnuplot_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 "{}".

* __gnuplot_draw_figure__.m (__gnuplot_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 -r 86d62705c6a7 -r 5f6e51677910 scripts/plot/util/__gnuplot_drawnow__.m
--- a/scripts/plot/util/__gnuplot_drawnow__.m	Sun Oct 25 21:14:07 2015 +0100
+++ b/scripts/plot/util/__gnuplot_drawnow__.m	Fri Jul 17 01:03:49 2015 -0500
@@ -39,11 +39,11 @@
       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);
         __gnuplot_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);
           __gnuplot_draw_figure__ (h, fid, enhanced, mono);
         endif
       else
@@ -79,9 +79,10 @@
       ## 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
     __gnuplot_draw_figure__ (h, plot_stream(1), enhanced, mono);
     fflush (plot_stream(1));
@@ -106,7 +107,7 @@
 
 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)
@@ -118,11 +119,6 @@
     ## passed on to gnuplot.  The terminal may respect the graphics toolkit.
     [term, opts_str] = gnuplot_trim_term (term);
     term = lower (term);
-    if (strcmp (term, "lua"))
-      ## Replace "lua tikz" with just "tikz"
-      term = "tikz";
-      opts_str = strrep (opts_str, "tikz", "");
-    endif
   endif
 
   if (strfind (opts_str, "noenhanced"))
@@ -267,14 +263,34 @@
       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
@@ -296,6 +312,7 @@
         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.
@@ -321,7 +338,7 @@
         || 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
@@ -329,7 +346,7 @@
       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 -r 86d62705c6a7 -r 5f6e51677910 scripts/plot/util/print.m
--- a/scripts/plot/util/print.m	Sun Oct 25 21:14:07 2015 +0100
+++ b/scripts/plot/util/print.m	Fri Jul 17 01:03:49 2015 -0500
@@ -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{pslatexstandalone} device is not available with the
+## Gnuplot toolkit.  (See @samp{epslatexstandalone} instead.)   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,211 @@
   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}',...
+%!                      '\author{Octave}',...
+%!                      '\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 = strrep (latexviewer, '\LaTeX', 'PDF \LaTeX');
+%!   pdflatexviewer = strrep (pdflatexviewer, 'PostScript', 'PDF');
+%!   pdflatexviewer = strrep (pdflatexviewer, 'latex -output-directory', 'pdflatex -output-directory');
+%!   pdflatexviewer = strrep (pdflatexviewer, '%f-sa.dvi', '%f-sa.pdf');
+%!   pdflatexviewer = strrep (pdflatexviewer, 'xdvi %f-sa', strrep(pdfviewer,'%f.%e','%f-sa.pdf'));
+%! sapdflatexviewer = ['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');
+%! satikzviewer = strrep (latexviewer, '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', pdflatexviewer; ...
+%!            'pslatexstandalone',  'tex', salatexviewer; ...
+%!            'epslatexstandalone', 'tex', salatexviewer; ...
+%!            'pdflatexstandalone', 'tex', sapdflatexviewer; ...
+%!            'texdraw',            'tex', texdrawviewer; ...
+%!            'emtex',              'tex', latexviewer; ...
+%!            'latex',              'tex', latexviewer; ...
+%!            'eepic',              'tex', latexviewer; ...
+%!            'pstricks',           'tex', pstricksviewer; ...
+%!            'tikz',               'tex', tikzviewer; ...
+%!            'tikzstandalone',     'tex', sapdflatexviewer; ...
+%!            'lua',                'tex', tikzviewer; ...
+%!            'fig',                '',    xfigviewer; ...
+%!            'tkcanvas',           '',    tktclviewer; ...
+%!            'canvas',             '',    htmlviewer; ...
+%!            'cgm',                '',    bitviewer; ...
+%!            'context',            '',    bitviewer; ...
+%!            'corel',              '',    bitviewer; ...
+%!            'dxf',                '',    bitviewer; ...
+%!            'emf',                '',    bitviewer; ...
+%!            'hpgl',               '',    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 -r 86d62705c6a7 -r 5f6e51677910 scripts/plot/util/private/__gnuplot_draw_axes__.m
--- a/scripts/plot/util/private/__gnuplot_draw_axes__.m	Sun Oct 25 21:14:07 2015 +0100
+++ b/scripts/plot/util/private/__gnuplot_draw_axes__.m	Fri Jul 17 01:03:49 2015 -0500
@@ -1731,7 +1731,7 @@
             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 @@
                                 have_cdata(i));
       endif
     endfor
+    fputs (plot_stream, "\n");
   else
     fputs (plot_stream, "plot \"-\";\nInf Inf\ne\n");
   endif
@@ -1787,7 +1788,7 @@
 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 @@
 
   ## 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 @@
 
 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 -r 86d62705c6a7 -r 5f6e51677910 scripts/plot/util/private/__gnuplot_draw_figure__.m
--- a/scripts/plot/util/private/__gnuplot_draw_figure__.m	Sun Oct 25 21:14:07 2015 +0100
+++ b/scripts/plot/util/private/__gnuplot_draw_figure__.m	Fri Jul 17 01:03:49 2015 -0500
@@ -139,7 +139,13 @@
               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 -r 86d62705c6a7 -r 5f6e51677910 scripts/plot/util/private/__gnuplot_has_terminal__.m
--- a/scripts/plot/util/private/__gnuplot_has_terminal__.m	Sun Oct 25 21:14:07 2015 +0100
+++ b/scripts/plot/util/private/__gnuplot_has_terminal__.m	Fri Jul 17 01:03:49 2015 -0500
@@ -28,6 +28,9 @@
 
   term = strtrim (term);
   term = lower (strtok (term, " "));
+  if (strcmp (term, "pdflatex"))
+    term = "cairolatex";
+  endif
 
   if (__gnuplot_has_feature__ ("variable_GPVAL_TERMINALS"))
     if (nargin < 2)
diff -r 86d62705c6a7 -r 5f6e51677910 scripts/plot/util/private/__gnuplot_print__.m
--- a/scripts/plot/util/private/__gnuplot_print__.m	Sun Oct 25 21:14:07 2015 +0100
+++ b/scripts/plot/util/private/__gnuplot_print__.m	Fri Jul 17 01:03:49 2015 -0500
@@ -67,9 +67,14 @@
       else
         eps_drawnow (opts, opts.name, gp_opts);
       endif
-    case {"epslatex", "pslatex", "pstex", "epslatexstandalone"}
+    case {"emtex", "latex", "epslatex", "pslatex", "pstex",...
+          "epslatexstandalone", "cairolatex", "pdflatex",...
+          "pdflatexstandalone"}
       dot = find (opts.name == ".", 1, "last");
-      n = find (opts.devopt == "l", 1);
+      n = (strfind (opts.devopt, "latex"));
+      if isempty (n)
+        n = (strfind (opts.devopt, "tex"));
+      end
       suffix = opts.devopt(1:n-1);
       [ndir, name, ext] = fileparts (opts.name);
       if (isempty (ext))
@@ -88,23 +93,62 @@
                ext, lower (opts.devopt));
       endif
 
-      if (strfind (opts.devopt, "standalone"))
+      if (strfind (lower (opts.devopt), "standalone"))
         term = sprintf ("%s ",
                         strrep (opts.devopt, "standalone", " standalone"));
       else
         term = sprintf ("%s ", opts.devopt);
       endif
+      if (strncmp (term, "pdflatex ", 9))
+        ## Cairo terminal can generate pdf and latex
+        term = strrep (term, "pdflatex ", "cairolatex pdf ");
+      endif
       if (__gnuplot_has_feature__ ("epslatex_implies_eps_filesuffix"))
         suffix = "tex";
       else
         ## 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
+      switch paperunits
+      case {"inches"}
+        xsize = paperposition(3);
+        xunit = "in";
+        ysize = paperposition(4);
+        yunit = "in";
+      case {"centimeters"}
+        xsize = paperposition(3);
+        xunit = "cm";
+        ysize = paperposition(4);
+        yunit = "cm";
+      case {"points"}
+        xsize = paperposition(3) / 72;
+        xunit = "in";
+        ysize = paperposition(4) / 72;
+        yunit = "in";
+      otherwise
+        error ("__gnuplot_print__: Unknown paperunits %s", paperunits);
+      end
+      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 {"lua", "tikz", "tikzstandalone"}
+      if (strcmp (opts.devopt, "lua"))
+        ## Replace "lua tikz" with just "tikz"
+        term = "tikz";
+        gp_opts = strrep (gp_opts, "tikz", "");
+      else
+        term = opts.devopt;
+      endif
       if (__gnuplot_has_terminal__ ("tikz"))
-        local_drawnow (["lua tikz " gp_opts], opts.name, opts);
+        local_drawnow ([(strrep (term, "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",
@@ -114,7 +158,7 @@
       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
@@ -122,9 +166,24 @@
                "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"];
@@ -245,11 +304,15 @@
       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))
@@ -263,14 +326,6 @@
       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 -r 86d62705c6a7 -r 5f6e51677910 scripts/plot/util/private/__print_parse_opts__.m
--- a/scripts/plot/util/private/__print_parse_opts__.m	Sun Oct 25 21:14:07 2015 +0100
+++ b/scripts/plot/util/private/__print_parse_opts__.m	Fri Jul 17 01:03:49 2015 -0500
@@ -117,11 +117,11 @@
       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"))
@@ -318,7 +318,7 @@
       ## 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;
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1446883063 -3600
#      Sat Nov 07 08:57:43 2015 +0100
# Node ID 90801e918dc39043047141a7dfd72898e3808cf3
# Parent  5f6e51677910da2f0d2f6a8c6dac54914c783311
allow for more pdf viewers (added mupdf)

diff -r 5f6e51677910 -r 90801e918dc3 scripts/plot/util/print.m
--- a/scripts/plot/util/print.m	Fri Jul 17 01:03:49 2015 -0500
+++ b/scripts/plot/util/print.m	Sat Nov 07 08:57:43 2015 +0100
@@ -791,11 +791,14 @@
 %! % 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
+%!   if (system ('acroread -v > /dev/null') == 0)
+%!     pdfviewer = 'acroread %f.%e';
+%!   elseif (any (system ('xpdf -v >& /dev/null') == [0 99]))
+%!     pdfviewer = 'xpdf %f.%e';
+%!   elseif (system ("command -v mupdf") == 0)
+%!     pdfviewer = 'mupdf %f.%e';
+%!   else
+%!     warning("no pdf viewer found")
 %!   endif
 %! endif
 %! bitviewer = 'eog %f.%e';
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1446896791 -3600
#      Sat Nov 07 12:46:31 2015 +0100
# Node ID a123c7a073c8405c439a456097216bdea550b193
# Parent  90801e918dc39043047141a7dfd72898e3808cf3
do not change size, do not force cairo for png and pdf

diff -r 90801e918dc3 -r a123c7a073c8 scripts/plot/util/private/__gnuplot_print__.m
--- a/scripts/plot/util/private/__gnuplot_print__.m	Sat Nov 07 08:57:43 2015 +0100
+++ b/scripts/plot/util/private/__gnuplot_print__.m	Sat Nov 07 12:46:31 2015 +0100
@@ -109,33 +109,6 @@
         ## 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
-      switch paperunits
-      case {"inches"}
-        xsize = paperposition(3);
-        xunit = "in";
-        ysize = paperposition(4);
-        yunit = "in";
-      case {"centimeters"}
-        xsize = paperposition(3);
-        xunit = "cm";
-        ysize = paperposition(4);
-        yunit = "cm";
-      case {"points"}
-        xsize = paperposition(3) / 72;
-        xunit = "in";
-        ysize = paperposition(4) / 72;
-        yunit = "in";
-      otherwise
-        error ("__gnuplot_print__: Unknown paperunits %s", paperunits);
-      end
-      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 {"lua", "tikz", "tikzstandalone"}
@@ -170,20 +143,6 @@
           "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"];
# HG changeset patch
# User Ben Abbott <bpabbott@mac.com>
# Date 1447267260 -3600
#      Wed Nov 11 19:41:00 2015 +0100
# Node ID c5e030571631630b541f6b2a54a5421c6dde9465
# Parent  a123c7a073c8405c439a456097216bdea550b193
bring back the size setting, but only for non-ghostscript devices

diff -r a123c7a073c8 -r c5e030571631 scripts/plot/util/private/__gnuplot_print__.m
--- a/scripts/plot/util/private/__gnuplot_print__.m	Sat Nov 07 12:46:31 2015 +0100
+++ b/scripts/plot/util/private/__gnuplot_print__.m	Wed Nov 11 19:41:00 2015 +0100
@@ -47,6 +47,17 @@
   gp_opts = font_spec (opts);
 
   pipeline = "";
+  ## size settings are handled in __ghostscript__.m for the gs devices
+  if (! any(strcmp(lower (opts.devopt), opts.ghostscript.device)))
+    paperunits = get (opts.figure, "paperunits");
+    unwind_protect
+      set (opts.figure, "paperunits", "inches");
+      paperposition = get (opts.figure, "paperposition");
+    unwind_protect_cleanup
+      set (opts.figure, "paperunits", paperunits);
+    end_unwind_protect
+    gp_opts = sprintf ("%s size %3.2fin,%5.3fin", gp_opts, paperposition(3:4));
+  endif
 
   switch (lower (opts.devopt))
     case {"eps", "eps2", "epsc", "epsc2"}
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1448482301 -3600
#      Wed Nov 25 21:11:41 2015 +0100
# Node ID 1b91bdc53cd736f8b9c13ec55daebee97029d0a7
# Parent  c5e030571631630b541f6b2a54a5421c6dde9465
add labels and legend

diff -r c5e030571631 -r 1b91bdc53cd7 scripts/plot/util/print.m
--- a/scripts/plot/util/print.m	Wed Nov 11 19:41:00 2015 +0100
+++ b/scripts/plot/util/print.m	Wed Nov 25 21:11:41 2015 +0100
@@ -936,6 +936,16 @@
 %!         subplot (1, 2, 1);
 %!         x = [0:35];
 %!         plot (x, x.^2, 'r-', x, flip(x).^2, 'g:');
+%!         if strcmp(devlist{dev_idx,2}, "tex")
+%!           xlabel("$x_{label}$")
+%!           ylabel("$y_{label}$")
+%!           legend("$x^2$", "flipped")
+%!         else
+%!           xlabel("x_{label}")
+%!           ylabel("y_{label}")
+%!           legend("x^2", "flipped")
+%!         endif
+%!         legend("location", "north")
 %!         subplot (1, 2, 2);
 %!         surf (peaks);
 %!         pause (0); ## Needed to cause drawnow before print()
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1448482416 -3600
#      Wed Nov 25 21:13:36 2015 +0100
# Node ID 6e74affbab6eb9cc01b9a677c67e705da18c7d79
# Parent  1b91bdc53cd736f8b9c13ec55daebee97029d0a7
set PaperPositionMode to "auto"

diff -r 1b91bdc53cd7 -r 6e74affbab6e scripts/plot/util/print.m
--- a/scripts/plot/util/print.m	Wed Nov 25 21:11:41 2015 +0100
+++ b/scripts/plot/util/print.m	Wed Nov 25 21:13:36 2015 +0100
@@ -909,7 +909,8 @@
 %!   graphics_toolkit (gtlk{i_gtlk});
 %!   fid = figure ();
 %!   set (fid, 'PaperUnits', 'inches');
-%!   set (fid, 'PaperPosition', [0 0 5 3]);
+%!   set (fid, 'PaperSize', [5 3]);
+%!   set (fid, 'PaperPositionMode', 'auto');
 %!
 %!   do
 %!
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1448477802 -3600
#      Wed Nov 25 19:56:42 2015 +0100
# Node ID 08e7a39394ced9b0ec2ef02333dc387d55c81b58
# Parent  6e74affbab6eb9cc01b9a677c67e705da18c7d79
do not reposition objects with "data" units

diff -r 6e74affbab6e -r 08e7a39394ce scripts/plot/util/private/__opengl_print__.m
--- a/scripts/plot/util/private/__opengl_print__.m	Wed Nov 25 21:13:36 2015 +0100
+++ b/scripts/plot/util/private/__opengl_print__.m	Wed Nov 25 19:56:42 2015 +0100
@@ -28,7 +28,8 @@
   ## gl2ps takes positions in pixels as if they were points (1 pt = 1 inch / 72)
   ## to get the right size after printing, the positions must be rescaled
   sppi = get(0, "screenpixelsperinch");
-  h_list = num2cell(findall (opts.figure, "-property", "position"));
+  h_list = findall (gcf, "-property", "position", "-not", "units", "data");
+  h_list = num2cell (h_list);
   old_positions = cellfun(@(h) get(h, "position"), h_list, "UniformOutput", false);
   cellfun(@(h, old_pos) set(h, "position", old_pos * 72 / sppi), h_list, old_positions)
   
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1448660216 -3600
#      Fri Nov 27 22:36:56 2015 +0100
# Node ID 1204042c1f6fb562371741cf70d6b9090207b32b
# Parent  08e7a39394ced9b0ec2ef02333dc387d55c81b58
do not reposition objects with "normalized" units

diff -r 08e7a39394ce -r 1204042c1f6f scripts/plot/util/private/__opengl_print__.m
--- a/scripts/plot/util/private/__opengl_print__.m	Wed Nov 25 19:56:42 2015 +0100
+++ b/scripts/plot/util/private/__opengl_print__.m	Fri Nov 27 22:36:56 2015 +0100
@@ -28,7 +28,9 @@
   ## gl2ps takes positions in pixels as if they were points (1 pt = 1 inch / 72)
   ## to get the right size after printing, the positions must be rescaled
   sppi = get(0, "screenpixelsperinch");
-  h_list = findall (gcf, "-property", "position", "-not", "units", "data");
+  h_list = findall (gcf, "-property", "position", 
+                         "-not", "units", "data", 
+                         "-not", "units", "normalized");
   h_list = num2cell (h_list);
   old_positions = cellfun(@(h) get(h, "position"), h_list, "UniformOutput", false);
   cellfun(@(h, old_pos) set(h, "position", old_pos * 72 / sppi), h_list, old_positions)
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1448662680 -3600
#      Fri Nov 27 23:18:00 2015 +0100
# Node ID 13b2af5f2f994a1518653b2c16eb3e02fb553469
# Parent  1204042c1f6fb562371741cf70d6b9090207b32b
fix pageoffset

diff -r 1204042c1f6f -r 13b2af5f2f99 scripts/plot/util/print.m
--- a/scripts/plot/util/print.m	Fri Nov 27 22:36:56 2015 +0100
+++ b/scripts/plot/util/print.m	Fri Nov 27 23:18:00 2015 +0100
@@ -910,7 +910,9 @@
 %!   fid = figure ();
 %!   set (fid, 'PaperUnits', 'inches');
 %!   set (fid, 'PaperSize', [5 3]);
-%!   set (fid, 'PaperPositionMode', 'auto');
+%!   margins = 0.5;
+%!   paperpos = [margins, margins, get(fid, 'PaperSize') - 2 * margins];
+%!   set (fid, 'PaperPosition', paperpos);
 %!
 %!   do
 %!
diff -r 1204042c1f6f -r 13b2af5f2f99 scripts/plot/util/private/__ghostscript__.m
--- a/scripts/plot/util/private/__ghostscript__.m	Fri Nov 27 22:36:56 2015 +0100
+++ b/scripts/plot/util/private/__ghostscript__.m	Fri Nov 27 23:18:00 2015 +0100
@@ -107,9 +107,11 @@
       error ("print:badpapersize", "__ghostscript__.m: invalid 'papersize'");
     endif
     gs_opts = sprintf ("%s -dFIXEDMEDIA", gs_opts);
+    ## conversion from pixels (on screen) to physical size, in points (1/72 in)
+    pageoffset_pt = round (opts.pageoffset * 72 / get (0 , "screenpixelsperinch"));
     ## "pageoffset" is relative to the coordinates, not the BBox LLHC.
     str = sprintf ("%s [%d %d] %s", "<< /Margins [0 0] /.HWMargins [0 0 0 0] /PageOffset",
-                   fix (opts.pageoffset), ">> setpagedevice");
+                   pageoffset_pt, ">> setpagedevice");
     offset_ps = {"%!PS-Adobe-3.0", str, "%%EOF"};
     if (isfield (opts, "offsetfile"))
       offsetfile = opts.offsetfile;
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1448731627 -3600
#      Sat Nov 28 18:27:07 2015 +0100
# Node ID 9bf9df07d2b912bbbba7568d41977b017e39010e
# Parent  13b2af5f2f994a1518653b2c16eb3e02fb553469
rescale linewidths as well as positions

diff -r 13b2af5f2f99 -r 9bf9df07d2b9 scripts/plot/util/private/__opengl_print__.m
--- a/scripts/plot/util/private/__opengl_print__.m	Fri Nov 27 23:18:00 2015 +0100
+++ b/scripts/plot/util/private/__opengl_print__.m	Sat Nov 28 18:27:07 2015 +0100
@@ -26,14 +26,31 @@
   dos_shell = (ispc () && ! isunix ());
 
   ## gl2ps takes positions in pixels as if they were points (1 pt = 1 inch / 72)
-  ## to get the right size after printing, the positions must be rescaled
+  ## to get the right size after printing, some properties must be rescaled
   sppi = get(0, "screenpixelsperinch");
-  h_list = findall (gcf, "-property", "position", 
-                         "-not", "units", "data", 
-                         "-not", "units", "normalized");
-  h_list = num2cell (h_list);
-  old_positions = cellfun(@(h) get(h, "position"), h_list, "UniformOutput", false);
-  cellfun(@(h, old_pos) set(h, "position", old_pos * 72 / sppi), h_list, old_positions)
+  rescale_fun = @(old_value) old_value * 72 / sppi;
+  
+  props(1).name = "position";
+  ## mind the dots for multiline (the cell array must be 1d)
+  props(1).conditions = {"-not", "units", "data", ...
+                         "-not", "units", "normalized"};
+  props(2).name = "linewidth";
+  props(2).conditions = {};
+  
+  for idx = 1:numel(props)
+    h_list = findall(gcf, "-property", props(idx).name, props(idx).conditions{:});
+    old_values = get(h_list, props(idx).name);
+    props(idx).h_list = num2cell(h_list);
+    if iscell(old_values)
+      props(idx).old_values = old_values;
+    else
+      ## there was only one handle in h_list
+      ## put the property in a cell array, for consistency
+      props(idx).old_values = {old_values};
+    endif 
+    cellfun(@(h, old_val) set(h, props(idx).name, rescale_fun(old_val)), 
+            props(idx).h_list, props(idx).old_values);
+  endfor
   
   set (0, "currentfigure", opts.figure);
   drawnow ("expose");
@@ -191,7 +208,10 @@
     opts.latex_standalone (opts);
   endif
 
-  ## set the positions back to normal
-  cellfun(@(h, old_pos) set(h, "position", old_pos), h_list, old_positions)
+  ## set the properties back to normal
+  for idx = 1:numel(props)
+    cellfun(@(h, old_val) set(h, props(idx).name, old_val), 
+            props(idx).h_list, props(idx).old_values);
+  endfor
 endfunction
 
# HG changeset patch
# User ederag <edera@gmx.fr>
# Date 1448745838 -3600
#      Sat Nov 28 22:23:58 2015 +0100
# Node ID f4fb56769486048e297f2a0b718f5abc4c4c7d4b
# Parent  9bf9df07d2b912bbbba7568d41977b017e39010e
use the new handle for changed objects

diff -r 9bf9df07d2b9 -r f4fb56769486 scripts/plot/util/private/__opengl_print__.m
--- a/scripts/plot/util/private/__opengl_print__.m	Sat Nov 28 18:27:07 2015 +0100
+++ b/scripts/plot/util/private/__opengl_print__.m	Sat Nov 28 22:23:58 2015 +0100
@@ -210,8 +210,15 @@
 
   ## set the properties back to normal
   for idx = 1:numel(props)
+    ## FIXME:
+    ## Some objects can be replaced (legend children for instance)
+    ## But it seems that handles returned by findall are always in the same order
+    ## Hence use the current list instead of the old one
+    ## This seems fragile though.
+    h_list = findall(gcf, "-property", props(idx).name, props(idx).conditions{:});
+    h_list = num2cell(h_list);
     cellfun(@(h, old_val) set(h, props(idx).name, old_val), 
-            props(idx).h_list, props(idx).old_values);
+            h_list, props(idx).old_values);
   endfor
 endfunction
 
