or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

cli.mdfile-processing.mdformatting.mdindex.md

formatting.mddocs/

0

# Code Formatting

1

2

Core formatting functionality that transforms JavaScript code using Prettier with Standard-compliant defaults. These functions provide direct access to formatting operations without file system interactions.

3

4

## Capabilities

5

6

### Format Function

7

8

Formats source code using Prettier with Standard-compliant defaults.

9

10

```javascript { .api }

11

/**

12

* Formats source code using Prettier with Standard-compliant defaults

13

* @param source - JavaScript source code to format

14

* @param options - Optional formatting options merged with Standard defaults

15

* @returns Formatted source code string

16

*/

17

function format(source, options);

18

```

19

20

**Default formatting options:**

21

- Single quotes instead of double quotes

22

- No semicolons

23

- Space before function parentheses

24

- Generator and yield star spacing enabled

25

- JSX single quotes

26

27

**Usage Examples:**

28

29

```javascript

30

const { format } = require('prettier-standard');

31

32

// Basic formatting

33

const code = 'function hello(){return"world";}';

34

const formatted = format(code);

35

// Result: 'function hello () {\n return \'world\'\n}\n'

36

37

// With custom options

38

const customFormatted = format(code, {

39

semi: true,

40

singleQuote: false

41

});

42

// Result: 'function hello () {\n return "world";\n}\n'

43

44

// TypeScript/JSX formatting

45

const jsxCode = '<div className="test">Hello</div>';

46

const formattedJsx = format(jsxCode, { parser: 'babel' });

47

```

48

49

### Check Function

50

51

Checks if source code is already formatted according to Standard rules without modifying it.

52

53

```javascript { .api }

54

/**

55

* Checks if source code is already formatted according to Standard rules

56

* @param source - JavaScript source code to check

57

* @param options - Optional formatting options merged with Standard defaults

58

* @returns Boolean indicating if code is properly formatted

59

*/

60

function check(source, options);

61

```

62

63

**Usage Examples:**

64

65

```javascript

66

const { check } = require('prettier-standard');

67

68

// Check properly formatted code

69

const goodCode = 'function hello () {\n return \'world\'\n}\n';

70

const isValid = check(goodCode);

71

// Result: true

72

73

// Check improperly formatted code

74

const badCode = 'function hello(){return"world";}';

75

const isInvalid = check(badCode);

76

// Result: false

77

78

// Check with custom options

79

const semiCode = 'function hello () {\n return "world";\n}\n';

80

const isValidSemi = check(semiCode, { semi: true, singleQuote: false });

81

// Result: true

82

```

83

84

### Format With Cursor

85

86

Formats source code while maintaining cursor position information.

87

88

```javascript { .api }

89

/**

90

* Formats source code while maintaining cursor position

91

* @param source - JavaScript source code to format

92

* @param options - Formatting options including cursorOffset

93

* @returns Object with formatted text and cursor position

94

*/

95

function formatWithCursor(source, options);

96

```

97

98

**Usage Examples:**

99

100

```javascript

101

const { formatWithCursor } = require('prettier-standard');

102

103

const result = formatWithCursor('function hello(){return"world";}', {

104

cursorOffset: 15 // Position in original code

105

});

106

107

console.log(result.formatted);

108

// Result: 'function hello () {\n return \'world\'\n}\n'

109

console.log(result.cursorOffset);

110

// Result: New cursor position in formatted code

111

```

112

113

### Format With Ranges

114

115

Formats specific character ranges within source code, useful for formatting only changed portions.

116

117

```javascript { .api }

118

/**

119

* Formats specific ranges within source code

120

* @param source - JavaScript source code to format

121

* @param ranges - Array of range objects with rangeStart and rangeEnd properties

122

* @param options - Optional formatting options

123

* @returns Formatted source code string

124

*/

125

function formatWithRanges(source, ranges, options);

126

```

127

128

**Usage Examples:**

129

130

```javascript

131

const { formatWithRanges } = require('prettier-standard');

132

133

const code = 'function hello(){return"world";}\nfunction goodbye(){return"farewell";}';

134

const ranges = [

135

{ rangeStart: 0, rangeEnd: 30 } // Format only first function

136

];

137

138

const formatted = formatWithRanges(code, ranges);

139

// Only the first function gets formatted

140

```

141

142

### Check With Ranges

143

144

Checks if specific character ranges within source code are properly formatted.

145

146

```javascript { .api }

147

/**

148

* Checks if specific ranges within source code are properly formatted

149

* @param source - JavaScript source code to check

150

* @param ranges - Array of range objects with rangeStart and rangeEnd properties

151

* @param options - Optional formatting options

152

* @returns Boolean indicating if all ranges are properly formatted

153

*/

154

function checkWithRanges(source, ranges, options);

155

```

156

157

**Usage Examples:**

158

159

```javascript

160

const { checkWithRanges } = require('prettier-standard');

161

162

const code = 'function hello () {\n return \'world\'\n}\nfunction bad(){return"bad";}';

163

const ranges = [

164

{ rangeStart: 0, rangeEnd: 35 } // Check only first function

165

];

166

167

const isValid = checkWithRanges(code, ranges);

168

// Result: true (only first function is checked)

169

```

170

171

### Get File Info

172

173

Gets file information for determining parser and formatting capabilities.

174

175

```javascript { .api }

176

/**

177

* Gets file information for a given file path

178

* @param filePath - Path to file for analysis

179

* @param options - Optional file info options

180

* @returns File information object with parser and formatting details

181

*/

182

function getFileInfo(filePath, options);

183

```

184

185

**Usage Examples:**

186

187

```javascript

188

const { getFileInfo } = require('prettier-standard');

189

190

const fileInfo = getFileInfo('example.js');

191

console.log(fileInfo.inferredParser); // 'babel'

192

console.log(fileInfo.ignored); // false

193

194

const tsInfo = getFileInfo('example.ts');

195

console.log(tsInfo.inferredParser); // '@typescript-eslint/parser'

196

```

197

198

### Resolve Config

199

200

Resolves Prettier configuration for a given file path.

201

202

```javascript { .api }

203

/**

204

* Resolves Prettier configuration for a given file path

205

* @param filePath - Path to resolve configuration for

206

* @param options - Configuration resolution options

207

* @returns Promise resolving to configuration object or null

208

*/

209

resolveConfig.sync(filePath, options);

210

resolveConfig(filePath, options); // Promise version

211

```

212

213

**Usage Examples:**

214

215

```javascript

216

const { resolveConfig } = require('prettier-standard');

217

218

// Synchronous config resolution

219

const config = resolveConfig.sync('/path/to/file.js', {

220

editorconfig: true

221

});

222

223

// Asynchronous config resolution

224

const config = await resolveConfig('/path/to/file.js', {

225

editorconfig: true

226

});

227

228

console.log(config); // { singleQuote: true, semi: false, ... }

229

```

230

231

### Clear Config Cache

232

233

Clears the internal configuration cache.

234

235

```javascript { .api }

236

/**

237

* Clears the internal configuration cache

238

*/

239

function clearConfigCache();

240

```

241

242

**Usage Examples:**

243

244

```javascript

245

const { clearConfigCache } = require('prettier-standard');

246

247

// Clear cache when configuration files change

248

clearConfigCache();

249

```

250

251

### Get Support Info

252

253

Gets information about supported languages, parsers, and file extensions.

254

255

```javascript { .api }

256

/**

257

* Gets information about supported languages, parsers, and file extensions

258

* @returns Object containing support information

259

*/

260

function getSupportInfo();

261

```

262

263

**Usage Examples:**

264

265

```javascript

266

const { getSupportInfo } = require('prettier-standard');

267

268

const supportInfo = getSupportInfo();

269

console.log(supportInfo.languages); // Array of supported languages

270

console.log(supportInfo.languages[0].extensions); // File extensions for first language

271

```

272

273

## Configuration Options

274

275

### Standard Defaults

276

277

Prettier Standard applies these defaults to ensure Standard compliance:

278

279

```javascript { .api }

280

const standardDefaults = {

281

spaceBeforeFunctionParen: true, // function () instead of function()

282

generatorStarSpacing: true, // function * gen() instead of function* gen()

283

yieldStarSpacing: true, // yield * expr instead of yield* expr

284

singleQuote: true, // 'hello' instead of "hello"

285

semi: false, // no semicolons

286

jsxSingleQuote: true // <div className='test'> instead of <div className="test">

287

};

288

```

289

290

### Parser Selection

291

292

If no parser is specified in options, the parser is automatically determined:

293

- Default parser: `'babel'` for most JavaScript files

294

- For stdin without filepath: `'babel'`

295

- File extension-based detection for TypeScript, CSS, JSON, etc.

296

297

## Error Handling

298

299

All formatting functions may throw errors for:

300

- **Syntax Errors**: Unparseable code will throw with descriptive error messages

301

- **Unsupported File Types**: Files with unsupported extensions or content

302

- **Invalid Options**: Malformed or conflicting formatting options

303

304

**Example error handling:**

305

306

```javascript

307

const { format } = require('prettier-standard');

308

309

try {

310

const formatted = format('function broken( { // Invalid syntax');

311

} catch (error) {

312

if (error.message.includes('SyntaxError')) {

313

console.error('Code has syntax errors:', error.message);

314

}

315

}

316

```