[TxMt] Re: Properly escaping characters in ruby script
Grant Hollingworth
grant at antiflux.org
Sat Apr 11 23:14:10 UTC 2009
* Ian Duncan [8-Apr-09 17:37]:
> #!/usr/bin/env ruby
> require "#{ENV['TM_SUPPORT_PATH']}/lib/escape"
> arg = STDIN.read
> arg.chomp!
> arg = e_as arg
> arg.gsub!("\`", "\\`")
> puts("pointfree \"" + arg + "\"")
>
> The puts is just for debugging purposes. When I run this command on
> the selected text:
>
> \x y -> x `div` y
>
> I am hoping to get:
>
> pointfree "\\x y -> x \`div\` y"
>
> But I get this instead:
>
> pointfree "\\x y -> x \\x y -> x div\\x y -> x `div y"
Short answer: use e_sn
Replacing backslashes is a pain. There are a few things going on:
1. the string interpretation
2. the regular expression engine also uses backslashes as the escape
character
3. \` means "the text before the match" -- that's why you're seeing
double
To fix it, you can:
1. add more toothpicks
arg.gsub('`', '\\\\`')
2. use the block form of gsub, which only evaluates the string once
arg.gsub('`') { '\`' }
3. match the space before the backtick, which is what e_sn does
arg.gsub(/(?=`)/, '\\')
More information about the textmate
mailing list