Skip to content

Instantly share code, notes, and snippets.

@plapier
Last active December 14, 2015 02:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plapier/5018143 to your computer and use it in GitHub Desktop.
Save plapier/5018143 to your computer and use it in GitHub Desktop.
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
Copy link
Author

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
Copy link

Nice work!

@gabebw
Copy link

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
Copy link

@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