A code formatter for the Motoko smart contract language.

Overview

Motoko Formatter · npm version GitHub license PRs Welcome

A Prettier plugin for the Motoko programming language.


Setup

After making sure Node.js is installed on your local machine, run the following command in your Motoko project directory:

npm install --save-dev prettier prettier-plugin-motoko

Command-line usage

Format your Motoko files using the Prettier CLI:

npx prettier -- --write **/*.mo

Check if your Motoko files are correctly formatted:

npx prettier -- --check **/*.mo

Alternatively, check out mo-fmt for a standalone Motoko formatter CLI:

mo-fmt **/*
mo-fmt -c **/*

VS Code support

Customization

Configure the formatter by creating a .prettierrc file in your project directory (full documentation).

Example .prettierrc configuration with default values:

{
    "bracketSpacing": true,
    "printWidth": 80,
    "semi": true,
    "tabWidth": 2,
    "trailingComma": "es5",
    "useTabs": false
}

Multiple languages

Prettier will apply the same configuration to Motoko, JavaScript, CSS, HTML, and any other supported languages.

You can specifically configure Motoko files using a configuration override in your .prettierrc file:

{
    "overrides": [{
        "files": "*.mo",
        "options": {
            "bracketSpacing": true
        }
    }]
}

Ignoring code

Skip formatting a statement using a prettier-ignore comment:

// prettier-ignore
func ignored<A>(a:A){a};

func formatted<B>(b : B) { b };

Contributing

Feel free to submit a GitHub issue to report a bug or suggest a feature.

If you're interested in becoming an open-source contributor, be sure to check out the open issues in case anything catches your eye.

Comments
  • Bug: Record merging syntax with switch statement adds a semicolon instead of a comma

    Bug: Record merging syntax with switch statement adds a semicolon instead of a comma

    Example case:

    let person_1 = {
      name = "John";
      ageGroup = #minor";
    };
    
    let minor_permissions = { ... };
    let adult_permissions = { ... };
    
    let person_1_plus_permissions = person_1 and (
      switch(person1.ageGroup) {
        case (#minor) { minorPermissions };
        case (#adult) { adultPermissions };
      },  // prettier puts a `;` here instead of a `,`, which throws a syntax error
    );
    
    
    opened by ByronBecker 4
  • fix: '" at build time after format">

    fix: "unexpected token '>'" at build time after format

    Great work with the plugin 👍

    I gave it a try in Papyrs backend / providers (PR 21) and landed on following issue at build time after having formatted the code:

    /Users/daviddalbusco/.../storage.store.mo:96.5-96.6: syntax error [M0001], unexpected token '>', expected one of token or sequence:

    The root cause of the issue is the following type of function:

    private func update(key: Text, record: Data, putData: PutData): Result.Result<Data, Text> {
    

    Gets formatted to:

    private func checkTimestamp(record : Data, id : Text, updated_at : Time.Time) : Result.Result<
      Text,
      Text
    > {
    

    The Motoko compiler does not expect the last > to finds place on a new line. Adapting code manually as following fix the build issue:

    private func checkTimestamp(record : Data, id : Text, updated_at : Time.Time) : Result.Result<
      Text,
      Text> {
    

    dfx 0.11.1

    opened by peterpeterparker 3
  • Strange addition of space character

    Strange addition of space character

    Before formatting image

    After formatting image

    "Full" snippet:

    assertAllTrue([
      fundedPlan.size() == 1,
      failures.size() == 1,
      fundedPlan[0].2 == 500_000_000_000,
      fundedPlan[0].3 == { e8s = 50_000_000 },
      failures[0].2 == 1_000_000_000_000,
      failures[0].3 == 500_000_000_000,
    ]);
    
    opened by jorgenbuilder 1
  • Indentation differs from style guide

    Indentation differs from style guide

    According to the style guide, code should be indented with 2 spaces, currently 4 spaces are used.

    https://internetcomputer.org/docs/current/developer-docs/build/cdks/motoko-dfinity/style/#indentation

    Each level of indentation should be 2 spaces.

    opened by f0i 1
  • bug: using a quote in a comment breaks formatting

    bug: using a quote in a comment breaks formatting

    Issue

    While adding following comment to one of my canister, I noticed that the auto formatting was breaking - was generating an incorrect format for my code.

    /**
     * Does a bucket id exists? - i.e. not a bucket for a user but is a canister id linked to any user's bucket? 
     */
    

    After debugging I noticed that the root cause was using a quote ' in the comment. i.e. if I remove the quote, format is generated correctly.

    opened by peterpeterparker 1
  • Improve parenthesized expression wrapping

    Improve parenthesized expression wrapping

    Current behavior:

    test(
      "example test",
      func() {
        assert 1 == 1;
      },
    );
    

    Expected behavior(?):

    test("example test", func() {
      assert 1 == 1;
    });
    
    opened by rvanasa 1
  • Generics with comments are fun :)

    Generics with comments are fun :)

    canisters : HashMap.HashMap<
      // The principal of the canister.
      Principal, 
      // The configuration of the canister.
      CanisterConfig
    >;
    

    becomes

    canisters : HashMap.HashMap</* The principal of the canister. */ Principal, /* The configuration of the canister. */ CanisterConfig>;`
    
    opened by ByronBecker 4
  • multiline concatenated string formatted into one very long line

    multiline concatenated string formatted into one very long line

    using the experimental LS with dfx 0.11.2 the following happens Screenshot 2022-10-25 at 12 25 47

    IMO it would be nice if it would be formatted into multiple lines if the string exceeds a certain width to maintain readability

    https://github.com/flowerpowerdao/punks-nft-canister/pull/32/commits/521759d663068a907fdd95756e9ce823c4b7fe46#diff-303c0b742b59bc66b0e9f6e381809d383386ab3b0ba9cda25a74f1405fc411edL195-L196

    opened by letmejustputthishere 1
  • complex indenting example with odd behaviour

    complex indenting example with odd behaviour

    This was motoko code generated by Go. I try and make the generator as close to the prettified output as possible.

    image

    so then I put a newline after update(, and Ctrl-S

    image

    and then finally one after do { on line 81, and Ctrl-S

    image

    I've found myself just trying to enter random newlines to make it format correctly, and I wasn't sure this was the desired behaviour.

    opened by borovan 4
  • Format numbers for better readability

    Format numbers for better readability

    Enforce the [style guide recommendation](https://internetcomputer.org/docs/current/developer-docs/build/cdks/motoko-dfinity/style/#miscellaneous] for numbers:

    Group by 3 digits in decimal numbers and by 4 in hexadecimal notation.

    In addition, add leading zeros in hex notation to be 2 digits or a multiple of 4 digits.

    Examples:

    • 1000000 would be formatted as 1_000_000
    • 0x2 would be formatted as 0x02
    • 0x123456 would be formatted as 0x0012_3456
    • 12_34_56 would be formatted as 123_456
    • 0.123456 would be formatted as 0.123_456
    opened by f0i 0
  • There should be a space between comment marker and comment

    There should be a space between comment marker and comment

    After a comment marker (//) at least one space should be inserted to improve readability. Additional spaces should be preserved.

    Examples:

    • //some comment would be formatted as // some comment

    // module {
    //   asdf;
    //}
    

    would be formatted as

    // module {          <- keep one space
    //   asdf;           <- keep multiple spaces
    // }                 <- add one space
    
    opened by f0i 1
Releases(v0.2.7)
Owner
DFINITY
The Internet Computer aims to reinvent the internet as a computer to host secure software and a new breed of open internet services.
DFINITY
Hemsida för personer i Sverige som kan och vill erbjuda boende till människor på flykt

Getting Started with Create React App This project was bootstrapped with Create React App. Available Scripts In the project directory, you can run: np

null 4 May 3, 2022
Kurs-repo för kursen Webbserver och Databaser

Webbserver och databaser This repository is meant for CME students to access exercises and codealongs that happen throughout the course. I hope you wi

null 14 Jan 3, 2023
All-in-one code linter and formatter for TypeScript and JavaScript

Uniform is a CLI tool - code linter and formatter for JavaScript and TypeScript. Works using eslint and prettier under the hood.

Irakli Dautashvili 21 Feb 27, 2022
Write "hello world" in your native language, code "hello world" in your favorite programming language!

Hello World, All languages! ?? ?? Write "hello world" in your native language, code "hello world" in your favorite language! #hacktoberfest2022 How to

Carolina Calixto 6 Dec 13, 2022
A WASM shell parser and formatter with bash support, based on mvdan/sh

sh-syntax A WASM shell parser and formatter with bash support, based on mvdan/sh TOC Usage Install API Changelog License Usage Install # yarn yarn add

RxTS 7 Jan 1, 2023
Dead simple, single file, tiny byte formatter

tiny-byte-size Dead simple, no configuration needed, tiny byte formatter npm install tiny-byte-size Usage const byteSize = require('tiny-byte-size')

Mathias Buus 17 Aug 24, 2022
First smart contract deployed on Rinkeby.

Inbox-Contract First smart contract deployed on Rinkeby. It has a basic constructor which accpets a string and assigns the string to the message varia

Stanley Moukhametzianov 1 Dec 26, 2021
Web3-citizens-app - React application based on smart contract using web3 and MetaMask extention.

Citizens App (web3-react-redux) React application based on smart contract using web3 and MetaMask extention. Start the applicarion Recomend to install

Denys Voloshyn 3 Aug 25, 2022
Aergo Timer Service schedule smart contract function calls

Aergo Timer Service ⏰ Create timers to call functions on your smart contracts Schedule calls based on time interval or on specific date-times For a sm

aergo 3 Mar 10, 2022
Blockchain, Smart Contract, Ganache, Remix, Web3, Solidity, Java Script, MQTT, ESP32, RFID, DHT11,

Blockchain, Smart Contract, Ganache, Remix, Web3, Solidity, Java Script, MQTT, ESP32, RFID, DHT11,

Hajar OUAAROUCH 5 May 24, 2022
SmartBuilder: A Block-based Visual Programming Framework for Smart Contract Development

SmartBuilder A Block-based Visual Programming Framework for Smart Contract Development Technology stack used SmartBuilder Framework - Google Blockly A

ibelab 4 Mar 29, 2022
Ethereum smart contract gas cost waste pattern detection and patching tool

Ethereum smart contract gas cost waste pattern detection and patching tool

ibelab 4 Mar 23, 2022
A simple multilateral escrow smart contract for ETH and ERC-20 tokens governed by Cobie.

Multilateral Escrow Smart Contract Governed by Cobie Test Deployments Cobie's address: 0x4Cbe68d825d21cB4978F56815613eeD06Cf30152 Rinkeby: 0xFfE420602

Pascal Marco Caversaccio 28 Dec 15, 2022
This repository contains the Solidity smart contract of Enso, a detailed list of features and deployment instructions.

Enso NFT Smart Contract This repository contains the Solidity smart contract of Enso, a detailed list of features and deployment instructions. We stro

enso NFT 3 Apr 24, 2022
This is a development platform to quickly generate, develop & deploy smart contract based applications on StarkNet.

generator-starknet This is a development platform to quickly generate, develop, & deploy smart contract based apps on StarkNet. Installation First, in

Only Dust 34 Nov 18, 2022
Connect your Ethereum smart contract to any real world API using the oracle pattern!

Minimal Viable Oracle (MVO) - An effective way to Build your own oracle with Solidity Smart contracts cannot access off-chain data directly. This repo

Noah 9 Aug 25, 2022
In this repository, I try to perform a mainnet fork and then simulate popular smart contract exploits on various DEFI Protocols using Hardhat Framework.

defiHacks_via_Hardhat 1. Alchemix Access Control Bug Any user could have called setWhitelist() to give an attacker the ability to call the harvest fun

null 34 Dec 27, 2022
Pull a smart contract from mainnet onto your local chain.

hardhat-copy hardhat-copy helps you import an Ethereum mainnet smart contract onto your local Hardhat node, enabling you to rapidly experiment with pr

Alexander Thomas 6 Aug 21, 2022
🔆🔎👀 Smart Contract Storage Viewer, DataType Guesser, Toolbox & Transaction Decoder

?? ?? ?? Smart Contract Storage HexViewer Demo Target - the target contract API Endpoint - your infura (or equivalent) api key Retrieves smart contrac

tintin 85 Nov 27, 2022