Emacs/JuliaFormatter -- how to call a shell command on region

Posted on January 4, 2024
Tags: howto, emacs, julia

Quick reminder on how to write emacs lisp functions calling shell commands on the region.

In doom emacs based on emacs 29.1 with the julia-formatter.el package, I could not get a proper auto formatting to work in reasonable time, but I wanted to write an article in org-mode with a lot of julia source blocks, which I partly copy-pasted and which were therefore unformatted. For the moment I ended up writing a small emacs-lisp wrapper function to call the julia formatter from the commandline passing the current region or buffer as the stdin.

First I needed to install the JuliaFormatter.jl package:

] add JuliaFormatter

The simple cli onliner to format stdin is

julia -e 'import JuliaFormatter; print(JuliaFormatter.format_text(read(stdin, String)))'

This was wrapped in the shell-command-on-region called from interactive defuns:

(defun mnd/format-julia-region (p1 p2)
  (interactive "r")
  (shell-command-on-region p1 p2 "julia -e 'using JuliaFormatter; print(format_text(read(stdin, String)))'" nil t))

(defun mnd/format-julia-buffer ()
  (interactive)
  (mnd/format-julia-region (point-min) (point-max)))

The optional third (nil) and forth (t) arguments from the shell-command-on-region specify the output-buffer (nil) and whether to replace the region with the command’s stdout (t), respectively (see docstring).

Got the job done in less time than to dig into getting the emacs package to run.