DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Taisei
Taisei

Posted on • Updated on

Code Formatting in Nim [nim prettyοΌ½

This is my first post on dev. By the way, do you guys know Nim? It's an elegant language, compiles to C, and has a Python-like syntax. So it's very fast and easy to write. I've been using it for work recently. I was looking for a code formatting tool for it and finally found one called Nim pretty.

How to use Nim pretty

You can use it easily. Here's a sample code.

const     hello   =      "Hello"
echo   "Say, ",                      hello
Enter fullscreen mode Exit fullscreen mode

It's terrible syntax, right? Here's a way to format it.
You can run the following command.

nimpretty --indent:2 sample.nim
Enter fullscreen mode Exit fullscreen mode

The sample code can be formatted as follows.

const hello = "Hello"
echo "Say, ", hello
Enter fullscreen mode Exit fullscreen mode

The terrible code was formatted with an indent as 2.
It became quite readable but you don't want to run the command for each file, right?

Here's a better way. You can run the following command.

find . -name "*.nim" -exec nimpretty --indent:2 {} +
Enter fullscreen mode Exit fullscreen mode

All Nim files in a directory can be formatted. It's a combination of a Nim pretty command and shell script.

You can create a task in a nimble file as below if you don't want to type or copy the command every time.

version       = "0.0.1"
author        = "Sample"
description   = "Sample code"
license       = "Sample"

task pretty, "Formats all nim files":
  exec "find . -name '*.nim' -exec nimpretty --indent:2 {} +"
Enter fullscreen mode Exit fullscreen mode

And you can run the following command.

nimble pretty
Enter fullscreen mode Exit fullscreen mode

Then all Nim files can be formatted even if they are in different directories.

That's all. Any tips about Nim would be appreciated.
Thank you!!

Top comments (0)

12 Rarely Used Javascript APIs You Need

Practical examples of some unique Javascript APIs that beautifully demonstrate a practical use-case.