Skip to content

Instantly share code, notes, and snippets.

@plapier

plapier/js2coffeescript.rb

Last active Dec 14, 2015
Embed
What would you like to do?
Convert Javascript to CoffeeScript (vice versa) directly from vim. Uses js2coffee library.
#!/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
@plapier

This comment has been minimized.

Copy link
Owner Author

@plapier plapier commented Feb 23, 2013

Requirement: https://github.com/rstacruz/js2coffee

Install

  1. Place this file in ~/bin/ and remove .rb extension
  2. $ chomd +x ~/bin/js2coffeescript
  3. Visual select (highlight) the lines you want to convert
  4. !js2coffeescript
    (The vim command should look like this :'<,'>!js2coffeescript)

Add this to your vim config:

" Convert Js to Coffee
vmap <Leader>jc <esc>:'<,'>!js2coffeescript<CR>

" Convert Coffee to JS
vmap <leader>cj <esc>:'<,'>!coffee -sbp<CR>

@andrewpthorp

This comment has been minimized.

Copy link

@andrewpthorp andrewpthorp commented Feb 23, 2013

Nice work!

@gabebw

This comment has been minimized.

Copy link

@gabebw gabebw commented Feb 23, 2013

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.

@unrealhoang

This comment has been minimized.

Copy link

@unrealhoang unrealhoang commented May 8, 2013

@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