Skip to content

Commit

Permalink
fix(markdown-mode): prevent block change from stripping numbers (#140)
Browse files Browse the repository at this point in the history
* fix: prevent block change from stripping numbers

fixes #69

* add matchLeadingBlockCharacters tests

* docs(commands): reseat TODOs for match regex

* fix(commands): add support for all ordered list markers in matchLeadingBlockCharacters

Co-authored-by: Ben Kelly <b-kelly@users.noreply.github.com>
  • Loading branch information
dancormier and b-kelly committed Jun 16, 2022
1 parent cb41a05 commit 32385e2
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 3 deletions.
15 changes: 12 additions & 3 deletions src/commonmark/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,11 +192,20 @@ function setBlockType(
/**
* Returns any block formatting characters (plus trailing space) at the very start of the passed text
* @param text The text to check for leading block characters
* @internal
*/
function matchLeadingBlockCharacters(text: string) {
export function matchLeadingBlockCharacters(text: string) {
// TODO this might be too aggressive... remove based on a whitelist instead?
// TODO HACK assumes all block types are non-letter characters followed by a single space
return /^[^a-zA-Z]+\s{1}(?=[a-zA-Z_*[!]|$)/.exec(text)?.[0] || "";
// Match ordered list markers; see https://spec.commonmark.org/0.30/#ordered-list-marker
let match = /^(\d+)(?:\.|\))\s/.exec(text)?.[0];

// If text is not an ordered list block, check for other block types
if (!match) {
// TODO HACK assumes all non-ordered list block types are non-letter characters followed by a single space
match = /^[^a-zA-Z0-9]+\s{1}(?=[a-zA-Z0-9_*[!]|$)+/.exec(text)?.[0];
}

return match || "";
}

/**
Expand Down
33 changes: 33 additions & 0 deletions test/commonmark/commands.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -521,4 +521,37 @@ some text`;
});
});
});

describe("matchLeadingBlockCharacters", () => {
it("return no leading characters", () => {
const command = commands.matchLeadingBlockCharacters(
"42 shouldn't be returned"
);

expect(command).toBe("");
});

it("return ordered list leading characters", () => {
let command = commands.matchLeadingBlockCharacters("23. -ol item");

expect(command).toBe("23. ");

command = commands.matchLeadingBlockCharacters("23) -ol item");

expect(command).toBe("23) ");
});

it("return unordered list leading characters", () => {
const command = commands.matchLeadingBlockCharacters("- 1 ul item");

expect(command).toBe("- ");
});

it("return heading leading characters", () => {
const command =
commands.matchLeadingBlockCharacters("## Heading level 2");

expect(command).toBe("## ");
});
});
});

0 comments on commit 32385e2

Please sign in to comment.