Hi, I am hoping to write a plugin to emulate emacs ctrl+l command: Pressing ctrl+l once scrolls so that the line the cursor is on is in the center. Pressing ctrl+l again scrolls so that the line is at the top and ctrl+l again scrolls so that the line is at the bottom.
Note: putting the line in the center is not an issue - there are other plugins that do this.
I am having trouble with how to scroll a note so that the line the cursor is on is at the top of the users view. One way would be to get the number of lines in the current view then use the recenter function to recenter the line that would put the cursor line at the top. But I can not find how to get the number of lines in the current view. If I can get one command to recenter, one to move to top and one to move to bottom then I can combine them just fine.
Thanks for any help offered!
(I do see the post " Is there any way to make the line where the cursor is located back to the center/top of the screen? " but from what I can see it only takes care of recentering the cursor line, does not move the line to the top)
The Obsidian Editor API doesn’t expose scroll-position control precise enough for this. For most editing contexts, the cleaner solution is to drop down to CodeMirror 6’s EditorView via editor.cm:
import { EditorView } from '@codemirror/view';
editor.cm.dispatch({
effects: EditorView.scrollIntoView(
editor.cm.state.selection.main.head,
{ y: 'center' } // or 'start' (top) / 'end' (bottom)
)
});
Caveat: editor.cm is not part of Obsidian’s official public API — but it’s widely used in the plugin ecosystem.
This works well in normal text and in Source Mode. But Live Preview table cells need a different approach — when the cursor is in a table cell, Obsidian creates a separate inner EditorView for that cell, and editor.cm.state.selection.main.head points to a placeholder in the outer view rather than the actual cursor.
For table cell support, window.getSelection() gives the true browser cursor position regardless of inner/outer view. See how it’s implemented in my plugin Universal Cursor Hotkeys (relevant source on GitHub) — it also implements the recenter-top-bottom cycle (center → top → bottom) as a Ctrl+L command.