Rescript formatting

I’m a bit lost with source formatting.

As I understand, formatting (old refmt) is embedded into the compiler (bsc).

I can only see a -format filename option right now: is it possible to use stdin to feed bsc with text to be formatted ? I suppose the answer is no, because I can’t find the -i option to specify if the code is an interface or not. Is it on the roadmap ?
also I don’t find the option to set the number of columns.

1 Like

The formatter is part of the bsc compiler. It currently recognises ReScript .res and .resi files automatically based on the file extension. You don’t need to supply an -i arg, it’s parsed from the extension.

The VSCode extension has an example on how to print code from the editor’s buffer:


It unfortunately requires a tempfile. Enhancing the format command with input from stdin would make this easier. The width arg is currently not exposed.

You confirm my worries.
I hope it’ll be reconsidered, because that will be a regression for all IntelliJ users.
I created this issue: https://github.com/rescript-lang/rescript-compiler/issues/4846.
I see that column width issue is already created: https://github.com/rescript-lang/rescript-compiler/issues/4838.
Thanks.

1 Like

So, how do u guys do formatting?

2 Likes

I wrote a script that reads from stdin, writes that to a temporarily file, formats it with bsc -format, then prints the result to stdout. I added it to my path, then setup my editor to call it on format.

As a bonus, it also will check for bsc in node_modules before checking for a system-wide installation (assuming you editor calls the format command from your project root)

#!/bin/sh

trap 'rm -f "$TMPFILE"' EXIT

TMPFILE=$(mktemp "refmt.XXXXXXXXXX.res" --tmpdir=/tmp)
echo "$(</dev/stdin)" > "$TMPFILE"

BSC=./node_modules/.bin/bsc
if test -f "$BSC"; then
  FORMAT_CMD="$BSC -format $TMPFILE"
  eval $FORMAT_CMD
  exit
fi

if command -v bsc &> /dev/null
then
  bsc -format "$TMPFILE"
  exit
fi
1 Like

Note in the master, we support in place formatting like this:

bsc -o output.res -format input.res # the flag order matters
5 Likes

Cool! The text editor is use (kakoune) which (to my understanding) requires the formatting command to read from stdin and print to stdout, then it will handle replacing the buffer contents. I’m not sure if in-place formatting would work in this case, because it would cause required the buffer to reload to get the formatted version.

In any case, good to know!

we are going to integrate this with rescript format subcommand
see this

4 Likes