Last updated
Code Snippet Formatting
A code snippet formatter takes raw code and applies consistent formatting: indentation, spacing, line length limits, and language-specific conventions. Well-formatted snippets are easier to read in documentation, blog posts, and presentations. The key is using the right formatter for each language.
Formatting Principles
- Consistent indentation: 2 spaces for JS/HTML/CSS, 4 spaces for Python, tabs for Go.
- Line length: Keep lines under 80–100 characters for readability in narrow contexts.
- Trailing whitespace: Remove all trailing spaces and ensure a final newline.
- Blank lines: Use blank lines to separate logical sections, but not excessively.
- Comments: Keep comments in formatted output — they explain intent.
Formatting with Prettier API
JavaScript
import * as prettier from 'prettier';
async function formatSnippet(code, language) {
const parserMap = {
javascript: 'babel',
typescript: 'typescript',
css: 'css',
html: 'html',
json: 'json',
markdown: 'markdown',
yaml: 'yaml'
};
const parser = parserMap[language];
if (!parser) return code; // unsupported language
return prettier.format(code, {
parser,
printWidth: 80,
tabWidth: 2,
semi: true,
singleQuote: true,
trailingComma: 'es5'
});
}