Skip to content

Commit

Permalink
fix: don't convert inline-code in headings
Browse files Browse the repository at this point in the history
  • Loading branch information
simonhaenisch committed Aug 28, 2024
1 parent 451d0c1 commit 24af714
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 5 deletions.
15 changes: 14 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,20 @@ const convertHeadingsToTitleCase = (code, options) => {

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

return line.replace(content, titleCase(content, titleCaseOptions));
const inlineCodeMatches = Array.from(content.matchAll(/`.+?`/g));

let newContent = titleCase(content, titleCaseOptions);

for (const match of inlineCodeMatches) {
const [inlineCode] = match;

newContent =
newContent.slice(0, match.index) +
inlineCode +
newContent.slice(match.index + inlineCode.length);
}

return line.replace(content, newContent);
})
.join('\n');
} catch (error) {
Expand Down
33 changes: 29 additions & 4 deletions index.spec.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
// @ts-check

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

/**
Expand All @@ -14,21 +14,46 @@ const prettify = async (code, options) =>
...options,
});

test('converts headings to title case', async (t) => {
it('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) => {
it('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) => {
it('does not convert inline code', async (t) => {
const formattedCode = await prettify('# heading with `inline-code` in it');

t.is(formattedCode, '# Heading with `inline-code` in It\n');
});

it('does not convert multiple inline code fragments', async (t) => {
const formattedCode = await prettify(
'# heading with `inline-code` but `twice`',
);

t.is(formattedCode, '# Heading with `inline-code` but `twice`\n');
});

it('leaves inline code intact when the same code is used multiple times', async (t) => {
const formattedCode = await prettify(
'# heading with same `inline-code` twice `inline-code`',
);

t.is(
formattedCode,
'# Heading with Same `inline-code` Twice `inline-code`\n',
);
});

it('passes title-case options from the prettier config', async (t) => {
const formattedCode = await prettify(
'# some sentence - Only affects the first word!',
{
Expand Down

0 comments on commit 24af714

Please sign in to comment.