Skip to content

Commit

Permalink
initial version
Browse files Browse the repository at this point in the history
  • Loading branch information
simonhaenisch committed Aug 27, 2024
0 parents commit ff18244
Show file tree
Hide file tree
Showing 11 changed files with 327 additions and 0 deletions.
20 changes: 20 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
root = true

[*]
indent_style = tab
indent_size = 2
tab_width = 2
end_of_line = lf
charset = utf-8
insert_final_newline = true
trim_trailing_whitespace = true

[package.json]
indent_style = space

[*.yml]
indent_style = space

[*.md]
indent_style = space
trim_trailing_whitespace = false
1 change: 1 addition & 0 deletions .github/funding.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
github: simonhaenisch
26 changes: 26 additions & 0 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Tests

on: push

jobs:
test:
strategy:
matrix:
os: ['ubuntu-latest', 'macos-latest', 'windows-latest']
node: [18, 20, 22]

runs-on: ${{ matrix.os }}

name: Node.js ${{ matrix.node }} on ${{ matrix.os }}

steps:
- uses: actions/checkout@v4

- name: Use Node.js ${{ matrix.node }}
uses: actions/setup-node@v4
with:
node-version: ${{ matrix.node }}

- run: npm install

- run: npm test
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
1 change: 1 addition & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package-lock=false
17 changes: 17 additions & 0 deletions index.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { Plugin } from 'prettier';

/**
* Declaration merging for the `prettier` module.
*/
declare module 'prettier' {
export interface Options {
titleCase?: string;
}

export interface ParserOptions {
titleCase?: string;
}
}

declare const plugin: Plugin;
export default plugin;
76 changes: 76 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
/// <reference types="./index.d.ts" />
// @ts-check

import { parsers } from 'prettier/plugins/markdown';
import { titleCase } from 'title-case';

/**
* Set `convertHeadingsToTitleCase` as the given parser's `preprocess` hook, or merge it with the existing one.
*
* @param {import('prettier').Parser} parser prettier parser
*/
const withTitleCasePreprocess = (parser) => {
return {
...parser,
/**
* @param {string} code
* @param {import('prettier').ParserOptions} options
*/
preprocess: (code, options) =>
convertHeadingsToTitleCase(
parser.preprocess ? parser.preprocess(code, options) : code,
options,
),
};
};

/**
* Convert all headings to title case using the `title-case` package.
*
* @param {string} code
* @param {import('prettier').ParserOptions} options
*/
const convertHeadingsToTitleCase = (code, options) => {
try {
const titleCaseOptions = options.titleCase
? JSON.parse(options.titleCase)
: undefined;

return code
.split('\n')
.map((line) => {
if (!line.startsWith('#')) {
return line;
}

const content = line.replace(/^#+/, '').trim();

return line.replace(content, titleCase(content, titleCaseOptions));
})
.join('\n');
} catch (error) {
if (process.env.DEBUG) {
console.error(error);
}

return code;
}
};

/**
* @type {import('prettier').Plugin}
*/
export default {
options: {
titleCase: {
type: 'string',
default: undefined,
category: 'TitleCase',
description:
'JSON-stringified object with options for the `title-case` package.',
},
},
parsers: {
markdown: withTitleCasePreprocess(parsers.markdown),
},
};
40 changes: 40 additions & 0 deletions index.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// @ts-check

import test from 'ava';
import * as prettier from 'prettier';

/**
* @param {string} code
* @param {prettier.Options} [options]
*/
const prettify = async (code, options) =>
prettier.format(code, {
plugins: ['./index.js'],
filepath: 'file.md',
...options,
});

test('converts headings to title case', async (t) => {
const formattedCode = await prettify(
'# test One\n\nlorem ipsum\n\n## test two',
);

t.is(formattedCode, '# Test One\n\nlorem ipsum\n\n## Test Two\n');
});

test('ignores additional # chars in the heading', async (t) => {
const formattedCode = await prettify('### A heading with a # in it');

t.is(formattedCode, '### A Heading with a # in It\n');
});

test('passes title-case options from the prettier config', async (t) => {
const formattedCode = await prettify(
'# some sentence - Only affects the first word!',
{
titleCase: JSON.stringify({ sentenceCase: true }),
},
);

t.is(formattedCode, '# Some sentence - Only affects the first word!\n');
});
21 changes: 21 additions & 0 deletions license
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) Simon Hänisch

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
55 changes: 55 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
{
"name": "prettier-plugin-md-title-case",
"version": "1.0.0",
"description": "Make Prettier convert your Markdown headings to title-case.",
"keywords": [
"prettier",
"prettier-plugin",
"markdown",
"title-case"
],
"type": "module",
"main": "index.js",
"types": "index.d.ts",
"scripts": {
"test": "ava --verbose",
"preversion": "npm test"
},
"files": [
"index.d.ts"
],
"author": "Simon Haenisch (https://github.com/simonhaenisch)",
"license": "MIT",
"repository": "simonhaenisch/prettier-plugin-md-title-case",
"homepage": "https://github.com/simonhaenisch/prettier-plugin-md-title-case#readme",
"dependencies": {
"title-case": "^4.3.1"
},
"peerDependencies": {
"prettier": "3"
},
"devDependencies": {
"@types/node": "22.5.0",
"ava": "6.1.3",
"prettier": "3.3.3",
"prettier-plugin-organize-imports": "4.0.0"
},
"prettier": {
"plugins": [
"prettier-plugin-organize-imports",
"./index.js"
],
"singleQuote": true,
"overrides": [
{
"files": [
".js",
".ts"
],
"options": {
"useTabs": true
}
}
]
}
}
69 changes: 69 additions & 0 deletions readme.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/simonhaenisch/prettier-plugin-md-title-case/test.yml?label=CI)](https://github.com/simonhaenisch/prettier-plugin-md-title-case/actions?query=branch%3Amaster)

# Prettier Plugin: Markdown Title Case

> Make sure that your Markdown headings stay consistent no matter who writes them.
A plugin that makes Prettier convert your markdown headings to title case using the [title-case](https://npmjs.com/packages/title-case) npm package.

**Features**

- 🚀 Zero config (but configurable).
- 🤓 No more inconsistent headings.
- 🤙 No more fixing other people's titles.

**Caveat**

This plugin inherits, extends, and then overrides the built-in Prettier parser for `markdown`. This means that it is incompatible with other plugins that do the same; only the last loaded plugin that exports one of those parsers will function.

## Installation

```sh
npm install --save-dev prettier-plugin-md-title-case
```

_Note that `prettier` is a peer dependency, so make sure you have it installed in your project. Prettier 2 is not supported as this package is written with ESM syntax._

## Usage

Configure Prettier to use the plugin according to the [Plugins docs](https://prettier.io/docs/en/plugins.html), for example by adding it to the `plugins` config:

```js
// prettier.config.js

/** @type {import('prettier').Config} */
export default {
plugins: ['prettier-plugin-md-title-case'],
};
```

Any line starting with `#` will be considered a heading. Doesn't work for inline-HTML.

## Configuration

You can pass the supported options of `title-case` (see [npmjs.com/package/title-case#options](https://www.npmjs.com/package/title-case#options)) to your Prettier config as a JSON-stringified object via the `titleCase` option.

```js
// prettier.config.js

/** @type {import('title-case').Options} */
const titleCaseOptions = { locale: 'en_US' };

/** @type {import('prettier').Config} */
export default {
plugins: ['prettier-plugin-md-title-case'],
titleCase: JSON.stringify(titleCaseOptions),
};
```

## Debug Logs

If it doesn't work, you can try to prefix your `prettier` command with `DEBUG=true` (or any truthy value) which will make this plugin print runtime exception logs.

## Rationale/Disclaimer

This plugin acts outside of [Prettier's scope](https://prettier.io/docs/en/rationale#what-prettier-is-_not_-concerned-about) because _"Prettier only prints code. It does not transform it."_, and technically converting the case is a code transformation. In my opinion however, Markdown is just markup and not really code, and it doesn't change the AST of the Markdown file (just the contents of some nodes). Therefore the practical benefits outweigh sticking with the philosophy in this case.

## License

[MIT](/license).

0 comments on commit ff18244

Please sign in to comment.