Linux – How tonsert the result of a “.w” evaluation at the end of a line in Vim

command linelinuxvimvimrc

I'd like to be able to evaluate a line of Javascript (or other code) in Vim, and have the result appear in a comment at the end of the line.

For example, if I have a file like:

console.log(4 + 5);

and my cursor is on that line, and I use the command :.w !node -e, the result "9" will appear in the buffer below. if I use :. !node -e, the whole line will be replaced with the result, 9.

How can I instead create a command that will append the result to the line's end in a comment, like so:

console.log(4 + 5);    // 9

Also of note is that using :r will print whatever is passed to it in the next line. r !echo "This is text." will insert "This is text." on the line below the cursor. However a command like…

:r ". !node -e"

…will try to read ". !node -e" as a file instead of a command; I don't really understand this behavior, but it makes things a bit less intuitive.

I'd like the end result to be somewhat reminiscent of the way the Atom text editor handles Hydrogen kernels, with the result of the code eval appearing at the left of the code. The plan is to create a keybinding (<C-Enter> or <F5>) to auto-evaluate the current line and display the result.

Best Answer

If your lines look like: 4+5= you could use something like:

 :map  "_ay/=^Mo^[!!echo ^Ra \| bc^MkJ
  1. _ ............... to jump to start of actual line
  2. "ay/=^M ... to yank till = into buffer a
  3. o^[ ........... make a new empty line
  4. !! .............. start a shell program to write result into this new line
  5. ^Ra .......... insert content of buffer a in comand: echo ^Ra \| bc^M
  6. k .............. go to pevious line
  7. J .............. join next line (result) to aktual line
  8. perhaps you want to delete blank from joining with x

I hope this is what you are .