Skip to content

Commit 1827bbc

Browse files
committed
fix: match position lines -> chars
1 parent 736484c commit 1827bbc

File tree

2 files changed

+13
-13
lines changed

2 files changed

+13
-13
lines changed

docs/openapi.yaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1583,10 +1583,10 @@ paths:
15831583
properties:
15841584
end:
15851585
type: "number"
1586-
description: "Line number or 0 when the filename matched"
1586+
description: "End character position of the match within the file. Starts with 0."
15871587
start:
15881588
type: "number"
1589-
description: "Line number or 0 when the filename matched"
1589+
description: "Start character position of the match within the file. Starts with 0."
15901590
source:
15911591
type: "string"
15921592
description: "Where the search term matched: 'filename' or 'content'"

src/requestHandler.ts

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1010,26 +1010,28 @@ export default class RequestHandler {
10101010
});
10111011
}
10121012

1013-
// Below we virtually add the headline to the search text with 2 line breaks.
1014-
// That causes the start and end line numbers to be wrong with an offset of 2.
1015-
// This is fixed by substracting 2 from the start and end position.
1016-
const positionOffset = 2;
1017-
10181013
for (const file of this.app.vault.getMarkdownFiles()) {
10191014
const cachedContents = await this.app.vault.cachedRead(file);
10201015

10211016
// Add the headline to the search text to include it in the search.
1022-
const result = search(file.basename + "\n\n" + cachedContents);
1017+
const filenamePrefix = file.basename + "\n\n";
1018+
const result = search(filenamePrefix + cachedContents);
1019+
1020+
// We added the headline to the search text with 2 line breaks.
1021+
// That causes the start and end position numbers to be wrong with an offset
1022+
// of the char length of the headline + 2 line breaks.
1023+
// This is fixed by substracting the positionOffset from the start and end position.
1024+
const positionOffset = filenamePrefix.length - 1;
10231025

10241026
if (result) {
10251027
const contextMatches: SearchContext[] = [];
10261028
for (const match of result.matches) {
10271029
if (match[0] == 0) {
1028-
// When start position is line 1, that means the search term matched within the headline.
1030+
// When start position is between 0 and positionOffset, that means the search term matched within the headline.
10291031
contextMatches.push({
10301032
match: {
1031-
start: 0,
1032-
end: 0,
1033+
start: match[0],
1034+
end: match[1],
10331035
source: "filename"
10341036
},
10351037
context: file.basename,
@@ -1048,8 +1050,6 @@ export default class RequestHandler {
10481050
),
10491051
});
10501052
}
1051-
1052-
10531053
}
10541054

10551055
results.push({

0 commit comments

Comments
 (0)