Search code examples
formulavimmaximaascii-art

vim script to insert ascii-art formulas


I try to use Vim as much as I can to learn it.
Today I had to write lots of mathematical functions. I wrote them like f(x)=e^(x/sqrt(x)) (nonsensefunction for example) but this is very hard to read.

My idea was to use the console output of maxima and insert it in the text to get something like:

             x
          -------
          sqrt(x)
f(x) := e

which is very easy to read.

I already know a lot of maxima commands so it would be very easy and productive for me to write formulas in the maxima syntax and get them in this wonderful output :)

I had absolutely no experience with vimscript. How can I do this?


Solution

  • i use this in my ~/.vimrc file:

     " calls maxima --very-quit -r "[ARG];"
     function! AsciiMath(formula)
       let cmdln='maxima --very-quiet -r "'.a:formula.';"'
       let @a=system(cmdln)
       if !v:shell_error
     "    echo @a
         put a
       else
         echo '"'.a:formula.'" is an invalid maxima expression"'
       endif
     endfunction 
    

    and call it like:
    :call AsciiMath("f(x):=e^(x/sqrt(x))")

    i think the function is straght forward to understand, but there are some tricky parts:

    • put requires a register as argument see :h registers and :h put
    • arguments cannot be used like formula they need the prefix (namespace) a: use it like a:formula.
    • if you have vim configured to reload the .vimrc file then you should use function! instead of function because otherwise you 'll get an error (something like "[FUNCTIONNAME] is allready defined")
    • system() returns the console output of its argument as returnvalue and puts the returnvalue of its argument in v:shell_error.