Skip to content

Commit 4d60826

Browse files
committed
Fix indented comments
1 parent 6828e13 commit 4d60826

File tree

3 files changed

+35
-9
lines changed

3 files changed

+35
-9
lines changed

.changeset/friendly-teachers-sort.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@code-hike/lighter": patch
3+
---
4+
5+
Fix indented comments

lib/src/comments.ts

+11-3
Original file line numberDiff line numberDiff line change
@@ -148,10 +148,18 @@ function getAnnotationsFromLine(
148148
) {
149149
const prefix = prefixes[lang];
150150
tokens = tokens.flatMap((token) => {
151-
if (token.style.color === COMMENT && token.content.startsWith(prefix)) {
152-
const content = token.content.slice(prefix.length);
151+
if (token.style.color !== COMMENT) {
152+
return [token];
153+
}
154+
const trimmed = token.content.trimStart();
155+
if (trimmed.startsWith(prefix)) {
156+
const content = trimmed.slice(prefix.length);
157+
const punctuation = token.content.slice(
158+
0,
159+
token.content.length - content.length
160+
);
153161
const t = [
154-
{ content: prefix, style: { color: PUNCTUATION } },
162+
{ content: punctuation, style: { color: PUNCTUATION } },
155163
] as Token[];
156164
if (content.length) {
157165
t.push({ content, style: token.style });

lib/test/comments.test.ts

+19-6
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,6 @@ let codes = [
9090
["# foo", "sh"],
9191
["# foo", "tcl"],
9292
["<!-- foo-->", "vue-html"],
93-
["* foo", "abap"],
9493
["; foo", "beancount"],
9594
["' foo", "vb"],
9695
["<!-- foo-->", "html"],
@@ -126,12 +125,10 @@ let codes = [
126125
// ["// foo", "apl"],
127126
// ["# foo", "shellsession"],
128127
// ["(* foo *)", "ocaml"],
129-
];
130128

131-
// codes = [
132-
// // test
133-
// ["// foo", "actionscript-3"],
134-
// ];
129+
// fails indented
130+
// ["* foo", "abap"],
131+
];
135132

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

168165
expect(comments).toHaveLength(1);
169166
expect(comments[0]).toBe(" foo");
167+
expect(extracted.code).toBe(code);
168+
});
169+
});
170+
171+
describe.each(codes)("extract indented annotations", (code, lang) => {
172+
test(lang, async () => {
173+
let comments = [];
174+
const c = " " + code;
175+
const extracted = await extractAnnotations(c, lang, (comment) => {
176+
comments.push(comment);
177+
return null;
178+
});
179+
180+
expect(comments).toHaveLength(1);
181+
expect(comments[0]).toBe(" foo");
182+
expect(extracted.code).toBe(c);
170183
});
171184
});

0 commit comments

Comments
 (0)