Question

I've run into a strange problem with Ruby that I can't explain. I have the following script that grabs whatever code is currently in the clipboard, runs it through a syntax highlighter, then puts the new version BACK into the clipboard:

#!/usr/bin/ruby1.9.1

require 'coderay'

language = "auto";
if(ARGV.length > 0)
    language = ARGV[0];
end

print("Using language: #{language} \n");

codeToHighlight = `xsel --clipboard`

highlightedCode = CodeRay.scan(codeToHighlight, language.intern()).div

IO.popen("xsel --clipboard", mode='w') do |io|
  io.write highlightedCode
  io.flush
end

The odd part is that if I run it directly within a terminal, it works fine. If I run it via "xterm -e", however, it doesn't work. I found this thread on another site that asked the same question, but the person never got an answer: http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/138423

That person found that if they added a pause at the end of the script like so...

10000.times do
   puts ""
end

...it works. Why is this? Is there a way to fix this? I tried rewriting the script so that the popen returns an IO object and I could manually call close, but that doesn't make a difference.

Was it helpful?

Solution

How about if you execute it with gnome-terminal -e instead of xterm -e?

UPDATE:

OK, here is my best guess. You know how if you send a terminal program to the background (either with & after the command or with ctl-z) and then you close the terminal it kills the program, right? Well, xsel forks a child process to write to the clipboard, but it must be getting killed when the ruby wrapper script finishes and and xterm closes.

That would explain why the pause at the end allows it to work - it just gives enough time for the child process to finish before the terminal quits. It also explains why it works when run manually - you leave the terminal open long enough for the child process to finish.

Try adding the -n option to your xsel command, and I bet it works. -n keeps xsel from forking.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top