Skip to content

Offline, privacy-first grammar checker. Fast, open-source, Rust-powered

fix(obsidian): correctly handle Unicode conversions

Elijah Potterde2a655c5627
diff --git a/harper-core/dictionary.dict b/harper-core/dictionary.dict
index d9ac7f33f..1752a2140 100644
--- a/harper-core/dictionary.dict
+++ b/harper-core/dictionary.dict
@@ -20082,10 +20082,9 @@ diaereses/1
diaeresis/1M
diagnose/4DSG
diagnosis/14M
-diagnostic/51S
+diagnostic/51MS
diagnostically/
diagnostician/1SM
-diagnostics/1M
diagonal/51SMY
diagram/14SM
diagrammatic/5
diff --git a/packages/obsidian-plugin/src/index.ts b/packages/obsidian-plugin/src/index.ts
index ab2d23852..195ed081c 100644
--- a/packages/obsidian-plugin/src/index.ts
+++ b/packages/obsidian-plugin/src/index.ts
@@ -1,3 +1,4 @@
+import { toArray } from 'lodash-es';
import logoSvg from '../logo.svg';
import { Plugin, Menu, PluginManifest, App, Notice } from 'obsidian';
import { LintConfig, Linter, Suggestion } from 'harper.js';
@@ -167,12 +168,16 @@ export default class HarperPlugin extends Plugin {
return linter(
async (view) => {
const text = view.state.doc.sliceString(-1);
+ const chars = toArray(text);
const lints = await this.harper.lint(text);
return lints.map((lint) => {
const span = lint.span();
+ span.start = charIndexToCodePointIndex(span.start, chars);
+ span.end = charIndexToCodePointIndex(span.end, chars);
+
return {
from: span.start,
to: span.end,
@@ -224,3 +229,18 @@ export default class HarperPlugin extends Plugin {
);
}
}
+
+/** Harper returns positions based on char indexes,
+ * but Obsidian identifies locations in documents based on Unicode code points.
+ * This converts between from the former to the latter.*/
+function charIndexToCodePointIndex(index: number, sourceChars: string[]): number {
+ let traversed = 0;
+
+ for (let i = 0; i < index; i++) {
+ const delta = sourceChars[i].length;
+
+ traversed += delta;
+ }
+
+ return traversed;
+}