Skip to content

Instantly share code, notes, and snippets.

@hernan604
Last active August 29, 2015 14:00
Show Gist options
  • Select an option

  • Save hernan604/11073741 to your computer and use it in GitHub Desktop.

Select an option

Save hernan604/11073741 to your computer and use it in GitHub Desktop.
evaluate javascript in vim with perl + vim::x
package JsEval;
use strict;
use warnings;
use Vim::X;
use JavaScript::V8;
#ABSTRACT: Eval lines of js typed in vim. Use 'vim_log(args)' to print output
=head2 .vimrc
perl use JsEval;
map ,jseval :<c-u>call JsEval( line("'<"), line("'>") );
=head2 USAGE
You must have a file open in vim.
Type in a couple lines of javascript code, ie:
var x = 3;
var y = 4;
vim_log( x + y )
make the visual block on all those lines, and press ,jseval
see the results.
another example, type this in a file and visual select block and press ,jseval. It will vim_log the results, see the code below:
var Sumthing = ( function ( args ) {
"use strict";
var _this = this;
ATTRS: {
this.name = undefined;
this.age = undefined;
}
BUILD_ARGS: {
if ( args ) {
for ( var i in args ) {
if ( this.hasOwnProperty( i ) ) {
this[ i ] = args[ i ];
}
}
}
}
METHODS: {
this.say_hi = function ( ) {
return "Hi, my name is " + _this.name + ". I am " + _this.age + "yrs old.";
}
}
} )
var sumthing = new Sumthing( { "name" : "Joe", "age" : 62 } );
vim_log(sumthing.say_hi());
vim_log( "TYPEOF: " + typeof "" );
vim_log( "TYPEOF: " + typeof 2 );
vim_log( "TYPEOF: " + typeof Sumthing );
vim_log( "TYPEOF: " + typeof sumthing );
=cut
sub JsEval : Vim(args) {
my $range_init = shift;
my $range_end = shift;
my @range = ( $range_init .. $range_end );
my @lines = map { vim_line($_)->content } @range;
my $js_src = join "\n", @lines;
vim_delete(@range);
my $context = JavaScript::V8::Context->new( time_limit => 5 );
$context->bind_function( vim_log => sub { vim_cursor->append( @_ ) } );
$context->eval( $js_src );
}
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment