Sublime Forum

Help with sending code from ST2 to R

#1

I use Sublime Text primarily for R code. I found a version of send selection to R in the package forum and have been using it. It sort of works, but it handles single quotes and double quotes poorly and inconsistently. That is, it works some of the time but not all of the time. Since the R syntax requires use of quotes (I can’t lose those entirely), I need to address this issue.

I am using this attached code (sits in a file called Send-Selection.py in my ~/Library/Application Support/Sublime Text 2/Packages/User folder. I run ST2 on OSX 10.7.3

import sublime, sublime_plugin
import os, subprocess, string

class SendSelectionCommand(sublime_plugin.TextCommand):
   @staticmethod
   def cleanString(str):
      str=string.replace(str,'"','\\"')
      str=string.replace(str,'\\','\\\\')
      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"):
            # define list of arguments
            args='osascript','-e','tell app "R64" to activate']
            # split selection into lines
            selection=self.cleanString(selection).split("\n")
            # add code lines to list of arguments
            for part in selection:
               args.extend('-e', 'tell app "R64" to cmd "' + part + '"\n'])
            # execute code and activate ST2
            p = subprocess.Popen(args)
            subprocess.Popen("""osascript -e 'tell app "Sublime Text 2" to activate' """, shell=True)

How it fails:

If I select this line source('../initialize.r') from a file called test.r (and ST2 recognizes that it is R), and press ⌘ + Enter, it does send the code to R, but escapes the so I get this error in my R interactive console:

[code]>source(…/initialize.r)
Error in source(…/initialize.r) : object ‘…’ not found

[/code]

How do I overcome this? Thanks for any advice and I am happy to clarify if anything I’ve said is unclear.

0 Likes