or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

index.md

index.mddocs/

0

# Prettier Plugin Solidity

1

2

A Prettier plugin that provides automatic code formatting for Solidity smart contracts. The plugin integrates seamlessly with Prettier's formatting ecosystem to ensure consistent, readable Solidity code across blockchain and Ethereum development projects.

3

4

## Package Information

5

6

- **Package Name**: prettier-plugin-solidity

7

- **Package Type**: npm

8

- **Language**: JavaScript (ES Modules)

9

- **Installation**: `npm install --save-dev prettier prettier-plugin-solidity`

10

11

## Core Imports

12

13

```javascript

14

// Default plugin import (ESM) - exports plugin object

15

import prettierPluginSolidity from "prettier-plugin-solidity";

16

17

// For use with Prettier API (same as default import)

18

import prettier from "prettier";

19

import solidityPlugin from "prettier-plugin-solidity";

20

```

21

22

For CommonJS environments:

23

24

```javascript

25

// CommonJS import (uses standalone build)

26

const prettierPluginSolidity = require("prettier-plugin-solidity");

27

28

// Explicit standalone build import

29

const solidityPlugin = require("prettier-plugin-solidity/standalone");

30

```

31

32

For browser environments:

33

34

```html

35

<script src="https://unpkg.com/prettier@latest"></script>

36

<script src="https://unpkg.com/prettier-plugin-solidity@latest"></script>

37

```

38

39

## Basic Usage

40

41

### Command Line Usage

42

43

```bash

44

# Format Solidity files with explicit plugin

45

npx prettier --write --plugin=prettier-plugin-solidity 'contracts/**/*.sol'

46

47

# Add to package.json scripts

48

{

49

"scripts": {

50

"format": "prettier --write --plugin=prettier-plugin-solidity 'contracts/**/*.sol'",

51

"lint": "prettier --list-different --plugin=prettier-plugin-solidity 'contracts/**/*.sol'"

52

}

53

}

54

```

55

56

### Configuration File Usage

57

58

```json

59

{

60

"plugins": ["prettier-plugin-solidity"],

61

"overrides": [

62

{

63

"files": "*.sol",

64

"options": {

65

"parser": "solidity-parse",

66

"printWidth": 80,

67

"tabWidth": 4,

68

"useTabs": false,

69

"singleQuote": false,

70

"bracketSpacing": false

71

}

72

}

73

]

74

}

75

```

76

77

### Programmatic Usage

78

79

```javascript

80

import prettier from "prettier";

81

import solidityPlugin from "prettier-plugin-solidity";

82

83

const solidityCode = `

84

contract Example{function test(){uint256 x=1+2;}}

85

`;

86

87

const formatted = await prettier.format(solidityCode, {

88

parser: "solidity-parse",

89

plugins: [solidityPlugin]

90

});

91

92

console.log(formatted);

93

// Output: properly formatted Solidity code

94

```

95

96

### Browser Usage

97

98

```javascript

99

// After loading scripts

100

async function formatSolidity(code) {

101

return await prettier.format(code, {

102

parser: "solidity-parse",

103

plugins: [prettierPlugins.solidityPlugin]

104

});

105

}

106

107

const originalCode = 'contract Foo {}';

108

const formattedCode = await formatSolidity(originalCode);

109

```

110

111

## Architecture

112

113

The plugin follows Prettier's plugin architecture with these core components:

114

115

- **Parser Integration**: Uses @solidity-parser/parser for AST generation

116

- **Node Printers**: 70+ specialized formatters for different Solidity syntax elements

117

- **Comment Handling**: Preserves and formats comments according to context

118

- **Compiler Compatibility**: Adapts formatting based on Solidity compiler version

119

- **Options System**: Configurable formatting preferences for different coding styles

120

121

## Capabilities

122

123

### Main Plugin Export

124

125

The default export provides the complete Prettier plugin configuration.

126

127

```javascript { .api }

128

/**

129

* Default export containing the complete Prettier plugin configuration

130

*/

131

interface PrettierPluginSolidity {

132

/** Language definitions for Solidity */

133

languages: LanguageSupport[];

134

/** Parser configurations */

135

parsers: { [parserName: string]: Parser };

136

/** Printer configurations */

137

printers: { [astFormat: string]: Printer };

138

/** Plugin-specific options */

139

options: OptionsDefinition;

140

/** Default formatting options */

141

defaultOptions: DefaultOptions;

142

}

143

144

interface LanguageSupport {

145

/** Linguist language identifier */

146

linguistLanguageId: number;

147

/** Language name */

148

name: string;

149

/** Programming language type */

150

type: string;

151

/** Syntax highlighting color */

152

color: string;

153

/** ACE editor mode */

154

aceMode: string;

155

/** TextMate scope */

156

tmScope: string;

157

/** File extensions */

158

extensions: string[];

159

/** Available parsers */

160

parsers: string[];

161

/** VS Code language identifiers */

162

vscodeLanguageIds: string[];

163

}

164

```

165

166

### Parser Configuration

167

168

Solidity source code parsing with AST generation and compiler-specific transformations.

169

170

```javascript { .api }

171

/**

172

* Parser configuration for Solidity code

173

*/

174

interface Parser {

175

/** AST format identifier */

176

astFormat: string;

177

/** Parse function */

178

parse: (text: string, parsers?: any, options?: ParseOptions) => SolidityAST;

179

/** Location start function */

180

locStart: (node: ASTNode) => number;

181

/** Location end function */

182

locEnd: (node: ASTNode) => number;

183

}

184

185

interface ParseOptions {

186

/** Solidity compiler version for compatibility */

187

compiler?: string;

188

/** Enable experimental ternary formatting */

189

experimentalTernaries?: boolean;

190

/** Quote preference for hex literals */

191

singleQuote?: boolean;

192

[key: string]: any;

193

}

194

195

interface SolidityAST {

196

/** AST node type */

197

type: string;

198

/** Child nodes */

199

children?: SolidityAST[];

200

/** Source location information */

201

loc?: SourceLocation;

202

/** Source range information */

203

range?: [number, number];

204

/** Associated comments */

205

comments?: Comment[];

206

[key: string]: any;

207

}

208

```

209

210

### Printer Configuration

211

212

AST to formatted code conversion with support for all Solidity language constructs.

213

214

```javascript { .api }

215

/**

216

* Printer configuration for Solidity AST

217

*/

218

interface Printer {

219

/** Main print function */

220

print: (path: ASTPath, options: PrintOptions, print: PrintFunction) => string;

221

/** Comment attachment predicate */

222

canAttachComment: (node: ASTNode) => boolean;

223

/** Comment handling functions */

224

handleComments: CommentHandlers;

225

/** Block comment detection */

226

isBlockComment: (comment: Comment) => boolean;

227

/** AST cleaning function */

228

massageAstNode: (node: ASTNode, newNode: ASTNode, parent: ASTNode) => ASTNode;

229

/** Comment printer */

230

printComment: (commentPath: CommentPath) => string;

231

}

232

233

interface CommentHandlers {

234

/** Handle own-line comments */

235

ownLine: (comment: Comment, text: string, options: PrintOptions) => void;

236

/** Handle end-of-line comments */

237

endOfLine: (comment: Comment, text: string, options: PrintOptions) => void;

238

/** Handle remaining comments */

239

remaining: (comment: Comment, text: string, options: PrintOptions) => void;

240

}

241

242

interface PrintOptions {

243

/** Line width for wrapping */

244

printWidth: number;

245

/** Tab width in spaces */

246

tabWidth: number;

247

/** Use tabs instead of spaces */

248

useTabs: boolean;

249

/** Spaces around brackets */

250

bracketSpacing: boolean;

251

/** Use single quotes */

252

singleQuote: boolean;

253

/** Solidity compiler version */

254

compiler?: string;

255

/** Enable experimental ternaries */

256

experimentalTernaries?: boolean;

257

[key: string]: any;

258

}

259

```

260

261

### Formatting Options

262

263

Configurable options for customizing Solidity code formatting behavior.

264

265

```javascript { .api }

266

/**

267

* Available formatting options for Solidity code

268

*/

269

interface OptionsDefinition {

270

/** Line width configuration */

271

printWidth: OptionDefinition<number>;

272

/** Tab width configuration */

273

tabWidth: OptionDefinition<number>;

274

/** Tab usage configuration */

275

useTabs: OptionDefinition<boolean>;

276

/** Bracket spacing configuration */

277

bracketSpacing: OptionDefinition<boolean>;

278

/** Quote style configuration */

279

singleQuote: OptionDefinition<boolean>;

280

/** Experimental ternary configuration */

281

experimentalTernaries: OptionDefinition<boolean>;

282

/** Compiler version configuration */

283

compiler: OptionDefinition<string>;

284

}

285

286

interface OptionDefinition<T> {

287

/** Option introduction version */

288

since?: string;

289

/** Option category */

290

category: string;

291

/** Option type */

292

type: string;

293

/** Default value */

294

default: T;

295

/** Option description */

296

description: string;

297

/** Opposite description for boolean options */

298

oppositeDescription?: string;

299

/** Numeric range constraints */

300

range?: { start: number; end: number; step: number };

301

}

302

303

interface DefaultOptions {

304

/** Default bracket spacing setting */

305

bracketSpacing: boolean;

306

/** Default tab width setting */

307

tabWidth: number;

308

}

309

```

310

311

### Node Type Support

312

313

The plugin provides formatting support for all Solidity language constructs through specialized node printers.

314

315

```javascript { .api }

316

/**

317

* Supported Solidity AST node types with dedicated formatters

318

*/

319

type SupportedNodeTypes =

320

// Core language constructs

321

| "SourceUnit" | "PragmaDirective" | "ImportDirective"

322

// Contract structures

323

| "ContractDefinition" | "InheritanceSpecifier"

324

| "StateVariableDeclaration" | "FunctionDefinition"

325

| "ModifierDefinition" | "EventDefinition" | "CustomErrorDefinition"

326

| "StructDefinition" | "EnumDefinition" | "EnumValue"

327

// Type system

328

| "ElementaryTypeName" | "UserDefinedTypeName" | "FunctionTypeName"

329

| "ArrayTypeName" | "Mapping" | "TypeDefinition"

330

// Statements

331

| "Block" | "ExpressionStatement" | "VariableDeclarationStatement"

332

| "IfStatement" | "ForStatement" | "WhileStatement" | "DoWhileStatement"

333

| "BreakStatement" | "ContinueStatement" | "ReturnStatement"

334

| "EmitStatement" | "RevertStatement" | "TryStatement" | "CatchClause"

335

| "UncheckedStatement" | "ThrowStatement"

336

// Expressions

337

| "BinaryOperation" | "UnaryOperation" | "Conditional"

338

| "FunctionCall" | "MemberAccess" | "IndexAccess" | "IndexRangeAccess"

339

| "NewExpression" | "TupleExpression" | "NameValueExpression"

340

// Literals

341

| "BooleanLiteral" | "NumberLiteral" | "DecimalNumber" | "HexNumber"

342

| "StringLiteral" | "HexLiteral" | "Identifier"

343

// Assembly

344

| "InlineAssemblyStatement" | "AssemblyBlock" | "AssemblyCall"

345

| "AssemblyIf" | "AssemblyFor" | "AssemblySwitch" | "AssemblyCase"

346

| "AssemblyAssignment" | "AssemblyLocalDefinition" | "AssemblyStackAssignment"

347

| "AssemblyFunctionDefinition" | "AssemblyMemberAccess"

348

// Declarations

349

| "VariableDeclaration" | "UsingForDeclaration" | "FileLevelConstant"

350

| "ModifierInvocation" | "NameValueList" | "LabelDefinition";

351

```

352

353

### Comment Handling

354

355

Intelligent comment preservation and formatting that maintains code readability.

356

357

```javascript { .api }

358

/**

359

* Comment handling utilities

360

*/

361

interface CommentUtilities {

362

/** Check if comment is block-style */

363

isBlockComment: (comment: Comment) => boolean;

364

/** Print comment with appropriate formatting */

365

printComment: (commentPath: CommentPath) => string;

366

/** Handle prettier-ignore comments */

367

hasNodeIgnoreComment: (node: ASTNode) => boolean;

368

}

369

370

```

371

372

### Compiler Compatibility

373

374

Version-specific formatting adaptations for different Solidity compiler versions.

375

376

```javascript { .api }

377

/**

378

* Compiler version compatibility features

379

*/

380

interface CompilerCompatibility {

381

/** Check if compiler version satisfies range */

382

satisfies: (version: string, range: string) => boolean;

383

/** Apply version-specific AST transformations */

384

applyVersionTransforms: (ast: SolidityAST, version: string) => SolidityAST;

385

}

386

387

/**

388

* Compiler version milestones affecting formatting

389

*/

390

type CompilerMilestones = {

391

/** v0.7.4: Multi-line import support */

392

"0.7.4": "multiline-imports";

393

/** v0.8.0: Exponentiation operator precedence changes */

394

"0.8.0": "exponentiation-precedence";

395

};

396

```

397

398

### Utility Functions

399

400

Helper functions for string formatting and compatibility checks.

401

402

```javascript { .api }

403

/**

404

* Utility functions used throughout the plugin

405

*/

406

interface PluginUtilities {

407

/** Format string literals with proper quoting */

408

printString: (content: string, options: PrintOptions) => string;

409

/** Check Prettier version compatibility */

410

prettierVersionSatisfies: (range: string) => boolean;

411

/** Detect prettier-ignore comments on nodes */

412

hasNodeIgnoreComment: (node: ASTNode) => boolean;

413

}

414

```

415

416

## Types

417

418

```javascript { .api }

419

interface ASTNode {

420

/** Node type identifier */

421

type: string;

422

/** Source location information */

423

loc?: SourceLocation;

424

/** Source range */

425

range?: [number, number];

426

/** Associated comments */

427

comments?: Comment[];

428

[key: string]: any;

429

}

430

431

interface SourceLocation {

432

/** Start position */

433

start: Position;

434

/** End position */

435

end: Position;

436

}

437

438

interface Position {

439

/** Line number (1-based) */

440

line: number;

441

/** Column number (0-based) */

442

column: number;

443

}

444

445

interface ASTPath {

446

/** Get current node */

447

getValue: () => ASTNode;

448

/** Get parent node */

449

getParentNode: (level?: number) => ASTNode;

450

/** Call function with child path */

451

call: <T>(fn: (path: ASTPath) => T, ...names: (string | number)[]) => T;

452

/** Map over child paths */

453

map: <T>(fn: (path: ASTPath, index: number) => T, ...names: (string | number)[]) => T[];

454

}

455

456

interface Comment {

457

/** Comment type */

458

type: "BlockComment" | "LineComment";

459

/** Comment content */

460

value: string;

461

/** Source location */

462

loc: SourceLocation;

463

/** Source range */

464

range: [number, number];

465

}

466

467

interface CommentPath {

468

/** Get current comment */

469

getValue: () => Comment;

470

[key: string]: any;

471

}

472

473

type PrintFunction = (path: ASTPath) => string;

474

```