I like to segment my code with comments. I don’t go nuts with it, but it helps me to have a visual delineation of what certain blocks of code do. Usually it will look something like this:
class Boat < ActiveRecord::Base
# validations ------------------------------------
validates_presence_of :name
validates_presence_of :pony
validates_presence_of :me
# callbacks --------------------------------------
def before_save
#...
end
# business ---------------------------------------
end
One problem I run into frequently is trying to keep a consistent right hand side margin with those comments. As the source code grows in length, it becomes increasingly hard to make sure that the right hand side lines up. Even if you’re not OCD, it becomes a bit ugly to have jagged right hand side edges for these comments. So I thought, this is the perfect time to create my first TextMate bundle.
I’ll spare you the details of my failures trying to figure out how to do this. The final macro ended up being Ruby code and made use of the environment variables that TextMate provides to these scripts. It also uses the TextMate::UI class to query the user for the text of the comment title. If text is already selected before the bundle command is invoked, that will be the default for the title.
#!/usr/bin/env ruby
require "#{ENV["TM_SUPPORT_PATH"]}/lib/exit_codes"
require "#{ENV["TM_SUPPORT_PATH"]}/lib/ui"
MAX_LENGTH = 80
if text = TextMate::UI.request_string(:title => "Title",
:prompt => "Comment Title:",
:default => ENV["TM_SELECTED_TEXT"])
result = "# "
result += text
result += " "
result += "-" * (MAX_LENGTH - result.length - ENV['TM_LINE_INDEX'].to_i)
print result
end
The use of the TM_LINE_INDEX environment variable gives us the column position of the caret on the current line. Using this allows us to ensure that the right hand side always lines up, no matter what indentation one starts on when creating the comment.
I bind the command to ctrl-opt-cmd-c.



If you use this, you probably will want to use the following settings for your macro in the bundle editor:

You can also download the bundle directly if you’d like.
