Skip to content

Commit

Permalink
Fix indented comments
Browse files Browse the repository at this point in the history
  • Loading branch information
pomber committed Jul 13, 2024
1 parent 6828e13 commit 4d60826
Show file tree
Hide file tree
Showing 3 changed files with 35 additions and 9 deletions.
5 changes: 5 additions & 0 deletions .changeset/friendly-teachers-sort.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@code-hike/lighter": patch
---

Fix indented comments
14 changes: 11 additions & 3 deletions lib/src/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,18 @@ function getAnnotationsFromLine(
) {
const prefix = prefixes[lang];
tokens = tokens.flatMap((token) => {
if (token.style.color === COMMENT && token.content.startsWith(prefix)) {
const content = token.content.slice(prefix.length);
if (token.style.color !== COMMENT) {
return [token];
}
const trimmed = token.content.trimStart();
if (trimmed.startsWith(prefix)) {
const content = trimmed.slice(prefix.length);
const punctuation = token.content.slice(
0,
token.content.length - content.length
);
const t = [
{ content: prefix, style: { color: PUNCTUATION } },
{ content: punctuation, style: { color: PUNCTUATION } },
] as Token[];
if (content.length) {
t.push({ content, style: token.style });
Expand Down
25 changes: 19 additions & 6 deletions lib/test/comments.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,6 @@ let codes = [
["# foo", "sh"],
["# foo", "tcl"],
["<!-- foo-->", "vue-html"],
["* foo", "abap"],
["; foo", "beancount"],
["' foo", "vb"],
["<!-- foo-->", "html"],
Expand Down Expand Up @@ -126,12 +125,10 @@ let codes = [
// ["// foo", "apl"],
// ["# foo", "shellsession"],
// ["(* foo *)", "ocaml"],
];

// codes = [
// // test
// ["// foo", "actionscript-3"],
// ];
// fails indented
// ["* foo", "abap"],
];

describe.each(codes)("extract annotations", (code, lang) => {
test(lang, async () => {
Expand Down Expand Up @@ -167,5 +164,21 @@ describe.each(codes)("extract annotations", (code, lang) => {

expect(comments).toHaveLength(1);
expect(comments[0]).toBe(" foo");
expect(extracted.code).toBe(code);
});
});

describe.each(codes)("extract indented annotations", (code, lang) => {
test(lang, async () => {
let comments = [];
const c = " " + code;
const extracted = await extractAnnotations(c, lang, (comment) => {
comments.push(comment);
return null;
});

expect(comments).toHaveLength(1);
expect(comments[0]).toBe(" foo");
expect(extracted.code).toBe(c);
});
});

0 comments on commit 4d60826

Please sign in to comment.