forked from obsidianmd/obsidian-sample-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
53 lines (39 loc) · 1.27 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
import { App, Editor, MarkdownView, Modal, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
export default class EditorAutofocus extends Plugin {
async onload() {
this.registerEvent(
this.app.workspace.on('file-open', async (file) => {
let editor = this.getEditor();
if (editor) {
// if we have more than two lines, it's probably not a new file. just bail.
if (editor.lineCount() > 2) {
return
}
// focus on the editor, skip the tab title bar
editor.focus();
// wait a while, so obsidian filename heading sync can do its thing
await sleep(100);
// see if the first character of the first line is a #
let firstLine = editor.getLine(0);
let firstCharacter = firstLine.substr(0, 1);
if (firstCharacter != '#') {
return;
}
// otherwise, select the heading
let lineLength = firstLine.length;
if (lineLength > 1) {
editor.setSelection(
{ line: 0, ch: 2 },
{ line: 0, ch: lineLength }
);
}
}
})
);
}
onunload() {
}
private getEditor(): Editor | undefined {
return this.app.workspace.getActiveViewOfType(MarkdownView)?.editor;
}
}