A better file_regex for Ruby on Sublime Text for OS X: Fix double-clicking on errors in the build output window.

posted 2013-Jan-27

For a few days now I’ve noticed that when I run a Ruby file in Sublime Text that has an error and I double-click on that error line, it does not take me to the file where the error occurred. Instead, it opens a new tab with no contents and the title of the line. Phah. Moreover, when I double-click on a non-error line (to select some text) it does the same thing. Phah!

I tracked it down to a pretty bogus Ruby.sublime-build file. (You can find this file by going to Preferences ▸ Browse Packages… and then opening the Ruby folder. For me, this is /Users/phrogz/Library/Application Support/Sublime Text 2/Packages/Ruby/Ruby.sublime-build

Here’s what the file looks like:

{
  "cmd": ["/usr/local/bin/ruby", "$file"],
  "file_regex": "^(...*?):([0-9]*):?([0-9]*)",
  "selector": "source.ruby"
}

Pathetic. Specifically, that file_regex line is trying to capture the path to the file by taking the first 3+ characters at the start of the line up to a colon, and then maybe finding some digits as a line number, and then taking whatever comes after the next colon as the “error message” to display. The use of * quantifiers and optional colons, however, means that this will match any line that has a colon in it.

I decided to get much more specific. I get error messages that look like this on OS X:

/Users/phrogz/Code/scxmlrb/interpreter.rb:215:in `microstep': undefined local variable or method `bonkers' for <bob>:SCXML::Machine (NameError)
	from /Users/phrogz/Code/scxmlrb/interpreter.rb:95:in `block in step'
	from /Users/phrogz/Code/scxmlrb/interpreter.rb:45:in `loop'
	from /Users/phrogz/Code/scxmlrb/interpreter.rb:45:in `step'
	from /Users/phrogz/Code/scxmlrb/scxml.rb:47:in `<main>'

So, I changed my file_regex to the following:

{
  "cmd": ["/usr/local/bin/ruby", "$file"],
  "file_regex": "^(?:\\s+from )?(/[^:]+):(\\d+):in `.+?'(?:(: (.+)))?$",
  "selector": "source.ruby"
}

And now I can double-click on any error line in a stack trace and open the correct file and go to the correct line, I see the error message echoed in the status bar when I double-click on the error line, and (oddly, most importantly) I can double-click on text in non-error lines and Sublime doesn’t try to open a file that doesn’t exist.

Gavin Kistner
01:31PM ET
2014-Sep-17

Here is a reasonable replacement version for Windows, that allows colons in the path:
"file_regex": "^(?:\\tfrom )?(.+?):(\\d+):in `.+?(?:(: (.+)))?$"

net.mind details contact résumé other
Phrogz.net