Banner of how-i-use-vim-to-do-quick-calculations-while-writing-latex-4.jpg

How I Use Vim to Do Quick Calculations While Writing LaTeX


Category: vim

📅 September 28, 2025   |   👁️ Views: 1

Author:   mosaid

Supercharging Vim: Running Python Code Directly from Your Editor

Running python directly in vim
Running python directly in vim

I've always loved Vim for its speed, simplicity, and ability to stay entirely in the terminal while doing serious work. But recently, I added a layer of magic that completely changed how I use it — running Python code directly from Vim without leaving the editor. This has been a game-changer, especially when editing LaTeX documents or writing technical content that needs quick calculations on the fly.

Imagine this: I'm writing an article and need to calculate a percentage or quickly check a value before putting it into my text. Instead of switching to a Python REPL or using a calculator, I just visually select the code, hit a keybinding, and Vim either shows me the result in a scratch buffer or replaces the selected text with the computed value. It's seamless, and it's awesome.

The Magic Behind It

Here’s what makes this possible — two small but powerful Vimscript functions that I added to my configuration. The first one runs any visually selected Python code and shows me the output in a new scratch buffer:

    
function! RunPythonSelection() range
    " Save current register and selection type
    let l:save_reg = getreg('"')
    let l:save_regtype = getregtype('"')

    " Yank the visually selected text into the default register
    normal! ""gvy
    let l:code = getreg('"')

    " Restore register
    call setreg('"', l:save_reg, l:save_regtype)

    " Trim leading/trailing whitespace
    let l:code = substitute(l:code, '^\s*', '', '')
    let l:code = substitute(l:code, '\s*$', '', '')

    " Run the exact selected text as Python code
    let l:output = system('python3 -c ' . shellescape(l:code))

    " Open a scratch buffer and display the output
    enew
    call setline(1, split(l:output, "\n"))
    setlocal buftype=nofile bufhidden=wipe noswapfile nowrap
endfunction


xnoremap  <leader>c :<C-u>call RunPythonSelection()<CR>

This function is brilliant for experimentation. I just highlight a few lines of Python, press <leader>c, and I get a temporary buffer with the result — no clutter in my main file, no switching windows.

But Wait, It Gets Better

Sometimes I don't just want to see the result, I want to replace the selected text with the result. That's where the second function comes in:

    
function! RunPythonAndReplace() range
    " Save current register and selection type
    let l:save_reg = getreg('"')
    let l:save_regtype = getregtype('"')

    " Yank visually selected text into the default register
    normal! ""gvy
    let l:code = getreg('"')

    " Restore register contents
    call setreg('"', l:save_reg, l:save_regtype)

    " Trim whitespace
    let l:code = substitute(l:code, '^\s*', '', '')
    let l:code = substitute(l:code, '\s*$', '', '')

    " Detect if selection is a single line
    if line("'<") == line("'>")
        let l:code = 'print(' . l:code . ')'
    endif

    " add some imports
    let l:code = 'from math import *;' . l:code

    " Run the code through Python
    let l:output = system('python3 -c ' . shellescape(l:code))

    " Remove trailing newline from output
    let l:output = substitute(l:output, '\n\+$', '', '')

    " Replace the selection with the output
    execute "normal! gv\"_c" . l:output
endfunction

xnoremap  <leader>r :<C-u>call RunPythonAndReplace()<CR>

This one is my favorite. Let's say I'm writing a LaTeX file and I have:

    
The success rate is $ (45/60)*100 $ \%.

I can just visually select (45/60)*100, hit <leader>r, and boom — it’s replaced with 75.0. This keeps me focused and lets me write accurate numbers without ever leaving my editor.

Running python directly in vim
Running python directly in vim

Why This Matters

Context Switching is the Enemy: Leaving Vim to open a calculator or REPL breaks flow. This solves that.

Perfect for Technical Writing: I use this trick while editing LaTeX code, which often requires quick math or unit conversions.

Great for Learning: You can experiment with Python right inside Vim, which is fantastic if you're learning to code or testing snippets.

Completely Customizable: These functions are just Vimscript — you can extend them, add error handling, or even log outputs to a file.

My Verdict

Vim was already my favorite editor, but these little functions make it feel like a true integrated environment. Whether I'm writing articles, preparing lecture notes, or hacking on LaTeX, I now have instant Python execution at my fingertips. And honestly, it feels like cheating — but in the best possible way.

If you use Vim and write technical documents or code, give these functions a try. They’ll make your workflow smoother, faster, and more fun.


← Quran Player Daemon: Audio Playback with Desktop Visualization