[Sciviews-commits] r212 - in komodo/SciViews-K: content content/js content/js/tools templates

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Thu Oct 15 19:34:24 CEST 2009


Author: prezez
Date: 2009-10-15 19:34:23 +0200 (Thu, 15 Oct 2009)
New Revision: 212

Modified:
   komodo/SciViews-K/content/RHelpWindow.xul
   komodo/SciViews-K/content/js/commands.js
   komodo/SciViews-K/content/js/r.js
   komodo/SciViews-K/content/js/tools/file.js
   komodo/SciViews-K/content/js/tools/strings.js
   komodo/SciViews-K/content/rsearch.html
   komodo/SciViews-K/templates/.Rprofile
Log:
New function: sv.r.pager to display text files generated by R.
.RProfile modified for R to use RHelp window as 'pager' and 'browser' (try ? and ?? commands from R)


Modified: komodo/SciViews-K/content/RHelpWindow.xul
===================================================================
--- komodo/SciViews-K/content/RHelpWindow.xul	2009-10-14 16:42:12 UTC (rev 211)
+++ komodo/SciViews-K/content/RHelpWindow.xul	2009-10-15 17:34:23 UTC (rev 212)
@@ -64,7 +64,7 @@
 var rHelpTopic;
 
 
-function go(uri) {
+function go(uri, loadFlags) {
 	// these are still undefined when calling .go on load event,
 	// so define them here:
 
@@ -81,7 +81,6 @@
 		}, false);
 		return;
 	}
-	//alert(uri);
 
 	if (uri) {
 		rHelpTopic.value = uri;
@@ -96,7 +95,7 @@
 
 	if (isUri) {
 		// This looks like a URL
-		rHelpBrowser.webNavigation.loadURI(uri, null, null, null, null);
+		rHelpBrowser.webNavigation.loadURI(uri, loadFlags, null, null, null);
 	} else {
 		// Look for this 'topic' web page
 		sv.r.help(uri);
@@ -234,7 +233,8 @@
 function rHelpSearch(topic) {
 	if (!topic)	return;
 
-	rHelpBrowser.webNavigation.loadURI("chrome://sciviewsk/content/rsearch.html?" + encodeURIComponent(topic),
+	rHelpBrowser.webNavigation.loadURI("chrome://sciviewsk/content/rsearch.html?" +
+					encodeURIComponent(topic),
 					rHelpBrowser.webNavigation.LOAD_FLAGS_NONE,
 					null, null, null);
 }

Modified: komodo/SciViews-K/content/js/commands.js
===================================================================
--- komodo/SciViews-K/content/js/commands.js	2009-10-14 16:42:12 UTC (rev 211)
+++ komodo/SciViews-K/content/js/commands.js	2009-10-15 17:34:23 UTC (rev 212)
@@ -363,7 +363,7 @@
 				if (!isUri) {
 					if (isWin)
 						uri = uri.replace(/\//g, "\\");
-					uri = sv.tools.file.getURI(sv.tools.file.getfile(uri));
+					uri = sv.tools.file.getURI(uri);
 				}
 			} catch (e) {
 				// fallback:

Modified: komodo/SciViews-K/content/js/r.js
===================================================================
--- komodo/SciViews-K/content/js/r.js	2009-10-14 16:42:12 UTC (rev 211)
+++ komodo/SciViews-K/content/js/r.js	2009-10-15 17:34:23 UTC (rev 212)
@@ -672,6 +672,22 @@
 	return(res);
 }
 
+
+sv.r.pager = function(file, title) {
+	var rSearchUrl = "chrome://sciviewsk/content/rsearch.html";
+	var content = sv.tools.file.read(file);
+	//content = content.replace(/([\w\.\-]+)::([\w\.\-]+)/ig, '<a href="javascript:sv.r.help(\'$2\', \'$1\');">$1::$2</a>');
+	content = content.replace(/([\w\.\-]+)::([\w\.\-]+)/ig,
+		'<a href="' + rSearchUrl + '?$1::$2">$1::$2</a>');
+
+	content = "<pre id=\"rPagerTextContent\" title=\"" + title + "\">" + content + "</div>";
+
+	sv.tools.file.write(file, content, sv.socket.charset);
+	sv.command.openHelp(rSearchUrl + "?file:" + file);
+}
+
+
+
 // The callback for sv.r.search
 //TODO: make private
 sv.r.search_select = function (topics) {
@@ -724,6 +740,7 @@
 
 	idxname = idxsep + idxname.join(idxsep);
 
+	// TODO: make it a pref:
 	var url = "http://search.r-project.org/cgi-bin/namazu.cgi?query=" + topic +
 	"&max=20&result=normal&sort=score" + idxname;
 
@@ -731,9 +748,8 @@
 
 }
 
-
-
 // List available datasets ("loaded" or not defined = loaded packages, or "all")
+// TODO: display results in RHelp window
 sv.r.dataList = function (which) {
 	var res = false;
 	if (typeof(which) == "undefined" | which == "" | which == "loaded") {
@@ -1183,6 +1199,8 @@
 		file.create(DIRECTORY_TYPE, 511);
 	}
 	// ... also make sure that Data, Script and Report subdirs exist
+	// [KB] I find this behavior with creating, often unneeded, dirs quite annoying.
+	// TODO: create these directories only when written to.
 	var subdirs = [datadir, scriptdir, reportdir];
     for (var i in subdirs) {
 		if (subdirs[i] != "") {
@@ -1234,9 +1252,11 @@
 	dir = sv.r.initSession(dir, datadir, scriptdir, reportdir);
 
 	// Switch to the new session directory in R
-	cmd = cmd + 'setwd("' + dir + '")\noptions(R.initdir = "' + dir + '")\n';
+	cmd = cmd + 'setwd("' + dir.addslashes() + '")\noptions(R.initdir = "'
+	+ dir.addslashes() + '")\n';
 
 	// Do we load .RData and .Rhistory?
+	// TODO: loadhistory APPENDS a history. Make R clear the current history first.
 	if (loadNew) {
 		cmd = cmd + 'if (file.exists(".RData")) load(".RData")\n' +
 					 'if (file.exists(".Rhistory")) loadhistory()\n';
@@ -1251,7 +1271,7 @@
         // Break possible partial multiline command in R from previous session
         // and indicate that we are in a new session now in the R console
         // TODO: report if we load something or not
-        sv.r.escape('cat("Session directory is now ' + dir +
+        sv.r.escape('cat("Session directory is now ' + dir.addslashes() +
             '\n", file = stderr())');
 		// Refresh active objects support
 

Modified: komodo/SciViews-K/content/js/tools/file.js
===================================================================
--- komodo/SciViews-K/content/js/tools/file.js	2009-10-14 16:42:12 UTC (rev 211)
+++ komodo/SciViews-K/content/js/tools/file.js	2009-10-15 17:34:23 UTC (rev 212)
@@ -216,6 +216,11 @@
 	}
 
 	this.getURI = function(file) {
+		if (typeof file == "string") {
+			file = this.getfile(file);
+		}
+		if (!file)	return null;
+
 		var ios = Components.classes["@mozilla.org/network/io-service;1"].
                     getService(Components.interfaces.nsIIOService);
 		var URL = ios.newFileURI(file);
@@ -227,7 +232,7 @@
 		var fileSvc = Components.classes["@activestate.com/koFileService;1"]
 			.getService(Components.interfaces.koIFileService);
 		var file = fileSvc.getFileFromURI(uri);
-		file.open(0);
+		file.open('r');
 		var res = file.readfile();
 		file.close();
 		return res;

Modified: komodo/SciViews-K/content/js/tools/strings.js
===================================================================
--- komodo/SciViews-K/content/js/tools/strings.js	2009-10-14 16:42:12 UTC (rev 211)
+++ komodo/SciViews-K/content/js/tools/strings.js	2009-10-15 17:34:23 UTC (rev 212)
@@ -34,16 +34,17 @@
 // changes a string to a regular expression
 sv.tools.strings.toRegex = function (str) {
 	// brackets
-	str = str.replace(/([\(\)\[\]])/g, "\\$1");
-
-	// TODO: anything else
+	str = str.replace(/([\]\(\\\*\+\?\|\{\[\(\)\^\$\.\#])/g, "\\$1")
+		.replace(/\t/g, "\\t")	//.replace(/ /, "\\s")
+		.replace(/\n/g, "\\n")	.replace(/\r/g, "\\r")
+		.replace(/\f/g, "\\f");
 	return(str);
 }
 
 // Get filename or last directory name in a file path
 sv.tools.strings.filename = function (str) {
 	// Under Windows, replace \ by /
-	if (navigator.platform.indexOf("Win") > -1) {
+	if (navigator.platform.indexOf("Win") == 0) {
 		str = str.replace(/[\\]/g, "/");
 	}
 	// Remove last trailing '/'
@@ -55,24 +56,35 @@
 }
 
 
+sv.tools.strings.addslashes = function(str) {
+	// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
+	return str.replace(/([\\"'])/g, "\\$1").replace(/\x00/g, "\\0").replace(/\u0000/g, "\\0");
+}
+
+
+sv.tools.strings.trim = function (str, which) {
+	if (!which) which == "both";
+	var rx;
+	switch(which) {
+		case "left": rx = /^\s+/g; break;
+		case "right": rx = /\s+$/g; break;
+		default: rx = /^\s+|\s+$/g; break;
+	}
+	return str.replace(rx, '');
+}
+
 //// Additional methods to String objects //////////////////////////////////////
 // Trim function for String
-String.prototype.trim = function () {
-	return this.replace(/^\s+|\s+$/g, '');
-}
+String.prototype.trim = function() sv.tools.strings.trim(this);
 
 // Right trim
-String.prototype.rtrim = function () {
-	return this.replace(/\s+$/, '');
-}
+String.prototype.rtrim = function() sv.tools.strings.trim(this, "right");
 
 // Left trim
-String.prototype.ltrim = function () {
-	return this.replace(/^\s+/, '');
-}
+String.prototype.ltrim = function() sv.tools.strings.trim(this, "left");
 
 // Add slashes
-String.prototype.addslashes = function () {
-	// original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
-	return this.replace(/([\\"'])/g, "\\$1").replace(/\x00/g, "\\0");
-}
+String.prototype.addslashes = function () sv.tools.strings.addslashes(this);
+
+// Escape string for regular expression
+String.prototype.regExpEscape = function() sv.tools.strings.toRegex(this);

Modified: komodo/SciViews-K/content/rsearch.html
===================================================================
--- komodo/SciViews-K/content/rsearch.html	2009-10-14 16:42:12 UTC (rev 211)
+++ komodo/SciViews-K/content/rsearch.html	2009-10-15 17:34:23 UTC (rev 212)
@@ -48,11 +48,15 @@
 			return;
 
 		var doc = document;
-		var out = doc.getElementById("results");
 
-		while (out.childNodes.length) out.removeChild(out.firstChild);
+		var header = doc.body.appendChild(doc.createElement("h1"));
+		header.textContent = "Search results";
 
+		var out = doc.body.appendChild(doc.createElement("div"));
 
+		//while (out.childNodes.length) out.removeChild(out.firstChild);
+
+
 		data = data.split(/[\r\n]+/);
 		var p = doc.createElement("p");
 		p.appendChild(doc.createTextNode('Search text was: "' + data[0].replace(/(^\s+|\s+$)/g, "") + '"'));
@@ -104,19 +108,53 @@
 }
 
 
+function rHelp (topic, pkg) {
+	var res = false;
+
+	if (!topic && !pkg) {
+		return false;
+	} else {
+		var cmd = '';
+		cmd += pkg? ' package = "' + pkg + '", ' : "";
+		cmd += topic? ' topic = "' + topic + '", ' : "";
+		cmd = 'cat(unclass(help(' + cmd + ' htmlhelp = TRUE)))';
+
+		res = sv.r.evalCallback(cmd, function(path) {
+			rHelpWin.go("file://" + path,
+				Components.interfaces.nsIWebNavigation
+				.LOAD_FLAGS_REPLACE_HISTORY);
+		});
+	}
+	return res;
+}
+
+
 function init() {
 	rHelpWin = _getWindowByURI(rHelpXulUri);
 	sv = rHelpWin.sv;
 
-	askR(decodeURIComponent(document.location.search.replace(/^\?/, "")));
+	var topic = decodeURIComponent(document.location.search.replace(/^\?/, ""));
+
+	if (topic.indexOf("file:") == 0) {
+		topic = topic.substr(5);
+
+		var content = document.createElement("body");
+		content.innerHTML = sv.tools.file.read(topic);
+		rHelpWin.document.title = document.title = content.firstChild.getAttribute("title");
+		document.body = content;
+	} else {
+		var matches = topic.match(/([\w\.\-\_]+)::([\w\.\-\_]+)/i);
+		if (matches) {
+			rHelp(matches[2], matches[1]);
+		} else {
+			askR(topic);
+		}
+
+	}
 }
 
-
 </script>
 </head>
 
-<body onload="init();">
-<h1>Search results:</h1>
-<div id="results"></div>
-</body>
+<body onload="init();"></body>
 </html>

Modified: komodo/SciViews-K/templates/.Rprofile
===================================================================
--- komodo/SciViews-K/templates/.Rprofile	2009-10-14 16:42:12 UTC (rev 211)
+++ komodo/SciViews-K/templates/.Rprofile	2009-10-15 17:34:23 UTC (rev 212)
@@ -2,10 +2,18 @@
 # SciViews-R installation and startup for running R with Komodo/SciViews-K
 # Version 0.9.0, 2009-09-20 Ph. Grosjean (phgrosjean at sciviews.org)
 
-# TODO: Include all this as a function in svMisc??
+#TODO: Include all this as a function in svMisc??
+#TODO: [KB] Fix problem with installing sv* packages when not running R as root.
+#      R tries to install them forever, and finally crashes my Ubuntu (Bug #685)
+
 # Make sure we don't process this twice in case of duplicate items in .Rprofile
+svStart <- function(){
+# [KB] Wrapped this in a function, so we can be sure it does not leave any garbage or
+#      overwrites user's objects.
+
 if (!exists(".SciViewsReady", envir = .GlobalEnv)) {
-	.SciViewsReady <- FALSE
+
+	assign(".SciViewsReady", FALSE, .GlobalEnv)
 	minVersion <- c(R = "2.8.0", svMisc = "0.9-53", svSocket = "0.9-48", svGUI = "0.9-46")
 
 	# First of all, check R version... redefine compareVersion() because it is
@@ -31,13 +39,10 @@
 	} else res <- TRUE
 
 	# Load main R packages
-	if (res) res <- require(methods, quietly = TRUE)
-	if (res) res <- require(datasets, quietly = TRUE)
-	if (res) res <- require(utils, quietly = TRUE)
-	if (res) res <- require(grDevices, quietly = TRUE)
-	if (res) res <- require(graphics, quietly = TRUE)
-	if (res) res <- require(stats, quietly = TRUE)
+	res <- all(sapply(c("methods", "datasets", "utils", "grDevices", "graphics", "stats"),
+				  function(x) require(x, quietly = TRUE, character.only = TRUE)))
 
+
 	# Get environment variables
 	if (res) {
 		args <- commandArgs()
@@ -142,87 +147,53 @@
 		# Load packages svMisc, svSocket & svGUI (possibly after installing
 		# or upgrading them). User is supposed to agree with this install
 		# from the moment he tries to start and configure R from Komodo Edit
+
+		pkgs <- c("svMisc", "svSocket", "svGUI")
 		ext <- switch(.Platform$pkgType,
 			mac.binary = "\\.tgz",
 			win.binary = "\\.zip",
 			"\\.tar.gz")
 
-		## svMisc
-		file <- dir(pattern = paste("svMisc", ext, sep = ".+"))
-		file <- sort(file)[length(file)]	# Keep newest one found
-		desc <- system.file("DESCRIPTION", package = "svMisc")
-		if (desc == "") {
-			cat("Installing missing package 'svMisc'\n")
-			if (length(file)) {
-				install.packages(file, repos = NULL) # or use "http://R-Forge.R-project.org"
-				res <- require(svMisc, quietly = TRUE)
-			} else res <- FALSE
-		} else { # Check version
-			if ((compareVersion(packageDescription("svMisc", fields = "Version"),
-				minVersion["svMisc"]) < 0)) {
-				cat("Updating package 'svMisc'\n")
+		res <- sapply(pkgs, function(pkgName) {
+			file <- dir(pattern = paste(pkgName, ext, sep = ".+"))
+			file <- sort(file)[length(file)]	# Keep newest one found
+			desc <- system.file("DESCRIPTION", package = pkgName)
+			if (desc == "") {
+				cat("Installing missing package", sQuote(pkgName), "\n")
 				if (length(file)) {
-					install.packages(file, repos = NULL)
-					res <- require(svMisc, quietly = TRUE)
+					install.packages(file, repos = NULL) # or use "http://R-Forge.R-project.org"
+					res <- require(pkgName, quietly = TRUE, character.only = TRUE)
 				} else res <- FALSE
-			} else res <- require(svMisc, quietly = TRUE)
-		}
-
-		## svSocket
-		file <- dir(pattern = paste("svSocket", ext, sep = ".+"))
-		file <- sort(file)[length(file)]	# Keep newest one
-		desc <- system.file("DESCRIPTION", package = "svSocket")
-		if (desc == "") {
-			cat("Installing missing package 'svSocket'\n")
-			if (length(file)) {
-				install.packages(file, repos = NULL)
-				res[2] <- require(svSocket, quietly = TRUE)
-			} else res[2] <- FALSE
-		} else { # Check version
-			if ((compareVersion(packageDescription("svSocket", fields = "Version"),
-				minVersion["svSocket"]) < 0)) {
-				cat("Updating package 'svSocket'\n")
-				if (length(file)) {
-					install.packages(file, repos = NULL)
-					res[2] <- require(svSocket, quietly = TRUE)
-				} else res[2] <- FALSE
-			} else res[2] <- require(svSocket, quietly = TRUE)
-		}
-
-		## svGUI
-		file <- dir(pattern = paste("svGUI", ext, sep = ".+"))
-		file <- sort(file)[length(file)]	# Keep newest one
-		desc <- system.file("DESCRIPTION", package = "svGUI")
-		res[3] <- TRUE
-		if (desc == "") {
-			cat("Installing missing package 'svGUI'\n")
-			if (length(file)) {
-				install.packages(file, repos = NULL)
-			} else res[3] <- FALSE
-		} else { # Check version
-			if ((compareVersion(packageDescription("svGUI", fields = "Version"),
-				minVersion["svGUI"]) < 0)) {
-				cat("Updating package 'svGUI'\n")
-				if (length(file)) {
-					install.packages(file, repos = NULL)
-				} else res[3] <- FALSE
+			} else { # Check version
+				if ((compareVersion(packageDescription(pkgName, fields = "Version"),
+					minVersion[pkgName]) < 0)) {
+					cat("Updating package", sQuote(pkgName), "\n")
+					if (length(file)) {
+						install.packages(file, repos = NULL)
+						res <- require(pkgName, quietly = TRUE, character.only = TRUE)
+					} else res <- FALSE
+				} else res <- require(pkgName, quietly = TRUE, character.only = TRUE)
 			}
-		}
-		rm(desc, ext, file)
+			return(res)
+		})
+
+		rm(ext)
 		# Try starting the R socket server now
 		if (inherits(try(startSocketServer(port = getOption("ko.serve")),
 			silent = TRUE), "try-error")) {
+
 			cat("Impossible to start the SciViews R socket server\n(socket",
 				getOption("ko.serve"), "already in use?)\n")
 			cat("Solve the problem, then type: require(svGUI)\n")
 			cat("or choose a different port for the server in Komodo\n")
+
 		} else {
 			# Finally, load svGUI
-			if (res[3]) res[3] <- require(svGUI, quietly = TRUE)
+			if (res["svGUI"]) res["svGUI"] <- require("svGUI", quietly = TRUE)
 
 			if (all(res)) {
 				cat("R is SciViews ready!\n")
-				.SciViewsReady <- TRUE
+				assign(".SciViewsReady", TRUE, .GlobalEnv)
 
 				# Indicate what we have as default packages
 				options(defaultPackages = c("datasets", "utils", "grDevices",
@@ -245,26 +216,17 @@
 
 		# A custom pager consists in displaying the file in Komodo
 		svPager <- function (files, header, title, delete.file) {
-			# Note: header and title are NOT used here!
-			# Create full path for files in current directory
-			nodir <- dirname(files) == "."
-			files[nodir] <- file.path(getwd(), files[nodir])
-			# Make sure that files exists
-			if (!all(file.exists(files)))
-				warning("One or more files are not found on the disk!")
-			# We display those files using options(editor) settings
-			cmds <- paste('"', getOption("editor"), '" ', files, sep = "")
-			for (cmd in cmds) {
-				res <- try(system(cmd), silent = TRUE)
-				if (inherits(res, "try-error"))
-					warning("Error running ", cmd)
+			files <- gsub("\\", "\\\\", files[1], fixed = TRUE)
+			koCmd(paste("sv.r.pager(", files, ",", title ,")", sep="\""))
+			if (delete.file) {
+				koCmd(paste("window.setTimeout(try { sv.tools.file.getfile(", files, ").remove(false); } catch(e) {}, 10000);", sep="\""))
 			}
-			# Do we delete these files?
-			# FIXME: if we delete the file, Komodo will not be able to read it
-			# so, currently, we don't delete the file (but need something else!)
-			#if (delete.file) unlink(files)
 		}
 
+		svBrowser <- function(url) {
+			koCmd(paste("sv.command.openHelp(", gsub("\\", "\\\\", url, fixed = TRUE), ")", sep="\""))
+		}
+
 		# Look if and where komodo is installed
 		if (.Platform$OS.type == "unix") {
 			if (Sys.getenv("koAppFile") != "") {
@@ -283,8 +245,7 @@
 					"otherwise, R cannot find it!", sep="\n")
 			} else {
 				# Change the editor and the pager to Komodo
-				options(editor = Komodo)
-				options(pager = svPager)
+				options(editor = Komodo, browser = svBrowser, pager = svPager)
 			}
 		} else {
 		    # if komodo path was passed in environment
@@ -312,8 +273,7 @@
 					"You can find it at http://www.activestate.com/Products/komodo_edit.\n")
 			} else {
 				# Change the editor and the pager to Komodo
-				options(editor = Komodo)
-				options(pager = svPager)
+				options(editor = Komodo, browser = svBrowser, pager = svPager)
 			}
 			options(warn = owarn)
 			rm(owarn)
@@ -325,6 +285,7 @@
 		if (.Platform$OS.type == "windows") options(chmhelp = FALSE)
 		options(htmlhelp = TRUE)
 
+
 		# Change the working directory to the provided directory
 		setwd(getOption("R.initdir"))
 
@@ -381,4 +342,14 @@
 		invisible(koCmd("sv.socket.updateCharset();"));
 	}
 }
+
+
+}
+
+
+
+svStart()
+
+rm(svStart)
+
 ### SciViews install end ###



More information about the Sciviews-commits mailing list