File: tangle.R

package info (click to toggle)
r-cran-xml 3.99-0.19-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,688 kB
  • sloc: ansic: 6,659; xml: 2,890; asm: 486; sh: 12; makefile: 2
file content (66 lines) | stat: -rw-r--r-- 2,096 bytes parent folder | download | duplicates (8)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#
# tangle code from an XML file to a collection of files
#

getXPathExpr =
function(language, nodeNames)
{
 paste(paste("//", unlist(outer(language, nodeNames, FUN = "paste", sep = ":")), sep = ""), collapse = "|")
}

getTargetFiles =
function(doc, language = names(xmlNamespaceDefinitions(doc)),
          nodeNames = c("code", "function", "plot", "class", "method"),
           xpath = getXPathExpr(language, nodeNames))
{
  if(is.character(doc))
    doc = xmlParse(doc)
  
  nodes = getNodeSet(doc, xpath)
  ans = structure(sapply(nodes, xmlGetAttr, "file"),
                    names = sapply(nodes, function(x) names(xmlNamespace(x)) ))

  ans = tapply(ans, names(ans), function(x) unique(unlist(x)))
  ans[ sapply(ans, length) != 0 ]
}

xmlTangle =
function(doc, files = getTargetFiles(doc, xpath = xpath), dir = ".",
         language = names(xmlNamespaceDefinitions(doc)),
         nodeNames = c("code", "function", "plot", "class", "method"),
           xpath = getXPathExpr(language, nodeNames))
{
  if(is.character(doc))
    doc = xmlParse(doc)

  if(length(files) == 0 && "r" %in% language) {
      return(tangleR(doc, out = NA))
  }
  
  files =
   structure(lapply(names(files),
                   function(ns) {
                     xp = paste("//", ns, ":", nodeNames, sep = "")
                     structure(sapply(files[[ns]],
                                      function(file) {
                                        expr = paste(xp, "[@file=", sQuote(file), "]", collapse = "|")
                                        paste(xpathSApply(doc, expr, xmlValue), collapse = "\n")
                                      }), names = files[[ns]])
                   }), names = names(files), class = "FileContentsList")

  if(!is.na(dir))
    save.FileContentsList (files, dir)
  else
    files
}

save.FileContentsList =
function(x, dir = ".")
{
  x = structure(unlist(x, recursive = FALSE), names = unlist(lapply(x, names)))
  files = paste(dir, names(x), sep = .Platform$file.sep)
  sapply(seq(along = files),
          function(i) cat(x[[i]], file = files[i]))
  files
}