Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

gregor.hoch

macrumors member
Original poster
Apr 5, 2011
51
6
Hi, I am trying to send some code from a text editor (Sublime Text 2) to R. The script is based on python and right now I am calling the shell from python and Applescript from the shell. It works in most cases but I am having problems with backslashes in the code I want to send. Below is the code and two examples. When I commend out str=string.replace(str,'\\','\\\\'), the code is send to R as print("""), which is no solution...
Any suggestions?

Thanks!

Example 1 (works):
print("test")
gives me this for cmd
Code:
osascript<<-END
  tell app "R"
  activate
  cmd "print(\"test\")"
  end tell
END

Example 2 - Error: is not send to R, terminal produced error (syntax error: Expected end of line, etc. but found unknown token. (-2741)):
print("\"")
gives me this for cmd
Code:
osascript<<-END
  tell app "R"
  activate
  cmd "print(\"\\\"\")"
  end tell
END


Code:
class SendSelectionCommand(sublime_plugin.TextCommand):	
	@staticmethod
	def cleanString(str):
		str=string.replace(str,'\\','\\\\')
		str=string.replace(str,'"','\\"')		
#		str=string.replace(str,"'",r"\'")
		return str

	def run(self, edit):
		# get selection	
		selection = ""
		for region in self.view.sel():
			selection+=self.view.substr(region) + "\n"
		selection = (selection[::-1].replace('\n'[::-1], '', 1))[::-1]

		# only proceed if selection is not empty
		if(selection!=""):
			extension = os.path.splitext(self.view.file_name())[1]

			# R file
			if(extension.lower()==".r"):
				cmd = 'osascript<<-END\n'
				cmd+= '  tell app "R"\n'
				cmd+= '  activate\n'
				selection=self.cleanString(selection).split("\n")
				for part in selection:
					cmd+= '  cmd "' + part + '"\n'					
				cmd+= '  end tell\nEND'			
				os.system(cmd)
				subprocess.Popen("""osascript -e 'tell app "Sublime Text 2" to activate' """, shell=True)
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.