Archive

Archive for the ‘TextMate’ Category

TextMate Emacs-like indentation (for R files)

November 11, 2007 8 comments

If you use OS X, TextMate is hands down the best editor available for this platform. It integrate perfectly with the OS X environment. While the Project Window is probably the greatest thing about TextMate for the everyday user, its extensibility is what makes it a wonderful companion in editing.

The biggest complain I have about TextMate is that it does not handle indentation very well. I write a lot of R code and I am used to the indentation provided by ess (Emacs Speak Statistics). Frustrated, I decided to do something about it. After looking for option I realized that I could combine the feature of Emacs with those of TextMate to improve indentation. In practice I was able to use emacs (with ess) as beckend for the indentation. If you want to try follow the following steps:

1. Install ess (Emacs Speak Statistics) from http://ess.r-project.or in /usr/share/emacs/site-lisp;

2. In TextMate go to Bundles|Bundle Editor|Show Bundle Editor…

3. Create a new command, say Tidy

4. Add the following script:

#!/usr/bin/perl
my $in;
my $now = "tidyRcode";
my $file = "/tmp/tmptx_${now}.R";
my $eb=$ENV{'TM_BUNDLE_SUPPORT'};
open FILE, ">$file" or die "unable to open $file $!";
while () {
print FILE $_;
}
close(FILE);
`emacs -batch --eval "(require 'ess)" ${file} --eval '(indent-region (point-min) (point-max) nil)' -f ess-fix-miscellaneous -f save-buffer &> /dev/null`;
my $in = `cat ${file}`;
print $in;

5. Select the following options:

  • Input: Selected Text or Document;
  • Output: Replace Selected Text;
  • Key Equivalent: Shift+Cmd+H;
  • Scope Selector: source.r

You can see the picture below with my setting

TextMate Emacs-like indentation (for R files)

Now you are ready to go. While you are editing R code, simply select and press Shift+Cmd+H and you will see your code….the ess way.

UPDATE: The perl code does not work on Leopard (at least my Leopard with Emacs 22.1.1 + Textmate 1.5.9).

This version in Ruby works:

#!/usr/bin/ruby
require “ftools”
# Handle selection (less useful, probably) or full file.
tmp_file = “/tmp/textmate-tidy.#{$}.R”
selected = ENV['TM_SELECTED_TEXT'] || ”
if (selected.empty?)
raise(“No selected text or file.”) if (ENV['TM_FILEPATH'].empty?)
File.copy(ENV['TM_FILEPATH'], tmp_file)
else
File.open(tmp_file, ‘w’) { |fout| fout.print selected }
end
user = ENV['USER'] ||”
user_opt = “-u #{user}” unless (user.empty?)
cmd = “emacs -u \”#{user}\” -batch \”#{tmp_file}\” -eval \”(require ‘ess)\” -eval \”(indent-region (point-min) (point-max) nil)\” -f ess-fix-miscellaneous -f save-buffer &> /dev/null”
system(cmd) || raise(“Failed to indent with Emacs.”)
system(“cat #{tmp_file}”)
File.delete(tmp_file)
Categories: R, TextMate
Follow

Get every new post delivered to your Inbox.