typescript - Obsidian 插件:设置光标位置
我想通过编程方式打开一个文件(通过我的 Obsidian 插件)并跳转到特定的光标位置。我尝试了以下代码,似乎只差一点点了:
const editor = this.app.workspace.getActiveViewOfType(MarkdownView).editor;
editor.setSelection(cursor);
editor.focus()
我尝试过添加 this.app.workspace.updateOptions()、editor.refresh() ——但都没有帮助——文件已打开,但光标总是在开头,而不是在正确的光标位置
答案#1
你可以使用视图的 code mirror 对象,并调用 setCursor 方法。
截至撰写时,它仅在 “obsidian-typings” 测试版中公开。
使用 npm i --save-dev [email 安装它
这是一个滚动到页面底部的示例:
import { MarkdownView } from "obsidian";
import { CodeMirrorEditor } from "obsidian-typings";
const view:MarkdownView =
this.app.workspace.getActiveViewOfType(MarkdownView);
if (view) {
const cm:CodeMirrorEditor = view.editor.cm;
cm.setCursor(cm.lastLine(), 0);
view.editor.scrollTo(0, cm.lastLine());
cm.focus();
}
