Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jlecour/3550146 to your computer and use it in GitHub Desktop.
Save jlecour/3550146 to your computer and use it in GitHub Desktop.
Textmate bundle command to create a variable declaration with the contents of the selection.
#!/usr/bin/env ruby -wKU
# Save: Nothing
# Input: Document
# Output: Replace Input
# Caret Placement: Line Interpolation
COCOA_DIALOG_COMMAND = "#{ENV["TM_SUPPORT_PATH"]}/bin/CocoaDialog.app/Contents/MacOS/CocoaDialog"
def get_var_name
options = 'standard-inputbox --float --title "Variable Name" --focus-textbox --editable --text foo --informative-text "Enter a name for the variable"'
dialog_command = "\"#{COCOA_DIALOG_COMMAND}\" #{options}"
results = `#{dialog_command}`.split
results[0] == '1' && !results[1].nil? ? results[1].strip : nil
end
lines = STDIN.readlines()
result = lines # no change by default
if ENV.member?("TM_SELECTED_TEXT")
if (var_name = get_var_name)
line_and_cols = if ENV.member?("TM_SELECTION")
# selection is in format line:col-line:col eg: 5:3-5:15
# beware that the start of selection may be after the end of selection if the
# selection was made from right to left (or bottom to top)
l1, c1, l2, c2 = ENV["TM_SELECTION"].split('-').map {|x| x.split(':') }.flatten.map { |x| x.to_i - 1 }
else
l1, c1, l2, c2 = [
ENV["TM_INPUT_START_LINE"].to_i - 1,
ENV["TM_INPUT_START_LINE_INDEX"].to_i,
ENV["TM_LINE_NUMBER"].to_i - 1,
ENV["TM_LINE_INDEX"].to_i
]
# if the selection was made from right to left (or bottom to top)
# we need to compute the last character's index
if c2 == c1 && ENV["TM_SELECTED_TEXT"].length > 0
c2 = c1 + ENV["TM_SELECTED_TEXT"].length
end
end
if l1 > l2
l1, l2 = l2, l1
c1, c2 = c2, c1
elsif l1 == l2 && c1 > c2
c1, c2 = c2, c1
end
# Get the indention of the line at the start of the selection.
indent = lines[l1][/^\s*/].to_s
var_prefix = "#{var_name} = "
indent2 = indent + (" " * var_prefix.length)
selection = ENV["TM_SELECTED_TEXT"].strip.split("\n")
var_value = selection.first + "\n" + selection.drop(1).map {|s| indent2 + s.lstrip + "\n"}.join
var_decl = indent + var_prefix + var_value
replaced_selection = lines[l1][0...c1] + var_name + lines[l2][c2..-1]
result = lines[0...l1]
result += [var_decl, replaced_selection]
result += lines[l2+1..-1]
end
end
print result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment