Class: KnitrEngine

Inherits:
Object
  • Object
show all
Defined in:
lib/gknit/knitr_engine.rb

Direct Known Subclasses

IncludeEngine, RbEngine, RubyEngine

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#backgroundObject (readonly)

background: ('#F7F7F7'; character or numeric) background color of chunks in LaTeX output (passed to the LaTeX package framed); the color model is rgb; it can be either a numeric vector of length 3, with each element between 0 and 1 to denote red, green and blue, or any built-in color in R like red or springgreen3 (see colors() for a full list), or a hex string like #FFFF00, or an integer (all these colors will be converted to the RGB model; see ?col2rgb for details)



175
176
177
# File 'lib/gknit/knitr_engine.rb', line 175

def background
  @background
end

#class__outputObject (readonly)

class.output: (NULL; character) useful for HTML output, appends classes that can be used in conjunction with css, so you can apply custom formatting.



128
129
130
# File 'lib/gknit/knitr_engine.rb', line 128

def class__output
  @class__output
end

#class__sourceObject (readonly)

class.source: (NULL; character) useful for HTML output, appends classes that can be used in conjunction with css, so you can apply custom formatting.



179
180
181
# File 'lib/gknit/knitr_engine.rb', line 179

def class__source
  @class__source
end

#collapseObject (readonly)

collapse: (FALSE; logical; applies to Markdown output only) whether to, if possible, collapse all the source and output blocks from one code chunk into a single block (by default, they are written to separate

 blocks)



77
78
79
# File 'lib/gknit/knitr_engine.rb', line 77

def collapse
  @collapse
end

#commentObject (readonly)

comment: ('##'; character) the prefix to be put before source code output; default is to comment out the output by ##, which is good for readers to copy R source code since output is masked in comments (set comment=NA to disable this feature)



158
159
160
# File 'lib/gknit/knitr_engine.rb', line 158

def comment
  @comment
end

#devObject (readonly)

dev: ('pdf' for LaTeX output and 'png' for HTML/markdown; character) the function name which will be used as a graphical device to record plots; for the convenience of usage, this package has included all the graphics devices in base R as well as those in Cairo, cairoDevice and tikzDevice, e.g. if we set dev='CairoPDF', the function with the same name in the Cairo package will be used for graphics output; if none of the 20 built-in devices is appropriate, we can still provide yet another name as long as it is a legal function name which can record plots (it must be of the form function(filename, width, height)); note the units for images are always inches (even for bitmap devices, in which DPI is used to convert between pixels and inches); currently available devices are bmp, postscript, pdf, png, svg, jpeg, pictex, tiff, win.metafile, cairo_pdf, cairo_ps, CairoJPEG, CairoPNG, CairoPS, CairoPDF, CairoSVG, CairoTIFF, Cairo_pdf, Cairo_png, Cairo_ps, Cairo_svg, tikz and a series of quartz devices including quartz_pdf, quartz_png, quartz_jpeg, quartz_tiff, quartz_gif, quartz_psd, quartz_bmp which are just wrappers to the function quartz() with different file types

  • the options dev, fig.ext, fig.width, fig.height and dpi can be vectors (shorter ones will be recycled), e.g. <<foo, dev=c('pdf', 'png')>>= creates two files for the same plot: foo.pdf and foo.png


233
234
235
# File 'lib/gknit/knitr_engine.rb', line 233

def dev
  @dev
end

#dev__argsObject (readonly)

dev.args: (NULL) more arguments to be passed to the device, e.g. dev.args=list(bg='yellow', pointsize=10); note this depends on the specific device (see the device documentation); when dev has multiple elements, dev.args can be a list of lists of arguments with each list of arguments to be passed to each single device, e.g. <<dev=c('pdf', 'tiff'), dev.args=list(pdf = list(colormodel = 'cmyk', useDingats = TRUE), tiff = list(compression = 'lzw'))>>=



242
243
244
# File 'lib/gknit/knitr_engine.rb', line 242

def dev__args
  @dev__args
end

#dpiObject (readonly)

dpi: (72; numeric) the DPI (dots per inch) for bitmap devices (dpi * inches = pixels)



250
251
252
# File 'lib/gknit/knitr_engine.rb', line 250

def dpi
  @dpi
end

#echoObject (readonly)

echo: (TRUE; logical) whether to include Ruby source code in the output file



63
64
65
# File 'lib/gknit/knitr_engine.rb', line 63

def echo
  @echo
end

#errorObject (readonly)

error: (TRUE; logical) whether to preserve errors (from stop()); by default, the evaluation will not stop even in case of errors!! if we want R to stop on errors, we need to set this option to FALSE when the chunk option include = FALSE, error knitr will stop on error, because it is easy to overlook potential errors in this case



91
92
93
# File 'lib/gknit/knitr_engine.rb', line 91

def error
  @error
end

#evalObject (readonly)

eval: (TRUE; logical) whether to evaluate the code chunk



55
56
57
# File 'lib/gknit/knitr_engine.rb', line 55

def eval
  @eval
end

#externalObject (readonly)

external: (TRUE; logical) whether to externalize tikz graphics (pre-compile tikz graphics to PDF); it is only used for the tikz() device in the tikzDevice package (i.e., when dev='tikz') and it can save time for LaTeX compilation



364
365
366
# File 'lib/gknit/knitr_engine.rb', line 364

def external
  @external
end

#fig__alignObject (readonly)

fig.align: ('default'; character) alignment of figures in the output document (possible values are left, right and center; default is not to make any alignment adjustments); note that for Markdown output, forcing figure alignments will lead to the HTML tag instead of the original Markdown syntax , because Markdown does not have native support for figure alignments (see #611)



309
310
311
# File 'lib/gknit/knitr_engine.rb', line 309

def fig__align
  @fig__align
end

#fig__aspObject (readonly)

fig.asp: (NULL; numeric) the aspect ratio of the plot, i.e. the ratio of height/width; when fig.asp is specified, the height of a plot (the chunk option fig.height) is calculated from fig.width * fig.asp



260
261
262
# File 'lib/gknit/knitr_engine.rb', line 260

def fig__asp
  @fig__asp
end

#fig__capObject (readonly)

fig.cap: (NULL; character) figure caption to be used in a figure environment in LaTeX (in \caption{}); if NULL or NA, it will be ignored, otherwise a figure environment will be used for the plots in the chunk (output in \beginfigure and \endfigure)



319
320
321
# File 'lib/gknit/knitr_engine.rb', line 319

def fig__cap
  @fig__cap
end

#fig__dimObject (readonly)

fig.dim: (NULL; numeric) if a numeric vector of length 2, it gives fig.width and fig.height, e.g., fig.dim = c(5, 7) is a shorthand of fig.width = 5, fig.height = 7; if both fig.asp and fig.dim are provided, fig.asp will be ignored (with a warning)



266
267
268
# File 'lib/gknit/knitr_engine.rb', line 266

def fig__dim
  @fig__dim
end

#fig__envObject (readonly)

fig.env: ('figure') the LaTeX environment for figures, e.g. set fig.env='marginfigure' to get \beginmarginfigure



313
314
315
# File 'lib/gknit/knitr_engine.rb', line 313

def fig__env
  @fig__env
end

#fig__extObject (readonly)

fig.ext: (NULL; character) file extension of the figure output (if NULL, it will be derived from the graphical device; see knitr:::auto_exts for details)



247
248
249
# File 'lib/gknit/knitr_engine.rb', line 247

def fig__ext
  @fig__ext
end

#fig__filenameObject (readonly)

Returns the value of attribute fig__filename.



193
194
195
# File 'lib/gknit/knitr_engine.rb', line 193

def fig__filename
  @fig__filename
end

#fig__heightObject (readonly)

Returns the value of attribute fig__height.



255
256
257
# File 'lib/gknit/knitr_engine.rb', line 255

def fig__height
  @fig__height
end

#fig__keepObject (readonly)

fig.keep: ('high'; character) how plots in chunks should be kept; it takes five possible character values or a numeric vector (see the end of this section for an example)

  • high: only keep high-level plots (merge low-level changes into high-level plots);
  • none: discard all plots;
  • all: keep all plots (low-level plot changes may produce new plots)
  • first: only keep the first plot
  • last: only keep the last plot if set to a numeric vector: interpret value as index of (low-level) plots to keep


204
205
206
# File 'lib/gknit/knitr_engine.rb', line 204

def fig__keep
  @fig__keep
end

#fig__lpObject (readonly)

Returns the value of attribute fig__lp.



329
330
331
# File 'lib/gknit/knitr_engine.rb', line 329

def fig__lp
  @fig__lp
end

#fig__ncolObject (readonly)

fig.ncol: (NULL; integer) the number of columns of subfigures; see here for examples (note that fig.ncol and fig.sep only work for LaTeX output)



343
344
345
# File 'lib/gknit/knitr_engine.rb', line 343

def fig__ncol
  @fig__ncol
end

#fig__pathObject (readonly)

fig.path: ('figure/'; character) prefix to be used for figure filenames (fig.path and chunk labels are concatenated to make filenames); it may contain a directory like figure/prefix- (will be created if it does not exist); this path is relative to the current working directory; if the prefix ends in a trailing slash, e.g. output/figures/, figures will be saved in the specified directory without any changes to filename prefix, thus providing a relative filepath alternative to the package-level option base.dir



192
193
194
# File 'lib/gknit/knitr_engine.rb', line 192

def fig__path
  @fig__path
end

#fig__posObject (readonly)

fig.pos: (''; character) a character string for the figure position arrangement to be used in \beginfigure



333
334
335
# File 'lib/gknit/knitr_engine.rb', line 333

def fig__pos
  @fig__pos
end

#fig__processObject (readonly)

fig.process: (NULL) a function to post-process a figure file; it should take a filename, and return a character string as the new source of the figure to be inserted in the output



355
356
357
# File 'lib/gknit/knitr_engine.rb', line 355

def fig__process
  @fig__process
end

#fig__retinaObject (readonly)

fig.retina: (1; numeric) this option only applies to HTML output; for Retina displays, setting this option to a ratio (usually 2) will change the chunk option dpi to dpi * fig.retina, and out.width to fig.width * dpi / fig.retina internally; for example, the physical size of an image is doubled and its display size is halved when fig.retina = 2



292
293
294
# File 'lib/gknit/knitr_engine.rb', line 292

def fig__retina
  @fig__retina
end

#fig__scapObject (readonly)

fig.scap: (NULL; character) short caption; if NULL, all the words before . or ; or : will be used as a short caption; if NA, it will be ignored



323
324
325
# File 'lib/gknit/knitr_engine.rb', line 323

def fig__scap
  @fig__scap
end

#fig__sepObject (readonly)

fig.sep: (NULL; character) a character vector of separators to be inserted among subfigures; when fig.ncol is specified, fig.sep defaults to a character vector of which every N-th element is \newline (where N is the number of columns), e.g., fig.ncol = 2 means fig.sep = c('', '', '\newline', '', '', '\newline', '', ...)



350
351
352
# File 'lib/gknit/knitr_engine.rb', line 350

def fig__sep
  @fig__sep
end

#fig__showObject (readonly)

fig.show: ('asis'; character) how to show/arrange the plots; four possible values are

  • asis: show plots exactly in places where they were generated (as if the code were run in an R terminal);
  • hold: hold all plots and output them in the very end of a code chunk;
  • animate: wrap all plots into an animation if there are mutiple plots in a chunk;
  • hide: generate plot files but hide them in the output document


213
214
215
# File 'lib/gknit/knitr_engine.rb', line 213

def fig__show
  @fig__show
end

#fig__showtextObject (readonly)

fig.showtext: (NULL) if TRUE, call showtext::showtext.begin() before drawing plots; see the documentation of the showtext package for details



359
360
361
# File 'lib/gknit/knitr_engine.rb', line 359

def fig__showtext
  @fig__showtext
end

#fig__subcapObject (readonly)

fig.subcap: (NULL) captions for subfigures; when there are multiple plots in a chunk, and neither fig.subcap nor fig.cap is NULL, \subfloat{} will be used for individual plots (you need to add \usepackagesubfig in the preamble); see 067-graphics-options.Rnw for an example



339
340
341
# File 'lib/gknit/knitr_engine.rb', line 339

def fig__subcap
  @fig__subcap
end

#fig__widthObject (readonly)

fig.width, fig.height: (both are 7; numeric) width and height of the plot, to be used in the graphics device (in inches) and have to be numeric



254
255
256
# File 'lib/gknit/knitr_engine.rb', line 254

def fig__width
  @fig__width
end

#highlightObject (readonly)

highlight: (TRUE; logical) whether to highlight the source code (it is FALSE by default if the output is Sweave or listings)



162
163
164
# File 'lib/gknit/knitr_engine.rb', line 162

def highlight
  @highlight
end

#includeObject (readonly)

include: (TRUE; logical) whether to include the chunk output in the final output document; if include=FALSE, nothing will be written into the output document, but the code is still evaluated and plot files are generated if there are any plots in the chunk, so you can manually insert figures; note this is the only chunk option that is not cached, i.e., changing it will not invalidate the cache



109
110
111
# File 'lib/gknit/knitr_engine.rb', line 109

def include
  @include
end

#keepObject (readonly)

Returns the value of attribute keep.



370
371
372
# File 'lib/gknit/knitr_engine.rb', line 370

def keep
  @keep
end

#labelObject (readonly)

fig.lp: ('fig:'; character) label prefix for the figure label to be used in \label{}; the actual label is made by concatenating this prefix and the chunk label, e.g. the figure label for <>= will be fig:foo-plot by default



328
329
330
# File 'lib/gknit/knitr_engine.rb', line 328

def label
  @label
end

#messageObject (readonly)

message: (TRUE; logical) whether to preserve messages emitted by message() (similar to warning)



95
96
97
# File 'lib/gknit/knitr_engine.rb', line 95

def message
  @message
end

#optionsObject (readonly)

Returns the value of attribute options.



48
49
50
# File 'lib/gknit/knitr_engine.rb', line 48

def options
  @options
end

#out__extraObject (readonly)

out.extra: (NULL; character) extra options for figures, e.g. out.extra='angle=90' in LaTeX output will rotate the figure by 90 degrees; it can be an arbitrary string, e.g. you can write multiple figure options in this option; it also applies to HTML images (extra options will be written into the tag, e.g. out.extra='style="display:block;"')



285
286
287
# File 'lib/gknit/knitr_engine.rb', line 285

def out__extra
  @out__extra
end

#out__heightObject (readonly)

Returns the value of attribute out__height.



278
279
280
# File 'lib/gknit/knitr_engine.rb', line 278

def out__height
  @out__height
end

#out__widthObject (readonly)

out.width, out.height: (NULL; character) width and height of the plot in the final output file (can be different with its real fig.width and fig.height, i.e. plots can be scaled in the output document); depending on the output format, these two options can take flexible values, e.g. for LaTeX output, they can be .8\linewidth, 3in or 8cm and for HTML, they may be 300px (do not have to be in inches like fig.width and fig.height; backslashes must be escaped as \); for LaTeX output, the default value for out.width will be changed to \maxwidth which is defined here out.width can also be a percentage, e.g. '40%' will be translated to 0.4\linewidth when the output format is LaTeX



277
278
279
# File 'lib/gknit/knitr_engine.rb', line 277

def out__width
  @out__width
end

#promptObject (readonly)

prompt: (FALSE; logical) whether to add the prompt characters in the R code (see prompt and continue in ?base::options; note that adding prompts can make it difficult for readers to copy R code from the output, so prompt=FALSE may be a better choice this option may not work well when the chunk option engine is not R (#1274)



152
153
154
# File 'lib/gknit/knitr_engine.rb', line 152

def prompt
  @prompt
end

#renderObject (readonly)

render: (knitr::knit_print; function(x, options, ...)) the function which formats the result of the chunk for the final output format. The function is given the chunk result as first argument and the list of chunk options as a named argument options. If the function contains further arguments which match names of chunk options, they are filled with the respective values. The function is expected to return one string which is then rendered appropriately for the current output format. For more information, invoke the help about custom chunk rendering: Invoke in R: vignette('knit_print', package = 'knitr') and ?knitr::knit_print.



124
125
126
# File 'lib/gknit/knitr_engine.rb', line 124

def render
  @render
end

#resize__heightObject (readonly)

Returns the value of attribute resize__height.



301
302
303
# File 'lib/gknit/knitr_engine.rb', line 301

def resize__height
  @resize__height
end

#resize__widthObject (readonly)

resize.width, resize.height: (NULL; character) the width and height to be used in \resizebox{}{} in LaTeX; these two options are not needed unless you want to resize tikz graphics because there is no natural way to do it; however, according to tikzDevice authors, tikz graphics is not meant to be resized to maintain consistency in style with other texts in LaTeX; if only one of them is NULL, ! will be used (read the documentation of graphicx if you do not understand this)



300
301
302
# File 'lib/gknit/knitr_engine.rb', line 300

def resize__width
  @resize__width
end

#resultsObject (readonly)

results: ('markup'; character) takes these possible values markup: mark up the results using the output hook, e.g. put results in a special LaTeX environment asis: output as-is, i.e., write raw results from R into the output document hold: hold all the output pieces and push them to the end of a chunk hide (or FALSE): hide results; this option only applies to normal R output (not warnings, messages or errors)



72
73
74
# File 'lib/gknit/knitr_engine.rb', line 72

def results
  @results
end

#sanitizeObject (readonly)

sanitize: (FALSE; character) whether to sanitize tikz graphics (escape special LaTeX characters); see documentation in the tikzDevice package



368
369
370
# File 'lib/gknit/knitr_engine.rb', line 368

def sanitize
  @sanitize
end

#sizeObject (readonly)

size: ('normalsize'; character) font size for the default LaTeX output (see ?highlight in the highlight package for a list of possible values)



166
167
168
# File 'lib/gknit/knitr_engine.rb', line 166

def size
  @size
end

#splitObject (readonly)

split: (FALSE; logical) whether to split the output from R into separate files and include them into LaTeX by \input{} or HTML by ; this option only works for .Rnw, .Rtex, and .Rhtml documents (it does not work for R Markdown)



101
102
103
# File 'lib/gknit/knitr_engine.rb', line 101

def split
  @split
end

#strip__whiteObject (readonly)

strip.white: (TRUE; logical) whether to remove the white lines in the beginning or end of a source chunk in the output



113
114
115
# File 'lib/gknit/knitr_engine.rb', line 113

def strip__white
  @strip__white
end

#tidyObject (readonly)

tidy: (FALSE) whether to reformat the R code; other possible values are:

* TRUE (equivalent to 'formatR'): use formatR::tidy_source() to reformat the code;
* 'styler': use styler::style_text() to reformat the code;
* a custom function of the form function(code, ...) {} to return the reformatted code;
* if reformatting failed, the original R code will not be changed (with a warning)


139
140
141
# File 'lib/gknit/knitr_engine.rb', line 139

def tidy
  @tidy
end

#tidy__optsObject (readonly)

tidy.opts: (NULL; list) a list of options to be passed to the function determined by the tidy option, e.g., tidy.opts = list(blank = FALSE, width.cutoff = 60) for tidy = 'formatR' to remove blank lines and set the approximate line width to be 60



145
146
147
# File 'lib/gknit/knitr_engine.rb', line 145

def tidy__opts
  @tidy__opts
end

#warningObject (readonly)

warning: (TRUE; logical) whether to preserve warnings (produced by warning()) in the output like we run R code in a terminal (if FALSE, all warnings will be printed in the console instead of the output document); it can also take numeric values as indices to select a subset of warnings to include in the output



84
85
86
# File 'lib/gknit/knitr_engine.rb', line 84

def warning
  @warning
end

Class Method Details

.device(dev_type, filename = nil, *args, width: 480, height: 480, units: "px", res: 72, pointsize: 12, bg: "white") ⇒ Object



Parameters:

  • dev_type (String)

    name of the device type to open

  • filename (String) (defaults to: nil)

    filename to store the image. By default nil for the awt device

  • args (Array)

    other parameters to be passed to device. Right now, there are no other parameters that should be passed to the available devices. Might be needed when more devices are available

  • width (Numeric) (defaults to: 480)

    width of the figure, by default 480

  • height (Numeric) (defaults to: 480)

    hegiht of the figure, by default 480

  • units (String) (defaults to: "px")

    string with units definition, by default 'px'. Could be 'in', 'cm'

  • res (Numeric) (defaults to: 72)

    resolution in dpi, if not provided set to 72

  • pointsize (Numeric) (defaults to: 12)
  • bg (String) (defaults to: "white")


594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
# File 'lib/gknit/knitr_engine.rb', line 594

def self.device(dev_type, filename = nil, *args, width: 480, height: 480,
                units: "px", res: 72, pointsize: 12, bg: "white")
  supported_devices = %w[awt svg png pdf jpg jpeg bmp]
  dev_name = dev_type.to_s.strip
  unless supported_devices.include?(dev_name)
    raise "Unsupported graphics device '#{dev_name}'. Supported devices: #{supported_devices.join(', ')}"
  end

  case dev_name
      
  when "awt"
  when "svg"
    R.svg(filename)
  when "png"
    R.png(filename, width, height, units, pointsize, bg, res, *args)
  when "pdf"
    width_in = width
    height_in = height
    units_s = units.to_s
    if units_s == "px"
      width_in = width.to_f / res.to_f
      height_in = height.to_f / res.to_f
    elsif units_s == "cm"
      width_in = width.to_f / 2.54
      height_in = height.to_f / 2.54
    end
    R.pdf(filename, width_in, height_in, *args)
  when "jpg", "jpeg"
    R.jpeg(filename, width, height, units, pointsize, bg, res, *args)
  when "bmp" 
    R.bmp(filename, width, height, units, pointsize, bg, res, *args)
  end
  
end

Instance Method Details

#add(spec) ⇒ Object


Adds the new knitr engine to the list of engines

Parameters:

  • spec (Hash)

    hash with only one pair containing the machine key and the engine function



711
712
713
714
# File 'lib/gknit/knitr_engine.rb', line 711

def add(spec)
  # Use [[ so R returns the engine function; single bracket [ returns a list, not callable
  R.knitr___knit_engines[["set"]].call(spec)
end

#add_hook(spec) ⇒ Object





720
721
722
# File 'lib/gknit/knitr_engine.rb', line 720

def add_hook(spec)

end

#capture_plotObject


Captures a plot by calling evaluate::plot_snapshot, which has the latest plotted graphics.



653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
# File 'lib/gknit/knitr_engine.rb', line 653

def capture_plot

  # gets a plot snapshot (base R recordPlot via evaluate_plot_snapshot)
  plot = R.evaluate_plot_snapshot

  if (!(plot.is__null.unboxed_get(0)))
    # create directory for the graphics files if does not already exists
    unless File.directory?(@fig__path)
      FileUtils.mkdir_p(@fig__path)
    end

    # use absolute path so the file is created where Ruby expects and include_graphics can find it
    filename_abs = File.expand_path(@filename)
    # Save in one R call (open device, replayPlot, dev.off) so the file is actually written
    w = (@fig__width >> 0) rescue 480
    h = (@fig__height >> 0) rescue 480
    res = (@dpi >> 0) rescue 72
    dev_str = @dev.respond_to?(:>>) ? (@dev >> 0) : @dev.to_s
    dev_str = dev_str.to_s.split.first if dev_str.respond_to?(:to_s)
    units_str = (units.respond_to?(:>>) ? (units >> 0) : units).to_s rescue "in"
    R.save_recorded_plot(filename_abs, plot, w, h, dev_str, res, units_str)
    return plot
  end

  # Fallback when recordPlot() returns NULL on non-screen devices:
  # copy from the active device to the target figure file.
  unless File.directory?(@fig__path)
    FileUtils.mkdir_p(@fig__path)
  end
  filename_abs = File.expand_path(@filename)
  w = (@fig__width >> 0) rescue 480
  h = (@fig__height >> 0) rescue 480
  res = (@dpi >> 0) rescue 72
  dev_str = @dev.respond_to?(:>>) ? (@dev >> 0).to_s : @dev.to_s
  dev_str = dev_str.gsub('"', '').strip

  case
  when dev_str.include?('png')
    R::Support.eval("grDevices::dev.copy(grDevices::png, filename='#{filename_abs.gsub("'", "\\\\'")}', width=#{w}, height=#{h}, units='in', res=#{res}); grDevices::dev.off()")
    return true
  when dev_str.include?('svg')
    R::Support.eval("grDevices::dev.copy(grDevices::svg, filename='#{filename_abs.gsub("'", "\\\\'")}', width=#{w}, height=#{h}); grDevices::dev.off()")
    return true
  when dev_str.include?('pdf')
    R::Support.eval("grDevices::dev.copy(grDevices::pdf, file='#{filename_abs.gsub("'", "\\\\'")}', width=#{w}, height=#{h}); grDevices::dev.off()")
    return true
  end

  false

end

#fig_keepObject


Process the fig.keep chunk option

Parameters:

  • keep (String/Numeric)

    a string or a number. If it is a string then it should be one of the following:

    • high: only keep high-level plots (merge low-level changes into high-level plots);
    • none: discard all plots;
    • all: keep all plots (low-level plot changes may produce new plots)
    • first: only keep the first plot
    • last: only keep the last plot if set to a numeric vector: interpret value as index of (low-level) plots to keep In this case, set variable @keep to "index" and variable @keep_ind as the numeric index.


469
470
471
472
473
474
475
476
477
478
# File 'lib/gknit/knitr_engine.rb', line 469

def fig_keep
  @keep = @fig__keep
  @keep_idx = nil
  
  if (@keep.is__numeric.unboxed_get(0))
    @keep_idx = @keep
    @keep = "index"
  end
  
end

#figure_artifact_ready?(path) ⇒ Boolean


A figure is renderable only if the artifact exists and is valid for its device. For PDFs, enforce at least one page so LaTeX includegraphics won't fail.

Returns:

  • (Boolean)


634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'lib/gknit/knitr_engine.rb', line 634

def figure_artifact_ready?(path)
  return false unless File.exist?(path)
  return false unless File.size(path).to_i > 0

  ext = File.extname(path).downcase
  return true unless ext == ".pdf"

  pdf_data = File.binread(path)
  counts = pdf_data.scan(%r{/Count\s+(\d+)}).flatten.map(&:to_i)
  !counts.empty? && counts.max > 0
rescue StandardError
  false
end

#file_extObject





484
485
486
487
488
489
490
491
492
493
# File 'lib/gknit/knitr_engine.rb', line 484

def file_ext
  # guess plot file type if it is NULL
  # Use @fig__ext (already set from options['fig.ext']) to avoid calling R's fig.ext(options) which triggers invalid connection
  fig_ext_empty = @fig__ext.nil? || (@fig__ext.respond_to?(:to_s) && @fig__ext.to_s.strip.empty?)
  # NA from knitr "inherit" must not skip dev2ext (same as GalaazUtil.knitr_logical_trueish? for chunk options).
  keep_plots = GalaazUtil.knitr_logical_trueish?(((@keep != 'none') rescue nil))
  if keep_plots && fig_ext_empty
    @fig__ext = (R.knitr_dev2ext(@options).unboxed_get(0))
  end
end

#process_options(options) ⇒ Object


Process the chunk options



499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/gknit/knitr_engine.rb', line 499

def process_options(options)

  @options = options

  # Chunk options
  @label = (options['label'].unboxed_get(0))
  
  # Text results
  @eval = options[["eval"]] 
  @echo = GalaazUtil.knitr_option_trueish?(options, 'echo', default: true)
  @results = options['results'] 
  @collapse = options['collapse'] 
  @warning = options['warning'] 
  @error = options['error'] 
  @message = options['message'] 
  @split = options['split'] 
  @include = GalaazUtil.knitr_option_trueish?(options, 'include', default: true)
  @strip__white = options['strip.white'] 
  # @render = options['render'] # a function
  @class__output = options['class.output'] 
  
  # Code Decoration
  # @tidy = options['tidy'] 
  # @tidy__opts = options['tidy.opts']
  @prompt = options['prompt']  
  @comment = options['comment'] 
  @highlight = options['highlight'] 
  @size = options['size'] 
  @background = options['background'] 
  @class__source = options['class_source'] 
  
  # Plots - avoid unboxed_get in callback as it uses RESULT_FIFO which fails with "invalid connection"
  @fig__path = scalar_option_string(options['fig.path'])
  @fig__keep = options['fig.keep'] # can be a vector; use options['fig.keep'] not options.fig__keep to avoid R's fig.keep() which triggers invalid connection
  @fig__show = options['fig.show'] 
  @dev = options['dev'] 
  # @dev__args = options['dev.args'] # can be a vector
  @fig__ext = scalar_option_string(options['fig.ext'])
  @dpi = options['dpi'] 
  @fig__width = options['fig.width'] 
  @fig__height = options['fig.height'] 
  @fig__asp = options['fig.asp'] 
  # @fig__dim = options['fig.dim']  # vector with two elements
  @out__width = options['out.width'] 
  @out__height = options['out.height'] 
  @out__extra = options['out.extra'] 
  @fig__retina = options['fig.retina'] 
  @resize__width = options['resize.width'] 
  @resize__height = options['resize.height'] 
  @fig__align = options['fig.align'] 
  @fig__env = options['fig.env'] 
  @fig__cap = options['fig.cap'] 
  @fig__scap = options['fig.scap'] 
  @fig__lp = options['fig.lp'] 
  @fig__pos = options['fig.pos'] 
  @fig__subcap = options['fig.subcap'] 
  @fig__ncol = options['fig.ncol'] 
  # @fig__sep = options['fig.sep'] # a vector
  @fig__process = options['fig.process'] 
  @fig__showtext = options['fig.showtext'] 
  @external = options['external'] 
  @sanitize = options['sanitize'] 

  # verifies if figures should be kept
  fig_keep

  # if figures are to be kept, take or guess the file extension
  file_ext
  
  # make final filename
  @filename = "#{@fig__path}#{@label}.#{@fig__ext}"
  @options["filename"] = "."

  # create temporary file for storing plots
  # TODO: should remove this directory afterwards
  @tmp_fig = (R.tempfile().unboxed_get(0))
  
end

#scalar_option_string(opt) ⇒ Object


Safely normalize scalar chunk option values that may come boxed from R.



448
449
450
451
452
453
# File 'lib/gknit/knitr_engine.rb', line 448

def scalar_option_string(opt)
  return opt.unboxed_get(0).to_s if opt.respond_to?(:unboxed_get)
  opt.to_s
rescue StandardError
  opt.to_s
end

#unitsObject





439
440
441
442
# File 'lib/gknit/knitr_engine.rb', line 439

def units
  opt_units = (@options[["units"]])
  (opt_units.is__null.unboxed_get(0)) ? "in" : opt_units
end