Last active
December 14, 2015 02:59
-
-
Save plapier/5018143 to your computer and use it in GitHub Desktop.
Convert Javascript to CoffeeScript (vice versa) directly from vim.
Uses js2coffee library.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'tempfile' | |
file = Tempfile.new(['js2coffee', '.js']) | |
file.write ARGF.read # write vim selection to tmp file | |
file.rewind | |
file.close | |
puts `js2coffee #{file.path}` # requires js2coffee | |
file.unlink # deletes the temp file |
Nice work!
Nicely done.
I have one idea, which avoids writing a file (which means this version might be faster than the version that does create a file).
#!/usr/bin/env ruby
input = ARGF.read
# requires js2coffee
output = `js2coffee <<EOJS\n#{input}\nEOJS`
puts output
This uses ZSH's/Bash's here document syntax to pass the input as a big chunk of text to js2coffee. Instead of passing it a path to a file, it passes in the actual contents of the file.
This ends up sending this command to the shell:
js2coffee <<EOJS
var cool = true;
function square(x) {
return x * x;
}
EOJS
The <<EOJS
marks the start of a big chunk of text, and EOJS
marks the end of the chunk of text. You can use PHIL
or whatever instead of EOJS
, they just need to match.
@gabebw I tried your solution but still got Invalid Token due to the BOM header.
So I modified your solution a bit
#!/usr/bin/env ruby
input = ARGF.read.gsub("\xEF\xBB\xBF", '')
# requires js2coffee
output = `js2coffee <<EOJS\n#{input}\nEOJS`
puts output
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Requirement: https://github.com/rstacruz/js2coffee
Install
~/bin/
and remove.rb
extension$ chomd +x ~/bin/js2coffeescript
!js2coffeescript
(The vim command should look like this
:'<,'>!js2coffeescript
)Add this to your vim config: