diff --git a/src/plugins/search/search.js b/src/plugins/search/search.js
index a30f67b74..baca3c95a 100644
--- a/src/plugins/search/search.js
+++ b/src/plugins/search/search.js
@@ -257,12 +257,14 @@ export function genIndex(path, content = '', router, depth, indexKey) {
indexKey: indexKey,
};
} else {
+ const code = token.type === 'code' ? token.text : null;
+
if (tokenIndex === 0) {
slug = router.toURL(path);
index[slug] = {
slug,
title: path !== '/' ? path.slice(1) : 'Home Page',
- body: markdownToTxt(/** @type {any} */ (token).text || ''),
+ body: code ?? markdownToTxt(/** @type {any} */ (token).text || ''),
path: path,
indexKey: indexKey,
};
@@ -281,7 +283,7 @@ export function genIndex(path, content = '', router, depth, indexKey) {
token.text = getListData(token);
// @ts-expect-error
- index[slug].body += '\n' + markdownToTxt(token.text || '');
+ index[slug].body += '\n' + (code ?? markdownToTxt(token.text || ''));
} else {
// @ts-expect-error
token.text = getTableData(token);
@@ -289,7 +291,7 @@ export function genIndex(path, content = '', router, depth, indexKey) {
token.text = getListData(token);
// @ts-expect-error
- index[slug].body = markdownToTxt(token.text || '');
+ index[slug].body = code ?? markdownToTxt(token.text || '');
}
index[slug].path = path;
diff --git a/test/e2e/search.test.js b/test/e2e/search.test.js
index cfcfdf99c..9d80e22b3 100644
--- a/test/e2e/search.test.js
+++ b/test/e2e/search.test.js
@@ -524,6 +524,39 @@ console.log('Hello World');
);
});
+ for (const [name, markdown, title] of [
+ [
+ 'after a heading',
+ '# Code examples\n\n```html\n\n```',
+ 'Code examples',
+ ],
+ [
+ 'after a paragraph',
+ '# Code examples\n\nAn example:\n\n```html\n\n```',
+ 'Code examples',
+ ],
+ ['without a heading', '```html\n\n```', 'Home Page'],
+ [
+ 'in an indented code block',
+ '# Code examples\n\n ',
+ 'Code examples',
+ ],
+ ]) {
+ test(`searches HTML examples ${name}`, async ({ page }) => {
+ await docsifyInit({
+ markdown: { homepage: markdown },
+ scriptURLs: ['/dist/plugins/search.js'],
+ });
+
+ await page.locator('input[type=search]').fill('customwidget');
+ await expect(page.locator('.results-panel .title')).toHaveText(title);
+ await expect(page.locator('.results-panel .content')).toContainText(
+ '',
+ );
+ await expect(page.locator('.results-panel customwidget')).toHaveCount(0);
+ });
+ }
+
test('search result should remove file markdown and keep href attribution for files', async ({
page,
}) => {