-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.ts
113 lines (98 loc) · 2.75 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
import { Plugin } from "obsidian";
import { lineNumbersRelative } from "./extension";
import { Extension } from "@codemirror/state";
export default class RelativeLineNumbers extends Plugin {
private editorExtension: Extension[] = [];
enabled: boolean;
isLegacy() {
return (this.app as any).vault.config?.legacyEditor;
}
async onload() {
this.registerEditorExtension(this.editorExtension);
// @ts-ignore
const showLineNumber: Boolean = this.app.vault.getConfig("showLineNumber");
if (showLineNumber) {
this.enable();
}
this.setupConfigChangeListener();
this.addCommand({
id: "toggle-relative-line-numbers",
name: "Toggle Relative Line Numbers",
callback: () => {
if (showLineNumber) {
if (this.enabled) {
this.disable();
} else {
this.enable();
}
}
},
});
}
onunload() {
this.disable();
}
enable() {
this.enabled = true;
if (this.isLegacy()) {
this.legacyEnable();
} else {
this.editorExtension.length = 0;
this.editorExtension.push(lineNumbersRelative());
this.app.workspace.updateOptions();
}
}
disable() {
this.enabled = false;
if (this.isLegacy()) {
this.legacyDisable();
} else {
this.editorExtension.length = 0;
this.app.workspace.updateOptions();
}
}
legacyEnable() {
this.registerCodeMirror((cm) => {
cm.on("cursorActivity", this.legacyRelativeLineNumbers);
});
}
legacyDisable() {
this.app.workspace.iterateCodeMirrors((cm) => {
cm.off("cursorActivity", this.legacyRelativeLineNumbers);
cm.setOption(
"lineNumberFormatter",
// @ts-ignore
CodeMirror.defaults["lineNumberFormatter"]
);
});
}
setupConfigChangeListener() {
// @ts-ignore
const configChangedEvent = this.app.vault.on("config-changed", () => {
const showLineNumber: Boolean =
// @ts-ignore
this.app.vault.getConfig("showLineNumber");
if (showLineNumber && !this.enabled) {
this.enable();
} else if (!showLineNumber && this.enabled) {
this.disable();
}
});
// @ts-ignore
configChangedEvent.ctx = this;
this.registerEvent(configChangedEvent);
}
legacyRelativeLineNumbers(cm: CodeMirror.Editor) {
const current = cm.getCursor().line + 1;
if (cm.state.curLineNum === current) {
return;
}
cm.state.curLineNum = current;
cm.setOption("lineNumberFormatter", (line: number) => {
if (line === current) {
return String(current);
}
return String(Math.abs(current - line));
});
}
}