[Pgfsweave-commits] r27 - in pkg: . R exec inst/doc inst/doc/figs inst/example inst/misc/vignette-src inst/tests man

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Tue Feb 22 20:15:18 CET 2011


Author: cameronbracken
Date: 2011-02-22 20:15:17 +0100 (Tue, 22 Feb 2011)
New Revision: 27

Added:
   pkg/inst/example/pgfSweave-latex-example.Rnw
Removed:
   pkg/inst/doc/figs/fig-pgfSweave-hist.pdf
   pkg/inst/doc/pgfSweave_hans.pdf
Modified:
   pkg/ChangeLog
   pkg/DESCRIPTION
   pkg/NAMESPACE
   pkg/NEWS
   pkg/R/cacheSweaveUnexportedFunctions.R
   pkg/R/pgfSweave.R
   pkg/R/pgfSweaveDriver.R
   pkg/R/utilities.R
   pkg/R/zzz.R
   pkg/README.md
   pkg/exec/pgfsweave-script.R
   pkg/inst/doc/figs/fig-normalSweave.pdf
   pkg/inst/doc/figs/fig-pgfSweave-tikz-hist.pdf
   pkg/inst/doc/pgfSweave-example-Rnw.in
   pkg/inst/doc/pgfSweave-example-tex.in
   pkg/inst/doc/pgfSweave-example.pdf
   pkg/inst/doc/pgfSweave.Rnw
   pkg/inst/doc/pgfSweave.pdf
   pkg/inst/example/Makefile
   pkg/inst/example/pgfSweave-example.Rnw
   pkg/inst/misc/vignette-src/Makefile
   pkg/inst/misc/vignette-src/pgfSweave-vignette-source.Rnw
   pkg/inst/tests/Makefile
   pkg/man/pgfSweave.Rd
   pkg/man/pgfSweaveDriver.Rd
Log:
Squashed commit of the following:

commit d38f61ceb6549a73e070ee20befeafb3027902ae
Author: cameronbracken <cameron.bracken at gmail.com>
Date:   Tue Feb 22 12:11:52 2011 -0700

    Update PGF version check to 2.10

commit 0bad74ef4c42e0a33e6dd2e94510c4722524bff9
Author: cameronbracken <cameron.bracken at gmail.com>
Date:   Tue Feb 22 11:59:02 2011 -0700

    Use the correct options function in the driver

commit 2ec6cea4fa2c3e1d7531238f27566c0ac24ef78d
Author: cameronbracken <cameron.bracken at gmail.com>
Date:   Mon Feb 21 17:13:58 2011 -0700

    Remove everything from the tex.driver option

commit 844d9a9d6c95b966a1bdaf3f2e732ad99058d9b2
Author: cameronbracken <cameron.bracken at gmail.com>
Date:   Mon Feb 21 17:09:21 2011 -0700

    Update to the documentation and vignette with recent changes, new
    example of using tikz externalization library to generate eps graphics

commit 4d07efb597e262913c5112aa712686da9278f043
Author: cameronbracken <cameron.bracken at gmail.com>
Date:   Tue Feb 8 14:07:39 2011 -0700

    Redefine Houtput environment to use \raggedright to avoid the extra space added by flushleft

commit b83eeceb5b7db4c388ddb92140cb5a0c07895a86
Author: cameronbracken <cameron.bracken at gmail.com>
Date:   Fri Jan 21 10:27:33 2011 -0700

    Greatly reduce package load time (from 5 to 1 second) by using import
    instead of depends

commit 916336bf42692191836e42a2f4e8b378854121d5
Author: cameronbracken <cameron.bracken at gmail.com>
Date:   Tue Jan 18 17:33:58 2011 -0700

    First cut using the tikz external library, also generate highlighted
    output in a special environment. See full commit message for details

    - Use the tikz external library with the `list and make` option. This
      option allows for externalized graphic dependency checking and
      parallel compilation of external graphics

      - The tikz external library with this option uses a slightly
        different workflow, namely:

        1. Run (pdf)latex once to generate a makefile with graphic
           dependencies
        2. Run make to externalize graphics
        3. Run (pdf)latex again

      - pgfSweave() and pgfSweave-script.R have been updated accordingly
        and now have a new option to specify the number of processors
      - All the old externalization command stuff has been removed, so no
        more .sh file!
      - Instead of the \pgfrealjobname command added, the \tikzexternalize
        command is added automatically in addition to the
      - Also use the \tikzexternalfiledependsonfile feature to add
        dependency on the .tikz file

    - Externalized graphics now have another layer of crude caching on their
      own, this was attempted before but now works correctly.  A digest of
      the entire chunk is computed and stored in a stashR database for the
      chunk (if cache is already TRUE, then the existing db is used). If
      anything changes in the code chunk at all, including white space, the
      graphic is updated, otherwise the figure is not regenerated.  This
      also helps a bit for plain pdf and eps output.

    - Highlighted output is now output in a `Houtput` environment just like
      the regular Sweave echo'd output. This environment is defined by
      default to be a `flushleft` environment so that graphics can be
      centered with \centering or something similar. This environment can also
      be redefined by the user with \renewenvironment

    - Move some functions around and add some more comments

Modified: pkg/ChangeLog
===================================================================
--- pkg/ChangeLog	2011-01-17 00:02:51 UTC (rev 26)
+++ pkg/ChangeLog	2011-02-22 19:15:17 UTC (rev 27)
@@ -1,3 +1,109 @@
+commit 4d07efb597e262913c5112aa712686da9278f043
+Author: cameronbracken <cameron.bracken at gmail.com>
+Date:   Tue Feb 8 14:07:39 2011 -0700
+
+    Redefine Houtput environment to use \raggedright to avoid the extra space added by flushleft
+
+ R/pgfSweaveDriver.R |    2 +-
+ 1 files changed, 1 insertions(+), 1 deletions(-)
+
+commit b83eeceb5b7db4c388ddb92140cb5a0c07895a86
+Author: cameronbracken <cameron.bracken at gmail.com>
+Date:   Fri Jan 21 10:27:33 2011 -0700
+
+    Greatly reduce package load time (from 5 to 1 second) by using import
+    instead of depends
+
+ DESCRIPTION             |    6 +++---
+ NAMESPACE               |    3 +++
+ R/pgfSweaveDriver.R     |   18 +++++++++++-------
+ exec/pgfsweave-script.R |    4 ----
+ 4 files changed, 17 insertions(+), 14 deletions(-)
+
+commit 916336bf42692191836e42a2f4e8b378854121d5
+Author: cameronbracken <cameron.bracken at gmail.com>
+Date:   Tue Jan 18 17:33:58 2011 -0700
+
+    First cut using the tikz external library, also generate highlighted
+    output in a special environment. See full commit message for details
+    
+    - Use the tikz external library with the `list and make` option. This
+      option allows for externalized graphic dependency checking and
+      parallel compilation of external graphics
+    
+      - The tikz external library with this option uses a slightly
+        different workflow, namely:
+    
+        1. Run (pdf)latex once to generate a makefile with graphic
+           dependencies
+        2. Run make to externalize graphics
+        3. Run (pdf)latex again
+    
+      - pgfSweave() and pgfSweave-script.R have been updated accordingly
+        and now have a new option to specify the number of processors
+      - All the old externalization command stuff has been removed, so no
+        more .sh file!
+      - Instead of the \pgfrealjobname command added, the \tikzexternalize
+        command is added automatically in addition to the
+      - Also use the \tikzexternalfiledependsonfile feature to add
+        dependency on the .tikz file
+    
+    - Externalized graphics now have another layer of crude caching on their
+      own, this was attempted before but now works correctly.  A digest of
+      the entire chunk is computed and stored in a stashR database for the
+      chunk (if cache is already TRUE, then the existing db is used). If
+      anything changes in the code chunk at all, including white space, the
+      graphic is updated, otherwise the figure is not regenerated.  This
+      also helps a bit for plain pdf and eps output.
+    
+    - Highlighted output is now output in a `Houtput` environment just like
+      the regular Sweave echo'd output. This environment is defined by
+      default to be a `flushleft` environment so that graphics can be
+      centered with \centering or something similar. This environment can also
+      be redefined by the user with \renewenvironment
+    
+    - Move some functions around and add some more comments
+
+ R/cacheSweaveUnexportedFunctions.R |   73 +++++++++++++-
+ R/pgfSweave.R                      |   41 ++++----
+ R/pgfSweaveDriver.R                |  194 +++++++++++++++-------------------
+ R/utilities.R                      |  205 ++++--------------------------------
+ exec/pgfsweave-script.R            |   42 +++++---
+ inst/example/pgfSweave-example.Rnw |    6 +-
+ 6 files changed, 227 insertions(+), 334 deletions(-)
+
+commit 40a152d1531f4f62c101c92ef6afcd3630f148cd
+Author: cameronbracken <cameron.bracken at gmail.com>
+Date:   Sun Jan 16 16:57:32 2011 -0700
+
+    Prep for next release
+
+ ChangeLog                                          |  152 ++++++++++++++++++++
+ DESCRIPTION                                        |    2 +-
+ NEWS                                               |    1 +
+ inst/doc/figs/fig-normalSweave.pdf                 |  Bin 2937 -> 2965 bytes
+ inst/doc/figs/fig-pgfSweave-hist.pdf               |  Bin 16299 -> 16286 bytes
+ inst/doc/figs/fig-pgfSweave-tikz-hist.pdf          |  Bin 26907 -> 26912 bytes
+ inst/doc/pgfSweave-example-Rnw.in                  |    9 +-
+ inst/doc/pgfSweave-example-tex.in                  |   20 ++-
+ inst/doc/pgfSweave-example.pdf                     |  Bin 76150 -> 78139 bytes
+ inst/doc/pgfSweave.Rnw                             |   87 ++++++------
+ inst/doc/pgfSweave.pdf                             |  Bin 276681 -> 278812 bytes
+ inst/doc/pgfSweave_hans.pdf                        |  Bin 236103 -> 236105 bytes
+ inst/misc/vignette-src/Makefile                    |   13 +-
+ .../vignette-src/pgfSweave-vignette-source.Rnw     |   73 +++++-----
+ inst/tests/Makefile                                |    2 +-
+ 15 files changed, 260 insertions(+), 99 deletions(-)
+
+commit fcad9715f3ed976c77c7ac99fa4099123d6e976e
+Author: cameronbracken <cameron.bracken at gmail.com>
+Date:   Sun Jan 16 16:56:13 2011 -0700
+
+    Improve automatic insertion of \pgfrealjobname
+
+ R/pgfSweaveDriver.R |   66 +++++++++++++++++++++++++++++---------------------
+ 1 files changed, 38 insertions(+), 28 deletions(-)
+
 commit 199bb28ffa62532c8df42500519ef4516c04e5fc
 Author: cameronbracken <cameron.bracken at gmail.com>
 Date:   Sun Jan 16 14:58:51 2011 -0700

Modified: pkg/DESCRIPTION
===================================================================
--- pkg/DESCRIPTION	2011-01-17 00:02:51 UTC (rev 26)
+++ pkg/DESCRIPTION	2011-02-22 19:15:17 UTC (rev 27)
@@ -1,22 +1,22 @@
 Package: pgfSweave
 Type: Package
-Title: Quality speedy graphics compilation with Sweave
-Version: 1.1.3
+Title: Quality speedy graphics compilation and caching with Sweave
+Version: 1.2.0
 Date: 2011-01-16
 Author: Cameron Bracken <cameron.bracken at gmail.com> and Charlie Sharpsteen <source at sharpsteen.net>
 Maintainer: Cameron Bracken <cameron.bracken at gmail.com> 
-Depends: stashR, filehash, tikzDevice, cacheSweave, getopt, highlight, formatR
-Imports: digest, tools, utils
-SystemRequirement: pgf (>=2.00) (http://sourceforge.net/projects/pgf/) for the 
-      vignette and for externalization.
-Description:  pgfSweave provides a number of improvements to the improve 
+Depends: stashR, filehash, highlight, getopt, formatR
+Imports: digest, tools, utils, tikzDevice, cacheSweave
+SystemRequirement: pgf (>=2.10) (http://sourceforge.net/projects/pgf/) for the 
+      vignette and for externalization, GNU Make for externalization
+Description:  pgfSweave provides a number of improvements to the
       speed and quality of Sweave output including: (1) capabilities for 
       'caching' graphics generated with Sweave on top of the caching 
       mechanisms provided by cacheSweave, (2) an interface to the tikzDevice 
       package which provides graphics with consistent font style, sizing 
       and quality as the main document and (3) highlighting of echo'd source 
       code via the highlight package. pgfSweave provides a new driver for 
-      Sweave (pgfSweaveDriver) with new chunk options tikz, pgf, external, 
+      Sweave (pgfSweaveDriver) with new chunk options tikz, external, 
       sanitize, highlight and tidy on top of the cache option provided by 
       cacheSweave.
 License: GPL (>= 3)

Modified: pkg/NAMESPACE
===================================================================
--- pkg/NAMESPACE	2011-01-17 00:02:51 UTC (rev 26)
+++ pkg/NAMESPACE	2011-02-22 19:15:17 UTC (rev 27)
@@ -4,3 +4,6 @@
 import(utils)
 importFrom(digest, "digest")
 importFrom(tools, "texi2dvi")
+importFrom(tikzDevice, "tikz")
+importFrom(formatR, "tidy.source", "parse.tidy", "deparse.tidy")
+importFrom(cacheSweave, "getCacheDir", "setCacheDir")
\ No newline at end of file

Modified: pkg/NEWS
===================================================================
--- pkg/NEWS	2011-01-17 00:02:51 UTC (rev 26)
+++ pkg/NEWS	2011-02-22 19:15:17 UTC (rev 27)
@@ -1,15 +1,35 @@
 Please see the README.md file for development info
 
 --------------------------
+Version 1.2.0 - 2011-02-21
+--------------------------
+* [NEW] Use the tikz externalization library instead of the pgf backend. This 
+        allows for more flexibility and faster compilations but BEWARE, this 
+        requires at least pgf 2.10 and may break backward computability in 
+        some cases 
+* [NEW] GNU Make is now a system requirement for externalizing graphics, 
+        NOT for compiling the package
+* [NEW] Option to specify number of processors when externalizing graphics
+* [NEW] Externalized graphics now have another layer of crude caching
+* [NEW] Highlighted output is now output in a separate environment to fix the 
+        centering issues
+* [NEW] Example document using plain latex and the tikz external library to 
+        generate eps graphics, `inst/example/pgfSweave-latex-example.Rnw`
+* [CHANGED] The `tex.driver' option has been removed, the same effect can be 
+        achieved using the tikz externalization library, see the new 
+        example for how
+* [DEPRECIATED] The `pgf' option is depreciated, please use the `tikz' option
+
+--------------------------
 Version 1.1.3 - 2011-01-07
 --------------------------
 * [NEW] Use the "null device" to avoid generation of Rplots.pdf, as suggested 
-  by yihui, fixes Issue 8
+        by yihui, fixes Issue 8
 * [NEW] New Vignette, courtesy of Hans Ekbrand! Focuses on the use of 
-  pgfSweave with large data sets 
+        pgfSweave with large data sets 
 * [NEW] Example using caching by Yihui, inst/example/caching.Rnw
 * [NEW] Inline comments are now preserved thanks to changes in the 
-  tidy.source() function from the formatR package 
+        tidy.source() function from the formatR package 
 * [NEW] The formatR package is now a dependency of pgfSweave
 * [FIXED] Reusing code chunks now works as expected, fixes Issue 9
 * [FIXED] Links to tidy.source now correctly point to formatR

Modified: pkg/R/cacheSweaveUnexportedFunctions.R
===================================================================
--- pkg/R/cacheSweaveUnexportedFunctions.R	2011-01-17 00:02:51 UTC (rev 26)
+++ pkg/R/cacheSweaveUnexportedFunctions.R	2011-02-22 19:15:17 UTC (rev 27)
@@ -1,7 +1,8 @@
 ######################################################################
 ## These functions are directly copied from the cacheSweave package.
 ## The reason they are copied here is because they are internal functions
-## and hence are not exported into the global environment.  Some functions ## are also hacked a little, which is the reason the ::: operator is not 
+## and hence are not exported into the global environment.  Some functions 
+## are also hacked a little, which is the reason the ::: operator is not 
 ## used. The  original comments and header are preserved.
 
 
@@ -86,7 +87,7 @@
 ## If 'source()' was used, there may be new symbols in the global
 ## environment, unless 'source(local = TRUE)' was used.  Also applies
 ## for 'set.seed()'.
-        
+
 checkNewSymbols <- function(e1, e2) {
         if(identical(e1, e2))
                 return(character(0))
@@ -129,6 +130,8 @@
         ## Dump the values of the keys to the database
         dumpToDB(db, list = keys, envir = env)
 
+	if(length(keys) > 0)
+		copy2env(keys, env, globalenv())
         keys
 }
 
@@ -140,6 +143,72 @@
         paste(".__", x, "__", sep = "")
 }
 
+hash <- function(object) {
+	digest(object, algo = "sha1")
+}
+
+hashExpr <- function(expr) {
+	expr <- deparse(expr, width.cutoff = 60)
+	hash(expr)
+}
+
+cacheSweaveEvalWithOpt <- function (expr, options) {
+  chunkDigest <- options$chunkDigest
+  
+  ## 'expr' is a single expression, so something like 'a <- 1'
+  res <- NULL
+
+  if(!options$eval)
+          return(res)
+  if(options$cache) {
+    cachedir <- getCacheDir()
+
+    ## Create database name from chunk label and MD5
+    ## digest
+    dbName <- makeChunkDatabaseName(cachedir, options, chunkDigest)
+    exprDigest <- mangleDigest(hashExpr(expr))
+
+    ## Create 'stashR' database
+    db <- new("localDB", dir = dbName, name = basename(dbName))
+
+    ## If the current expression is not cached, then
+    ## evaluate the expression and dump the resulting
+    ## objects to the database.  Otherwise, just read the
+    ## vector of keys from the database
+
+    if(!dbExists(db, exprDigest)) {
+
+      keys <- try({
+        evalAndDumpToDB(db, expr, exprDigest)
+      }, silent = TRUE)
+
+      ## If there was an error then just return the
+      ## condition object and let Sweave deal with it.
+      if(inherits(keys, "try-error"))
+        return(keys)
+
+    } else {
+
+      keys <- dbFetch(db, exprDigest)
+      dbLazyLoad(db, globalenv(), keys)
+
+    }
+    keys
+
+  } else {
+
+    ## If caching is turned off, just evaluate the expression
+    ## in the global environment
+    res <- try(withVisible(eval(expr, .GlobalEnv)),
+               silent=TRUE)
+    if(inherits(res, "try-error"))
+      return(res)
+    if(options$print | (options$term & res$visible))
+      print(res$value)
+  }
+  res
+}
+
 makeMapFileName <- function(Rnwfile) {
         mapfile <- sub("\\.Rnw$", "\\.map", Rnwfile)
 

Modified: pkg/R/pgfSweave.R
===================================================================
--- pkg/R/pgfSweave.R	2011-01-17 00:02:51 UTC (rev 26)
+++ pkg/R/pgfSweave.R	2011-02-22 19:15:17 UTC (rev 27)
@@ -1,4 +1,4 @@
-pgfSweave <- function(file, compile.tex = TRUE, syntax = getOption("SweaveSyntax"), ...){
+pgfSweave <- function(file, compile.tex = TRUE, syntax = getOption("SweaveSyntax"), np = 2,...){
     
     #Run Sweave
     Sweave(file,driver=pgfSweaveDriver,syntax=syntax)
@@ -6,26 +6,27 @@
     #if available compile pgf graphics
     if(compile.tex){
         
-        #Strip the extension and compile the pgf graphics separately
-        
-        bn <- strsplit(basename(file),"\\.Rnw")[[1]][1]
-        dn <- dirname(file)
-        fn <- file.path(dn,bn)
-        cmds <- readLines(paste(fn,'sh',sep='.'))
-        dummy <- lapply(cmds,system)
+        #Strip the extension
+        fn <- tools::file_path_sans_ext(file)
 
-        #if using miktex on windows the flag is not needed
-        #texlive on linux/macosx needs the --jobname flag
-        if(.Platform$OS.type != 'windows'){
-            flag <- paste('--jobname=',bn,sep='')
-    
-            #set special versions of calls to latex or pdflatex
-            if(is.null(match.call()$pdf))
-                Sys.setenv(LATEX=paste("latex",flag))
-            else
-                Sys.setenv(PDFLATEX=paste("pdflatex",flag))
-        }
-    
+        # set initial calls to latex or pdflatex to generate makefile and 
+        # dependency lists
+        cmd <- 
+        if(is.null(match.call()$pdf))
+            Sys.getenv("LATEX","latex")
+        else
+            Sys.getenv("PDFLATEX","pdflatex")
+
+            # Initial call to pdflatex or latex
+        system(paste(cmd,fn))
+
+            # call make to externalize graphics
+        make <- Sys.which('make')
+        if(file.access(make, 1) == 0)
+          system(paste(make," -j ",np," -f ",fn,".makefile",sep=""))
+        else 
+          warning('`make` is not available, graphics will not be externalized.')
+
         #run texi2dvi on the tex file        
         tools::texi2dvi(paste(fn,'tex',sep='.'),...)
     }

Modified: pkg/R/pgfSweaveDriver.R
===================================================================
--- pkg/R/pgfSweaveDriver.R	2011-01-17 00:02:51 UTC (rev 26)
+++ pkg/R/pgfSweaveDriver.R	2011-02-22 19:15:17 UTC (rev 27)
@@ -28,7 +28,7 @@
        runcode = pgfSweaveRuncode,
        writedoc = pgfSweaveWritedoc,
        finish = utils::RweaveLatexFinish,
-       checkopts = pgfSweaveOptions
+       checkopts = utils::RweaveLatexOptions
        )
 }
 
@@ -42,7 +42,7 @@
               eval=TRUE, split=FALSE, stylepath=TRUE,
               pdf=FALSE, eps=FALSE, cache=FALSE, pgf=FALSE,
               tikz=TRUE, external=FALSE, sanitize = FALSE,
-              highlight = TRUE, tidy = FALSE, tex.driver="pdflatex")
+              highlight = TRUE, tidy = FALSE)
 {
     out <- utils::RweaveLatexSetup(file, syntax, output=output, quiet=quiet,
                      debug=debug, echo=echo, eval=eval,
@@ -58,7 +58,6 @@
     out$options[["pgf"]] <- pgf
     out$options[["tikz"]] <- tikz
     out$options[["external"]] <- external
-    out$options[["tex.driver"]] <- tex.driver
     out$options[["sanitize"]] <- sanitize
     out$options[["highlight"]] <- ifelse(echo,highlight,FALSE)
     out$options[["tidy"]] <- tidy
@@ -72,10 +71,8 @@
     ## End additions [RDP]
 
     ## [CWB]  create a shell script with a command for each modified graphic
-    out[["shellFile"]] <- makeExternalShellScriptName(file)
-    out[["srcfileName"]] <- sub("\\.[Rr]nw$", "\\.tex", file)
-    out[["jobname"]] <- basename(removeExt(file))
-    file.create(out[["shellFile"]])  ## Overwrite an existing file
+    out[["srcfileName"]] <-paste(tools::file_path_sans_ext(file), "tex", sep='')
+    out[["jobname"]] <- basename(tools::file_path_sans_ext(file))
     ######################################################################
 
       # Avoids creation of Rplots.pdf
@@ -86,55 +83,8 @@
     out
 }
 
-    # changes in Sweave in 2.12 make it necessary to copy this function here
-    # to register the tex.driver option, I wish there was an easier way....
-pgfSweaveOptions <- function(options)
-{
-
-    ## ATTENTION: Changes in this function have to be reflected in the
-    ## defaults in the init function!
-
-    ## convert a character string to logical
-    c2l <- function(x){
-        if(is.null(x)) return(FALSE)
-        else return(as.logical(toupper(as.character(x))))
-    }
-
-    NUMOPTS <- c("width", "height")
-    NOLOGOPTS <- c(NUMOPTS, "results", "prefix.string",
-                   "engine", "label", "strip.white",
-                   "pdf.version", "pdf.encoding", "tex.driver")
-    for(opt in names(options)){
-        if(! (opt %in% NOLOGOPTS)){
-            oldval <- options[[opt]]
-            if(!is.logical(options[[opt]])){
-                options[[opt]] <- c2l(options[[opt]])
-            }
-            if(is.na(options[[opt]]))
-                stop(gettextf("invalid value for '%s' : %s", opt, oldval),
-                     domain = NA)
-        }
-        else if(opt %in% NUMOPTS){
-            options[[opt]] <- as.numeric(options[[opt]])
-        }
-    }
-
-    if(!is.null(options$results))
-        options$results <- tolower(as.character(options$results))
-    options$results <- match.arg(options$results,
-                                 c("verbatim", "tex", "hide"))
-
-    if(!is.null(options$strip.white))
-        options$strip.white <- tolower(as.character(options$strip.white))
-    options$strip.white <- match.arg(options$strip.white,
-                                     c("true", "false", "all"))
-    options
-}
-
-    # Copied from Sweave in R version 2.12, internal chages make it necessary
-    # to register the tex.driver option as a "NOLOGOPT"
     # This function checks for the \usepackage{Sweave} line and the
-    # \pgfrealjobname line
+    # \tikzexternalize line
 pgfSweaveWritedoc <- function(object, chunk)
 {
     linesout <- attr(chunk, "srclines")
@@ -142,9 +92,9 @@
     if(length(grep("\\usepackage[^\\}]*Sweave.*\\}", chunk)))
         object$havesty <- TRUE
 
-    haverealjobname <- FALSE
-    if(length(grep("\\pgfrealjobname\\{.*\\}", chunk)))
-        haverealjobname <- TRUE
+    havetikzexternalize <- FALSE
+    if(length(grep("\\tikzexternalize.*^", chunk)))
+        havetikzexternalize <- TRUE
 
 
     if(!object$havesty){
@@ -159,54 +109,45 @@
         }
     }
 
-      # add pgfrealjobname if it doesnt exist
-    if(!haverealjobname){
-     begindoc <- "^[[:space:]]*\\\\begin\\{document\\}"
-     which <- grep(begindoc, chunk)
-      # if Sweave line also does not exist
-     #otherwhich <- grep("\\usepackage[^\\}]*Sweave.*\\}", chunk)
-     otherwhich <- grep("^[[:space:]]*\\\\usepackage\\{.*tikz.*\\}", chunk)
-     other <- FALSE
-     if(length(which) == 0){which <- otherwhich;other <- T}
-     if (length(which)) {
-     if(length(which) > 1) {cat('haverealjobname',which,'\n');browser()}
-      chunk[which] <- 
-        if(other) 
-          paste(chunk[which],"\n\\pgfrealjobname{",object$jobname,"}\n", sep="")
-        else
-          paste("\\pgfrealjobname{",object$jobname,"}\n",chunk[which], sep="")
-      linesout <- linesout[c(1L:which, which, seq(from=which+1L, length.out=length(linesout)-which))]
-      object$haverealjobname <- TRUE
+      # add tikzexternalize if it doesnt exist
+    if(!havetikzexternalize){
+        # add the lines after the \usepackage{tikz} statement
+      which <- grep("^[[:space:]]*\\\\usepackage\\{.*tikz.*\\}", chunk)
+      if(length(which)){
+        chunk[which] <- paste(chunk[which],"\\usetikzlibrary{external}",
+          "\\tikzexternalize[mode=list and make]\n", sep="\n")
+        linesout <- linesout[c(1L:which, which, seq(from=which+1L, length.out=length(linesout)-which))]
+        object$havetikzexternalize <- TRUE
       }
     }
      
-     # always add the syntax definitions because there is no real way to
-     # check if a single code chunk as the option before hand.
-      if (!object$haveHighlightSyntaxDef){
-              # get the latex style definitions from the highlight package
-        tf <- tempfile()
-        cat(styler('default', 'sty', styler_assistant_latex),sep='\n',file=tf)
-        cat(boxes_latex(),sep='\n',file=tf,append=T)
-        hstyle <- readLines(tf)
-          # find where to put the style definitions
-        begindoc <- "^[[:space:]]*\\\\begin\\{document\\}"
-          # first try to put it before the begin{document} command
-          # this may not work if there is a code chunk before it
-        which <- grep(begindoc, chunk)
-          # also try to put it by the Sweave style file, 
-        otherwhich <- grep("\\usepackage[^\\}]*Sweave.*\\}", chunk)
-        if(!length(which)) which <- otherwhich
-        
-              # put in the style definitions before the \begin{document}
-              # or \usepackage{Sweave}
-        if(length(which)) {
-    if(length(which) > 1) cat('havehighlight',which,'\n')          
-          chunk <- c(chunk[1:(which-1)],hstyle,chunk[which:length(chunk)])
-          linesout <- linesout[c(1L:which, which, seq(from = which +
-              1L, length.out = length(linesout) - which))]
-          object$haveHighlightSyntaxDef <- TRUE
-        }
+      # always add the syntax definitions because there is no real way to
+      # check if a single code chunk as the option before hand.
+    if (!object$haveHighlightSyntaxDef){
+      
+        # get the latex style definitions from the highlight package
+      tf <- tempfile()
+      cat(styler('default', 'sty', styler_assistant_latex),sep='\n',file=tf)
+      cat(boxes_latex(),sep='\n',file=tf,append=T)
+      hstyle <- readLines(tf)
+
+
+        # find where to put the style definitions
+      begindoc <- "^[[:space:]]*\\\\documentclass.*$"
+      which <- grep(begindoc, chunk)
+
+        # add definitions for highlight environment
+      hstyle <- c(hstyle, "\\newenvironment{Houtput}{\\raggedright}{%\n%\n}")
+
+            # put in the style definitions after the \documentclass command
+      if(length(which)) {
+        chunk <- c(chunk[1:which],hstyle,chunk[(which+1):length(chunk)])
+        linesout <- linesout[c(1L:which, which, seq(from = which +
+            1L, length.out = length(linesout) - which))]
+        object$haveHighlightSyntaxDef <- TRUE
       }
+    }
+    
     while(length(pos <- grep(object$syntax$docexpr, chunk)))
     {
         cmdloc <- regexpr(object$syntax$docexpr, chunk[pos[1L]])
@@ -223,6 +164,7 @@
 
         chunk[pos[1L]] <- sub(object$syntax$docexpr, val, chunk[pos[1L]])
     }
+    
     while(length(pos <- grep(object$syntax$docopt, chunk)))
     {
         opts <- sub(paste(".*", object$syntax$docopt, ".*", sep=""),
@@ -312,13 +254,6 @@
   SweaveHooks(options, run=TRUE)
 
     # remove unwanted "#line" directives added by R 2.12
-  removeLineJunk <- function(chunk){
-    lines <- grep("#line", chunk)
-    srclines <- attr(chunk, "srclines")
-    chunk <- chunk[-lines]
-    attr(chunk, "srclines") <- srclines[-lines]
-    chunk
-  }
   chunk <- removeLineJunk(chunk)
 
   ## parse entire chunk block
@@ -331,17 +266,6 @@
 
   RweaveTryStop(chunkexps, options)
 
-  ## [CWB] Create a DB entry which is simply the digest of the text of
-  ## the chunk so that if anything has changed the chunk will be
-  ## recognised as having a change if ANYTHING gets changed, even white
-  ## space. this still doesnt fix the problem of actually caching the
-  ## plotting commands and others which do not create objects in the
-  ## global environment when they are evaluated but at least the figures
-  ## will get regenerated.
-  chunkTextEvalString <- paste("chunkText <- '",
-    digest(paste(chunk,collapse='')), "'", sep='')
-  attr(chunk, "digest") <- digest(paste(chunk,collapse=''))
-  ## end [CWB]
 
   ## Adding my own stuff here [RDP]
   ## Add 'chunkDigest' to 'options'
@@ -350,6 +274,8 @@
 
   openSinput <- FALSE
   openSchunk <- FALSE
+    # for the highlighted output environment
+  openHoutput <- FALSE
 
   if(length(chunkexps)==0)
     return(object)
@@ -419,6 +345,13 @@
         }
           cat("\\begin{Sinput}",file=chunkout, append=TRUE)
           openSinput <- TRUE
+      }else if(!openHoutput & options$highlight){
+
+          cat("\\begin{Houtput}\n",file=chunkout, append=TRUE)
+          linesout[thisline + 1] <- srcline
+          thisline <- thisline + 1
+          openHoutput <- TRUE
+
       }
 
          # Actual printing of chunk code
@@ -436,12 +369,13 @@
 
           if(nce == 1)
             cat(newline_latex(),file=chunkout, append=TRUE)
+
           highlight(parser.output=parser(text=dce),
             renderer=renderer_latex(document=FALSE),
             output = chunkout, showPrompts=TRUE,final.newline = TRUE)
               # highlight doesnt put in an ending newline for some reason
           cat(newline_latex(),file=chunkout, append=TRUE)
-          
+
         }
 
       }else{
@@ -464,18 +398,20 @@
         ## tmpcon <- textConnection("output", "w")
         ## avoid the limitations (and overhead) of output text connections
       tmpcon <- file()
+        ## collect output to temporary file
       sink(file=tmpcon)
       err <- NULL
 
+
+        # use the cacheSweave mechanism to cache objects
       if(options$eval) err <- cacheSweaveEvalWithOpt(ce, options)
-      ## [RDP] end change
 
       cat("\n") # make sure final line is complete
       sink()
       output <- readLines(tmpcon)
       close(tmpcon)
 
-      ## delete empty output
+        ## delete empty output
       if(length(output)==1 & output[1]=="") output <- NULL
 
       RweaveTryStop(err, options)
@@ -546,6 +482,11 @@
     thisline <- thisline + 1
   }
 
+  if(openHoutput){
+    cat("\\end{Houtput}\n", file=chunkout, append=TRUE)
+    linesout[thisline + 1] <- srcline
+    thisline <- thisline + 1
+  }
 
   if(is.null(options$label) & options$split)
     close(chunkout)
@@ -557,14 +498,18 @@
     thisline <- thisline + 1
   }
 
+  chunkChanged <- 
+    if( options$external )
+      hasChunkChanged(chunk,chunkprefix,options)
+    else
+      TRUE
+
   if(options$fig && options$eval){
 
-    ## [CWB] adding checking for external options
-    pdfExists <- file.exists(paste(chunkprefix, "pdf", sep="."))
-    epsExists <- file.exists(paste(chunkprefix, "eps", sep="."))
-
     if(options$eps & !options$pgf & !options$tikz){
-      if(!options$external | !epsExists ){
+        # Still apply graphics caching to postscript device
+        # only regenerate the image if the chunk has been changed.
+      if(!options$external | chunkChanged ){
 
           # [CWB] the useKerning option was added in R 2.9.0
           # so check for the R version and set the
@@ -588,7 +533,9 @@
       }
     }
     if(options$pdf & !options$pgf & !options$tikz){
-      if(!options$external | !pdfExists ){
+      # Still apply graphics caching to pdf device
+      # only regenerate the image if the chunk has been changed.
+      if(!options$external | chunkChanged ){
         grDevices::pdf(file=paste(chunkprefix, "pdf", sep="."),
           width=options$width, height=options$height,
           version=options$pdf.version, encoding=options$pdf.encoding)
@@ -614,7 +561,7 @@
     ##
 
     if(options$pgf){
-      if( !pdfExists ){
+      if( !options$external | chunkChanged ){
 
           # [CWB] the useKerning option was added in R 2.9.0
           # so check for the R version and set the
@@ -646,8 +593,9 @@
         if(inherits(err, "try-error")) stop(err)
       }
     }
-    if(options$tikz){
-      if(ifelse(options$tex.driver == "latex", !epsExists, !pdfExists)){
+
+    if( options$tikz ){
+      if( !options$external | chunkChanged ){
         tikzDevice::tikz(file=paste(chunkprefix, "tikz", sep="."),
           width=options$width, height=options$height,
           sanitize=options$sanitize)
@@ -660,57 +608,40 @@
         if(inherits(err, "try-error")) stop(err)
       }
     }
-    
-      # External option, write commands to externalize graphics if the 
-      # graphic file does not exist
-    if( options$external ){
-      if(ifelse(options$tex.driver == "latex", !epsExists, !pdfExists) && 
-         (!options$pdf && !options$eps)){
 
-        shellFile <- object[["shellFile"]]
-        tex.driver <- options[["tex.driver"]]
-
-        cat(tex.driver, ' --jobname=', chunkprefix,' ',
-          object[["srcfileName"]], '\n', sep='',  file=shellFile, append=TRUE)
-        if(tex.driver == "latex"){
-          cat('dvipdf ',paste(chunkprefix,'dvi',sep='.'), '\n', sep='',
-            file=shellFile, append=TRUE)
-          cat('pdftops -eps ',paste(chunkprefix,'pdf',sep='.'),
-            '\n', sep='', file=shellFile, append=TRUE)
-        }
-      }
-    }
-      # Write the extrnalization commands if the user does not want 
-      # to do it themselves already
+      # Write the extrnalization commands
     if(options$include && options$external) {
-      cat("\n\\beginpgfgraphicnamed{",chunkprefix,"}\n",sep="",
+      cat("\n\\tikzsetnextfilename{",chunkprefix,"}\n",sep="",
         file=object$output, append=TRUE)
+      cat("\n\\tikzexternalfiledependsonfile{",chunkprefix,"}{",
+        paste(chunkprefix, "tikz", sep="."),"}\n",sep="",
+        file=object$output, append=TRUE)
+        
       linesout[thisline + 1] <- srcline
       thisline <- thisline + 1
     }
+
       # Write the includegraphics command for eps or pdf 
       # only if we are not useing pgf or tikz
     if(options$include && !options$pgf && !options$tikz && !options$external) {
+
       cat("\\includegraphics{", chunkprefix, "}\n", sep="",
         file=object$output, append=TRUE)
       linesout[thisline + 1] <- srcline
       thisline <- thisline + 1
+
     }
       # input statements for tikz and pgf
     if(options$include && (options$pgf || options$tikz)) {
-      #if tikz takes precident over pgf option
+
+        #if tikz takes precident over pgf option
       suffix <- ifelse(options$tikz,'tikz','pgf')
       cat("\\input{", paste(chunkprefix,suffix,sep='.'),
         "}\n", sep="", file=object$output, append=TRUE)
       linesout[thisline + 1] <- srcline
       thisline <- thisline + 1
+
     }
-      # ending externalization command
-    if(options$include && options$external) {
-      cat("\\endpgfgraphicnamed\n",sep="",file=object$output, append=TRUE)
-      linesout[thisline + 1] <- srcline
-      thisline <- thisline + 1
-    }
     ##end graphics options [CWB]
     #############################################
   }

Modified: pkg/R/utilities.R
===================================================================
--- pkg/R/utilities.R	2011-01-17 00:02:51 UTC (rev 26)
+++ pkg/R/utilities.R	2011-02-22 19:15:17 UTC (rev 27)
@@ -16,199 +16,38 @@
 ##
 ################################################################################
 
-######################################################################
-## Take a 'filehash' database and insert a bunch of key/value pairs
-
-dumpToDB <- function(db, list = character(0), envir = parent.frame()) {
-        if(!is(db, "filehash"))
-                stop("'db' should be a 'filehash' database")
-        for(i in seq(along = list))
-                dbInsert(db, list[i], get(list[i], envir, inherits = FALSE))
-        invisible(db)
+removeLineJunk <- function(chunk){
+  lines <- grep("#line", chunk)
+  srclines <- attr(chunk, "srclines")
+  chunk <- chunk[-lines]
+  attr(chunk, "srclines") <- srclines[-lines]
+  chunk
 }
 
-copy2env <- function(keys, fromEnv, toEnv) {
-        for(key in keys) {
-                assign(key, get(key, fromEnv, inherits = FALSE), toEnv)
-        }
-}
-
-## Take an environment and return a copy.  Not an exact copy because
-## we don't get all keys (not sure why, but for some reason I remember
-## that getting all the keys caused problems.
-
-copyEnv <- function(from) {
-        env <- new.env(parent = parent.env(from))
-        keys <- ls(from, all.names = FALSE)
-
-        for(key in keys) 
-                assign(key, get(key, from, inherits = FALSE), env)
-        env
-}
-
-isNewOrModified <- function(specials, e1, e2) {
-        sapply(specials, function(s) {
[TRUNCATED]

To get the complete diff run:
    svnlook diff /svnroot/pgfsweave -r 27


More information about the Pgfsweave-commits mailing list